passport-bridge 0.16.4 → 0.16.8

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 (119) hide show
  1. package/README.md +47 -26
  2. package/dist/bridgeExchange.d.ts +1 -1
  3. package/dist/bridgeExchange.js +1 -1
  4. package/dist/cli.js +6 -6
  5. package/dist/cliActions.d.ts +28 -0
  6. package/dist/cliActions.js +224 -0
  7. package/dist/cliAnswered.d.ts +5 -0
  8. package/dist/cliAnswered.js +27 -2
  9. package/dist/cliApprovalLink.d.ts +5 -0
  10. package/dist/cliApprovalLink.js +21 -0
  11. package/dist/cliArgs.d.ts +1 -1
  12. package/dist/cliArgs.js +17 -7
  13. package/dist/cliAutopilot.d.ts +13 -3
  14. package/dist/cliAutopilot.js +25 -34
  15. package/dist/cliAutopilotPolicy.d.ts +20 -0
  16. package/dist/cliCodexTrust.d.ts +42 -0
  17. package/dist/cliCodexTrust.js +145 -0
  18. package/dist/cliEnv.d.ts +9 -2
  19. package/dist/cliEnv.js +30 -20
  20. package/dist/cliExec.d.ts +2 -8
  21. package/dist/cliExec.js +15 -25
  22. package/dist/cliExecGuard.d.ts +10 -0
  23. package/dist/cliExecGuard.js +36 -0
  24. package/dist/cliGuardHealth.d.ts +42 -0
  25. package/dist/cliGuardHealth.js +154 -0
  26. package/dist/cliGuardState.d.ts +60 -0
  27. package/dist/cliGuardState.js +121 -0
  28. package/dist/cliHook.d.ts +5 -59
  29. package/dist/cliHook.js +158 -158
  30. package/dist/cliHookClassify.d.ts +12 -0
  31. package/dist/cliHookDecide.d.ts +13 -0
  32. package/dist/cliHookDecide.js +35 -2
  33. package/dist/cliHookDeliver.d.ts +153 -0
  34. package/dist/cliHookDeliver.js +281 -0
  35. package/dist/cliHookExtras.d.ts +26 -0
  36. package/dist/cliHookExtras.js +34 -0
  37. package/dist/cliHookGuard.d.ts +7 -4
  38. package/dist/cliHookGuard.js +65 -10
  39. package/dist/cliHookInstall.d.ts +14 -0
  40. package/dist/cliHookInstall.js +10 -70
  41. package/dist/cliHookLocal.d.ts +6 -0
  42. package/dist/cliHookLocal.js +56 -3
  43. package/dist/cliHookLocalCode.d.ts +11 -0
  44. package/dist/cliHookLocalCode.js +18 -5
  45. package/dist/cliHookRewrite.js +1 -1
  46. package/dist/cliHookScripts.d.ts +51 -0
  47. package/dist/cliHookScripts.js +247 -0
  48. package/dist/cliHookStatus.d.ts +18 -0
  49. package/dist/cliHookStatus.js +111 -0
  50. package/dist/cliInit.d.ts +3 -0
  51. package/dist/cliInit.js +18 -6
  52. package/dist/cliKeys.d.ts +8 -0
  53. package/dist/cliKeys.js +71 -20
  54. package/dist/cliKeysBack.d.ts +41 -0
  55. package/dist/cliKeysBack.js +124 -0
  56. package/dist/cliLogin.js +1 -1
  57. package/dist/cliOpaqueId.d.ts +10 -0
  58. package/dist/cliOpaqueId.js +48 -0
  59. package/dist/cliOutput.js +18 -10
  60. package/dist/cliPolicy.d.ts +3 -0
  61. package/dist/cliPolicy.js +17 -0
  62. package/dist/cliPolicyV2.js +76 -3
  63. package/dist/cliScan.js +3 -3
  64. package/dist/cliScriptRead.d.ts +199 -0
  65. package/dist/cliScriptRead.js +512 -0
  66. package/dist/cliScriptText.d.ts +78 -0
  67. package/dist/cliScriptText.js +412 -0
  68. package/dist/cliSeen.d.ts +40 -0
  69. package/dist/cliSeen.js +203 -0
  70. package/dist/cliSession.d.ts +1 -0
  71. package/dist/cliSession.js +2 -0
  72. package/dist/cliSetup.js +3 -3
  73. package/dist/cliSetupLock.d.ts +37 -0
  74. package/dist/cliSetupLock.js +330 -0
  75. package/dist/cliSetupOrg.d.ts +2 -0
  76. package/dist/cliSetupOrg.js +28 -2
  77. package/dist/cliSpeed.d.ts +104 -0
  78. package/dist/cliSpeed.js +320 -0
  79. package/dist/cliStatusGuard.d.ts +28 -0
  80. package/dist/cliStatusGuard.js +77 -0
  81. package/dist/cliSupport.d.ts +4 -0
  82. package/dist/completion.js +8 -4
  83. package/dist/credentials.js +8 -0
  84. package/dist/envResolve.d.ts +9 -5
  85. package/dist/envResolve.js +27 -8
  86. package/dist/execTarget.d.ts +8 -0
  87. package/dist/execTarget.js +28 -0
  88. package/dist/fastPathFlag.d.ts +38 -0
  89. package/dist/fastPathFlag.js +90 -0
  90. package/dist/hookFastPath.d.ts +44 -0
  91. package/dist/hookFastPath.js +234 -0
  92. package/dist/hookMain.d.ts +2 -0
  93. package/dist/hookMain.js +53 -0
  94. package/dist/hookOutbox.d.ts +27 -0
  95. package/dist/hookOutbox.js +176 -0
  96. package/dist/initAutopilotStep.js +6 -8
  97. package/dist/initInstall.d.ts +6 -3
  98. package/dist/initInstall.js +44 -5
  99. package/dist/initKeysStep.js +5 -0
  100. package/dist/initLocalSteps.js +7 -7
  101. package/dist/initUi.d.ts +10 -0
  102. package/dist/initUi.js +27 -0
  103. package/dist/launcherFastPath.d.ts +55 -0
  104. package/dist/launcherFastPath.js +347 -0
  105. package/dist/lockedHooks.d.ts +99 -0
  106. package/dist/lockedHooks.js +178 -0
  107. package/dist/managedHooks.d.ts +10 -0
  108. package/dist/managedHooks.js +80 -0
  109. package/dist/managedSkills.js +4 -4
  110. package/dist/passport.js +5 -4
  111. package/dist/pluginPin.d.ts +1 -1
  112. package/dist/pluginPin.js +1 -1
  113. package/dist/recoveryIdentity.js +2 -2
  114. package/dist/version.d.ts +1 -1
  115. package/dist/version.js +1 -1
  116. package/dist/webLinks.d.ts +5 -0
  117. package/dist/webLinks.js +49 -0
  118. package/npm-shrinkwrap.json +2 -2
  119. package/package.json +3 -2
@@ -123,9 +123,32 @@ function readState(profile) {
123
123
  function writeState(profile, state) {
124
124
  writePrivateAtomic(statePath(profile), ".answered", `${JSON.stringify(state)}\n`, "answered counts");
125
125
  }
126
- /** At most one report per interval per profile, claimed before any network. */
126
+ function intervalMarker(profile) {
127
+ assertProfileName(profile);
128
+ return join(directory(), `.${profile}.report`);
129
+ }
130
+ /** Whether a batch report is due, without claiming it. Never throws. */
131
+ export function reportIntervalDue(profile, now = Date.now()) {
132
+ try {
133
+ const last = statSync(intervalMarker(profile)).mtimeMs;
134
+ return now - last >= ANSWERED_REPORT_MS || last > now;
135
+ }
136
+ catch (error) {
137
+ return error.code === "ENOENT";
138
+ }
139
+ }
140
+ /** At most one batch report (answered counts and speed numbers) per interval
141
+ * per profile, claimed before any network. Never throws. */
142
+ export function claimReportInterval(profile, now = Date.now()) {
143
+ try {
144
+ return claimInterval(profile, now);
145
+ }
146
+ catch {
147
+ return false;
148
+ }
149
+ }
127
150
  function claimInterval(profile, now) {
128
- const marker = join(directory(), `.${profile}.report`);
151
+ const marker = intervalMarker(profile);
129
152
  try {
130
153
  const last = statSync(marker).mtimeMs;
131
154
  if (now - last < ANSWERED_REPORT_MS && last <= now)
@@ -136,6 +159,8 @@ function claimInterval(profile, now) {
136
159
  return false;
137
160
  }
138
161
  try {
162
+ ensurePrivateDirectory(true);
163
+ mkdirSync(directory(), { recursive: true, mode: 0o700 });
139
164
  const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
140
165
  closeSync(openSync(marker, constants.O_WRONLY | constants.O_CREAT | noFollow, 0o600));
141
166
  utimesSync(marker, now / 1000, now / 1000);
@@ -0,0 +1,5 @@
1
+ import type { ParsedArgs } from "./cliArgs.js";
2
+ import { type CliFailure, type Env } from "./cliSupport.js";
3
+ /** A failure that names an approval also names where to answer it. Returns
4
+ * the same failure, so the CLI's catch can link it in one step. */
5
+ export declare function linkApproval(error: CliFailure, args: ParsedArgs | undefined, env: Env): CliFailure;
@@ -0,0 +1,21 @@
1
+ import { resolveCliAuth } from "./cliSupport.js";
2
+ import { workspaceOfToken } from "./tokenWorkspace.js";
3
+ import { approvalLink } from "./webLinks.js";
4
+ /** A failure that names an approval also names where to answer it. Returns
5
+ * the same failure, so the CLI's catch can link it in one step. */
6
+ export function linkApproval(error, args, env) {
7
+ const id = error.details.approvalId;
8
+ if (!args || !id || error.details.approvalUrl || error.cause === "unknown_approval")
9
+ return error;
10
+ try {
11
+ const auth = resolveCliAuth(args, env);
12
+ const workspace = auth.kind === "profile" ? workspaceOfToken(auth.refreshToken) : "";
13
+ const url = approvalLink(auth.endpoint, id, workspace || undefined);
14
+ if (url)
15
+ error.details.approvalUrl = url;
16
+ }
17
+ catch {
18
+ // No profile to read the origin from: the approval id alone still works.
19
+ }
20
+ return error;
21
+ }
package/dist/cliArgs.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const COMMANDS: readonly ["init", "login", "logout", "profiles", "use", "status", "doctor", "ready", "search", "describe", "run", "connect", "resources", "prompts", "discover", "scan", "hook", "wait", "rules", "sessions", "env", "sync", "exec", "undo", "keys", "setup", "session", "access", "completion", "help", "version"];
1
+ export declare const COMMANDS: readonly ["init", "login", "logout", "profiles", "use", "status", "doctor", "ready", "search", "describe", "run", "connect", "resources", "prompts", "discover", "scan", "hook", "wait", "rules", "actions", "sessions", "env", "sync", "exec", "undo", "keys", "setup", "session", "access", "completion", "help", "version"];
2
2
  export type Command = (typeof COMMANDS)[number];
3
3
  export declare class ArgError extends Error {
4
4
  }
package/dist/cliArgs.js CHANGED
@@ -18,6 +18,7 @@ export const COMMANDS = [
18
18
  "hook",
19
19
  "wait",
20
20
  "rules",
21
+ "actions",
21
22
  "sessions",
22
23
  "env",
23
24
  "sync",
@@ -47,12 +48,16 @@ const FLAGS = {
47
48
  yes: { kind: "boolean", commands: ["init", "setup", "keys", "undo"] },
48
49
  org: { kind: "value", commands: ["setup"] },
49
50
  clients: { kind: "value", commands: ["setup"] },
51
+ lock: { kind: "boolean", commands: ["setup"] },
52
+ strict: { kind: "boolean", commands: ["setup"] },
50
53
  "skip-apps": { kind: "boolean", commands: ["init"] },
51
54
  "skip-agents": { kind: "boolean", commands: ["init"] },
52
55
  "skip-guard": { kind: "boolean", commands: ["init"] },
53
56
  "move-keys": { kind: "boolean", commands: ["init"] },
54
57
  app: { kind: "value", commands: ["search"] },
55
- args: { kind: "value", commands: ["run"] },
58
+ args: { kind: "value", commands: ["run", "actions"] },
59
+ id: { kind: "value", commands: ["actions"] },
60
+ class: { kind: "value", commands: ["actions"] },
56
61
  set: { kind: "repeat", commands: ["run", "prompts"] },
57
62
  "set-json": { kind: "repeat", commands: ["run"] },
58
63
  wait: { kind: "value", commands: ["run", "connect", "exec"] },
@@ -69,12 +74,16 @@ const FLAGS = {
69
74
  "public-jwk-file": { kind: "value", commands: ["access"] },
70
75
  "delegation-id": { kind: "value", commands: ["access"] },
71
76
  "client-id": { kind: "value", commands: ["access"] },
72
- environment: { kind: "value", commands: ["rules"] },
77
+ environment: { kind: "value", commands: ["rules", "actions"] },
73
78
  status: { kind: "value", commands: ["sessions"] },
74
79
  remove: { kind: "boolean", commands: ["sync"] },
75
80
  last: { kind: "boolean", commands: ["undo"] },
76
81
  option: { kind: "value", commands: ["undo"] }
77
82
  };
83
+ /** `--agent` is the documented name; `--client` keeps working everywhere. */
84
+ const FLAG_ALIASES = { agent: "client", agents: "clients" };
85
+ const shownFlag = (name) => Object.keys(FLAG_ALIASES).find((alias) => FLAG_ALIASES[alias] === name) ?? name;
86
+ const passedTwice = (name) => shownFlag(name) === name ? `--${name} may only be passed once.` : `Pass --${shownFlag(name)} or --${name} once.`;
78
87
  export class ArgError extends Error {
79
88
  }
80
89
  function knownCommand(value) {
@@ -109,10 +118,11 @@ export function parseArgs(argv) {
109
118
  command = "version";
110
119
  continue;
111
120
  }
112
- const { name, inline } = flagParts(raw);
121
+ const { name: given, inline } = flagParts(raw);
122
+ const name = FLAG_ALIASES[given] ?? given;
113
123
  const spec = FLAGS[name];
114
124
  if (!spec)
115
- throw new ArgError(`Unknown option: --${name}`);
125
+ throw new ArgError(`Unknown option: --${given}`);
116
126
  if (spec.kind === "boolean") {
117
127
  if (inline !== undefined)
118
128
  throw new ArgError(`--${name} does not take a value.`);
@@ -123,13 +133,13 @@ export function parseArgs(argv) {
123
133
  }
124
134
  const value = inline !== undefined ? inline : argv[++i];
125
135
  if (value === undefined)
126
- throw new ArgError(`--${name} requires a value.`);
136
+ throw new ArgError(`--${given} requires a value.`);
127
137
  if (spec.kind === "repeat") {
128
138
  (repeats[name] ??= []).push(value);
129
139
  }
130
140
  else {
131
141
  if (Object.hasOwn(values, name))
132
- throw new ArgError(`--${name} may only be passed once.`);
142
+ throw new ArgError(passedTwice(name));
133
143
  values[name] = value;
134
144
  }
135
145
  continue;
@@ -158,7 +168,7 @@ export function parseArgs(argv) {
158
168
  for (const name of [...Object.keys(values), ...Object.keys(repeats), ...booleans]) {
159
169
  const allowed = FLAGS[name]?.commands;
160
170
  if (allowed && !allowed.includes(command))
161
- throw new ArgError(`--${name} is not valid with ${command}.`);
171
+ throw new ArgError(`--${shownFlag(name)} is not valid with ${command}.`);
162
172
  }
163
173
  validateShape(command, positionals);
164
174
  validateNumbers(values);
@@ -10,6 +10,7 @@
10
10
  * `rules test` classifies the command on this machine and sends only the
11
11
  * vendor and verb (and the environment kind), never the command line.
12
12
  */
13
+ import { type GuardStatus } from "./cliStatusGuard.js";
13
14
  import { type ParsedArgs } from "./cliArgs.js";
14
15
  import { type Preset, type PresetRow } from "./cliAutopilotPolicy.js";
15
16
  import { type MemberApi } from "./cliClient.js";
@@ -17,6 +18,7 @@ import { type LocalMachine } from "./cliHookLocal.js";
17
18
  import { type EnvKind } from "./cliHookEnvironment.js";
18
19
  import { type LinkFs } from "./envLinkFs.js";
19
20
  export { env } from "./cliEnv.js";
21
+ export { actions } from "./cliActions.js";
20
22
  import { type CommandResult, type Runtime } from "./cliSupport.js";
21
23
  /** Long enough to be useful, short enough for an agent's default 2-minute
22
24
  * command timeout. */
@@ -70,15 +72,23 @@ export type AutopilotStatus = {
70
72
  today: number;
71
73
  source: "workspace" | "this-computer";
72
74
  };
75
+ /** "Passport added 0.3 s and asked you twice today. …": across your
76
+ * computers when Passport keeps the numbers, else this computer's own. */
77
+ speed?: {
78
+ line: string;
79
+ source: "workspace" | "this-computer";
80
+ };
73
81
  /** Agents whose own allowlist Passport keeps in sync, with how many entries. */
74
82
  allowlists?: Array<{
75
83
  agent: string;
76
84
  name: string;
77
85
  entries: number;
78
86
  }>;
87
+ /** Batch A: each agent's guard here, coverage this week, and fixes. */
88
+ guard?: GuardStatus;
79
89
  };
80
- /** Local midnight, so "today" is the person's today wherever the server is. */
81
- export declare function localMidnight(now: number): number;
90
+ export { localMidnight } from "./cliSpeed.js";
82
91
  /** Read presets and floors for `passport status`. Never throws. */
83
92
  export declare function autopilotStatus(fetchApi: (path: string, init: RequestInit) => Promise<Response>, profile: string | undefined, signal: AbortSignal, now?: number): Promise<AutopilotStatus>;
84
- export declare function autopilotLines(status: AutopilotStatus): string[];
93
+ /** `passport status` lines; with the web origin, a link to change the rules. */
94
+ export declare function autopilotLines(status: AutopilotStatus, webOrigin?: string): string[];
@@ -10,6 +10,7 @@
10
10
  * `rules test` classifies the command on this machine and sends only the
11
11
  * vendor and verb (and the environment kind), never the command line.
12
12
  */
13
+ import { guardLines, guardStatus } from "./cliStatusGuard.js";
13
14
  import { bool, value } from "./cliArgs.js";
14
15
  import { OTHER_APPS, PRESET_LABEL, PRESET_ROWS, rowLabel } from "./cliAutopilotPolicy.js";
15
16
  import { memberApi } from "./cliClient.js";
@@ -20,8 +21,10 @@ import { NODE_LINK_FS } from "./envLinkFs.js";
20
21
  import { resolveTarget } from "./envResolve.js";
21
22
  // `passport env` lives in cliEnv.ts; the dispatcher reaches it through here.
22
23
  export { env } from "./cliEnv.js";
24
+ export { actions } from "./cliActions.js";
23
25
  import { looseningLines } from "./cliLoosening.js";
24
26
  import { readCliPolicy } from "./cliPolicy.js";
27
+ import { ruleLink, sessionLink } from "./webLinks.js";
25
28
  import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, sanitize, sleep, timeoutMs } from "./cliSupport.js";
26
29
  /** Long enough to be useful, short enough for an agent's default 2-minute
27
30
  * command timeout. */
@@ -75,7 +78,7 @@ function waitOutcome(id, body) {
75
78
  const lead = message ?? `Approved${by ? ` by ${by}` : ""}.`;
76
79
  const next = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
77
80
  // Once, when this approval reaches the threshold: "Tip: You've approved
78
- // railway redeploy in Staging 5 times. ... Make it a rule: <link>".
81
+ // railway redeploy in Staging 3 times. ... Make it a rule: <link>".
79
82
  const suggestion = text(body.suggestion, 400);
80
83
  const human = suggestion ? `${next}\n${suggestion}` : next;
81
84
  return {
@@ -376,7 +379,12 @@ export async function sessions(args, runtime, deps = {}) {
376
379
  const rows = (Array.isArray(page.sessions) ? page.sessions : []).slice(0, 50);
377
380
  const now = (deps.now ?? Date.now)();
378
381
  const human = rows.length
379
- ? rows.map((row) => sessionLine(row, now)).join("\n")
382
+ ? rows
383
+ .map((row) => {
384
+ const link = sessionLink(client.origin, typeof row.id === "string" ? row.id : undefined);
385
+ return link ? `${sessionLine(row, now)}\n ${link}` : sessionLine(row, now);
386
+ })
387
+ .join("\n")
380
388
  : "No sessions yet. Start your agent and its actions will show up here.";
381
389
  return { json: { sessions: rows, nextCursor: page.nextCursor ?? null }, human };
382
390
  }
@@ -398,36 +406,7 @@ function presetMap(raw) {
398
406
  out[OTHER_APPS] = body[OTHER_APPS];
399
407
  return out;
400
408
  }
401
- /** Local midnight, so "today" is the person's today wherever the server is. */
402
- export function localMidnight(now) {
403
- const date = new Date(now);
404
- date.setHours(0, 0, 0, 0);
405
- return date.getTime();
406
- }
407
- async function answeredStatus(fetchApi, profile, signal, now) {
408
- const { answeredToday } = await import("./cliAnswered.js");
409
- const local = profile ? answeredToday(profile, now) : 0;
410
- try {
411
- const response = await fetchApi(`/api/my/stats?range=24h&todayStart=${localMidnight(now)}`, {
412
- method: "GET",
413
- headers: { accept: "application/json" },
414
- signal
415
- });
416
- if (response.ok) {
417
- const body = await readBoundedJson(response);
418
- const today = body.answered?.today;
419
- // Batches reach Passport every few minutes; never show less than this computer counted.
420
- if (typeof today === "number" && Number.isFinite(today))
421
- return { today: Math.max(today, local), source: "workspace" };
422
- }
423
- else
424
- await response.body?.cancel().catch(() => undefined);
425
- }
426
- catch {
427
- /* This computer's own count. */
428
- }
429
- return { today: local, source: "this-computer" };
430
- }
409
+ export { localMidnight } from "./cliSpeed.js";
431
410
  async function allowlistStatus() {
432
411
  try {
433
412
  const { readManifest } = await import("./nativeSync.js");
@@ -476,8 +455,9 @@ export async function autopilotStatus(fetchApi, profile, signal, now = Date.now(
476
455
  }
477
456
  const reason = text(body.floors?.reason, 120);
478
457
  const exceptions = looseningLines(body);
479
- const answered = await answeredStatus(fetchApi, profile, signal, now);
458
+ const { answered, speed } = await (await import("./cliSpeed.js")).todayStatus(fetchApi, profile, signal, now);
480
459
  const allowlists = await allowlistStatus();
460
+ const guard = await guardStatus(fetchApi, profile, signal, now);
481
461
  return {
482
462
  presets: presetMap(body.presets),
483
463
  floors,
@@ -485,6 +465,8 @@ export async function autopilotStatus(fetchApi, profile, signal, now = Date.now(
485
465
  ...(exceptions.length ? { exceptions } : {}),
486
466
  cache,
487
467
  ...(answered ? { answered } : {}),
468
+ ...(speed ? { speed } : {}),
469
+ ...(guard ? { guard } : {}),
488
470
  ...(allowlists ? { allowlists } : {})
489
471
  };
490
472
  }
@@ -492,7 +474,8 @@ export async function autopilotStatus(fetchApi, profile, signal, now = Date.now(
492
474
  return { presets: null, floors: null, cache };
493
475
  }
494
476
  }
495
- export function autopilotLines(status) {
477
+ /** `passport status` lines; with the web origin, a link to change the rules. */
478
+ export function autopilotLines(status, webOrigin) {
496
479
  const lines = [];
497
480
  if (status.presets) {
498
481
  const presets = status.presets;
@@ -502,11 +485,19 @@ export function autopilotLines(status) {
502
485
  if (floors.length)
503
486
  lines.push(`Team floors: ${floors.join(" · ")}${status.floorReason ? ` (${sanitize(status.floorReason)})` : ""}`);
504
487
  lines.push(...(status.exceptions ?? []));
488
+ const rules = ruleLink(webOrigin);
489
+ if (rules)
490
+ lines.push(`Change your rules: ${rules}`);
505
491
  }
506
492
  const { cache } = status;
507
493
  lines.push(cache.fetchedAt === null
508
494
  ? "Rules on this computer: not synced yet"
509
495
  : `Rules on this computer: synced ${ageText(cache.ageMs ?? 0)}${cache.version === 1 ? " (older server: asks before destructive commands only)" : ""}`);
496
+ if (status.speed) {
497
+ lines.push(`${status.speed.line}${status.speed.source === "this-computer" ? " (this computer)" : ""}`);
498
+ }
499
+ // The guard state sits next to the speed line: both say how the guard is doing here.
500
+ lines.push(...guardLines(status.guard));
510
501
  if (status.answered) {
511
502
  const count = status.answered.today;
512
503
  lines.push(`Answered for you: ${count.toLocaleString("en-US")} ${count === 1 ? "prompt" : "prompts"} today${status.answered.source === "this-computer" ? " on this computer" : ""}`);
@@ -87,12 +87,17 @@ export type AutopilotPolicy = {
87
87
  /** The server decides everyday commands too (Phase 1.5): reports and
88
88
  * decide requests may carry them. */
89
89
  localCommands?: boolean;
90
+ /** The server keeps the hook's speed numbers (cli-policy v2 `speed`). */
91
+ reportsSpeed?: boolean;
90
92
  /** Production classes someone else must approve: never run here, and never
91
93
  * approved in the agent's own prompt. "Maya or Sam" names who approves. */
92
94
  secondPerson?: {
93
95
  classes: ActionClass[];
94
96
  approvers: string;
95
97
  };
98
+ /** What the guard does per environment when Passport can't be reached
99
+ * (Batch A). Absent from older servers: built-in defaults apply. */
100
+ offline?: Record<ActionEnv, "ask" | "block" | "allow">;
96
101
  /** Resources the workspace placed, by id (Phase 4.5). Present only when the
97
102
  * server reads where a finding lands, so findings may carry it. */
98
103
  resources?: Array<{
@@ -101,7 +106,22 @@ export type AutopilotPolicy = {
101
106
  label: string;
102
107
  kind: EnvKind;
103
108
  source: "detected" | "set" | "assumed";
109
+ /** The label came from the connected app, not from a link file. */
110
+ confirmed?: boolean;
104
111
  }>;
112
+ /** Known project scripts (Batch A item 5), vendor `project`: they set class
113
+ * and environment only, never an allow. */
114
+ project?: {
115
+ actions: Array<{
116
+ id: string;
117
+ repo?: string;
118
+ program: string;
119
+ args: string;
120
+ environment: EnvKind;
121
+ actionClass: ActionClass;
122
+ contentHash?: string;
123
+ }>;
124
+ };
105
125
  };
106
126
  /** The platform a vendor CLI acts on, so its rules and environments line up
107
127
  * with the same platform's MCP app (server `cliPlatform`). */
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Whether Codex trusts Passport's guard hook (Batch A, "Not trusted").
3
+ *
4
+ * Codex runs a hook from `~/.codex/hooks.json` only after the person trusts
5
+ * it in `/hooks`. It then stores, in `~/.codex/config.toml`,
6
+ *
7
+ * [hooks.state."<hooks.json path>:pre_tool_use:<group>:<handler>"]
8
+ * trusted_hash = "sha256:<hex>"
9
+ *
10
+ * and runs the hook only while that hash matches the hook as written now. The
11
+ * hash input, confirmed in openai/codex (codex-rs/hooks/src/engine/discovery.rs
12
+ * `hook_hash`, codex-rs/config/src/fingerprint.rs `version_for_toml`) and
13
+ * against codex-cli 0.146.0's `hooks/list`, is the normalized identity
14
+ * `{ event_name, matcher?, hooks: [handler] }`, where the handler is
15
+ * `{ type: "command", command, timeout (default 600), async (default false),
16
+ * statusMessage?, additionalContextLimit? (when not 2500) }`, serialized as
17
+ * JSON with every object's keys sorted, no whitespace, then SHA-256.
18
+ *
19
+ * Read-only: Passport never writes Codex's trust; only the person can.
20
+ */
21
+ import type { CodexTrust } from "./cliGuardState.js";
22
+ type Handler = Record<string, unknown>;
23
+ /** Codex's trust hash for one PreToolUse command handler. */
24
+ export declare function codexHookHash(matcher: string | undefined, handler: Handler): string;
25
+ /** Where Passport's guard sits in hooks.json: its group and handler index. */
26
+ export declare function findGuardEntry(settings: unknown, isGuard: (command: unknown) => boolean): {
27
+ group: number;
28
+ handler: number;
29
+ matcher?: string;
30
+ entry: Handler;
31
+ } | null;
32
+ /** `[hooks.state."<key>"]` tables in config.toml: each key's trusted hash and enabled flag. */
33
+ export declare function codexHookStates(toml: string): Map<string, {
34
+ trustedHash?: string;
35
+ enabled?: boolean;
36
+ }>;
37
+ /**
38
+ * Codex's trust in Passport's guard entry in `hooksPath`, or undefined when
39
+ * the file holds no guard entry (nothing to trust).
40
+ */
41
+ export declare function codexGuardTrust(hooksPath: string, isGuard: (command: unknown) => boolean): CodexTrust | undefined;
42
+ export {};
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Whether Codex trusts Passport's guard hook (Batch A, "Not trusted").
3
+ *
4
+ * Codex runs a hook from `~/.codex/hooks.json` only after the person trusts
5
+ * it in `/hooks`. It then stores, in `~/.codex/config.toml`,
6
+ *
7
+ * [hooks.state."<hooks.json path>:pre_tool_use:<group>:<handler>"]
8
+ * trusted_hash = "sha256:<hex>"
9
+ *
10
+ * and runs the hook only while that hash matches the hook as written now. The
11
+ * hash input, confirmed in openai/codex (codex-rs/hooks/src/engine/discovery.rs
12
+ * `hook_hash`, codex-rs/config/src/fingerprint.rs `version_for_toml`) and
13
+ * against codex-cli 0.146.0's `hooks/list`, is the normalized identity
14
+ * `{ event_name, matcher?, hooks: [handler] }`, where the handler is
15
+ * `{ type: "command", command, timeout (default 600), async (default false),
16
+ * statusMessage?, additionalContextLimit? (when not 2500) }`, serialized as
17
+ * JSON with every object's keys sorted, no whitespace, then SHA-256.
18
+ *
19
+ * Read-only: Passport never writes Codex's trust; only the person can.
20
+ */
21
+ import { createHash } from "node:crypto";
22
+ import { readFileSync } from "node:fs";
23
+ import { dirname, join, resolve } from "node:path";
24
+ const MAX_BYTES = 1024 * 1024;
25
+ const DEFAULT_TIMEOUT_SEC = 600;
26
+ const DEFAULT_CONTEXT_LIMIT = 2500;
27
+ function sortDeep(value) {
28
+ if (Array.isArray(value))
29
+ return value.map(sortDeep);
30
+ if (value && typeof value === "object") {
31
+ return Object.fromEntries(Object.keys(value)
32
+ .sort()
33
+ .map((key) => [key, sortDeep(value[key])]));
34
+ }
35
+ return value;
36
+ }
37
+ /** Codex's trust hash for one PreToolUse command handler. */
38
+ export function codexHookHash(matcher, handler) {
39
+ const timeout = typeof handler.timeout === "number" && Number.isFinite(handler.timeout)
40
+ ? Math.max(1, Math.floor(handler.timeout))
41
+ : DEFAULT_TIMEOUT_SEC;
42
+ const normalized = {
43
+ type: "command",
44
+ command: handler.command,
45
+ timeout,
46
+ async: handler.async === true
47
+ };
48
+ if (typeof handler.statusMessage === "string")
49
+ normalized.statusMessage = handler.statusMessage;
50
+ if (typeof handler.additionalContextLimit === "number" && handler.additionalContextLimit !== DEFAULT_CONTEXT_LIMIT) {
51
+ normalized.additionalContextLimit = handler.additionalContextLimit;
52
+ }
53
+ const identity = { event_name: "pre_tool_use", hooks: [normalized] };
54
+ if (typeof matcher === "string")
55
+ identity.matcher = matcher;
56
+ return `sha256:${createHash("sha256")
57
+ .update(JSON.stringify(sortDeep(identity)))
58
+ .digest("hex")}`;
59
+ }
60
+ function readBounded(path) {
61
+ try {
62
+ const raw = readFileSync(path, "utf8");
63
+ return Buffer.byteLength(raw) > MAX_BYTES ? null : raw;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /** Where Passport's guard sits in hooks.json: its group and handler index. */
70
+ export function findGuardEntry(settings, isGuard) {
71
+ const hooks = settings?.hooks;
72
+ const groups = hooks && Array.isArray(hooks.PreToolUse) ? hooks.PreToolUse : [];
73
+ for (let group = 0; group < groups.length; group++) {
74
+ const value = groups[group];
75
+ const handlers = value && Array.isArray(value.hooks) ? value.hooks : [];
76
+ for (let handler = 0; handler < handlers.length; handler++) {
77
+ const entry = handlers[handler];
78
+ if (entry && (entry.type === undefined || entry.type === "command") && isGuard(entry.command)) {
79
+ return {
80
+ group,
81
+ handler,
82
+ ...(typeof value?.matcher === "string" ? { matcher: value.matcher } : {}),
83
+ entry
84
+ };
85
+ }
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ /** A TOML basic string's contents, unescaped (the forms Codex writes). */
91
+ function unquote(body) {
92
+ return body.replace(/\\(["\\/bfnrt])/g, (_match, char) => char === "b" ? "\b" : char === "f" ? "\f" : char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? "\t" : char);
93
+ }
94
+ /** `[hooks.state."<key>"]` tables in config.toml: each key's trusted hash and enabled flag. */
95
+ export function codexHookStates(toml) {
96
+ const states = new Map();
97
+ let current = null;
98
+ for (const raw of toml.split(/\r?\n/)) {
99
+ const line = raw.trim();
100
+ if (line.startsWith("[")) {
101
+ const header = /^\[\s*hooks\s*\.\s*state\s*\.\s*"((?:[^"\\]|\\.)*)"\s*\]$/.exec(line);
102
+ current = header ? { ...(states.get(unquote(header[1])) ?? {}) } : null;
103
+ if (header)
104
+ states.set(unquote(header[1]), current);
105
+ continue;
106
+ }
107
+ if (!current)
108
+ continue;
109
+ const hash = /^trusted_hash\s*=\s*"((?:[^"\\]|\\.)*)"/.exec(line);
110
+ if (hash)
111
+ current.trustedHash = unquote(hash[1]);
112
+ const enabled = /^enabled\s*=\s*(true|false)\b/.exec(line);
113
+ if (enabled)
114
+ current.enabled = enabled[1] === "true";
115
+ }
116
+ return states;
117
+ }
118
+ /**
119
+ * Codex's trust in Passport's guard entry in `hooksPath`, or undefined when
120
+ * the file holds no guard entry (nothing to trust).
121
+ */
122
+ export function codexGuardTrust(hooksPath, isGuard) {
123
+ const raw = readBounded(hooksPath);
124
+ if (raw === null)
125
+ return undefined;
126
+ let settings;
127
+ try {
128
+ settings = JSON.parse(raw);
129
+ }
130
+ catch {
131
+ return undefined;
132
+ }
133
+ const found = findGuardEntry(settings, isGuard);
134
+ if (!found)
135
+ return undefined;
136
+ const absolute = resolve(hooksPath);
137
+ const key = `${absolute}:pre_tool_use:${found.group}:${found.handler}`;
138
+ const states = codexHookStates(readBounded(join(dirname(absolute), "config.toml")) ?? "");
139
+ const state = states.get(key);
140
+ if (state?.enabled === false)
141
+ return "disabled";
142
+ if (!state?.trustedHash)
143
+ return "untrusted";
144
+ return state.trustedHash === codexHookHash(found.matcher, found.entry) ? "trusted" : "modified";
145
+ }
package/dist/cliEnv.d.ts CHANGED
@@ -28,6 +28,8 @@ export type EnvRow = {
28
28
  how: string;
29
29
  kind: string;
30
30
  assumed: boolean;
31
+ /** Placed by the naming rule: `staging` is Staging. */
32
+ named?: boolean;
31
33
  note?: string;
32
34
  };
33
35
  /** One row per linked vendor, as the table and `--json` show it. */
@@ -35,6 +37,11 @@ export declare function envRows(links: DetectedLink[]): EnvRow[];
35
37
  /** The links in this folder, placed with this computer's copy of the rules. */
36
38
  export declare function linksHere(args: ParsedArgs, runtime: Runtime, deps?: EnvDependencies): DetectedLink[];
37
39
  export declare const ENV_EMPTY = "No linked apps in this folder.";
38
- /** The Environments table `init` shows for this project. */
39
- export declare function envTableLines(rows: EnvRow[]): string[];
40
+ /**
41
+ * The Environments table `passport env` and `init` show, one string per line.
42
+ * Columns line up when every row fits in `width`; otherwise each row is
43
+ * stacked (app and resource, then how and environment) so nothing wraps into
44
+ * the next column.
45
+ */
46
+ export declare function envTableLines(rows: EnvRow[], width?: number): string[];
40
47
  export declare function env(args: ParsedArgs, runtime: Runtime, deps?: EnvDependencies): Promise<CommandResult>;