@atbash/cli 0.5.15-dev.17 → 0.5.15-dev.18

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.
Files changed (37) hide show
  1. package/README.md +6 -55
  2. package/dist/bin/atbash.js +1 -4
  3. package/dist/bin/atbash.js.map +1 -1
  4. package/dist/commands/connect.d.ts +24 -84
  5. package/dist/commands/connect.js +73 -289
  6. package/dist/commands/connect.js.map +1 -1
  7. package/dist/commands/held.js +4 -0
  8. package/dist/commands/held.js.map +1 -1
  9. package/dist/commands/history.js +2 -0
  10. package/dist/commands/history.js.map +1 -1
  11. package/dist/commands/judge.js +1 -0
  12. package/dist/commands/judge.js.map +1 -1
  13. package/dist/commands/policy.js +2 -0
  14. package/dist/commands/policy.js.map +1 -1
  15. package/dist/commands/setup.d.ts +8 -390
  16. package/dist/commands/setup.js +167 -1871
  17. package/dist/commands/setup.js.map +1 -1
  18. package/dist/commands/stats.js +1 -0
  19. package/dist/commands/stats.js.map +1 -1
  20. package/dist/commands/status.js +2 -0
  21. package/dist/commands/status.js.map +1 -1
  22. package/dist/commands/tier.js +2 -0
  23. package/dist/commands/tier.js.map +1 -1
  24. package/dist/commands/tools.js +7 -1
  25. package/dist/commands/tools.js.map +1 -1
  26. package/dist/commands/whoami.js +2 -0
  27. package/dist/commands/whoami.js.map +1 -1
  28. package/package.json +2 -3
  29. package/dist/commands/mcp-cmd.d.ts +0 -13
  30. package/dist/commands/mcp-cmd.js +0 -216
  31. package/dist/commands/mcp-cmd.js.map +0 -1
  32. package/dist/shared/atbash-targets.d.ts +0 -49
  33. package/dist/shared/atbash-targets.js +0 -63
  34. package/dist/shared/atbash-targets.js.map +0 -1
  35. package/dist/shared/openclaw-runtime.d.ts +0 -221
  36. package/dist/shared/openclaw-runtime.js +0 -453
  37. package/dist/shared/openclaw-runtime.js.map +0 -1
@@ -42,22 +42,7 @@ exports.keyCandidatesInDir = keyCandidatesInDir;
42
42
  exports.resolveKeySource = resolveKeySource;
43
43
  exports.keyFileContents = keyFileContents;
44
44
  exports.isJsonc = isJsonc;
45
- exports.openclawEntryDecision = openclawEntryDecision;
46
45
  exports.mergeOpenclawConfig = mergeOpenclawConfig;
47
- exports.openclawInstallState = openclawInstallState;
48
- exports.detectIndent = detectIndent;
49
- exports.serializeLike = serializeLike;
50
- exports.detectMcpClients = detectMcpClients;
51
- exports.findHermesPython = findHermesPython;
52
- exports.wantedRuntime = wantedRuntime;
53
- exports.mergeHermesEnabledPlugins = mergeHermesEnabledPlugins;
54
- exports.hermesGatewayRunning = hermesGatewayRunning;
55
- exports.hermesPluginState = hermesPluginState;
56
- exports.pythonInstallStrategy = pythonInstallStrategy;
57
- exports.mergeHermesEnv = mergeHermesEnv;
58
- exports.hadInlineKey = hadInlineKey;
59
- exports.mergeMcpServer = mergeMcpServer;
60
- exports.openclawPatchPayload = openclawPatchPayload;
61
46
  exports.buildPlan = buildPlan;
62
47
  exports.lineDiff = lineDiff;
63
48
  exports.renderPlan = renderPlan;
@@ -70,10 +55,8 @@ const path = __importStar(require("path"));
70
55
  const child_process_1 = require("child_process");
71
56
  const chalk_1 = __importDefault(require("chalk"));
72
57
  const jsonc = __importStar(require("jsonc-parser"));
73
- const yaml_1 = require("yaml");
74
58
  const sdk_1 = require("@atbash/sdk");
75
- const atbash_targets_1 = require("../shared/atbash-targets");
76
- const openclaw_runtime_1 = require("../shared/openclaw-runtime");
59
+ const connect_1 = require("./connect");
77
60
  /**
78
61
  * `atbash setup` — the write half of onboarding.
79
62
  *
@@ -101,11 +84,9 @@ const openclaw_runtime_1 = require("../shared/openclaw-runtime");
101
84
  * 2. It never writes the private key into an MCP client config. The documented
102
85
  * `@atbash/mcp` wiring passes the key as an `ATBASH_AGENT_PRIVKEY` env value
103
86
  * inside e.g. `claude_desktop_config.json` — a file people screenshot, sync
104
- * and share, and that package has no key-file fallback (verified against the
105
- * published 0.1.3). So the entry setup writes points at `atbash mcp`, which
106
- * reads the 0600 key file and passes the key to the server through the child
107
- * environment. The config file itself gets NO credential — and an entry that
108
- * was hand-wired with one has it removed.
87
+ * and share. That package has no key-file fallback today (verified against
88
+ * the published 0.1.3), so MCP clients are REPORTED with the snippet to add
89
+ * by hand rather than silently seeded with a secret.
109
90
  * 3. It never edits application source. Code-level integrations (LangChain,
110
91
  * LangGraph, AutoGen, Eliza, the SDK boundary) are the owner's to write.
111
92
  * 4. It never rewrites a config file that uses comments or trailing commas.
@@ -128,160 +109,17 @@ const OPENCLAW_CONFIG_REL = [".openclaw", "openclaw.json"];
128
109
  const OPENCLAW_EXTENSIONS_REL = [".openclaw", "extensions"];
129
110
  const HERMES_AGENT_REL = [".hermes", "hermes-agent"];
130
111
  /**
131
- * The OpenClaw plugin package.
112
+ * The OpenClaw plugin, and the entry key it registers itself as.
132
113
  *
133
- * The doc comment here used to assert "the entry key really is `openclaw` not
134
- * a copy-paste slip", which directly contradicts OPENCLAW_ENTRY three lines
135
- * below and was the belief that made every config an earlier release wrote inert.
136
- * Installs of the earlier `@atbash/atbash-plugin` register under
137
- * `atbash-plugin`, and the dashboard's capability scan recognizes both that and
138
- * `atbash-openclaw` — so an existing config carrying the legacy key is already
139
- * governed and must not be given a second, duplicate entry.
114
+ * The entry key really is `openclaw` that is what `@atbash/atbash-openclaw`
115
+ * registers as, not a copy-paste slip. Installs of the earlier
116
+ * `@atbash/atbash-plugin` register under `atbash-plugin`, and the dashboard's
117
+ * capability scan recognizes BOTH. So an existing config carrying the legacy key
118
+ * is already governed and must not be given a second, duplicate entry.
140
119
  */
141
120
  const OPENCLAW_PKG = "@atbash/atbash-openclaw";
142
- /**
143
- * The entry key `@atbash/atbash-openclaw` registers as.
144
- *
145
- * ⚠️ It is `atbash-openclaw`, NOT `openclaw`. `openclaw` is the id of the RETIRED
146
- * `@atbash-plugin/openclaw` package, and the published docs are explicit about
147
- * what happens if you use it: "the plugin id here is `atbash-openclaw`, so a
148
- * leftover `openclaw` entry silently configures nothing." Earlier releases of
149
- * this command wrote `openclaw`, so every config they produced was inert — no
150
- * error, no warning, just a plugin reading a config block nobody looks at.
151
- */
152
- const OPENCLAW_ENTRY = "atbash-openclaw";
153
- /** Installs of the earlier `@atbash/atbash-plugin` register under this. */
121
+ const OPENCLAW_ENTRY = "openclaw";
154
122
  const OPENCLAW_LEGACY_ENTRY = "atbash-plugin";
155
- /**
156
- * Drop the `hooks` block from a plugin entry.
157
- *
158
- * ⚠️ WHETHER `hooks` IS VALID DEPENDS ON THE OPENCLAW VERSION, and this note
159
- * used to state the 2026.2.x answer as a fact about OpenClaw itself.
160
- *
161
- * On 2026.2.1 it is not a key at all, and an unrecognized entry key is fatal —
162
- * verified by feeding a generated config through OPENCLAW_CONFIG_PATH:
163
- *
164
- * - plugins.entries.atbash-openclaw: Unrecognized key: "hooks"
165
- *
166
- * Rejecting means refusing to load ANY config, which also makes
167
- * `openclaw plugins install` exit 1. But the key was ADDED later. Straight out
168
- * of 2026.6.6's own `openclaw config schema`, an entry accepts
169
- * `enabled | hooks | subagent | llm | config`, and `hooks` accepts
170
- * `allowPromptInjection | allowConversationAccess | timeoutMs | timeouts`.
171
- *
172
- * We still strip it and never write it, now on evidence rather than on the claim
173
- * above:
174
- *
175
- * 1. Nothing under `hooks` is required — the schema's `required` list is empty.
176
- * 2. It gates hook FAMILIES this plugin does not use. `allowConversationAccess`
177
- * covers `before_agent_run`, `llm_input`, `llm_output`, `agent_end` and
178
- * friends; `allowPromptInjection` covers `before_prompt_build`. The plugin
179
- * registers exactly one hook, `before_tool_call`, which is in neither
180
- * (verified by grepping the installed plugin, not by reading its README).
181
- * 3. Writing it would break every 2026.2.x machine for no gain, and those are
182
- * real — the reference box for these attestations is one.
183
- *
184
- * ⚠️ RE-CHECK IF THE PLUGIN EVER ADDS A SECOND HOOK. The schema says
185
- * "Non-bundled plugins must opt in explicitly", so a new conversation-reading
186
- * hook would be silently denied on 2026.6.6+ with no config error to notice: the
187
- * plugin would load, still gate tool calls, and quietly see nothing else.
188
- */
189
- function stripInvalidHooks(entry, supported = false) {
190
- // ⚠️ ONLY WHERE THE KEY IS ACTUALLY INVALID. This used to delete `hooks`
191
- // unconditionally, which is right on 2026.2.x — where an unrecognized entry key
192
- // makes OpenClaw refuse the whole config — and destructive on 2026.6.6+, where
193
- // the key is valid, optional and undeprecated.
194
- //
195
- // `hooks.timeoutMs` bounds this plugin's hook latency "without changing plugin
196
- // code". An operator who sets it has made a deliberate choice, and silently
197
- // removing it on the next run is not repair — it also contradicts the rule
198
- // stated further down this file: an existing entry is touched as little as
199
- // possible.
200
- //
201
- // Defaults to `false` (strip), so a caller that cannot determine support gets
202
- // the fail-safe behaviour. A lost timeout value is a far smaller harm than a
203
- // config OpenClaw will not load at all.
204
- if (!supported && "hooks" in entry)
205
- delete entry.hooks;
206
- return entry;
207
- }
208
- /**
209
- * The one hook permission worth WRITING: deny this plugin prompt mutation.
210
- *
211
- * WHY THIS IS NOT DECORATION. `allowPromptInjection` DEFAULTS TO ALLOWED for
212
- * non-bundled plugins — OpenClaw's plugin-hooks docs say so in as many words
213
- * ("It defaults to allowed") — so without this key the guard holds permission to
214
- * mutate prompts via `before_prompt_build`, `agent_turn_prepare`,
215
- * `heartbeat_prompt_contribution` and durable next-turn injections. It uses none
216
- * of them: it registers exactly one hook, `before_tool_call`.
217
- *
218
- * The gate is enforced by OPENCLAW, not by the plugin, so the denial holds even
219
- * if the plugin or one of its dependencies is compromised — and it bundles a
220
- * fair few (`@atbash/sdk`, the whole `@opentelemetry` tree). A guard being
221
- * visibly constrained by the runtime it guards is the right posture, and it is
222
- * auditable: someone reading the config can see the boundary stops at tool calls.
223
- *
224
- * ⚠️ It does NOT affect `before_tool_call` — "No conversation-access opt-in is
225
- * needed for `before_tool_call`", and this gate covers prompt-mutation hooks
226
- * only. There is no functional risk to what the plugin actually does.
227
- *
228
- * ⚠️ AND WE DELIBERATELY DO NOT WRITE `allowConversationAccess: false`. That one
229
- * already defaults to denied ("Non-bundled plugins must opt in explicitly"), so
230
- * writing it changes nothing — and writing keys that change nothing is exactly
231
- * the habit that produced this file's worst bugs: the entry schema is
232
- * `additionalProperties: false`, so every key we write is a liability we then own
233
- * on every OpenClaw version. It would also silently deny a future
234
- * conversation-reading hook, with an explicit `false` in the config to mislead
235
- * whoever debugs it.
236
- */
237
- const HOOK_PERMISSIONS = { allowPromptInjection: false };
238
- /**
239
- * Add the denial without disturbing anything the operator set.
240
- *
241
- * Fills the key in only when it is ABSENT. An operator who wrote
242
- * `allowPromptInjection: true` meant it, and overriding a deliberate choice is
243
- * not this command's business — "touch an existing entry as little as possible"
244
- * applies to permissions too. Their `timeoutMs`/`timeouts` are untouched either
245
- * way.
246
- */
247
- function withHookPermissions(entry, supported) {
248
- if (!supported)
249
- return entry;
250
- const existing = isRecord(entry.hooks) ? entry.hooks : {};
251
- return { ...entry, hooks: { ...HOOK_PERMISSIONS, ...existing } };
252
- }
253
- /** The retired `@atbash-plugin/openclaw` id — inert if left in a config. */
254
- const OPENCLAW_RETIRED_ENTRY = "openclaw";
255
- /**
256
- * The npm tag to install, chosen from the deployment the agent was onboarded on.
257
- *
258
- * The judge endpoint and chain ids are NOT configurable at runtime — they come
259
- * from the SDK the plugin bundles, so the tag is an environment choice. Verified
260
- * on the registry: the two tarballs' plugin code is byte-identical and only
261
- * `package.json` differs —
262
- *
263
- * 0.1.14 → @atbash/sdk@0.7.0 → https://atbash.ai BRID 0163241D…
264
- * 0.1.14-dev.0 → @atbash/sdk@0.10.5-dev.0 → …dev-two.vercel.app BRID 02668C52…
265
- *
266
- * Install the wrong one and it loads cleanly, fires its hook, and fails every
267
- * judge call because the agent does not exist on the chain that build targets.
268
- * The docs warn that a resolving org name is not proof the build is right, since
269
- * org names are not unique across environments — so this is derived from --host
270
- * and nothing else.
271
- */
272
- function openclawPackageForHost(endpoint) {
273
- if (!endpoint)
274
- return OPENCLAW_PKG; // no host given: production is the safe default
275
- let hostname = "";
276
- try {
277
- hostname = new URL(endpoint).hostname.toLowerCase();
278
- }
279
- catch {
280
- return OPENCLAW_PKG;
281
- }
282
- const isProduction = hostname === "atbash.ai" || hostname === "www.atbash.ai";
283
- return isProduction ? OPENCLAW_PKG : `${OPENCLAW_PKG}@dev`;
284
- }
285
123
  /** File modes: 0700 for the key directory, 0600 for the key itself. */
286
124
  const DIR_MODE = 0o700;
287
125
  const KEY_MODE = 0o600;
@@ -370,45 +208,7 @@ function normalizePrivkey(raw) {
370
208
  const clean = raw.replace(/^0x/i, "").trim().toLowerCase();
371
209
  return (0, sdk_1.isValidPrivateKey)(clean) ? clean : "";
372
210
  }
373
- /** Only sniff the contents of small files a key file is a few hundred bytes. */
374
- const MAX_SNIFF_BYTES = 8 * 1024;
375
- /** Bound the content-sniff so `--keys-dir ~` cannot turn into a directory crawl. */
376
- const MAX_SNIFF_FILES = 60;
377
- /** Newest-first, so a freshly downloaded key wins over one from last month. */
378
- function newestFirst(files) {
379
- return files
380
- .map((file) => {
381
- let mtime = 0;
382
- try {
383
- mtime = fs.statSync(file).mtimeMs;
384
- }
385
- catch { /* unreadable — sorts last */ }
386
- return { file, mtime };
387
- })
388
- .sort((a, b) => b.mtime - a.mtime)
389
- .map((e) => e.file);
390
- }
391
- /**
392
- * Files in a directory that plausibly hold an Atbash agent key, newest first.
393
- *
394
- * TWO PASSES, and the second one is the point.
395
- *
396
- * By name first — `guard-client-key`, `agent-keys-*.txt` and friends — because
397
- * matching the name is cheap and unambiguous. But a name-only match is a cliff:
398
- * rename the download, or export from a wallet UI that picks its own filename,
399
- * and the operator gets "no key file found" while the key sits right there in the
400
- * directory they explicitly pointed at.
401
- *
402
- * So if no name matches, read the small files and keep the ones that actually
403
- * PARSE as key material. That is a narrow test — `privkey=`, the documented JSON
404
- * shape, or a file that is nothing but a 64-hex key — not "contains something
405
- * hex-looking", so an unrelated file does not get mistaken for an identity.
406
- *
407
- * Reading files the operator did not name individually is justified by the flag
408
- * itself: `--keys-dir` is an explicit instruction to look in that directory. It
409
- * is bounded to small regular files and a file count, nothing is transmitted, and
410
- * the caller prints WHICH file it used before doing anything with it.
411
- */
211
+ /** Files in a directory that plausibly hold an Atbash agent key, newest first. */
412
212
  function keyCandidatesInDir(dir) {
413
213
  let names;
414
214
  try {
@@ -417,31 +217,21 @@ function keyCandidatesInDir(dir) {
417
217
  catch {
418
218
  return [];
419
219
  }
420
- const byName = names.filter((n) => n === "guard-client-key" ||
220
+ const matches = names.filter((n) => n === "guard-client-key" ||
421
221
  /^agent-keys-.*\.txt$/i.test(n) ||
422
222
  /^atbash.*(key|keys).*\.(txt|json)$/i.test(n));
423
- if (byName.length)
424
- return newestFirst(byName.map((n) => path.join(dir, n)));
425
- const byContent = [];
426
- let examined = 0;
427
- for (const name of names) {
428
- if (examined >= MAX_SNIFF_FILES)
429
- break;
430
- const file = path.join(dir, name);
223
+ return matches
224
+ .map((n) => path.join(dir, n))
225
+ .map((file) => {
226
+ let mtime = 0;
431
227
  try {
432
- const stat = fs.statSync(file);
433
- if (!stat.isFile() || stat.size === 0 || stat.size > MAX_SNIFF_BYTES)
434
- continue;
435
- }
436
- catch {
437
- continue;
228
+ mtime = fs.statSync(file).mtimeMs;
438
229
  }
439
- examined++;
440
- const text = readTextFile(file);
441
- if (text !== null && parseKeyMaterial(text))
442
- byContent.push(file);
443
- }
444
- return newestFirst(byContent);
230
+ catch { /* unreadable — sorts last */ }
231
+ return { file, mtime };
232
+ })
233
+ .sort((a, b) => b.mtime - a.mtime)
234
+ .map((e) => e.file);
445
235
  }
446
236
  /**
447
237
  * Read a secret from the terminal without echoing it.
@@ -457,56 +247,23 @@ function keyCandidatesInDir(dir) {
457
247
  async function promptForKeyOrPath() {
458
248
  const { createInterface } = await Promise.resolve().then(() => __importStar(require("node:readline")));
459
249
  return new Promise((resolveP) => {
250
+ const input = process.stdin;
251
+ const rl = createInterface({ input, output: process.stdout, terminal: true });
252
+ // Mute the echo so a pasted key does not sit on screen (or in a scrollback
253
+ // buffer that gets screenshotted). A pasted path is muted too; that is a
254
+ // small cost against leaving a private key visible.
255
+ const asMutable = rl;
460
256
  const prompt = "Paste the agent's private key, or the path to its key file: ";
461
- // Write the prompt ourselves, THEN suppress every subsequent write.
462
- //
463
- // The obvious implementation compares each write against the prompt text and
464
- // lets that one through but a pasted value containing the prompt as a
465
- // substring would then be echoed to the terminal, which is exactly the
466
- // failure this mute exists to prevent. Emitting the prompt up front means the
467
- // suppressor never has to decide what a write IS: after this point, nothing
468
- // is echoed, unconditionally.
469
- process.stdout.write(prompt);
470
- const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
471
- rl._writeToOutput = () => {
472
- /* nothing typed after the prompt is ever echoed */
257
+ asMutable._writeToOutput = function (s) {
258
+ if (s.includes(prompt))
259
+ asMutable.output?.write(s);
260
+ else if (s === "\r\n" || s === "\n")
261
+ asMutable.output?.write(s);
262
+ // every other keystroke echo is dropped
473
263
  };
474
- rl.question("", (answer) => {
475
- rl.close();
476
- // readline's own newline was suppressed along with everything else, so the
477
- // next line of output would otherwise land on the prompt line.
478
- process.stdout.write("\n");
479
- resolveP(answer.trim());
480
- });
264
+ rl.question(prompt, (answer) => { rl.close(); resolveP(answer.trim()); });
481
265
  });
482
266
  }
483
- /**
484
- * Interpret whatever someone typed at the prompt: a raw key, a file, or a
485
- * directory to search. Shared by the "no key found" prompt and the "use the
486
- * existing key?" prompt so both accept the same things — an operator who can
487
- * paste a path in one place should not find it rejected in the other.
488
- */
489
- async function keyFromAnswer(answer, home) {
490
- const direct = parseKeyMaterial(answer);
491
- if (direct)
492
- return { material: direct, from: "key entered at the prompt" };
493
- const asPath = expandHome(answer, home);
494
- if (!exists(asPath))
495
- return null;
496
- let isDir = false;
497
- try {
498
- isDir = fs.statSync(asPath).isDirectory();
499
- }
500
- catch {
501
- return null;
502
- }
503
- const file = isDir ? keyCandidatesInDir(asPath)[0] : asPath;
504
- if (!file)
505
- return null;
506
- const text = readTextFile(file);
507
- const material = text === null ? null : parseKeyMaterial(text);
508
- return material ? { material, from: `${file} (given at the prompt)` } : null;
509
- }
510
267
  /**
511
268
  * Find the agent key, trying every way an owner could plausibly have it.
512
269
  *
@@ -540,15 +297,7 @@ async function resolveKeySource(opts) {
540
297
  const dir = expandHome(opts.keysDir, home);
541
298
  const candidates = keyCandidatesInDir(dir);
542
299
  if (!candidates.length) {
543
- return {
544
- error: [
545
- `No agent key found in ${dir}.`,
546
- "Looked for guard-client-key / agent-keys-*.txt by name, then read the small",
547
- "files there to see if any parsed as an agent key. Neither found one.",
548
- "Point at the file directly with --key-file, or paste the key with no flags",
549
- "at all and setup will prompt for it.",
550
- ].join("\n"),
551
- };
300
+ return { error: `No agent key file found in ${dir} (looked for guard-client-key and agent-keys-*.txt).` };
552
301
  }
553
302
  return fromFile(candidates[0], "--keys-dir");
554
303
  }
@@ -560,39 +309,11 @@ async function resolveKeySource(opts) {
560
309
  return { material, from: "ATBASH_AGENT_KEY" };
561
310
  }
562
311
  // 5. Already in the canonical place — a re-run, or a machine set up before.
563
- //
564
- // This used to be taken SILENTLY, and that was a trap. A machine that has ever
565
- // governed one agent already has a key here, so onboarding a SECOND agent
566
- // picked up the first one's key and then failed registration against a pubkey
567
- // the operator never chose:
568
- //
569
- // Agent key source: existing key file (~/.config/atbash/guard-client-key)
570
- // That agent is not registered on this deployment.
571
- //
572
- // which reads as "onboarding is broken" rather than "I used a different key
573
- // than you meant". So when there is someone to ask, ask — and make the existing
574
- // key the easy answer for the common case (a genuine re-run) without making it
575
- // the only answer.
576
312
  const keyFile = path.join(home, ...KEY_FILE_REL);
577
313
  if (exists(keyFile)) {
578
314
  const found = fromFile(keyFile, "existing key file");
579
- if (!("error" in found)) {
580
- if (!opts.allowPrompt)
581
- return found; // non-interactive: same as before
582
- const existingPub = (0, sdk_1.derivePublicKey)(found.material.privkey);
583
- process.stdout.write(`\n This machine already has an agent key at ${keyFile}\n` +
584
- ` Public key: ${existingPub}\n`);
585
- const useExisting = await confirm(" Use that key? [Y/n] ", true);
586
- if (useExisting)
587
- return found;
588
- const answer = await promptForKeyOrPath();
589
- if (!answer)
590
- return { error: "No key provided." };
591
- const supplied = await keyFromAnswer(answer, home);
592
- if (supplied)
593
- return supplied;
594
- return { error: "That is neither a 64-hex private key nor a path that exists." };
595
- }
315
+ if (!("error" in found))
316
+ return found;
596
317
  }
597
318
  // 6. The CLI's own config, populated by `atbash set agent-key`.
598
319
  const fromConfig = (0, sdk_1.resolve)("agentKey");
@@ -606,9 +327,20 @@ async function resolveKeySource(opts) {
606
327
  const answer = await promptForKeyOrPath();
607
328
  if (!answer)
608
329
  return { error: "No key provided." };
609
- const supplied = await keyFromAnswer(answer, home);
610
- if (supplied)
611
- return supplied;
330
+ const direct = parseKeyMaterial(answer);
331
+ if (direct)
332
+ return { material: direct, from: "interactive prompt" };
333
+ const asPath = expandHome(answer, home);
334
+ if (exists(asPath)) {
335
+ const stat = fs.statSync(asPath);
336
+ if (stat.isDirectory()) {
337
+ const candidates = keyCandidatesInDir(asPath);
338
+ if (candidates.length)
339
+ return fromFile(candidates[0], "directory given at the prompt");
340
+ return { error: `No agent key file found in ${asPath}.` };
341
+ }
342
+ return fromFile(asPath, "file given at the prompt");
343
+ }
612
344
  return { error: "That is neither a 64-hex private key nor a path that exists." };
613
345
  }
614
346
  return {
@@ -651,865 +383,62 @@ function isJsonc(text) {
651
383
  *
652
384
  * A MERGE, not a replacement — that distinction is the whole reason this command
653
385
  * exists. Other plugins already in `allow`, `load.paths` and `entries` are
654
- * preserved.
655
- *
656
- * WHICH entry is governed depends on what is being installed. When this run
657
- * installs `@atbash/atbash-openclaw` — every run that is not `--no-install` —
658
- * the plugin that ends up on disk registers as `atbash-openclaw`, so that is the
659
- * entry that gets the config, and a legacy `atbash-plugin` entry is STOOD DOWN
660
- * rather than configured. Only a `--no-install` run on a box whose sole entry is
661
- * the legacy one keeps writing to the legacy key: there, nothing is arriving to
662
- * replace it, and switching it off would leave the machine unguarded.
386
+ * preserved, and an entry from the legacy `@atbash/atbash-plugin` install is
387
+ * updated where it stands rather than being shadowed by a duplicate: the
388
+ * dashboard scan recognizes both keys, so two entries would mean two hooks.
663
389
  *
664
390
  * `load.paths` gets the real absolute extension path. The published docs show a
665
391
  * `<your-username>` placeholder that people paste verbatim, producing a path that
666
392
  * does not exist and a plugin that never loads.
667
393
  */
668
- /**
669
- * WHICH entry this run governs, and whether a legacy one is being stood down.
670
- *
671
- * Extracted so the hand-merge and the `openclaw config patch` payload cannot
672
- * disagree. Two implementations of this decision is exactly how a build ended up
673
- * writing the modern plugin's `orgName` onto the LEGACY entry — whose schema is
674
- * closed and has no such field — so OpenClaw rejected the whole file and the run
675
- * broke its own install step.
676
- *
677
- * An entry is not the only way the legacy plugin is present: `plugins.installs`
678
- * records it independently, and an installed, allowed plugin loads with its
679
- * defaults whether or not anyone wrote an entry for it.
680
- */
681
- function openclawEntryDecision(config, opts = {}) {
682
- const installsModern = opts.installsModern !== false;
683
- const plugins = isRecord(config.plugins) ? config.plugins : {};
684
- const entries = isRecord(plugins.entries) ? plugins.entries : {};
685
- const installs = isRecord(plugins.installs) ? plugins.installs : {};
686
- const legacy = OPENCLAW_LEGACY_ENTRY in entries || OPENCLAW_LEGACY_ENTRY in installs;
687
- const modern = OPENCLAW_ENTRY in entries;
688
- // Only a --no-install run on a box whose sole entry is the legacy one keeps
689
- // writing to the legacy key: there, nothing is arriving to replace it, and
690
- // switching it off would leave the machine unguarded.
691
- const useLegacy = !installsModern && legacy && !modern;
692
- return {
693
- entryKey: useLegacy ? OPENCLAW_LEGACY_ENTRY : OPENCLAW_ENTRY,
694
- useLegacy,
695
- legacy,
696
- standDownLegacy: !useLegacy && legacy,
697
- };
698
- }
699
- function mergeOpenclawConfig(config, home, orgName, opts = {}) {
700
- const installsModern = opts.installsModern !== false;
701
- // Whether THIS machine's OpenClaw accepts `hooks` on a plugin entry. Probed
702
- // from `openclaw config schema` by the caller; absent means "assume not", which
703
- // is the fail-safe direction. See stripInvalidHooks.
704
- const hooksSupported = opts.hooksSupported === true;
394
+ function mergeOpenclawConfig(config, home) {
705
395
  const out = { ...config };
706
396
  const plugins = { ...(isRecord(out.plugins) ? out.plugins : {}) };
397
+ // Which key is this install governed under? Keep an existing legacy entry
398
+ // where it is instead of adding a second one.
707
399
  const entries = { ...(isRecord(plugins.entries) ? plugins.entries : {}) };
708
- // Which entry is this install governed under, and does one already exist?
709
- //
710
- // ⚠️ `legacy && !modern` used to be enough to pick the legacy key, and it broke
711
- // a real machine. Setup installs `@atbash/atbash-openclaw`, then wrote that
712
- // plugin's config — `orgName` included — onto the LEGACY `atbash-plugin`
713
- // entry. The legacy plugin's manifest declares `"additionalProperties": false`
714
- // and knows no `orgName`, so OpenClaw rejected the whole file —
715
- //
716
- // Invalid config at ~/.openclaw/openclaw.json:
717
- // - plugins.entries.atbash-plugin.config: invalid config: <root>:
718
- // must NOT have additional properties
719
- //
720
- // — refused to load any config, and `openclaw plugins install` then exited 1.
721
- // The run broke its own install step and half-applied, while the plugin it did
722
- // install sat there with no config at all.
723
- //
724
- // An entry is not the only way the legacy plugin is present: `plugins.installs`
725
- // records it independently, and a plugin that is installed and allowed loads
726
- // with its defaults whether or not anyone wrote an entry for it.
727
- const { entryKey, useLegacy, legacy } = openclawEntryDecision(config, { installsModern });
728
- const existing = isRecord(entries[entryKey]) ? entries[entryKey] : null;
729
- // Stand the legacy plugin down when the modern one is taking over. Two live
730
- // entries means two hooks, so every tool call would be judged twice — against
731
- // two different SDK versions.
732
- //
733
- // The entry is reduced to `{ enabled: false }`. Leaving its `config` behind as
734
- // a way back looks considerate and is not: OpenClaw then warns
735
- //
736
- // - plugins.entries.atbash-plugin: plugin disabled (not in allowlist) but
737
- // config is present
738
- //
739
- // on EVERY config load, and it loads many times per command — a real machine
740
- // printed that line hundreds of times for a single `openclaw plugins install`,
741
- // burying the output the operator was reading. The way back is the timestamped
742
- // `.atbash-bak` this command already writes beside the file.
743
- if (!useLegacy && legacy) {
744
- entries[OPENCLAW_LEGACY_ENTRY] = { enabled: false };
745
- }
746
- // ⚠️ AN EXISTING ENTRY IS TOUCHED AS LITTLE AS POSSIBLE.
747
- //
748
- // This function used to assert the full documented shape onto whatever it
749
- // found, which broke a real machine: a legacy `atbash-plugin` install accepts
750
- // only `config` and `enabled`, so writing the `hooks` block that the NEW
751
- // `openclaw` entry documents made the whole file invalid —
752
- //
753
- // Invalid config at ~/.openclaw/openclaw.json:
754
- // - plugins.entries.atbash-plugin: Unrecognized key: "hooks"
755
- //
756
- // and OpenClaw then refused to load any config at all. It also rewrote an
757
- // absolute `chromiaSecretPath` to a `~` one for no gain.
758
- //
759
- // A plugin that is already installed and registered does not need `load`
760
- // re-declared — it is working. The only thing setup has any business changing
761
- // is that it is switched on, allowed, and pointed at the right key.
762
- if (existing) {
763
- const existingConfig = isRecord(existing.config) ? existing.config : {};
764
- // The exception to leaving an existing entry alone: strip `hooks`. "Touch as
765
- // little as possible" is the right rule, but it must not mean stepping
766
- // politely around damage this tool caused — a later run would leave the
767
- // machine broken forever and report nothing wrong.
768
- const repaired = withHookPermissions(stripInvalidHooks({ ...existing }, hooksSupported), hooksSupported);
769
- entries[entryKey] = {
770
- ...repaired,
771
- enabled: true,
772
- config: {
773
- ...existingConfig,
774
- enabled: true,
775
- enforceDecision: true,
776
- ...keyPathUpdate(existingConfig, home),
777
- // `orgName` exists only in the modern plugin's configSchema. The legacy
778
- // one closes with `"additionalProperties": false`, so writing it there
779
- // invalidates the entire file — the failure this whole branch guards.
780
- ...(entryKey === OPENCLAW_LEGACY_ENTRY ? {} : orgNameUpdate(existingConfig, orgName)),
781
- },
782
- };
783
- plugins.entries = entries;
784
- // An allowlist that does not name this entry means the plugin never loads,
785
- // however well configured it is — the modern entry arriving on a box whose
786
- // `allow` still says only `atbash-plugin` is exactly that. Only ever an
787
- // adjustment to a list that already exists: conjuring one where there was
788
- // none would newly restrict every other plugin on the machine.
789
- const reconciled = reconcileAllow(plugins.allow, entryKey, !useLegacy && legacy);
790
- if (reconciled)
791
- plugins.allow = reconciled;
792
- const prunedLoad = pruneRetiredLoadPath(plugins.load, home);
793
- if (prunedLoad)
794
- plugins.load = prunedLoad;
795
- out.plugins = plugins;
796
- return out;
797
- }
798
- // No entry yet — configure the ENTRY, and nothing else.
799
- //
800
- // ⚠️ THIS IS THE FRESH-INSTALL PATH, AND IT USED TO CREATE BOTH
801
- // `plugins.allow` AND `plugins.load.paths`. That is the config a reporter got
802
- // on a clean OpenClaw 2026.6.6, which then refused to load it:
803
- //
804
- // - plugins.load.paths: plugin path not found:
805
- // /Users/me/.openclaw/extensions/atbash-openclaw
806
- // - plugins.allow: plugins.allow now gates bundled provider discovery by
807
- // default; run "openclaw doctor --fix" …
808
- //
809
- // `load.paths` was the fatal half, and note WHY it could never have worked: it
810
- // named `~/.openclaw/extensions/<id>`, which is the 2026.2.x plugin store.
811
- // 2026.6.x installs plugins as npm dependencies of `~/.openclaw` — into
812
- // `~/.openclaw/node_modules` — and leaves `extensions/` empty. So we wrote a
813
- // path OpenClaw was never going to create, and a `load.paths` entry naming a
814
- // missing directory fails the ENTIRE config, which then takes down the
815
- // `openclaw plugins install` in this very same run. The command broke its own
816
- // install step and left behind a dangling entry that `openclaw doctor --fix`
817
- // then offers to delete — silently un-governing the agent.
818
- //
819
- // Neither key is ours to write:
820
- //
821
- // - `openclaw plugins install` records where it put the plugin and loads from
822
- // that record. The location has moved twice in six months across four
823
- // channels; we cannot know it and must not guess it.
824
- // - `allow` only matters if the operator KEEPS such a list, and newer builds
825
- // have repurposed it to gate bundled provider discovery. Creating one where
826
- // there was none newly restricts every other plugin on the machine — a side
827
- // effect nobody asked this command for.
828
- //
829
- // Existing lists are still MAINTAINED, here and in the branch above, because an
830
- // `allow` list that omits this entry means the plugin never loads however well
831
- // configured it is. Adjust what is there; conjure nothing.
832
- const reconciledAllow = reconcileAllow(plugins.allow, entryKey, !useLegacy && legacy);
833
- if (reconciledAllow)
834
- plugins.allow = reconciledAllow;
835
- // A retired path is still pruned when present: that entry is fatal on every
836
- // version, so removing it is repair rather than assertion.
837
- const prunedLoad = pruneRetiredLoadPath(plugins.load, home);
838
- if (prunedLoad)
839
- plugins.load = prunedLoad;
840
- // `orgName` is the modern plugin's field. This branch can still land on the
841
- // legacy key — a `--no-install` run against a box where the old plugin is in
842
- // `plugins.installs` but nobody ever wrote it an entry — and its configSchema
843
- // is closed, so the field would invalidate the file.
844
- //
845
- // No `hooks` block: see OPENCLAW_ENTRY_KEYS. It is not a key OpenClaw has.
846
- entries[entryKey] = withHookPermissions({
400
+ const entryKey = OPENCLAW_LEGACY_ENTRY in entries && !(OPENCLAW_ENTRY in entries)
401
+ ? OPENCLAW_LEGACY_ENTRY
402
+ : OPENCLAW_ENTRY;
403
+ const allow = Array.isArray(plugins.allow) ? [...plugins.allow] : [];
404
+ if (!allow.includes(entryKey))
405
+ allow.push(entryKey);
406
+ plugins.allow = allow;
407
+ const load = { ...(isRecord(plugins.load) ? plugins.load : {}) };
408
+ const extensionPath = path.join(home, ...OPENCLAW_EXTENSIONS_REL, OPENCLAW_ENTRY);
409
+ const paths = Array.isArray(load.paths) ? [...load.paths] : [];
410
+ if (!paths.includes(extensionPath))
411
+ paths.push(extensionPath);
412
+ load.paths = paths;
413
+ plugins.load = load;
414
+ // Preserve any unrelated fields the owner set on the entry (debug, custom
415
+ // hooks); only the fields Atbash owns are asserted.
416
+ const existing = isRecord(entries[entryKey]) ? entries[entryKey] : {};
417
+ const existingConfig = isRecord(existing.config) ? existing.config : {};
418
+ const existingHooks = isRecord(existing.hooks) ? existing.hooks : {};
419
+ entries[entryKey] = {
420
+ ...existing,
847
421
  enabled: true,
848
422
  config: {
423
+ ...existingConfig,
849
424
  enabled: true,
850
425
  enforceDecision: true,
426
+ // The path, not the key. This is the whole point of the canonical location.
851
427
  chromiaSecretPath: `~/${KEY_FILE_REL.join("/")}`,
852
- ...(entryKey !== OPENCLAW_LEGACY_ENTRY && orgName?.trim() ? { orgName: orgName.trim() } : {}),
853
428
  },
854
- }, hooksSupported);
429
+ hooks: {
430
+ ...existingHooks,
431
+ allowConversationAccess: true,
432
+ allowPromptInjection: true,
433
+ },
434
+ };
855
435
  plugins.entries = entries;
856
436
  out.plugins = plugins;
857
437
  return out;
858
438
  }
859
- /**
860
- * The key-path field, but only when it actually needs changing.
861
- *
862
- * `/Users/me/.config/atbash/guard-client-key` and `~/.config/atbash/guard-client-key`
863
- * are the same file, and the plugin expands `~`. Rewriting one into the other is
864
- * a diff the operator has to read and approve for no behavioural change, so an
865
- * existing value that already resolves to the canonical key file is left exactly
866
- * as they wrote it.
867
- */
868
- /**
869
- * `orgName`, but only when we have one and it differs from what is there.
870
- *
871
- * The plugin resolves WHICH CHAIN to query from this, so it is required for orgs
872
- * on a private chain and harmless otherwise. It cannot be derived on the machine
873
- * — it has to match the dashboard exactly — so it arrives via --org-name, which
874
- * the post-deploy screen fills in because the browser already knows it.
875
- *
876
- * Never overwrites an existing value with nothing: a run without the flag must
877
- * not silently strip an orgName someone already has working.
878
- */
879
- function orgNameUpdate(existingConfig, orgName) {
880
- const wanted = orgName?.trim();
881
- if (!wanted)
882
- return {};
883
- return existingConfig.orgName === wanted ? {} : { orgName: wanted };
884
- }
885
- /**
886
- * `plugins.allow`, adjusted — or `undefined` when there is no list to adjust.
887
- *
888
- * OpenClaw loads a plugin only if the allowlist names it, so an entry that is
889
- * perfectly configured under a name the list does not carry does nothing at all.
890
- * That is the state a legacy box lands in the moment the modern entry appears:
891
- * `allow` still reads `["atbash-plugin"]`.
892
- *
893
- * Returns `undefined` rather than a fresh array when no list exists, because an
894
- * allowlist conjured out of nothing does not just permit this plugin — it newly
895
- * restricts every other plugin on the machine.
896
- */
897
- function reconcileAllow(current, entryKey, dropLegacy) {
898
- if (!Array.isArray(current))
899
- return undefined;
900
- const allow = current.filter((name) => !(dropLegacy && String(name) === OPENCLAW_LEGACY_ENTRY));
901
- if (!allow.some((name) => String(name) === entryKey))
902
- allow.push(entryKey);
903
- return allow;
904
- }
905
- /**
906
- * `plugins.load`, with a path pointing at the retired plugin id dropped.
907
- *
908
- * `@atbash-plugin/openclaw` registered as `openclaw` and no longer publishes, so
909
- * `<home>/.openclaw/extensions/openclaw` is a directory that cannot exist. A
910
- * `load.paths` entry naming a missing directory is not inert — OpenClaw fails
911
- * the whole config on it:
912
- *
913
- * - plugins.load.paths: plugin: plugin path not found:
914
- * /Users/me/.openclaw/extensions/openclaw
915
- *
916
- * which then takes down `openclaw plugins install` along with everything else.
917
- * Only ever removes that one exact path; any other path is the operator's.
918
- */
919
- function pruneRetiredLoadPath(current, home) {
920
- if (!isRecord(current))
921
- return undefined;
922
- if (!Array.isArray(current.paths))
923
- return current;
924
- const retired = path.join(home, ...OPENCLAW_EXTENSIONS_REL, OPENCLAW_RETIRED_ENTRY);
925
- const paths = current.paths.filter((p) => typeof p !== "string" || path.resolve(expandHome(p.trim(), home)) !== path.resolve(retired));
926
- return paths.length === current.paths.length ? current : { ...current, paths };
927
- }
928
- /**
929
- * What `openclaw plugins install` would actually do with this spec.
930
- *
931
- * ⚠️ That command cannot overwrite. If the extension directory is there it
932
- * aborts —
933
- *
934
- * plugin already exists: ~/.openclaw/extensions/atbash-openclaw
935
- * (delete it first)
936
- *
937
- * — and exits 1. A plan that lists the install unconditionally therefore fails
938
- * on its SECOND run against the same machine, and setup then reports "this
939
- * machine is NOT fully wired" about a machine that is completely wired. Setup is
940
- * meant to be re-runnable; a step that can only ever succeed once is not.
941
- *
942
- * There is no `plugins uninstall` in OpenClaw 2026.2.1 — the subcommands are
943
- * list/info/enable/disable/install/update/doctor — so the way to refresh an
944
- * existing install is `plugins update <id>`, which re-resolves the recorded spec
945
- * and reports "up to date" when there is nothing to do.
946
- */
947
- /**
948
- * The plugin version recorded by a 2026.7.x npm-project install, if there is one.
949
- *
950
- * `openclaw plugins install` creates `~/.openclaw/npm/projects/<mangled>/` whose
951
- * package.json pins the plugin exactly:
952
- *
953
- * dependencies: { "@atbash/atbash-openclaw": "0.1.14-dev.0" }
954
- *
955
- * The directory name is derived from the package name (`@atbash/atbash-openclaw`
956
- * → `atbash-atbash-openclaw-<hash>`), which is how the plugin is told apart from
957
- * `@opentelemetry/api`, a dependency OpenClaw adds to every one of these projects.
958
- */
959
- function openclawNpmProjectVersion(home) {
960
- const mangle = (name) => name.replace(/^@/, "").replace(/[/]/g, "-");
961
- const projectsDir = path.join(home, ".openclaw", "npm", "projects");
962
- let projects = [];
963
- try {
964
- projects = fs.readdirSync(projectsDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
965
- }
966
- catch {
967
- return undefined;
968
- }
969
- for (const project of projects) {
970
- const raw = readTextFile(path.join(projectsDir, project, "package.json"));
971
- if (raw === null)
972
- continue;
973
- let deps = {};
974
- try {
975
- const parsed = JSON.parse(raw);
976
- deps = isRecord(parsed.dependencies) ? parsed.dependencies : {};
977
- }
978
- catch {
979
- continue;
980
- }
981
- for (const [name, version] of Object.entries(deps)) {
982
- if (!project.startsWith(mangle(name)))
983
- continue;
984
- if (name !== OPENCLAW_PKG && name !== OPENCLAW_ENTRY)
985
- continue;
986
- if (typeof version === "string")
987
- return version;
988
- }
989
- }
990
- return undefined;
991
- }
992
- function openclawInstallState(home, spec) {
993
- // ── The 2026.7.x layout FIRST: it is what a current install produces, and it
994
- // is authoritative whenever it is present.
995
- //
996
- // ⚠️ THIS FUNCTION USED TO READ ONLY `extensions/` + `plugins.installs`, and on
997
- // a real 2026.7.1 machine that produced actively harmful advice. That machine
998
- // carried BOTH a stale `extensions/atbash-openclaw` left from the 2026.2.x era
999
- // AND the real install under `npm/projects/`. The old code saw the stale
1000
- // directory (installed = true), found no `plugins.installs` record — 2026.7.x
1001
- // keeps that in `~/.openclaw/state/openclaw.sqlite` — and concluded "a
1002
- // different, unidentifiable build is installed". Setup then told the operator
1003
- // to `rm -rf ~/.openclaw/extensions/atbash-openclaw` and reinstall, on a
1004
- // machine whose plugin was installed, correct, and loading. The release
1005
- // immediately before had planned a plain `plugins update` for the same box.
1006
- const projectVersion = openclawNpmProjectVersion(home);
1007
- if (projectVersion) {
1008
- // The npm project records a VERSION, not the `@dev`/plain TAG that was asked
1009
- // for, so compare lineage the way verifyOpenclawPlugin does: a `-dev.` build
1010
- // satisfies `@dev` and only that. Comparing the literal spec string here
1011
- // would report every correct install as a mismatch.
1012
- const wantsDev = /@dev$/.test(spec);
1013
- return { installed: true, sameSpec: wantsDev === /-dev\./.test(projectVersion), version: projectVersion };
1014
- }
1015
- if (!exists(path.join(home, ...OPENCLAW_EXTENSIONS_REL, OPENCLAW_ENTRY))) {
1016
- return { installed: false, sameSpec: false };
1017
- }
1018
- const raw = readTextFile(path.join(home, ...OPENCLAW_CONFIG_REL));
1019
- let record = null;
1020
- if (raw !== null) {
1021
- const parsed = jsonc.parse(raw, [], { allowTrailingComma: true, disallowComments: false });
1022
- const installs = isRecord(parsed) && isRecord(parsed.plugins) ? parsed.plugins.installs : null;
1023
- if (isRecord(installs) && isRecord(installs[OPENCLAW_ENTRY])) {
1024
- record = installs[OPENCLAW_ENTRY];
1025
- }
1026
- }
1027
- return {
1028
- installed: true,
1029
- // No record means an install this command did not make and cannot identify.
1030
- // Treated as a mismatch: telling someone to `update` a plugin whose origin
1031
- // is unknown could quietly keep them on a build for the wrong chain.
1032
- sameSpec: typeof record?.spec === "string" && record.spec === spec,
1033
- version: typeof record?.version === "string" ? record.version : undefined,
1034
- };
1035
- }
1036
- function keyPathUpdate(existingConfig, home) {
1037
- const canonical = path.join(home, ...KEY_FILE_REL);
1038
- const current = existingConfig.chromiaSecretPath;
1039
- if (typeof current === "string" && path.resolve(expandHome(current.trim(), home)) === path.resolve(canonical)) {
1040
- return {};
1041
- }
1042
- return { chromiaSecretPath: `~/${KEY_FILE_REL.join("/")}` };
1043
- }
1044
439
  function isRecord(v) {
1045
440
  return !!v && typeof v === "object" && !Array.isArray(v);
1046
441
  }
1047
- /**
1048
- * Detect the indentation a JSON file already uses, so a merge does not reformat
1049
- * the parts it did not touch.
1050
- *
1051
- * Without this, `JSON.stringify(obj, null, 2)` re-indents a tab-indented or
1052
- * 4-space config from top to bottom. The RESULT is still correct, but the diff
1053
- * shown for approval becomes every line in the file, which buries the two lines
1054
- * that actually changed — and the operator's own formatting choice is collateral
1055
- * damage in a file we were asked to make one addition to.
1056
- *
1057
- * Falls back to two spaces, which is what the published docs show.
1058
- */
1059
- function detectIndent(text) {
1060
- if (!text)
1061
- return 2;
1062
- // First line that is indented under an opening brace/bracket tells us the unit.
1063
- const match = text.match(/\n([ \t]+)\S/);
1064
- if (!match)
1065
- return 2;
1066
- const indent = match[1];
1067
- return indent.startsWith("\t") ? "\t" : indent.length;
1068
- }
1069
- /**
1070
- * Serialize a merged config the way the file was already written: same
1071
- * indentation, and a trailing newline only if the original had one.
1072
- */
1073
- function serializeLike(original, value) {
1074
- const body = JSON.stringify(value, null, detectIndent(original));
1075
- // A file that ended without a newline keeps ending without one. Trivial, but it
1076
- // is one more line of unexplained diff for someone reviewing the change.
1077
- const trailing = original === null || original.endsWith("\n") ? "\n" : "";
1078
- return body + trailing;
1079
- }
1080
- /**
1081
- * The MCP server entry setup writes into a client's config.
1082
- *
1083
- * Note what is NOT here: an `env` block. The published `@atbash/mcp` wiring
1084
- * carries the agent's private key in one, because that package reads only
1085
- * ATBASH_AGENT_PRIVKEY. Going through `atbash mcp` instead means the launcher
1086
- * reads the 0600 key file and passes the key to the server in the child process
1087
- * environment, so this entry holds no credential and the client's config file is
1088
- * no more sensitive after setup runs than it was before.
1089
- *
1090
- * Deliberately NOT pinned to an exact CLI version: unlike the one-shot connector
1091
- * command, this entry persists in the operator's config and is re-executed every
1092
- * time the client starts. Pinning here would freeze their MCP server at whatever
1093
- * version happened to be current on the day they ran setup.
1094
- */
1095
- const MCP_SERVER_ENTRY = { command: "npx", args: ["--yes", "@atbash/cli", "mcp"] };
1096
- const MCP_SERVER_NAME = "atbash";
1097
- /**
1098
- * MCP client configs present under this home directory.
1099
- *
1100
- * Paths come from the shared MCP_CONFIGS so the writer and the scanner cannot
1101
- * drift: a client the scan reports but setup cannot find would look like a bug in
1102
- * whichever of the two the operator happened to trust.
1103
- */
1104
- function detectMcpClients(home) {
1105
- const out = [];
1106
- const seen = new Set();
1107
- for (const { label, segs } of atbash_targets_1.MCP_CONFIGS) {
1108
- if (seen.has(label))
1109
- continue;
1110
- const file = path.join(home, ...segs);
1111
- if (!exists(file))
1112
- continue;
1113
- seen.add(label);
1114
- // Read which key this file already uses rather than assuming. VS Code's
1115
- // mcp.json uses `servers`; writing `mcpServers` into it would be ignored.
1116
- const existing = readJsonLoose(file);
1117
- const serversKey = existing && isRecord(existing.servers) && !isRecord(existing.mcpServers) ? "servers" : "mcpServers";
1118
- out.push({ label, file, format: "json", serversKey });
1119
- }
1120
- // Claude Code and Codex are special-cased in the scanner too — same paths.
1121
- const claudeCode = path.join(home, ".claude.json");
1122
- if (exists(claudeCode))
1123
- out.push({ label: "Claude Code", file: claudeCode, format: "json", serversKey: "mcpServers" });
1124
- const codex = path.join(home, ".codex", "config.toml");
1125
- if (exists(codex))
1126
- out.push({ label: "Codex", file: codex, format: "toml", serversKey: "mcpServers" });
1127
- return out;
1128
- }
1129
- /** Tolerant read used only to sniff an existing file's shape. */
1130
- function readJsonLoose(file) {
1131
- const text = readTextFile(file);
1132
- if (text === null)
1133
- return null;
1134
- const value = jsonc.parse(text, [], { allowTrailingComma: true, disallowComments: false });
1135
- return isRecord(value) ? value : null;
1136
- }
1137
- /**
1138
- * Add the Atbash server to a client config's server map, in place.
1139
- *
1140
- * A merge, like the OpenClaw one: every server the operator already configured
1141
- * stays exactly as it is. An existing `atbash` entry is REPLACED rather than
1142
- * merged field-by-field — a stale `env` block carrying a private key from the old
1143
- * hand-written wiring is precisely what we want gone, and preserving it would
1144
- * defeat the point of routing through the launcher.
1145
- */
1146
- /** The Hermes plugin, and the exact version the wiring is written against. */
1147
- const HERMES_PKG = "atbash-hermes-plugin";
1148
- const HERMES_VERSION = "0.4.5";
1149
- /** The name Hermes lists this plugin under, and the allow-list entry. */
1150
- const HERMES_PLUGIN_ENTRY = "atbash-hermes-plugin";
1151
- /**
1152
- * Find the Python interpreter that actually runs Hermes.
1153
- *
1154
- * This is the difference between installing the plugin and only appearing to.
1155
- * `pip install atbash-hermes-plugin` puts the package wherever the *shell's*
1156
- * `pip` points — commonly a system or conda Python — while Hermes typically runs
1157
- * from its own virtualenv. The install succeeds, prints nothing alarming, and the
1158
- * plugin is invisible to Hermes forever. Nobody can debug that from the output.
1159
- *
1160
- * The launcher knows the answer. A pip-installed console script begins with a
1161
- * shebang naming the interpreter that created it:
1162
- *
1163
- * $ head -1 $(command -v hermes)
1164
- * #!/Users/me/.hermes/hermes-agent/venv/bin/python3
1165
- *
1166
- * So resolve `hermes`, read its first line, and use that interpreter directly via
1167
- * `-m pip`. Falls back to the conventional venv location under ~/.hermes, then to
1168
- * null — and a null becomes a printed command rather than a guess, because a
1169
- * wrong guess here is the silent failure this whole function exists to avoid.
1170
- */
1171
- function findHermesPython(home) {
1172
- const viable = (candidate) => {
1173
- try {
1174
- return fs.statSync(candidate).isFile();
1175
- }
1176
- catch {
1177
- return false;
1178
- }
1179
- };
1180
- // 1. The launcher's own shebang — authoritative, but only for a real run.
1181
- //
1182
- // `--home <dir>` exists so a dry run can be hermetic (the release checklist
1183
- // depends on it). A PATH lookup ignores it entirely: under `--home /tmp/fake`
1184
- // this would find the operator's ACTUAL hermes and plan an install into their
1185
- // real virtualenv. So the shebang route is skipped whenever `home` is not the
1186
- // machine's own home — the caller then falls through to the venv path under the
1187
- // given home, which is correctly scoped.
1188
- const realHome = process.env.HOME || os.homedir();
1189
- const scoped = path.resolve(home) !== path.resolve(realHome);
1190
- const which = scoped
1191
- ? { status: 1, stdout: "" }
1192
- : (0, child_process_1.spawnSync)(process.platform === "win32" ? "where" : "which", ["hermes"], { encoding: "utf8" });
1193
- const launcher = which.status === 0 ? which.stdout.split(/\r?\n/)[0]?.trim() : "";
1194
- if (launcher && viable(launcher)) {
1195
- const firstLine = (readTextFile(launcher) ?? "").split(/\r?\n/)[0] ?? "";
1196
- const shebang = firstLine.startsWith("#!") ? firstLine.slice(2).trim() : "";
1197
- // `#!/usr/bin/env python3` names no path; anything else should be absolute.
1198
- const interpreter = shebang.split(/\s+/).filter((part) => !part.endsWith("/env"))[0] ?? "";
1199
- if (/python[0-9.]*$/.test(interpreter) && viable(interpreter)) {
1200
- return { python: interpreter, how: `shebang of ${launcher}` };
1201
- }
1202
- }
1203
- // 2. The conventional venv Hermes ships with.
1204
- for (const name of ["python3", "python"]) {
1205
- const candidate = path.join(home, ".hermes", "hermes-agent", "venv", "bin", name);
1206
- if (viable(candidate))
1207
- return { python: candidate, how: "Hermes virtualenv under ~/.hermes" };
1208
- }
1209
- return null;
1210
- }
1211
- /** Same rule as buildPlan's `wanted`: an empty --runtime list means everything. */
1212
- function wantedRuntime(id, only) {
1213
- return only.length === 0 || only.includes(id);
1214
- }
1215
- /**
1216
- * Add the plugin to Hermes' opt-in allow-list at `plugins.enabled` in
1217
- * `~/.hermes/config.yaml`.
1218
- *
1219
- * WHY NOT `hermes plugins enable`: that command cannot accept this plugin, on
1220
- * this version, ever. `_plugin_exists` (hermes_cli/plugins_cmd.py) looks only for
1221
- * a DIRECTORY in the user plugins dir or a bundled dir — it never consults entry
1222
- * points. Meanwhile the runtime loader (`plugins.py:_scan_entry_points`) does
1223
- * discover them. So Hermes will happily LOAD a pip-installed plugin but refuses
1224
- * to put one on the allow-list it requires, and since plugins are opt-in, a
1225
- * package that cannot get onto the list can never load. Running that command
1226
- * exits 1 with "not installed or bundled". Writing the list entry directly is the
1227
- * only route that works.
1228
- *
1229
- * A LINE MERGE, not a parse-and-reserialize. config.yaml is tens of kilobytes of
1230
- * heavily commented configuration; round-tripping it through a YAML emitter would
1231
- * strip every comment and reflow the file. So this inserts the one line needed and
1232
- * leaves every other byte alone — the same discipline as the .env merge.
1233
- */
1234
- function mergeHermesEnabledPlugins(existing, plugin = HERMES_PLUGIN_ENTRY) {
1235
- const lines = existing === null ? [] : existing.split("\n");
1236
- // Already on the list? Then there is nothing to do.
1237
- const pluginsAt = lines.findIndex((l) => /^plugins:\s*(#.*)?$/.test(l));
1238
- if (pluginsAt !== -1) {
1239
- // Walk the plugins block (indented lines) looking for `enabled:` and its items.
1240
- let enabledAt = -1;
1241
- let end = lines.length;
1242
- for (let i = pluginsAt + 1; i < lines.length; i++) {
1243
- const line = lines[i];
1244
- if (line.trim() === "" || line.startsWith("#"))
1245
- continue;
1246
- if (!/^\s/.test(line)) {
1247
- end = i;
1248
- break;
1249
- } // dedented — block over
1250
- if (/^\s+enabled:\s*(#.*)?$/.test(line))
1251
- enabledAt = i;
1252
- }
1253
- if (enabledAt !== -1) {
1254
- // Collect the list items under `enabled:` and bail if ours is there.
1255
- const itemIndent = (lines[enabledAt].match(/^\s*/)?.[0] ?? " ") + " ";
1256
- let last = enabledAt;
1257
- for (let i = enabledAt + 1; i < end; i++) {
1258
- if (/^\s*-\s+/.test(lines[i])) {
1259
- if (lines[i].replace(/^\s*-\s+/, "").trim().replace(/^["']|["']$/g, "") === plugin)
1260
- return existing;
1261
- last = i;
1262
- }
1263
- else if (lines[i].trim() !== "")
1264
- break;
1265
- }
1266
- lines.splice(last + 1, 0, `${itemIndent}- ${plugin}`);
1267
- return lines.join("\n");
1268
- }
1269
- // A plugins block with no `enabled:` key — add one inside it.
1270
- lines.splice(pluginsAt + 1, 0, " enabled:", ` - ${plugin}`);
1271
- return lines.join("\n");
1272
- }
1273
- // No plugins block at all — which is the default, and means nothing loads.
1274
- const out = existing === null ? [] : [...lines];
1275
- if (out.length && out[out.length - 1].trim() !== "")
1276
- out.push("");
1277
- out.push("# Added by `atbash setup` - Hermes loads only plugins on this allow-list");
1278
- out.push("plugins:", " enabled:", ` - ${plugin}`);
1279
- let text = out.join("\n");
1280
- if (!text.endsWith("\n"))
1281
- text += "\n";
1282
- return text;
1283
- }
1284
- /**
1285
- * Is a Hermes gateway service running, and therefore restartable?
1286
- *
1287
- * "Restart Hermes" only means something when there is a service to bounce.
1288
- * Hermes has two shapes: `hermes` starts an interactive chat session, and
1289
- * `hermes gateway install` registers a launchd/systemd background service. A
1290
- * setup command must not conflate them —
1291
- *
1292
- * - with a service running, `hermes gateway restart` picks up the new config and
1293
- * is worth doing for the operator;
1294
- * - without one, there is nothing to restart. The plugin loads the next time
1295
- * they run `hermes`, and anything we "restarted" would either be a no-op or,
1296
- * worse, an interactive session someone is in the middle of using.
1297
- *
1298
- * `gateway status` exits 0 either way, so the state comes from its text.
1299
- */
1300
- function hermesGatewayRunning() {
1301
- const probe = (0, child_process_1.spawnSync)("hermes", ["gateway", "status"], { encoding: "utf8" });
1302
- if (probe.status !== 0 || typeof probe.stdout !== "string")
1303
- return false;
1304
- // "✗ Gateway is not running" vs a running report.
1305
- return !/not\s+running/i.test(probe.stdout);
1306
- }
1307
- /**
1308
- * Is Hermes CONFIGURED to load the plugin?
1309
- *
1310
- * This used to shell out to `hermes plugins list` and look for an atbash row —
1311
- * a signal that can never be true. `_discover_all_plugins` (plugins_cmd.py) walks
1312
- * plugin DIRECTORIES only: bundled, user, project. It never scans entry points,
1313
- * exactly like the `_plugin_exists` gate behind `plugins enable`. So a
1314
- * pip-installed plugin is invisible to both, and the check reported "not picked
1315
- * up" while everything was in fact correct — then told the operator to run the
1316
- * enable command that cannot work. Advising a known-impossible fix is worse than
1317
- * saying nothing.
1318
- *
1319
- * The two facts that actually decide it are both on disk:
1320
- *
1321
- * 1. the package is importable by the interpreter that runs Hermes, and
1322
- * 2. its name is on the `plugins.enabled` allow-list in config.yaml, which is
1323
- * what the RUNTIME loader (`plugins.py:_scan_entry_points`) honours.
1324
- *
1325
- * "configured" is as far as a setup command can honestly go. Proof of loading is
1326
- * a line in the agent log after Hermes next starts, which is why the caller points
1327
- * at that rather than claiming enforcement.
1328
- */
1329
- function hermesPluginState(home) {
1330
- const venvBase = path.join(home, ".hermes", "hermes-agent", "venv", "lib");
1331
- let installed = false;
1332
- try {
1333
- installed = fs.readdirSync(venvBase, { withFileTypes: true })
1334
- .filter((e) => e.isDirectory())
1335
- .some((e) => exists(venvBase, e.name, "site-packages", "atbash_hermes_plugin"));
1336
- }
1337
- catch {
1338
- return "unknown";
1339
- }
1340
- const configYaml = readTextFile(path.join(home, ".hermes", "config.yaml"));
1341
- if (configYaml === null)
1342
- return installed ? "not-enabled" : "not-installed";
1343
- let enabled = false;
1344
- try {
1345
- const parsed = (0, yaml_1.parse)(configYaml);
1346
- const list = parsed?.plugins?.enabled;
1347
- enabled = Array.isArray(list) && list.some((n) => String(n).trim() === HERMES_PLUGIN_ENTRY);
1348
- }
1349
- catch {
1350
- return "unknown";
1351
- }
1352
- if (!installed)
1353
- return "not-installed";
1354
- return enabled ? "configured" : "not-enabled";
1355
- }
1356
- /**
1357
- * How to install a Python package into a specific interpreter on THIS machine.
1358
- *
1359
- * `<python> -m pip install` is the obvious answer and it is frequently wrong: a
1360
- * venv created by `uv venv` has no pip at all (that is uv's default), so the
1361
- * command fails with
1362
- *
1363
- * /path/venv/bin/python3: No module named pip
1364
- *
1365
- * after setup has already written every config file — which is exactly what
1366
- * happened on a real Hermes box. So probe, in order of what suits the venv:
1367
- *
1368
- * 1. `uv pip install --python <python>` when uv is present. Correct for a
1369
- * uv-created venv and fast; uv is also what created most pip-less venvs.
1370
- * 2. `<python> -m pip install` when pip actually answers.
1371
- * 3. Neither — hand it over, with `ensurepip` named, rather than planning a
1372
- * command that is known in advance to fail.
1373
- */
1374
- function pythonInstallStrategy(python, pkg) {
1375
- const uv = (0, child_process_1.spawnSync)(process.platform === "win32" ? "where" : "which", ["uv"], { stdio: "ignore" });
1376
- if (uv.status === 0) {
1377
- return {
1378
- kind: "exec",
1379
- command: "uv",
1380
- args: ["pip", "install", "--python", python, pkg],
1381
- how: "uv, targeting the interpreter that runs Hermes",
1382
- };
1383
- }
1384
- const pip = (0, child_process_1.spawnSync)(python, ["-m", "pip", "--version"], { stdio: "ignore" });
1385
- if (pip.status === 0) {
1386
- return { kind: "exec", command: python, args: ["-m", "pip", "install", pkg], how: "pip in the interpreter that runs Hermes" };
1387
- }
1388
- return {
1389
- kind: "manual",
1390
- why: `${python} has no pip (a venv created by \`uv venv\` has none by default) and uv is not on PATH, so setup cannot install into it. Bootstrap pip, then install:`,
1391
- snippet: [`${python} -m ensurepip --upgrade`, `${python} -m pip install ${pkg}`].join("\n"),
1392
- };
1393
- }
1394
- /**
1395
- * The env vars the Hermes plugin documents, merged into an existing `.env`.
1396
- *
1397
- * A `.env` is line-oriented and hand-maintained, so this is a line merge rather
1398
- * than a parse-and-reserialize: keys Atbash owns are replaced in place (keeping
1399
- * their position), keys it does not own are never touched, and anything else in
1400
- * the file — comments, blank lines, unrelated settings, ordering — survives
1401
- * exactly as written. Reformatting someone's .env to add four lines would be a
1402
- * poor trade.
1403
- *
1404
- * Values are from the published plugin README (PyPI atbash-hermes-plugin 0.4.5).
1405
- * `ATBASH_ORG_NAME` is deliberately NOT written: its value is the operator's org,
1406
- * which this command has no reliable way to know, and a wrong org sends the SDK
1407
- * at the wrong chain. It is called out in the manual step instead.
1408
- */
1409
- function mergeHermesEnv(existing) {
1410
- const desired = {
1411
- ATBASH_KEY_PATH: "$HOME/.config/atbash/guard-client-key",
1412
- ATBASH_ENFORCE_DECISION: "true",
1413
- };
1414
- const lines = existing === null ? [] : existing.split("\n");
1415
- const seen = new Set();
1416
- const out = lines.map((line) => {
1417
- const match = line.match(/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=/);
1418
- const key = match?.[1];
1419
- if (!key || !(key in desired) || seen.has(key))
1420
- return line;
1421
- seen.add(key);
1422
- // Already correct — keep the operator's own formatting rather than rewriting.
1423
- if (line.trim() === `${key}=${desired[key]}`)
1424
- return line;
1425
- return `${key}=${desired[key]}`;
1426
- });
1427
- const missing = Object.entries(desired).filter(([key]) => !seen.has(key));
1428
- if (missing.length) {
1429
- // Separate the block we add from whatever came before it.
1430
- if (out.length && out[out.length - 1].trim() !== "")
1431
- out.push("");
1432
- // ASCII-only comment on purpose: .env files are read by many different
1433
- // parsers and a stray multi-byte dash is a free way to trip a strict one.
1434
- if (existing !== null)
1435
- out.push("# Added by `atbash setup` - Atbash Hermes plugin");
1436
- for (const [key, value] of missing)
1437
- out.push(`${key}=${value}`);
1438
- }
1439
- let text = out.join("\n");
1440
- if (!text.endsWith("\n"))
1441
- text += "\n";
1442
- return text;
1443
- }
1444
- /**
1445
- * Does this config's existing Atbash entry carry a key in its `env` block?
1446
- *
1447
- * True means the operator hand-wired it from the published docs and their private
1448
- * key is sitting in that file today. Setup takes it out, but the backup it writes
1449
- * first still has it — so this exists to make that sayable rather than silently
1450
- * relocating the leak.
1451
- */
1452
- function hadInlineKey(config, serversKey = "mcpServers") {
1453
- const servers = isRecord(config[serversKey]) ? config[serversKey] : undefined;
1454
- const entry = servers && isRecord(servers[MCP_SERVER_NAME]) ? servers[MCP_SERVER_NAME] : undefined;
1455
- const env = entry && isRecord(entry.env) ? entry.env : undefined;
1456
- if (!env)
1457
- return false;
1458
- // Any 64-hex value, under any key name — not just the documented one, since a
1459
- // hand-edited config may well have renamed it.
1460
- return Object.values(env).some((v) => typeof v === "string" && /^(0x)?[0-9a-fA-F]{64}$/.test(v.trim()));
1461
- }
1462
- function mergeMcpServer(config, serversKey = "mcpServers") {
1463
- const out = { ...config };
1464
- const servers = { ...(isRecord(out[serversKey]) ? out[serversKey] : {}) };
1465
- servers[MCP_SERVER_NAME] = { ...MCP_SERVER_ENTRY, args: [...MCP_SERVER_ENTRY.args] };
1466
- out[serversKey] = servers;
1467
- return out;
1468
- }
1469
- /** The exec-step id the OpenClaw config write depends on. See Step.requires. */
1470
- const OPENCLAW_INSTALL_ID = "openclaw-install";
1471
- /**
1472
- * The change we want, expressed as a PATCH rather than a whole file.
1473
- *
1474
- * `openclaw config patch` merges objects recursively and validates in one write,
1475
- * so this is intent — "this entry should exist and look like this" — instead of
1476
- * "here are the complete new bytes of your config". That difference is what makes
1477
- * it survive the things that kept defeating us from outside: OpenClaw's own
1478
- * format changes, key renames, comment preservation, file permissions, its
1479
- * migrations, and the fact that it rewrites `openclaw.json` on its own (a machine
1480
- * in the field carried three `openclaw.json.clobbered.<timestamp>` files).
1481
- *
1482
- * ⚠️ DO NOT call `config patch --dry-run` from buildPlan to preview this. It is
1483
- * NOT side-effect free: running it triggers OpenClaw's state migrations, which
1484
- * wrote `~/.openclaw/update-check.json.migrated` and moved config-health state
1485
- * into SQLite on the machine this was developed on. `atbash setup --dry-run`
1486
- * promises that nothing is written, and that promise has to hold for OpenClaw's
1487
- * housekeeping too. The preview stays a merge we compute ourselves.
1488
- */
1489
- function openclawPatchPayload(args) {
1490
- const entries = {
1491
- [args.entryKey]: {
1492
- enabled: true,
1493
- // See HOOK_PERMISSIONS: `allowPromptInjection` defaults to ALLOWED, so
1494
- // without this the guard holds a prompt-mutation permission it never uses.
1495
- // `config patch` merges recursively, so an operator's own `hooks` keys
1496
- // (timeoutMs/timeouts) survive alongside it.
1497
- ...(args.hooksSupported ? { hooks: { ...HOOK_PERMISSIONS } } : {}),
1498
- config: {
1499
- enabled: true,
1500
- enforceDecision: true,
1501
- chromiaSecretPath: args.keyPath,
1502
- ...(args.entryKey !== OPENCLAW_LEGACY_ENTRY && args.orgName?.trim() ? { orgName: args.orgName.trim() } : {}),
1503
- },
1504
- },
1505
- };
1506
- // Two live entries means two hooks and every tool call judged twice against two
1507
- // different SDKs, so the handover happens in the SAME patch as the new entry —
1508
- // never as a second write that could land on its own.
1509
- if (args.standDownLegacy)
1510
- entries[OPENCLAW_LEGACY_ENTRY] = { enabled: false };
1511
- return `${JSON.stringify({ plugins: { entries } }, null, 2)}\n`;
1512
- }
1513
442
  /** Is `openclaw` runnable on this machine? Decides install-for-you vs print-it. */
1514
443
  function hasExecutable(command) {
1515
444
  const probe = (0, child_process_1.spawnSync)(process.platform === "win32" ? "where" : "which", [command], { stdio: "ignore" });
@@ -1524,13 +453,7 @@ function hasExecutable(command) {
1524
453
  * writes a config for a plugin they do not have.
1525
454
  */
1526
455
  function buildPlan(args) {
1527
- const { home, privkey, pubkey, noInstall, only, orgName, endpoint } = args;
1528
- // Capability, never a version comparison. A version table is what went stale
1529
- // and produced a config that broke a fresh machine.
1530
- const canPatch = Boolean(args.openclaw?.caps.patch);
1531
- // Probed, never inferred: `hooks` is unknown on 2026.2.1 and valid on 2026.6.6+,
1532
- // so the same key is fatal on one build and legitimate on the other.
1533
- const hooksSupported = args.openclaw?.hooksSupported === true;
456
+ const { home, privkey, pubkey, noInstall, only } = args;
1534
457
  const steps = [];
1535
458
  const notes = [];
1536
459
  const found = [];
@@ -1543,33 +466,7 @@ function buildPlan(args) {
1543
466
  const alreadyThisKey = currentKeyFile !== null && parseKeyMaterial(currentKeyFile)?.privkey === privkey;
1544
467
  if (!alreadyThisKey) {
1545
468
  if (currentKeyFile !== null) {
1546
- // The outgoing key belongs to a real agent that this machine may still be
1547
- // governing. A `.atbash-bak` preserves the bytes but not the identity — six
1548
- // months later nobody knows which agent `guard-client-key.atbash-bak` was.
1549
- // So archive it under its own public key: recoverable, self-identifying,
1550
- // and a path a runtime config can point at directly if this box needs to
1551
- // run two agents (both OpenClaw's `chromiaSecretPath` and Hermes'
1552
- // `ATBASH_KEY_PATH` take an explicit path).
1553
- const outgoing = parseKeyMaterial(currentKeyFile);
1554
- const outgoingPub = outgoing ? (0, sdk_1.derivePublicKey)(outgoing.privkey) : null;
1555
- if (outgoingPub) {
1556
- const archive = path.join(home, ".config", "atbash", "keys", `${outgoingPub}.key`);
1557
- if (!exists(archive)) {
1558
- steps.push({
1559
- kind: "write",
1560
- label: `Archive the agent key already on this machine (${outgoingPub.slice(0, 12)}…)`,
1561
- file: archive,
1562
- mode: KEY_MODE,
1563
- before: null,
1564
- after: currentKeyFile,
1565
- secret: true,
1566
- });
1567
- }
1568
- notes.push(`${keyFile} currently holds a DIFFERENT agent (${outgoingPub.slice(0, 12)}…). It is archived to ~/.config/atbash/keys/${outgoingPub.slice(0, 12)}….key before being replaced, so that agent is recoverable — but every integration on this machine reading the default path will switch to the new agent.`);
1569
- }
1570
- else {
1571
- notes.push(`${keyFile} holds something this command could not parse as an agent key. It will be backed up before being replaced.`);
1572
- }
469
+ notes.push(`${keyFile} already holds a DIFFERENT agent key. It will be backed up before being replaced — check that you meant to re-point this machine at another agent.`);
1573
470
  }
1574
471
  steps.push({
1575
472
  kind: "write",
@@ -1592,118 +489,26 @@ function buildPlan(args) {
1592
489
  if (wanted("openclaw")) {
1593
490
  if (!noInstall) {
1594
491
  if (hasExecutable("openclaw")) {
1595
- const spec = openclawPackageForHost(endpoint);
1596
- const installed = openclawInstallState(home, spec);
1597
- if (!installed.installed) {
1598
- steps.push({
1599
- kind: "exec",
1600
- label: spec.endsWith("@dev")
1601
- ? `Install ${spec} — the development build, matching the deployment this agent was onboarded on`
1602
- : `Install ${spec} — the production build`,
1603
- command: "openclaw",
1604
- args: ["plugins", "install", spec],
1605
- id: OPENCLAW_INSTALL_ID,
1606
- });
1607
- }
1608
- else if (installed.sameSpec) {
1609
- // Already the right package: refresh it rather than re-installing.
1610
- // `plugins install` would abort with "plugin already exists" and take
1611
- // the whole run down with it — see openclawInstallState.
1612
- steps.push({
1613
- kind: "exec",
1614
- label: `Update ${spec} to the newest build under its tag (installed: ${installed.version ?? "unknown"})`,
1615
- command: "openclaw",
1616
- // Deliberately NOT tagged with OPENCLAW_INSTALL_ID: the plugin is
1617
- // already on disk here, so the config entry refers to something real
1618
- // whether or not this refresh succeeds. Gating the config on an
1619
- // update would withhold a correct config over a failed download.
1620
- args: ["plugins", "update", OPENCLAW_ENTRY],
1621
- });
1622
- }
1623
- else {
1624
- // A DIFFERENT spec is installed — typically the production build on a
1625
- // machine onboarded against a dev deployment, or the reverse. This is
1626
- // not cosmetic: the judge endpoint and chain ids come from the SDK the
1627
- // plugin bundles, so the wrong build fails every judge call against a
1628
- // chain this agent is not on. It cannot be fixed by `update`, which
1629
- // re-resolves the spec already recorded, and 2026.2.1 has no
1630
- // `plugins uninstall`, so the directory has to go by hand.
1631
- steps.push({
1632
- kind: "manual",
1633
- label: `Replace the installed OpenClaw plugin with ${spec}`,
1634
- detail: `A different build is installed${installed.version ? ` (${installed.version})` : ""} and OpenClaw cannot overwrite it — \`plugins install\` aborts with "plugin already exists", and \`plugins update\` would only re-resolve the spec it already has. The plugin's judge endpoint and chain ids come from the SDK it bundles, so the wrong build fails every judge call. Remove it and install the right one:`,
1635
- snippet: `rm -rf ${path.join(home, ...OPENCLAW_EXTENSIONS_REL, OPENCLAW_ENTRY)}\nopenclaw plugins install ${spec}`,
1636
- });
1637
- }
1638
- if (spec.endsWith("@dev")) {
1639
- notes.push("The plugin's judge endpoint and chain ids come from the SDK it bundles, so the npm tag is an environment choice. This agent was onboarded on a development deployment, so the `@dev` build is the matching one — the production build would load, fire its hook, and fail every judge call because the agent does not exist on the chain it targets.");
1640
- }
492
+ steps.push({ kind: "exec", label: `Install ${OPENCLAW_PKG}`, command: "openclaw", args: ["plugins", "install", OPENCLAW_PKG] });
1641
493
  }
1642
494
  else {
1643
495
  steps.push({
1644
496
  kind: "manual",
1645
497
  label: "Install the OpenClaw plugin",
1646
498
  detail: "The `openclaw` command is not on this machine's PATH, so the plugin cannot be installed for you. Run this wherever the OpenClaw CLI lives:",
1647
- snippet: `openclaw plugins install ${openclawPackageForHost(endpoint)}`,
499
+ snippet: `openclaw plugins install ${OPENCLAW_PKG}`,
1648
500
  });
1649
501
  }
1650
502
  }
1651
503
  const raw = readTextFile(openclawConfigFile);
1652
- // The config entry must not be written unless the plugin it names is going
1653
- // to exist. `requires` is set only for a FRESH install — see Step.requires
1654
- // for what a dangling entry costs.
1655
- const requires = steps.some((s) => s.kind === "exec" && s.id === OPENCLAW_INSTALL_ID)
1656
- ? OPENCLAW_INSTALL_ID
1657
- : undefined;
1658
- // Hand the merge to OpenClaw where it can do it: one validated write, in
1659
- // its own current format, whatever that has become.
1660
- //
1661
- // The entry decision comes from the SAME function the hand-merge uses, so
1662
- // the two paths cannot pick different keys — see openclawEntryDecision.
1663
- let parsedForDecision = {};
1664
- if (raw !== null) {
1665
- try {
1666
- const p = isJsonc(raw)
1667
- ? jsonc.parse(raw, [], { allowTrailingComma: true, disallowComments: false })
1668
- : JSON.parse(raw);
1669
- if (isRecord(p))
1670
- parsedForDecision = p;
1671
- }
1672
- catch {
1673
- /* an unparseable config decides nothing; treat it as empty */
1674
- }
1675
- }
1676
- const decision = openclawEntryDecision(parsedForDecision, { installsModern: !noInstall });
1677
- const patchPayload = canPatch
1678
- ? openclawPatchPayload({
1679
- entryKey: decision.entryKey,
1680
- orgName,
1681
- keyPath: `~/${KEY_FILE_REL.join("/")}`,
1682
- standDownLegacy: decision.standDownLegacy,
1683
- hooksSupported,
1684
- })
1685
- : undefined;
1686
504
  if (raw !== null && isJsonc(raw)) {
1687
- // A config with comments or trailing commas. Rewriting it as strict JSON
1688
- // deletes the operator's comments, so we never do that.
1689
- //
1690
- // But `openclaw config patch` can edit this file WITHOUT losing them —
1691
- // it is OpenClaw's own JSON5-aware writer. So where that exists, the
1692
- // operator gets one command instead of a hand-merge, and this stops
1693
- // being the awkward case.
1694
- steps.push(patchPayload
1695
- ? {
1696
- kind: "manual",
1697
- label: `Enable the plugin in ${openclawConfigFile}`,
1698
- detail: "That file uses comments or trailing commas, so Atbash will not rewrite it — doing so as strict JSON would delete them. OpenClaw can apply the change itself and keep your comments. Run this (it validates before writing, and changes nothing else):",
1699
- snippet: `openclaw config patch --stdin <<'JSON'\n${patchPayload.trimEnd()}\nJSON`,
1700
- }
1701
- : {
1702
- kind: "manual",
1703
- label: `Enable the plugin in ${openclawConfigFile}`,
1704
- detail: "That file uses comments or trailing commas, and rewriting it as strict JSON would delete them. Merge this into the existing `plugins` object by hand — keep any other plugins already in `entries`:",
1705
- snippet: JSON.stringify(mergeOpenclawConfig((jsonc.parse(raw, [], { allowTrailingComma: true, disallowComments: false }) ?? {}), home, orgName, { installsModern: !noInstall, hooksSupported }), null, 2),
1706
- });
505
+ // Rewriting this would delete the owner's comments. Print instead.
506
+ steps.push({
507
+ kind: "manual",
508
+ label: `Enable the plugin in ${openclawConfigFile}`,
509
+ detail: "That file uses comments or trailing commas, and rewriting it as strict JSON would delete them. Merge this into the existing `plugins` object by hand — keep any other plugins already in `allow` and `entries`:",
510
+ snippet: JSON.stringify(mergeOpenclawConfig((jsonc.parse(raw, [], { allowTrailingComma: true, disallowComments: false }) ?? {}), home), null, 2),
511
+ });
1707
512
  }
1708
513
  else {
1709
514
  let current = {};
@@ -1717,37 +522,16 @@ function buildPlan(args) {
1717
522
  notes.push(`${openclawConfigFile} is not valid JSON — it will be backed up and rewritten from scratch, which loses whatever was in it. Fix the file first if it holds configuration you need.`);
1718
523
  }
1719
524
  }
1720
- const after = serializeLike(raw, mergeOpenclawConfig(current, home, orgName, { installsModern: !noInstall, hooksSupported }));
525
+ const after = JSON.stringify(mergeOpenclawConfig(current, home), null, 2) + "\n";
1721
526
  if (raw !== after) {
1722
527
  steps.push({
1723
528
  kind: "write",
1724
529
  label: raw === null
1725
530
  ? "Create ~/.openclaw/openclaw.json with the plugin enabled"
1726
- : patchPayload
1727
- ? "Enable the plugin in ~/.openclaw/openclaw.json (OpenClaw applies and validates the merge itself)"
1728
- : "Enable the plugin in ~/.openclaw/openclaw.json (a merge — existing plugins are kept)",
531
+ : "Enable the plugin in ~/.openclaw/openclaw.json (a merge — existing plugins are kept)",
1729
532
  file: openclawConfigFile,
1730
533
  before: raw,
1731
534
  after,
1732
- ...(requires ? { requires } : {}),
1733
- // The diff above is the merge WE compute, and it is what the operator
1734
- // approves. Where OpenClaw can apply the change itself we send it the
1735
- // equivalent patch instead of these bytes, so the result is validated
1736
- // and written in OpenClaw's own current format. The two agree on
1737
- // content; OpenClaw may differ on formatting, and its formatting is
1738
- // the correct one.
1739
- ...(patchPayload
1740
- ? {
1741
- applyVia: {
1742
- command: "openclaw",
1743
- args: ["config", "patch", "--stdin"],
1744
- payload: patchPayload,
1745
- // Pin the target so the patch cannot land on a different
1746
- // config than the one this step names — see applyVia.env.
1747
- env: { OPENCLAW_CONFIG_PATH: openclawConfigFile },
1748
- },
1749
- }
1750
- : {}),
1751
535
  });
1752
536
  }
1753
537
  else {
@@ -1763,188 +547,47 @@ function buildPlan(args) {
1763
547
  // judged. Setup places the key file and says so; it does not pretend to wire it.
1764
548
  if (exists(home, ...HERMES_AGENT_REL)) {
1765
549
  found.push("Hermes");
1766
- if (wanted("hermes")) {
1767
- const envFile = path.join(home, ".hermes", ".env");
1768
- const raw = readTextFile(envFile);
1769
- const merged = mergeHermesEnv(raw);
1770
- if (merged !== raw) {
1771
- steps.push({
1772
- kind: "write",
1773
- label: raw === null
1774
- ? "Create ~/.hermes/.env pointing the Hermes plugin at the agent key"
1775
- : "Point the Hermes plugin at the agent key in ~/.hermes/.env (a merge — your other settings are kept)",
1776
- file: envFile,
1777
- before: raw,
1778
- after: merged,
1779
- });
1780
- }
1781
- else {
1782
- notes.push(`${envFile} already points the Hermes plugin at this key — left untouched.`);
1783
- }
1784
- const hermesConfig = path.join(home, ".hermes", "config.yaml");
1785
- const rawConfig = readTextFile(hermesConfig);
1786
- const withPlugin = mergeHermesEnabledPlugins(rawConfig);
1787
- if (withPlugin !== rawConfig) {
1788
- steps.push({
1789
- kind: "write",
1790
- label: rawConfig === null
1791
- ? "Create ~/.hermes/config.yaml enabling the plugin"
1792
- : "Add the plugin to Hermes' enabled allow-list in ~/.hermes/config.yaml",
1793
- file: hermesConfig,
1794
- before: rawConfig,
1795
- after: withPlugin,
1796
- });
1797
- notes.push("Hermes loads ONLY plugins on the `plugins.enabled` allow-list, so installing the package is not enough. `hermes plugins enable` cannot add it that command only recognises plugin directories, not pip-installed entry points so setup writes the list entry directly.");
1798
- }
1799
- else if (rawConfig !== null) {
1800
- notes.push(`${hermesConfig} already has the plugin on its enabled list — left untouched.`);
1801
- }
1802
- // Only a running gateway service can be restarted for them. An interactive
1803
- // session cannot, and must not be see hermesGatewayRunning.
1804
- const restartable = hasExecutable("hermes") && hermesGatewayRunning();
1805
- // The Python package must land in the interpreter that RUNS Hermes, not
1806
- // whichever pip the shell happens to resolve. When we can identify that
1807
- // interpreter we install into it directly; when we cannot, we hand the
1808
- // command over rather than guess, because guessing wrong installs
1809
- // successfully and governs nothing.
1810
- if (!noInstall) {
1811
- const hermesPython = findHermesPython(home);
1812
- if (hermesPython) {
1813
- const spec = `${HERMES_PKG}==${HERMES_VERSION}`;
1814
- const strategy = pythonInstallStrategy(hermesPython.python, spec);
1815
- if (strategy.kind === "exec") {
1816
- steps.push({
1817
- kind: "exec",
1818
- label: `Install ${HERMES_PKG} via ${strategy.how} (interpreter found via ${hermesPython.how})`,
1819
- command: strategy.command,
1820
- args: strategy.args,
1821
- });
1822
- }
1823
- else {
1824
- steps.push({
1825
- kind: "manual",
1826
- label: "Install the Hermes plugin",
1827
- detail: strategy.why,
1828
- snippet: strategy.snippet,
1829
- });
1830
- }
1831
- // The plugin pins atbash-sdk==0.4.5, which constrains cryptography — on
1832
- // a venv with a newer one this install is a DOWNGRADE of a shared
1833
- // dependency. Say so; it is the kind of thing that breaks the host app
1834
- // and is invisible in a list of file writes.
1835
- notes.push(`Installing ${HERMES_PKG} may change shared Python dependencies in that venv (it pins atbash-sdk==${HERMES_VERSION}, which constrains cryptography). Check the resolver output before confirming if Hermes depends on newer versions.`);
1836
- // Installing is not enabling. Hermes keeps plugins off until told
1837
- // otherwise, so without this the hook is never registered and the
1838
- // agent is not governed — while every file on disk says it is.
1839
- // Ordered after the install because `enable` needs the package present.
1840
- }
1841
- else {
1842
- steps.push({
1843
- kind: "manual",
1844
- label: "Install the Hermes plugin",
1845
- detail: [
1846
- "The `hermes` launcher is not on this machine's PATH, so setup cannot tell which Python interpreter runs Hermes — and installing into the wrong one succeeds while governing nothing.",
1847
- "",
1848
- "Run this with the interpreter Hermes uses (if it runs in a virtualenv, that venv's python):",
1849
- ].join("\n"),
1850
- snippet: `/path/to/hermes/venv/bin/python -m pip install ${HERMES_PKG}==${HERMES_VERSION}`,
1851
- });
1852
- }
1853
- }
1854
- if (restartable) {
1855
- steps.push({
1856
- kind: "exec",
1857
- label: "Restart the Hermes gateway so it loads the plugin",
1858
- command: "hermes",
1859
- args: ["gateway", "restart"],
1860
- });
1861
- }
1862
- else {
1863
- notes.push("No Hermes gateway service is running, so there is nothing to restart — the plugin loads the next time you start Hermes. (If you run it as a service, `hermes gateway install` then `hermes gateway restart`.)");
1864
- }
1865
- notes.push("Confirm the hook registered after Hermes next starts: `tail -n 50 ~/.hermes/logs/agent.log | grep -i atbash`. `hermes plugins list` will not show it — that listing only walks plugin directories.");
1866
- notes.push("ATBASH_ENFORCE_DECISION=true is fail-closed: if Atbash cannot be reached, the Hermes tool call is blocked rather than allowed.");
1867
- notes.push("ATBASH_ORG_NAME is not set for you — it decides which chain the SDK uses, and a wrong value points at the wrong one. Add it to ~/.hermes/.env yourself if your org needs it.");
1868
- }
1869
- }
1870
- // ── 4. MCP clients.
1871
- //
1872
- // This used to be a manual step, and the reason was specific: `@atbash/mcp`
1873
- // reads its identity from ATBASH_AGENT_PRIVKEY with no key-file fallback, so
1874
- // the documented wiring puts a raw private key inside the client's own config —
1875
- // `claude_desktop_config.json` and friends, files that get synced between
1876
- // machines and pasted into help requests. Automating that would have meant the
1877
- // automation's whole job was planting a secret somewhere worse.
1878
- //
1879
- // `atbash mcp` removes the reason. The client spawns the launcher, which reads
1880
- // the key from the 0600 file and hands it to the server through the child
1881
- // environment only. The config entry carries NO credential, so it is safe to
1882
- // write — and a config with no secret in it is strictly better than the one the
1883
- // operator would have hand-written from the docs.
1884
- if (wanted("mcp")) {
1885
- for (const client of detectMcpClients(home)) {
1886
- found.push(client.label);
1887
- if (client.format !== "json") {
1888
- // TOML (Codex) — @iarna/toml can round-trip values but not comments, and
1889
- // a config.toml is usually hand-maintained. Print it instead.
1890
- steps.push({
1891
- kind: "manual",
1892
- label: `Add Atbash to ${client.label}`,
1893
- detail: `${client.file} is TOML, and rewriting it would drop any comments in it. Add this table by hand:`,
1894
- snippet: ["[mcp_servers.atbash]", 'command = "npx"', 'args = ["--yes", "@atbash/cli", "mcp"]'].join("\n"),
1895
- });
1896
- continue;
1897
- }
1898
- const raw = readTextFile(client.file);
1899
- if (raw !== null && isJsonc(raw)) {
1900
- steps.push({
1901
- kind: "manual",
1902
- label: `Add Atbash to ${client.label}`,
1903
- detail: `${client.file} uses comments or trailing commas, and rewriting it as strict JSON would delete them. Merge this in by hand — note it holds no key, so the file stays as non-secret as it is today:`,
1904
- snippet: JSON.stringify({ mcpServers: { atbash: MCP_SERVER_ENTRY } }, null, 2),
1905
- });
1906
- continue;
1907
- }
1908
- let current = {};
1909
- if (raw !== null) {
1910
- try {
1911
- const parsed = JSON.parse(raw);
1912
- if (isRecord(parsed))
1913
- current = parsed;
1914
- }
1915
- catch {
1916
- notes.push(`${client.file} is not valid JSON, so it was left alone. Fix the file and re-run to wire ${client.label}.`);
1917
- continue;
1918
- }
1919
- }
1920
- const after = serializeLike(raw, mergeMcpServer(current, client.serversKey));
1921
- if (raw !== after) {
1922
- // A hand-wired entry from the old documented shape carries the private key
1923
- // in an `env` block. Replacing it REMOVES that secret from the live config
1924
- // — good — but the backup we are about to take still contains it, and an
1925
- // operator who does not know that has simply moved the leak to a new file.
1926
- if (hadInlineKey(current, client.serversKey)) {
1927
- notes.push(`${client.file} currently holds your private key in an env block. Setup replaces that entry with the keyless launcher, but the .atbash-bak it leaves behind WILL still contain the key — delete that backup once you have confirmed the client works.`);
1928
- }
1929
- steps.push({
1930
- kind: "write",
1931
- label: `Add Atbash as an MCP server in ${client.label} (a merge — existing servers are kept${hadInlineKey(current, client.serversKey) ? ", and your key is removed from this file" : ""})`,
1932
- file: client.file,
1933
- before: raw,
1934
- after,
1935
- });
1936
- }
1937
- else {
1938
- notes.push(`${client.label} already has the Atbash MCP server — left untouched.`);
1939
- }
1940
- }
1941
- if (found.some((f) => f !== "OpenClaw" && f !== "Hermes")) {
1942
- notes.push("Restart any MCP client that was changed — clients read their server list at startup.");
1943
- // A client whose first launch of the server takes ~12s can report a startup
1944
- // timeout that looks like a broken config. Say so, so the first thing an
1945
- // operator does is retry rather than undo the wiring.
1946
- notes.push("The first time a client starts the Atbash server it takes ~10-15s while npx caches the package; after that it is about a second. If a client reports a startup timeout on the very first try, start it again.");
1947
- }
550
+ notes.push("Hermes is installed here. It shares this agent's skills and signing key, but the Atbash hook lives in the OpenClaw gateway — actions driven through the Hermes API are NOT judged, even while the OpenClaw side reports enforcing. Route that work through OpenClaw, or guard it in code with @atbash/sdk.");
551
+ }
552
+ // ── 4. MCP clients: detected and reported, never seeded.
553
+ // The documented @atbash/mcp wiring carries the private key as an
554
+ // ATBASH_AGENT_PRIVKEY env value inside the client's own config file, and that
555
+ // package has no key-file fallback (checked against the published 0.1.3). We
556
+ // will not write a private key into a file people share and sync, so this is
557
+ // the one place setup deliberately stays manual.
558
+ const mcpClients = [];
559
+ const seenClients = new Set();
560
+ for (const { label, segs } of connect_1.MCP_CONFIGS) {
561
+ if (seenClients.has(label))
562
+ continue;
563
+ if (exists(home, ...segs)) {
564
+ seenClients.add(label);
565
+ mcpClients.push(`${label} (${path.join(home, ...segs)})`);
566
+ }
567
+ }
568
+ // Claude Code and Codex live outside MCP_CONFIGS in the scanner too — same paths.
569
+ if (exists(home, ".claude.json"))
570
+ mcpClients.push(`Claude Code (${path.join(home, ".claude.json")})`);
571
+ if (exists(home, ".codex", "config.toml"))
572
+ mcpClients.push(`Codex (${path.join(home, ".codex", "config.toml")})`);
573
+ if (mcpClients.length) {
574
+ found.push(`${mcpClients.length} MCP client config${mcpClients.length === 1 ? "" : "s"}`);
575
+ steps.push({
576
+ kind: "manual",
577
+ label: `Optional: expose Atbash as an MCP server to ${mcpClients.length} detected client${mcpClients.length === 1 ? "" : "s"}`,
578
+ detail: [
579
+ `Detected: ${mcpClients.join(", ")}.`,
580
+ "",
581
+ "This step is NOT done for you, on purpose. The published @atbash/mcp wiring takes the agent's private key as an ATBASH_AGENT_PRIVKEY value inside the client's own config file, and that package has no key-file fallback today. Atbash will not write your private key into a file that gets synced, shared and screenshotted.",
582
+ "",
583
+ "If you want it anyway, add this yourself and fill in the key — and treat that config file as a secret from then on:",
584
+ ].join("\n"),
585
+ snippet: JSON.stringify({
586
+ mcpServers: {
587
+ atbash: { command: "npx", args: ["-y", "@atbash/mcp"], env: { ATBASH_AGENT_PRIVKEY: "<your agent private key>" } },
588
+ },
589
+ }, null, 2),
590
+ });
1948
591
  }
1949
592
  if (!found.length) {
1950
593
  notes.push("No OpenClaw, Hermes or MCP client configuration was found under this home directory. The key file is still placed, so an SDK-level integration in your own code will find it — but nothing on this machine is wired to a runtime.");
@@ -2100,57 +743,17 @@ function backupFile(file) {
2100
743
  fs.copyFileSync(file, target);
2101
744
  return target;
2102
745
  }
2103
- /**
2104
- * Execute the plan, in the order that cannot leave a half-wired machine.
2105
- *
2106
- * 1. Independent writes the key file above all. Safe on their own, useful
2107
- * even if everything after fails, and required by the plugin at load.
2108
- * 2. Commands — the plugin install, so the plugin id EXISTS on disk.
2109
- * 3. Dependent writes — the plugin config, now that it refers to something
2110
- * real. Skipped outright if its install failed (see Step.requires).
2111
- * 4. Verify, and roll back anything we broke (see verify).
2112
- *
2113
- * ⚠️ THE ORDER IS THE FIX, and it is the reverse of what this function used to
2114
- * do. "Writes first, then commands, so a failed install still leaves a correct
2115
- * config behind" sounds prudent and produces the single worst outcome available:
2116
- * a config entry for a plugin that is not installed, which OpenClaw reports as a
2117
- * stale reference and offers to delete via `doctor --fix` — silently un-governing
2118
- * the agent — and which on 2026.2.x helped make the config unloadable, killing
2119
- * the install that would have fixed it.
2120
- */
2121
- function applyPlan(plan, opts = {}) {
2122
- const result = { written: [], backups: [], ran: [], failures: [], skipped: [], rolledBack: [] };
2123
- /** Backup path per file, so a verify failure can put the original back. */
2124
- const backupOf = new Map();
2125
- const writeStep = (step) => {
746
+ /** Execute the plan. Writes first, then commands, so a failed install still
747
+ * leaves a correct config and key file behind for a manual retry. */
748
+ function applyPlan(plan) {
749
+ const result = { written: [], backups: [], ran: [], failures: [] };
750
+ for (const step of plan.steps) {
751
+ if (step.kind !== "write")
752
+ continue;
2126
753
  try {
2127
754
  const backup = backupFile(step.file);
2128
- if (backup) {
755
+ if (backup)
2129
756
  result.backups.push(backup);
2130
- backupOf.set(step.file, backup);
2131
- }
2132
- // Hand the change to the runtime where the plan says to — it merges and
2133
- // validates in its own format, which is the whole point.
2134
- if (step.applyVia) {
2135
- const run = (0, child_process_1.spawnSync)(step.applyVia.command, step.applyVia.args, {
2136
- input: step.applyVia.payload,
2137
- encoding: "utf8",
2138
- timeout: 120000,
2139
- env: { ...process.env, ...(step.applyVia.env ?? {}) },
2140
- });
2141
- const out = `${run.stdout ?? ""}${run.stderr ?? ""}`.trim();
2142
- if (run.error || run.status !== 0) {
2143
- // Do NOT silently fall back to writing the file ourselves. The runtime
2144
- // refusing the change is information — usually that the config is
2145
- // invalid for a reason we did not cause — and overwriting the file by
2146
- // hand would bury it and destroy whatever the runtime was protecting.
2147
- result.failures.push(`${step.applyVia.command} ${step.applyVia.args.join(" ")} did not apply the change to ${step.file}` +
2148
- (out ? `:\n ${out.split("\n").join("\n ")}` : `: ${run.error?.message ?? `exit ${run.status}`}`));
2149
- return;
2150
- }
2151
- result.written.push(step.file);
2152
- return;
2153
- }
2154
757
  fs.mkdirSync(path.dirname(step.file), { recursive: true, mode: step.mode === KEY_MODE ? DIR_MODE : undefined });
2155
758
  fs.writeFileSync(step.file, step.after, step.mode ? { mode: step.mode } : {});
2156
759
  // writeFileSync's mode is ignored for a file that already existed, so
@@ -2162,88 +765,16 @@ function applyPlan(plan, opts = {}) {
2162
765
  catch (err) {
2163
766
  result.failures.push(`${step.file}: ${err instanceof Error ? err.message : String(err)}`);
2164
767
  }
2165
- };
2166
- // ── 1. Writes that depend on nothing.
2167
- for (const step of plan.steps) {
2168
- if (step.kind === "write" && !step.requires)
2169
- writeStep(step);
2170
768
  }
2171
- // ── 2. Commands, recording which ones a dependent write may rely on.
2172
- const succeeded = new Set();
2173
769
  for (const step of plan.steps) {
2174
770
  if (step.kind !== "exec")
2175
771
  continue;
2176
772
  const label = `${step.command} ${step.args.join(" ")}`;
2177
773
  const run = (0, child_process_1.spawnSync)(step.command, step.args, { stdio: "inherit" });
2178
- // Three distinct outcomes, and they used to collapse into one misleading
2179
- // message. `spawnSync` reports a binary it could not launch via `.error` with
2180
- // `status` left null — so an ENOENT printed "exited on a signal", which reads
2181
- // like the plugin installer crashed rather than "that command is not here".
2182
- // The distinction matters because only one of them is the operator's to fix,
2183
- // and the fix is to run it somewhere the CLI exists.
2184
- if (run.error) {
2185
- const missing = run.error.code === "ENOENT";
2186
- result.failures.push(missing
2187
- ? `${step.command} is not on this machine's PATH, so \`${label}\` did not run. Everything else above was applied — run that one command wherever the ${step.command} CLI lives.`
2188
- : `${label} could not start: ${run.error.message}`);
2189
- }
2190
- else if (run.status === 0) {
774
+ if (run.status === 0)
2191
775
  result.ran.push(label);
2192
- if (step.id)
2193
- succeeded.add(step.id);
2194
- }
2195
- else if (run.signal) {
2196
- result.failures.push(`${label} was killed by ${run.signal}`);
2197
- }
2198
- else {
2199
- result.failures.push(`${label} exited with code ${run.status}`);
2200
- }
2201
- }
2202
- // ── 3. Writes that needed one of those commands to have worked.
2203
- for (const step of plan.steps) {
2204
- if (step.kind !== "write" || !step.requires)
2205
- continue;
2206
- if (!succeeded.has(step.requires)) {
2207
- // The whole point: no config for a plugin that is not there. Say what was
2208
- // NOT done and why, because silence here reads as success.
2209
- result.skipped.push(`${step.file} was left unchanged: it configures something the step above did not manage to install, ` +
2210
- `and a config entry for a missing plugin is worse than none — the runtime reports it as stale and ` +
2211
- `offers to delete it. Fix the failure above and re-run; nothing needs undoing first.`);
2212
- continue;
2213
- }
2214
- writeStep(step);
2215
- }
2216
- // ── 4. Verify, and undo what we broke.
2217
- //
2218
- // Only files WE wrote in this run, and only when the runtime can actually
2219
- // answer. A `valid: false` on a file we did not touch is someone else's
2220
- // problem to fix and not ours to revert.
2221
- if (opts.verify) {
2222
- for (const file of [...new Set(result.written)]) {
2223
- const verdict = opts.verify(file);
2224
- if (!verdict || verdict.valid)
2225
- continue;
2226
- const backup = backupOf.get(file);
2227
- if (!backup) {
2228
- // Nothing to restore to — the file did not exist before this run. Deleting
2229
- // it would be the honest inverse, but a config we created and a config the
2230
- // runtime created are indistinguishable by now, so say so instead of
2231
- // guessing. Leaving a file we cannot vouch for, unmentioned, is the one
2232
- // outcome that is not allowed.
2233
- result.failures.push(`${file} did not validate after being written, and there was no previous version to restore:\n ${verdict.problems}`);
2234
- continue;
2235
- }
2236
- try {
2237
- fs.copyFileSync(backup, file);
2238
- result.rolledBack.push(file);
2239
- result.written = result.written.filter((f) => f !== file);
2240
- result.failures.push(`${file} did not validate after being written, so the original was restored from ${backup}:\n ${verdict.problems}`);
2241
- }
2242
- catch (err) {
2243
- result.failures.push(`${file} did not validate AND could not be restored from ${backup} (${err instanceof Error ? err.message : String(err)}). ` +
2244
- `The backup is still on disk — put it back by hand before starting the runtime.`);
2245
- }
2246
- }
776
+ else
777
+ result.failures.push(`${label} exited ${run.status ?? "on a signal"}`);
2247
778
  }
2248
779
  return result;
2249
780
  }
@@ -2257,26 +788,23 @@ function applyPlan(plan, opts = {}) {
2257
788
  */
2258
789
  async function verifyRegistration(privkey, endpoint) {
2259
790
  try {
2260
- const atbash = new sdk_1.Atbash(privkey, { endpoint });
791
+ const atbash = new sdk_1.Atbash(privkey, {
792
+ endpoint,
793
+ blockchainRid: (0, sdk_1.resolve)("blockchainRid") || undefined,
794
+ orgName: (0, sdk_1.resolve)("orgName") || undefined,
795
+ });
2261
796
  return (await atbash.checkAgentExists()) ? { state: "registered" } : { state: "unregistered" };
2262
797
  }
2263
798
  catch (err) {
2264
799
  return { state: "unknown", reason: err instanceof Error ? err.message : String(err) };
2265
800
  }
2266
801
  }
2267
- /**
2268
- * Confirmation prompt. Defaults to NO — anything but an explicit yes is a no —
2269
- * except where `defaultYes` is set, which is only for questions where the safe
2270
- * answer is also the common one (reusing the key already on this machine).
2271
- */
2272
- async function confirm(question, defaultYes = false) {
802
+ /** y/N confirmation. Anything but an explicit yes is a no. */
803
+ async function confirm(question) {
2273
804
  const { createInterface } = await Promise.resolve().then(() => __importStar(require("node:readline")));
2274
805
  const rl = createInterface({ input: process.stdin, output: process.stdout });
2275
806
  const answer = await new Promise((r) => rl.question(question, (a) => { rl.close(); r(a); }));
2276
- const trimmed = answer.trim();
2277
- if (!trimmed)
2278
- return defaultYes;
2279
- return /^y(es)?$/i.test(trimmed);
807
+ return /^y(es)?$/i.test(answer.trim());
2280
808
  }
2281
809
  // ── The command ─────────────────────────────────────────────────────────────
2282
810
  function registerSetupCommand(program) {
@@ -2288,14 +816,12 @@ function registerSetupCommand(program) {
2288
816
  .option("--keys-dir <dir>", "Directory holding the key file, e.g. ~/Downloads")
2289
817
  .option("--host <url>", "Atbash deployment to check the agent's registration against")
2290
818
  .option("--runtime <ids...>", "Only configure these runtimes (currently: openclaw)")
2291
- .option("--org-name <name>", "Organization the agent was onboarded under, exactly as the dashboard shows it — the plugin resolves which chain to query from this")
2292
819
  .option("--dry-run", "Show exactly which files would change, and the diffs, then exit WITHOUT writing anything")
2293
820
  .option("-y, --yes", "Do not ask for confirmation before writing")
2294
821
  .option("--no-install", "Do not install any package; write the key file and configs only")
2295
822
  .option("--skip-verify", "Do not check the agent's registration (no network calls at all)")
2296
823
  .option("--allow-unrecognized-host", "Permit a --host that is not a known Atbash deployment")
2297
824
  .option("--home <dir>", "Home directory to configure (for testing)")
2298
- .option("--replace-key", "Consent to changing which agent this machine signs as, when --key names a different agent than the one already here (needed for non-interactive runs)")
2299
825
  .action(async (opts) => {
2300
826
  const home = opts.home || process.env.HOME || os.homedir();
2301
827
  const dryRun = !!opts.dryRun;
@@ -2328,62 +854,9 @@ function registerSetupCommand(program) {
2328
854
  process.exit(1);
2329
855
  }
2330
856
  console.log(chalk_1.default.dim(`\n Agent key source: ${keySource.from}`));
2331
- // ── Replacing this machine's AGENT IDENTITY is its own decision.
2332
- //
2333
- // Everything else this command does is additive: a config entry, a plugin,
2334
- // a key file where there was none. This one is a substitution, and it is
2335
- // the only change here that alters WHO the machine is. After it, every
2336
- // integration reading the default key path signs as a different on-chain
2337
- // agent, so tool calls are attributed to someone else — including tool
2338
- // calls made by work that was already running.
2339
- //
2340
- // It used to be folded into the single "Apply N changes to this machine?"
2341
- // prompt, listed as one write among several. An operator concentrating on
2342
- // the plugin config could accept it without registering that their agent
2343
- // identity changed, and `--yes` — which reasonably means "don't ask me
2344
- // about the file writes" — skipped it entirely. So it gets asked
2345
- // separately, and a blanket `--yes` does not answer it: saying yes to
2346
- // writing files is not the same as saying yes to becoming a different
2347
- // agent. `--replace-key` is how a script says it deliberately.
2348
- //
2349
- // Declining ABORTS rather than continuing, because continuing cannot honour
2350
- // what was asked. The operator ran `--key <NEW>` meaning "wire this machine
2351
- // to NEW"; with the key left alone the machine keeps signing as OLD, so
2352
- // proceeding would configure a runtime that reports one agent while the
2353
- // dashboard shows another — the exact silent mismatch the rest of this work
2354
- // exists to remove.
2355
- const canonicalKeyFile = path.join(home, ...KEY_FILE_REL);
2356
- const existingRaw = readTextFile(canonicalKeyFile);
2357
- const existingMaterial = existingRaw === null ? null : parseKeyMaterial(existingRaw);
2358
- const existingPubkey = existingMaterial ? (0, sdk_1.derivePublicKey)(existingMaterial.privkey) : undefined;
2359
- if (existingPubkey && existingPubkey.toLowerCase() !== pubkey.toLowerCase()) {
2360
- const archive = path.join(home, ".config", "atbash", "keys", `${existingPubkey}.key`);
2361
- console.log(chalk_1.default.yellow("\n This machine is about to change which agent it signs as.") +
2362
- chalk_1.default.dim(`\n now: ${existingPubkey}`) +
2363
- chalk_1.default.dim(`\n new: ${pubkey}`) +
2364
- chalk_1.default.dim(`\n Every integration on this machine reading ${canonicalKeyFile}`) +
2365
- chalk_1.default.dim("\n will switch to the new agent. The current key is archived first, to") +
2366
- chalk_1.default.dim(`\n ${archive}, so the old agent stays recoverable.\n`));
2367
- const approved = opts.replaceKey
2368
- ? true
2369
- : dryRun
2370
- ? true // a preview decides nothing; the real run will still ask
2371
- : process.stdin.isTTY
2372
- ? await confirm(" Replace the agent this machine signs as? [y/N] ")
2373
- : false;
2374
- if (!approved) {
2375
- console.log(chalk_1.default.dim("\n Nothing was changed.") +
2376
- chalk_1.default.dim(`\n This machine still signs as ${existingPubkey}.`) +
2377
- (process.stdin.isTTY
2378
- ? chalk_1.default.dim("\n Re-run without --key to configure it for the agent already here.\n")
2379
- : chalk_1.default.dim("\n Re-run with --replace-key to switch agents non-interactively,") +
2380
- chalk_1.default.dim("\n or without --key to configure it for the agent already here.\n")));
2381
- return;
2382
- }
2383
- }
2384
857
  // ── Registration check. Only the public key crosses the network.
2385
858
  if (!opts.skipVerify) {
2386
- const endpoint = (opts.host || (0, sdk_1.resolve)("judgeEndpoint") || atbash_targets_1.DEFAULT_HOST || sdk_1.DEFAULT_ENDPOINT).replace(/\/$/, "");
859
+ const endpoint = (opts.host || (0, sdk_1.resolve)("judgeEndpoint") || connect_1.DEFAULT_HOST || sdk_1.DEFAULT_ENDPOINT).replace(/\/$/, "");
2387
860
  let hostname = "";
2388
861
  try {
2389
862
  hostname = new URL(endpoint).hostname.toLowerCase();
@@ -2395,8 +868,7 @@ function registerSetupCommand(program) {
2395
868
  // An unrecognized host could answer "registered" for any key, which is
2396
869
  // exactly the confirmation this check exists to provide. Exact hostname
2397
870
  // match, never a suffix — "atbash.ai.evil.com" must not pass.
2398
- const recognizedHost = atbash_targets_1.KNOWN_HOSTS.has(hostname);
2399
- if (!recognizedHost && !opts.allowUnrecognizedHost) {
871
+ if (!connect_1.KNOWN_HOSTS.has(hostname) && !opts.allowUnrecognizedHost) {
2400
872
  console.error(chalk_1.default.red(`\n ${hostname} is not a recognized Atbash deployment.`) +
2401
873
  chalk_1.default.dim("\n Re-run with --allow-unrecognized-host if you meant to point at a self-hosted instance,\n or with --skip-verify to configure this machine without any network call.\n"));
2402
874
  process.exit(1);
@@ -2404,21 +876,7 @@ function registerSetupCommand(program) {
2404
876
  const verdict = await verifyRegistration(privkey, endpoint);
2405
877
  if (verdict.state === "unregistered") {
2406
878
  console.error(chalk_1.default.red("\n That agent is not registered on this deployment.") +
2407
- chalk_1.default.dim(`\n Public key: ${pubkey}\n Key came from: ${keySource.from}\n`));
2408
- // The likeliest cause is not "you skipped onboarding" — it is "this is a
2409
- // key you did not choose". Say so when the key was found rather than
2410
- // supplied, because the fix is completely different.
2411
- if (/existing key file|atbash config/.test(keySource.from)) {
2412
- console.error(chalk_1.default.yellow(" This is a key that was already on this machine, not one you supplied.") +
2413
- chalk_1.default.dim("\n If you are onboarding a DIFFERENT agent, pass its key explicitly:" +
2414
- "\n --key <64-hex> the key shown in the browser" +
2415
- "\n --keys-dir ~/Downloads the key file you saved" +
2416
- "\n Or re-run and answer 'n' when asked whether to use the existing key.\n"));
2417
- }
2418
- else {
2419
- console.error(chalk_1.default.dim(" Finish onboarding first — wiring a runtime to an unregistered agent leaves it\n" +
2420
- " looking governed while the plugin can never get a verdict.\n"));
2421
- }
879
+ chalk_1.default.dim(`\n Public key: ${pubkey}\n Finish onboarding first — wiring a runtime to an unregistered agent leaves it\n looking governed while the plugin can never get a verdict.\n`));
2422
880
  process.exit(1);
2423
881
  }
2424
882
  if (verdict.state === "unknown") {
@@ -2429,73 +887,8 @@ function registerSetupCommand(program) {
2429
887
  return;
2430
888
  }
2431
889
  }
2432
- else if (recognizedHost) {
2433
- console.log(chalk_1.default.green(` Agent is registered on ${hostname}.`));
2434
- }
2435
890
  else {
2436
- // --allow-unrecognized-host is a real bypass, and its most dangerous
2437
- // property is that the check still PRINTS a reassuring answer. A host
2438
- // chosen by an attacker returns "registered" for any key at all, so a
2439
- // "✓ registered" line here would be the attacker's own claim wearing
2440
- // Atbash's voice. Never let that line stand unqualified: say the answer
2441
- // came from an unvouched-for server, so a talked-into-it operator sees
2442
- // the one thing that would tell them something is wrong.
2443
- console.log(chalk_1.default.yellow(` ${hostname} answered "registered" — but this is NOT a recognized Atbash deployment.`));
2444
- console.log(chalk_1.default.yellow(" A registration check against an unrecognized host proves nothing: any server") +
2445
- chalk_1.default.yellow("\n can answer \"registered\" for any key. Treat this as UNVERIFIED."));
2446
- console.log(chalk_1.default.dim(` Recognized deployments: ${[...atbash_targets_1.KNOWN_HOSTS].join(", ")}`));
2447
- }
2448
- }
2449
- // ── What OpenClaw is on this machine, and can we ask it to do the work?
2450
- //
2451
- // This runs BEFORE the plan, and before anything is written, because both
2452
- // answers change what we do:
2453
- //
2454
- // - No OpenClaw at all → say so and stop touching OpenClaw. The likeliest
2455
- // cause is the operator running this on the wrong computer, and the
2456
- // previous behavior (write config for a runtime that is not here) left
2457
- // a machine carrying governance for an agent it does not run.
2458
- // - An OLD OpenClaw → still supported, still wired. It just cannot
2459
- // validate the change for us, so we say that once, offer the upgrade
2460
- // command FOR ITS OWN CHANNEL, and continue. Refusing here would break
2461
- // 2026.2.x boxes that demonstrably work.
2462
- //
2463
- // Nothing below compares version numbers to decide anything: capability is
2464
- // probed from the binary. A version table is exactly what went stale and
2465
- // produced the config that broke the reporter's machine.
2466
- const wantsOpenclaw = wantedRuntime("openclaw", opts.runtime ?? []);
2467
- const openclaw = wantsOpenclaw ? (0, openclaw_runtime_1.detectOpenclaw)() : undefined;
2468
- if (openclaw) {
2469
- const status = (0, openclaw_runtime_1.supportStatus)(openclaw);
2470
- console.log(status.supported ? chalk_1.default.dim(`\n ${status.message}`) : chalk_1.default.yellow(`\n ${status.message}`));
2471
- if (status.upgrade) {
2472
- console.log(chalk_1.default.dim(" To upgrade it: ") + chalk_1.default.cyan(status.upgrade));
2473
- }
2474
- // ── PREFLIGHT. The step this command never had.
2475
- //
2476
- // Setup merged into ~/.openclaw/openclaw.json without ever checking
2477
- // whether that file currently loads. On a machine whose config was
2478
- // ALREADY broken it added its entry to an unloadable file and then its
2479
- // own `openclaw plugins install` step died on the pre-existing breakage —
2480
- // reported to the operator as an Atbash failure, which it was not.
2481
- //
2482
- // A `valid: false` here is NOT a reason to refuse: the operator may well
2483
- // be running setup precisely because their config is broken, and some of
2484
- // what we do (pruning a retired `load.paths`) is the repair. So report
2485
- // the problems in OpenClaw's own words and carry on — the point is that
2486
- // nobody is left debugging our step for someone else's breakage.
2487
- if (openclaw.caps.validate) {
2488
- const configPath = path.join(home, ...OPENCLAW_CONFIG_REL);
2489
- if (fs.existsSync(configPath)) {
2490
- const verdict = (0, openclaw_runtime_1.validateConfig)(openclaw, configPath, "openclaw", home);
2491
- if (verdict && !verdict.valid) {
2492
- console.log(chalk_1.default.yellow("\n ⚠ OpenClaw reports your CURRENT config is invalid, before Atbash changes anything:") +
2493
- chalk_1.default.dim(`\n${verdict.problems.split("\n").map((l) => ` ${l}`).join("\n")}`) +
2494
- chalk_1.default.dim("\n Atbash will still wire its entry, and will back the file up first. If the") +
2495
- chalk_1.default.dim("\n problem above is not one Atbash introduced, it needs fixing separately —") +
2496
- chalk_1.default.dim("\n OpenClaw will not load ANY config while it stands, so the plugin cannot run.\n"));
2497
- }
2498
- }
891
+ console.log(chalk_1.default.green(` Agent is registered on ${hostname}.`));
2499
892
  }
2500
893
  }
2501
894
  // ── Plan, show, then (maybe) apply.
@@ -2505,24 +898,7 @@ function registerSetupCommand(program) {
2505
898
  pubkey,
2506
899
  noInstall: opts.install === false,
2507
900
  only: opts.runtime ?? [],
2508
- orgName: opts.orgName,
2509
- // Lets the plan hand the config merge to OpenClaw where it can do it, and
2510
- // tells it whether THIS build accepts `hooks` on a plugin entry — asked of
2511
- // `openclaw config schema`, since the same key is fatal on 2026.2.x and
2512
- // legitimate on 2026.6.6+. Unknown resolves to "not supported", which is
2513
- // the fail-safe direction.
2514
- ...(openclaw ? { openclaw: { ...openclaw, hooksSupported: (0, openclaw_runtime_1.pluginEntryAcceptsHooks)(openclaw) === true } } : {}),
2515
- // The same host the registration check used, so the plugin build and the
2516
- // chain the agent lives on cannot disagree.
2517
- endpoint: opts.host || (0, sdk_1.resolve)("judgeEndpoint") || atbash_targets_1.DEFAULT_HOST,
2518
901
  });
2519
- // Private-chain orgs need it and it cannot be derived here, so say so
2520
- // rather than writing a config that resolves the wrong chain in silence.
2521
- if (!opts.orgName?.trim() && plan.found.includes("OpenClaw")) {
2522
- console.log(chalk_1.default.dim("\n No --org-name given. The OpenClaw plugin resolves which chain to query from it,") +
2523
- chalk_1.default.dim("\n so add it yourself if your org is on a private chain (harmless otherwise):") +
2524
- chalk_1.default.dim("\n plugins.entries.atbash-openclaw.config.orgName\n"));
2525
- }
2526
902
  renderPlan(plan, pubkey);
2527
903
  const changes = plan.steps.filter((s) => s.kind === "write" || s.kind === "exec");
2528
904
  if (dryRun) {
@@ -2545,16 +921,7 @@ function registerSetupCommand(program) {
2545
921
  return;
2546
922
  }
2547
923
  }
2548
- // Verification is OpenClaw's own answer, not ours — and only for the file
2549
- // it is the authority on. Setup used to report success based purely on
2550
- // having written what it intended to write, which is how a machine with
2551
- // nothing installed was told it was "fully wired".
2552
- const openclawConfigPath = path.join(home, ...OPENCLAW_CONFIG_REL);
2553
- const result = applyPlan(plan, {
2554
- verify: openclaw?.caps.validate
2555
- ? (file) => (path.resolve(file) === path.resolve(openclawConfigPath) ? (0, openclaw_runtime_1.validateConfig)(openclaw, file, "openclaw", home) : undefined)
2556
- : undefined,
2557
- });
924
+ const result = applyPlan(plan);
2558
925
  console.log();
2559
926
  for (const file of result.written)
2560
927
  console.log(chalk_1.default.green(` ✓ wrote ${file}`));
@@ -2562,85 +929,14 @@ function registerSetupCommand(program) {
2562
929
  console.log(chalk_1.default.dim(` backup: ${file}`));
2563
930
  for (const cmd of result.ran)
2564
931
  console.log(chalk_1.default.green(` ✓ ran ${cmd}`));
2565
- for (const file of result.rolledBack)
2566
- console.log(chalk_1.default.yellow(` ↩ restored ${file} — the change did not validate`));
2567
- // A write we deliberately did not make is not a silent non-event: it is the
2568
- // difference between "no config" and "config for a plugin that isn't there",
2569
- // and the operator has to know which one they have.
2570
- for (const skip of result.skipped)
2571
- console.log(chalk_1.default.yellow(` ⊘ ${skip}`));
2572
932
  for (const failure of result.failures)
2573
933
  console.log(chalk_1.default.red(` ✗ ${failure}`));
2574
- if (result.failures.length || result.skipped.length) {
934
+ if (result.failures.length) {
2575
935
  console.log(chalk_1.default.yellow("\n Finished with failures — this machine is NOT fully wired.") +
2576
936
  chalk_1.default.dim("\n Everything that did succeed is listed above; the steps that failed can be re-run.\n"));
2577
937
  process.exitCode = 1;
2578
938
  return;
2579
939
  }
2580
- // ── Check, do not assume.
2581
- //
2582
- // Every step reporting success is not the same as the runtime having
2583
- // picked the plugin up, and this command used to print "Done" on the
2584
- // strength of the former. On a real machine the install succeeded, the
2585
- // entry point was correct, and Hermes still listed nothing — so the agent
2586
- // was ungoverned behind a green summary. Where a runtime can be asked, ask.
2587
- if (plan.found.includes("Hermes") && wantedRuntime("hermes", opts.runtime ?? [])) {
2588
- const state = hermesPluginState(home);
2589
- if (state === "configured") {
2590
- console.log(chalk_1.default.green("\n Hermes is configured to load the plugin.") +
2591
- chalk_1.default.dim("\n It takes effect on the next Hermes start. Confirm the hook registered:") +
2592
- chalk_1.default.dim("\n tail -n 50 ~/.hermes/logs/agent.log | grep -i atbash") +
2593
- chalk_1.default.dim("\n (`hermes plugins list` will NOT show it — that listing only walks plugin") +
2594
- chalk_1.default.dim("\n directories and cannot see a pip-installed one.)\n"));
2595
- }
2596
- else if (state === "not-enabled") {
2597
- console.log(chalk_1.default.yellow("\n The plugin is installed but NOT on Hermes' enabled allow-list — this agent is not governed.") +
2598
- chalk_1.default.dim("\n Hermes loads only what is listed. Add it to ~/.hermes/config.yaml:") +
2599
- chalk_1.default.dim("\n plugins:\n enabled:\n - " + HERMES_PLUGIN_ENTRY + "\n"));
2600
- process.exitCode = 1;
2601
- return;
2602
- }
2603
- else if (state === "not-installed") {
2604
- console.log(chalk_1.default.yellow("\n The plugin is not installed in the interpreter that runs Hermes — this agent is not governed.\n"));
2605
- process.exitCode = 1;
2606
- return;
2607
- }
2608
- // "unknown": nothing readable to judge by, so claim nothing.
2609
- }
2610
- // ── OpenClaw gets the last word about OpenClaw.
2611
- //
2612
- // Everything above reports what setup DID. This reports what OpenClaw now
2613
- // SEES, which is the only thing that answers "is this agent governed?".
2614
- // The reporter's machine had a config entry, no plugin, and a green
2615
- // summary — a false green on a control boundary is the most expensive
2616
- // failure this command can produce.
2617
- if (openclaw?.present && plan.found.includes("OpenClaw") && wantedRuntime("openclaw", opts.runtime ?? [])) {
2618
- const verdict = (0, openclaw_runtime_1.verifyOpenclawPlugin)(openclaw, {
2619
- entryIds: [OPENCLAW_ENTRY, OPENCLAW_LEGACY_ENTRY],
2620
- configPath: openclawConfigPath,
2621
- // Pin HOME too: plugin discovery walks $HOME/.openclaw, so without it a
2622
- // --home run reports the operator's real machine instead of this one.
2623
- home,
2624
- expectedSpec: openclawPackageForHost(opts.host || (0, sdk_1.resolve)("judgeEndpoint") || atbash_targets_1.DEFAULT_HOST),
2625
- });
2626
- if (verdict.state === "loaded") {
2627
- console.log(chalk_1.default.green(`\n OpenClaw loads the plugin — entry \`${verdict.entry}\`${verdict.version ? `, build ${verdict.version}` : ""}.`) +
2628
- chalk_1.default.dim("\n Its hook registers when the gateway starts, so restart the gateway to enforce.\n"));
2629
- }
2630
- else if (verdict.state === "unknown") {
2631
- // Say plainly that this is unverified rather than papering over it.
2632
- console.log(chalk_1.default.yellow("\n Could not confirm with OpenClaw whether the plugin loaded.") +
2633
- chalk_1.default.dim(`\n ${verdict.detail ?? ""}\n Check it yourself with: `) + chalk_1.default.cyan("openclaw plugins list") + "\n");
2634
- }
2635
- else {
2636
- console.log(chalk_1.default.yellow(`\n This agent is NOT governed yet — OpenClaw does not report the plugin as loaded.`) +
2637
- chalk_1.default.dim(`\n ${verdict.detail ?? ""}`) +
2638
- chalk_1.default.dim(`\n Inspect it with: `) + chalk_1.default.cyan("openclaw plugins list") + chalk_1.default.dim(" and ") + chalk_1.default.cyan("openclaw doctor") +
2639
- chalk_1.default.dim("\n ⚠ `openclaw doctor --fix` will DELETE an Atbash entry it considers stale, so read its plan before accepting.\n"));
2640
- process.exitCode = 1;
2641
- return;
2642
- }
2643
- }
2644
940
  console.log(chalk_1.default.green("\n Done.") + chalk_1.default.dim(" Restart the runtime so it loads the hook, then re-scan this machine"));
2645
941
  console.log(chalk_1.default.dim(" from the agent's page in the dashboard to confirm it reports as enforcing.\n"));
2646
942
  });