passport-bridge 0.15.0 → 0.16.1

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 (67) hide show
  1. package/README.md +31 -13
  2. package/dist/bridgeExchange.d.ts +11 -1
  3. package/dist/bridgeExchange.js +12 -1
  4. package/dist/cliArgs.d.ts +1 -1
  5. package/dist/cliArgs.js +9 -2
  6. package/dist/cliAutopilot.d.ts +8 -1
  7. package/dist/cliAutopilot.js +47 -16
  8. package/dist/cliAutopilotPolicy.d.ts +33 -1
  9. package/dist/cliAutopilotPolicy.js +34 -1
  10. package/dist/cliClient.js +2 -1
  11. package/dist/cliEnv.d.ts +40 -0
  12. package/dist/cliEnv.js +157 -0
  13. package/dist/cliExec.d.ts +23 -2
  14. package/dist/cliExec.js +53 -8
  15. package/dist/cliHook.d.ts +8 -0
  16. package/dist/cliHook.js +11 -6
  17. package/dist/cliHookClassify.d.ts +7 -0
  18. package/dist/cliHookClassify.js +22 -2
  19. package/dist/cliHookDecide.d.ts +3 -2
  20. package/dist/cliHookDecide.js +13 -2
  21. package/dist/cliHookEnvironment.d.ts +9 -3
  22. package/dist/cliHookEnvironment.js +69 -15
  23. package/dist/cliHookGuard.d.ts +26 -2
  24. package/dist/cliHookGuard.js +72 -17
  25. package/dist/cliHookLocal.js +9 -3
  26. package/dist/cliHookVendors.js +8 -2
  27. package/dist/cliHookVendorsMore.d.ts +21 -0
  28. package/dist/cliHookVendorsMore.js +196 -0
  29. package/dist/cliInit.d.ts +12 -1
  30. package/dist/cliInit.js +43 -10
  31. package/dist/cliKeys.js +8 -3
  32. package/dist/cliLoosening.d.ts +34 -0
  33. package/dist/cliLoosening.js +107 -0
  34. package/dist/cliOutput.d.ts +10 -1
  35. package/dist/cliOutput.js +64 -3
  36. package/dist/cliPolicyV2.js +90 -3
  37. package/dist/cliSupport.d.ts +9 -0
  38. package/dist/cliSupport.js +25 -0
  39. package/dist/cliUndo.d.ts +49 -0
  40. package/dist/cliUndo.js +312 -0
  41. package/dist/completion.js +6 -2
  42. package/dist/envDatabase.d.ts +28 -0
  43. package/dist/envDatabase.js +166 -0
  44. package/dist/envLinkFs.d.ts +57 -0
  45. package/dist/envLinkFs.js +140 -0
  46. package/dist/envLinksCloud.d.ts +31 -0
  47. package/dist/envLinksCloud.js +233 -0
  48. package/dist/envLinksHosting.d.ts +33 -0
  49. package/dist/envLinksHosting.js +463 -0
  50. package/dist/envResolve.d.ts +48 -0
  51. package/dist/envResolve.js +221 -0
  52. package/dist/envTarget.d.ts +61 -0
  53. package/dist/envTarget.js +50 -0
  54. package/dist/execBackupTarget.d.ts +25 -0
  55. package/dist/execBackupTarget.js +201 -0
  56. package/dist/initAutopilotStep.js +44 -3
  57. package/dist/initKeysStep.js +17 -2
  58. package/dist/initState.d.ts +3 -0
  59. package/dist/initUi.d.ts +43 -2
  60. package/dist/initUi.js +174 -32
  61. package/dist/passport.js +11 -14
  62. package/dist/pluginPin.d.ts +1 -1
  63. package/dist/pluginPin.js +1 -1
  64. package/dist/version.d.ts +1 -1
  65. package/dist/version.js +1 -1
  66. package/npm-shrinkwrap.json +2 -2
  67. package/package.json +1 -1
package/README.md CHANGED
@@ -48,7 +48,7 @@ passport run github_search_issues '{"query":"SSO"}'
48
48
 
49
49
  | Command | Purpose |
50
50
  | --- | --- |
51
- | `init [--yes] [--no-open] [--cloud <origin>] [--skip-apps\|--skip-agents\|--skip-guard] [--verbose] [--json]` | Set up Passport for this computer's agents in one pass. Every step asks first, can be skipped, and is safe to run again. |
51
+ | `init [--yes] [--move-keys] [--no-open] [--cloud <origin>] [--skip-apps\|--skip-agents\|--skip-guard] [--verbose] [--json]` | Set up Passport for this computer's agents in one pass. Every step asks first, can be skipped, and is safe to run again. |
52
52
  | `login` | Browser sign-in or sign-up (or device sign-in with `--workspace`); saves a rotating CLI credential and makes the profile active. |
53
53
  | `logout` | Revoke the credential and always remove the local profile (warns if revocation fails). |
54
54
  | `profiles` / `use <name>` | List stored profiles / select the active one. Offline. |
@@ -67,6 +67,7 @@ passport run github_search_issues '{"query":"SSO"}'
67
67
  | `wait <approval-id> [--timeout <s>]` | Wait for a person to decide an approval request (default 100 seconds). |
68
68
  | `rules test "<command>" [--environment <kind>]` | What Autopilot decides for a command, why, and which environment it acts on. |
69
69
  | `sessions [--status running\|idle\|ended]` | Your agents' recent sessions with what Passport decided. |
70
+ | `undo <action-id>\|--last [--option <id>] [--yes]` | Undo an action Passport took a backup before, within 7 days. See [Undo](#undo). |
70
71
  | `setup --org <pek_key> [--yes] [--clients <list>]` | Set up every agent on this computer for your company without asking anything (MDM and scripts). See [Company rollout](#company-rollout). |
71
72
  | `setup` | Install and maintain assigned team workflows as managed skills. |
72
73
  | `session` | Run NDJSON commands over one authenticated MCP session. |
@@ -123,19 +124,21 @@ Reads agent MCP configs (Claude Desktop, Claude Code, Cursor, VS Code, Codex), C
123
124
 
124
125
  ```sh
125
126
  npx passport-bridge@latest init # or: passport init
126
- npx passport-bridge@latest init --yes # accept every default; needed without a terminal
127
+ npx passport-bridge@latest init --yes # accept every default; needed without a terminal. Keys stay put
128
+ npx passport-bridge@latest init --yes --move-keys # also move CLI keys into Passport and sign those CLIs out
127
129
  npx passport-bridge@latest init --yes --json # one summary object with each step's status
128
130
  ```
129
131
 
130
- Seven steps, each reusing the command that owns it:
132
+ Eight steps, each reusing the command that owns it:
131
133
 
132
134
  1. **Scan**: the same local scan as `passport scan`, as one summary line (`--verbose` prints the table).
133
135
  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`.
134
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.
135
- 4. **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.`
136
- 5. **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.
137
- 6. **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 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. Once the new copy is in place, older copies are deleted unless a hook still runs them.
138
- 7. **Autopilot**: how much agents can do on their own, per environment:
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.`). 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 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. Once the new copy is in place, older copies are deleted unless a hook still runs them.
141
+ 8. **Autopilot**: how much agents can do on their own, per environment:
139
142
 
140
143
  ```
141
144
  Autopilot How much can agents do on their own?
@@ -159,7 +162,7 @@ What changes on disk, and how to undo it:
159
162
  | VS Code user `mcp.json` | `servers.passport` | `MCP: List Servers`, then remove it |
160
163
  | `~/.claude/settings.json`, `~/.codex/hooks.json`, `~/.cursor/hooks.json` | Passport's audit and guard hooks | `passport hook uninstall --client <agent> --apply` |
161
164
 
162
- 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. 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.
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.
163
166
 
164
167
  ### Company rollout
165
168
 
@@ -248,29 +251,43 @@ passport rules test "rm -rf ~/"
248
251
  passport wait apr_123
249
252
  passport sessions
250
253
  passport sync # or: passport sync --remove
254
+ passport env # or: passport env set railway qa staging
251
255
  ```
252
256
 
257
+ - `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`). A name in a link file never loosens anything: an unplaced id is Production, and for a placed id its mapping decides while a different name is treated as a rename (sent as the new label, which the server stores). 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.
258
+
253
259
  - `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.
254
260
  - `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`.
255
261
  - `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.
256
262
  - `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.
257
- - `status` adds `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. 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`.
263
+ - `status` adds `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`.
258
264
  - `rules test`, `sessions`, and `sync` need a member profile. `wait` also works for a cloud agent's key, on the approval its own `passport exec` opened.
259
265
 
260
266
  ### Keys and passport exec
261
267
 
262
268
  ```sh
263
- passport keys move # confirm each key, store it in Passport, sign that CLI out here
269
+ passport keys move # confirm each key [y/n], store it in Passport, sign that CLI out here
264
270
  passport keys # what Passport holds, and what's still on this computer
265
271
  passport keys add railway # store a key you paste (stdin, never echoed)
266
272
  passport exec -- railway up -e staging
267
273
  ```
268
274
 
269
- - `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, stores the key in Passport (`POST /api/my/keys`), then signs that CLI out with its own command (`railway logout`, `gh auth logout`, `vercel logout`, `wrangler logout`, `supabase logout`, `stripe logout`) or removes only that entry. 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. From the CLI, a different key than the one already in Passport is refused; rotate it in Apps. The scan report sent afterwards carries provider counts only.
275
+ - `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 with its own command (`railway logout`, `gh auth logout`, `vercel logout`, `wrangler logout`, `supabase logout`, `stripe logout`) or removes only that entry. 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. From the CLI, a different key than the one already in Passport is refused; rotate it in Apps. The scan report sent afterwards carries provider counts only.
270
276
  - `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`).
271
277
  - 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.
272
278
  - 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.
273
279
  - 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.
280
+ - 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.
281
+
282
+ ### Undo
283
+
284
+ ```sh
285
+ passport undo act_123
286
+ passport undo --last --yes
287
+ ```
288
+
289
+ - Shows what comes back and what won't, how old the backup is, and how long undo stays available, then asks `Undo it? [y/N]` (and which option, when there are several). Without a terminal it prints the preview and `passport undo <id> --yes`; `--option <id>` picks an option.
290
+ - Passport decides an undo from the CLI like a change in that environment. Asks first: exit 4 with the approval id; run `passport wait <id>`, then the undo again. Blocked or declined: exit 5. Done: exit 0, with each step (`✓`/`✗`). Partly done or failed: exit 1. Expired, already undone, or otherwise unavailable: exit 5 with the reason. No backup: exit 6. Needs a member profile.
274
291
 
275
292
  ### Persistent sessions
276
293
 
@@ -381,10 +398,11 @@ With `--json`, stdout is exactly one JSON value; hints and warnings go to stderr
381
398
  | `profiles` | `{profiles:[{name,active,client?}],active?}` |
382
399
  | `use` | `{profile,active:true}` |
383
400
  | `logout` | `{profile,removed,revoked}` |
384
- | `status` | `{workspace,member,endpoint,auth,profile?,client,mcps,autopilot?:{presets,floors,floorReason?,cache:{version,fetchedAt,ageMs}},next?}` |
401
+ | `status` | `{workspace,member,endpoint,auth,profile?,client,mcps,autopilot?:{presets,floors,floorReason?,exceptions?,cache:{version,fetchedAt,ageMs}},next?}` |
385
402
  | `wait` | `{approvalId,status:"approved",scope?,message}`; declined, expired, and still-waiting are errors with `approvalId` |
386
403
  | `rules` | `{command,decision,cause?,explanation?,environment?,environmentAssumed?,actionClass?,source}` |
387
404
  | `sessions` | `{sessions:[{id,client,folder,status,startedAt,lastActivityAt,counts,environments,waiting}],nextCursor}` |
405
+ | `undo` | `{actionId,status,message,steps:[{label,ok,detail?}],option,undoActionId?}`; without `--yes` off a terminal, `{actionId,status:"preview",preview,next}`; pending, blocked, and declined are errors |
388
406
  | `doctor` | `{version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}`, also on failure |
389
407
  | `ready` | `{ready,version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}` |
390
408
  | `search` | Gateway payload with `results` or `catalog`, and `note` |
@@ -405,7 +423,7 @@ Errors: `{"error":"...","cause":"blocked","exitCode":5,"app":"github"}`, optiona
405
423
  | Exit | Meaning |
406
424
  | ---: | --- |
407
425
  | 0 | Success |
408
- | 1 | Network, timeout, server, or unsupported-content error |
426
+ | 1 | Network, timeout, server, or unsupported-content error. When Passport can't be reached: `Passport couldn't be reached at <host>. Check your connection and try again.` |
409
427
  | 2 | Missing, expired, or revoked authentication |
410
428
  | 3 | App needs member sign-in |
411
429
  | 4 | Approval pending (including `wait` still waiting at its timeout) |
@@ -21,14 +21,23 @@ export type ExchangeRetryPolicy = {
21
21
  budgetMs: number;
22
22
  };
23
23
  export declare const DEFAULT_EXCHANGE_RETRY: ExchangeRetryPolicy;
24
+ /** A one-shot CLI command: a couple of quick retries, then one clear line.
25
+ * The next command still lands inside the server's grace window. */
26
+ export declare const CLI_EXCHANGE_RETRY: ExchangeRetryPolicy;
27
+ /** A token exchange is one small request. A CLI attempt that hasn't answered
28
+ * by now is retried instead of holding the command for the full deadline. */
29
+ export declare const CLI_EXCHANGE_ATTEMPT_MS = 10000;
24
30
  export type TokenManagerOptions = {
25
31
  /** Defaults to DEFAULT_EXCHANGE_RETRY for rotating managers and no retry
26
32
  * for non-rotating ones, whose failures are never ambiguous. */
27
33
  retry?: ExchangeRetryPolicy;
28
34
  /** Keep the process alive while waiting to retry. A serving bridge sets
29
35
  * this so a startup retry is never cut short; one-shot CLI commands leave
30
- * it off so a pending retry cannot hold a finished command open. */
36
+ * it off so a pending retry cannot hold a finished command open (the CLI
37
+ * keeps itself alive until its command settles). */
31
38
  keepAliveDuringRetry?: boolean;
39
+ /** Don't log retries to stderr. The CLI prints one line when it gives up. */
40
+ quietRetries?: boolean;
32
41
  };
33
42
  /**
34
43
  * Holds the long-lived refresh token and mints short-lived access tokens
@@ -57,6 +66,7 @@ export declare class TokenManager {
57
66
  private tenantFlipLogged;
58
67
  private readonly retry;
59
68
  private readonly keepAliveDuringRetry;
69
+ private readonly quietRetries;
60
70
  /**
61
71
  * @param onRotate durably persist a rotated refresh token before its access
62
72
  * token is usable. Rejection leaves the child pending for local retry.
@@ -36,6 +36,15 @@ export const DEFAULT_EXCHANGE_RETRY = Object.freeze({
36
36
  delaysMs: Object.freeze([1_000, 2_000, 4_000, 8_000, 16_000, 32_000, 60_000]),
37
37
  budgetMs: 4 * 60_000
38
38
  });
39
+ /** A one-shot CLI command: a couple of quick retries, then one clear line.
40
+ * The next command still lands inside the server's grace window. */
41
+ export const CLI_EXCHANGE_RETRY = Object.freeze({
42
+ delaysMs: Object.freeze([1_000, 2_000]),
43
+ budgetMs: 5_000
44
+ });
45
+ /** A token exchange is one small request. A CLI attempt that hasn't answered
46
+ * by now is retried instead of holding the command for the full deadline. */
47
+ export const CLI_EXCHANGE_ATTEMPT_MS = 10_000;
39
48
  const NO_EXCHANGE_RETRY = Object.freeze({ delaysMs: Object.freeze([]), budgetMs: 0 });
40
49
  /** An exchange failure that may have been committed server-side, or is
41
50
  * simply transient. Carries the original error so callers see the same
@@ -120,6 +129,7 @@ export class TokenManager {
120
129
  tenantFlipLogged = false;
121
130
  retry;
122
131
  keepAliveDuringRetry;
132
+ quietRetries;
123
133
  /**
124
134
  * @param onRotate durably persist a rotated refresh token before its access
125
135
  * token is usable. Rejection leaves the child pending for local retry.
@@ -143,6 +153,7 @@ export class TokenManager {
143
153
  this.homeWorkspace = workspaceOfToken(refreshToken);
144
154
  this.retry = options.retry ?? (onRotate ? DEFAULT_EXCHANGE_RETRY : NO_EXCHANGE_RETRY);
145
155
  this.keepAliveDuringRetry = options.keepAliveDuringRetry === true;
156
+ this.quietRetries = options.quietRetries === true;
146
157
  }
147
158
  /** The refresh token this process last presented or adopted. In-process
148
159
  * only: never log it. Recovery correlates with it and self-heal compares
@@ -313,7 +324,7 @@ export class TokenManager {
313
324
  if (delay === undefined || this.requestSignal?.aborted || Date.now() - started + delay > this.retry.budgetMs) {
314
325
  throw error.original;
315
326
  }
316
- if (retries === 0)
327
+ if (retries === 0 && !this.quietRetries)
317
328
  log("token exchange did not complete; retrying within the rotation grace window");
318
329
  retries++;
319
330
  await sleepFor(delay, this.requestSignal, this.keepAliveDuringRetry);
package/dist/cliArgs.d.ts CHANGED
@@ -1,4 +1,4 @@
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", "sessions", "sync", "exec", "keys", "setup", "session", "access", "completion", "help", "version"];
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", "sessions", "env", "sync", "exec", "undo", "keys", "setup", "session", "access", "completion", "help", "version"];
2
2
  export type Command = (typeof COMMANDS)[number];
3
3
  export declare class ArgError extends Error {
4
4
  }
package/dist/cliArgs.js CHANGED
@@ -19,8 +19,10 @@ export const COMMANDS = [
19
19
  "wait",
20
20
  "rules",
21
21
  "sessions",
22
+ "env",
22
23
  "sync",
23
24
  "exec",
25
+ "undo",
24
26
  "keys",
25
27
  "setup",
26
28
  "session",
@@ -42,12 +44,13 @@ const FLAGS = {
42
44
  apply: { kind: "boolean", commands: ["setup", "hook"] },
43
45
  guard: { kind: "boolean", commands: ["hook"] },
44
46
  "no-open": { kind: "boolean", commands: ["login", "init"] },
45
- yes: { kind: "boolean", commands: ["init", "setup", "keys"] },
47
+ yes: { kind: "boolean", commands: ["init", "setup", "keys", "undo"] },
46
48
  org: { kind: "value", commands: ["setup"] },
47
49
  clients: { kind: "value", commands: ["setup"] },
48
50
  "skip-apps": { kind: "boolean", commands: ["init"] },
49
51
  "skip-agents": { kind: "boolean", commands: ["init"] },
50
52
  "skip-guard": { kind: "boolean", commands: ["init"] },
53
+ "move-keys": { kind: "boolean", commands: ["init"] },
51
54
  app: { kind: "value", commands: ["search"] },
52
55
  args: { kind: "value", commands: ["run"] },
53
56
  set: { kind: "repeat", commands: ["run", "prompts"] },
@@ -68,7 +71,9 @@ const FLAGS = {
68
71
  "client-id": { kind: "value", commands: ["access"] },
69
72
  environment: { kind: "value", commands: ["rules"] },
70
73
  status: { kind: "value", commands: ["sessions"] },
71
- remove: { kind: "boolean", commands: ["sync"] }
74
+ remove: { kind: "boolean", commands: ["sync"] },
75
+ last: { kind: "boolean", commands: ["undo"] },
76
+ option: { kind: "value", commands: ["undo"] }
72
77
  };
73
78
  export class ArgError extends Error {
74
79
  }
@@ -179,7 +184,9 @@ function validateShape(command, positionals) {
179
184
  wait: 1,
180
185
  rules: 2,
181
186
  sessions: 0,
187
+ env: 4,
182
188
  sync: 0,
189
+ undo: 1,
183
190
  keys: 2,
184
191
  setup: 3,
185
192
  session: 0,
@@ -15,6 +15,8 @@ import { type Preset, type PresetRow } from "./cliAutopilotPolicy.js";
15
15
  import { type MemberApi } from "./cliClient.js";
16
16
  import { type LocalMachine } from "./cliHookLocal.js";
17
17
  import { type EnvKind } from "./cliHookEnvironment.js";
18
+ import { type LinkFs } from "./envLinkFs.js";
19
+ export { env } from "./cliEnv.js";
18
20
  import { type CommandResult, type Runtime } from "./cliSupport.js";
19
21
  /** Long enough to be useful, short enough for an agent's default 2-minute
20
22
  * command timeout. */
@@ -24,7 +26,11 @@ export type AutopilotDependencies = {
24
26
  now?: () => number;
25
27
  /** The machine `rules test` reads paths on; tests pass a pretend one. */
26
28
  machine?: LocalMachine;
29
+ /** Where folder links are read from; tests pass a pretend one. */
30
+ linkFs?: LinkFs;
27
31
  };
32
+ export declare function api(args: ParsedArgs, runtime: Runtime, deps: AutopilotDependencies, waitMs?: number, agentKeyOk?: boolean): MemberApi;
33
+ export declare function json<T>(response: Response, fallback: string): Promise<T>;
28
34
  export declare function wait(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
29
35
  export declare function rules(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
30
36
  type SessionRow = {
@@ -51,6 +57,8 @@ export type AutopilotStatus = {
51
57
  presets: (Record<EnvKind, Preset> & Partial<Record<PresetRow, Preset>>) | null;
52
58
  floors: Partial<Record<PresetRow, Preset | null>> | null;
53
59
  floorReason?: string;
60
+ /** One line per exception that lets something run your presets would ask about. */
61
+ exceptions?: string[];
54
62
  cache: {
55
63
  version: 1 | 2 | null;
56
64
  fetchedAt: number | null;
@@ -74,4 +82,3 @@ export declare function localMidnight(now: number): number;
74
82
  /** Read presets and floors for `passport status`. Never throws. */
75
83
  export declare function autopilotStatus(fetchApi: (path: string, init: RequestInit) => Promise<Response>, profile: string | undefined, signal: AbortSignal, now?: number): Promise<AutopilotStatus>;
76
84
  export declare function autopilotLines(status: AutopilotStatus): string[];
77
- export {};
@@ -14,8 +14,13 @@ import { bool, value } from "./cliArgs.js";
14
14
  import { OTHER_APPS, PRESET_LABEL, PRESET_ROWS, rowLabel } from "./cliAutopilotPolicy.js";
15
15
  import { memberApi } from "./cliClient.js";
16
16
  import { classifyLine, localMachine } from "./cliHookLocal.js";
17
- import { ENV_KINDS, ENV_LABEL, environmentHintWith, isEnvKind } from "./cliHookEnvironment.js";
17
+ import { ENV_KINDS, ENV_LABEL, isEnvKind } from "./cliHookEnvironment.js";
18
18
  import { decideGuard, guardLabel } from "./cliHookGuard.js";
19
+ import { NODE_LINK_FS } from "./envLinkFs.js";
20
+ import { resolveTarget } from "./envResolve.js";
21
+ // `passport env` lives in cliEnv.ts; the dispatcher reaches it through here.
22
+ export { env } from "./cliEnv.js";
23
+ import { looseningLines } from "./cliLoosening.js";
19
24
  import { readCliPolicy } from "./cliPolicy.js";
20
25
  import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, sanitize, sleep, timeoutMs } from "./cliSupport.js";
21
26
  /** Long enough to be useful, short enough for an agent's default 2-minute
@@ -23,7 +28,7 @@ import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, san
23
28
  export const WAIT_DEFAULT_SECONDS = 100;
24
29
  const WAIT_POLL_SECONDS = 30;
25
30
  const APPROVAL_ID = /^[A-Za-z0-9_-]{1,80}$/;
26
- function api(args, runtime, deps, waitMs = 0, agentKeyOk = false) {
31
+ export function api(args, runtime, deps, waitMs = 0, agentKeyOk = false) {
27
32
  if (deps.api)
28
33
  return deps.api;
29
34
  const auth = resolveCliAuth(args, runtime.env);
@@ -39,7 +44,7 @@ function api(args, runtime, deps, waitMs = 0, agentKeyOk = false) {
39
44
  signal: runtime.signal
40
45
  });
41
46
  }
42
- async function json(response, fallback) {
47
+ export async function json(response, fallback) {
43
48
  if (response.status === 401 || response.status === 403) {
44
49
  return failure(await safeApiError(response, "Passport refused this profile."), 2, "auth", {
45
50
  hint: "Run: passport login"
@@ -68,14 +73,19 @@ function waitOutcome(id, body) {
68
73
  if (status === "allowed" || status === "approved") {
69
74
  // "Approved by Ramish." or "Now allowed by your rules.", then the next step.
70
75
  const lead = message ?? `Approved${by ? ` by ${by}` : ""}.`;
71
- const human = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
76
+ const next = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
77
+ // Once, when this approval reaches the threshold: "Tip: You've approved
78
+ // railway redeploy in Staging 5 times. ... Make it a rule: <link>".
79
+ const suggestion = text(body.suggestion, 400);
80
+ const human = suggestion ? `${next}\n${suggestion}` : next;
72
81
  return {
73
82
  json: {
74
83
  approvalId: id,
75
84
  status: "approved",
76
85
  ...(scope ? { scope } : {}),
77
86
  ...(by ? { decidedBy: by } : {}),
78
- message: human
87
+ message: next,
88
+ ...(suggestion ? { suggestion } : {})
79
89
  },
80
90
  human,
81
91
  essential: true
@@ -187,8 +197,8 @@ function inEnvironment(findings, environment) {
187
197
  ? { ...finding, local: { ...finding.local, environment } }
188
198
  : { ...finding, pushEnvironment: undefined, args: [...(finding.args ?? []), "--environment", environment] });
189
199
  }
190
- function localTest(command, findings, complete, policy) {
191
- const decision = decideGuard(findings, policy, command, complete);
200
+ function localTest(command, findings, complete, policy, machine) {
201
+ const decision = decideGuard(findings, policy, command, complete, machine);
192
202
  if (!decision)
193
203
  return null;
194
204
  return {
@@ -203,15 +213,13 @@ function localTest(command, findings, complete, policy) {
203
213
  * What `rules test` sends: an everyday command as what it is (program, verb,
204
214
  * class, place), never its words; a vendor command as its label.
205
215
  */
206
- function testBody(lead, label, cached, environment) {
216
+ function testBody(lead, label, target, environment) {
207
217
  if (lead.local) {
208
218
  const finding = { vendor: lead.vendor, verb: lead.verb ?? "invoke", risk: lead.risk };
209
219
  return { finding: { ...finding, environment: environment ?? lead.local.environment } };
210
220
  }
211
- const hint = lead.vendor
212
- ? environmentHintWith(lead.vendor, lead.args ?? [], cached?.version === 2 ? { flags: cached.autopilot.environmentFlags, known: cached.autopilot.environments } : {})
213
- : undefined;
214
- const placed = environment ?? lead.pushEnvironment ?? (hint && hint.source !== "assumed" ? hint.kind : undefined);
221
+ // Where this computer placed it: a flag, the folder's link, or a mapping.
222
+ const placed = environment ?? lead.pushEnvironment ?? (target && target.source !== "assumed" ? target.kind : undefined);
215
223
  return { command: label, ...(placed ? { environment: placed } : {}) };
216
224
  }
217
225
  /** The workspace's answer, or null to decide on this computer. */
@@ -249,7 +257,19 @@ export async function rules(args, runtime, deps = {}) {
249
257
  }
250
258
  const environment = environmentFlag;
251
259
  // Paths are read where you run this, like the hook reads the agent's folder.
252
- const line = classifyLine(command, deps.machine ?? localMachine(process.cwd(), runtime.env));
260
+ const machine = deps.machine ?? localMachine(process.cwd(), runtime.env);
261
+ const line = classifyLine(command, machine);
262
+ // Folder links are read here too, unless a test gave a pretend machine only.
263
+ const guardMachine = deps.machine && !deps.linkFs
264
+ ? undefined
265
+ : {
266
+ cwd: machine.cwd,
267
+ rawCwd: deps.machine ? machine.cwd : process.cwd(),
268
+ projectRoot: machine.projectRoot,
269
+ home: machine.home,
270
+ env: runtime.env,
271
+ fs: deps.linkFs ?? NODE_LINK_FS
272
+ };
253
273
  const all = inEnvironment(line.findings, environment);
254
274
  const findings = all.filter((finding) => finding.vendor);
255
275
  if (!findings.length) {
@@ -269,13 +289,21 @@ export async function rules(args, runtime, deps = {}) {
269
289
  }
270
290
  })();
271
291
  const cached = profile ? readCliPolicy(profile) : null;
272
- const decided = decideGuard(all, cached, command, line.complete);
292
+ const decided = decideGuard(all, cached, command, line.complete, guardMachine);
273
293
  // The command that decides: the strictest one the rules spoke about.
274
294
  const lead = decided?.findings[0] ?? findings[0];
275
295
  const label = guardLabel(lead);
276
- const local = localTest(command, all, line.complete, cached);
296
+ const local = localTest(command, all, line.complete, cached, guardMachine);
297
+ const v2 = cached?.version === 2 ? cached.autopilot : undefined;
298
+ const target = decided?.decided?.find((entry) => entry.finding === lead)?.target ??
299
+ (lead.vendor && !lead.local
300
+ ? resolveTarget(lead.vendor, lead.args ?? [], {
301
+ ...(v2 ? { flags: v2.environmentFlags, known: v2.environments } : {}),
302
+ ...(v2?.resources ? { resources: v2.resources } : {})
303
+ })
304
+ : undefined);
277
305
  // The server knows grants, every rule, and the workspace's environments.
278
- const asked = profile || deps.api ? await askServer(testBody(lead, label, cached, environment), args, runtime, deps) : null;
306
+ const asked = profile || deps.api ? await askServer(testBody(lead, label, target, environment), args, runtime, deps) : null;
279
307
  let result = asked;
280
308
  let source = result ? "Decided by your workspace's rules." : "";
281
309
  if (!result) {
@@ -447,12 +475,14 @@ export async function autopilotStatus(fetchApi, profile, signal, now = Date.now(
447
475
  floors[row] = isPresetName(floor) ? floor : null;
448
476
  }
449
477
  const reason = text(body.floors?.reason, 120);
478
+ const exceptions = looseningLines(body);
450
479
  const answered = await answeredStatus(fetchApi, profile, signal, now);
451
480
  const allowlists = await allowlistStatus();
452
481
  return {
453
482
  presets: presetMap(body.presets),
454
483
  floors,
455
484
  ...(reason ? { floorReason: reason } : {}),
485
+ ...(exceptions.length ? { exceptions } : {}),
456
486
  cache,
457
487
  ...(answered ? { answered } : {}),
458
488
  ...(allowlists ? { allowlists } : {})
@@ -471,6 +501,7 @@ export function autopilotLines(status) {
471
501
  const floors = PRESET_ROWS.filter((row) => status.floors?.[row]).map((row) => `${rowLabel(row)} at least ${PRESET_LABEL[status.floors[row]]}`);
472
502
  if (floors.length)
473
503
  lines.push(`Team floors: ${floors.join(" · ")}${status.floorReason ? ` (${sanitize(status.floorReason)})` : ""}`);
504
+ lines.push(...(status.exceptions ?? []));
474
505
  }
475
506
  const { cache } = status;
476
507
  lines.push(cache.fetchedAt === null
@@ -39,6 +39,20 @@ export type CliRule = {
39
39
  owner?: string;
40
40
  /** The server's whole cause line, used as is when present. */
41
41
  label?: string;
42
+ /** Actions an approved exception lifts this rule for (this person only). */
43
+ except?: RuleException[];
44
+ };
45
+ export type RuleException = {
46
+ vendor?: string;
47
+ verb?: string;
48
+ appKey?: string;
49
+ actionClass?: ActionClass;
50
+ environment: ActionEnv | "any";
51
+ };
52
+ /** The second-person rule's cause lines, as the server words them. */
53
+ export declare const SECOND_PERSON_LABEL: {
54
+ readonly change: "Production changes need someone else to approve";
55
+ readonly delete: "Production deletes need someone else to approve";
42
56
  };
43
57
  /** A flag that names an environment: `--prod` names one itself, `--environment`
44
58
  * takes the name as its value. */
@@ -73,6 +87,21 @@ export type AutopilotPolicy = {
73
87
  /** The server decides everyday commands too (Phase 1.5): reports and
74
88
  * decide requests may carry them. */
75
89
  localCommands?: boolean;
90
+ /** Production classes someone else must approve: never run here, and never
91
+ * approved in the agent's own prompt. "Maya or Sam" names who approves. */
92
+ secondPerson?: {
93
+ classes: ActionClass[];
94
+ approvers: string;
95
+ };
96
+ /** Resources the workspace placed, by id (Phase 4.5). Present only when the
97
+ * server reads where a finding lands, so findings may carry it. */
98
+ resources?: Array<{
99
+ platform: string;
100
+ resourceKey: string;
101
+ label: string;
102
+ kind: EnvKind;
103
+ source: "detected" | "set" | "assumed";
104
+ }>;
76
105
  };
77
106
  /** The platform a vendor CLI acts on, so its rules and environments line up
78
107
  * with the same platform's MCP app (server `cliPlatform`). */
@@ -101,6 +130,9 @@ export type LocalDecision = {
101
130
  decision: Decision;
102
131
  cause: Cause;
103
132
  };
104
- /** The server's `decideAction`, minus grants (only the server knows them). */
133
+ /** The server's `decideAction`, minus grants (only the server knows them).
134
+ * The second-person rule turns a Production run into an ask the server owns. */
105
135
  export declare function decideAction(policy: AutopilotPolicy, facts: ActionFacts): LocalDecision;
136
+ /** Whether an ask needs someone other than the person at the keyboard. */
137
+ export declare function needsSecondPerson(cause: Cause | undefined): boolean;
106
138
  export declare function decisionRank(decision: Decision): number;
@@ -14,6 +14,11 @@
14
14
  import { ENV_LABEL } from "./cliHookEnvironment.js";
15
15
  export const PRESETS = ["careful", "balanced", "handsoff"];
16
16
  export const ACTION_CLASSES = ["read", "change", "delete", "irreversible"];
17
+ /** The second-person rule's cause lines, as the server words them. */
18
+ export const SECOND_PERSON_LABEL = {
19
+ change: "Production changes need someone else to approve",
20
+ delete: "Production deletes need someone else to approve"
21
+ };
17
22
  /** The platform a vendor CLI acts on, so its rules and environments line up
18
23
  * with the same platform's MCP app (server `cliPlatform`). */
19
24
  export function platformOf(vendor) {
@@ -112,8 +117,22 @@ function ruleMatches(rule, facts) {
112
117
  }
113
118
  if (rule.decision === "allow" && facts.actionClass === "irreversible" && level !== LEVEL_ACTION)
114
119
  return false;
120
+ // An approved exception lifts this rule for the action it names.
121
+ if (rule.except?.some((lift) => exceptionCovers(lift, facts)))
122
+ return false;
115
123
  return true;
116
124
  }
125
+ function exceptionCovers(lift, facts) {
126
+ if (lift.environment !== "any" && lift.environment !== facts.environment)
127
+ return false;
128
+ if (lift.vendor !== undefined && lift.verb !== undefined)
129
+ return lift.vendor === facts.vendor && lift.verb === facts.verb;
130
+ if (lift.appKey !== undefined && !appMatches(lift.appKey, facts))
131
+ return false;
132
+ if (lift.actionClass !== undefined && lift.actionClass !== facts.actionClass)
133
+ return false;
134
+ return lift.appKey !== undefined || lift.actionClass !== undefined;
135
+ }
117
136
  function matchText(rule) {
118
137
  if (rule.vendor !== undefined && rule.verb !== undefined)
119
138
  return `${rule.vendor} ${rule.verb}`;
@@ -173,8 +192,22 @@ function mostSpecific(rules) {
173
192
  function stricter(a, b) {
174
193
  return DECISION_RANK[b] > DECISION_RANK[a] ? b : a;
175
194
  }
176
- /** The server's `decideAction`, minus grants (only the server knows them). */
195
+ /** The server's `decideAction`, minus grants (only the server knows them).
196
+ * The second-person rule turns a Production run into an ask the server owns. */
177
197
  export function decideAction(policy, facts) {
198
+ const decided = decideByRules(policy, facts);
199
+ const classes = policy.secondPerson?.classes ?? [];
200
+ if (decided.decision !== "allow" || facts.environment !== "production" || !classes.includes(facts.actionClass)) {
201
+ return decided;
202
+ }
203
+ const label = facts.actionClass === "change" ? SECOND_PERSON_LABEL.change : SECOND_PERSON_LABEL.delete;
204
+ return { decision: "ask", cause: { kind: "floor", label } };
205
+ }
206
+ /** Whether an ask needs someone other than the person at the keyboard. */
207
+ export function needsSecondPerson(cause) {
208
+ return cause?.label === SECOND_PERSON_LABEL.change || cause?.label === SECOND_PERSON_LABEL.delete;
209
+ }
210
+ function decideByRules(policy, facts) {
178
211
  const matching = policy.rules.filter((rule) => ruleMatches(rule, facts));
179
212
  // 1. Block rules, any scope. The most specific one names the cause.
180
213
  const blocks = matching.filter((rule) => rule.decision === "block");
package/dist/cliClient.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
2
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
3
  import { TokenManager } from "./bridge.js";
4
+ import { CLI_EXCHANGE_ATTEMPT_MS, CLI_EXCHANGE_RETRY } from "./bridgeExchange.js";
4
5
  import { persistCurrentProfileRotation, recoverProfileRotation, withProfileLock } from "./credentials.js";
5
6
  import { VERSION } from "./version.js";
6
7
  import { SERVER_TOO_OLD } from "./cliProtocol.js";
@@ -53,7 +54,7 @@ function authedFetchFor(options) {
53
54
  const manager = new TokenManager(endpoint, options.auth.refreshToken, (next, previous) => persistCurrentProfileRotation(profile, previous, next, endpoint), {
54
55
  reload: () => recoverProfileRotation(profile)?.refreshToken,
55
56
  lock: (fn) => withProfileLock(profile, fn)
56
- }, options.timeoutMs, options.signal);
57
+ }, Math.min(options.timeoutMs, CLI_EXCHANGE_ATTEMPT_MS), options.signal, fetch, { retry: CLI_EXCHANGE_RETRY, quietRetries: true });
57
58
  return decorateFetch(manager.authedFetch, {
58
59
  "x-passport-surface": "cli",
59
60
  ...(options.caller ? { "x-passport-caller": options.caller } : {})