passport-bridge 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -262,7 +262,7 @@ An ask becomes one Activity row. In Claude Code, with the audit hook registered,
262
262
 
263
263
  **When Passport can't be reached.** A local run, block, or attended ask stands as decided. When the guard needs Passport (an unattended ask, Codex, or a Production action someone else approves) and it doesn't answer within the budget, the environment's `offline` setting from cli-policy v2 decides: ask, block, or allow (ask everywhere by default). An ask nobody can answer (unattended, or Codex) blocks, a second-person action is always blocked, and allow never covers an irreversible action or an ask from a team floor, team or workspace rule, approver rule, or approved exception. A policy synced more than 7 days ago uses the default. The reason ends with one line saying why, such as `Nobody is here to approve it and Passport couldn't be reached, so it's blocked.`
264
264
 
265
- **App access.** The person's pass for the app a `passport exec` CLI acts on (Railway for `railway`, GitHub for `gh`, and so on) comes with cli-policy v2 as `appAccess`. No access blocks every command of that CLI with `You don't have access to Railway in Passport. Ask an admin.` and a link to the app's Access tab; read-only blocks everything but reads. `passport exec` says the same (exit 5, cause `no_access`, with `Access: <link>`). A CLI whose app isn't in the workspace keeps working from its key.
265
+ **App access.** The person's pass for the app a `passport exec` CLI acts on (Railway for `railway`, GitHub for `gh`, and so on) comes with cli-policy v2 as `access`, one record per CLI whose app limits the person (an older server's `appAccess` map is read the same way). The guard applies it before any rule, and no rule or exception lifts it. No access blocks every command of that CLI with `You don't have access to Railway in Passport. Ask an admin.` and a link to the app's Access tab; read-only blocks everything but reads. `passport exec` says the same (exit 5, cause `no_access`, with `Access: <link>`). A CLI whose app isn't in the workspace keeps working from its key.
266
266
 
267
267
  `src/cliPolicy.ts` caches the member's CLI policy (`GET /api/my/cli-policy`) at `$PASSPORT_HOME/cli-policy/<profile>.json` (mode 600). Servers with Autopilot send version 2 (`src/cliPolicyV2.ts`: presets, floors, CLI rules, irreversible and delete verbs, environment flags, placed environments); older servers send version 1, and then the guard keeps its earlier shape: ask or deny before destructive verbs, never allow, no server call, and reports without the Autopilot fields. `passport login` and `passport status` refresh it and `passport logout` removes it. A 404 or error keeps the previous copy; with no copy the guard asks before every destructive verb. `PASSPORT_HOOK_DISABLED=1` turns both hooks off.
268
268
 
@@ -2,6 +2,9 @@
2
2
  * Autopilot decisions on this machine, from the cached cli-policy v2.
3
3
  *
4
4
  * The same order the server uses (docs: autopilot map, section 4):
5
+ * 0. The access ceiling: the person's pass for the app the CLI acts on.
6
+ * No access blocks every command, Read-only runs only reads. Nothing
7
+ * below lifts it.
5
8
  * 1. Block rules → Blocked.
6
9
  * 2. (Grants given in this session live on the server; unattended runs ask it.)
7
10
  * 3. The most specific exception (action > app > class), strictest across
@@ -17,7 +20,7 @@ export type Preset = (typeof PRESETS)[number];
17
20
  export declare const ACTION_CLASSES: readonly ["read", "change", "delete", "irreversible"];
18
21
  export type ActionClass = (typeof ACTION_CLASSES)[number];
19
22
  export type Decision = "allow" | "ask" | "block";
20
- export type CauseKind = "block" | "grant" | "rule" | "floor" | "preset" | "default";
23
+ export type CauseKind = "access" | "block" | "grant" | "rule" | "floor" | "preset" | "default";
21
24
  export type Cause = {
22
25
  kind: CauseKind;
23
26
  id?: string;
@@ -74,11 +77,28 @@ export type RuleException = {
74
77
  actionClass?: ActionClass;
75
78
  environment: ActionEnv | "any";
76
79
  };
77
- /** One vendor's app access: the server's cause and message, and the Access link. */
78
- export type AppAccessEntry = {
79
- pass: "full" | "readonly" | "none";
80
+ /**
81
+ * One access ceiling record (cli-policy v2 `access`, shared `CliAccessRecord`):
82
+ * the person's pass for the app a vendor CLI acts on, sent only when it limits
83
+ * them. No record means no ceiling.
84
+ */
85
+ export type AccessRecord = {
86
+ layer: "access";
87
+ /** The vendor CLI it governs, e.g. `railway` or `flyctl`. */
88
+ vendor: string;
89
+ appKey: string;
90
+ /** The app's name, "Railway". */
80
91
  app: string;
92
+ pass: "none" | "readonly";
93
+ /** The cause line: "No access to Railway in Passport". */
81
94
  cause: string;
95
+ /** What the person and the agent read. */
96
+ message: string;
97
+ /** The app's Access tab, when the server sent a valid link. */
98
+ link?: string;
99
+ };
100
+ /** What a person reads when the access ceiling blocks: the message and the Access link. */
101
+ export type AccessBlock = {
82
102
  message: string;
83
103
  link?: string;
84
104
  };
@@ -131,10 +151,10 @@ export type AutopilotPolicy = {
131
151
  /** What the guard does per environment when Passport can't be reached
132
152
  * (Batch A). Absent from older servers: built-in defaults apply. */
133
153
  offline?: Record<ActionEnv, "ask" | "block" | "allow">;
134
- /** The person's pass for the app each vendor CLI acts on (cli-policy v2
135
- * `appAccess`), by vendor: No access blocks every command, Read-only runs
136
- * only reads. A vendor without an entry has no app in the workspace. */
137
- appAccess?: Record<string, AppAccessEntry>;
154
+ /** The access ceiling (cli-policy v2 `access`): one record per vendor CLI
155
+ * whose app limits this person. No access blocks every command, Read-only
156
+ * runs only reads. A vendor without a record has no ceiling. */
157
+ access?: AccessRecord[];
138
158
  /** Resources the workspace placed, by id (Phase 4.5). Present only when the
139
159
  * server reads where a finding lands, so findings may carry it. */
140
160
  resources?: Array<{
@@ -186,9 +206,14 @@ export type ActionFacts = {
186
206
  export type LocalDecision = {
187
207
  decision: Decision;
188
208
  cause: Cause;
209
+ /** Blocked by the access ceiling: what the person reads. */
210
+ access?: AccessBlock;
189
211
  };
212
+ /** The access record for a vendor CLI, under either spelling (`fly`, `flyctl`). */
213
+ export declare function accessRecordFor(policy: AutopilotPolicy, vendor: string): AccessRecord | undefined;
190
214
  /** The server's `decideAction`, minus grants (only the server knows them).
191
- * The second-person rule turns a Production run into an ask the server owns. */
215
+ * The access ceiling comes first and nothing lifts it; the second-person rule
216
+ * turns a Production run into an ask the server owns. */
192
217
  export declare function decideAction(policy: AutopilotPolicy, facts: ActionFacts): LocalDecision;
193
218
  /** Whether an ask needs someone other than the person at the keyboard. */
194
219
  export declare function needsSecondPerson(cause: Cause | undefined): boolean;
@@ -2,6 +2,9 @@
2
2
  * Autopilot decisions on this machine, from the cached cli-policy v2.
3
3
  *
4
4
  * The same order the server uses (docs: autopilot map, section 4):
5
+ * 0. The access ceiling: the person's pass for the app the CLI acts on.
6
+ * No access blocks every command, Read-only runs only reads. Nothing
7
+ * below lifts it.
5
8
  * 1. Block rules → Blocked.
6
9
  * 2. (Grants given in this session live on the server; unattended runs ask it.)
7
10
  * 3. The most specific exception (action > app > class), strictest across
@@ -12,6 +15,7 @@
12
15
  * Every decision carries its cause, and every cause reads as one line.
13
16
  */
14
17
  import { ENV_LABEL } from "./cliHookEnvironment.js";
18
+ import { vendorKeys } from "./cliHookVendors.js";
15
19
  export const PRESETS = ["careful", "balanced", "handsoff"];
16
20
  export const ACTION_CLASSES = ["read", "change", "delete", "irreversible"];
17
21
  /**
@@ -253,9 +257,36 @@ function mostSpecific(rules) {
253
257
  function stricter(a, b) {
254
258
  return DECISION_RANK[b] > DECISION_RANK[a] ? b : a;
255
259
  }
260
+ /** The access record for a vendor CLI, under either spelling (`fly`, `flyctl`). */
261
+ export function accessRecordFor(policy, vendor) {
262
+ const records = policy.access;
263
+ if (!records?.length)
264
+ return undefined;
265
+ for (const key of vendorKeys(vendor)) {
266
+ const record = records.find((entry) => entry.vendor === key);
267
+ if (record)
268
+ return record;
269
+ }
270
+ return undefined;
271
+ }
272
+ /** The access ceiling: No access blocks every command, Read-only blocks all but reads. */
273
+ function accessCeiling(policy, facts) {
274
+ const record = accessRecordFor(policy, facts.vendor);
275
+ if (!record || (record.pass === "readonly" && facts.actionClass === "read"))
276
+ return null;
277
+ return {
278
+ decision: "block",
279
+ cause: { kind: "access", label: record.cause },
280
+ access: { message: record.message, ...(record.link ? { link: record.link } : {}) }
281
+ };
282
+ }
256
283
  /** The server's `decideAction`, minus grants (only the server knows them).
257
- * The second-person rule turns a Production run into an ask the server owns. */
284
+ * The access ceiling comes first and nothing lifts it; the second-person rule
285
+ * turns a Production run into an ask the server owns. */
258
286
  export function decideAction(policy, facts) {
287
+ const ceiling = accessCeiling(policy, facts);
288
+ if (ceiling)
289
+ return ceiling;
259
290
  const decided = decideByRules(policy, facts);
260
291
  const classes = policy.secondPerson?.classes ?? [];
261
292
  if (decided.decision !== "allow" || facts.environment !== "production" || !classes.includes(facts.actionClass)) {
package/dist/cliHook.js CHANGED
@@ -17,6 +17,7 @@
17
17
  import { value } from "./cliArgs.js";
18
18
  import { summarize } from "./cliHookClassify.js";
19
19
  import { classifyLine, localMachine, workingFolder, worthReporting } from "./cliHookLocal.js";
20
+ import { projectOf } from "./cliHookProject.js";
20
21
  import { codexAskBlocked, planGuard } from "./cliHookDecide.js";
21
22
  import { decideGuard, guardMachineOf } from "./cliHookGuard.js";
22
23
  import { detectMode } from "./cliHookMode.js";
@@ -124,11 +125,15 @@ function context(input, env, declared) {
124
125
  const toolUseId = text(input.tool_use_id, 128);
125
126
  const roots = Array.isArray(input.workspace_roots) ? input.workspace_roots : [];
126
127
  const cwdName = directoryName(input.cwd) ?? directoryName(roots[0]);
128
+ // Sessions group by project: its name and branch only, read locally and cached.
129
+ const { project, branch } = sessionId ? projectOf(workingFolder(input)) : {};
127
130
  return {
128
131
  runtime: detectRuntime(input, env, declared),
129
132
  ...(sessionId ? { sessionId } : {}),
130
133
  ...(toolUseId ? { toolUseId } : {}),
131
- ...(cwdName ? { cwdName } : {})
134
+ ...(cwdName ? { cwdName } : {}),
135
+ ...(project ? { project } : {}),
136
+ ...(branch ? { branch } : {})
132
137
  };
133
138
  }
134
139
  function reportable(findings, decided = [], local = false) {
@@ -141,7 +146,7 @@ function reportable(findings, decided = [], local = false) {
141
146
  const entry = decided.find((candidate) => candidate.finding === finding);
142
147
  return {
143
148
  vendor: finding.vendor,
144
- verb: safeVerb(finding.verb),
149
+ verb: safeVerb(finding.verbKey ?? finding.verb),
145
150
  risk: finding.risk,
146
151
  ...(entry?.reported ? { environment: entry.reported } : {}),
147
152
  ...entry?.placement,
@@ -26,7 +26,7 @@ export const CLI_DECIDE_PATH = "/api/my/cli/decide";
26
26
  const MAX_RESPONSE_BYTES = 16 * 1024;
27
27
  const MAX_FINDINGS = 8;
28
28
  const ID = /^[A-Za-z0-9_-]{1,80}$/;
29
- const CAUSE_KINDS = new Set(["block", "grant", "rule", "floor", "preset", "default"]);
29
+ const CAUSE_KINDS = new Set(["access", "block", "grant", "rule", "floor", "preset", "default"]);
30
30
  const CLASSES = new Set(["read", "change", "delete", "irreversible"]);
31
31
  function line(raw, max) {
32
32
  if (typeof raw !== "string")
@@ -17,6 +17,10 @@ export type CliHookReport = {
17
17
  sessionId?: string;
18
18
  toolUseId?: string;
19
19
  cwdName?: string;
20
+ /** The repository's name (never its owner or URL), for grouping sessions. */
21
+ project?: string;
22
+ /** The checked-out branch, when there is one. */
23
+ branch?: string;
20
24
  exitCode?: number;
21
25
  durationMs?: number;
22
26
  findings: ReportedFinding[];
@@ -114,6 +118,8 @@ export type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
114
118
  export declare function profileApi(profile: string, signal: AbortSignal, fetcher: typeof fetch): Promise<ApiCall | null>;
115
119
  /** The report an older server accepts: no Autopilot fields, ask or deny only. */
116
120
  export declare function legacyReport(report: CliHookReport): CliHookReport | null;
121
+ /** The report a server from before project grouping accepts (bridge 0.21.0). */
122
+ export declare function withoutProject(report: CliHookReport): CliHookReport;
117
123
  type Send = (report: CliHookReport) => Promise<void>;
118
124
  /** Deliver reports with the same credential `passport discover` uses. Agent
119
125
  * keys are deliberately unsupported: a hook reports a person's own shell.
@@ -49,11 +49,16 @@ export async function profileApi(profile, signal, fetcher) {
49
49
  export function legacyReport(report) {
50
50
  if (report.decision === "allow")
51
51
  return null;
52
- const { scripts: _scripts, opaqueIds: _ids, projectChanged: _changed, drift: _drift, ...rest } = report;
52
+ const { scripts: _scripts, opaqueIds: _ids, projectChanged: _changed, drift: _drift, ...rest } = withoutProject(report);
53
53
  if (!rest.findings.length && !rest.opaque)
54
54
  return null;
55
55
  return { ...rest, findings: report.findings.map(({ vendor, verb, risk }) => ({ vendor, verb, risk })) };
56
56
  }
57
+ /** The report a server from before project grouping accepts (bridge 0.21.0). */
58
+ export function withoutProject(report) {
59
+ const { project: _project, branch: _branch, ...rest } = report;
60
+ return rest;
61
+ }
57
62
  function hasAutopilotFields(report) {
58
63
  return (report.decision === "allow" ||
59
64
  report.scripts !== undefined ||
@@ -72,8 +77,13 @@ async function postWith(api, report, signal) {
72
77
  body: JSON.stringify(body),
73
78
  signal
74
79
  });
75
- const response = await post(report);
80
+ let response = await post(report);
76
81
  await response.body?.cancel().catch(() => undefined);
82
+ // A server from before project grouping refuses those two fields: send the rest.
83
+ if (response.status === 400 && (report.project !== undefined || report.branch !== undefined)) {
84
+ response = await post(withoutProject(report));
85
+ await response.body?.cancel().catch(() => undefined);
86
+ }
77
87
  // A server that refuses the Autopilot fields still gets the row it knows.
78
88
  const legacy = response.status === 400 && hasAutopilotFields(report) ? legacyReport(report) : null;
79
89
  if (legacy)
@@ -13,7 +13,7 @@
13
13
  * With a v1 policy (an older server) or none at all, the guard keeps its old
14
14
  * shape: ask or deny, never allow.
15
15
  */
16
- import { type ActionClass, type ActionEnv, type Cause, type Decision } from "./cliAutopilotPolicy.js";
16
+ import { type AccessBlock, type ActionClass, type ActionEnv, type Cause, type Decision } from "./cliAutopilotPolicy.js";
17
17
  import type { CliFinding } from "./cliHookClassify.js";
18
18
  import { type EnvSource } from "./cliHookEnvironment.js";
19
19
  import { type LinkFs } from "./envLinkFs.js";
@@ -39,10 +39,7 @@ export type DecidedFinding = {
39
39
  access?: AppAccessBlock;
40
40
  };
41
41
  /** "You don't have access to Railway in Passport. Ask an admin." and the app's Access link. */
42
- export type AppAccessBlock = {
43
- message: string;
44
- link?: string;
45
- };
42
+ export type AppAccessBlock = AccessBlock;
46
43
  export type GuardDecision = {
47
44
  verdict: GuardVerdict;
48
45
  /** The finding that set the verdict, e.g. `railway volume delete`. */
@@ -83,6 +80,16 @@ export declare function guardMachineOf(machine: {
83
80
  }, rawCwd: unknown, env: Record<string, string | undefined>): GuardMachine;
84
81
  /** The words a person needs to recognise the command, never its arguments. */
85
82
  export declare function guardLabel(finding: CliFinding): string;
83
+ /**
84
+ * Read, Change, Delete, or Irreversible: the server's `cliActionClass`, from
85
+ * the tables it serves. A read is a read, whatever lists it. A write is a
86
+ * Change unless a safety pack raises it (`deletes`); anything else is raised.
87
+ * A raised verb is Irreversible where `irreversible` lists it, or
88
+ * `irreversibleInProduction` does and it runs in Production; otherwise a Delete.
89
+ */
90
+ export declare function classOf(policy: CachedCliPolicyV2, finding: CliFinding & {
91
+ vendor: string;
92
+ }, verb: string, environment: ActionEnv): ActionClass;
86
93
  /** One recognized command's decision, or null when Autopilot has no opinion. */
87
94
  export declare function decideFinding(finding: CliFinding, policy: CachedCliPolicyV2, machine?: GuardMachine): DecidedFinding | null;
88
95
  /**
@@ -18,8 +18,7 @@ import { reportedEnvironment } from "./cliHookEnvironment.js";
18
18
  import { placementOf, resolveTarget, targetNote } from "./envResolve.js";
19
19
  import { NODE_LINK_FS } from "./envLinkFs.js";
20
20
  import { normalizeArgv, splitCommands } from "./cliHookParse.js";
21
- import { VENDORS } from "./cliHookVendors.js";
22
- import { IRREVERSIBLE_IN_PRODUCTION } from "./cliHookVendorsMore.js";
21
+ import { VENDORS, vendorKeys } from "./cliHookVendors.js";
23
22
  /** This machine for folder links: the command's folder (canonical, and as
24
23
  * the agent named it), the project, home, and the agent's shell. */
25
24
  export function guardMachineOf(machine, rawCwd, env) {
@@ -49,16 +48,8 @@ const RANK = { allow: 0, ask: 1, deny: 2 };
49
48
  const LABEL_TOKEN = /^-{0,2}[A-Za-z0-9][A-Za-z0-9._:+-]{0,39}$/;
50
49
  /** Shell features that hide what will run. Any of them: no allow. */
51
50
  const OPAQUE_SHELL = /[<>`$\\\n]|\$\(/;
52
- /** Built in, whatever the server sends: these can't be taken back. */
53
- const BUILT_IN_IRREVERSIBLE = { gh: ["repo delete"] };
54
51
  /** Classes the guard decides; anything else (http, api, sql, local) is no decision. */
55
52
  const CLASS_OF_RISK = CLASS_OF_HOOK_RISK;
56
- /** `fly` and `flyctl` share one map; the server may key either spelling. */
57
- function vendorKeys(vendor) {
58
- const spec = Object.hasOwn(VENDORS, vendor) ? VENDORS[vendor] : undefined;
59
- const aliases = spec ? Object.keys(VENDORS).filter((key) => VENDORS[key] === spec && key !== vendor) : [];
60
- return [vendor, ...aliases];
61
- }
62
53
  function policyDecision(policy, vendor, verb) {
63
54
  for (const key of vendorKeys(vendor)) {
64
55
  const verbs = Object.hasOwn(policy.vendors, key) ? policy.vendors[key] : undefined;
@@ -107,6 +98,8 @@ function verdictV1(finding, policy) {
107
98
  return null;
108
99
  const explicit = policy ? policyDecision(policy, finding.vendor, finding.verbKey ?? finding.verb) : undefined;
109
100
  // Built-in default when no policy was ever synced: ask before destructive.
101
+ // Every irreversible verb (the server's irreversible tables) is destructive
102
+ // too, so this covers them without a list of its own.
110
103
  const decision = explicit ?? (finding.risk === "destructive" ? (policy?.default.destructive ?? "ask") : undefined);
111
104
  if (decision === "never")
112
105
  return "deny";
@@ -140,25 +133,25 @@ function listed(map, vendor, verb) {
140
133
  return false;
141
134
  return vendorKeys(vendor).some((key) => Object.hasOwn(map, key) && map[key].includes(verb));
142
135
  }
143
- /** Read, Change, Delete, or Irreversible, as the server's packs define them. */
144
- function classOf(policy, finding, verb, environment) {
136
+ /**
137
+ * Read, Change, Delete, or Irreversible: the server's `cliActionClass`, from
138
+ * the tables it serves. A read is a read, whatever lists it. A write is a
139
+ * Change unless a safety pack raises it (`deletes`); anything else is raised.
140
+ * A raised verb is Irreversible where `irreversible` lists it, or
141
+ * `irreversibleInProduction` does and it runs in Production; otherwise a Delete.
142
+ */
143
+ export function classOf(policy, finding, verb, environment) {
145
144
  const { autopilot } = policy;
146
- // The server's `cliActionClass`: a read is a read, whatever lists it.
147
145
  if (finding.risk === "read")
148
146
  return "read";
149
- if (listed(autopilot.irreversible, finding.vendor, verb) || listed(BUILT_IN_IRREVERSIBLE, finding.vendor, verb)) {
147
+ if (finding.risk === "write" && !listed(autopilot.deletes, finding.vendor, verb))
148
+ return "change";
149
+ if (listed(autopilot.irreversible, finding.vendor, verb))
150
150
  return "irreversible";
151
- }
152
- const productionOnly = listed(autopilot.irreversibleInProduction, finding.vendor, verb) ||
153
- listed(IRREVERSIBLE_IN_PRODUCTION, finding.vendor, verb);
154
- if (environment === "production" && productionOnly) {
151
+ if (environment === "production" && listed(autopilot.irreversibleInProduction, finding.vendor, verb)) {
155
152
  return "irreversible";
156
153
  }
157
- // Force-pushing the default branch rewrites history others already have.
158
- if (finding.vendor === "git" && verb === "push --force" && environment === "production")
159
- return "irreversible";
160
- const base = CLASS_OF_RISK[finding.risk] ?? "delete";
161
- return base === "change" && listed(autopilot.deletes, finding.vendor, verb) ? "delete" : base;
154
+ return "delete";
162
155
  }
163
156
  /** Commands run as administrator never run silently. */
164
157
  const SUDO_CAUSE = { kind: "default", label: "Commands run with sudo always ask" };
@@ -176,6 +169,7 @@ function decideLocal(finding, policy) {
176
169
  finding,
177
170
  decision: sudo ? "ask" : decided.decision,
178
171
  cause: sudo ? SUDO_CAUSE : decided.cause,
172
+ ...(decided.access ? { access: decided.access } : {}),
179
173
  environment: facts.environment,
180
174
  environmentSource: "flag",
181
175
  reported: facts.environment,
@@ -187,7 +181,7 @@ function decideLocal(finding, policy) {
187
181
  * repository's own `.passport/actions.toml` may only ask or block. */
188
182
  function decideProject(finding, policy) {
189
183
  const facts = finding.project;
190
- const { decision, cause } = decideAction(policy.autopilot, {
184
+ const { decision, cause, access } = decideAction(policy.autopilot, {
191
185
  vendor: "project",
192
186
  verb: finding.verb,
193
187
  actionClass: facts.actionClass,
@@ -199,6 +193,7 @@ function decideProject(finding, policy) {
199
193
  finding,
200
194
  decision,
201
195
  cause,
196
+ ...(access ? { access } : {}),
202
197
  environment: facts.environment,
203
198
  environmentSource: "mapping",
204
199
  reported: facts.environment,
@@ -231,27 +226,20 @@ export function decideFinding(finding, policy, machine) {
231
226
  : target;
232
227
  const verb = finding.verbKey ?? finding.verb;
233
228
  const actionClass = classOf(policy, finding, verb, hint.kind);
234
- const ruled = decideAction(policy.autopilot, {
229
+ // The access ceiling comes first inside the engine: No access blocks every
230
+ // command, Read-only runs only reads (the same as exec).
231
+ const { decision, cause, access } = decideAction(policy.autopilot, {
235
232
  vendor: finding.vendor,
236
233
  verb,
237
234
  actionClass,
238
235
  environment: hint.kind
239
236
  });
240
- // The person's pass for the app this CLI acts on comes first: No access
241
- // blocks every command, Read-only runs only reads (the same as exec).
242
- const pass = Object.hasOwn(policy.autopilot.appAccess ?? {}, finding.vendor)
243
- ? policy.autopilot.appAccess[finding.vendor]
244
- : undefined;
245
- const limited = pass && (pass.pass === "none" || (pass.pass === "readonly" && actionClass !== "read"));
246
- const { decision, cause } = limited
247
- ? { decision: "block", cause: { kind: "block", label: pass.cause } }
248
- : ruled;
249
237
  const reported = finding.pushEnvironment ?? reportedEnvironment(hint);
250
238
  return {
251
239
  finding,
252
240
  decision,
253
241
  cause,
254
- ...(limited ? { access: { message: pass.message, ...(pass.link ? { link: pass.link } : {}) } } : {}),
242
+ ...(access ? { access } : {}),
255
243
  environment: hint.kind,
256
244
  environmentSource: hint.source,
257
245
  ...(reported ? { reported } : {}),
@@ -402,6 +390,9 @@ export function denyMessage(decision, owner) {
402
390
  // The app's access, in the words exec uses, with where an admin changes it.
403
391
  if (decision.access)
404
392
  return decision.access.link ? `${decision.access.message} ${decision.access.link}` : decision.access.message;
393
+ // The server's access block without its message: no rule or exception lifts it.
394
+ if (decision.cause?.kind === "access")
395
+ return `${decision.cause.label}. Ask an admin for access.`;
405
396
  if (decision.cause) {
406
397
  const mine = decision.cause.label.startsWith("Your rule");
407
398
  const next = mine
@@ -57,6 +57,18 @@ export declare function localMachine(cwd: unknown, env?: Record<string, string |
57
57
  export declare function placeOfPath(path: string, machine: LocalMachine): Place;
58
58
  /** The path a word names, relative to `cwd`; null when it can't be known. */
59
59
  export declare function resolveWord(word: ShellWord, cwd: string | null, machine: LocalMachine): string | null;
60
+ export declare function readRef(text: string | null, prefix: string): string | null;
61
+ /**
62
+ * Where a repository keeps its data, read from the files git itself writes:
63
+ * the checkout's root, its own git folder (a worktree's lives under the main
64
+ * repository's `.git/worktrees/`), and the common folder every worktree of
65
+ * that repository shares. Null outside a repository.
66
+ */
67
+ export declare function gitLayout(dir: string, fs: LocalFs): {
68
+ root: string;
69
+ gitDir: string;
70
+ commonDir: string;
71
+ } | null;
60
72
  /** The current and default branch of the repository holding `dir`. */
61
73
  export declare function gitBranches(dir: string, fs: LocalFs): {
62
74
  current: string | null;
@@ -319,25 +319,38 @@ export function resolveWord(word, cwd, machine) {
319
319
  return canonical(base, machine.fs);
320
320
  return posix.join(canonical(base, machine.fs), "x");
321
321
  }
322
- function readRef(text, prefix) {
322
+ export function readRef(text, prefix) {
323
323
  const match = text ? /^ref:\s*(\S+)/.exec(text.trim()) : null;
324
324
  return match && match[1].startsWith(prefix) ? match[1].slice(prefix.length) : null;
325
325
  }
326
- /** The current and default branch of the repository holding `dir`. */
327
- export function gitBranches(dir, fs) {
326
+ /**
327
+ * Where a repository keeps its data, read from the files git itself writes:
328
+ * the checkout's root, its own git folder (a worktree's lives under the main
329
+ * repository's `.git/worktrees/`), and the common folder every worktree of
330
+ * that repository shares. Null outside a repository.
331
+ */
332
+ export function gitLayout(dir, fs) {
328
333
  const root = gitRoot(dir, fs);
329
334
  if (!root)
330
- return { current: null, defaultBranch: null };
335
+ return null;
331
336
  const marker = posix.join(root, ".git");
332
337
  let gitDir = marker;
333
338
  if (fs.isFile(marker)) {
334
339
  const pointer = /^gitdir:\s*(.+)$/m.exec(fs.readText(marker) ?? "")?.[1]?.trim();
335
340
  if (!pointer)
336
- return { current: null, defaultBranch: null };
337
- gitDir = pointer.startsWith("/") ? pointer : posix.join(root, pointer);
341
+ return null;
342
+ gitDir = posix.normalize(pointer.startsWith("/") ? pointer : posix.join(root, pointer));
338
343
  }
339
344
  const common = fs.readText(posix.join(gitDir, "commondir"))?.trim();
340
- const commonDir = common ? (common.startsWith("/") ? common : posix.join(gitDir, common)) : gitDir;
345
+ const commonDir = common ? posix.normalize(common.startsWith("/") ? common : posix.join(gitDir, common)) : gitDir;
346
+ return { root, gitDir, commonDir };
347
+ }
348
+ /** The current and default branch of the repository holding `dir`. */
349
+ export function gitBranches(dir, fs) {
350
+ const layout = gitLayout(dir, fs);
351
+ if (!layout)
352
+ return { current: null, defaultBranch: null };
353
+ const { gitDir, commonDir } = layout;
341
354
  return {
342
355
  current: readRef(fs.readText(posix.join(gitDir, "HEAD")), "refs/heads/"),
343
356
  defaultBranch: readRef(fs.readText(posix.join(commonDir, "refs/remotes/origin/HEAD")), "refs/remotes/origin/")
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Which project and branch an agent's command runs in, for grouping sessions
3
+ * by project. Read from the files git writes (no `git` process, no network),
4
+ * once per folder per process, and never throws.
5
+ *
6
+ * - project: the repository's name from its `origin` remote (the last path
7
+ * segment without `.git`; never the owner, host, or full URL), else the
8
+ * main checkout's folder name (so a worktree maps to its repository), else
9
+ * the working folder's own name.
10
+ * - branch: the checked-out branch; nothing for a detached HEAD.
11
+ *
12
+ * Outside a repository there is neither; the server falls back to the folder.
13
+ */
14
+ import { type LocalFs } from "./cliHookLocal.js";
15
+ export type ProjectInfo = {
16
+ project?: string;
17
+ branch?: string;
18
+ };
19
+ /** What this reads from the machine. Injected so tests never touch it. */
20
+ export type ProjectFs = Pick<LocalFs, "isDirectory" | "isFile" | "readText"> & {
21
+ /** The repository's config, which can be larger than `readText` allows. */
22
+ readConfig?(path: string): string | null;
23
+ };
24
+ export declare const MAX_PROJECT = 80;
25
+ export declare const MAX_BRANCH = 120;
26
+ /**
27
+ * The repository name in a remote URL: `git@github.com:acme/api.git`,
28
+ * `https://github.com/acme/api`, `ssh://git@host:22/acme/api.git/`, or a
29
+ * local path. Query strings and fragments are dropped, so a token in one
30
+ * never comes through.
31
+ */
32
+ export declare function repoNameFromUrl(url: string): string | undefined;
33
+ /** The `url` of `[remote "origin"]` in a git config. */
34
+ export declare function originUrl(config: string): string | undefined;
35
+ /** Detect without caching. Exported for tests. */
36
+ export declare function detectProject(cwd: string, fs: ProjectFs): ProjectInfo;
37
+ /**
38
+ * The project and branch for an agent's working folder, cached per folder
39
+ * for this process. Empty for anything but an absolute path, outside a
40
+ * repository, or on any error.
41
+ */
42
+ export declare function projectOf(cwd: unknown, fs?: ProjectFs): ProjectInfo;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Which project and branch an agent's command runs in, for grouping sessions
3
+ * by project. Read from the files git writes (no `git` process, no network),
4
+ * once per folder per process, and never throws.
5
+ *
6
+ * - project: the repository's name from its `origin` remote (the last path
7
+ * segment without `.git`; never the owner, host, or full URL), else the
8
+ * main checkout's folder name (so a worktree maps to its repository), else
9
+ * the working folder's own name.
10
+ * - branch: the checked-out branch; nothing for a detached HEAD.
11
+ *
12
+ * Outside a repository there is neither; the server falls back to the folder.
13
+ */
14
+ import { closeSync, openSync, readSync } from "node:fs";
15
+ import { posix } from "node:path";
16
+ import { gitLayout, NODE_FS, readRef } from "./cliHookLocal.js";
17
+ export const MAX_PROJECT = 80;
18
+ export const MAX_BRANCH = 120;
19
+ /** A config's `origin` section sits near the top; this is plenty. */
20
+ const CONFIG_BYTES = 64 * 1024;
21
+ const CACHE_LIMIT = 64;
22
+ function readHead(path) {
23
+ let descriptor;
24
+ try {
25
+ descriptor = openSync(path, "r");
26
+ const buffer = Buffer.alloc(CONFIG_BYTES);
27
+ const read = readSync(descriptor, buffer, 0, CONFIG_BYTES, 0);
28
+ return buffer.toString("utf8", 0, read);
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ finally {
34
+ if (descriptor !== undefined)
35
+ closeSync(descriptor);
36
+ }
37
+ }
38
+ const NODE_PROJECT_FS = { ...NODE_FS, readConfig: readHead };
39
+ /** One line of text: no control characters, trimmed, bounded. */
40
+ function clean(value, max) {
41
+ if (typeof value !== "string")
42
+ return undefined;
43
+ const cleaned = value
44
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
45
+ .trim()
46
+ .slice(0, max)
47
+ .trim();
48
+ return cleaned || undefined;
49
+ }
50
+ /** A name, never a path: the last segment, without a `.git` suffix. */
51
+ function nameOf(value) {
52
+ if (!value)
53
+ return undefined;
54
+ const trimmed = value.replace(/[\\/]+$/, "");
55
+ const segment = trimmed.slice(Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"), trimmed.lastIndexOf(":")) + 1);
56
+ const name = clean(segment.replace(/\.git$/i, ""), MAX_PROJECT);
57
+ return name && name !== "." && name !== ".." ? name : undefined;
58
+ }
59
+ /**
60
+ * The repository name in a remote URL: `git@github.com:acme/api.git`,
61
+ * `https://github.com/acme/api`, `ssh://git@host:22/acme/api.git/`, or a
62
+ * local path. Query strings and fragments are dropped, so a token in one
63
+ * never comes through.
64
+ */
65
+ export function repoNameFromUrl(url) {
66
+ const bare = url.trim().replace(/[?#].*$/, "");
67
+ return nameOf(bare);
68
+ }
69
+ /** The `url` of `[remote "origin"]` in a git config. */
70
+ export function originUrl(config) {
71
+ let inOrigin = false;
72
+ for (const raw of config.split(/\r?\n/)) {
73
+ const line = raw.trim();
74
+ if (!line || line.startsWith("#") || line.startsWith(";"))
75
+ continue;
76
+ const section = /^\[\s*([^\]\s"]+)(?:\s+"([^"]*)")?\s*\]/.exec(line);
77
+ if (section) {
78
+ inOrigin = section[1].toLowerCase() === "remote" && section[2] === "origin";
79
+ continue;
80
+ }
81
+ if (!inOrigin)
82
+ continue;
83
+ const entry = /^url\s*=\s*(.*)$/i.exec(line);
84
+ if (entry) {
85
+ const value = entry[1].replace(/^"(.*)"$/, "$1").trim();
86
+ if (value)
87
+ return value;
88
+ }
89
+ }
90
+ return undefined;
91
+ }
92
+ /** The main checkout's folder name: `/code/api/.git` → "api"; a bare `api.git` → "api". */
93
+ function commonName(commonDir) {
94
+ const dir = commonDir.replace(/\/+$/, "");
95
+ return posix.basename(dir) === ".git" ? nameOf(posix.dirname(dir)) : nameOf(dir);
96
+ }
97
+ /** Detect without caching. Exported for tests. */
98
+ export function detectProject(cwd, fs) {
99
+ const layout = gitLayout(posix.normalize(cwd), fs);
100
+ if (!layout)
101
+ return {};
102
+ const configPath = posix.join(layout.commonDir, "config");
103
+ const config = fs.readConfig ? fs.readConfig(configPath) : fs.readText(configPath);
104
+ const remote = config ? originUrl(config) : undefined;
105
+ const project = (remote && repoNameFromUrl(remote)) ?? commonName(layout.commonDir) ?? nameOf(cwd);
106
+ const branch = clean(readRef(fs.readText(posix.join(layout.gitDir, "HEAD")), "refs/heads/"), MAX_BRANCH);
107
+ return { ...(project ? { project } : {}), ...(branch ? { branch } : {}) };
108
+ }
109
+ const cache = new Map();
110
+ /**
111
+ * The project and branch for an agent's working folder, cached per folder
112
+ * for this process. Empty for anything but an absolute path, outside a
113
+ * repository, or on any error.
114
+ */
115
+ export function projectOf(cwd, fs = NODE_PROJECT_FS) {
116
+ if (typeof cwd !== "string" || !cwd.startsWith("/") || cwd.length > 4096)
117
+ return {};
118
+ const cached = fs === NODE_PROJECT_FS ? cache.get(cwd) : undefined;
119
+ if (cached)
120
+ return cached;
121
+ let info = {};
122
+ try {
123
+ info = detectProject(cwd, fs);
124
+ }
125
+ catch {
126
+ info = {};
127
+ }
128
+ if (fs === NODE_PROJECT_FS) {
129
+ if (cache.size >= CACHE_LIMIT)
130
+ cache.delete(cache.keys().next().value);
131
+ cache.set(cwd, info);
132
+ }
133
+ return info;
134
+ }
@@ -20,4 +20,7 @@ export type VendorSpec = {
20
20
  opTokenRisk?: Record<string, CliRisk>;
21
21
  };
22
22
  export declare const VENDORS: Record<string, VendorSpec>;
23
+ /** A vendor and its aliases: `fly` and `flyctl` share one map, and the server
24
+ * may key either spelling. The vendor itself comes first. */
25
+ export declare function vendorKeys(vendor: string): string[];
23
26
  export declare const NPX_PACKAGE_TO_VENDOR: Record<string, string>;
@@ -570,6 +570,13 @@ VENDORS.fly = VENDORS.flyctl;
570
570
  VENDORS.neon = VENDORS.neonctl;
571
571
  VENDORS.tf = VENDORS.terraform;
572
572
  VENDORS.k = VENDORS.kubectl;
573
+ /** A vendor and its aliases: `fly` and `flyctl` share one map, and the server
574
+ * may key either spelling. The vendor itself comes first. */
575
+ export function vendorKeys(vendor) {
576
+ const spec = Object.hasOwn(VENDORS, vendor) ? VENDORS[vendor] : undefined;
577
+ const aliases = spec ? Object.keys(VENDORS).filter((key) => VENDORS[key] === spec && key !== vendor) : [];
578
+ return [vendor, ...aliases];
579
+ }
573
580
  // npx / bunx / pnpm dlx / yarn dlx package-name -> vendor name
574
581
  export const NPX_PACKAGE_TO_VENDOR = {
575
582
  vercel: "vercel",
@@ -4,8 +4,9 @@
4
4
  * connection string. Same shape and meaning as `cliHookVendors.ts`: each risk
5
5
  * describes what the verb does, never what Passport permits.
6
6
  *
7
- * Database verbs that throw data away are destructive (a Delete); dropping a
8
- * Production database can't be undone (see `IRREVERSIBLE_IN_PRODUCTION`).
7
+ * Database verbs that throw data away are destructive (a Delete). Which of
8
+ * them can't be undone in Production (dropping a database) comes from the
9
+ * server's irreversible tables in cli-policy v2, never from this file.
9
10
  */
10
11
  /** The same shape as `VendorSpec` in cliHookVendors.ts (kept local: no import cycle). */
11
12
  type Risk = "read" | "write" | "destructive" | "local";
@@ -16,6 +17,4 @@ type VendorSpec = {
16
17
  export declare const MORE_VENDORS: Record<string, VendorSpec>;
17
18
  /** npx / bunx / pnpm dlx package names for these CLIs. */
18
19
  export declare const MORE_NPX_PACKAGES: Record<string, string>;
19
- /** Verbs that can't be taken back when they run against Production. */
20
- export declare const IRREVERSIBLE_IN_PRODUCTION: Record<string, string[]>;
21
20
  export {};
@@ -4,8 +4,9 @@
4
4
  * connection string. Same shape and meaning as `cliHookVendors.ts`: each risk
5
5
  * describes what the verb does, never what Passport permits.
6
6
  *
7
- * Database verbs that throw data away are destructive (a Delete); dropping a
8
- * Production database can't be undone (see `IRREVERSIBLE_IN_PRODUCTION`).
7
+ * Database verbs that throw data away are destructive (a Delete). Which of
8
+ * them can't be undone in Production (dropping a database) comes from the
9
+ * server's irreversible tables in cli-policy v2, never from this file.
9
10
  */
10
11
  const RAILS_DB = {
11
12
  "db:migrate": "write",
@@ -187,10 +188,3 @@ export const MORE_NPX_PACKAGES = {
187
188
  knex: "knex",
188
189
  "sequelize-cli": "sequelize"
189
190
  };
190
- /** Verbs that can't be taken back when they run against Production. */
191
- export const IRREVERSIBLE_IN_PRODUCTION = {
192
- rails: ["db:drop"],
193
- rake: ["db:drop"],
194
- sequelize: ["db:drop"],
195
- psql: ["drop database"]
196
- };
@@ -14,7 +14,7 @@ export type ShimDependencies = {
14
14
  };
15
15
  /** A shim as JSON: no home-folder paths beyond Passport's own. */
16
16
  export declare function shimJson(shim: ShimInfo): {
17
- vendor: "railway" | "wrangler" | "vercel" | "flyctl" | "supabase" | "aws" | "stripe" | "gh" | "neonctl";
17
+ vendor: "railway" | "wrangler" | "vercel" | "flyctl" | "supabase" | "aws" | "stripe" | "neonctl" | "gh";
18
18
  command: string;
19
19
  state: import("./execShims.js").ShimState;
20
20
  path: string;
@@ -169,6 +169,7 @@ function offline(value) {
169
169
  return out;
170
170
  }
171
171
  const PASSES = new Set(["full", "readonly", "none"]);
172
+ const MAX_ACCESS = 128;
172
173
  /** An absolute http(s) link, or undefined. */
173
174
  function webLink(value) {
174
175
  if (typeof value !== "string" || value.length > 300 || /[\u0000- \u007f]/.test(value))
@@ -181,8 +182,53 @@ function webLink(value) {
181
182
  return undefined;
182
183
  }
183
184
  }
184
- /** `appAccess` by vendor: absent is none at all, anything malformed rejects the document. */
185
- function appAccess(value) {
185
+ /** One ceiling record's words: the server's, or the same words built from the app's name. */
186
+ function accessRecord(vendor, appKey, pass, body) {
187
+ const app = printable(body.app, 80);
188
+ if (!app)
189
+ return null;
190
+ const cause = printable(body.cause, 160) || `${pass === "none" ? "No access" : "Read-only access"} to ${app} in Passport`;
191
+ const link = webLink(body.link);
192
+ return {
193
+ layer: "access",
194
+ vendor,
195
+ appKey,
196
+ app,
197
+ pass,
198
+ cause,
199
+ message: printable(body.message, 240) || `${cause}.`,
200
+ ...(link ? { link } : {})
201
+ };
202
+ }
203
+ /** `access`, the ceiling records: absent is none at all, anything malformed rejects the document. */
204
+ function access(value) {
205
+ if (value === undefined)
206
+ return undefined;
207
+ if (!Array.isArray(value) || value.length > MAX_ACCESS)
208
+ return null;
209
+ const out = [];
210
+ for (const raw of value) {
211
+ const body = plainObject(raw);
212
+ if (!body || body.layer !== "access")
213
+ return null;
214
+ const { vendor, appKey, pass } = body;
215
+ if (typeof vendor !== "string" || !VENDOR_KEY.test(vendor) || UNSAFE_KEYS.has(vendor))
216
+ return null;
217
+ if (typeof appKey !== "string" || !VENDOR_KEY.test(appKey))
218
+ return null;
219
+ if (pass !== "none" && pass !== "readonly")
220
+ return null;
221
+ const record = accessRecord(vendor, appKey, pass, body);
222
+ if (!record)
223
+ return null;
224
+ out.push(record);
225
+ }
226
+ return out;
227
+ }
228
+ /** An older server's `appAccess` map (bridges up to 0.19), as ceiling records:
229
+ * the vendors whose pass is not full. The map doesn't name the app's key, so
230
+ * the vendor stands in. Anything malformed rejects the document, as before. */
231
+ function legacyAccess(value) {
186
232
  if (value === undefined)
187
233
  return undefined;
188
234
  const body = plainObject(value);
@@ -191,24 +237,19 @@ function appAccess(value) {
191
237
  const entries = Object.entries(body);
192
238
  if (entries.length > MAX_VENDORS)
193
239
  return null;
194
- const out = {};
240
+ const out = [];
195
241
  for (const [vendor, raw] of entries) {
196
242
  const entry = plainObject(raw);
197
243
  if (!VENDOR_KEY.test(vendor) || UNSAFE_KEYS.has(vendor) || !entry || !PASSES.has(entry.pass))
198
244
  return null;
199
- const pass = entry.pass;
200
- const app = printable(entry.app, 80);
201
- if (!app)
245
+ if (!printable(entry.app, 80))
246
+ return null;
247
+ if (entry.pass === "full")
248
+ continue;
249
+ const record = accessRecord(vendor, vendor, entry.pass, entry);
250
+ if (!record)
202
251
  return null;
203
- const cause = printable(entry.cause, 160) || `${pass === "none" ? "No access" : "Read-only access"} to ${app} in Passport`;
204
- const link = webLink(entry.link);
205
- out[vendor] = {
206
- pass,
207
- app,
208
- cause,
209
- message: printable(entry.message, 240) || `${cause}.`,
210
- ...(link ? { link } : {})
211
- };
252
+ out.push(record);
212
253
  }
213
254
  return out;
214
255
  }
@@ -385,7 +426,7 @@ export function serializeCliPolicyV2(policy) {
385
426
  })),
386
427
  ...(autopilot.secondPerson ? { secondPerson: autopilot.secondPerson } : {}),
387
428
  ...(autopilot.offline ? { offline: autopilot.offline } : {}),
388
- ...(autopilot.appAccess ? { appAccess: autopilot.appAccess } : {}),
429
+ ...(autopilot.access ? { access: autopilot.access } : {}),
389
430
  irreversible: autopilot.irreversible,
390
431
  irreversibleInProduction: autopilot.irreversibleInProduction ?? {},
391
432
  deletes: autopilot.deletes ?? {},
@@ -439,8 +480,9 @@ export function parseCliPolicyV2(value) {
439
480
  const knownProject = project(body.project);
440
481
  if (knownProject === null)
441
482
  return null;
442
- const access = appAccess(body.appAccess);
443
- if (access === null)
483
+ // The ceiling records; an older server sends only the `appAccess` map.
484
+ const ceiling = body.access !== undefined ? access(body.access) : legacyAccess(body.appAccess);
485
+ if (ceiling === null)
444
486
  return null;
445
487
  return {
446
488
  version: 2,
@@ -461,7 +503,7 @@ export function parseCliPolicyV2(value) {
461
503
  ...(body.speed === true ? { reportsSpeed: true } : {}),
462
504
  ...(parsedSecondPerson?.classes.length ? { secondPerson: parsedSecondPerson } : {}),
463
505
  ...(offline(body.offline) ? { offline: offline(body.offline) } : {}),
464
- ...(access && Object.keys(access).length ? { appAccess: access } : {}),
506
+ ...(ceiling?.length ? { access: ceiling } : {}),
465
507
  ...(knownProject ? { project: knownProject } : {})
466
508
  }
467
509
  };
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * `passport sessions [--status running|idle|ended]`: your agents' recent
3
- * sessions with what Passport decided. On a terminal the rows line up when
4
- * they fit and stack one session at a time when they don't; piped output
5
- * keeps its fixed format.
3
+ * sessions with what Passport decided. Running sessions come first, under
4
+ * their project ("mcp-passport · 2 running"); ended ones follow. On a
5
+ * terminal the rows line up when they fit and stack one session at a time
6
+ * when they don't; piped output keeps its fixed format.
6
7
  */
7
8
  import { type ParsedArgs } from "./cliArgs.js";
8
9
  import { type AutopilotDependencies } from "./cliAutopilot.js";
@@ -12,6 +13,8 @@ type SessionRow = {
12
13
  id?: unknown;
13
14
  client?: unknown;
14
15
  folder?: unknown;
16
+ project?: unknown;
17
+ branch?: unknown;
15
18
  status?: unknown;
16
19
  startedAt?: unknown;
17
20
  lastActivityAt?: unknown;
@@ -25,11 +28,22 @@ type SessionRow = {
25
28
  environments?: unknown;
26
29
  waiting?: unknown;
27
30
  };
28
- /** One session's cells, for the terminal table: status, agent, folder,
29
- * started, counts, and environments with what's waiting. */
31
+ /** Sessions that reported no project or folder (app connections). */
32
+ export declare const NO_PROJECT = "No project";
33
+ /** A checked copy of shared/autopilotContract.ts sessionProject (the CLI
34
+ * can't import shared/): the repository, else the folder's name. */
35
+ export declare function projectOf(row: SessionRow): string | undefined;
36
+ /** One session's cells, for the terminal table: status, agent, branch (or
37
+ * folder), started, counts, and environments with what's waiting. Ended rows
38
+ * name their project too, since no group heading does. */
30
39
  export declare function sessionCells(row: SessionRow, now: number, unicode?: boolean): string[];
40
+ /** Running sessions under their project, busiest-latest first; then the rest. */
41
+ export declare function sessionSections(rows: SessionRow[]): Array<{
42
+ heading: string;
43
+ rows: SessionRow[];
44
+ }>;
31
45
  /** Sessions on a terminal, every one laid out the same way: its state, agent,
32
- * and folder; then when it started, what Passport decided, and where, broken
46
+ * and branch; then when it started, what Passport decided, and where, broken
33
47
  * only between those parts; then its link. */
34
48
  export declare function sessionTable(rows: SessionRow[], links: Array<string | null>, now: number, term: Term): string[];
35
49
  export declare function sessionLine(row: SessionRow, now: number, unicode?: boolean): string;
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * `passport sessions [--status running|idle|ended]`: your agents' recent
3
- * sessions with what Passport decided. On a terminal the rows line up when
4
- * they fit and stack one session at a time when they don't; piped output
5
- * keeps its fixed format.
3
+ * sessions with what Passport decided. Running sessions come first, under
4
+ * their project ("mcp-passport · 2 running"); ended ones follow. On a
5
+ * terminal the rows line up when they fit and stack one session at a time
6
+ * when they don't; piped output keeps its fixed format.
6
7
  */
7
8
  import { value } from "./cliArgs.js";
8
9
  import { api, json } from "./cliAutopilot.js";
@@ -24,6 +25,8 @@ const CLIENT_NAMES = {
24
25
  cli: "Passport CLI",
25
26
  terminal: "Passport CLI"
26
27
  };
28
+ /** Sessions that reported no project or folder (app connections). */
29
+ export const NO_PROJECT = "No project";
27
30
  function count(raw) {
28
31
  return typeof raw === "number" && Number.isFinite(raw) && raw >= 0 ? Math.trunc(raw) : 0;
29
32
  }
@@ -35,8 +38,29 @@ function when(ms, now) {
35
38
  const time = date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
36
39
  return sameDay ? time : `${date.toLocaleDateString("en-US", { month: "short", day: "numeric" })} ${time}`;
37
40
  }
38
- /** One session's cells, for the terminal table: status, agent, folder,
39
- * started, counts, and environments with what's waiting. */
41
+ /** The folder's last segment ("/Users/x/code/api" → "api"). */
42
+ function folderName(raw) {
43
+ const folder = (text(raw, 400) ?? "").replace(/[\\/]+$/, "");
44
+ return text(folder.slice(Math.max(folder.lastIndexOf("/"), folder.lastIndexOf("\\")) + 1), 40);
45
+ }
46
+ /** A checked copy of shared/autopilotContract.ts sessionProject (the CLI
47
+ * can't import shared/): the repository, else the folder's name. */
48
+ export function projectOf(row) {
49
+ return text(row.project, 40) ?? folderName(row.folder);
50
+ }
51
+ /** What a row is called: its branch, else its folder. */
52
+ function placeOf(row) {
53
+ return text(row.branch, 60) ?? folderName(row.folder) ?? "";
54
+ }
55
+ function environmentsOf(row) {
56
+ return Array.isArray(row.environments) ? row.environments.filter(isEnvKind).map((env) => ENV_LABEL[env]) : [];
57
+ }
58
+ function running(row) {
59
+ return row.status === "running" || row.status === "idle";
60
+ }
61
+ /** One session's cells, for the terminal table: status, agent, branch (or
62
+ * folder), started, counts, and environments with what's waiting. Ended rows
63
+ * name their project too, since no group heading does. */
40
64
  export function sessionCells(row, now, unicode = true) {
41
65
  const status = row.status === "running" ? "Running" : row.status === "idle" ? "Idle" : "Ended";
42
66
  const dot = row.status === "running" ? (unicode ? "● " : "* ") : unicode ? "– " : "- ";
@@ -45,21 +69,38 @@ export function sessionCells(row, now, unicode = true) {
45
69
  const parts = [`${count(counts.ran)} ran`, `${count(counts.asked)} asked`];
46
70
  if (count(counts.blocked))
47
71
  parts.push(`${count(counts.blocked)} blocked`);
48
- const environments = Array.isArray(row.environments)
49
- ? row.environments.filter(isEnvKind).map((env) => ENV_LABEL[env])
50
- : [];
72
+ const environments = environmentsOf(row);
51
73
  const waiting = count(row.waiting) ? `Waiting for you (${count(row.waiting)})` : "";
74
+ const project = projectOf(row);
75
+ const place = placeOf(row);
76
+ const where = !running(row) && project && text(row.branch, 60)
77
+ ? `${project} ${unicode ? "›" : ">"} ${place}`
78
+ : place || (running(row) ? "" : (project ?? ""));
52
79
  return [
53
80
  `${dot}${status}`,
54
81
  CLIENT_NAMES[client] ?? client,
55
- text(row.folder, 40) ?? "",
82
+ where,
56
83
  `started ${when(row.startedAt, now)}`,
57
84
  parts.join(" · "),
58
85
  [environments.join(", "), waiting].filter(Boolean).join(" · ")
59
86
  ];
60
87
  }
88
+ /** Running sessions under their project, busiest-latest first; then the rest. */
89
+ export function sessionSections(rows) {
90
+ const latest = (row) => (typeof row.lastActivityAt === "number" ? row.lastActivityAt : 0);
91
+ const groups = new Map();
92
+ for (const row of rows.filter(running).sort((a, b) => latest(b) - latest(a))) {
93
+ const key = projectOf(row) ?? NO_PROJECT;
94
+ groups.set(key, [...(groups.get(key) ?? []), row]);
95
+ }
96
+ const ended = rows.filter((row) => !running(row));
97
+ return [
98
+ ...[...groups].map(([project, members]) => ({ heading: `${project} · ${members.length} running`, rows: members })),
99
+ ...(ended.length ? [{ heading: "Ended", rows: ended }] : [])
100
+ ];
101
+ }
61
102
  /** Sessions on a terminal, every one laid out the same way: its state, agent,
62
- * and folder; then when it started, what Passport decided, and where, broken
103
+ * and branch; then when it started, what Passport decided, and where, broken
63
104
  * only between those parts; then its link. */
64
105
  export function sessionTable(rows, links, now, term) {
65
106
  const cells = rows.map((row) => sessionCells(row, now, term.unicode));
@@ -78,31 +119,23 @@ export function sessionTable(rows, links, now, term) {
78
119
  });
79
120
  }
80
121
  export function sessionLine(row, now, unicode = true) {
81
- const status = row.status === "running" ? "Running" : row.status === "idle" ? "Idle" : "Ended";
82
- const dot = row.status === "running" ? (unicode ? "● " : "* ") : unicode ? "– " : "- ";
83
- const client = text(row.client, 40) ?? "agent";
84
- const name = CLIENT_NAMES[client] ?? client;
85
- const folder = text(row.folder, 40) ?? "";
86
- const counts = row.counts ?? {};
87
- const parts = [`${count(counts.ran)} ran`, `${count(counts.asked)} asked`];
88
- if (count(counts.blocked))
89
- parts.push(`${count(counts.blocked)} blocked`);
90
- const environments = Array.isArray(row.environments)
91
- ? row.environments.filter(isEnvKind).map((env) => ENV_LABEL[env])
92
- : [];
122
+ const [state = "", name = "", where = "", started = "", counts = ""] = sessionCells(row, now, unicode);
93
123
  const waiting = count(row.waiting) ? ` Waiting for you (${count(row.waiting)})` : "";
94
- return [
95
- `${dot}${status.padEnd(7)}`,
96
- name.padEnd(12),
97
- folder.padEnd(18),
98
- `started ${when(row.startedAt, now)}`.padEnd(18),
99
- parts.join(" · "),
100
- environments.length ? ` ${environments.join(", ")}` : ""
101
- ]
124
+ const envs = environmentsOf(row).join(", ");
125
+ return [state.padEnd(9), name.padEnd(12), where.padEnd(18), started.padEnd(18), counts, envs ? ` ${envs}` : ""]
102
126
  .join(" ")
103
127
  .trimEnd()
104
128
  .concat(waiting);
105
129
  }
130
+ /** Every section: its heading, then its rows, with a blank line between. */
131
+ function render(rows, links, now, rowsOf) {
132
+ return sessionSections(rows)
133
+ .map((section) => {
134
+ const sectionLinks = section.rows.map((row) => links[rows.indexOf(row)] ?? null);
135
+ return [section.heading, ...rowsOf(section.rows, sectionLinks)].join("\n");
136
+ })
137
+ .join("\n\n");
138
+ }
106
139
  export async function sessions(args, runtime, deps = {}) {
107
140
  const status = value(args, "status");
108
141
  if (status !== undefined && !["running", "idle", "ended"].includes(status)) {
@@ -123,9 +156,7 @@ export async function sessions(args, runtime, deps = {}) {
123
156
  const human = !rows.length
124
157
  ? "No sessions yet. Start your agent and its actions will show up here."
125
158
  : term.tty
126
- ? sessionTable(rows, links, now, term).join("\n")
127
- : rows
128
- .map((row, index) => links[index] ? `${sessionLine(row, now)}\n ${links[index]}` : sessionLine(row, now))
129
- .join("\n");
159
+ ? render(rows, links, now, (section, sectionLinks) => sessionTable(section, sectionLinks, now, term))
160
+ : render(rows, links, now, (section, sectionLinks) => section.map((row, index) => sectionLinks[index] ? `${sessionLine(row, now)}\n ${sectionLinks[index]}` : sessionLine(row, now)));
130
161
  return { json: { sessions: rows, nextCursor: page.nextCursor ?? null }, human };
131
162
  }
@@ -4,4 +4,4 @@
4
4
  * the version, then runs `npm run set-version -- <version>` in the plugin repo
5
5
  * and pushes (docs/RELEASING.md). `pluginPin.test.ts` fails when it drifts.
6
6
  */
7
- export declare const PLUGIN_PIN = "0.19.0";
7
+ export declare const PLUGIN_PIN = "0.21.0";
package/dist/pluginPin.js CHANGED
@@ -4,4 +4,4 @@
4
4
  * the version, then runs `npm run set-version -- <version>` in the plugin repo
5
5
  * and pushes (docs/RELEASING.md). `pluginPin.test.ts` fails when it drifts.
6
6
  */
7
- export const PLUGIN_PIN = "0.19.0";
7
+ export const PLUGIN_PIN = "0.21.0";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.19.0";
1
+ export declare const VERSION = "0.21.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Keep in lockstep with bridge/package.json.
2
- export const VERSION = "0.19.0";
2
+ export const VERSION = "0.21.0";
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "passport-bridge",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "passport-bridge",
9
- "version": "0.19.0",
9
+ "version": "0.21.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "1.32.1"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passport-bridge",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Passport CLI for governed terminal and CI agents, plus the local stdio-to-cloud MCP bridge.",
5
5
  "license": "MIT",
6
6
  "repository": {