@atbash/cli 0.5.15-dev.1 → 0.5.15-dev.2

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.
@@ -0,0 +1,1367 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.parseKeyMaterial = parseKeyMaterial;
40
+ exports.normalizePrivkey = normalizePrivkey;
41
+ exports.keyCandidatesInDir = keyCandidatesInDir;
42
+ exports.resolveKeySource = resolveKeySource;
43
+ exports.keyFileContents = keyFileContents;
44
+ exports.isJsonc = isJsonc;
45
+ exports.mergeOpenclawConfig = mergeOpenclawConfig;
46
+ exports.detectIndent = detectIndent;
47
+ exports.serializeLike = serializeLike;
48
+ exports.detectMcpClients = detectMcpClients;
49
+ exports.findHermesPython = findHermesPython;
50
+ exports.mergeHermesEnv = mergeHermesEnv;
51
+ exports.hadInlineKey = hadInlineKey;
52
+ exports.mergeMcpServer = mergeMcpServer;
53
+ exports.buildPlan = buildPlan;
54
+ exports.lineDiff = lineDiff;
55
+ exports.renderPlan = renderPlan;
56
+ exports.backupFile = backupFile;
57
+ exports.applyPlan = applyPlan;
58
+ exports.registerSetupCommand = registerSetupCommand;
59
+ const fs = __importStar(require("fs"));
60
+ const os = __importStar(require("os"));
61
+ const path = __importStar(require("path"));
62
+ const child_process_1 = require("child_process");
63
+ const chalk_1 = __importDefault(require("chalk"));
64
+ const jsonc = __importStar(require("jsonc-parser"));
65
+ const sdk_1 = require("@atbash/sdk");
66
+ const atbash_targets_1 = require("../shared/atbash-targets");
67
+ /**
68
+ * `atbash setup` — the write half of onboarding.
69
+ *
70
+ * Onboarding registers an agent on chain and issues its certificate. None of
71
+ * that governs anything until the runtime on the agent's machine is pointed at
72
+ * Atbash, and that step used to be four manual operations: move a downloaded
73
+ * key file, install a plugin, hand-merge a JSON block into an existing config
74
+ * "without erasing the existing configurations", restart the gateway. The merge
75
+ * is the one people get wrong, and getting it wrong means an agent that reports
76
+ * registered while enforcing nothing.
77
+ *
78
+ * This command does those steps.
79
+ *
80
+ * ── RELATIONSHIP TO `atbash connect` ─────────────────────────────────────────
81
+ * `connect` is READ-ONLY and must stay that way: the onboarding page promises
82
+ * "installs nothing, changes nothing", and a cautious agent asked to run it is
83
+ * right to verify that. `setup` is the separate, explicitly-named command that
84
+ * writes. Never move write behavior into `connect`, and never describe `setup`
85
+ * with `connect`'s copy.
86
+ *
87
+ * ── WHAT IT WILL NOT DO ──────────────────────────────────────────────────────
88
+ * 1. It never sends the private key anywhere. The key is read locally, written
89
+ * locally, and used locally to derive a public key. The only network call is
90
+ * an optional registration check that transmits the PUBLIC key.
91
+ * 2. It never writes the private key into an MCP client config. The documented
92
+ * `@atbash/mcp` wiring passes the key as an `ATBASH_AGENT_PRIVKEY` env value
93
+ * inside e.g. `claude_desktop_config.json` — a file people screenshot, sync
94
+ * and share, and that package has no key-file fallback (verified against the
95
+ * published 0.1.3). So the entry setup writes points at `atbash mcp`, which
96
+ * reads the 0600 key file and passes the key to the server through the child
97
+ * environment. The config file itself gets NO credential — and an entry that
98
+ * was hand-wired with one has it removed.
99
+ * 3. It never edits application source. Code-level integrations (LangChain,
100
+ * LangGraph, AutoGen, Eliza, the SDK boundary) are the owner's to write.
101
+ * 4. It never rewrites a config file that uses comments or trailing commas.
102
+ * Reserializing JSONC as JSON silently deletes the owner's comments, so
103
+ * those files fall back to a printed snippet.
104
+ *
105
+ * ── NOTHING HERE IS INVENTED ─────────────────────────────────────────────────
106
+ * The plugin package name, the entry key it registers as, the config field names
107
+ * and the key-file format are all taken from the published integration docs. A
108
+ * plausible-looking config for a plugin that does not exist is worse than no
109
+ * config: it sends someone editing files for a package they cannot install.
110
+ */
111
+ // ── The canonical resting place for the agent key ───────────────────────────
112
+ // Every Atbash integration reads this path, and `@atbash/sdk`'s resolveKeyPath
113
+ // defaults to it. Whichever way the key arrives — pasted inline, read out of the
114
+ // browser download, already present — it ends up here once, and every runtime
115
+ // config we write REFERENCES this path rather than embedding the secret again.
116
+ const KEY_FILE_REL = [".config", "atbash", "guard-client-key"];
117
+ const OPENCLAW_CONFIG_REL = [".openclaw", "openclaw.json"];
118
+ const OPENCLAW_EXTENSIONS_REL = [".openclaw", "extensions"];
119
+ const HERMES_AGENT_REL = [".hermes", "hermes-agent"];
120
+ /**
121
+ * The OpenClaw plugin, and the entry key it registers itself as.
122
+ *
123
+ * The entry key really is `openclaw` — that is what `@atbash/atbash-openclaw`
124
+ * registers as, not a copy-paste slip. Installs of the earlier
125
+ * `@atbash/atbash-plugin` register under `atbash-plugin`, and the dashboard's
126
+ * capability scan recognizes BOTH. So an existing config carrying the legacy key
127
+ * is already governed and must not be given a second, duplicate entry.
128
+ */
129
+ const OPENCLAW_PKG = "@atbash/atbash-openclaw";
130
+ const OPENCLAW_ENTRY = "openclaw";
131
+ const OPENCLAW_LEGACY_ENTRY = "atbash-plugin";
132
+ /** File modes: 0700 for the key directory, 0600 for the key itself. */
133
+ const DIR_MODE = 0o700;
134
+ const KEY_MODE = 0o600;
135
+ // ── small filesystem helpers (best-effort; never throw) ─────────────────────
136
+ const exists = (...segs) => {
137
+ try {
138
+ return fs.existsSync(path.join(...segs));
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ };
144
+ const readTextFile = (file) => {
145
+ try {
146
+ return fs.readFileSync(file, "utf8");
147
+ }
148
+ catch {
149
+ return null;
150
+ }
151
+ };
152
+ /**
153
+ * Expand a leading `~/`. `--key-file ~/Downloads/keys.txt` typed inside quotes
154
+ * reaches us unexpanded, and failing on it would look like a missing file.
155
+ */
156
+ function expandHome(p, home) {
157
+ if (p === "~")
158
+ return home;
159
+ if (p.startsWith("~/"))
160
+ return path.join(home, p.slice(2));
161
+ return p;
162
+ }
163
+ /**
164
+ * Pull key material out of whatever the owner pointed us at.
165
+ *
166
+ * Accepts every shape Atbash itself produces or documents, so "the file I
167
+ * downloaded from the modal" always works:
168
+ * - `privkey=…` / `pubkey=…` lines (what onboarding downloads, and what the
169
+ * plugin parses)
170
+ * - `{"privKey":…,"pubKey":…}` JSON (the alternate documented key-file form)
171
+ * - a bare 64-hex private key on its own line (someone who copied just the key)
172
+ *
173
+ * Returns null rather than throwing: the caller tries several sources in turn and
174
+ * an unparseable one is a reason to move on, not to abort.
175
+ */
176
+ function parseKeyMaterial(raw) {
177
+ const text = raw.trim();
178
+ if (!text)
179
+ return null;
180
+ if (text.startsWith("{")) {
181
+ try {
182
+ const o = JSON.parse(text);
183
+ const priv = String(o.privKey ?? o.privkey ?? o.privateKey ?? "").trim();
184
+ const pub = String(o.pubKey ?? o.pubkey ?? o.publicKey ?? "").trim();
185
+ const clean = normalizePrivkey(priv);
186
+ return clean ? { privkey: clean, statedPubkey: pub || undefined } : null;
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ }
192
+ let priv = "";
193
+ let pub = "";
194
+ for (const line of text.split(/\r?\n/)) {
195
+ const trimmed = line.trim();
196
+ if (trimmed.startsWith("#") || !trimmed)
197
+ continue;
198
+ // Tolerate `privkey = x` and `privkey: x` — hand-edited files drift.
199
+ const kv = trimmed.match(/^(privkey|private_key|privatekey|pubkey|public_key|publickey)\s*[:=]\s*(.+)$/i);
200
+ if (kv) {
201
+ const value = kv[2].trim();
202
+ if (/^p(riv|rivate)/i.test(kv[1]))
203
+ priv = value;
204
+ else
205
+ pub = value;
206
+ continue;
207
+ }
208
+ // A bare key on its own line — only if we have not already found a labelled one.
209
+ if (!priv && /^(0x)?[0-9a-fA-F]{64}$/.test(trimmed))
210
+ priv = trimmed;
211
+ }
212
+ const clean = normalizePrivkey(priv);
213
+ return clean ? { privkey: clean, statedPubkey: pub || undefined } : null;
214
+ }
215
+ /** Normalize to the lowercase 64-hex the SDK validates, or "" if it is not one. */
216
+ function normalizePrivkey(raw) {
217
+ const clean = raw.replace(/^0x/i, "").trim().toLowerCase();
218
+ return (0, sdk_1.isValidPrivateKey)(clean) ? clean : "";
219
+ }
220
+ /** Only sniff the contents of small files — a key file is a few hundred bytes. */
221
+ const MAX_SNIFF_BYTES = 8 * 1024;
222
+ /** Bound the content-sniff so `--keys-dir ~` cannot turn into a directory crawl. */
223
+ const MAX_SNIFF_FILES = 60;
224
+ /** Newest-first, so a freshly downloaded key wins over one from last month. */
225
+ function newestFirst(files) {
226
+ return files
227
+ .map((file) => {
228
+ let mtime = 0;
229
+ try {
230
+ mtime = fs.statSync(file).mtimeMs;
231
+ }
232
+ catch { /* unreadable — sorts last */ }
233
+ return { file, mtime };
234
+ })
235
+ .sort((a, b) => b.mtime - a.mtime)
236
+ .map((e) => e.file);
237
+ }
238
+ /**
239
+ * Files in a directory that plausibly hold an Atbash agent key, newest first.
240
+ *
241
+ * TWO PASSES, and the second one is the point.
242
+ *
243
+ * By name first — `guard-client-key`, `agent-keys-*.txt` and friends — because
244
+ * matching the name is cheap and unambiguous. But a name-only match is a cliff:
245
+ * rename the download, or export from a wallet UI that picks its own filename,
246
+ * and the operator gets "no key file found" while the key sits right there in the
247
+ * directory they explicitly pointed at.
248
+ *
249
+ * So if no name matches, read the small files and keep the ones that actually
250
+ * PARSE as key material. That is a narrow test — `privkey=`, the documented JSON
251
+ * shape, or a file that is nothing but a 64-hex key — not "contains something
252
+ * hex-looking", so an unrelated file does not get mistaken for an identity.
253
+ *
254
+ * Reading files the operator did not name individually is justified by the flag
255
+ * itself: `--keys-dir` is an explicit instruction to look in that directory. It
256
+ * is bounded to small regular files and a file count, nothing is transmitted, and
257
+ * the caller prints WHICH file it used before doing anything with it.
258
+ */
259
+ function keyCandidatesInDir(dir) {
260
+ let names;
261
+ try {
262
+ names = fs.readdirSync(dir);
263
+ }
264
+ catch {
265
+ return [];
266
+ }
267
+ const byName = names.filter((n) => n === "guard-client-key" ||
268
+ /^agent-keys-.*\.txt$/i.test(n) ||
269
+ /^atbash.*(key|keys).*\.(txt|json)$/i.test(n));
270
+ if (byName.length)
271
+ return newestFirst(byName.map((n) => path.join(dir, n)));
272
+ const byContent = [];
273
+ let examined = 0;
274
+ for (const name of names) {
275
+ if (examined >= MAX_SNIFF_FILES)
276
+ break;
277
+ const file = path.join(dir, name);
278
+ try {
279
+ const stat = fs.statSync(file);
280
+ if (!stat.isFile() || stat.size === 0 || stat.size > MAX_SNIFF_BYTES)
281
+ continue;
282
+ }
283
+ catch {
284
+ continue;
285
+ }
286
+ examined++;
287
+ const text = readTextFile(file);
288
+ if (text !== null && parseKeyMaterial(text))
289
+ byContent.push(file);
290
+ }
291
+ return newestFirst(byContent);
292
+ }
293
+ /**
294
+ * Read a secret from the terminal without echoing it.
295
+ *
296
+ * Prompting exists so the key does not have to appear in the command line: an
297
+ * inline `--key` is convenient (it is what makes a one-line command copied out of
298
+ * the browser work) but it lands in shell history and in the process list. When
299
+ * there is a TTY and no key was supplied, ask instead.
300
+ *
301
+ * The prompt deliberately accepts a PATH as well as a key, because "where are
302
+ * your keys?" and "paste your key" are the same question from the owner's side.
303
+ */
304
+ async function promptForKeyOrPath() {
305
+ const { createInterface } = await Promise.resolve().then(() => __importStar(require("node:readline")));
306
+ return new Promise((resolveP) => {
307
+ const prompt = "Paste the agent's private key, or the path to its key file: ";
308
+ // Write the prompt ourselves, THEN suppress every subsequent write.
309
+ //
310
+ // The obvious implementation compares each write against the prompt text and
311
+ // lets that one through — but a pasted value containing the prompt as a
312
+ // substring would then be echoed to the terminal, which is exactly the
313
+ // failure this mute exists to prevent. Emitting the prompt up front means the
314
+ // suppressor never has to decide what a write IS: after this point, nothing
315
+ // is echoed, unconditionally.
316
+ process.stdout.write(prompt);
317
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
318
+ rl._writeToOutput = () => {
319
+ /* nothing typed after the prompt is ever echoed */
320
+ };
321
+ rl.question("", (answer) => {
322
+ rl.close();
323
+ // readline's own newline was suppressed along with everything else, so the
324
+ // next line of output would otherwise land on the prompt line.
325
+ process.stdout.write("\n");
326
+ resolveP(answer.trim());
327
+ });
328
+ });
329
+ }
330
+ /**
331
+ * Find the agent key, trying every way an owner could plausibly have it.
332
+ *
333
+ * Order is "most explicit first": a flag the owner typed beats a file we guessed
334
+ * at. The last resort is the interactive prompt, and if there is no TTY the
335
+ * caller gets a clear error listing the flags rather than a hang.
336
+ */
337
+ async function resolveKeySource(opts) {
338
+ const { home } = opts;
339
+ const fromFile = (file, label) => {
340
+ const text = readTextFile(file);
341
+ if (text === null)
342
+ return { error: `Could not read ${file}` };
343
+ const material = parseKeyMaterial(text);
344
+ if (!material)
345
+ return { error: `${file} does not contain a valid 64-hex agent private key.` };
346
+ return { material, from: `${label} (${file})` };
347
+ };
348
+ // 1. Inline — what a one-line command copied from the onboarding modal uses.
349
+ if (opts.key) {
350
+ const material = parseKeyMaterial(opts.key);
351
+ if (!material)
352
+ return { error: "--key is not a valid agent private key (expected 64 hex characters)." };
353
+ return { material, from: "--key on the command line" };
354
+ }
355
+ // 2. An explicit file.
356
+ if (opts.keyFile)
357
+ return fromFile(expandHome(opts.keyFile, home), "--key-file");
358
+ // 3. A directory to look in — "the keys are in my Downloads folder".
359
+ if (opts.keysDir) {
360
+ const dir = expandHome(opts.keysDir, home);
361
+ const candidates = keyCandidatesInDir(dir);
362
+ if (!candidates.length) {
363
+ return {
364
+ error: [
365
+ `No agent key found in ${dir}.`,
366
+ "Looked for guard-client-key / agent-keys-*.txt by name, then read the small",
367
+ "files there to see if any parsed as an agent key. Neither found one.",
368
+ "Point at the file directly with --key-file, or paste the key with no flags",
369
+ "at all and setup will prompt for it.",
370
+ ].join("\n"),
371
+ };
372
+ }
373
+ return fromFile(candidates[0], "--keys-dir");
374
+ }
375
+ // 4. The environment variable the rest of the CLI already honours.
376
+ const fromEnv = process.env.ATBASH_AGENT_KEY;
377
+ if (fromEnv) {
378
+ const material = parseKeyMaterial(fromEnv);
379
+ if (material)
380
+ return { material, from: "ATBASH_AGENT_KEY" };
381
+ }
382
+ // 5. Already in the canonical place — a re-run, or a machine set up before.
383
+ const keyFile = path.join(home, ...KEY_FILE_REL);
384
+ if (exists(keyFile)) {
385
+ const found = fromFile(keyFile, "existing key file");
386
+ if (!("error" in found))
387
+ return found;
388
+ }
389
+ // 6. The CLI's own config, populated by `atbash set agent-key`.
390
+ const fromConfig = (0, sdk_1.resolve)("agentKey");
391
+ if (fromConfig) {
392
+ const material = parseKeyMaterial(fromConfig);
393
+ if (material)
394
+ return { material, from: "atbash config (agentKey)" };
395
+ }
396
+ // 7. Ask.
397
+ if (opts.allowPrompt) {
398
+ const answer = await promptForKeyOrPath();
399
+ if (!answer)
400
+ return { error: "No key provided." };
401
+ const direct = parseKeyMaterial(answer);
402
+ if (direct)
403
+ return { material: direct, from: "interactive prompt" };
404
+ const asPath = expandHome(answer, home);
405
+ if (exists(asPath)) {
406
+ const stat = fs.statSync(asPath);
407
+ if (stat.isDirectory()) {
408
+ const candidates = keyCandidatesInDir(asPath);
409
+ if (candidates.length)
410
+ return fromFile(candidates[0], "directory given at the prompt");
411
+ return { error: `No agent key file found in ${asPath}.` };
412
+ }
413
+ return fromFile(asPath, "file given at the prompt");
414
+ }
415
+ return { error: "That is neither a 64-hex private key nor a path that exists." };
416
+ }
417
+ return {
418
+ error: [
419
+ "No agent key found.",
420
+ "Provide one with --key <64-hex>, --key-file <path>, or --keys-dir <dir>,",
421
+ `or place it at ${keyFile} first.`,
422
+ ].join("\n"),
423
+ };
424
+ }
425
+ /** The key file, in the `key=value` form the plugin and the SDK both parse. */
426
+ function keyFileContents(privkey, pubkey) {
427
+ return [
428
+ "# Atbash agent key",
429
+ "# Keep this file private (chmod 600). Read locally by every Atbash integration.",
430
+ `pubkey=${pubkey}`,
431
+ `privkey=${privkey}`,
432
+ "",
433
+ ].join("\n");
434
+ }
435
+ /**
436
+ * True when a JSON file uses JSONC features (comments, trailing commas).
437
+ *
438
+ * We must not auto-merge into one: writing it back with JSON.stringify would
439
+ * silently delete the owner's comments. Detected by the disagreement between the
440
+ * strict and tolerant parsers — strict fails, tolerant succeeds.
441
+ */
442
+ function isJsonc(text) {
443
+ try {
444
+ JSON.parse(text);
445
+ return false;
446
+ }
447
+ catch { /* fall through */ }
448
+ const errors = [];
449
+ const value = jsonc.parse(text, errors, { allowTrailingComma: true, disallowComments: false });
450
+ return errors.length === 0 && value !== undefined;
451
+ }
452
+ /**
453
+ * Merge the Atbash plugin block into an OpenClaw config object, in place.
454
+ *
455
+ * A MERGE, not a replacement — that distinction is the whole reason this command
456
+ * exists. Other plugins already in `allow`, `load.paths` and `entries` are
457
+ * preserved, and an entry from the legacy `@atbash/atbash-plugin` install is
458
+ * updated where it stands rather than being shadowed by a duplicate: the
459
+ * dashboard scan recognizes both keys, so two entries would mean two hooks.
460
+ *
461
+ * `load.paths` gets the real absolute extension path. The published docs show a
462
+ * `<your-username>` placeholder that people paste verbatim, producing a path that
463
+ * does not exist and a plugin that never loads.
464
+ */
465
+ function mergeOpenclawConfig(config, home) {
466
+ const out = { ...config };
467
+ const plugins = { ...(isRecord(out.plugins) ? out.plugins : {}) };
468
+ // Which key is this install governed under? Keep an existing legacy entry
469
+ // where it is instead of adding a second one.
470
+ const entries = { ...(isRecord(plugins.entries) ? plugins.entries : {}) };
471
+ const entryKey = OPENCLAW_LEGACY_ENTRY in entries && !(OPENCLAW_ENTRY in entries)
472
+ ? OPENCLAW_LEGACY_ENTRY
473
+ : OPENCLAW_ENTRY;
474
+ const allow = Array.isArray(plugins.allow) ? [...plugins.allow] : [];
475
+ if (!allow.includes(entryKey))
476
+ allow.push(entryKey);
477
+ plugins.allow = allow;
478
+ const load = { ...(isRecord(plugins.load) ? plugins.load : {}) };
479
+ const extensionPath = path.join(home, ...OPENCLAW_EXTENSIONS_REL, OPENCLAW_ENTRY);
480
+ const paths = Array.isArray(load.paths) ? [...load.paths] : [];
481
+ if (!paths.includes(extensionPath))
482
+ paths.push(extensionPath);
483
+ load.paths = paths;
484
+ plugins.load = load;
485
+ // Preserve any unrelated fields the owner set on the entry (debug, custom
486
+ // hooks); only the fields Atbash owns are asserted.
487
+ const existing = isRecord(entries[entryKey]) ? entries[entryKey] : {};
488
+ const existingConfig = isRecord(existing.config) ? existing.config : {};
489
+ const existingHooks = isRecord(existing.hooks) ? existing.hooks : {};
490
+ entries[entryKey] = {
491
+ ...existing,
492
+ enabled: true,
493
+ config: {
494
+ ...existingConfig,
495
+ enabled: true,
496
+ enforceDecision: true,
497
+ // The path, not the key. This is the whole point of the canonical location.
498
+ chromiaSecretPath: `~/${KEY_FILE_REL.join("/")}`,
499
+ },
500
+ hooks: {
501
+ ...existingHooks,
502
+ allowConversationAccess: true,
503
+ allowPromptInjection: true,
504
+ },
505
+ };
506
+ plugins.entries = entries;
507
+ out.plugins = plugins;
508
+ return out;
509
+ }
510
+ function isRecord(v) {
511
+ return !!v && typeof v === "object" && !Array.isArray(v);
512
+ }
513
+ /**
514
+ * Detect the indentation a JSON file already uses, so a merge does not reformat
515
+ * the parts it did not touch.
516
+ *
517
+ * Without this, `JSON.stringify(obj, null, 2)` re-indents a tab-indented or
518
+ * 4-space config from top to bottom. The RESULT is still correct, but the diff
519
+ * shown for approval becomes every line in the file, which buries the two lines
520
+ * that actually changed — and the operator's own formatting choice is collateral
521
+ * damage in a file we were asked to make one addition to.
522
+ *
523
+ * Falls back to two spaces, which is what the published docs show.
524
+ */
525
+ function detectIndent(text) {
526
+ if (!text)
527
+ return 2;
528
+ // First line that is indented under an opening brace/bracket tells us the unit.
529
+ const match = text.match(/\n([ \t]+)\S/);
530
+ if (!match)
531
+ return 2;
532
+ const indent = match[1];
533
+ return indent.startsWith("\t") ? "\t" : indent.length;
534
+ }
535
+ /**
536
+ * Serialize a merged config the way the file was already written: same
537
+ * indentation, and a trailing newline only if the original had one.
538
+ */
539
+ function serializeLike(original, value) {
540
+ const body = JSON.stringify(value, null, detectIndent(original));
541
+ // A file that ended without a newline keeps ending without one. Trivial, but it
542
+ // is one more line of unexplained diff for someone reviewing the change.
543
+ const trailing = original === null || original.endsWith("\n") ? "\n" : "";
544
+ return body + trailing;
545
+ }
546
+ /**
547
+ * The MCP server entry setup writes into a client's config.
548
+ *
549
+ * Note what is NOT here: an `env` block. The published `@atbash/mcp` wiring
550
+ * carries the agent's private key in one, because that package reads only
551
+ * ATBASH_AGENT_PRIVKEY. Going through `atbash mcp` instead means the launcher
552
+ * reads the 0600 key file and passes the key to the server in the child process
553
+ * environment, so this entry holds no credential and the client's config file is
554
+ * no more sensitive after setup runs than it was before.
555
+ *
556
+ * Deliberately NOT pinned to an exact CLI version: unlike the one-shot connector
557
+ * command, this entry persists in the operator's config and is re-executed every
558
+ * time the client starts. Pinning here would freeze their MCP server at whatever
559
+ * version happened to be current on the day they ran setup.
560
+ */
561
+ const MCP_SERVER_ENTRY = { command: "npx", args: ["--yes", "@atbash/cli", "mcp"] };
562
+ const MCP_SERVER_NAME = "atbash";
563
+ /**
564
+ * MCP client configs present under this home directory.
565
+ *
566
+ * Paths come from the shared MCP_CONFIGS so the writer and the scanner cannot
567
+ * drift: a client the scan reports but setup cannot find would look like a bug in
568
+ * whichever of the two the operator happened to trust.
569
+ */
570
+ function detectMcpClients(home) {
571
+ const out = [];
572
+ const seen = new Set();
573
+ for (const { label, segs } of atbash_targets_1.MCP_CONFIGS) {
574
+ if (seen.has(label))
575
+ continue;
576
+ const file = path.join(home, ...segs);
577
+ if (!exists(file))
578
+ continue;
579
+ seen.add(label);
580
+ // Read which key this file already uses rather than assuming. VS Code's
581
+ // mcp.json uses `servers`; writing `mcpServers` into it would be ignored.
582
+ const existing = readJsonLoose(file);
583
+ const serversKey = existing && isRecord(existing.servers) && !isRecord(existing.mcpServers) ? "servers" : "mcpServers";
584
+ out.push({ label, file, format: "json", serversKey });
585
+ }
586
+ // Claude Code and Codex are special-cased in the scanner too — same paths.
587
+ const claudeCode = path.join(home, ".claude.json");
588
+ if (exists(claudeCode))
589
+ out.push({ label: "Claude Code", file: claudeCode, format: "json", serversKey: "mcpServers" });
590
+ const codex = path.join(home, ".codex", "config.toml");
591
+ if (exists(codex))
592
+ out.push({ label: "Codex", file: codex, format: "toml", serversKey: "mcpServers" });
593
+ return out;
594
+ }
595
+ /** Tolerant read used only to sniff an existing file's shape. */
596
+ function readJsonLoose(file) {
597
+ const text = readTextFile(file);
598
+ if (text === null)
599
+ return null;
600
+ const value = jsonc.parse(text, [], { allowTrailingComma: true, disallowComments: false });
601
+ return isRecord(value) ? value : null;
602
+ }
603
+ /**
604
+ * Add the Atbash server to a client config's server map, in place.
605
+ *
606
+ * A merge, like the OpenClaw one: every server the operator already configured
607
+ * stays exactly as it is. An existing `atbash` entry is REPLACED rather than
608
+ * merged field-by-field — a stale `env` block carrying a private key from the old
609
+ * hand-written wiring is precisely what we want gone, and preserving it would
610
+ * defeat the point of routing through the launcher.
611
+ */
612
+ /** The Hermes plugin, and the exact version the wiring is written against. */
613
+ const HERMES_PKG = "atbash-hermes-plugin";
614
+ const HERMES_VERSION = "0.4.5";
615
+ /**
616
+ * Find the Python interpreter that actually runs Hermes.
617
+ *
618
+ * This is the difference between installing the plugin and only appearing to.
619
+ * `pip install atbash-hermes-plugin` puts the package wherever the *shell's*
620
+ * `pip` points — commonly a system or conda Python — while Hermes typically runs
621
+ * from its own virtualenv. The install succeeds, prints nothing alarming, and the
622
+ * plugin is invisible to Hermes forever. Nobody can debug that from the output.
623
+ *
624
+ * The launcher knows the answer. A pip-installed console script begins with a
625
+ * shebang naming the interpreter that created it:
626
+ *
627
+ * $ head -1 $(command -v hermes)
628
+ * #!/Users/me/.hermes/hermes-agent/venv/bin/python3
629
+ *
630
+ * So resolve `hermes`, read its first line, and use that interpreter directly via
631
+ * `-m pip`. Falls back to the conventional venv location under ~/.hermes, then to
632
+ * null — and a null becomes a printed command rather than a guess, because a
633
+ * wrong guess here is the silent failure this whole function exists to avoid.
634
+ */
635
+ function findHermesPython(home) {
636
+ const viable = (candidate) => {
637
+ try {
638
+ return fs.statSync(candidate).isFile();
639
+ }
640
+ catch {
641
+ return false;
642
+ }
643
+ };
644
+ // 1. The launcher's own shebang — authoritative, but only for a real run.
645
+ //
646
+ // `--home <dir>` exists so a dry run can be hermetic (the release checklist
647
+ // depends on it). A PATH lookup ignores it entirely: under `--home /tmp/fake`
648
+ // this would find the operator's ACTUAL hermes and plan an install into their
649
+ // real virtualenv. So the shebang route is skipped whenever `home` is not the
650
+ // machine's own home — the caller then falls through to the venv path under the
651
+ // given home, which is correctly scoped.
652
+ const realHome = process.env.HOME || os.homedir();
653
+ const scoped = path.resolve(home) !== path.resolve(realHome);
654
+ const which = scoped
655
+ ? { status: 1, stdout: "" }
656
+ : (0, child_process_1.spawnSync)(process.platform === "win32" ? "where" : "which", ["hermes"], { encoding: "utf8" });
657
+ const launcher = which.status === 0 ? which.stdout.split(/\r?\n/)[0]?.trim() : "";
658
+ if (launcher && viable(launcher)) {
659
+ const firstLine = (readTextFile(launcher) ?? "").split(/\r?\n/)[0] ?? "";
660
+ const shebang = firstLine.startsWith("#!") ? firstLine.slice(2).trim() : "";
661
+ // `#!/usr/bin/env python3` names no path; anything else should be absolute.
662
+ const interpreter = shebang.split(/\s+/).filter((part) => !part.endsWith("/env"))[0] ?? "";
663
+ if (/python[0-9.]*$/.test(interpreter) && viable(interpreter)) {
664
+ return { python: interpreter, how: `shebang of ${launcher}` };
665
+ }
666
+ }
667
+ // 2. The conventional venv Hermes ships with.
668
+ for (const name of ["python3", "python"]) {
669
+ const candidate = path.join(home, ".hermes", "hermes-agent", "venv", "bin", name);
670
+ if (viable(candidate))
671
+ return { python: candidate, how: "Hermes virtualenv under ~/.hermes" };
672
+ }
673
+ return null;
674
+ }
675
+ /**
676
+ * The env vars the Hermes plugin documents, merged into an existing `.env`.
677
+ *
678
+ * A `.env` is line-oriented and hand-maintained, so this is a line merge rather
679
+ * than a parse-and-reserialize: keys Atbash owns are replaced in place (keeping
680
+ * their position), keys it does not own are never touched, and anything else in
681
+ * the file — comments, blank lines, unrelated settings, ordering — survives
682
+ * exactly as written. Reformatting someone's .env to add four lines would be a
683
+ * poor trade.
684
+ *
685
+ * Values are from the published plugin README (PyPI atbash-hermes-plugin 0.4.5).
686
+ * `ATBASH_ORG_NAME` is deliberately NOT written: its value is the operator's org,
687
+ * which this command has no reliable way to know, and a wrong org sends the SDK
688
+ * at the wrong chain. It is called out in the manual step instead.
689
+ */
690
+ function mergeHermesEnv(existing) {
691
+ const desired = {
692
+ ATBASH_KEY_PATH: "$HOME/.config/atbash/guard-client-key",
693
+ ATBASH_ENFORCE_DECISION: "true",
694
+ };
695
+ const lines = existing === null ? [] : existing.split("\n");
696
+ const seen = new Set();
697
+ const out = lines.map((line) => {
698
+ const match = line.match(/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=/);
699
+ const key = match?.[1];
700
+ if (!key || !(key in desired) || seen.has(key))
701
+ return line;
702
+ seen.add(key);
703
+ // Already correct — keep the operator's own formatting rather than rewriting.
704
+ if (line.trim() === `${key}=${desired[key]}`)
705
+ return line;
706
+ return `${key}=${desired[key]}`;
707
+ });
708
+ const missing = Object.entries(desired).filter(([key]) => !seen.has(key));
709
+ if (missing.length) {
710
+ // Separate the block we add from whatever came before it.
711
+ if (out.length && out[out.length - 1].trim() !== "")
712
+ out.push("");
713
+ // ASCII-only comment on purpose: .env files are read by many different
714
+ // parsers and a stray multi-byte dash is a free way to trip a strict one.
715
+ if (existing !== null)
716
+ out.push("# Added by `atbash setup` - Atbash Hermes plugin");
717
+ for (const [key, value] of missing)
718
+ out.push(`${key}=${value}`);
719
+ }
720
+ let text = out.join("\n");
721
+ if (!text.endsWith("\n"))
722
+ text += "\n";
723
+ return text;
724
+ }
725
+ /**
726
+ * Does this config's existing Atbash entry carry a key in its `env` block?
727
+ *
728
+ * True means the operator hand-wired it from the published docs and their private
729
+ * key is sitting in that file today. Setup takes it out, but the backup it writes
730
+ * first still has it — so this exists to make that sayable rather than silently
731
+ * relocating the leak.
732
+ */
733
+ function hadInlineKey(config, serversKey = "mcpServers") {
734
+ const servers = isRecord(config[serversKey]) ? config[serversKey] : undefined;
735
+ const entry = servers && isRecord(servers[MCP_SERVER_NAME]) ? servers[MCP_SERVER_NAME] : undefined;
736
+ const env = entry && isRecord(entry.env) ? entry.env : undefined;
737
+ if (!env)
738
+ return false;
739
+ // Any 64-hex value, under any key name — not just the documented one, since a
740
+ // hand-edited config may well have renamed it.
741
+ return Object.values(env).some((v) => typeof v === "string" && /^(0x)?[0-9a-fA-F]{64}$/.test(v.trim()));
742
+ }
743
+ function mergeMcpServer(config, serversKey = "mcpServers") {
744
+ const out = { ...config };
745
+ const servers = { ...(isRecord(out[serversKey]) ? out[serversKey] : {}) };
746
+ servers[MCP_SERVER_NAME] = { ...MCP_SERVER_ENTRY, args: [...MCP_SERVER_ENTRY.args] };
747
+ out[serversKey] = servers;
748
+ return out;
749
+ }
750
+ /** Is `openclaw` runnable on this machine? Decides install-for-you vs print-it. */
751
+ function hasExecutable(command) {
752
+ const probe = (0, child_process_1.spawnSync)(process.platform === "win32" ? "where" : "which", [command], { stdio: "ignore" });
753
+ return probe.status === 0;
754
+ }
755
+ /**
756
+ * Work out everything that needs doing on this machine, without doing any of it.
757
+ *
758
+ * Detection drives the plan rather than a flag the owner picks, for the same
759
+ * reason the scan does: what is actually installed here is knowable, and asking
760
+ * someone to identify their own runtime from a list invites a wrong answer that
761
+ * writes a config for a plugin they do not have.
762
+ */
763
+ function buildPlan(args) {
764
+ const { home, privkey, pubkey, noInstall, only } = args;
765
+ const steps = [];
766
+ const notes = [];
767
+ const found = [];
768
+ const wanted = (id) => only.length === 0 || only.includes(id);
769
+ // ── 1. The key file. Always, for every runtime: it is the one artifact every
770
+ // integration reads, and the thing the owner would otherwise move by hand.
771
+ const keyFile = path.join(home, ...KEY_FILE_REL);
772
+ const desiredKeyFile = keyFileContents(privkey, pubkey);
773
+ const currentKeyFile = readTextFile(keyFile);
774
+ const alreadyThisKey = currentKeyFile !== null && parseKeyMaterial(currentKeyFile)?.privkey === privkey;
775
+ if (!alreadyThisKey) {
776
+ if (currentKeyFile !== null) {
777
+ 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.`);
778
+ }
779
+ steps.push({
780
+ kind: "write",
781
+ label: currentKeyFile === null ? "Save the agent key where every integration looks for it" : "Replace the agent key file",
782
+ file: keyFile,
783
+ mode: KEY_MODE,
784
+ before: currentKeyFile,
785
+ after: desiredKeyFile,
786
+ secret: true,
787
+ });
788
+ }
789
+ else {
790
+ notes.push(`${keyFile} already holds this agent's key — left untouched.`);
791
+ }
792
+ // ── 2. OpenClaw: the one runtime governed purely by a config file, so the one
793
+ // this command can finish end to end.
794
+ const openclawConfigFile = path.join(home, ...OPENCLAW_CONFIG_REL);
795
+ if (exists(openclawConfigFile) || exists(home, ".openclaw")) {
796
+ found.push("OpenClaw");
797
+ if (wanted("openclaw")) {
798
+ if (!noInstall) {
799
+ if (hasExecutable("openclaw")) {
800
+ steps.push({ kind: "exec", label: `Install ${OPENCLAW_PKG}`, command: "openclaw", args: ["plugins", "install", OPENCLAW_PKG] });
801
+ }
802
+ else {
803
+ steps.push({
804
+ kind: "manual",
805
+ label: "Install the OpenClaw plugin",
806
+ 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:",
807
+ snippet: `openclaw plugins install ${OPENCLAW_PKG}`,
808
+ });
809
+ }
810
+ }
811
+ const raw = readTextFile(openclawConfigFile);
812
+ if (raw !== null && isJsonc(raw)) {
813
+ // Rewriting this would delete the owner's comments. Print instead.
814
+ steps.push({
815
+ kind: "manual",
816
+ label: `Enable the plugin in ${openclawConfigFile}`,
817
+ 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`:",
818
+ snippet: JSON.stringify(mergeOpenclawConfig((jsonc.parse(raw, [], { allowTrailingComma: true, disallowComments: false }) ?? {}), home), null, 2),
819
+ });
820
+ }
821
+ else {
822
+ let current = {};
823
+ if (raw !== null) {
824
+ try {
825
+ const parsed = JSON.parse(raw);
826
+ if (isRecord(parsed))
827
+ current = parsed;
828
+ }
829
+ catch {
830
+ 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.`);
831
+ }
832
+ }
833
+ const after = serializeLike(raw, mergeOpenclawConfig(current, home));
834
+ if (raw !== after) {
835
+ steps.push({
836
+ kind: "write",
837
+ label: raw === null
838
+ ? "Create ~/.openclaw/openclaw.json with the plugin enabled"
839
+ : "Enable the plugin in ~/.openclaw/openclaw.json (a merge — existing plugins are kept)",
840
+ file: openclawConfigFile,
841
+ before: raw,
842
+ after,
843
+ });
844
+ }
845
+ else {
846
+ notes.push(`${openclawConfigFile} already has the plugin enabled — left untouched.`);
847
+ }
848
+ }
849
+ notes.push("Restart the OpenClaw gateway. The hook is registered at startup, so the plugin does nothing until it restarts.");
850
+ }
851
+ }
852
+ // ── 3. Hermes: not a runtime that merely lacks a plugin. It runs the SAME
853
+ // agent, reads the same skills and the same key — but the Atbash hook lives in
854
+ // the OpenClaw gateway, so anything driven through the Hermes API is never
855
+ // judged. Setup places the key file and says so; it does not pretend to wire it.
856
+ if (exists(home, ...HERMES_AGENT_REL)) {
857
+ found.push("Hermes");
858
+ if (wanted("hermes")) {
859
+ const envFile = path.join(home, ".hermes", ".env");
860
+ const raw = readTextFile(envFile);
861
+ const merged = mergeHermesEnv(raw);
862
+ if (merged !== raw) {
863
+ steps.push({
864
+ kind: "write",
865
+ label: raw === null
866
+ ? "Create ~/.hermes/.env pointing the Hermes plugin at the agent key"
867
+ : "Point the Hermes plugin at the agent key in ~/.hermes/.env (a merge — your other settings are kept)",
868
+ file: envFile,
869
+ before: raw,
870
+ after: merged,
871
+ });
872
+ }
873
+ else {
874
+ notes.push(`${envFile} already points the Hermes plugin at this key — left untouched.`);
875
+ }
876
+ // The Python package must land in the interpreter that RUNS Hermes, not
877
+ // whichever pip the shell happens to resolve. When we can identify that
878
+ // interpreter we install into it directly; when we cannot, we hand the
879
+ // command over rather than guess, because guessing wrong installs
880
+ // successfully and governs nothing.
881
+ if (!noInstall) {
882
+ const hermesPython = findHermesPython(home);
883
+ if (hermesPython) {
884
+ steps.push({
885
+ kind: "exec",
886
+ label: `Install ${HERMES_PKG} into the interpreter that runs Hermes (found via ${hermesPython.how})`,
887
+ command: hermesPython.python,
888
+ args: ["-m", "pip", "install", `${HERMES_PKG}==${HERMES_VERSION}`],
889
+ });
890
+ }
891
+ else {
892
+ steps.push({
893
+ kind: "manual",
894
+ label: "Install the Hermes plugin",
895
+ detail: [
896
+ "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.",
897
+ "",
898
+ "Run this with the interpreter Hermes uses (if it runs in a virtualenv, that venv's python):",
899
+ ].join("\n"),
900
+ snippet: `/path/to/hermes/venv/bin/python -m pip install ${HERMES_PKG}==${HERMES_VERSION}`,
901
+ });
902
+ }
903
+ }
904
+ notes.push("Restart Hermes — it reads .env and discovers plugins at startup. Then confirm with `hermes plugins list | grep atbash`.");
905
+ notes.push("ATBASH_ENFORCE_DECISION=true is fail-closed: if Atbash cannot be reached, the Hermes tool call is blocked rather than allowed.");
906
+ 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.");
907
+ }
908
+ }
909
+ // ── 4. MCP clients.
910
+ //
911
+ // This used to be a manual step, and the reason was specific: `@atbash/mcp`
912
+ // reads its identity from ATBASH_AGENT_PRIVKEY with no key-file fallback, so
913
+ // the documented wiring puts a raw private key inside the client's own config —
914
+ // `claude_desktop_config.json` and friends, files that get synced between
915
+ // machines and pasted into help requests. Automating that would have meant the
916
+ // automation's whole job was planting a secret somewhere worse.
917
+ //
918
+ // `atbash mcp` removes the reason. The client spawns the launcher, which reads
919
+ // the key from the 0600 file and hands it to the server through the child
920
+ // environment only. The config entry carries NO credential, so it is safe to
921
+ // write — and a config with no secret in it is strictly better than the one the
922
+ // operator would have hand-written from the docs.
923
+ if (wanted("mcp")) {
924
+ for (const client of detectMcpClients(home)) {
925
+ found.push(client.label);
926
+ if (client.format !== "json") {
927
+ // TOML (Codex) — @iarna/toml can round-trip values but not comments, and
928
+ // a config.toml is usually hand-maintained. Print it instead.
929
+ steps.push({
930
+ kind: "manual",
931
+ label: `Add Atbash to ${client.label}`,
932
+ detail: `${client.file} is TOML, and rewriting it would drop any comments in it. Add this table by hand:`,
933
+ snippet: ["[mcp_servers.atbash]", 'command = "npx"', 'args = ["--yes", "@atbash/cli", "mcp"]'].join("\n"),
934
+ });
935
+ continue;
936
+ }
937
+ const raw = readTextFile(client.file);
938
+ if (raw !== null && isJsonc(raw)) {
939
+ steps.push({
940
+ kind: "manual",
941
+ label: `Add Atbash to ${client.label}`,
942
+ 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:`,
943
+ snippet: JSON.stringify({ mcpServers: { atbash: MCP_SERVER_ENTRY } }, null, 2),
944
+ });
945
+ continue;
946
+ }
947
+ let current = {};
948
+ if (raw !== null) {
949
+ try {
950
+ const parsed = JSON.parse(raw);
951
+ if (isRecord(parsed))
952
+ current = parsed;
953
+ }
954
+ catch {
955
+ notes.push(`${client.file} is not valid JSON, so it was left alone. Fix the file and re-run to wire ${client.label}.`);
956
+ continue;
957
+ }
958
+ }
959
+ const after = serializeLike(raw, mergeMcpServer(current, client.serversKey));
960
+ if (raw !== after) {
961
+ // A hand-wired entry from the old documented shape carries the private key
962
+ // in an `env` block. Replacing it REMOVES that secret from the live config
963
+ // — good — but the backup we are about to take still contains it, and an
964
+ // operator who does not know that has simply moved the leak to a new file.
965
+ if (hadInlineKey(current, client.serversKey)) {
966
+ 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.`);
967
+ }
968
+ steps.push({
969
+ kind: "write",
970
+ 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" : ""})`,
971
+ file: client.file,
972
+ before: raw,
973
+ after,
974
+ });
975
+ }
976
+ else {
977
+ notes.push(`${client.label} already has the Atbash MCP server — left untouched.`);
978
+ }
979
+ }
980
+ if (found.some((f) => f !== "OpenClaw" && f !== "Hermes")) {
981
+ notes.push("Restart any MCP client that was changed — clients read their server list at startup.");
982
+ // A client whose first launch of the server takes ~12s can report a startup
983
+ // timeout that looks like a broken config. Say so, so the first thing an
984
+ // operator does is retry rather than undo the wiring.
985
+ 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.");
986
+ }
987
+ }
988
+ if (!found.length) {
989
+ 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.");
990
+ }
991
+ return { steps, notes, found };
992
+ }
993
+ // ── Showing the plan ────────────────────────────────────────────────────────
994
+ /**
995
+ * A minimal line diff, so the preview shows what CHANGES rather than dumping a
996
+ * whole config and leaving the owner to spot the difference. Standard LCS; these
997
+ * files are small enough that the quadratic table is irrelevant.
998
+ */
999
+ function lineDiff(before, after) {
1000
+ const a = before.split("\n");
1001
+ const b = after.split("\n");
1002
+ const table = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
1003
+ for (let i = a.length - 1; i >= 0; i--) {
1004
+ for (let j = b.length - 1; j >= 0; j--) {
1005
+ table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
1006
+ }
1007
+ }
1008
+ const out = [];
1009
+ let i = 0;
1010
+ let j = 0;
1011
+ while (i < a.length && j < b.length) {
1012
+ if (a[i] === b[j]) {
1013
+ out.push(` ${a[i]}`);
1014
+ i++;
1015
+ j++;
1016
+ }
1017
+ else if (table[i + 1][j] >= table[i][j + 1]) {
1018
+ out.push(`- ${a[i]}`);
1019
+ i++;
1020
+ }
1021
+ else {
1022
+ out.push(`+ ${b[j]}`);
1023
+ j++;
1024
+ }
1025
+ }
1026
+ for (; i < a.length; i++)
1027
+ out.push(`- ${a[i]}`);
1028
+ for (; j < b.length; j++)
1029
+ out.push(`+ ${b[j]}`);
1030
+ return out;
1031
+ }
1032
+ /** Drop unchanged runs down to a little context, so a long config stays readable. */
1033
+ function condense(diff, context = 2) {
1034
+ const keep = new Set();
1035
+ diff.forEach((line, index) => {
1036
+ if (line.startsWith("+") || line.startsWith("-")) {
1037
+ for (let k = index - context; k <= index + context; k++)
1038
+ if (k >= 0 && k < diff.length)
1039
+ keep.add(k);
1040
+ }
1041
+ });
1042
+ const out = [];
1043
+ let skipping = false;
1044
+ diff.forEach((line, index) => {
1045
+ if (keep.has(index)) {
1046
+ out.push(line);
1047
+ skipping = false;
1048
+ }
1049
+ else if (!skipping) {
1050
+ out.push(chalk_1.default.dim(" …"));
1051
+ skipping = true;
1052
+ }
1053
+ });
1054
+ return out;
1055
+ }
1056
+ /**
1057
+ * Print the plan. Used for `--dry-run` and for the confirmation prompt, so what
1058
+ * the owner is shown and what they agree to cannot diverge.
1059
+ *
1060
+ * The key file's CONTENTS are never printed — the whole point of the file is that
1061
+ * the private key stays put, and echoing it into a terminal scrollback undoes
1062
+ * that. The path, mode and the public key are shown instead.
1063
+ */
1064
+ function renderPlan(plan, pubkey) {
1065
+ console.log();
1066
+ console.log(chalk_1.default.bold(" Atbash setup"));
1067
+ console.log(chalk_1.default.dim(` Agent public key: ${pubkey}`));
1068
+ console.log(chalk_1.default.dim(` Detected on this machine: ${plan.found.length ? plan.found.join(", ") : "no supported runtime"}`));
1069
+ console.log();
1070
+ const writes = plan.steps.filter((s) => s.kind === "write");
1071
+ const execs = plan.steps.filter((s) => s.kind === "exec");
1072
+ const manuals = plan.steps.filter((s) => s.kind === "manual");
1073
+ if (!writes.length && !execs.length) {
1074
+ console.log(chalk_1.default.green(" Nothing to change — this machine is already wired.") + "\n");
1075
+ }
1076
+ if (writes.length) {
1077
+ console.log(chalk_1.default.bold(` Files (${writes.length})`));
1078
+ for (const step of writes) {
1079
+ console.log(` ${chalk_1.default.cyan(step.file)}${step.mode ? chalk_1.default.dim(` mode ${step.mode.toString(8)}`) : ""}`);
1080
+ console.log(` ${step.label}`);
1081
+ if (step.secret) {
1082
+ // Deliberately not the contents.
1083
+ console.log(chalk_1.default.dim(` Contents: pubkey= and privkey= lines for the agent above. Not printed — it is a private key.`));
1084
+ }
1085
+ else if (step.before === null) {
1086
+ for (const line of step.after.split("\n").slice(0, 40))
1087
+ console.log(chalk_1.default.dim(` + ${line}`));
1088
+ if (step.after.split("\n").length > 40)
1089
+ console.log(chalk_1.default.dim(" …"));
1090
+ }
1091
+ else {
1092
+ for (const line of condense(lineDiff(step.before, step.after))) {
1093
+ const painted = line.startsWith("+") ? chalk_1.default.green(line) : line.startsWith("-") ? chalk_1.default.red(line) : chalk_1.default.dim(line);
1094
+ console.log(` ${painted}`);
1095
+ }
1096
+ }
1097
+ if (step.before !== null)
1098
+ console.log(chalk_1.default.dim(" The existing file is copied to a .atbash-bak alongside it first."));
1099
+ console.log();
1100
+ }
1101
+ }
1102
+ if (execs.length) {
1103
+ console.log(chalk_1.default.bold(` Commands (${execs.length})`));
1104
+ for (const step of execs)
1105
+ console.log(` ${chalk_1.default.cyan(`${step.command} ${step.args.join(" ")}`)}\n ${step.label}`);
1106
+ console.log();
1107
+ }
1108
+ if (manuals.length) {
1109
+ console.log(chalk_1.default.bold(` For you to do (${manuals.length})`));
1110
+ for (const step of manuals) {
1111
+ console.log(` ${chalk_1.default.yellow("•")} ${chalk_1.default.bold(step.label)}`);
1112
+ for (const line of step.detail.split("\n"))
1113
+ console.log(` ${chalk_1.default.dim(line)}`);
1114
+ if (step.snippet)
1115
+ for (const line of step.snippet.split("\n"))
1116
+ console.log(chalk_1.default.dim(` ${line}`));
1117
+ console.log();
1118
+ }
1119
+ }
1120
+ if (plan.notes.length) {
1121
+ console.log(chalk_1.default.bold(" Notes"));
1122
+ for (const note of plan.notes)
1123
+ console.log(` ${chalk_1.default.dim("•")} ${chalk_1.default.dim(note)}`);
1124
+ console.log();
1125
+ }
1126
+ }
1127
+ // ── Doing it ────────────────────────────────────────────────────────────────
1128
+ /**
1129
+ * Copy a file aside before overwriting it, without ever clobbering an existing
1130
+ * backup — a second run must not overwrite the pristine copy from the first.
1131
+ */
1132
+ function backupFile(file) {
1133
+ if (!fs.existsSync(file))
1134
+ return null;
1135
+ let target = `${file}.atbash-bak`;
1136
+ let n = 1;
1137
+ while (fs.existsSync(target))
1138
+ target = `${file}.atbash-bak.${n++}`;
1139
+ fs.copyFileSync(file, target);
1140
+ return target;
1141
+ }
1142
+ /** Execute the plan. Writes first, then commands, so a failed install still
1143
+ * leaves a correct config and key file behind for a manual retry. */
1144
+ function applyPlan(plan) {
1145
+ const result = { written: [], backups: [], ran: [], failures: [] };
1146
+ for (const step of plan.steps) {
1147
+ if (step.kind !== "write")
1148
+ continue;
1149
+ try {
1150
+ const backup = backupFile(step.file);
1151
+ if (backup)
1152
+ result.backups.push(backup);
1153
+ fs.mkdirSync(path.dirname(step.file), { recursive: true, mode: step.mode === KEY_MODE ? DIR_MODE : undefined });
1154
+ fs.writeFileSync(step.file, step.after, step.mode ? { mode: step.mode } : {});
1155
+ // writeFileSync's mode is ignored for a file that already existed, so
1156
+ // assert it explicitly — a key file at 0644 is the failure this guards.
1157
+ if (step.mode)
1158
+ fs.chmodSync(step.file, step.mode);
1159
+ result.written.push(step.file);
1160
+ }
1161
+ catch (err) {
1162
+ result.failures.push(`${step.file}: ${err instanceof Error ? err.message : String(err)}`);
1163
+ }
1164
+ }
1165
+ for (const step of plan.steps) {
1166
+ if (step.kind !== "exec")
1167
+ continue;
1168
+ const label = `${step.command} ${step.args.join(" ")}`;
1169
+ const run = (0, child_process_1.spawnSync)(step.command, step.args, { stdio: "inherit" });
1170
+ // Three distinct outcomes, and they used to collapse into one misleading
1171
+ // message. `spawnSync` reports a binary it could not launch via `.error` with
1172
+ // `status` left null — so an ENOENT printed "exited on a signal", which reads
1173
+ // like the plugin installer crashed rather than "that command is not here".
1174
+ // The distinction matters because only one of them is the operator's to fix,
1175
+ // and the fix is to run it somewhere the CLI exists.
1176
+ if (run.error) {
1177
+ const missing = run.error.code === "ENOENT";
1178
+ result.failures.push(missing
1179
+ ? `${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.`
1180
+ : `${label} could not start: ${run.error.message}`);
1181
+ }
1182
+ else if (run.status === 0) {
1183
+ result.ran.push(label);
1184
+ }
1185
+ else if (run.signal) {
1186
+ result.failures.push(`${label} was killed by ${run.signal}`);
1187
+ }
1188
+ else {
1189
+ result.failures.push(`${label} exited with code ${run.status}`);
1190
+ }
1191
+ }
1192
+ return result;
1193
+ }
1194
+ // ── Registration check ──────────────────────────────────────────────────────
1195
+ /**
1196
+ * Confirm the agent this key belongs to is actually registered.
1197
+ *
1198
+ * Wiring a runtime to an unregistered agent produces the worst outcome available:
1199
+ * a machine that looks governed, with a plugin that cannot get a verdict. The
1200
+ * check sends only the PUBLIC key (GET /api/ai/exists), never the private one.
1201
+ */
1202
+ async function verifyRegistration(privkey, endpoint) {
1203
+ try {
1204
+ const atbash = new sdk_1.Atbash(privkey, { endpoint });
1205
+ return (await atbash.checkAgentExists()) ? { state: "registered" } : { state: "unregistered" };
1206
+ }
1207
+ catch (err) {
1208
+ return { state: "unknown", reason: err instanceof Error ? err.message : String(err) };
1209
+ }
1210
+ }
1211
+ /** y/N confirmation. Anything but an explicit yes is a no. */
1212
+ async function confirm(question) {
1213
+ const { createInterface } = await Promise.resolve().then(() => __importStar(require("node:readline")));
1214
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1215
+ const answer = await new Promise((r) => rl.question(question, (a) => { rl.close(); r(a); }));
1216
+ return /^y(es)?$/i.test(answer.trim());
1217
+ }
1218
+ // ── The command ─────────────────────────────────────────────────────────────
1219
+ function registerSetupCommand(program) {
1220
+ program
1221
+ .command("setup")
1222
+ .description("Wire this machine's runtime to a registered Atbash agent: place the agent key, install the plugin and merge its config (WRITES to your machine — use --dry-run first)")
1223
+ .option("-k, --key <privkey>", "Agent private key (64 hex). Convenient, but it lands in your shell history — prefer the prompt or --key-file")
1224
+ .option("--key-file <path>", "Read the key from a file (the agent-keys-*.txt from onboarding, or an existing guard-client-key)")
1225
+ .option("--keys-dir <dir>", "Directory holding the key file, e.g. ~/Downloads")
1226
+ .option("--host <url>", "Atbash deployment to check the agent's registration against")
1227
+ .option("--runtime <ids...>", "Only configure these runtimes (currently: openclaw)")
1228
+ .option("--dry-run", "Show exactly which files would change, and the diffs, then exit WITHOUT writing anything")
1229
+ .option("-y, --yes", "Do not ask for confirmation before writing")
1230
+ .option("--no-install", "Do not install any package; write the key file and configs only")
1231
+ .option("--skip-verify", "Do not check the agent's registration (no network calls at all)")
1232
+ .option("--allow-unrecognized-host", "Permit a --host that is not a known Atbash deployment")
1233
+ .option("--home <dir>", "Home directory to configure (for testing)")
1234
+ .action(async (opts) => {
1235
+ const home = opts.home || process.env.HOME || os.homedir();
1236
+ const dryRun = !!opts.dryRun;
1237
+ // A key on argv is in the shell history and in `ps` output. Say so once,
1238
+ // rather than silently accepting the convenient-but-leaky path.
1239
+ if (opts.key) {
1240
+ console.log(chalk_1.default.yellow("\n Note: a key passed with --key is recorded in your shell history.") +
1241
+ chalk_1.default.dim("\n Clear it afterwards, or re-run without --key and paste it at the hidden prompt."));
1242
+ }
1243
+ const keySource = await resolveKeySource({
1244
+ key: opts.key,
1245
+ keyFile: opts.keyFile,
1246
+ keysDir: opts.keysDir,
1247
+ home,
1248
+ allowPrompt: process.stdin.isTTY === true,
1249
+ });
1250
+ if ("error" in keySource) {
1251
+ console.error(chalk_1.default.red(`\n${keySource.error}\n`));
1252
+ process.exit(1);
1253
+ }
1254
+ const privkey = keySource.material.privkey;
1255
+ const pubkey = (0, sdk_1.derivePublicKey)(privkey);
1256
+ // A key file whose stated pubkey does not match the private key is either
1257
+ // corrupt or two different keypairs spliced together. Either way, wiring a
1258
+ // runtime with it produces signatures nobody can attribute.
1259
+ const stated = keySource.material.statedPubkey?.replace(/^0x/i, "").toLowerCase();
1260
+ if (stated && stated !== pubkey.toLowerCase()) {
1261
+ console.error(chalk_1.default.red("\n The key file's `pubkey` does not match the key derived from its `privkey`.") +
1262
+ chalk_1.default.dim(`\n File says: ${stated}\n Derived: ${pubkey}\n Fix the file (or re-download it) before wiring anything.\n`));
1263
+ process.exit(1);
1264
+ }
1265
+ console.log(chalk_1.default.dim(`\n Agent key source: ${keySource.from}`));
1266
+ // ── Registration check. Only the public key crosses the network.
1267
+ if (!opts.skipVerify) {
1268
+ const endpoint = (opts.host || (0, sdk_1.resolve)("judgeEndpoint") || atbash_targets_1.DEFAULT_HOST || sdk_1.DEFAULT_ENDPOINT).replace(/\/$/, "");
1269
+ let hostname = "";
1270
+ try {
1271
+ hostname = new URL(endpoint).hostname.toLowerCase();
1272
+ }
1273
+ catch {
1274
+ console.error(chalk_1.default.red(`\n --host is not a valid URL: ${endpoint}\n`));
1275
+ process.exit(1);
1276
+ }
1277
+ // An unrecognized host could answer "registered" for any key, which is
1278
+ // exactly the confirmation this check exists to provide. Exact hostname
1279
+ // match, never a suffix — "atbash.ai.evil.com" must not pass.
1280
+ const recognizedHost = atbash_targets_1.KNOWN_HOSTS.has(hostname);
1281
+ if (!recognizedHost && !opts.allowUnrecognizedHost) {
1282
+ console.error(chalk_1.default.red(`\n ${hostname} is not a recognized Atbash deployment.`) +
1283
+ 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"));
1284
+ process.exit(1);
1285
+ }
1286
+ const verdict = await verifyRegistration(privkey, endpoint);
1287
+ if (verdict.state === "unregistered") {
1288
+ console.error(chalk_1.default.red("\n That agent is not registered on this deployment.") +
1289
+ 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`));
1290
+ process.exit(1);
1291
+ }
1292
+ if (verdict.state === "unknown") {
1293
+ console.log(chalk_1.default.yellow(`\n Could not confirm the agent's registration (${verdict.reason}).`));
1294
+ console.log(chalk_1.default.dim(" The wiring below is still correct, but nothing has verified that this agent exists."));
1295
+ if (!opts.yes && !dryRun && process.stdin.isTTY && !(await confirm(" Continue anyway? [y/N] "))) {
1296
+ console.log(chalk_1.default.dim("\n Nothing was changed.\n"));
1297
+ return;
1298
+ }
1299
+ }
1300
+ else if (recognizedHost) {
1301
+ console.log(chalk_1.default.green(` Agent is registered on ${hostname}.`));
1302
+ }
1303
+ else {
1304
+ // --allow-unrecognized-host is a real bypass, and its most dangerous
1305
+ // property is that the check still PRINTS a reassuring answer. A host
1306
+ // chosen by an attacker returns "registered" for any key at all, so a
1307
+ // "✓ registered" line here would be the attacker's own claim wearing
1308
+ // Atbash's voice. Never let that line stand unqualified: say the answer
1309
+ // came from an unvouched-for server, so a talked-into-it operator sees
1310
+ // the one thing that would tell them something is wrong.
1311
+ console.log(chalk_1.default.yellow(` ${hostname} answered "registered" — but this is NOT a recognized Atbash deployment.`));
1312
+ console.log(chalk_1.default.yellow(" A registration check against an unrecognized host proves nothing: any server") +
1313
+ chalk_1.default.yellow("\n can answer \"registered\" for any key. Treat this as UNVERIFIED."));
1314
+ console.log(chalk_1.default.dim(` Recognized deployments: ${[...atbash_targets_1.KNOWN_HOSTS].join(", ")}`));
1315
+ }
1316
+ }
1317
+ // ── Plan, show, then (maybe) apply.
1318
+ const plan = buildPlan({
1319
+ home,
1320
+ privkey,
1321
+ pubkey,
1322
+ noInstall: opts.install === false,
1323
+ only: opts.runtime ?? [],
1324
+ });
1325
+ renderPlan(plan, pubkey);
1326
+ const changes = plan.steps.filter((s) => s.kind === "write" || s.kind === "exec");
1327
+ if (dryRun) {
1328
+ console.log(chalk_1.default.green(" Dry run — nothing was written.") +
1329
+ chalk_1.default.dim(" Re-run without --dry-run to apply.\n"));
1330
+ return;
1331
+ }
1332
+ if (!changes.length) {
1333
+ console.log(chalk_1.default.dim(" Nothing to apply.\n"));
1334
+ return;
1335
+ }
1336
+ if (!opts.yes) {
1337
+ if (!process.stdin.isTTY) {
1338
+ console.error(chalk_1.default.red(" Refusing to write without confirmation.") +
1339
+ chalk_1.default.dim(" Re-run with --yes (or --dry-run to preview).\n"));
1340
+ process.exit(1);
1341
+ }
1342
+ if (!(await confirm(` Apply ${changes.length} change${changes.length === 1 ? "" : "s"} to this machine? [y/N] `))) {
1343
+ console.log(chalk_1.default.dim("\n Nothing was changed.\n"));
1344
+ return;
1345
+ }
1346
+ }
1347
+ const result = applyPlan(plan);
1348
+ console.log();
1349
+ for (const file of result.written)
1350
+ console.log(chalk_1.default.green(` ✓ wrote ${file}`));
1351
+ for (const file of result.backups)
1352
+ console.log(chalk_1.default.dim(` backup: ${file}`));
1353
+ for (const cmd of result.ran)
1354
+ console.log(chalk_1.default.green(` ✓ ran ${cmd}`));
1355
+ for (const failure of result.failures)
1356
+ console.log(chalk_1.default.red(` ✗ ${failure}`));
1357
+ if (result.failures.length) {
1358
+ console.log(chalk_1.default.yellow("\n Finished with failures — this machine is NOT fully wired.") +
1359
+ chalk_1.default.dim("\n Everything that did succeed is listed above; the steps that failed can be re-run.\n"));
1360
+ process.exitCode = 1;
1361
+ return;
1362
+ }
1363
+ 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"));
1364
+ console.log(chalk_1.default.dim(" from the agent's page in the dashboard to confirm it reports as enforcing.\n"));
1365
+ });
1366
+ }
1367
+ //# sourceMappingURL=setup.js.map