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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1458 @@
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
+ * Interpret whatever someone typed at the prompt: a raw key, a file, or a
332
+ * directory to search. Shared by the "no key found" prompt and the "use the
333
+ * existing key?" prompt so both accept the same things — an operator who can
334
+ * paste a path in one place should not find it rejected in the other.
335
+ */
336
+ async function keyFromAnswer(answer, home) {
337
+ const direct = parseKeyMaterial(answer);
338
+ if (direct)
339
+ return { material: direct, from: "key entered at the prompt" };
340
+ const asPath = expandHome(answer, home);
341
+ if (!exists(asPath))
342
+ return null;
343
+ let isDir = false;
344
+ try {
345
+ isDir = fs.statSync(asPath).isDirectory();
346
+ }
347
+ catch {
348
+ return null;
349
+ }
350
+ const file = isDir ? keyCandidatesInDir(asPath)[0] : asPath;
351
+ if (!file)
352
+ return null;
353
+ const text = readTextFile(file);
354
+ const material = text === null ? null : parseKeyMaterial(text);
355
+ return material ? { material, from: `${file} (given at the prompt)` } : null;
356
+ }
357
+ /**
358
+ * Find the agent key, trying every way an owner could plausibly have it.
359
+ *
360
+ * Order is "most explicit first": a flag the owner typed beats a file we guessed
361
+ * at. The last resort is the interactive prompt, and if there is no TTY the
362
+ * caller gets a clear error listing the flags rather than a hang.
363
+ */
364
+ async function resolveKeySource(opts) {
365
+ const { home } = opts;
366
+ const fromFile = (file, label) => {
367
+ const text = readTextFile(file);
368
+ if (text === null)
369
+ return { error: `Could not read ${file}` };
370
+ const material = parseKeyMaterial(text);
371
+ if (!material)
372
+ return { error: `${file} does not contain a valid 64-hex agent private key.` };
373
+ return { material, from: `${label} (${file})` };
374
+ };
375
+ // 1. Inline — what a one-line command copied from the onboarding modal uses.
376
+ if (opts.key) {
377
+ const material = parseKeyMaterial(opts.key);
378
+ if (!material)
379
+ return { error: "--key is not a valid agent private key (expected 64 hex characters)." };
380
+ return { material, from: "--key on the command line" };
381
+ }
382
+ // 2. An explicit file.
383
+ if (opts.keyFile)
384
+ return fromFile(expandHome(opts.keyFile, home), "--key-file");
385
+ // 3. A directory to look in — "the keys are in my Downloads folder".
386
+ if (opts.keysDir) {
387
+ const dir = expandHome(opts.keysDir, home);
388
+ const candidates = keyCandidatesInDir(dir);
389
+ if (!candidates.length) {
390
+ return {
391
+ error: [
392
+ `No agent key found in ${dir}.`,
393
+ "Looked for guard-client-key / agent-keys-*.txt by name, then read the small",
394
+ "files there to see if any parsed as an agent key. Neither found one.",
395
+ "Point at the file directly with --key-file, or paste the key with no flags",
396
+ "at all and setup will prompt for it.",
397
+ ].join("\n"),
398
+ };
399
+ }
400
+ return fromFile(candidates[0], "--keys-dir");
401
+ }
402
+ // 4. The environment variable the rest of the CLI already honours.
403
+ const fromEnv = process.env.ATBASH_AGENT_KEY;
404
+ if (fromEnv) {
405
+ const material = parseKeyMaterial(fromEnv);
406
+ if (material)
407
+ return { material, from: "ATBASH_AGENT_KEY" };
408
+ }
409
+ // 5. Already in the canonical place — a re-run, or a machine set up before.
410
+ //
411
+ // This used to be taken SILENTLY, and that was a trap. A machine that has ever
412
+ // governed one agent already has a key here, so onboarding a SECOND agent
413
+ // picked up the first one's key and then failed registration against a pubkey
414
+ // the operator never chose:
415
+ //
416
+ // Agent key source: existing key file (~/.config/atbash/guard-client-key)
417
+ // That agent is not registered on this deployment.
418
+ //
419
+ // which reads as "onboarding is broken" rather than "I used a different key
420
+ // than you meant". So when there is someone to ask, ask — and make the existing
421
+ // key the easy answer for the common case (a genuine re-run) without making it
422
+ // the only answer.
423
+ const keyFile = path.join(home, ...KEY_FILE_REL);
424
+ if (exists(keyFile)) {
425
+ const found = fromFile(keyFile, "existing key file");
426
+ if (!("error" in found)) {
427
+ if (!opts.allowPrompt)
428
+ return found; // non-interactive: same as before
429
+ const existingPub = (0, sdk_1.derivePublicKey)(found.material.privkey);
430
+ process.stdout.write(`\n This machine already has an agent key at ${keyFile}\n` +
431
+ ` Public key: ${existingPub}\n`);
432
+ const useExisting = await confirm(" Use that key? [Y/n] ", true);
433
+ if (useExisting)
434
+ return found;
435
+ const answer = await promptForKeyOrPath();
436
+ if (!answer)
437
+ return { error: "No key provided." };
438
+ const supplied = await keyFromAnswer(answer, home);
439
+ if (supplied)
440
+ return supplied;
441
+ return { error: "That is neither a 64-hex private key nor a path that exists." };
442
+ }
443
+ }
444
+ // 6. The CLI's own config, populated by `atbash set agent-key`.
445
+ const fromConfig = (0, sdk_1.resolve)("agentKey");
446
+ if (fromConfig) {
447
+ const material = parseKeyMaterial(fromConfig);
448
+ if (material)
449
+ return { material, from: "atbash config (agentKey)" };
450
+ }
451
+ // 7. Ask.
452
+ if (opts.allowPrompt) {
453
+ const answer = await promptForKeyOrPath();
454
+ if (!answer)
455
+ return { error: "No key provided." };
456
+ const supplied = await keyFromAnswer(answer, home);
457
+ if (supplied)
458
+ return supplied;
459
+ return { error: "That is neither a 64-hex private key nor a path that exists." };
460
+ }
461
+ return {
462
+ error: [
463
+ "No agent key found.",
464
+ "Provide one with --key <64-hex>, --key-file <path>, or --keys-dir <dir>,",
465
+ `or place it at ${keyFile} first.`,
466
+ ].join("\n"),
467
+ };
468
+ }
469
+ /** The key file, in the `key=value` form the plugin and the SDK both parse. */
470
+ function keyFileContents(privkey, pubkey) {
471
+ return [
472
+ "# Atbash agent key",
473
+ "# Keep this file private (chmod 600). Read locally by every Atbash integration.",
474
+ `pubkey=${pubkey}`,
475
+ `privkey=${privkey}`,
476
+ "",
477
+ ].join("\n");
478
+ }
479
+ /**
480
+ * True when a JSON file uses JSONC features (comments, trailing commas).
481
+ *
482
+ * We must not auto-merge into one: writing it back with JSON.stringify would
483
+ * silently delete the owner's comments. Detected by the disagreement between the
484
+ * strict and tolerant parsers — strict fails, tolerant succeeds.
485
+ */
486
+ function isJsonc(text) {
487
+ try {
488
+ JSON.parse(text);
489
+ return false;
490
+ }
491
+ catch { /* fall through */ }
492
+ const errors = [];
493
+ const value = jsonc.parse(text, errors, { allowTrailingComma: true, disallowComments: false });
494
+ return errors.length === 0 && value !== undefined;
495
+ }
496
+ /**
497
+ * Merge the Atbash plugin block into an OpenClaw config object, in place.
498
+ *
499
+ * A MERGE, not a replacement — that distinction is the whole reason this command
500
+ * exists. Other plugins already in `allow`, `load.paths` and `entries` are
501
+ * preserved, and an entry from the legacy `@atbash/atbash-plugin` install is
502
+ * updated where it stands rather than being shadowed by a duplicate: the
503
+ * dashboard scan recognizes both keys, so two entries would mean two hooks.
504
+ *
505
+ * `load.paths` gets the real absolute extension path. The published docs show a
506
+ * `<your-username>` placeholder that people paste verbatim, producing a path that
507
+ * does not exist and a plugin that never loads.
508
+ */
509
+ function mergeOpenclawConfig(config, home) {
510
+ const out = { ...config };
511
+ const plugins = { ...(isRecord(out.plugins) ? out.plugins : {}) };
512
+ // Which key is this install governed under? Keep an existing legacy entry
513
+ // where it is instead of adding a second one.
514
+ const entries = { ...(isRecord(plugins.entries) ? plugins.entries : {}) };
515
+ const entryKey = OPENCLAW_LEGACY_ENTRY in entries && !(OPENCLAW_ENTRY in entries)
516
+ ? OPENCLAW_LEGACY_ENTRY
517
+ : OPENCLAW_ENTRY;
518
+ const allow = Array.isArray(plugins.allow) ? [...plugins.allow] : [];
519
+ if (!allow.includes(entryKey))
520
+ allow.push(entryKey);
521
+ plugins.allow = allow;
522
+ const load = { ...(isRecord(plugins.load) ? plugins.load : {}) };
523
+ const extensionPath = path.join(home, ...OPENCLAW_EXTENSIONS_REL, OPENCLAW_ENTRY);
524
+ const paths = Array.isArray(load.paths) ? [...load.paths] : [];
525
+ if (!paths.includes(extensionPath))
526
+ paths.push(extensionPath);
527
+ load.paths = paths;
528
+ plugins.load = load;
529
+ // Preserve any unrelated fields the owner set on the entry (debug, custom
530
+ // hooks); only the fields Atbash owns are asserted.
531
+ const existing = isRecord(entries[entryKey]) ? entries[entryKey] : {};
532
+ const existingConfig = isRecord(existing.config) ? existing.config : {};
533
+ const existingHooks = isRecord(existing.hooks) ? existing.hooks : {};
534
+ entries[entryKey] = {
535
+ ...existing,
536
+ enabled: true,
537
+ config: {
538
+ ...existingConfig,
539
+ enabled: true,
540
+ enforceDecision: true,
541
+ // The path, not the key. This is the whole point of the canonical location.
542
+ chromiaSecretPath: `~/${KEY_FILE_REL.join("/")}`,
543
+ },
544
+ hooks: {
545
+ ...existingHooks,
546
+ allowConversationAccess: true,
547
+ allowPromptInjection: true,
548
+ },
549
+ };
550
+ plugins.entries = entries;
551
+ out.plugins = plugins;
552
+ return out;
553
+ }
554
+ function isRecord(v) {
555
+ return !!v && typeof v === "object" && !Array.isArray(v);
556
+ }
557
+ /**
558
+ * Detect the indentation a JSON file already uses, so a merge does not reformat
559
+ * the parts it did not touch.
560
+ *
561
+ * Without this, `JSON.stringify(obj, null, 2)` re-indents a tab-indented or
562
+ * 4-space config from top to bottom. The RESULT is still correct, but the diff
563
+ * shown for approval becomes every line in the file, which buries the two lines
564
+ * that actually changed — and the operator's own formatting choice is collateral
565
+ * damage in a file we were asked to make one addition to.
566
+ *
567
+ * Falls back to two spaces, which is what the published docs show.
568
+ */
569
+ function detectIndent(text) {
570
+ if (!text)
571
+ return 2;
572
+ // First line that is indented under an opening brace/bracket tells us the unit.
573
+ const match = text.match(/\n([ \t]+)\S/);
574
+ if (!match)
575
+ return 2;
576
+ const indent = match[1];
577
+ return indent.startsWith("\t") ? "\t" : indent.length;
578
+ }
579
+ /**
580
+ * Serialize a merged config the way the file was already written: same
581
+ * indentation, and a trailing newline only if the original had one.
582
+ */
583
+ function serializeLike(original, value) {
584
+ const body = JSON.stringify(value, null, detectIndent(original));
585
+ // A file that ended without a newline keeps ending without one. Trivial, but it
586
+ // is one more line of unexplained diff for someone reviewing the change.
587
+ const trailing = original === null || original.endsWith("\n") ? "\n" : "";
588
+ return body + trailing;
589
+ }
590
+ /**
591
+ * The MCP server entry setup writes into a client's config.
592
+ *
593
+ * Note what is NOT here: an `env` block. The published `@atbash/mcp` wiring
594
+ * carries the agent's private key in one, because that package reads only
595
+ * ATBASH_AGENT_PRIVKEY. Going through `atbash mcp` instead means the launcher
596
+ * reads the 0600 key file and passes the key to the server in the child process
597
+ * environment, so this entry holds no credential and the client's config file is
598
+ * no more sensitive after setup runs than it was before.
599
+ *
600
+ * Deliberately NOT pinned to an exact CLI version: unlike the one-shot connector
601
+ * command, this entry persists in the operator's config and is re-executed every
602
+ * time the client starts. Pinning here would freeze their MCP server at whatever
603
+ * version happened to be current on the day they ran setup.
604
+ */
605
+ const MCP_SERVER_ENTRY = { command: "npx", args: ["--yes", "@atbash/cli", "mcp"] };
606
+ const MCP_SERVER_NAME = "atbash";
607
+ /**
608
+ * MCP client configs present under this home directory.
609
+ *
610
+ * Paths come from the shared MCP_CONFIGS so the writer and the scanner cannot
611
+ * drift: a client the scan reports but setup cannot find would look like a bug in
612
+ * whichever of the two the operator happened to trust.
613
+ */
614
+ function detectMcpClients(home) {
615
+ const out = [];
616
+ const seen = new Set();
617
+ for (const { label, segs } of atbash_targets_1.MCP_CONFIGS) {
618
+ if (seen.has(label))
619
+ continue;
620
+ const file = path.join(home, ...segs);
621
+ if (!exists(file))
622
+ continue;
623
+ seen.add(label);
624
+ // Read which key this file already uses rather than assuming. VS Code's
625
+ // mcp.json uses `servers`; writing `mcpServers` into it would be ignored.
626
+ const existing = readJsonLoose(file);
627
+ const serversKey = existing && isRecord(existing.servers) && !isRecord(existing.mcpServers) ? "servers" : "mcpServers";
628
+ out.push({ label, file, format: "json", serversKey });
629
+ }
630
+ // Claude Code and Codex are special-cased in the scanner too — same paths.
631
+ const claudeCode = path.join(home, ".claude.json");
632
+ if (exists(claudeCode))
633
+ out.push({ label: "Claude Code", file: claudeCode, format: "json", serversKey: "mcpServers" });
634
+ const codex = path.join(home, ".codex", "config.toml");
635
+ if (exists(codex))
636
+ out.push({ label: "Codex", file: codex, format: "toml", serversKey: "mcpServers" });
637
+ return out;
638
+ }
639
+ /** Tolerant read used only to sniff an existing file's shape. */
640
+ function readJsonLoose(file) {
641
+ const text = readTextFile(file);
642
+ if (text === null)
643
+ return null;
644
+ const value = jsonc.parse(text, [], { allowTrailingComma: true, disallowComments: false });
645
+ return isRecord(value) ? value : null;
646
+ }
647
+ /**
648
+ * Add the Atbash server to a client config's server map, in place.
649
+ *
650
+ * A merge, like the OpenClaw one: every server the operator already configured
651
+ * stays exactly as it is. An existing `atbash` entry is REPLACED rather than
652
+ * merged field-by-field — a stale `env` block carrying a private key from the old
653
+ * hand-written wiring is precisely what we want gone, and preserving it would
654
+ * defeat the point of routing through the launcher.
655
+ */
656
+ /** The Hermes plugin, and the exact version the wiring is written against. */
657
+ const HERMES_PKG = "atbash-hermes-plugin";
658
+ const HERMES_VERSION = "0.4.5";
659
+ /**
660
+ * Find the Python interpreter that actually runs Hermes.
661
+ *
662
+ * This is the difference between installing the plugin and only appearing to.
663
+ * `pip install atbash-hermes-plugin` puts the package wherever the *shell's*
664
+ * `pip` points — commonly a system or conda Python — while Hermes typically runs
665
+ * from its own virtualenv. The install succeeds, prints nothing alarming, and the
666
+ * plugin is invisible to Hermes forever. Nobody can debug that from the output.
667
+ *
668
+ * The launcher knows the answer. A pip-installed console script begins with a
669
+ * shebang naming the interpreter that created it:
670
+ *
671
+ * $ head -1 $(command -v hermes)
672
+ * #!/Users/me/.hermes/hermes-agent/venv/bin/python3
673
+ *
674
+ * So resolve `hermes`, read its first line, and use that interpreter directly via
675
+ * `-m pip`. Falls back to the conventional venv location under ~/.hermes, then to
676
+ * null — and a null becomes a printed command rather than a guess, because a
677
+ * wrong guess here is the silent failure this whole function exists to avoid.
678
+ */
679
+ function findHermesPython(home) {
680
+ const viable = (candidate) => {
681
+ try {
682
+ return fs.statSync(candidate).isFile();
683
+ }
684
+ catch {
685
+ return false;
686
+ }
687
+ };
688
+ // 1. The launcher's own shebang — authoritative, but only for a real run.
689
+ //
690
+ // `--home <dir>` exists so a dry run can be hermetic (the release checklist
691
+ // depends on it). A PATH lookup ignores it entirely: under `--home /tmp/fake`
692
+ // this would find the operator's ACTUAL hermes and plan an install into their
693
+ // real virtualenv. So the shebang route is skipped whenever `home` is not the
694
+ // machine's own home — the caller then falls through to the venv path under the
695
+ // given home, which is correctly scoped.
696
+ const realHome = process.env.HOME || os.homedir();
697
+ const scoped = path.resolve(home) !== path.resolve(realHome);
698
+ const which = scoped
699
+ ? { status: 1, stdout: "" }
700
+ : (0, child_process_1.spawnSync)(process.platform === "win32" ? "where" : "which", ["hermes"], { encoding: "utf8" });
701
+ const launcher = which.status === 0 ? which.stdout.split(/\r?\n/)[0]?.trim() : "";
702
+ if (launcher && viable(launcher)) {
703
+ const firstLine = (readTextFile(launcher) ?? "").split(/\r?\n/)[0] ?? "";
704
+ const shebang = firstLine.startsWith("#!") ? firstLine.slice(2).trim() : "";
705
+ // `#!/usr/bin/env python3` names no path; anything else should be absolute.
706
+ const interpreter = shebang.split(/\s+/).filter((part) => !part.endsWith("/env"))[0] ?? "";
707
+ if (/python[0-9.]*$/.test(interpreter) && viable(interpreter)) {
708
+ return { python: interpreter, how: `shebang of ${launcher}` };
709
+ }
710
+ }
711
+ // 2. The conventional venv Hermes ships with.
712
+ for (const name of ["python3", "python"]) {
713
+ const candidate = path.join(home, ".hermes", "hermes-agent", "venv", "bin", name);
714
+ if (viable(candidate))
715
+ return { python: candidate, how: "Hermes virtualenv under ~/.hermes" };
716
+ }
717
+ return null;
718
+ }
719
+ /**
720
+ * The env vars the Hermes plugin documents, merged into an existing `.env`.
721
+ *
722
+ * A `.env` is line-oriented and hand-maintained, so this is a line merge rather
723
+ * than a parse-and-reserialize: keys Atbash owns are replaced in place (keeping
724
+ * their position), keys it does not own are never touched, and anything else in
725
+ * the file — comments, blank lines, unrelated settings, ordering — survives
726
+ * exactly as written. Reformatting someone's .env to add four lines would be a
727
+ * poor trade.
728
+ *
729
+ * Values are from the published plugin README (PyPI atbash-hermes-plugin 0.4.5).
730
+ * `ATBASH_ORG_NAME` is deliberately NOT written: its value is the operator's org,
731
+ * which this command has no reliable way to know, and a wrong org sends the SDK
732
+ * at the wrong chain. It is called out in the manual step instead.
733
+ */
734
+ function mergeHermesEnv(existing) {
735
+ const desired = {
736
+ ATBASH_KEY_PATH: "$HOME/.config/atbash/guard-client-key",
737
+ ATBASH_ENFORCE_DECISION: "true",
738
+ };
739
+ const lines = existing === null ? [] : existing.split("\n");
740
+ const seen = new Set();
741
+ const out = lines.map((line) => {
742
+ const match = line.match(/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=/);
743
+ const key = match?.[1];
744
+ if (!key || !(key in desired) || seen.has(key))
745
+ return line;
746
+ seen.add(key);
747
+ // Already correct — keep the operator's own formatting rather than rewriting.
748
+ if (line.trim() === `${key}=${desired[key]}`)
749
+ return line;
750
+ return `${key}=${desired[key]}`;
751
+ });
752
+ const missing = Object.entries(desired).filter(([key]) => !seen.has(key));
753
+ if (missing.length) {
754
+ // Separate the block we add from whatever came before it.
755
+ if (out.length && out[out.length - 1].trim() !== "")
756
+ out.push("");
757
+ // ASCII-only comment on purpose: .env files are read by many different
758
+ // parsers and a stray multi-byte dash is a free way to trip a strict one.
759
+ if (existing !== null)
760
+ out.push("# Added by `atbash setup` - Atbash Hermes plugin");
761
+ for (const [key, value] of missing)
762
+ out.push(`${key}=${value}`);
763
+ }
764
+ let text = out.join("\n");
765
+ if (!text.endsWith("\n"))
766
+ text += "\n";
767
+ return text;
768
+ }
769
+ /**
770
+ * Does this config's existing Atbash entry carry a key in its `env` block?
771
+ *
772
+ * True means the operator hand-wired it from the published docs and their private
773
+ * key is sitting in that file today. Setup takes it out, but the backup it writes
774
+ * first still has it — so this exists to make that sayable rather than silently
775
+ * relocating the leak.
776
+ */
777
+ function hadInlineKey(config, serversKey = "mcpServers") {
778
+ const servers = isRecord(config[serversKey]) ? config[serversKey] : undefined;
779
+ const entry = servers && isRecord(servers[MCP_SERVER_NAME]) ? servers[MCP_SERVER_NAME] : undefined;
780
+ const env = entry && isRecord(entry.env) ? entry.env : undefined;
781
+ if (!env)
782
+ return false;
783
+ // Any 64-hex value, under any key name — not just the documented one, since a
784
+ // hand-edited config may well have renamed it.
785
+ return Object.values(env).some((v) => typeof v === "string" && /^(0x)?[0-9a-fA-F]{64}$/.test(v.trim()));
786
+ }
787
+ function mergeMcpServer(config, serversKey = "mcpServers") {
788
+ const out = { ...config };
789
+ const servers = { ...(isRecord(out[serversKey]) ? out[serversKey] : {}) };
790
+ servers[MCP_SERVER_NAME] = { ...MCP_SERVER_ENTRY, args: [...MCP_SERVER_ENTRY.args] };
791
+ out[serversKey] = servers;
792
+ return out;
793
+ }
794
+ /** Is `openclaw` runnable on this machine? Decides install-for-you vs print-it. */
795
+ function hasExecutable(command) {
796
+ const probe = (0, child_process_1.spawnSync)(process.platform === "win32" ? "where" : "which", [command], { stdio: "ignore" });
797
+ return probe.status === 0;
798
+ }
799
+ /**
800
+ * Work out everything that needs doing on this machine, without doing any of it.
801
+ *
802
+ * Detection drives the plan rather than a flag the owner picks, for the same
803
+ * reason the scan does: what is actually installed here is knowable, and asking
804
+ * someone to identify their own runtime from a list invites a wrong answer that
805
+ * writes a config for a plugin they do not have.
806
+ */
807
+ function buildPlan(args) {
808
+ const { home, privkey, pubkey, noInstall, only } = args;
809
+ const steps = [];
810
+ const notes = [];
811
+ const found = [];
812
+ const wanted = (id) => only.length === 0 || only.includes(id);
813
+ // ── 1. The key file. Always, for every runtime: it is the one artifact every
814
+ // integration reads, and the thing the owner would otherwise move by hand.
815
+ const keyFile = path.join(home, ...KEY_FILE_REL);
816
+ const desiredKeyFile = keyFileContents(privkey, pubkey);
817
+ const currentKeyFile = readTextFile(keyFile);
818
+ const alreadyThisKey = currentKeyFile !== null && parseKeyMaterial(currentKeyFile)?.privkey === privkey;
819
+ if (!alreadyThisKey) {
820
+ if (currentKeyFile !== null) {
821
+ // The outgoing key belongs to a real agent that this machine may still be
822
+ // governing. A `.atbash-bak` preserves the bytes but not the identity — six
823
+ // months later nobody knows which agent `guard-client-key.atbash-bak` was.
824
+ // So archive it under its own public key: recoverable, self-identifying,
825
+ // and a path a runtime config can point at directly if this box needs to
826
+ // run two agents (both OpenClaw's `chromiaSecretPath` and Hermes'
827
+ // `ATBASH_KEY_PATH` take an explicit path).
828
+ const outgoing = parseKeyMaterial(currentKeyFile);
829
+ const outgoingPub = outgoing ? (0, sdk_1.derivePublicKey)(outgoing.privkey) : null;
830
+ if (outgoingPub) {
831
+ const archive = path.join(home, ".config", "atbash", "keys", `${outgoingPub}.key`);
832
+ if (!exists(archive)) {
833
+ steps.push({
834
+ kind: "write",
835
+ label: `Archive the agent key already on this machine (${outgoingPub.slice(0, 12)}…)`,
836
+ file: archive,
837
+ mode: KEY_MODE,
838
+ before: null,
839
+ after: currentKeyFile,
840
+ secret: true,
841
+ });
842
+ }
843
+ 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.`);
844
+ }
845
+ else {
846
+ notes.push(`${keyFile} holds something this command could not parse as an agent key. It will be backed up before being replaced.`);
847
+ }
848
+ }
849
+ steps.push({
850
+ kind: "write",
851
+ label: currentKeyFile === null ? "Save the agent key where every integration looks for it" : "Replace the agent key file",
852
+ file: keyFile,
853
+ mode: KEY_MODE,
854
+ before: currentKeyFile,
855
+ after: desiredKeyFile,
856
+ secret: true,
857
+ });
858
+ }
859
+ else {
860
+ notes.push(`${keyFile} already holds this agent's key — left untouched.`);
861
+ }
862
+ // ── 2. OpenClaw: the one runtime governed purely by a config file, so the one
863
+ // this command can finish end to end.
864
+ const openclawConfigFile = path.join(home, ...OPENCLAW_CONFIG_REL);
865
+ if (exists(openclawConfigFile) || exists(home, ".openclaw")) {
866
+ found.push("OpenClaw");
867
+ if (wanted("openclaw")) {
868
+ if (!noInstall) {
869
+ if (hasExecutable("openclaw")) {
870
+ steps.push({ kind: "exec", label: `Install ${OPENCLAW_PKG}`, command: "openclaw", args: ["plugins", "install", OPENCLAW_PKG] });
871
+ }
872
+ else {
873
+ steps.push({
874
+ kind: "manual",
875
+ label: "Install the OpenClaw plugin",
876
+ 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:",
877
+ snippet: `openclaw plugins install ${OPENCLAW_PKG}`,
878
+ });
879
+ }
880
+ }
881
+ const raw = readTextFile(openclawConfigFile);
882
+ if (raw !== null && isJsonc(raw)) {
883
+ // Rewriting this would delete the owner's comments. Print instead.
884
+ steps.push({
885
+ kind: "manual",
886
+ label: `Enable the plugin in ${openclawConfigFile}`,
887
+ 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`:",
888
+ snippet: JSON.stringify(mergeOpenclawConfig((jsonc.parse(raw, [], { allowTrailingComma: true, disallowComments: false }) ?? {}), home), null, 2),
889
+ });
890
+ }
891
+ else {
892
+ let current = {};
893
+ if (raw !== null) {
894
+ try {
895
+ const parsed = JSON.parse(raw);
896
+ if (isRecord(parsed))
897
+ current = parsed;
898
+ }
899
+ catch {
900
+ 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.`);
901
+ }
902
+ }
903
+ const after = serializeLike(raw, mergeOpenclawConfig(current, home));
904
+ if (raw !== after) {
905
+ steps.push({
906
+ kind: "write",
907
+ label: raw === null
908
+ ? "Create ~/.openclaw/openclaw.json with the plugin enabled"
909
+ : "Enable the plugin in ~/.openclaw/openclaw.json (a merge — existing plugins are kept)",
910
+ file: openclawConfigFile,
911
+ before: raw,
912
+ after,
913
+ });
914
+ }
915
+ else {
916
+ notes.push(`${openclawConfigFile} already has the plugin enabled — left untouched.`);
917
+ }
918
+ }
919
+ notes.push("Restart the OpenClaw gateway. The hook is registered at startup, so the plugin does nothing until it restarts.");
920
+ }
921
+ }
922
+ // ── 3. Hermes: not a runtime that merely lacks a plugin. It runs the SAME
923
+ // agent, reads the same skills and the same key — but the Atbash hook lives in
924
+ // the OpenClaw gateway, so anything driven through the Hermes API is never
925
+ // judged. Setup places the key file and says so; it does not pretend to wire it.
926
+ if (exists(home, ...HERMES_AGENT_REL)) {
927
+ found.push("Hermes");
928
+ if (wanted("hermes")) {
929
+ const envFile = path.join(home, ".hermes", ".env");
930
+ const raw = readTextFile(envFile);
931
+ const merged = mergeHermesEnv(raw);
932
+ if (merged !== raw) {
933
+ steps.push({
934
+ kind: "write",
935
+ label: raw === null
936
+ ? "Create ~/.hermes/.env pointing the Hermes plugin at the agent key"
937
+ : "Point the Hermes plugin at the agent key in ~/.hermes/.env (a merge — your other settings are kept)",
938
+ file: envFile,
939
+ before: raw,
940
+ after: merged,
941
+ });
942
+ }
943
+ else {
944
+ notes.push(`${envFile} already points the Hermes plugin at this key — left untouched.`);
945
+ }
946
+ // The Python package must land in the interpreter that RUNS Hermes, not
947
+ // whichever pip the shell happens to resolve. When we can identify that
948
+ // interpreter we install into it directly; when we cannot, we hand the
949
+ // command over rather than guess, because guessing wrong installs
950
+ // successfully and governs nothing.
951
+ if (!noInstall) {
952
+ const hermesPython = findHermesPython(home);
953
+ if (hermesPython) {
954
+ steps.push({
955
+ kind: "exec",
956
+ label: `Install ${HERMES_PKG} into the interpreter that runs Hermes (found via ${hermesPython.how})`,
957
+ command: hermesPython.python,
958
+ args: ["-m", "pip", "install", `${HERMES_PKG}==${HERMES_VERSION}`],
959
+ });
960
+ }
961
+ else {
962
+ steps.push({
963
+ kind: "manual",
964
+ label: "Install the Hermes plugin",
965
+ detail: [
966
+ "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.",
967
+ "",
968
+ "Run this with the interpreter Hermes uses (if it runs in a virtualenv, that venv's python):",
969
+ ].join("\n"),
970
+ snippet: `/path/to/hermes/venv/bin/python -m pip install ${HERMES_PKG}==${HERMES_VERSION}`,
971
+ });
972
+ }
973
+ }
974
+ notes.push("Restart Hermes — it reads .env and discovers plugins at startup. Then confirm with `hermes plugins list | grep atbash`.");
975
+ notes.push("ATBASH_ENFORCE_DECISION=true is fail-closed: if Atbash cannot be reached, the Hermes tool call is blocked rather than allowed.");
976
+ 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.");
977
+ }
978
+ }
979
+ // ── 4. MCP clients.
980
+ //
981
+ // This used to be a manual step, and the reason was specific: `@atbash/mcp`
982
+ // reads its identity from ATBASH_AGENT_PRIVKEY with no key-file fallback, so
983
+ // the documented wiring puts a raw private key inside the client's own config —
984
+ // `claude_desktop_config.json` and friends, files that get synced between
985
+ // machines and pasted into help requests. Automating that would have meant the
986
+ // automation's whole job was planting a secret somewhere worse.
987
+ //
988
+ // `atbash mcp` removes the reason. The client spawns the launcher, which reads
989
+ // the key from the 0600 file and hands it to the server through the child
990
+ // environment only. The config entry carries NO credential, so it is safe to
991
+ // write — and a config with no secret in it is strictly better than the one the
992
+ // operator would have hand-written from the docs.
993
+ if (wanted("mcp")) {
994
+ for (const client of detectMcpClients(home)) {
995
+ found.push(client.label);
996
+ if (client.format !== "json") {
997
+ // TOML (Codex) — @iarna/toml can round-trip values but not comments, and
998
+ // a config.toml is usually hand-maintained. Print it instead.
999
+ steps.push({
1000
+ kind: "manual",
1001
+ label: `Add Atbash to ${client.label}`,
1002
+ detail: `${client.file} is TOML, and rewriting it would drop any comments in it. Add this table by hand:`,
1003
+ snippet: ["[mcp_servers.atbash]", 'command = "npx"', 'args = ["--yes", "@atbash/cli", "mcp"]'].join("\n"),
1004
+ });
1005
+ continue;
1006
+ }
1007
+ const raw = readTextFile(client.file);
1008
+ if (raw !== null && isJsonc(raw)) {
1009
+ steps.push({
1010
+ kind: "manual",
1011
+ label: `Add Atbash to ${client.label}`,
1012
+ 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:`,
1013
+ snippet: JSON.stringify({ mcpServers: { atbash: MCP_SERVER_ENTRY } }, null, 2),
1014
+ });
1015
+ continue;
1016
+ }
1017
+ let current = {};
1018
+ if (raw !== null) {
1019
+ try {
1020
+ const parsed = JSON.parse(raw);
1021
+ if (isRecord(parsed))
1022
+ current = parsed;
1023
+ }
1024
+ catch {
1025
+ notes.push(`${client.file} is not valid JSON, so it was left alone. Fix the file and re-run to wire ${client.label}.`);
1026
+ continue;
1027
+ }
1028
+ }
1029
+ const after = serializeLike(raw, mergeMcpServer(current, client.serversKey));
1030
+ if (raw !== after) {
1031
+ // A hand-wired entry from the old documented shape carries the private key
1032
+ // in an `env` block. Replacing it REMOVES that secret from the live config
1033
+ // — good — but the backup we are about to take still contains it, and an
1034
+ // operator who does not know that has simply moved the leak to a new file.
1035
+ if (hadInlineKey(current, client.serversKey)) {
1036
+ 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.`);
1037
+ }
1038
+ steps.push({
1039
+ kind: "write",
1040
+ 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" : ""})`,
1041
+ file: client.file,
1042
+ before: raw,
1043
+ after,
1044
+ });
1045
+ }
1046
+ else {
1047
+ notes.push(`${client.label} already has the Atbash MCP server — left untouched.`);
1048
+ }
1049
+ }
1050
+ if (found.some((f) => f !== "OpenClaw" && f !== "Hermes")) {
1051
+ notes.push("Restart any MCP client that was changed — clients read their server list at startup.");
1052
+ // A client whose first launch of the server takes ~12s can report a startup
1053
+ // timeout that looks like a broken config. Say so, so the first thing an
1054
+ // operator does is retry rather than undo the wiring.
1055
+ 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.");
1056
+ }
1057
+ }
1058
+ if (!found.length) {
1059
+ 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.");
1060
+ }
1061
+ return { steps, notes, found };
1062
+ }
1063
+ // ── Showing the plan ────────────────────────────────────────────────────────
1064
+ /**
1065
+ * A minimal line diff, so the preview shows what CHANGES rather than dumping a
1066
+ * whole config and leaving the owner to spot the difference. Standard LCS; these
1067
+ * files are small enough that the quadratic table is irrelevant.
1068
+ */
1069
+ function lineDiff(before, after) {
1070
+ const a = before.split("\n");
1071
+ const b = after.split("\n");
1072
+ const table = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
1073
+ for (let i = a.length - 1; i >= 0; i--) {
1074
+ for (let j = b.length - 1; j >= 0; j--) {
1075
+ table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
1076
+ }
1077
+ }
1078
+ const out = [];
1079
+ let i = 0;
1080
+ let j = 0;
1081
+ while (i < a.length && j < b.length) {
1082
+ if (a[i] === b[j]) {
1083
+ out.push(` ${a[i]}`);
1084
+ i++;
1085
+ j++;
1086
+ }
1087
+ else if (table[i + 1][j] >= table[i][j + 1]) {
1088
+ out.push(`- ${a[i]}`);
1089
+ i++;
1090
+ }
1091
+ else {
1092
+ out.push(`+ ${b[j]}`);
1093
+ j++;
1094
+ }
1095
+ }
1096
+ for (; i < a.length; i++)
1097
+ out.push(`- ${a[i]}`);
1098
+ for (; j < b.length; j++)
1099
+ out.push(`+ ${b[j]}`);
1100
+ return out;
1101
+ }
1102
+ /** Drop unchanged runs down to a little context, so a long config stays readable. */
1103
+ function condense(diff, context = 2) {
1104
+ const keep = new Set();
1105
+ diff.forEach((line, index) => {
1106
+ if (line.startsWith("+") || line.startsWith("-")) {
1107
+ for (let k = index - context; k <= index + context; k++)
1108
+ if (k >= 0 && k < diff.length)
1109
+ keep.add(k);
1110
+ }
1111
+ });
1112
+ const out = [];
1113
+ let skipping = false;
1114
+ diff.forEach((line, index) => {
1115
+ if (keep.has(index)) {
1116
+ out.push(line);
1117
+ skipping = false;
1118
+ }
1119
+ else if (!skipping) {
1120
+ out.push(chalk_1.default.dim(" …"));
1121
+ skipping = true;
1122
+ }
1123
+ });
1124
+ return out;
1125
+ }
1126
+ /**
1127
+ * Print the plan. Used for `--dry-run` and for the confirmation prompt, so what
1128
+ * the owner is shown and what they agree to cannot diverge.
1129
+ *
1130
+ * The key file's CONTENTS are never printed — the whole point of the file is that
1131
+ * the private key stays put, and echoing it into a terminal scrollback undoes
1132
+ * that. The path, mode and the public key are shown instead.
1133
+ */
1134
+ function renderPlan(plan, pubkey) {
1135
+ console.log();
1136
+ console.log(chalk_1.default.bold(" Atbash setup"));
1137
+ console.log(chalk_1.default.dim(` Agent public key: ${pubkey}`));
1138
+ console.log(chalk_1.default.dim(` Detected on this machine: ${plan.found.length ? plan.found.join(", ") : "no supported runtime"}`));
1139
+ console.log();
1140
+ const writes = plan.steps.filter((s) => s.kind === "write");
1141
+ const execs = plan.steps.filter((s) => s.kind === "exec");
1142
+ const manuals = plan.steps.filter((s) => s.kind === "manual");
1143
+ if (!writes.length && !execs.length) {
1144
+ console.log(chalk_1.default.green(" Nothing to change — this machine is already wired.") + "\n");
1145
+ }
1146
+ if (writes.length) {
1147
+ console.log(chalk_1.default.bold(` Files (${writes.length})`));
1148
+ for (const step of writes) {
1149
+ console.log(` ${chalk_1.default.cyan(step.file)}${step.mode ? chalk_1.default.dim(` mode ${step.mode.toString(8)}`) : ""}`);
1150
+ console.log(` ${step.label}`);
1151
+ if (step.secret) {
1152
+ // Deliberately not the contents.
1153
+ console.log(chalk_1.default.dim(` Contents: pubkey= and privkey= lines for the agent above. Not printed — it is a private key.`));
1154
+ }
1155
+ else if (step.before === null) {
1156
+ for (const line of step.after.split("\n").slice(0, 40))
1157
+ console.log(chalk_1.default.dim(` + ${line}`));
1158
+ if (step.after.split("\n").length > 40)
1159
+ console.log(chalk_1.default.dim(" …"));
1160
+ }
1161
+ else {
1162
+ for (const line of condense(lineDiff(step.before, step.after))) {
1163
+ const painted = line.startsWith("+") ? chalk_1.default.green(line) : line.startsWith("-") ? chalk_1.default.red(line) : chalk_1.default.dim(line);
1164
+ console.log(` ${painted}`);
1165
+ }
1166
+ }
1167
+ if (step.before !== null)
1168
+ console.log(chalk_1.default.dim(" The existing file is copied to a .atbash-bak alongside it first."));
1169
+ console.log();
1170
+ }
1171
+ }
1172
+ if (execs.length) {
1173
+ console.log(chalk_1.default.bold(` Commands (${execs.length})`));
1174
+ for (const step of execs)
1175
+ console.log(` ${chalk_1.default.cyan(`${step.command} ${step.args.join(" ")}`)}\n ${step.label}`);
1176
+ console.log();
1177
+ }
1178
+ if (manuals.length) {
1179
+ console.log(chalk_1.default.bold(` For you to do (${manuals.length})`));
1180
+ for (const step of manuals) {
1181
+ console.log(` ${chalk_1.default.yellow("•")} ${chalk_1.default.bold(step.label)}`);
1182
+ for (const line of step.detail.split("\n"))
1183
+ console.log(` ${chalk_1.default.dim(line)}`);
1184
+ if (step.snippet)
1185
+ for (const line of step.snippet.split("\n"))
1186
+ console.log(chalk_1.default.dim(` ${line}`));
1187
+ console.log();
1188
+ }
1189
+ }
1190
+ if (plan.notes.length) {
1191
+ console.log(chalk_1.default.bold(" Notes"));
1192
+ for (const note of plan.notes)
1193
+ console.log(` ${chalk_1.default.dim("•")} ${chalk_1.default.dim(note)}`);
1194
+ console.log();
1195
+ }
1196
+ }
1197
+ // ── Doing it ────────────────────────────────────────────────────────────────
1198
+ /**
1199
+ * Copy a file aside before overwriting it, without ever clobbering an existing
1200
+ * backup — a second run must not overwrite the pristine copy from the first.
1201
+ */
1202
+ function backupFile(file) {
1203
+ if (!fs.existsSync(file))
1204
+ return null;
1205
+ let target = `${file}.atbash-bak`;
1206
+ let n = 1;
1207
+ while (fs.existsSync(target))
1208
+ target = `${file}.atbash-bak.${n++}`;
1209
+ fs.copyFileSync(file, target);
1210
+ return target;
1211
+ }
1212
+ /** Execute the plan. Writes first, then commands, so a failed install still
1213
+ * leaves a correct config and key file behind for a manual retry. */
1214
+ function applyPlan(plan) {
1215
+ const result = { written: [], backups: [], ran: [], failures: [] };
1216
+ for (const step of plan.steps) {
1217
+ if (step.kind !== "write")
1218
+ continue;
1219
+ try {
1220
+ const backup = backupFile(step.file);
1221
+ if (backup)
1222
+ result.backups.push(backup);
1223
+ fs.mkdirSync(path.dirname(step.file), { recursive: true, mode: step.mode === KEY_MODE ? DIR_MODE : undefined });
1224
+ fs.writeFileSync(step.file, step.after, step.mode ? { mode: step.mode } : {});
1225
+ // writeFileSync's mode is ignored for a file that already existed, so
1226
+ // assert it explicitly — a key file at 0644 is the failure this guards.
1227
+ if (step.mode)
1228
+ fs.chmodSync(step.file, step.mode);
1229
+ result.written.push(step.file);
1230
+ }
1231
+ catch (err) {
1232
+ result.failures.push(`${step.file}: ${err instanceof Error ? err.message : String(err)}`);
1233
+ }
1234
+ }
1235
+ for (const step of plan.steps) {
1236
+ if (step.kind !== "exec")
1237
+ continue;
1238
+ const label = `${step.command} ${step.args.join(" ")}`;
1239
+ const run = (0, child_process_1.spawnSync)(step.command, step.args, { stdio: "inherit" });
1240
+ // Three distinct outcomes, and they used to collapse into one misleading
1241
+ // message. `spawnSync` reports a binary it could not launch via `.error` with
1242
+ // `status` left null — so an ENOENT printed "exited on a signal", which reads
1243
+ // like the plugin installer crashed rather than "that command is not here".
1244
+ // The distinction matters because only one of them is the operator's to fix,
1245
+ // and the fix is to run it somewhere the CLI exists.
1246
+ if (run.error) {
1247
+ const missing = run.error.code === "ENOENT";
1248
+ result.failures.push(missing
1249
+ ? `${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.`
1250
+ : `${label} could not start: ${run.error.message}`);
1251
+ }
1252
+ else if (run.status === 0) {
1253
+ result.ran.push(label);
1254
+ }
1255
+ else if (run.signal) {
1256
+ result.failures.push(`${label} was killed by ${run.signal}`);
1257
+ }
1258
+ else {
1259
+ result.failures.push(`${label} exited with code ${run.status}`);
1260
+ }
1261
+ }
1262
+ return result;
1263
+ }
1264
+ // ── Registration check ──────────────────────────────────────────────────────
1265
+ /**
1266
+ * Confirm the agent this key belongs to is actually registered.
1267
+ *
1268
+ * Wiring a runtime to an unregistered agent produces the worst outcome available:
1269
+ * a machine that looks governed, with a plugin that cannot get a verdict. The
1270
+ * check sends only the PUBLIC key (GET /api/ai/exists), never the private one.
1271
+ */
1272
+ async function verifyRegistration(privkey, endpoint) {
1273
+ try {
1274
+ const atbash = new sdk_1.Atbash(privkey, { endpoint });
1275
+ return (await atbash.checkAgentExists()) ? { state: "registered" } : { state: "unregistered" };
1276
+ }
1277
+ catch (err) {
1278
+ return { state: "unknown", reason: err instanceof Error ? err.message : String(err) };
1279
+ }
1280
+ }
1281
+ /**
1282
+ * Confirmation prompt. Defaults to NO — anything but an explicit yes is a no —
1283
+ * except where `defaultYes` is set, which is only for questions where the safe
1284
+ * answer is also the common one (reusing the key already on this machine).
1285
+ */
1286
+ async function confirm(question, defaultYes = false) {
1287
+ const { createInterface } = await Promise.resolve().then(() => __importStar(require("node:readline")));
1288
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1289
+ const answer = await new Promise((r) => rl.question(question, (a) => { rl.close(); r(a); }));
1290
+ const trimmed = answer.trim();
1291
+ if (!trimmed)
1292
+ return defaultYes;
1293
+ return /^y(es)?$/i.test(trimmed);
1294
+ }
1295
+ // ── The command ─────────────────────────────────────────────────────────────
1296
+ function registerSetupCommand(program) {
1297
+ program
1298
+ .command("setup")
1299
+ .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)")
1300
+ .option("-k, --key <privkey>", "Agent private key (64 hex). Convenient, but it lands in your shell history — prefer the prompt or --key-file")
1301
+ .option("--key-file <path>", "Read the key from a file (the agent-keys-*.txt from onboarding, or an existing guard-client-key)")
1302
+ .option("--keys-dir <dir>", "Directory holding the key file, e.g. ~/Downloads")
1303
+ .option("--host <url>", "Atbash deployment to check the agent's registration against")
1304
+ .option("--runtime <ids...>", "Only configure these runtimes (currently: openclaw)")
1305
+ .option("--dry-run", "Show exactly which files would change, and the diffs, then exit WITHOUT writing anything")
1306
+ .option("-y, --yes", "Do not ask for confirmation before writing")
1307
+ .option("--no-install", "Do not install any package; write the key file and configs only")
1308
+ .option("--skip-verify", "Do not check the agent's registration (no network calls at all)")
1309
+ .option("--allow-unrecognized-host", "Permit a --host that is not a known Atbash deployment")
1310
+ .option("--home <dir>", "Home directory to configure (for testing)")
1311
+ .action(async (opts) => {
1312
+ const home = opts.home || process.env.HOME || os.homedir();
1313
+ const dryRun = !!opts.dryRun;
1314
+ // A key on argv is in the shell history and in `ps` output. Say so once,
1315
+ // rather than silently accepting the convenient-but-leaky path.
1316
+ if (opts.key) {
1317
+ console.log(chalk_1.default.yellow("\n Note: a key passed with --key is recorded in your shell history.") +
1318
+ chalk_1.default.dim("\n Clear it afterwards, or re-run without --key and paste it at the hidden prompt."));
1319
+ }
1320
+ const keySource = await resolveKeySource({
1321
+ key: opts.key,
1322
+ keyFile: opts.keyFile,
1323
+ keysDir: opts.keysDir,
1324
+ home,
1325
+ allowPrompt: process.stdin.isTTY === true,
1326
+ });
1327
+ if ("error" in keySource) {
1328
+ console.error(chalk_1.default.red(`\n${keySource.error}\n`));
1329
+ process.exit(1);
1330
+ }
1331
+ const privkey = keySource.material.privkey;
1332
+ const pubkey = (0, sdk_1.derivePublicKey)(privkey);
1333
+ // A key file whose stated pubkey does not match the private key is either
1334
+ // corrupt or two different keypairs spliced together. Either way, wiring a
1335
+ // runtime with it produces signatures nobody can attribute.
1336
+ const stated = keySource.material.statedPubkey?.replace(/^0x/i, "").toLowerCase();
1337
+ if (stated && stated !== pubkey.toLowerCase()) {
1338
+ console.error(chalk_1.default.red("\n The key file's `pubkey` does not match the key derived from its `privkey`.") +
1339
+ chalk_1.default.dim(`\n File says: ${stated}\n Derived: ${pubkey}\n Fix the file (or re-download it) before wiring anything.\n`));
1340
+ process.exit(1);
1341
+ }
1342
+ console.log(chalk_1.default.dim(`\n Agent key source: ${keySource.from}`));
1343
+ // ── Registration check. Only the public key crosses the network.
1344
+ if (!opts.skipVerify) {
1345
+ const endpoint = (opts.host || (0, sdk_1.resolve)("judgeEndpoint") || atbash_targets_1.DEFAULT_HOST || sdk_1.DEFAULT_ENDPOINT).replace(/\/$/, "");
1346
+ let hostname = "";
1347
+ try {
1348
+ hostname = new URL(endpoint).hostname.toLowerCase();
1349
+ }
1350
+ catch {
1351
+ console.error(chalk_1.default.red(`\n --host is not a valid URL: ${endpoint}\n`));
1352
+ process.exit(1);
1353
+ }
1354
+ // An unrecognized host could answer "registered" for any key, which is
1355
+ // exactly the confirmation this check exists to provide. Exact hostname
1356
+ // match, never a suffix — "atbash.ai.evil.com" must not pass.
1357
+ const recognizedHost = atbash_targets_1.KNOWN_HOSTS.has(hostname);
1358
+ if (!recognizedHost && !opts.allowUnrecognizedHost) {
1359
+ console.error(chalk_1.default.red(`\n ${hostname} is not a recognized Atbash deployment.`) +
1360
+ 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"));
1361
+ process.exit(1);
1362
+ }
1363
+ const verdict = await verifyRegistration(privkey, endpoint);
1364
+ if (verdict.state === "unregistered") {
1365
+ console.error(chalk_1.default.red("\n That agent is not registered on this deployment.") +
1366
+ chalk_1.default.dim(`\n Public key: ${pubkey}\n Key came from: ${keySource.from}\n`));
1367
+ // The likeliest cause is not "you skipped onboarding" — it is "this is a
1368
+ // key you did not choose". Say so when the key was found rather than
1369
+ // supplied, because the fix is completely different.
1370
+ if (/existing key file|atbash config/.test(keySource.from)) {
1371
+ console.error(chalk_1.default.yellow(" This is a key that was already on this machine, not one you supplied.") +
1372
+ chalk_1.default.dim("\n If you are onboarding a DIFFERENT agent, pass its key explicitly:" +
1373
+ "\n --key <64-hex> the key shown in the browser" +
1374
+ "\n --keys-dir ~/Downloads the key file you saved" +
1375
+ "\n Or re-run and answer 'n' when asked whether to use the existing key.\n"));
1376
+ }
1377
+ else {
1378
+ console.error(chalk_1.default.dim(" Finish onboarding first — wiring a runtime to an unregistered agent leaves it\n" +
1379
+ " looking governed while the plugin can never get a verdict.\n"));
1380
+ }
1381
+ process.exit(1);
1382
+ }
1383
+ if (verdict.state === "unknown") {
1384
+ console.log(chalk_1.default.yellow(`\n Could not confirm the agent's registration (${verdict.reason}).`));
1385
+ console.log(chalk_1.default.dim(" The wiring below is still correct, but nothing has verified that this agent exists."));
1386
+ if (!opts.yes && !dryRun && process.stdin.isTTY && !(await confirm(" Continue anyway? [y/N] "))) {
1387
+ console.log(chalk_1.default.dim("\n Nothing was changed.\n"));
1388
+ return;
1389
+ }
1390
+ }
1391
+ else if (recognizedHost) {
1392
+ console.log(chalk_1.default.green(` Agent is registered on ${hostname}.`));
1393
+ }
1394
+ else {
1395
+ // --allow-unrecognized-host is a real bypass, and its most dangerous
1396
+ // property is that the check still PRINTS a reassuring answer. A host
1397
+ // chosen by an attacker returns "registered" for any key at all, so a
1398
+ // "✓ registered" line here would be the attacker's own claim wearing
1399
+ // Atbash's voice. Never let that line stand unqualified: say the answer
1400
+ // came from an unvouched-for server, so a talked-into-it operator sees
1401
+ // the one thing that would tell them something is wrong.
1402
+ console.log(chalk_1.default.yellow(` ${hostname} answered "registered" — but this is NOT a recognized Atbash deployment.`));
1403
+ console.log(chalk_1.default.yellow(" A registration check against an unrecognized host proves nothing: any server") +
1404
+ chalk_1.default.yellow("\n can answer \"registered\" for any key. Treat this as UNVERIFIED."));
1405
+ console.log(chalk_1.default.dim(` Recognized deployments: ${[...atbash_targets_1.KNOWN_HOSTS].join(", ")}`));
1406
+ }
1407
+ }
1408
+ // ── Plan, show, then (maybe) apply.
1409
+ const plan = buildPlan({
1410
+ home,
1411
+ privkey,
1412
+ pubkey,
1413
+ noInstall: opts.install === false,
1414
+ only: opts.runtime ?? [],
1415
+ });
1416
+ renderPlan(plan, pubkey);
1417
+ const changes = plan.steps.filter((s) => s.kind === "write" || s.kind === "exec");
1418
+ if (dryRun) {
1419
+ console.log(chalk_1.default.green(" Dry run — nothing was written.") +
1420
+ chalk_1.default.dim(" Re-run without --dry-run to apply.\n"));
1421
+ return;
1422
+ }
1423
+ if (!changes.length) {
1424
+ console.log(chalk_1.default.dim(" Nothing to apply.\n"));
1425
+ return;
1426
+ }
1427
+ if (!opts.yes) {
1428
+ if (!process.stdin.isTTY) {
1429
+ console.error(chalk_1.default.red(" Refusing to write without confirmation.") +
1430
+ chalk_1.default.dim(" Re-run with --yes (or --dry-run to preview).\n"));
1431
+ process.exit(1);
1432
+ }
1433
+ if (!(await confirm(` Apply ${changes.length} change${changes.length === 1 ? "" : "s"} to this machine? [y/N] `))) {
1434
+ console.log(chalk_1.default.dim("\n Nothing was changed.\n"));
1435
+ return;
1436
+ }
1437
+ }
1438
+ const result = applyPlan(plan);
1439
+ console.log();
1440
+ for (const file of result.written)
1441
+ console.log(chalk_1.default.green(` ✓ wrote ${file}`));
1442
+ for (const file of result.backups)
1443
+ console.log(chalk_1.default.dim(` backup: ${file}`));
1444
+ for (const cmd of result.ran)
1445
+ console.log(chalk_1.default.green(` ✓ ran ${cmd}`));
1446
+ for (const failure of result.failures)
1447
+ console.log(chalk_1.default.red(` ✗ ${failure}`));
1448
+ if (result.failures.length) {
1449
+ console.log(chalk_1.default.yellow("\n Finished with failures — this machine is NOT fully wired.") +
1450
+ chalk_1.default.dim("\n Everything that did succeed is listed above; the steps that failed can be re-run.\n"));
1451
+ process.exitCode = 1;
1452
+ return;
1453
+ }
1454
+ 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"));
1455
+ console.log(chalk_1.default.dim(" from the agent's page in the dashboard to confirm it reports as enforcing.\n"));
1456
+ });
1457
+ }
1458
+ //# sourceMappingURL=setup.js.map