passport-bridge 0.16.10 → 0.16.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +16 -7
  2. package/dist/cli.js +6 -2
  3. package/dist/cliActions.js +20 -14
  4. package/dist/cliArgs.d.ts +3 -0
  5. package/dist/cliArgs.js +50 -6
  6. package/dist/cliAsk.d.ts +28 -0
  7. package/dist/cliAsk.js +49 -0
  8. package/dist/cliAutopilotPolicy.d.ts +15 -0
  9. package/dist/cliExec.d.ts +4 -0
  10. package/dist/cliExec.js +8 -1
  11. package/dist/cliGuardState.d.ts +20 -3
  12. package/dist/cliGuardState.js +24 -12
  13. package/dist/cliHook.js +4 -2
  14. package/dist/cliHookDecide.d.ts +16 -4
  15. package/dist/cliHookDecide.js +58 -14
  16. package/dist/cliHookDeliver.d.ts +17 -1
  17. package/dist/cliHookDeliver.js +70 -19
  18. package/dist/cliHookGuard.d.ts +9 -0
  19. package/dist/cliHookGuard.js +16 -2
  20. package/dist/cliHookInstall.d.ts +2 -0
  21. package/dist/cliHookInstall.js +2 -1
  22. package/dist/cliHookStatus.js +2 -4
  23. package/dist/cliKeys.d.ts +10 -3
  24. package/dist/cliKeys.js +60 -45
  25. package/dist/cliLogin.js +5 -2
  26. package/dist/cliMain.d.ts +7 -0
  27. package/dist/cliMain.js +502 -0
  28. package/dist/cliOutput.d.ts +3 -0
  29. package/dist/cliOutput.js +115 -8
  30. package/dist/cliPolicyV2.js +53 -2
  31. package/dist/cliSuggest.d.ts +19 -0
  32. package/dist/cliSuggest.js +57 -0
  33. package/dist/cliUndo.js +3 -8
  34. package/dist/compileCache.d.ts +8 -0
  35. package/dist/compileCache.js +60 -0
  36. package/dist/execNoKey.d.ts +9 -0
  37. package/dist/execNoKey.js +25 -0
  38. package/dist/hookMain.js +7 -11
  39. package/dist/hookOutbox.d.ts +15 -2
  40. package/dist/hookOutbox.js +143 -3
  41. package/dist/initKeysStep.d.ts +1 -1
  42. package/dist/initKeysStep.js +8 -7
  43. package/dist/initOutro.js +2 -1
  44. package/dist/initUi.d.ts +7 -2
  45. package/dist/initUi.js +22 -9
  46. package/dist/passport.d.ts +1 -7
  47. package/dist/passport.js +15 -499
  48. package/dist/pluginPin.d.ts +1 -1
  49. package/dist/pluginPin.js +1 -1
  50. package/dist/version.d.ts +1 -1
  51. package/dist/version.js +1 -1
  52. package/dist/webLinks.d.ts +2 -0
  53. package/dist/webLinks.js +7 -0
  54. package/npm-shrinkwrap.json +2 -2
  55. package/package.json +1 -1
package/dist/cliOutput.js CHANGED
@@ -4,6 +4,106 @@ import { CliFailure, sanitize } from "./cliSupport.js";
4
4
  import { termOf, wrap } from "./term.js";
5
5
  import { VERSION } from "./version.js";
6
6
  const RENAMED_FLAGS = "--agent and --agents were --client and --clients; the old names still work.";
7
+ /** What each exit code means. Scripts and agents branch on these; the
8
+ * meanings never change (bridge/README.md, docs/troubleshooting.mdx). */
9
+ export const EXIT_CODES = [
10
+ [0, "Success"],
11
+ [1, "Network, timeout, or server error, or Passport couldn't be reached"],
12
+ [2, "Sign in, or pick a profile: the sign-in is missing, expired, or revoked"],
13
+ [3, "An app needs you to sign in, or Passport has no working key for it"],
14
+ [4, "Waiting for approval; the approval id is included"],
15
+ [5, "Blocked, declined, or expired: your rules, a guardrail, or a person said no"],
16
+ [6, "Usage mistake: an unknown command, option, tool, or app"]
17
+ ];
18
+ /** Each help page leads with these, after its usage line. */
19
+ const EXAMPLES = {
20
+ help: [
21
+ ["passport init", "Set up Passport for your agents"],
22
+ ["passport status", "See you, this computer, the guard, apps, and keys"],
23
+ ["passport exec -- railway up", "Run a CLI with a key Passport holds"],
24
+ ['passport rules test "railway up"', "See what Autopilot decides for a command"],
25
+ ["passport help <command>", "Every option for one command"]
26
+ ],
27
+ init: [
28
+ ["passport init", "Detect, show one plan, ask once"],
29
+ ["passport init --dry-run", "Show the plan and change nothing"],
30
+ ["passport init --yes", "Use the recommended setup without asking"]
31
+ ],
32
+ login: [
33
+ ["passport login", "Sign in through the browser"],
34
+ ["passport login --no-open", "Print the link instead of opening a browser"]
35
+ ],
36
+ status: [
37
+ ["passport status", "One screen: you, this computer, the guard, apps, keys"],
38
+ ["passport status --json", "The same as one JSON object"]
39
+ ],
40
+ wait: [
41
+ ["passport wait apr_123", "Wait up to 100 seconds for a decision"],
42
+ ["passport wait apr_123 --timeout 300", "Wait up to five minutes"]
43
+ ],
44
+ rules: [
45
+ ['passport rules test "railway up"', "What Autopilot decides, and why"],
46
+ ['passport rules test "npm run deploy" --environment staging', "The same, for Staging"]
47
+ ],
48
+ actions: [
49
+ ["passport actions", "Project scripts Passport knows"],
50
+ ["passport actions add make deploy --environment production --class change", "Tell Passport what one does"]
51
+ ],
52
+ env: [
53
+ ["passport env", "Where commands in this folder land"],
54
+ ["passport env set railway api production", "Place a resource for the workspace"]
55
+ ],
56
+ sessions: [["passport sessions --status running", "Sessions still running"]],
57
+ sync: [
58
+ ["passport sync", "Update each agent's own allowlist"],
59
+ ["passport sync --remove", "Take Passport's entries out"]
60
+ ],
61
+ exec: [
62
+ ["passport exec -- railway up", "Run it after your rules decide"],
63
+ ["passport exec --wait 120 -- gh pr merge 42", "Wait up to two minutes for an approval"]
64
+ ],
65
+ undo: [
66
+ ["passport undo --last", "Preview your newest undoable action, then ask"],
67
+ ["passport undo act_123 --yes", "Run the undo without asking"]
68
+ ],
69
+ keys: [
70
+ ["passport keys", "Keys Passport holds, and any still on this computer"],
71
+ ["passport keys move railway", "Move the Railway key into Passport"],
72
+ ["passport keys add vercel", "Store a key you paste"]
73
+ ],
74
+ scan: [
75
+ ["passport scan", "Keys your agents can reach from this folder"],
76
+ ["passport scan --check", "CI and pre-commit: exit 5 on a high or medium key"]
77
+ ],
78
+ hook: [
79
+ ["passport hook install --guard --apply", "Check each shell command before it runs"],
80
+ ["passport hook status", "Each agent's hooks and guard"]
81
+ ],
82
+ search: [['passport search "issues"', "Tools you can run that match"]],
83
+ describe: [["passport describe github_search_issues", "One tool's parameters"]],
84
+ run: [['passport run github_search_issues \'{"query":"SSO"}\'', "Run a tool through your rules"]],
85
+ connect: [["passport connect github --wait 120", "Sign in to an app and wait for it"]],
86
+ completion: [["passport completion zsh", "Print zsh completion"]]
87
+ };
88
+ /** Past this, each example in the block gets its own line, with what it does under it. */
89
+ const EXAMPLE_COLUMN = 40;
90
+ function exampleLines(examples) {
91
+ const width = Math.max(...examples.map(([command]) => command.length));
92
+ return [
93
+ "Examples:",
94
+ ...examples.map(([command, what]) => width > EXAMPLE_COLUMN ? ` ${command}\n ${what}` : ` ${command.padEnd(width)} ${what}`)
95
+ ].join("\n");
96
+ }
97
+ /** A verb's page: its usage lines, then examples, then the rest. */
98
+ function withExamples(page, examples) {
99
+ if (!examples?.length)
100
+ return page;
101
+ const lines = page.split("\n");
102
+ let usage = 0;
103
+ while (usage < lines.length && /^(?:sudo )?(?:passport|npx) /.test(lines[usage]))
104
+ usage++;
105
+ return [...lines.slice(0, usage), "", exampleLines(examples), "", ...lines.slice(usage)].join("\n");
106
+ }
7
107
  function helpText(verb) {
8
108
  const details = {
9
109
  init: 'passport init [--yes] [--dry-run] [--move-keys] [--no-open] [--cloud <origin>] [--skip-apps] [--skip-agents] [--skip-guard] [--verbose] [--json]\nnpx passport-bridge@latest init [same options]\nSets up Passport in one pass: scans for keys your agents can reach, signs you in (or up), then shows one plan before changing anything: the apps it connects, the agents it adds Passport to, the guard for shell commands, how much agents can do on their own (Autopilot), every file it edits (each backed up first), and what stays as it is. One question applies it; n goes step by step. Run it again any time: finished steps are left as they are, and with nothing to change it asks nothing.\n --yes use the recommended setup without asking (needed without a terminal); never waits for app sign-ins; CLI keys stay on this computer\n --dry-run show the plan and change nothing\n --move-keys also move CLI keys into Passport and sign those CLIs out\n --no-open print links instead of opening a browser\n --cloud <url> a self-hosted Passport\n --skip-apps, --skip-agents, --skip-guard leave that step out\n --verbose show the full scan\n --json with --yes: one JSON summary with each step\'s status and the plan; without --yes: the plan only\nUndo: passport hook uninstall --agent <agent> --apply, then remove the "passport" entry from each agent.',
@@ -20,7 +120,7 @@ function helpText(verb) {
20
120
  sessions: "passport sessions [--status running|idle|ended]\nLists your agents' recent sessions with what Passport decided: ran, asked, and blocked.\nJSON: {sessions:[{id,client,folder,status,startedAt,lastActivityAt,counts,environments,waiting}],nextCursor}",
21
121
  exec: "passport exec [--wait <sec>] [--ask-again] [--verbose] [--mask | --no-masking] -- <cli> [args…]\nRuns railway, gh, vercel, wrangler, supabase, stripe, aws, neonctl, or flyctl with a key Passport holds, after your Autopilot rules decide. The key reaches only that command's environment, short-lived where the vendor allows (GitHub App tokens, 15-minute AWS sessions, 15-minute Cloudflare tokens). The exit code passes through unchanged.\n Output: when stdout isn't a terminal (an agent's shell, a pipe, a log), any copy of the key the CLI prints (raw, base64, or URL-encoded) reads <hidden by Passport>, since that output is kept and read later. In a terminal the CLI gets the terminal itself (colors, prompts), unmasked.\n --mask hide the key in a terminal too (the CLI then writes to a pipe)\n --no-masking never hide it (PASSPORT_EXEC_NO_MASKING=1 does the same through a shim)\n Asks: waits for your approval in Passport when you're at the keyboard or with --wait; otherwise exits 4 with the approval id. Run passport wait <id>, then the command again.\n Blocked or declined: exit 5 with the reason. A decline answers the same command for ten minutes; --ask-again requests it again.\n No key in Passport, or it stopped working: exit 3.\n Offline: nothing runs (exit 1); exec never uses a key on this computer.\n Refuses shells, env, and subcommands that would print the key or run another program with it.\n --verbose say which key was issued (on stderr)",
22
122
  undo: "passport undo <action-id> [--option <id>] [--yes]\npassport undo --last [--option <id>] [--yes]\nUndoes an action Passport took a backup before (deletes and overwrites through Passport, within 7 days). Shows what comes back and what won't, then asks. Without a terminal, add --yes to run it. Passport decides the undo like a change in that environment; when Production approvers cover the action, one of them approves it.\n --last your newest action that can be undone\n --option <id> pick a listed option (default: the first)\n Done: exit 0. Partly done or failed: exit 1.\n Asks first: exit 4 with the approval id. Run passport wait <id>, then the undo again.\n Blocked, declined, or can't be undone: exit 5. No backup: exit 6.\nJSON: {actionId,status,message,steps:[{label,ok,detail?}],option,undoActionId?}; a preview is {actionId,status:\"preview\",preview,next}",
23
- keys: "passport keys [list]\npassport keys move [--yes] [--no-shim]\npassport keys add <cli>\npassport keys shim [<cli>] [--remove]\nmove: finds CLI sign-ins on this computer (Railway, GitHub CLI, Vercel, Wrangler, Supabase, Stripe, AWS, and keys in Claude Code's settings), stores each in Passport after you confirm it, then signs that CLI out here. .env files are never touched: your apps need them. add: stores a key you paste (read from stdin, never echoed). Agents then use the keys through passport exec.\nshim: so typing railway keeps working after its key moves, a small railway command in Passport's folder (~/.passport/cli/bin) runs passport exec -- railway. move offers one for each CLI it moved ([Y/n]; --yes installs them, --no-shim skips). Put the folder first on PATH (the line is printed when it isn't). With no <cli>, lists them; --remove <cli|all> takes them out. A shim goes by itself when Passport no longer holds that key, and when you sign out of the last profile.",
123
+ keys: "passport keys [list]\npassport keys move [<cli>] [--yes] [--no-shim]\npassport keys add <cli>\npassport keys shim [<cli>] [--remove]\nmove: finds CLI sign-ins on this computer (Railway, GitHub CLI, Vercel, Wrangler, Supabase, Stripe, AWS, and keys in Claude Code's settings), stores each in Passport after you confirm it ([y/N]), then signs that CLI out here. With <cli>, only that one. When Passport already holds a different key for that CLI, every agent that uses it would switch, so you type the CLI's name at a terminal to replace it; no flag does it, and without a terminal both keys stay. .env files are never touched: your apps need them. add: stores a key you paste (read from stdin, never echoed). Agents then use the keys through passport exec.\nshim: so typing railway keeps working after its key moves, a small railway command in Passport's folder (~/.passport/cli/bin) runs passport exec -- railway. move offers one for each CLI it moved ([Y/n]; --yes installs them, --no-shim skips). Put the folder first on PATH (the line is printed when it isn't). With no <cli>, lists them; --remove <cli|all> takes them out. A shim goes by itself when Passport no longer holds that key, and when you sign out of the last profile.",
24
124
  doctor: "passport doctor [--profile <name>]\nChecks Node, credential-store safety, endpoint security, server health, authentication, serverInfo, and the exact CLI protocol. JSON includes {ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}.",
25
125
  ready: "passport ready [--profile <name>]\nRuns the local, authentication, server, and exact CLI-protocol preflight. JSON includes {ready,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}.",
26
126
  search: "passport search [query...] [--app <key>]\nEmpty query lists the complete permitted catalog. JSON is the server search payload.",
@@ -40,14 +140,18 @@ function helpText(verb) {
40
140
  version: "passport version\nWorks without a profile or network."
41
141
  };
42
142
  const renamed = verb && details[verb]?.includes("--agent") ? `\n${RENAMED_FLAGS}` : "";
43
- if ((verb === "scan" || verb === "init") && details[verb])
44
- return details[verb] + renamed;
45
- if (verb && details[verb])
46
- return `${details[verb]}${renamed}\n\nGlobal: --profile <name> --json --timeout <sec> --quiet --caller <id>`;
143
+ const page = verb && details[verb] ? withExamples(details[verb], verb === "help" ? undefined : EXAMPLES[verb]) : undefined;
144
+ if ((verb === "scan" || verb === "init") && page)
145
+ return page + renamed;
146
+ if (page)
147
+ return `${page}${renamed}\n\nGlobal: --profile <name> --json --timeout <sec> --quiet --caller <id>`;
47
148
  return `Passport CLI ${VERSION}
48
149
 
49
150
  Usage: passport <command> [options]
50
151
 
152
+ ${exampleLines(EXAMPLES.help)}
153
+
154
+ Commands:
51
155
  scan Find keys your agents can reach. Local, no account
52
156
  init Set up Passport for your agents, step by step
53
157
  login Sign in or sign up in the browser
@@ -83,7 +187,9 @@ Usage: passport <command> [options]
83
187
 
84
188
  Global: --profile <name> --json --timeout <sec> --quiet --caller <id>
85
189
 
86
- Exit codes: 0 success · 1 network/server · 2 auth · 3 needs-connect · 4 approval-pending · 5 policy, guardrail, selection, or approval denial · 6 usage/unknown
190
+ Exit codes:
191
+ ${EXIT_CODES.map(([code, meaning]) => ` ${code} ${meaning}`).join("\n")}
192
+
87
193
  With --json, stdout is exactly one JSON value. Hints and warnings use stderr.
88
194
  ${RENAMED_FLAGS}`;
89
195
  }
@@ -163,8 +269,9 @@ export function unreachableMessage(origin) {
163
269
  export function asFailure(error, origin) {
164
270
  if (error instanceof CliFailure)
165
271
  return error;
166
- if (error instanceof ArgError)
167
- return new CliFailure(sanitize(error.message), 6, "usage");
272
+ if (error instanceof ArgError) {
273
+ return new CliFailure(sanitize(error.message), 6, "usage", error.suggestion ? { next: [{ argv: error.suggestion, description: "The closest match." }] } : {});
274
+ }
168
275
  const raw = error instanceof Error ? error.message : String(error);
169
276
  const message = sanitize(raw);
170
277
  if (message === SERVER_TOO_OLD || message.includes("CLI-compatible server")) {
@@ -118,7 +118,8 @@ function rule(value) {
118
118
  ...(scope ? { scope } : {}),
119
119
  ...(owner ? { owner } : {}),
120
120
  ...(label ? { label } : {}),
121
- ...(except.length ? { except } : {})
121
+ ...(except.length ? { except } : {}),
122
+ ...(body.exception === true ? { exception: true } : {})
122
123
  };
123
124
  }
124
125
  /** Actions an approved exception lifts a rule for. */
@@ -167,6 +168,50 @@ function offline(value) {
167
168
  }
168
169
  return out;
169
170
  }
171
+ const PASSES = new Set(["full", "readonly", "none"]);
172
+ /** An absolute http(s) link, or undefined. */
173
+ function webLink(value) {
174
+ if (typeof value !== "string" || value.length > 300 || /[\u0000- \u007f]/.test(value))
175
+ return undefined;
176
+ try {
177
+ const url = new URL(value);
178
+ return url.protocol === "https:" || url.protocol === "http:" ? value : undefined;
179
+ }
180
+ catch {
181
+ return undefined;
182
+ }
183
+ }
184
+ /** `appAccess` by vendor: absent is none at all, anything malformed rejects the document. */
185
+ function appAccess(value) {
186
+ if (value === undefined)
187
+ return undefined;
188
+ const body = plainObject(value);
189
+ if (!body)
190
+ return null;
191
+ const entries = Object.entries(body);
192
+ if (entries.length > MAX_VENDORS)
193
+ return null;
194
+ const out = {};
195
+ for (const [vendor, raw] of entries) {
196
+ const entry = plainObject(raw);
197
+ if (!VENDOR_KEY.test(vendor) || UNSAFE_KEYS.has(vendor) || !entry || !PASSES.has(entry.pass))
198
+ return null;
199
+ const pass = entry.pass;
200
+ const app = printable(entry.app, 80);
201
+ if (!app)
202
+ return null;
203
+ const cause = printable(entry.cause, 160) || `${pass === "none" ? "No access" : "Read-only access"} to ${app} in Passport`;
204
+ const link = webLink(entry.link);
205
+ out[vendor] = {
206
+ pass,
207
+ app,
208
+ cause,
209
+ message: printable(entry.message, 240) || `${cause}.`,
210
+ ...(link ? { link } : {})
211
+ };
212
+ }
213
+ return out;
214
+ }
170
215
  function printable(value, max) {
171
216
  return typeof value === "string"
172
217
  ? value
@@ -335,10 +380,12 @@ export function serializeCliPolicyV2(policy) {
335
380
  environment: lift.environment
336
381
  }))
337
382
  }
338
- : {})
383
+ : {}),
384
+ ...(rule.exception ? { exception: true } : {})
339
385
  })),
340
386
  ...(autopilot.secondPerson ? { secondPerson: autopilot.secondPerson } : {}),
341
387
  ...(autopilot.offline ? { offline: autopilot.offline } : {}),
388
+ ...(autopilot.appAccess ? { appAccess: autopilot.appAccess } : {}),
342
389
  irreversible: autopilot.irreversible,
343
390
  irreversibleInProduction: autopilot.irreversibleInProduction ?? {},
344
391
  deletes: autopilot.deletes ?? {},
@@ -392,6 +439,9 @@ export function parseCliPolicyV2(value) {
392
439
  const knownProject = project(body.project);
393
440
  if (knownProject === null)
394
441
  return null;
442
+ const access = appAccess(body.appAccess);
443
+ if (access === null)
444
+ return null;
395
445
  return {
396
446
  version: 2,
397
447
  updatedAt: body.updatedAt,
@@ -411,6 +461,7 @@ export function parseCliPolicyV2(value) {
411
461
  ...(body.speed === true ? { reportsSpeed: true } : {}),
412
462
  ...(parsedSecondPerson?.classes.length ? { secondPerson: parsedSecondPerson } : {}),
413
463
  ...(offline(body.offline) ? { offline: offline(body.offline) } : {}),
464
+ ...(access && Object.keys(access).length ? { appAccess: access } : {}),
414
465
  ...(knownProject ? { project: knownProject } : {})
415
466
  }
416
467
  };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * "Did you mean" for a mistyped command, option, or subcommand: the closest
3
+ * known name, or nothing when none is close. Close means a unique prefix of at
4
+ * least three letters, or a few edits away (one for a short name), counting a
5
+ * swap of two neighbouring letters as one edit (`stauts` → `status`).
6
+ */
7
+ /** Edits between two strings: insert, delete, replace, or swap two neighbours. */
8
+ export declare function editDistance(left: string, right: string): number;
9
+ /** The known name closest to `input`, or undefined when none is close. */
10
+ export declare function closest(input: string, names: readonly string[]): string | undefined;
11
+ /** `Unknown keys command "mvoe". Did you mean: passport keys move`, and the
12
+ * suggested argv for --json's `next`. */
13
+ export declare function unknownSubcommand(command: string, typed: string, names: readonly string[]): {
14
+ message: string;
15
+ next?: Array<{
16
+ argv: string[];
17
+ description: string;
18
+ }>;
19
+ };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * "Did you mean" for a mistyped command, option, or subcommand: the closest
3
+ * known name, or nothing when none is close. Close means a unique prefix of at
4
+ * least three letters, or a few edits away (one for a short name), counting a
5
+ * swap of two neighbouring letters as one edit (`stauts` → `status`).
6
+ */
7
+ /** Edits between two strings: insert, delete, replace, or swap two neighbours. */
8
+ export function editDistance(left, right) {
9
+ const rows = left.length + 1;
10
+ const columns = right.length + 1;
11
+ const table = Array.from({ length: rows }, (_, row) => Array.from({ length: columns }, (_, column) => (row === 0 ? column : column === 0 ? row : 0)));
12
+ for (let row = 1; row < rows; row++) {
13
+ for (let column = 1; column < columns; column++) {
14
+ const cost = left[row - 1] === right[column - 1] ? 0 : 1;
15
+ let best = Math.min(table[row - 1][column] + 1, table[row][column - 1] + 1, table[row - 1][column - 1] + cost);
16
+ if (row > 1 && column > 1 && left[row - 1] === right[column - 2] && left[row - 2] === right[column - 1]) {
17
+ best = Math.min(best, table[row - 2][column - 2] + 1);
18
+ }
19
+ table[row][column] = best;
20
+ }
21
+ }
22
+ return table[left.length][right.length];
23
+ }
24
+ /** The known name closest to `input`, or undefined when none is close. */
25
+ export function closest(input, names) {
26
+ const typed = input.toLowerCase();
27
+ if (!typed)
28
+ return undefined;
29
+ const prefixed = names.filter((name) => name.startsWith(typed));
30
+ if (typed.length >= 3 && prefixed.length === 1)
31
+ return prefixed[0];
32
+ const reach = typed.length <= 4 ? 1 : 2;
33
+ let best;
34
+ let bestDistance = reach + 1;
35
+ for (const name of names) {
36
+ const distance = editDistance(typed, name);
37
+ if (distance < bestDistance) {
38
+ best = name;
39
+ bestDistance = distance;
40
+ }
41
+ }
42
+ return best;
43
+ }
44
+ /** `Unknown keys command "mvoe". Did you mean: passport keys move`, and the
45
+ * suggested argv for --json's `next`. */
46
+ export function unknownSubcommand(command, typed, names) {
47
+ const guess = closest(typed, names);
48
+ const shown = `Unknown ${command} command "${typed}".`;
49
+ if (!guess) {
50
+ return { message: `${shown} Use ${names.map((name) => `passport ${command} ${name}`).join(", ")}.` };
51
+ }
52
+ const argv = ["passport", command, guess];
53
+ return {
54
+ message: `${shown} Did you mean: ${argv.join(" ")}`,
55
+ next: [{ argv, description: "The closest match." }]
56
+ };
57
+ }
package/dist/cliUndo.js CHANGED
@@ -13,6 +13,7 @@ import { bool, value } from "./cliArgs.js";
13
13
  import { api, json } from "./cliAutopilot.js";
14
14
  import { failure, safeApiError, timeoutMs } from "./cliSupport.js";
15
15
  import { processTerminal } from "./initUi.js";
16
+ import { askYesNo } from "./cliAsk.js";
16
17
  /* Checked copies of shared/undoContract.ts (the CLI can't import shared/);
17
18
  * cliUndo.test.ts fails if they drift. */
18
19
  export const UNDO_RETENTION_DAYS = 7;
@@ -164,14 +165,8 @@ async function choose(terminal, preview, runtime) {
164
165
  runtime.stdout.write(`Type a number from 1 to ${preview.options.length}.\n`);
165
166
  }
166
167
  }
167
- for (;;) {
168
- const answer = (await terminal.question(`Undo it? [y/N] `, runtime.signal)).trim().toLowerCase();
169
- if (answer === "y" || answer === "yes")
170
- return picked;
171
- if (answer === "" || answer === "n" || answer === "no")
172
- return undefined;
173
- runtime.stdout.write("Type y or n.\n");
174
- }
168
+ const yes = await askYesNo((prompt) => terminal.question(prompt, runtime.signal), (text) => runtime.stdout.write(`${text}\n`), "Undo it?", "destructive");
169
+ return yes ? picked : undefined;
175
170
  }
176
171
  const EXIT = { done: 0, partial: 1, failed: 1, busy: 1, unavailable: 5 };
177
172
  /** The action and its preview: the one named, or my newest that can be undone. */
@@ -0,0 +1,8 @@
1
+ type CacheModule = {
2
+ enableCompileCache?: (directory?: string) => unknown;
3
+ };
4
+ export declare function compileCacheDir(env?: NodeJS.ProcessEnv): string | undefined;
5
+ /** Only a real folder (not a link) this user owns, that no one else can write. */
6
+ export declare function privateFolder(directory: string, uid?: number | undefined): boolean;
7
+ export declare function enableCompileCache(env?: NodeJS.ProcessEnv, node?: CacheModule): string | undefined;
8
+ export {};
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Node's compile cache for the CLI's own modules: the second and later runs
3
+ * of `passport` skip compiling them again (Node 22.1+, `module.enableCompileCache`).
4
+ *
5
+ * The cache lives in `$PASSPORT_HOME/cli/compile-cache` (`~/.passport` by
6
+ * default), a folder only this person can write: compiled code read from a
7
+ * folder someone else can write would run as them. A folder that's shared or
8
+ * owned by someone else is never used; neither is the repository or the
9
+ * system's temp folder. It waits for Passport's folder to exist (sign-in or
10
+ * init makes it), so `scan` on a fresh computer still leaves nothing behind. `NODE_COMPILE_CACHE` (Node's own setting) and
11
+ * `NODE_DISABLE_COMPILE_CACHE` keep working. Never throws: without a cache
12
+ * the CLI is only slower.
13
+ *
14
+ * Imports nothing of the CLI's: everything loaded before this runs isn't cached.
15
+ */
16
+ import { existsSync, lstatSync, mkdirSync } from "node:fs";
17
+ import module from "node:module";
18
+ import { homedir } from "node:os";
19
+ import { dirname, join } from "node:path";
20
+ export function compileCacheDir(env = process.env) {
21
+ const home = env.PASSPORT_HOME || (homedir() ? join(homedir(), ".passport") : "");
22
+ return home ? join(home, "cli", "compile-cache") : undefined;
23
+ }
24
+ /** Only a real folder (not a link) this user owns, that no one else can write. */
25
+ export function privateFolder(directory, uid = process.getuid?.()) {
26
+ const stats = lstatSync(directory);
27
+ if (!stats.isDirectory())
28
+ return false;
29
+ if (uid === undefined)
30
+ return true; // Windows: the profile folder's own ACLs apply.
31
+ return stats.uid === uid && (stats.mode & 0o022) === 0;
32
+ }
33
+ export function enableCompileCache(env = process.env, node = module) {
34
+ try {
35
+ if (env.NODE_DISABLE_COMPILE_CACHE || env.NODE_COMPILE_CACHE)
36
+ return undefined;
37
+ if (typeof node.enableCompileCache !== "function")
38
+ return undefined;
39
+ const directory = compileCacheDir(env);
40
+ if (!directory)
41
+ return undefined;
42
+ // Passport's folder is never created just for a cache (`scan` leaves no
43
+ // state behind), and every folder on the way must be this user's alone,
44
+ // so nobody else can swap the cache out from under it.
45
+ const cli = dirname(directory);
46
+ if (!privateFolder(dirname(cli)))
47
+ return undefined;
48
+ for (const folder of [cli, directory]) {
49
+ if (!existsSync(folder))
50
+ mkdirSync(folder, { mode: 0o700 });
51
+ if (!privateFolder(folder))
52
+ return undefined;
53
+ }
54
+ node.enableCompileCache(directory);
55
+ return directory;
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `passport exec` with no key in Passport. Passport can't see this computer,
3
+ * so its answer says to add one in Apps; when this computer still has the
4
+ * CLI's own sign-in, the fix is one command here instead:
5
+ * "Run passport keys move railway". Read here only; nothing is sent.
6
+ */
7
+ import { CliFailure, type Runtime } from "./cliSupport.js";
8
+ import { type ExecVendor } from "./execVendors.js";
9
+ export declare function keyHereFailure(error: CliFailure, vendor: ExecVendor, runtime: Runtime, home?: string): CliFailure;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * `passport exec` with no key in Passport. Passport can't see this computer,
3
+ * so its answer says to add one in Apps; when this computer still has the
4
+ * CLI's own sign-in, the fix is one command here instead:
5
+ * "Run passport keys move railway". Read here only; nothing is sent.
6
+ */
7
+ import { CliFailure } from "./cliSupport.js";
8
+ import { EXEC_VENDOR_NAMES } from "./execVendors.js";
9
+ import { findLocalKeys } from "./keysLocal.js";
10
+ export function keyHereFailure(error, vendor, runtime, home) {
11
+ try {
12
+ const here = findLocalKeys({ env: runtime.env, ...(home ? { home } : {}) }).some((key) => key.vendor === vendor && key.secret && !key.unholdable);
13
+ if (!here)
14
+ return error;
15
+ const name = EXEC_VENDOR_NAMES[vendor];
16
+ return new CliFailure(`No ${name} key in Passport yet, but this computer has one. Run passport keys move ${vendor}`, 3, "no_key", {
17
+ next: [
18
+ { argv: ["passport", "keys", "move", vendor], description: `Move this computer's ${name} key into Passport.` }
19
+ ]
20
+ });
21
+ }
22
+ catch {
23
+ return error;
24
+ }
25
+ }
package/dist/hookMain.js CHANGED
@@ -1,15 +1,9 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * The shell hooks' own entry. The launcher starts this for `passport hook
4
- * guard`, `passport hook`, and `passport hook flush`, so a hook loads only the
5
- * guard, not the whole CLI: every agent shell command waits for it. Anything
6
- * else (help, `hook install`, a bad flag) goes to the full CLI, unchanged.
7
- */
8
- import { parseArgs } from "./cliArgs.js";
9
- import { holdForCommand } from "./cliSupport.js";
2
+ import { enableCompileCache } from "./compileCache.js";
10
3
  const HOOK_ACTIONS = new Set([undefined, "guard", "flush"]);
11
- function hookArgs(argv) {
4
+ async function hookArgs(argv) {
12
5
  try {
6
+ const { parseArgs } = await import("./cliArgs.js");
13
7
  const args = parseArgs(argv);
14
8
  if (args.command !== "hook" || !HOOK_ACTIONS.has(args.positionals[0]))
15
9
  return null;
@@ -22,9 +16,10 @@ function hookArgs(argv) {
22
16
  }
23
17
  }
24
18
  async function run(argv) {
25
- const args = hookArgs(argv);
19
+ const args = await hookArgs(argv);
26
20
  if (!args)
27
- return (await import("./passport.js")).main(argv);
21
+ return (await import("./cliMain.js")).main(argv);
22
+ const { holdForCommand } = await import("./cliSupport.js");
28
23
  const controller = new AbortController();
29
24
  const release = holdForCommand(() => controller.abort(new Error("Cancelled.")));
30
25
  const runtime = {
@@ -48,6 +43,7 @@ async function run(argv) {
48
43
  release();
49
44
  }
50
45
  }
46
+ enableCompileCache();
51
47
  void run(process.argv.slice(2)).then((code) => {
52
48
  process.exitCode = code;
53
49
  });
@@ -2,7 +2,8 @@
2
2
  * Reports the shell hooks send later, so no hook ever waits on the network
3
3
  * after it has answered. The after-hook (`passport hook`) and the guard's own
4
4
  * report append here and return; a detached `passport hook flush` sends them
5
- * within the hook budget, at most one starting every couple of seconds.
5
+ * within the hook budget, at most one starting every couple of seconds and
6
+ * only one running at a time (`takeFlushLock`).
6
7
  *
7
8
  * Each line is one report exactly as it would have been sent: vendors, coarse
8
9
  * verbs, risk classes, ids, a folder name; never a command line. The file is
@@ -11,14 +12,26 @@
11
12
  */
12
13
  /** At most one flush starts in this window. */
13
14
  export declare const FLUSH_GAP_MS = 2000;
15
+ /** A flush lock this old belongs to a flush that died without letting go: a
16
+ * live one exits well before (`FLUSH_DEADLINE_MS`). */
17
+ export declare const FLUSH_LOCK_STALE_MS = 10000;
14
18
  /** Queue reports to send. False when they couldn't be queued. */
15
19
  export declare function queueReports(profile: string, reports: object[], now?: number): boolean;
16
20
  /** Everything queued, claimed so no other flush sends it too. */
17
21
  export declare function takeQueued(profile: string, now?: number): object[];
18
22
  /** Whether anything is queued. Cheap: no reads. */
19
23
  export declare function hasQueued(profile: string): boolean;
20
- /** Claim the next flush: true at most once per FLUSH_GAP_MS. */
24
+ /** Claim the next flush: true at most once per FLUSH_GAP_MS, and never while
25
+ * another flush still runs. */
21
26
  export declare function claimFlush(profile: string, now?: number): boolean;
27
+ /** Whether a flush for this profile is running now. */
28
+ export declare function flushRunning(profile: string, now?: number): boolean;
29
+ /**
30
+ * Take the one flush slot for this profile: a release function, or null when
31
+ * another flush holds it (this one then has nothing to do). A lock left by a
32
+ * flush that died is taken over. Never throws.
33
+ */
34
+ export declare function takeFlushLock(profile: string, now?: number): (() => void) | null;
22
35
  /**
23
36
  * Start `passport hook flush` on its own: detached, no stdio, not waited for,
24
37
  * so the hook that started it exits at once and the agent never waits on the