passport-bridge 0.16.8 → 0.16.12

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 (99) hide show
  1. package/README.md +44 -27
  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 +59 -8
  6. package/dist/cliAsk.d.ts +28 -0
  7. package/dist/cliAsk.js +49 -0
  8. package/dist/cliAutopilot.d.ts +3 -40
  9. package/dist/cliAutopilot.js +8 -240
  10. package/dist/cliExec.d.ts +29 -0
  11. package/dist/cliExec.js +156 -38
  12. package/dist/cliHelp.d.ts +11 -0
  13. package/dist/cliHelp.js +37 -0
  14. package/dist/cliHookDeliver.d.ts +17 -1
  15. package/dist/cliHookDeliver.js +70 -19
  16. package/dist/cliHookInstall.d.ts +2 -0
  17. package/dist/cliHookInstall.js +2 -1
  18. package/dist/cliHookStatus.js +2 -4
  19. package/dist/cliInit.d.ts +22 -5
  20. package/dist/cliInit.js +147 -107
  21. package/dist/cliKeys.d.ts +18 -4
  22. package/dist/cliKeys.js +123 -53
  23. package/dist/cliKeysShim.d.ts +40 -0
  24. package/dist/cliKeysShim.js +110 -0
  25. package/dist/cliLogin.d.ts +2 -14
  26. package/dist/cliLogin.js +200 -213
  27. package/dist/cliLogout.d.ts +8 -0
  28. package/dist/cliLogout.js +57 -0
  29. package/dist/cliMain.d.ts +7 -0
  30. package/dist/cliMain.js +502 -0
  31. package/dist/cliMemberCall.d.ts +22 -0
  32. package/dist/cliMemberCall.js +38 -0
  33. package/dist/cliOutput.d.ts +3 -0
  34. package/dist/cliOutput.js +130 -18
  35. package/dist/cliSessions.d.ts +36 -0
  36. package/dist/cliSessions.js +129 -0
  37. package/dist/cliSetupOrg.d.ts +2 -0
  38. package/dist/cliSetupOrg.js +30 -9
  39. package/dist/cliStatus.d.ts +73 -0
  40. package/dist/cliStatus.js +387 -0
  41. package/dist/cliStatusGuard.d.ts +0 -2
  42. package/dist/cliStatusGuard.js +1 -18
  43. package/dist/cliStatusLocal.d.ts +22 -0
  44. package/dist/cliStatusLocal.js +18 -0
  45. package/dist/cliSuggest.d.ts +19 -0
  46. package/dist/cliSuggest.js +57 -0
  47. package/dist/cliSupport.d.ts +4 -0
  48. package/dist/cliUndo.js +3 -8
  49. package/dist/cliWait.d.ts +14 -0
  50. package/dist/cliWait.js +180 -0
  51. package/dist/compileCache.d.ts +8 -0
  52. package/dist/compileCache.js +60 -0
  53. package/dist/completion.js +17 -6
  54. package/dist/execMask.d.ts +55 -0
  55. package/dist/execMask.js +189 -0
  56. package/dist/execNoKey.d.ts +9 -0
  57. package/dist/execNoKey.js +25 -0
  58. package/dist/execShims.d.ts +59 -0
  59. package/dist/execShims.js +258 -0
  60. package/dist/hookMain.js +7 -11
  61. package/dist/hookOutbox.d.ts +15 -2
  62. package/dist/hookOutbox.js +143 -3
  63. package/dist/initAppsStep.d.ts +26 -5
  64. package/dist/initAppsStep.js +73 -65
  65. package/dist/initAutopilotStep.d.ts +42 -11
  66. package/dist/initAutopilotStep.js +160 -86
  67. package/dist/initInstall.d.ts +9 -2
  68. package/dist/initInstall.js +31 -4
  69. package/dist/initKeysStep.d.ts +16 -1
  70. package/dist/initKeysStep.js +69 -40
  71. package/dist/initLocalSteps.d.ts +65 -4
  72. package/dist/initLocalSteps.js +273 -169
  73. package/dist/initOutro.d.ts +10 -0
  74. package/dist/initOutro.js +148 -0
  75. package/dist/initPlan.d.ts +39 -0
  76. package/dist/initPlan.js +193 -0
  77. package/dist/initState.d.ts +32 -0
  78. package/dist/initUi.d.ts +43 -11
  79. package/dist/initUi.js +175 -103
  80. package/dist/loginFlow.d.ts +71 -0
  81. package/dist/loginFlow.js +235 -0
  82. package/dist/loginIdentity.d.ts +27 -0
  83. package/dist/loginIdentity.js +131 -0
  84. package/dist/loginPending.d.ts +23 -0
  85. package/dist/loginPending.js +89 -0
  86. package/dist/passport.d.ts +1 -7
  87. package/dist/passport.js +15 -623
  88. package/dist/pluginPin.d.ts +1 -1
  89. package/dist/pluginPin.js +1 -1
  90. package/dist/releaseTooling.d.ts +7 -0
  91. package/dist/releaseTooling.js +29 -0
  92. package/dist/term.d.ts +104 -0
  93. package/dist/term.js +209 -0
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -1
  96. package/dist/waitingLine.d.ts +38 -0
  97. package/dist/waitingLine.js +78 -0
  98. package/npm-shrinkwrap.json +2 -2
  99. package/package.json +2 -1
package/README.md CHANGED
@@ -36,9 +36,11 @@ passport run github_search_issues '{"query":"SSO"}'
36
36
  ```
37
37
 
38
38
  - First time? Bare `passport login` opens `/cli` in your browser. Sign in with Google, GitHub, or an emailed code, then connect a workspace you belong to or create one. No workspace id needed.
39
- - Confirm that the code in the browser matches the one in your terminal. Nothing connects until you click Connect.
39
+ - One screen every time: `Code: HJKT-WQRM`, the pre-filled `Link:`, and `Check the code matches the one in your browser before you approve.` Nothing connects until you click Connect. It ends `Signed in as Erin Park to Acme.`; `--verbose` adds the profile name and where it's saved.
40
+ - Already signed in? On a terminal, `passport login` asks `Already signed in as Erin Park to Acme. Switch? [y/N]`. Enter keeps you signed in; `--switch` skips the question and lets the browser pick again. A sign-in that stopped working just signs in again.
40
41
  - Re-signing in? Bare `passport login` reuses the workspace of the active profile, the sole CLI profile, or the one workspace all saved profiles share. With several workspaces saved it lists them and asks for `--workspace`.
41
- - `--workspace ws_example` signs in to one known workspace (the device flow). Self-hosted: add `--cloud https://passport.example.com` (origin only). A server without browser sign-in keeps asking for `--workspace`.
42
+ - `--workspace ws_example` takes the same browser sign-in straight to that workspace, and only that workspace is accepted. Self-hosted: add `--cloud https://passport.example.com` (origin only). A server without browser sign-in falls back to its device flow when the workspace is known, else asks for `--workspace`.
43
+ - Without a terminal (an agent's shell, CI) or with `--json`, login is two steps, like `stripe login --non-interactive`: it prints `{status:"pending", verification_url, code, next_step, login_id}` and exits; once the code is approved in the browser, run `next_step` (`passport login --complete <login_id>`) to save the profile. The poll secret stays in an owner-only file under `~/.passport/login-pending/`.
42
44
  - `--no-open` (or `PASSPORT_NO_OPEN=1`) prints the sign-in link instead of opening a browser. Use it over SSH and in headless sessions; open the link on any device.
43
45
  - Remote servers must use HTTPS. Plain HTTP works only on `localhost`, `127.0.0.0/8`, or `::1`.
44
46
  - Requires a gateway reporting serverInfo `passport` 0.5.0 or newer with the four-tool CLI protocol; older servers fail before any tool call.
@@ -52,7 +54,7 @@ passport run github_search_issues '{"query":"SSO"}'
52
54
  | `login` | Browser sign-in or sign-up (or device sign-in with `--workspace`); saves a rotating CLI credential and makes the profile active. |
53
55
  | `logout` | Revoke the credential and always remove the local profile (warns if revocation fails). |
54
56
  | `profiles` / `use <name>` | List stored profiles / select the active one. Offline. |
55
- | `status` | Workspace, member, agent, and app connection states, plus Autopilot presets, team floors, and how old this computer's copy of your rules is. |
57
+ | `status` | One screen: you, your workspace, and this computer; each agent's guard and its fix; Autopilot; apps; keys in Passport; this folder's environments; the CLI version. |
56
58
  | `doctor` | Check Node, credential-file safety, HTTPS policy, `/healthz`, auth, serverInfo, and CLI protocol. Exit 1 on a failed check, with the full report. |
57
59
  | `ready` | Readiness preflight for automation; gate on its `ready` field and exit code. |
58
60
  | `search [query] [--app <key>]` | Search permitted tools. Empty query lists the full catalog. |
@@ -124,31 +126,32 @@ Reads agent MCP configs (Claude Desktop, Claude Code, Cursor, VS Code, Codex), C
124
126
 
125
127
  ```sh
126
128
  npx passport-bridge@latest init # or: passport init
127
- npx passport-bridge@latest init --yes # accept every default; needed without a terminal. Keys stay put
129
+ npx passport-bridge@latest init --dry-run # the plan only; nothing changes (so does --json without --yes)
130
+ npx passport-bridge@latest init --yes # the recommended setup without asking; needed without a terminal. Keys stay put
128
131
  npx passport-bridge@latest init --yes --move-keys # also move CLI keys into Passport and sign those CLIs out
129
- npx passport-bridge@latest init --yes --json # one summary object with each step's status
132
+ npx passport-bridge@latest init --yes --json # one summary object with each step's status and the plan
130
133
  ```
131
134
 
135
+ Plan, then apply. Init scans and signs in, then reads every step below without changing anything and shows one plan: **Will** (what the recommended setup changes), **Edits** (every file it edits, each backed up first), **Already set up**, **Not changed** (with how to change it later), and **You do**, then the Autopilot presets and Environments. One question follows: `Use the recommended setup? (n to choose step by step) [Y/n]`. Enter applies the plan; `n` walks each step with its own question. When nothing is missing it says `Nothing to change.` and asks nothing. It ends with a ✓ list of what's true now and what's left for you, and one next command (the `PATH` line, `passport connect --wait 300`, a first thing to ask your agent, or `passport status`).
136
+
132
137
  Eight steps, each reusing the command that owns it:
133
138
 
134
139
  1. **Scan**: the same local scan as `passport scan`, as one summary line (`--verbose` prints the table).
135
140
  2. **Sign in**: reuses the active or only CLI profile, asks which one when there are several, or runs the browser sign-in from `passport login`.
136
- 3. **Apps**: Railway, Vercel, Supabase, Cloudflare, GitHub, and Stripe, when the scan found a key or its CLI is on PATH. Missing apps are added through the same catalog rules as the web (an app your workspace reviews first says `! Stripe needs approval from your admin.`), then one sign-in page covers the rest. In a terminal init waits until they connect (Enter stops waiting); without one it prints the page and `Next: passport connect --wait 300` and moves on.
137
- 4. **Keys**: for each CLI sign-in on this computer, the same question as `passport keys move`: `Store your Railway account token in Passport and sign the Railway CLI out on this computer? [y/n]`. It has no default: Enter asks again (`Type y or n.`). `--yes` never moves a key: the step prints `Keys stayed on this computer. Run passport keys move to move them.` Add `--move-keys` to move every key it finds unasked; the closing summary then says which (`Moved your Railway key into Passport and signed that CLI out on this computer.`) and which old keys to rotate (`Rotate the old Railway key once your agents don't need it.`, only when a key moved in that run). When Passport already holds a different key for that CLI, an interactive run asks `Replace the Railway key in Passport with the one on this computer? [y/n]` (no default): yes replaces it and signs the CLI out, keeping links; no prints `Kept the key in Passport. This computer's Railway CLI stays signed in.` `--yes` never replaces a key. Quiet when there's nothing to move.
138
- 5. **Environments**: the environments Passport has placed for your apps, each with its kind: `Found 3 environments: production (Railway), preview (Vercel), qa (Railway)`. Anything Passport can't place counts as Production; change it any time in Rules. With no app connected yet it says `Environments appear once an app is connected.`
139
- 6. **Agents**: Passport's one MCP URL with this workspace as its hint (`https://passportmcp.com/mcp?ws=<workspace>`), with each agent's own browser sign-in; a server that doesn't serve `/mcp` yet (read from its OAuth protected-resource metadata) gets the workspace's own URL (`https://<host>/w/<workspace>/mcp`). An existing entry at either URL for this workspace counts as set up, so no token lands in a config file. Claude Code and Codex through their own CLIs (`claude mcp add --transport http --scope user`, `codex mcp add --url`), Cursor through `~/.cursor/mcp.json`, VS Code through `code --add-mcp` or its user `mcp.json`. Claude Desktop connects through Settings → Connectors, so init prints that step.
140
- 7. **Guard**: asks `Apply your Autopilot rules before each shell command in <agents>? [Y/n]`, then runs `passport hook install --guard` for Claude Code, Codex, and Cursor (Codex: blocks only), pointing at the launcher `$PASSPORT_HOME/cli/bin/passport` (`passport.cmd` on Windows), which runs a stable copy of the CLI in `$PASSPORT_HOME/cli/<version>/` (never npm's cache), or at a global `passport-bridge` of the same version or newer. An upgrade rewrites the launcher and the `cli/current` link in one rename each, so hooks follow without being edited; the launcher runs the recorded node, or the node on PATH once that one is removed. A hook from an older init that names a version folder is replaced where it stands, next to your other hooks. Once the new copy is in place, older copies are deleted unless a hook still runs them.
141
+ 3. **Apps**: Railway, Vercel, Supabase, Cloudflare, GitHub, and Stripe, when the scan found a key or its CLI is on PATH. Missing apps are added through the same catalog rules as the web (an app your workspace reviews first says `! Stripe needs approval from your admin.`), then one sign-in page covers the rest. In a terminal init waits until they connect (Enter stops waiting); with `--yes` or without a terminal it prints the page, adds `passport connect --wait 300` to `next`, and moves on.
142
+ 4. **Keys**: the recommended setup keeps them; the plan says `Your Railway and GitHub keys stay on this computer. Move them any time: passport keys move`. Step by step asks the same question as `passport keys move` for each: `Store your Railway account token in Passport and sign the Railway CLI out on this computer? [y/N]`. Enter keeps the key here; an answer that isn't y or n asks again (`Type y or n.`). Add `--move-keys` to move every key it finds without asking; the closing list then says which (`Moved your Railway key into Passport and signed that CLI out here`) and, once per moved key, where to rotate the old one (`Rotate the old Railway key, since copies may exist elsewhere: https://railway.com/account/tokens`). When Passport already holds a different key for that CLI, an interactive run asks `Passport already holds a different Railway key. Replace it with this computer's? Every agent that uses it switches to this one.` then `Type railway to confirm, or press Enter to cancel:`: only the name replaces it and signs the CLI out, keeping links; anything else prints `Kept the key in Passport. This computer's Railway CLI stays signed in.` `--yes` never replaces a key. Quiet when there's nothing to move.
143
+ 5. **Environments**: the environments Passport has placed for your apps, grouped by kind (`Production production (Railway), production (Vercel)`), one row per resource. Anything Passport can't place counts as Production and is listed once: `Treated as Production until placed: blue (Railway). Change it in Rules.` A resource named for its kind (`production` in Production) is never called assumed. This folder's links follow (`This folder: Railway production · linked · Production`). With no app connected yet it says they appear once one is.
144
+ 6. **Agents**: Passport's one MCP URL with this workspace as its hint (`https://passportmcp.com/mcp?ws=<workspace>`), with each agent's own browser sign-in; a server that doesn't serve `/mcp` yet (read from its OAuth protected-resource metadata) gets the workspace's own URL (`https://<host>/w/<workspace>/mcp`). An existing entry at either URL for this workspace counts as set up, so no token lands in a config file. Claude Code and Codex through their own CLIs (`claude mcp add --transport http --scope user`, `codex mcp add --url`), Cursor through `~/.cursor/mcp.json`, VS Code through `code --add-mcp` or its user `mcp.json`. Claude Desktop connects through Settings → Connectors: on a terminal init copies the URL and says `Claude Desktop: Settings → Connectors → Add custom connector → paste the URL (copied)`; without one it names the URL.
145
+ 7. **Guard**: (step by step asks `Check each shell command in <agents> before it runs? [Y/n]`) runs `passport hook install --guard` for Claude Code, Codex, and Cursor (in Codex, a command your rules ask about is blocked with how to approve it, since Codex can't show Passport's questions), pointing at the launcher `$PASSPORT_HOME/cli/bin/passport` (`passport.cmd` on Windows), which runs a stable copy of the CLI in `$PASSPORT_HOME/cli/<version>/` (never npm's cache), or at a global `passport-bridge` of the same version or newer. An upgrade rewrites the launcher and the `cli/current` link in one rename each, so hooks follow without being edited; the launcher runs the recorded node, or the node on PATH once that one is removed. A hook from an older init that names a version folder is replaced where it stands, next to your other hooks. Once the new copy is in place, older copies are deleted unless a hook still runs them.
141
146
  8. **Autopilot**: how much agents can do on their own, per environment:
142
147
 
143
148
  ```
144
- Autopilot How much can agents do on their own?
145
- Production Careful reads run, changes ask
146
- Staging Balanced reads and changes run, deletes ask
147
- Development Hands-off everything except irreversible runs
148
- Keep these? [Y/n]
149
+ Autopilot Production Careful reads run, changes ask
150
+ Staging Balanced reads and changes run, deletes ask
151
+ Development Hands-off everything except irreversible runs
149
152
  ```
150
153
 
151
- `n` chooses per environment; `--yes` keeps the defaults. A team floor stricter than a default is shown with why (`Your team requires Careful or stricter in Staging.`), and choices below it aren't offered. A CLI credential can only make presets stricter; a looser pick says so in one line and keeps the current ones. A re-run shows the presets `(already set up)` without asking. The closing summary says what will ask: `Autopilot on. You'll be asked only for Production changes, deletes outside Development, and irreversible actions.` A server without Autopilot gets the earlier Safety step instead.
154
+ The plan shows them once. Step by step asks one compact question per environment where a choice is left (`Staging: 1 Careful 2 Balanced 3 Hands-off [2]`, Enter keeps it); the recommended setup and `--yes` keep the defaults. A team floor stricter than a default is shown with why (`Your team requires Careful or stricter in Staging.`), and choices below it aren't offered. A CLI credential can only make presets stricter; a looser pick says so in one line and keeps the current ones. A re-run lists them under Already set up without asking. The closing list says what will ask: `Autopilot on. You'll be asked only for Production changes, deletes outside Development, and irreversible actions.` A server without Autopilot gets the earlier Safety step instead.
152
155
 
153
156
  What changes on disk, and how to undo it:
154
157
 
@@ -162,7 +165,7 @@ What changes on disk, and how to undo it:
162
165
  | VS Code user `mcp.json` | `servers.passport` | `MCP: List Servers`, then remove it |
163
166
  | `~/.claude/settings.json`, `~/.codex/hooks.json`, `~/.cursor/hooks.json` | Passport's audit and guard hooks | `passport hook uninstall --agent <agent> --apply` |
164
167
 
165
- Before editing a file it didn't create, init says which file and keeps one copy of the original as `<file>.passport-backup`. It changes only Passport's own entries, writes atomically, refuses a malformed file with one line, and leaves an existing Passport entry alone unless it points at npm's cache or a file that's gone. Ctrl-C at any point stops cleanly; run init again to pick up where it left off. A question only takes keys typed after it appears, so an Enter pressed during a pause never answers it. Any wait longer than a moment shows what it's for in the step's row (`Sign in Checking your sign-in…`); off a terminal nothing extra prints. If Passport can't be reached, init says `Couldn't reach Passport at <origin>. Check your connection, then run passport init again.` and exits 1. Without a terminal, `init` needs `--yes` (exit 6 otherwise), and `--json` needs `--yes`. It never edits your shell profile: it prints the one `PATH` line to add if you want `passport` everywhere.
168
+ The plan names every file init edits before it edits any, and it keeps one copy of each original as `<file>.passport-backup`. It changes only Passport's own entries, writes atomically, refuses a malformed file with one line, and leaves an existing Passport entry alone unless it points at npm's cache or a file that's gone. Ctrl-C at any point stops cleanly; run init again to pick up where it left off. A question only takes keys typed after it appears, so an Enter pressed during a pause never answers it. Any wait longer than a moment shows what it's for in the step's row (`Sign in Checking your sign-in…`), clipped to one row so it's always replaced cleanly, and work that holds the terminal (an agent's own CLI, copying the CLI for the hooks) says so before it starts; off a terminal nothing extra prints. Everything wraps to the terminal's width, at least 40 columns. If Passport can't be reached, init says `Couldn't reach Passport at <origin>. Check your connection, then run passport init again.` and exits 1. Without a terminal, `init` needs `--yes` or `--dry-run` (exit 6 otherwise); `--json` without `--yes` is a dry run. It never edits your shell profile: it prints the one `PATH` line to add if you want `passport` everywhere.
166
169
 
167
170
  ### Company rollout
168
171
 
@@ -276,26 +279,32 @@ passport actions sync # propose this repository's .passport/actions.toml
276
279
  - `env` lists where commands in this folder land, read the way each vendor's own CLI reads it (`src/envResolve.ts`; order: flag, the folder's link, the vendor's default, the workspace's saved mapping, the whole-word naming rule, else Production). Link readers: `src/envLinksHosting.ts` (Railway `~/.railway/config.json`, Vercel `.vercel/project.json` / `repo.json`, Supabase `supabase/.temp/project-ref`, Wrangler config, Netlify `.netlify/state.json`, Firebase `.firebaserc` + configstore, Convex `CONVEX_DEPLOYMENT`, Neon `.neon`), `src/envLinksCloud.ts` (Fly, Heroku git remotes, kubeconfig, AWS profile, gcloud configuration, Terraform workspace, Stripe key mode), and `src/envDatabase.ts` (database URLs: only `DATABASE_URL`, `DIRECT_URL`, `POSTGRES_URL*`, `DATABASE_URL_UNPOOLED`, reduced to a host-derived key; the URL, user, and password never leave the function). Files are read fresh for every command, size-capped, and a link file symlinked out of the project is ignored (`src/envLinkFs.ts`). For a placed id its mapping decides, and a different name in the link file is treated as a rename (sent as the new label, which the server stores). A name in a link file never loosens anything: an unplaced id is named only by a label the server confirmed through the connected app (`resources[].confirmed`), which the naming rule then reads (`source: "name"`, shown as `Staging (from its name)`); without one, or when it says nothing, it is assumed Production. The table keeps its columns when every row fits the terminal and stacks each row otherwise. Findings to a server that sends `resources` in cli-policy v2 carry `{kind, source, resourceKey?, label?, platform?, flag?, via}`. `env set` calls `PUT /api/my/environments/:platform/:key`; members may only say Production.
277
280
 
278
281
  - `rules test` classifies the command here and sends only its app and verb (and the environment kind) to `POST /api/my/rules/test`, never the command line. An everyday command goes as a finding (`{finding: {vendor, verb, risk, environment}}`), because only this computer can place its paths. It prints the decision, its cause, the environment, and the class. Without a server answer it decides from this computer's copy and says how old it is. `--environment` picks one when the flags don't say.
279
- - `wait` long-polls `GET /api/my/approvals/<id>/wait`. Approved: `Approved by Ramish. Run the command again.` (exit 0). Declined: the note for the agent, `Declined by Ramish: <note>` (exit 5, cause `approval_denied`). Expired: `Expired. The agent can ask again.` (exit 5, cause `approval_expired`). Still waiting at `--timeout` (default 100 seconds, under an agent's 2-minute command limit): exit 4 with the same command as `next`.
282
+ - `wait` long-polls `GET /api/my/approvals/<id>/wait`, after a short first look that names who decides. On a terminal it prints the approval link at once and one live line (`Waiting for Erin · 1:32 left`); piped, `Waiting for a decision on <id> (up to 100 seconds).` and `Open in Passport: <url>` once Passport says it's still pending. Ctrl-C exits 4 with `The request is still open. Run passport wait <id> to keep waiting.` Approved: `Approved by Ramish. Run the command again.` (exit 0). Declined: the note for the agent, `Declined by Ramish: <note>` (exit 5, cause `approval_denied`). Expired: `Expired. The agent can ask again.` (exit 5, cause `approval_expired`). Still waiting at `--timeout` (default 100 seconds, under an agent's 2-minute command limit): exit 4 with the same command as `next`.
280
283
  - `sessions` lists recent sessions (`GET /api/my/agent-sessions`): status, agent, folder, start, `42 ran · 2 asked · 1 blocked`, environments touched, and `Waiting for you` when approvals are pending.
281
284
  - `sync` writes the allows Passport is sure of into each agent's own permission settings, so those prompts disappear offline and in Codex (`src/nativeSync.ts`). Only reads, test runners, builds and type checks, linters that only check, `git status`, `git add`, and `git commit`, checked against the person's rules. Formatters, fixing linters, `mv`/`cp`, and package scripts stay with the hook, which sees what they touch; deletes, installs, pushes, and Production never sync. Claude Code: `Bash(npm test *)` in `permissions.allow` of `~/.claude/settings.json`. Codex: `prefix_rule(pattern = ["npm", "test"], decision = "allow")` in `~/.codex/rules/passport.rules`, a file Passport owns. Cursor CLI: `Shell(npm:test*)` in `permissions.allow` of `~/.cursor/cli-config.json`. Cursor: `npm test` in `terminalAllowlist` of `~/.cursor/permissions.json`, only when that list already exists there (defining it replaces Cursor's in-app list). Entries Passport added are listed in `$PASSPORT_HOME/native-sync.json`; an entry you had before is never claimed or removed, and a file Passport can't parse exactly (JSONC) is left alone. Sync runs on `init`, `setup --org`, every rules refresh, and `passport sync`; `hook uninstall`, `sync --remove`, and signing out of the last profile take the entries out.
282
- - `status` adds each agent's guard (`Guard: Claude Code On · Codex Not trusted`), the coverage line, and each fix, and sends the daily guard report when due. It also adds today's speed line, `Passport added 0.3 s and asked you twice today. 412 actions ran on their own.` (across your computers when the server keeps speed numbers, else `(this computer)`), and `Answered for you: N prompts today` (allows the hook gave in Claude Code and Cursor, and Codex commands Passport synced, counted only when the agent would have prompted) and which agents' allowlists are synced. Under the presets, one line per exception that lets something run your presets would ask about, in the web's words: `! 1 exception: deletes run in Production without asking, even without a backup.` Counts are appended locally (`$PASSPORT_HOME/answered/`) and sent in batches at most every five minutes as `answered: {batch, count}` on `POST /api/my/cli-activity`.
285
+ - `status` is one screen, like `gh auth status`, with a label per row (`You` with the name you signed in as, `Computer`, `Guard`, `Autopilot`, `Apps`, `Keys`, `Shims`, `This folder`, `Allowlists`, `CLI`); under 60 columns each label gets its own row, and piped it never wraps. `Guard` lists each agent's guard (`✓ Claude Code On`, `! Codex Not trusted`) with its fix on the line under it, the coverage line, and sends the daily guard report when due. It also adds today's speed line, `Passport added 0.3 s and asked you twice today. 412 actions ran on their own.` (across your computers when the server keeps speed numbers, else `(this computer)`), and `Answered for you: N prompts today` (allows the hook gave in Claude Code and Cursor, and Codex commands Passport synced, counted only when the agent would have prompted) and which agents' allowlists are synced. Under the presets, one line per exception that lets something run your presets would ask about, in the web's words: `! 1 exception: deletes run in Production without asking, even without a backup.` Counts are appended locally (`$PASSPORT_HOME/answered/`) and sent in batches at most every five minutes as `answered: {batch, count}` on `POST /api/my/cli-activity`.
283
286
  - `actions` tells Passport what a project script does (`src/cliActions.ts`): `actions add <script> [args…] --environment <kind> --class <class>` sends the path in the repository (or `make`, `npm`, `pnpm`, `yarn` with the target), an argument glob, the repository's remote fingerprint and name, and the SHA-256 of what it runs, never its contents, to `POST /api/my/project-actions`. `--id <op_…>` resolves a Session row's **Tell Passport what this does** from this computer's scan cache. `actions sync` proposes each entry of `.passport/actions.toml`. A change, delete, or irreversible in Production applies at once; anything looser waits for an admin. The guard then decides a matching run as vendor `project` with that class and environment; it never makes a line allowed on its own, and a changed script stops matching (`projectChanged`) until it's set again. `.passport/actions.toml` entries apply locally only when they ask or block.
284
287
  - `rules test`, `sessions`, `actions`, and `sync` need a member profile. `wait` also works for a cloud agent's key, on the approval its own `passport exec` opened.
285
288
 
286
289
  ### Keys and passport exec
287
290
 
288
291
  ```sh
289
- passport keys move # confirm each key [y/n], store it in Passport, sign that CLI out here
292
+ passport keys move # confirm each key [y/N], store it in Passport, sign that CLI out here
293
+ passport keys move railway # only the Railway key
290
294
  passport keys # what Passport holds, and what's still on this computer
291
295
  passport keys add railway # store a key you paste (stdin, never echoed)
292
296
  passport exec -- railway up -e staging
297
+ passport keys shim # the CLIs that run through Passport when you type them
293
298
  ```
294
299
 
300
+ - Shims keep a moved CLI working when you type it. After each key it moves, `keys move` asks `Keep typing railway in your terminal? Passport runs it with the key it now holds. [Y/n]` (`--yes` installs, `--no-shim` skips) and writes `~/.passport/cli/bin/railway`, which runs `passport exec -- railway "$@"` through the stable launcher. Put that folder ahead of the vendor's on PATH; when it isn't, the CLI prints the same `export PATH=…` line init prints (it never edits your shell profile). `passport keys shim <cli>` adds one, `--remove <cli|all>` takes them out, and `status --json` lists them under `shims`. `exec` never runs a shim: it finds the vendor's own CLI past Passport's folder and anything carrying the shim marker, and a shim stops after three nested calls. A shim goes by itself when Passport no longer holds that vendor's key and when the last profile signs out. POSIX only.
301
+ - Masking, like `op run`, when stdout isn't a terminal (an agent's shell, a pipe, a CI log, where output is kept and read later): `exec` reads the CLI's stdout and stderr and replaces each issued value (raw, base64, URL-encoded) with `<hidden by Passport>`. Output streams; the exit code (or 128 + signal) passes through. In a terminal the CLI gets the terminal itself (colors, prompts), unmasked: a person watching their own screen isn't the risk. `--mask` masks in a terminal too (the CLI then writes to a pipe); `--no-masking` (or `PASSPORT_EXEC_NO_MASKING=1` through a shim) never masks. Cost on an M-series Mac (`npm run bench:mask`): about 625 MB/s through the masker against 1,155 MB/s for a bare pipe, and a few microseconds per line.
302
+ - Releases: Passport's own release computer keeps its Railway sign-in, so releases never depend on Passport. In a repository with `scripts/lib/local-release-controller.mjs`, `keys move` and `init` ask `This computer deploys Passport with the Railway CLI. Moving the key will stop releases. Keep it here? [Y/n]` (Enter, `--yes`, and no terminal keep it). Release attestation checks the exact Railway CLI binary on PATH with a throwaway HOME, so a shim in front of it fails closed. See `docs/DEPLOY.md`.
303
+
295
304
  - After a move, `keys move` remembers where each removed key was in `$PASSPORT_HOME/keys-moved.json` (vendor, `~/…` location, file, field names, size, modified time; never a value or hash). With the daily guard report, files that changed are read again; a key that's back is reported as `reappeared: [vendor]` on `POST /api/my/keys/report`, so the key reads "Back on <computer>" in Apps with the fix `passport keys move`. Kept keys are never listed. The report's computer is the CLI's own sign-in (its Device); the name it sends stays for older servers.
296
- - `keys move` finds CLI sign-ins (Railway, GitHub CLI, Vercel, Wrangler API tokens, Supabase, Stripe test keys, the AWS `default` profile) and tokens in Claude Code's settings `env`. For each it asks `[y/n]` with no default (an empty answer asks again; `--yes` moves them all), stores the key in Passport (`POST /api/my/keys`), then signs that CLI out by removing only the credential: the token fields of `~/.railway/config.json` (project links stay), `token` in Vercel's `auth.json` (not revoked; the current team stays), Wrangler's sign-in keys in `default.toml`, the Supabase `access-token` file and its keychain token (saved database passwords stay), the Stripe profile's API keys and its live key in the keychain (account, color, and other profiles stay), the AWS profile's key lines, or the one settings entry. Files are written atomically with their mode kept. Vendor sign-outs don't run because they do more (`railway logout` unlinks every project, `vercel logout` revokes the token Passport just stored); only the GitHub CLI's `gh auth logout --hostname github.com` runs, adding `--user <active>` when several accounts are signed in, so other hosts and accounts stay. Keychain items are deleted by exact service and account (`security delete-generic-password` on macOS, `secret-tool clear` on Linux); where that isn't possible the row says which keychain copy may stay. Wrangler OAuth tokens are removed locally, not revoked. A sign-out that fails leaves the key in Passport and says what's left on disk. `.env` files are never touched: "Used by your app, so Passport leaves it." Browser-session sign-ins (Railway, Vercel, Wrangler OAuth) can't move; the line says how to make a token instead. A different key than the one already in Passport is replaced only when the person answers yes to `Replace the <CLI> key in Passport with the one on this computer? [y/n]`; the CLI then names the key it replaces (`replace: <keyId>` on `POST /api/my/keys`). The server alerts the owner and admins with an Undo, records it in the audit trail, and keeps the old value encrypted for seven days (`POST /api/my/keys/:id/restore` from the browser, or the alert). Without a person (`--yes`, no terminal), both keys stay. The scan report sent afterwards carries provider counts only.
305
+ - `keys move` finds CLI sign-ins (Railway, GitHub CLI, Vercel, Wrangler API tokens, Supabase, Stripe test keys, the AWS `default` profile) and tokens in Claude Code's settings `env`. For each it asks `[y/N]` (Enter keeps it; `--yes` moves them all; `keys move <cli>` only that CLI's), stores the key in Passport (`POST /api/my/keys`), then signs that CLI out by removing only the credential: the token fields of `~/.railway/config.json` (project links stay), `token` in Vercel's `auth.json` (not revoked; the current team stays), Wrangler's sign-in keys in `default.toml`, the Supabase `access-token` file and its keychain token (saved database passwords stay), the Stripe profile's API keys and its live key in the keychain (account, color, and other profiles stay), the AWS profile's key lines, or the one settings entry. Files are written atomically with their mode kept. Vendor sign-outs don't run because they do more (`railway logout` unlinks every project, `vercel logout` revokes the token Passport just stored); only the GitHub CLI's `gh auth logout --hostname github.com` runs, adding `--user <active>` when several accounts are signed in, so other hosts and accounts stay. Keychain items are deleted by exact service and account (`security delete-generic-password` on macOS, `secret-tool clear` on Linux); where that isn't possible the row says which keychain copy may stay. Wrangler OAuth tokens are removed locally, not revoked. A sign-out that fails leaves the key in Passport and says what's left on disk. `.env` files are never touched: "Used by your app, so Passport leaves it." Browser-session sign-ins (Railway, Vercel, Wrangler OAuth) can't move; the line says how to make a token instead. A different key than the one already in Passport is replaced only when the person types the CLI's name at a terminal (`Type railway to confirm, or press Enter to cancel:`); no flag does it, so an agent's script can never swap a key. The CLI then names the key it replaces (`replace: <keyId>` on `POST /api/my/keys`). The server alerts the owner and admins with an Undo, records it in the audit trail, and keeps the old value encrypted for seven days (`POST /api/my/keys/:id/restore` from the browser, or the alert). Without a person at a terminal (`--yes`, no terminal), both keys stay, and the line says `Replacing a key in Passport needs you at a terminal. Run passport keys move railway yourself.` The scan report sent afterwards carries provider counts only.
297
306
  - `exec -- <cli> …` runs railway, gh, vercel, wrangler, supabase, stripe, aws, neonctl, or flyctl from PATH. It classifies the command here, asks `POST /api/my/exec/authorize`, and on allow sets only that vendor's variables (`GH_TOKEN`, `RAILWAY_API_TOKEN`, `VERCEL_TOKEN`, `CLOUDFLARE_API_TOKEN`, `SUPABASE_ACCESS_TOKEN`, `STRIPE_API_KEY`, `AWS_*`, `NEON_API_KEY`, `FLY_API_TOKEN`) in the child's environment, removing Passport's own and any stray vendor tokens. Output and exit code pass through. Afterwards it reports the exit code and duration (`POST /api/my/exec/result`, best effort, two seconds at most) so the session row reads Ran or Failed. It refuses paths, shells, `env`, and subcommands that would print the key, sign in again, mint longer-lived tokens, or run another program with the key (`railway run`, `gh auth`, gh extensions, `aws configure`, `vercel dev`, `fly tokens`).
298
- - Asks wait for your approval in Passport (web or push) when you're at the keyboard or with `--wait <sec>`; otherwise exit 4 with the approval id: run `passport wait <id>`, then the command again. An approval is used once. Blocked or declined: exit 5. No key, or it stopped working: exit 3 ("Your Railway key in Passport stopped working. Update it in Apps."). Offline: exit 1, nothing runs, and exec never uses a key on this computer instead. A team that requires the guard refuses exec for an agent whose computer hasn't reported its guard On in 48 hours: exit 5 with `Blocked by Passport: guard required…` and the fix.
307
+ - Asks wait for your approval in Passport (web or push) when you're at the keyboard or with `--wait <sec>`; otherwise exit 4 with the approval id: run `passport wait <id>`, then the command again. While it waits, the approval link prints at once and, on a terminal, one live line counts down (`Waiting for Erin · 1:32 left`); piped, it prints the waiting line and `Open in Passport: <url>`. Ctrl-C exits 4: `The request is still open. Run passport wait <id> to keep waiting, then run the command again.` An approval is used once. Blocked or declined: exit 5. A decline answers the same command for ten minutes, said with who and when: `Declined 2 minutes ago by Erin: Not during the freeze.` and `Run with --ask-again to request again.`; `--ask-again` opens a new request. No key, or it stopped working: exit 3 (`No Railway key in Passport yet. Add a Railway key in Passport → Apps.`, or `Your Railway key in Passport stopped working. Update it in Apps.`). When this computer still has the Railway CLI's own sign-in, the no-key line is `No Railway key in Passport yet, but this computer has one. Run passport keys move railway` instead (read here; Passport never sees this computer's files). Offline: exit 1, nothing runs, and exec never uses a key on this computer instead. A team that requires the guard refuses exec for an agent whose computer hasn't reported its guard On in 48 hours: exit 5 with `Blocked by Passport: guard required…` and the fix.
299
308
  - In Claude Code, the guard rewrites a plain vendor command whose key is in Passport to `passport exec` (PreToolUse `updatedInput` with allow; a block stays a deny). When the rules ask, or someone is at the keyboard, the rewrite adds `--wait 120`, so the agent holds while the person approves: "Approve it on your phone or in Passport." Codex and Cursor get no rewrite: use `passport exec` there.
300
309
  - Cloud agents (Agents → Cloud agents) run exec and MCP with `PASSPORT_AGENT_KEY` and `PASSPORT_ENDPOINT`: the owner's rules decide, the owner's keys are used, and approvals go to the owner.
301
310
  - Backups: for `gh issue close`, `gh pr close`, `gh api -X DELETE` of a branch, `vercel env rm`, `vercel rollback`, and `vercel promote`, exec also sends the ids Passport needs to take a backup first (repo and number or branch; the linked Vercel project and variable name from `.vercel/project.json`), never a value. After the run it prints `Backup taken. Undo within 7 days: passport undo <action-id>`, or `No backup: <reason>` for a delete it couldn't back up.
@@ -411,15 +420,21 @@ const actions = await client.actions(); // or client.actions(delegationId)
411
420
 
412
421
  ## Output contract
413
422
 
414
- With `--json`, stdout is exactly one JSON value; hints and warnings go to stderr.
423
+ With `--json`, stdout is exactly one JSON value; hints and warnings go to stderr. JSON shapes only gain fields.
424
+
425
+ A mistyped command, option, subcommand, or `help <command>` exits 6 with the closest match, stated rather than asked (`Unknown command "stauts". Did you mean: passport status`, `Unknown option "--jsn". Did you mean: --json`); with `--json` the match is in `next`. With nothing close it says where to look (`Run passport help to see every command.`). `help <unknown>` never prints the general help. Help pages lead with examples, and `passport help` ends with the exit codes below.
426
+
427
+ Questions follow one convention (`src/cliAsk.ts`), only on a terminal: `[Y/n]` for a safe step (Enter is yes); `[y/N]` for a destructive one, such as signing a CLI out, switching who you're signed in as, or an undo (Enter is no); and for a severe one you type its name (`Type railway to confirm, or press Enter to cancel:`). `--yes` never answers a severe question. A severe step a script may take gets `--confirm=<name>`; replacing a key Passport holds, today's only severe step, deliberately has no flag, so it only ever happens on a person's answer at a terminal.
428
+
429
+ On a terminal, human output comes from one renderer (`src/term.ts`): it wraps to the window's width (at least 40 columns, at most 100) without breaking a URL or a `passport` command, hangs wrapped lines under their label or mark, stacks a table one row at a time when its columns don't fit, and clips a live line (a countdown, a "Checking…" row) to one row so it's always replaced cleanly. Marks always sit next to words (`✓ On`, `! Not trusted`, `– skipped`), with `+`, `!`, `-` where the terminal can't show them. Piped output never wraps, has no color, and draws no live lines. `NO_COLOR` and `TERM=dumb` turn color off.
415
430
 
416
431
  | Command | JSON value |
417
432
  | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
418
- | `login` | `{profile,endpoint,client,surface,active,workspaceId,workspaceName?,next}` (`workspaceName` after browser sign-in) |
433
+ | `login` | `{profile,endpoint,client,surface,active,workspaceId,workspaceName?,memberName?,next}`; without a terminal or with `--json`, step one is `{status:"pending",verification_url,code,expires_in,next_step,login_id,next}` |
419
434
  | `profiles` | `{profiles:[{name,active,client?}],active?}` |
420
435
  | `use` | `{profile,active:true}` |
421
- | `logout` | `{profile,removed,revoked}` |
422
- | `status` | `{workspace,member,endpoint,auth,profile?,client,mcps,autopilot?:{presets,floors,floorReason?,exceptions?,cache:{version,fetchedAt,ageMs}},next?}` |
436
+ | `logout` | `{profile,removed,revoked,shimsRemoved?}` |
437
+ | `status` | `{workspace,member,endpoint,auth,profile?,client,mcps,autopilot?:{presets,floors,floorReason?,exceptions?,cache:{version,fetchedAt,ageMs}},next?,computer,keys?,keysOnThisComputer?,folder,cli:{version},signedInAs?,shims?:[{vendor,command,state}]}` |
423
438
  | `wait` | `{approvalId,status:"approved",scope?,message}`; declined, expired, and still-waiting are errors with `approvalId` |
424
439
  | `rules` | `{command,decision,cause?,explanation?,environment?,environmentAssumed?,actionClass?,source}` |
425
440
  | `sessions` | `{sessions:[{id,client,folder,status,startedAt,lastActivityAt,counts,environments,waiting}],nextCursor}` |
@@ -449,7 +464,7 @@ Errors: `{"error":"...","cause":"blocked","exitCode":5,"app":"github"}`, optiona
449
464
  | 3 | App needs member sign-in |
450
465
  | 4 | Approval pending (including `wait` still waiting at its timeout) |
451
466
  | 5 | Policy, guardrail, selection, or approval denial (including a declined or expired approval in `wait`) |
452
- | 6 | Invalid usage or unknown tool/app |
467
+ | 6 | Usage mistake: an unknown command, option, tool, or app (with the closest match when there is one) |
453
468
 
454
469
  ## MCP stdio bridge
455
470
 
@@ -472,6 +487,8 @@ passport-bridge serve --profile cursor@ws_example
472
487
 
473
488
  ## Maintainers
474
489
 
490
+ Startup: `dist/passport.js` (the npm bin, the launcher `$PASSPORT_HOME/cli/bin/passport`, and `passport.cmd` on Windows) and the hooks' `dist/hookMain.js` are tiny entries that turn on Node's compile cache (`module.enableCompileCache`, `src/compileCache.ts`) before loading the CLI (`src/cliMain.ts`), so the second and later runs skip compiling it. The cache is `$PASSPORT_HOME/cli/compile-cache` (`~/.passport/cli/compile-cache`), created 0700 and used only while it's owned by this user and nobody else can write it: never the repository or the system's temp folder. `NODE_COMPILE_CACHE` and `NODE_DISABLE_COMPILE_CACHE` keep Node's meaning. `npm run bench:guard` times the guard and `version`, `--help`, and `status` (piped, Passport refusing connections) through the launcher; `PASSPORT_BENCH_NO_CACHE=1` times the same build without the cache. The hook path never loads the renderer or prompt code (`src/termImports.test.ts`).
491
+
475
492
  Tests never reach production Passport: `scripts/no-production-guard.mjs` is preloaded by the unit tests and, through `NODE_OPTIONS`, by every process `cli-e2e.ts` starts, and any request to passportmcp.com fails the run. Harnesses use a local server with `--cloud http://127.0.0.1:<port>` (or `PASSPORT_CLOUD`) and `PASSPORT_NO_OPEN=1`.
476
493
 
477
494
  `npm run pack:verified` builds the npm tarball, checks required files, and writes a `.sha256` checksum file (verify with `sha256sum -c passport-bridge-<version>.tgz.sha256`). Releases publish only through the repository's npm trusted-publisher workflow.
package/dist/cli.js CHANGED
@@ -38,7 +38,7 @@ async function passportOneLiner() {
38
38
  return;
39
39
  }
40
40
  ensureOneLinerRuntime();
41
- const { main: passport } = await import("./passport.js");
41
+ const { main: passport } = await import("./cliMain.js");
42
42
  process.exitCode = await passport(process.argv.slice(2), process.env, {
43
43
  stdin: process.stdin,
44
44
  stdout: process.stdout,
@@ -62,7 +62,11 @@ async function main() {
62
62
  return logout();
63
63
  if (command === "status")
64
64
  return status();
65
- process.stderr.write(`Unknown command: ${command}\nRun \`passport-bridge --help\` for usage.\n`);
65
+ const { closest } = await import("./cliSuggest.js");
66
+ const guess = closest(command, ["serve", "login", "logout", "status", "help", "version", ...PASSPORT_ONE_LINERS]);
67
+ process.stderr.write(guess
68
+ ? `Unknown command "${command}". Did you mean: passport-bridge ${guess}\n`
69
+ : `Unknown command "${command}". Run passport-bridge --help to see every command.\n`);
66
70
  process.exit(1);
67
71
  }
68
72
  function help() {
@@ -23,6 +23,8 @@ import { memberApi } from "./cliClient.js";
23
23
  import { localMachine, NODE_FS } from "./cliHookLocal.js";
24
24
  import { lookupOpaqueId, normalizeRemote, originUrl, remoteFingerprint, sha256 } from "./cliScriptRead.js";
25
25
  import { linesDigestInput, makeLines, packageLines, parseRepoActions } from "./cliScriptText.js";
26
+ import { unknownSubcommand } from "./cliSuggest.js";
27
+ import { table, termOf } from "./term.js";
26
28
  import { callerFrom, failure, resolveCliAuth, safeApiError, timeoutMs } from "./cliSupport.js";
27
29
  const ENVIRONMENTS = new Set(["production", "staging", "development"]);
28
30
  const CLASSES = new Set(["read", "change", "delete", "irreversible"]);
@@ -196,19 +198,22 @@ async function list(args, runtime, deps) {
196
198
  return failure(await safeApiError(response, "Passport couldn't list them."), 1, "server");
197
199
  const body = (await readBoundedJson(response).catch(() => ({})));
198
200
  const actions = body.projectActions ?? [];
199
- const human = actions.length
200
- ? actions
201
- .map((action) => {
202
- const where = action.environment ? (ENV_WORD[action.environment] ?? action.environment) : "";
203
- const notes = [
204
- action.repoName ?? "Any repository",
205
- ...(action.setByName ? [`Set by ${action.setByName}`] : []),
206
- ...(action.status === "proposed" ? ["Proposed"] : []),
207
- ...(action.changedAt ? ["Changed since set"] : [])
208
- ];
209
- return `${action.label ?? "script"} ${where} · ${action.actionClass ?? ""} ${notes.join(" · ")}`;
210
- })
211
- .join("\n")
201
+ // One aligned row per script (script, environment, class, repository,
202
+ // notes); on a narrow terminal each row stacks.
203
+ const rows = actions.map((action) => [
204
+ action.label ?? "script",
205
+ action.environment ? (ENV_WORD[action.environment] ?? action.environment) : "",
206
+ action.actionClass ?? "",
207
+ action.repoName ?? "Any repository",
208
+ [
209
+ ...(action.setByName ? [`Set by ${action.setByName}`] : []),
210
+ ...(action.status === "proposed" ? ["Proposed"] : []),
211
+ ...(action.changedAt ? ["Changed since set"] : [])
212
+ ].join(" · ")
213
+ ]);
214
+ const width = termOf((runtime.stdout ?? {}), runtime.env).width;
215
+ const human = rows.length
216
+ ? table(rows, width).join("\n")
212
217
  : "No project scripts yet. Add one: passport actions add <script> --environment <kind> --class <class>";
213
218
  return { json: { actions }, human };
214
219
  }
@@ -220,5 +225,6 @@ export async function actions(args, runtime, deps = {}) {
220
225
  return add(args, runtime, deps);
221
226
  if (action === "sync")
222
227
  return sync(args, runtime, deps);
223
- return failure("Use passport actions, actions add, or actions sync.", 6, "usage");
228
+ const unknown = unknownSubcommand("actions", action, ["list", "add", "sync"]);
229
+ return failure(unknown.message, 6, "usage", unknown.next ? { next: unknown.next } : {});
224
230
  }
package/dist/cliArgs.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  export declare const COMMANDS: readonly ["init", "login", "logout", "profiles", "use", "status", "doctor", "ready", "search", "describe", "run", "connect", "resources", "prompts", "discover", "scan", "hook", "wait", "rules", "actions", "sessions", "env", "sync", "exec", "undo", "keys", "setup", "session", "access", "completion", "help", "version"];
2
2
  export type Command = (typeof COMMANDS)[number];
3
+ /** A usage mistake. `suggestion` is the command the person most likely meant. */
3
4
  export declare class ArgError extends Error {
5
+ readonly suggestion?: string[] | undefined;
6
+ constructor(message: string, suggestion?: string[] | undefined);
4
7
  }
5
8
  export type ParsedArgs = {
6
9
  command: Command;
package/dist/cliArgs.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { closest } from "./cliSuggest.js";
1
2
  export const COMMANDS = [
2
3
  "init",
3
4
  "login",
@@ -54,6 +55,8 @@ const FLAGS = {
54
55
  "skip-agents": { kind: "boolean", commands: ["init"] },
55
56
  "skip-guard": { kind: "boolean", commands: ["init"] },
56
57
  "move-keys": { kind: "boolean", commands: ["init"] },
58
+ "dry-run": { kind: "boolean", commands: ["init"] },
59
+ "ask-again": { kind: "boolean", commands: ["exec"] },
57
60
  app: { kind: "value", commands: ["search"] },
58
61
  args: { kind: "value", commands: ["run", "actions"] },
59
62
  id: { kind: "value", commands: ["actions"] },
@@ -65,7 +68,12 @@ const FLAGS = {
65
68
  alias: { kind: "value", commands: ["connect"] },
66
69
  open: { kind: "boolean", commands: ["connect"] },
67
70
  out: { kind: "value", commands: ["resources", "prompts"] },
68
- verbose: { kind: "boolean", commands: ["scan", "init", "exec"] },
71
+ verbose: { kind: "boolean", commands: ["scan", "init", "exec", "login"] },
72
+ "no-masking": { kind: "boolean", commands: ["exec"] },
73
+ mask: { kind: "boolean", commands: ["exec"] },
74
+ "no-shim": { kind: "boolean", commands: ["keys"] },
75
+ switch: { kind: "boolean", commands: ["login"] },
76
+ complete: { kind: "value", commands: ["login"] },
69
77
  path: { kind: "value", commands: ["scan"] },
70
78
  check: { kind: "boolean", commands: ["scan"] },
71
79
  input: { kind: "value", commands: ["access"] },
@@ -76,7 +84,7 @@ const FLAGS = {
76
84
  "client-id": { kind: "value", commands: ["access"] },
77
85
  environment: { kind: "value", commands: ["rules", "actions"] },
78
86
  status: { kind: "value", commands: ["sessions"] },
79
- remove: { kind: "boolean", commands: ["sync"] },
87
+ remove: { kind: "boolean", commands: ["sync", "keys"] },
80
88
  last: { kind: "boolean", commands: ["undo"] },
81
89
  option: { kind: "value", commands: ["undo"] }
82
90
  };
@@ -84,7 +92,34 @@ const FLAGS = {
84
92
  const FLAG_ALIASES = { agent: "client", agents: "clients" };
85
93
  const shownFlag = (name) => Object.keys(FLAG_ALIASES).find((alias) => FLAG_ALIASES[alias] === name) ?? name;
86
94
  const passedTwice = (name) => shownFlag(name) === name ? `--${name} may only be passed once.` : `Pass --${shownFlag(name)} or --${name} once.`;
95
+ /** A usage mistake. `suggestion` is the command the person most likely meant. */
87
96
  export class ArgError extends Error {
97
+ suggestion;
98
+ constructor(message, suggestion) {
99
+ super(message);
100
+ this.suggestion = suggestion;
101
+ }
102
+ }
103
+ /** Every option name a command takes, as typed (`--agent`, not `--client`). */
104
+ function optionsFor(command) {
105
+ const names = Object.keys(FLAGS)
106
+ .filter((name) => !command || !FLAGS[name].commands || FLAGS[name].commands.includes(command))
107
+ .map(shownFlag);
108
+ return [...new Set(names)];
109
+ }
110
+ function unknownCommand(raw, help = false) {
111
+ const guess = closest(raw, COMMANDS);
112
+ const argv = guess ? ["passport", ...(help ? ["help"] : []), guess] : undefined;
113
+ return new ArgError(`Unknown command "${raw}". ${argv ? `Did you mean: ${argv.join(" ")}` : "Run passport help to see every command."}`, argv);
114
+ }
115
+ function unknownOption(raw, command) {
116
+ const given = raw.startsWith("--") ? flagParts(raw).name : raw.replace(/^-+/, "");
117
+ const guess = closest(given, optionsFor(command));
118
+ if (guess) {
119
+ return new ArgError(`Unknown option "${raw}". Did you mean: --${guess}`, command ? ["passport", command, `--${guess}`] : undefined);
120
+ }
121
+ const where = command && command !== "help" ? `passport help ${command}` : "passport help";
122
+ return new ArgError(`Unknown option "${raw}". Run ${where} to see the options.`);
88
123
  }
89
124
  function knownCommand(value) {
90
125
  return COMMANDS.includes(value);
@@ -102,6 +137,9 @@ export function parseArgs(argv) {
102
137
  const repeats = {};
103
138
  const booleans = new Set();
104
139
  let positionalOnly = false;
140
+ // An unknown option is reported once the command is known, so the
141
+ // suggestion comes from that command's own options.
142
+ let unknown;
105
143
  for (let i = 0; i < argv.length; i++) {
106
144
  let raw = argv[i];
107
145
  if (!positionalOnly && raw === "--") {
@@ -121,8 +159,10 @@ export function parseArgs(argv) {
121
159
  const { name: given, inline } = flagParts(raw);
122
160
  const name = FLAG_ALIASES[given] ?? given;
123
161
  const spec = FLAGS[name];
124
- if (!spec)
125
- throw new ArgError(`Unknown option: --${given}`);
162
+ if (!spec) {
163
+ unknown ??= raw;
164
+ continue;
165
+ }
126
166
  if (spec.kind === "boolean") {
127
167
  if (inline !== undefined)
128
168
  throw new ArgError(`--${name} does not take a value.`);
@@ -144,11 +184,13 @@ export function parseArgs(argv) {
144
184
  }
145
185
  continue;
146
186
  }
147
- if (!positionalOnly && raw.startsWith("-") && raw !== "-")
148
- throw new ArgError(`Unknown option: ${raw}`);
187
+ if (!positionalOnly && raw.startsWith("-") && raw !== "-") {
188
+ unknown ??= raw;
189
+ continue;
190
+ }
149
191
  if (!command) {
150
192
  if (!knownCommand(raw))
151
- throw new ArgError(`Unknown command: ${raw}`);
193
+ throw unknownCommand(raw);
152
194
  command = raw;
153
195
  }
154
196
  else {
@@ -159,7 +201,14 @@ export function parseArgs(argv) {
159
201
  positionalOnly = true;
160
202
  }
161
203
  }
162
- command ??= "help";
204
+ if (unknown !== undefined)
205
+ throw unknownOption(unknown, command);
206
+ return settle({ command: command ?? "help", positionals, values, repeats, booleans });
207
+ }
208
+ /** `--help` becomes `help <command>`; then every option must fit the command. */
209
+ function settle(args) {
210
+ let { command } = args;
211
+ const { positionals, values, repeats, booleans } = args;
163
212
  if (booleans.has("help") && command !== "help") {
164
213
  positionals.splice(0, positionals.length, command);
165
214
  command = "help";
@@ -170,6 +219,8 @@ export function parseArgs(argv) {
170
219
  if (allowed && !allowed.includes(command))
171
220
  throw new ArgError(`--${shownFlag(name)} is not valid with ${command}.`);
172
221
  }
222
+ if (command === "help" && positionals[0] !== undefined && !knownCommand(positionals[0]))
223
+ throw unknownCommand(positionals[0], true);
173
224
  validateShape(command, positionals);
174
225
  validateNumbers(values);
175
226
  return { command, positionals, values, repeats, booleans };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The one question convention for every prompt the CLI shows (init, keys,
3
+ * undo, login):
4
+ *
5
+ * [Y/n] a safe step. Enter says yes.
6
+ * [y/N] a destructive step: it signs a CLI out, removes something
7
+ * from this computer, switches who you're signed in as, or
8
+ * undoes an action. Enter says no.
9
+ * type the name a severe step: it replaces a key every agent uses. Only the
10
+ * exact name says yes; Enter or anything else says no. A
11
+ * severe step a script may take gets --confirm=<name>; replacing
12
+ * a key Passport holds deliberately has none, so an agent's
13
+ * script can never swap one.
14
+ *
15
+ * A prompt only ever appears on a terminal. --yes answers safe and destructive
16
+ * questions, never a severe one.
17
+ */
18
+ export type Stakes = "safe" | "destructive";
19
+ export declare function choices(stakes: Stakes): "[Y/n]" | "[y/N]";
20
+ /** true or false, or undefined when the answer is neither. */
21
+ export declare function answerOf(answer: string, stakes: Stakes): boolean | undefined;
22
+ export declare const ASK_AGAIN = "Type y or n.";
23
+ /** Asks until the answer is yes, no, or Enter (the default). */
24
+ export declare function askYesNo(ask: (prompt: string) => Promise<string>, say: (text: string) => void, question: string, stakes: Stakes): Promise<boolean>;
25
+ /** The second line of a severe question. */
26
+ export declare function typeNamePrompt(name: string): string;
27
+ /** Only the exact name confirms. */
28
+ export declare function nameConfirmed(answer: string, name: string): boolean;
package/dist/cliAsk.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The one question convention for every prompt the CLI shows (init, keys,
3
+ * undo, login):
4
+ *
5
+ * [Y/n] a safe step. Enter says yes.
6
+ * [y/N] a destructive step: it signs a CLI out, removes something
7
+ * from this computer, switches who you're signed in as, or
8
+ * undoes an action. Enter says no.
9
+ * type the name a severe step: it replaces a key every agent uses. Only the
10
+ * exact name says yes; Enter or anything else says no. A
11
+ * severe step a script may take gets --confirm=<name>; replacing
12
+ * a key Passport holds deliberately has none, so an agent's
13
+ * script can never swap one.
14
+ *
15
+ * A prompt only ever appears on a terminal. --yes answers safe and destructive
16
+ * questions, never a severe one.
17
+ */
18
+ export function choices(stakes) {
19
+ return stakes === "safe" ? "[Y/n]" : "[y/N]";
20
+ }
21
+ /** true or false, or undefined when the answer is neither. */
22
+ export function answerOf(answer, stakes) {
23
+ const typed = answer.trim().toLowerCase();
24
+ if (typed === "y" || typed === "yes")
25
+ return true;
26
+ if (typed === "n" || typed === "no")
27
+ return false;
28
+ if (typed === "")
29
+ return stakes === "safe";
30
+ return undefined;
31
+ }
32
+ export const ASK_AGAIN = "Type y or n.";
33
+ /** Asks until the answer is yes, no, or Enter (the default). */
34
+ export async function askYesNo(ask, say, question, stakes) {
35
+ for (;;) {
36
+ const answer = answerOf(await ask(`${question} ${choices(stakes)} `), stakes);
37
+ if (answer !== undefined)
38
+ return answer;
39
+ say(ASK_AGAIN);
40
+ }
41
+ }
42
+ /** The second line of a severe question. */
43
+ export function typeNamePrompt(name) {
44
+ return `Type ${name} to confirm, or press Enter to cancel:`;
45
+ }
46
+ /** Only the exact name confirms. */
47
+ export function nameConfirmed(answer, name) {
48
+ return answer.trim() === name;
49
+ }
@@ -1,9 +1,7 @@
1
1
  /**
2
2
  * Autopilot from the terminal:
3
3
  *
4
- * passport wait <approval-id> [--timeout <sec>] wait for a person to decide
5
4
  * passport rules test "<command>" [--environment <kind>]
6
- * passport sessions [--status running|idle|ended]
7
5
  *
8
6
  * plus the Autopilot lines `passport status` adds. Every command here uses the
9
7
  * member API with a saved profile; agent keys have no person to wait for.
@@ -13,47 +11,14 @@
13
11
  import { type GuardStatus } from "./cliStatusGuard.js";
14
12
  import { type ParsedArgs } from "./cliArgs.js";
15
13
  import { type Preset, type PresetRow } from "./cliAutopilotPolicy.js";
16
- import { type MemberApi } from "./cliClient.js";
17
- import { type LocalMachine } from "./cliHookLocal.js";
18
14
  import { type EnvKind } from "./cliHookEnvironment.js";
19
- import { type LinkFs } from "./envLinkFs.js";
20
15
  export { env } from "./cliEnv.js";
21
16
  export { actions } from "./cliActions.js";
22
17
  import { type CommandResult, type Runtime } from "./cliSupport.js";
23
- /** Long enough to be useful, short enough for an agent's default 2-minute
24
- * command timeout. */
25
- export declare const WAIT_DEFAULT_SECONDS = 100;
26
- export type AutopilotDependencies = {
27
- api?: MemberApi;
28
- now?: () => number;
29
- /** The machine `rules test` reads paths on; tests pass a pretend one. */
30
- machine?: LocalMachine;
31
- /** Where folder links are read from; tests pass a pretend one. */
32
- linkFs?: LinkFs;
33
- };
34
- export declare function api(args: ParsedArgs, runtime: Runtime, deps: AutopilotDependencies, waitMs?: number, agentKeyOk?: boolean): MemberApi;
35
- export declare function json<T>(response: Response, fallback: string): Promise<T>;
36
- export declare function wait(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
18
+ export { api, json, type AutopilotDependencies } from "./cliMemberCall.js";
19
+ export { wait } from "./cliWait.js";
20
+ import { type AutopilotDependencies } from "./cliMemberCall.js";
37
21
  export declare function rules(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
38
- type SessionRow = {
39
- id?: unknown;
40
- client?: unknown;
41
- folder?: unknown;
42
- status?: unknown;
43
- startedAt?: unknown;
44
- lastActivityAt?: unknown;
45
- counts?: {
46
- ran?: unknown;
47
- asked?: unknown;
48
- approved?: unknown;
49
- declined?: unknown;
50
- blocked?: unknown;
51
- };
52
- environments?: unknown;
53
- waiting?: unknown;
54
- };
55
- export declare function sessionLine(row: SessionRow, now: number, unicode?: boolean): string;
56
- export declare function sessions(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
57
22
  export type AutopilotStatus = {
58
23
  /** The three environments, and "other" (Other apps) when the server has it. */
59
24
  presets: (Record<EnvKind, Preset> & Partial<Record<PresetRow, Preset>>) | null;
@@ -90,5 +55,3 @@ export type AutopilotStatus = {
90
55
  export { localMidnight } from "./cliSpeed.js";
91
56
  /** Read presets and floors for `passport status`. Never throws. */
92
57
  export declare function autopilotStatus(fetchApi: (path: string, init: RequestInit) => Promise<Response>, profile: string | undefined, signal: AbortSignal, now?: number): Promise<AutopilotStatus>;
93
- /** `passport status` lines; with the web origin, a link to change the rules. */
94
- export declare function autopilotLines(status: AutopilotStatus, webOrigin?: string): string[];