@caveman-ai/cli 1.3.0 → 1.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -0
- package/dist/agent-skills.generated.js +1 -1
- package/dist/agents.generated.js +387 -10
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +112 -13
- package/dist/index.js +2610 -127
- package/dist/proxy-fetch.js +3 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
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
15
|
import { installProxyAwareFetch } from "./proxy-fetch.js";
|
|
@@ -59,8 +60,13 @@ function gatewayUrlFromConfigFile() {
|
|
|
59
60
|
// adding an agent is a new profile file, not a code change. Any other command
|
|
60
61
|
// still runs verbatim with the generic provider base-URL injection.
|
|
61
62
|
const AGENTS = PROFILES;
|
|
62
|
-
// binOf
|
|
63
|
+
// binOf prefers the first installed published binary and falls back to the
|
|
64
|
+
// primary name for install hints. Some packages intentionally publish aliases.
|
|
63
65
|
function binOf(a) {
|
|
66
|
+
for (const name of a.binary_names) {
|
|
67
|
+
if (which(name))
|
|
68
|
+
return name;
|
|
69
|
+
}
|
|
64
70
|
return a.binary_names[0] ?? a.id;
|
|
65
71
|
}
|
|
66
72
|
// findAgent resolves a wrap target to a profile by id first, then by any of its
|
|
@@ -313,6 +319,8 @@ function resolveInvocation(raw) {
|
|
|
313
319
|
const top = raw[0] ?? "help";
|
|
314
320
|
if (top === "--help")
|
|
315
321
|
return { verb: "help", argv: [], handler: help };
|
|
322
|
+
if (top === "--version")
|
|
323
|
+
return { verb: "version", argv: [], handler: LEGACY_HANDLERS.version };
|
|
316
324
|
if ((top === "tools" || top === "cloud") && raw.length === 1) {
|
|
317
325
|
return { verb: top, argv: [], group: top, handler: () => printDiscovery(top) };
|
|
318
326
|
}
|
|
@@ -1951,8 +1959,10 @@ async function start(argv = []) {
|
|
|
1951
1959
|
const subscriptionCompress = subscriptionCompressEnabled(startGate);
|
|
1952
1960
|
// A bare proxy has no active-agent identity, so it cannot prove that whichever
|
|
1953
1961
|
// subscription client arrives owns a compatible recovery tool. Keep the global
|
|
1954
|
-
// recovery signal off;
|
|
1955
|
-
//
|
|
1962
|
+
// recovery signal off; `caveman wrap <agent>` binds recovery to a checked agent
|
|
1963
|
+
// profile out of band, and for every other client the proxy reads the retrieve
|
|
1964
|
+
// tool out of the request itself. Inherited environment claims never cross this
|
|
1965
|
+
// boundary.
|
|
1956
1966
|
const mcpRecovery = startMcpRecoveryAvailable();
|
|
1957
1967
|
const env = {
|
|
1958
1968
|
...process.env,
|
|
@@ -2468,12 +2478,52 @@ function readPendingAgentNativeBundleRemoval(agent) {
|
|
|
2468
2478
|
throw new Error(`cannot read pending ${agent} agent-native removal journal: ${error.message}`);
|
|
2469
2479
|
}
|
|
2470
2480
|
}
|
|
2481
|
+
function mcpServerToolName(serverName) {
|
|
2482
|
+
if (serverName === "caveman")
|
|
2483
|
+
return "caveman_retrieve";
|
|
2484
|
+
if (serverName === "caveman-browse")
|
|
2485
|
+
return "caveman_browse";
|
|
2486
|
+
if (serverName === "caveman-cloud")
|
|
2487
|
+
return "caveman_context";
|
|
2488
|
+
if (serverName === "caveman-delegate")
|
|
2489
|
+
return "caveman_delegate";
|
|
2490
|
+
return undefined;
|
|
2491
|
+
}
|
|
2492
|
+
function parseMcpServerMarkerBytes(agent, serverName, bytes) {
|
|
2493
|
+
try {
|
|
2494
|
+
const value = JSON.parse(bytes.toString("utf8"));
|
|
2495
|
+
const expectedTool = mcpServerToolName(serverName);
|
|
2496
|
+
if (!expectedTool || value.tool !== expectedTool)
|
|
2497
|
+
return null;
|
|
2498
|
+
const hasConfigPath = Object.hasOwn(value, "config_path");
|
|
2499
|
+
const expectedKeys = hasConfigPath
|
|
2500
|
+
? ["args", "command", "config_path", "schema_version", "tool"]
|
|
2501
|
+
: ["args", "command", "tool"];
|
|
2502
|
+
if (Object.keys(value).sort().join("\0") !== expectedKeys.join("\0"))
|
|
2503
|
+
return null;
|
|
2504
|
+
if (typeof value.command !== "string" || !value.command.trim() || /[\r\n]/.test(value.command) || !Array.isArray(value.args) || !value.args.every((arg) => typeof arg === "string"))
|
|
2505
|
+
return null;
|
|
2506
|
+
if (hasConfigPath && (value.schema_version !== 1
|
|
2507
|
+
|| agent !== "kilo" && agent !== "qwen"
|
|
2508
|
+
|| typeof value.config_path !== "string"
|
|
2509
|
+
|| value.config_path !== canonicalMcpConfigPath(value.config_path)))
|
|
2510
|
+
return null;
|
|
2511
|
+
return {
|
|
2512
|
+
command: value.command,
|
|
2513
|
+
args: value.args,
|
|
2514
|
+
...(hasConfigPath ? { config_path: value.config_path, schema_version: 1 } : {}),
|
|
2515
|
+
};
|
|
2516
|
+
}
|
|
2517
|
+
catch {
|
|
2518
|
+
return null;
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2471
2521
|
function readMcpServerMarker(agent, serverName) {
|
|
2472
2522
|
try {
|
|
2473
|
-
const
|
|
2474
|
-
if (
|
|
2523
|
+
const path = mcpServerMarkerPath(agent, serverName);
|
|
2524
|
+
if ((agent === "kilo" || agent === "qwen") && lstatSync(path).isSymbolicLink())
|
|
2475
2525
|
return null;
|
|
2476
|
-
return
|
|
2526
|
+
return parseMcpServerMarkerBytes(agent, serverName, readFileSync(path));
|
|
2477
2527
|
}
|
|
2478
2528
|
catch {
|
|
2479
2529
|
return null;
|
|
@@ -4232,11 +4282,17 @@ async function wrap(rest) {
|
|
|
4232
4282
|
console.error("caveman wrap: --pixel not yet supported for codex subscription sessions");
|
|
4233
4283
|
process.exit(1);
|
|
4234
4284
|
}
|
|
4235
|
-
|
|
4236
|
-
|
|
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
|
+
}
|
|
4237
4293
|
// `wrap` is a zero-commit trial. Native hooks/MCP/config live only in a temp
|
|
4238
4294
|
// host pack for this child; persistent integration requires an explicit install.
|
|
4239
|
-
await runWrapped(resolved, extra, agent, parsed, codexAuthMode === "subscription");
|
|
4295
|
+
await runWrapped(resolved, extra, agent, parsed, codexAuthMode === "subscription", routeDecision);
|
|
4240
4296
|
}
|
|
4241
4297
|
// ===========================================================================
|
|
4242
4298
|
// First-run experience. One-time (per machine) interactive moment on the first
|
|
@@ -4787,8 +4843,12 @@ async function agentShortcut(rest) {
|
|
|
4787
4843
|
// is the one-command compression path. If the proxy can't be reached, a TTY run
|
|
4788
4844
|
// offers to launch the agent directly (no Caveman, no compression this run) rather
|
|
4789
4845
|
// than wire it to a dead endpoint; non-TTY runs warn and route through as before.
|
|
4790
|
-
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) {
|
|
4791
|
-
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);
|
|
4792
4852
|
const summary = result.summaryKind && result.sessionStart
|
|
4793
4853
|
? printSessionSavings(result.summaryKind, result.sessionStart, agent?.id)
|
|
4794
4854
|
: null;
|
|
@@ -4849,7 +4909,7 @@ function routedAiderArgs(args) {
|
|
|
4849
4909
|
process.stderr.write(`caveman: aider model not set; routing with --model ${AIDER_ROUTED_DEFAULT_MODEL}\n`);
|
|
4850
4910
|
return ["--model", AIDER_ROUTED_DEFAULT_MODEL, ...args];
|
|
4851
4911
|
}
|
|
4852
|
-
async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = false) {
|
|
4912
|
+
async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = false, routeDecision) {
|
|
4853
4913
|
const { host, port } = gatewayHostPort(gw);
|
|
4854
4914
|
const local = wrapMode(gw) === "local";
|
|
4855
4915
|
let proxyStarted = false;
|
|
@@ -4858,14 +4918,23 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4858
4918
|
// Gemini cannot preserve both contracts. Launch direct instead of routing a
|
|
4859
4919
|
// request that will 401 or misuse one credential as the other.
|
|
4860
4920
|
const managedGeminiUnsupported = !local && agent?.id === "gemini";
|
|
4861
|
-
|
|
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;
|
|
4862
4928
|
if (managedGeminiUnsupported) {
|
|
4863
4929
|
process.stderr.write("caveman: managed Gemini CLI wrap is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials; launching directly\n");
|
|
4864
4930
|
}
|
|
4931
|
+
if (routeOverride && agent) {
|
|
4932
|
+
process.stderr.write(`caveman: ${routeOverrideLabel(agent)} ${routeOverride.surface} ${routeOverride.reason}; launching directly\n`);
|
|
4933
|
+
}
|
|
4865
4934
|
// The local proxy compresses with no account. When wrap runs the LOCAL
|
|
4866
4935
|
// proxy path we resolve the mode; managed gateway traffic is governed by the cloud
|
|
4867
4936
|
// policy engine, so we never resolve it here.
|
|
4868
|
-
const gateApplies = local && !opts.noProxy;
|
|
4937
|
+
const gateApplies = !direct && local && !opts.noProxy;
|
|
4869
4938
|
const entitlement = gateApplies ? readWrapEntitlement() : null;
|
|
4870
4939
|
const entitlementState = gateApplies ? readWrapEntitlementState() : null;
|
|
4871
4940
|
const gate = gateApplies ? resolveWrapGate(entitlement, new Date(), opts.mode) : null;
|
|
@@ -4887,20 +4956,20 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4887
4956
|
// detail itself — i.e. it has the caveman MCP retrieve tool installed (run
|
|
4888
4957
|
// `caveman mcp install <agent>`). When it does, signal the proxy to use MCP
|
|
4889
4958
|
// recovery (which lets it compress streams); otherwise streams pass through.
|
|
4890
|
-
const ephemeralMcp = agent && (agent.id === "claude" || agent.id === "codex")
|
|
4959
|
+
const ephemeralMcp = !direct && agent && (agent.id === "claude" || agent.id === "codex")
|
|
4891
4960
|
&& !opts.minimal && opts.mcpMode === "auto" && wrapRecoveryEligible(opts)
|
|
4892
4961
|
? probeMcpBinary()
|
|
4893
4962
|
: null;
|
|
4894
4963
|
if (ephemeralMcp && !ephemeralMcp.probe.current)
|
|
4895
4964
|
queueStaleMcpBinary(ephemeralMcp.probe);
|
|
4896
4965
|
const ephemeralMcpBinary = ephemeralMcp?.probe.current ? ephemeralMcp.binary : undefined;
|
|
4897
|
-
const mcpRecovery = Boolean(ephemeralMcpBinary) || wrapMcpRecoveryAvailable(agent, opts);
|
|
4898
|
-
const delegateAlreadyInstalled = Boolean(agent && mcpServerInstalled(agent.id, "caveman-delegate"));
|
|
4899
|
-
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")
|
|
4900
4969
|
&& !opts.minimal && opts.delegate && !delegateAlreadyInstalled
|
|
4901
4970
|
? resolveDelegateMcpCommand()
|
|
4902
4971
|
: null;
|
|
4903
|
-
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) {
|
|
4904
4973
|
process.stderr.write("caveman: delegate enabled but caveman-delegate server is unavailable; launching without delegate\n");
|
|
4905
4974
|
}
|
|
4906
4975
|
const desiredRecoveryViaMCP = observeEstimate ? false : mcpRecovery;
|
|
@@ -4908,7 +4977,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4908
4977
|
const proxyVersion = gateApplies ? probeProxyVersion() : null;
|
|
4909
4978
|
let runtime = { owner: "unknown" };
|
|
4910
4979
|
let runtimeState = null;
|
|
4911
|
-
let proxyReady = await portListening(host, port);
|
|
4980
|
+
let proxyReady = direct ? false : await portListening(host, port);
|
|
4912
4981
|
if (proxyReady && gateApplies) {
|
|
4913
4982
|
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
4914
4983
|
if (runtime.owner === "unknown") {
|
|
@@ -4947,7 +5016,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4947
5016
|
proxyStarted = await startWrapProxy(effectiveMode, desiredRecoveryViaMCP, codexSubscription ? false : observeEstimate ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, codexSubscription ? "codex-subscription" : "standard", observeEstimate);
|
|
4948
5017
|
proxyReady = await portListening(host, port);
|
|
4949
5018
|
}
|
|
4950
|
-
runtime = proxyReady ?
|
|
5019
|
+
runtime = proxyReady ? await awaitProxyRuntimeState(port, proxyVersion) : { owner: "unknown" };
|
|
4951
5020
|
if (runtime.owner === "unknown" || !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)) {
|
|
4952
5021
|
runtimeState = runtime.owner === "unknown"
|
|
4953
5022
|
? OFF_STATES.foreignProcess(host, port)
|
|
@@ -4980,7 +5049,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4980
5049
|
}
|
|
4981
5050
|
}
|
|
4982
5051
|
}
|
|
4983
|
-
if (!proxyReady) {
|
|
5052
|
+
if (!proxyReady && !direct) {
|
|
4984
5053
|
if (local && !opts.noProxy) {
|
|
4985
5054
|
proxyStarted = codexSubscription
|
|
4986
5055
|
? await startWrapProxy(effectiveMode, desiredRecoveryViaMCP, false, undefined, undefined, gw, "codex-subscription", observeEstimate)
|
|
@@ -4988,14 +5057,14 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4988
5057
|
}
|
|
4989
5058
|
proxyReady = await portListening(host, port);
|
|
4990
5059
|
if (proxyReady && gateApplies) {
|
|
4991
|
-
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
5060
|
+
runtime = proxyStarted ? await awaitProxyRuntimeState(port, proxyVersion) : readProxyRuntimeState(port, proxyVersion);
|
|
4992
5061
|
if (runtime.owner === "unknown") {
|
|
4993
5062
|
runtimeState = proxyVersion?.capabilities.includes("run_state")
|
|
4994
5063
|
? OFF_STATES.foreignProcess(host, port)
|
|
4995
5064
|
: OFF_STATES.staleBinary("caveman-proxy", proxyVersion?.version ?? "unknown", cliVersion());
|
|
4996
5065
|
}
|
|
4997
5066
|
}
|
|
4998
|
-
if (!proxyReady
|
|
5067
|
+
if (!proxyReady) {
|
|
4999
5068
|
const startHint = codexSubscription || opts.mode === "record" ? "caveman start" : `CAVEMAN_MODE=${opts.mode} caveman start`;
|
|
5000
5069
|
if (codexSubscription && opts.noProxy) {
|
|
5001
5070
|
// Explicit proxy:false leaves subscription Codex in pass-through launch mode
|
|
@@ -5017,7 +5086,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5017
5086
|
process.stderr.write(`${mark("warn")} cancelled — run ${cyan(startHint)}, then re-run your wrap\n`);
|
|
5018
5087
|
emitCommandRunOnce("error", "usage");
|
|
5019
5088
|
removeProxySessionMarker(sessionMarker);
|
|
5020
|
-
return { code: 130, proxyStarted };
|
|
5089
|
+
return { code: 130, proxyStarted, routeBypass };
|
|
5021
5090
|
}
|
|
5022
5091
|
}
|
|
5023
5092
|
else {
|
|
@@ -5026,10 +5095,21 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5026
5095
|
}
|
|
5027
5096
|
}
|
|
5028
5097
|
}
|
|
5098
|
+
// A foreign listener on the proxy port is the same failure as a gate
|
|
5099
|
+
// mismatch, with a worse consequence: launching routed would hand the
|
|
5100
|
+
// operator's provider keys to a process caveman does not own (#945).
|
|
5029
5101
|
if (runtimeState?.id === "running-gate-mismatch") {
|
|
5030
5102
|
process.stderr.write(`${mark("warn")} ${runtimeState.line}\n`);
|
|
5031
5103
|
direct = true;
|
|
5032
5104
|
}
|
|
5105
|
+
else if (proxyReady && gateApplies && !proxyStarted && runtime.owner === "unknown") {
|
|
5106
|
+
// A listener caveman did not start this run and cannot prove it owns: a
|
|
5107
|
+
// foreign process, or a proxy binary too old to answer. Routing anyway
|
|
5108
|
+
// would hand the operator's provider keys to that listener (#945).
|
|
5109
|
+
if (runtimeState)
|
|
5110
|
+
process.stderr.write(`${mark("warn")} ${runtimeState.line}\n`);
|
|
5111
|
+
direct = true;
|
|
5112
|
+
}
|
|
5033
5113
|
const subscriptionCompressionActive = !direct && proxyReady && subscriptionCompress && desiredRecoveryViaMCP
|
|
5034
5114
|
&& proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP);
|
|
5035
5115
|
if (direct) {
|
|
@@ -5106,7 +5186,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5106
5186
|
? { ...process.env }
|
|
5107
5187
|
: agent?.id === "codex"
|
|
5108
5188
|
? buildCodexEphemeralWrapEnv(gw, codexSubscription, ephemeralMcpBinary, includeShrink, ephemeralDelegateMcp)
|
|
5109
|
-
: buildWrapEnv(agent, gw, opts.mcpMode);
|
|
5189
|
+
: buildWrapEnv(agent, gw, opts.mcpMode, cmdArgs);
|
|
5110
5190
|
if (!direct && agent?.id === "claude") {
|
|
5111
5191
|
const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp);
|
|
5112
5192
|
childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
|
|
@@ -5122,13 +5202,24 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5122
5202
|
childArgs = cmdArgs;
|
|
5123
5203
|
process.stderr.write(`${mark("warn")} temporary native pack unavailable: ${error.message}; launching ${agent?.display_name ?? bin} directly\n`);
|
|
5124
5204
|
}
|
|
5205
|
+
// Profile args are routing injection too. Qwen's extension lock must never
|
|
5206
|
+
// leak into a launch we explicitly classified as direct; preserve only the
|
|
5207
|
+
// user's argv on every bypass and native-pack failure path.
|
|
5208
|
+
if (direct && agent?.id === "qwen"
|
|
5209
|
+
&& agent.args.every((arg, index) => childArgs[index] === arg)) {
|
|
5210
|
+
childArgs = childArgs.slice(agent.args.length);
|
|
5211
|
+
}
|
|
5125
5212
|
if (!direct && agent?.id === "claude")
|
|
5126
5213
|
Object.assign(env, claudeCaveBuildEnv());
|
|
5127
5214
|
if (!direct)
|
|
5128
5215
|
maybeWarnHermesMissingKey(agent, gw);
|
|
5129
5216
|
if (direct) {
|
|
5217
|
+
// buildWrapEnv writes the agent-attributed `${gw}/w/<agent>` form, and an
|
|
5218
|
+
// outer routed wrap may leak the bare form; a direct launch strips both.
|
|
5219
|
+
const gwPrefix = `${gw.replace(/\/+$/, "")}/`;
|
|
5130
5220
|
for (const k of WRAP_BASE_URL_ENV_VARS) {
|
|
5131
|
-
|
|
5221
|
+
const value = env[k];
|
|
5222
|
+
if (value !== undefined && (value === gw || value.startsWith(gwPrefix)))
|
|
5132
5223
|
delete env[k];
|
|
5133
5224
|
}
|
|
5134
5225
|
}
|
|
@@ -5213,7 +5304,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5213
5304
|
cleanupWrapTempDirs();
|
|
5214
5305
|
removeProxySessionMarker(sessionMarker);
|
|
5215
5306
|
}
|
|
5216
|
-
return { code, proxyStarted, sessionStart, summaryKind };
|
|
5307
|
+
return { code, proxyStarted, routeBypass, sessionStart, summaryKind };
|
|
5217
5308
|
}
|
|
5218
5309
|
export function claudeCaveBuildEnv() {
|
|
5219
5310
|
const lockPath = join(process.cwd(), ".caveman", "agent.lock.json");
|
|
@@ -5423,17 +5514,37 @@ function renderTemplate(s, gw = gatewayURL()) {
|
|
|
5423
5514
|
.replaceAll("{{cave_api_key}}", caveAPIKey)
|
|
5424
5515
|
.replaceAll("{{cave_org_id}}", orgIdFromConfigFile());
|
|
5425
5516
|
}
|
|
5517
|
+
const OPTIONAL_OPENAI_KEY_ENV_TEMPLATE = "{{cave_optional_openai_key_env}}";
|
|
5426
5518
|
// renderDeep applies renderTemplate to every string leaf of a JSON value — used to
|
|
5427
5519
|
// render an agent's inline-config template before it is stringified into an env var.
|
|
5428
|
-
|
|
5520
|
+
// Optional credential references disappear as whole object properties when their
|
|
5521
|
+
// source variable is unavailable. Secrets never enter generated JSON: the retained
|
|
5522
|
+
// value is the agent-native `$OPENAI_API_KEY` reference, not its expansion.
|
|
5523
|
+
function renderDeep(v, gw = gatewayURL(), env = process.env, options = {}) {
|
|
5524
|
+
if (v === OPTIONAL_OPENAI_KEY_ENV_TEMPLATE) {
|
|
5525
|
+
const key = env.OPENAI_API_KEY;
|
|
5526
|
+
const inherited = typeof key === "string" && !!key.trim() && !/[\r\n]/.test(key);
|
|
5527
|
+
return (options.optionalOpenAIKeyEnvAvailable ?? inherited)
|
|
5528
|
+
? options.optionalOpenAIKeyReference ?? "$OPENAI_API_KEY"
|
|
5529
|
+
: undefined;
|
|
5530
|
+
}
|
|
5429
5531
|
if (typeof v === "string")
|
|
5430
5532
|
return renderTemplate(v, gw);
|
|
5431
|
-
if (Array.isArray(v))
|
|
5432
|
-
return v.map((item) =>
|
|
5533
|
+
if (Array.isArray(v)) {
|
|
5534
|
+
return v.map((item) => {
|
|
5535
|
+
const rendered = renderDeep(item, gw, env, options);
|
|
5536
|
+
if (rendered === undefined)
|
|
5537
|
+
throw new Error("optional profile credentials cannot be array elements");
|
|
5538
|
+
return rendered;
|
|
5539
|
+
});
|
|
5540
|
+
}
|
|
5433
5541
|
if (v && typeof v === "object") {
|
|
5434
5542
|
const out = {};
|
|
5435
|
-
for (const [k, val] of Object.entries(v))
|
|
5436
|
-
|
|
5543
|
+
for (const [k, val] of Object.entries(v)) {
|
|
5544
|
+
const rendered = renderDeep(val, gw, env, options);
|
|
5545
|
+
if (rendered !== undefined)
|
|
5546
|
+
out[k] = rendered;
|
|
5547
|
+
}
|
|
5437
5548
|
return out;
|
|
5438
5549
|
}
|
|
5439
5550
|
return v;
|
|
@@ -5461,22 +5572,27 @@ function stripJson5Comments(s) {
|
|
|
5461
5572
|
continue;
|
|
5462
5573
|
}
|
|
5463
5574
|
if (ch === "/" && next === "/") {
|
|
5575
|
+
out += " ";
|
|
5464
5576
|
i += 2;
|
|
5465
|
-
while (i < s.length && s[i] !== "\n" && s[i] !== "\r")
|
|
5577
|
+
while (i < s.length && s[i] !== "\n" && s[i] !== "\r") {
|
|
5578
|
+
out += /\s/.test(s[i]) ? s[i] : " ";
|
|
5466
5579
|
i++;
|
|
5580
|
+
}
|
|
5467
5581
|
if (i < s.length)
|
|
5468
5582
|
out += s[i];
|
|
5469
5583
|
continue;
|
|
5470
5584
|
}
|
|
5471
5585
|
if (ch === "/" && next === "*") {
|
|
5586
|
+
out += " ";
|
|
5472
5587
|
i += 2;
|
|
5473
5588
|
while (i < s.length && !(s[i] === "*" && s[i + 1] === "/")) {
|
|
5474
|
-
|
|
5475
|
-
out += s[i];
|
|
5589
|
+
out += /\s/.test(s[i]) ? s[i] : " ";
|
|
5476
5590
|
i++;
|
|
5477
5591
|
}
|
|
5478
|
-
if (i < s.length)
|
|
5592
|
+
if (i < s.length) {
|
|
5593
|
+
out += " ";
|
|
5479
5594
|
i++;
|
|
5595
|
+
}
|
|
5480
5596
|
continue;
|
|
5481
5597
|
}
|
|
5482
5598
|
out += ch;
|
|
@@ -5530,15 +5646,38 @@ function isPlainObject(v) {
|
|
|
5530
5646
|
const proto = Object.getPrototypeOf(v);
|
|
5531
5647
|
return proto === Object.prototype || proto === null;
|
|
5532
5648
|
}
|
|
5649
|
+
function isSafeObjectKey(key) {
|
|
5650
|
+
return key !== "__proto__" && key !== "constructor" && key !== "prototype";
|
|
5651
|
+
}
|
|
5533
5652
|
export function deepMerge(base, overlay) {
|
|
5534
|
-
if (isPlainObject(
|
|
5535
|
-
const out = {
|
|
5536
|
-
|
|
5537
|
-
|
|
5653
|
+
if (isPlainObject(overlay)) {
|
|
5654
|
+
const out = {};
|
|
5655
|
+
if (isPlainObject(base)) {
|
|
5656
|
+
for (const [k, v] of Object.entries(base)) {
|
|
5657
|
+
if (isSafeObjectKey(k))
|
|
5658
|
+
out[k] = isPlainObject(v) ? deepMerge({}, v) : v;
|
|
5659
|
+
}
|
|
5660
|
+
}
|
|
5661
|
+
for (const [k, v] of Object.entries(overlay)) {
|
|
5662
|
+
if (isSafeObjectKey(k))
|
|
5663
|
+
out[k] = deepMerge(out[k], v);
|
|
5664
|
+
}
|
|
5538
5665
|
return out;
|
|
5539
5666
|
}
|
|
5540
5667
|
return overlay;
|
|
5541
5668
|
}
|
|
5669
|
+
export function platformDefaultConfigPath(kind, platform = process.platform, _env = process.env) {
|
|
5670
|
+
if (kind !== "qwen-system-settings")
|
|
5671
|
+
return undefined;
|
|
5672
|
+
if (platform === "darwin")
|
|
5673
|
+
return "/Library/Application Support/QwenCode/settings.json";
|
|
5674
|
+
// Qwen 0.22.3 deliberately does not consult %ProgramData% here.
|
|
5675
|
+
if (platform === "win32")
|
|
5676
|
+
return "C:\\ProgramData\\qwen-code\\settings.json";
|
|
5677
|
+
if (platform === "linux")
|
|
5678
|
+
return "/etc/qwen-code/settings.json";
|
|
5679
|
+
return undefined;
|
|
5680
|
+
}
|
|
5542
5681
|
function baseConfigPath(base) {
|
|
5543
5682
|
const envPath = base.env_var ? process.env[base.env_var] : undefined;
|
|
5544
5683
|
if (envPath && envPath.trim())
|
|
@@ -5546,6 +5685,11 @@ function baseConfigPath(base) {
|
|
|
5546
5685
|
const stateDir = base.state_dir?.env_var ? process.env[base.state_dir.env_var] : undefined;
|
|
5547
5686
|
if (stateDir && stateDir.trim())
|
|
5548
5687
|
return join(expandTilde(stateDir), base.state_dir.filename);
|
|
5688
|
+
const platformDefault = base.platform_default
|
|
5689
|
+
? platformDefaultConfigPath(base.platform_default)
|
|
5690
|
+
: undefined;
|
|
5691
|
+
if (platformDefault)
|
|
5692
|
+
return platformDefault;
|
|
5549
5693
|
return expandTilde(base.path);
|
|
5550
5694
|
}
|
|
5551
5695
|
function readBaseConfig(inj) {
|
|
@@ -6001,16 +6145,30 @@ function nativeHooksDocument(agentId, includeShrink, base = {}, includeRecall =
|
|
|
6001
6145
|
? ["SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "SubagentStart", "SubagentStop", "Stop", "SessionEnd"]
|
|
6002
6146
|
: ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "SubagentStart", "SubagentStop", "Stop", "SessionEnd"];
|
|
6003
6147
|
const command = nativeHookCommand(agentId);
|
|
6148
|
+
const identity = `native-hook:${agentId}`;
|
|
6004
6149
|
for (const event of lifecycle) {
|
|
6005
|
-
|
|
6006
|
-
|
|
6007
|
-
|
|
6150
|
+
// Replace, never accumulate: a caveman native-hook entry for this agent
|
|
6151
|
+
// that points at another binary or adapter path (an upgrade, a moved
|
|
6152
|
+
// install, a dev build) is the SAME hook, so it goes before ours is added.
|
|
6153
|
+
// Matching on the exact command string alone appended a new set on every
|
|
6154
|
+
// path change and the host ran three caveman hooks per event.
|
|
6155
|
+
const list = (Array.isArray(hooks[event]) ? hooks[event] : [])
|
|
6156
|
+
.filter((entry) => managedHookIdentity(hookEntryCommand(entry) ?? "") !== identity);
|
|
6157
|
+
list.push(nativeHookEntry(command, agentId));
|
|
6008
6158
|
hooks[event] = list;
|
|
6009
6159
|
}
|
|
6010
6160
|
if (includeShrink) {
|
|
6011
6161
|
const shrinkEvent = agentId === "gemini" ? "BeforeTool" : "PreToolUse";
|
|
6012
6162
|
const list = Array.isArray(hooks[shrinkEvent]) ? hooks[shrinkEvent] : [];
|
|
6013
6163
|
const shrinkCommand = `${cavemanBinForHook()} shrink-hook`;
|
|
6164
|
+
// Same replace-not-accumulate rule as the native hook: a shrink-hook entry
|
|
6165
|
+
// under another caveman path is ours.
|
|
6166
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
6167
|
+
const entry = list[i];
|
|
6168
|
+
const existing = entry ? hookEntryCommand(entry) : undefined;
|
|
6169
|
+
if (existing !== undefined && existing !== shrinkCommand && managedHookIdentity(existing) === "shrink-hook")
|
|
6170
|
+
list.splice(i, 1);
|
|
6171
|
+
}
|
|
6014
6172
|
if (!list.some((entry) => hookEntryCommand(entry) === shrinkCommand)) {
|
|
6015
6173
|
list.push(agentId === "gemini"
|
|
6016
6174
|
? { matcher: "run_shell_command", ...nativeHookEntry(shrinkCommand, agentId) }
|
|
@@ -6254,6 +6412,127 @@ function atomicWriteFile(path, bytes, mode = 0o600) {
|
|
|
6254
6412
|
throw error;
|
|
6255
6413
|
}
|
|
6256
6414
|
}
|
|
6415
|
+
function fsyncParentDirectory(path) {
|
|
6416
|
+
let fd;
|
|
6417
|
+
try {
|
|
6418
|
+
fd = openSync(dirname(path), constants.O_RDONLY);
|
|
6419
|
+
fsyncSync(fd);
|
|
6420
|
+
}
|
|
6421
|
+
catch {
|
|
6422
|
+
// Some platforms/filesystems reject directory fsync. File fsync + atomic
|
|
6423
|
+
// rename still provides strongest portable guarantee available to Node.
|
|
6424
|
+
}
|
|
6425
|
+
finally {
|
|
6426
|
+
if (fd !== undefined)
|
|
6427
|
+
try {
|
|
6428
|
+
closeSync(fd);
|
|
6429
|
+
}
|
|
6430
|
+
catch { /* best effort */ }
|
|
6431
|
+
}
|
|
6432
|
+
}
|
|
6433
|
+
function durableAtomicWriteFile(path, bytes, mode = 0o600) {
|
|
6434
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
6435
|
+
const temp = join(dirname(path), `.${basename(path)}.caveman-${process.pid}-${randomUUID()}.tmp`);
|
|
6436
|
+
let fd;
|
|
6437
|
+
try {
|
|
6438
|
+
fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, mode);
|
|
6439
|
+
writeFileSync(fd, bytes);
|
|
6440
|
+
fchmodSync(fd, mode);
|
|
6441
|
+
fsyncSync(fd);
|
|
6442
|
+
closeSync(fd);
|
|
6443
|
+
fd = undefined;
|
|
6444
|
+
renameSync(temp, path);
|
|
6445
|
+
fsyncParentDirectory(path);
|
|
6446
|
+
}
|
|
6447
|
+
catch (error) {
|
|
6448
|
+
if (fd !== undefined)
|
|
6449
|
+
try {
|
|
6450
|
+
closeSync(fd);
|
|
6451
|
+
}
|
|
6452
|
+
catch { /* original error wins */ }
|
|
6453
|
+
try {
|
|
6454
|
+
unlinkSync(temp);
|
|
6455
|
+
}
|
|
6456
|
+
catch { /* no partial */ }
|
|
6457
|
+
throw error;
|
|
6458
|
+
}
|
|
6459
|
+
}
|
|
6460
|
+
// Publish a fully-synced file without replacing an existing intent. Hard-linking
|
|
6461
|
+
// a same-directory temp gives O_EXCL semantics plus atomic visibility.
|
|
6462
|
+
function durableCreateFile(path, bytes, mode = 0o600) {
|
|
6463
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
6464
|
+
const temp = join(dirname(path), `.${basename(path)}.caveman-create-${process.pid}-${randomUUID()}.tmp`);
|
|
6465
|
+
try {
|
|
6466
|
+
durableAtomicWriteFile(temp, bytes, mode);
|
|
6467
|
+
linkSync(temp, path);
|
|
6468
|
+
fsyncParentDirectory(path);
|
|
6469
|
+
}
|
|
6470
|
+
finally {
|
|
6471
|
+
try {
|
|
6472
|
+
unlinkSync(temp);
|
|
6473
|
+
}
|
|
6474
|
+
catch { /* published or failed before temp creation */ }
|
|
6475
|
+
}
|
|
6476
|
+
}
|
|
6477
|
+
function optionalBytesEqual(left, right) {
|
|
6478
|
+
return left === null ? right === null : right !== null && left.equals(right);
|
|
6479
|
+
}
|
|
6480
|
+
function durableReplaceFileIfUnchanged(path, expected, next, mode = 0o600) {
|
|
6481
|
+
const current = fileBytes(path);
|
|
6482
|
+
if (!optionalBytesEqual(current, expected))
|
|
6483
|
+
throw new Error(`${path} changed during MCP update; refusing overwrite`);
|
|
6484
|
+
if (next === null) {
|
|
6485
|
+
if (current !== null) {
|
|
6486
|
+
const atDelete = fileBytes(path);
|
|
6487
|
+
if (!optionalBytesEqual(atDelete, expected))
|
|
6488
|
+
throw new Error(`${path} changed during MCP update; refusing removal`);
|
|
6489
|
+
unlinkSync(path);
|
|
6490
|
+
fsyncParentDirectory(path);
|
|
6491
|
+
}
|
|
6492
|
+
return;
|
|
6493
|
+
}
|
|
6494
|
+
// Prepare durable replacement first, then run final compare immediately
|
|
6495
|
+
// before rename. Per-agent lock serializes Caveman writers; this CAS catches
|
|
6496
|
+
// external edits observed before commit without erasing them.
|
|
6497
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
6498
|
+
const temp = join(dirname(path), `.${basename(path)}.caveman-cas-${process.pid}-${randomUUID()}.tmp`);
|
|
6499
|
+
let fd;
|
|
6500
|
+
try {
|
|
6501
|
+
fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, mode);
|
|
6502
|
+
writeFileSync(fd, next);
|
|
6503
|
+
fchmodSync(fd, mode);
|
|
6504
|
+
fsyncSync(fd);
|
|
6505
|
+
closeSync(fd);
|
|
6506
|
+
fd = undefined;
|
|
6507
|
+
const atCommit = fileBytes(path);
|
|
6508
|
+
if (!optionalBytesEqual(atCommit, expected))
|
|
6509
|
+
throw new Error(`${path} changed during MCP update; refusing overwrite`);
|
|
6510
|
+
renameSync(temp, path);
|
|
6511
|
+
fsyncParentDirectory(path);
|
|
6512
|
+
}
|
|
6513
|
+
catch (error) {
|
|
6514
|
+
if (fd !== undefined)
|
|
6515
|
+
try {
|
|
6516
|
+
closeSync(fd);
|
|
6517
|
+
}
|
|
6518
|
+
catch { /* original error wins */ }
|
|
6519
|
+
try {
|
|
6520
|
+
unlinkSync(temp);
|
|
6521
|
+
}
|
|
6522
|
+
catch { /* no partial */ }
|
|
6523
|
+
throw error;
|
|
6524
|
+
}
|
|
6525
|
+
}
|
|
6526
|
+
function durableUnlink(path) {
|
|
6527
|
+
try {
|
|
6528
|
+
unlinkSync(path);
|
|
6529
|
+
fsyncParentDirectory(path);
|
|
6530
|
+
}
|
|
6531
|
+
catch (error) {
|
|
6532
|
+
if (error.code !== "ENOENT")
|
|
6533
|
+
throw error;
|
|
6534
|
+
}
|
|
6535
|
+
}
|
|
6257
6536
|
function parseJsonFileObject(path, bytes) {
|
|
6258
6537
|
if (!bytes || bytes.length === 0)
|
|
6259
6538
|
return {};
|
|
@@ -6748,15 +7027,23 @@ function aiderNativeMutations(gw) {
|
|
|
6748
7027
|
];
|
|
6749
7028
|
}
|
|
6750
7029
|
function codexNativeConfig(source, gw, subscription, mcpBinary) {
|
|
6751
|
-
|
|
7030
|
+
// Remove caveman's own marker blocks FIRST. The legacy table strippers below
|
|
7031
|
+
// skip every line after a caveman table until the next TOML header, and the
|
|
7032
|
+
// tables block ends with [mcp_servers.caveman] followed by the end marker, so
|
|
7033
|
+
// running them first ate "# <<< caveman:native-tables" and the block this
|
|
7034
|
+
// function had itself written failed its own re-parse as "corrupted" on the
|
|
7035
|
+
// next wrap (every `caveman codex` run fell back to session-only wrap and
|
|
7036
|
+
// doctor reported drift).
|
|
7037
|
+
let stripped = source;
|
|
6752
7038
|
for (const [begin, end] of [[CODEX_NATIVE_ROOT_BEGIN, CODEX_NATIVE_ROOT_END], [CODEX_NATIVE_TABLES_BEGIN, CODEX_NATIVE_TABLES_END]]) {
|
|
6753
7039
|
const start = stripped.indexOf(begin);
|
|
6754
7040
|
const finish = stripped.indexOf(end);
|
|
6755
|
-
if ((start === -1) !== (finish === -1))
|
|
7041
|
+
if ((start === -1) !== (finish === -1) || finish < start)
|
|
6756
7042
|
throw new Error("existing Codex Caveman block is corrupted; run `caveman doctor codex`");
|
|
6757
7043
|
if (start !== -1)
|
|
6758
7044
|
stripped = `${stripped.slice(0, start)}${stripped.slice(finish + end.length)}`.trim();
|
|
6759
7045
|
}
|
|
7046
|
+
stripped = stripCodexCavemanMcpToml(stripCodexCavemanProviderToml(stripped));
|
|
6760
7047
|
const rootBlock = `${CODEX_NATIVE_ROOT_BEGIN}\nmodel_provider = "caveman"\n${CODEX_NATIVE_ROOT_END}`;
|
|
6761
7048
|
const providerLines = codexCavemanProviderToml(gw, subscription).split("\n").slice(1).join("\n");
|
|
6762
7049
|
const tablesBlock = [
|
|
@@ -7150,6 +7437,99 @@ function withIntegrationLock(agent, run) {
|
|
|
7150
7437
|
catch { /* best effort; future process can reclaim stale owner */ }
|
|
7151
7438
|
}
|
|
7152
7439
|
}
|
|
7440
|
+
function withMcpConfigLock(configPath, run) {
|
|
7441
|
+
const canonicalPath = canonicalMcpConfigPath(configPath);
|
|
7442
|
+
const key = createHash("sha256").update(canonicalPath).digest("hex").slice(0, 20);
|
|
7443
|
+
const lock = join(dirname(canonicalPath), `.caveman-mcp-${key}.lock`);
|
|
7444
|
+
const token = randomUUID();
|
|
7445
|
+
const claim = `${lock}.claim-${token}`;
|
|
7446
|
+
const owner = { schema_version: 1, pid: process.pid, token, config_path: canonicalPath, started_at: new Date().toISOString() };
|
|
7447
|
+
mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
|
|
7448
|
+
mkdirSync(claim, { mode: 0o700 });
|
|
7449
|
+
try {
|
|
7450
|
+
durableAtomicWriteFile(join(claim, "owner.json"), Buffer.from(JSON.stringify(owner) + "\n"));
|
|
7451
|
+
try {
|
|
7452
|
+
renameSync(claim, lock);
|
|
7453
|
+
fsyncParentDirectory(lock);
|
|
7454
|
+
}
|
|
7455
|
+
catch (error) {
|
|
7456
|
+
// Rename-to-existing differs by platform (EEXIST, ENOTEMPTY, EPERM,
|
|
7457
|
+
// EACCES). Existing published lock is authority regardless of errno.
|
|
7458
|
+
try {
|
|
7459
|
+
lstatSync(lock);
|
|
7460
|
+
}
|
|
7461
|
+
catch {
|
|
7462
|
+
throw error;
|
|
7463
|
+
}
|
|
7464
|
+
let stale = false;
|
|
7465
|
+
try {
|
|
7466
|
+
const lockStat = lstatSync(lock);
|
|
7467
|
+
const ownerPath = join(lock, "owner.json");
|
|
7468
|
+
const ownerStat = lstatSync(ownerPath);
|
|
7469
|
+
const existing = JSON.parse(readFileSync(ownerPath, "utf8"));
|
|
7470
|
+
const keys = ["config_path", "pid", "schema_version", "started_at", "token"];
|
|
7471
|
+
if (!lockStat.isDirectory() || lockStat.isSymbolicLink()
|
|
7472
|
+
|| !ownerStat.isFile() || ownerStat.isSymbolicLink()
|
|
7473
|
+
|| readdirSync(lock).sort().join("\0") !== "owner.json"
|
|
7474
|
+
|| Object.keys(existing).sort().join("\0") !== keys.join("\0")
|
|
7475
|
+
|| existing.schema_version !== 1
|
|
7476
|
+
|| typeof existing.pid !== "number" || !Number.isInteger(existing.pid) || existing.pid <= 1
|
|
7477
|
+
|| typeof existing.token !== "string"
|
|
7478
|
+
|| !/^[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)
|
|
7479
|
+
|| existing.config_path !== canonicalPath
|
|
7480
|
+
|| typeof existing.started_at !== "string"
|
|
7481
|
+
|| new Date(existing.started_at).toISOString() !== existing.started_at
|
|
7482
|
+
|| process.platform !== "win32" && ((lockStat.mode | ownerStat.mode) & 0o077) !== 0) {
|
|
7483
|
+
throw new Error("invalid MCP lock owner");
|
|
7484
|
+
}
|
|
7485
|
+
try {
|
|
7486
|
+
process.kill(existing.pid, 0);
|
|
7487
|
+
}
|
|
7488
|
+
catch (probeError) {
|
|
7489
|
+
stale = probeError.code === "ESRCH";
|
|
7490
|
+
}
|
|
7491
|
+
}
|
|
7492
|
+
catch {
|
|
7493
|
+
// Populated claim is durable before publication, so malformed or
|
|
7494
|
+
// ownerless lock can never be our crash residue. Never delete it.
|
|
7495
|
+
stale = false;
|
|
7496
|
+
}
|
|
7497
|
+
if (!stale)
|
|
7498
|
+
throw new Error(`MCP config change already running for ${canonicalPath}`);
|
|
7499
|
+
const quarantine = `${lock}.stale-${token}`;
|
|
7500
|
+
try {
|
|
7501
|
+
renameSync(lock, quarantine);
|
|
7502
|
+
renameSync(claim, lock);
|
|
7503
|
+
fsyncParentDirectory(lock);
|
|
7504
|
+
process.stderr.write(`${mark("warn")} reclaimed stale MCP config lock for ${canonicalPath}\n`);
|
|
7505
|
+
}
|
|
7506
|
+
catch {
|
|
7507
|
+
throw new Error(`MCP config change already running for ${canonicalPath}`);
|
|
7508
|
+
}
|
|
7509
|
+
finally {
|
|
7510
|
+
try {
|
|
7511
|
+
rmSync(quarantine, { recursive: true, force: true });
|
|
7512
|
+
}
|
|
7513
|
+
catch { /* isolated stale lock only */ }
|
|
7514
|
+
}
|
|
7515
|
+
}
|
|
7516
|
+
return run();
|
|
7517
|
+
}
|
|
7518
|
+
finally {
|
|
7519
|
+
try {
|
|
7520
|
+
rmSync(claim, { recursive: true, force: true });
|
|
7521
|
+
}
|
|
7522
|
+
catch { /* published or absent */ }
|
|
7523
|
+
try {
|
|
7524
|
+
const current = JSON.parse(readFileSync(join(lock, "owner.json"), "utf8"));
|
|
7525
|
+
if (current.token === token) {
|
|
7526
|
+
rmSync(lock, { recursive: true, force: true });
|
|
7527
|
+
fsyncParentDirectory(lock);
|
|
7528
|
+
}
|
|
7529
|
+
}
|
|
7530
|
+
catch { /* only owning token may remove a published lock */ }
|
|
7531
|
+
}
|
|
7532
|
+
}
|
|
7153
7533
|
function applyNativeMutations(agent, profile, mutations) {
|
|
7154
7534
|
const base = join(cavemanHome(), "integrations", "backups", agent, randomUUID());
|
|
7155
7535
|
mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
@@ -8250,14 +8630,53 @@ function withoutCavemanMcpServer(overlay) {
|
|
|
8250
8630
|
delete next["mcp"];
|
|
8251
8631
|
return next;
|
|
8252
8632
|
}
|
|
8253
|
-
function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "auto") {
|
|
8633
|
+
function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "auto", agentArgs = []) {
|
|
8254
8634
|
const baseConfig = readBaseConfig(inj);
|
|
8255
8635
|
const mode = wrapMode(modeGw);
|
|
8256
8636
|
const staticOverlay = mode === "managed" && inj.config_overlay.managed !== undefined ? inj.config_overlay.managed : inj.config_overlay.local;
|
|
8257
8637
|
const builder = overlayBuilders[agent.id];
|
|
8258
|
-
const
|
|
8259
|
-
|
|
8638
|
+
const renderOptions = {};
|
|
8639
|
+
if (agent.id === "qwen" && mode === "managed") {
|
|
8640
|
+
const available = qwenEffectiveOpenAIKeyAvailable();
|
|
8641
|
+
if (available === null)
|
|
8642
|
+
throw new Error("cannot safely resolve Qwen's effective OPENAI_API_KEY");
|
|
8643
|
+
renderOptions.optionalOpenAIKeyEnvAvailable = available;
|
|
8644
|
+
}
|
|
8645
|
+
let rawOverlay = renderDeep(builder ? builder(agent, baseConfig, { mode, gatewayUrl: gw, env }) : staticOverlay, gw, env, renderOptions);
|
|
8646
|
+
if (agent.id === "qwen" && mcpMode === "auto") {
|
|
8647
|
+
const ownedMcp = ownedMcpRegistration(agent.id, agentArgs);
|
|
8648
|
+
if (ownedMcp) {
|
|
8649
|
+
// Qwen merges system settings last. Mirror only a still-journaled native
|
|
8650
|
+
// entry into this temporary system overlay so project settings cannot
|
|
8651
|
+
// replace the recovery server after Caveman has claimed it is available.
|
|
8652
|
+
rawOverlay = deepMerge(rawOverlay, { mcpServers: { caveman: qwenMcpEntry(ownedMcp) } });
|
|
8653
|
+
}
|
|
8654
|
+
else {
|
|
8655
|
+
// Qwen can advertise MCP schemas even when enterprise policy blocks calls.
|
|
8656
|
+
// Suppress the exact server in this highest-precedence temporary overlay
|
|
8657
|
+
// whenever native registration + journal + effective policy do not agree.
|
|
8658
|
+
const configured = jsonValueAt(baseConfig, ["mcp", "excluded"]);
|
|
8659
|
+
const preserved = Array.isArray(configured)
|
|
8660
|
+
? configured.filter((item) => typeof item === "string")
|
|
8661
|
+
: [];
|
|
8662
|
+
rawOverlay = deepMerge(rawOverlay, {
|
|
8663
|
+
mcp: { excluded: [...new Set([...preserved, "caveman"])] },
|
|
8664
|
+
});
|
|
8665
|
+
}
|
|
8666
|
+
}
|
|
8667
|
+
const overlay = (mcpMode === "auto" ? rawOverlay : withoutCavemanMcpServer(rawOverlay));
|
|
8260
8668
|
const merged = deepMerge(baseConfig, overlay);
|
|
8669
|
+
if (agent.id === "qwen") {
|
|
8670
|
+
// Qwen treats these as whole-object REPLACE settings. Our generic merge is
|
|
8671
|
+
// intentionally conservative for other agents, but retaining a sibling
|
|
8672
|
+
// provider here would make it selectable at runtime outside /w/qwen.
|
|
8673
|
+
for (const key of ["modelProviders", "providerProtocol"]) {
|
|
8674
|
+
const value = overlay[key];
|
|
8675
|
+
if (value === undefined)
|
|
8676
|
+
throw new Error(`Qwen routed profile is missing ${key}`);
|
|
8677
|
+
merged[key] = cloneJsonValue(value);
|
|
8678
|
+
}
|
|
8679
|
+
}
|
|
8261
8680
|
const rendered = JSON.stringify(merged, null, 2);
|
|
8262
8681
|
if (rendered === undefined)
|
|
8263
8682
|
throw new Error("merged config is not JSON");
|
|
@@ -8395,14 +8814,14 @@ function applyClaudeBedrockWrap(env, agent, renderedGw, modeGw) {
|
|
|
8395
8814
|
// - config-env-content: render the mode-selected inline config and set it as one var
|
|
8396
8815
|
// - config-file: merge a mode-selected overlay into a temp config file
|
|
8397
8816
|
// An unrecognized method falls through to the generic union (fail-open), not a guess.
|
|
8398
|
-
// mcpMode governs
|
|
8399
|
-
//
|
|
8817
|
+
// mcpMode governs every temporary config arm that can inject the caveman MCP
|
|
8818
|
+
// server. It defaults to "auto" — today's behavior — rather than
|
|
8400
8819
|
// resolving config here, so this exported function stays a function of its
|
|
8401
8820
|
// arguments and cannot pick up the developer's own global config in tests. The
|
|
8402
8821
|
// one production caller passes the SAME opts.mcpMode that wrapMcpRecoveryAvailable
|
|
8403
8822
|
// reads, which is what keeps "what we inject" and "what we tell the proxy" from
|
|
8404
8823
|
// ever disagreeing.
|
|
8405
|
-
export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
8824
|
+
export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentArgs = []) {
|
|
8406
8825
|
if (agent?.id === "gemini" && wrapMode(gw) === "managed") {
|
|
8407
8826
|
throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
|
|
8408
8827
|
}
|
|
@@ -8420,6 +8839,23 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
|
8420
8839
|
return env;
|
|
8421
8840
|
if (applyClaudeBedrockWrap(env, agent, renderedGw, gw))
|
|
8422
8841
|
return env;
|
|
8842
|
+
const routeOverride = agentRouteOverride(agent, agentArgs);
|
|
8843
|
+
if (agent.id === "qwen") {
|
|
8844
|
+
const override = routeOverride;
|
|
8845
|
+
if (override?.surface === "effective settings") {
|
|
8846
|
+
throw new Error("cannot safely resolve Qwen's effective settings");
|
|
8847
|
+
}
|
|
8848
|
+
if (override?.surface === "--safe-mode" && override.reason === "ignores Caveman system settings") {
|
|
8849
|
+
throw new Error("Qwen safe mode ignores Caveman system settings");
|
|
8850
|
+
}
|
|
8851
|
+
// These environment switches outrank settings in pinned Qwen 0.22.3.
|
|
8852
|
+
// Keep side-request tools and workflow-spawned agents off in routed mode;
|
|
8853
|
+
// corresponding system settings provide the durable second lock.
|
|
8854
|
+
env.ENABLE_WEB_SEARCH = "0";
|
|
8855
|
+
env.QWEN_CODE_DISABLE_WORKFLOWS = "1";
|
|
8856
|
+
}
|
|
8857
|
+
if (routeOverride)
|
|
8858
|
+
throw new Error(`${routeOverrideLabel(agent)} ${routeOverride.surface} ${routeOverride.reason}`);
|
|
8423
8859
|
const inj = agent.injection;
|
|
8424
8860
|
if (inj.method === "env") {
|
|
8425
8861
|
for (const [k, raw] of Object.entries(inj.env)) {
|
|
@@ -8431,21 +8867,42 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
|
8431
8867
|
else if (inj.method === "config-env-content") {
|
|
8432
8868
|
const cc = inj.config_content;
|
|
8433
8869
|
const content = wrapMode(gw) === "managed" && cc.managed !== undefined ? cc.managed : cc.local;
|
|
8434
|
-
|
|
8870
|
+
const renderOptions = agent.id === "kilo"
|
|
8871
|
+
? { optionalOpenAIKeyReference: "{env:OPENAI_API_KEY}" }
|
|
8872
|
+
: {};
|
|
8873
|
+
let rendered = renderDeep(content, renderedGw, env, renderOptions);
|
|
8874
|
+
if (agent.id === "kilo" && mcpMode === "auto") {
|
|
8875
|
+
const ownedMcp = ownedMcpRegistration(agent.id, agentArgs);
|
|
8876
|
+
if (ownedMcp) {
|
|
8877
|
+
// Project exact owned registration into Kilo's highest user-controlled
|
|
8878
|
+
// layer. Route preflight rejects active org/managed sources that load
|
|
8879
|
+
// afterward, so no later known policy can silently disable recovery.
|
|
8880
|
+
rendered = deepMerge(rendered, { mcp: { caveman: kiloMcpEntry(ownedMcp) } });
|
|
8881
|
+
}
|
|
8882
|
+
}
|
|
8883
|
+
env[inj.env_var] = JSON.stringify(rendered);
|
|
8435
8884
|
}
|
|
8436
8885
|
else if (inj.method === "config-file") {
|
|
8437
8886
|
try {
|
|
8438
|
-
applyConfigFileInjection(env, agent, inj, renderedGw, gw, mcpMode);
|
|
8887
|
+
applyConfigFileInjection(env, agent, inj, renderedGw, gw, mcpMode, agentArgs);
|
|
8439
8888
|
}
|
|
8440
8889
|
catch (e) {
|
|
8441
8890
|
// OpenClaw ignores the generic base-URL union. Config injection is its only
|
|
8442
8891
|
// provider redirect, so a failed/missing route must abort the wrapped path;
|
|
8443
8892
|
// spawnWrapped then launches direct with an explicit warning.
|
|
8444
|
-
if (agent.id === "openclaw")
|
|
8893
|
+
if (agent.id === "openclaw" || agent.id === "qwen")
|
|
8445
8894
|
throw e;
|
|
8446
8895
|
process.stderr.write(`caveman: ${agent.id} config-file injection failed; using generic env wrap (${e.message})\n`);
|
|
8447
8896
|
}
|
|
8448
8897
|
}
|
|
8898
|
+
// Qwen 0.22 discovers MCP servers in the background by default. Its first
|
|
8899
|
+
// request can therefore omit caveman_retrieve even though our durable marker
|
|
8900
|
+
// says recovery is installed. Proxy compression must never outrun recovery,
|
|
8901
|
+
// so marker-backed Qwen wraps use Qwen's compatibility switch to finish MCP
|
|
8902
|
+
// discovery before the first model request.
|
|
8903
|
+
if (agent.id === "qwen" && mcpInstalled(agent.id, agentArgs)) {
|
|
8904
|
+
env.QWEN_CODE_LEGACY_MCP_BLOCKING = "1";
|
|
8905
|
+
}
|
|
8449
8906
|
if (agent.id === "hermes")
|
|
8450
8907
|
applyHermesAuthEnv(env, renderedGw, gw);
|
|
8451
8908
|
if (agent.id === "claude" && wrapMode(gw) === "local" && env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined && proxyAnthropicUpstreamIsFirstParty()) {
|
|
@@ -9533,6 +9990,41 @@ function cavemanBin(name, envVar) {
|
|
|
9533
9990
|
function mcpServerMarkerPath(agentId, serverName) {
|
|
9534
9991
|
return join(cavemanHome(), "mcp", serverName === "caveman" ? `${agentId}.json` : `${agentId}.${serverName}.json`);
|
|
9535
9992
|
}
|
|
9993
|
+
function canonicalOwnedMcpMarkerPath(agent, serverName) {
|
|
9994
|
+
const path = mcpServerMarkerPath(agent, serverName);
|
|
9995
|
+
try {
|
|
9996
|
+
if (lstatSync(path).isSymbolicLink()) {
|
|
9997
|
+
throw new Error(`${path} is a symlink; refusing transactional ownership mutation`);
|
|
9998
|
+
}
|
|
9999
|
+
}
|
|
10000
|
+
catch (error) {
|
|
10001
|
+
if (error.code !== "ENOENT")
|
|
10002
|
+
throw error;
|
|
10003
|
+
}
|
|
10004
|
+
return canonicalMcpConfigPath(path);
|
|
10005
|
+
}
|
|
10006
|
+
// A native MCP registration and its Caveman ownership journal form one logical
|
|
10007
|
+
// write. Prove the journal directory is writable before touching agent config;
|
|
10008
|
+
// otherwise Kilo/Qwen would refuse both a later upgrade and removal because the
|
|
10009
|
+
// surviving registration has no trustworthy owner.
|
|
10010
|
+
function preflightMcpServerMarker(agentId, serverName) {
|
|
10011
|
+
const path = mcpServerMarkerPath(agentId, serverName);
|
|
10012
|
+
const probe = join(dirname(path), `.${basename(path)}.preflight-${process.pid}-${randomUUID()}`);
|
|
10013
|
+
try {
|
|
10014
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
10015
|
+
chmodSync(dirname(path), 0o700);
|
|
10016
|
+
durableAtomicWriteFile(probe, Buffer.alloc(0));
|
|
10017
|
+
unlinkSync(probe);
|
|
10018
|
+
fsyncParentDirectory(probe);
|
|
10019
|
+
}
|
|
10020
|
+
catch (error) {
|
|
10021
|
+
try {
|
|
10022
|
+
unlinkSync(probe);
|
|
10023
|
+
}
|
|
10024
|
+
catch { /* no probe survived */ }
|
|
10025
|
+
throw new Error(`cannot persist ${agentId} ${serverName} MCP ownership journal at ${path}: ${error.message}`);
|
|
10026
|
+
}
|
|
10027
|
+
}
|
|
9536
10028
|
function mcpMarkerPath(agentId) {
|
|
9537
10029
|
return mcpServerMarkerPath(agentId, "caveman");
|
|
9538
10030
|
}
|
|
@@ -9544,7 +10036,9 @@ function mcpServerInstalled(agentId, serverName) {
|
|
|
9544
10036
|
return false;
|
|
9545
10037
|
}
|
|
9546
10038
|
}
|
|
9547
|
-
function mcpInstalled(agentId) {
|
|
10039
|
+
function mcpInstalled(agentId, agentArgs = []) {
|
|
10040
|
+
if (agentId === "kilo" || agentId === "qwen")
|
|
10041
|
+
return ownedMcpRegistration(agentId, agentArgs) !== null;
|
|
9548
10042
|
return mcpServerInstalled(agentId, "caveman");
|
|
9549
10043
|
}
|
|
9550
10044
|
// configFileOverlayHasMcp asks whether the PROFILE would inject this MCP server
|
|
@@ -9582,7 +10076,7 @@ function queueStaleMcpBinary(probe) {
|
|
|
9582
10076
|
// that is — the proxy would otherwise either elide bytes nothing can expand, or
|
|
9583
10077
|
// pass through while the agent still pays for tools it isn't allowed to use.
|
|
9584
10078
|
// (honesty rule: no-placeholder)
|
|
9585
|
-
function wrapMcpRecoveryAvailable(agent, opts) {
|
|
10079
|
+
function wrapMcpRecoveryAvailable(agent, opts, agentArgs = []) {
|
|
9586
10080
|
if (!wrapRecoveryEligible(opts) || !agent)
|
|
9587
10081
|
return false;
|
|
9588
10082
|
if (agent.id === "pi") {
|
|
@@ -9593,13 +10087,19 @@ function wrapMcpRecoveryAvailable(agent, opts) {
|
|
|
9593
10087
|
queueStaleMcpBinary(compatibility.probe);
|
|
9594
10088
|
return compatibility.probe.current;
|
|
9595
10089
|
}
|
|
10090
|
+
// Kilo and Qwen can apply policy after user-owned config. Never turn their
|
|
10091
|
+
// durable marker into a proxy-wide recovery assertion: each request must
|
|
10092
|
+
// carry the exact namespaced retrieve tool and prove recovery in band. The
|
|
10093
|
+
// validated registration below still drives launch-time projection/blocking.
|
|
10094
|
+
if (agent.id === "kilo" || agent.id === "qwen")
|
|
10095
|
+
return false;
|
|
9596
10096
|
// Two independent sources of a real caveman_retrieve: a marker from
|
|
9597
10097
|
// `caveman tools mcp install`, or the profile's own config-file overlay. The
|
|
9598
10098
|
// second only counts under `auto`, because that is exactly when buildWrapEnv
|
|
9599
10099
|
// still merges it — under marker-only/false the overlay is stripped, so
|
|
9600
10100
|
// counting it here would tell the proxy about a tool this launch removed.
|
|
9601
10101
|
const overlayInjects = opts.mcpMode === "auto" && configFileOverlayHasCavemanMcp(agent);
|
|
9602
|
-
if (!mcpInstalled(agent.id) && !overlayInjects)
|
|
10102
|
+
if (!mcpInstalled(agent.id, agentArgs) && !overlayInjects)
|
|
9603
10103
|
return false;
|
|
9604
10104
|
const compatibility = probeMcpBinary();
|
|
9605
10105
|
if (!compatibility)
|
|
@@ -9611,8 +10111,10 @@ function wrapMcpRecoveryAvailable(agent, opts) {
|
|
|
9611
10111
|
return true;
|
|
9612
10112
|
}
|
|
9613
10113
|
// Bare start cannot bind a machine-level MCP marker or inherited opt-in to the
|
|
9614
|
-
// client issuing a later request
|
|
9615
|
-
//
|
|
10114
|
+
// client issuing a later request, so it never CLAIMS recovery on their behalf:
|
|
10115
|
+
// CAVEMAN_RECOVERY stays off and the proxy decides per request, from the caveman
|
|
10116
|
+
// retrieve tool the caller's own tool list carries (gateway.mcpRecoveryAvailable).
|
|
10117
|
+
// Agent-scoped wrap performs the only supported out-of-band compatibility check.
|
|
9616
10118
|
function startMcpRecoveryAvailable() {
|
|
9617
10119
|
return false;
|
|
9618
10120
|
}
|
|
@@ -9850,20 +10352,28 @@ function mcpUninstall(target, serverName = "caveman") {
|
|
|
9850
10352
|
targets = [a];
|
|
9851
10353
|
}
|
|
9852
10354
|
else {
|
|
9853
|
-
targets = AGENTS.filter((a) => mcpServerInstalled(a.id, serverName)
|
|
10355
|
+
targets = AGENTS.filter((a) => mcpServerInstalled(a.id, serverName)
|
|
10356
|
+
|| ((a.id === "kilo" || a.id === "qwen") && (existsSync(mcpPendingJournalPath(a.id, serverName))
|
|
10357
|
+
|| existsSync(mcpConfigPendingJournalPath(a.id === "kilo" ? kiloConfigPath() : qwenConfigPath())))));
|
|
9854
10358
|
if (targets.length === 0) {
|
|
9855
10359
|
console.error(`no agents have the ${serverName} MCP tool installed`);
|
|
9856
10360
|
return;
|
|
9857
10361
|
}
|
|
9858
10362
|
}
|
|
9859
10363
|
for (const a of targets) {
|
|
9860
|
-
|
|
9861
|
-
|
|
9862
|
-
|
|
9863
|
-
}
|
|
9864
|
-
catch {
|
|
9865
|
-
// marker already gone — the visible state is what matters.
|
|
10364
|
+
const uninstallOne = (lockedConfigPath) => {
|
|
10365
|
+
if (a.id === "kilo" || a.id === "qwen") {
|
|
10366
|
+
return transactOwnedMcpConfig(a.id, serverName, "uninstall", undefined, lockedConfigPath);
|
|
9866
10367
|
}
|
|
10368
|
+
if (!uninstallMcpForAgent(a, serverName))
|
|
10369
|
+
return false;
|
|
10370
|
+
durableUnlink(mcpServerMarkerPath(a.id, serverName));
|
|
10371
|
+
return true;
|
|
10372
|
+
};
|
|
10373
|
+
const removed = a.id === "kilo" || a.id === "qwen"
|
|
10374
|
+
? withOwnedMcpTransactionLock(a.id, serverName, uninstallOne)
|
|
10375
|
+
: uninstallOne();
|
|
10376
|
+
if (removed) {
|
|
9867
10377
|
process.stderr.write(`${mark("ok")} ${a.display_name}: ${serverName} MCP tool removed\n`);
|
|
9868
10378
|
}
|
|
9869
10379
|
}
|
|
@@ -9886,6 +10396,9 @@ function uninstallMcpForAgent(a, serverName = "caveman") {
|
|
|
9886
10396
|
return removeMcpCodexToml(serverName);
|
|
9887
10397
|
case "opencode":
|
|
9888
10398
|
return removeMcpJson(join(homedir(), ".config", "opencode", "opencode.json"), ["mcp", serverName]);
|
|
10399
|
+
case "kilo":
|
|
10400
|
+
case "qwen":
|
|
10401
|
+
throw new Error(`${a.display_name} MCP changes require the ownership transaction`);
|
|
9889
10402
|
case "gemini":
|
|
9890
10403
|
return removeMcpJson(join(homedir(), ".gemini", "settings.json"), ["mcpServers", serverName]);
|
|
9891
10404
|
case "hermes":
|
|
@@ -9964,63 +10477,1974 @@ function removeMcpJson(path, keyPath) {
|
|
|
9964
10477
|
return false;
|
|
9965
10478
|
}
|
|
9966
10479
|
}
|
|
9967
|
-
function
|
|
9968
|
-
if (
|
|
9969
|
-
|
|
9970
|
-
|
|
10480
|
+
function kiloPathFromEnv(value, name) {
|
|
10481
|
+
if (/[\0\r\n]/.test(value))
|
|
10482
|
+
throw new Error(`${name} contains an invalid path character`);
|
|
10483
|
+
// Kilo passes env paths directly to its loader. Shell-style "~/" expansion
|
|
10484
|
+
// does not occur inside an environment value; relative paths resolve from cwd.
|
|
10485
|
+
return normalize(isAbsolute(value) ? value : resolve(value));
|
|
10486
|
+
}
|
|
10487
|
+
function kiloConfigInDirectory(directory, source) {
|
|
10488
|
+
// Mirror pinned Kilo's native global writer: prefer an existing canonical
|
|
10489
|
+
// config in this order, otherwise create kilo.json. JSONC stays read-only here
|
|
10490
|
+
// because a JSON stringify would destroy comments.
|
|
10491
|
+
const candidates = ["kilo.jsonc", "kilo.json", "opencode.jsonc", "opencode.json"];
|
|
10492
|
+
const selected = candidates.map((name) => join(directory, name)).find((path) => existsSync(path))
|
|
10493
|
+
?? join(directory, "kilo.json");
|
|
10494
|
+
return { path: selected, jsonc: extname(selected).toLowerCase() === ".jsonc", source };
|
|
10495
|
+
}
|
|
10496
|
+
// Kilo 7.5.6's native config writer targets KILO_CONFIG_DIR when present. That
|
|
10497
|
+
// directory is also loaded after KILO_CONFIG, so it must win for effective MCP
|
|
10498
|
+
// ownership. Explicit KILO_CONFIG wins only without a custom config directory;
|
|
10499
|
+
// xdg-basedir is the final fallback.
|
|
10500
|
+
function kiloConfigLocation() {
|
|
10501
|
+
const configuredDirectory = process.env.KILO_CONFIG_DIR;
|
|
10502
|
+
if (configuredDirectory) {
|
|
10503
|
+
return kiloConfigInDirectory(kiloPathFromEnv(configuredDirectory, "KILO_CONFIG_DIR"), "KILO_CONFIG_DIR");
|
|
10504
|
+
}
|
|
10505
|
+
const explicit = process.env.KILO_CONFIG;
|
|
10506
|
+
if (explicit) {
|
|
10507
|
+
const path = kiloPathFromEnv(explicit, "KILO_CONFIG");
|
|
10508
|
+
return { path, jsonc: extname(path).toLowerCase() === ".jsonc", source: "KILO_CONFIG" };
|
|
10509
|
+
}
|
|
10510
|
+
// Pinned Kilo strips accidental newlines from xdg-basedir output before use.
|
|
10511
|
+
const configuredRoot = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
10512
|
+
const cleanedRoot = configuredRoot.replace(/[\r\n]+/g, "");
|
|
10513
|
+
if (!cleanedRoot)
|
|
10514
|
+
throw new Error("Kilo config root resolves to an empty path");
|
|
10515
|
+
const root = normalize(isAbsolute(cleanedRoot) ? cleanedRoot : resolve(cleanedRoot));
|
|
10516
|
+
return kiloConfigInDirectory(join(root, "kilo"), "XDG_CONFIG_HOME");
|
|
10517
|
+
}
|
|
10518
|
+
function kiloConfigPath() {
|
|
10519
|
+
return kiloConfigLocation().path;
|
|
10520
|
+
}
|
|
10521
|
+
function kiloMcpEntry(mcp) {
|
|
10522
|
+
return {
|
|
10523
|
+
type: "local",
|
|
10524
|
+
command: [mcp.command, ...mcp.args],
|
|
10525
|
+
enabled: true,
|
|
10526
|
+
};
|
|
10527
|
+
}
|
|
10528
|
+
function kiloMcpEntryMatches(value, mcp) {
|
|
10529
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
10530
|
+
return false;
|
|
10531
|
+
const entry = value;
|
|
10532
|
+
const keys = Object.keys(entry).sort();
|
|
10533
|
+
const command = [mcp.command, ...mcp.args];
|
|
10534
|
+
if (keys.length !== 3 || keys[0] !== "command" || keys[1] !== "enabled" || keys[2] !== "type")
|
|
10535
|
+
return false;
|
|
10536
|
+
return entry.type === "local"
|
|
10537
|
+
&& entry.enabled === true
|
|
10538
|
+
&& Array.isArray(entry.command)
|
|
10539
|
+
&& entry.command.length === command.length
|
|
10540
|
+
&& entry.command.every((arg, index) => typeof arg === "string" && arg === command[index]);
|
|
10541
|
+
}
|
|
10542
|
+
function readStrictMcpJsonRoot(path) {
|
|
10543
|
+
let bytes;
|
|
10544
|
+
try {
|
|
10545
|
+
bytes = readFileSync(path);
|
|
9971
10546
|
}
|
|
9972
|
-
|
|
9973
|
-
|
|
9974
|
-
|
|
10547
|
+
catch (e) {
|
|
10548
|
+
if (e.code === "ENOENT")
|
|
10549
|
+
return { root: {}, exists: false, bytes: null };
|
|
10550
|
+
console.error(`${mark("warn")} cannot read ${path}: ${e.message}; not modifying it`);
|
|
10551
|
+
return null;
|
|
9975
10552
|
}
|
|
9976
|
-
|
|
9977
|
-
|
|
9978
|
-
if (!
|
|
9979
|
-
console.error("
|
|
9980
|
-
|
|
10553
|
+
const raw = bytes.toString("utf8");
|
|
10554
|
+
try {
|
|
10555
|
+
if (!raw.trim()) {
|
|
10556
|
+
console.error(`${mark("warn")} ${path} is empty; not modifying it`);
|
|
10557
|
+
return null;
|
|
9981
10558
|
}
|
|
9982
|
-
|
|
9983
|
-
|
|
9984
|
-
|
|
9985
|
-
|
|
9986
|
-
if (!resolved) {
|
|
9987
|
-
console.error("caveman-delegate-mcp.mjs not found — set CAVEMAN_DELEGATE_MCP to the script path");
|
|
9988
|
-
process.exit(1);
|
|
10559
|
+
const parsed = JSON.parse(raw);
|
|
10560
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
10561
|
+
console.error(`${mark("warn")} ${path} is not a JSON object; not modifying it`);
|
|
10562
|
+
return null;
|
|
9989
10563
|
}
|
|
9990
|
-
|
|
10564
|
+
return { root: parsed, exists: true, bytes };
|
|
9991
10565
|
}
|
|
9992
|
-
|
|
9993
|
-
|
|
10566
|
+
catch (e) {
|
|
10567
|
+
console.error(`${mark("warn")} cannot read ${path}: ${e.message}; not modifying it`);
|
|
10568
|
+
return null;
|
|
9994
10569
|
}
|
|
9995
|
-
|
|
9996
|
-
|
|
9997
|
-
|
|
9998
|
-
|
|
9999
|
-
|
|
10000
|
-
|
|
10570
|
+
}
|
|
10571
|
+
function canonicalMcpConfigPath(path) {
|
|
10572
|
+
const absolute = normalize(resolve(path));
|
|
10573
|
+
const missing = [];
|
|
10574
|
+
let ancestor = absolute;
|
|
10575
|
+
while (true) {
|
|
10576
|
+
try {
|
|
10577
|
+
return normalize(join(realpathSync(ancestor), ...missing));
|
|
10578
|
+
}
|
|
10579
|
+
catch {
|
|
10580
|
+
try {
|
|
10581
|
+
if (lstatSync(ancestor).isSymbolicLink()) {
|
|
10582
|
+
throw new Error(`MCP config path contains dangling symlink ${ancestor}; refusing mutation`);
|
|
10583
|
+
}
|
|
10584
|
+
}
|
|
10585
|
+
catch (error) {
|
|
10586
|
+
if (error.code !== "ENOENT")
|
|
10587
|
+
throw error;
|
|
10588
|
+
}
|
|
10589
|
+
const parent = dirname(ancestor);
|
|
10590
|
+
if (parent === ancestor)
|
|
10591
|
+
return absolute;
|
|
10592
|
+
missing.unshift(basename(ancestor));
|
|
10593
|
+
ancestor = parent;
|
|
10001
10594
|
}
|
|
10002
|
-
targets = [a];
|
|
10003
10595
|
}
|
|
10004
|
-
|
|
10005
|
-
|
|
10006
|
-
|
|
10007
|
-
|
|
10008
|
-
|
|
10596
|
+
}
|
|
10597
|
+
function ownedMcpConfigPlan(agent, path, loaded, after) {
|
|
10598
|
+
const canonicalPath = canonicalMcpConfigPath(path);
|
|
10599
|
+
let beforeMode = 0o600;
|
|
10600
|
+
if (loaded.exists) {
|
|
10601
|
+
beforeMode = statSync(canonicalPath).mode & 0o777;
|
|
10602
|
+
if (!optionalBytesEqual(fileBytes(canonicalPath), loaded.bytes)) {
|
|
10603
|
+
throw new Error(`${canonicalPath} changed while planning MCP update; refusing overwrite`);
|
|
10009
10604
|
}
|
|
10010
10605
|
}
|
|
10011
|
-
|
|
10012
|
-
|
|
10013
|
-
|
|
10014
|
-
|
|
10015
|
-
|
|
10016
|
-
|
|
10017
|
-
|
|
10018
|
-
|
|
10019
|
-
|
|
10020
|
-
|
|
10021
|
-
|
|
10022
|
-
|
|
10023
|
-
|
|
10606
|
+
return {
|
|
10607
|
+
agent,
|
|
10608
|
+
path: canonicalPath,
|
|
10609
|
+
before: loaded.bytes,
|
|
10610
|
+
beforeMode,
|
|
10611
|
+
after,
|
|
10612
|
+
changed: !optionalBytesEqual(loaded.bytes, after),
|
|
10613
|
+
};
|
|
10614
|
+
}
|
|
10615
|
+
function movedOwnedMcpEntryState(agent, serverName, marker) {
|
|
10616
|
+
const activePath = canonicalMcpConfigPath(agent === "kilo" ? kiloConfigPath() : qwenConfigPath());
|
|
10617
|
+
if (marker.config_path === activePath || fileBytes(activePath) === null)
|
|
10618
|
+
return "absent";
|
|
10619
|
+
const root = agent === "kilo" ? readOptionalJsonObject(activePath) : readQwenJsonObject(activePath);
|
|
10620
|
+
if (!root)
|
|
10621
|
+
return "ambiguous";
|
|
10622
|
+
const entry = jsonValueAt(root, agent === "kilo" ? ["mcp", serverName] : ["mcpServers", serverName]);
|
|
10623
|
+
if (entry === undefined)
|
|
10624
|
+
return "absent";
|
|
10625
|
+
// Exact match proves a physical move; a different value can be same moved
|
|
10626
|
+
// registration edited afterward. Both retain ownership marker fail-closed.
|
|
10627
|
+
return "present";
|
|
10628
|
+
}
|
|
10629
|
+
function movedOwnedMcpRemovalBlocked(agent, serverName, marker) {
|
|
10630
|
+
const state = movedOwnedMcpEntryState(agent, serverName, marker);
|
|
10631
|
+
if (state === "absent")
|
|
10632
|
+
return false;
|
|
10633
|
+
const activePath = canonicalMcpConfigPath(agent === "kilo" ? kiloConfigPath() : qwenConfigPath());
|
|
10634
|
+
console.error(`${mark("warn")} recorded ${agent} MCP config is missing while ${activePath} ${state === "present" ? "contains" : "may contain"} moved ${serverName} state; retaining ownership marker`);
|
|
10635
|
+
return true;
|
|
10636
|
+
}
|
|
10637
|
+
function kiloJsoncBlocksMutation(path) {
|
|
10638
|
+
const location = kiloConfigLocation();
|
|
10639
|
+
if (location.jsonc && canonicalMcpConfigPath(location.path) === path) {
|
|
10640
|
+
console.error(`${mark("warn")} ${location.source} selects JSONC ${path}; refusing comment-destructive mutation`);
|
|
10641
|
+
return true;
|
|
10642
|
+
}
|
|
10643
|
+
return false;
|
|
10644
|
+
}
|
|
10645
|
+
function planMcpKiloJson(mcp, serverName = "caveman") {
|
|
10646
|
+
const path = canonicalMcpConfigPath(kiloConfigPath());
|
|
10647
|
+
const marker = readMcpServerMarker("kilo", serverName);
|
|
10648
|
+
if (marker?.config_path && marker.config_path !== path) {
|
|
10649
|
+
console.error(`${mark("warn")} ${serverName} is owned in ${marker.config_path}; uninstall it before installing into ${path}`);
|
|
10650
|
+
return null;
|
|
10651
|
+
}
|
|
10652
|
+
if (kiloJsoncBlocksMutation(path))
|
|
10653
|
+
return null;
|
|
10654
|
+
const loaded = readStrictMcpJsonRoot(path);
|
|
10655
|
+
if (!loaded)
|
|
10656
|
+
return null;
|
|
10657
|
+
const { root } = loaded;
|
|
10658
|
+
if (root.mcp !== undefined && (!root.mcp || typeof root.mcp !== "object" || Array.isArray(root.mcp))) {
|
|
10659
|
+
console.error(`${mark("warn")} ${path} mcp must be a JSON object; not modifying it`);
|
|
10660
|
+
return null;
|
|
10661
|
+
}
|
|
10662
|
+
const servers = root.mcp;
|
|
10663
|
+
const current = servers?.[serverName];
|
|
10664
|
+
if (marker && !marker.config_path && current === undefined) {
|
|
10665
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Kilo config; refusing relocation`);
|
|
10666
|
+
return null;
|
|
10667
|
+
}
|
|
10668
|
+
if (current !== undefined) {
|
|
10669
|
+
if (!marker) {
|
|
10670
|
+
console.error(`${mark("warn")} ${path} mcp.${serverName} exists but is not Caveman-journaled; refusing overwrite`);
|
|
10671
|
+
return null;
|
|
10672
|
+
}
|
|
10673
|
+
if (!kiloMcpEntryMatches(current, marker)) {
|
|
10674
|
+
console.error(`${mark("warn")} ${path} mcp.${serverName} changed since Caveman installed it; refusing overwrite`);
|
|
10675
|
+
return null;
|
|
10676
|
+
}
|
|
10677
|
+
if (kiloMcpEntryMatches(current, mcp)) {
|
|
10678
|
+
return ownedMcpConfigPlan("kilo", path, loaded, loaded.bytes);
|
|
10679
|
+
}
|
|
10680
|
+
}
|
|
10681
|
+
const nextServers = servers ?? {};
|
|
10682
|
+
nextServers[serverName] = kiloMcpEntry(mcp);
|
|
10683
|
+
root.mcp = nextServers;
|
|
10684
|
+
return ownedMcpConfigPlan("kilo", path, loaded, Buffer.from(JSON.stringify(root, null, 2) + "\n"));
|
|
10685
|
+
}
|
|
10686
|
+
function planRemoveMcpKiloJson(serverName = "caveman") {
|
|
10687
|
+
const marker = readMcpServerMarker("kilo", serverName);
|
|
10688
|
+
const path = marker?.config_path ?? canonicalMcpConfigPath(kiloConfigPath());
|
|
10689
|
+
const loaded = readStrictMcpJsonRoot(path);
|
|
10690
|
+
if (!loaded)
|
|
10691
|
+
return null;
|
|
10692
|
+
if (!loaded.exists) {
|
|
10693
|
+
if (marker && !marker.config_path) {
|
|
10694
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Kilo config; refusing removal`);
|
|
10695
|
+
return null;
|
|
10696
|
+
}
|
|
10697
|
+
if (marker?.config_path && movedOwnedMcpRemovalBlocked("kilo", serverName, marker))
|
|
10698
|
+
return null;
|
|
10699
|
+
return ownedMcpConfigPlan("kilo", path, loaded, null);
|
|
10700
|
+
}
|
|
10701
|
+
const { root } = loaded;
|
|
10702
|
+
if (root.mcp !== undefined && (!root.mcp || typeof root.mcp !== "object" || Array.isArray(root.mcp))) {
|
|
10703
|
+
console.error(`${mark("warn")} ${path} mcp must be a JSON object; not modifying it`);
|
|
10704
|
+
return null;
|
|
10705
|
+
}
|
|
10706
|
+
const servers = root.mcp;
|
|
10707
|
+
const current = servers?.[serverName];
|
|
10708
|
+
if (current === undefined) {
|
|
10709
|
+
if (marker && !marker.config_path) {
|
|
10710
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Kilo config; refusing removal`);
|
|
10711
|
+
return null;
|
|
10712
|
+
}
|
|
10713
|
+
return ownedMcpConfigPlan("kilo", path, loaded, loaded.bytes);
|
|
10714
|
+
}
|
|
10715
|
+
if (!marker) {
|
|
10716
|
+
console.error(`${mark("warn")} ${path} mcp.${serverName} exists but is not Caveman-journaled; refusing removal`);
|
|
10717
|
+
return null;
|
|
10718
|
+
}
|
|
10719
|
+
if (!kiloMcpEntryMatches(current, marker)) {
|
|
10720
|
+
console.error(`${mark("warn")} ${path} mcp.${serverName} changed since Caveman installed it; refusing removal`);
|
|
10721
|
+
return null;
|
|
10722
|
+
}
|
|
10723
|
+
delete servers[serverName];
|
|
10724
|
+
if (Object.keys(servers).length === 0)
|
|
10725
|
+
delete root.mcp;
|
|
10726
|
+
return ownedMcpConfigPlan("kilo", path, loaded, Buffer.from(JSON.stringify(root, null, 2) + "\n"));
|
|
10727
|
+
}
|
|
10728
|
+
const qwenHomeBootstrapKeys = [
|
|
10729
|
+
"QWEN_HOME",
|
|
10730
|
+
"QWEN_RUNTIME_DIR",
|
|
10731
|
+
"QWEN_CODE_MCP_APPROVALS_PATH",
|
|
10732
|
+
"QWEN_CODE_TRUSTED_FOLDERS_PATH",
|
|
10733
|
+
];
|
|
10734
|
+
function qwenReadDotEnv(path) {
|
|
10735
|
+
try {
|
|
10736
|
+
const parsed = parseEnv(readFileSync(path, "utf8"));
|
|
10737
|
+
return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "string"));
|
|
10738
|
+
}
|
|
10739
|
+
catch (error) {
|
|
10740
|
+
if (error.code === "ENOENT")
|
|
10741
|
+
return {};
|
|
10742
|
+
return null;
|
|
10743
|
+
}
|
|
10744
|
+
}
|
|
10745
|
+
function qwenResolveHomeRoot(value) {
|
|
10746
|
+
const configured = value?.trim();
|
|
10747
|
+
const root = configured ? expandTilde(configured) : join(homedir(), ".qwen");
|
|
10748
|
+
return isAbsolute(root) ? root : resolve(root);
|
|
10749
|
+
}
|
|
10750
|
+
// Qwen resolves QWEN_HOME from user-level dotenv before reading settings.
|
|
10751
|
+
// Mirror that bootstrap so install, uninstall, and recovery checks all inspect
|
|
10752
|
+
// the same settings file as pinned Qwen 0.22.3.
|
|
10753
|
+
function qwenHomeState() {
|
|
10754
|
+
const env = { ...process.env };
|
|
10755
|
+
const initialHome = env.QWEN_HOME;
|
|
10756
|
+
const initialRoot = qwenResolveHomeRoot(initialHome);
|
|
10757
|
+
const candidates = [join(initialRoot, ".env")];
|
|
10758
|
+
if (!initialHome)
|
|
10759
|
+
candidates.push(join(homedir(), ".env"));
|
|
10760
|
+
let ambiguous = false;
|
|
10761
|
+
const load = (path) => {
|
|
10762
|
+
const parsed = qwenReadDotEnv(path);
|
|
10763
|
+
if (!parsed) {
|
|
10764
|
+
ambiguous = true;
|
|
10765
|
+
return;
|
|
10766
|
+
}
|
|
10767
|
+
for (const key of qwenHomeBootstrapKeys) {
|
|
10768
|
+
if (parsed[key] && !Object.hasOwn(env, key))
|
|
10769
|
+
env[key] = parsed[key];
|
|
10770
|
+
}
|
|
10771
|
+
};
|
|
10772
|
+
for (const path of candidates)
|
|
10773
|
+
load(path);
|
|
10774
|
+
const discoveredRoot = qwenResolveHomeRoot(env.QWEN_HOME);
|
|
10775
|
+
if (env.QWEN_HOME && env.QWEN_HOME !== initialHome && discoveredRoot !== initialRoot) {
|
|
10776
|
+
// Pinned Qwen performs a second pass through a newly discovered QWEN_HOME.
|
|
10777
|
+
// Trust and approval paths can live there, not only QWEN_RUNTIME_DIR.
|
|
10778
|
+
load(join(discoveredRoot, ".env"));
|
|
10779
|
+
}
|
|
10780
|
+
return { root: discoveredRoot, env, ambiguous };
|
|
10781
|
+
}
|
|
10782
|
+
function qwenHomeEnvFallback(state = qwenHomeState()) {
|
|
10783
|
+
if (state.ambiguous)
|
|
10784
|
+
return null;
|
|
10785
|
+
const candidates = [join(state.root, ".env")];
|
|
10786
|
+
if (!state.env.QWEN_HOME)
|
|
10787
|
+
candidates.push(join(homedir(), ".env"));
|
|
10788
|
+
const fallback = {};
|
|
10789
|
+
for (const path of candidates) {
|
|
10790
|
+
const parsed = qwenReadDotEnv(path);
|
|
10791
|
+
if (!parsed)
|
|
10792
|
+
return null;
|
|
10793
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
10794
|
+
if (!Object.hasOwn(state.env, key) && fallback[key] === undefined)
|
|
10795
|
+
fallback[key] = value;
|
|
10796
|
+
}
|
|
10797
|
+
}
|
|
10798
|
+
return fallback;
|
|
10799
|
+
}
|
|
10800
|
+
function qwenConfigPath() {
|
|
10801
|
+
return join(qwenHomeState().root, "settings.json");
|
|
10802
|
+
}
|
|
10803
|
+
function qwenMcpEntry(mcp) {
|
|
10804
|
+
return { command: mcp.command, args: mcp.args };
|
|
10805
|
+
}
|
|
10806
|
+
function qwenMcpEntryMatches(value, mcp) {
|
|
10807
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
10808
|
+
return false;
|
|
10809
|
+
const entry = value;
|
|
10810
|
+
const keys = Object.keys(entry).sort();
|
|
10811
|
+
if (keys.length !== 2 || keys[0] !== "args" || keys[1] !== "command")
|
|
10812
|
+
return false;
|
|
10813
|
+
return entry.command === mcp.command
|
|
10814
|
+
&& Array.isArray(entry.args)
|
|
10815
|
+
&& entry.args.length === mcp.args.length
|
|
10816
|
+
&& entry.args.every((arg, index) => typeof arg === "string" && arg === mcp.args[index]);
|
|
10817
|
+
}
|
|
10818
|
+
function jsonValueAt(root, path) {
|
|
10819
|
+
let current = root;
|
|
10820
|
+
for (const key of path) {
|
|
10821
|
+
if (!current || typeof current !== "object" || Array.isArray(current))
|
|
10822
|
+
return undefined;
|
|
10823
|
+
current = current[key];
|
|
10824
|
+
}
|
|
10825
|
+
return current;
|
|
10826
|
+
}
|
|
10827
|
+
function readOptionalJsonObject(path) {
|
|
10828
|
+
try {
|
|
10829
|
+
const value = readJson5Lenient(path);
|
|
10830
|
+
return asJsonObject(value) ?? null;
|
|
10831
|
+
}
|
|
10832
|
+
catch (error) {
|
|
10833
|
+
return error.code === "ENOENT" ? {} : null;
|
|
10834
|
+
}
|
|
10835
|
+
}
|
|
10836
|
+
// Qwen settings and trust files are JSON-with-comments, not JSON5: trailing
|
|
10837
|
+
// commas are corruption in 0.22.3. Read-only safety checks must not accept a
|
|
10838
|
+
// policy or credential source the pinned binary will discard during recovery.
|
|
10839
|
+
function readQwenJsonObject(path) {
|
|
10840
|
+
try {
|
|
10841
|
+
const value = JSON.parse(stripJson5Comments(readFileSync(path, "utf8")));
|
|
10842
|
+
return asJsonObject(value) ?? null;
|
|
10843
|
+
}
|
|
10844
|
+
catch (error) {
|
|
10845
|
+
return error.code === "ENOENT" ? {} : null;
|
|
10846
|
+
}
|
|
10847
|
+
}
|
|
10848
|
+
function qwenResolvedSettingString(value, fallback = {}) {
|
|
10849
|
+
return value.replace(/\$(?:(\w+)|{([^}]+)})/g, (match, bare, braced) => {
|
|
10850
|
+
const name = bare || braced || "";
|
|
10851
|
+
if (typeof fallback[name] === "string")
|
|
10852
|
+
return fallback[name];
|
|
10853
|
+
return typeof process.env[name] === "string" ? process.env[name] : match;
|
|
10854
|
+
});
|
|
10855
|
+
}
|
|
10856
|
+
const qwenEnvReference = /\$(?:(\w+)|{([^}]+)})/;
|
|
10857
|
+
// Qwen 0.22.3 uses this complete indicator set to decide whether any legacy
|
|
10858
|
+
// V1 shape triggers migration for the whole settings scope. Keep detection
|
|
10859
|
+
// exact even though Caveman only materializes fields used by its safety gates.
|
|
10860
|
+
const qwenV1IndicatorKeys = [
|
|
10861
|
+
"theme", "model", "autoAccept", "hideTips", "vimMode", "checkpointing",
|
|
10862
|
+
"accessibility", "allowedTools", "allowMCPServers", "autoConfigureMaxOldSpaceSize",
|
|
10863
|
+
"bugCommand", "chatCompression", "coreTools", "contextFileName", "customThemes",
|
|
10864
|
+
"customWittyPhrases", "debugKeystrokeLogging", "dnsResolutionOrder", "enforcedAuthType",
|
|
10865
|
+
"excludeTools", "excludeMCPServers", "excludedProjectEnvVars", "fileFiltering",
|
|
10866
|
+
"folderTrustFeature", "folderTrust", "hasSeenIdeIntegrationNudge", "hideWindowTitle",
|
|
10867
|
+
"showStatusInTitle", "showLineNumbers", "showCitations", "ideMode", "includeDirectories",
|
|
10868
|
+
"loadMemoryFromIncludeDirectories", "maxSessionTurns", "mcpServerCommand",
|
|
10869
|
+
"memoryImportFormat", "preferredEditor", "sandbox", "selectedAuthType",
|
|
10870
|
+
"shouldUseNodePtyShell", "shellPager", "shellShowColor", "skipNextSpeakerCheck",
|
|
10871
|
+
"toolDiscoveryCommand", "toolCallCommand", "usageStatisticsEnabled", "useExternalAuth",
|
|
10872
|
+
"useRipgrep", "enableWelcomeBack", "approvalMode", "sessionTokenLimit", "contentGenerator",
|
|
10873
|
+
"skipLoopDetection", "skipStartupContext", "enableOpenAILogging", "tavilyApiKey",
|
|
10874
|
+
"disableAutoUpdate", "disableUpdateNag", "disableLoadingPhrases", "disableFuzzySearch",
|
|
10875
|
+
"disableCacheControl",
|
|
10876
|
+
];
|
|
10877
|
+
// Subset of V1 -> V2 relocations consumed by credential/trust/MCP gates below.
|
|
10878
|
+
// Migration still triggers from the complete upstream indicator set above.
|
|
10879
|
+
const qwenV1PolicyMigrationMap = {
|
|
10880
|
+
allowMCPServers: "mcp.allowed",
|
|
10881
|
+
coreTools: "tools.core",
|
|
10882
|
+
excludeMCPServers: "mcp.excluded",
|
|
10883
|
+
excludeTools: "tools.exclude",
|
|
10884
|
+
excludedProjectEnvVars: "advanced.excludedEnvVars",
|
|
10885
|
+
folderTrust: "security.folderTrust.enabled",
|
|
10886
|
+
};
|
|
10887
|
+
function qwenSetNestedPropertySafe(root, path, value) {
|
|
10888
|
+
const keys = path.split(".");
|
|
10889
|
+
if (keys.some((key) => !isSafeObjectKey(key)))
|
|
10890
|
+
return;
|
|
10891
|
+
const last = keys.pop();
|
|
10892
|
+
if (!last)
|
|
10893
|
+
return;
|
|
10894
|
+
let current = root;
|
|
10895
|
+
for (const key of keys) {
|
|
10896
|
+
if (current[key] === undefined)
|
|
10897
|
+
current[key] = {};
|
|
10898
|
+
const next = current[key];
|
|
10899
|
+
if (!next || typeof next !== "object")
|
|
10900
|
+
return;
|
|
10901
|
+
current = next;
|
|
10902
|
+
}
|
|
10903
|
+
current[last] = value;
|
|
10904
|
+
}
|
|
10905
|
+
// Mirror policy-relevant output of Qwen's per-scope V1 migration without
|
|
10906
|
+
// rewriting user files. Existing nested V2 content wins exactly as upstream's
|
|
10907
|
+
// parent-path carry step does.
|
|
10908
|
+
function qwenMigratePolicySettings(source) {
|
|
10909
|
+
const version = source["$version"];
|
|
10910
|
+
if (typeof version === "number" && version >= 2)
|
|
10911
|
+
return cloneJsonValue(source);
|
|
10912
|
+
const shouldMigrate = qwenV1IndicatorKeys.some((key) => {
|
|
10913
|
+
if (!Object.hasOwn(source, key))
|
|
10914
|
+
return false;
|
|
10915
|
+
const value = source[key];
|
|
10916
|
+
return !value || typeof value !== "object" || Array.isArray(value);
|
|
10917
|
+
});
|
|
10918
|
+
if (!shouldMigrate)
|
|
10919
|
+
return cloneJsonValue(source);
|
|
10920
|
+
const result = {};
|
|
10921
|
+
const processed = new Set();
|
|
10922
|
+
for (const [legacyKey, targetPath] of Object.entries(qwenV1PolicyMigrationMap)) {
|
|
10923
|
+
if (!Object.hasOwn(source, legacyKey))
|
|
10924
|
+
continue;
|
|
10925
|
+
qwenSetNestedPropertySafe(result, targetPath, source[legacyKey]);
|
|
10926
|
+
processed.add(legacyKey);
|
|
10927
|
+
}
|
|
10928
|
+
for (const [key, value] of Object.entries(source)) {
|
|
10929
|
+
if (processed.has(key))
|
|
10930
|
+
continue;
|
|
10931
|
+
const parentOfMigratedPath = [...processed].some((legacyKey) => qwenV1PolicyMigrationMap[legacyKey].startsWith(`${key}.`));
|
|
10932
|
+
if (!parentOfMigratedPath) {
|
|
10933
|
+
result[key] = value;
|
|
10934
|
+
continue;
|
|
10935
|
+
}
|
|
10936
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
10937
|
+
result[key] = value;
|
|
10938
|
+
continue;
|
|
10939
|
+
}
|
|
10940
|
+
for (const [nestedKey, nestedValue] of Object.entries(value)) {
|
|
10941
|
+
const nestedPath = `${key}.${nestedKey}`;
|
|
10942
|
+
const alreadyMigrated = [...processed].some((legacyKey) => qwenV1PolicyMigrationMap[legacyKey] === nestedPath);
|
|
10943
|
+
if (!alreadyMigrated)
|
|
10944
|
+
qwenSetNestedPropertySafe(result, nestedPath, nestedValue);
|
|
10945
|
+
}
|
|
10946
|
+
}
|
|
10947
|
+
result["$version"] = 2;
|
|
10948
|
+
return result;
|
|
10949
|
+
}
|
|
10950
|
+
function qwenResolveSettingValue(value, fallback) {
|
|
10951
|
+
if (typeof value === "string")
|
|
10952
|
+
return qwenResolvedSettingString(value, fallback);
|
|
10953
|
+
if (Array.isArray(value))
|
|
10954
|
+
return value.map((item) => qwenResolveSettingValue(item, fallback));
|
|
10955
|
+
if (!value || typeof value !== "object")
|
|
10956
|
+
return value;
|
|
10957
|
+
const resolved = { ...value };
|
|
10958
|
+
for (const [key, child] of Object.entries(resolved))
|
|
10959
|
+
resolved[key] = qwenResolveSettingValue(child, fallback);
|
|
10960
|
+
return resolved;
|
|
10961
|
+
}
|
|
10962
|
+
function qwenStringList(root, path, fallback) {
|
|
10963
|
+
const value = jsonValueAt(root, path);
|
|
10964
|
+
if (value === undefined)
|
|
10965
|
+
return undefined;
|
|
10966
|
+
if (!fallback)
|
|
10967
|
+
return null;
|
|
10968
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
|
|
10969
|
+
return null;
|
|
10970
|
+
const resolved = value.map((item) => qwenResolvedSettingString(item, fallback)).filter(Boolean);
|
|
10971
|
+
// Qwen loads .env files after this wrapper starts. An unresolved reference
|
|
10972
|
+
// can therefore become a restrictive rule later; unknown policy fails closed.
|
|
10973
|
+
if (resolved.some((item) => qwenEnvReference.test(item)))
|
|
10974
|
+
return null;
|
|
10975
|
+
return resolved;
|
|
10976
|
+
}
|
|
10977
|
+
// Exact wildcard matcher used by Qwen 0.22 for mcp.allowed/mcp.excluded:
|
|
10978
|
+
// `*` spans any run, `?` spans one character, everything else is literal.
|
|
10979
|
+
function qwenMcpServerPatternMatches(name, pattern) {
|
|
10980
|
+
let nameIndex = 0;
|
|
10981
|
+
let patternIndex = 0;
|
|
10982
|
+
let starNameIndex = -1;
|
|
10983
|
+
let starPatternIndex = -1;
|
|
10984
|
+
while (nameIndex < name.length) {
|
|
10985
|
+
if (patternIndex < pattern.length && (pattern[patternIndex] === "?" || pattern[patternIndex] === name[nameIndex])) {
|
|
10986
|
+
nameIndex++;
|
|
10987
|
+
patternIndex++;
|
|
10988
|
+
}
|
|
10989
|
+
else if (patternIndex < pattern.length && pattern[patternIndex] === "*") {
|
|
10990
|
+
starPatternIndex = patternIndex++;
|
|
10991
|
+
starNameIndex = nameIndex;
|
|
10992
|
+
}
|
|
10993
|
+
else if (starPatternIndex !== -1) {
|
|
10994
|
+
patternIndex = starPatternIndex + 1;
|
|
10995
|
+
nameIndex = ++starNameIndex;
|
|
10996
|
+
}
|
|
10997
|
+
else {
|
|
10998
|
+
return false;
|
|
10999
|
+
}
|
|
11000
|
+
}
|
|
11001
|
+
while (patternIndex < pattern.length && pattern[patternIndex] === "*")
|
|
11002
|
+
patternIndex++;
|
|
11003
|
+
return patternIndex === pattern.length;
|
|
11004
|
+
}
|
|
11005
|
+
const qwenCavemanToolName = "mcp__caveman__caveman_retrieve";
|
|
11006
|
+
function qwenSanitizeToolName(value) {
|
|
11007
|
+
const sanitized = value.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
11008
|
+
return /^[A-Za-z]/.test(sanitized) ? sanitized : `tool_${sanitized}`;
|
|
11009
|
+
}
|
|
11010
|
+
function qwenNormalizeToolName(value) {
|
|
11011
|
+
if (value.length <= 63 && /^[A-Za-z][A-Za-z0-9_-]*$/.test(value))
|
|
11012
|
+
return value;
|
|
11013
|
+
const sanitized = qwenSanitizeToolName(value);
|
|
11014
|
+
let hash = 2166136261;
|
|
11015
|
+
for (let index = 0; index < value.length; index++)
|
|
11016
|
+
hash = Math.imul(hash ^ value.charCodeAt(index), 16777619);
|
|
11017
|
+
const suffix = `_${(hash >>> 0).toString(36).padStart(7, "0")}`;
|
|
11018
|
+
return `${sanitized.slice(0, 63 - suffix.length)}${suffix}`;
|
|
11019
|
+
}
|
|
11020
|
+
// Port of Qwen 0.22.3's MCP permission matcher for one exact target tool.
|
|
11021
|
+
function qwenCavemanToolDenied(rule) {
|
|
11022
|
+
let pattern = rule.trim();
|
|
11023
|
+
const open = pattern.indexOf("(");
|
|
11024
|
+
if (open !== -1) {
|
|
11025
|
+
if (!pattern.endsWith(")") || pattern.slice(open + 1, -1).trim() !== "")
|
|
11026
|
+
return false;
|
|
11027
|
+
pattern = pattern.slice(0, open).trim();
|
|
11028
|
+
}
|
|
11029
|
+
else if (pattern.includes(")")) {
|
|
11030
|
+
return false;
|
|
11031
|
+
}
|
|
11032
|
+
if (pattern === qwenCavemanToolName)
|
|
11033
|
+
return true;
|
|
11034
|
+
if (!pattern.endsWith("*") && pattern.split("__").length >= 3) {
|
|
11035
|
+
const normalized = pattern.startsWith("mcp__") ? qwenNormalizeToolName(pattern) : pattern;
|
|
11036
|
+
if (normalized === qwenCavemanToolName)
|
|
11037
|
+
return true;
|
|
11038
|
+
}
|
|
11039
|
+
if (pattern.endsWith("*")) {
|
|
11040
|
+
return qwenCavemanToolName.startsWith(qwenSanitizeToolName(pattern.slice(0, -1)));
|
|
11041
|
+
}
|
|
11042
|
+
const patternParts = pattern.split("__");
|
|
11043
|
+
const toolParts = qwenCavemanToolName.split("__");
|
|
11044
|
+
return patternParts.length === 2
|
|
11045
|
+
&& patternParts[0] === toolParts[0]
|
|
11046
|
+
&& qwenSanitizeToolName(patternParts[1]) === qwenSanitizeToolName(toolParts[1]);
|
|
11047
|
+
}
|
|
11048
|
+
function qwenCavemanToolDisabled(name) {
|
|
11049
|
+
return name.trim() === qwenCavemanToolName;
|
|
11050
|
+
}
|
|
11051
|
+
function qwenConfigFileInjection() {
|
|
11052
|
+
const profile = AGENTS.find((agent) => agent.id === "qwen");
|
|
11053
|
+
return profile?.injection.method === "config-file" ? profile.injection : undefined;
|
|
11054
|
+
}
|
|
11055
|
+
function qwenSettingsLayerPaths() {
|
|
11056
|
+
const injection = qwenConfigFileInjection();
|
|
11057
|
+
if (!injection?.base_config)
|
|
11058
|
+
return null;
|
|
11059
|
+
const state = qwenHomeState();
|
|
11060
|
+
if (state.ambiguous)
|
|
11061
|
+
return null;
|
|
11062
|
+
const system = baseConfigPath(injection.base_config);
|
|
11063
|
+
const configuredDefaults = process.env.QWEN_CODE_SYSTEM_DEFAULTS_PATH?.trim();
|
|
11064
|
+
const defaultsRoot = configuredDefaults ? expandTilde(configuredDefaults) : join(dirname(system), "system-defaults.json");
|
|
11065
|
+
const defaults = isAbsolute(defaultsRoot) ? defaultsRoot : resolve(defaultsRoot);
|
|
11066
|
+
// Keep system settings last even when operator paths alias another layer;
|
|
11067
|
+
// last-layer identity matters for enterprise MCP server shadow checks.
|
|
11068
|
+
return [
|
|
11069
|
+
defaults,
|
|
11070
|
+
join(state.root, "settings.json"),
|
|
11071
|
+
join(process.cwd(), ".qwen", "settings.json"),
|
|
11072
|
+
system,
|
|
11073
|
+
];
|
|
11074
|
+
}
|
|
11075
|
+
function qwenMergedSettings(layers) {
|
|
11076
|
+
let merged = {};
|
|
11077
|
+
for (const layer of layers)
|
|
11078
|
+
merged = deepMerge(merged, layer);
|
|
11079
|
+
return merged;
|
|
11080
|
+
}
|
|
11081
|
+
function qwenPathVariants(rawPath) {
|
|
11082
|
+
const variants = new Set([normalize(resolve(rawPath))]);
|
|
11083
|
+
try {
|
|
11084
|
+
variants.add(normalize(realpathSync(rawPath)));
|
|
11085
|
+
}
|
|
11086
|
+
catch {
|
|
11087
|
+
// Qwen compares a lexical absolute path when a target cannot be resolved.
|
|
11088
|
+
}
|
|
11089
|
+
return variants;
|
|
11090
|
+
}
|
|
11091
|
+
function qwenPathWithinRoot(childPath, parentPath) {
|
|
11092
|
+
const remainder = relative(parentPath, childPath);
|
|
11093
|
+
return remainder === "" || (!remainder.startsWith(`..${sep}`) && remainder !== ".." && !isAbsolute(remainder));
|
|
11094
|
+
}
|
|
11095
|
+
function qwenPathDepth(path) {
|
|
11096
|
+
const remainder = relative(parse(path).root, path);
|
|
11097
|
+
return remainder === "" ? 0 : remainder.split(sep).filter(Boolean).length;
|
|
11098
|
+
}
|
|
11099
|
+
// Mirror Qwen 0.22.3's persisted trust-rule precedence. Unknown workspaces are
|
|
11100
|
+
// trusted by Qwen's initial settings load; malformed trust state is ambiguous
|
|
11101
|
+
// here and must fail closed before an optional credential reference is emitted.
|
|
11102
|
+
function qwenWorkspaceTrusted(settings, workspacePath) {
|
|
11103
|
+
const enabled = jsonValueAt(settings, ["security", "folderTrust", "enabled"]);
|
|
11104
|
+
if (enabled === undefined || enabled === false)
|
|
11105
|
+
return true;
|
|
11106
|
+
if (enabled !== true)
|
|
11107
|
+
return null;
|
|
11108
|
+
const state = qwenHomeState();
|
|
11109
|
+
if (state.ambiguous)
|
|
11110
|
+
return null;
|
|
11111
|
+
const configuredPath = state.env.QWEN_CODE_TRUSTED_FOLDERS_PATH;
|
|
11112
|
+
const trustedPath = configuredPath || join(state.root, "trustedFolders.json");
|
|
11113
|
+
const config = readQwenJsonObject(trustedPath);
|
|
11114
|
+
if (!config)
|
|
11115
|
+
return null;
|
|
11116
|
+
const workspaceVariants = qwenPathVariants(workspacePath);
|
|
11117
|
+
let winnerDepth = -1;
|
|
11118
|
+
let winnerTrusted;
|
|
11119
|
+
for (const [rulePath, rawLevel] of Object.entries(config)) {
|
|
11120
|
+
if (rawLevel !== "TRUST_FOLDER" && rawLevel !== "TRUST_PARENT" && rawLevel !== "DO_NOT_TRUST")
|
|
11121
|
+
return null;
|
|
11122
|
+
const rootPath = rawLevel === "TRUST_PARENT" ? dirname(rulePath) : rulePath;
|
|
11123
|
+
let matchDepth = -1;
|
|
11124
|
+
for (const workspaceVariant of workspaceVariants) {
|
|
11125
|
+
for (const ruleVariant of qwenPathVariants(rootPath)) {
|
|
11126
|
+
if (qwenPathWithinRoot(workspaceVariant, ruleVariant)) {
|
|
11127
|
+
matchDepth = Math.max(matchDepth, qwenPathDepth(ruleVariant));
|
|
11128
|
+
}
|
|
11129
|
+
}
|
|
11130
|
+
}
|
|
11131
|
+
if (matchDepth < 0)
|
|
11132
|
+
continue;
|
|
11133
|
+
const trusted = rawLevel !== "DO_NOT_TRUST";
|
|
11134
|
+
if (matchDepth > winnerDepth || (matchDepth === winnerDepth && !trusted && winnerTrusted !== false)) {
|
|
11135
|
+
winnerDepth = matchDepth;
|
|
11136
|
+
winnerTrusted = trusted;
|
|
11137
|
+
}
|
|
11138
|
+
}
|
|
11139
|
+
return winnerTrusted ?? true;
|
|
11140
|
+
}
|
|
11141
|
+
function qwenSettingsLayers() {
|
|
11142
|
+
const paths = qwenSettingsLayerPaths();
|
|
11143
|
+
if (!paths)
|
|
11144
|
+
return null;
|
|
11145
|
+
const fallback = qwenHomeEnvFallback();
|
|
11146
|
+
if (!fallback)
|
|
11147
|
+
return null;
|
|
11148
|
+
const layers = [];
|
|
11149
|
+
for (const path of paths) {
|
|
11150
|
+
const layer = readQwenJsonObject(path);
|
|
11151
|
+
if (!layer)
|
|
11152
|
+
return null;
|
|
11153
|
+
const migrated = qwenMigratePolicySettings(layer);
|
|
11154
|
+
layers.push(qwenResolveSettingValue(migrated, fallback));
|
|
11155
|
+
}
|
|
11156
|
+
// Qwen decides workspace trust from System + User settings (User wins in
|
|
11157
|
+
// this initial check), then drops the entire workspace layer when untrusted.
|
|
11158
|
+
const initialTrustSettings = deepMerge(layers[3], layers[1]);
|
|
11159
|
+
const workspaceTrusted = qwenWorkspaceTrusted(initialTrustSettings, process.cwd());
|
|
11160
|
+
if (workspaceTrusted === null)
|
|
11161
|
+
return null;
|
|
11162
|
+
if (!workspaceTrusted)
|
|
11163
|
+
layers[2] = {};
|
|
11164
|
+
return layers;
|
|
11165
|
+
}
|
|
11166
|
+
function qwenSettingsPermitRecovery(marker, layers) {
|
|
11167
|
+
const fallback = qwenHomeEnvFallback();
|
|
11168
|
+
if (!fallback)
|
|
11169
|
+
return false;
|
|
11170
|
+
// System settings are enterprise-owned and outrank Caveman's user entry.
|
|
11171
|
+
// Never replace a different server carrying the same name.
|
|
11172
|
+
const systemEntry = jsonValueAt(layers[layers.length - 1], ["mcpServers", "caveman"]);
|
|
11173
|
+
if (systemEntry !== undefined && !qwenMcpEntryMatches(systemEntry, marker))
|
|
11174
|
+
return false;
|
|
11175
|
+
let allowedConfigured = false;
|
|
11176
|
+
let allowed = false;
|
|
11177
|
+
for (const layer of layers) {
|
|
11178
|
+
const allowList = qwenStringList(layer, ["mcp", "allowed"], fallback);
|
|
11179
|
+
const excludeList = qwenStringList(layer, ["mcp", "excluded"], fallback);
|
|
11180
|
+
const denyRules = qwenStringList(layer, ["permissions", "deny"], fallback);
|
|
11181
|
+
const legacyDenyRules = qwenStringList(layer, ["tools", "exclude"], fallback);
|
|
11182
|
+
const disabledTools = qwenStringList(layer, ["tools", "disabled"], fallback);
|
|
11183
|
+
if (allowList === null || excludeList === null || denyRules === null || legacyDenyRules === null || disabledTools === null)
|
|
11184
|
+
return false;
|
|
11185
|
+
if (allowList !== undefined) {
|
|
11186
|
+
allowedConfigured = true;
|
|
11187
|
+
if (allowList.some((pattern) => qwenMcpServerPatternMatches("caveman", pattern)))
|
|
11188
|
+
allowed = true;
|
|
11189
|
+
}
|
|
11190
|
+
if (excludeList?.some((pattern) => qwenMcpServerPatternMatches("caveman", pattern)))
|
|
11191
|
+
return false;
|
|
11192
|
+
if (denyRules?.some(qwenCavemanToolDenied) || legacyDenyRules?.some(qwenCavemanToolDenied))
|
|
11193
|
+
return false;
|
|
11194
|
+
if (disabledTools?.some(qwenCavemanToolDisabled))
|
|
11195
|
+
return false;
|
|
11196
|
+
}
|
|
11197
|
+
return !allowedConfigured || allowed;
|
|
11198
|
+
}
|
|
11199
|
+
function qwenUserLevelEnvPaths(state = qwenHomeState()) {
|
|
11200
|
+
return new Set([
|
|
11201
|
+
normalize(join(homedir(), ".env")),
|
|
11202
|
+
normalize(join(state.root, ".env")),
|
|
11203
|
+
normalize(join(homedir(), ".qwen", ".env")),
|
|
11204
|
+
]);
|
|
11205
|
+
}
|
|
11206
|
+
function qwenEnvFileIsQwenScoped(path, state) {
|
|
11207
|
+
const normalized = normalize(path);
|
|
11208
|
+
return qwenUserLevelEnvPaths(state).has(normalized) || basename(dirname(normalized)) === ".qwen";
|
|
11209
|
+
}
|
|
11210
|
+
// advanced.excludedEnvVars uses Qwen's UNION merge strategy. Malformed final
|
|
11211
|
+
// state is ambiguous; fail closed instead of guessing which project env keys
|
|
11212
|
+
// the pinned binary will accept.
|
|
11213
|
+
function qwenExcludedEnvVars(layers) {
|
|
11214
|
+
let merged;
|
|
11215
|
+
for (const layer of layers) {
|
|
11216
|
+
const next = jsonValueAt(layer, ["advanced", "excludedEnvVars"]);
|
|
11217
|
+
if (next === undefined)
|
|
11218
|
+
continue;
|
|
11219
|
+
if (Array.isArray(merged)) {
|
|
11220
|
+
const additions = Array.isArray(next) ? next : [next];
|
|
11221
|
+
merged = [...new Set([...merged, ...additions])];
|
|
11222
|
+
}
|
|
11223
|
+
else {
|
|
11224
|
+
merged = next;
|
|
11225
|
+
}
|
|
11226
|
+
}
|
|
11227
|
+
if (merged === undefined)
|
|
11228
|
+
return ["DEBUG", "DEBUG_MODE"];
|
|
11229
|
+
return Array.isArray(merged) && merged.every((item) => typeof item === "string")
|
|
11230
|
+
? merged
|
|
11231
|
+
: null;
|
|
11232
|
+
}
|
|
11233
|
+
function qwenEnvironmentFilePaths(layers) {
|
|
11234
|
+
const state = qwenHomeState();
|
|
11235
|
+
const home = homedir();
|
|
11236
|
+
const legacy = join(home, ".qwen");
|
|
11237
|
+
const effectiveSettings = qwenMergedSettings(layers);
|
|
11238
|
+
const found = [];
|
|
11239
|
+
const push = (path) => {
|
|
11240
|
+
if (existsSync(path) && !found.includes(path))
|
|
11241
|
+
found.push(path);
|
|
11242
|
+
};
|
|
11243
|
+
const pushWorkspace = (path, workspacePath) => {
|
|
11244
|
+
if (!existsSync(path))
|
|
11245
|
+
return false;
|
|
11246
|
+
const trusted = qwenWorkspaceTrusted(effectiveSettings, workspacePath);
|
|
11247
|
+
if (trusted === null)
|
|
11248
|
+
return null;
|
|
11249
|
+
if (!trusted)
|
|
11250
|
+
return false;
|
|
11251
|
+
push(path);
|
|
11252
|
+
return true;
|
|
11253
|
+
};
|
|
11254
|
+
const pushHome = () => {
|
|
11255
|
+
push(join(state.root, ".env"));
|
|
11256
|
+
if (state.root !== legacy)
|
|
11257
|
+
push(join(legacy, ".env"));
|
|
11258
|
+
push(join(home, ".env"));
|
|
11259
|
+
};
|
|
11260
|
+
let current;
|
|
11261
|
+
try {
|
|
11262
|
+
current = realpathSync(process.cwd());
|
|
11263
|
+
}
|
|
11264
|
+
catch {
|
|
11265
|
+
current = resolve(process.cwd());
|
|
11266
|
+
}
|
|
11267
|
+
while (true) {
|
|
11268
|
+
if (current === home) {
|
|
11269
|
+
pushHome();
|
|
11270
|
+
break;
|
|
11271
|
+
}
|
|
11272
|
+
const scoped = join(current, ".qwen", ".env");
|
|
11273
|
+
const scopedAdded = pushWorkspace(scoped, current);
|
|
11274
|
+
if (scopedAdded === null)
|
|
11275
|
+
return null;
|
|
11276
|
+
if (scopedAdded) {
|
|
11277
|
+
pushHome();
|
|
11278
|
+
break;
|
|
11279
|
+
}
|
|
11280
|
+
const plain = join(current, ".env");
|
|
11281
|
+
const plainAdded = pushWorkspace(plain, current);
|
|
11282
|
+
if (plainAdded === null)
|
|
11283
|
+
return null;
|
|
11284
|
+
if (plainAdded) {
|
|
11285
|
+
pushHome();
|
|
11286
|
+
break;
|
|
11287
|
+
}
|
|
11288
|
+
const parent = dirname(current);
|
|
11289
|
+
if (!parent || parent === current) {
|
|
11290
|
+
pushHome();
|
|
11291
|
+
break;
|
|
11292
|
+
}
|
|
11293
|
+
current = parent;
|
|
11294
|
+
}
|
|
11295
|
+
return found;
|
|
11296
|
+
}
|
|
11297
|
+
function qwenEffectiveEnvValue(layers, key) {
|
|
11298
|
+
const inherited = process.env[key];
|
|
11299
|
+
if (inherited)
|
|
11300
|
+
return inherited;
|
|
11301
|
+
const state = qwenHomeState();
|
|
11302
|
+
const excluded = qwenExcludedEnvVars(layers);
|
|
11303
|
+
if (!excluded)
|
|
11304
|
+
return null;
|
|
11305
|
+
const envPaths = qwenEnvironmentFilePaths(layers);
|
|
11306
|
+
if (!envPaths)
|
|
11307
|
+
return null;
|
|
11308
|
+
for (const path of envPaths) {
|
|
11309
|
+
const parsed = qwenReadDotEnv(path);
|
|
11310
|
+
if (!parsed)
|
|
11311
|
+
return null;
|
|
11312
|
+
if (!qwenEnvFileIsQwenScoped(path, state) && excluded.includes(key))
|
|
11313
|
+
continue;
|
|
11314
|
+
const candidate = parsed[key];
|
|
11315
|
+
if (candidate)
|
|
11316
|
+
return candidate;
|
|
11317
|
+
}
|
|
11318
|
+
// settings.env is the lowest environment tier; system settings win over
|
|
11319
|
+
// workspace, user, and system defaults for each key. Qwen's normal loader
|
|
11320
|
+
// intentionally does not apply excludedEnvVars to settings.env.
|
|
11321
|
+
const env = jsonValueAt(qwenMergedSettings(layers), ["env"]);
|
|
11322
|
+
if (env === undefined)
|
|
11323
|
+
return undefined;
|
|
11324
|
+
if (!env || typeof env !== "object" || Array.isArray(env))
|
|
11325
|
+
return null;
|
|
11326
|
+
const candidate = env[key];
|
|
11327
|
+
if (candidate === undefined)
|
|
11328
|
+
return undefined;
|
|
11329
|
+
return typeof candidate === "string" ? candidate : null;
|
|
11330
|
+
}
|
|
11331
|
+
function qwenOpenAIKeyAvailability(value) {
|
|
11332
|
+
if (value === null)
|
|
11333
|
+
return null;
|
|
11334
|
+
if (value === undefined || !value.trim())
|
|
11335
|
+
return false;
|
|
11336
|
+
if (qwenEnvReference.test(value) || /[\r\n]/.test(value))
|
|
11337
|
+
return null;
|
|
11338
|
+
return true;
|
|
11339
|
+
}
|
|
11340
|
+
// Qwen resolves settings before loading project dotenv/settings.env. Its normal
|
|
11341
|
+
// process then relaunches once, inheriting those late-loaded values, and resolves
|
|
11342
|
+
// the temporary system settings again. Pre-existing no-relaunch/sandbox processes
|
|
11343
|
+
// skip that second pass, so only process env or Qwen's home fallback can safely
|
|
11344
|
+
// satisfy a header reference there.
|
|
11345
|
+
function qwenEffectiveOpenAIKeyAvailable() {
|
|
11346
|
+
const layers = qwenSettingsLayers();
|
|
11347
|
+
if (!layers)
|
|
11348
|
+
return null;
|
|
11349
|
+
const noRelaunch = qwenEffectiveEnvValue(layers, "QWEN_CODE_NO_RELAUNCH");
|
|
11350
|
+
const sandbox = qwenEffectiveEnvValue(layers, "SANDBOX");
|
|
11351
|
+
if (noRelaunch === null || sandbox === null)
|
|
11352
|
+
return null;
|
|
11353
|
+
if (!noRelaunch && !sandbox) {
|
|
11354
|
+
return qwenOpenAIKeyAvailability(qwenEffectiveEnvValue(layers, "OPENAI_API_KEY"));
|
|
11355
|
+
}
|
|
11356
|
+
const fallback = qwenHomeEnvFallback();
|
|
11357
|
+
if (!fallback)
|
|
11358
|
+
return null;
|
|
11359
|
+
const inherited = process.env.OPENAI_API_KEY;
|
|
11360
|
+
return qwenOpenAIKeyAvailability(typeof inherited === "string" ? inherited : fallback.OPENAI_API_KEY);
|
|
11361
|
+
}
|
|
11362
|
+
function qwenMatchedOption(arg, names) {
|
|
11363
|
+
for (const name of names) {
|
|
11364
|
+
if (arg === name)
|
|
11365
|
+
return { inline: false };
|
|
11366
|
+
if (arg.startsWith(`${name}=`))
|
|
11367
|
+
return { inline: true, value: arg.slice(name.length + 1) };
|
|
11368
|
+
}
|
|
11369
|
+
return null;
|
|
11370
|
+
}
|
|
11371
|
+
function kiloProfileModelIds(agent) {
|
|
11372
|
+
if (agent.id !== "kilo" || agent.injection.method !== "config-env-content")
|
|
11373
|
+
return new Set();
|
|
11374
|
+
const contents = [agent.injection.config_content.local, agent.injection.config_content.managed ?? agent.injection.config_content.local];
|
|
11375
|
+
let shared;
|
|
11376
|
+
for (const content of contents) {
|
|
11377
|
+
const enabled = jsonValueAt(content, ["enabled_providers"]);
|
|
11378
|
+
const models = jsonValueAt(content, ["provider", "caveman", "models"]);
|
|
11379
|
+
if (!Array.isArray(enabled) || enabled.length !== 1 || enabled[0] !== "caveman"
|
|
11380
|
+
|| !models || typeof models !== "object" || Array.isArray(models))
|
|
11381
|
+
return new Set();
|
|
11382
|
+
const ids = new Set(Object.keys(models).filter((id) => id && id.trim() === id).map((id) => `caveman/${id}`));
|
|
11383
|
+
shared = shared === undefined ? ids : new Set([...shared].filter((id) => ids.has(id)));
|
|
11384
|
+
}
|
|
11385
|
+
return shared ?? new Set();
|
|
11386
|
+
}
|
|
11387
|
+
function kiloManagedPolicyPresent() {
|
|
11388
|
+
const directory = process.env.KILO_TEST_MANAGED_CONFIG_DIR || (process.platform === "darwin"
|
|
11389
|
+
? "/Library/Application Support/kilo"
|
|
11390
|
+
: process.platform === "win32"
|
|
11391
|
+
? join(process.env.ProgramData || "C:\\ProgramData", "kilo")
|
|
11392
|
+
: "/etc/kilo");
|
|
11393
|
+
// Exact Kilo 7.5.6 managed file set. config.json is a legacy global filename,
|
|
11394
|
+
// but managed loading deliberately excludes it.
|
|
11395
|
+
const configFiles = ["kilo.jsonc", "kilo.json", "opencode.jsonc", "opencode.json"];
|
|
11396
|
+
if (configFiles.some((name) => existsSync(join(directory, name))))
|
|
11397
|
+
return true;
|
|
11398
|
+
if (process.platform !== "darwin")
|
|
11399
|
+
return false;
|
|
11400
|
+
const preferenceFiles = ["/Library/Managed Preferences/ai.opencode.managed.plist"];
|
|
11401
|
+
try {
|
|
11402
|
+
preferenceFiles.unshift(join("/Library/Managed Preferences", userInfo().username, "ai.opencode.managed.plist"));
|
|
11403
|
+
}
|
|
11404
|
+
catch {
|
|
11405
|
+
// System-level preference remains covered; an unreadable username is itself
|
|
11406
|
+
// unusual, but no user path can be resolved safely enough to claim absence.
|
|
11407
|
+
return true;
|
|
11408
|
+
}
|
|
11409
|
+
return preferenceFiles.some((path) => existsSync(path));
|
|
11410
|
+
}
|
|
11411
|
+
function kiloDatabasePath() {
|
|
11412
|
+
const rawDataRoot = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
|
|
11413
|
+
const cleanedDataRoot = rawDataRoot.replace(/[\r\n]+/g, "");
|
|
11414
|
+
if (!cleanedDataRoot)
|
|
11415
|
+
throw new Error("Kilo data root resolves to an empty path");
|
|
11416
|
+
const dataRoot = normalize(isAbsolute(cleanedDataRoot) ? cleanedDataRoot : resolve(cleanedDataRoot));
|
|
11417
|
+
const configured = process.env.KILO_DB;
|
|
11418
|
+
if (configured === ":memory:")
|
|
11419
|
+
return null;
|
|
11420
|
+
if (configured) {
|
|
11421
|
+
if (/[\0\r\n]/.test(configured))
|
|
11422
|
+
throw new Error("KILO_DB contains an invalid path character");
|
|
11423
|
+
return normalize(isAbsolute(configured) ? configured : join(dataRoot, "kilo", configured));
|
|
11424
|
+
}
|
|
11425
|
+
return join(dataRoot, "kilo", "kilo.db");
|
|
11426
|
+
}
|
|
11427
|
+
function kiloActiveOrganizationState() {
|
|
11428
|
+
let path;
|
|
11429
|
+
try {
|
|
11430
|
+
path = kiloDatabasePath();
|
|
11431
|
+
if (path === null)
|
|
11432
|
+
return "none";
|
|
11433
|
+
const stat = statSync(path);
|
|
11434
|
+
if (!stat.isFile())
|
|
11435
|
+
return "unknown";
|
|
11436
|
+
}
|
|
11437
|
+
catch (error) {
|
|
11438
|
+
if (error.code === "ENOENT")
|
|
11439
|
+
return "none";
|
|
11440
|
+
return "unknown";
|
|
11441
|
+
}
|
|
11442
|
+
const script = [
|
|
11443
|
+
'const { DatabaseSync } = require("node:sqlite");',
|
|
11444
|
+
'const db = new DatabaseSync(process.argv[1], { readOnly: true });',
|
|
11445
|
+
'try {',
|
|
11446
|
+
' 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();',
|
|
11447
|
+
' process.stdout.write(row?.active === 1 ? "active" : "none");',
|
|
11448
|
+
'} finally { db.close(); }',
|
|
11449
|
+
].join("\n");
|
|
11450
|
+
const probe = spawnSync(process.execPath, ["--no-warnings", "-e", script, path], {
|
|
11451
|
+
encoding: "utf8",
|
|
11452
|
+
timeout: 2_000,
|
|
11453
|
+
env: { ...process.env, NODE_NO_WARNINGS: "1", NODE_OPTIONS: "" },
|
|
11454
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
11455
|
+
});
|
|
11456
|
+
if (probe.status !== 0 || probe.signal || probe.error)
|
|
11457
|
+
return "unknown";
|
|
11458
|
+
return probe.stdout === "active" ? "active" : probe.stdout === "none" ? "none" : "unknown";
|
|
11459
|
+
}
|
|
11460
|
+
function kiloHigherPriorityRouteOverride() {
|
|
11461
|
+
if (kiloManagedPolicyPresent()) {
|
|
11462
|
+
return { surface: "managed policy", reason: "loads after Caveman's inline routing config" };
|
|
11463
|
+
}
|
|
11464
|
+
const organization = kiloActiveOrganizationState();
|
|
11465
|
+
if (organization === "active") {
|
|
11466
|
+
return { surface: "active organization", reason: "can load routing policy after Caveman's inline config" };
|
|
11467
|
+
}
|
|
11468
|
+
if (organization === "unknown") {
|
|
11469
|
+
return { surface: "organization state", reason: "cannot be verified safely" };
|
|
11470
|
+
}
|
|
11471
|
+
return null;
|
|
11472
|
+
}
|
|
11473
|
+
// Kilo's inline config selects a routed default, but its CLI model option has
|
|
11474
|
+
// higher precedence and attach mode delegates inference to another server whose
|
|
11475
|
+
// environment this process cannot control. Detect both before proxy/bootstrap
|
|
11476
|
+
// work. Unknown short-option clusters fail direct instead of guessing yargs.
|
|
11477
|
+
function kiloRouteOverride(agent, args) {
|
|
11478
|
+
const higherPriority = kiloHigherPriorityRouteOverride();
|
|
11479
|
+
if (higherPriority)
|
|
11480
|
+
return higherPriority;
|
|
11481
|
+
const separator = args.indexOf("--");
|
|
11482
|
+
const parsedArgs = separator === -1 ? args : args.slice(0, separator);
|
|
11483
|
+
const valueOptions = new Set([
|
|
11484
|
+
"--log-level", "--port", "--hostname", "--mdns-domain", "--cors",
|
|
11485
|
+
"--session", "-s", "--worktree", "--prompt", "--agent", "--replay-limit",
|
|
11486
|
+
"--command", "--format", "--file", "-f", "--title", "--password", "-p",
|
|
11487
|
+
"--username", "-u", "--dir", "--variant", "--timeout", "--parallel", "--output",
|
|
11488
|
+
"--repo", "--repo-type", "--branch", "--mode", "--org-id", "--session-id", "--message-id",
|
|
11489
|
+
]);
|
|
11490
|
+
const booleanOptions = new Set([
|
|
11491
|
+
"-h", "--help", "-v", "--version", "--print-logs", "--pure", "--mdns",
|
|
11492
|
+
"-c", "--continue", "--fork", "--cloud-fork", "--auto", "--mini", "--no-replay",
|
|
11493
|
+
"--share", "--thinking", "-i", "--interactive", "--stream", "--verbose", "--quiet",
|
|
11494
|
+
]);
|
|
11495
|
+
let command;
|
|
11496
|
+
let modelValue;
|
|
11497
|
+
let modelOccurrences = 0;
|
|
11498
|
+
for (let index = 0; index < parsedArgs.length; index++) {
|
|
11499
|
+
const arg = parsedArgs[index];
|
|
11500
|
+
if (arg === "--attach" || arg.startsWith("--attach=")) {
|
|
11501
|
+
return { surface: "--attach", reason: "uses another server's provider route" };
|
|
11502
|
+
}
|
|
11503
|
+
const model = qwenMatchedOption(arg, ["--model", "--m", "-m"]);
|
|
11504
|
+
if (model) {
|
|
11505
|
+
modelOccurrences++;
|
|
11506
|
+
const value = model?.inline ? model.value : parsedArgs[index + 1];
|
|
11507
|
+
if (typeof value !== "string" || !value || value.startsWith("-")) {
|
|
11508
|
+
return { surface: "--model", reason: "is repeated or malformed" };
|
|
11509
|
+
}
|
|
11510
|
+
modelValue = value;
|
|
11511
|
+
if (!model?.inline)
|
|
11512
|
+
index++;
|
|
11513
|
+
continue;
|
|
11514
|
+
}
|
|
11515
|
+
if (arg.startsWith("-") && !arg.startsWith("--") && arg.slice(1).includes("m")) {
|
|
11516
|
+
return { surface: "-m", reason: "is ambiguous inside a short-option cluster" };
|
|
11517
|
+
}
|
|
11518
|
+
const equals = arg.indexOf("=");
|
|
11519
|
+
const optionName = equals === -1 ? arg : arg.slice(0, equals);
|
|
11520
|
+
if (valueOptions.has(optionName)) {
|
|
11521
|
+
if (equals === -1) {
|
|
11522
|
+
const value = parsedArgs[index + 1];
|
|
11523
|
+
if (typeof value !== "string" || !value || value.startsWith("-")) {
|
|
11524
|
+
return { surface: optionName, reason: "is malformed and makes command routing ambiguous" };
|
|
11525
|
+
}
|
|
11526
|
+
index++;
|
|
11527
|
+
}
|
|
11528
|
+
else if (!arg.slice(equals + 1)) {
|
|
11529
|
+
return { surface: optionName, reason: "is malformed and makes command routing ambiguous" };
|
|
11530
|
+
}
|
|
11531
|
+
continue;
|
|
11532
|
+
}
|
|
11533
|
+
if (booleanOptions.has(optionName)) {
|
|
11534
|
+
if (equals !== -1) {
|
|
11535
|
+
const value = arg.slice(equals + 1);
|
|
11536
|
+
if (value !== "true" && value !== "false") {
|
|
11537
|
+
return { surface: optionName, reason: "has a non-boolean value and makes command routing ambiguous" };
|
|
11538
|
+
}
|
|
11539
|
+
}
|
|
11540
|
+
else if (parsedArgs[index + 1] === "true" || parsedArgs[index + 1] === "false") {
|
|
11541
|
+
index++;
|
|
11542
|
+
}
|
|
11543
|
+
continue;
|
|
11544
|
+
}
|
|
11545
|
+
if (arg.startsWith("-")) {
|
|
11546
|
+
return { surface: "arguments", reason: "cannot be parsed safely with Kilo 7.5.6 option arities" };
|
|
11547
|
+
}
|
|
11548
|
+
if (command === undefined) {
|
|
11549
|
+
command = arg;
|
|
11550
|
+
if (command === "attach")
|
|
11551
|
+
return { surface: "attach", reason: "uses another server's provider route" };
|
|
11552
|
+
if (command === "cloud" || command === "roll-call") {
|
|
11553
|
+
return { surface: command, reason: "runs outside Kilo's local single-model route" };
|
|
11554
|
+
}
|
|
11555
|
+
if (command === "daemon" || command === "console") {
|
|
11556
|
+
return { surface: command, reason: "can outlive Caveman's wrap session" };
|
|
11557
|
+
}
|
|
11558
|
+
}
|
|
11559
|
+
}
|
|
11560
|
+
if (modelOccurrences > 1)
|
|
11561
|
+
return { surface: "--model", reason: "is repeated or malformed" };
|
|
11562
|
+
const routedModels = kiloProfileModelIds(agent);
|
|
11563
|
+
if (routedModels.size === 0)
|
|
11564
|
+
return { surface: "routing profile", reason: "does not confine Kilo to Caveman providers" };
|
|
11565
|
+
if (modelValue !== undefined && !routedModels.has(modelValue)) {
|
|
11566
|
+
return { surface: "--model", reason: "selects a model outside Caveman's routed profile" };
|
|
11567
|
+
}
|
|
11568
|
+
return null;
|
|
11569
|
+
}
|
|
11570
|
+
function qwenProfileModelIds(agent) {
|
|
11571
|
+
if (agent.id !== "qwen" || agent.injection.method !== "config-file")
|
|
11572
|
+
return new Set();
|
|
11573
|
+
const overlays = [agent.injection.config_overlay.local, agent.injection.config_overlay.managed ?? agent.injection.config_overlay.local];
|
|
11574
|
+
let shared;
|
|
11575
|
+
for (const overlay of overlays) {
|
|
11576
|
+
const models = jsonValueAt(overlay, ["modelProviders", "openai"]);
|
|
11577
|
+
if (!Array.isArray(models))
|
|
11578
|
+
return new Set();
|
|
11579
|
+
const ids = new Set(models.flatMap((model) => {
|
|
11580
|
+
const id = jsonValueAt(model, ["id"]);
|
|
11581
|
+
return typeof id === "string" && id.trim() === id && id ? [id] : [];
|
|
11582
|
+
}));
|
|
11583
|
+
shared = shared === undefined ? ids : new Set([...shared].filter((id) => ids.has(id)));
|
|
11584
|
+
}
|
|
11585
|
+
return shared ?? new Set();
|
|
11586
|
+
}
|
|
11587
|
+
function qwenBooleanArg(args, index, positive, negative) {
|
|
11588
|
+
const arg = args[index];
|
|
11589
|
+
const negated = qwenMatchedOption(arg, negative);
|
|
11590
|
+
if (negated?.inline)
|
|
11591
|
+
return { matched: true, malformed: true, consumed: 0 };
|
|
11592
|
+
if (negated)
|
|
11593
|
+
return { matched: true, value: false, malformed: false, consumed: 0 };
|
|
11594
|
+
const enabled = qwenMatchedOption(arg, positive);
|
|
11595
|
+
if (!enabled)
|
|
11596
|
+
return { matched: false, malformed: false, consumed: 0 };
|
|
11597
|
+
if (enabled.inline) {
|
|
11598
|
+
if (enabled.value === "true" || enabled.value === "false") {
|
|
11599
|
+
return { matched: true, value: enabled.value === "true", malformed: false, consumed: 0 };
|
|
11600
|
+
}
|
|
11601
|
+
return { matched: true, malformed: true, consumed: 0 };
|
|
11602
|
+
}
|
|
11603
|
+
const next = args[index + 1];
|
|
11604
|
+
if (next === "true" || next === "false") {
|
|
11605
|
+
return { matched: true, value: next === "true", malformed: false, consumed: 1 };
|
|
11606
|
+
}
|
|
11607
|
+
return { matched: true, value: true, malformed: false, consumed: 0 };
|
|
11608
|
+
}
|
|
11609
|
+
// Qwen's temporary system settings route can be superseded by CLI routing and
|
|
11610
|
+
// auth flags, while safe/bare modes can discard it entirely. Parse the pinned
|
|
11611
|
+
// 0.22.3 spellings before proxy startup. Ambiguous or repeated selectors launch
|
|
11612
|
+
// direct: preserving the user's argv is safer than claiming traffic was routed.
|
|
11613
|
+
function qwenShortOptionLetters(arg) {
|
|
11614
|
+
if (!arg.startsWith("-") || arg.startsWith("--") || arg.length < 2)
|
|
11615
|
+
return new Set();
|
|
11616
|
+
const letters = new Set();
|
|
11617
|
+
// yargs expands boolean clusters left-to-right, but these aliases consume the
|
|
11618
|
+
// remaining suffix as their value. Do not mistake model/prompt text for flags.
|
|
11619
|
+
const takesValue = new Set(["e", "i", "m", "o", "p", "r"]);
|
|
11620
|
+
for (const letter of arg.slice(1).split("=", 1)[0]) {
|
|
11621
|
+
letters.add(letter);
|
|
11622
|
+
if (takesValue.has(letter))
|
|
11623
|
+
break;
|
|
11624
|
+
}
|
|
11625
|
+
return letters;
|
|
11626
|
+
}
|
|
11627
|
+
function qwenExtensionRouteOverride(args) {
|
|
11628
|
+
let confined = 0;
|
|
11629
|
+
for (const arg of args) {
|
|
11630
|
+
if (arg === "--extensions=none") {
|
|
11631
|
+
confined++;
|
|
11632
|
+
continue;
|
|
11633
|
+
}
|
|
11634
|
+
if (arg === "--extensions" || arg === "-e" || arg.startsWith("--extensions=") || arg.startsWith("-e")
|
|
11635
|
+
|| qwenShortOptionLetters(arg).has("e")) {
|
|
11636
|
+
return { surface: "--extensions", reason: "can load model-routing code outside Caveman's locked session" };
|
|
11637
|
+
}
|
|
11638
|
+
}
|
|
11639
|
+
return confined > 1
|
|
11640
|
+
? { surface: "--extensions", reason: "is repeated or ambiguous" }
|
|
11641
|
+
: null;
|
|
11642
|
+
}
|
|
11643
|
+
function qwenControlSurfaceOverride(args) {
|
|
11644
|
+
for (const arg of args) {
|
|
11645
|
+
if (arg === "--")
|
|
11646
|
+
break;
|
|
11647
|
+
const shortOptions = qwenShortOptionLetters(arg);
|
|
11648
|
+
if (arg === "--continue" || arg.startsWith("--continue=") || shortOptions.has("c")
|
|
11649
|
+
|| arg === "--resume" || arg.startsWith("--resume=") || shortOptions.has("r")
|
|
11650
|
+
|| arg === "--fork-session" || arg.startsWith("--fork-session=")
|
|
11651
|
+
|| arg === "--forkSession" || arg.startsWith("--forkSession=")) {
|
|
11652
|
+
return { surface: "session restore", reason: "can reactivate a recorded provider route outside Caveman's locked session" };
|
|
11653
|
+
}
|
|
11654
|
+
}
|
|
11655
|
+
const directFlags = ["--acp", "--experimental-acp", "--experimentalAcp", "--experimental-skills", "--experimentalSkills"];
|
|
11656
|
+
for (let index = 0; index < args.length; index++) {
|
|
11657
|
+
const match = qwenBooleanArg(args, index, directFlags, []);
|
|
11658
|
+
if (!match.matched)
|
|
11659
|
+
continue;
|
|
11660
|
+
if (match.malformed || match.value === true) {
|
|
11661
|
+
return { surface: args[index].split("=", 1)[0], reason: "exposes runtime model selection outside Caveman's locked session" };
|
|
11662
|
+
}
|
|
11663
|
+
index += match.consumed;
|
|
11664
|
+
}
|
|
11665
|
+
if (args.some((arg) => {
|
|
11666
|
+
return arg === "--list-extensions" || arg === "--listExtensions" || qwenShortOptionLetters(arg).has("l") || arg.startsWith("--channel=") || arg === "--channel";
|
|
11667
|
+
})) {
|
|
11668
|
+
return { surface: "control mode", reason: "does not run one confined Qwen model session" };
|
|
11669
|
+
}
|
|
11670
|
+
const controlCommands = new Set(["auth", "channel", "extensions", "hooks", "mcp", "review", "serve", "sessions", "update"]);
|
|
11671
|
+
const booleanOptions = new Set([
|
|
11672
|
+
"--telemetry", "--debug", "--bare", "--safe-mode", "--insecure", "--chat-recording",
|
|
11673
|
+
"--sandbox", "--yolo", "--experimental-lsp", "--restore-ask-user-question",
|
|
11674
|
+
"--screen-reader", "--include-partial-messages", "--continue", "--fork-session", "--worktree",
|
|
11675
|
+
"-s", "-c", "-v", "--version", "-h", "--help",
|
|
11676
|
+
]);
|
|
11677
|
+
const valueOptions = new Set([
|
|
11678
|
+
"--telemetry-target", "--telemetry-otlp-endpoint", "--telemetry-otlp-protocol", "--telemetry-log-prompts",
|
|
11679
|
+
"--telemetry-outfile", "--proxy", "--model", "-m", "--prompt", "-p", "--prompt-interactive", "-i",
|
|
11680
|
+
"--system-prompt", "--append-system-prompt", "--sandbox-image", "--approval-mode", "--allowed-mcp-server-names",
|
|
11681
|
+
"--mcp-config", "--allowed-tools", "--include-directories", "--openai-logging", "--openai-logging-dir",
|
|
11682
|
+
"--openai-api-key", "--openai-base-url", "--input-format", "--output-format", "-o", "--json-fd",
|
|
11683
|
+
"--json-file", "--json-schema", "--input-file", "--resume", "-r", "--session-id", "--sandbox-session-id",
|
|
11684
|
+
"--max-session-turns", "--max-wall-time", "--max-tool-calls", "--max-subagent-depth", "--core-tools",
|
|
11685
|
+
"--exclude-tools", "--disabled-slash-commands", "--auth-type",
|
|
11686
|
+
]);
|
|
11687
|
+
const routedArgs = args.filter((arg) => arg !== "--extensions=none");
|
|
11688
|
+
for (let index = 0; index < routedArgs.length; index++) {
|
|
11689
|
+
const arg = routedArgs[index];
|
|
11690
|
+
if (arg === "--")
|
|
11691
|
+
break;
|
|
11692
|
+
if (arg.startsWith("--") && arg.includes("="))
|
|
11693
|
+
continue;
|
|
11694
|
+
if (booleanOptions.has(arg)) {
|
|
11695
|
+
if (routedArgs[index + 1] === "true" || routedArgs[index + 1] === "false")
|
|
11696
|
+
index++;
|
|
11697
|
+
continue;
|
|
11698
|
+
}
|
|
11699
|
+
if (valueOptions.has(arg)) {
|
|
11700
|
+
if (routedArgs[index + 1] !== undefined)
|
|
11701
|
+
index++;
|
|
11702
|
+
continue;
|
|
11703
|
+
}
|
|
11704
|
+
if (arg.startsWith("-"))
|
|
11705
|
+
continue;
|
|
11706
|
+
return controlCommands.has(arg)
|
|
11707
|
+
? { surface: arg, reason: "is a Qwen control command, not one confined model session" }
|
|
11708
|
+
: null;
|
|
11709
|
+
}
|
|
11710
|
+
return null;
|
|
11711
|
+
}
|
|
11712
|
+
function qwenRouteOverride(agent, args) {
|
|
11713
|
+
const extensionOverride = qwenExtensionRouteOverride(args);
|
|
11714
|
+
if (extensionOverride)
|
|
11715
|
+
return extensionOverride;
|
|
11716
|
+
const controlOverride = qwenControlSurfaceOverride(args);
|
|
11717
|
+
if (controlOverride)
|
|
11718
|
+
return controlOverride;
|
|
11719
|
+
// Qwen 0.22.3 checks raw process.argv before yargs and forces SIMPLE mode
|
|
11720
|
+
// whenever this exact token occurs, even after `--` or beside `false`.
|
|
11721
|
+
if (args.includes("--bare"))
|
|
11722
|
+
return { surface: "--bare", reason: "ignores Caveman system settings" };
|
|
11723
|
+
const modelValues = [];
|
|
11724
|
+
const fallbackValues = [];
|
|
11725
|
+
const authValues = [];
|
|
11726
|
+
const safeValues = [];
|
|
11727
|
+
const bareValues = [];
|
|
11728
|
+
let modelOccurrences = 0;
|
|
11729
|
+
let authOccurrences = 0;
|
|
11730
|
+
let safeMalformed = false;
|
|
11731
|
+
let bareMalformed = false;
|
|
11732
|
+
let modelMalformed = false;
|
|
11733
|
+
let fallbackMalformed = false;
|
|
11734
|
+
let authMalformed = false;
|
|
11735
|
+
for (let index = 0; index < args.length; index++) {
|
|
11736
|
+
const arg = args[index];
|
|
11737
|
+
if (arg === "--")
|
|
11738
|
+
break;
|
|
11739
|
+
if (qwenMatchedOption(arg, ["--openai-api-key", "--openaiApiKey"])) {
|
|
11740
|
+
return { surface: "--openai-api-key", reason: "overrides Caveman's credential route" };
|
|
11741
|
+
}
|
|
11742
|
+
if (qwenMatchedOption(arg, ["--openai-base-url", "--openaiBaseUrl"])) {
|
|
11743
|
+
return { surface: "--openai-base-url", reason: "overrides Caveman's gateway route" };
|
|
11744
|
+
}
|
|
11745
|
+
const model = qwenMatchedOption(arg, ["--model", "--m"]);
|
|
11746
|
+
if (model || arg === "-m") {
|
|
11747
|
+
modelOccurrences++;
|
|
11748
|
+
const value = model?.inline ? model.value : args[index + 1];
|
|
11749
|
+
if (typeof value !== "string" || !value || value === "--" || (!model?.inline && value.startsWith("-"))) {
|
|
11750
|
+
modelMalformed = true;
|
|
11751
|
+
}
|
|
11752
|
+
else {
|
|
11753
|
+
modelValues.push(value);
|
|
11754
|
+
if (!model?.inline)
|
|
11755
|
+
index++;
|
|
11756
|
+
}
|
|
11757
|
+
continue;
|
|
11758
|
+
}
|
|
11759
|
+
if (arg.startsWith("-") && !arg.startsWith("--") && arg.slice(1).includes("m")) {
|
|
11760
|
+
if (!arg.startsWith("-m=")) {
|
|
11761
|
+
return { surface: "-m", reason: "is ambiguous inside a short-option cluster" };
|
|
11762
|
+
}
|
|
11763
|
+
modelOccurrences++;
|
|
11764
|
+
const value = arg.slice(3);
|
|
11765
|
+
if (!value)
|
|
11766
|
+
modelMalformed = true;
|
|
11767
|
+
else
|
|
11768
|
+
modelValues.push(value);
|
|
11769
|
+
continue;
|
|
11770
|
+
}
|
|
11771
|
+
const fallback = qwenMatchedOption(arg, ["--fallback-model", "--fallbackModel"]);
|
|
11772
|
+
if (fallback) {
|
|
11773
|
+
const raw = [];
|
|
11774
|
+
if (fallback.inline) {
|
|
11775
|
+
if (fallback.value !== undefined)
|
|
11776
|
+
raw.push(fallback.value);
|
|
11777
|
+
}
|
|
11778
|
+
// yargs arrays consume every following non-option token even when first
|
|
11779
|
+
// value used `=`; all of them participate in the effective fallback list.
|
|
11780
|
+
while (index + 1 < args.length && !args[index + 1].startsWith("-"))
|
|
11781
|
+
raw.push(args[++index]);
|
|
11782
|
+
const values = raw.flatMap((value) => value.split(",").map((item) => item.trim()).filter(Boolean));
|
|
11783
|
+
if (values.length === 0)
|
|
11784
|
+
fallbackMalformed = true;
|
|
11785
|
+
else
|
|
11786
|
+
fallbackValues.push(...values);
|
|
11787
|
+
continue;
|
|
11788
|
+
}
|
|
11789
|
+
const auth = qwenMatchedOption(arg, ["--auth-type", "--authType"]);
|
|
11790
|
+
if (auth) {
|
|
11791
|
+
authOccurrences++;
|
|
11792
|
+
const value = auth.inline ? auth.value : args[index + 1];
|
|
11793
|
+
if (typeof value !== "string" || !value || value === "--" || (!auth.inline && value.startsWith("-"))) {
|
|
11794
|
+
authMalformed = true;
|
|
11795
|
+
}
|
|
11796
|
+
else {
|
|
11797
|
+
authValues.push(value);
|
|
11798
|
+
if (!auth.inline)
|
|
11799
|
+
index++;
|
|
11800
|
+
}
|
|
11801
|
+
continue;
|
|
11802
|
+
}
|
|
11803
|
+
const safe = qwenBooleanArg(args, index, ["--safe-mode", "--safeMode"], ["--no-safe-mode", "--no-safeMode"]);
|
|
11804
|
+
if (safe.matched) {
|
|
11805
|
+
safeMalformed ||= safe.malformed;
|
|
11806
|
+
if (safe.value !== undefined)
|
|
11807
|
+
safeValues.push(safe.value);
|
|
11808
|
+
index += safe.consumed;
|
|
11809
|
+
continue;
|
|
11810
|
+
}
|
|
11811
|
+
const bare = qwenBooleanArg(args, index, ["--bare"], ["--no-bare"]);
|
|
11812
|
+
if (bare.matched) {
|
|
11813
|
+
bareMalformed ||= bare.malformed;
|
|
11814
|
+
if (bare.value !== undefined)
|
|
11815
|
+
bareValues.push(bare.value);
|
|
11816
|
+
index += bare.consumed;
|
|
11817
|
+
}
|
|
11818
|
+
}
|
|
11819
|
+
if (modelMalformed || modelOccurrences > 1 || modelValues.length !== modelOccurrences) {
|
|
11820
|
+
return { surface: "--model", reason: "is repeated or malformed" };
|
|
11821
|
+
}
|
|
11822
|
+
if (fallbackMalformed || fallbackValues.length > 3) {
|
|
11823
|
+
return { surface: "--fallback-model", reason: "is repeated or malformed" };
|
|
11824
|
+
}
|
|
11825
|
+
if (authMalformed || authOccurrences > 1 || authValues.length !== authOccurrences) {
|
|
11826
|
+
return { surface: "--auth-type", reason: "is repeated or malformed" };
|
|
11827
|
+
}
|
|
11828
|
+
if (safeMalformed || safeValues.length > 1)
|
|
11829
|
+
return { surface: "--safe-mode", reason: "is repeated or malformed" };
|
|
11830
|
+
if (bareMalformed || bareValues.length > 1)
|
|
11831
|
+
return { surface: "--bare", reason: "is repeated or malformed" };
|
|
11832
|
+
const routedModels = qwenProfileModelIds(agent);
|
|
11833
|
+
if (routedModels.size === 0)
|
|
11834
|
+
return { surface: "routing profile", reason: "has no common local and managed model" };
|
|
11835
|
+
if (modelValues.some((model) => !routedModels.has(model))) {
|
|
11836
|
+
return { surface: "--model", reason: "selects a model outside Caveman's routed profile" };
|
|
11837
|
+
}
|
|
11838
|
+
if (fallbackValues.some((model) => !routedModels.has(model))) {
|
|
11839
|
+
return { surface: "--fallback-model", reason: "selects a model outside Caveman's routed profile" };
|
|
11840
|
+
}
|
|
11841
|
+
if (authValues.some((auth) => auth !== "openai")) {
|
|
11842
|
+
return { surface: "--auth-type", reason: "selects an auth provider outside Caveman's routed profile" };
|
|
11843
|
+
}
|
|
11844
|
+
const layers = qwenSettingsLayers();
|
|
11845
|
+
if (!layers)
|
|
11846
|
+
return { surface: "effective settings", reason: "cannot be resolved safely" };
|
|
11847
|
+
for (const layer of layers) {
|
|
11848
|
+
const enforcedType = jsonValueAt(layer, ["security", "auth", "enforcedType"]);
|
|
11849
|
+
if (enforcedType !== undefined && enforcedType !== "openai") {
|
|
11850
|
+
return { surface: "enforced auth policy", reason: "requires a provider outside Caveman's routed profile" };
|
|
11851
|
+
}
|
|
11852
|
+
}
|
|
11853
|
+
const safeEnv = qwenEffectiveEnvValue(layers, "QWEN_CODE_SAFE_MODE");
|
|
11854
|
+
const bareEnv = qwenEffectiveEnvValue(layers, "QWEN_CODE_SIMPLE");
|
|
11855
|
+
if (safeEnv === null || bareEnv === null)
|
|
11856
|
+
return { surface: "effective settings", reason: "cannot be resolved safely" };
|
|
11857
|
+
const truthy = (value) => !!value && ["1", "true", "yes", "on"].includes(value.toLowerCase().trim());
|
|
11858
|
+
const safeMode = safeValues[0] ?? truthy(safeEnv);
|
|
11859
|
+
// Pinned Qwen implements bare mode as CLI-true OR QWEN_CODE_SIMPLE. An
|
|
11860
|
+
// explicit CLI false cannot neutralize an ambient true value.
|
|
11861
|
+
const bareMode = bareValues[0] === true || truthy(bareEnv);
|
|
11862
|
+
if (safeMode)
|
|
11863
|
+
return { surface: "--safe-mode", reason: "ignores Caveman system settings" };
|
|
11864
|
+
if (bareMode)
|
|
11865
|
+
return { surface: "--bare", reason: "ignores Caveman system settings" };
|
|
11866
|
+
return null;
|
|
11867
|
+
}
|
|
11868
|
+
function agentRouteOverride(agent, args) {
|
|
11869
|
+
if (agent.id === "kilo")
|
|
11870
|
+
return kiloRouteOverride(agent, args);
|
|
11871
|
+
if (agent.id === "qwen")
|
|
11872
|
+
return qwenRouteOverride(agent, args);
|
|
11873
|
+
// Claude Code 2.1.196+ refuses Remote Control unless ANTHROPIC_BASE_URL is
|
|
11874
|
+
// api.anthropic.com, and the first-party escape hatch does not apply (#947).
|
|
11875
|
+
if (agent.id === "claude" && args.includes("remote-control")) {
|
|
11876
|
+
return { surface: "remote-control", reason: "only runs against api.anthropic.com, so it cannot route through the proxy" };
|
|
11877
|
+
}
|
|
11878
|
+
return null;
|
|
11879
|
+
}
|
|
11880
|
+
function routeOverrideLabel(agent) {
|
|
11881
|
+
if (agent.id === "qwen")
|
|
11882
|
+
return "Qwen";
|
|
11883
|
+
if (agent.id === "kilo")
|
|
11884
|
+
return "Kilo";
|
|
11885
|
+
return agent.display_name;
|
|
11886
|
+
}
|
|
11887
|
+
function qwenCliBoolean(args, name) {
|
|
11888
|
+
let value;
|
|
11889
|
+
const camel = name.replace(/-([a-z])/g, (_match, char) => char.toUpperCase());
|
|
11890
|
+
const names = new Set([name, camel]);
|
|
11891
|
+
for (let index = 0; index < args.length; index++) {
|
|
11892
|
+
const arg = args[index];
|
|
11893
|
+
if (arg === "--")
|
|
11894
|
+
break;
|
|
11895
|
+
if ([...names].some((candidate) => arg === `--no-${candidate}`)) {
|
|
11896
|
+
value = false;
|
|
11897
|
+
continue;
|
|
11898
|
+
}
|
|
11899
|
+
const withValue = [...names].find((candidate) => arg.startsWith(`--${candidate}=`));
|
|
11900
|
+
if (withValue) {
|
|
11901
|
+
value = arg.slice(arg.indexOf("=") + 1) === "true";
|
|
11902
|
+
continue;
|
|
11903
|
+
}
|
|
11904
|
+
if (![...names].some((candidate) => arg === `--${candidate}`))
|
|
11905
|
+
continue;
|
|
11906
|
+
const next = args[index + 1];
|
|
11907
|
+
if (next === "true" || next === "false") {
|
|
11908
|
+
value = next === "true";
|
|
11909
|
+
index++;
|
|
11910
|
+
}
|
|
11911
|
+
else {
|
|
11912
|
+
value = true;
|
|
11913
|
+
}
|
|
11914
|
+
}
|
|
11915
|
+
return value;
|
|
11916
|
+
}
|
|
11917
|
+
function qwenModeEnabled(args, name, envKey, layers) {
|
|
11918
|
+
const explicit = qwenCliBoolean(args, name);
|
|
11919
|
+
if (explicit !== undefined)
|
|
11920
|
+
return explicit;
|
|
11921
|
+
const raw = qwenEffectiveEnvValue(layers, envKey);
|
|
11922
|
+
if (raw === null)
|
|
11923
|
+
return null;
|
|
11924
|
+
return !!raw && ["1", "true", "yes", "on"].includes(raw.toLowerCase().trim());
|
|
11925
|
+
}
|
|
11926
|
+
function qwenArgsPermitRecovery(args, layers) {
|
|
11927
|
+
if (qwenModeEnabled(args, "safe-mode", "QWEN_CODE_SAFE_MODE", layers) !== false)
|
|
11928
|
+
return false;
|
|
11929
|
+
if (qwenModeEnabled(args, "bare", "QWEN_CODE_SIMPLE", layers) !== false)
|
|
11930
|
+
return false;
|
|
11931
|
+
let allowedConfigured = false;
|
|
11932
|
+
const allowed = [];
|
|
11933
|
+
for (let index = 0; index < args.length; index++) {
|
|
11934
|
+
const arg = args[index];
|
|
11935
|
+
if (arg === "--")
|
|
11936
|
+
break;
|
|
11937
|
+
if (arg === "--mcp-config" || arg.startsWith("--mcp-config="))
|
|
11938
|
+
return false;
|
|
11939
|
+
if (arg.startsWith("--exclude-tools=")) {
|
|
11940
|
+
const denied = arg.slice(arg.indexOf("=") + 1).split(",").map((item) => item.trim()).filter(Boolean);
|
|
11941
|
+
if (denied.some(qwenCavemanToolDenied))
|
|
11942
|
+
return false;
|
|
11943
|
+
continue;
|
|
11944
|
+
}
|
|
11945
|
+
if (arg === "--exclude-tools") {
|
|
11946
|
+
while (index + 1 < args.length && !args[index + 1].startsWith("-")) {
|
|
11947
|
+
const denied = args[++index].split(",").map((item) => item.trim()).filter(Boolean);
|
|
11948
|
+
if (denied.some(qwenCavemanToolDenied))
|
|
11949
|
+
return false;
|
|
11950
|
+
}
|
|
11951
|
+
continue;
|
|
11952
|
+
}
|
|
11953
|
+
if (arg.startsWith("--allowed-mcp-server-names=")) {
|
|
11954
|
+
allowedConfigured = true;
|
|
11955
|
+
allowed.push(...arg.slice(arg.indexOf("=") + 1).split(",").map((item) => item.trim()).filter(Boolean));
|
|
11956
|
+
continue;
|
|
11957
|
+
}
|
|
11958
|
+
if (arg !== "--allowed-mcp-server-names")
|
|
11959
|
+
continue;
|
|
11960
|
+
allowedConfigured = true;
|
|
11961
|
+
while (index + 1 < args.length && !args[index + 1].startsWith("-")) {
|
|
11962
|
+
allowed.push(...args[++index].split(",").map((item) => item.trim()).filter(Boolean));
|
|
11963
|
+
}
|
|
11964
|
+
}
|
|
11965
|
+
return !allowedConfigured || allowed.some((pattern) => qwenMcpServerPatternMatches("caveman", pattern));
|
|
11966
|
+
}
|
|
11967
|
+
function ownedMcpRegistration(agentId, agentArgs = []) {
|
|
11968
|
+
const marker = readMcpServerMarker(agentId, "caveman");
|
|
11969
|
+
if (!marker)
|
|
11970
|
+
return null;
|
|
11971
|
+
if (agentId === "kilo") {
|
|
11972
|
+
const activePath = canonicalMcpConfigPath(kiloConfigPath());
|
|
11973
|
+
if (marker.config_path && marker.config_path !== activePath)
|
|
11974
|
+
return null;
|
|
11975
|
+
const config = readOptionalJsonObject(marker.config_path ?? activePath);
|
|
11976
|
+
return config && kiloMcpEntryMatches(jsonValueAt(config, ["mcp", "caveman"]), marker) ? marker : null;
|
|
11977
|
+
}
|
|
11978
|
+
if (agentId === "qwen") {
|
|
11979
|
+
const activePath = canonicalMcpConfigPath(qwenConfigPath());
|
|
11980
|
+
if (marker.config_path && marker.config_path !== activePath)
|
|
11981
|
+
return null;
|
|
11982
|
+
const layers = qwenSettingsLayers();
|
|
11983
|
+
if (!layers || !qwenArgsPermitRecovery(agentArgs, layers))
|
|
11984
|
+
return null;
|
|
11985
|
+
const config = readQwenJsonObject(marker.config_path ?? activePath);
|
|
11986
|
+
if (!config || !qwenMcpEntryMatches(jsonValueAt(config, ["mcpServers", "caveman"]), marker))
|
|
11987
|
+
return null;
|
|
11988
|
+
return qwenSettingsPermitRecovery(marker, layers) ? marker : null;
|
|
11989
|
+
}
|
|
11990
|
+
return marker;
|
|
11991
|
+
}
|
|
11992
|
+
function planMcpQwenJson(mcp, serverName = "caveman") {
|
|
11993
|
+
const path = canonicalMcpConfigPath(qwenConfigPath());
|
|
11994
|
+
const marker = readMcpServerMarker("qwen", serverName);
|
|
11995
|
+
if (marker?.config_path && marker.config_path !== path) {
|
|
11996
|
+
console.error(`${mark("warn")} ${serverName} is owned in ${marker.config_path}; uninstall it before installing into ${path}`);
|
|
11997
|
+
return null;
|
|
11998
|
+
}
|
|
11999
|
+
const loaded = readStrictMcpJsonRoot(path);
|
|
12000
|
+
if (!loaded)
|
|
12001
|
+
return null;
|
|
12002
|
+
const { root } = loaded;
|
|
12003
|
+
if (root.mcpServers !== undefined && (!root.mcpServers || typeof root.mcpServers !== "object" || Array.isArray(root.mcpServers))) {
|
|
12004
|
+
console.error(`${mark("warn")} ${path} mcpServers must be a JSON object; not modifying it`);
|
|
12005
|
+
return null;
|
|
12006
|
+
}
|
|
12007
|
+
const servers = root.mcpServers;
|
|
12008
|
+
const current = servers?.[serverName];
|
|
12009
|
+
if (marker && !marker.config_path && current === undefined) {
|
|
12010
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Qwen config; refusing relocation`);
|
|
12011
|
+
return null;
|
|
12012
|
+
}
|
|
12013
|
+
if (current !== undefined) {
|
|
12014
|
+
if (!marker) {
|
|
12015
|
+
console.error(`${mark("warn")} ${path} mcpServers.${serverName} exists but is not Caveman-journaled; refusing overwrite`);
|
|
12016
|
+
return null;
|
|
12017
|
+
}
|
|
12018
|
+
if (!qwenMcpEntryMatches(current, marker)) {
|
|
12019
|
+
console.error(`${mark("warn")} ${path} mcpServers.${serverName} changed since Caveman installed it; refusing overwrite`);
|
|
12020
|
+
return null;
|
|
12021
|
+
}
|
|
12022
|
+
if (qwenMcpEntryMatches(current, mcp)) {
|
|
12023
|
+
return ownedMcpConfigPlan("qwen", path, loaded, loaded.bytes);
|
|
12024
|
+
}
|
|
12025
|
+
}
|
|
12026
|
+
const nextServers = servers ?? {};
|
|
12027
|
+
nextServers[serverName] = qwenMcpEntry(mcp);
|
|
12028
|
+
root.mcpServers = nextServers;
|
|
12029
|
+
return ownedMcpConfigPlan("qwen", path, loaded, Buffer.from(JSON.stringify(root, null, 2) + "\n"));
|
|
12030
|
+
}
|
|
12031
|
+
function planRemoveMcpQwenJson(serverName = "caveman") {
|
|
12032
|
+
const marker = readMcpServerMarker("qwen", serverName);
|
|
12033
|
+
const path = marker?.config_path ?? canonicalMcpConfigPath(qwenConfigPath());
|
|
12034
|
+
const loaded = readStrictMcpJsonRoot(path);
|
|
12035
|
+
if (!loaded)
|
|
12036
|
+
return null;
|
|
12037
|
+
if (!loaded.exists) {
|
|
12038
|
+
if (marker && !marker.config_path) {
|
|
12039
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Qwen config; refusing removal`);
|
|
12040
|
+
return null;
|
|
12041
|
+
}
|
|
12042
|
+
if (marker?.config_path && movedOwnedMcpRemovalBlocked("qwen", serverName, marker))
|
|
12043
|
+
return null;
|
|
12044
|
+
return ownedMcpConfigPlan("qwen", path, loaded, null);
|
|
12045
|
+
}
|
|
12046
|
+
const { root } = loaded;
|
|
12047
|
+
if (root.mcpServers !== undefined && (!root.mcpServers || typeof root.mcpServers !== "object" || Array.isArray(root.mcpServers))) {
|
|
12048
|
+
console.error(`${mark("warn")} ${path} mcpServers must be a JSON object; not modifying it`);
|
|
12049
|
+
return null;
|
|
12050
|
+
}
|
|
12051
|
+
const servers = root.mcpServers;
|
|
12052
|
+
const current = servers?.[serverName];
|
|
12053
|
+
if (current === undefined) {
|
|
12054
|
+
if (marker && !marker.config_path) {
|
|
12055
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Qwen config; refusing removal`);
|
|
12056
|
+
return null;
|
|
12057
|
+
}
|
|
12058
|
+
return ownedMcpConfigPlan("qwen", path, loaded, loaded.bytes);
|
|
12059
|
+
}
|
|
12060
|
+
if (!marker) {
|
|
12061
|
+
console.error(`${mark("warn")} ${path} mcpServers.${serverName} exists but is not Caveman-journaled; refusing removal`);
|
|
12062
|
+
return null;
|
|
12063
|
+
}
|
|
12064
|
+
if (!qwenMcpEntryMatches(current, marker)) {
|
|
12065
|
+
console.error(`${mark("warn")} ${path} mcpServers.${serverName} changed since Caveman installed it; refusing removal`);
|
|
12066
|
+
return null;
|
|
12067
|
+
}
|
|
12068
|
+
delete servers[serverName];
|
|
12069
|
+
if (Object.keys(servers).length === 0)
|
|
12070
|
+
delete root.mcpServers;
|
|
12071
|
+
return ownedMcpConfigPlan("qwen", path, loaded, Buffer.from(JSON.stringify(root, null, 2) + "\n"));
|
|
12072
|
+
}
|
|
12073
|
+
function optionalBytesHash(bytes) {
|
|
12074
|
+
return bytes ? bytesHash(bytes) : null;
|
|
12075
|
+
}
|
|
12076
|
+
function mcpPendingJournalPath(agent, serverName) {
|
|
12077
|
+
return `${canonicalOwnedMcpMarkerPath(agent, serverName)}.pending`;
|
|
12078
|
+
}
|
|
12079
|
+
function mcpConfigPendingJournalPath(configPath) {
|
|
12080
|
+
const canonicalPath = canonicalMcpConfigPath(configPath);
|
|
12081
|
+
return join(dirname(canonicalPath), `.${basename(canonicalPath)}.caveman-mcp.pending.json`);
|
|
12082
|
+
}
|
|
12083
|
+
function mcpMarkerBytes(mcp, tool, configPath) {
|
|
12084
|
+
return Buffer.from(JSON.stringify({
|
|
12085
|
+
...(configPath ? { schema_version: 1 } : {}),
|
|
12086
|
+
tool,
|
|
12087
|
+
command: mcp.command,
|
|
12088
|
+
args: mcp.args,
|
|
12089
|
+
...(configPath ? { config_path: canonicalMcpConfigPath(configPath) } : {}),
|
|
12090
|
+
}, null, 2) + "\n");
|
|
12091
|
+
}
|
|
12092
|
+
function validMcpMarkerBytes(bytes, agent, serverName) {
|
|
12093
|
+
return parseMcpServerMarkerBytes(agent, serverName, bytes) !== null;
|
|
12094
|
+
}
|
|
12095
|
+
function decodePendingBytes(value, field) {
|
|
12096
|
+
if (value === null)
|
|
12097
|
+
return null;
|
|
12098
|
+
if (typeof value !== "string")
|
|
12099
|
+
throw new Error(`${field} must be base64 or null`);
|
|
12100
|
+
const bytes = Buffer.from(value, "base64");
|
|
12101
|
+
if (bytes.toString("base64") !== value)
|
|
12102
|
+
throw new Error(`${field} is not canonical base64`);
|
|
12103
|
+
return bytes;
|
|
12104
|
+
}
|
|
12105
|
+
function validOptionalHash(value) {
|
|
12106
|
+
return value === null || (typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value));
|
|
12107
|
+
}
|
|
12108
|
+
function ownedMcpPendingLabel(agent, serverName) {
|
|
12109
|
+
return agent && serverName ? `${agent} ${serverName} MCP` : "owned MCP";
|
|
12110
|
+
}
|
|
12111
|
+
function readOwnedMcpPendingJournalAt(path, expected = {}) {
|
|
12112
|
+
const label = ownedMcpPendingLabel(expected.agent, expected.serverName);
|
|
12113
|
+
let bytes;
|
|
12114
|
+
let value;
|
|
12115
|
+
try {
|
|
12116
|
+
bytes = readFileSync(path);
|
|
12117
|
+
value = JSON.parse(bytes.toString("utf8"));
|
|
12118
|
+
}
|
|
12119
|
+
catch (error) {
|
|
12120
|
+
if (error.code === "ENOENT")
|
|
12121
|
+
return null;
|
|
12122
|
+
throw new Error(`cannot read pending ${label} transaction: ${error.message}`);
|
|
12123
|
+
}
|
|
12124
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
12125
|
+
throw new Error(`pending ${label} transaction is malformed; refusing recovery`);
|
|
12126
|
+
}
|
|
12127
|
+
if (process.platform !== "win32" && (statSync(path).mode & 0o077) !== 0) {
|
|
12128
|
+
throw new Error(`pending ${label} transaction has unsafe permissions; refusing recovery`);
|
|
12129
|
+
}
|
|
12130
|
+
const keys = [
|
|
12131
|
+
"action", "agent", "config_after_sha256", "config_before_base64", "config_before_mode", "config_path",
|
|
12132
|
+
"config_before_sha256", "marker_after_base64", "marker_after_sha256", "marker_before_base64", "marker_before_mode",
|
|
12133
|
+
"marker_before_sha256", "marker_path", "schema_version", "server_name", "transaction_id",
|
|
12134
|
+
].sort();
|
|
12135
|
+
const journalAgent = value.agent;
|
|
12136
|
+
const journalServer = value.server_name;
|
|
12137
|
+
if (Object.keys(value).sort().join("\0") !== keys.join("\0")
|
|
12138
|
+
|| value.schema_version !== 1
|
|
12139
|
+
|| typeof value.transaction_id !== "string"
|
|
12140
|
+
|| !/^[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)
|
|
12141
|
+
|| (journalAgent !== "kilo" && journalAgent !== "qwen")
|
|
12142
|
+
|| typeof journalServer !== "string"
|
|
12143
|
+
|| !mcpServerToolName(journalServer)
|
|
12144
|
+
|| (expected.agent !== undefined && journalAgent !== expected.agent)
|
|
12145
|
+
|| (expected.serverName !== undefined && journalServer !== expected.serverName)
|
|
12146
|
+
|| (value.action !== "install" && value.action !== "uninstall")
|
|
12147
|
+
|| typeof value.config_path !== "string"
|
|
12148
|
+
|| value.config_path !== canonicalMcpConfigPath(value.config_path)
|
|
12149
|
+
|| (expected.configPath !== undefined && value.config_path !== canonicalMcpConfigPath(expected.configPath))
|
|
12150
|
+
|| typeof value.marker_path !== "string"
|
|
12151
|
+
|| value.marker_path !== canonicalMcpConfigPath(value.marker_path)
|
|
12152
|
+
|| (expected.locatorPath !== undefined && `${value.marker_path}.pending` !== canonicalMcpConfigPath(expected.locatorPath))
|
|
12153
|
+
|| !Number.isInteger(value.config_before_mode) || value.config_before_mode < 0 || value.config_before_mode > 0o777
|
|
12154
|
+
|| !Number.isInteger(value.marker_before_mode) || value.marker_before_mode < 0 || value.marker_before_mode > 0o777
|
|
12155
|
+
|| !validOptionalHash(value.config_before_sha256)
|
|
12156
|
+
|| !validOptionalHash(value.config_after_sha256)
|
|
12157
|
+
|| !validOptionalHash(value.marker_before_sha256)
|
|
12158
|
+
|| !validOptionalHash(value.marker_after_sha256)) {
|
|
12159
|
+
throw new Error(`pending ${label} transaction is malformed; refusing recovery`);
|
|
12160
|
+
}
|
|
12161
|
+
try {
|
|
12162
|
+
const configBefore = decodePendingBytes(value.config_before_base64, "config_before_base64");
|
|
12163
|
+
const markerBefore = decodePendingBytes(value.marker_before_base64, "marker_before_base64");
|
|
12164
|
+
const markerAfter = decodePendingBytes(value.marker_after_base64, "marker_after_base64");
|
|
12165
|
+
if (optionalBytesHash(configBefore) !== value.config_before_sha256
|
|
12166
|
+
|| optionalBytesHash(markerBefore) !== value.marker_before_sha256
|
|
12167
|
+
|| optionalBytesHash(markerAfter) !== value.marker_after_sha256
|
|
12168
|
+
|| (markerBefore !== null && !validMcpMarkerBytes(markerBefore, journalAgent, journalServer))
|
|
12169
|
+
|| (markerAfter !== null && !validMcpMarkerBytes(markerAfter, journalAgent, journalServer))
|
|
12170
|
+
|| (markerBefore !== null && parseMcpServerMarkerBytes(journalAgent, journalServer, markerBefore)?.config_path !== undefined
|
|
12171
|
+
&& parseMcpServerMarkerBytes(journalAgent, journalServer, markerBefore)?.config_path !== value.config_path)
|
|
12172
|
+
|| (markerAfter !== null && parseMcpServerMarkerBytes(journalAgent, journalServer, markerAfter)?.config_path !== value.config_path)
|
|
12173
|
+
|| (value.action === "install") !== (markerAfter !== null)) {
|
|
12174
|
+
throw new Error("journal bytes do not match declared transaction state");
|
|
12175
|
+
}
|
|
12176
|
+
return {
|
|
12177
|
+
journal: value,
|
|
12178
|
+
configBefore,
|
|
12179
|
+
markerBefore,
|
|
12180
|
+
markerAfter,
|
|
12181
|
+
path,
|
|
12182
|
+
bytes,
|
|
12183
|
+
};
|
|
12184
|
+
}
|
|
12185
|
+
catch (error) {
|
|
12186
|
+
throw new Error(`pending ${label} transaction is malformed: ${error.message}`);
|
|
12187
|
+
}
|
|
12188
|
+
}
|
|
12189
|
+
function readOwnedMcpPendingLocator(agent, serverName) {
|
|
12190
|
+
const path = canonicalMcpConfigPath(mcpPendingJournalPath(agent, serverName));
|
|
12191
|
+
return readOwnedMcpPendingJournalAt(path, { agent, serverName, locatorPath: path });
|
|
12192
|
+
}
|
|
12193
|
+
function readOwnedMcpConfigPending(configPath) {
|
|
12194
|
+
const canonicalPath = canonicalMcpConfigPath(configPath);
|
|
12195
|
+
return readOwnedMcpPendingJournalAt(mcpConfigPendingJournalPath(canonicalPath), { configPath: canonicalPath });
|
|
12196
|
+
}
|
|
12197
|
+
function recoverOwnedMcpTransaction(pending) {
|
|
12198
|
+
if (!pending)
|
|
12199
|
+
return "none";
|
|
12200
|
+
const { journal, configBefore, markerBefore } = pending;
|
|
12201
|
+
const agent = journal.agent;
|
|
12202
|
+
const serverName = journal.server_name;
|
|
12203
|
+
const configPath = journal.config_path;
|
|
12204
|
+
const markerPath = journal.marker_path;
|
|
12205
|
+
const configPendingPath = mcpConfigPendingJournalPath(configPath);
|
|
12206
|
+
const locatorPath = `${markerPath}.pending`;
|
|
12207
|
+
const configPending = readOwnedMcpPendingJournalAt(configPendingPath, { agent, serverName, configPath });
|
|
12208
|
+
const locatorPending = readOwnedMcpPendingJournalAt(locatorPath, { agent, serverName, configPath, locatorPath });
|
|
12209
|
+
if (configPending && locatorPending && !configPending.bytes.equals(locatorPending.bytes)) {
|
|
12210
|
+
throw new Error(`${agent} ${serverName} MCP transaction journals disagree; refusing recovery`);
|
|
12211
|
+
}
|
|
12212
|
+
const configCurrent = fileBytes(configPath);
|
|
12213
|
+
const markerCurrent = fileBytes(markerPath);
|
|
12214
|
+
const configHash = optionalBytesHash(configCurrent);
|
|
12215
|
+
const markerHash = optionalBytesHash(markerCurrent);
|
|
12216
|
+
const configIsBefore = configHash === journal.config_before_sha256;
|
|
12217
|
+
const configIsAfter = configHash === journal.config_after_sha256;
|
|
12218
|
+
const markerIsBefore = markerHash === journal.marker_before_sha256;
|
|
12219
|
+
const markerIsAfter = markerHash === journal.marker_after_sha256;
|
|
12220
|
+
const removePendingCopies = () => {
|
|
12221
|
+
if (configPending)
|
|
12222
|
+
durableUnlink(configPendingPath);
|
|
12223
|
+
if (locatorPending)
|
|
12224
|
+
durableUnlink(locatorPath);
|
|
12225
|
+
};
|
|
12226
|
+
if (configIsAfter && markerIsAfter) {
|
|
12227
|
+
removePendingCopies();
|
|
12228
|
+
process.stderr.write(`${mark("warn")} finalized interrupted ${agent} ${serverName} MCP transaction\n`);
|
|
12229
|
+
return "finalized";
|
|
12230
|
+
}
|
|
12231
|
+
if (configIsBefore && markerIsBefore) {
|
|
12232
|
+
removePendingCopies();
|
|
12233
|
+
process.stderr.write(`${mark("warn")} discarded uncommitted ${agent} ${serverName} MCP transaction\n`);
|
|
12234
|
+
return "discarded";
|
|
12235
|
+
}
|
|
12236
|
+
if ((!configIsBefore && !configIsAfter) || (!markerIsBefore && !markerIsAfter)) {
|
|
12237
|
+
throw new Error(`${agent} ${serverName} MCP config or ownership journal changed during interrupted transaction; refusing destructive recovery`);
|
|
12238
|
+
}
|
|
12239
|
+
if (!configPending || !locatorPending) {
|
|
12240
|
+
throw new Error(`${agent} ${serverName} MCP transaction lost one durable journal copy; refusing destructive recovery`);
|
|
12241
|
+
}
|
|
12242
|
+
if (!configIsBefore) {
|
|
12243
|
+
durableReplaceFileIfUnchanged(configPath, configCurrent, configBefore, journal.config_before_mode);
|
|
12244
|
+
}
|
|
12245
|
+
if (!markerIsBefore) {
|
|
12246
|
+
durableReplaceFileIfUnchanged(markerPath, markerCurrent, markerBefore, journal.marker_before_mode);
|
|
12247
|
+
}
|
|
12248
|
+
if (optionalBytesHash(fileBytes(configPath)) !== journal.config_before_sha256
|
|
12249
|
+
|| optionalBytesHash(fileBytes(markerPath)) !== journal.marker_before_sha256) {
|
|
12250
|
+
throw new Error(`${agent} ${serverName} MCP rollback postflight mismatch`);
|
|
12251
|
+
}
|
|
12252
|
+
removePendingCopies();
|
|
12253
|
+
process.stderr.write(`${mark("warn")} rolled back interrupted ${agent} ${serverName} MCP transaction\n`);
|
|
12254
|
+
return "rolled-back";
|
|
12255
|
+
}
|
|
12256
|
+
function transactOwnedMcpConfig(agent, serverName, action, mcp, lockedConfigPath) {
|
|
12257
|
+
const plan = action === "install"
|
|
12258
|
+
? agent === "kilo" ? planMcpKiloJson(mcp, serverName) : planMcpQwenJson(mcp, serverName)
|
|
12259
|
+
: agent === "kilo" ? planRemoveMcpKiloJson(serverName) : planRemoveMcpQwenJson(serverName);
|
|
12260
|
+
if (!plan)
|
|
12261
|
+
return false;
|
|
12262
|
+
if (lockedConfigPath && plan.path !== canonicalMcpConfigPath(lockedConfigPath)) {
|
|
12263
|
+
throw new Error(`${agent} ${serverName} MCP config target changed while acquiring lock; refusing mutation`);
|
|
12264
|
+
}
|
|
12265
|
+
const markerPath = canonicalOwnedMcpMarkerPath(agent, serverName);
|
|
12266
|
+
const markerBefore = fileBytes(markerPath);
|
|
12267
|
+
if (markerBefore !== null && !validMcpMarkerBytes(markerBefore, agent, serverName)) {
|
|
12268
|
+
throw new Error(`${markerPath} is not a valid Caveman ownership journal; refusing overwrite`);
|
|
12269
|
+
}
|
|
12270
|
+
const markerBeforeMode = markerBefore === null ? 0o600 : statSync(markerPath).mode & 0o777;
|
|
12271
|
+
if (!optionalBytesEqual(fileBytes(markerPath), markerBefore)) {
|
|
12272
|
+
throw new Error(`${markerPath} changed while planning MCP update; refusing overwrite`);
|
|
12273
|
+
}
|
|
12274
|
+
const markerAfter = action === "install" ? mcpMarkerBytes(mcp, mcpServerToolName(serverName), plan.path) : null;
|
|
12275
|
+
if (!plan.changed && optionalBytesEqual(markerBefore, markerAfter))
|
|
12276
|
+
return true;
|
|
12277
|
+
const journal = {
|
|
12278
|
+
schema_version: 1,
|
|
12279
|
+
transaction_id: randomUUID(),
|
|
12280
|
+
agent,
|
|
12281
|
+
server_name: serverName,
|
|
12282
|
+
action,
|
|
12283
|
+
config_path: plan.path,
|
|
12284
|
+
marker_path: markerPath,
|
|
12285
|
+
config_before_base64: plan.before?.toString("base64") ?? null,
|
|
12286
|
+
config_before_mode: plan.beforeMode,
|
|
12287
|
+
config_before_sha256: optionalBytesHash(plan.before),
|
|
12288
|
+
config_after_sha256: optionalBytesHash(plan.after),
|
|
12289
|
+
marker_before_base64: markerBefore?.toString("base64") ?? null,
|
|
12290
|
+
marker_before_mode: markerBeforeMode,
|
|
12291
|
+
marker_before_sha256: optionalBytesHash(markerBefore),
|
|
12292
|
+
marker_after_base64: markerAfter?.toString("base64") ?? null,
|
|
12293
|
+
marker_after_sha256: optionalBytesHash(markerAfter),
|
|
12294
|
+
};
|
|
12295
|
+
const locatorPath = `${markerPath}.pending`;
|
|
12296
|
+
const configPendingPath = mcpConfigPendingJournalPath(plan.path);
|
|
12297
|
+
const pendingBytes = Buffer.from(JSON.stringify(journal, null, 2) + "\n");
|
|
12298
|
+
if (fileBytes(locatorPath) !== null || fileBytes(configPendingPath) !== null) {
|
|
12299
|
+
throw new Error(`${agent} ${serverName} MCP transaction journal already exists; refusing overwrite`);
|
|
12300
|
+
}
|
|
12301
|
+
durableCreateFile(locatorPath, pendingBytes);
|
|
12302
|
+
try {
|
|
12303
|
+
durableCreateFile(configPendingPath, pendingBytes);
|
|
12304
|
+
}
|
|
12305
|
+
catch (error) {
|
|
12306
|
+
durableUnlink(locatorPath);
|
|
12307
|
+
throw error;
|
|
12308
|
+
}
|
|
12309
|
+
try {
|
|
12310
|
+
if (action === "install") {
|
|
12311
|
+
if (plan.changed)
|
|
12312
|
+
durableReplaceFileIfUnchanged(plan.path, plan.before, plan.after, plan.beforeMode);
|
|
12313
|
+
if (!optionalBytesEqual(markerBefore, markerAfter))
|
|
12314
|
+
durableReplaceFileIfUnchanged(markerPath, markerBefore, markerAfter);
|
|
12315
|
+
}
|
|
12316
|
+
else {
|
|
12317
|
+
if (!optionalBytesEqual(markerBefore, markerAfter))
|
|
12318
|
+
durableReplaceFileIfUnchanged(markerPath, markerBefore, markerAfter);
|
|
12319
|
+
if (plan.changed)
|
|
12320
|
+
durableReplaceFileIfUnchanged(plan.path, plan.before, plan.after, plan.beforeMode);
|
|
12321
|
+
}
|
|
12322
|
+
if (optionalBytesHash(fileBytes(plan.path)) !== journal.config_after_sha256
|
|
12323
|
+
|| optionalBytesHash(fileBytes(markerPath)) !== journal.marker_after_sha256) {
|
|
12324
|
+
throw new Error(`${agent} ${serverName} MCP transaction postflight mismatch`);
|
|
12325
|
+
}
|
|
12326
|
+
durableUnlink(configPendingPath);
|
|
12327
|
+
durableUnlink(locatorPath);
|
|
12328
|
+
return true;
|
|
12329
|
+
}
|
|
12330
|
+
catch (error) {
|
|
12331
|
+
try {
|
|
12332
|
+
const recovery = recoverOwnedMcpTransaction(readOwnedMcpConfigPending(plan.path) ?? readOwnedMcpPendingLocator(agent, serverName));
|
|
12333
|
+
if (recovery === "finalized")
|
|
12334
|
+
return true;
|
|
12335
|
+
}
|
|
12336
|
+
catch (recoveryError) {
|
|
12337
|
+
throw new Error(`${agent} ${serverName} MCP transaction failed and safe recovery was blocked: ${recoveryError.message}; original error: ${error.message}`);
|
|
12338
|
+
}
|
|
12339
|
+
throw new Error(`${agent} ${serverName} MCP transaction failed and rolled back: ${error.message}`);
|
|
12340
|
+
}
|
|
12341
|
+
}
|
|
12342
|
+
function withOwnedMcpTransactionLock(agent, serverName, run) {
|
|
12343
|
+
const markerPath = canonicalOwnedMcpMarkerPath(agent, serverName);
|
|
12344
|
+
return withMcpConfigLock(markerPath, () => {
|
|
12345
|
+
const activeConfigPath = () => canonicalMcpConfigPath(agent === "kilo" ? kiloConfigPath() : qwenConfigPath());
|
|
12346
|
+
const resourcePath = () => readOwnedMcpPendingLocator(agent, serverName)?.journal.config_path
|
|
12347
|
+
?? readMcpServerMarker(agent, serverName)?.config_path
|
|
12348
|
+
?? activeConfigPath();
|
|
12349
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
12350
|
+
const lockPath = canonicalMcpConfigPath(resourcePath());
|
|
12351
|
+
const outcome = withMcpConfigLock(lockPath, () => {
|
|
12352
|
+
const locatorPending = readOwnedMcpPendingLocator(agent, serverName);
|
|
12353
|
+
if (locatorPending) {
|
|
12354
|
+
if (locatorPending.journal.config_path !== lockPath)
|
|
12355
|
+
return { retry: true };
|
|
12356
|
+
recoverOwnedMcpTransaction(locatorPending);
|
|
12357
|
+
return { retry: true };
|
|
12358
|
+
}
|
|
12359
|
+
const configPending = readOwnedMcpConfigPending(lockPath);
|
|
12360
|
+
if (configPending) {
|
|
12361
|
+
recoverOwnedMcpTransaction(configPending);
|
|
12362
|
+
return { retry: true };
|
|
12363
|
+
}
|
|
12364
|
+
if (canonicalMcpConfigPath(resourcePath()) !== lockPath)
|
|
12365
|
+
return { retry: true };
|
|
12366
|
+
return { retry: false, value: run(lockPath) };
|
|
12367
|
+
});
|
|
12368
|
+
if (!outcome.retry)
|
|
12369
|
+
return outcome.value;
|
|
12370
|
+
}
|
|
12371
|
+
throw new Error(`${agent} ${serverName} MCP transaction state kept changing; refusing mutation`);
|
|
12372
|
+
});
|
|
12373
|
+
}
|
|
12374
|
+
function mcpInstall(target, serverName = "caveman") {
|
|
12375
|
+
if (serverName !== "caveman" && serverName !== "caveman-browse" && serverName !== "caveman-cloud" && serverName !== "caveman-delegate") {
|
|
12376
|
+
console.error(`unknown MCP server '${serverName}'. valid: caveman, caveman-browse, caveman-cloud, caveman-delegate`);
|
|
12377
|
+
process.exit(2);
|
|
12378
|
+
}
|
|
12379
|
+
let mcp;
|
|
12380
|
+
if (serverName === "caveman") {
|
|
12381
|
+
mcp = resolveMcpCommand();
|
|
12382
|
+
}
|
|
12383
|
+
else if (serverName === "caveman-browse") {
|
|
12384
|
+
const binary = resolveGoBin("caveman-browse", "CAVEMAN_BROWSE_BIN");
|
|
12385
|
+
if (!binary) {
|
|
12386
|
+
console.error("caveman-browse binary not found — run `caveman setup --install` first");
|
|
12387
|
+
process.exit(1);
|
|
12388
|
+
}
|
|
12389
|
+
mcp = { command: binary, args: [] };
|
|
12390
|
+
}
|
|
12391
|
+
else if (serverName === "caveman-delegate") {
|
|
12392
|
+
const resolved = resolveDelegateMcpCommand();
|
|
12393
|
+
if (!resolved) {
|
|
12394
|
+
console.error("caveman-delegate-mcp.mjs not found — set CAVEMAN_DELEGATE_MCP to the script path");
|
|
12395
|
+
process.exit(1);
|
|
12396
|
+
}
|
|
12397
|
+
mcp = resolved;
|
|
12398
|
+
}
|
|
12399
|
+
else {
|
|
12400
|
+
mcp = resolveCloudMcpCommand();
|
|
12401
|
+
}
|
|
12402
|
+
let targets;
|
|
12403
|
+
if (target) {
|
|
12404
|
+
const a = findAgent(target);
|
|
12405
|
+
if (!a) {
|
|
12406
|
+
console.error(`unknown agent '${target}'. known: ${AGENTS.map((x) => x.id).join(", ")}`);
|
|
12407
|
+
process.exit(2);
|
|
12408
|
+
}
|
|
12409
|
+
targets = [a];
|
|
12410
|
+
}
|
|
12411
|
+
else {
|
|
12412
|
+
targets = AGENTS.filter((a) => which(binOf(a)));
|
|
12413
|
+
if (targets.length === 0) {
|
|
12414
|
+
console.error("no known agents detected on PATH; pass an agent id, e.g. `caveman mcp install claude`");
|
|
12415
|
+
process.exit(1);
|
|
12416
|
+
}
|
|
12417
|
+
}
|
|
12418
|
+
let installed = 0;
|
|
12419
|
+
for (const a of targets) {
|
|
12420
|
+
preflightMcpServerMarker(a.id, serverName);
|
|
12421
|
+
const installOne = (lockedConfigPath) => {
|
|
12422
|
+
if (a.id === "kilo" || a.id === "qwen") {
|
|
12423
|
+
return transactOwnedMcpConfig(a.id, serverName, "install", mcp, lockedConfigPath);
|
|
12424
|
+
}
|
|
12425
|
+
if (!installMcpForAgent(a, mcp, serverName))
|
|
12426
|
+
return false;
|
|
12427
|
+
try {
|
|
12428
|
+
if (serverName === "caveman") {
|
|
12429
|
+
writeMcpMarker(a.id, mcp);
|
|
12430
|
+
}
|
|
12431
|
+
else {
|
|
12432
|
+
writeMcpServerMarker(a.id, serverName, mcp, serverName === "caveman-browse" ? "caveman_browse" : serverName === "caveman-delegate" ? "caveman_delegate" : "caveman_context");
|
|
12433
|
+
}
|
|
12434
|
+
}
|
|
12435
|
+
catch (error) {
|
|
12436
|
+
throw new Error(`${a.display_name}: MCP ownership journal failed; native config may already contain the registration: ${error.message}`);
|
|
12437
|
+
}
|
|
12438
|
+
return true;
|
|
12439
|
+
};
|
|
12440
|
+
const installedForAgent = a.id === "kilo" || a.id === "qwen"
|
|
12441
|
+
? withOwnedMcpTransactionLock(a.id, serverName, installOne)
|
|
12442
|
+
: installOne();
|
|
12443
|
+
if (installedForAgent) {
|
|
12444
|
+
installed++;
|
|
12445
|
+
const tool = serverName === "caveman"
|
|
12446
|
+
? "caveman_retrieve"
|
|
12447
|
+
: serverName === "caveman-browse"
|
|
10024
12448
|
? "caveman_browse"
|
|
10025
12449
|
: serverName === "caveman-delegate"
|
|
10026
12450
|
? "caveman_delegate"
|
|
@@ -10048,6 +12472,9 @@ function installMcpForAgent(a, mcp, serverName = "caveman") {
|
|
|
10048
12472
|
command: [mcp.command, ...mcp.args],
|
|
10049
12473
|
enabled: true,
|
|
10050
12474
|
});
|
|
12475
|
+
case "kilo":
|
|
12476
|
+
case "qwen":
|
|
12477
|
+
throw new Error(`${a.display_name} MCP changes require the ownership transaction`);
|
|
10051
12478
|
case "gemini":
|
|
10052
12479
|
return installMcpJson(join(homedir(), ".gemini", "settings.json"), ["mcpServers", serverName], {
|
|
10053
12480
|
command: mcp.command,
|
|
@@ -10246,13 +12673,7 @@ function writeMcpMarker(agentId, mcp) {
|
|
|
10246
12673
|
}
|
|
10247
12674
|
function writeMcpServerMarker(agentId, serverName, mcp, tool) {
|
|
10248
12675
|
const path = mcpServerMarkerPath(agentId, serverName);
|
|
10249
|
-
|
|
10250
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
10251
|
-
writeFileSync(path, JSON.stringify({ tool, command: mcp.command, args: mcp.args }, null, 2) + "\n");
|
|
10252
|
-
}
|
|
10253
|
-
catch {
|
|
10254
|
-
// best-effort: without the marker, wrap simply tries the loadout again later.
|
|
10255
|
-
}
|
|
12676
|
+
durableAtomicWriteFile(path, mcpMarkerBytes(mcp, tool));
|
|
10256
12677
|
}
|
|
10257
12678
|
// compress streams stdin through the caveman-engine binary (resolved via
|
|
10258
12679
|
// CAVEMAN_ENGINE_BIN, default `caveman-engine` on PATH) and writes the compressed
|
|
@@ -10553,7 +12974,7 @@ async function shrinkHook() {
|
|
|
10553
12974
|
process.exit(0);
|
|
10554
12975
|
let raw;
|
|
10555
12976
|
try {
|
|
10556
|
-
raw = await
|
|
12977
|
+
raw = await readHookStdin();
|
|
10557
12978
|
}
|
|
10558
12979
|
catch {
|
|
10559
12980
|
process.exit(0);
|
|
@@ -11152,7 +13573,7 @@ async function nativeHook(argv) {
|
|
|
11152
13573
|
process.exit(0);
|
|
11153
13574
|
let raw;
|
|
11154
13575
|
try {
|
|
11155
|
-
raw = await
|
|
13576
|
+
raw = await readHookStdin();
|
|
11156
13577
|
}
|
|
11157
13578
|
catch {
|
|
11158
13579
|
process.exit(0);
|
|
@@ -11534,7 +13955,7 @@ function writeRecallHookMarker(agentId) {
|
|
|
11534
13955
|
async function memRecallHook() {
|
|
11535
13956
|
let raw;
|
|
11536
13957
|
try {
|
|
11537
|
-
raw = await
|
|
13958
|
+
raw = await readHookStdin();
|
|
11538
13959
|
}
|
|
11539
13960
|
catch {
|
|
11540
13961
|
process.exit(0);
|
|
@@ -13898,6 +16319,57 @@ function readStdin() {
|
|
|
13898
16319
|
process.stdin.on("error", reject);
|
|
13899
16320
|
});
|
|
13900
16321
|
}
|
|
16322
|
+
// readHookStdin is for host hook callbacks (shrink-hook, mem recall, native-hook):
|
|
16323
|
+
// the host writes ONE JSON object and closes, but under the Windows pipe
|
|
16324
|
+
// implementation that close can lag arbitrarily (#729/#833, #949), and a hook that
|
|
16325
|
+
// waits for EOF burns the host's whole budget with its work already done. Resolve
|
|
16326
|
+
// on the first complete JSON object; EOF still resolves for hosts that close
|
|
16327
|
+
// promptly. Same 2 MiB cap as native-hook-fast.
|
|
16328
|
+
function readHookStdin() {
|
|
16329
|
+
return new Promise((resolve, reject) => {
|
|
16330
|
+
if (process.stdin.isTTY) {
|
|
16331
|
+
reject(new Error("no hook payload on stdin"));
|
|
16332
|
+
return;
|
|
16333
|
+
}
|
|
16334
|
+
const chunks = [];
|
|
16335
|
+
let bytes = 0;
|
|
16336
|
+
let done = false;
|
|
16337
|
+
const finish = () => {
|
|
16338
|
+
if (done)
|
|
16339
|
+
return;
|
|
16340
|
+
done = true;
|
|
16341
|
+
// pause() stops the flow but the 'data' listener keeps the handle referenced;
|
|
16342
|
+
// unref() lets the process exit as soon as stdout flushes.
|
|
16343
|
+
process.stdin.pause();
|
|
16344
|
+
try {
|
|
16345
|
+
process.stdin.unref();
|
|
16346
|
+
}
|
|
16347
|
+
catch { /* not every stream type supports it */ }
|
|
16348
|
+
resolve(Buffer.concat(chunks));
|
|
16349
|
+
};
|
|
16350
|
+
process.stdin.on("data", (chunk) => {
|
|
16351
|
+
if (done)
|
|
16352
|
+
return;
|
|
16353
|
+
bytes += chunk.length;
|
|
16354
|
+
if (bytes > 2 * 1024 * 1024) {
|
|
16355
|
+
done = true;
|
|
16356
|
+
reject(new Error("hook payload too large"));
|
|
16357
|
+
return;
|
|
16358
|
+
}
|
|
16359
|
+
chunks.push(chunk);
|
|
16360
|
+
// A partial payload throws here and we simply wait for more bytes.
|
|
16361
|
+
try {
|
|
16362
|
+
JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
16363
|
+
}
|
|
16364
|
+
catch {
|
|
16365
|
+
return;
|
|
16366
|
+
}
|
|
16367
|
+
finish();
|
|
16368
|
+
});
|
|
16369
|
+
process.stdin.on("end", finish);
|
|
16370
|
+
process.stdin.on("error", reject);
|
|
16371
|
+
});
|
|
16372
|
+
}
|
|
13901
16373
|
async function init(argv) {
|
|
13902
16374
|
// Reuse login's own resolution (C8 review finding 6): init used to compute
|
|
13903
16375
|
// its own baseURL with a bare localhost:8080 literal and no CAVE_API_URL
|
|
@@ -14086,6 +16558,17 @@ function readProxyRuntimeState(port, versionInfo) {
|
|
|
14086
16558
|
return { owner: "unknown" };
|
|
14087
16559
|
}
|
|
14088
16560
|
}
|
|
16561
|
+
// A proxy caveman just started binds its port before its run state is
|
|
16562
|
+
// readable; polling briefly keeps that window from reading as a foreign owner.
|
|
16563
|
+
async function awaitProxyRuntimeState(port, versionInfo, timeoutMs = 3000) {
|
|
16564
|
+
const deadline = Date.now() + timeoutMs;
|
|
16565
|
+
for (;;) {
|
|
16566
|
+
const state = readProxyRuntimeState(port, versionInfo);
|
|
16567
|
+
if (state.owner !== "unknown" || Date.now() >= deadline)
|
|
16568
|
+
return state;
|
|
16569
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
16570
|
+
}
|
|
16571
|
+
}
|
|
14089
16572
|
function capabilitySourcesForStatus() {
|
|
14090
16573
|
const resolution = resolveCapabilities();
|
|
14091
16574
|
const sourceOrder = ["proxy-yaml", "legacy-wrap", "global", "project", "env"];
|