passcontrol 0.7.2 → 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.
@@ -7,13 +7,26 @@ import path from "node:path";
7
7
  import { createInterface } from "node:readline/promises";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { ed25519 } from "@noble/curves/ed25519";
10
+ import { availableGroups, browse, printStatic, updateRecents } from "../cli/menu.mjs";
11
+ import {
12
+ agentStateArgv,
13
+ collectMenuRemoteStatus,
14
+ integrationPreviewArgv,
15
+ killSwitchArgv,
16
+ logsArgv,
17
+ verificationArgv,
18
+ } from "../cli/menu-session.mjs";
10
19
  import {
11
20
  CLOUD_GATEWAY,
12
21
  CONFIG_FILE,
13
22
  OPENAI_SHAPE_PROVIDERS,
14
23
  PROVIDERS,
15
24
  WORKSPACE_IMPORT_MAX_VERSION,
25
+ accent,
26
+ alarm,
27
+ amber,
16
28
  assertConfigLoaded,
29
+ bareGatewayOrigin,
17
30
  config,
18
31
  configPathLabel,
19
32
  defaultModelForProvider,
@@ -22,6 +35,8 @@ import {
22
35
  formatChallengeError,
23
36
  formatProxyError,
24
37
  globalConfigPath,
38
+ mergeConfigFile,
39
+ muted,
25
40
  heading,
26
41
  ok,
27
42
  redact,
@@ -45,6 +60,7 @@ import {
45
60
  } from "../cli/mcp/integration.mjs";
46
61
  import {
47
62
  GUI_PRESET_LABELS,
63
+ INTEGRATIONS,
48
64
  integrationChoices,
49
65
  isGuiPreset,
50
66
  isIntegration,
@@ -53,14 +69,23 @@ import {
53
69
  import { importCompletionMessage, noAgentCreateMessage } from "../cli/workspace-import-report.mjs";
54
70
  import { checkForUpdate } from "../cli/update-check.mjs";
55
71
  import { startSidecar } from "../cli/sidecar.mjs";
72
+ import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
56
73
  import { loginCommand } from "../cli/login.mjs";
74
+ import { logoutCommand } from "../cli/logout.mjs";
75
+ import { proveItWorks } from "../cli/selftest.mjs";
57
76
  import {
58
77
  checkIssuerPublishesKey,
59
78
  generateInstanceKey,
60
79
  instanceKidFromSeed,
61
80
  } from "../cli/instance-key.mjs";
62
- import { FAILURE_REASONS, verifyAgentToken, verifyReceipt } from "../cli/verify.mjs";
81
+ import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifyStatement } from "../cli/verify.mjs";
63
82
  import { compareProtocolSets } from "../cli/protocols.mjs";
83
+ import {
84
+ PASSPORT_KEY_STORAGE_OS,
85
+ createPassportCredentialStore,
86
+ keyStorageDeclaration,
87
+ migratePassportKey,
88
+ } from "../cli/passport-key-store.mjs";
64
89
 
65
90
  const b64url = (bytes) =>
66
91
  Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -75,14 +100,6 @@ const CLI_VERSION = (() => {
75
100
  }
76
101
  })();
77
102
 
78
- // Fixed demo credentials for `passcontrol try` — LOCAL demo stack ONLY. The demo
79
- // passport can only ever reach the keyless `demo` provider (no real key, no cost,
80
- // no real upstream); the demo provider + these seeds exist only when the stack is
81
- // brought up with PASSCONTROL_DEMO=1. Hardcoding them is safe, like the seeded dev
82
- // password — they grant nothing in a real deployment.
83
- // App-side source of truth: lib/demo/identity.ts (duplicated here to keep the shipped plain-ESM CLI transpilation-free).
84
- const DEMO_PASSPORT_ID = "kZCFp7d2x4VDruiulJ21gogYbczBDAGZa-OuwR3qgh8";
85
- const DEMO_PASSPORT_SECRET = "XqsVuXtmWiu6bKEmmqov2Q2TwkOVdzlZMWR-NWubSKo";
86
103
  const DEMO_API_KEY = "pc_demolocaltrydemolocaltrydemolocaltry0000";
87
104
  const DASHBOARD_STATE_FILE = "local-dashboard.json";
88
105
  const APP_STATE_FILE = "app.json";
@@ -147,13 +164,13 @@ function usage() {
147
164
  Governed identity and credentials for AI agents.
148
165
 
149
166
  ${heading("Usage:")}
150
- ${cmd} show cockpit status
167
+ ${cmd} browse the commands (shows status when not a terminal)
168
+ ${cmd} settings browse the commands
151
169
  ${cmd} <command> [options]
152
170
 
153
171
  ${heading("Quick start")}
154
172
  Cloud. No Docker, no database — this CLI is the only thing you install.
155
173
  ${cmd} login [--project] sign in through your browser and set this machine up
156
- ${cmd} try run the 60-second keyless guided demo
157
174
  ${cmd} call "hi" mint a visa and make a governed model call
158
175
  ${cmd} mcp passport identity for Claude Desktop, Cursor, Claude Code
159
176
  ${cmd} sidecar [--port 8788] [--allow-connect host[,host]]
@@ -165,11 +182,13 @@ ${heading("Operate")}
165
182
  ${cmd} version [--json] CLI, gateway and database schema versions
166
183
  ${cmd} doctor [--deep] [--fix] diagnose setup and repair a stopped dashboard
167
184
  ${cmd} open open the Control Tower in a browser
185
+ ${cmd} logout [--revoke-agent] revoke this machine's key and clear its credentials
168
186
  ${cmd} init [--global] configure by hand, without a browser
169
187
 
170
188
  ${heading("Manage")}
171
189
  ${cmd} agent list [--json] list agents
172
- ${cmd} agent create <name> create an agent passport
190
+ ${cmd} agent create <name> [--write]
191
+ create an agent passport (--write saves it here)
173
192
  ${cmd} agent rotate <id> [--grace <seconds>]
174
193
  rotate locally and reveal the new secret once
175
194
  ${cmd} agent suspend <id> suspend an agent
@@ -180,6 +199,8 @@ ${heading("Manage")}
180
199
  show operator audit history
181
200
  ${cmd} logs [--limit 20] [--json]
182
201
  show governed call logs
202
+ ${cmd} statements [--limit 20] [--json]
203
+ show the chain of signed spend statements
183
204
  ${cmd} kill on|off toggle the tenant kill switch
184
205
  ${cmd} export [--out FILE] save a workspace configuration snapshot
185
206
  ${cmd} import <file> [--confirm IMPORT]
@@ -192,6 +213,8 @@ ${heading("Integrate")}
192
213
  integrations: ${integrationChoices()}
193
214
 
194
215
  ${heading("Trust")}
216
+ ${cmd} key status show the local passport key storage tier
217
+ ${cmd} key migrate move a tier 0 file key into the OS credential store
195
218
  ${cmd} keygen instance create the receipt-signing key
196
219
  ${cmd} verify receipt <jws> --issuer <origin>
197
220
  verify a signed call receipt
@@ -228,6 +251,7 @@ function agentUsage() {
228
251
  ${heading("Usage:")}
229
252
  ${cmd} agent list
230
253
  ${cmd} agent create <name> [--provider <provider>] [--scope <model-pattern>]
254
+ [--write [--project] [--force]]
231
255
  ${cmd} agent rotate <id> [--grace <seconds>]
232
256
  ${cmd} agent suspend <id>
233
257
  ${cmd} agent resume <id>
@@ -235,6 +259,7 @@ ${heading("Usage:")}
235
259
 
236
260
  ${heading("Examples")}
237
261
  ${cmd} agent create prod-summarizer --provider anthropic --scope 'claude-*'
262
+ ${cmd} agent create this-box --write # save the passport here, never print it
238
263
  ${cmd} agent rotate <id> --grace 3600
239
264
  ${cmd} agent suspend <id>
240
265
 
@@ -270,8 +295,10 @@ async function fetchWithTimeout(url, init = {}, timeoutMs = 1200) {
270
295
 
271
296
  async function gatewayStatus(noNetwork = false) {
272
297
  if (noNetwork) return { label: "not checked", ok: null };
298
+ const origin = probeGatewayOrigin(config);
299
+ if (!origin) return { label: "invalid configuration", ok: false };
273
300
  try {
274
- const res = await fetchWithTimeout(config.gateway, { method: "GET" });
301
+ const res = await fetchWithTimeout(origin, { method: "GET" });
275
302
  return { label: res.ok ? `online (${res.status})` : `unhealthy (${res.status})`, ok: res.ok };
276
303
  } catch {
277
304
  return { label: "offline or unreachable", ok: false };
@@ -280,7 +307,9 @@ async function gatewayStatus(noNetwork = false) {
280
307
 
281
308
  async function printCockpit({ noNetwork = false, json = false } = {}) {
282
309
  const gateway = await gatewayStatus(noNetwork);
283
- const passportConfigured = Boolean(config.passportId && config.passportSecret);
310
+ const passportSecret = config.passportSecret;
311
+ const passportStorage = config.passportStorage;
312
+ const passportConfigured = Boolean(config.passportId && passportSecret);
284
313
  const adminConfigured = Boolean(config.apiKey);
285
314
  const dashboard = dashboardStatusLabel(gateway, noNetwork);
286
315
  const app = appRootLabel();
@@ -301,6 +330,9 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
301
330
  provider: config.provider,
302
331
  model: config.model,
303
332
  passport_configured: passportConfigured,
333
+ passport_key_storage_tier: passportStorage.tier,
334
+ passport_key_storage_source: passportStorage.source,
335
+ passport_key_storage_fallback: passportStorage.fallback,
304
336
  control_api_key_configured: adminConfigured,
305
337
  },
306
338
  system_health: systemHealthForJson(systemHealth),
@@ -316,6 +348,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
316
348
  console.log(formatLabel("Provider", config.provider));
317
349
  console.log(formatLabel("Model", config.model));
318
350
  console.log(formatLabel("Passport", passportConfigured ? redact(config.passportId) : "missing"));
351
+ console.log(formatLabel("Key storage", passportStorage.message));
319
352
  console.log(formatLabel("Admin key", adminConfigured ? redact(config.apiKey, 6) : "missing"));
320
353
  console.log(formatLabel("System health", systemHealthLabel(systemHealth)));
321
354
  console.log(`${formatLabel("Sidecar", `foreground command (\`${cliCommand("sidecar")}\`)`)}\n`);
@@ -878,14 +911,29 @@ async function waitForPortRelease(port, timeoutMs = 5000) {
878
911
  return !await portIsListening(port);
879
912
  }
880
913
 
881
- async function waitForGateway(timeoutMs = 30000) {
882
- const deadline = Date.now() + timeoutMs;
883
- while (Date.now() < deadline) {
884
- const gateway = await gatewayStatus(false);
885
- if (gateway.ok) return true;
886
- await pause(250);
887
- }
888
- return false;
914
+ /**
915
+ * Adapter over cli/gateway-wait.mjs — that module owns the decision, this
916
+ * supplies the three real probes. `port` and `pid` are optional because one
917
+ * caller (an already-running dashboard we did not spawn) knows the pid but the
918
+ * budget logic is the same either way.
919
+ */
920
+ async function waitForGateway({ port = null, pid = null } = {}) {
921
+ return awaitGateway({
922
+ probeGateway: async () => (await gatewayStatus(false)).ok,
923
+ probePort: port ? () => portIsListening(port) : null,
924
+ processAlive: pid
925
+ ? () => {
926
+ try {
927
+ process.kill(pid, 0);
928
+ return true;
929
+ } catch {
930
+ return false;
931
+ }
932
+ }
933
+ : null,
934
+ onCompiling: () =>
935
+ step("server is up and compiling — first run only, this can take a couple of minutes…"),
936
+ });
889
937
  }
890
938
 
891
939
  function ownSupabaseDatabaseIsRunning(offset = 0) {
@@ -980,7 +1028,7 @@ async function startDashboard(opts = {}) {
980
1028
  const running = runningManagedDashboard();
981
1029
  if (running) {
982
1030
  step(`dashboard is still starting (PID ${running.pid}); waiting for ${dashboard.url}…`);
983
- if (await waitForGateway()) {
1031
+ if (await waitForGateway({ port: dashboard.port, pid: running.pid })) {
984
1032
  ok(`dashboard online at ${dashboard.url}`);
985
1033
  return dashboard;
986
1034
  }
@@ -1006,7 +1054,7 @@ async function startDashboard(opts = {}) {
1006
1054
  );
1007
1055
 
1008
1056
  step(`starting local dashboard at ${dashboard.url}…`);
1009
- if (!await waitForGateway()) {
1057
+ if (!await waitForGateway({ port: dashboard.port, pid: child.pid })) {
1010
1058
  throw new Error(`Dashboard did not become ready. See ${logPath}.`);
1011
1059
  }
1012
1060
  ok(`dashboard online at ${dashboard.url}`);
@@ -1257,10 +1305,24 @@ async function initCommand(opts) {
1257
1305
  const provider = await ask("Provider", config.provider || "anthropic");
1258
1306
  assertProvider(provider);
1259
1307
  const modelFallback = provider === config.provider ? config.model : defaultModelForProvider(provider);
1308
+ const gatewayInput = await ask("Gateway URL", config.gateway);
1309
+ const passportIdInput = await ask("Passport ID", config.passportId);
1310
+ // Never use a passport secret as ask()'s fallback: fallbacks are rendered
1311
+ // inside square brackets, which would print a Keychain-retrieved key. A
1312
+ // blank answer preserves the current key silently. For Tier 1 that means
1313
+ // preserving only the non-secret marker; the key stays in the OS store.
1314
+ const passportSecretInput = await ask(
1315
+ "Passport Secret (input is visible; leave blank to keep current)"
1316
+ );
1317
+ const preserveOsStorage =
1318
+ !passportSecretInput && config.passportStorageMarker === PASSPORT_KEY_STORAGE_OS;
1260
1319
  const values = {
1261
- PASSCONTROL_GATEWAY: await ask("Gateway URL", config.gateway),
1262
- PASSPORT_ID: await ask("Passport ID", config.passportId),
1263
- PASSPORT_SECRET: await ask("Passport Secret (input is visible)", config.passportSecret),
1320
+ PASSCONTROL_GATEWAY: gatewayInput,
1321
+ PASSPORT_ID: passportIdInput,
1322
+ PASSPORT_SECRET: preserveOsStorage
1323
+ ? ""
1324
+ : passportSecretInput || config.passportSecret,
1325
+ PASSPORT_KEY_STORAGE: preserveOsStorage ? PASSPORT_KEY_STORAGE_OS : "",
1264
1326
  PASSCONTROL_API_KEY: await ask("Control API key (optional, input is visible)", config.apiKey),
1265
1327
  PROVIDER: provider,
1266
1328
  MODEL: await ask("Model", modelFallback),
@@ -1279,8 +1341,15 @@ async function initCommand(opts) {
1279
1341
  // covers every minting caller, `doctor --deep` and `try` included.
1280
1342
  async function mintVisa(current = config) {
1281
1343
  const origin = requirePassportGateway(current);
1282
- const { passportId, passportSecret } = requirePassport(current);
1283
- const payloadObj = { passport_id: passportId, ts: Date.now(), nonce: crypto.randomUUID() };
1344
+ const { passportId, passportSecret, keyStorage } = requirePassport(current);
1345
+ const payloadObj = {
1346
+ passport_id: passportId,
1347
+ ts: Date.now(),
1348
+ nonce: crypto.randomUUID(),
1349
+ // Declared, never checked: see lib/passport-key-storage.ts. Inside the
1350
+ // signed bytes so the claim belongs to whoever holds the key.
1351
+ ...(keyStorage ? { key_storage: keyStorage } : {}),
1352
+ };
1284
1353
  const payload = b64url(new TextEncoder().encode(JSON.stringify(payloadObj)));
1285
1354
  const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
1286
1355
  const res = await fetch(`${origin}/api/auth/challenge`, {
@@ -1370,111 +1439,6 @@ async function callCommand(rest, opts) {
1370
1439
  ok("done - check the dashboard audit log + spend for this call.");
1371
1440
  }
1372
1441
 
1373
- // `passcontrol try` — the 60-second, no-key, no-accounts experience. Uses the
1374
- // seeded demo passport (demo scope only) to make a GOVERNED call through the
1375
- // keyless `demo` provider, then arms the kill switch to show the same call
1376
- // blocked. Everything is real (visa, scope, budget, kill) except the model.
1377
- async function tryCommand() {
1378
- // Covers the demo proxy call AND the kill-switch PUT below, which builds its
1379
- // own control-plane URL rather than going through the guarded `api()`.
1380
- const gateway = requirePassportGateway(config);
1381
- const demo = { gateway, passportId: DEMO_PASSPORT_ID, passportSecret: DEMO_PASSPORT_SECRET };
1382
-
1383
- const demoCall = async () => {
1384
- const { visa } = await mintVisa(demo);
1385
- return fetch(`${gateway}/api/v1/demo/chat/completions`, {
1386
- method: "POST",
1387
- headers: { "content-type": "application/json", authorization: `Bearer ${visa}` },
1388
- body: JSON.stringify({
1389
- model: "demo-1",
1390
- max_tokens: 64,
1391
- messages: [{ role: "user", content: "Say hi in exactly three words" }],
1392
- }),
1393
- });
1394
- };
1395
- const setKill = async (armed) => {
1396
- const res = await fetch(`${gateway}/api/control/v1/kill-switch`, {
1397
- method: "PUT",
1398
- headers: {
1399
- "content-type": "application/json",
1400
- authorization: `Bearer ${DEMO_API_KEY}`,
1401
- "idempotency-key": crypto.randomUUID(),
1402
- },
1403
- body: JSON.stringify({ armed }),
1404
- });
1405
- if (!res.ok) throw new Error(`kill-switch ${armed ? "on" : "off"} → ${res.status} ${await res.text()}`);
1406
- };
1407
-
1408
- console.log(`${heading("PassControl — 60-second try (no provider key, no accounts)")}\n`);
1409
- step(`gateway: ${gateway}`);
1410
-
1411
- // 1. Governed, keyless call.
1412
- let res;
1413
- try {
1414
- res = await demoCall();
1415
- } catch (e) {
1416
- const msg = e?.message || String(e);
1417
- if (/unknown_passport|Challenge failed|challenge/i.test(msg)) {
1418
- // Gateway reachable, but the demo passport isn't seeded in ITS database.
1419
- fail(`The gateway is up, but the demo passport isn't seeded here (${msg}).`);
1420
- step("Seed + enable the demo on this stack:");
1421
- step(" PASSCONTROL_DEMO=1 npm run dev:stack # seeds the demo passport + control key");
1422
- step(" PASSCONTROL_DEMO=1 npm run dev:docker # enables the keyless demo provider");
1423
- } else {
1424
- fail(`Could not reach the gateway at ${gateway} (${msg}).`);
1425
- step(`Nothing installed yet? The same pipeline runs keyless in your browser: ${HOSTED_DEMO_URL}`);
1426
- step("To run it here instead, bring the local demo stack up first:");
1427
- step(" PASSCONTROL_DEMO=1 npm run dev:stack # Supabase + Redis + migrate + seed the demo passport");
1428
- step(" PASSCONTROL_DEMO=1 npm run dev:docker # start the gateway with the demo provider enabled");
1429
- }
1430
- process.exitCode = 1;
1431
- return;
1432
- }
1433
- if (res.status === 404) {
1434
- fail("The demo provider is not enabled on this gateway.");
1435
- step("Start it with PASSCONTROL_DEMO=1 (e.g. `PASSCONTROL_DEMO=1 npm run dev:docker`).");
1436
- process.exitCode = 1;
1437
- return;
1438
- }
1439
- if (res.status === 401 || res.status === 403) {
1440
- fail(`Demo passport not accepted (${res.status}). Re-seed the demo stack: PASSCONTROL_DEMO=1 npm run seed`);
1441
- process.exitCode = 1;
1442
- return;
1443
- }
1444
- if (!res.ok) {
1445
- fail(`Unexpected ${res.status}: ${await res.text()}`);
1446
- process.exitCode = 1;
1447
- return;
1448
- }
1449
-
1450
- const json = await res.json().catch(() => ({}));
1451
- const text = json?.choices?.[0]?.message?.content ?? JSON.stringify(json);
1452
- const usage = json?.usage ?? {};
1453
- ok("Governed keyless call succeeded — the passport signed the challenge, the gateway issued a short-lived visa and enforced scope + budget, and no key was needed:");
1454
- console.log(`\n ${text}\n`);
1455
- step(`tokens: ${usage.total_tokens ?? "?"} (prompt ${usage.prompt_tokens ?? "?"} + completion ${usage.completion_tokens ?? "?"})`);
1456
-
1457
- // 2. Kill switch blocks the very next call.
1458
- console.log("");
1459
- step("arming the kill switch…");
1460
- await setKill(true);
1461
- try {
1462
- const blocked = await demoCall();
1463
- if (blocked.status === 403) {
1464
- ok(`Kill switch works — the same call is now ${blocked.status} blocked_suspended.`);
1465
- } else {
1466
- fail(`Expected 403 after arming the kill switch, got ${blocked.status}.`);
1467
- }
1468
- } finally {
1469
- await setKill(false);
1470
- step("kill switch disarmed.");
1471
- }
1472
-
1473
- console.log("");
1474
- ok("That's PassControl: cryptographic identity → short-lived visa → governed call → instant kill. The provider key never touched the agent.");
1475
- step("Next: add a real provider key in the Control Tower and re-point your agent at the gateway (see the README).");
1476
- }
1477
-
1478
1442
  async function api(method, pathPart, body, { timeoutMs } = {}) {
1479
1443
  // Destination first, key second — same order and same reason as the SDK's
1480
1444
  // ControlClient. `config.gateway` is whatever PASSCONTROL_GATEWAY said, and
@@ -1567,10 +1531,43 @@ async function agentCommand(rest, opts) {
1567
1531
  scopes: [{ provider, models: [scopeModel] }],
1568
1532
  });
1569
1533
  ok(`created agent ${created.id} (${created.name})`);
1534
+
1535
+ // --write puts the passport somewhere durable INSTEAD of on the terminal.
1536
+ // Ordering matters: the file is written before anything is printed, so a
1537
+ // failure to write can still fall through to printing. The reverse — print
1538
+ // suppressed, write failed — loses the key permanently.
1539
+ if (opts.write) {
1540
+ const target = opts.project ? path.join(process.cwd(), CONFIG_FILE) : globalConfigPath();
1541
+ // Refuse rather than prompt. This command is run non-interactively (CI,
1542
+ // provisioning scripts) at least as often as by hand, and PassControl has
1543
+ // no copy of whatever is already in that file — an overwrite is not
1544
+ // undoable by us or by anyone.
1545
+ const existing = fs.existsSync(target) ? fs.readFileSync(target, "utf8") : "";
1546
+ if (/^PASSPORT_SECRET=(.+)$/mu.exec(existing)?.[1]?.trim() && !opts.force) {
1547
+ throw new Error(
1548
+ `${target} already holds a passport secret, and PassControl has no copy of it.\n` +
1549
+ " Re-run with --force to replace it, or without --write to print the new one instead."
1550
+ );
1551
+ }
1552
+ mergeConfigFile(target, {
1553
+ PASSPORT_ID: passportId,
1554
+ PASSPORT_SECRET: b64url(priv),
1555
+ PASSPORT_KEY_STORAGE: "",
1556
+ });
1557
+ ok(`wrote the passport to ${target} — it was not printed`);
1558
+ break;
1559
+ }
1560
+
1570
1561
  step("Store these - the secret is shown once and is the agent's passport:");
1571
1562
  console.log(` PASSPORT_ID=${passportId}`);
1572
1563
  console.log(` PASSPORT_SECRET=${b64url(priv)}`);
1573
- step("Paste them into .passcontrol, then run `passcontrol call \"hi\"`.");
1564
+ // The paste is the fallback, not the lesson. Copying a private key between
1565
+ // a browser, a clipboard and a file is how a passport secret once ended up
1566
+ // in a Hermes `api_key` field — and for a second machine it is not even
1567
+ // necessary: `login` there mints its own passport and copies nothing.
1568
+ step("Running this agent on ANOTHER machine? Run `passcontrol login` there instead —");
1569
+ step("it creates its own passport locally and no secret is ever copied.");
1570
+ step("Otherwise store the secret like a password, or re-run with --write to save it here.");
1574
1571
  break;
1575
1572
  }
1576
1573
  case "suspend":
@@ -1621,6 +1618,10 @@ async function agentCommand(rest, opts) {
1621
1618
  ? `The OLD key keeps working until ${until}. Both keys authenticate until then — deploy the new one before it passes.`
1622
1619
  : "The old key stops working immediately."
1623
1620
  );
1621
+ // No --write here, deliberately: see the note above the reveal. What this
1622
+ // CAN say is that a machine you control does not need the rotation at all.
1623
+ step("Rotating only to set up a new machine? `passcontrol login` there creates its own");
1624
+ step("passport instead, and leaves this one working everywhere it already runs.");
1624
1625
  break;
1625
1626
  }
1626
1627
  default:
@@ -1669,6 +1670,7 @@ async function logsCommand(opts) {
1669
1670
  controlPath("/logs", {
1670
1671
  limit: safeLimit(opts.limit),
1671
1672
  agent_id: opts.agentId,
1673
+ class: opts.class,
1672
1674
  status: opts.status,
1673
1675
  })
1674
1676
  );
@@ -1717,11 +1719,12 @@ async function sidecarCommand(rest, opts) {
1717
1719
  // sidecar mints on demand for the lifetime of the process, so a bad
1718
1720
  // destination has to be refused at start, not at the first proxied request.
1719
1721
  const gateway = requirePassportGateway(config);
1720
- const { passportId, passportSecret } = requirePassport(config);
1722
+ const { passportId, passportSecret, keyStorage } = requirePassport(config);
1721
1723
  startSidecar({
1722
1724
  gateway,
1723
1725
  passportId,
1724
1726
  passportSecret,
1727
+ keyStorage,
1725
1728
  port: sidecarPort(opts),
1726
1729
  host: String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1"),
1727
1730
  // Named on the command line, never inferred. A sidecar reachable off-host
@@ -1750,9 +1753,9 @@ async function sidecarCommand(rest, opts) {
1750
1753
 
1751
1754
  async function mcpCommand() {
1752
1755
  const gateway = requirePassportGateway(config);
1753
- const { passportId, passportSecret } = requirePassport(config);
1756
+ const { passportId, passportSecret, keyStorage } = requirePassport(config);
1754
1757
  const { startMcpServer } = await import("../cli/mcp/server.mjs");
1755
- await startMcpServer({ gateway, passportId, passportSecret });
1758
+ await startMcpServer({ gateway, passportId, passportSecret, keyStorage });
1756
1759
  }
1757
1760
 
1758
1761
  function sidecarPort(opts = {}) {
@@ -2150,14 +2153,25 @@ async function doctorCommand(opts = {}) {
2150
2153
  printSystemHealthDiagnostic(await fetchSystemHealth());
2151
2154
  await runLocalPrerequisiteChecks({ report: true });
2152
2155
  if (config.passportId && config.passportSecret) {
2153
- try {
2154
- const visa = await mintVisa(config);
2155
- ok(`Visa mint works (expires in ${visa.expires_in ?? 300}s)`);
2156
- } catch (error) {
2157
- fail(`Visa mint failed: ${error.message}`);
2158
- }
2156
+ // The whole chain, not just the mint. "Visa mint works" proves the passport
2157
+ // authenticates and says nothing about scope, budget, the proxy or receipts —
2158
+ // so the most useful diagnostic in the tool was the one thing `login` already
2159
+ // did better. Shared implementation (cli/selftest.mjs) rather than a second
2160
+ // copy, because two copies of a five-leg check drift.
2161
+ const proof = await proveItWorks({
2162
+ origin: requirePassportGateway(config),
2163
+ passportId: config.passportId,
2164
+ passportSecret: config.passportSecret,
2165
+ keyStorage: keyStorageDeclaration(config.passportStorage),
2166
+ apiKey: config.apiKey,
2167
+ fetchImpl: fetch,
2168
+ });
2169
+ if (proof.receipt === "verified") ok("End to end: governed call made, receipt verified");
2170
+ else if (proof.call) step("Governed call works; its receipt was not verified (see above)");
2171
+ else if (proof.visa) step("Passport authenticates; no governed call was possible here");
2172
+ else fail("Passport could not authenticate — see the reason above");
2159
2173
  } else {
2160
- step("Skipping visa mint check: no passport configured.");
2174
+ step("Skipping the end-to-end check: no passport configured.");
2161
2175
  }
2162
2176
 
2163
2177
  if (config.apiKey) {
@@ -2215,10 +2229,11 @@ async function verifyCommand(rest, opts) {
2215
2229
  const artifact = rest[1];
2216
2230
  const issuer = String(opts.issuer || process.env.PASSCONTROL_ISSUER || "");
2217
2231
 
2218
- if ((what !== "token" && what !== "receipt") || !artifact) {
2232
+ if ((what !== "token" && what !== "receipt" && what !== "statement") || !artifact) {
2219
2233
  throw new Error(
2220
2234
  "Usage: passcontrol verify token <jwt> --audience <aud> --issuer <origin>\n" +
2221
- " passcontrol verify receipt <jws> --issuer <origin>"
2235
+ " passcontrol verify receipt <jws> --issuer <origin>\n" +
2236
+ " passcontrol verify statement <jws> --issuer <origin>"
2222
2237
  );
2223
2238
  }
2224
2239
  if (!issuer) {
@@ -2231,7 +2246,9 @@ async function verifyCommand(rest, opts) {
2231
2246
  const result =
2232
2247
  what === "token"
2233
2248
  ? await verifyAgentToken(artifact, { issuer, audience: String(opts.audience || "") })
2234
- : await verifyReceipt(artifact, { issuer });
2249
+ : what === "statement"
2250
+ ? await verifyStatement(artifact, { issuer })
2251
+ : await verifyReceipt(artifact, { issuer });
2235
2252
 
2236
2253
  if (!result.ok) {
2237
2254
  fail(`Not valid: ${FAILURE_REASONS[result.reason] ?? result.reason}`);
@@ -2240,8 +2257,32 @@ async function verifyCommand(rest, opts) {
2240
2257
  }
2241
2258
 
2242
2259
  const c = result.claims;
2243
- ok(what === "token" ? "Token is valid." : "Receipt is valid.");
2260
+ ok(what === "token" ? "Token is valid." : what === "statement" ? "Statement is valid." : "Receipt is valid.");
2244
2261
  step(`Issuer: ${c.iss}`);
2262
+ if (what === "statement") {
2263
+ // What this signature does and does not settle. The totals below are what
2264
+ // the issuer CLAIMED and committed to — verifying the signature proves they
2265
+ // cannot change it now, not that it was right when they computed it.
2266
+ // Recomputing `root` needs every receipt in the window, which you do not have.
2267
+ step(`Workspace: ${c.sub}`);
2268
+ step(`Statement: #${c.seq}${c.pst ? "" : " (first in this chain)"}`);
2269
+ step(
2270
+ `Window: ${new Date(c.per?.from * 1000).toISOString()} → ${new Date(c.per?.to * 1000).toISOString()}`
2271
+ );
2272
+ step(`Covers: ${c.n} of ${c.nr} logged calls · ${c.cost} µ¢`);
2273
+ if (c.nr > c.n) {
2274
+ step(` ${c.nr - c.n} call(s) carried no receipt and are NOT covered by the root.`);
2275
+ }
2276
+ if (c.unp) step(` ${c.unp} call(s) could not be priced — that cost is unknown, not zero.`);
2277
+ if (c.unk) step(` ${c.unk} call(s) have no recorded cost and no recorded reason.`);
2278
+ step(`Root: ${c.root ?? "none — this window covered no receipts"}`);
2279
+ step(`Follows: ${c.pst ?? "nothing — this is the head of the chain"}`);
2280
+ step("");
2281
+ step("This proves the issuer committed to that set of receipts at that time and");
2282
+ step("cannot change it now. It does not independently confirm the totals: that");
2283
+ step("would need every receipt in the window.");
2284
+ return;
2285
+ }
2245
2286
  step(`Passport: ${c.sub}`);
2246
2287
  if (what === "token") {
2247
2288
  step(`Audience: ${c.aud}`);
@@ -2259,6 +2300,61 @@ async function verifyCommand(rest, opts) {
2259
2300
  }
2260
2301
  }
2261
2302
 
2303
+ /**
2304
+ * The chain of signed spend statements for this workspace.
2305
+ *
2306
+ * `covered` and `rows` are shown side by side on purpose, and so are the two
2307
+ * pricing columns. A statement's honesty is in the gap between them — rows it
2308
+ * could not cover, calls nobody could price, calls whose pricing was never
2309
+ * recorded — and a table that printed only the count and the cost would quietly
2310
+ * turn "we cannot say" into "zero".
2311
+ */
2312
+ async function statementsCommand(opts) {
2313
+ // One binary serves both audiences, so this command ships everywhere while the
2314
+ // endpoint behind it exists only on a deployment that OPERATES a chain. A
2315
+ // gateway that merely verifies statements has no /statements route, and the
2316
+ // 404 that comes back is a correct answer about that gateway rather than a
2317
+ // fault — say so, instead of letting a raw HTTP error read as a broken CLI.
2318
+ let rows;
2319
+ try {
2320
+ rows = await api("GET", controlPath("/statements", { limit: safeLimit(opts.limit) }));
2321
+ } catch (e) {
2322
+ // api() formats a failure as `<status> <code> <message> (req <id>)`, so the
2323
+ // status is the leading token. Anchor on it: a 200 body that merely contains
2324
+ // "404" must not be read as a missing route.
2325
+ if (/^404\b/.test(String(e?.message || ""))) {
2326
+ step("This gateway does not operate a statement chain.");
2327
+ step("Producing statements — the nightly job, the stored chain, inclusion proofs —");
2328
+ step("is a hosted capability. Verifying one needs no account and works here:");
2329
+ step(" passcontrol verify statement <jws> --issuer <origin>");
2330
+ return;
2331
+ }
2332
+ throw e;
2333
+ }
2334
+ if (opts.json) {
2335
+ console.log(JSON.stringify(rows, null, 2));
2336
+ return;
2337
+ }
2338
+ if (!Array.isArray(rows) || rows.length === 0) {
2339
+ step("No signed statements yet. They are produced once a day, for the day before.");
2340
+ step("If this stays empty, check that the deployment sets INSTANCE_SIGNING_KEY and");
2341
+ step("that its statements cron is scheduled.");
2342
+ return;
2343
+ }
2344
+ console.table(
2345
+ rows.map((row) => ({
2346
+ seq: row.seq,
2347
+ day: String(row.period_start ?? "").slice(0, 10),
2348
+ covered: row.covered_count,
2349
+ rows: row.row_count,
2350
+ "µ¢": row.cost_microcents,
2351
+ unpriced: row.unpriced_count,
2352
+ unknown: row.unknown_pricing_count,
2353
+ chained: row.prev_digest ? "yes" : "first",
2354
+ }))
2355
+ );
2356
+ }
2357
+
2262
2358
  async function keygenCommand(rest) {
2263
2359
  const target = rest[0];
2264
2360
  if (target !== "instance") {
@@ -2280,6 +2376,66 @@ async function keygenCommand(rest) {
2280
2376
  step("JWKS max-age window, then start signing with it.");
2281
2377
  }
2282
2378
 
2379
+ function passportFileForMigration() {
2380
+ if (operatorEnv("PASSPORT_SECRET") !== undefined) {
2381
+ throw new Error(
2382
+ "PASSPORT_SECRET comes from the operator environment. Migration can remove only a tier 0 config-file key; move it into a PassControl config file first."
2383
+ );
2384
+ }
2385
+
2386
+ let source = null;
2387
+ for (const candidate of config.sources) {
2388
+ if (Object.prototype.hasOwnProperty.call(candidate.values, "PASSPORT_SECRET")) source = candidate;
2389
+ }
2390
+ const secret = String(source?.values?.PASSPORT_SECRET ?? "");
2391
+ if (!source || !secret) {
2392
+ throw new Error("No tier 0 passport key was found in a PassControl config file.");
2393
+ }
2394
+ return { path: source.path, secret };
2395
+ }
2396
+
2397
+ async function keyCommand(rest, opts = {}) {
2398
+ const subcommand = rest[0] ?? "status";
2399
+ if (subcommand === "status") {
2400
+ if (rest.length > 1) throw new Error(`Usage: ${cliCommand("key status")}`);
2401
+ assertConfigLoaded();
2402
+ const storage = config.passportStorage;
2403
+ console.log(formatLabel("Key storage", storage.message, 14));
2404
+ if (storage.fallback) warn("The OS credential store was not used; this process is using the tier 0 file key.");
2405
+ return;
2406
+ }
2407
+
2408
+ if (subcommand !== "migrate" || rest.length > 1) {
2409
+ throw new Error(`Usage: ${cliCommand("key status")}\n ${cliCommand("key migrate")}`);
2410
+ }
2411
+ if (opts.to && opts.to !== "keychain" && opts.to !== "os") {
2412
+ throw new Error("--to supports only `keychain` (the operating system credential store).");
2413
+ }
2414
+ assertConfigLoaded();
2415
+ if (config.passportStorageMarker === PASSPORT_KEY_STORAGE_OS) {
2416
+ throw new Error("This passport is already configured for tier 1 OS credential storage.");
2417
+ }
2418
+ if (!config.passportId) throw new Error("No PASSPORT_ID is configured for this passport key.");
2419
+
2420
+ const file = passportFileForMigration();
2421
+ const store = createPassportCredentialStore();
2422
+ const result = migratePassportKey({
2423
+ passportId: config.passportId,
2424
+ secret: file.secret,
2425
+ store,
2426
+ removeFileSecret: () => mergeConfigFile(file.path, {
2427
+ PASSPORT_SECRET: "",
2428
+ PASSPORT_KEY_STORAGE: PASSPORT_KEY_STORAGE_OS,
2429
+ }),
2430
+ });
2431
+
2432
+ if (!result.ok) {
2433
+ throw new Error(`${result.message} Key storage in use: tier 0 — file (${file.path}).`);
2434
+ }
2435
+ ok(result.message);
2436
+ step(`Removed PASSPORT_SECRET from ${file.path} only after verified readback.`);
2437
+ }
2438
+
2283
2439
  async function openDashboard(opts = {}) {
2284
2440
  let parsed;
2285
2441
  try {
@@ -2442,8 +2598,408 @@ function printImportReport(report, { preview }) {
2442
2598
  console.log(`\nAn agent already in the workspace is left exactly as it is — import never overwrites.`);
2443
2599
  }
2444
2600
 
2445
- async function main() {
2446
- const { opts, rest } = parseArgv(process.argv.slice(2));
2601
+ function menuLocalStatus() {
2602
+ let gateway = "invalid or unavailable";
2603
+ // `host` is what the header shows and `gateway` is what the per-item "Current:"
2604
+ // lines show, so both are kept. Dropping the scheme from the header loses
2605
+ // nothing an operator needs: bareGatewayOrigin only accepts plain HTTP for a
2606
+ // loopback host, so http ⟺ loopback ⟺ the LOCAL badge already on the line.
2607
+ let host = "";
2608
+ let loopback = false;
2609
+ try {
2610
+ gateway = bareGatewayOrigin(config.gateway);
2611
+ const url = new URL(gateway);
2612
+ host = url.host;
2613
+ loopback = LOCAL_DASHBOARD_HOSTS.has(url.hostname);
2614
+ } catch {
2615
+ // Never the configured value: a rejected gateway URL can itself carry a
2616
+ // credential. "invalid" and "not configured" are different failures and the
2617
+ // operator fixes them differently, so they are not collapsed into one word.
2618
+ host = config.gateway ? "invalid" : "not configured";
2619
+ }
2620
+ const passportReady = Boolean(config.passportId && config.passportSecret);
2621
+ const controlReady = Boolean(config.apiKey);
2622
+ const source = configPathLabel(config.sources);
2623
+ const key = config.passportStorage?.message ?? `tier ${config.passportStorage?.tier ?? "unknown"}`;
2624
+ return {
2625
+ gateway,
2626
+ host,
2627
+ loopback,
2628
+ source,
2629
+ provider: `${config.provider}/${config.model}`,
2630
+ passport: passportReady ? "ready" : "missing",
2631
+ control: controlReady ? "ready" : "missing",
2632
+ key,
2633
+ app: appRootLabel(),
2634
+ current: {
2635
+ config: source,
2636
+ provider: `${config.provider}/${config.model}`,
2637
+ account: controlReady ? "control key configured" : "control key missing",
2638
+ app: appRootLabel(),
2639
+ key,
2640
+ gateway,
2641
+ },
2642
+ };
2643
+ }
2644
+
2645
+ async function menuRemoteStatus() {
2646
+ return collectMenuRemoteStatus({
2647
+ hasApiKey: Boolean(config.apiKey),
2648
+ gatewayStatus: () => gatewayStatus(false),
2649
+ request: (pathPart, options) => api("GET", pathPart, undefined, options),
2650
+ safeText: safeHealthText,
2651
+ });
2652
+ }
2653
+
2654
+ /**
2655
+ * Status tones for the browser header. Semantic, not decorative: a green ● is a
2656
+ * working thing, a dim ○ is an absent-but-not-broken thing, an amber ! is
2657
+ * degraded, and a red × is failed. Red appears in exactly two places in this
2658
+ * whole interface — a failed row here, and the Danger zone under the cursor —
2659
+ * which is what keeps it meaning something.
2660
+ */
2661
+ const MENU_TONES = {
2662
+ ok: { glyph: "\u25cf", ink: accent },
2663
+ idle: { glyph: "\u25cb", ink: muted },
2664
+ warn: { glyph: "!", ink: amber },
2665
+ bad: { glyph: "\u00d7", ink: alarm },
2666
+ };
2667
+ const MENU_LABEL_WIDTH = 10;
2668
+ const MENU_STATE_WIDTH = 16;
2669
+
2670
+ /**
2671
+ * Fit a cell to its column, with an ellipsis when it does not.
2672
+ *
2673
+ * The state column has to hold whatever `collectMenuRemoteStatus` produces, and
2674
+ * two of its values are already longer than the column: "100+ agents (partial)"
2675
+ * on a fleet of a hundred, and any account email past sixteen characters. An
2676
+ * overlong cell does not wrap, it pushes that row's tail right of every other
2677
+ * row's and the table stops being a table. Truncating loses the end of one
2678
+ * value; not truncating loses the alignment of all of them.
2679
+ */
2680
+ function menuCell(text, width) {
2681
+ const value = String(text ?? "");
2682
+ // A truncated cell still ends in a space. Filling the column edge to edge
2683
+ // ran the ellipsis straight into the next column — "…write key" reads as one
2684
+ // mangled word rather than as two cells, which is the exact failure the
2685
+ // truncation is here to prevent.
2686
+ if (value.length <= width - 1) return value.padEnd(width);
2687
+ return `${value.slice(0, width - 2)}\u2026 `;
2688
+ }
2689
+
2690
+ function menuRow(tone, label, state, tail = "") {
2691
+ const { glyph, ink } = MENU_TONES[tone];
2692
+ // Pad the RAW strings, then colour them. padEnd counts escape bytes, so
2693
+ // colouring first pushes every later column right by the width of an
2694
+ // invisible sequence — and because only some rows are coloured, the table
2695
+ // would jitter as the cursor moved. Every padEnd here is on plain text.
2696
+ const head = ` ${ink(glyph)} ${menuCell(label, MENU_LABEL_WIDTH)}`;
2697
+ if (!tail) return `${head}${ink(state)}`;
2698
+ return `${head}${ink(menuCell(state, MENU_STATE_WIDTH))}${muted(tail)}`;
2699
+ }
2700
+
2701
+ /**
2702
+ * Shorten a gatewayStatus label to one word, with the tone it deserves.
2703
+ *
2704
+ * The HTTP code in that label is real information, but it belongs in
2705
+ * `passcontrol status`, not on a line the operator reads fifty times a day.
2706
+ * "not authenticated" maps to "not checked" rather than to a failure on
2707
+ * purpose: with no control key the menu never probes the gateway at all, so its
2708
+ * health is unknown rather than bad — and the Account row directly below is the
2709
+ * one that should explain why.
2710
+ */
2711
+ function gatewayTone(label) {
2712
+ const text = String(label ?? "");
2713
+ if (text.startsWith("online")) return ["ok", "online"];
2714
+ if (text.startsWith("unhealthy")) return ["warn", "unhealthy"];
2715
+ if (text === "not authenticated" || text === "not checked") return ["idle", "not checked"];
2716
+ if (text === "invalid configuration") return ["bad", "misconfigured"];
2717
+ return ["bad", "unreachable"];
2718
+ }
2719
+
2720
+ /**
2721
+ * Where the passport private key resolves from, as a tone and two short cells.
2722
+ *
2723
+ * The tail never carries the file path, only the word "file". The path is in
2724
+ * `passcontrol key status` and in `passcontrol status`; on the front door it is
2725
+ * an implementation detail wide enough to push the row off the screen.
2726
+ */
2727
+ function keyTone(storage) {
2728
+ if (storage?.fallback) return ["warn", "file fallback", "the OS store was unavailable"];
2729
+ if (storage?.available !== true) return ["idle", "not configured", ""];
2730
+ if (storage?.tier === 1) return ["ok", "ready", String(storage.source ?? "OS store")];
2731
+ return ["ok", "ready", "file"];
2732
+ }
2733
+
2734
+ /**
2735
+ * `PassControl <version>` on the left, a LOCAL/REMOTE badge at the right margin.
2736
+ *
2737
+ * The badge comes from the same loopback set the stack commands use, so LOCAL
2738
+ * means exactly what `passcontrol start` means by it. REMOTE rather than CLOUD:
2739
+ * a self-hosted gateway on a LAN address or a company domain is neither local
2740
+ * nor Cloud, and only one of those two words stays true for it. On a non-TTY
2741
+ * `columns` is undefined, so the badge falls back to two spaces instead of
2742
+ * padding a piped line out to a width nobody is watching.
2743
+ */
2744
+ function menuTitle(local) {
2745
+ const badge = local.loopback ? "LOCAL" : "REMOTE";
2746
+ const plain = `PassControl ${CLI_VERSION}`;
2747
+ const painted = `${heading("PassControl")} ${muted(CLI_VERSION)}`;
2748
+ const gap = (Number(process.stdout.columns) || 0) - plain.length - badge.length - 1;
2749
+ return gap > 2 ? `${painted}${" ".repeat(gap)}${muted(badge)}` : `${painted} ${muted(badge)}`;
2750
+ }
2751
+
2752
+ /**
2753
+ * The browser header: a glyph table, not a status dump.
2754
+ *
2755
+ * It answers three questions and stops — is PassControl alive, what is it
2756
+ * pointed at, and is anything wrong. The configuration path, the HTTP status
2757
+ * code, the storage tier number and the redacted identifiers that used to sit
2758
+ * here are all one keystroke away in `passcontrol status`. A front door has to
2759
+ * be readable at a glance, and a detail that is always on screen stops reading
2760
+ * as a detail.
2761
+ *
2762
+ * THE TABLE IS A FIXED HEIGHT FOR A GIVEN INSTALL, and that is a layout
2763
+ * requirement rather than a nicety. The four control-plane reads land about a
2764
+ * second after the first frame; if the rows they fill did not exist until then,
2765
+ * the whole menu below would shift down under the reader's eyes just as they
2766
+ * were choosing. So Account and Fleet are drawn as "checking…" while the reads
2767
+ * are in flight and as "unavailable" when they fail — same rows, same height,
2768
+ * only the words change. `remote` has four states and each renders: `null` in
2769
+ * flight, `false` on the static non-TTY path that makes no requests at all,
2770
+ * `{unavailable:true}` for failed reads, and an object for the answer.
2771
+ *
2772
+ * The one row that appears and disappears is the kill switch, and only into the
2773
+ * gap at the bottom: it is drawn when armed, which is an emergency worth a line
2774
+ * and a colour, and omitted when clear, which is the state that should take up
2775
+ * no room. Six rows is the ceiling, and the whole top level fits an 80x24
2776
+ * terminal with it.
2777
+ */
2778
+ function menuHeader(local, remote) {
2779
+ const pending = remote === null;
2780
+ const staticOnly = remote === false;
2781
+ const broken = Boolean(remote) && remote !== true && remote.unavailable === true;
2782
+ const live = !pending && !staticOnly && !broken ? remote : null;
2783
+ const rows = [];
2784
+
2785
+ if (pending) rows.push(menuRow("idle", "Gateway", "checking\u2026", local.host));
2786
+ else if (staticOnly) rows.push(menuRow("idle", "Gateway", "not checked", local.host));
2787
+ else if (broken) rows.push(menuRow("bad", "Gateway", "unreachable", local.host));
2788
+ else {
2789
+ const [tone, state] = gatewayTone(live.gateway);
2790
+ rows.push(menuRow(tone, "Gateway", state, local.host));
2791
+ }
2792
+
2793
+ rows.push(local.passport === "ready"
2794
+ ? menuRow("ok", "Provider", "ready", local.provider)
2795
+ : menuRow("idle", "Provider", "no passport", local.provider));
2796
+
2797
+ const [tone, state, tail] = keyTone(config.passportStorage);
2798
+ rows.push(menuRow(tone, "Key", state, tail));
2799
+
2800
+ // Everything below is a control-plane fact, so the static path ends here
2801
+ // rather than printing rows of "unknown" it never tried to look up. So does
2802
+ // an install with no control key: "no control key" on the Account row is the
2803
+ // whole explanation, and two more rows repeating it would be noise.
2804
+ if (staticOnly) return [menuTitle(local), ...rows].join("\n");
2805
+ if (local.control === "missing") {
2806
+ rows.push(menuRow("idle", "Account", "no control key"));
2807
+ return [menuTitle(local), ...rows].join("\n");
2808
+ }
2809
+
2810
+ if (pending) rows.push(menuRow("idle", "Account", "checking\u2026"));
2811
+ else if (!live || live.account === "unavailable") rows.push(menuRow("idle", "Account", "unavailable"));
2812
+ else if (live.account === null) rows.push(menuRow("idle", "Account", "not served here"));
2813
+ else {
2814
+ const [email, scope = ""] = String(live.account).split(" \u00b7 ");
2815
+ rows.push(menuRow("ok", "Account", email, scope));
2816
+ }
2817
+
2818
+ if (pending) rows.push(menuRow("idle", "Fleet", "checking\u2026"));
2819
+ else if (live && live.fleet !== "unavailable") {
2820
+ const [size, ...rest] = String(live.fleet).split(" \u00b7 ");
2821
+ rows.push(menuRow("ok", "Fleet", size, rest.join(" \u00b7 ")));
2822
+ } else rows.push(menuRow("idle", "Fleet", "unavailable"));
2823
+
2824
+ // Armed, the kill switch is the reason every call in the workspace is
2825
+ // failing, and it must not read as another grey line in a table. Clear, it is
2826
+ // the absence of an alarm and takes no row at all — `passcontrol kill` and
2827
+ // `passcontrol status` both still report it in full.
2828
+ if (live && String(live.kill).includes("armed")) {
2829
+ rows.push(menuRow("bad", "Kill", "ARMED", live.kill));
2830
+ }
2831
+
2832
+ return [menuTitle(local), ...rows].join("\n");
2833
+ }
2834
+
2835
+ async function chooseMenuOption(question, options) {
2836
+ console.log(`\n${heading(question)}`);
2837
+ options.forEach((option, index) => console.log(` ${index + 1}. ${option.label}`));
2838
+ const answer = await promptLine("Choose a number, or q to cancel: ", "q");
2839
+ if (String(answer).toLowerCase() === "q") return null;
2840
+ const index = Number(answer) - 1;
2841
+ return Number.isInteger(index) && options[index] ? options[index] : null;
2842
+ }
2843
+
2844
+ async function eligibleAgent(status) {
2845
+ const agents = await api("GET", controlPath("/agents", { status, limit: 100 }), undefined, { timeoutMs: 1200 });
2846
+ if (!Array.isArray(agents) || agents.length === 0) {
2847
+ step(`No ${status} agents are eligible.`);
2848
+ return null;
2849
+ }
2850
+ return chooseMenuOption(
2851
+ status === "active" ? "Suspend an active agent" : "Resume a suspended agent",
2852
+ agents.map((agent) => ({ value: agent.id, label: `${safeHealthText(agent.name, "unnamed")} · ${String(agent.id).slice(0, 8)}…` }))
2853
+ );
2854
+ }
2855
+
2856
+ async function guideMenuChoice(chosen) {
2857
+ switch (chosen.guide) {
2858
+ case "integration": {
2859
+ const picked = await chooseMenuOption("Preview an integration", INTEGRATIONS.map((value) => ({ value, label: value })));
2860
+ return picked ? integrationPreviewArgv(picked.value) : null; // Preview only: never append --write.
2861
+ }
2862
+ case "logs": {
2863
+ const agents = await api("GET", "/agents?limit=100", undefined, { timeoutMs: 1200 });
2864
+ const agent = await chooseMenuOption("Logs: agent", [
2865
+ { value: "", label: "All agents" },
2866
+ ...(Array.isArray(agents) ? agents.map((row) => ({ value: row.id, label: `${safeHealthText(row.name, "unnamed")} · ${String(row.id).slice(0, 8)}…` })) : []),
2867
+ ]);
2868
+ if (!agent) return null;
2869
+ const callClass = await chooseMenuOption("Logs: call class", ["all", "inference", "housekeeping"].map((value) => ({ value, label: value })));
2870
+ if (!callClass) return null;
2871
+ const status = await promptLine("Optional status filter (Enter for all): ", "");
2872
+ const limit = await chooseMenuOption("Logs: limit", [20, 50, 100].map((value) => ({ value, label: String(value) })));
2873
+ if (!limit) return null;
2874
+ return logsArgv({ agentId: agent.value, callClass: callClass.value, status, limit: limit.value });
2875
+ }
2876
+ case "verify-receipt":
2877
+ case "verify-token": {
2878
+ const type = chosen.guide === "verify-token" ? "token" : "receipt";
2879
+ const artifact = await promptLine(`${type === "token" ? "Token" : "Receipt"}: `, "");
2880
+ if (!artifact) return null;
2881
+ const issuer = await promptLine("Trusted issuer (https origin): ", process.env.PASSCONTROL_ISSUER || "");
2882
+ if (!issuer) return null;
2883
+ const audience = type === "token" ? await promptLine("Expected token audience: ", "") : "";
2884
+ if (type === "token" && !audience) return null;
2885
+ return verificationArgv({ type, artifact, issuer, audience });
2886
+ }
2887
+ case "suspend":
2888
+ case "resume": {
2889
+ const suspend = chosen.guide === "suspend";
2890
+ const picked = await eligibleAgent(suspend ? "active" : "suspended");
2891
+ if (!picked) return null;
2892
+ const confirmed = await confirmYes(`${suspend ? "Suspend" : "Resume"} ${picked.label}? [y/N] `, { default: false });
2893
+ return confirmed ? agentStateArgv({ suspend, id: picked.value }) : null;
2894
+ }
2895
+ case "kill": {
2896
+ const state = await api("GET", "/kill-switch", undefined, { timeoutMs: 1200 });
2897
+ if (state.armed) {
2898
+ const confirmed = await confirmYes("Disable the tenant kill switch? [y/N] ", { default: false });
2899
+ return killSwitchArgv({ armed: true, confirmed });
2900
+ }
2901
+ const typed = await promptLine("Type ARM to enable the tenant kill switch: ", "");
2902
+ return killSwitchArgv({ armed: false, typed });
2903
+ }
2904
+ case "key-migrate": {
2905
+ const confirmed = await confirmYes("Move the file key into the OS credential store? [y/N] ", { default: false });
2906
+ return confirmed ? ["key", "migrate"] : null;
2907
+ }
2908
+ default:
2909
+ return [...chosen.run];
2910
+ }
2911
+ }
2912
+
2913
+ async function pauseForSettings() {
2914
+ const answer = await promptLine("\nPress Enter to return to Settings, or q to quit: ", "");
2915
+ return String(answer).toLowerCase() !== "q";
2916
+ }
2917
+
2918
+ /** Drive one in-memory settings session; no arguments, artifacts, or secrets are retained. */
2919
+ /**
2920
+ * What this machine can actually do, for the groups that ask.
2921
+ *
2922
+ * `localStack` is true when a PassControl checkout resolves — the surrounding
2923
+ * repo, `PASSCONTROL_APP_ROOT`, or a remembered one. An install from npm has
2924
+ * none of those, and on that machine the Local stack commands would all fail
2925
+ * and `setup` would be an unsolicited invitation to run the server yourself.
2926
+ *
2927
+ * A THROW counts as true, not false. `resolveAppRootSource` only throws when
2928
+ * `PASSCONTROL_APP_ROOT` is set to something that is not a checkout — which is
2929
+ * an operator who has deliberately pointed at a local deployment and got the
2930
+ * path wrong. Hiding the group would take away `doctor`'s neighbours from
2931
+ * exactly the person trying to fix it. Absence of a checkout is the signal;
2932
+ * a broken pointer is a self-hoster with a typo.
2933
+ */
2934
+ function menuCapabilities() {
2935
+ try {
2936
+ return { localStack: resolveAppRootSource() !== null };
2937
+ } catch {
2938
+ return { localStack: true };
2939
+ }
2940
+ }
2941
+
2942
+ async function settingsCommand() {
2943
+ const local = menuLocalStatus();
2944
+ const staticHeader = menuHeader(local, false);
2945
+ const capabilities = menuCapabilities();
2946
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
2947
+ printStatic((text) => process.stdout.write(text), {
2948
+ header: staticHeader,
2949
+ groups: availableGroups(capabilities),
2950
+ });
2951
+ return;
2952
+ }
2953
+
2954
+ let recentIds = [];
2955
+ for (;;) {
2956
+ const chosen = await browse({
2957
+ header: (remote) => menuHeader(local, remote),
2958
+ context: local.current,
2959
+ recentIds,
2960
+ status: menuRemoteStatus(),
2961
+ capabilities,
2962
+ });
2963
+ if (!chosen) return;
2964
+
2965
+ let argv;
2966
+ if (chosen.guide) {
2967
+ // A guide only GATHERS input — its first act is a control-plane read, and
2968
+ // nothing has been written when that read fails. So the failure costs the
2969
+ // answer, not the session. Without this the error escapes settingsCommand
2970
+ // entirely and main()'s top-level catch calls process.exit(1) from inside
2971
+ // the menu: picking "Governed call logs" with the gateway down ended the
2972
+ // whole session with a bare "fetch failed". Unlike the run below, this
2973
+ // catch is NOT gated on returnToMenu — no command has run yet, so there is
2974
+ // no half-finished write for the session to end on.
2975
+ try {
2976
+ argv = await guideMenuChoice(chosen);
2977
+ } catch (error) {
2978
+ fail(error.message);
2979
+ if (!(await pauseForSettings())) return;
2980
+ continue;
2981
+ }
2982
+ } else if (chosen.needsArgs) {
2983
+ console.log(`\n ${heading("Command template — nothing was run:")}\n\n passcontrol ${chosen.detail}\n`);
2984
+ if (!(await pauseForSettings())) return;
2985
+ continue;
2986
+ } else argv = [...chosen.run];
2987
+ if (!argv) continue;
2988
+
2989
+ console.log(`\n ${heading("Running:")} passcontrol ${argv.join(" ")}\n`);
2990
+ try {
2991
+ await main(argv, { skipUpdate: true });
2992
+ } catch (error) {
2993
+ if (!chosen.returnToMenu) throw error;
2994
+ fail(error.message);
2995
+ }
2996
+ recentIds = updateRecents(recentIds, chosen);
2997
+ if (!chosen.returnToMenu || !(await pauseForSettings())) return;
2998
+ }
2999
+ }
3000
+
3001
+ async function main(argv = process.argv.slice(2), runtime = {}) {
3002
+ const { opts, rest } = parseArgv(argv);
2447
3003
  const [command, ...commandRest] = rest;
2448
3004
 
2449
3005
  // Started here and awaited at the very end, so the registry lookup overlaps
@@ -2452,7 +3008,7 @@ async function main() {
2452
3008
  // it can never turn a registry outage into a slow `passcontrol call`.
2453
3009
  // .catch() rather than try/catch: an unhandled rejection from a background
2454
3010
  // nicety must not take down a command that already did its job.
2455
- const updateNotice = checkForUpdate({
3011
+ const updateNotice = runtime.skipUpdate ? Promise.resolve(null) : checkForUpdate({
2456
3012
  current: CLI_VERSION,
2457
3013
  json: Boolean(opts.json),
2458
3014
  }).catch(() => null);
@@ -2472,7 +3028,23 @@ async function main() {
2472
3028
  return;
2473
3029
  }
2474
3030
 
3031
+ // Bare `passcontrol` opens the browser for a human at a terminal, and keeps
3032
+ // printing status for everything else. The TTY guard is what makes this safe
3033
+ // to change: scripts, CI and `cli/mcp/gateway.mjs` all reach the old
3034
+ // behaviour, because none of them is a terminal. `--json` and `--no-network`
3035
+ // are explicit requests for the status output and win over the menu.
3036
+ if (command === undefined && !opts.json && !opts.noNetwork && process.stdin.isTTY && process.stdout.isTTY) {
3037
+ await settingsCommand();
3038
+ await announceUpdate();
3039
+ return;
3040
+ }
3041
+
2475
3042
  switch (command) {
3043
+ case "settings":
3044
+ case "menu": {
3045
+ await settingsCommand();
3046
+ break;
3047
+ }
2476
3048
  case undefined:
2477
3049
  case "status":
2478
3050
  await printCockpit({ noNetwork: Boolean(opts.noNetwork), json: Boolean(opts.json) });
@@ -2482,6 +3054,9 @@ async function main() {
2482
3054
  // through startDashboard, which clones the self-host repo.
2483
3055
  await loginCommand(opts, { openUrl, promptLine, confirmYes });
2484
3056
  break;
3057
+ case "logout":
3058
+ await logoutCommand(opts, { confirmYes });
3059
+ break;
2485
3060
  case "init":
2486
3061
  await initCommand(opts);
2487
3062
  break;
@@ -2513,8 +3088,18 @@ async function main() {
2513
3088
  await callCommand(commandRest, opts);
2514
3089
  break;
2515
3090
  case "try":
2516
- await tryCommand();
2517
- break;
3091
+ // Removed, not silently dropped. `passcontrol try` is named in the help
3092
+ // text and README of every published release up to this one, so somebody
3093
+ // is following a page that still lists it. `Unknown command "try"` reads
3094
+ // as a broken install; this reads as a changelog.
3095
+ //
3096
+ // CLI_VERSION, never a typed literal — tests/site-metadata.test.ts exists
3097
+ // because advertised version strings drift the moment they are hand-written.
3098
+ throw new Error(
3099
+ `\`passcontrol try\` was removed in ${CLI_VERSION}.\n` +
3100
+ " `passcontrol login` now does the same thing with YOUR agent rather than a\n" +
3101
+ " shared demo one: a governed call and a signed receipt you can verify."
3102
+ );
2518
3103
  case "sidecar":
2519
3104
  await sidecarCommand(commandRest, opts);
2520
3105
  break;
@@ -2540,6 +3125,9 @@ async function main() {
2540
3125
  case "logs":
2541
3126
  await logsCommand(opts);
2542
3127
  break;
3128
+ case "statements":
3129
+ await statementsCommand(opts);
3130
+ break;
2543
3131
  case "kill":
2544
3132
  await killCommand(commandRest);
2545
3133
  break;
@@ -2555,6 +3143,9 @@ async function main() {
2555
3143
  case "keygen":
2556
3144
  await keygenCommand(commandRest);
2557
3145
  break;
3146
+ case "key":
3147
+ await keyCommand(commandRest, opts);
3148
+ break;
2558
3149
  case "verify":
2559
3150
  await verifyCommand(commandRest, opts);
2560
3151
  break;