passport-bridge 0.30.0 → 0.31.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 (106) hide show
  1. package/README.md +9 -6
  2. package/dist/cliAllowances.d.ts +47 -0
  3. package/dist/cliAllowances.js +89 -0
  4. package/dist/cliArgs.js +2 -1
  5. package/dist/cliAutopilot.d.ts +4 -0
  6. package/dist/cliAutopilot.js +6 -2
  7. package/dist/cliAutopilotPolicy.d.ts +38 -0
  8. package/dist/cliAutopilotPolicy.js +29 -10
  9. package/dist/cliChanges.d.ts +7 -0
  10. package/dist/cliChanges.js +37 -3
  11. package/dist/cliExec.d.ts +2 -27
  12. package/dist/cliExec.js +7 -16
  13. package/dist/cliGuardHealth.d.ts +9 -4
  14. package/dist/cliGuardHealth.js +13 -6
  15. package/dist/cliGuardState.js +5 -3
  16. package/dist/cliHook.d.ts +2 -5
  17. package/dist/cliHook.js +66 -72
  18. package/dist/cliHookAfter.d.ts +71 -0
  19. package/dist/cliHookAfter.js +134 -0
  20. package/dist/cliHookAllowance.d.ts +22 -0
  21. package/dist/cliHookAllowance.js +34 -0
  22. package/dist/cliHookClassify.d.ts +4 -0
  23. package/dist/cliHookClassify.js +41 -39
  24. package/dist/cliHookCreates.d.ts +41 -0
  25. package/dist/cliHookCreates.js +195 -0
  26. package/dist/cliHookDecide.d.ts +3 -0
  27. package/dist/cliHookDecide.js +30 -1
  28. package/dist/cliHookDeliver.d.ts +27 -0
  29. package/dist/cliHookDeliver.js +9 -0
  30. package/dist/cliHookEnvironment.js +22 -9
  31. package/dist/cliHookGuard.d.ts +13 -0
  32. package/dist/cliHookGuard.js +20 -15
  33. package/dist/cliHookInput.d.ts +8 -0
  34. package/dist/cliHookLease.d.ts +78 -0
  35. package/dist/cliHookLease.js +216 -0
  36. package/dist/cliHookLifecycle.d.ts +5 -2
  37. package/dist/cliHookLifecycle.js +18 -5
  38. package/dist/cliHookLocal.d.ts +8 -1
  39. package/dist/cliHookLocal.js +32 -4
  40. package/dist/cliHookNotice.d.ts +11 -3
  41. package/dist/cliHookNotice.js +53 -9
  42. package/dist/cliHookOutcome.d.ts +16 -0
  43. package/dist/cliHookOutcome.js +53 -0
  44. package/dist/cliHookPairing.d.ts +9 -0
  45. package/dist/cliHookPairing.js +42 -0
  46. package/dist/cliHookParse.d.ts +6 -0
  47. package/dist/cliHookParse.js +10 -2
  48. package/dist/cliHookProject.d.ts +2 -0
  49. package/dist/cliHookProject.js +11 -0
  50. package/dist/cliHookRewrite.d.ts +22 -0
  51. package/dist/cliHookRewrite.js +183 -10
  52. package/dist/cliHookScripts.js +2 -0
  53. package/dist/cliHookSessionEnd.d.ts +14 -0
  54. package/dist/cliHookSessionEnd.js +45 -1
  55. package/dist/cliHookSessionState.d.ts +45 -0
  56. package/dist/cliHookSessionState.js +130 -0
  57. package/dist/cliHookSpawn.d.ts +23 -0
  58. package/dist/cliHookSpawn.js +219 -0
  59. package/dist/cliHookStuck.d.ts +42 -0
  60. package/dist/cliHookStuck.js +69 -0
  61. package/dist/cliHookUncheckedName.d.ts +7 -0
  62. package/dist/cliHookUncheckedName.js +57 -0
  63. package/dist/cliHookVendors.d.ts +4 -0
  64. package/dist/cliHookVendors.js +40 -17
  65. package/dist/cliHookVendorsMore.js +3 -1
  66. package/dist/cliLoosening.d.ts +17 -3
  67. package/dist/cliLoosening.js +72 -10
  68. package/dist/cliOutput.js +4 -3
  69. package/dist/cliPolicy.js +3 -1
  70. package/dist/cliPolicyV2.js +49 -4
  71. package/dist/cliRequest.d.ts +3 -0
  72. package/dist/cliRequest.js +5 -0
  73. package/dist/cliRequestTask.d.ts +22 -0
  74. package/dist/cliRequestTask.js +87 -0
  75. package/dist/cliStatus.d.ts +3 -1
  76. package/dist/cliStatus.js +15 -3
  77. package/dist/cliStatusGuard.js +1 -1
  78. package/dist/execBackupLine.d.ts +7 -0
  79. package/dist/execBackupLine.js +16 -0
  80. package/dist/execLease.d.ts +5 -0
  81. package/dist/execLease.js +38 -0
  82. package/dist/hookFastPath.js +7 -0
  83. package/dist/hookPromptFast.d.ts +2 -1
  84. package/dist/hookPromptFast.js +11 -8
  85. package/dist/initAutopilotStep.d.ts +1 -18
  86. package/dist/initAutopilotStep.js +16 -27
  87. package/dist/initLocalSteps.js +11 -0
  88. package/dist/initOutro.js +16 -7
  89. package/dist/initUi.d.ts +6 -2
  90. package/dist/initUi.js +12 -3
  91. package/dist/leaseCommands.d.ts +42 -0
  92. package/dist/leaseCommands.js +118 -0
  93. package/dist/pluginPin.d.ts +1 -1
  94. package/dist/pluginPin.js +1 -1
  95. package/dist/repoRules.d.ts +45 -0
  96. package/dist/repoRules.js +179 -0
  97. package/dist/sessionBrief.d.ts +27 -0
  98. package/dist/sessionBrief.js +89 -0
  99. package/dist/signInFailure.d.ts +28 -0
  100. package/dist/signInFailure.js +65 -0
  101. package/dist/version.d.ts +1 -1
  102. package/dist/version.js +1 -1
  103. package/dist/watchNotice.d.ts +66 -0
  104. package/dist/watchNotice.js +233 -0
  105. package/npm-shrinkwrap.json +6 -6
  106. package/package.json +1 -1
@@ -4,8 +4,9 @@
4
4
  * Home, and the bell show it. Self-reported, read-only, and counts and flags
5
5
  * only: never a command, a path, or a setting's value.
6
6
  *
7
- * Sent from a guard run that has 300 ms of its budget left, from
8
- * `passport exec`, and from `passport status`.
7
+ * Sent from a guard run that has 300 ms of its budget left and from
8
+ * `passport exec` once a day, and every time from `passport init` (after the
9
+ * guard step) and `passport status`.
9
10
  */
10
11
  import { closeSync, constants, mkdirSync, openSync, readFileSync, statSync, utimesSync } from "node:fs";
11
12
  import { join } from "node:path";
@@ -143,12 +144,18 @@ export async function sendGuardHealth(api, profile, env, signal) {
143
144
  return null;
144
145
  }
145
146
  }
146
- /** The daily report, if due: claim, then send. */
147
- export async function guardHeartbeat(api, profile, env, signal, now = Date.now()) {
148
- if (!claimGuardHeartbeat(profile, now))
147
+ /**
148
+ * The daily report, if due: claim, then send. `force` sends it now anyway,
149
+ * for `init` (it just turned the guard on) and `status` (someone is looking),
150
+ * so Agents shows each agent's guard without waiting a day.
151
+ */
152
+ export async function guardHeartbeat(api, profile, env, signal, now = Date.now(), force = false) {
153
+ const due = claimGuardHeartbeat(profile, now);
154
+ if (!due && !(force && stampHeartbeat(profile, now)))
149
155
  return null;
150
156
  const sent = await sendGuardHealth(api, profile, env, signal);
151
157
  // Once a day too: has a key `passport keys move` removed come back?
152
- await (await import("./cliKeysBack.js")).checkKeysBack(api, signal, process.env, profile).catch(() => undefined);
158
+ if (due)
159
+ await (await import("./cliKeysBack.js")).checkKeysBack(api, signal, process.env, profile).catch(() => undefined);
153
160
  return sent;
154
161
  }
@@ -24,6 +24,8 @@ export const GUARD_STATE_LABEL = {
24
24
  export const GUARD_MIN_CLI_VERSION = "0.16.0";
25
25
  export const GUARD_HEARTBEAT_MS = 24 * 60 * 60_000;
26
26
  export const DOCS_BASE = "https://docs.passportmcp.com";
27
+ /** Work's Actions view, the commands Passport couldn't check. */
28
+ const UNCHECKED_LINK = "#work?view=actions&outcome=unchecked";
27
29
  function versionParts(version) {
28
30
  const [major, minor, patch] = version.split(".").map((part) => Number.parseInt(part, 10));
29
31
  return [major || 0, minor || 0, patch || 0];
@@ -79,9 +81,9 @@ export function problemFix(kind, client) {
79
81
  };
80
82
  case "coverage-drop":
81
83
  return {
82
- text: "Open the agent's tasks on Work and look at what Passport couldn't tell.",
83
- link: agent,
84
- docs: `${DOCS_BASE}/member/cli-hook#decided-placed-and-blind`
84
+ text: "See them on Work. To teach Passport one of your project scripts, run passport actions add.",
85
+ link: UNCHECKED_LINK,
86
+ docs: `${DOCS_BASE}/member/cli-hook#tell-passport-what-a-script-does`
85
87
  };
86
88
  case "key-back":
87
89
  return {
package/dist/cliHook.d.ts CHANGED
@@ -18,10 +18,12 @@ import { type ParsedArgs } from "./cliArgs.js";
18
18
  import { type CliFinding } from "./cliHookClassify.js";
19
19
  import { type DecidedFinding, type GuardDecision } from "./cliHookGuard.js";
20
20
  import { type HookInput } from "./cliHookInput.js";
21
+ export { pairingId } from "./cliHookPairing.js";
21
22
  import { type CliHookReport, type HookDependencies, type HookRuntime } from "./cliHookDeliver.js";
22
23
  export { HOOK_BUDGET_MS, HOOK_RUNTIMES, legacyReport, type CliHookReport, type HookDependencies, type HookRuntime, type ReportedFinding } from "./cliHookDeliver.js";
23
24
  export { opaqueKind, opaqueProgram } from "./cliHookOpaque.js";
24
25
  import { type ScriptReader } from "./cliScriptRead.js";
26
+ export { outcomeOf } from "./cliHookOutcome.js";
25
27
  import type { CommandResult, Env, Runtime } from "./cliSupport.js";
26
28
  export type { HookInput };
27
29
  /** One shell command, whichever agent format it arrived in. */
@@ -43,11 +45,6 @@ export declare function safeVerb(raw: string | null): string;
43
45
  * hooks by default.
44
46
  */
45
47
  export declare function detectRuntime(input: HookInput, env: Env, declared?: string): HookRuntime;
46
- /** Exit status of the command the agent ran, when the runtime reports one. */
47
- export declare function outcomeOf(response: unknown): {
48
- exitCode?: number;
49
- durationMs?: number;
50
- };
51
48
  export declare function buildReport(input: HookInput, findings: CliFinding[], env: Env, declared?: string, decided?: DecidedFinding[], local?: boolean, scripts?: ScriptReader, backedUp?: ReadonlySet<CliFinding>): CliHookReport | null;
52
49
  /** What the guard answered, and for which findings. The audit row that
53
50
  * follows a command that ran carries its outcome and any opaque parts. */
package/dist/cliHook.js CHANGED
@@ -23,18 +23,23 @@ import { guardMachineOf } from "./cliHookGuard.js";
23
23
  import { detectMode } from "./cliHookMode.js";
24
24
  import { cappedHold, holdSeconds } from "./cliHookHold.js";
25
25
  import { commandText, readInput } from "./cliHookInput.js";
26
+ import { pairingId, withPairing, withParked } from "./cliHookPairing.js";
27
+ export { pairingId } from "./cliHookPairing.js";
26
28
  import { budgetSignal, expiredAsks, HOOK_BUDGET_MS, HOOK_RUNTIMES, leftovers, localProfile, localSelection, profileApi, queueAfterCommand, reportSender, runFlush, startFlushIfDue } from "./cliHookDeliver.js";
27
29
  export { HOOK_BUDGET_MS, HOOK_RUNTIMES, legacyReport } from "./cliHookDeliver.js";
28
30
  import { hookViaPlugin } from "./hookPlugin.js";
29
31
  import { guardLocalBackups, markLocalBackups } from "./localBackups.js";
30
32
  import { auditBackups, auditDecision, auditedCommand, markTrashed } from "./cliHookAudit.js";
33
+ import { uncheckedNames } from "./cliHookUncheckedName.js";
31
34
  import { opaqueParts } from "./cliHookOpaque.js";
32
35
  export { opaqueKind, opaqueProgram } from "./cliHookOpaque.js";
33
- import { hasExpired, holdAsk, takeAsk } from "./cliHookPending.js";
36
+ import { hasExpired, holdAsk } from "./cliHookPending.js";
34
37
  import { readCliPolicy } from "./cliPolicy.js";
35
38
  import { saveScriptCache, scriptReader, scriptReport } from "./cliScriptRead.js";
36
39
  import { standDownForManaged } from "./managedHooks.js";
37
40
  import { withStep } from "./cliHookStep.js";
41
+ import { isCursorEvent, outcomeOfInput } from "./cliHookOutcome.js";
42
+ export { outcomeOf } from "./cliHookOutcome.js";
38
43
  const MAX_FINDINGS = 8;
39
44
  const MAX_OPAQUE_KINDS = 6;
40
45
  const SHELL_TOOLS = new Set(["Bash", "bash", "shell", "Shell"]);
@@ -52,7 +57,9 @@ function text(candidate, max) {
52
57
  /** This machine for the guard, with the repository's name for code to main. */
53
58
  function guardAtFor(machine, input, env) {
54
59
  const repo = projectOf(workingFolder(input)).project;
55
- return { ...guardMachineOf(machine, workingFolder(input), env), ...(repo ? { repo } : {}) };
60
+ const id = sessionOfInput(input);
61
+ const session = id ? { runtime: detectRuntime(input, env), id } : undefined;
62
+ return { ...guardMachineOf(machine, workingFolder(input), env), ...(repo ? { repo } : {}), session };
56
63
  }
57
64
  /** The agent's own session id, as the hook input names it. */
58
65
  function sessionOfInput(input) {
@@ -66,9 +73,6 @@ function directoryName(candidate) {
66
73
  const segment = trimmed.slice(Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\")) + 1);
67
74
  return text(segment, 80);
68
75
  }
69
- function integer(candidate) {
70
- return typeof candidate === "number" && Number.isFinite(candidate) ? Math.trunc(candidate) : undefined;
71
- }
72
76
  function record(candidate) {
73
77
  return candidate && typeof candidate === "object" && !Array.isArray(candidate)
74
78
  ? candidate
@@ -83,9 +87,6 @@ export function safeVerb(raw) {
83
87
  .slice(0, 4);
84
88
  return tokens.join(" ").slice(0, 80).trim() || UNRECOGNIZED_VERB;
85
89
  }
86
- function isCursorEvent(input) {
87
- return input.hook_event_name === "beforeShellExecution" || input.hook_event_name === "afterShellExecution";
88
- }
89
90
  /**
90
91
  * Which agent sent this. An installed hook names its client with `--client`;
91
92
  * Cursor is also recognised by its own event names and version field, which
@@ -103,35 +104,6 @@ export function detectRuntime(input, env, declared) {
103
104
  typeof input.tool_use_id === "string";
104
105
  return claudeCode ? "claude-code" : "other";
105
106
  }
106
- /** Exit status of the command the agent ran, when the runtime reports one. */
107
- export function outcomeOf(response) {
108
- const body = record(response);
109
- const exit = integer(body.exitCode) ?? integer(body.exit_code) ?? integer(body.returnCode);
110
- const duration = integer(body.durationMs) ?? integer(body.duration_ms);
111
- const failed = body.is_error === true || body.isError === true;
112
- return {
113
- ...(exit !== undefined
114
- ? { exitCode: exit }
115
- : body.interrupted === true
116
- ? { exitCode: 130 }
117
- : failed
118
- ? { exitCode: 1 }
119
- : {}),
120
- ...(duration !== undefined && duration >= 0 ? { durationMs: duration } : {})
121
- };
122
- }
123
- function outcomeOfInput(input) {
124
- if (input.hook_event_name === "PostToolUseFailure") {
125
- // The call failed or was interrupted: it ran, and it did not succeed.
126
- const reported = outcomeOf(input.tool_response);
127
- const exitCode = reported.exitCode ?? (input.is_interrupt === true ? 130 : 1);
128
- return { ...reported, exitCode: exitCode === 0 ? 1 : exitCode };
129
- }
130
- if (!isCursorEvent(input))
131
- return outcomeOf(input.tool_response);
132
- const duration = integer(input.duration);
133
- return duration !== undefined && duration >= 0 ? { durationMs: duration } : {};
134
- }
135
107
  function context(input, env, declared) {
136
108
  const sessionId = text(input.session_id, 128) ?? text(input.conversation_id, 128);
137
109
  const toolUseId = text(input.tool_use_id, 128);
@@ -182,6 +154,7 @@ export function buildReport(input, findings, env, declared, decided = [], local
182
154
  if (!governed.length && !summary.opaque && !extra.projectChanged && !extra.drift)
183
155
  return null;
184
156
  const { kinds, programs } = opaqueParts(summary.unknown, MAX_OPAQUE_KINDS);
157
+ const names = uncheckedNames(summary.unknown, MAX_OPAQUE_KINDS);
185
158
  const where = context(input, env, declared);
186
159
  return {
187
160
  ...where,
@@ -190,6 +163,7 @@ export function buildReport(input, findings, env, declared, decided = [], local
190
163
  opaque: summary.opaque,
191
164
  ...(summary.opaque && kinds.length ? { opaqueKinds: kinds } : {}),
192
165
  ...(summary.opaque && programs.length ? { opaquePrograms: programs } : {}),
166
+ ...(summary.opaque && names.length ? { opaqueNames: names } : {}),
193
167
  ...extra
194
168
  };
195
169
  }
@@ -293,14 +267,20 @@ async function runAudit(args, runtime, deps) {
293
267
  const event = hookEvent(input, "post", args, runtime);
294
268
  if (!event)
295
269
  return;
296
- const audited = auditedCommand(event.command);
297
- if (!audited)
298
- return;
299
- const { command, trashed } = audited;
300
270
  if (event.cursorImported && (await cursorHasOwnEntry(runtime, "audit")))
301
271
  return;
302
272
  const profile = localProfile(args, runtime.env);
303
273
  const policy = profile ? readCliPolicy(profile) : null;
274
+ const now = (deps.now ?? Date.now)();
275
+ const runtimeName = detectRuntime(input, runtime.env, value(args, "client"));
276
+ const after = await import("./cliHookAfter.js");
277
+ const facts = { input, profile, policy, runtimeName, cursorImported: event.cursorImported, now };
278
+ const base = () => context(input, runtime.env, value(args, "client"));
279
+ const audited = auditedCommand(event.command);
280
+ // `passport exec` records its own row; what it created or kept failing at still counts.
281
+ if (!audited)
282
+ return void (await after.afterExec({ ...facts, command: event.command, args, runtime, deps, base }));
283
+ const { command, trashed } = audited;
304
284
  // The post-hook reads the same scripts again: a change since the guard's
305
285
  // check is drift (item 6).
306
286
  const scripts = scriptReader({ phase: "post", project: projectContext(policy), now: deps.budget?.scriptClock });
@@ -309,7 +289,7 @@ async function runAudit(args, runtime, deps) {
309
289
  const findings = line.findings;
310
290
  saveScriptCache(scripts);
311
291
  // v2: the same decision the guard made, so the row says why it ran.
312
- const key = context(input, runtime.env, value(args, "client"));
292
+ const key = withPairing(context(input, runtime.env, value(args, "client")), input, event.command);
313
293
  const { taken, backedUp } = auditBackups(findings, key, Boolean(trashed));
314
294
  const guardAt = { ...guardAtFor(machine, input, runtime.env), ...taken };
315
295
  const { decision, local, decided } = auditDecision(findings, policy, command, line.complete, guardAt);
@@ -319,16 +299,25 @@ async function runAudit(args, runtime, deps) {
319
299
  if (report && policy?.version === 2) {
320
300
  report = withStep({ ...report, ...autopilotDecision(decision) }, input, policy);
321
301
  }
322
- const now = (deps.now ?? Date.now)();
302
+ // A sign-in that expired, what it created, a retry loop: the report, and what Claude Code reads.
303
+ const told = after.afterCommand({ ...facts, command, findings, report, base });
304
+ report = told.report;
305
+ if (told.output)
306
+ runtime.stdout.write(`${JSON.stringify(told.output)}\n`);
323
307
  // The guard parked what it decided before this exact command: send one row
324
308
  // for both, "asked first, then ran" (or the server's own allow).
325
309
  if (report && !event.cursorImported)
326
- report = await withParked(report, input, profile, now);
310
+ report = await withParked(report, pairingId(input, event.command), profile, now);
311
+ // A deploy lease the guard took for this command: released, and noted when it waited.
312
+ const leases = report && profile ? await import("./cliHookLease.js") : null;
313
+ if (leases)
314
+ report = await leases.afterRun(report, event.command, () => profileApi(profile, budget, deps.fetch ?? fetch));
315
+ const agent = report?.runtime ?? detectRuntime(input, runtime.env, value(args, "client"));
316
+ await (await import("./cliHookNotice.js")).tellWatch(input, report, agent, args, runtime, deps, budget, now);
327
317
  if (!report && !hasExpired(now))
328
318
  return;
329
319
  if (!deps.send && !deps.fetch) {
330
- const runtimeName = report?.runtime ?? detectRuntime(input, runtime.env, value(args, "client"));
331
- await queueAfterCommand(report, args, runtime, runtimeName, now);
320
+ await queueAfterCommand(report, args, runtime, report?.runtime ?? runtimeName, now);
332
321
  return;
333
322
  }
334
323
  const send = await reportSender(args, runtime, budget, deps);
@@ -339,20 +328,6 @@ async function runAudit(args, runtime, deps) {
339
328
  await Promise.allSettled(reports.map((entry) => send(entry)));
340
329
  }
341
330
  /** One row for an ask and the run that followed it; how long the person took to say yes. */
342
- async function withParked(report, input, profile, now) {
343
- const toolUseId = text(input.tool_use_id, 128);
344
- const parked = toolUseId ? takeAsk(report.runtime, report.sessionId, toolUseId) : null;
345
- if (!parked)
346
- return report;
347
- const held = parked.report;
348
- if (held.decision === "allow")
349
- return { ...report, decision: "allow" };
350
- // From the prompt to the command finishing, less its own run time.
351
- const waited = now - parked.createdAt - (report.durationMs ?? 0);
352
- if (profile && waited >= 0)
353
- (await import("./cliSpeed.js")).noteApprovalWait(profile, report.runtime, waited, now);
354
- return { ...report, decision: "ask", ran: true };
355
- }
356
331
  function outputClient(event, runtime) {
357
332
  if (event.cursorNative)
358
333
  return "cursor";
@@ -365,9 +340,10 @@ function outputClient(event, runtime) {
365
340
  * allow, or an ask parked until the command runs). */
366
341
  async function guardReport(base, plan, context) {
367
342
  if (plan.server && base)
368
- return serverDecidedReport(base, plan.server, context.now, plan.held);
369
- // Offline, this computer's answer replaces the local Ask on the record.
370
- const decided = base && plan.offline && plan.verdict ? { ...base, decision: plan.verdict } : base;
343
+ return serverDecidedReport(base, plan.server, context.now, plan.held, context.pairingId);
344
+ // Offline, or refused for another session's deploy, this computer's answer is the record.
345
+ const own = base && (plan.offline || plan.lease) && plan.verdict;
346
+ const decided = own ? { ...base, decision: plan.verdict, ...(plan.lease ? { lease: plan.lease } : {}) } : base;
371
347
  const report = decided && context.v2 && decided.decision === "allow" ? null : codexAskBlocked(decided);
372
348
  if (!report)
373
349
  return null;
@@ -384,21 +360,22 @@ async function guardReport(base, plan, context) {
384
360
  * earlier) is parked for the run's own row; a waiting request is "asked"; a
385
361
  * declined one is "asked, not run"; a block is a block.
386
362
  */
387
- function serverDecidedReport(base, server, now, held) {
363
+ function serverDecidedReport(base, server, now, held, pairingId = base.toolUseId) {
388
364
  if (server.decision === "none")
389
365
  return null;
390
366
  // Held, and approved in time: "asked first, then ran", once the run reports.
391
367
  if (held === "approved") {
392
368
  const asked = { ...base, decision: "ask" };
393
- if (base.toolUseId && holdAsk(base.runtime, base.sessionId, base.toolUseId, asked, now))
369
+ if (pairingId && holdAsk(base.runtime, base.sessionId, pairingId, asked, now))
394
370
  return null;
395
371
  return { ...asked, ran: true };
396
372
  }
397
373
  if (held === "declined" || held === "expired")
398
374
  return { ...base, decision: "ask", ran: false };
399
375
  if (server.decision === "allow") {
400
- if (base.toolUseId)
401
- holdAsk(base.runtime, base.sessionId, base.toolUseId, { ...base, decision: "allow" }, now);
376
+ // Cursor too (by its pairing id), so the run's own row says it was allowed, not asked.
377
+ if (pairingId)
378
+ holdAsk(base.runtime, base.sessionId, pairingId, { ...base, decision: "allow" }, now);
402
379
  return null;
403
380
  }
404
381
  if (server.decision === "ask")
@@ -450,6 +427,17 @@ function startOf(deps) {
450
427
  const now = (deps.now ?? Date.now)();
451
428
  return deps.now ? now : Math.min(now, Math.round(performance.timeOrigin));
452
429
  }
430
+ /** Before the guard decides as usual: a stuck agent's answer (`cliHookStuck.ts`, read only when it
431
+ * can matter), then the sign-in and rewrite answers. */
432
+ async function earlyAnswer(input, stuck, rewrite) {
433
+ const sessionId = sessionOfInput(input);
434
+ const claudeCode = stuck.client === "claude-code" && !stuck.cursorImported;
435
+ const retryLoops = stuck.policy?.version === 2 && stuck.policy.autopilot.retryLoops === true;
436
+ const told = sessionId && (retryLoops || !claudeCode)
437
+ ? (await import("./cliHookStuck.js")).stuckAnswer({ ...stuck, sessionId, claudeCode })
438
+ : null;
439
+ return told ?? (await import("./cliHookRewrite.js")).guardEarlyAnswer(rewrite);
440
+ }
453
441
  async function runGuard(args, runtime, deps) {
454
442
  if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
455
443
  return;
@@ -474,22 +462,27 @@ async function runGuard(args, runtime, deps) {
474
462
  const declared = value(args, "client");
475
463
  const client = outputClient(event, detectRuntime(input, runtime.env, declared));
476
464
  // Which deletes will have a backup on this computer, so the rules decide knowing it.
465
+ const key = withPairing(context(input, runtime.env, declared), input, event.command);
477
466
  const backups = guardLocalBackups(event.command, line, policy, {
478
- ...{ ...guardAtFor(machine, input, runtime.env), machine, key: context(input, runtime.env, declared) },
467
+ ...{ ...guardAtFor(machine, input, runtime.env), machine, key },
479
468
  rewrite: client === "claude-code" && !event.cursorImported
480
469
  });
481
470
  let decision = backups.decision;
482
471
  const local = policy?.version === 2 && policy.autopilot.localCommands === true;
483
472
  const mode = detectMode(input, runtime.env).mode;
484
473
  const canReport = Boolean(profile) && !runtime.env.PASSPORT_AGENT_KEY && !runtime.env.PASSPORT_ENDPOINT;
485
- // A sign-in for a CLI whose key Passport holds (any agent), or the rewrite to exec (Claude Code).
474
+ // A retry loop the person asked to stop, or a sign-in that expired here (Codex, Cursor); then a
475
+ // sign-in for a CLI whose key Passport holds (any agent), or the rewrite to exec (Claude Code).
486
476
  const rewritten = profile
487
- ? await (await import("./cliHookRewrite.js")).guardEarlyAnswer({
477
+ ? await earlyAnswer(input, {
478
+ ...{ command: event.command, cursorImported: Boolean(event.cursorImported), client, mode, policy, decision },
479
+ ...{ findings: line.findings, runtimeName: detectRuntime(input, runtime.env, declared), now: clock() }
480
+ }, {
488
481
  command: event.command,
489
482
  toolInput: record(input.tool_input),
490
483
  sessionId: text(input.session_id, 128),
491
484
  named: value(args, "profile"),
492
- ...{ decision, profile, machine, env: runtime.env, invocation: deps.invocation, client, canReport },
485
+ ...{ decision, profile, machine, env: runtime.env, invocation: deps.invocation, client, canReport, policy },
493
486
  cursorImported: Boolean(event.cursorImported),
494
487
  attended: mode === "attended"
495
488
  })
@@ -551,7 +544,8 @@ async function runGuard(args, runtime, deps) {
551
544
  const report = await guardReport(withStep(base && plan.output ? base : null, input, policy), plan, {
552
545
  v2: policy?.version === 2,
553
546
  runtime,
554
- now: clock()
547
+ now: clock(),
548
+ pairingId: pairingId(input, event.command)
555
549
  });
556
550
  if (!deps.send && !deps.fetch) {
557
551
  // The agent is waiting for this process to exit: never wait on the network
@@ -0,0 +1,71 @@
1
+ /**
2
+ * What the after-hook learns once a command has run, on this computer (spec
3
+ * "agent time savers" 1 and 4):
4
+ *
5
+ * - its exit status (`outcomeOf`);
6
+ * - a vendor sign-in that expired here (`signInFailure.ts`, from the last
7
+ * 4 KB of output, read locally and never sent);
8
+ * - what it created or removed that keeps running (`cliHookCreates.ts`);
9
+ * - how many times in a row the same command failed (`cliHookSessionState.ts`).
10
+ *
11
+ * The report carries only the vendor, kinds, names, and counts, and only to
12
+ * a server that keeps them (cli-policy v2 `afterFacts`). The agent hears
13
+ * about a sign-in or a retry loop in its own words: Claude Code as
14
+ * `additionalContext` now; Codex and Cursor from the guard on their next try.
15
+ */
16
+ import type { ParsedArgs } from "./cliArgs.js";
17
+ import type { CliFinding } from "./cliHookClassify.js";
18
+ import type { CliHookReport, HookDependencies, HookRuntime } from "./cliHookDeliver.js";
19
+ import type { HookInput } from "./cliHookInput.js";
20
+ import type { CachedCliPolicy } from "./cliPolicy.js";
21
+ import type { Runtime } from "./cliSupport.js";
22
+ import { type ExecVendor } from "./execVendors.js";
23
+ /** The agent hears about a retry loop from this many failures in a row. */
24
+ export declare const RETRY_TELL_AT = 3;
25
+ /** What Claude Code reads when the sign-in expired. */
26
+ export declare function signInContext(vendor: ExecVendor, held: boolean, rerouted: boolean): string;
27
+ /** What the agent reads when the same command keeps failing. */
28
+ export declare function retryContext(streak: number, program: string | undefined, asksNext: boolean): string;
29
+ type AfterContext = {
30
+ input: HookInput;
31
+ command: string;
32
+ findings: readonly CliFinding[];
33
+ report: CliHookReport | null;
34
+ /** The report's agent, session, and folder, for a report built here. */
35
+ base: () => Omit<CliHookReport, "findings" | "opaque">;
36
+ profile: string | undefined;
37
+ policy: CachedCliPolicy | null;
38
+ runtimeName: HookRuntime;
39
+ cursorImported: boolean;
40
+ now: number;
41
+ /** `passport exec` ran it with the key Passport holds: a sign-in here isn't the cause. */
42
+ exec?: true;
43
+ };
44
+ /**
45
+ * After a command: the report with what the hook learned, and what Claude
46
+ * Code should read (or null). Codex and Cursor are told by the guard on the
47
+ * next try, from this session's state.
48
+ */
49
+ export declare function afterCommand(context: AfterContext): {
50
+ report: CliHookReport | null;
51
+ output: Record<string, unknown> | null;
52
+ };
53
+ /**
54
+ * `passport exec` records its own action, so the after-hook sends no row for
55
+ * it; what the command inside it created, removed, or kept failing at is
56
+ * still worth knowing. Queued like any report, never sent inline.
57
+ */
58
+ export declare function afterExec(context: {
59
+ input: HookInput;
60
+ command: string;
61
+ args: ParsedArgs;
62
+ runtime: Runtime;
63
+ deps: HookDependencies;
64
+ base: () => Omit<CliHookReport, "findings" | "opaque">;
65
+ profile: string | undefined;
66
+ policy: CachedCliPolicy | null;
67
+ runtimeName: HookRuntime;
68
+ cursorImported: boolean;
69
+ now: number;
70
+ }): Promise<void>;
71
+ export {};
@@ -0,0 +1,134 @@
1
+ /**
2
+ * What the after-hook learns once a command has run, on this computer (spec
3
+ * "agent time savers" 1 and 4):
4
+ *
5
+ * - its exit status (`outcomeOf`);
6
+ * - a vendor sign-in that expired here (`signInFailure.ts`, from the last
7
+ * 4 KB of output, read locally and never sent);
8
+ * - what it created or removed that keeps running (`cliHookCreates.ts`);
9
+ * - how many times in a row the same command failed (`cliHookSessionState.ts`).
10
+ *
11
+ * The report carries only the vendor, kinds, names, and counts, and only to
12
+ * a server that keeps them (cli-policy v2 `afterFacts`). The agent hears
13
+ * about a sign-in or a retry loop in its own words: Claude Code as
14
+ * `additionalContext` now; Codex and Cursor from the guard on their next try.
15
+ */
16
+ import { resourcesOf } from "./cliHookCreates.js";
17
+ import { classifyLine, localMachine, workingFolder } from "./cliHookLocal.js";
18
+ import { execInner } from "./cliHookRewrite.js";
19
+ import { nextRetry, readSessionState, writeSessionState } from "./cliHookSessionState.js";
20
+ import { readExecVendors } from "./execMarker.js";
21
+ import { EXEC_VENDOR_NAMES, vendorCommand } from "./execVendors.js";
22
+ import { readKeysChoices } from "./keysKept.js";
23
+ import { outputTail, signInFailureOf } from "./signInFailure.js";
24
+ import { outcomeOfInput } from "./cliHookOutcome.js";
25
+ import { RETRY_ASK_AT } from "./cliHookStuck.js";
26
+ /** The agent hears about a retry loop from this many failures in a row. */
27
+ export const RETRY_TELL_AT = 3;
28
+ /** What Claude Code reads when the sign-in expired. */
29
+ export function signInContext(vendor, held, rerouted) {
30
+ const name = EXEC_VENDOR_NAMES[vendor];
31
+ const command = vendorCommand(vendor);
32
+ if (held) {
33
+ return `Passport: the ${name} sign-in on this computer expired. Passport holds your ${name} key, so run it as \`passport exec -- ${command} <command>\`${rerouted ? " or just rerun it" : ""}.`;
34
+ }
35
+ return `Passport: the ${name} sign-in on this computer expired, and Passport doesn't hold a ${name} key for this person. Passport asked them to add one. Don't retry ${command} until they have; tell them what you were about to do.`;
36
+ }
37
+ /** What the agent reads when the same command keeps failing. */
38
+ export function retryContext(streak, program, asksNext) {
39
+ const what = program ? `this ${program} command` : "this command";
40
+ return `Passport: ${what} failed ${streak} times in a row. Stop retrying and read the error, or ask for help.${asksNext ? " Passport will ask before it runs again." : ""}`;
41
+ }
42
+ /** Whether Passport holds a key for this vendor (this computer's list, or the
43
+ * rules Passport sent), and whether the guard sends the CLI through it. */
44
+ function heldKey(profile, policy, vendor) {
45
+ if (!profile)
46
+ return { held: false, rerouted: false };
47
+ const marked = readExecVendors(profile).has(vendor);
48
+ const told = policy?.version === 2 && (policy.autopilot.heldKeys ?? []).includes(vendor);
49
+ return { held: marked || told, rerouted: marked && !readKeysChoices(profile).kept[vendor] };
50
+ }
51
+ function learn(context, state) {
52
+ const { exitCode } = outcomeOfInput(context.input);
53
+ const failed = exitCode !== undefined && exitCode !== 0;
54
+ const signIn = failed && !context.exec ? signInFailureOf(context.findings, outputTail(context.input), exitCode) : null;
55
+ const resources = failed ? { creates: [], removes: [] } : resourcesOf(context.findings);
56
+ const retry = nextRetry(state, context.command, exitCode, context.now);
57
+ const program = retry.state.retry?.program;
58
+ return { learned: { signIn, resources, streak: retry.streak, ...(program ? { program } : {}) }, state: retry.state };
59
+ }
60
+ /** The report's new facts, only for a server that keeps them. */
61
+ function withFacts(context, learned) {
62
+ if (context.policy?.version !== 2 || !context.policy.autopilot.reportsAfterFacts)
63
+ return context.report;
64
+ const { creates, removes } = learned.resources;
65
+ const facts = {
66
+ ...(learned.signIn ? { signIn: { vendor: learned.signIn } } : {}),
67
+ ...(creates.length ? { creates } : {}),
68
+ ...(removes.length ? { removes } : {}),
69
+ ...(learned.streak >= RETRY_TELL_AT
70
+ ? { retry: { streak: learned.streak, ...(learned.program ? { program: learned.program } : {}) } }
71
+ : {})
72
+ };
73
+ if (!Object.keys(facts).length)
74
+ return context.report;
75
+ return { ...(context.report ?? { ...context.base(), findings: [], opaque: false }), ...facts };
76
+ }
77
+ /**
78
+ * After a command: the report with what the hook learned, and what Claude
79
+ * Code should read (or null). Codex and Cursor are told by the guard on the
80
+ * next try, from this session's state.
81
+ */
82
+ export function afterCommand(context) {
83
+ const sessionId = context.report?.sessionId ?? context.base().sessionId;
84
+ const before = readSessionState(context.runtimeName, sessionId, context.now);
85
+ const { learned, state } = learn(context, before);
86
+ const key = learned.signIn
87
+ ? heldKey(context.profile, context.policy, learned.signIn)
88
+ : { held: false, rerouted: false };
89
+ const claude = context.runtimeName === "claude-code" && !context.cursorImported;
90
+ const next = learned.signIn && !claude
91
+ ? { ...state, signIn: { vendor: learned.signIn, held: key.held, at: context.now } }
92
+ : state;
93
+ if (JSON.stringify(next) !== JSON.stringify(before))
94
+ writeSessionState(context.runtimeName, sessionId, next);
95
+ const report = withFacts(context, learned);
96
+ if (!claude)
97
+ return { report, output: null };
98
+ const asksNext = context.policy?.version === 2 && context.policy.autopilot.retryLoops === true;
99
+ const lines = [
100
+ ...(learned.signIn ? [signInContext(learned.signIn, key.held, key.rerouted && claude)] : []),
101
+ ...(learned.streak >= RETRY_TELL_AT
102
+ ? [retryContext(learned.streak, learned.program, asksNext && learned.streak >= RETRY_ASK_AT)]
103
+ : [])
104
+ ];
105
+ const event = typeof context.input.hook_event_name === "string" ? context.input.hook_event_name : "PostToolUse";
106
+ return {
107
+ report,
108
+ output: lines.length ? { hookSpecificOutput: { hookEventName: event, additionalContext: lines.join("\n") } } : null
109
+ };
110
+ }
111
+ /**
112
+ * `passport exec` records its own action, so the after-hook sends no row for
113
+ * it; what the command inside it created, removed, or kept failing at is
114
+ * still worth knowing. Queued like any report, never sent inline.
115
+ */
116
+ export async function afterExec(context) {
117
+ const inner = execInner(context.command);
118
+ if (!inner)
119
+ return;
120
+ const machine = localMachine(workingFolder(context.input), context.runtime.env);
121
+ const findings = classifyLine(inner, machine).findings;
122
+ const { report, output } = afterCommand({ ...context, command: inner, findings, report: null, exec: true });
123
+ if (output)
124
+ context.runtime.stdout.write(`${JSON.stringify(output)}\n`);
125
+ if (!report)
126
+ return;
127
+ const deliver = await import("./cliHookDeliver.js");
128
+ if (!context.deps.send && !context.deps.fetch) {
129
+ await deliver.queueAfterCommand(report, context.args, context.runtime, context.runtimeName, context.now);
130
+ return;
131
+ }
132
+ const send = await deliver.reportSender(context.args, context.runtime, deliver.budgetSignal(context.runtime, context.deps), context.deps);
133
+ await send?.(report).catch(() => undefined);
134
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The guard's check before a command a task allowance let run: the rules on
3
+ * this computer may be up to an hour old, so the guard asks Passport which
4
+ * allowances the session still holds (`liveAllowanceIds`, 300 ms at most).
5
+ * One a person revoked, or one whose task went quiet, no longer counts: the
6
+ * line is decided again by the rules alone, so it asks as it would have.
7
+ * When Passport doesn't answer in time, the synced allowance stands.
8
+ */
9
+ import { type GuardDecision } from "./cliHookGuard.js";
10
+ import { type SessionRef } from "./cliHookSessionEnd.js";
11
+ type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
12
+ /** The allowances a line's allow leans on, by id. */
13
+ export declare function allowancesUsed(decision: GuardDecision | null): string[];
14
+ /** The same line decided without the allowances that are gone. */
15
+ export declare function withoutAllowances(decision: GuardDecision, gone: ReadonlySet<string>): GuardDecision | null;
16
+ export declare function checkAllowances(decision: GuardDecision | null, context: {
17
+ report: SessionRef;
18
+ openApi: () => Promise<ApiCall | null>;
19
+ budget: AbortSignal;
20
+ now: () => number;
21
+ }): Promise<GuardDecision | null>;
22
+ export {};
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The guard's check before a command a task allowance let run: the rules on
3
+ * this computer may be up to an hour old, so the guard asks Passport which
4
+ * allowances the session still holds (`liveAllowanceIds`, 300 ms at most).
5
+ * One a person revoked, or one whose task went quiet, no longer counts: the
6
+ * line is decided again by the rules alone, so it asks as it would have.
7
+ * When Passport doesn't answer in time, the synced allowance stands.
8
+ */
9
+ import { aggregate } from "./cliHookGuard.js";
10
+ import { liveAllowanceIds } from "./cliHookSessionEnd.js";
11
+ /** The allowances a line's allow leans on, by id. */
12
+ export function allowancesUsed(decision) {
13
+ if (decision?.verdict !== "allow")
14
+ return [];
15
+ return (decision.decided ?? []).flatMap((entry) => entry.cause.kind === "grant" && entry.cause.id ? [entry.cause.id] : []);
16
+ }
17
+ /** The same line decided without the allowances that are gone. */
18
+ export function withoutAllowances(decision, gone) {
19
+ const decided = decision.decided ?? [];
20
+ const plain = decided.map(({ without, ...entry }) => without && entry.cause.id && gone.has(entry.cause.id)
21
+ ? { ...entry, ...without }
22
+ : { ...entry, ...(without ? { without } : {}) });
23
+ return aggregate(plain, plain.length, true);
24
+ }
25
+ export async function checkAllowances(decision, context) {
26
+ const used = allowancesUsed(decision);
27
+ if (!decision || !used.length)
28
+ return decision;
29
+ const live = await liveAllowanceIds(context.report, context.openApi, context);
30
+ if (live === null)
31
+ return decision;
32
+ const gone = new Set(used.filter((id) => !live.includes(id)));
33
+ return gone.size ? withoutAllowances(decision, gone) : decision;
34
+ }
@@ -46,6 +46,10 @@ export type CliFinding = {
46
46
  /** Read from the project's own script (`cliScriptRead.ts`): its name as a
47
47
  * person knows it, "deploy.sh" or "make deploy". Reported as provenance. */
48
48
  from?: string;
49
+ /** An unchecked part as a person names it: `make release`, `npm run
50
+ * migrate`, `scripts/deploy.sh`. Local; reported only as the safe name
51
+ * `cliHookUncheckedName.ts` makes of it. */
52
+ subject?: string;
49
53
  /** A known project script (item 5): the server's project action that
50
54
  * classifies it. It sets class and environment only; it never allows. */
51
55
  project?: {