passport-bridge 0.14.0 → 0.16.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 (96) hide show
  1. package/README.md +40 -3
  2. package/dist/cliAnswered.d.ts +38 -0
  3. package/dist/cliAnswered.js +217 -0
  4. package/dist/cliArgs.d.ts +1 -1
  5. package/dist/cliArgs.js +33 -7
  6. package/dist/cliAutopilot.d.ts +23 -1
  7. package/dist/cliAutopilot.js +179 -51
  8. package/dist/cliAutopilotPolicy.d.ts +50 -6
  9. package/dist/cliAutopilotPolicy.js +53 -4
  10. package/dist/cliEnv.d.ts +40 -0
  11. package/dist/cliEnv.js +157 -0
  12. package/dist/cliExec.d.ts +83 -0
  13. package/dist/cliExec.js +453 -0
  14. package/dist/cliHook.d.ts +19 -24
  15. package/dist/cliHook.js +95 -70
  16. package/dist/cliHookClassify.d.ts +30 -0
  17. package/dist/cliHookClassify.js +32 -2
  18. package/dist/cliHookDecide.d.ts +6 -3
  19. package/dist/cliHookDecide.js +26 -9
  20. package/dist/cliHookEnvironment.d.ts +9 -3
  21. package/dist/cliHookEnvironment.js +69 -15
  22. package/dist/cliHookGuard.d.ts +32 -6
  23. package/dist/cliHookGuard.js +155 -26
  24. package/dist/cliHookInput.d.ts +27 -0
  25. package/dist/cliHookInput.js +47 -0
  26. package/dist/cliHookInstall.js +16 -0
  27. package/dist/cliHookLocal.d.ts +79 -0
  28. package/dist/cliHookLocal.js +473 -0
  29. package/dist/cliHookParse.d.ts +33 -0
  30. package/dist/cliHookParse.js +144 -30
  31. package/dist/cliHookRewrite.d.ts +45 -0
  32. package/dist/cliHookRewrite.js +135 -0
  33. package/dist/cliHookVendors.js +8 -2
  34. package/dist/cliHookVendorsMore.d.ts +21 -0
  35. package/dist/cliHookVendorsMore.js +196 -0
  36. package/dist/cliInit.js +2 -1
  37. package/dist/cliKeys.d.ts +67 -0
  38. package/dist/cliKeys.js +426 -0
  39. package/dist/cliLogin.js +1 -1
  40. package/dist/cliOutput.js +10 -0
  41. package/dist/cliPolicy.d.ts +2 -0
  42. package/dist/cliPolicyRefresh.d.ts +7 -0
  43. package/dist/cliPolicyRefresh.js +20 -0
  44. package/dist/cliPolicyV2.js +126 -16
  45. package/dist/cliSetupOrg.js +12 -0
  46. package/dist/cliSync.d.ts +14 -0
  47. package/dist/cliSync.js +63 -0
  48. package/dist/cliUndo.d.ts +49 -0
  49. package/dist/cliUndo.js +312 -0
  50. package/dist/completion.js +12 -1
  51. package/dist/envDatabase.d.ts +28 -0
  52. package/dist/envDatabase.js +166 -0
  53. package/dist/envLinkFs.d.ts +57 -0
  54. package/dist/envLinkFs.js +140 -0
  55. package/dist/envLinksCloud.d.ts +31 -0
  56. package/dist/envLinksCloud.js +233 -0
  57. package/dist/envLinksHosting.d.ts +33 -0
  58. package/dist/envLinksHosting.js +463 -0
  59. package/dist/envResolve.d.ts +48 -0
  60. package/dist/envResolve.js +221 -0
  61. package/dist/envTarget.d.ts +61 -0
  62. package/dist/envTarget.js +50 -0
  63. package/dist/execBackupTarget.d.ts +25 -0
  64. package/dist/execBackupTarget.js +201 -0
  65. package/dist/execMarker.d.ts +7 -0
  66. package/dist/execMarker.js +66 -0
  67. package/dist/execVendors.d.ts +34 -0
  68. package/dist/execVendors.js +221 -0
  69. package/dist/initAutopilotStep.js +72 -5
  70. package/dist/initKeysStep.d.ts +2 -0
  71. package/dist/initKeysStep.js +67 -0
  72. package/dist/initLocalSteps.js +1 -1
  73. package/dist/initState.d.ts +3 -0
  74. package/dist/keysLocal.d.ts +56 -0
  75. package/dist/keysLocal.js +494 -0
  76. package/dist/localCommands.d.ts +39 -0
  77. package/dist/localCommands.js +534 -0
  78. package/dist/localFiles.d.ts +22 -0
  79. package/dist/localFiles.js +272 -0
  80. package/dist/localGit.d.ts +24 -0
  81. package/dist/localGit.js +270 -0
  82. package/dist/localNetwork.d.ts +16 -0
  83. package/dist/localNetwork.js +185 -0
  84. package/dist/localShared.d.ts +99 -0
  85. package/dist/localShared.js +173 -0
  86. package/dist/localTools.d.ts +52 -0
  87. package/dist/localTools.js +643 -0
  88. package/dist/nativeSync.d.ts +89 -0
  89. package/dist/nativeSync.js +376 -0
  90. package/dist/passport.js +25 -12
  91. package/dist/pluginPin.d.ts +1 -1
  92. package/dist/pluginPin.js +1 -1
  93. package/dist/version.d.ts +1 -1
  94. package/dist/version.js +1 -1
  95. package/npm-shrinkwrap.json +2 -2
  96. package/package.json +1 -1
@@ -13,9 +13,13 @@
13
13
  import { bool, value } from "./cliArgs.js";
14
14
  import { OTHER_APPS, PRESET_LABEL, PRESET_ROWS, rowLabel } from "./cliAutopilotPolicy.js";
15
15
  import { memberApi } from "./cliClient.js";
16
- import { classifyCommand } from "./cliHookClassify.js";
17
- import { ENV_KINDS, ENV_LABEL, environmentHintWith, isEnvKind } from "./cliHookEnvironment.js";
16
+ import { classifyLine, localMachine } from "./cliHookLocal.js";
17
+ import { ENV_KINDS, ENV_LABEL, isEnvKind } from "./cliHookEnvironment.js";
18
18
  import { decideGuard, guardLabel } from "./cliHookGuard.js";
19
+ import { NODE_LINK_FS } from "./envLinkFs.js";
20
+ import { resolveTarget } from "./envResolve.js";
21
+ // `passport env` lives in cliEnv.ts; the dispatcher reaches it through here.
22
+ export { env } from "./cliEnv.js";
19
23
  import { readCliPolicy } from "./cliPolicy.js";
20
24
  import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, sanitize, sleep, timeoutMs } from "./cliSupport.js";
21
25
  /** Long enough to be useful, short enough for an agent's default 2-minute
@@ -23,11 +27,11 @@ import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, san
23
27
  export const WAIT_DEFAULT_SECONDS = 100;
24
28
  const WAIT_POLL_SECONDS = 30;
25
29
  const APPROVAL_ID = /^[A-Za-z0-9_-]{1,80}$/;
26
- function api(args, runtime, deps, waitMs = 0) {
30
+ export function api(args, runtime, deps, waitMs = 0, agentKeyOk = false) {
27
31
  if (deps.api)
28
32
  return deps.api;
29
33
  const auth = resolveCliAuth(args, runtime.env);
30
- if (auth.kind !== "profile") {
34
+ if (auth.kind !== "profile" && !agentKeyOk) {
31
35
  return failure("This needs a member profile. Agent keys have no person to ask.", 6, "member_profile_required", {
32
36
  hint: "Run: passport login"
33
37
  });
@@ -39,7 +43,7 @@ function api(args, runtime, deps, waitMs = 0) {
39
43
  signal: runtime.signal
40
44
  });
41
45
  }
42
- async function json(response, fallback) {
46
+ export async function json(response, fallback) {
43
47
  if (response.status === 401 || response.status === 403) {
44
48
  return failure(await safeApiError(response, "Passport refused this profile."), 2, "auth", {
45
49
  hint: "Run: passport login"
@@ -68,14 +72,19 @@ function waitOutcome(id, body) {
68
72
  if (status === "allowed" || status === "approved") {
69
73
  // "Approved by Ramish." or "Now allowed by your rules.", then the next step.
70
74
  const lead = message ?? `Approved${by ? ` by ${by}` : ""}.`;
71
- const human = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
75
+ const next = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
76
+ // Once, when this approval reaches the threshold: "Tip: You've approved
77
+ // railway redeploy in Staging 5 times. ... Make it a rule: <link>".
78
+ const suggestion = text(body.suggestion, 400);
79
+ const human = suggestion ? `${next}\n${suggestion}` : next;
72
80
  return {
73
81
  json: {
74
82
  approvalId: id,
75
83
  status: "approved",
76
84
  ...(scope ? { scope } : {}),
77
85
  ...(by ? { decidedBy: by } : {}),
78
- message: human
86
+ message: next,
87
+ ...(suggestion ? { suggestion } : {})
79
88
  },
80
89
  human,
81
90
  essential: true
@@ -100,12 +109,16 @@ export async function wait(args, runtime, deps = {}) {
100
109
  const totalSeconds = value(args, "timeout") ? Number(value(args, "timeout")) : WAIT_DEFAULT_SECONDS;
101
110
  const now = deps.now ?? Date.now;
102
111
  const deadline = now() + totalSeconds * 1000;
103
- const client = api(args, runtime, deps, (WAIT_POLL_SECONDS + 10) * 1000);
112
+ // A cloud agent waits on the approval its own `passport exec` opened; the
113
+ // request went to its owner.
114
+ const agentKey = !deps.api && Boolean(runtime.env.PASSPORT_AGENT_KEY);
115
+ const client = api(args, runtime, deps, (WAIT_POLL_SECONDS + 10) * 1000, true);
116
+ const base = agentKey ? "/api/my/exec/approvals/" : "/api/my/approvals/";
104
117
  let announced = false;
105
118
  for (;;) {
106
119
  const left = Math.ceil((deadline - now()) / 1000);
107
120
  const poll = Math.max(1, Math.min(WAIT_POLL_SECONDS, left));
108
- const response = await client.fetchApi(`/api/my/approvals/${encodeURIComponent(id)}/wait?timeout=${poll}`, {
121
+ const response = await client.fetchApi(`${base}${encodeURIComponent(id)}/wait?timeout=${poll}`, {
109
122
  method: "GET",
110
123
  headers: { accept: "application/json" },
111
124
  signal: AbortSignal.any([runtime.signal, AbortSignal.timeout((poll + 10) * 1000)])
@@ -173,11 +186,18 @@ function ruleTestLines(label, result, source) {
173
186
  ` ${source}`
174
187
  ];
175
188
  }
176
- function localTest(command, policy, environment) {
177
- const findings = classifyCommand(command).map((finding) => environment && finding.vendor
178
- ? { ...finding, args: [...(finding.args ?? []), "--environment", environment] }
179
- : finding);
180
- const decision = decideGuard(findings, policy, command);
189
+ /** Place every finding in the environment the person picked. */
190
+ function inEnvironment(findings, environment) {
191
+ if (!environment)
192
+ return findings;
193
+ return findings.map((finding) => !finding.vendor
194
+ ? finding
195
+ : finding.local
196
+ ? { ...finding, local: { ...finding.local, environment } }
197
+ : { ...finding, pushEnvironment: undefined, args: [...(finding.args ?? []), "--environment", environment] });
198
+ }
199
+ function localTest(command, findings, complete, policy, machine) {
200
+ const decision = decideGuard(findings, policy, command, complete, machine);
181
201
  if (!decision)
182
202
  return null;
183
203
  return {
@@ -188,6 +208,43 @@ function localTest(command, policy, environment) {
188
208
  ...(decision.actionClass ? { actionClass: decision.actionClass } : {})
189
209
  };
190
210
  }
211
+ /**
212
+ * What `rules test` sends: an everyday command as what it is (program, verb,
213
+ * class, place), never its words; a vendor command as its label.
214
+ */
215
+ function testBody(lead, label, target, environment) {
216
+ if (lead.local) {
217
+ const finding = { vendor: lead.vendor, verb: lead.verb ?? "invoke", risk: lead.risk };
218
+ return { finding: { ...finding, environment: environment ?? lead.local.environment } };
219
+ }
220
+ // Where this computer placed it: a flag, the folder's link, or a mapping.
221
+ const placed = environment ?? lead.pushEnvironment ?? (target && target.source !== "assumed" ? target.kind : undefined);
222
+ return { command: label, ...(placed ? { environment: placed } : {}) };
223
+ }
224
+ /** The workspace's answer, or null to decide on this computer. */
225
+ async function askServer(body, args, runtime, deps) {
226
+ try {
227
+ const client = api(args, runtime, deps);
228
+ const response = await client.fetchApi("/api/my/rules/test", {
229
+ method: "POST",
230
+ headers: { "content-type": "application/json", accept: "application/json" },
231
+ body: JSON.stringify(body),
232
+ signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
233
+ });
234
+ if (!response.ok) {
235
+ await response.body?.cancel().catch(() => undefined);
236
+ return null;
237
+ }
238
+ const answer = await readBoundedJson(response);
239
+ // Only an answer with a decision counts; anything else falls back to this computer.
240
+ return answer && ["allow", "ask", "block", "none"].includes(answer.decision) ? answer : null;
241
+ }
242
+ catch (error) {
243
+ if (runtime.signal.aborted)
244
+ throw error;
245
+ return null;
246
+ }
247
+ }
191
248
  export async function rules(args, runtime, deps = {}) {
192
249
  const [action, command] = args.positionals;
193
250
  if (action !== "test" || !command?.trim()) {
@@ -198,11 +255,28 @@ export async function rules(args, runtime, deps = {}) {
198
255
  return failure("--environment must be production, staging, or development.", 6, "usage");
199
256
  }
200
257
  const environment = environmentFlag;
201
- const findings = classifyCommand(command).filter((finding) => finding.vendor);
202
- const label = findings.length ? guardLabel(findings[0]) : "This command";
258
+ // Paths are read where you run this, like the hook reads the agent's folder.
259
+ const machine = deps.machine ?? localMachine(process.cwd(), runtime.env);
260
+ const line = classifyLine(command, machine);
261
+ // Folder links are read here too, unless a test gave a pretend machine only.
262
+ const guardMachine = deps.machine && !deps.linkFs
263
+ ? undefined
264
+ : {
265
+ cwd: machine.cwd,
266
+ rawCwd: deps.machine ? machine.cwd : process.cwd(),
267
+ projectRoot: machine.projectRoot,
268
+ home: machine.home,
269
+ env: runtime.env,
270
+ fs: deps.linkFs ?? NODE_LINK_FS
271
+ };
272
+ const all = inEnvironment(line.findings, environment);
273
+ const findings = all.filter((finding) => finding.vendor);
203
274
  if (!findings.length) {
204
275
  const result = { decision: "none" };
205
- return { json: { command: null, ...result }, human: ruleTestLines(label, result, "").filter(Boolean).join("\n") };
276
+ return {
277
+ json: { command: null, ...result },
278
+ human: ruleTestLines("This command", result, "").filter(Boolean).join("\n")
279
+ };
206
280
  }
207
281
  const profile = (() => {
208
282
  try {
@@ -214,40 +288,23 @@ export async function rules(args, runtime, deps = {}) {
214
288
  }
215
289
  })();
216
290
  const cached = profile ? readCliPolicy(profile) : null;
217
- const local = localTest(command, cached, environment);
218
- const hint = findings[0].vendor
219
- ? environmentHintWith(findings[0].vendor, findings[0].args ?? [], cached?.version === 2
220
- ? {
221
- flags: cached.autopilot.environmentFlags,
222
- known: cached.autopilot.environments
223
- }
224
- : {})
225
- : undefined;
226
- const placed = environment ?? (hint && hint.source !== "assumed" ? hint.kind : undefined);
291
+ const decided = decideGuard(all, cached, command, line.complete, guardMachine);
292
+ // The command that decides: the strictest one the rules spoke about.
293
+ const lead = decided?.findings[0] ?? findings[0];
294
+ const label = guardLabel(lead);
295
+ const local = localTest(command, all, line.complete, cached, guardMachine);
296
+ const v2 = cached?.version === 2 ? cached.autopilot : undefined;
297
+ const target = decided?.decided?.find((entry) => entry.finding === lead)?.target ??
298
+ (lead.vendor && !lead.local
299
+ ? resolveTarget(lead.vendor, lead.args ?? [], {
300
+ ...(v2 ? { flags: v2.environmentFlags, known: v2.environments } : {}),
301
+ ...(v2?.resources ? { resources: v2.resources } : {})
302
+ })
303
+ : undefined);
227
304
  // The server knows grants, every rule, and the workspace's environments.
228
- let result = null;
229
- let source = "";
230
- if (profile || deps.api) {
231
- try {
232
- const client = api(args, runtime, deps);
233
- const response = await client.fetchApi("/api/my/rules/test", {
234
- method: "POST",
235
- headers: { "content-type": "application/json", accept: "application/json" },
236
- body: JSON.stringify({ command: label, ...(placed ? { environment: placed } : {}) }),
237
- signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
238
- });
239
- if (response.ok) {
240
- result = await readBoundedJson(response);
241
- source = "Decided by your workspace's rules.";
242
- }
243
- else
244
- await response.body?.cancel().catch(() => undefined);
245
- }
246
- catch (error) {
247
- if (runtime.signal.aborted)
248
- throw error;
249
- }
250
- }
305
+ const asked = profile || deps.api ? await askServer(testBody(lead, label, target, environment), args, runtime, deps) : null;
306
+ let result = asked;
307
+ let source = result ? "Decided by your workspace's rules." : "";
251
308
  if (!result) {
252
309
  result = local ?? { decision: "none" };
253
310
  source = cached
@@ -340,6 +397,58 @@ function presetMap(raw) {
340
397
  out[OTHER_APPS] = body[OTHER_APPS];
341
398
  return out;
342
399
  }
400
+ /** Local midnight, so "today" is the person's today wherever the server is. */
401
+ export function localMidnight(now) {
402
+ const date = new Date(now);
403
+ date.setHours(0, 0, 0, 0);
404
+ return date.getTime();
405
+ }
406
+ async function answeredStatus(fetchApi, profile, signal, now) {
407
+ const { answeredToday } = await import("./cliAnswered.js");
408
+ const local = profile ? answeredToday(profile, now) : 0;
409
+ try {
410
+ const response = await fetchApi(`/api/my/stats?range=24h&todayStart=${localMidnight(now)}`, {
411
+ method: "GET",
412
+ headers: { accept: "application/json" },
413
+ signal
414
+ });
415
+ if (response.ok) {
416
+ const body = await readBoundedJson(response);
417
+ const today = body.answered?.today;
418
+ // Batches reach Passport every few minutes; never show less than this computer counted.
419
+ if (typeof today === "number" && Number.isFinite(today))
420
+ return { today: Math.max(today, local), source: "workspace" };
421
+ }
422
+ else
423
+ await response.body?.cancel().catch(() => undefined);
424
+ }
425
+ catch {
426
+ /* This computer's own count. */
427
+ }
428
+ return { today: local, source: "this-computer" };
429
+ }
430
+ async function allowlistStatus() {
431
+ try {
432
+ const { readManifest } = await import("./nativeSync.js");
433
+ const manifest = readManifest();
434
+ if (!manifest)
435
+ return undefined;
436
+ const names = {
437
+ "claude-code": "Claude Code",
438
+ codex: "Codex",
439
+ "cursor-cli": "Cursor CLI",
440
+ cursor: "Cursor"
441
+ };
442
+ return Object.entries(manifest.agents).map(([agent, entry]) => ({
443
+ agent,
444
+ name: names[agent] ?? agent,
445
+ entries: entry?.entries.length ?? 0
446
+ }));
447
+ }
448
+ catch {
449
+ return undefined;
450
+ }
451
+ }
343
452
  /** Read presets and floors for `passport status`. Never throws. */
344
453
  export async function autopilotStatus(fetchApi, profile, signal, now = Date.now()) {
345
454
  const cached = profile ? readCliPolicy(profile) : null;
@@ -365,7 +474,16 @@ export async function autopilotStatus(fetchApi, profile, signal, now = Date.now(
365
474
  floors[row] = isPresetName(floor) ? floor : null;
366
475
  }
367
476
  const reason = text(body.floors?.reason, 120);
368
- return { presets: presetMap(body.presets), floors, ...(reason ? { floorReason: reason } : {}), cache };
477
+ const answered = await answeredStatus(fetchApi, profile, signal, now);
478
+ const allowlists = await allowlistStatus();
479
+ return {
480
+ presets: presetMap(body.presets),
481
+ floors,
482
+ ...(reason ? { floorReason: reason } : {}),
483
+ cache,
484
+ ...(answered ? { answered } : {}),
485
+ ...(allowlists ? { allowlists } : {})
486
+ };
369
487
  }
370
488
  catch {
371
489
  return { presets: null, floors: null, cache };
@@ -385,5 +503,15 @@ export function autopilotLines(status) {
385
503
  lines.push(cache.fetchedAt === null
386
504
  ? "Rules on this computer: not synced yet"
387
505
  : `Rules on this computer: synced ${ageText(cache.ageMs ?? 0)}${cache.version === 1 ? " (older server: asks before destructive commands only)" : ""}`);
506
+ if (status.answered) {
507
+ const count = status.answered.today;
508
+ lines.push(`Answered for you: ${count.toLocaleString("en-US")} ${count === 1 ? "prompt" : "prompts"} today${status.answered.source === "this-computer" ? " on this computer" : ""}`);
509
+ }
510
+ if (status.allowlists) {
511
+ const synced = status.allowlists.filter((entry) => entry.entries > 0);
512
+ lines.push(synced.length
513
+ ? `Agent allowlists: ${synced.map((entry) => `${entry.name} (${entry.entries})`).join(", ")}, kept in sync by passport sync`
514
+ : "Agent allowlists: on, nothing to add yet");
515
+ }
388
516
  return lines;
389
517
  }
@@ -32,13 +32,27 @@ export type CliRule = {
32
32
  /** An app rule: matches every command of that platform's CLI. */
33
33
  appKey?: string;
34
34
  actionClass?: ActionClass;
35
- environment: EnvKind | "any";
35
+ environment: ActionEnv | "any";
36
36
  /** "me", "workspace", or "team:<name>": who the rule belongs to. */
37
37
  scope?: string;
38
38
  /** The server's owner words: "Your rule", "Engineering team rule". */
39
39
  owner?: string;
40
40
  /** The server's whole cause line, used as is when present. */
41
41
  label?: string;
42
+ /** Actions an approved exception lifts this rule for (this person only). */
43
+ except?: RuleException[];
44
+ };
45
+ export type RuleException = {
46
+ vendor?: string;
47
+ verb?: string;
48
+ appKey?: string;
49
+ actionClass?: ActionClass;
50
+ environment: ActionEnv | "any";
51
+ };
52
+ /** The second-person rule's cause lines, as the server words them. */
53
+ export declare const SECOND_PERSON_LABEL: {
54
+ readonly change: "Production changes need someone else to approve";
55
+ readonly delete: "Production deletes need someone else to approve";
42
56
  };
43
57
  /** A flag that names an environment: `--prod` names one itself, `--environment`
44
58
  * takes the name as its value. */
@@ -46,9 +60,16 @@ export type EnvironmentFlag = {
46
60
  flag: string;
47
61
  value?: EnvKind;
48
62
  };
63
+ /** Where an action runs: an environment, or "other" (Other apps: apps
64
+ * without environments, and this computer outside the project). */
65
+ export type ActionEnv = EnvKind | "other";
49
66
  export type AutopilotPolicy = {
50
- presets: Record<EnvKind, Preset>;
51
- floors: Record<EnvKind, Preset | null>;
67
+ presets: Record<EnvKind, Preset> & {
68
+ other?: Preset;
69
+ };
70
+ floors: Record<EnvKind, Preset | null> & {
71
+ other?: Preset | null;
72
+ };
52
73
  rules: CliRule[];
53
74
  /** Verbs that are irreversible wherever they run. */
54
75
  irreversible: Record<string, string[]>;
@@ -63,6 +84,24 @@ export type AutopilotPolicy = {
63
84
  name: string;
64
85
  kind: EnvKind;
65
86
  }>;
87
+ /** The server decides everyday commands too (Phase 1.5): reports and
88
+ * decide requests may carry them. */
89
+ localCommands?: boolean;
90
+ /** Production classes someone else must approve: never run here, and never
91
+ * approved in the agent's own prompt. "Maya or Sam" names who approves. */
92
+ secondPerson?: {
93
+ classes: ActionClass[];
94
+ approvers: string;
95
+ };
96
+ /** Resources the workspace placed, by id (Phase 4.5). Present only when the
97
+ * server reads where a finding lands, so findings may carry it. */
98
+ resources?: Array<{
99
+ platform: string;
100
+ resourceKey: string;
101
+ label: string;
102
+ kind: EnvKind;
103
+ source: "detected" | "set" | "assumed";
104
+ }>;
66
105
  };
67
106
  /** The platform a vendor CLI acts on, so its rules and environments line up
68
107
  * with the same platform's MCP app (server `cliPlatform`). */
@@ -74,7 +113,9 @@ export type PresetRow = EnvKind | typeof OTHER_APPS;
74
113
  export declare const PRESET_ROWS: PresetRow[];
75
114
  export declare function rowLabel(row: string): string;
76
115
  export declare const PRESET_LABEL: Record<Preset, string>;
77
- export declare const DEFAULT_PRESETS: Record<EnvKind, Preset>;
116
+ export declare const DEFAULT_PRESETS: Record<ActionEnv, Preset>;
117
+ /** "Production", "Other apps". */
118
+ export declare function envLabel(env: ActionEnv): string;
78
119
  export declare function stricterPreset(a: Preset, b: Preset | null | undefined): Preset;
79
120
  export declare function presetStrictness(preset: Preset): number;
80
121
  export declare function presetDecision(preset: Preset, actionClass: ActionClass): Decision;
@@ -83,12 +124,15 @@ export type ActionFacts = {
83
124
  /** The vendor-map verb, e.g. `volume delete` or `push --force`. */
84
125
  verb: string;
85
126
  actionClass: ActionClass;
86
- environment: EnvKind;
127
+ environment: ActionEnv;
87
128
  };
88
129
  export type LocalDecision = {
89
130
  decision: Decision;
90
131
  cause: Cause;
91
132
  };
92
- /** The server's `decideAction`, minus grants (only the server knows them). */
133
+ /** The server's `decideAction`, minus grants (only the server knows them).
134
+ * The second-person rule turns a Production run into an ask the server owns. */
93
135
  export declare function decideAction(policy: AutopilotPolicy, facts: ActionFacts): LocalDecision;
136
+ /** Whether an ask needs someone other than the person at the keyboard. */
137
+ export declare function needsSecondPerson(cause: Cause | undefined): boolean;
94
138
  export declare function decisionRank(decision: Decision): number;
@@ -14,6 +14,11 @@
14
14
  import { ENV_LABEL } from "./cliHookEnvironment.js";
15
15
  export const PRESETS = ["careful", "balanced", "handsoff"];
16
16
  export const ACTION_CLASSES = ["read", "change", "delete", "irreversible"];
17
+ /** The second-person rule's cause lines, as the server words them. */
18
+ export const SECOND_PERSON_LABEL = {
19
+ change: "Production changes need someone else to approve",
20
+ delete: "Production deletes need someone else to approve"
21
+ };
17
22
  /** The platform a vendor CLI acts on, so its rules and environments line up
18
23
  * with the same platform's MCP app (server `cliPlatform`). */
19
24
  export function platformOf(vendor) {
@@ -46,8 +51,13 @@ const PRESET_TABLE = {
46
51
  export const DEFAULT_PRESETS = {
47
52
  production: "careful",
48
53
  staging: "balanced",
49
- development: "handsoff"
54
+ development: "handsoff",
55
+ other: "balanced"
50
56
  };
57
+ /** "Production", "Other apps". */
58
+ export function envLabel(env) {
59
+ return env === OTHER_APPS ? "Other apps" : ENV_LABEL[env];
60
+ }
51
61
  const STRICTNESS = { careful: 2, balanced: 1, handsoff: 0 };
52
62
  const DECISION_RANK = { allow: 0, ask: 1, block: 2 };
53
63
  export function stricterPreset(a, b) {
@@ -107,8 +117,22 @@ function ruleMatches(rule, facts) {
107
117
  }
108
118
  if (rule.decision === "allow" && facts.actionClass === "irreversible" && level !== LEVEL_ACTION)
109
119
  return false;
120
+ // An approved exception lifts this rule for the action it names.
121
+ if (rule.except?.some((lift) => exceptionCovers(lift, facts)))
122
+ return false;
110
123
  return true;
111
124
  }
125
+ function exceptionCovers(lift, facts) {
126
+ if (lift.environment !== "any" && lift.environment !== facts.environment)
127
+ return false;
128
+ if (lift.vendor !== undefined && lift.verb !== undefined)
129
+ return lift.vendor === facts.vendor && lift.verb === facts.verb;
130
+ if (lift.appKey !== undefined && !appMatches(lift.appKey, facts))
131
+ return false;
132
+ if (lift.actionClass !== undefined && lift.actionClass !== facts.actionClass)
133
+ return false;
134
+ return lift.appKey !== undefined || lift.actionClass !== undefined;
135
+ }
112
136
  function matchText(rule) {
113
137
  if (rule.vendor !== undefined && rule.verb !== undefined)
114
138
  return `${rule.vendor} ${rule.verb}`;
@@ -132,7 +156,11 @@ function ruleLabel(rule) {
132
156
  ? "Team rule"
133
157
  : "Rule";
134
158
  const verb = rule.decision === "allow" ? "always run" : rule.decision === "ask" ? "ask before" : "no";
135
- const where = rule.environment === "any" ? "" : ` in ${ENV_LABEL[rule.environment]}`;
159
+ const where = rule.environment === "any"
160
+ ? ""
161
+ : rule.environment === OTHER_APPS
162
+ ? " in other apps"
163
+ : ` in ${ENV_LABEL[rule.environment]}`;
136
164
  // cli-policy v2 doesn't say whose rule it is; don't guess.
137
165
  if (owner === "Rule")
138
166
  return `A rule says ${verb} ${matchText(rule)}${where}`;
@@ -143,12 +171,19 @@ function presetLabel(env, preset, actionClass, decision) {
143
171
  return "Reads always run";
144
172
  if (actionClass === "irreversible")
145
173
  return "Irreversible actions always ask";
174
+ if (env === OTHER_APPS) {
175
+ // The server's words: "Other apps are Balanced", "Other apps: deletes ask first (Balanced)".
176
+ if (decision === "allow")
177
+ return `Other apps are ${PRESET_LABEL[preset]}`;
178
+ return `Other apps: ${CLASS_PLURAL[actionClass]} ask first (${PRESET_LABEL[preset]})`;
179
+ }
146
180
  if (decision === "allow")
147
181
  return `${ENV_LABEL[env]} is ${PRESET_LABEL[preset]}`;
148
182
  return `${ENV_LABEL[env]} ${CLASS_PLURAL[actionClass]} ask first (${PRESET_LABEL[preset]})`;
149
183
  }
150
184
  function floorLabel(env, preset) {
151
- return `Your team requires ${PRESET_LABEL[preset]} or stricter in ${ENV_LABEL[env]}`;
185
+ const where = env === OTHER_APPS ? "for other apps" : `in ${ENV_LABEL[env]}`;
186
+ return `Your team requires ${PRESET_LABEL[preset]} or stricter ${where}`;
152
187
  }
153
188
  function mostSpecific(rules) {
154
189
  const top = Math.max(...rules.map(ruleLevel));
@@ -157,8 +192,22 @@ function mostSpecific(rules) {
157
192
  function stricter(a, b) {
158
193
  return DECISION_RANK[b] > DECISION_RANK[a] ? b : a;
159
194
  }
160
- /** The server's `decideAction`, minus grants (only the server knows them). */
195
+ /** The server's `decideAction`, minus grants (only the server knows them).
196
+ * The second-person rule turns a Production run into an ask the server owns. */
161
197
  export function decideAction(policy, facts) {
198
+ const decided = decideByRules(policy, facts);
199
+ const classes = policy.secondPerson?.classes ?? [];
200
+ if (decided.decision !== "allow" || facts.environment !== "production" || !classes.includes(facts.actionClass)) {
201
+ return decided;
202
+ }
203
+ const label = facts.actionClass === "change" ? SECOND_PERSON_LABEL.change : SECOND_PERSON_LABEL.delete;
204
+ return { decision: "ask", cause: { kind: "floor", label } };
205
+ }
206
+ /** Whether an ask needs someone other than the person at the keyboard. */
207
+ export function needsSecondPerson(cause) {
208
+ return cause?.label === SECOND_PERSON_LABEL.change || cause?.label === SECOND_PERSON_LABEL.delete;
209
+ }
210
+ function decideByRules(policy, facts) {
162
211
  const matching = policy.rules.filter((rule) => ruleMatches(rule, facts));
163
212
  // 1. Block rules, any scope. The most specific one names the cause.
164
213
  const blocks = matching.filter((rule) => rule.decision === "block");
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `passport env`: where commands in this folder land, the way each vendor's
3
+ * own CLI would decide it (Autopilot Phase 4.5).
4
+ *
5
+ * passport env [--json]
6
+ * passport env set <vendor> <resource> <production|staging|development>
7
+ *
8
+ * Read on this computer. Rows name the vendor, the resource's label, how
9
+ * Passport knows (linked, a flag, the vendor's default), and its kind; never a
10
+ * path, URL, or key. `env set` places a resource for the whole workspace:
11
+ * admins may choose any kind, everyone else only Production.
12
+ */
13
+ import { type ParsedArgs } from "./cliArgs.js";
14
+ import { type MemberApi } from "./cliClient.js";
15
+ import { type LocalMachine } from "./cliHookLocal.js";
16
+ import { type LinkFs } from "./envLinkFs.js";
17
+ import { type DetectedLink } from "./envResolve.js";
18
+ import { type CommandResult, type Runtime } from "./cliSupport.js";
19
+ export type EnvDependencies = {
20
+ api?: MemberApi;
21
+ machine?: LocalMachine;
22
+ linkFs?: LinkFs;
23
+ cwd?: string;
24
+ };
25
+ export type EnvRow = {
26
+ vendor: string;
27
+ resource: string;
28
+ how: string;
29
+ kind: string;
30
+ assumed: boolean;
31
+ note?: string;
32
+ };
33
+ /** One row per linked vendor, as the table and `--json` show it. */
34
+ export declare function envRows(links: DetectedLink[]): EnvRow[];
35
+ /** The links in this folder, placed with this computer's copy of the rules. */
36
+ export declare function linksHere(args: ParsedArgs, runtime: Runtime, deps?: EnvDependencies): DetectedLink[];
37
+ 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
+ export declare function env(args: ParsedArgs, runtime: Runtime, deps?: EnvDependencies): Promise<CommandResult>;