passport-bridge 0.25.0 → 0.26.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.
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`.
@@ -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
+ }
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;
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.
@@ -13,7 +13,9 @@ export type ClientSpec = {
13
13
  post: string;
14
14
  /** Where a command that failed or was interrupted is reported, if separate. */
15
15
  postFailure?: string;
16
- /** Session start and end events the audit entry also runs on (no matcher). */
16
+ /** Session events the audit entry also runs on (no matcher): start and
17
+ * end, and for Claude Code each prompt, which carries a late approval's
18
+ * notice into the conversation (`approvalNotice.ts`). */
17
19
  lifecycle?: string[];
18
20
  path(env: Env): string;
19
21
  };
@@ -29,7 +29,7 @@ export const CLIENTS = {
29
29
  // Claude Code reports an interrupted or failed tool call here instead of
30
30
  // PostToolUse, so an approved command that failed still counts as ran.
31
31
  postFailure: "PostToolUseFailure",
32
- lifecycle: ["SessionStart", "SessionEnd"],
32
+ lifecycle: ["SessionStart", "SessionEnd", "UserPromptSubmit"],
33
33
  path: claudeSettingsPath
34
34
  },
35
35
  codex: {
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Where the hooks and `passport exec` meet late approvals (`approvalNotice.ts`):
3
+ * remember a session that opened a request a person answers later, and on
4
+ * that session's next prompt or resume, print what was approved meanwhile.
5
+ */
6
+ import { type ParsedArgs } from "./cliArgs.js";
7
+ import type { GuardPlan } from "./cliHookDecide.js";
8
+ import type { HookDependencies } from "./cliHookDeliver.js";
9
+ import type { HookInput } from "./cliHookInput.js";
10
+ import type { Runtime } from "./cliSupport.js";
11
+ /** The guard opened a request a person answers later (not one approved during the hold). */
12
+ export declare function rememberGuardAsk(plan: GuardPlan, client: string, sessionId: string | undefined, now: number): Promise<void>;
13
+ /** `passport exec` opened a request: the same, from its request body. */
14
+ export declare function rememberExecAsk(approvalId: string, body: Record<string, unknown>, now: number): Promise<void>;
15
+ /**
16
+ * On Claude Code's SessionStart or UserPromptSubmit: context for the agent
17
+ * about approvals it missed, never more than the hook's budget. True when the
18
+ * event was a prompt, which the audit hook has nothing else to do for.
19
+ */
20
+ export declare function tellApproved(input: HookInput, args: ParsedArgs, runtime: Runtime, deps: HookDependencies, budget: AbortSignal,
21
+ /** Managed settings run Passport's hooks instead: this copy stays quiet. */
22
+ managedElsewhere: () => boolean): Promise<boolean>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Where the hooks and `passport exec` meet late approvals (`approvalNotice.ts`):
3
+ * remember a session that opened a request a person answers later, and on
4
+ * that session's next prompt or resume, print what was approved meanwhile.
5
+ */
6
+ import { value } from "./cliArgs.js";
7
+ /** The guard opened a request a person answers later (not one approved during the hold). */
8
+ export async function rememberGuardAsk(plan, client, sessionId, now) {
9
+ if (!plan.server?.approvalId || plan.server.decision !== "ask" || plan.held === "approved")
10
+ return;
11
+ (await import("./approvalNotice.js")).noteWaitingSession(client, sessionId, now);
12
+ }
13
+ /** `passport exec` opened a request: the same, from its request body. */
14
+ export async function rememberExecAsk(approvalId, body, now) {
15
+ if (approvalId && typeof body.runtime === "string" && typeof body.sessionId === "string") {
16
+ (await import("./approvalNotice.js")).noteWaitingSession(body.runtime, body.sessionId, now);
17
+ }
18
+ }
19
+ /**
20
+ * On Claude Code's SessionStart or UserPromptSubmit: context for the agent
21
+ * about approvals it missed, never more than the hook's budget. True when the
22
+ * event was a prompt, which the audit hook has nothing else to do for.
23
+ */
24
+ export async function tellApproved(input, args, runtime, deps, budget,
25
+ /** Managed settings run Passport's hooks instead: this copy stays quiet. */
26
+ managedElsewhere) {
27
+ const event = input.hook_event_name;
28
+ if (event !== "SessionStart" && event !== "UserPromptSubmit")
29
+ return false;
30
+ const prompt = event === "UserPromptSubmit";
31
+ const [{ localProfile, profileApi }, { approvalNotice }] = await Promise.all([
32
+ import("./cliHookDeliver.js"),
33
+ import("./approvalNotice.js")
34
+ ]);
35
+ const profile = localProfile(args, runtime.env);
36
+ if (!profile || runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT || managedElsewhere())
37
+ return prompt;
38
+ // Session events carry no tool-use id: an entry without `--client` is Claude Code's.
39
+ const named = (value(args, "client") ?? runtime.env.PASSPORT_HOOK_RUNTIME)?.trim().toLowerCase();
40
+ const output = await approvalNotice(input, {
41
+ runtime: named && named !== "claude-code" ? named : "claude-code",
42
+ openApi: () => profileApi(profile, budget, deps.fetch ?? fetch),
43
+ signal: budget,
44
+ now: deps.now ?? Date.now
45
+ });
46
+ if (output)
47
+ runtime.stdout.write(`${JSON.stringify(output)}\n`);
48
+ return prompt;
49
+ }
@@ -13,6 +13,12 @@ import { guardEntryOf } from "./cliHookInstall.js";
13
13
  import { credentialDir, writePrivateAtomic } from "./credentialStorage.js";
14
14
  export const HOLD_NOTICE = "Approvals can now continue automatically.";
15
15
  const DAY_MS = 24 * 60 * 60 * 1000;
16
+ /**
17
+ * A stamp counts as from the future (the clock went back) only past this. A
18
+ * stamp written a moment ago routinely reads a fraction of a millisecond
19
+ * ahead of `Date.now()`, which truncates to whole milliseconds.
20
+ */
21
+ const CLOCK_SKEW_MS = 60_000;
16
22
  /** The command that turns the hold on for one agent's guard. */
17
23
  export function holdFixCommand(client) {
18
24
  return `passport hook install${client === "claude-code" ? "" : ` --agent ${client}`} --apply`;
@@ -45,7 +51,7 @@ export function holdNoticeDue(version, now = Date.now()) {
45
51
  try {
46
52
  const shownAt = statSync(stampPath()).mtimeMs;
47
53
  const shownFor = readBoundedUtf8File(stampPath(), 64).trim();
48
- return shownFor !== version || now - shownAt >= DAY_MS || shownAt > now;
54
+ return shownFor !== version || now - shownAt >= DAY_MS || shownAt - now > CLOCK_SKEW_MS;
49
55
  }
50
56
  catch {
51
57
  return true;
package/dist/hookMain.js CHANGED
@@ -19,12 +19,21 @@ async function run(argv) {
19
19
  const args = await hookArgs(argv);
20
20
  if (!args)
21
21
  return (await import("./cliMain.js")).main(argv);
22
+ // The audit entry also runs on every Claude Code prompt: one with nothing to
23
+ // tell ends here, before the hook loads (`hookPromptFast.ts`).
24
+ let stdin = process.stdin;
25
+ if (args.positionals[0] === undefined && process.env.PASSPORT_HOOK_DISABLED !== "1") {
26
+ const fast = await (await import("./hookPromptFast.js")).promptFastPath(process.stdin, process.env, 1_500);
27
+ if (fast.done)
28
+ return 0;
29
+ stdin = fast.stdin;
30
+ }
22
31
  const { holdForCommand } = await import("./cliSupport.js");
23
32
  const controller = new AbortController();
24
33
  const release = holdForCommand(() => controller.abort(new Error("Cancelled.")));
25
34
  const runtime = {
26
35
  env: process.env,
27
- stdin: process.stdin,
36
+ stdin,
28
37
  stdout: process.stdout,
29
38
  stderr: process.stderr,
30
39
  signal: controller.signal,
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Claude Code runs the audit entry on every prompt (`UserPromptSubmit`), only
3
+ * so a late approval can reach the agent (`approvalNotice.ts`). Almost every
4
+ * prompt has nothing to tell: no session on this computer waited for a
5
+ * person. This reads the event before the hook loads anything else and, for a
6
+ * prompt with no marker anywhere, ends there. Anything else gets the same
7
+ * bytes, unchanged, through a fresh stream.
8
+ *
9
+ * Node built-ins only, so a prompt costs little more than Node's own start.
10
+ */
11
+ type Source = AsyncIterable<string | Uint8Array>;
12
+ /** Whether any session on this computer waits to hear about an approval. */
13
+ export declare function anyWaitingSession(env: Record<string, string | undefined>): boolean;
14
+ /**
15
+ * For the audit entry: `done` when the event is a prompt with nothing to tell
16
+ * (the hook exits at once), else the event's bytes as a new stdin. An event
17
+ * too big or too slow to read is passed on empty, which the hook already
18
+ * treats as no event.
19
+ */
20
+ export declare function promptFastPath(source: Source | undefined, env: Record<string, string | undefined>, budgetMs: number): Promise<{
21
+ done: true;
22
+ } | {
23
+ done: false;
24
+ stdin: Source;
25
+ }>;
26
+ export {};
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Claude Code runs the audit entry on every prompt (`UserPromptSubmit`), only
3
+ * so a late approval can reach the agent (`approvalNotice.ts`). Almost every
4
+ * prompt has nothing to tell: no session on this computer waited for a
5
+ * person. This reads the event before the hook loads anything else and, for a
6
+ * prompt with no marker anywhere, ends there. Anything else gets the same
7
+ * bytes, unchanged, through a fresh stream.
8
+ *
9
+ * Node built-ins only, so a prompt costs little more than Node's own start.
10
+ */
11
+ import { readdirSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ /** What `cliHookInput.ts` reads at most; past it, the hook reads nothing. */
15
+ const STDIN_MAX_BYTES = 1024 * 1024;
16
+ /** Whether any session on this computer waits to hear about an approval. */
17
+ export function anyWaitingSession(env) {
18
+ try {
19
+ const dir = join(env.PASSPORT_HOME || join(homedir(), ".passport"), "hook-approvals");
20
+ return readdirSync(dir).some((name) => name.endsWith(".json"));
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }
26
+ /** Read the event within `budgetMs`: the bytes, or null when it's too big or slow. */
27
+ async function readAll(source, budgetMs) {
28
+ const read = (async () => {
29
+ const chunks = [];
30
+ let bytes = 0;
31
+ for await (const chunk of source) {
32
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk);
33
+ bytes += buffer.byteLength;
34
+ if (bytes > STDIN_MAX_BYTES)
35
+ return null;
36
+ chunks.push(buffer);
37
+ }
38
+ return Buffer.concat(chunks);
39
+ })().catch(() => null);
40
+ let timer;
41
+ const late = new Promise((resolve) => {
42
+ timer = setTimeout(() => {
43
+ const destroy = source.destroy;
44
+ if (typeof destroy === "function")
45
+ destroy.call(source);
46
+ resolve(null);
47
+ }, budgetMs);
48
+ });
49
+ try {
50
+ return await Promise.race([read, late]);
51
+ }
52
+ finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+ async function* replay(bytes) {
57
+ if (bytes?.byteLength)
58
+ yield bytes;
59
+ }
60
+ /**
61
+ * For the audit entry: `done` when the event is a prompt with nothing to tell
62
+ * (the hook exits at once), else the event's bytes as a new stdin. An event
63
+ * too big or too slow to read is passed on empty, which the hook already
64
+ * treats as no event.
65
+ */
66
+ export async function promptFastPath(source, env, budgetMs) {
67
+ if (!source)
68
+ return { done: false, stdin: replay(null) };
69
+ const bytes = await readAll(source, budgetMs);
70
+ // A cheap look before parsing: only a prompt can end here.
71
+ if (bytes && bytes.includes("UserPromptSubmit") && !anyWaitingSession(env)) {
72
+ try {
73
+ const event = JSON.parse(bytes.toString("utf8"));
74
+ if (event && event.hook_event_name === "UserPromptSubmit")
75
+ return { done: true };
76
+ }
77
+ catch {
78
+ /* Not an event: the hook decides, as before. */
79
+ }
80
+ }
81
+ return { done: false, stdin: replay(bytes) };
82
+ }
@@ -4,4 +4,4 @@
4
4
  * the version, then runs `npm run set-version -- <version>` in the plugin repo
5
5
  * and pushes (docs/RELEASING.md). `pluginPin.test.ts` fails when it drifts.
6
6
  */
7
- export declare const PLUGIN_PIN = "0.25.0";
7
+ export declare const PLUGIN_PIN = "0.26.0";
package/dist/pluginPin.js CHANGED
@@ -4,4 +4,4 @@
4
4
  * the version, then runs `npm run set-version -- <version>` in the plugin repo
5
5
  * and pushes (docs/RELEASING.md). `pluginPin.test.ts` fails when it drifts.
6
6
  */
7
- export const PLUGIN_PIN = "0.25.0";
7
+ export const PLUGIN_PIN = "0.26.0";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.25.0";
1
+ export declare const VERSION = "0.26.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Keep in lockstep with bridge/package.json.
2
- export const VERSION = "0.25.0";
2
+ export const VERSION = "0.26.0";
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "passport-bridge",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "passport-bridge",
9
- "version": "0.25.0",
9
+ "version": "0.26.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "1.32.1"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passport-bridge",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "Passport CLI for governed terminal and CI agents, plus the local stdio-to-cloud MCP bridge.",
5
5
  "license": "MIT",
6
6
  "repository": {