@caveman-ai/cli 2.0.1 → 4.0.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 +18 -1
- package/dist/agent-skills.generated.js +3 -3
- package/dist/agents.generated.js +37 -27
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +74 -30
- package/dist/device-auth.generated.js +176 -0
- package/dist/home-acl.js +45 -0
- package/dist/index.js +3012 -587
- package/dist/learn-autopilot.js +2 -1
- package/dist/modules/apply.js +622 -0
- package/dist/modules/cloud.js +150 -0
- package/dist/modules/config-home.js +73 -0
- package/dist/modules/doctor.js +86 -0
- package/dist/modules/index-file.js +157 -0
- package/dist/modules/onboard.js +860 -0
- package/dist/modules/provider-logins.js +292 -0
- package/dist/modules/registry.js +96 -0
- package/dist/modules/status.js +71 -0
- package/dist/modules/stop.js +99 -0
- package/dist/native-hook-fast.js +15 -7
- package/dist/native-pipe.js +17 -0
- package/dist/portable-command.js +60 -16
- package/dist/portable-process.mjs +61 -11
- package/dist/provider-routing.js +11 -0
- package/dist/reserved-verbs.generated.js +3 -0
- package/dist/stats-cli.js +2 -0
- package/package.json +4 -4
package/dist/learn-autopilot.js
CHANGED
|
@@ -13,6 +13,7 @@ import { closeSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, st
|
|
|
13
13
|
import { homedir, setPriority } from "node:os";
|
|
14
14
|
import { dirname, join } from "node:path";
|
|
15
15
|
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { cloudConfigPath } from "./modules/config-home.js";
|
|
16
17
|
const ANNOUNCE_CLASSES = new Set(["reducible", "recurring_context"]);
|
|
17
18
|
const ANNOUNCE_MIN_TOKENS_PER_TURN = 2000;
|
|
18
19
|
// Doctor findings that break what the agent loads qualify with no token rate.
|
|
@@ -59,7 +60,7 @@ export function autopilotEnabled() {
|
|
|
59
60
|
if (env)
|
|
60
61
|
return { enabled: !["0", "false", "off", "no"].includes(env), source: "env" };
|
|
61
62
|
try {
|
|
62
|
-
const config = JSON.parse(readFileSync(
|
|
63
|
+
const config = JSON.parse(readFileSync(cloudConfigPath(), "utf8"));
|
|
63
64
|
if (typeof config.learnAutopilot === "boolean")
|
|
64
65
|
return { enabled: config.learnAutopilot, source: "config" };
|
|
65
66
|
}
|
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
// Switching modules on and off: the plan, the one confirmation, the apply.
|
|
2
|
+
//
|
|
3
|
+
// Module state is `modules.<id>` booleans in the global capability config
|
|
4
|
+
// (absent = the registry default, or off when a key the module owns is already
|
|
5
|
+
// off there). Switching a module writes its registry effects through the CLI's
|
|
6
|
+
// own config writer, and agent wiring reuses the native enable/disable/repair
|
|
7
|
+
// path and its journal. index.ts owns those primitives and hands them in once
|
|
8
|
+
// through setModuleHost, so nothing here is a second wiring path or a second
|
|
9
|
+
// config writer.
|
|
10
|
+
import { spawnSync } from "node:child_process";
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
import { join, sep } from "node:path";
|
|
14
|
+
import { portableInvocation } from "../portable-command.js";
|
|
15
|
+
import { cloudAnswer, cloudProduct, ROUTING_ON_LINE, routeState, routingPause } from "./cloud.js";
|
|
16
|
+
import { setupRan } from "./onboard.js";
|
|
17
|
+
import { findModule, MODULES } from "./registry.js";
|
|
18
|
+
import { moduleFix } from "./status.js";
|
|
19
|
+
let host;
|
|
20
|
+
export function setModuleHost(value) {
|
|
21
|
+
host = value;
|
|
22
|
+
}
|
|
23
|
+
export function moduleHost() {
|
|
24
|
+
if (!host)
|
|
25
|
+
throw new Error("module host not initialized");
|
|
26
|
+
return host;
|
|
27
|
+
}
|
|
28
|
+
function objectOf(value) {
|
|
29
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
30
|
+
}
|
|
31
|
+
function tilde(path) {
|
|
32
|
+
const home = homedir();
|
|
33
|
+
return path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path;
|
|
34
|
+
}
|
|
35
|
+
function storedModules() {
|
|
36
|
+
return objectOf(moduleHost().readConfig().modules);
|
|
37
|
+
}
|
|
38
|
+
function inScope(id, only) {
|
|
39
|
+
return !only || only.includes(id);
|
|
40
|
+
}
|
|
41
|
+
export function currentSelection() {
|
|
42
|
+
const h = moduleHost();
|
|
43
|
+
const stored = storedModules();
|
|
44
|
+
return Object.fromEntries(MODULES.map((m) => [
|
|
45
|
+
m.id,
|
|
46
|
+
typeof stored[m.id] === "boolean" ? stored[m.id]
|
|
47
|
+
// A config from before modules that already switched the module's primary
|
|
48
|
+
// key off reads as off. Only the first key counts: think.toon or
|
|
49
|
+
// think.shrink off alone is a tuning of input, not input off.
|
|
50
|
+
: m.capabilities.slice(0, 1).some((effect) => {
|
|
51
|
+
const capability = h.capability(effect.key);
|
|
52
|
+
return capability.invalid === undefined && capability.global === effect.off;
|
|
53
|
+
}) ? false
|
|
54
|
+
: m.defaultOn,
|
|
55
|
+
]));
|
|
56
|
+
}
|
|
57
|
+
// The agents `on` acts on: the ones already wired, or, before any is, every
|
|
58
|
+
// supported agent found on PATH that the user did not `caveman disable`.
|
|
59
|
+
export function defaultAgents() {
|
|
60
|
+
const native = moduleHost().nativeAgents();
|
|
61
|
+
const wired = native.filter((agent) => agent.wired);
|
|
62
|
+
return (wired.length ? wired : native.filter((agent) => agent.detected && !agent.optedOut)).map((agent) => agent.id);
|
|
63
|
+
}
|
|
64
|
+
// Module state is the authority for the keys a module owns, but only where
|
|
65
|
+
// the state moves: a module switched on or off (or whose primary key — its
|
|
66
|
+
// first capability, think.mode for input — contradicts its state) gets every
|
|
67
|
+
// key that disagrees rewritten to that state's value. A module that stays as
|
|
68
|
+
// it is keeps deliberate tuning (think.toon=false under input on). An invalid
|
|
69
|
+
// value is always rewritten. Only modules in scope are touched.
|
|
70
|
+
function configChanges(selection, only) {
|
|
71
|
+
const h = moduleHost();
|
|
72
|
+
const stored = storedModules();
|
|
73
|
+
const current = currentSelection();
|
|
74
|
+
const scoped = MODULES.filter((m) => inScope(m.id, only));
|
|
75
|
+
const state = scoped.filter((m) => stored[m.id] !== selection[m.id]).map((m) => [m.id, selection[m.id]]);
|
|
76
|
+
const effects = [];
|
|
77
|
+
const disagrees = (on, global, off) => on ? global === off : global !== off;
|
|
78
|
+
for (const m of scoped) {
|
|
79
|
+
const primary = m.capabilities[0];
|
|
80
|
+
const moving = current[m.id] !== selection[m.id]
|
|
81
|
+
|| (primary !== undefined && disagrees(selection[m.id], h.capability(primary.key).global, primary.off));
|
|
82
|
+
for (const effect of m.capabilities) {
|
|
83
|
+
const capability = h.capability(effect.key);
|
|
84
|
+
if ((moving && disagrees(selection[m.id], capability.global, effect.off)) || capability.invalid !== undefined) {
|
|
85
|
+
effects.push([effect.key, selection[m.id] ? effect.on : effect.off]);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return { state, effects };
|
|
90
|
+
}
|
|
91
|
+
// Agent wiring changes only when an agent-wired module is in scope. Switching
|
|
92
|
+
// one on wires the given agents that are not wired yet; the last one off
|
|
93
|
+
// unwires every agent. A full plan (no scope) also unwires agents outside
|
|
94
|
+
// `agents`.
|
|
95
|
+
function wiringChanges(selection, agents, only) {
|
|
96
|
+
const native = moduleHost().nativeAgents();
|
|
97
|
+
const wired = native.filter((agent) => agent.wired).map((agent) => agent.id);
|
|
98
|
+
const supported = agents.filter((agent) => native.some((info) => info.id === agent));
|
|
99
|
+
const none = { wire: [], unwire: [] };
|
|
100
|
+
if (!MODULES.some((m) => m.wiresAgents && inScope(m.id, only)))
|
|
101
|
+
return none;
|
|
102
|
+
if (!MODULES.some((m) => m.wiresAgents && selection[m.id]))
|
|
103
|
+
return { wire: [], unwire: wired };
|
|
104
|
+
const turningOn = MODULES.some((m) => m.wiresAgents && inScope(m.id, only) && selection[m.id]);
|
|
105
|
+
return {
|
|
106
|
+
wire: turningOn ? supported.filter((agent) => !wired.includes(agent)) : [],
|
|
107
|
+
unwire: only ? [] : wired.filter((agent) => !supported.includes(agent)),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
// Wired agents that stay wired but carry hooks built from a key this run
|
|
111
|
+
// changes, the Auto model the routing module adds or takes away, or a base
|
|
112
|
+
// URL that is no longer the traffic target (an earlier login's managed
|
|
113
|
+
// gateway), or a login that appeared since: any plan re-wires those, never
|
|
114
|
+
// anything else.
|
|
115
|
+
function refreshAgents(effects, unwire, state) {
|
|
116
|
+
const h = moduleHost();
|
|
117
|
+
const keyChanged = effects.some(([key]) => h.wiringKeys.includes(key)) || state.some(([id]) => id === "routing");
|
|
118
|
+
return h.nativeAgents()
|
|
119
|
+
.filter((agent) => agent.wired && !unwire.includes(agent.id) && (keyChanged || h.agentStaleRoute(agent.id) || h.agentIncomplete(agent.id)))
|
|
120
|
+
.map((agent) => agent.id);
|
|
121
|
+
}
|
|
122
|
+
// Modules in scope that are on and miss a binary they need. An external
|
|
123
|
+
// binary is missing when no usable copy resolves, unless an override names
|
|
124
|
+
// one: a download would not be the copy used then. A hub binary an older
|
|
125
|
+
// release installed counts as missing too: a CLI upgrade leaves it in place.
|
|
126
|
+
function binaryNeeds(selection, only) {
|
|
127
|
+
const h = moduleHost();
|
|
128
|
+
const on = MODULES.filter((m) => selection[m.id] && inScope(m.id, only));
|
|
129
|
+
const behind = h.binariesBehindPin();
|
|
130
|
+
const missingOf = (m) => [
|
|
131
|
+
...m.binaries.filter((name) => !h.resolveBinary(name) || behind.includes(name)),
|
|
132
|
+
...(m.external && !externalOverride(m) && !externalBin(m) ? [m.external.binary] : []),
|
|
133
|
+
];
|
|
134
|
+
const missing = [...new Set(on.flatMap(missingOf))];
|
|
135
|
+
return { missing, modules: on.filter((m) => missingOf(m).length).map((m) => m.id) };
|
|
136
|
+
}
|
|
137
|
+
function externalOverride(def) {
|
|
138
|
+
return process.env[`${def.external.binary.toUpperCase().replace(/-/g, "_")}_BIN`] || undefined;
|
|
139
|
+
}
|
|
140
|
+
// Blocks reports this from `version --json` once it can answer
|
|
141
|
+
// `hooks status --json` (rc.2).
|
|
142
|
+
const STATUS_JSON = "hooks_status_json";
|
|
143
|
+
const answersJson = new Map();
|
|
144
|
+
function reportsStatusJson(bin) {
|
|
145
|
+
let known = answersJson.get(bin);
|
|
146
|
+
if (known === undefined) {
|
|
147
|
+
try {
|
|
148
|
+
const out = runExternal(bin, ["version", "--json"], 5000);
|
|
149
|
+
const capabilities = JSON.parse(out.stdout).capabilities;
|
|
150
|
+
known = out.status === 0 && Array.isArray(capabilities) && capabilities.includes(STATUS_JSON);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
known = false;
|
|
154
|
+
}
|
|
155
|
+
answersJson.set(bin, known);
|
|
156
|
+
}
|
|
157
|
+
return known;
|
|
158
|
+
}
|
|
159
|
+
// The external binary the hub runs: the override, the copy the hub installed
|
|
160
|
+
// (recorded in modules.lock.json), or one on PATH new enough to report its
|
|
161
|
+
// hooks as JSON. A user's own current Blocks stays usable; an older one is
|
|
162
|
+
// passed over for the signed download.
|
|
163
|
+
function externalBin(def) {
|
|
164
|
+
const name = def.external.binary;
|
|
165
|
+
const explicit = externalOverride(def);
|
|
166
|
+
if (explicit)
|
|
167
|
+
return existsSync(explicit) ? explicit : null;
|
|
168
|
+
const local = join(process.env.CAVEMAN_HOME ?? join(homedir(), ".caveman"), "bin", process.platform === "win32" ? `${name}.exe` : name);
|
|
169
|
+
if (moduleHost().lockedBinaries(def.id).includes(name) && existsSync(local))
|
|
170
|
+
return local;
|
|
171
|
+
const onPath = moduleHost().which(name);
|
|
172
|
+
return onPath && reportsStatusJson(onPath) ? onPath : null;
|
|
173
|
+
}
|
|
174
|
+
// Why an external module cannot run: no binary, or the copy that resolves (or
|
|
175
|
+
// the only one on PATH) cannot report its hooks. Undefined when it can.
|
|
176
|
+
function externalProblem(def, bin, status) {
|
|
177
|
+
if (bin && status)
|
|
178
|
+
return undefined;
|
|
179
|
+
const old = bin ?? (externalOverride(def) ? null : moduleHost().which(def.external.binary));
|
|
180
|
+
return old ? `${tilde(old)} is older than Blocks rc.2 · update or remove it` : `${def.external.binary} not installed`;
|
|
181
|
+
}
|
|
182
|
+
// Output is captured: the hub says one line per step, and shows the binary's
|
|
183
|
+
// own output only when the step fails.
|
|
184
|
+
function runExternal(bin, args, timeout) {
|
|
185
|
+
const invocation = portableInvocation(bin, args);
|
|
186
|
+
return spawnSync(invocation.command, invocation.args, { encoding: "utf8", timeout, stdio: ["ignore", "pipe", "pipe"] });
|
|
187
|
+
}
|
|
188
|
+
// Harness name → hook installed, from `<binary> hooks status --json`
|
|
189
|
+
// ({ harnesses: [{ name, installed }] }). Undefined when the binary cannot say.
|
|
190
|
+
function externalStatus(def, bin, flags = []) {
|
|
191
|
+
try {
|
|
192
|
+
const out = runExternal(bin, [...def.external.status, ...flags], 5000);
|
|
193
|
+
const parsed = JSON.parse(out.stdout);
|
|
194
|
+
if (out.status !== 0 || !Array.isArray(parsed.harnesses))
|
|
195
|
+
return undefined;
|
|
196
|
+
return Object.fromEntries(parsed.harnesses.filter((h) => typeof h.name === "string").map((h) => [h.name, h.installed === true]));
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
return undefined;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
// Blocks' harness names for the agents the hub wires; it hooks no others.
|
|
203
|
+
const EXTERNAL_HARNESSES = { claude: "claude-code", codex: "codex", opencode: "opencode" };
|
|
204
|
+
const harnessFlags = (agents) => agents.flatMap((agent) => EXTERNAL_HARNESSES[agent] ? ["--harness", EXTERNAL_HARNESSES[agent]] : []);
|
|
205
|
+
// The install/uninstall an external module needs, for the selected agents
|
|
206
|
+
// only. It is in scope when named, and also when it is on and this run wires
|
|
207
|
+
// an agent, so a new agent gets its hook in the same run. Install runs when a
|
|
208
|
+
// selected agent's hook is missing or, without a status answer, when the
|
|
209
|
+
// module is first recorded on. Uninstall runs only when the hub had it
|
|
210
|
+
// recorded on, so hooks installed with Blocks' own installer stay. `bin` is
|
|
211
|
+
// null when no usable binary resolves; the run is then skipped. `before` is
|
|
212
|
+
// the status ahead of the run.
|
|
213
|
+
function externalRuns(selection, only, agents, wiring) {
|
|
214
|
+
const stored = storedModules();
|
|
215
|
+
const runs = [];
|
|
216
|
+
for (const def of MODULES) {
|
|
217
|
+
if (!def.external || !(inScope(def.id, only) || (selection[def.id] && wiring)))
|
|
218
|
+
continue;
|
|
219
|
+
const bin = externalBin(def);
|
|
220
|
+
if (!inScope(def.id, only) && !bin)
|
|
221
|
+
continue;
|
|
222
|
+
if (selection[def.id]) {
|
|
223
|
+
const flags = harnessFlags(agents);
|
|
224
|
+
if (flags.length === 0)
|
|
225
|
+
continue;
|
|
226
|
+
const before = bin ? externalStatus(def, bin, flags) : undefined;
|
|
227
|
+
const needed = before ? Object.values(before).some((installed) => !installed) : stored[def.id] !== true;
|
|
228
|
+
if (needed)
|
|
229
|
+
runs.push({ def, args: def.external.install, install: true, bin, flags, before });
|
|
230
|
+
}
|
|
231
|
+
else if (stored[def.id] === true && bin) {
|
|
232
|
+
runs.push({ def, args: def.external.uninstall, install: false, bin, flags: harnessFlags(Object.keys(EXTERNAL_HARNESSES)) });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return runs;
|
|
236
|
+
}
|
|
237
|
+
// The hub's name for a Blocks harness.
|
|
238
|
+
function harnessName(name) {
|
|
239
|
+
const agent = Object.keys(EXTERNAL_HARNESSES).find((id) => EXTERNAL_HARNESSES[id] === name);
|
|
240
|
+
return agent ? moduleHost().agentName(agent) : name;
|
|
241
|
+
}
|
|
242
|
+
// What a harness's new hook still asks of the user, from Blocks' trust notes;
|
|
243
|
+
// notes that ask nothing are left out.
|
|
244
|
+
const EXTERNAL_ASKS = {
|
|
245
|
+
codex: "Codex asks once: open /hooks in Codex and approve the caveman-blocks hook",
|
|
246
|
+
};
|
|
247
|
+
// One line for a finished install, built from the status it leaves, then one
|
|
248
|
+
// line per new hook the user still has to approve.
|
|
249
|
+
function externalReady(def, bin, flags, before) {
|
|
250
|
+
const after = externalStatus(def, bin, flags);
|
|
251
|
+
if (!after)
|
|
252
|
+
return [`○ ${def.id}: ${externalProblem(def, bin, after)}`];
|
|
253
|
+
const hooked = Object.keys(after).filter((name) => after[name]);
|
|
254
|
+
if (hooked.length === 0)
|
|
255
|
+
return [`○ ${def.id}: no agent to hook yet`];
|
|
256
|
+
return [
|
|
257
|
+
`✓ ${def.id} ready (${hooked.map(harnessName).join(", ")})`,
|
|
258
|
+
...hooked.filter((name) => !before?.[name] && EXTERNAL_ASKS[name]).map((name) => ` ${EXTERNAL_ASKS[name]}`),
|
|
259
|
+
];
|
|
260
|
+
}
|
|
261
|
+
export async function planModules(selection, agents, options = {}) {
|
|
262
|
+
const h = moduleHost();
|
|
263
|
+
const { only } = options;
|
|
264
|
+
const lines = [];
|
|
265
|
+
const notes = [];
|
|
266
|
+
const { state, effects } = configChanges(selection, only);
|
|
267
|
+
const { wire, unwire } = wiringChanges(selection, agents, only);
|
|
268
|
+
const { missing } = binaryNeeds(selection, only);
|
|
269
|
+
// Hub binaries ship in every release; an external one (Blocks) only in a
|
|
270
|
+
// release whose signed modules.json carries it, so the plan says so.
|
|
271
|
+
const externals = new Set(MODULES.flatMap((m) => (m.external ? [m.external.binary] : [])));
|
|
272
|
+
const hubMissing = missing.filter((name) => !externals.has(name));
|
|
273
|
+
const externalMissing = missing.filter((name) => externals.has(name));
|
|
274
|
+
if (hubMissing.length)
|
|
275
|
+
lines.push({ action: "DOWNLOAD", target: hubMissing.join(", "), detail: `signed, ${h.binaryRelease}` });
|
|
276
|
+
if (externalMissing.length)
|
|
277
|
+
lines.push({ action: "DOWNLOAD", target: externalMissing.join(", "), detail: `signed, if ${h.binaryRelease} carries it` });
|
|
278
|
+
if (state.length || effects.length) {
|
|
279
|
+
lines.push({
|
|
280
|
+
action: existsSync(h.configPath()) ? "UPDATE" : "CREATE",
|
|
281
|
+
target: tilde(h.configPath()),
|
|
282
|
+
detail: [
|
|
283
|
+
...[true, false].map((on) => [on, state.filter(([, value]) => value === on).map(([id]) => id)])
|
|
284
|
+
.filter(([, ids]) => ids.length).map(([on, ids]) => `modules ${on ? "on" : "off"}: ${ids.join(", ")}`),
|
|
285
|
+
...effects.map(([key, value]) => `${key} = ${value}`),
|
|
286
|
+
].join(" · "),
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
for (const agent of unwire) {
|
|
290
|
+
for (const file of h.wiredFiles(agent))
|
|
291
|
+
lines.push({ action: "UPDATE", target: tilde(file), detail: `remove ${agent} wiring` });
|
|
292
|
+
}
|
|
293
|
+
for (const agent of wire) {
|
|
294
|
+
try {
|
|
295
|
+
for (const file of h.planWiring(agent)) {
|
|
296
|
+
lines.push({ action: file.exists ? "UPDATE" : "CREATE", target: tilde(file.file), detail: file.kind.replace("-", " ") });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
// An agent on its own endpoint is left as is. The plan says so in short;
|
|
301
|
+
// the step's result says why and how to route it anyway, once.
|
|
302
|
+
const own = error.ownEndpoint;
|
|
303
|
+
if (own) {
|
|
304
|
+
notes.push(`${h.agentName(agent)} stays as is: it sends its requests to its own endpoint ${own}`);
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
// The binaries the plan downloads first are what this needs; enable
|
|
308
|
+
// reports any real refusal when it runs.
|
|
309
|
+
lines.push({ action: "UPDATE", target: `${agent} config`, detail: "route + hooks" });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
const target = h.agentTraffic().target === "local" ? "the local runtime" : "the managed gateway";
|
|
313
|
+
for (const agent of refreshAgents(effects, unwire, state)) {
|
|
314
|
+
const was = h.agentStaleRoute(agent);
|
|
315
|
+
const detail = was ? `point ${agent} at ${target} (was ${was})` : h.agentIncomplete(agent) ? `wire the new ${agent} login` : `refresh ${agent} hooks`;
|
|
316
|
+
const wired = h.wiredFiles(agent);
|
|
317
|
+
for (const file of wired)
|
|
318
|
+
lines.push({ action: "UPDATE", target: tilde(file), detail });
|
|
319
|
+
// A login that appeared since brings files the journal does not hold yet.
|
|
320
|
+
if (h.agentIncomplete(agent)) {
|
|
321
|
+
try {
|
|
322
|
+
for (const file of h.planWiring(agent)) {
|
|
323
|
+
if (!wired.includes(file.file))
|
|
324
|
+
lines.push({ action: file.exists ? "UPDATE" : "CREATE", target: tilde(file.file), detail });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
catch { /* repair reports a real refusal when it runs */ }
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
// aider is wired without the runtime; every other agent starts it.
|
|
331
|
+
if (wire.some((agent) => agent !== "aider") && await h.runtimeAutostarts()) {
|
|
332
|
+
lines.push({ action: "RUN", target: "caveman-proxy", detail: "start local runtime" });
|
|
333
|
+
}
|
|
334
|
+
for (const run of externalRuns(selection, only, agents, wire.length > 0)) {
|
|
335
|
+
const name = run.def.external.binary;
|
|
336
|
+
// A binary the plan downloads first is not a skip.
|
|
337
|
+
const skipped = !run.bin && !missing.includes(name);
|
|
338
|
+
const names = [...new Set(run.flags.filter((flag) => flag !== "--harness").map(harnessName))];
|
|
339
|
+
lines.push({ action: "RUN", target: `${name} ${run.args.join(" ")}`, detail: skipped ? `skipped: ${externalProblem(run.def, null, undefined)}` : run.install ? names.join(", ") : "" });
|
|
340
|
+
}
|
|
341
|
+
for (const def of MODULES) {
|
|
342
|
+
if (def.external && selection[def.id] && inScope(def.id, only) && agents.length && harnessFlags(agents).length === 0) {
|
|
343
|
+
notes.push(`${def.id} stays idle: none of the selected agents takes its hook (${Object.keys(EXTERNAL_HARNESSES).map((agent) => h.agentName(agent)).join(", ")})`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// Core is withheld in record mode, which is what input switched off means.
|
|
347
|
+
if (selection.output && !selection.input && currentSelection().input && inScope("input", only)) {
|
|
348
|
+
notes.push("output also pauses: it runs through input");
|
|
349
|
+
}
|
|
350
|
+
return { selection: { ...selection }, agents: [...agents], lines, ...(only ? { only: [...only] } : {}), ...(notes.length ? { notes } : {}) };
|
|
351
|
+
}
|
|
352
|
+
// Every door that wires an agent, or points one at the local runtime, runs this
|
|
353
|
+
// first: never to a port another program answers on (runtimePortTaken).
|
|
354
|
+
export async function claimRuntimePort(say = (line) => process.stderr.write(`${line}\n`)) {
|
|
355
|
+
const h = moduleHost();
|
|
356
|
+
const moved = await h.runtimePortTaken();
|
|
357
|
+
if (!moved)
|
|
358
|
+
return;
|
|
359
|
+
h.useRuntimePort(moved.free);
|
|
360
|
+
say(`○ ${moved.held} is in use by another program · local runtime on port ${moved.free}`);
|
|
361
|
+
}
|
|
362
|
+
// `progress` gets one line per step as it completes ("✓ Claude Code wired");
|
|
363
|
+
// failures come back in `problems` with their full message.
|
|
364
|
+
export async function applyModules(plan, opts) {
|
|
365
|
+
const h = moduleHost();
|
|
366
|
+
if (plan.lines.length === 0)
|
|
367
|
+
return { ok: true, problems: [] };
|
|
368
|
+
if (!opts.yes) {
|
|
369
|
+
if (!h.interactive())
|
|
370
|
+
return { ok: false, problems: ["nothing changed: pass --yes to apply without a prompt"] };
|
|
371
|
+
if (!(await h.confirm("Continue? [y/N]")))
|
|
372
|
+
return { ok: false, problems: ["nothing changed"] };
|
|
373
|
+
}
|
|
374
|
+
const problems = [];
|
|
375
|
+
const fail = (what, error) => problems.push(`${what}: ${error instanceof Error ? error.message : String(error)}`);
|
|
376
|
+
const say = opts.progress ?? (() => { });
|
|
377
|
+
const needs = binaryNeeds(plan.selection, plan.only);
|
|
378
|
+
if (needs.missing.length) {
|
|
379
|
+
try {
|
|
380
|
+
for (const note of await h.installBinaries(needs.modules, opts.downloading))
|
|
381
|
+
say(`○ ${note}`);
|
|
382
|
+
// A release from before modules.json brings no external binary.
|
|
383
|
+
const still = binaryNeeds(plan.selection, plan.only).missing;
|
|
384
|
+
const got = needs.missing.filter((name) => !still.includes(name));
|
|
385
|
+
if (got.length)
|
|
386
|
+
say(`✓ downloaded ${got.join(", ")}`);
|
|
387
|
+
}
|
|
388
|
+
catch (error) {
|
|
389
|
+
fail("download", error);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
// Decide everything before the first config write: the external uninstall
|
|
393
|
+
// reads the module state this run replaces.
|
|
394
|
+
const { state, effects } = configChanges(plan.selection, plan.only);
|
|
395
|
+
const { wire, unwire } = wiringChanges(plan.selection, plan.agents, plan.only);
|
|
396
|
+
const refresh = refreshAgents(effects, unwire, state);
|
|
397
|
+
if (wire.some((agent) => agent !== "aider") || refresh.some((agent) => h.agentStaleRoute(agent)))
|
|
398
|
+
await claimRuntimePort(say);
|
|
399
|
+
const runs = externalRuns(plan.selection, plan.only, plan.agents, wire.length > 0);
|
|
400
|
+
const startsRuntime = wire.some((agent) => agent !== "aider") && await h.runtimeAutostarts();
|
|
401
|
+
const step = (agent, done, act) => {
|
|
402
|
+
try {
|
|
403
|
+
act();
|
|
404
|
+
say(`✓ ${h.agentName(agent)} ${done}`);
|
|
405
|
+
return true;
|
|
406
|
+
}
|
|
407
|
+
catch (error) {
|
|
408
|
+
// An agent on its own endpoint is left as is: a note, not a failure.
|
|
409
|
+
if (error.ownEndpoint) {
|
|
410
|
+
say(`○ ${error.message}`);
|
|
411
|
+
return true;
|
|
412
|
+
}
|
|
413
|
+
fail(agent, error);
|
|
414
|
+
return false;
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
// Unwiring reads no config, so it goes first. When the last agent-wired
|
|
418
|
+
// module goes off and an agent stays wired, the modules this run switched
|
|
419
|
+
// off keep their state and keys: status must not say off over a wired
|
|
420
|
+
// agent, and running off again retries the unwire. A config the writes
|
|
421
|
+
// would refuse (broken JSON) stops the run here, before any agent changes.
|
|
422
|
+
if (state.length || effects.length)
|
|
423
|
+
h.mutateConfig(() => { });
|
|
424
|
+
const wasOn = currentSelection();
|
|
425
|
+
const stuck = unwire.filter((agent) => !step(agent, "unwired", () => h.unwireAgent(agent)));
|
|
426
|
+
const kept = stuck.length && !MODULES.some((m) => m.wiresAgents && plan.selection[m.id])
|
|
427
|
+
? MODULES.filter((m) => m.wiresAgents && wasOn[m.id]) : [];
|
|
428
|
+
if (kept.length) {
|
|
429
|
+
const ids = kept.map((m) => m.id);
|
|
430
|
+
const list = (items) => new Intl.ListFormat("en").format(items);
|
|
431
|
+
problems.push(`${list(ids)} stay${ids.length > 1 ? "" : "s"} on while ${list(stuck.map((agent) => h.agentName(agent)))} ${stuck.length > 1 ? "are" : "is"} still wired; fix the problem above, then run this again`);
|
|
432
|
+
}
|
|
433
|
+
const recorded = state.filter(([id]) => !kept.some((m) => m.id === id));
|
|
434
|
+
if (recorded.length)
|
|
435
|
+
h.mutateConfig((out) => { out.modules = { ...objectOf(out.modules), ...Object.fromEntries(recorded) }; });
|
|
436
|
+
// Effects land before wiring: enable and repair read think.shrink for hooks.
|
|
437
|
+
for (const [key, value] of effects)
|
|
438
|
+
if (!kept.some((m) => m.capabilities.some((effect) => effect.key === key)))
|
|
439
|
+
h.setConfigValue(key, value);
|
|
440
|
+
for (const agent of wire)
|
|
441
|
+
step(agent, "wired", () => h.wireAgent(agent));
|
|
442
|
+
const target = h.agentTraffic().target === "local" ? "local runtime" : "managed gateway";
|
|
443
|
+
for (const agent of refresh)
|
|
444
|
+
step(agent, h.agentStaleRoute(agent) ? `routing: ${target}` : "hooks refreshed", () => h.refreshAgent(agent));
|
|
445
|
+
if (startsRuntime) {
|
|
446
|
+
say(await h.runtimeListening(1000) ? "✓ local runtime started" : "○ local runtime starts with your next agent session");
|
|
447
|
+
}
|
|
448
|
+
for (const run of runs) {
|
|
449
|
+
const name = run.def.external.binary;
|
|
450
|
+
// Absent binary: the module stays on but inactive, and the verb says why.
|
|
451
|
+
if (!run.bin) {
|
|
452
|
+
const why = externalProblem(run.def, null, undefined);
|
|
453
|
+
say(`○ ${run.def.id}: ${why.endsWith(" not installed") ? `${why} yet` : why}`);
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
const out = runExternal(run.bin, [...run.args, ...run.flags], 120_000);
|
|
457
|
+
const output = `${out.stdout ?? ""}${out.stderr ?? ""}`.trim();
|
|
458
|
+
if (out.status !== 0)
|
|
459
|
+
problems.push(`${name} ${run.args.join(" ")} failed${out.error ? `: ${out.error.message}` : ""}${output ? `\n${output}` : ""}`);
|
|
460
|
+
else if (run.install)
|
|
461
|
+
for (const line of externalReady(run.def, run.bin, run.flags, run.before))
|
|
462
|
+
say(line);
|
|
463
|
+
else
|
|
464
|
+
say(`✓ ${run.def.id}: ${name} ${run.args.join(" ")}`);
|
|
465
|
+
}
|
|
466
|
+
for (const agent of wire) {
|
|
467
|
+
const ask = h.agentAsk(agent);
|
|
468
|
+
if (ask)
|
|
469
|
+
say(`○ ${ask}`);
|
|
470
|
+
}
|
|
471
|
+
return { ok: problems.length === 0, problems };
|
|
472
|
+
}
|
|
473
|
+
function externalAgentState(status, agent) {
|
|
474
|
+
const harness = EXTERNAL_HARNESSES[agent];
|
|
475
|
+
const installed = harness === undefined ? undefined : status?.[harness];
|
|
476
|
+
return installed === undefined ? "n/a" : installed ? "wired" : "not wired";
|
|
477
|
+
}
|
|
478
|
+
// Env variables resolveCapabilities (index.ts) reads for the keys modules own.
|
|
479
|
+
const ENV_NAMES = {
|
|
480
|
+
"think.mode": "CAVEMAN_WRAP_MODE",
|
|
481
|
+
"think.core": "CAVEMAN_CORE",
|
|
482
|
+
"think.toon": "CAVEMAN_TOON",
|
|
483
|
+
"think.shrink": "CAVEMAN_SHRINK",
|
|
484
|
+
};
|
|
485
|
+
// A sign-in module is active once Cloud answers for the signed-in account;
|
|
486
|
+
// a /me without the product's fields still counts as an answer.
|
|
487
|
+
function inactiveReason(m, selection, signedIn, external, cloud) {
|
|
488
|
+
const h = moduleHost();
|
|
489
|
+
if (m.needsSignIn) {
|
|
490
|
+
if (!signedIn)
|
|
491
|
+
return `sign in to turn on ${m.id}`;
|
|
492
|
+
// caveman-proxy acts only on an explicit switch: signing in alone never
|
|
493
|
+
// starts a Cloud feature (a config from before modules has none).
|
|
494
|
+
if (storedModules()[m.id] !== true)
|
|
495
|
+
return `${m.id} not switched on in config`;
|
|
496
|
+
if (cloud?.status === 401)
|
|
497
|
+
return "login expired";
|
|
498
|
+
const me = cloud?.me ?? null;
|
|
499
|
+
const product = cloudProduct(me, m.id);
|
|
500
|
+
if (!me || product?.state === "off")
|
|
501
|
+
return `waiting for Cloud ${m.id}`;
|
|
502
|
+
const pause = m.id === "routing" ? routingPause(product) : product?.state === "limited" ? product : undefined;
|
|
503
|
+
if (pause)
|
|
504
|
+
return `${m.id} paused · ${(pause.reason ?? "limit").replace(/_/g, " ")}`;
|
|
505
|
+
// caveman-proxy was refused the key (one minted before it could route,
|
|
506
|
+
// or revoked); a new login mints one.
|
|
507
|
+
if (m.id === "routing" && routeState()?.outcome === "degraded")
|
|
508
|
+
return `${m.id} degraded · Cloud refused this login's key`;
|
|
509
|
+
}
|
|
510
|
+
const blocked = m.external && external ? externalProblem(m, external.bin, external.status) : undefined;
|
|
511
|
+
if (blocked)
|
|
512
|
+
return blocked;
|
|
513
|
+
const missing = m.binaries.filter((name) => !h.resolveBinary(name));
|
|
514
|
+
if (missing.length)
|
|
515
|
+
return `${missing.join(", ")} not installed`;
|
|
516
|
+
for (const effect of m.capabilities) {
|
|
517
|
+
const capability = h.capability(effect.key);
|
|
518
|
+
if (capability.invalid !== undefined)
|
|
519
|
+
return `${effect.key} has an invalid value: ${capability.invalid}`;
|
|
520
|
+
if (capability.value === effect.off && capability.source === "project")
|
|
521
|
+
return "overridden by project config";
|
|
522
|
+
if (capability.value === effect.off && capability.source === "env")
|
|
523
|
+
return `overridden by ${ENV_NAMES[effect.key] ?? "the environment"}`;
|
|
524
|
+
if (capability.global === effect.off)
|
|
525
|
+
return `${effect.key} is ${effect.off} in config`;
|
|
526
|
+
}
|
|
527
|
+
if (m.id === "output" && !h.coreActive())
|
|
528
|
+
return selection.input ? "record mode keeps it off" : "paused while input is off";
|
|
529
|
+
return undefined;
|
|
530
|
+
}
|
|
531
|
+
export async function moduleStates() {
|
|
532
|
+
const h = moduleHost();
|
|
533
|
+
const selection = currentSelection();
|
|
534
|
+
const stored = storedModules();
|
|
535
|
+
const setUp = setupRan();
|
|
536
|
+
const agents = h.nativeAgents().filter((agent) => agent.detected || agent.wired);
|
|
537
|
+
const signedIn = h.signedIn();
|
|
538
|
+
const cloud = signedIn && MODULES.some((m) => m.needsSignIn && selection[m.id]) ? await cloudAnswer() : null;
|
|
539
|
+
return MODULES.map((m) => {
|
|
540
|
+
const on = selection[m.id];
|
|
541
|
+
const bin = on && m.external ? externalBin(m) : null;
|
|
542
|
+
const status = m.external && bin ? externalStatus(m, bin) : undefined;
|
|
543
|
+
const why = on ? inactiveReason(m, selection, signedIn, { bin, status }, cloud) : undefined;
|
|
544
|
+
// Before the first setup, a module that acts only once setup records it
|
|
545
|
+
// on (Cloud routing, Blocks' hooks) is not set up yet rather than broken.
|
|
546
|
+
const reason = why && !setUp && (m.needsSignIn || m.external) && typeof stored[m.id] !== "boolean" ? "not set up" : why;
|
|
547
|
+
const perAgent = Object.fromEntries(agents.map((agent) => [
|
|
548
|
+
agent.id,
|
|
549
|
+
m.wiresAgents ? agent.wired ? "wired" : "not wired" : externalAgentState(status, agent.id),
|
|
550
|
+
]));
|
|
551
|
+
return { id: m.id, on, active: on && !reason, ...(reason ? { reason } : {}), perAgent };
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
export function renderPlan(plan) {
|
|
555
|
+
const width = Math.min(32, Math.max(...plan.lines.map((line) => line.target.length)));
|
|
556
|
+
const lines = plan.lines.map((line) => ` ${line.action.padEnd(9)} ${line.target.padEnd(width)} ${line.detail}`.trimEnd());
|
|
557
|
+
return `This will\n${[...lines, ...(plan.notes ?? []).map((note) => `note: ${note}`)].join("\n")}\n`;
|
|
558
|
+
}
|
|
559
|
+
export async function moduleSwitchCommand(on, argv) {
|
|
560
|
+
const verb = on ? "on" : "off";
|
|
561
|
+
const flags = argv.filter((arg) => arg.startsWith("-"));
|
|
562
|
+
const names = argv.filter((arg) => !arg.startsWith("-"));
|
|
563
|
+
const all = flags.includes("--all");
|
|
564
|
+
const ids = MODULES.map((m) => m.id).join(", ");
|
|
565
|
+
const badFlag = flags.some((flag) => !["--all", "--yes", "-y", "--dry-run"].includes(flag));
|
|
566
|
+
// Exactly one of: module names, or --all.
|
|
567
|
+
const badTargets = all ? names.length > 0 : names.length === 0;
|
|
568
|
+
if (badFlag || badTargets) {
|
|
569
|
+
console.error(`usage: caveman ${verb} <module…> | --all [--yes] [--dry-run]\nmodules: ${ids}`);
|
|
570
|
+
process.exit(2);
|
|
571
|
+
}
|
|
572
|
+
const unknown = names.filter((name) => !findModule(name));
|
|
573
|
+
if (unknown.length) {
|
|
574
|
+
console.error(`unknown module: ${unknown.join(", ")} · modules: ${ids}`);
|
|
575
|
+
process.exit(2);
|
|
576
|
+
}
|
|
577
|
+
const named = MODULES.filter((m) => all || names.includes(m.id)).map((m) => m.id);
|
|
578
|
+
const selection = currentSelection();
|
|
579
|
+
for (const id of named)
|
|
580
|
+
selection[id] = on;
|
|
581
|
+
// `off` never wires an agent that is not wired yet.
|
|
582
|
+
const agents = on ? defaultAgents() : moduleHost().nativeAgents().filter((agent) => agent.wired).map((agent) => agent.id);
|
|
583
|
+
const plan = await planModules(selection, agents, all ? {} : { only: named });
|
|
584
|
+
const label = all ? "every module" : named.join(", ");
|
|
585
|
+
if (plan.lines.length === 0) {
|
|
586
|
+
console.log(`✓ ${label} already ${verb}`);
|
|
587
|
+
if (on)
|
|
588
|
+
await signInFor(named);
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
process.stdout.write(renderPlan(plan));
|
|
592
|
+
if (flags.includes("--dry-run"))
|
|
593
|
+
return;
|
|
594
|
+
const result = await applyModules(plan, { yes: flags.includes("--yes") || flags.includes("-y"), progress: (line) => console.log(line) });
|
|
595
|
+
if (!result.ok) {
|
|
596
|
+
for (const problem of result.problems)
|
|
597
|
+
console.error(`✗ ${problem}`);
|
|
598
|
+
process.exitCode = 1;
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
if (on)
|
|
602
|
+
await signInFor(named);
|
|
603
|
+
for (const state of (await moduleStates()).filter((item) => named.includes(item.id))) {
|
|
604
|
+
const fix = moduleFix(state);
|
|
605
|
+
const why = state.on && !state.active ? ` · ${state.reason}${fix ? ` · ${fix}` : ""}` : "";
|
|
606
|
+
console.log(`✓ ${state.id} ${verb}${why}`);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
// `on routing` signs in when it needs to, in a terminal only; login then says
|
|
610
|
+
// what routing does now and what data leaves the machine. Already signed in,
|
|
611
|
+
// it says what routing sends here.
|
|
612
|
+
async function signInFor(named) {
|
|
613
|
+
const h = moduleHost();
|
|
614
|
+
if (!named.some((id) => findModule(id)?.needsSignIn))
|
|
615
|
+
return;
|
|
616
|
+
if (h.signedIn()) {
|
|
617
|
+
if (named.includes("routing"))
|
|
618
|
+
console.log(ROUTING_ON_LINE);
|
|
619
|
+
}
|
|
620
|
+
else if (h.interactive())
|
|
621
|
+
await h.signIn();
|
|
622
|
+
}
|