passport-bridge 0.22.0 → 0.24.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 (82) hide show
  1. package/README.md +61 -56
  2. package/dist/cliArgs.js +7 -1
  3. package/dist/cliAutopilotPolicy.d.ts +9 -0
  4. package/dist/cliExec.js +5 -1
  5. package/dist/cliGuardHealth.js +1 -1
  6. package/dist/cliGuardState.js +2 -2
  7. package/dist/cliHook.js +28 -13
  8. package/dist/cliHookClassify.d.ts +4 -0
  9. package/dist/cliHookClients.d.ts +23 -0
  10. package/dist/cliHookClients.js +52 -0
  11. package/dist/cliHookDecide.d.ts +5 -1
  12. package/dist/cliHookDecide.js +5 -1
  13. package/dist/cliHookDeliver.d.ts +24 -8
  14. package/dist/cliHookDeliver.js +59 -2
  15. package/dist/cliHookExtras.d.ts +8 -3
  16. package/dist/cliHookExtras.js +16 -3
  17. package/dist/cliHookGuard.d.ts +5 -0
  18. package/dist/cliHookGuard.js +12 -6
  19. package/dist/cliHookInput.d.ts +5 -0
  20. package/dist/cliHookInstall.d.ts +6 -6
  21. package/dist/cliHookInstall.js +16 -40
  22. package/dist/cliHookLifecycle.d.ts +22 -0
  23. package/dist/cliHookLifecycle.js +101 -0
  24. package/dist/cliHookLocal.d.ts +3 -0
  25. package/dist/cliHookLocal.js +20 -2
  26. package/dist/cliHookLocalCode.d.ts +2 -0
  27. package/dist/cliHookLocalCode.js +1 -1
  28. package/dist/cliHookRepo.d.ts +20 -0
  29. package/dist/cliHookRepo.js +36 -0
  30. package/dist/cliHookRewrite.d.ts +15 -1
  31. package/dist/cliHookRewrite.js +50 -1
  32. package/dist/cliHookScripts.d.ts +1 -0
  33. package/dist/cliHookScripts.js +14 -6
  34. package/dist/cliHookStep.d.ts +19 -0
  35. package/dist/cliHookStep.js +76 -0
  36. package/dist/cliKeys.d.ts +6 -58
  37. package/dist/cliKeys.js +72 -41
  38. package/dist/cliKeysBack.d.ts +31 -15
  39. package/dist/cliKeysBack.js +70 -47
  40. package/dist/cliKeysKeep.d.ts +34 -0
  41. package/dist/cliKeysKeep.js +110 -0
  42. package/dist/cliKeysSignOut.d.ts +33 -0
  43. package/dist/cliKeysSignOut.js +72 -0
  44. package/dist/cliKeysTypes.d.ts +74 -0
  45. package/dist/cliKeysTypes.js +1 -0
  46. package/dist/cliOutput.js +10 -4
  47. package/dist/cliPolicyV2.js +29 -2
  48. package/dist/cliScriptRead.d.ts +8 -1
  49. package/dist/cliScriptRead.js +22 -11
  50. package/dist/cliSeen.d.ts +77 -15
  51. package/dist/cliSeen.js +171 -34
  52. package/dist/cliSessions.d.ts +23 -45
  53. package/dist/cliSessions.js +135 -147
  54. package/dist/cliSessionsJson.d.ts +192 -0
  55. package/dist/cliSessionsJson.js +353 -0
  56. package/dist/cliSessionsRender.d.ts +35 -0
  57. package/dist/cliSessionsRender.js +350 -0
  58. package/dist/cliStatus.js +5 -1
  59. package/dist/cliStatusGuard.d.ts +5 -1
  60. package/dist/cliStatusGuard.js +4 -0
  61. package/dist/cliUsage.d.ts +71 -0
  62. package/dist/cliUsage.js +333 -0
  63. package/dist/completion.js +2 -2
  64. package/dist/execVendors.d.ts +27 -2
  65. package/dist/execVendors.js +74 -23
  66. package/dist/hookFastPath.js +3 -2
  67. package/dist/initKeysStep.js +1 -0
  68. package/dist/keysKept.d.ts +17 -0
  69. package/dist/keysKept.js +92 -0
  70. package/dist/keysLocal.d.ts +2 -0
  71. package/dist/keysLocal.js +6 -0
  72. package/dist/keysReport.d.ts +32 -0
  73. package/dist/keysReport.js +72 -0
  74. package/dist/localReach.d.ts +30 -0
  75. package/dist/localReach.js +94 -0
  76. package/dist/pluginPin.d.ts +1 -1
  77. package/dist/pluginPin.js +1 -1
  78. package/dist/scanStores.js +50 -2
  79. package/dist/version.d.ts +1 -1
  80. package/dist/version.js +1 -1
  81. package/npm-shrinkwrap.json +55 -161
  82. package/package.json +1 -1
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { type ParsedArgs } from "./cliArgs.js";
8
8
  import { readCliPolicy } from "./cliPolicy.js";
9
+ import type { LegacySeen, SeenBatch } from "./cliSeen.js";
9
10
  import { type Env, type Runtime } from "./cliSupport.js";
10
11
  /** Claude Code, Codex, and Cursor fail open on a slow hook, so the budget is ours. */
11
12
  export declare const HOOK_BUDGET_MS = 1500;
@@ -46,6 +47,14 @@ export type CliHookReport = {
46
47
  batch: string;
47
48
  clients: unknown[];
48
49
  };
50
+ /** Token numbers per agent session (`cliUsage.ts`). Numbers and model ids only. */
51
+ usage?: {
52
+ batch: string;
53
+ sessions: Array<{
54
+ id: string;
55
+ models: unknown[];
56
+ }>;
57
+ };
49
58
  /** Project scripts in this command (item 6): how many parts were fully and
50
59
  * partly checked. Counts only. */
51
60
  scripts?: {
@@ -58,14 +67,18 @@ export type CliHookReport = {
58
67
  projectChanged?: string[];
59
68
  /** A script changed between the guard's check and the run. */
60
69
  drift?: true;
61
- /** Coverage: what the guard saw for this agent on one day (`cliSeen.ts`). Counts only. */
62
- seen?: {
63
- batch: string;
64
- day: string;
65
- count: number;
66
- governed: number;
67
- opaque: number;
68
- };
70
+ /** Coverage: what the guard saw for this agent on one day (`cliSeen.ts`),
71
+ * split by agent session when known. Counts, and blind programs' names. */
72
+ seen?: SeenBatch | LegacySeen;
73
+ /** The agent session ended or started (SessionEnd / SessionStart). */
74
+ sessionEnded?: boolean;
75
+ sessionStarted?: true;
76
+ /** With a start marker: the model's name and whether a person is there. */
77
+ model?: string;
78
+ attended?: boolean;
79
+ /** Claude Code's one-line description of this step, redacted on this
80
+ * computer (`cliHookStep.ts`); only when the workspace turned it on. */
81
+ description?: string;
69
82
  };
70
83
  /** One governed command as reported: never its arguments. v2 adds the
71
84
  * environment: a short name the flags gave, or a kind. */
@@ -118,6 +131,9 @@ export type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
118
131
  export declare function profileApi(profile: string, signal: AbortSignal, fetcher: typeof fetch): Promise<ApiCall | null>;
119
132
  /** The report an older server accepts: no Autopilot fields, ask or deny only. */
120
133
  export declare function legacyReport(report: CliHookReport): CliHookReport | null;
134
+ /** The report a server from before session markers (bridge 0.23.0) accepts,
135
+ * or null: a start marker alone has nothing it knows. */
136
+ export declare function withoutSessionFacts(report: CliHookReport): CliHookReport | null;
121
137
  /** The report a server from before project grouping accepts (bridge 0.21.0). */
122
138
  export declare function withoutProject(report: CliHookReport): CliHookReport;
123
139
  type Send = (report: CliHookReport) => Promise<void>;
@@ -54,6 +54,15 @@ export function legacyReport(report) {
54
54
  return null;
55
55
  return { ...rest, findings: report.findings.map(({ vendor, verb, risk }) => ({ vendor, verb, risk })) };
56
56
  }
57
+ function hasSessionFacts(report) {
58
+ return report.sessionStarted !== undefined || report.model !== undefined || report.attended !== undefined;
59
+ }
60
+ /** The report a server from before session markers (bridge 0.23.0) accepts,
61
+ * or null: a start marker alone has nothing it knows. */
62
+ export function withoutSessionFacts(report) {
63
+ const { sessionStarted: _started, model: _model, attended: _attended, ...rest } = report;
64
+ return rest.sessionEnded || rest.findings.length || rest.opaque ? rest : null;
65
+ }
57
66
  /** The report a server from before project grouping accepts (bridge 0.21.0). */
58
67
  export function withoutProject(report) {
59
68
  const { project: _project, branch: _branch, ...rest } = report;
@@ -70,15 +79,32 @@ function hasAutopilotFields(report) {
70
79
  finding.from !== undefined ||
71
80
  finding.projectAction !== undefined));
72
81
  }
73
- async function postWith(api, report, signal) {
82
+ async function postWith(api, initial, signal) {
74
83
  const post = (body) => api(CLI_ACTIVITY_PATH, {
75
84
  method: "POST",
76
85
  headers: { "content-type": "application/json", "x-passport-surface": "cli" },
77
86
  body: JSON.stringify(body),
78
87
  signal
79
88
  });
89
+ let report = initial;
80
90
  let response = await post(report);
81
91
  await response.body?.cancel().catch(() => undefined);
92
+ // A server from before step descriptions (bridge 0.24.0) refuses the field.
93
+ if (response.status === 400 && report.description !== undefined) {
94
+ const { description: _description, ...rest } = report;
95
+ report = rest;
96
+ response = await post(report);
97
+ await response.body?.cancel().catch(() => undefined);
98
+ }
99
+ // A server from before session markers (bridge 0.23.0) refuses their facts.
100
+ if (response.status === 400 && hasSessionFacts(report)) {
101
+ const older = withoutSessionFacts(report);
102
+ if (!older)
103
+ return;
104
+ report = older;
105
+ response = await post(report);
106
+ await response.body?.cancel().catch(() => undefined);
107
+ }
82
108
  // A server from before project grouping refuses those two fields: send the rest.
83
109
  if (response.status === 400 && (report.project !== undefined || report.branch !== undefined)) {
84
110
  response = await post(withoutProject(report));
@@ -286,7 +312,11 @@ export async function leftovers(queued, context) {
286
312
  const extras = await import("./cliHookExtras.js");
287
313
  const seen = extras.claimSeen(profile, now);
288
314
  const heartbeat = extras.heartbeatDue(profile, now);
289
- if (!reports.length && !refresh && !answered && !speedBatch && !seen && !heartbeat)
315
+ // Token numbers, read here from transcripts the hooks noted: never on a hook's path.
316
+ const usage = await import("./cliUsage.js");
317
+ const keepsUsage = context.policy?.version === 2 && context.policy.autopilot.reportsUsage === true;
318
+ const usageBatch = keepsUsage && !usage.usageOptedOut(context.runtime.env) ? usage.claimUsageBatch(profile, due, now) : null;
319
+ if (!reports.length && !refresh && !answered && !speedBatch && !seen && !heartbeat && !usageBatch)
290
320
  return;
291
321
  const api = context.api ?? (await profileApi(profile, budget, deps.fetch ?? fetch));
292
322
  if (!api)
@@ -329,13 +359,40 @@ export async function leftovers(queued, context) {
329
359
  signal: budget
330
360
  });
331
361
  await response.body?.cancel().catch(() => undefined);
362
+ // A server from before the buckets: the old counts. Before per-session
363
+ // counts: the totals alone.
364
+ if (response.status === 400 && batch.seen && "decided" in batch.seen) {
365
+ return postSeen({ seen: extras.legacySeen(batch.seen) }, runtimeName);
366
+ }
367
+ if (response.status === 400 && batch.seen?.sessions) {
368
+ const { sessions: _sessions, ...totals } = batch.seen;
369
+ return postSeen({ seen: totals }, runtimeName);
370
+ }
332
371
  return response.ok;
333
372
  };
373
+ const postUsage = async (batch) => {
374
+ const entry = { runtime: "claude-code", findings: [], opaque: false, usage: usage.wireBatch(batch) };
375
+ if (deps.send) {
376
+ await send(entry);
377
+ return usage.settleUsageBatch(profile, batch.batch);
378
+ }
379
+ const response = await api(CLI_ACTIVITY_PATH, {
380
+ method: "POST",
381
+ headers: { "content-type": "application/json", "x-passport-surface": "cli" },
382
+ body: JSON.stringify(entry),
383
+ signal: budget
384
+ });
385
+ await response.body?.cancel().catch(() => undefined);
386
+ // A server that can't keep token numbers (400) won't keep this batch later either.
387
+ if (response.ok || response.status === 400)
388
+ usage.settleUsageBatch(profile, batch.batch);
389
+ };
334
390
  const { refreshRules } = await import("./cliPolicyRefresh.js");
335
391
  await Promise.allSettled([
336
392
  ...reports.map((entry) => send(entry)),
337
393
  postAll(),
338
394
  seen ? extras.sendSeen(seen, postSeen, profile, now) : null,
395
+ usageBatch ? postUsage(usageBatch) : null,
339
396
  heartbeat ? extras.heartbeat(api, profile, context.runtime.env, budget, now) : null,
340
397
  refresh ? refreshRules(profile, budget, { api, ...(deps.now ? { now: deps.now } : {}) }) : null
341
398
  ]);
@@ -4,18 +4,23 @@
4
4
  * report (only when 300 ms or more of the budget is left, so it never slows
5
5
  * an agent down).
6
6
  */
7
- import type { CliFinding } from "./cliHookClassify.js";
8
- import { type SeenBatch } from "./cliSeen.js";
7
+ import { type LegacySeen, type SeenBatch, type SeenLine } from "./cliSeen.js";
9
8
  import type { Env } from "./cliSupport.js";
10
9
  export declare const HEARTBEAT_MIN_LEFT_MS = 300;
11
10
  type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
12
11
  type Claimed = SeenBatch & {
13
12
  runtime: string;
13
+ sessionBytes?: number;
14
+ programBytes?: number;
14
15
  };
15
16
  /** Count what the guard saw, once even when Cursor runs its imported copy of
16
17
  * Claude Code's hook next to its own. Never throws. */
17
- export declare function countSeen(profile: string | undefined, runtime: string, findings: CliFinding[], now: number, duplicate: () => Promise<boolean>): Promise<void>;
18
+ export declare function countSeen(profile: string | undefined, runtime: string, line: SeenLine, now: number, duplicate: () => Promise<boolean>,
19
+ /** The agent's own session id: the batch then splits its counts by session. */
20
+ sessionId?: string): Promise<void>;
18
21
  export declare function claimSeen(profile: string, now: number): Claimed | null;
22
+ /** A batch as servers from before the buckets take it: `opaque` already is the blind count. */
23
+ export declare function legacySeen(seen: SeenBatch): LegacySeen;
19
24
  /** A guard run's first report waits a day; later ones go when due. */
20
25
  export declare function heartbeatDue(profile: string, now: number): boolean;
21
26
  /** Send one coverage batch under its agent; it counts as sent once Passport took it. */
@@ -10,21 +10,34 @@ export const HEARTBEAT_MIN_LEFT_MS = 300;
10
10
  const HOOK_RUNTIMES = new Set(["claude-code", "codex", "copilot", "cursor", "other"]);
11
11
  /** Count what the guard saw, once even when Cursor runs its imported copy of
12
12
  * Claude Code's hook next to its own. Never throws. */
13
- export async function countSeen(profile, runtime, findings, now, duplicate) {
13
+ export async function countSeen(profile, runtime, line, now, duplicate,
14
+ /** The agent's own session id: the batch then splits its counts by session. */
15
+ sessionId) {
14
16
  if (!profile || (await duplicate().catch(() => false)))
15
17
  return;
16
- noteSeen(profile, runtime, seenMark(findings), now);
18
+ noteSeen(profile, runtime, seenMark(line), now, sessionId);
17
19
  }
18
20
  export function claimSeen(profile, now) {
19
21
  return claimSeenBatch(profile, now);
20
22
  }
23
+ /** A batch as servers from before the buckets take it: `opaque` already is the blind count. */
24
+ export function legacySeen(seen) {
25
+ const { decided: _d, placed: _p, blind: _b, blindPrograms: _programs, sessions, ...totals } = seen;
26
+ return {
27
+ ...totals,
28
+ ...(sessions?.length
29
+ ? { sessions: sessions.map(({ id, count, governed, opaque }) => ({ id, count, governed, opaque })) }
30
+ : {})
31
+ };
32
+ }
21
33
  /** A guard run's first report waits a day; later ones go when due. */
22
34
  export function heartbeatDue(profile, now) {
23
35
  return guardHeartbeatDue(profile, now, true);
24
36
  }
25
37
  /** Send one coverage batch under its agent; it counts as sent once Passport took it. */
26
38
  export async function sendSeen(claimed, post, profile, now) {
27
- const { runtime, ...seen } = claimed;
39
+ // Where the session log was read up to stays on this computer.
40
+ const { runtime, sessionBytes: _read, programBytes: _programs, ...seen } = claimed;
28
41
  const ok = await post({ seen }, HOOK_RUNTIMES.has(runtime) ? runtime : "other");
29
42
  if (ok)
30
43
  settleSeenBatch(profile, claimed.batch, now);
@@ -64,6 +64,8 @@ export type GuardDecision = {
64
64
  };
65
65
  /** This machine, for reading folder links. Absent: flags and defaults only. */
66
66
  export type GuardMachine = {
67
+ /** The repository's name (what reports carry as `project`), when known. */
68
+ repo?: string;
67
69
  cwd: string | null;
68
70
  rawCwd?: string | null;
69
71
  projectRoot: string | null;
@@ -98,6 +100,9 @@ export declare function decideFinding(finding: CliFinding, policy: CachedCliPoli
98
100
  * variables, wrappers, heredocs, or environment prefixes.
99
101
  */
100
102
  export declare function fullyRecognized(command: string, findings: CliFinding[]): boolean;
103
+ /** Each recognized command's own decision, even when the line as a whole
104
+ * gets none: the audit row still says where each one landed. */
105
+ export declare function decideEach(findings: CliFinding[], policy: CachedCliPolicyV2, machine?: GuardMachine): DecidedFinding[];
101
106
  /** The strictest verdict across every command in the line wins. */
102
107
  export declare function decideGuard(findings: CliFinding[], policy: CachedCliPolicy | null, command?: string, complete?: boolean, machine?: GuardMachine): GuardDecision | null;
103
108
  export declare function askMessage(decision: GuardDecision): string;
@@ -16,6 +16,7 @@
16
16
  import { CLASS_EFFECT, CLASS_EFFECT_OTHER, CLASS_OF_RISK as CLASS_OF_HOOK_RISK, causeSentence, decideAction, decisionRank, envLabel } from "./cliAutopilotPolicy.js";
17
17
  import { reportedEnvironment } from "./cliHookEnvironment.js";
18
18
  import { placementOf, resolveTarget, targetNote } from "./envResolve.js";
19
+ import { repositoryHint } from "./cliHookRepo.js";
19
20
  import { NODE_LINK_FS } from "./envLinkFs.js";
20
21
  import { normalizeArgv, splitCommands } from "./cliHookParse.js";
21
22
  import { VENDORS, vendorKeys } from "./cliHookVendors.js";
@@ -211,9 +212,11 @@ export function decideFinding(finding, policy, machine) {
211
212
  // SQL is read from a regex; only a destructive statement gets an opinion.
212
213
  if (finding.vendor === "psql" ? finding.risk !== "destructive" : !CLASS_OF_RISK[finding.risk])
213
214
  return null;
215
+ // git and gh: where the repository action lands (a newer server), else
214
216
  // `git push`: the branch decides (default branch = Production).
215
217
  const where = whereFor(finding, machine);
216
- const target = finding.pushEnvironment
218
+ const repo = repositoryHint(finding, policy, machine?.repo);
219
+ const target = finding.pushEnvironment || repo
217
220
  ? undefined
218
221
  : resolveTarget(finding.vendor, finding.args ?? [], {
219
222
  flags: policy.autopilot.environmentFlags,
@@ -221,9 +224,7 @@ export function decideFinding(finding, policy, machine) {
221
224
  ...(policy.autopilot.resources ? { resources: policy.autopilot.resources } : {}),
222
225
  ...(where ? { where } : {})
223
226
  });
224
- const hint = finding.pushEnvironment
225
- ? { kind: finding.pushEnvironment, source: "flag" }
226
- : target;
227
+ const hint = repo?.hint ?? (finding.pushEnvironment ? { kind: finding.pushEnvironment, source: "flag" } : target);
227
228
  const verb = finding.verbKey ?? finding.verb;
228
229
  const actionClass = classOf(policy, finding, verb, hint.kind);
229
230
  // The access ceiling comes first inside the engine: No access blocks every
@@ -234,7 +235,7 @@ export function decideFinding(finding, policy, machine) {
234
235
  actionClass,
235
236
  environment: hint.kind
236
237
  });
237
- const reported = finding.pushEnvironment ?? reportedEnvironment(hint);
238
+ const reported = repo ? repo.reported : (finding.pushEnvironment ?? reportedEnvironment(hint));
238
239
  return {
239
240
  finding,
240
241
  decision,
@@ -277,7 +278,7 @@ function verdictOf(decision) {
277
278
  return decision === "block" ? "deny" : decision;
278
279
  }
279
280
  function decideV2(command, findings, policy, complete, machine) {
280
- const decided = findings.map((finding) => decideFinding(finding, policy, machine)).filter((entry) => entry !== null);
281
+ const decided = decideEach(findings, policy, machine);
281
282
  if (!decided.length)
282
283
  return null;
283
284
  const strictest = decided
@@ -310,6 +311,11 @@ function decideV2(command, findings, policy, complete, machine) {
310
311
  ...(strictest.access ? { access: strictest.access } : {})
311
312
  };
312
313
  }
314
+ /** Each recognized command's own decision, even when the line as a whole
315
+ * gets none: the audit row still says where each one landed. */
316
+ export function decideEach(findings, policy, machine) {
317
+ return findings.map((finding) => decideFinding(finding, policy, machine)).filter((entry) => entry !== null);
318
+ }
313
319
  /** The strictest verdict across every command in the line wins. */
314
320
  export function decideGuard(findings, policy, command = "", complete, machine) {
315
321
  if (policy?.version === 2)
@@ -23,5 +23,10 @@ export type HookInput = {
23
23
  cursor_version?: unknown;
24
24
  duration?: unknown;
25
25
  workspace_roots?: unknown;
26
+ /** SessionStart: the model's name (a string, or `{ id }`). */
27
+ model?: unknown;
28
+ /** Claude Code: the session's transcript file, read later only for token
29
+ * numbers (`cliUsage.ts`), never by the hook itself. */
30
+ transcript_path?: unknown;
26
31
  };
27
32
  export declare function readInput(runtime: Runtime, signal: AbortSignal): Promise<HookInput | null>;
@@ -11,14 +11,15 @@
11
11
  * | Claude Code | ~/.claude/settings.json | PreToolUse (Bash) | PostToolUse (Bash) |
12
12
  * | Codex | ~/.codex/hooks.json | PreToolUse (Bash) | PostToolUse (Bash) |
13
13
  * | Cursor | ~/.cursor/hooks.json | beforeShellExecution | afterShellExecution |
14
+ *
15
+ * The audit entry also runs when a session starts and ends (Claude Code
16
+ * SessionStart and SessionEnd, Codex SessionStart), so a session's start and
17
+ * end are true. Cursor has no documented session events.
14
18
  */
15
19
  import { type ParsedArgs } from "./cliArgs.js";
16
20
  import { type CommandResult, type Env, type Runtime } from "./cliSupport.js";
17
- export declare const HOOK_CLIENTS: readonly ["claude-code", "codex", "cursor"];
18
- export type HookClient = (typeof HOOK_CLIENTS)[number];
19
- export declare function claudeSettingsPath(env: Env): string;
20
- export declare function codexHooksPath(env: Env): string;
21
- export declare function cursorHooksPath(env: Env): string;
21
+ import { type HookClient } from "./cliHookClients.js";
22
+ export { HOOK_CLIENTS, claudeSettingsPath, codexHooksPath, cursorHooksPath, type HookClient } from "./cliHookClients.js";
22
23
  type Settings = Record<string, unknown> & {
23
24
  hooks?: Record<string, unknown>;
24
25
  };
@@ -97,4 +98,3 @@ export declare function guardEntryOf(client: HookClient, env: Env): {
97
98
  timeout?: unknown;
98
99
  } | null;
99
100
  export declare function hookRegistration(action: "install" | "uninstall" | "status", client: string | undefined, args: ParsedArgs, runtime: Runtime): CommandResult;
100
- export {};
@@ -11,6 +11,10 @@
11
11
  * | Claude Code | ~/.claude/settings.json | PreToolUse (Bash) | PostToolUse (Bash) |
12
12
  * | Codex | ~/.codex/hooks.json | PreToolUse (Bash) | PostToolUse (Bash) |
13
13
  * | Cursor | ~/.cursor/hooks.json | beforeShellExecution | afterShellExecution |
14
+ *
15
+ * The audit entry also runs when a session starts and ends (Claude Code
16
+ * SessionStart and SessionEnd, Codex SessionStart), so a session's start and
17
+ * end are true. Cursor has no documented session events.
14
18
  */
15
19
  import { randomBytes } from "node:crypto";
16
20
  import { accessSync, closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
@@ -24,45 +28,10 @@ import { credentialDir } from "./credentialStorage.js";
24
28
  import { launcherPath } from "./initInstall.js";
25
29
  import { failure } from "./cliSupport.js";
26
30
  import { countOf } from "./plural.js";
27
- export const HOOK_CLIENTS = ["claude-code", "codex", "cursor"];
31
+ import { CLIENTS, HOOK_CLIENTS } from "./cliHookClients.js";
32
+ export { HOOK_CLIENTS, claudeSettingsPath, codexHooksPath, cursorHooksPath } from "./cliHookClients.js";
28
33
  const SETTINGS_MAX_BYTES = 1024 * 1024;
29
34
  const HOOK_TIMEOUT_SECONDS = 5;
30
- export function claudeSettingsPath(env) {
31
- const configured = env.CLAUDE_CONFIG_DIR?.trim();
32
- return join(configured || join(homedir(), ".claude"), "settings.json");
33
- }
34
- export function codexHooksPath(env) {
35
- const configured = env.CODEX_HOME?.trim();
36
- return join(configured || join(homedir(), ".codex"), "hooks.json");
37
- }
38
- export function cursorHooksPath(env) {
39
- // Cursor has no documented override for its home; tests and sandboxes use
40
- // PASSPORT_CURSOR_HOME so a run never touches the real ~/.cursor.
41
- const configured = env.PASSPORT_CURSOR_HOME?.trim();
42
- return join(configured || join(homedir(), ".cursor"), "hooks.json");
43
- }
44
- const CLIENTS = {
45
- "claude-code": {
46
- id: "claude-code",
47
- name: "Claude Code",
48
- format: "groups",
49
- pre: "PreToolUse",
50
- post: "PostToolUse",
51
- // Claude Code reports an interrupted or failed tool call here instead of
52
- // PostToolUse, so an approved command that failed still counts as ran.
53
- postFailure: "PostToolUseFailure",
54
- path: claudeSettingsPath
55
- },
56
- codex: { id: "codex", name: "Codex", format: "groups", pre: "PreToolUse", post: "PostToolUse", path: codexHooksPath },
57
- cursor: {
58
- id: "cursor",
59
- name: "Cursor",
60
- format: "cursor",
61
- pre: "beforeShellExecution",
62
- post: "afterShellExecution",
63
- path: cursorHooksPath
64
- }
65
- };
66
35
  const PASSPORT_COMMAND = /passport[^\s"']*["']?\s+hook(\s+guard)?(?:\s+--client(?:\s+|=)[a-z-]{1,24})?(?:\s+--hold(?:\s+|=)\d{1,2})?\s*$/i;
67
36
  const VERB_TAIL = /^\s+hook(\s+guard)?(?:\s+--client(?:\s+|=)[a-z-]{1,24})?(?:\s+--hold(?:\s+|=)\d{1,2})?\s*$/i;
68
37
  /** "audit", "guard", or null. Recognises `passport hook`, an absolute path to
@@ -245,7 +214,11 @@ function commandsIn(spec, settings, event) {
245
214
  function slotsOf(spec, kind) {
246
215
  if (kind === "guard")
247
216
  return [{ kind, event: spec.pre }];
248
- return [{ kind, event: spec.post }, ...(spec.postFailure ? [{ kind, event: spec.postFailure }] : [])];
217
+ return [
218
+ { kind, event: spec.post },
219
+ ...(spec.postFailure ? [{ kind, event: spec.postFailure }] : []),
220
+ ...(spec.lifecycle ?? []).map((event) => ({ kind, event }))
221
+ ];
249
222
  }
250
223
  function registeredAt(spec, settings, slot) {
251
224
  const found = commandsIn(spec, settings, slot.event).find(isOurs(slot.kind));
@@ -284,9 +257,12 @@ function withEntry(spec, settings, slot, command) {
284
257
  const groups = list;
285
258
  // An older Passport entry (another version's path) is replaced where it stands.
286
259
  const owner = groups.findIndex((group) => group && Array.isArray(group.hooks) && group.hooks.some((candidate) => ours(candidate?.command)));
287
- const index = owner !== -1 ? owner : groups.findIndex((group) => group && group.matcher === "Bash");
260
+ // Session events take no matcher; tool events go under Bash.
261
+ const lifecycle = spec.lifecycle?.includes(event) ?? false;
262
+ const fits = (group) => (lifecycle ? group.matcher === undefined : group.matcher === "Bash");
263
+ const index = owner !== -1 ? owner : groups.findIndex((group) => group && fits(group));
288
264
  if (index === -1)
289
- groups.push({ matcher: "Bash", hooks: [entry] });
265
+ groups.push(lifecycle ? { hooks: [entry] } : { matcher: "Bash", hooks: [entry] });
290
266
  else {
291
267
  const existing = Array.isArray(groups[index].hooks) ? groups[index].hooks : [];
292
268
  const at = existing.findIndex((candidate) => ours(candidate?.command));
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Session start and end (Claude Code SessionStart and SessionEnd, Codex
3
+ * SessionStart): the audit entry runs on them too, and sends one marker so a
4
+ * session's start and end are true and "Running" is accurate. Like every
5
+ * report after a command, the marker is queued and a detached flush sends it;
6
+ * the hook never waits on the network.
7
+ *
8
+ * What it carries: the agent's session id, the folder's and repository's
9
+ * names, the model's name when the agent says it, and whether a person is at
10
+ * the keyboard when Passport can tell. Never a prompt, a path, or a transcript.
11
+ * For Claude Code it also notes, on this computer only, where the session's
12
+ * transcript is, so the detached flush can count its tokens (`cliUsage.ts`).
13
+ */
14
+ import { type ParsedArgs } from "./cliArgs.js";
15
+ import type { CliHookReport, HookDependencies, HookRuntime } from "./cliHookDeliver.js";
16
+ import type { HookInput } from "./cliHookInput.js";
17
+ import type { Env, Runtime } from "./cliSupport.js";
18
+ export declare function isLifecycleEvent(input: HookInput): boolean;
19
+ /** The marker for one lifecycle event, or null (no session id, or not one). */
20
+ export declare function lifecycleReport(input: HookInput, runtime: HookRuntime, env: Env): CliHookReport | null;
21
+ /** Handle a lifecycle event: true when it was one (whatever happened next). */
22
+ export declare function lifecycle(input: HookInput, args: ParsedArgs, runtime: Runtime, deps: HookDependencies): Promise<boolean>;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Session start and end (Claude Code SessionStart and SessionEnd, Codex
3
+ * SessionStart): the audit entry runs on them too, and sends one marker so a
4
+ * session's start and end are true and "Running" is accurate. Like every
5
+ * report after a command, the marker is queued and a detached flush sends it;
6
+ * the hook never waits on the network.
7
+ *
8
+ * What it carries: the agent's session id, the folder's and repository's
9
+ * names, the model's name when the agent says it, and whether a person is at
10
+ * the keyboard when Passport can tell. Never a prompt, a path, or a transcript.
11
+ * For Claude Code it also notes, on this computer only, where the session's
12
+ * transcript is, so the detached flush can count its tokens (`cliUsage.ts`).
13
+ */
14
+ import { value } from "./cliArgs.js";
15
+ import { detectMode } from "./cliHookMode.js";
16
+ import { projectOf } from "./cliHookProject.js";
17
+ const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:@/[\]-]{0,79}$/;
18
+ const SESSION_ID = /^[A-Za-z0-9._:-]{1,128}$/;
19
+ export function isLifecycleEvent(input) {
20
+ return input.hook_event_name === "SessionStart" || input.hook_event_name === "SessionEnd";
21
+ }
22
+ /** The model's name from the event: a string, or `{ id }`. */
23
+ function modelOf(input) {
24
+ const raw = input.model;
25
+ const name = typeof raw === "string"
26
+ ? raw
27
+ : raw && typeof raw === "object" && typeof raw.id === "string"
28
+ ? raw.id
29
+ : undefined;
30
+ return name && MODEL.test(name) && !name.includes("..") ? name : undefined;
31
+ }
32
+ function folderName(cwd) {
33
+ if (typeof cwd !== "string")
34
+ return undefined;
35
+ const trimmed = cwd.replace(/[\\/]+$/, "");
36
+ const name = trimmed.slice(Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\")) + 1);
37
+ return name && name.length <= 80 && !/[\u0000-\u001f]/.test(name) ? name : undefined;
38
+ }
39
+ /** The marker for one lifecycle event, or null (no session id, or not one). */
40
+ export function lifecycleReport(input, runtime, env) {
41
+ if (!isLifecycleEvent(input))
42
+ return null;
43
+ const sessionId = typeof input.session_id === "string" ? input.session_id : undefined;
44
+ if (!sessionId || !SESSION_ID.test(sessionId))
45
+ return null;
46
+ const started = input.hook_event_name === "SessionStart";
47
+ const model = modelOf(input);
48
+ const mode = detectMode(input, env);
49
+ const cwdName = folderName(input.cwd);
50
+ const { project, branch } = started ? projectOf(input.cwd) : {};
51
+ return {
52
+ runtime,
53
+ sessionId,
54
+ findings: [],
55
+ opaque: false,
56
+ ...(started ? { sessionStarted: true } : { sessionEnded: true }),
57
+ ...(cwdName ? { cwdName } : {}),
58
+ ...(project ? { project } : {}),
59
+ ...(branch ? { branch } : {}),
60
+ ...(model ? { model } : {}),
61
+ // Only when Passport can actually tell; the default guess is not a fact.
62
+ ...(mode.signal !== "default" ? { attended: mode.mode === "attended" } : {})
63
+ };
64
+ }
65
+ /** Which agent: the installed entry names it (`--client codex`); Claude
66
+ * Code's entry is unqualified. */
67
+ function runtimeOf(args, env) {
68
+ const named = (value(args, "client") ?? env.PASSPORT_HOOK_RUNTIME)?.trim().toLowerCase();
69
+ return named === "codex" || named === "cursor" || named === "copilot" ? named : "claude-code";
70
+ }
71
+ /** Handle a lifecycle event: true when it was one (whatever happened next). */
72
+ export async function lifecycle(input, args, runtime, deps) {
73
+ if (!isLifecycleEvent(input))
74
+ return false;
75
+ const name = runtimeOf(args, runtime.env);
76
+ const report = lifecycleReport(input, name, runtime.env);
77
+ if (!report)
78
+ return true;
79
+ const deliver = await import("./cliHookDeliver.js");
80
+ const now = (deps.now ?? Date.now)();
81
+ await noteUsage(input, runtime.env, name, deliver.profileAuth(args, runtime.env));
82
+ if (!deps.send && !deps.fetch) {
83
+ await deliver.queueAfterCommand(report, args, runtime, name, now);
84
+ return true;
85
+ }
86
+ const send = await deliver.reportSender(args, runtime, deliver.budgetSignal(runtime, deps), deps);
87
+ if (send)
88
+ await send(report).catch(() => undefined);
89
+ return true;
90
+ }
91
+ /** Claude Code's own sessions only, and only when the workspace keeps token numbers. */
92
+ async function noteUsage(input, env, name, profile) {
93
+ if (!profile || name !== "claude-code" || input.cursor_version !== undefined || !input.transcript_path)
94
+ return;
95
+ const { readCliPolicy } = await import("./cliPolicy.js");
96
+ const policy = readCliPolicy(profile);
97
+ if (policy?.version !== 2 || !policy.autopilot.reportsUsage)
98
+ return;
99
+ const { noteTranscript } = await import("./cliUsage.js");
100
+ noteTranscript(profile, input.session_id, input.transcript_path, input.hook_event_name === "SessionEnd", env);
101
+ }
@@ -78,6 +78,9 @@ export type LineResult = {
78
78
  findings: CliFinding[];
79
79
  /** Every part understood: the only lines Passport may allow. */
80
80
  complete: boolean;
81
+ /** A part Passport couldn't tell anything about (an unknown program, a
82
+ * one-liner): the program that ran it, for coverage's Blind count. */
83
+ blind?: string;
81
84
  };
82
85
  /** A local action as a finding the guard and reports understand. */
83
86
  export declare function localFinding(action: LocalAction): CliFinding;
@@ -21,7 +21,7 @@ import { classifyArgv, classifyNestedText } from "./cliHookClassify.js";
21
21
  import { heredocBodies, projectCode } from "./cliHookLocalCode.js";
22
22
  import { SCRIPT_MAX_BYTES } from "./cliScriptRead.js";
23
23
  import { scriptReading } from "./cliHookScripts.js";
24
- import { splitCommands } from "./cliHookParse.js";
24
+ import { INTERPRETERS, normalizeArgv, splitCommands } from "./cliHookParse.js";
25
25
  import { VENDORS } from "./cliHookVendors.js";
26
26
  import { databasePrefix } from "./envDatabase.js";
27
27
  import { classifyLocalCommand } from "./localCommands.js";
@@ -375,9 +375,16 @@ export function localFinding(action) {
375
375
  }
376
376
  };
377
377
  }
378
+ /** The program a part ran, by name. A path is never sent: a file run by path is "script". */
379
+ function programOf(argv) {
380
+ const normalized = normalizeArgv(argv);
381
+ return normalized.via.includes("absolute-path") ? "script" : (normalized.argv[0] ?? "");
382
+ }
378
383
  function isVendor(program) {
379
384
  return Object.hasOwn(VENDORS, program);
380
385
  }
386
+ /** Interpreter flags whose code is on the line itself: a one-liner. */
387
+ const INLINE_CODE = /^(-e|-p|-c|--eval|--print)$/;
381
388
  function contextAt(cwd, machine) {
382
389
  const here = cwd ? placeOfPath(cwd, machine) : "unknown";
383
390
  const branches = cwd && (here === "project" || here === "project-root") ? gitBranches(cwd, machine.fs) : null;
@@ -452,6 +459,11 @@ function vendorFindings(shape, outcome, walk, depth, cwd) {
452
459
  walk.findings.push(...findings);
453
460
  if (outcome.kind !== "vendor") {
454
461
  walk.complete = false;
462
+ // Blind: nothing Passport knows ran here, or code given on the line itself.
463
+ const program = programOf(argv);
464
+ const oneLiner = INTERPRETERS.has(program) && argv.some((word) => INLINE_CODE.test(word));
465
+ if (oneLiner || findings.every((finding) => finding.risk === "unknown"))
466
+ walk.blind ??= program;
455
467
  return;
456
468
  }
457
469
  // A vendor part is understood when it is one confident, plain invocation.
@@ -477,6 +489,7 @@ function ownCode(shape, at, machine, walk) {
477
489
  walk.findings.push(...inner.findings);
478
490
  if (!inner.complete)
479
491
  walk.complete = false;
492
+ walk.blind ??= inner.blind;
480
493
  return true;
481
494
  }
482
495
  walk.findings.push(...code.actions.map(localFinding));
@@ -548,14 +561,19 @@ export function classifyLine(command, machine, depth = 0) {
548
561
  continue;
549
562
  vendorFindings(shape, outcome, walk, depth, cwd);
550
563
  }
564
+ nestedInto(nested, machine, depth, walk);
565
+ return walk;
566
+ }
567
+ /** Substitutions and heredocs: their vendor findings, and a shell's local ones. */
568
+ function nestedInto(nested, machine, depth, walk) {
551
569
  for (const sub of nested) {
552
570
  walk.findings.push(...classifyNestedText(sub, [], depth));
553
571
  if (sub.kind !== "heredoc" || /^(bash|sh|zsh|dash)$/.test(sub.target ?? "")) {
554
572
  const inner = classifyLine(sub.text, machine, depth + 1);
555
573
  walk.findings.push(...inner.findings.filter((finding) => finding.local));
574
+ walk.blind ??= inner.blind;
556
575
  }
557
576
  }
558
- return walk;
559
577
  }
560
578
  /** The folder the agent's command runs in: its cwd, or Cursor's first workspace root. */
561
579
  export function workingFolder(input) {
@@ -26,6 +26,8 @@ export type CodeScript = {
26
26
  word?: ShellWord;
27
27
  /** The words after it: arguments, or make targets and flags. */
28
28
  rest: ShellWord[];
29
+ /** The interpreter that runs it, when one was named (`node`, `python3`). */
30
+ runner?: string;
29
31
  };
30
32
  export type CodeFindings = {
31
33
  actions: LocalAction[];