passport-bridge 0.25.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +5 -3
  2. package/dist/approvalNotice.d.ts +73 -0
  3. package/dist/approvalNotice.js +211 -0
  4. package/dist/blindKind.d.ts +15 -0
  5. package/dist/blindKind.js +5 -0
  6. package/dist/cliChanges.d.ts +12 -4
  7. package/dist/cliChanges.js +26 -15
  8. package/dist/cliExec.js +2 -2
  9. package/dist/cliGuardState.js +2 -2
  10. package/dist/cliHook.js +5 -0
  11. package/dist/cliHookBlind.d.ts +15 -0
  12. package/dist/cliHookBlind.js +65 -0
  13. package/dist/cliHookClients.d.ts +3 -1
  14. package/dist/cliHookClients.js +1 -1
  15. package/dist/cliHookLocal.d.ts +7 -16
  16. package/dist/cliHookLocal.js +75 -97
  17. package/dist/cliHookLocalCode.js +7 -1
  18. package/dist/cliHookLocalFs.d.ts +15 -0
  19. package/dist/cliHookLocalFs.js +77 -0
  20. package/dist/cliHookNotice.d.ts +22 -0
  21. package/dist/cliHookNotice.js +49 -0
  22. package/dist/cliHookScripts.d.ts +2 -1
  23. package/dist/cliOutput.js +2 -2
  24. package/dist/cliProjectSummary.d.ts +1 -1
  25. package/dist/cliProjectSummary.js +19 -8
  26. package/dist/cliScriptRead.d.ts +5 -4
  27. package/dist/cliScriptRead.js +3 -2
  28. package/dist/cliSeen.d.ts +24 -15
  29. package/dist/cliSeen.js +34 -16
  30. package/dist/cliSessions.js +20 -6
  31. package/dist/cliSessionsJson.d.ts +48 -0
  32. package/dist/cliSessionsJson.js +40 -10
  33. package/dist/cliSessionsRender.d.ts +4 -0
  34. package/dist/cliSessionsRender.js +42 -8
  35. package/dist/holdNotice.js +7 -1
  36. package/dist/hookMain.js +10 -1
  37. package/dist/hookPromptFast.d.ts +26 -0
  38. package/dist/hookPromptFast.js +82 -0
  39. package/dist/inlineCode.d.ts +35 -0
  40. package/dist/inlineCode.js +201 -0
  41. package/dist/inlineScan.d.ts +23 -0
  42. package/dist/inlineScan.js +389 -0
  43. package/dist/localCommands.d.ts +10 -3
  44. package/dist/localCommands.js +59 -37
  45. package/dist/localFiles.d.ts +38 -2
  46. package/dist/localFiles.js +453 -33
  47. package/dist/localGit.js +53 -17
  48. package/dist/localShared.d.ts +3 -0
  49. package/dist/pluginPin.d.ts +1 -1
  50. package/dist/pluginPin.js +1 -1
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/npm-shrinkwrap.json +2 -2
  54. package/package.json +1 -1
package/README.md CHANGED
@@ -265,12 +265,14 @@ The guard decides from local data inside `HOOK_BUDGET_MS` (1.5 s) and prints fir
265
265
 
266
266
  An ask becomes one Activity row. In Claude Code, with the audit hook registered, the guard parks its report in `$PASSPORT_HOME/hook-pending/` (`src/cliHookPending.ts`, mode 600, claimed by atomic rename). The audit hook for the same tool-use id sends the run with `decision: "ask", ran: true` ("asked first, then ran"). An ask nobody claims within 30 minutes (no agent fires a hook for a declined prompt) is sent by the next hook run as `ran: false` ("asked first, not run"). An allow the server gave is parked the same way, so the run's row says `Approved earlier this session`. Cursor has no tool-use id to match, so its asks are sent at once as their own "asked first" row. Denies are always sent at once; asks and blocks the server decided are recorded by the server.
267
267
 
268
- - Claude Code: `PreToolUse`, plus `PostToolUse` and `PostToolUseFailure` (failed or interrupted calls, recorded as ran with a non-zero exit), in `~/.claude/settings.json` (`CLAUDE_CONFIG_DIR` honored).
268
+ - Claude Code: `PreToolUse`, plus `PostToolUse` and `PostToolUseFailure` (failed or interrupted calls, recorded as ran with a non-zero exit), in `~/.claude/settings.json` (`CLAUDE_CONFIG_DIR` honored). The audit entry also runs on `SessionStart`, `SessionEnd`, and (0.26.0+) `UserPromptSubmit`, for late approvals below.
269
269
  - Codex: the same events in `~/.codex/hooks.json` (`CODEX_HOME` honored). Codex sends every shell command as `tool_name: "Bash"` with the model's raw command string in `tool_input.command` (never shell-wrapped), so it is read exactly like Claude Code's; its `apply_patch` tool is a file edit, not a shell command, and isn't recorded. Codex supports deny only (an ask fails the hook open, and its allow rewrites commands), so an ask is a deny there that says why (`Codex can't ask from a hook, so Passport blocked it. Approve it in Passport or run it yourself.`), recorded as a block. With a member profile and Autopilot, it goes to Passport like an unattended ask: an approval request, then the waiting line. Trust the hooks in Codex's `/hooks`.
270
270
  - Cursor: `beforeShellExecution`/`afterShellExecution` in `~/.cursor/hooks.json`. Cursor also imports Claude Code's hooks by default; that imported copy records nothing when Passport's own Cursor entry exists, so rows aren't doubled.
271
271
 
272
272
  **Hold for approval** (`src/cliHookHold.ts`). When nobody is at the keyboard and Passport opens an approval request, the guard holds for a person before answering: `hook install --guard` and `init` write `passport hook guard --hold 25` with the entry's `timeout` at 40 seconds for Claude Code (`--hold <0-45>` changes it; `0` writes today's entry; `hook install` also fixes a timeout that's too short). At runtime the hold is capped by the timeout Claude Code enforces on that entry, read from its settings, and an entry the guard can't find means no hold. If someone approves in time, the guard asks Passport again with the same request, which consumes the approval once and re-checks every rule, and only that allow runs the original command, with no retry. Anything else (no decision, a decline, expiry, an error, or a slow answer) declines the command with one line: who decides, when the request expires, and `Run "passport wait <id>" as a background command; it exits when someone decides. Then run this command again.` A decline during the hold carries the person's note. An entry without `--hold` never holds, because Claude Code runs a command when its hook outlives the timeout; `PASSPORT_HOOK_HOLD` can shorten a hold, never lengthen it. Codex never holds (its hook can't run an approved command), and neither does Cursor (what it does when a hook outlives its timeout isn't documented). Managed installs (`init --org`) don't hold yet, since a person's older CLI wouldn't know the flag. A guard from before the hold (no `--hold`, or a timeout too short for it) is named once a day, and once per CLI version, after an interactive command on a terminal: `Approvals can now continue automatically. Run: passport hook install --apply` (stderr; never from the hook, piped, or with `--json`). `passport doctor` shows the same as a warning, and `hook install --apply` keeps an existing guard current without `--guard`. Each approval binds to a normalized command key (`src/cliHookKey.ts`): every word and redirect target is redacted first, then quoting, pipes into read-only filters whose flags are all on that filter's harmless list, `2>&1`, output sent to /dev/null, and a trailing `|| true` are ignored, so an equivalent retry matches the same request. A key that still shows anything the summary hides falls back to the summary, and a key over 400 characters is sent as a SHA-256 of the whole key.
273
273
 
274
+ **Late approvals** (`src/approvalNotice.ts`, 0.26.0+). A guarded command's request stays open a day even after the agent stops waiting (its hold ended, its turn finished, or the session closed), including a `passport exec` that waited at the keyboard. Approving it then leaves a one-time pass for that exact command in that session: the agent's next try (the same command key, the same session id) gets the server's allow, once, and the pass lapses a day after the approval. A decline stays final. Nothing runs by itself. So the agent knows, the guard (and `exec`) leaves a marker per Claude Code session when it opens a request (`$PASSPORT_HOME/hook-approvals/<digest>.json`, mode 600, a time only, at most 200, two days), and the audit entry, on that session's next `SessionStart` (a resume) or `UserPromptSubmit`, asks `POST /api/my/cli/approved` with `{runtime, sessionId}` inside the hook's budget. Passport answers what it approved there that the agent hasn't used or heard about, marking each told, and the hook prints Claude Code's `hookSpecificOutput.additionalContext`: `Passport: a command this session asked about earlier was approved after you stopped waiting. It hasn't run.`, one line per approval with the command, who approved it (a display name, never an email), when, and when it lapses, then `If it's still needed, run the exact same command again; the approval lets it run once. Otherwise, ignore this.` The marker goes once nothing in the session waits. A prompt with no marker on the computer never touches the network or loads the hook: `src/hookPromptFast.ts` reads the event first and exits (about Node's own start, ~4 ms more on an M-series Mac). Codex and Cursor take no such context: their pass is used when the agent tries the command again. Existing installs add the `UserPromptSubmit` entry with `passport hook install --apply`.
275
+
274
276
  **Guard health** (`src/cliGuardHealth.ts`, states and fixes in `src/cliGuardState.ts`, a checked copy of `shared/guardContract.ts`). `passport hook status` and `passport status` show each agent's guard in the web's words, **On**, **Off**, **Outdated**, **Not trusted**, or **Locked**, and each problem's fix (on a terminal the command goes on its own `Run:` line): `passport hook install --agent <agent> --guard --apply`, `npx passport-bridge@latest init`, or `Open Codex → /hooks and trust Passport's hooks.` At most once a day (`$PASSPORT_HOME/guard/.<profile>.heartbeat`) the CLI sends `POST /api/my/guard-health` with `{cliVersion, launcherTarget?, clients: [{client, present, mode, guard, plugin, codexTrust?, locked?, disabledEnv?}]}`: flags only, never a command, path, or value. It goes from a guard run with at least 300 ms of its budget left (a hook's first one waits a day), from `passport exec`, and from `passport status`. Codex trust (`src/cliCodexTrust.ts`) compares `trusted_hash` in `~/.codex/config.toml` `[hooks.state."<hooks.json>:pre_tool_use:<group>:<handler>"]` with Codex's own hash of Passport's guard entry: SHA-256 of the sorted-key JSON of `{event_name, matcher?, hooks: [{type, command, timeout (600 when unset), async, statusMessage?, additionalContextLimit? (when not 2500)}]}`, as in openai/codex `hook_hash`/`version_for_toml`, checked against codex-cli 0.146.0's `hooks/list`. Missing is **Not trusted**, a different hash is **Not trusted** (modified), `enabled = false` is **Off**. **Locked** means managed settings hold Passport's guard: `/Library/Application Support/ClaudeCode/managed-settings.json` (and `managed-settings.d/`), `/etc/claude-code/…`, `/etc/codex/requirements.toml`, `/Library/Application Support/Cursor/hooks.json`, or `/etc/cursor/hooks.json` (`PASSPORT_MANAGED_ROOT` points tests elsewhere).
275
277
 
276
278
  **Coverage** (`src/cliSeen.ts`). The guard counts every command it saw, per agent per day, one character per command in `$PASSPORT_HOME/seen/<profile>.<agent>.<day>.log` (an app's action, not checked, or neither), and Cursor's imported copy of Claude Code's hook doesn't count twice. Counts go in their own batches, at most every five minutes, as `seen: {batch, day, count, governed, opaque}` on `POST /api/my/cli-activity`, never inside a report that can expire. `passport status` prints `Checked: 94% of commands Passport saw this week`.
@@ -305,8 +307,8 @@ passport actions sync # propose this repository's .passport/actions.toml
305
307
 
306
308
  - `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.
307
309
  - `wait` long-polls `GET /api/my/approvals/<id>/wait` (30 s per request), after a short first look that names who decides, until a person decides or the request expires; `--timeout <s>` caps it. Agents run it as a background command and are woken when it exits. Once Passport says the request is still pending (never for one that doesn't exist or is already decided), on a terminal it prints the approval link and one live line (`Waiting for Erin · 1:32 left`); piped, `Waiting for a decision on <id> (until it expires at 14:05).` and `Open in Passport: <url>`. Ctrl-C exits 4 with `The request is still open. Keep waiting any time.` and `Run: passport wait <id>`. Approved: `Approved by Ramish (once). Run the command again.`, or `… for this session. Matching commands in this session run without asking.` (exit 0). Declined: the person's note, cleaned and labelled, `Declined by Ramish. Their note: "Use staging first"` (exit 5, cause `approval_denied`). Expired: `Expired at 14:05 with no decision. Run the command again to ask again.` (exit 5, cause `approval_expired`). Still waiting at `--timeout`: exit 4 with the same command as `next`.
308
- - `sessions` lists work items the way the Sessions page does (`GET /api/my/work-items`): a pull request or branch with every session on it rolled up, grouped by project (or, for app connections, by the apps they used). Each item has its agents, then one shape line: actions, active time, failed, confirmed Production changes, unplaced changes, asks with how they ended, blocked, data checks, undone, and the share Passport couldn't check. Notable items come first; the rest fold into `14 routine work items · 3,200 reads · nothing needed you`. `--all` lists every item, `--running` only those with a running session, and `--production-changes` prints the ledger (`GET /api/my/production-ledger`, 7 days unless `--since`): changes to confirmed Production by app and target, then the unplaced count with a link to set environments. `--project`, `--pr`, `--since` (`today`, `24h`, `7d`, `30d`, `90d`, or a date read in local time), and `--status running|ended` go to the server, which applies them to every session in the window, never to a loaded page. The CLI follows up to five pages and then links the rest. `--project <name>` on its own (no lens, `--pr`, or `--status`) opens with the web project page's summary (`GET /api/my/projects/<name>`): sessions and how many run, Environments (the repository's placement, then each platform its changes reached and how many were unplaced), the rules for the apps and scripts it uses, and its Production changes in the last 7 days, then the work list; `--json` adds it as `project` (`{project,link,sinceTs,environments:[{appKey,appName,role,label,kind,source,reached,unplaced}],rules:[{id,kind,label,decision}],moreRules,production:{total,unplaced,apps},totals}`), and a server without the page prints the list alone. A work item with several sessions links to its own page (`#projects/<name>/work?branch=`). `sessions <id>` reads one session (`GET /api/my/agent-sessions/<id>`): its title, place, agent, and active time; the web page's summary strip (actions, shipped, Production, failed, asked, not checked, undo, data checks); and its 15 latest actions with what each acted on, where it landed, and how it ended. On a terminal parts wrap only between `·` and the timeline stacks when it doesn't fit; piped output never wraps and has no color.
309
- - `changes` lists every change, delete, and irreversible action that ran on confirmed Production in the window (`GET /api/my/production-changes`), the list Sessions › Production changes shows: grouped by app, newest first, each with its time and command (and what it acted on), then the agent, the person, the pull request (else branch), Failed or Approved, and Undo available, Undone by, or Undo expired. Consecutive alike changes (same command, target, agent, person, repository, and branch) fold into one line, `git push → main ×28` with their span of times, unless one failed, was approved, or has an undo state; `--json` keeps every change. With changes from more than one repository, each line names its repository. Blocked and declined actions never reached Production and aren't listed; unplaced changes are one count with a link to set environments. `--since` takes `1h`, `6h`, `24h` (the default), `7d`, `30d`, `today`, or a date read in local time; `--until` a date; `--project`, `--pr`, `--app`, and `--agent` narrow on the server. `--env` accepts only `production` for now. When the window holds more than one read returns, it says so and links the web page. The deploy and error lanes are web-only.
310
+ - `sessions` lists work items the way the Sessions page does (`GET /api/my/work-items`): a pull request or branch with every session on it rolled up, grouped by project (or, for app connections, by the apps they used). Each item has its agents, then one shape line: actions, active time, failed, confirmed Production changes, unplaced changes, asks with how they ended, blocked, data checks, undone, and the share Passport couldn't check. Notable items come first; the rest fold into `14 routine work items · 3,200 reads · nothing needed you`. `--all` lists every item, `--running` only those with a running session, and `--production-changes` prints the ledger (`GET /api/my/production-ledger`, 7 days unless `--since`): changes to confirmed Production by app and target, then the unplaced count with a link to set environments. `--project`, `--pr`, `--since` (`today`, `24h`, `7d`, `30d`, `90d`, or a date read in local time), and `--status running|ended` go to the server, which applies them to every session in the window, never to a loaded page. The CLI follows up to five pages and then links the rest. `--project <name>` on its own (no lens, `--pr`, or `--status`) opens with the web project page's summary (`GET /api/my/projects/<name>`): sessions and how many run, Environments (the repository's placement, then each platform its changes reached and how many were unplaced), the rules for the apps and scripts it uses, and its Production changes, all over the same window as `--since` (any time without it), then the work list; `--json` adds it as `project` (`{project,link,sinceTs,environments:[{appKey,appName,role,label,kind,source,reached,unplaced}],rules:[{id,kind,label,decision}],moreRules,production:{total,unplaced,apps},totals}`), and a server without the page prints the list alone. A work item with several sessions links to its own page (`#projects/<name>/work?branch=`). Every count the server sends carries its window (`window: {since, until, label}`); the CLI prints the label after the count (`16 work items · … · Last 7 days`) and keeps its own words for an older server. `sessions <id>` reads one session (`GET /api/my/agent-sessions/<id>`): its title, place, agent, and active time; the web page's summary strip (actions, shipped, Production, failed, asked, not checked, undo, data checks); and its 15 latest actions with what each acted on, where it landed, and how it ended. On a terminal parts wrap only between `·` and the timeline stacks when it doesn't fit; piped output never wraps and has no color.
311
+ - `changes` lists every change, delete, and irreversible action that ran on confirmed Production in the window (`GET /api/my/production-changes`), the list Sessions › Production changes shows: grouped by app, newest first, each with its time and command (and what it acted on), then the agent, the person, the pull request (else branch), Failed or Approved, and Undo available, Undone by, or Undo expired. Consecutive alike changes (same command, target, agent, person, repository, and branch) fold into one line, `git push → main ×28` with their span of times, unless one failed, was approved, or has an undo state; `--json` keeps every change. With changes from more than one repository, each line names its repository. Blocked and declined actions never reached Production and aren't listed; unplaced changes are one count with a link to set environments. `--since` takes `1h`, `6h`, `24h`, `7d` (the default), `30d`, `today`, or a date read in local time; `--until` a date; `--project`, `--pr`, `--app`, and `--agent` narrow on the server. `--env` accepts only `production` for now. When the window holds more than one read returns, it says so and links the web page. The deploy and error lanes are web-only.
310
312
  - `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`, `init --org`, every rules refresh, and `passport sync`; `hook uninstall`, `sync --remove`, and signing out of the last profile take the entries out.
311
313
  - `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 adds ~20 ms per action 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`.
312
314
  - `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.
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Late approvals, told to the agent. When a guarded command waits for a
3
+ * person and the agent stops waiting (its turn ended, the session closed),
4
+ * the person can still approve it for a day. That leaves a one-time pass for
5
+ * the same command in the same session, used on the agent's next try.
6
+ *
7
+ * So the agent knows, Claude Code's next hook in that session (SessionStart
8
+ * when it is resumed, or UserPromptSubmit when the person types again) asks
9
+ * Passport what was approved and adds one line of context per approval: what,
10
+ * by whom (a display name), and when. Passport marks each one told, so the
11
+ * agent hears about it once. Nothing runs here: the agent decides whether to
12
+ * run the command again.
13
+ *
14
+ * Every prompt runs this hook, so it asks Passport only for a session this
15
+ * computer saw wait for a person: the guard (and `passport exec`) leaves a
16
+ * small marker per session when it opens a request, and the hook removes it
17
+ * once nothing in the session waits or is left to tell. Codex and Cursor have
18
+ * no such context: their pass is used when the agent tries the command again.
19
+ *
20
+ * Markers are owner-only files named by a digest of the agent and session id,
21
+ * hold only a time, and are bounded in count and age. Never throws.
22
+ */
23
+ export declare const CLI_APPROVED_PATH = "/api/my/cli/approved";
24
+ /** A request stays open a day, and its pass a day after approval. */
25
+ export declare const MARKER_MAX_AGE_MS: number;
26
+ /** The hook events that can carry context into the agent. */
27
+ export declare const NOTICE_EVENTS: Set<string>;
28
+ type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
29
+ export type ApprovedNotice = {
30
+ approvalId: string;
31
+ action: string;
32
+ command?: string;
33
+ approvedBy: string;
34
+ approvedAt: number;
35
+ expiresAt: number;
36
+ };
37
+ /** The guard or `passport exec` opened a request a person answers: remember
38
+ * the session, so its next prompt asks Passport. False when it couldn't. */
39
+ export declare function noteWaitingSession(runtime: string, sessionId: string | undefined, now?: number): boolean;
40
+ /** Whether this session left a marker recently enough to ask about. */
41
+ export declare function sessionWaited(runtime: string, sessionId: string, now?: number): boolean;
42
+ export declare function forgetSession(runtime: string, sessionId: string): void;
43
+ /** Validate what Passport said. Anything unexpected is no answer. */
44
+ export declare function parseApproved(raw: unknown): {
45
+ approved: ApprovedNotice[];
46
+ waiting: number;
47
+ } | null;
48
+ /** Ask Passport, or null when it couldn't answer in time. Never throws. */
49
+ export declare function fetchApproved(api: ApiCall, runtime: string, sessionId: string, signal: AbortSignal): Promise<{
50
+ approved: ApprovedNotice[];
51
+ waiting: number;
52
+ } | null>;
53
+ /** "40 minutes", "3 hours" (at least a minute). */
54
+ export declare function span(ms: number): string;
55
+ /** What the agent reads: one line per approval, and what to do about it. */
56
+ export declare function noticeContext(notices: readonly ApprovedNotice[], now: number): string;
57
+ /** Claude Code's shape for context a hook adds to the conversation. */
58
+ export declare function contextOutput(event: string, context: string): Record<string, unknown>;
59
+ /**
60
+ * The notice for one hook event, or null. Asks Passport only for a Claude
61
+ * Code session that waited for a person, inside the hook's budget.
62
+ */
63
+ export declare function approvalNotice(input: {
64
+ hook_event_name?: unknown;
65
+ session_id?: unknown;
66
+ cursor_version?: unknown;
67
+ }, context: {
68
+ runtime: string;
69
+ openApi: () => Promise<ApiCall | null>;
70
+ signal: AbortSignal;
71
+ now: () => number;
72
+ }): Promise<Record<string, unknown> | null>;
73
+ export {};
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Late approvals, told to the agent. When a guarded command waits for a
3
+ * person and the agent stops waiting (its turn ended, the session closed),
4
+ * the person can still approve it for a day. That leaves a one-time pass for
5
+ * the same command in the same session, used on the agent's next try.
6
+ *
7
+ * So the agent knows, Claude Code's next hook in that session (SessionStart
8
+ * when it is resumed, or UserPromptSubmit when the person types again) asks
9
+ * Passport what was approved and adds one line of context per approval: what,
10
+ * by whom (a display name), and when. Passport marks each one told, so the
11
+ * agent hears about it once. Nothing runs here: the agent decides whether to
12
+ * run the command again.
13
+ *
14
+ * Every prompt runs this hook, so it asks Passport only for a session this
15
+ * computer saw wait for a person: the guard (and `passport exec`) leaves a
16
+ * small marker per session when it opens a request, and the hook removes it
17
+ * once nothing in the session waits or is left to tell. Codex and Cursor have
18
+ * no such context: their pass is used when the agent tries the command again.
19
+ *
20
+ * Markers are owner-only files named by a digest of the agent and session id,
21
+ * hold only a time, and are bounded in count and age. Never throws.
22
+ */
23
+ import { createHash } from "node:crypto";
24
+ import { lstatSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
25
+ import { basename, join } from "node:path";
26
+ import { readBoundedJson } from "./boundedResponse.js";
27
+ import { credentialDir, enforceOwner, ensurePrivateDirectory, writePrivateAtomic } from "./credentialStorage.js";
28
+ export const CLI_APPROVED_PATH = "/api/my/cli/approved";
29
+ /** A request stays open a day, and its pass a day after approval. */
30
+ export const MARKER_MAX_AGE_MS = 48 * 60 * 60 * 1000;
31
+ const MAX_MARKERS = 200;
32
+ const MAX_NOTICES = 5;
33
+ const MAX_RESPONSE_BYTES = 16 * 1024;
34
+ const DIRECTORY = "hook-approvals";
35
+ const SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
36
+ const ID = /^[A-Za-z0-9_-]{1,80}$/;
37
+ /** The hook events that can carry context into the agent. */
38
+ export const NOTICE_EVENTS = new Set(["SessionStart", "UserPromptSubmit"]);
39
+ function directory() {
40
+ return join(credentialDir(), DIRECTORY);
41
+ }
42
+ function markerPath(runtime, sessionId) {
43
+ const key = createHash("sha256").update(`${runtime}\u0000${sessionId}`).digest("hex").slice(0, 40);
44
+ return join(directory(), `${key}.json`);
45
+ }
46
+ /** The guard or `passport exec` opened a request a person answers: remember
47
+ * the session, so its next prompt asks Passport. False when it couldn't. */
48
+ export function noteWaitingSession(runtime, sessionId, now = Date.now()) {
49
+ if (runtime !== "claude-code" || !sessionId || !SESSION.test(sessionId))
50
+ return false;
51
+ try {
52
+ ensurePrivateDirectory(true);
53
+ try {
54
+ mkdirSync(directory(), { mode: 0o700 });
55
+ }
56
+ catch (error) {
57
+ if (error.code !== "EEXIST")
58
+ throw error;
59
+ }
60
+ const stat = lstatSync(directory());
61
+ if (stat.isSymbolicLink() || !stat.isDirectory())
62
+ return false;
63
+ enforceOwner(stat, "hook approvals directory");
64
+ const names = readdirSync(directory()).filter((name) => /^[0-9a-f]{40}\.json$/.test(name));
65
+ const path = markerPath(runtime, sessionId);
66
+ if (names.length >= MAX_MARKERS && !names.includes(basename(path)))
67
+ return false;
68
+ writePrivateAtomic(path, ".hook-approval", JSON.stringify({ at: now }), "hook approval");
69
+ return true;
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
75
+ /** Whether this session left a marker recently enough to ask about. */
76
+ export function sessionWaited(runtime, sessionId, now = Date.now()) {
77
+ try {
78
+ const stat = statSync(markerPath(runtime, sessionId));
79
+ if (now - stat.mtimeMs <= MARKER_MAX_AGE_MS)
80
+ return true;
81
+ forgetSession(runtime, sessionId);
82
+ return false;
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ }
88
+ export function forgetSession(runtime, sessionId) {
89
+ try {
90
+ rmSync(markerPath(runtime, sessionId), { force: true });
91
+ }
92
+ catch {
93
+ /* Asked again next time: harmless. */
94
+ }
95
+ }
96
+ function text(raw, max) {
97
+ if (typeof raw !== "string")
98
+ return undefined;
99
+ const cleaned = raw
100
+ .replace(/[\u0000-\u001f\u007f-\u009f`]/g, " ")
101
+ .replace(/\s+/g, " ")
102
+ .trim();
103
+ return cleaned ? cleaned.slice(0, max) : undefined;
104
+ }
105
+ function time(raw) {
106
+ return typeof raw === "number" && Number.isSafeInteger(raw) && raw > 0 ? raw : undefined;
107
+ }
108
+ /** Validate what Passport said. Anything unexpected is no answer. */
109
+ export function parseApproved(raw) {
110
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
111
+ return null;
112
+ const body = raw;
113
+ if (!Array.isArray(body.approved))
114
+ return null;
115
+ const waiting = typeof body.waiting === "number" && Number.isSafeInteger(body.waiting) ? body.waiting : 0;
116
+ const approved = [];
117
+ for (const entry of body.approved.slice(0, MAX_NOTICES)) {
118
+ if (!entry || typeof entry !== "object")
119
+ continue;
120
+ const item = entry;
121
+ const action = text(item.action, 80);
122
+ const approvedBy = text(item.approvedBy, 80);
123
+ const approvedAt = time(item.approvedAt);
124
+ const expiresAt = time(item.expiresAt);
125
+ if (typeof item.approvalId !== "string" || !ID.test(item.approvalId) || !action || !approvedBy)
126
+ continue;
127
+ if (!approvedAt || !expiresAt)
128
+ continue;
129
+ const command = text(item.command, 200);
130
+ approved.push({
131
+ approvalId: item.approvalId,
132
+ action,
133
+ ...(command ? { command } : {}),
134
+ approvedBy: approvedBy.includes("@") ? "a person in your workspace" : approvedBy,
135
+ approvedAt,
136
+ expiresAt
137
+ });
138
+ }
139
+ return { approved, waiting: Math.max(0, waiting) };
140
+ }
141
+ /** Ask Passport, or null when it couldn't answer in time. Never throws. */
142
+ export async function fetchApproved(api, runtime, sessionId, signal) {
143
+ try {
144
+ const response = await api(CLI_APPROVED_PATH, {
145
+ method: "POST",
146
+ headers: { "content-type": "application/json", accept: "application/json", "x-passport-surface": "cli" },
147
+ body: JSON.stringify({ runtime, sessionId }),
148
+ signal
149
+ });
150
+ if (!response.ok) {
151
+ await response.body?.cancel().catch(() => undefined);
152
+ return null;
153
+ }
154
+ return parseApproved(await readBoundedJson(response, MAX_RESPONSE_BYTES));
155
+ }
156
+ catch {
157
+ return null;
158
+ }
159
+ }
160
+ /** "40 minutes", "3 hours" (at least a minute). */
161
+ export function span(ms) {
162
+ const minutes = Math.max(1, Math.round(ms / 60_000));
163
+ if (minutes < 90)
164
+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;
165
+ const hours = Math.round(minutes / 60);
166
+ return `${hours} hour${hours === 1 ? "" : "s"}`;
167
+ }
168
+ /** What the agent reads: one line per approval, and what to do about it. */
169
+ export function noticeContext(notices, now) {
170
+ const lines = notices.map((notice) => {
171
+ const what = notice.command ? `${notice.action} (\`${notice.command}\`)` : notice.action;
172
+ const when = new Date(notice.approvedAt).toISOString().slice(0, 16).replace("T", " ");
173
+ return `- ${what}: approved by ${notice.approvedBy} ${span(now - notice.approvedAt)} ago (${when} UTC). The approval lapses in ${span(notice.expiresAt - now)}.`;
174
+ });
175
+ const lead = notices.length === 1
176
+ ? "Passport: a command this session asked about earlier was approved after you stopped waiting. It hasn't run."
177
+ : "Passport: commands this session asked about earlier were approved after you stopped waiting. They haven't run.";
178
+ return [
179
+ lead,
180
+ ...lines,
181
+ "If it's still needed, run the exact same command again; the approval lets it run once. Otherwise, ignore this."
182
+ ].join("\n");
183
+ }
184
+ /** Claude Code's shape for context a hook adds to the conversation. */
185
+ export function contextOutput(event, context) {
186
+ return { hookSpecificOutput: { hookEventName: event, additionalContext: context } };
187
+ }
188
+ /**
189
+ * The notice for one hook event, or null. Asks Passport only for a Claude
190
+ * Code session that waited for a person, inside the hook's budget.
191
+ */
192
+ export async function approvalNotice(input, context) {
193
+ const event = typeof input.hook_event_name === "string" ? input.hook_event_name : "";
194
+ if (!NOTICE_EVENTS.has(event) || context.runtime !== "claude-code" || input.cursor_version !== undefined)
195
+ return null;
196
+ const sessionId = typeof input.session_id === "string" && SESSION.test(input.session_id) ? input.session_id : "";
197
+ if (!sessionId || !sessionWaited(context.runtime, sessionId, context.now()))
198
+ return null;
199
+ const api = await context.openApi().catch(() => null);
200
+ if (!api || context.signal.aborted)
201
+ return null;
202
+ const answer = await fetchApproved(api, context.runtime, sessionId, context.signal);
203
+ if (!answer)
204
+ return null;
205
+ // Nothing waits and nothing is left to tell: stop asking for this session.
206
+ if (answer.waiting === 0 && answer.approved.length < MAX_NOTICES)
207
+ forgetSession(context.runtime, sessionId);
208
+ if (!answer.approved.length)
209
+ return null;
210
+ return contextOutput(event, noticeContext(answer.approved, context.now()));
211
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What a blind part of a command was, for coverage (`cliSeen.ts`): interpreter
3
+ * code on the line or in a heredoc, a file run by path or given to an
4
+ * interpreter (scripts, task targets, package scripts Passport couldn't
5
+ * read), or a program Passport doesn't know. Shared by the classifier,
6
+ * script reading, and the coverage log; imports nothing.
7
+ */
8
+ export type BlindKind = "inline" | "script" | "program";
9
+ /** The blind part of a classified line: its program's name, never a path, and its kind. */
10
+ export type Blind = {
11
+ program: string;
12
+ kind: BlindKind;
13
+ };
14
+ /** A blind part written as `program\tkind` (the coverage log, the script cache); no tab: a program. */
15
+ export declare function blindOfText(text: string): Blind;
@@ -0,0 +1,5 @@
1
+ /** A blind part written as `program\tkind` (the coverage log, the script cache); no tab: a program. */
2
+ export function blindOfText(text) {
3
+ const [program = "", kind] = text.split("\t");
4
+ return { program, kind: kind === "inline" || kind === "script" ? kind : "program" };
5
+ }
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `passport changes`: what changed in Production, the list Sessions ›
3
- * Production changes shows. Every change, delete, and irreversible action
4
- * that ran on confirmed Production in the window, grouped by app, newest
5
- * first, with the agent, the person, the work item, the result, and undo.
3
+ * Production changes shows. Every Production change in the window (a change
4
+ * that ran and succeeded on Production or on a target nobody placed, by the
5
+ * server's one classifier), grouped by app, newest first, with the agent, the
6
+ * person, the work item, the result, and undo.
6
7
  *
7
- * passport changes the last 24 hours
8
+ * passport changes the last 7 days
8
9
  * passport changes --env production --since 1h
9
10
  *
10
11
  * Filters run on the server (`GET /api/my/production-changes`). `--json`
@@ -13,6 +14,7 @@
13
14
  import { type ParsedArgs } from "./cliArgs.js";
14
15
  import { type AutopilotDependencies } from "./cliMemberCall.js";
15
16
  import { type CommandResult, type Runtime } from "./cliSupport.js";
17
+ import { type WindowJson } from "./cliSessionsJson.js";
16
18
  import { type Term } from "./term.js";
17
19
  export type UndoJson = {
18
20
  state: string;
@@ -33,6 +35,8 @@ export type ChangeJson = {
33
35
  actionClass: "change" | "delete" | "irreversible";
34
36
  result: "ok" | "error";
35
37
  approved: boolean;
38
+ /** Its target nobody placed: counted as Production until someone does. */
39
+ unplaced: boolean;
36
40
  sessionId: string | null;
37
41
  project: string | null;
38
42
  branch: string | null;
@@ -51,7 +55,11 @@ export type ChangesJson = {
51
55
  untilTs: number | null;
52
56
  total: number;
53
57
  unplaced: number;
58
+ /** False from a server that counted unplaced changes apart from `total`. */
59
+ unplacedIncluded: boolean;
54
60
  complete: boolean;
61
+ /** The span `total` covers; null from older servers. */
62
+ window: WindowJson | null;
55
63
  apps: Array<{
56
64
  vendor: string;
57
65
  appName: string;
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `passport changes`: what changed in Production, the list Sessions ›
3
- * Production changes shows. Every change, delete, and irreversible action
4
- * that ran on confirmed Production in the window, grouped by app, newest
5
- * first, with the agent, the person, the work item, the result, and undo.
3
+ * Production changes shows. Every Production change in the window (a change
4
+ * that ran and succeeded on Production or on a target nobody placed, by the
5
+ * server's one classifier), grouped by app, newest first, with the agent, the
6
+ * person, the work item, the result, and undo.
6
7
  *
7
- * passport changes the last 24 hours
8
+ * passport changes the last 7 days
8
9
  * passport changes --env production --since 1h
9
10
  *
10
11
  * Filters run on the server (`GET /api/my/production-changes`). `--json`
@@ -13,13 +14,13 @@
13
14
  import { value } from "./cliArgs.js";
14
15
  import { api, json } from "./cliMemberCall.js";
15
16
  import { failure, timeoutMs } from "./cliSupport.js";
16
- import { appName, clientName, count, list, oneOf, record, text, time } from "./cliSessionsJson.js";
17
+ import { appName, clientName, count, list, oneOf, record, text, time, windowOf } from "./cliSessionsJson.js";
17
18
  import { countOf } from "./plural.js";
18
19
  import { joinParts, mark, visibleLength, wrap, termOf } from "./term.js";
19
20
  import { hashLink } from "./webLinks.js";
20
21
  const DATE = /^\d{4}-\d{2}-\d{2}$/;
21
22
  const RANGES = ["1h", "6h", "24h", "7d", "30d", "today"];
22
- const DEFAULT_SINCE = "24h";
23
+ const DEFAULT_SINCE = "7d";
23
24
  const WINDOW_WORDS = {
24
25
  "1h": "last hour",
25
26
  "6h": "last 6 hours",
@@ -138,6 +139,7 @@ function changeOf(raw) {
138
139
  actionClass: oneOf(entry.actionClass, ["change", "delete", "irreversible"]) ?? "change",
139
140
  result: entry.result === "error" ? "error" : "ok",
140
141
  approved: entry.approved === true,
142
+ unplaced: entry.unplaced === true,
141
143
  sessionId: text(entry.sessionId, 128) ?? null,
142
144
  project: text(work.project, 200) ?? null,
143
145
  branch: text(work.branch, 200) ?? null,
@@ -180,7 +182,9 @@ export function changesOf(raw) {
180
182
  untilTs: time(page.untilTs),
181
183
  total: Math.max(count(page.total), changes.length),
182
184
  unplaced: count(page.unplaced),
185
+ unplacedIncluded: page.unplacedIncluded === true,
183
186
  complete: page.complete !== false,
187
+ window: windowOf(page.window),
184
188
  apps
185
189
  };
186
190
  }
@@ -228,6 +232,8 @@ export function changeParts(change, projects = false) {
228
232
  parts.push(change.branch);
229
233
  if (change.result === "error")
230
234
  parts.push("Failed");
235
+ if (change.unplaced)
236
+ parts.push("Unplaced");
231
237
  if (change.approved)
232
238
  parts.push("Approved");
233
239
  const undo = undoPart(change.undo);
@@ -268,18 +274,22 @@ export function foldChanges(changes) {
268
274
  }
269
275
  return runs;
270
276
  }
271
- function windowWord(since, sinceTs, now) {
272
- return WINDOW_WORDS[since] ?? (sinceTs ? `since ${changeTime(sinceTs, now)}` : `since ${since}`);
277
+ /** The server's label for the window it counted; an older server's, worded here. */
278
+ function windowWord(page, since, now) {
279
+ if (page.window)
280
+ return page.window.label;
281
+ return WINDOW_WORDS[since] ?? (page.sinceTs ? `since ${changeTime(page.sinceTs, now)}` : `since ${since}`);
273
282
  }
274
283
  export function renderChanges(page, term, now, since, links) {
275
284
  const arrow = term.unicode ? "→" : "->";
276
- const lines = joinParts([
277
- "Production changes",
278
- windowWord(since, page.sinceTs, now),
279
- `${countOf(page.total, "change")} on confirmed Production`
280
- ], term.width);
285
+ // Since the count shape, unplaced changes are among the total and listed;
286
+ // an older server listed confirmed Production only.
287
+ const where = page.unplacedIncluded ? "on Production" : "on confirmed Production";
288
+ const lines = joinParts(["Production changes", windowWord(page, since, now), `${countOf(page.total, "change")} ${where}`], term.width);
281
289
  if (!page.apps.length)
282
- lines.push("", ...wrap("Nothing your agents ran changed a target you placed in Production in this window.", term.width));
290
+ lines.push("", ...wrap(page.unplacedIncluded
291
+ ? "Nothing your agents ran changed Production in this window."
292
+ : "Nothing your agents ran changed a target you placed in Production in this window.", term.width));
283
293
  const projects = new Set(page.apps.flatMap((app) => app.changes.map((change) => change.project)).filter(Boolean)).size > 1;
284
294
  const times = term.unicode ? "×" : "x";
285
295
  for (const app of page.apps) {
@@ -301,7 +311,8 @@ export function renderChanges(page, term, now, since, links) {
301
311
  lines.push(`See all: ${links.more}`);
302
312
  }
303
313
  if (page.unplaced) {
304
- lines.push("", ...wrap(`${countOf(page.unplaced, "unplaced action")}, counted as Production until you place them.`, term.width));
314
+ const among = page.unplacedIncluded ? " among them" : "";
315
+ lines.push("", ...wrap(`${countOf(page.unplaced, "unplaced action")}${among}, counted as Production until you place them.`, term.width));
305
316
  if (links.environments)
306
317
  lines.push(`Set environments: ${links.environments}`);
307
318
  }
package/dist/cliExec.js CHANGED
@@ -401,13 +401,13 @@ function approvalUrl(auth, approvalId) {
401
401
  const workspace = auth.kind === "profile" ? workspaceOfToken(auth.refreshToken) : "";
402
402
  return approvalLink(auth.endpoint, approvalId, workspace || undefined) ?? undefined;
403
403
  }
404
- /** Ask, wait for a person when someone can, and ask again. While it waits,
405
- * stderr shows the approval link at once and a live countdown. */
404
+ /** Ask, wait for a person when someone can (stderr shows the link and a countdown), and ask again. */
406
405
  async function decide(ask, client, prepared, args, runtime, deps, auth) {
407
406
  const decided = await ask();
408
407
  if (decided.decision !== "ask")
409
408
  return decided;
410
409
  const approvalId = typeof decided.approvalId === "string" ? decided.approvalId : "";
410
+ await (await import("./cliHookNotice.js")).rememberExecAsk(approvalId, prepared.body, (deps.now ?? Date.now)());
411
411
  if (!approvalId || prepared.waitSeconds <= 0)
412
412
  return pendingFailure(decided, "Waiting for approval.");
413
413
  let waiting;
@@ -87,8 +87,8 @@ export function problemFix(kind, client) {
87
87
  return {
88
88
  text: "Move it back into Passport.",
89
89
  command: "passport keys move",
90
- link: "#apps",
91
- docs: `${DOCS_BASE}/member/cli-hook#keys-back-on-a-computer`
90
+ link: "#settings/keys",
91
+ docs: `${DOCS_BASE}/member/cli-hook#keys-in-passport`
92
92
  };
93
93
  }
94
94
  }
package/dist/cliHook.js CHANGED
@@ -282,6 +282,10 @@ async function runAudit(args, runtime, deps) {
282
282
  const input = await readInput(runtime, budget);
283
283
  if (!input)
284
284
  return;
285
+ // Claude Code resumed, or the person typed: say what was approved meanwhile.
286
+ const managed = () => managedElsewhere(input, args, runtime);
287
+ if (await (await import("./cliHookNotice.js")).tellApproved(input, args, runtime, deps, budget, managed))
288
+ return;
285
289
  // A session started or ended: one marker, queued like any report.
286
290
  if (await (await import("./cliHookLifecycle.js")).lifecycle(input, args, runtime, deps))
287
291
  return;
@@ -521,6 +525,7 @@ async function runGuard(args, runtime, deps) {
521
525
  });
522
526
  if (plan.output)
523
527
  runtime.stdout.write(`${JSON.stringify(plan.output)}\n`);
528
+ await (await import("./cliHookNotice.js")).rememberGuardAsk(plan, client, sessionOfInput(input), clock());
524
529
  saveScriptCache(scripts);
525
530
  const runtimeName = detectRuntime(input, runtime.env, declared);
526
531
  // Coverage: count what the guard saw, once even when Cursor runs both copies.
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What a blind part of a command was, for coverage: the program that ran it
3
+ * (a plain name, never a path) and its kind, so Rules › Project scripts can
4
+ * tell inline code from a project script from a program Passport doesn't know.
5
+ */
6
+ import type { BlindKind } from "./blindKind.js";
7
+ import type { ShellWord } from "./localCommands.js";
8
+ /** The program a part ran, by name. A file run by path (`./x.sh`, `~/bin/tool`,
9
+ * `$HOME/bin/tool`, `node_modules/.bin/tsc`) is "script". */
10
+ export declare function programOf(argv: string[]): string;
11
+ /** A program run from the home folder by `$HOME/…`: read like `~/…`, so its place is known. */
12
+ export declare function homeProgram<W extends ShellWord>(words: W[]): W[];
13
+ /** Script: a file run by path or given to an interpreter, a task target, a package
14
+ * script Passport couldn't read. Program: anything else it doesn't know. */
15
+ export declare function blindKind(program: string, argv: string[]): BlindKind;