@caveman-ai/cli 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/dist/agent-skills.generated.js +27 -3
- package/dist/agents.generated.js +37 -27
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +120 -35
- package/dist/index.js +807 -129
- package/dist/portable-command.js +36 -15
- package/dist/provider-routing.js +11 -0
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
3
|
-
import { accessSync, appendFileSync, closeSync, cpSync, existsSync, fchmodSync, fsyncSync, chmodSync, constants, copyFileSync, linkSync, mkdirSync, mkdtempSync, openSync, lstatSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { accessSync, appendFileSync, closeSync, cpSync, existsSync, fchmodSync, fsyncSync, chmodSync, constants, copyFileSync, linkSync, mkdirSync, mkdtempSync, openSync, lstatSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, utimesSync, writeFileSync, writeSync, } from "node:fs";
|
|
4
4
|
import { chmod, mkdir, open, readFile, rename, writeFile } from "node:fs/promises";
|
|
5
5
|
import { homedir, hostname, tmpdir, userInfo } from "node:os";
|
|
6
6
|
import { basename, delimiter, dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "node:path";
|
|
@@ -975,6 +975,90 @@ function telemetryTokenWatermarkFromDisk() {
|
|
|
975
975
|
return null;
|
|
976
976
|
}
|
|
977
977
|
}
|
|
978
|
+
// telemetryClaimLockPath is the sidecar used to serialize the read-compare-write
|
|
979
|
+
// below across OS processes; it sits beside config.json so its permission and
|
|
980
|
+
// cross-filesystem behavior always matches the file it protects.
|
|
981
|
+
function telemetryClaimLockPath() {
|
|
982
|
+
return `${configPath()}.telemetry.lock`;
|
|
983
|
+
}
|
|
984
|
+
// A lock older than this is presumed abandoned by a crashed holder; kept far
|
|
985
|
+
// above a real claim's own write time and above any waiter's acquire budget,
|
|
986
|
+
// so a slow but live holder is never mistaken for a dead one.
|
|
987
|
+
const TELEMETRY_CLAIM_LOCK_STALE_MS = 5000;
|
|
988
|
+
// acquireClaimLock spins on an atomic O_CREAT|O_EXCL create until it wins the
|
|
989
|
+
// lock or the budget runs out; a lock whose mtime is older than staleMs is
|
|
990
|
+
// treated as abandoned by a crashed holder and reclaimed, so a killed process
|
|
991
|
+
// cannot wedge the guarded operation off permanently.
|
|
992
|
+
//
|
|
993
|
+
// Shared by every watermark claim rather than copied per caller: the telemetry
|
|
994
|
+
// claim (#1116) and the sync claim (#1132) are the same read-mutate-write
|
|
995
|
+
// hazard over different state files, and a second copy of this spin is how the
|
|
996
|
+
// two would drift apart. Callers supply their own stale window because their
|
|
997
|
+
// hold times differ by orders of magnitude — see refreshClaimLock.
|
|
998
|
+
function acquireClaimLock(lockPath, budgetMs, staleMs) {
|
|
999
|
+
try {
|
|
1000
|
+
mkdirSync(dirname(lockPath), { recursive: true });
|
|
1001
|
+
}
|
|
1002
|
+
catch {
|
|
1003
|
+
return null;
|
|
1004
|
+
}
|
|
1005
|
+
// The token names THIS holder. releaseClaimLock unlinks only a lock that
|
|
1006
|
+
// still carries it, so a holder that was reclaimed as stale mid-section
|
|
1007
|
+
// cannot delete its successor's lock on the way out.
|
|
1008
|
+
const token = `${process.pid}:${randomUUID()}`;
|
|
1009
|
+
const deadline = Date.now() + budgetMs;
|
|
1010
|
+
for (;;) {
|
|
1011
|
+
try {
|
|
1012
|
+
const fd = openSync(lockPath, "wx");
|
|
1013
|
+
try {
|
|
1014
|
+
writeSync(fd, token);
|
|
1015
|
+
}
|
|
1016
|
+
finally {
|
|
1017
|
+
closeSync(fd);
|
|
1018
|
+
}
|
|
1019
|
+
return token;
|
|
1020
|
+
}
|
|
1021
|
+
catch (err) {
|
|
1022
|
+
if (err.code !== "EEXIST")
|
|
1023
|
+
return null;
|
|
1024
|
+
try {
|
|
1025
|
+
if (Date.now() - statSync(lockPath).mtimeMs > staleMs) {
|
|
1026
|
+
// Reclaim by rename, not unlink. Two waiters can both see the same
|
|
1027
|
+
// stale lock; with unlink the slower one would delete the lock the
|
|
1028
|
+
// faster one had already created in its place, and both would hold
|
|
1029
|
+
// it. Only one rename of the stale file can succeed; the loser's
|
|
1030
|
+
// rename fails and it loops back to the create attempt.
|
|
1031
|
+
const grave = `${lockPath}.${process.pid}.${Date.now()}.stale`;
|
|
1032
|
+
renameSync(lockPath, grave);
|
|
1033
|
+
unlinkSync(grave);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
catch {
|
|
1037
|
+
/* raced the holder releasing it, or another waiter reclaiming; loop back */
|
|
1038
|
+
}
|
|
1039
|
+
if (Date.now() >= deadline)
|
|
1040
|
+
return null;
|
|
1041
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
// releaseClaimLock drops a lock taken above, but only while it is still ours:
|
|
1046
|
+
// a lock a waiter reclaimed as stale carries the waiter's token now, and
|
|
1047
|
+
// unlinking it would hand the guarded section to a third process. The read
|
|
1048
|
+
// and the unlink are not one step; a reclaim between them needs the lock to
|
|
1049
|
+
// cross the stale threshold in that gap, which the sync heartbeat and the
|
|
1050
|
+
// millisecond telemetry hold keep far away. Never throws: a lock already gone
|
|
1051
|
+
// is the same end state as one we removed.
|
|
1052
|
+
function releaseClaimLock(lockPath, token) {
|
|
1053
|
+
try {
|
|
1054
|
+
if (readFileSync(lockPath, "utf8") !== token)
|
|
1055
|
+
return;
|
|
1056
|
+
unlinkSync(lockPath);
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
/* already gone */
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
978
1062
|
// telemetryTokenDelta returns what to report for THIS event and advances the
|
|
979
1063
|
// watermark to the totals it read. The send is fire-and-forget, so a dropped POST
|
|
980
1064
|
// loses that delta rather than replaying it — undercounting beats double-counting
|
|
@@ -997,11 +1081,15 @@ function telemetryTokenDelta() {
|
|
|
997
1081
|
const rebaselining = prior === null || rewound;
|
|
998
1082
|
if (processed === 0 && saved === 0 && !rebaselining)
|
|
999
1083
|
return null;
|
|
1000
|
-
// Claim the delta
|
|
1001
|
-
//
|
|
1002
|
-
//
|
|
1003
|
-
|
|
1084
|
+
// Claim the delta under a lock, not a bare compare: two processes exiting
|
|
1085
|
+
// together can both read the pre-write watermark before either commits (see
|
|
1086
|
+
// the regression test below).
|
|
1087
|
+
const lockPath = telemetryClaimLockPath();
|
|
1088
|
+
const lockToken = acquireClaimLock(lockPath, 500, TELEMETRY_CLAIM_LOCK_STALE_MS);
|
|
1089
|
+
if (!lockToken)
|
|
1090
|
+
return null;
|
|
1004
1091
|
let claimed = true;
|
|
1092
|
+
let readOnly = false;
|
|
1005
1093
|
try {
|
|
1006
1094
|
mutateRawConfig((out) => {
|
|
1007
1095
|
const current = parseTelemetryTokenWatermark(out.telemetryTokens);
|
|
@@ -1017,10 +1105,12 @@ function telemetryTokenDelta() {
|
|
|
1017
1105
|
});
|
|
1018
1106
|
}
|
|
1019
1107
|
catch {
|
|
1020
|
-
// Read-only home: report nothing rather than resend the same delta forever.
|
|
1021
|
-
|
|
1108
|
+
readOnly = true; // Read-only home: report nothing rather than resend the same delta forever.
|
|
1109
|
+
}
|
|
1110
|
+
finally {
|
|
1111
|
+
releaseClaimLock(lockPath, lockToken);
|
|
1022
1112
|
}
|
|
1023
|
-
if (!claimed)
|
|
1113
|
+
if (readOnly || !claimed)
|
|
1024
1114
|
return null;
|
|
1025
1115
|
if (processed === 0 && saved === 0)
|
|
1026
1116
|
return null;
|
|
@@ -3058,7 +3148,12 @@ function removeAgentNativeBundle(agent) {
|
|
|
3058
3148
|
recoverPendingAgentNativeBundle(agent);
|
|
3059
3149
|
const journal = readAgentNativeBundleJournal(agent);
|
|
3060
3150
|
if (!journal) {
|
|
3061
|
-
|
|
3151
|
+
// Accurate, but on its own a dead end (#1134): this verb undoes the bundle that
|
|
3152
|
+
// `setup --agent-native` installs, and nothing else. A user who reached the same
|
|
3153
|
+
// config through `caveman <agent>` or `caveman enable <agent>` has no bundle and
|
|
3154
|
+
// reads this as "caveman cannot be uninstalled". Name the verb that undoes theirs.
|
|
3155
|
+
process.stderr.write(`${mark("warn")} ${agent}: no agent-native bundle journal found — nothing was installed by \`caveman setup --agent-native ${agent}\`\n`);
|
|
3156
|
+
process.stderr.write(dim(` if you set it up with \`caveman ${agent}\` or \`caveman enable ${agent}\`, remove that with \`caveman disable ${agent}\`\n`));
|
|
3062
3157
|
return;
|
|
3063
3158
|
}
|
|
3064
3159
|
for (const skill of journal.skills) {
|
|
@@ -3738,6 +3833,13 @@ export const OFF_STATES = {
|
|
|
3738
3833
|
zdr: {
|
|
3739
3834
|
line: "ZDR org — wrap telemetry excluded by your data policy; local numbers only",
|
|
3740
3835
|
},
|
|
3836
|
+
// The proxy's cache tripwire: the client re-sent bytes the provider had
|
|
3837
|
+
// cached and caveman forwarded them differently. Never expected; a bug.
|
|
3838
|
+
cavemanCacheBust: (count) => ({
|
|
3839
|
+
id: "cache-bust",
|
|
3840
|
+
line: `caveman changed bytes the provider had already cached on ${count} request${count === 1 ? "" : "s"} today — those turns paid to re-cache their prompt; this is a caveman bug`,
|
|
3841
|
+
fix: "report it with ~/.caveman/proxy.log at github.com/JuliusBrussee/caveman/issues",
|
|
3842
|
+
}),
|
|
3741
3843
|
};
|
|
3742
3844
|
const OFF_STATE_PRECEDENCE = [
|
|
3743
3845
|
"binary-missing",
|
|
@@ -3750,6 +3852,7 @@ const OFF_STATE_PRECEDENCE = [
|
|
|
3750
3852
|
"mem-missing",
|
|
3751
3853
|
"zdr",
|
|
3752
3854
|
"stale-binary",
|
|
3855
|
+
"cache-bust",
|
|
3753
3856
|
];
|
|
3754
3857
|
function fixedOffState(id, item) {
|
|
3755
3858
|
return { id, line: item.line, ...(item.fix ? { fix: item.fix } : {}) };
|
|
@@ -5007,6 +5110,23 @@ async function agentShortcut(rest) {
|
|
|
5007
5110
|
process.exitCode = result.status ?? 1;
|
|
5008
5111
|
return;
|
|
5009
5112
|
}
|
|
5113
|
+
// Some host surfaces cannot run routed at all — Claude Code Remote Control
|
|
5114
|
+
// refuses any non-first-party ANTHROPIC_BASE_URL and its escape hatch does not
|
|
5115
|
+
// cover the check (#947, #1101). The native door would install machine-wide
|
|
5116
|
+
// routing and then launch the host straight into that refusal, leaving the
|
|
5117
|
+
// user both unrouted and unable to start the surface they asked for. Resolve
|
|
5118
|
+
// the override before any persistent write and hand these to wrap, whose
|
|
5119
|
+
// route-override path launches the host directly and writes nothing.
|
|
5120
|
+
const shortcutRouteOverride = agentRouteOverride(agent, rest.slice(1));
|
|
5121
|
+
if (shortcutRouteOverride) {
|
|
5122
|
+
// A native install already owns the host's base URL from its own config
|
|
5123
|
+
// file, which launching directly cannot undo — say so rather than let the
|
|
5124
|
+
// surface fail with the host's own opaque refusal.
|
|
5125
|
+
if (readNativeJournal(native)) {
|
|
5126
|
+
process.stderr.write(`${mark("warn")} ${routeOverrideLabel(agent)} ${shortcutRouteOverride.surface} ${shortcutRouteOverride.reason}, and the native integration still routes ${binOf(agent)} from its own config — run \`caveman disable ${native}\` first, then \`caveman enable ${native}\` afterwards\n`);
|
|
5127
|
+
}
|
|
5128
|
+
return wrap(rest);
|
|
5129
|
+
}
|
|
5010
5130
|
// A Cave Build lock is enforced at the wrap door (claudeCaveBuildEnv); the
|
|
5011
5131
|
// native door applies none of its transforms, so a locked project must keep
|
|
5012
5132
|
// routing through wrap or the lock would be silently unenforced.
|
|
@@ -5664,10 +5784,10 @@ function spawnLocalProxyProcess(mode, mcpRecovery, toon, pixelModels, pixelDensi
|
|
|
5664
5784
|
CAVEMAN_MODE: mode,
|
|
5665
5785
|
CAVEMAN_LISTEN: `${host}:${port}`,
|
|
5666
5786
|
// The recovery half of the proxy's subscription gate, and the switch that lets
|
|
5667
|
-
// it compress streams at all. Stamped EXPLICITLY in both directions: wrap
|
|
5668
|
-
//
|
|
5669
|
-
//
|
|
5670
|
-
// CAVEMAN_RECOVERY=mcp must not survive that answer — the proxy would elide
|
|
5787
|
+
// it compress streams at all. Stamped EXPLICITLY in both directions: wrap,
|
|
5788
|
+
// `enable`, the agent shortcut and the native hook derive it from the agent's
|
|
5789
|
+
// OWN MCP install (codex-subscription included; observe-only runs force it
|
|
5790
|
+
// off), so an exported CAVEMAN_RECOVERY=mcp must not survive that answer — the proxy would elide
|
|
5671
5791
|
// spans behind markers this agent has no caveman_retrieve tool to expand, while
|
|
5672
5792
|
// the CLI printed that compression was off. (honesty rule: no-placeholder)
|
|
5673
5793
|
CAVEMAN_RECOVERY: mcpRecovery ? "mcp" : "",
|
|
@@ -6580,12 +6700,109 @@ function assertNativeHooksShape(path, root, agentId) {
|
|
|
6580
6700
|
}
|
|
6581
6701
|
}
|
|
6582
6702
|
}
|
|
6703
|
+
// #1137, in one place: every persistent artifact caveman writes bakes in the
|
|
6704
|
+
// invocation `enable` resolved, and nothing checked that the invocation still
|
|
6705
|
+
// resolves. nvm installs each Node release in its own directory and
|
|
6706
|
+
// `nvm uninstall <old>` deletes it, so a routine upgrade leaves every baked
|
|
6707
|
+
// path dangling — while the artifact's own bytes are untouched, which is what
|
|
6708
|
+
// every ownership check looked at. The hosts differ only in where the
|
|
6709
|
+
// invocation is written; whether its targets exist is one question, asked here.
|
|
6710
|
+
//
|
|
6711
|
+
// `which` answers an absolute path by testing it directly, so this covers both
|
|
6712
|
+
// a bare name resolved through PATH and a path into a removed directory.
|
|
6713
|
+
function invocationTargetsExist(tokens) {
|
|
6714
|
+
const executable = tokens[0];
|
|
6715
|
+
if (executable === undefined || !which(executable))
|
|
6716
|
+
return false;
|
|
6717
|
+
// A `node <script>` invocation and a `--adapter <file>` argument name files
|
|
6718
|
+
// the executable itself cannot vouch for: node exists on every host after an
|
|
6719
|
+
// upgrade, the script it was pointed at does not.
|
|
6720
|
+
const files = [hookCommandBasename(executable) === "node" ? tokens[1] : undefined];
|
|
6721
|
+
const adapter = tokens.indexOf("--adapter");
|
|
6722
|
+
if (adapter !== -1)
|
|
6723
|
+
files.push(tokens[adapter + 1]);
|
|
6724
|
+
return !files.some((file) => file !== undefined && !existsSync(file));
|
|
6725
|
+
}
|
|
6726
|
+
// The generated opencode plugin and Pi extension bake their invocation as a
|
|
6727
|
+
// source literal rather than a host hook command, so ownership was judged by
|
|
6728
|
+
// the marker comment alone and #1137 stayed invisible on both. Parse what the
|
|
6729
|
+
// generators emit — not the journal, which for an install made before this
|
|
6730
|
+
// check records no invocation at all, and these are the installs already
|
|
6731
|
+
// broken on disk.
|
|
6732
|
+
//
|
|
6733
|
+
// Deliberately fail-open on an unrecognized shape: there is nothing to verify,
|
|
6734
|
+
// and answering `false` would report every install degraded. The regression
|
|
6735
|
+
// tests assert the emitted shape still matches, so a generator refactor that
|
|
6736
|
+
// silences this fails the suite instead of silently verifying nothing.
|
|
6737
|
+
function generatedInvocation(text) {
|
|
6738
|
+
// opencode: `const command = "…";` with `const prefix = […];`
|
|
6739
|
+
const command = text.match(/^const command = ("(?:[^"\\]|\\.)*");$/m);
|
|
6740
|
+
if (command) {
|
|
6741
|
+
const prefix = text.match(/^const prefix = (\[(?:[^[\]\\]|\\.)*\]);$/m);
|
|
6742
|
+
// A prefix line we cannot read means we cannot see the whole invocation,
|
|
6743
|
+
// and verifying the executable alone would be worse than verifying
|
|
6744
|
+
// nothing: `node` survives every upgrade, so the dangling member would be
|
|
6745
|
+
// exactly the script in the prefix we failed to parse.
|
|
6746
|
+
if (!prefix && /^const prefix = /m.test(text))
|
|
6747
|
+
return undefined;
|
|
6748
|
+
try {
|
|
6749
|
+
const parsedPrefix = prefix ? JSON.parse(prefix[1]) : [];
|
|
6750
|
+
if (!Array.isArray(parsedPrefix) || parsedPrefix.some((item) => typeof item !== "string"))
|
|
6751
|
+
return undefined;
|
|
6752
|
+
return [JSON.parse(command[1]), ...parsedPrefix];
|
|
6753
|
+
}
|
|
6754
|
+
catch {
|
|
6755
|
+
return undefined;
|
|
6756
|
+
}
|
|
6757
|
+
}
|
|
6758
|
+
// Pi: `process.env.CAVEMAN_PI_HOOK_CMD ??= "<json array, re-encoded>";`
|
|
6759
|
+
const pi = text.match(/^process\.env\.CAVEMAN_PI_HOOK_CMD \?\?= ("(?:[^"\\]|\\.)*");$/m);
|
|
6760
|
+
if (pi) {
|
|
6761
|
+
try {
|
|
6762
|
+
const parsed = JSON.parse(JSON.parse(pi[1]));
|
|
6763
|
+
if (!Array.isArray(parsed) || parsed.length === 0 || parsed.some((item) => typeof item !== "string"))
|
|
6764
|
+
return undefined;
|
|
6765
|
+
return parsed;
|
|
6766
|
+
}
|
|
6767
|
+
catch {
|
|
6768
|
+
return undefined;
|
|
6769
|
+
}
|
|
6770
|
+
}
|
|
6771
|
+
return undefined;
|
|
6772
|
+
}
|
|
6773
|
+
function generatedArtifactTargetsExist(text) {
|
|
6774
|
+
const tokens = generatedInvocation(text);
|
|
6775
|
+
return tokens === undefined || invocationTargetsExist(tokens);
|
|
6776
|
+
}
|
|
6777
|
+
// A managed hook is only healthy while the files its command runs still exist.
|
|
6778
|
+
// Identity is judged by basename, so a hook rendered into a directory that has
|
|
6779
|
+
// since been deleted (an nvm Node upgrade, #1137) kept matching the expected
|
|
6780
|
+
// document while the host ran a missing binary or adapter.
|
|
6781
|
+
function managedHookTargetsExist(root) {
|
|
6782
|
+
const hooks = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks)
|
|
6783
|
+
? root.hooks
|
|
6784
|
+
: {};
|
|
6785
|
+
for (const raw of Object.values(hooks)) {
|
|
6786
|
+
if (!Array.isArray(raw))
|
|
6787
|
+
continue;
|
|
6788
|
+
for (const entry of raw) {
|
|
6789
|
+
const command = entry && typeof entry === "object" ? hookEntryCommand(entry) : undefined;
|
|
6790
|
+
if (command === undefined || managedHookIdentity(command) === undefined)
|
|
6791
|
+
continue;
|
|
6792
|
+
if (!invocationTargetsExist(hookCommandTokens(command)))
|
|
6793
|
+
return false;
|
|
6794
|
+
}
|
|
6795
|
+
}
|
|
6796
|
+
return true;
|
|
6797
|
+
}
|
|
6583
6798
|
function nativeHookEntriesHealthy(root, agentId) {
|
|
6584
6799
|
const hooks = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks)
|
|
6585
6800
|
? root.hooks
|
|
6586
6801
|
: undefined;
|
|
6587
6802
|
if (!hooks)
|
|
6588
6803
|
return false;
|
|
6804
|
+
if (!managedHookTargetsExist(root))
|
|
6805
|
+
return false;
|
|
6589
6806
|
const expected = nativeHooksDocument(agentId, nativeShrinkEnabled()).hooks;
|
|
6590
6807
|
const required = Object.entries(expected).every(([event, expectedRaw]) => {
|
|
6591
6808
|
const actual = Array.isArray(hooks[event]) ? hooks[event] : [];
|
|
@@ -7490,6 +7707,43 @@ export default {
|
|
|
7490
7707
|
};
|
|
7491
7708
|
`;
|
|
7492
7709
|
}
|
|
7710
|
+
// opencode-go serves OpenAI and Anthropic wire shapes from opencode.ai, so it
|
|
7711
|
+
// rides the proxy's built-in /compat/opencode-go mount (same one Pi uses), which
|
|
7712
|
+
// keeps the caller's credential and forwards OpenCode's session headers (#1090).
|
|
7713
|
+
function opencodeNativeRoutes(gw) {
|
|
7714
|
+
const base = appendUrlPath(gw, "/w/opencode");
|
|
7715
|
+
return {
|
|
7716
|
+
openai: appendUrlPath(base, "/openai/v1"),
|
|
7717
|
+
anthropic: appendUrlPath(base, "/anthropic/v1"),
|
|
7718
|
+
"opencode-go": appendUrlPath(base, "/compat/opencode-go/v1"),
|
|
7719
|
+
};
|
|
7720
|
+
}
|
|
7721
|
+
// Only the journaled providers reach the proxy. Anything else (GitHub Copilot,
|
|
7722
|
+
// Zen) goes direct while the install reads healthy (#1190), so name it. Global
|
|
7723
|
+
// config only, the same file enable edits; a project opencode.json can still
|
|
7724
|
+
// pick another model.
|
|
7725
|
+
function opencodeUnroutedActiveProvider(routed) {
|
|
7726
|
+
for (const name of ["opencode.jsonc", "opencode.json"]) {
|
|
7727
|
+
try {
|
|
7728
|
+
const model = parseJsonc(readFileSync(join(homedir(), ".config", "opencode", name), "utf8"))?.model;
|
|
7729
|
+
if (typeof model === "string" && model.includes("/")) {
|
|
7730
|
+
const provider = model.slice(0, model.indexOf("/"));
|
|
7731
|
+
return routed.includes(provider) ? null : provider;
|
|
7732
|
+
}
|
|
7733
|
+
}
|
|
7734
|
+
catch { /* missing or unreadable: try the next source */ }
|
|
7735
|
+
}
|
|
7736
|
+
// No model pinned: OpenCode picks among signed-in providers, so only a
|
|
7737
|
+
// sign-in set with no routed provider at all is a sure miss.
|
|
7738
|
+
try {
|
|
7739
|
+
const dataRoot = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
|
|
7740
|
+
const signedIn = Object.keys(JSON.parse(readFileSync(join(dataRoot, "opencode", "auth.json"), "utf8")) ?? {});
|
|
7741
|
+
return signedIn.length > 0 && !signedIn.some((id) => routed.includes(id)) ? signedIn[0] : null;
|
|
7742
|
+
}
|
|
7743
|
+
catch {
|
|
7744
|
+
return null;
|
|
7745
|
+
}
|
|
7746
|
+
}
|
|
7493
7747
|
function opencodeNativeMutations(gw, mcpBinary) {
|
|
7494
7748
|
const configPath = join(homedir(), ".config", "opencode", "opencode.json");
|
|
7495
7749
|
const before = fileBytes(configPath);
|
|
@@ -7502,8 +7756,7 @@ function opencodeNativeMutations(gw, mcpBinary) {
|
|
|
7502
7756
|
}
|
|
7503
7757
|
const providers = root.provider && typeof root.provider === "object" && !Array.isArray(root.provider) ? root.provider : {};
|
|
7504
7758
|
const previousRoutes = {};
|
|
7505
|
-
const
|
|
7506
|
-
const routes = { openai: appendUrlPath(base, "/openai/v1"), anthropic: appendUrlPath(base, "/anthropic/v1") };
|
|
7759
|
+
const routes = opencodeNativeRoutes(gw);
|
|
7507
7760
|
for (const [providerID, route] of Object.entries(routes)) {
|
|
7508
7761
|
const provider = providers[providerID] && typeof providers[providerID] === "object" && !Array.isArray(providers[providerID]) ? providers[providerID] : {};
|
|
7509
7762
|
const options = provider.options && typeof provider.options === "object" && !Array.isArray(provider.options) ? provider.options : {};
|
|
@@ -8182,6 +8435,8 @@ function applyNativeMutations(agent, profile, mutations) {
|
|
|
8182
8435
|
atomicWriteFile(mutation.file, mutation.after);
|
|
8183
8436
|
written.push(mutation);
|
|
8184
8437
|
}
|
|
8438
|
+
if (agent === "claude")
|
|
8439
|
+
rememberClaudeProfile();
|
|
8185
8440
|
atomicWriteFile(nativeJournalPath(agent), Buffer.from(JSON.stringify(journal, null, 2) + "\n"));
|
|
8186
8441
|
unlinkSync(nativePendingJournalPath(agent));
|
|
8187
8442
|
return journal;
|
|
@@ -8342,6 +8597,69 @@ function nativeMutationsFor(agent, gw, mcpBinary) {
|
|
|
8342
8597
|
? piNativeMutations()
|
|
8343
8598
|
: aiderNativeMutations(gw);
|
|
8344
8599
|
}
|
|
8600
|
+
// Voice skills (`output` suite) ride along with a Claude/Codex native install so
|
|
8601
|
+
// `/caveman` exists after `caveman <agent>`. They are NOT native-journal
|
|
8602
|
+
// operations: those feed `nativeIntegrationStatus`, where an edited or deleted
|
|
8603
|
+
// file reads `degraded` and blocks enable, and `disable` restores them away. A
|
|
8604
|
+
// skill is the user's once written: `disable` turns off routing and hooks and
|
|
8605
|
+
// leaves it. The sidecar only marks that the install already ran.
|
|
8606
|
+
function nativeVoiceSkillsRecordPath(agent) {
|
|
8607
|
+
return join(cavemanHome(), "integrations", `${agent}.voice-skills.json`);
|
|
8608
|
+
}
|
|
8609
|
+
// Fail-open and once per install: an existing record means this already ran, so
|
|
8610
|
+
// a skill the user deleted afterwards is not written back.
|
|
8611
|
+
function installNativeVoiceSkills(agent) {
|
|
8612
|
+
if (agent !== "claude" && agent !== "codex")
|
|
8613
|
+
return;
|
|
8614
|
+
try {
|
|
8615
|
+
const record = nativeVoiceSkillsRecordPath(agent);
|
|
8616
|
+
if (existsSync(record))
|
|
8617
|
+
return;
|
|
8618
|
+
const root = join(agent === "claude" ? claudeConfigDir() : codexHomeDir(), "skills");
|
|
8619
|
+
const files = [];
|
|
8620
|
+
let failure;
|
|
8621
|
+
try {
|
|
8622
|
+
for (const name of AGENT_SKILL_SUITES.output ?? []) {
|
|
8623
|
+
const file = join(root, name, "SKILL.md");
|
|
8624
|
+
// The Skills CLI puts global Codex skills in ~/.agents/skills; a copy
|
|
8625
|
+
// there already answers `/caveman`, so a second one is only a duplicate.
|
|
8626
|
+
if (agent === "codex" && existsSync(join(homedir(), ".agents", "skills", name, "SKILL.md")))
|
|
8627
|
+
continue;
|
|
8628
|
+
const body = Buffer.from(SKILLS[name]);
|
|
8629
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
8630
|
+
// `wx` never clobbers: an existing SKILL.md (any content, any link) stays
|
|
8631
|
+
// the user's and is not recorded as ours.
|
|
8632
|
+
try {
|
|
8633
|
+
writeFileSync(file, body, { flag: "wx" });
|
|
8634
|
+
}
|
|
8635
|
+
catch (error) {
|
|
8636
|
+
if (error.code === "EEXIST")
|
|
8637
|
+
continue;
|
|
8638
|
+
// A half-written file would read as the user's on every later run.
|
|
8639
|
+
try {
|
|
8640
|
+
unlinkSync(file);
|
|
8641
|
+
}
|
|
8642
|
+
catch { /* nothing landed */ }
|
|
8643
|
+
throw error;
|
|
8644
|
+
}
|
|
8645
|
+
files.push(file);
|
|
8646
|
+
}
|
|
8647
|
+
}
|
|
8648
|
+
catch (error) {
|
|
8649
|
+
failure = error;
|
|
8650
|
+
}
|
|
8651
|
+
// A total failure leaves no record and is retried by the next enable.
|
|
8652
|
+
if (files.length > 0 || !failure)
|
|
8653
|
+
atomicWriteFile(record, Buffer.from(JSON.stringify({ files }, null, 2) + "\n"));
|
|
8654
|
+
if (failure)
|
|
8655
|
+
throw failure;
|
|
8656
|
+
if (files.length > 0)
|
|
8657
|
+
process.stderr.write(` voice skills: ${files.join(", ")}\n`);
|
|
8658
|
+
}
|
|
8659
|
+
catch (error) {
|
|
8660
|
+
process.stderr.write(dim(`→ voice skills not installed: ${error.message}\n`));
|
|
8661
|
+
}
|
|
8662
|
+
}
|
|
8345
8663
|
function enableNative(argv) {
|
|
8346
8664
|
const detected = argv.includes("--detected");
|
|
8347
8665
|
const target = argv.find((arg) => !arg.startsWith("--"));
|
|
@@ -8366,8 +8684,10 @@ function enableNative(argv) {
|
|
|
8366
8684
|
nativeProxyBinaryRequired(gw);
|
|
8367
8685
|
const existing = nativeIntegrationStatus(agent);
|
|
8368
8686
|
if (existing.installed) {
|
|
8369
|
-
if (existing.state === "installed")
|
|
8687
|
+
if (existing.state === "installed") {
|
|
8688
|
+
installNativeVoiceSkills(agent);
|
|
8370
8689
|
return "already";
|
|
8690
|
+
}
|
|
8371
8691
|
// `--fix` on purpose: bare `caveman doctor <agent>` prints JSON that says
|
|
8372
8692
|
// `degraded` and nothing that says how to leave that state, so pointing
|
|
8373
8693
|
// at it alone dead-ends the user who followed this line here (#1049).
|
|
@@ -8392,6 +8712,7 @@ function enableNative(argv) {
|
|
|
8392
8712
|
? ` lifecycle/Core: ${nativeHookCommand(agent)}; command-output rewrite unavailable in Codex\n`
|
|
8393
8713
|
: ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
|
|
8394
8714
|
applyNativeMutations(agent, profile, mutations);
|
|
8715
|
+
installNativeVoiceSkills(agent);
|
|
8395
8716
|
return "enabled";
|
|
8396
8717
|
});
|
|
8397
8718
|
// Outside the lock, and on BOTH outcomes. The native SessionStart hook
|
|
@@ -8603,7 +8924,7 @@ function restoreNativeOperation(operation) {
|
|
|
8603
8924
|
const providers = root.provider && typeof root.provider === "object" && !Array.isArray(root.provider) ? root.provider : {};
|
|
8604
8925
|
const routes = operation.owned?.routes && typeof operation.owned.routes === "object" && !Array.isArray(operation.owned.routes) ? operation.owned.routes : {};
|
|
8605
8926
|
const previousRoutes = operation.owned?.previous_routes && typeof operation.owned.previous_routes === "object" && !Array.isArray(operation.owned.previous_routes) ? operation.owned.previous_routes : {};
|
|
8606
|
-
for (const providerID of
|
|
8927
|
+
for (const providerID of Object.keys(routes)) {
|
|
8607
8928
|
const provider = providers[providerID] && typeof providers[providerID] === "object" && !Array.isArray(providers[providerID]) ? providers[providerID] : {};
|
|
8608
8929
|
const options = provider.options && typeof provider.options === "object" && !Array.isArray(provider.options) ? provider.options : {};
|
|
8609
8930
|
if (options.baseURL !== undefined && options.baseURL !== routes[providerID]) {
|
|
@@ -8708,15 +9029,170 @@ function writeNativeRestoration(file, bytes) {
|
|
|
8708
9029
|
throw error;
|
|
8709
9030
|
}
|
|
8710
9031
|
}
|
|
8711
|
-
function
|
|
9032
|
+
function claudeProfileRegistryPath() {
|
|
9033
|
+
return join(cavemanHome(), "integrations", "claude-profiles.json");
|
|
9034
|
+
}
|
|
9035
|
+
function rememberedClaudeProfiles() {
|
|
9036
|
+
const bytes = fileBytes(claudeProfileRegistryPath());
|
|
9037
|
+
if (!bytes)
|
|
9038
|
+
return [];
|
|
9039
|
+
const roots = JSON.parse(bytes.toString("utf8"));
|
|
9040
|
+
if (!Array.isArray(roots) || roots.some((root) => typeof root !== "string" || !isAbsolute(root))) {
|
|
9041
|
+
throw new Error("Claude profile registry is invalid; refusing incomplete disable");
|
|
9042
|
+
}
|
|
9043
|
+
return roots;
|
|
9044
|
+
}
|
|
9045
|
+
function rememberClaudeProfile() {
|
|
9046
|
+
const roots = new Set(rememberedClaudeProfiles());
|
|
9047
|
+
roots.add(claudeConfigDir());
|
|
9048
|
+
atomicWriteFile(claudeProfileRegistryPath(), Buffer.from(JSON.stringify([...roots].sort(), null, 2) + "\n"));
|
|
9049
|
+
}
|
|
9050
|
+
function nativeRealPath(file) {
|
|
9051
|
+
try {
|
|
9052
|
+
return realpathSync(file);
|
|
9053
|
+
}
|
|
9054
|
+
catch (error) {
|
|
9055
|
+
if (error.code !== "ENOENT")
|
|
9056
|
+
throw error;
|
|
9057
|
+
return resolve(file);
|
|
9058
|
+
}
|
|
9059
|
+
}
|
|
9060
|
+
function claudeProfileFiles(journal) {
|
|
9061
|
+
const roots = new Set([join(homedir(), ".claude"), claudeConfigDir(), ...rememberedClaudeProfiles()]);
|
|
9062
|
+
for (const entry of readdirSync(homedir(), { withFileTypes: true })) {
|
|
9063
|
+
if (/^\.claude[-_].+/.test(entry.name) && (entry.isDirectory() || entry.isSymbolicLink())) {
|
|
9064
|
+
roots.add(join(homedir(), entry.name));
|
|
9065
|
+
}
|
|
9066
|
+
}
|
|
9067
|
+
for (const operation of journal?.operations ?? []) {
|
|
9068
|
+
if (operation.kind === "claude-settings")
|
|
9069
|
+
roots.add(dirname(operation.file));
|
|
9070
|
+
}
|
|
9071
|
+
const files = new Set([nativeRealPath(join(homedir(), ".claude.json"))]);
|
|
9072
|
+
for (const root of roots) {
|
|
9073
|
+
for (const name of ["settings.json", "settings.local.json", ".claude.json", ".mcp.json"]) {
|
|
9074
|
+
files.add(nativeRealPath(join(root, name)));
|
|
9075
|
+
}
|
|
9076
|
+
}
|
|
9077
|
+
return [...files].sort();
|
|
9078
|
+
}
|
|
9079
|
+
function isClaudeRuntimeHook(command) {
|
|
9080
|
+
if (typeof command !== "string")
|
|
9081
|
+
return false;
|
|
9082
|
+
const identity = managedHookIdentity(command);
|
|
9083
|
+
return identity === "native-hook:claude" || identity === "shrink-hook" || identity === "mem:recall-hook";
|
|
9084
|
+
}
|
|
9085
|
+
function isCavemanClaudeRoute(value, hasNativeHooks) {
|
|
9086
|
+
if (typeof value !== "string")
|
|
9087
|
+
return false;
|
|
9088
|
+
try {
|
|
9089
|
+
const url = new URL(value);
|
|
9090
|
+
if (!["http:", "https:"].includes(url.protocol) || !/^\/w\/claude\/?$/.test(url.pathname))
|
|
9091
|
+
return false;
|
|
9092
|
+
return hasNativeHooks || ["localhost", "127.0.0.1", "[::1]", "gateway.caveman.so", "gw.caveman.so", "api.caveman.so"].includes(url.hostname)
|
|
9093
|
+
|| url.origin === new URL(gatewayURL()).origin;
|
|
9094
|
+
}
|
|
9095
|
+
catch {
|
|
9096
|
+
return false;
|
|
9097
|
+
}
|
|
9098
|
+
}
|
|
9099
|
+
// Journals restore known originals. Discovery also reaches copied profiles and
|
|
9100
|
+
// orphaned installs whose journal lived in a deleted test or alternate home.
|
|
9101
|
+
// Only recognizable Caveman runtime entries are removed without a journal.
|
|
9102
|
+
function cleanClaudeProfile(root) {
|
|
9103
|
+
let changed = false;
|
|
9104
|
+
let hasNativeHooks = false;
|
|
9105
|
+
const hooks = root.hooks;
|
|
9106
|
+
if (hooks && typeof hooks === "object" && !Array.isArray(hooks)) {
|
|
9107
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
9108
|
+
if (!Array.isArray(groups))
|
|
9109
|
+
continue;
|
|
9110
|
+
const kept = groups.filter((group) => {
|
|
9111
|
+
if (!group || typeof group !== "object" || !Array.isArray(group.hooks))
|
|
9112
|
+
return true;
|
|
9113
|
+
const remaining = group.hooks.filter((hook) => {
|
|
9114
|
+
if (!hook || !isClaudeRuntimeHook(hook.command))
|
|
9115
|
+
return true;
|
|
9116
|
+
if (managedHookIdentity(hook.command) === "native-hook:claude")
|
|
9117
|
+
hasNativeHooks = true;
|
|
9118
|
+
changed = true;
|
|
9119
|
+
return false;
|
|
9120
|
+
});
|
|
9121
|
+
if (remaining.length === group.hooks.length)
|
|
9122
|
+
return true;
|
|
9123
|
+
group.hooks = remaining;
|
|
9124
|
+
return remaining.length > 0;
|
|
9125
|
+
});
|
|
9126
|
+
if (kept.length > 0)
|
|
9127
|
+
hooks[event] = kept;
|
|
9128
|
+
else if (groups.length > 0)
|
|
9129
|
+
delete hooks[event];
|
|
9130
|
+
}
|
|
9131
|
+
if (changed && Object.keys(hooks).length === 0)
|
|
9132
|
+
delete root.hooks;
|
|
9133
|
+
}
|
|
9134
|
+
const env = root.env;
|
|
9135
|
+
if (env && typeof env === "object" && !Array.isArray(env)) {
|
|
9136
|
+
const values = env;
|
|
9137
|
+
if (isCavemanClaudeRoute(values.ANTHROPIC_BASE_URL, hasNativeHooks)) {
|
|
9138
|
+
delete values.ANTHROPIC_BASE_URL;
|
|
9139
|
+
if (values[CLAUDE_ASSUME_FIRST_PARTY_ENV] === "1")
|
|
9140
|
+
delete values[CLAUDE_ASSUME_FIRST_PARTY_ENV];
|
|
9141
|
+
for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"]) {
|
|
9142
|
+
if (typeof values[key] === "string" && /^cave_(?:live|test)_/.test(values[key]))
|
|
9143
|
+
delete values[key];
|
|
9144
|
+
}
|
|
9145
|
+
if (Object.keys(values).length === 0)
|
|
9146
|
+
delete root.env;
|
|
9147
|
+
changed = true;
|
|
9148
|
+
}
|
|
9149
|
+
}
|
|
9150
|
+
const servers = root.mcpServers;
|
|
9151
|
+
if (servers && typeof servers === "object" && !Array.isArray(servers)) {
|
|
9152
|
+
const entries = servers;
|
|
9153
|
+
const server = entries.caveman;
|
|
9154
|
+
if (server && typeof server.command === "string" && hookCommandBasename(server.command) === "caveman-mcp") {
|
|
9155
|
+
delete entries.caveman;
|
|
9156
|
+
if (Object.keys(entries).length === 0)
|
|
9157
|
+
delete root.mcpServers;
|
|
9158
|
+
changed = true;
|
|
9159
|
+
}
|
|
9160
|
+
}
|
|
9161
|
+
return changed;
|
|
9162
|
+
}
|
|
9163
|
+
function restoreNativeJournalFiles(journal, allClaudeProfiles = false) {
|
|
8712
9164
|
// Resolve every merge/conflict before first write. A conflict therefore leaves
|
|
8713
9165
|
// all host files and the journal byte-identical.
|
|
8714
|
-
const restored = journal
|
|
8715
|
-
|
|
9166
|
+
const restored = new Map((journal?.operations ?? []).map((operation) => [nativeRealPath(operation.file), restoreNativeOperation(operation)]));
|
|
9167
|
+
if (allClaudeProfiles) {
|
|
9168
|
+
for (const file of claudeProfileFiles(journal)) {
|
|
9169
|
+
const bytes = restored.has(file) ? restored.get(file) : fileBytes(file);
|
|
9170
|
+
if (!bytes)
|
|
9171
|
+
continue;
|
|
9172
|
+
const root = parseJsonc(bytes.toString("utf8"));
|
|
9173
|
+
if (!root || typeof root !== "object" || Array.isArray(root))
|
|
9174
|
+
throw new Error(`${file} is not a JSON object`);
|
|
9175
|
+
if (cleanClaudeProfile(root))
|
|
9176
|
+
restored.set(file, jsonBytes(root));
|
|
9177
|
+
}
|
|
9178
|
+
}
|
|
9179
|
+
const current = [...restored].map(([file]) => ({ file, bytes: fileBytes(file) }));
|
|
9180
|
+
if (allClaudeProfiles && current.length > 0) {
|
|
9181
|
+
const backup = join(cavemanHome(), "integrations", "backups", `claude-disable-${randomUUID()}`);
|
|
9182
|
+
const manifest = current.map((item, index) => {
|
|
9183
|
+
const path = join(backup, `${index}.bin`);
|
|
9184
|
+
if (item.bytes)
|
|
9185
|
+
atomicWriteFile(path, item.bytes);
|
|
9186
|
+
return { file: item.file, backup: item.bytes ? path : null };
|
|
9187
|
+
});
|
|
9188
|
+
atomicWriteFile(join(backup, "manifest.json"), Buffer.from(JSON.stringify(manifest, null, 2) + "\n"));
|
|
9189
|
+
process.stderr.write(`${mark("ok")} Claude profile backups: ${backup}\n`);
|
|
9190
|
+
}
|
|
8716
9191
|
try {
|
|
8717
|
-
for (const
|
|
8718
|
-
writeNativeRestoration(
|
|
8719
|
-
|
|
9192
|
+
for (const [file, bytes] of restored)
|
|
9193
|
+
writeNativeRestoration(file, bytes);
|
|
9194
|
+
if (journal)
|
|
9195
|
+
unlinkSync(nativeJournalPath(journal.agent));
|
|
8720
9196
|
}
|
|
8721
9197
|
catch (error) {
|
|
8722
9198
|
for (const item of current) {
|
|
@@ -8749,22 +9225,29 @@ function cleanupNativeAgentFiles(target, journal) {
|
|
|
8749
9225
|
catch { /* absent or non-empty: preserve */ }
|
|
8750
9226
|
}
|
|
8751
9227
|
}
|
|
8752
|
-
function disableNativeAgent(target) {
|
|
9228
|
+
function disableNativeAgent(target, allClaudeProfiles = false) {
|
|
8753
9229
|
const disabled = withIntegrationLock(target, () => {
|
|
8754
9230
|
recoverPendingNativeInstallUnlocked(target);
|
|
8755
9231
|
const journal = readNativeJournal(target);
|
|
9232
|
+
if (target === "claude" && allClaudeProfiles) {
|
|
9233
|
+
const changed = restoreNativeJournalFiles(journal, true);
|
|
9234
|
+
return changed.length > 0 ? { journal, files: changed.length } : undefined;
|
|
9235
|
+
}
|
|
8756
9236
|
if (!journal)
|
|
8757
9237
|
return undefined;
|
|
8758
9238
|
restoreNativeJournalFiles(journal);
|
|
8759
|
-
return journal;
|
|
9239
|
+
return { journal, files: journal.operations.length };
|
|
8760
9240
|
});
|
|
8761
9241
|
if (!disabled) {
|
|
8762
|
-
process.stderr.write(`${mark("warn")} ${target}: no native Caveman integration journal found\n`);
|
|
9242
|
+
process.stderr.write(`${mark("warn")} ${target === "claude" && allClaudeProfiles ? "Claude Code: no native Caveman routing or hooks found across discovered profiles" : `${target}: no native Caveman integration journal found`}\n`);
|
|
8763
9243
|
return false;
|
|
8764
9244
|
}
|
|
8765
|
-
|
|
9245
|
+
if (disabled.journal)
|
|
9246
|
+
cleanupNativeAgentFiles(target, disabled.journal);
|
|
8766
9247
|
const name = findAgent(target)?.display_name ?? target;
|
|
8767
9248
|
process.stderr.write(`${mark("ok")} ${name}: ${target === "aider" ? "shallow" : "native"} Caveman disabled; unrelated host edits preserved\n`);
|
|
9249
|
+
if (target === "claude" && allClaudeProfiles)
|
|
9250
|
+
process.stderr.write(`Checked all discovered Claude profiles. Restart running Claude sessions; their existing environment cannot be cleared by disable.\n`);
|
|
8768
9251
|
return true;
|
|
8769
9252
|
}
|
|
8770
9253
|
function repairNativeAgent(target) {
|
|
@@ -8799,21 +9282,18 @@ function repairNativeAgent(target) {
|
|
|
8799
9282
|
atomicWriteFile(nativeJournalPath(target), journalBytes);
|
|
8800
9283
|
throw error;
|
|
8801
9284
|
}
|
|
9285
|
+
installNativeVoiceSkills(target);
|
|
8802
9286
|
});
|
|
8803
9287
|
process.stderr.write(`${mark("ok")} ${profile.display_name}: native Caveman repaired; unrelated host edits preserved\n`);
|
|
8804
9288
|
}
|
|
8805
9289
|
function disableNative(argv) {
|
|
8806
|
-
if (argv.length === 1 && argv[0] === "--all") {
|
|
9290
|
+
if (argv.length === 0 || (argv.length === 1 && argv[0] === "--all")) {
|
|
8807
9291
|
const targets = ["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"]
|
|
8808
|
-
.filter((agent) => Boolean(readNativeJournal(agent) || readPendingNativeJournal(agent)));
|
|
8809
|
-
if (targets.length === 0) {
|
|
8810
|
-
process.stderr.write(`${mark("warn")} no native Caveman integrations are journaled\n`);
|
|
8811
|
-
return;
|
|
8812
|
-
}
|
|
9292
|
+
.filter((agent) => agent === "claude" || Boolean(readNativeJournal(agent) || readPendingNativeJournal(agent)));
|
|
8813
9293
|
let failed = 0;
|
|
8814
9294
|
for (const target of targets) {
|
|
8815
9295
|
try {
|
|
8816
|
-
disableNativeAgent(target);
|
|
9296
|
+
disableNativeAgent(target, true);
|
|
8817
9297
|
}
|
|
8818
9298
|
catch (error) {
|
|
8819
9299
|
failed++;
|
|
@@ -8827,7 +9307,7 @@ function disableNative(argv) {
|
|
|
8827
9307
|
const target = argv[0];
|
|
8828
9308
|
if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "pi" && target !== "aider") || argv.length !== 1)
|
|
8829
9309
|
commandUsage("disable <claude|codex|hermes|gemini|opencode|pi|aider> | disable --all");
|
|
8830
|
-
disableNativeAgent(target);
|
|
9310
|
+
disableNativeAgent(target, true);
|
|
8831
9311
|
}
|
|
8832
9312
|
function nativeIntegrationStatus(agent) {
|
|
8833
9313
|
const profile = findAgent(agent);
|
|
@@ -8879,17 +9359,19 @@ function nativeIntegrationStatus(agent) {
|
|
|
8879
9359
|
const providers = root.provider && typeof root.provider === "object" && !Array.isArray(root.provider) ? root.provider : {};
|
|
8880
9360
|
const routes = operation.owned?.routes && typeof operation.owned.routes === "object" && !Array.isArray(operation.owned.routes) ? operation.owned.routes : {};
|
|
8881
9361
|
const mcp = root.mcp && typeof root.mcp === "object" && !Array.isArray(root.mcp) ? root.mcp : {};
|
|
8882
|
-
owned =
|
|
9362
|
+
owned = Object.keys(routes).every((providerID) => {
|
|
8883
9363
|
const provider = providers[providerID] && typeof providers[providerID] === "object" && !Array.isArray(providers[providerID]) ? providers[providerID] : {};
|
|
8884
9364
|
const options = provider.options && typeof provider.options === "object" && !Array.isArray(provider.options) ? provider.options : {};
|
|
8885
9365
|
return options.baseURL === routes[providerID];
|
|
8886
9366
|
}) && JSON.stringify(mcp.caveman) === JSON.stringify(operation.owned?.installed_mcp);
|
|
8887
9367
|
}
|
|
8888
9368
|
else if (operation.kind === "opencode-plugin") {
|
|
8889
|
-
|
|
9369
|
+
const text = current.toString("utf8");
|
|
9370
|
+
owned = text.includes("caveman:native-opencode") && generatedArtifactTargetsExist(text);
|
|
8890
9371
|
}
|
|
8891
9372
|
else if (operation.kind === "pi-extension") {
|
|
8892
|
-
|
|
9373
|
+
const text = current.toString("utf8");
|
|
9374
|
+
owned = text.includes("caveman:native-pi") && generatedArtifactTargetsExist(text);
|
|
8893
9375
|
}
|
|
8894
9376
|
else if (operation.kind === "aider-config") {
|
|
8895
9377
|
const text = current.toString("utf8");
|
|
@@ -8921,7 +9403,7 @@ function nativeIntegrationStatus(agent) {
|
|
|
8921
9403
|
const mcp = probeMcpBinary();
|
|
8922
9404
|
const expectedRoute = agent === "codex"
|
|
8923
9405
|
? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
|
|
8924
|
-
: appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "
|
|
9406
|
+
: appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
|
|
8925
9407
|
const routeKind = agent === "claude" ? "claude-settings" : agent === "codex" ? "codex-config" : agent === "hermes" ? "hermes-config" : agent === "gemini" ? "gemini-env" : agent === "opencode" ? "opencode-config" : agent === "pi" ? "pi-extension" : "aider-config";
|
|
8926
9408
|
const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
|
|
8927
9409
|
// Pi's artifact encodes no route: the extension resolves the gateway at
|
|
@@ -8967,8 +9449,7 @@ function nativeIntegrationStatus(agent) {
|
|
|
8967
9449
|
return (semver[0] >= 2) === installedV2;
|
|
8968
9450
|
})();
|
|
8969
9451
|
const routeHealthy = ownedHealthy && (agent === "opencode"
|
|
8970
|
-
? routeOperation?.owned?.routes?.
|
|
8971
|
-
&& routeOperation?.owned?.routes?.anthropic === appendUrlPath(expectedRoute, "/anthropic/v1")
|
|
9452
|
+
? Object.entries(opencodeNativeRoutes(gatewayURL())).every(([providerID, route]) => routeOperation?.owned?.routes?.[providerID] === route)
|
|
8972
9453
|
: agent === "pi" ? piBundleCurrent : routeOperation?.owned?.route === expectedRoute);
|
|
8973
9454
|
const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
|
|
8974
9455
|
const recoveryHealthy = agent === "aider" || Boolean(mcp?.probe.current);
|
|
@@ -8977,6 +9458,13 @@ function nativeIntegrationStatus(agent) {
|
|
|
8977
9458
|
const coreActive = agent === "aider"
|
|
8978
9459
|
? ownedHealthy
|
|
8979
9460
|
: coreSupported && nativeCoreRuntimeState().active;
|
|
9461
|
+
const warnings = [];
|
|
9462
|
+
if (agent === "opencode" && installed) {
|
|
9463
|
+
const routed = Object.keys(routeOperation?.owned?.routes ?? {});
|
|
9464
|
+
const unrouted = opencodeUnroutedActiveProvider(routed);
|
|
9465
|
+
if (unrouted)
|
|
9466
|
+
warnings.push(`OpenCode's active provider "${unrouted}" is not routed through Caveman; its requests go direct and are not compressed or counted (routed: ${routed.join(", ")})`);
|
|
9467
|
+
}
|
|
8980
9468
|
const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
|
|
8981
9469
|
const components = {
|
|
8982
9470
|
routing: routeHealthy && proxyHealthy && (agent === "claude" ? fileText.includes("ANTHROPIC_BASE_URL") : agent === "codex" ? fileText.includes("model_providers.caveman") : agent === "hermes" ? fileText.includes(HERMES_NATIVE_ROUTE_BEGIN) : agent === "gemini" ? fileText.includes(GEMINI_NATIVE_ENV_BEGIN) : agent === "opencode" ? fileText.includes("caveman:native-opencode") : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes(AIDER_NATIVE_ROUTE_BEGIN)),
|
|
@@ -9028,6 +9516,7 @@ function nativeIntegrationStatus(agent) {
|
|
|
9028
9516
|
pack_current: packCurrent,
|
|
9029
9517
|
drifted,
|
|
9030
9518
|
components,
|
|
9519
|
+
warnings,
|
|
9031
9520
|
capabilities: nativeCapabilityReport(agent, components, versionStatus),
|
|
9032
9521
|
files: checks,
|
|
9033
9522
|
};
|
|
@@ -10530,6 +11019,37 @@ function writeSyncWatermark(key, id) {
|
|
|
10530
11019
|
mkdirSync(dirname(syncStatePath()), { recursive: true });
|
|
10531
11020
|
writeFileSync(syncStatePath(), JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
|
|
10532
11021
|
}
|
|
11022
|
+
// syncClaimLockPath is the sidecar that serializes the read-query-POST-write
|
|
11023
|
+
// in syncLocalSavings across OS processes; it sits beside sync.json so its
|
|
11024
|
+
// permission and cross-filesystem behavior always matches the file it protects.
|
|
11025
|
+
function syncClaimLockPath() {
|
|
11026
|
+
return `${syncStatePath()}.lock`;
|
|
11027
|
+
}
|
|
11028
|
+
// How long a waiter blocks before giving up and reporting `busy`. Deliberately
|
|
11029
|
+
// short: syncAfterWrap runs on the wrap exit path, and making a user wait out
|
|
11030
|
+
// someone else's upload to close a shell is worse than deferring their rows to
|
|
11031
|
+
// the next sync — nothing is lost either way, the watermark simply has not moved.
|
|
11032
|
+
const SYNC_CLAIM_LOCK_BUDGET_MS = 5000;
|
|
11033
|
+
// A sync lock is held across a network POST, which has no bounded duration, so
|
|
11034
|
+
// unlike the telemetry claim its stale window cannot be a guess at the hold
|
|
11035
|
+
// time: a live holder on a slow link would be judged dead and its rows POSTed
|
|
11036
|
+
// twice, which is the very bug the lock exists to prevent. The holder instead
|
|
11037
|
+
// heartbeats the lock while it works, so this window only has to outlast a
|
|
11038
|
+
// couple of missed beats.
|
|
11039
|
+
const SYNC_CLAIM_LOCK_STALE_MS = 15000;
|
|
11040
|
+
const SYNC_CLAIM_LOCK_HEARTBEAT_MS = 3000;
|
|
11041
|
+
// refreshClaimLock bumps a held lock's mtime so waiters keep seeing it as live.
|
|
11042
|
+
// Never throws — if the lock is gone the guarded work is already compromised,
|
|
11043
|
+
// and crashing the sync on a touch failure would lose the rows in flight.
|
|
11044
|
+
function refreshClaimLock(lockPath) {
|
|
11045
|
+
try {
|
|
11046
|
+
const now = new Date();
|
|
11047
|
+
utimesSync(lockPath, now, now);
|
|
11048
|
+
}
|
|
11049
|
+
catch {
|
|
11050
|
+
/* lock vanished or the FS refused the touch; the POST still completes */
|
|
11051
|
+
}
|
|
11052
|
+
}
|
|
10533
11053
|
// deriveDashboardUrl maps the control-api base URL to the dashboard costs page
|
|
10534
11054
|
// for the two shapes Caveman ships (local docker web :3000; hosted api.<domain>
|
|
10535
11055
|
// → apex, which serves the dashboard). Anything else returns "" — no guessing.
|
|
@@ -10671,82 +11191,112 @@ async function syncLocalSavings(cfg) {
|
|
|
10671
11191
|
}
|
|
10672
11192
|
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
10673
11193
|
let rows;
|
|
10674
|
-
|
|
10675
|
-
const firstSync = !hasSyncWatermark(key);
|
|
10676
|
-
const since = readSyncWatermark(key);
|
|
11194
|
+
let key;
|
|
10677
11195
|
try {
|
|
10678
|
-
|
|
10679
|
-
.map((row) => typeof row.name === "string" ? row.name : "")
|
|
10680
|
-
.filter(Boolean));
|
|
10681
|
-
const optional = (name, fallback) => columns.has(name) ? name : `${fallback} AS ${name}`;
|
|
10682
|
-
rows = db
|
|
10683
|
-
.prepare(`SELECT id, ts, request_id, trace_id, agent_slug, provider, model,
|
|
10684
|
-
status_code, error_code, latency_ms, request_bytes, response_bytes,
|
|
10685
|
-
input_tokens, output_tokens, cached_input_tokens,
|
|
10686
|
-
${optional("cache_creation_input_tokens", "0")}, total_cost_usd,
|
|
10687
|
-
savings_usd, basis, ${optional("token_usage_basis", "'unavailable'")},
|
|
10688
|
-
${optional("auth_mode", "'unknown'")}, runtime_mode, optimization_ids,
|
|
10689
|
-
compression_tokens_before, compression_tokens_after,
|
|
10690
|
-
${optional("compression_token_count_basis", "'unavailable'")}
|
|
10691
|
-
FROM requests WHERE id > ? ORDER BY id`)
|
|
10692
|
-
.all(since);
|
|
11196
|
+
key = syncWatermarkKey(cfg, dbFingerprint(db, dbPath, DatabaseSync));
|
|
10693
11197
|
}
|
|
10694
|
-
|
|
11198
|
+
catch (err) {
|
|
10695
11199
|
db.close();
|
|
11200
|
+
throw err;
|
|
11201
|
+
}
|
|
11202
|
+
// Everything from here to the watermark write is one claim: reading the
|
|
11203
|
+
// watermark, selecting the rows past it, POSTing them and committing the new
|
|
11204
|
+
// watermark. Without the lock two processes starting together both read the
|
|
11205
|
+
// pre-write watermark, both select the same rows and both POST them, so the
|
|
11206
|
+
// same spans land server-side twice (#1132). A waiter that cannot take the
|
|
11207
|
+
// lock in its budget sends nothing and leaves the watermark alone, so its
|
|
11208
|
+
// rows are picked up by the next sync rather than duplicated by this one.
|
|
11209
|
+
const lockPath = syncClaimLockPath();
|
|
11210
|
+
const lockToken = acquireClaimLock(lockPath, SYNC_CLAIM_LOCK_BUDGET_MS, SYNC_CLAIM_LOCK_STALE_MS);
|
|
11211
|
+
if (!lockToken) {
|
|
11212
|
+
db.close();
|
|
11213
|
+
return { kind: "busy" };
|
|
10696
11214
|
}
|
|
10697
|
-
|
|
10698
|
-
|
|
10699
|
-
|
|
10700
|
-
|
|
10701
|
-
|
|
10702
|
-
|
|
10703
|
-
|
|
10704
|
-
|
|
10705
|
-
|
|
10706
|
-
|
|
10707
|
-
|
|
10708
|
-
|
|
10709
|
-
|
|
10710
|
-
|
|
10711
|
-
|
|
10712
|
-
|
|
10713
|
-
|
|
10714
|
-
|
|
10715
|
-
|
|
10716
|
-
|
|
10717
|
-
|
|
10718
|
-
|
|
10719
|
-
|
|
10720
|
-
|
|
10721
|
-
|
|
10722
|
-
|
|
10723
|
-
|
|
10724
|
-
|
|
10725
|
-
|
|
10726
|
-
|
|
11215
|
+
// The POST below is unbounded, so keep proving this holder is alive; see
|
|
11216
|
+
// SYNC_CLAIM_LOCK_STALE_MS.
|
|
11217
|
+
const heartbeat = setInterval(() => refreshClaimLock(lockPath), SYNC_CLAIM_LOCK_HEARTBEAT_MS);
|
|
11218
|
+
heartbeat.unref();
|
|
11219
|
+
try {
|
|
11220
|
+
const firstSync = !hasSyncWatermark(key);
|
|
11221
|
+
const since = readSyncWatermark(key);
|
|
11222
|
+
try {
|
|
11223
|
+
const columns = new Set(db.prepare("PRAGMA table_info(requests)").all()
|
|
11224
|
+
.map((row) => typeof row.name === "string" ? row.name : "")
|
|
11225
|
+
.filter(Boolean));
|
|
11226
|
+
const optional = (name, fallback) => columns.has(name) ? name : `${fallback} AS ${name}`;
|
|
11227
|
+
rows = db
|
|
11228
|
+
.prepare(`SELECT id, ts, request_id, trace_id, agent_slug, provider, model,
|
|
11229
|
+
status_code, error_code, latency_ms, request_bytes, response_bytes,
|
|
11230
|
+
input_tokens, output_tokens, cached_input_tokens,
|
|
11231
|
+
${optional("cache_creation_input_tokens", "0")}, total_cost_usd,
|
|
11232
|
+
savings_usd, basis, ${optional("token_usage_basis", "'unavailable'")},
|
|
11233
|
+
${optional("auth_mode", "'unknown'")}, runtime_mode, optimization_ids,
|
|
11234
|
+
compression_tokens_before, compression_tokens_after,
|
|
11235
|
+
${optional("compression_token_count_basis", "'unavailable'")}
|
|
11236
|
+
FROM requests WHERE id > ? ORDER BY id`)
|
|
11237
|
+
.all(since);
|
|
11238
|
+
}
|
|
11239
|
+
finally {
|
|
11240
|
+
db.close();
|
|
11241
|
+
}
|
|
11242
|
+
if (rows.length === 0)
|
|
11243
|
+
return { kind: "empty" };
|
|
11244
|
+
// Per-row directive labels (review M12): a row synced from BEFORE a
|
|
11245
|
+
// directive's install carries no label — backlog sessions are not evidence
|
|
11246
|
+
// about a directive that did not exist yet. An unparseable row timestamp
|
|
11247
|
+
// labels nothing (fail closed).
|
|
11248
|
+
const directiveInstalls = installedDirectivesWithTimes();
|
|
11249
|
+
const rowDirectives = (r) => {
|
|
11250
|
+
if (directiveInstalls.length === 0)
|
|
11251
|
+
return [];
|
|
11252
|
+
const ts = typeof r.ts === "string" ? r.ts : "";
|
|
11253
|
+
// The proxy writes ClickHouse-layout UTC timestamps ("YYYY-MM-DD HH:MM:SS.mmm").
|
|
11254
|
+
const ms = Date.parse(ts.includes("T") ? ts : ts.replace(" ", "T") + "Z");
|
|
11255
|
+
if (!Number.isFinite(ms))
|
|
11256
|
+
return [];
|
|
11257
|
+
return directiveInstalls.filter((d) => ms >= d.installedAtMs).map((d) => d.id);
|
|
11258
|
+
};
|
|
11259
|
+
const body = rows.map((r) => syncRequestSpan(r, rowDirectives(r))).join("\n") + "\n";
|
|
11260
|
+
const response = await fetch(`${cfg.baseURL}/api/v1/imports?format=caveman-jsonl`, {
|
|
11261
|
+
method: "POST",
|
|
11262
|
+
headers: {
|
|
11263
|
+
authorization: `Bearer ${cfg.token}`,
|
|
11264
|
+
"content-type": "application/octet-stream",
|
|
11265
|
+
"x-cave-csrf": "cli",
|
|
11266
|
+
},
|
|
11267
|
+
body,
|
|
11268
|
+
});
|
|
11269
|
+
const result = (await response.json().catch(() => ({})));
|
|
11270
|
+
if (!response.ok || result.status !== "completed") {
|
|
11271
|
+
throw new Error(result.error?.message ?? `sync import failed (${response.status})`);
|
|
11272
|
+
}
|
|
11273
|
+
const num = (v) => (typeof v === "bigint" ? Number(v) : typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
11274
|
+
const maxId = rows.reduce((m, r) => Math.max(m, num(r.id)), since);
|
|
11275
|
+
writeSyncWatermark(key, maxId);
|
|
11276
|
+
const tokensSaved = rows.reduce((sum, r) => sum + Math.max(0, num(r.compression_tokens_before) - num(r.compression_tokens_after)), 0);
|
|
11277
|
+
const tokenBases = new Set(rows.map((r) => (typeof r.compression_token_count_basis === "string" ? r.compression_token_count_basis : "")).filter(Boolean));
|
|
11278
|
+
const tokenCountBasis = tokenBases.size === 0 ? "unavailable" : tokenBases.size === 1 ? [...tokenBases][0] ?? "unavailable" : "mixed";
|
|
11279
|
+
const cachedInputTokens = rows.reduce((sum, r) => sum + Math.max(0, num(r.cached_input_tokens)), 0);
|
|
11280
|
+
const cacheCreationInputTokens = rows.reduce((sum, r) => sum + Math.max(0, num(r.cache_creation_input_tokens)), 0);
|
|
11281
|
+
const headlineCompressionRefused = cacheCreationInputTokens > cachedInputTokens;
|
|
11282
|
+
const savingsUSD = rows.reduce((sum, r) => sum + num(r.savings_usd), 0);
|
|
11283
|
+
return {
|
|
11284
|
+
kind: "synced",
|
|
11285
|
+
spans: rows.length,
|
|
11286
|
+
tokensSaved,
|
|
11287
|
+
tokenCountBasis,
|
|
11288
|
+
cachedInputTokens,
|
|
11289
|
+
cacheCreationInputTokens,
|
|
11290
|
+
headlineCompressionRefused,
|
|
11291
|
+
savingsUSD,
|
|
11292
|
+
dashboard: deriveDashboardUrl(cfg.baseURL),
|
|
11293
|
+
firstSync,
|
|
11294
|
+
};
|
|
11295
|
+
}
|
|
11296
|
+
finally {
|
|
11297
|
+
clearInterval(heartbeat);
|
|
11298
|
+
releaseClaimLock(lockPath, lockToken);
|
|
10727
11299
|
}
|
|
10728
|
-
const num = (v) => (typeof v === "bigint" ? Number(v) : typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
10729
|
-
const maxId = rows.reduce((m, r) => Math.max(m, num(r.id)), since);
|
|
10730
|
-
writeSyncWatermark(key, maxId);
|
|
10731
|
-
const tokensSaved = rows.reduce((sum, r) => sum + Math.max(0, num(r.compression_tokens_before) - num(r.compression_tokens_after)), 0);
|
|
10732
|
-
const tokenBases = new Set(rows.map((r) => (typeof r.compression_token_count_basis === "string" ? r.compression_token_count_basis : "")).filter(Boolean));
|
|
10733
|
-
const tokenCountBasis = tokenBases.size === 0 ? "unavailable" : tokenBases.size === 1 ? [...tokenBases][0] ?? "unavailable" : "mixed";
|
|
10734
|
-
const cachedInputTokens = rows.reduce((sum, r) => sum + Math.max(0, num(r.cached_input_tokens)), 0);
|
|
10735
|
-
const cacheCreationInputTokens = rows.reduce((sum, r) => sum + Math.max(0, num(r.cache_creation_input_tokens)), 0);
|
|
10736
|
-
const headlineCompressionRefused = cacheCreationInputTokens > cachedInputTokens;
|
|
10737
|
-
const savingsUSD = rows.reduce((sum, r) => sum + num(r.savings_usd), 0);
|
|
10738
|
-
return {
|
|
10739
|
-
kind: "synced",
|
|
10740
|
-
spans: rows.length,
|
|
10741
|
-
tokensSaved,
|
|
10742
|
-
tokenCountBasis,
|
|
10743
|
-
cachedInputTokens,
|
|
10744
|
-
cacheCreationInputTokens,
|
|
10745
|
-
headlineCompressionRefused,
|
|
10746
|
-
savingsUSD,
|
|
10747
|
-
dashboard: deriveDashboardUrl(cfg.baseURL),
|
|
10748
|
-
firstSync,
|
|
10749
|
-
};
|
|
10750
11300
|
}
|
|
10751
11301
|
function syncSavingsLine(out, local = false) {
|
|
10752
11302
|
const destination = out.dashboard ? ` → ${out.dashboard}` : "";
|
|
@@ -10833,6 +11383,11 @@ async function sync() {
|
|
|
10833
11383
|
else if (out.kind === "empty") {
|
|
10834
11384
|
console.log("nothing new to sync — local inferred savings are already up to date");
|
|
10835
11385
|
}
|
|
11386
|
+
else if (out.kind === "busy") {
|
|
11387
|
+
// Not a failure: another caveman process holds the watermark and is
|
|
11388
|
+
// uploading these rows right now. Exit 0 — re-running is always safe.
|
|
11389
|
+
console.log("another sync is already running — local spans left for the next `caveman sync`");
|
|
11390
|
+
}
|
|
10836
11391
|
else {
|
|
10837
11392
|
if (out.firstSync)
|
|
10838
11393
|
console.log(SYNC_DISCLOSURE);
|
|
@@ -10880,6 +11435,9 @@ async function syncAfterLogin() {
|
|
|
10880
11435
|
if (savingsLane.value.kind === "synced") {
|
|
10881
11436
|
console.error(` ${mark("ok")} ${syncSavingsLine(savingsLane.value, true)}`);
|
|
10882
11437
|
}
|
|
11438
|
+
else if (savingsLane.value.kind === "busy") {
|
|
11439
|
+
console.error(dim(` another sync is already running — run \`${invokedAs()} sync\` afterwards to pick up the rest`));
|
|
11440
|
+
}
|
|
10883
11441
|
else {
|
|
10884
11442
|
console.error(dim(" no local spans to sync yet — `caveman wrap <agent>` records inferred savings locally; `caveman sync` uploads them"));
|
|
10885
11443
|
}
|
|
@@ -11027,9 +11585,38 @@ function mcpServerInstalled(agentId, serverName) {
|
|
|
11027
11585
|
return false;
|
|
11028
11586
|
}
|
|
11029
11587
|
}
|
|
11588
|
+
function nativeOpencodeMcpInstalled() {
|
|
11589
|
+
const journal = readNativeJournal("opencode");
|
|
11590
|
+
if (!journal)
|
|
11591
|
+
return false;
|
|
11592
|
+
const operation = journal.operations.find((item) => item.kind === "opencode-config");
|
|
11593
|
+
if (!operation?.owned?.installed_mcp)
|
|
11594
|
+
return false;
|
|
11595
|
+
const current = fileBytes(operation.file);
|
|
11596
|
+
if (!current)
|
|
11597
|
+
return false;
|
|
11598
|
+
try {
|
|
11599
|
+
const root = parseJsonFileObject(operation.file, current);
|
|
11600
|
+
const mcp = root.mcp && typeof root.mcp === "object" && !Array.isArray(root.mcp)
|
|
11601
|
+
? root.mcp
|
|
11602
|
+
: {};
|
|
11603
|
+
// canonicalize, not JSON.stringify: the comparison is about whether the
|
|
11604
|
+
// registration is still ours, and key order is not part of that. Any writer
|
|
11605
|
+
// that round-trips opencode.json through a rebuilt or sorted map reorders
|
|
11606
|
+
// these keys without changing the registration, and a raw stringify compare
|
|
11607
|
+
// would then report "MCP recovery missing" for a registration that is
|
|
11608
|
+
// present and correct — the same false negative this function exists to fix.
|
|
11609
|
+
return canonicalize(mcp.caveman) === canonicalize(operation.owned.installed_mcp);
|
|
11610
|
+
}
|
|
11611
|
+
catch {
|
|
11612
|
+
return false;
|
|
11613
|
+
}
|
|
11614
|
+
}
|
|
11030
11615
|
function mcpInstalled(agentId, agentArgs = []) {
|
|
11031
11616
|
if (agentId === "kilo" || agentId === "qwen")
|
|
11032
11617
|
return ownedMcpRegistration(agentId, agentArgs) !== null;
|
|
11618
|
+
if (agentId === "opencode" && nativeOpencodeMcpInstalled())
|
|
11619
|
+
return true;
|
|
11033
11620
|
return mcpServerInstalled(agentId, "caveman");
|
|
11034
11621
|
}
|
|
11035
11622
|
// configFileOverlayHasMcp asks whether the PROFILE would inject this MCP server
|
|
@@ -11168,11 +11755,17 @@ const HERMES_PLUGIN_ENABLE_BEGIN = "# >>> caveman:hermes-plugin-enable";
|
|
|
11168
11755
|
const HERMES_PLUGIN_ENABLE_END = "# <<< caveman:hermes-plugin-enable";
|
|
11169
11756
|
const HERMES_PLUGIN_NAME = "caveman_shrink";
|
|
11170
11757
|
export function hermesHome(env = process.env, platform = process.platform) {
|
|
11171
|
-
// Hermes 0.
|
|
11172
|
-
// overrides are stripped,
|
|
11758
|
+
// Hermes 0.21.5 hermes_constants.py: native Windows uses LOCALAPPDATA,
|
|
11759
|
+
// overrides are stripped, then Path(expanduser(expandvars(value))).
|
|
11760
|
+
// ponytail: no `~user` or Windows quote/escape forms; add if a user hits one.
|
|
11173
11761
|
const override = env.HERMES_HOME?.trim();
|
|
11174
|
-
if (override)
|
|
11175
|
-
|
|
11762
|
+
if (override) {
|
|
11763
|
+
const lookup = (whole, name) => env[name] ?? whole;
|
|
11764
|
+
let expanded = override.replace(/\$(\w+)|\$\{([^{}$]*)\}/g, (whole, bare, braced) => lookup(whole, bare ?? braced));
|
|
11765
|
+
if (platform === "win32")
|
|
11766
|
+
expanded = expanded.replace(/%([^%]+)%/g, lookup);
|
|
11767
|
+
return resolve(expanded.replace(/^~(?=$|[\\/])/, homedir()));
|
|
11768
|
+
}
|
|
11176
11769
|
if (platform === "win32") {
|
|
11177
11770
|
return join(env.LOCALAPPDATA?.trim() || join(homedir(), "AppData", "Local"), "hermes");
|
|
11178
11771
|
}
|
|
@@ -12875,11 +13468,33 @@ function agentRouteOverride(agent, args) {
|
|
|
12875
13468
|
return qwenRouteOverride(agent, args);
|
|
12876
13469
|
// Claude Code 2.1.196+ refuses Remote Control unless ANTHROPIC_BASE_URL is
|
|
12877
13470
|
// api.anthropic.com, and the first-party escape hatch does not apply (#947).
|
|
12878
|
-
if (agent.id === "claude" && args
|
|
13471
|
+
if (agent.id === "claude" && claudeStartsRemoteControl(args)) {
|
|
12879
13472
|
return { surface: "remote-control", reason: "only runs against api.anthropic.com, so it cannot route through the proxy" };
|
|
12880
13473
|
}
|
|
12881
13474
|
return null;
|
|
12882
13475
|
}
|
|
13476
|
+
// Claude Code spells Remote Control `--remote-control [name]`; the bare
|
|
13477
|
+
// `remote-control` word is the legacy subcommand. #947 matched only the latter,
|
|
13478
|
+
// so every user who followed the documented flag kept routing through the proxy
|
|
13479
|
+
// and kept being refused by the host (#1101).
|
|
13480
|
+
//
|
|
13481
|
+
// `--remote-control-session-name-prefix` only names auto-generated sessions and
|
|
13482
|
+
// does NOT start Remote Control, so it must not match — bypassing on it would
|
|
13483
|
+
// silently drop compression for a session that never needed the bypass. Scanning
|
|
13484
|
+
// stops at `--`, after which argv belongs to the agent's own payload.
|
|
13485
|
+
function claudeStartsRemoteControl(args) {
|
|
13486
|
+
// The bare legacy word is a subcommand, so it counts only in first position;
|
|
13487
|
+
// anywhere else it is a value (`-p remote-control`) and must keep routing.
|
|
13488
|
+
if (args[0] === "remote-control")
|
|
13489
|
+
return true;
|
|
13490
|
+
for (const arg of args) {
|
|
13491
|
+
if (arg === "--")
|
|
13492
|
+
return false;
|
|
13493
|
+
if (arg === "--remote-control" || arg.startsWith("--remote-control="))
|
|
13494
|
+
return true;
|
|
13495
|
+
}
|
|
13496
|
+
return false;
|
|
13497
|
+
}
|
|
12883
13498
|
function routeOverrideLabel(agent) {
|
|
12884
13499
|
if (agent.id === "qwen")
|
|
12885
13500
|
return "Qwen";
|
|
@@ -13583,7 +14198,13 @@ function installMcpCodexToml(mcp, serverName = "caveman") {
|
|
|
13583
14198
|
}
|
|
13584
14199
|
const blockStart = headerMatch.index + (headerMatch[1] ? 1 : 0);
|
|
13585
14200
|
const contentStart = headerMatch.index + headerMatch[0].length;
|
|
13586
|
-
|
|
14201
|
+
// /^[ \t]*\[/ — NOT [ \\t]. In a regex LITERAL `\\t` is an escaped backslash, so
|
|
14202
|
+
// the class was [space, backslash, "t"] and never matched a tab (#1134). A
|
|
14203
|
+
// tab-indented table is valid TOML, and Codex writes one for every trusted
|
|
14204
|
+
// project, so the boundary ran past it: the verify below never compared equal,
|
|
14205
|
+
// and the splice above deleted the user's tables. The uninstall twin
|
|
14206
|
+
// (removeMcpCodexToml) has always spelled this correctly.
|
|
14207
|
+
const nextHeaderOffset = existing.slice(contentStart).search(/^[ \t]*\[/m);
|
|
13587
14208
|
const blockEnd = nextHeaderOffset === -1 ? existing.length : contentStart + nextHeaderOffset;
|
|
13588
14209
|
const currentBlock = existing.slice(blockStart, blockEnd).trim();
|
|
13589
14210
|
if (currentBlock === expectedBlock.trim()) {
|
|
@@ -13624,7 +14245,8 @@ function codexMcpRegistrationMatches(serverName, mcp) {
|
|
|
13624
14245
|
return false;
|
|
13625
14246
|
const blockStart = headerMatch.index + (headerMatch[1] ? 1 : 0);
|
|
13626
14247
|
const contentStart = headerMatch.index + headerMatch[0].length;
|
|
13627
|
-
|
|
14248
|
+
// See the note in installMcpCodexToml: a literal [ \\t] never matched a tab (#1134).
|
|
14249
|
+
const nextHeaderOffset = existing.slice(contentStart).search(/^[ \t]*\[/m);
|
|
13628
14250
|
const blockEnd = nextHeaderOffset === -1 ? existing.length : contentStart + nextHeaderOffset;
|
|
13629
14251
|
const argsLine = mcp.args.length ? `\nargs = [${mcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]` : "";
|
|
13630
14252
|
const recoveryEnv = serverName === "caveman" ? `\n${CODEX_RECOVERY_ENV}` : "";
|
|
@@ -13933,6 +14555,18 @@ const SHRINK_ALLOW = new Set([
|
|
|
13933
14555
|
"ls", "tree", "du", "df", "ps", "docker", "kubectl", "terraform", "helm",
|
|
13934
14556
|
"aws", "gcloud", "az", "gh",
|
|
13935
14557
|
]);
|
|
14558
|
+
// Subcommands that must never be wrapped even though their tool is allowlisted:
|
|
14559
|
+
// they open an editor, attach a tty, or wait on a human. Keyed by tool, matched
|
|
14560
|
+
// against every token so a global option cannot hide the subcommand (#1133).
|
|
14561
|
+
const SHRINK_SKIP_SUBCOMMANDS = new Map([
|
|
14562
|
+
["git", new Set(["commit", "rebase", "mergetool"])],
|
|
14563
|
+
["npm", new Set(["init"])],
|
|
14564
|
+
["yarn", new Set(["init"])],
|
|
14565
|
+
["pnpm", new Set(["init"])],
|
|
14566
|
+
["docker", new Set(["run", "exec", "attach"])],
|
|
14567
|
+
["kubectl", new Set(["edit", "exec", "attach"])],
|
|
14568
|
+
["terraform", new Set(["apply", "destroy"])],
|
|
14569
|
+
]);
|
|
13936
14570
|
// shouldShrink decides whether a Bash command's output should be routed through
|
|
13937
14571
|
// `caveman shrink`. Conservative by design: it only rewrites a known-noisy,
|
|
13938
14572
|
// finite, non-interactive command with no shell operators (shrink execs argv
|
|
@@ -13950,13 +14584,16 @@ function shouldShrink(command) {
|
|
|
13950
14584
|
return false; // streaming/interactive
|
|
13951
14585
|
const tokens = cmd.split(/\s+/);
|
|
13952
14586
|
const first = tokens[0] ?? "";
|
|
13953
|
-
|
|
13954
|
-
|
|
13955
|
-
|
|
13956
|
-
|
|
13957
|
-
|
|
13958
|
-
|
|
13959
|
-
|
|
14587
|
+
// The excluded subcommand can sit anywhere after the tool, because a global
|
|
14588
|
+
// option may precede it and an option may or may not take a separate value
|
|
14589
|
+
// (`git -C . commit`, `docker --context x exec`, `terraform -chdir=infra apply`).
|
|
14590
|
+
// Comparing only tokens[1] let every one of those walk past the guard and get
|
|
14591
|
+
// wrapped anyway (#1133). We do not try to parse each tool's option grammar to
|
|
14592
|
+
// find "the" subcommand — we fail closed and decline if the word appears at all.
|
|
14593
|
+
// Over-matching costs one uncompressed command; under-matching hands `shrink`,
|
|
14594
|
+
// which captures output and must terminate, a command that opens an editor.
|
|
14595
|
+
const skip = SHRINK_SKIP_SUBCOMMANDS.get(first);
|
|
14596
|
+
if (skip && tokens.slice(1).some((token) => skip.has(token)))
|
|
13960
14597
|
return false;
|
|
13961
14598
|
return SHRINK_ALLOW.has(first);
|
|
13962
14599
|
}
|
|
@@ -14016,10 +14653,21 @@ async function shrinkHook() {
|
|
|
14016
14653
|
// not hook's explicit PowerShell shell. Never leak PowerShell `&` into it.
|
|
14017
14654
|
const rewritten = `${cavemanBinForHook(false)} shrink -- ${command.trim()}`;
|
|
14018
14655
|
// Gemini merges hookSpecificOutput.tool_input (snake_case, no event discriminator);
|
|
14019
|
-
// Claude
|
|
14656
|
+
// Claude REPLACES via hookSpecificOutput.updatedInput (camelCase + hookEventName).
|
|
14657
|
+
// Because Claude replaces, updatedInput must carry every field the host sent —
|
|
14658
|
+
// rebuilding it from `command` alone dropped timeout, run_in_background and
|
|
14659
|
+
// description, changing how the command ran (#1133). Gemini's merge already
|
|
14660
|
+
// preserves the rest, so sending only `command` there is correct as written.
|
|
14661
|
+
//
|
|
14662
|
+
// No permissionDecision either. It is the same objection #1037 raised for Codex,
|
|
14663
|
+
// and Claude Code — unlike Codex — provably honors it: answering "allow" turned a
|
|
14664
|
+
// compression decision into a permission grant covering every state-changing
|
|
14665
|
+
// command the allowlist accepts (`git push --force`, `kubectl delete`, `aws s3 rm`).
|
|
14666
|
+
// Whether the host applies updatedInput without a decision is its call; if it does
|
|
14667
|
+
// not, the command runs unwrapped and uncompressed, which is the safe direction.
|
|
14020
14668
|
const out = isGemini
|
|
14021
14669
|
? { hookSpecificOutput: { tool_input: { command: rewritten } } }
|
|
14022
|
-
: { hookSpecificOutput: { hookEventName: "PreToolUse",
|
|
14670
|
+
: { hookSpecificOutput: { hookEventName: "PreToolUse", updatedInput: { ...evt.tool_input, command: rewritten } } };
|
|
14023
14671
|
process.stdout.write(JSON.stringify(out));
|
|
14024
14672
|
}
|
|
14025
14673
|
const NATIVE_PROFILES = new Set([
|
|
@@ -14663,6 +15311,31 @@ async function nativeHook(argv) {
|
|
|
14663
15311
|
// Runtime startup is fail-open; host session and Core still proceed.
|
|
14664
15312
|
}
|
|
14665
15313
|
}
|
|
15314
|
+
// Codex's native config.toml bakes in the auth mode (subscription vs
|
|
15315
|
+
// api-key) at install time, but people run `codex login` afterwards all
|
|
15316
|
+
// the time, which flips it without touching config.toml. That leaves the
|
|
15317
|
+
// route stale until someone remembers to run `caveman doctor codex --fix`
|
|
15318
|
+
// by hand. Just do what that command would do, right here at session
|
|
15319
|
+
// start — but only for that specific drift. `degraded` also covers pack
|
|
15320
|
+
// version bumps, missing hooks, MCP recovery being down, etc., and none
|
|
15321
|
+
// of those should get a silent config rewrite just because Codex started;
|
|
15322
|
+
// those still surface through `caveman doctor codex` like normal.
|
|
15323
|
+
// Runs after the proxy revival above so the repair cannot race a
|
|
15324
|
+
// proxy this hook just spawned. The check is file-only on purpose:
|
|
15325
|
+
// nativeIntegrationStatus spawns `codex --version` and the proxy/MCP
|
|
15326
|
+
// probes, and this whole delegated SessionStart gets 3s. Codex has
|
|
15327
|
+
// already read config.toml by the time SessionStart fires, so the
|
|
15328
|
+
// repaired route takes effect from the next Codex launch.
|
|
15329
|
+
if (normalizedEvent === "SessionStart" && agent === "codex") {
|
|
15330
|
+
try {
|
|
15331
|
+
const route = readNativeJournal("codex")?.operations.find((operation) => operation.kind === "codex-config")?.owned?.route;
|
|
15332
|
+
if (typeof route === "string" && route !== codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription"))
|
|
15333
|
+
repairNativeAgent("codex");
|
|
15334
|
+
}
|
|
15335
|
+
catch {
|
|
15336
|
+
// Best-effort; a real problem still shows up in `caveman doctor codex`.
|
|
15337
|
+
}
|
|
15338
|
+
}
|
|
14666
15339
|
const runtimeRequest = sessionId && normalizedEvent !== "Unknown"
|
|
14667
15340
|
? nativeRuntimeRequest(agent, normalizedEvent, sessionId, event)
|
|
14668
15341
|
: undefined;
|
|
@@ -17573,7 +18246,7 @@ function readStdin() {
|
|
|
17573
18246
|
return;
|
|
17574
18247
|
}
|
|
17575
18248
|
const chunks = [];
|
|
17576
|
-
process.stdin.on("data", (chunk) => chunks.push(chunk));
|
|
18249
|
+
process.stdin.on("data", (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
|
|
17577
18250
|
process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
|
|
17578
18251
|
process.stdin.on("error", reject);
|
|
17579
18252
|
});
|
|
@@ -17979,6 +18652,9 @@ async function status(argv) {
|
|
|
17979
18652
|
if (refreshOffline())
|
|
17980
18653
|
states.push(fixedOffState("refresh-offline", OFF_STATES.refreshOffline));
|
|
17981
18654
|
const today = versionInfo ? readProxyObserveSummary(localMidnightRFC3339()) : null;
|
|
18655
|
+
const cavemanBusts = Number(today?.caveman_cache_bust_requests ?? 0);
|
|
18656
|
+
if (Number.isSafeInteger(cavemanBusts) && cavemanBusts > 0)
|
|
18657
|
+
states.push(OFF_STATES.cavemanCacheBust(cavemanBusts));
|
|
17982
18658
|
const runningMode = runtime.owner !== "unknown" && runtime.mode ? runtime.mode : null;
|
|
17983
18659
|
const resolvedMode = gate.mode;
|
|
17984
18660
|
const snapshot = readLearnSnapshot();
|
|
@@ -18041,6 +18717,8 @@ async function status(argv) {
|
|
|
18041
18717
|
const active = Object.entries(integration.capabilities).filter(([, value]) => value.active).map(([name]) => name);
|
|
18042
18718
|
process.stdout.write(statusRow(integration.agent, `${integration.state} · ${integration.version_status} · ${active.join(", ") || "proxy-only/none active"}`) + "\n");
|
|
18043
18719
|
}
|
|
18720
|
+
for (const warning of native.flatMap((integration) => integration.warnings))
|
|
18721
|
+
process.stdout.write(`${mark("warn")} ${warning}\n`);
|
|
18044
18722
|
const degraded = native.find((integration) => integration.state === "degraded");
|
|
18045
18723
|
const available = native.find((integration) => integration.state === "available" && integration.components.shared_runtime);
|
|
18046
18724
|
const needsRuntime = native.find((integration) => integration.state === "available" && !integration.components.shared_runtime);
|