passcontrol 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/menu.mjs ADDED
@@ -0,0 +1,733 @@
1
+ // The interactive command browser — `passcontrol settings`, and bare
2
+ // `passcontrol` on a TTY.
3
+ //
4
+ // Three constraints shaped this file, and each one rules out the obvious
5
+ // implementation, so they are worth stating:
6
+ //
7
+ // 1. NO NEW DEPENDENCY. This CLI has five, all pure JS, no native modules, and
8
+ // `research/passport-key-protection.md` §3 calls that "a fact worth
9
+ // protecting" — adding a native module to a credential CLI is a supply-chain
10
+ // decision, not an implementation detail. Every TUI library is either native
11
+ // or a large transitive tree, so the arrow keys are decoded from raw escape
12
+ // sequences here instead. It is about forty lines.
13
+ //
14
+ // 2. THE MENU IS A FRONT DOOR, NOT A REPLACEMENT. Every flat command keeps
15
+ // working exactly as it did. `cli/mcp/gateway.mjs`, shell scripts and agents
16
+ // invoke these by name; a menu that swallowed them would break every caller
17
+ // that is not a human at a terminal.
18
+ //
19
+ // 3. THE REGISTRY IS PINNED TO THE DISPATCH, NOT COPIED FROM IT. CLAUDE.md
20
+ // records that the `env`/`configure` usage strings drifted from the dispatch
21
+ // once already. `cli/__tests__/menu.test.mjs` parses the switch in
22
+ // `bin/passcontrol.mjs` and fails if a command exists that this file neither
23
+ // lists nor deliberately hides, so drift is caught by the suite rather than
24
+ // by a user finding a command the menu forgot.
25
+
26
+ /**
27
+ * The command groups, in the order they are shown.
28
+ *
29
+ * `run` is the argv this entry dispatches — an array, because several entries
30
+ * are subcommands (`key migrate`). Nothing here calls a handler directly:
31
+ * going through argv is what lets the menu print the exact equivalent command
32
+ * line before running it, which is the property that makes the menu teach the
33
+ * flat commands rather than hide them.
34
+ *
35
+ * `needsArgs` marks an entry that cannot run from a bare selection — it takes
36
+ * an agent id, a file, a prompt. The browser prints the command line and stops
37
+ * rather than guessing, because guessing an argument to `agent revoke` is not
38
+ * a recoverable mistake.
39
+ */
40
+ export const EFFECT_LABELS = Object.freeze({
41
+ read: "read-only",
42
+ preview: "preview",
43
+ local_write: "local write",
44
+ tenant_write: "tenant write",
45
+ irreversible: "irreversible",
46
+ launch: "launch",
47
+ long_running: "long-running",
48
+ });
49
+
50
+ export const NETWORK_LABELS = Object.freeze({
51
+ none: "no network",
52
+ gateway: "uses the gateway",
53
+ browser: "opens a browser",
54
+ provider: "may contact a provider",
55
+ });
56
+
57
+ const currentFrom = (key) => (context = {}) => context[key] ?? null;
58
+ const command = ({
59
+ id,
60
+ label,
61
+ run,
62
+ detail,
63
+ description,
64
+ effect = "read",
65
+ network = "none",
66
+ keywords = [],
67
+ current = () => null,
68
+ needsArgs = false,
69
+ guide = null,
70
+ returnToMenu = effect === "read" || effect === "preview",
71
+ }) => ({
72
+ id,
73
+ label,
74
+ run,
75
+ detail,
76
+ description,
77
+ effect,
78
+ network,
79
+ keywords: [...new Set([...id.split("-"), ...run, ...keywords])],
80
+ current,
81
+ needsArgs,
82
+ guide,
83
+ returnToMenu,
84
+ });
85
+
86
+ export const GROUPS = [
87
+ {
88
+ section: "CONTROL",
89
+ title: "Setup & config",
90
+ hint: "connect this machine to a gateway",
91
+ items: [
92
+ command({ id: "login", label: "Sign in through the browser", run: ["login"], detail: "login", description: "Approve this machine and create local credentials.", effect: "local_write", network: "browser", current: currentFrom("account") }),
93
+ command({ id: "init", label: "Configure by hand, no browser", run: ["init"], detail: "init", description: "Write a project or global PassControl configuration interactively.", effect: "local_write", current: currentFrom("config") }),
94
+ command({ id: "env", label: "Print integration settings", run: ["env"], detail: "env", description: "Print environment variables for a supported agent integration.", network: "none", current: currentFrom("provider") }),
95
+ command({ id: "configure", label: "Preview integration config", run: ["configure"], detail: "configure <integration>", description: "Choose an integration and preview its configuration without writing a file.", effect: "preview", guide: "integration", needsArgs: true, current: currentFrom("provider") }),
96
+ command({ id: "logout", label: "Sign out and clear credentials", run: ["logout"], detail: "logout", description: "Remove local credentials and optionally revoke their remote capabilities.", effect: "tenant_write", network: "gateway", current: currentFrom("account") }),
97
+ command({ id: "unlink", label: "Forget the remembered checkout", run: ["unlink"], detail: "unlink", description: "Remove the saved local app-checkout pointer.", effect: "local_write", current: currentFrom("app") }),
98
+ ],
99
+ },
100
+ {
101
+ section: "CONTROL",
102
+ title: "Fleet",
103
+ hint: "agents and their passports",
104
+ items: [
105
+ command({ id: "agent-list", label: "List agents", run: ["agent", "list"], detail: "agent list", description: "Show the fleet, lifecycle state, usage, and identifiers.", network: "gateway", current: currentFrom("fleet") }),
106
+ command({ id: "agent-create", label: "Create an agent passport", run: ["agent", "create"], detail: "agent create <name>", description: "Create a fleet row and reveal a new private passport once.", effect: "tenant_write", network: "gateway", needsArgs: true }),
107
+ command({ id: "agent-suspend", label: "Suspend an agent", run: ["agent", "suspend"], detail: "agent suspend <id>", description: "Temporarily refuse every new call from one active agent.", effect: "tenant_write", network: "gateway", guide: "suspend", needsArgs: true }),
108
+ command({ id: "agent-resume", label: "Resume an agent", run: ["agent", "resume"], detail: "agent resume <id>", description: "Allow a suspended agent to authenticate again.", effect: "tenant_write", network: "gateway", guide: "resume", needsArgs: true }),
109
+ command({ id: "kill", label: "Tenant kill switch", run: ["kill"], detail: "kill on|off", description: "Arm or disarm the workspace-wide emergency stop.", effect: "tenant_write", network: "gateway", guide: "kill", needsArgs: true, current: currentFrom("kill") }),
110
+ ],
111
+ },
112
+ {
113
+ section: "CONTROL",
114
+ title: "Money",
115
+ hint: "budgets and fleet spending",
116
+ items: [
117
+ command({ id: "spend", label: "Fleet and per-agent spend", run: ["spend"], detail: "spend", description: "Read reconciled token and monetary usage for the fleet.", network: "gateway", current: currentFrom("fleet") }),
118
+ // Lives under Money rather than Evidence, and not only because Evidence is
119
+ // full at seven rows (the 80x24 sweep in menu.test.mjs is the hard limit).
120
+ // This row answers "what did this fleet spend, and can I prove it" — the
121
+ // reading of it is a money question. Verifying somebody ELSE's statement
122
+ // is the evidence question, and that one sits with the other verifiers.
123
+ command({ id: "statements", label: "Signed spend statements", run: ["statements"], detail: "statements", description: "Show the daily chain committing to every receipt in each window.", network: "gateway" }),
124
+ ],
125
+ },
126
+ {
127
+ section: "AUDIT",
128
+ title: "Evidence",
129
+ hint: "events, receipts and proof",
130
+ items: [
131
+ command({ id: "audit", label: "Operator audit history", run: ["audit"], detail: "audit", description: "Show consequential operator actions and request identifiers.", network: "gateway" }),
132
+ command({ id: "logs", label: "Governed call logs", run: ["logs"], detail: "logs", description: "Filter governed calls by agent, class, status, and count.", network: "gateway", guide: "logs" }),
133
+ command({ id: "verify-receipt", label: "Verify a signed receipt", run: ["verify", "receipt"], detail: "verify receipt <jws>", description: "Verify a receipt against a pinned issuer without an account.", network: "gateway", guide: "verify-receipt", needsArgs: true }),
134
+ command({ id: "verify-statement", label: "Verify a signed spend statement", run: ["verify", "statement"], detail: "verify statement <jws>", description: "Verify a statement against a pinned issuer without an account.", network: "gateway", guide: "verify-statement", needsArgs: true }),
135
+ command({ id: "verify-token", label: "Verify an agent-to-agent token", run: ["verify", "token"], detail: "verify token <jwt>", description: "Verify a token against a pinned issuer and audience.", network: "gateway", guide: "verify-token", needsArgs: true }),
136
+ command({ id: "export", label: "Save a workspace snapshot", run: ["export"], detail: "export", description: "Write a redacted workspace configuration snapshot.", effect: "local_write", network: "gateway" }),
137
+ command({ id: "import", label: "Restore agents from a snapshot", run: ["import"], detail: "import <file>", description: "Add missing configuration from a snapshot without overwriting agents.", effect: "tenant_write", network: "gateway", needsArgs: true }),
138
+ ],
139
+ },
140
+ {
141
+ section: "AUDIT",
142
+ title: "Trust",
143
+ hint: "where the passport key lives",
144
+ items: [
145
+ command({ id: "key-status", label: "Show the local key storage tier", run: ["key", "status"], detail: "key status", description: "Report where this machine resolves its passport private key.", current: currentFrom("key") }),
146
+ command({ id: "key-migrate", label: "Move a file key into the OS store", run: ["key", "migrate"], detail: "key migrate", description: "Store the passport in the OS credential store, verify it, then remove the file copy.", effect: "local_write", guide: "key-migrate", current: currentFrom("key") }),
147
+ ],
148
+ },
149
+ {
150
+ section: "SYSTEM",
151
+ title: "Local stack",
152
+ hint: "run a gateway locally",
153
+ // Shown only on a machine that HAS a PassControl checkout. See
154
+ // `availableGroups` below for why, and why `doctor` was moved out of here.
155
+ requires: "localStack",
156
+ items: [
157
+ command({ id: "setup", label: "Clone the app and start everything", run: ["setup"], detail: "setup", description: "Prepare a local checkout and start the self-hosted stack.", effect: "local_write", network: "provider" }),
158
+ command({ id: "start", label: "Start the local stack", run: ["start"], detail: "start", description: "Start the remembered local dashboard and its dependencies.", effect: "local_write" }),
159
+ command({ id: "stop", label: "Stop the local stack", run: ["stop"], detail: "stop", description: "Stop the CLI-managed local dashboard process.", effect: "local_write" }),
160
+ command({ id: "restart", label: "Restart the local dashboard", run: ["restart"], detail: "restart", description: "Restart only the CLI-managed dashboard process.", effect: "local_write" }),
161
+ command({ id: "local-logs", label: "Show local dashboard logs", run: ["local-logs"], detail: "local-logs", description: "Follow the local dashboard process output.", effect: "long_running" }),
162
+ ],
163
+ },
164
+ {
165
+ section: "SYSTEM",
166
+ title: "Status & tools",
167
+ hint: "health and diagnostics",
168
+ items: [
169
+ command({ id: "doctor", label: "Diagnose setup", run: ["doctor"], detail: "doctor", description: "Inspect the local stack, gateway, credentials, and protocol compatibility.", network: "gateway", current: currentFrom("gateway") }),
170
+ command({ id: "status", label: "Show cockpit status", run: ["status"], detail: "status", description: "Show local configuration, gateway health, and the next useful action.", network: "gateway", current: currentFrom("gateway") }),
171
+ command({ id: "version", label: "CLI, gateway and schema versions", run: ["version"], detail: "version", description: "Compare CLI, gateway build, schema, and protocol versions.", network: "gateway" }),
172
+ command({ id: "open", label: "Open the Control Tower", run: ["open"], detail: "open", description: "Open the configured dashboard in the system browser.", effect: "launch", network: "browser" }),
173
+ command({ id: "call", label: "Make a governed model call", run: ["call"], detail: "call \"<prompt>\"", description: "Mint a visa and make a billable governed provider call.", effect: "tenant_write", network: "provider", needsArgs: true, current: currentFrom("provider") }),
174
+ ],
175
+ },
176
+ {
177
+ section: null,
178
+ danger: true,
179
+ title: "Danger zone",
180
+ hint: "revoke, rotate or destroy",
181
+ items: [
182
+ command({ id: "agent-rotate", label: "Rotate a passport key", run: ["agent", "rotate"], detail: "agent rotate <id>", description: "Replace an agent passport and reveal a new private key once.", effect: "irreversible", network: "gateway", needsArgs: true }),
183
+ command({ id: "agent-revoke", label: "Revoke an agent permanently", run: ["agent", "revoke"], detail: "agent revoke <id>", description: "Permanently prevent an agent from authenticating again.", effect: "irreversible", network: "gateway", needsArgs: true }),
184
+ command({ id: "keygen-instance", label: "Create a receipt-signing key", run: ["keygen", "instance"], detail: "keygen instance", description: "Reveal a new instance signing seed; replacing a live key requires a rotation plan.", effect: "irreversible", needsArgs: true }),
185
+ command({ id: "reset", label: "Destroy and recreate the local stack", run: ["reset"], detail: "reset --local --confirm RESET", description: "Delete and recreate local stack state after an explicit typed confirmation.", effect: "irreversible", needsArgs: true }),
186
+ ],
187
+ },
188
+ ];
189
+
190
+ /**
191
+ * Commands the browser deliberately does not list, each with its reason. The
192
+ * pin test reads this map, so "absent from the menu" is always a recorded
193
+ * decision rather than an oversight — that is the whole point of writing the
194
+ * reasons down next to the names.
195
+ */
196
+ export const HIDDEN = {
197
+ help: "the menu replaces it in this mode",
198
+ settings: "this is the menu itself",
199
+ menu: "an alias of settings",
200
+ mcp: "a long-lived stdio server — it owns the terminal and would never return to the menu",
201
+ sidecar: "a long-lived foreground server, same reason as mcp",
202
+ fleet: "an alias of `agent`, already listed once under Fleet",
203
+ agent: "reached through its subcommands under Fleet",
204
+ key: "reached through its subcommands under Trust",
205
+ keygen: "reached through its `instance` subcommand under Trust",
206
+ verify: "reached through its subcommands under Evidence",
207
+ try: "kept as an explanatory compatibility error, but no longer performs an operation",
208
+ };
209
+
210
+ /** Every top-level command name the menu can reach, flattened. */
211
+ export function menuCommands() {
212
+ const names = new Set();
213
+ for (const group of GROUPS) for (const item of group.items) names.add(item.run[0]);
214
+ return names;
215
+ }
216
+
217
+ export function allMenuItems(groups = GROUPS) {
218
+ const seen = new Set();
219
+ const items = [];
220
+ for (const group of groups) {
221
+ for (const item of group.items) {
222
+ if (seen.has(item.id)) continue;
223
+ seen.add(item.id);
224
+ items.push({ ...item, groupTitle: group.title });
225
+ }
226
+ }
227
+ return items;
228
+ }
229
+
230
+ export function searchMenu(query, groups = GROUPS) {
231
+ const needle = String(query ?? "").trim().toLowerCase();
232
+ const items = allMenuItems(groups);
233
+ if (!needle) return items;
234
+
235
+ // What a row IS beats what a row MENTIONS.
236
+ //
237
+ // The filter searches descriptions too, which is what makes the search useful
238
+ // — but an unranked filter returns group order, so a row that merely mentions
239
+ // the word in prose can land above the row that IS the word. Typing "receipt"
240
+ // and getting "Signed spend statements" first (its description explains that
241
+ // the chain commits to every receipt) is the case that surfaced this: the
242
+ // description is accurate and worth keeping, and the ranking is what was wrong.
243
+ //
244
+ // Two tiers only, and the sort is stable, so within a tier group order is
245
+ // preserved exactly as before.
246
+ const named = (item) => `${item.label} ${item.detail}`.toLowerCase().includes(needle);
247
+ const matches = items.filter((item) =>
248
+ [item.label, item.detail, item.description, item.groupTitle, ...item.keywords]
249
+ .join(" ")
250
+ .toLowerCase()
251
+ .includes(needle)
252
+ );
253
+ return [...matches.filter(named), ...matches.filter((item) => !named(item))];
254
+ }
255
+
256
+ export function recentEligible(item) {
257
+ return item?.effect === "read" || item?.effect === "preview";
258
+ }
259
+
260
+ export function updateRecents(recentIds, item, limit = 5) {
261
+ if (!recentEligible(item)) return [...recentIds];
262
+ return [item.id, ...recentIds.filter((id) => id !== item.id)].slice(0, limit);
263
+ }
264
+
265
+ /**
266
+ * The groups whose commands this machine can actually run.
267
+ *
268
+ * A group may name ONE capability in `requires`, and is drawn only when the
269
+ * caller reports it. Today there is exactly one: `Local stack` needs a
270
+ * PassControl checkout on this disk, and without one every command in it —
271
+ * `start`, `stop`, `restart`, `local-logs` — fails on the first line. Offering
272
+ * them is not a small inaccuracy; it is a menu describing a different machine.
273
+ *
274
+ * The second reason is a product one and worth writing down rather than
275
+ * discovering later. The default install of this CLI is a CLIENT for a hosted
276
+ * gateway, and `setup` clones the whole server and runs it locally. A front
277
+ * door that opens with that offer is telling every new user, unprompted, to go
278
+ * and run the thing themselves. That belongs in the documentation of a
279
+ * self-hosted deployment, chosen deliberately, not on the first screen of a
280
+ * client install.
281
+ *
282
+ * NOTHING IS REMOVED FROM THE CLI. `passcontrol setup`, `start`, `stop`,
283
+ * `restart` and `local-logs` all still work exactly as they did when typed, and
284
+ * `passcontrol --help` still lists every one of them — the menu is a front door,
285
+ * not a replacement, and someone self-hosting is following a README rather than
286
+ * hunting through a menu. `cli/__tests__/menu.test.mjs` still pins every
287
+ * dispatch command to this registry, so nothing here can quietly disappear.
288
+ *
289
+ * `doctor` was moved OUT of that group and into Status & tools for this change.
290
+ * It reports on the gateway, the credentials and the protocol as well as the
291
+ * local stack, so it is exactly the command a client install wants when
292
+ * something is wrong — and it would have been the collateral damage of hiding
293
+ * the group around it.
294
+ */
295
+ export function availableGroups(capabilities = {}, groups = GROUPS) {
296
+ return groups.filter((group) => !group.requires || capabilities[group.requires] === true);
297
+ }
298
+
299
+ export function groupsWithRecents(recentIds = [], groups = GROUPS) {
300
+ const byId = new Map(allMenuItems(groups).map((item) => [item.id, item]));
301
+ const items = recentIds.map((id) => byId.get(id)).filter(Boolean);
302
+ if (items.length === 0) return groups;
303
+ return [{ title: "Recent", hint: "safe choices from this session", items }, ...groups];
304
+ }
305
+
306
+ // ── key decoding ────────────────────────────────────────────────────────────
307
+
308
+ const ESC = "\x1b";
309
+ const CTRL_C = "\x03";
310
+
311
+ /**
312
+ * Map one chunk of stdin to an intent, or null for a key we ignore.
313
+ *
314
+ * Ctrl-C is decoded HERE rather than by a SIGINT handler, because raw mode is
315
+ * precisely the mode in which the terminal stops translating \x03 into a
316
+ * signal. A menu that left it to SIGINT would be unquittable by the one key
317
+ * everybody reaches for first.
318
+ */
319
+ export function decodeKey(chunk) {
320
+ const s = String(chunk);
321
+ if (s === CTRL_C) return "abort";
322
+ if (s === `${ESC}[A`) return "up";
323
+ if (s === `${ESC}[B`) return "down";
324
+ if (s === `${ESC}[C`) return "enter";
325
+ if (s === `${ESC}[D`) return "back";
326
+ if (s === `${ESC}[H`) return "first";
327
+ if (s === `${ESC}[F`) return "last";
328
+ if (s === "\r" || s === "\n") return "enter";
329
+ if (s === "\x7f" || s === "\b") return "backspace";
330
+ if (s === "\x15") return "clear";
331
+ if (s.length === 1 && s >= " " && s !== "\x7f") return `char:${s}`;
332
+ return null;
333
+ }
334
+
335
+ /**
336
+ * Split a raw-mode buffer into intents, returning whatever could not yet be
337
+ * decoded so the caller can prepend it to the next chunk.
338
+ *
339
+ * ONE `data` EVENT IS NOT ONE KEYPRESS, and assuming it was is the bug this
340
+ * function exists to fix. A first version of this file decoded each chunk whole
341
+ * and looked correct against synthetic single-key events in the unit tests —
342
+ * then dropped three of four arrow keys when driven through a real pty, because
343
+ * a terminal delivers held or quickly-repeated keys coalesced into one chunk
344
+ * (`\x1b[B\x1b[B`) and just as happily splits a single escape sequence across
345
+ * two (`\x1b` then `[B`). Neither shape matches any whole-chunk comparison, so
346
+ * both silently decoded to nothing.
347
+ *
348
+ * A lone trailing ESC is therefore never decoded on its own — it is held back,
349
+ * because it cannot be told apart from the first byte of a sequence still in
350
+ * flight. The cost is that bare Escape does nothing; `←`, `h` and `q` are the
351
+ * documented ways out, and a key that does nothing is much cheaper than a
352
+ * cursor that jumps because half an arrow key was read as Escape.
353
+ */
354
+ export function consumeKeys(buffer) {
355
+ const intents = [];
356
+ let i = 0;
357
+ while (i < buffer.length) {
358
+ const rest = buffer.length - i;
359
+ if (buffer[i] === ESC) {
360
+ // Hold an incomplete sequence for the next chunk rather than guessing.
361
+ if (rest < 3 && (rest === 1 || buffer[i + 1] === "[")) break;
362
+ if (buffer[i + 1] === "[") {
363
+ const intent = decodeKey(buffer.slice(i, i + 3));
364
+ if (intent) intents.push(intent);
365
+ i += 3; // an unrecognised CSI is consumed, not replayed
366
+ continue;
367
+ }
368
+ i += 1; // ESC followed by something else: drop the ESC
369
+ continue;
370
+ }
371
+ const intent = decodeKey(buffer[i]);
372
+ if (intent) intents.push(intent);
373
+ i += 1;
374
+ }
375
+ return { intents, rest: buffer.slice(i) };
376
+ }
377
+
378
+ /** Move a cursor within `length`, wrapping at both ends. */
379
+ export function moveCursor(index, intent, length) {
380
+ if (length <= 0) return 0;
381
+ if (intent === "up") return (index - 1 + length) % length;
382
+ if (intent === "down") return (index + 1) % length;
383
+ if (intent === "first") return 0;
384
+ if (intent === "last") return length - 1;
385
+ return index;
386
+ }
387
+
388
+ export const initialState = Object.freeze({ group: null, index: 0, chosen: null, done: null, search: null });
389
+
390
+ /**
391
+ * The pure state machine behind the browser, kept separate from rendering and
392
+ * from stdin so the navigation can be tested without a terminal at all: the
393
+ * tests drive it with a list of intents and assert where it lands.
394
+ *
395
+ * `back` at the top level does NOT quit. Leaving on a key the user pressed to
396
+ * mean "up one level" would throw away their place for a keystroke that meant
397
+ * the opposite; `q` and Ctrl-C are the two ways out, and both are on screen.
398
+ */
399
+ export function reduce(state, intent, groups = GROUPS) {
400
+ // Array.prototype.reduce passes its index as a third argument; accepting the
401
+ // pure reducer directly is convenient in tests and callers, so ignore it.
402
+ if (!Array.isArray(groups)) groups = GROUPS;
403
+ if (state.search) {
404
+ const results = searchMenu(state.search.query, groups);
405
+ if (intent === "abort") return { ...state, done: "abort" };
406
+ if (intent === "back") return { ...state, search: null };
407
+ if (intent === "up" || intent === "down" || intent === "first" || intent === "last") {
408
+ return {
409
+ ...state,
410
+ search: { ...state.search, index: moveCursor(state.search.index, intent, results.length) },
411
+ };
412
+ }
413
+ if (intent === "enter") {
414
+ const chosen = results[state.search.index];
415
+ return chosen ? { ...state, chosen } : state;
416
+ }
417
+ if (intent === "backspace") {
418
+ const query = state.search.query.slice(0, -1);
419
+ const next = searchMenu(query, groups);
420
+ return { ...state, search: { query, index: Math.min(state.search.index, Math.max(0, next.length - 1)) } };
421
+ }
422
+ if (intent === "clear") return { ...state, search: { query: "", index: 0 } };
423
+ if (intent.startsWith("char:")) {
424
+ const query = state.search.query + intent.slice(5);
425
+ return { ...state, search: { query, index: 0 } };
426
+ }
427
+ return state;
428
+ }
429
+
430
+ if (intent.startsWith("char:")) {
431
+ const char = intent.slice(5);
432
+ if (char === "/") return { ...state, search: { query: "", index: 0 } };
433
+ if (char === "k") intent = "up";
434
+ else if (char === "j") intent = "down";
435
+ else if (char === "l") intent = "enter";
436
+ else if (char === "h") intent = "back";
437
+ else if (char === "q") intent = "quit";
438
+ else return state;
439
+ }
440
+
441
+ const level = state.group === null ? groups : groups[state.group].items;
442
+ switch (intent) {
443
+ case "up":
444
+ case "down":
445
+ case "first":
446
+ case "last":
447
+ return { ...state, index: moveCursor(state.index, intent, level.length) };
448
+ case "enter":
449
+ if (state.group === null) return { ...state, group: state.index, index: 0 };
450
+ return { ...state, chosen: groups[state.group].items[state.index] };
451
+ case "back":
452
+ if (state.group === null) return state;
453
+ return { ...state, group: null, index: state.group, chosen: null };
454
+ case "quit":
455
+ case "abort":
456
+ return { ...state, done: intent };
457
+ default:
458
+ return state;
459
+ }
460
+ }
461
+
462
+ // ── rendering ───────────────────────────────────────────────────────────────
463
+
464
+ // A five-step ink scale, all inside the 16-colour set. Nothing in this CLI
465
+ // emits 38;5; or 38;2;, and a single file that did would look wrong beside the
466
+ // rest and can vanish outright on a terminal that has not been told its palette.
467
+ //
468
+ // The two dim levels are the point of the scale: `\x1b[2m` carries the
469
+ // descriptions and `\x1b[90m` sits a step below it for section headers and the
470
+ // footer, so the eye lands on titles first, descriptions second, and chrome
471
+ // last. On the terminals where `2m` is a no-op there is still one real level of
472
+ // separation rather than none.
473
+ const DIM = "\x1b[2m";
474
+ const FAINT = "\x1b[90m";
475
+ const BOLD = "\x1b[1m";
476
+ const LIME = "\x1b[92m";
477
+ const RED = "\x1b[31m";
478
+ const RESET = "\x1b[0m";
479
+
480
+ export const SEARCH_CHROME_LINES = 19;
481
+ const GROUP_TITLE_WIDTH = 20;
482
+ const ITEM_LABEL_WIDTH = 38;
483
+
484
+ /**
485
+ * Render the current level to an array of lines.
486
+ *
487
+ * Returns lines rather than printing them so a test can assert on what the
488
+ * user would see — including that the selected row is the one marked — without
489
+ * a pty. `colour` is off in tests, and off whenever stdout is not a TTY.
490
+ *
491
+ * Selection is a lime caret and a bold title, never a filled bar. A reversed
492
+ * block is the loudest thing a terminal can draw, and spending that on "where
493
+ * the cursor is" left nothing louder for "this row destroys an agent". The
494
+ * caret costs one column and reads as a pointer rather than as an alarm.
495
+ *
496
+ * Every padEnd here runs on plain text and the colour is applied afterwards.
497
+ * Padding a coloured string counts the escape bytes as characters, which pushes
498
+ * the next column right by an invisible amount — and since only the selected
499
+ * row is bold, the whole table would shift a few columns as the cursor moved.
500
+ */
501
+ function detailLines(item, context, { dim, bold, danger }) {
502
+ if (!item) return [];
503
+ const current = item.current(context);
504
+ const effect = EFFECT_LABELS[item.effect];
505
+ // An irreversible effect is the one label on this screen that is a warning
506
+ // rather than a fact, so it is the one that gets the red.
507
+ const painted = item.effect === "irreversible" ? danger(effect) : dim(effect);
508
+ // The label is deliberately NOT repeated here. It is already on screen one
509
+ // line up, bold, under the cursor — and the frame has to fit 80x24 with a
510
+ // six-item group above this block. The exact command takes its place as the
511
+ // heading, which is also the thing this panel exists to teach.
512
+ return [
513
+ "",
514
+ bold(` passcontrol ${item.detail}`),
515
+ ` ${item.description}`,
516
+ ` ${painted}${dim(` \u00b7 ${NETWORK_LABELS[item.network]}`)}`,
517
+ ...(current === null || current === "" ? [] : [dim(` Current: ${current}`)]),
518
+ ];
519
+ }
520
+
521
+ export function render(state, { colour = true, header = "", groups = GROUPS, context = {}, maxResults = Infinity } = {}) {
522
+ const ink = (code) => (s) => (colour ? `${code}${s}${RESET}` : s);
523
+ const dim = ink(DIM);
524
+ const faint = ink(FAINT);
525
+ const bold = ink(BOLD);
526
+ const lime = ink(LIME);
527
+ const danger = ink(`${RED}${BOLD}`);
528
+ const caret = (selected) => (selected ? ` ${lime("\u203a")} ` : " ");
529
+
530
+ const lines = [];
531
+ if (header) lines.push(header, "");
532
+
533
+ if (state.search) {
534
+ const results = searchMenu(state.search.query, groups);
535
+ lines.push(`${faint(" Search:")} ${bold(state.search.query)}`, "");
536
+ const windowStart = Math.max(0, state.search.index - maxResults + 1);
537
+ const visible = results.slice(windowStart, windowStart + maxResults);
538
+ visible.forEach((item, i) => {
539
+ const selected = windowStart + i === state.search.index;
540
+ const label = item.label.padEnd(ITEM_LABEL_WIDTH);
541
+ lines.push(selected
542
+ ? `${caret(true)}${bold(label)}${dim(item.groupTitle)}`
543
+ : `${caret(false)}${label}${faint(item.groupTitle)}`);
544
+ });
545
+ if (results.length === 0) lines.push(faint(" No matching commands"));
546
+ if (results.length > visible.length) lines.push(faint(` \u2026 showing ${windowStart + 1}-${windowStart + visible.length} of ${results.length}`));
547
+ lines.push(...detailLines(results[state.search.index], context, { dim, bold, danger }));
548
+ lines.push("", faint(" type to filter \u2191\u2193 navigate \u21b5 run \u2190 close"));
549
+ return lines;
550
+ }
551
+
552
+ if (state.group === null) {
553
+ lines.push(bold(" Choose a group"));
554
+ // Section headings are drawn, never navigated. They are not entries in
555
+ // `groups`, so `moveCursor` and `reduce` keep counting rows exactly as they
556
+ // did — the arrow-key arithmetic is untouched by this grouping, which is
557
+ // what makes it a change of appearance and not of behaviour.
558
+ //
559
+ // A named heading is its own separator and gets no blank line above it. The
560
+ // whole top level has to fit an 80x24 terminal, and it does not clear the
561
+ // screen and redraw so much as scroll the title off it: `browse` writes the
562
+ // frame after \x1b[2J\x1b[H, so one line too many costs the header on every
563
+ // keystroke. Three blank lines of breathing room were three lines too many.
564
+ let lastSection;
565
+ groups.forEach((group, i) => {
566
+ if (group.section !== lastSection) {
567
+ // A section with no name — Recent at the top, Danger zone at the
568
+ // bottom — gets a blank line and no heading. One row under a heading
569
+ // reads as a category; the same row after a gap reads as set apart.
570
+ if (group.section) lines.push(faint(` ${group.section}`));
571
+ else if (i > 0) lines.push("");
572
+ lastSection = group.section;
573
+ }
574
+ const selected = i === state.index;
575
+ const title = group.title.padEnd(GROUP_TITLE_WIDTH);
576
+ const name = selected ? (group.danger ? danger(title) : bold(title)) : title;
577
+ lines.push(`${caret(selected)}${name}${selected ? dim(group.hint) : faint(group.hint)}`);
578
+ });
579
+ lines.push("", faint(" \u2191\u2193 navigate \u21b5 open / search q quit"));
580
+ return lines;
581
+ }
582
+
583
+ const group = groups[state.group];
584
+ // Title and hint share one line here. At the top level they already sat side
585
+ // by side, so a second line would repeat a layout the reader has just seen —
586
+ // and this level has the least room of the three: a six-item group plus its
587
+ // detail block plus the header has to fit the same 80x24 frame.
588
+ const groupTitle = group.danger ? danger(` ${group.title}`) : bold(` ${group.title}`);
589
+ lines.push(`${groupTitle}${faint(` ${group.hint}`)}`, "");
590
+ group.items.forEach((item, i) => {
591
+ const selected = i === state.index;
592
+ const label = item.label.padEnd(ITEM_LABEL_WIDTH);
593
+ const detail = `passcontrol ${item.detail}`;
594
+ lines.push(selected
595
+ ? `${caret(true)}${bold(label)}${dim(detail)}`
596
+ : `${caret(false)}${label}${faint(detail)}`);
597
+ });
598
+ lines.push(...detailLines(group.items[state.index], context, { dim, bold, danger }));
599
+ lines.push("", faint(" \u2191\u2193 navigate \u21b5 run \u2190 back q quit"));
600
+ return lines;
601
+ }
602
+
603
+ // ── the interactive driver ──────────────────────────────────────────────────
604
+
605
+ const SHOW_CURSOR = "\x1b[?25h";
606
+ const HIDE_CURSOR = "\x1b[?25l";
607
+ const CLEAR = "\x1b[2J\x1b[H";
608
+
609
+ /**
610
+ * Print the whole menu as plain text. This is what a non-TTY gets, and it is a
611
+ * real answer rather than an error: piping `passcontrol settings` into a pager
612
+ * or a file should show the map, not fail because nobody is holding a keyboard.
613
+ */
614
+ export function printStatic(write, { header = "", groups = GROUPS } = {}) {
615
+ if (header) write(`${header}\n\n`);
616
+ let lastSection;
617
+ // Filtered the same way the browser is, and silently. A piped map describes
618
+ // the machine it was produced on; a footnote explaining what was left out
619
+ // would put the offer back on the screen it was taken off.
620
+ for (const group of groups) {
621
+ // The same sections the interactive top level draws, so a piped map and a
622
+ // browsed one describe the CLI with the same shape.
623
+ if (group.section && group.section !== lastSection) write(` ${group.section}\n`);
624
+ lastSection = group.section;
625
+ write(` ${group.title} — ${group.hint}\n`);
626
+ for (const item of group.items) {
627
+ write(` passcontrol ${item.detail}\n`);
628
+ }
629
+ write("\n");
630
+ }
631
+ write(" An interactive menu is available when this runs on a terminal.\n");
632
+ }
633
+
634
+ /**
635
+ * Drive the browser against a real terminal and resolve with the chosen entry,
636
+ * or null if the user left without choosing.
637
+ *
638
+ * The `finally` is the load-bearing part of this function. Raw mode with a
639
+ * hidden cursor is a global change to the user's terminal, not to this process:
640
+ * throwing out of the loop without restoring it leaves them in a shell with no
641
+ * echo and no cursor, which reads as a hung machine rather than as a crashed
642
+ * command. Every exit path — chosen, quit, Ctrl-C, an exception from render —
643
+ * goes through it.
644
+ */
645
+ export function browse({ stdin, stdout, header = "", recentIds = [], context = {}, status = null, capabilities = {} } = {}) {
646
+ const input = stdin ?? process.stdin;
647
+ const output = stdout ?? process.stdout;
648
+ const colour = Boolean(output.isTTY) && !process.env.NO_COLOR;
649
+ const groups = groupsWithRecents(recentIds, availableGroups(capabilities));
650
+
651
+ return new Promise((resolve, reject) => {
652
+ let state = initialState;
653
+ let settled = false;
654
+ let remoteStatus = null;
655
+
656
+ const draw = () => {
657
+ const renderedHeader = typeof header === "function" ? header(remoteStatus) : header;
658
+ const renderedContext = { ...context, ...(remoteStatus?.current ?? {}) };
659
+ output.write(CLEAR);
660
+ output.write(`${render(state, {
661
+ colour,
662
+ header: renderedHeader,
663
+ groups,
664
+ context: renderedContext,
665
+ // Everything the search level draws around its results, counted at its
666
+ // worst: seven header lines, the blank after them, the query line and
667
+ // its blank, the "… showing" line, six detail lines, and a blank plus
668
+ // the footer. Retuned with the header — it used to reserve twelve, for
669
+ // a header three lines shorter with no detail block above the fold.
670
+ // `cli/__tests__/menu.test.mjs` pins the arithmetic against the frame.
671
+ maxResults: Math.max(3, (Number(output.rows) || 24) - SEARCH_CHROME_LINES),
672
+ }).join("\n")}\n`);
673
+ };
674
+
675
+ const restore = () => {
676
+ input.off("data", onData);
677
+ if (input.isTTY && typeof input.setRawMode === "function") input.setRawMode(false);
678
+ input.pause();
679
+ output.write(SHOW_CURSOR);
680
+ };
681
+
682
+ const finish = (value, error) => {
683
+ if (settled) return;
684
+ settled = true;
685
+ try { restore(); } catch { /* the terminal is already gone; the result still stands */ }
686
+ if (error) reject(error); else resolve(value);
687
+ };
688
+
689
+ let pending = "";
690
+ function onData(chunk) {
691
+ try {
692
+ const { intents, rest } = consumeKeys(pending + String(chunk));
693
+ pending = rest;
694
+ if (intents.length === 0) return;
695
+ for (const intent of intents) {
696
+ state = reduce(state, intent, groups);
697
+ // Stop at the first intent that ends the session. Any coalesced bytes
698
+ // after the selection are deliberately discarded, so a buffered
699
+ // Enter cannot answer the command's next confirmation prompt.
700
+ if (state.chosen) return finish(state.chosen);
701
+ if (state.done) return finish(null);
702
+ }
703
+ draw();
704
+ } catch (error) {
705
+ finish(null, error);
706
+ }
707
+ }
708
+
709
+ try {
710
+ if (input.isTTY && typeof input.setRawMode === "function") input.setRawMode(true);
711
+ input.resume();
712
+ input.setEncoding("utf8");
713
+ output.write(HIDE_CURSOR);
714
+ input.on("data", onData);
715
+ draw();
716
+ if (status && typeof status.then === "function") {
717
+ Promise.resolve(status)
718
+ .then((value) => {
719
+ if (settled) return;
720
+ remoteStatus = value;
721
+ draw();
722
+ })
723
+ .catch(() => {
724
+ if (settled) return;
725
+ remoteStatus = { unavailable: true };
726
+ draw();
727
+ });
728
+ }
729
+ } catch (error) {
730
+ finish(null, error);
731
+ }
732
+ });
733
+ }