passport-bridge 0.24.0 → 0.26.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 (97) hide show
  1. package/README.md +72 -31
  2. package/dist/approvalNotice.d.ts +73 -0
  3. package/dist/approvalNotice.js +211 -0
  4. package/dist/cliArgs.d.ts +1 -1
  5. package/dist/cliArgs.js +17 -6
  6. package/dist/cliAutopilot.js +15 -4
  7. package/dist/cliAutopilotPolicy.d.ts +8 -0
  8. package/dist/cliAutopilotPolicy.js +23 -1
  9. package/dist/cliChanges.d.ts +80 -0
  10. package/dist/cliChanges.js +340 -0
  11. package/dist/cliClient.d.ts +5 -0
  12. package/dist/cliClient.js +15 -3
  13. package/dist/cliExec.js +2 -2
  14. package/dist/cliHook.d.ts +1 -1
  15. package/dist/cliHook.js +40 -35
  16. package/dist/cliHookAudit.d.ts +44 -0
  17. package/dist/cliHookAudit.js +57 -0
  18. package/dist/cliHookClients.d.ts +3 -1
  19. package/dist/cliHookClients.js +1 -1
  20. package/dist/cliHookDecide.js +3 -1
  21. package/dist/cliHookDeliver.d.ts +8 -0
  22. package/dist/cliHookDeliver.js +25 -0
  23. package/dist/cliHookGuard.d.ts +16 -1
  24. package/dist/cliHookGuard.js +31 -10
  25. package/dist/cliHookInput.d.ts +3 -0
  26. package/dist/cliHookInput.js +13 -0
  27. package/dist/cliHookLocal.d.ts +3 -2
  28. package/dist/cliHookLocal.js +5 -2
  29. package/dist/cliHookNotice.d.ts +22 -0
  30. package/dist/cliHookNotice.js +49 -0
  31. package/dist/cliHookRewrite.d.ts +2 -0
  32. package/dist/cliHookRewrite.js +1 -1
  33. package/dist/cliKeys.js +11 -1
  34. package/dist/cliKeysRotate.d.ts +24 -0
  35. package/dist/cliKeysRotate.js +149 -0
  36. package/dist/cliMain.js +56 -15
  37. package/dist/cliOutput.js +41 -5
  38. package/dist/cliPolicyV2.js +14 -0
  39. package/dist/cliProjectSummary.d.ts +9 -0
  40. package/dist/cliProjectSummary.js +134 -0
  41. package/dist/cliProtocol.d.ts +10 -0
  42. package/dist/cliProtocol.js +15 -0
  43. package/dist/cliRequest.d.ts +27 -0
  44. package/dist/cliRequest.js +92 -0
  45. package/dist/cliRestoreRequests.d.ts +57 -0
  46. package/dist/cliRestoreRequests.js +186 -0
  47. package/dist/cliSessions.d.ts +3 -0
  48. package/dist/cliSessions.js +24 -1
  49. package/dist/cliSessionsJson.d.ts +48 -2
  50. package/dist/cliSessionsJson.js +7 -9
  51. package/dist/cliSessionsRender.d.ts +8 -3
  52. package/dist/cliSessionsRender.js +16 -7
  53. package/dist/cliUndo.d.ts +1 -3
  54. package/dist/cliUndo.js +9 -15
  55. package/dist/cliUndoLocal.d.ts +27 -0
  56. package/dist/cliUndoLocal.js +105 -0
  57. package/dist/cliUpdate.d.ts +29 -0
  58. package/dist/cliUpdate.js +195 -0
  59. package/dist/cliWait.js +2 -2
  60. package/dist/completion.js +6 -1
  61. package/dist/doctor.js +4 -0
  62. package/dist/execNoKey.d.ts +4 -4
  63. package/dist/execNoKey.js +17 -11
  64. package/dist/gitBackup.d.ts +111 -0
  65. package/dist/gitBackup.js +391 -0
  66. package/dist/gitSnapshot.d.ts +82 -0
  67. package/dist/gitSnapshot.js +478 -0
  68. package/dist/holdNotice.js +7 -1
  69. package/dist/hookMain.js +10 -1
  70. package/dist/hookPromptFast.d.ts +26 -0
  71. package/dist/hookPromptFast.js +82 -0
  72. package/dist/initInstall.d.ts +22 -0
  73. package/dist/initInstall.js +70 -1
  74. package/dist/localBackups.d.ts +102 -0
  75. package/dist/localBackups.js +233 -0
  76. package/dist/localGit.d.ts +24 -0
  77. package/dist/localGit.js +44 -0
  78. package/dist/localRestore.d.ts +42 -0
  79. package/dist/localRestore.js +94 -0
  80. package/dist/localTrash.d.ts +97 -0
  81. package/dist/localTrash.js +394 -0
  82. package/dist/pluginPin.d.ts +1 -1
  83. package/dist/pluginPin.js +1 -1
  84. package/dist/plural.d.ts +2 -0
  85. package/dist/plural.js +13 -0
  86. package/dist/regenerable.d.ts +24 -0
  87. package/dist/regenerable.js +219 -0
  88. package/dist/selfUpdate.d.ts +92 -0
  89. package/dist/selfUpdate.js +361 -0
  90. package/dist/selfUpdateContract.d.ts +20 -0
  91. package/dist/selfUpdateContract.js +56 -0
  92. package/dist/updateTrigger.d.ts +18 -0
  93. package/dist/updateTrigger.js +77 -0
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -1
  96. package/npm-shrinkwrap.json +2 -2
  97. package/package.json +1 -1
@@ -0,0 +1,340 @@
1
+ /**
2
+ * `passport changes`: what changed in Production, the list Sessions ›
3
+ * Production changes shows. Every change, delete, and irreversible action
4
+ * that ran on confirmed Production in the window, grouped by app, newest
5
+ * first, with the agent, the person, the work item, the result, and undo.
6
+ *
7
+ * passport changes the last 24 hours
8
+ * passport changes --env production --since 1h
9
+ *
10
+ * Filters run on the server (`GET /api/my/production-changes`). `--json`
11
+ * prints `ChangesJson`, never the server's raw page.
12
+ */
13
+ import { value } from "./cliArgs.js";
14
+ import { api, json } from "./cliMemberCall.js";
15
+ import { failure, timeoutMs } from "./cliSupport.js";
16
+ import { appName, clientName, count, list, oneOf, record, text, time } from "./cliSessionsJson.js";
17
+ import { countOf } from "./plural.js";
18
+ import { joinParts, mark, visibleLength, wrap, termOf } from "./term.js";
19
+ import { hashLink } from "./webLinks.js";
20
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
21
+ const RANGES = ["1h", "6h", "24h", "7d", "30d", "today"];
22
+ const DEFAULT_SINCE = "24h";
23
+ const WINDOW_WORDS = {
24
+ "1h": "last hour",
25
+ "6h": "last 6 hours",
26
+ "24h": "last 24 hours",
27
+ "7d": "last 7 days",
28
+ "30d": "last 30 days",
29
+ today: "today"
30
+ };
31
+ /** A local date as this computer's midnight in epoch ms, the way the web sends it. */
32
+ function localMidnight(raw) {
33
+ const [year, month, day] = raw.split("-").map(Number);
34
+ const at = new Date(year, month - 1, day);
35
+ return at.getFullYear() === year && at.getMonth() === month - 1 && at.getDate() === day ? String(at.getTime()) : null;
36
+ }
37
+ /** `--since` as the server reads it. */
38
+ export function changesSince(raw) {
39
+ const value = raw.trim();
40
+ if (RANGES.includes(value))
41
+ return value;
42
+ return DATE.test(value) ? localMidnight(value) : null;
43
+ }
44
+ /** `--until` as the server reads it: a date (through its end) as written. */
45
+ function changesUntil(raw) {
46
+ const value = raw.trim();
47
+ return DATE.test(value) && localMidnight(value) ? value : null;
48
+ }
49
+ function filtersOf(args) {
50
+ const env = value(args, "env");
51
+ if (env !== undefined && env.trim().toLowerCase() !== "production")
52
+ return failure("Only --env production is supported for now.", 6, "usage");
53
+ const filters = {};
54
+ const since = value(args, "since") ?? DEFAULT_SINCE;
55
+ const parsedSince = changesSince(since);
56
+ if (!parsedSince)
57
+ return failure("--since must be 1h, 6h, 24h, 7d, 30d, today, or a date (YYYY-MM-DD).", 6, "usage");
58
+ filters.since = parsedSince;
59
+ const until = value(args, "until");
60
+ if (until !== undefined) {
61
+ const parsed = changesUntil(until);
62
+ if (!parsed)
63
+ return failure("--until must be a date (YYYY-MM-DD).", 6, "usage");
64
+ filters.until = parsed;
65
+ }
66
+ const project = value(args, "project");
67
+ if (project !== undefined) {
68
+ const name = text(project, 200);
69
+ if (!name)
70
+ return failure("--project needs a project name.", 6, "usage");
71
+ filters.project = name;
72
+ }
73
+ const pr = value(args, "pr");
74
+ if (pr !== undefined) {
75
+ const number = Number(pr.replace(/^#/, ""));
76
+ if (!Number.isSafeInteger(number) || number <= 0)
77
+ return failure("--pr must be a pull request number.", 6, "usage");
78
+ filters.pr = String(number);
79
+ }
80
+ const app = value(args, "app");
81
+ if (app !== undefined) {
82
+ const keys = text(app, 400);
83
+ if (!keys)
84
+ return failure("--app needs an app key.", 6, "usage");
85
+ filters.app = keys;
86
+ }
87
+ // `--agent` is read as `client` (cliArgs aliases).
88
+ const agent = value(args, "client");
89
+ if (agent !== undefined) {
90
+ const id = text(agent, 120);
91
+ if (!id)
92
+ return failure("--agent needs an agent name.", 6, "usage");
93
+ filters.agent = id;
94
+ }
95
+ return filters;
96
+ }
97
+ function query(params) {
98
+ const search = new URLSearchParams();
99
+ for (const [key, raw] of Object.entries(params))
100
+ if (raw)
101
+ search.set(key, raw);
102
+ const qs = search.toString();
103
+ return qs ? `?${qs}` : "";
104
+ }
105
+ /* -------------------------------- the JSON -------------------------------- */
106
+ function undoOf(raw) {
107
+ const undo = record(raw);
108
+ const state = text(undo.state, 40);
109
+ if (!state)
110
+ return null;
111
+ return { state, label: text(undo.label, 120) ?? state, undoneBy: text(undo.undoneBy, 120) ?? null };
112
+ }
113
+ function changeOf(raw) {
114
+ const entry = record(raw);
115
+ const id = text(entry.id, 128);
116
+ if (!id)
117
+ return null;
118
+ const appKey = text(entry.appKey, 80) ?? "";
119
+ const vendor = text(entry.vendor, 80) ?? appKey.replace(/^cli:/, "");
120
+ const tool = text(entry.tool, 160) ?? "";
121
+ const work = record(entry.work);
122
+ const pull = record(work.pull);
123
+ const pullNumber = count(pull.number);
124
+ const pullTitle = text(pull.title, 200);
125
+ const pullUrl = text(pull.url, 400);
126
+ const agent = text(entry.agent, 80) ?? "";
127
+ return {
128
+ id,
129
+ ts: time(entry.ts),
130
+ person: text(record(entry.person).name, 120) ?? null,
131
+ agent,
132
+ agentName: text(entry.agentName, 80) ?? clientName(agent),
133
+ appKey,
134
+ vendor,
135
+ appName: nameOf(text(entry.appName, 80), vendor),
136
+ command: text(entry.command, 200) ?? (appKey.startsWith("cli:") ? `${appKey.slice(4)} ${tool}` : tool),
137
+ target: text(entry.target, 160) ?? null,
138
+ actionClass: oneOf(entry.actionClass, ["change", "delete", "irreversible"]) ?? "change",
139
+ result: entry.result === "error" ? "error" : "ok",
140
+ approved: entry.approved === true,
141
+ sessionId: text(entry.sessionId, 128) ?? null,
142
+ project: text(work.project, 200) ?? null,
143
+ branch: text(work.branch, 200) ?? null,
144
+ pull: pullNumber && pullTitle
145
+ ? { number: pullNumber, title: pullTitle, url: pullUrl && /^https:\/\//.test(pullUrl) ? pullUrl : null }
146
+ : null,
147
+ undo: undoOf(entry.undo)
148
+ };
149
+ }
150
+ /** The server's app name, unless it's only the bare program ("git" reads "Git"). */
151
+ function nameOf(name, vendor) {
152
+ return name && name !== vendor ? name : appName(vendor);
153
+ }
154
+ /** The server's page as `ChangesJson`: grouped by app (newest first), then time. */
155
+ export function changesOf(raw) {
156
+ const page = record(raw);
157
+ const changes = list(page.changes)
158
+ .map(changeOf)
159
+ .filter((entry) => entry !== null);
160
+ const groups = new Map();
161
+ for (const change of changes) {
162
+ let group = groups.get(change.vendor);
163
+ if (!group) {
164
+ group = { vendor: change.vendor, appName: change.appName, changes: [], lastTs: 0 };
165
+ groups.set(change.vendor, group);
166
+ }
167
+ group.lastTs = Math.max(group.lastTs, change.ts ?? 0);
168
+ group.changes.push(change);
169
+ }
170
+ const apps = [...groups.values()]
171
+ .sort((a, b) => b.lastTs - a.lastTs || a.appName.localeCompare(b.appName))
172
+ .map(({ lastTs: _lastTs, ...group }) => ({
173
+ ...group,
174
+ changes: group.changes.sort((a, b) => (b.ts ?? 0) - (a.ts ?? 0) || a.id.localeCompare(b.id))
175
+ }));
176
+ return {
177
+ view: "production-changes",
178
+ environment: "production",
179
+ sinceTs: time(page.sinceTs),
180
+ untilTs: time(page.untilTs),
181
+ total: Math.max(count(page.total), changes.length),
182
+ unplaced: count(page.unplaced),
183
+ complete: page.complete !== false,
184
+ apps
185
+ };
186
+ }
187
+ /* -------------------------------- the text -------------------------------- */
188
+ function clock(ms) {
189
+ return new Date(ms).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
190
+ }
191
+ /** "14:02" today, "Oct 19 14:02" before. */
192
+ export function changeTime(ms, now) {
193
+ if (ms === null)
194
+ return "";
195
+ const date = new Date(ms);
196
+ if (new Date(now).toDateString() === date.toDateString())
197
+ return clock(ms);
198
+ return `${date.toLocaleDateString("en-US", { month: "short", day: "numeric" })} ${clock(ms)}`;
199
+ }
200
+ function undoPart(undo) {
201
+ if (!undo)
202
+ return null;
203
+ if (undo.state === "available" || undo.state === "conflict")
204
+ return "Undo available";
205
+ if (undo.state === "undone")
206
+ return `Undone by ${undo.undoneBy ?? "someone"}`;
207
+ if (undo.state === "expired")
208
+ return "Undo expired";
209
+ if (undo.state === "undoing")
210
+ return "Undoing";
211
+ if (undo.state === "partial")
212
+ return "Partly undone";
213
+ if (undo.state === "failed")
214
+ return "Undo failed";
215
+ return null;
216
+ }
217
+ /** The row's part line: agent · person · PR (else branch) · result · undo.
218
+ * With changes from more than one repository, the repository comes first. */
219
+ export function changeParts(change, projects = false) {
220
+ const parts = [change.agentName];
221
+ if (change.person)
222
+ parts.push(change.person);
223
+ if (projects && change.project && (change.pull || change.branch))
224
+ parts.push(change.project);
225
+ if (change.pull)
226
+ parts.push(`PR #${change.pull.number} ${change.pull.title}`);
227
+ else if (change.branch)
228
+ parts.push(change.branch);
229
+ if (change.result === "error")
230
+ parts.push("Failed");
231
+ if (change.approved)
232
+ parts.push("Approved");
233
+ const undo = undoPart(change.undo);
234
+ if (undo)
235
+ parts.push(undo);
236
+ return parts;
237
+ }
238
+ /** A change keeps its own line when it failed, was approved, or has an undo state worth seeing. */
239
+ function standsAlone(change) {
240
+ return change.result === "error" || change.approved || Boolean(change.undo && change.undo.state !== "expired");
241
+ }
242
+ function runKey(change) {
243
+ return JSON.stringify([change.command, change.target, change.agent, change.person, change.project, change.branch]);
244
+ }
245
+ /**
246
+ * Consecutive alike changes (same command, target, agent, person, and
247
+ * branch; newest first) as one line, the way the web folds them: 28 pushes
248
+ * read "git push -> main x28". `--json` keeps every change.
249
+ */
250
+ export function foldChanges(changes) {
251
+ const runs = [];
252
+ let open = null;
253
+ let openKey = "";
254
+ for (const change of changes) {
255
+ if (standsAlone(change)) {
256
+ runs.push([change]);
257
+ open = null;
258
+ continue;
259
+ }
260
+ const key = runKey(change);
261
+ if (open && key === openKey)
262
+ open.push(change);
263
+ else {
264
+ open = [change];
265
+ openKey = key;
266
+ runs.push(open);
267
+ }
268
+ }
269
+ return runs;
270
+ }
271
+ function windowWord(since, sinceTs, now) {
272
+ return WINDOW_WORDS[since] ?? (sinceTs ? `since ${changeTime(sinceTs, now)}` : `since ${since}`);
273
+ }
274
+ export function renderChanges(page, term, now, since, links) {
275
+ const arrow = term.unicode ? "→" : "->";
276
+ const lines = joinParts([
277
+ "Production changes",
278
+ windowWord(since, page.sinceTs, now),
279
+ `${countOf(page.total, "change")} on confirmed Production`
280
+ ], term.width);
281
+ if (!page.apps.length)
282
+ lines.push("", ...wrap("Nothing your agents ran changed a target you placed in Production in this window.", term.width));
283
+ const projects = new Set(page.apps.flatMap((app) => app.changes.map((change) => change.project)).filter(Boolean)).size > 1;
284
+ const times = term.unicode ? "×" : "x";
285
+ for (const app of page.apps) {
286
+ lines.push("", `${app.appName} · ${countOf(app.changes.length, "change")}`);
287
+ for (const run of foldChanges(app.changes)) {
288
+ const change = run[0];
289
+ const oldest = run[run.length - 1];
290
+ const title = change.target ? `${change.command} ${arrow} ${change.target}` : change.command;
291
+ const when = run.length > 1 ? `${changeTime(oldest.ts, now)}-${changeTime(change.ts, now)}` : changeTime(change.ts, now);
292
+ const count = run.length > 1 ? ` ${times}${run.length.toLocaleString("en-US")}` : "";
293
+ const head = `${mark(term, change.result === "error" ? "fail" : "warn")} ${when} ${title}${count}`;
294
+ lines.push(...(visibleLength(head) <= term.width ? [head] : wrap(head, term.width, "", " ")));
295
+ lines.push(...joinParts(changeParts(change, projects), term.width, " "));
296
+ }
297
+ }
298
+ if (!page.complete) {
299
+ lines.push("", ...wrap(`Showing the newest ${countOf(countRows(page), "change")}.`, term.width));
300
+ if (links.more)
301
+ lines.push(`See all: ${links.more}`);
302
+ }
303
+ if (page.unplaced) {
304
+ lines.push("", ...wrap(`${countOf(page.unplaced, "unplaced action")}, counted as Production until you place them.`, term.width));
305
+ if (links.environments)
306
+ lines.push(`Set environments: ${links.environments}`);
307
+ }
308
+ return lines.join("\n");
309
+ }
310
+ function countRows(page) {
311
+ return page.apps.reduce((sum, app) => sum + app.changes.length, 0);
312
+ }
313
+ /* -------------------------------- command -------------------------------- */
314
+ export async function changes(args, runtime, deps = {}) {
315
+ const now = (deps.now ?? Date.now)();
316
+ const filters = filtersOf(args);
317
+ const client = api(args, runtime, deps);
318
+ const term = termOf(runtime.stdout, runtime.env);
319
+ const response = await client.fetchApi(`/api/my/production-changes${query(filters)}`, {
320
+ method: "GET",
321
+ headers: { accept: "application/json" },
322
+ signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
323
+ });
324
+ const page = changesOf(await json(response, "This Passport server doesn't list Production changes yet. Run: passport sessions --production-changes"));
325
+ const since = value(args, "since")?.trim() ?? DEFAULT_SINCE;
326
+ const web = query({
327
+ view: "production",
328
+ since: filters.since,
329
+ until: filters.until,
330
+ project: filters.project,
331
+ pr: filters.pr
332
+ });
333
+ return {
334
+ json: page,
335
+ human: renderChanges(page, term, now, since, {
336
+ environments: hashLink(client.origin, "#rules?section=environments"),
337
+ more: hashLink(client.origin, `#sessions${web}`)
338
+ })
339
+ };
340
+ }
@@ -26,6 +26,10 @@ export type CliProtocolDiagnostics = {
26
26
  serverCompatible: boolean;
27
27
  tools: string[];
28
28
  toolsExact: boolean;
29
+ /** A matching server listed an agent's tools (an app's own tools, or the
30
+ * agent-only access request): the credential is an agent's, from
31
+ * `passport-bridge login`, not a CLI sign-in. */
32
+ agentSignIn: boolean;
29
33
  };
30
34
  type GatewayOptions = {
31
35
  auth: CliAuth;
@@ -48,6 +52,7 @@ export declare class CliGateway {
48
52
  private readonly signal?;
49
53
  private readonly apiFetch;
50
54
  readonly origin: string;
55
+ private readonly profileAuth;
51
56
  private closed;
52
57
  private constructor();
53
58
  static connect(options: GatewayOptions): Promise<CliGateway>;
package/dist/cliClient.js CHANGED
@@ -4,7 +4,7 @@ import { TokenManager } from "./bridge.js";
4
4
  import { CLI_EXCHANGE_ATTEMPT_MS, CLI_EXCHANGE_RETRY } from "./bridgeExchange.js";
5
5
  import { persistCurrentProfileRotation, recoverProfileRotation, withProfileLock } from "./credentials.js";
6
6
  import { VERSION } from "./version.js";
7
- import { SERVER_TOO_OLD } from "./cliProtocol.js";
7
+ import { AgentSignInError, SERVER_TOO_OLD } from "./cliProtocol.js";
8
8
  import { withCliDeadline } from "./cliDeadline.js";
9
9
  import { collectCliPages } from "./cliPagination.js";
10
10
  import { boundedMcpFetch } from "./boundedMcpFetch.js";
@@ -30,6 +30,10 @@ export function supportsCliServerInfo(info) {
30
30
  }
31
31
  return true;
32
32
  }
33
+ /** The CLI surface never lists app tools or the agent-only access request. */
34
+ function agentToolList(tools) {
35
+ return tools.some((name) => name === "passport_request_access" || !name.startsWith("passport_"));
36
+ }
33
37
  function decorateFetch(base, headersToAdd) {
34
38
  return (async (input, init) => {
35
39
  const headers = new Headers(input instanceof Request ? input.headers : undefined);
@@ -82,11 +86,13 @@ export class CliGateway {
82
86
  signal;
83
87
  apiFetch;
84
88
  origin;
89
+ profileAuth;
85
90
  closed = false;
86
91
  constructor(options) {
87
92
  this.timeoutMs = options.timeoutMs;
88
93
  this.signal = options.signal;
89
94
  this.origin = new URL(options.auth.endpoint).origin;
95
+ this.profileAuth = options.auth.kind === "profile";
90
96
  const authedFetch = authedFetchFor(options);
91
97
  this.apiFetch = authedFetch;
92
98
  this.transport = new StreamableHTTPClientTransport(new URL(options.auth.endpoint), {
@@ -112,6 +118,9 @@ export class CliGateway {
112
118
  // Check it before even listing tools so an older compact server cannot turn
113
119
  // an approval-pending result without structured cause into false success.
114
120
  const diagnostic = await this.protocolDiagnostics();
121
+ // Only a saved sign-in can be an agent's; an agent token always gets the CLI's four.
122
+ if (diagnostic.agentSignIn && this.profileAuth)
123
+ throw new AgentSignInError(this.origin);
115
124
  if (!diagnostic.serverCompatible || !diagnostic.toolsExact)
116
125
  throw new Error(SERVER_TOO_OLD);
117
126
  }
@@ -120,11 +129,14 @@ export class CliGateway {
120
129
  const info = this.client.getServerVersion();
121
130
  const tools = (await this.client.listTools({}, this.requestOptions())).tools.map((tool) => tool.name).sort();
122
131
  const required = [...CLI_PROTOCOL_TOOLS].sort();
132
+ const serverCompatible = supportsCliServerInfo(info);
133
+ const toolsExact = tools.length === required.length && required.every((name, index) => tools[index] === name);
123
134
  return {
124
135
  server: info ? { name: info.name, version: info.version } : undefined,
125
- serverCompatible: supportsCliServerInfo(info),
136
+ serverCompatible,
126
137
  tools,
127
- toolsExact: tools.length === required.length && required.every((name, index) => tools[index] === name)
138
+ toolsExact,
139
+ agentSignIn: serverCompatible && !toolsExact && agentToolList(tools)
128
140
  };
129
141
  }
130
142
  callTool(name, args, timeoutMs = this.timeoutMs) {
package/dist/cliExec.js CHANGED
@@ -401,13 +401,13 @@ function approvalUrl(auth, approvalId) {
401
401
  const workspace = auth.kind === "profile" ? workspaceOfToken(auth.refreshToken) : "";
402
402
  return approvalLink(auth.endpoint, approvalId, workspace || undefined) ?? undefined;
403
403
  }
404
- /** Ask, wait for a person when someone can, and ask again. While it waits,
405
- * stderr shows the approval link at once and a live countdown. */
404
+ /** Ask, wait for a person when someone can (stderr shows the link and a countdown), and ask again. */
406
405
  async function decide(ask, client, prepared, args, runtime, deps, auth) {
407
406
  const decided = await ask();
408
407
  if (decided.decision !== "ask")
409
408
  return decided;
410
409
  const approvalId = typeof decided.approvalId === "string" ? decided.approvalId : "";
410
+ await (await import("./cliHookNotice.js")).rememberExecAsk(approvalId, prepared.body, (deps.now ?? Date.now)());
411
411
  if (!approvalId || prepared.waitSeconds <= 0)
412
412
  return pendingFailure(decided, "Waiting for approval.");
413
413
  let waiting;
package/dist/cliHook.d.ts CHANGED
@@ -48,7 +48,7 @@ export declare function outcomeOf(response: unknown): {
48
48
  exitCode?: number;
49
49
  durationMs?: number;
50
50
  };
51
- export declare function buildReport(input: HookInput, findings: CliFinding[], env: Env, declared?: string, decided?: DecidedFinding[], local?: boolean, scripts?: ScriptReader): CliHookReport | null;
51
+ export declare function buildReport(input: HookInput, findings: CliFinding[], env: Env, declared?: string, decided?: DecidedFinding[], local?: boolean, scripts?: ScriptReader, backedUp?: ReadonlySet<CliFinding>): CliHookReport | null;
52
52
  /** What the guard answered, and for which findings. The audit row that
53
53
  * follows a command that ran carries its outcome and any opaque parts. */
54
54
  export declare function buildDecisionReport(input: HookInput, decision: GuardDecision, env: Env, declared?: string, local?: boolean): CliHookReport | null;
package/dist/cliHook.js CHANGED
@@ -19,13 +19,15 @@ import { summarize, unknownVerb, UNRECOGNIZED_VERB } from "./cliHookClassify.js"
19
19
  import { classifyLine, localMachine, workingFolder, worthReporting } from "./cliHookLocal.js";
20
20
  import { projectOf } from "./cliHookProject.js";
21
21
  import { codexAskBlocked, planGuard } from "./cliHookDecide.js";
22
- import { decideEach, decideGuard, guardMachineOf } from "./cliHookGuard.js";
22
+ import { guardMachineOf } from "./cliHookGuard.js";
23
23
  import { detectMode } from "./cliHookMode.js";
24
24
  import { cappedHold, holdSeconds } from "./cliHookHold.js";
25
- import { readInput } from "./cliHookInput.js";
25
+ import { commandText, readInput } from "./cliHookInput.js";
26
26
  import { budgetSignal, expiredAsks, HOOK_BUDGET_MS, HOOK_RUNTIMES, leftovers, localProfile, localSelection, profileApi, queueAfterCommand, reportSender, runFlush, startFlushIfDue } from "./cliHookDeliver.js";
27
27
  export { HOOK_BUDGET_MS, HOOK_RUNTIMES, legacyReport } from "./cliHookDeliver.js";
28
28
  import { hookViaPlugin } from "./hookPlugin.js";
29
+ import { guardLocalBackups, markLocalBackups } from "./localBackups.js";
30
+ import { auditBackups, auditDecision, auditedCommand, markTrashed } from "./cliHookAudit.js";
29
31
  import { opaqueParts } from "./cliHookOpaque.js";
30
32
  export { opaqueKind, opaqueProgram } from "./cliHookOpaque.js";
31
33
  import { hasExpired, holdAsk, takeAsk } from "./cliHookPending.js";
@@ -146,11 +148,11 @@ function context(input, env, declared) {
146
148
  ...(branch ? { branch } : {})
147
149
  };
148
150
  }
149
- function reportable(findings, decided = [], local = false) {
151
+ function reportable(findings, decided = [], local = false, backedUp) {
150
152
  return findings
151
153
  .filter((finding) => Boolean(finding.vendor))
152
154
  .filter((finding) => VENDOR_NAME.test(finding.vendor))
153
- .filter((finding) => worthReporting(finding, decided, local))
155
+ .filter((finding) => worthReporting(finding, decided, local, backedUp))
154
156
  .slice(0, MAX_FINDINGS)
155
157
  .map((finding) => {
156
158
  const entry = decided.find((candidate) => candidate.finding === finding);
@@ -170,20 +172,21 @@ function reportable(findings, decided = [], local = false) {
170
172
  function autopilotDecision(decision) {
171
173
  return decision?.cause ? { decision: decision.verdict } : {};
172
174
  }
173
- export function buildReport(input, findings, env, declared, decided = [], local = false, scripts) {
175
+ export function buildReport(input, findings, env, declared, decided = [], local = false, scripts, backedUp) {
174
176
  const summary = summarize(findings);
175
177
  const extra = scriptReport(scripts);
176
178
  // A script that changed under a project action is worth a row of its own.
177
179
  if (!summary.governed.length && !summary.opaque && !extra.projectChanged && !extra.drift)
178
180
  return null;
179
- const governed = reportable(summary.governed, decided, local);
181
+ const governed = reportable(summary.governed, decided, local, backedUp);
180
182
  if (!governed.length && !summary.opaque && !extra.projectChanged && !extra.drift)
181
183
  return null;
182
184
  const { kinds, programs } = opaqueParts(summary.unknown, MAX_OPAQUE_KINDS);
185
+ const where = context(input, env, declared);
183
186
  return {
184
- ...context(input, env, declared),
187
+ ...where,
185
188
  ...outcomeOfInput(input),
186
- findings: governed,
189
+ findings: markLocalBackups(governed, where),
187
190
  opaque: summary.opaque,
188
191
  ...(summary.opaque && kinds.length ? { opaqueKinds: kinds } : {}),
189
192
  ...(summary.opaque && programs.length ? { opaquePrograms: programs } : {}),
@@ -202,19 +205,6 @@ export function buildDecisionReport(input, decision, env, declared, local = fals
202
205
  return null;
203
206
  return { ...context(input, env, declared), findings, opaque: false, decision: decision.verdict };
204
207
  }
205
- /** A shell string as-is, or an argv array (`["bash", "-lc", "…"]`) re-quoted
206
- * so the classifier reads the same words the shell will. */
207
- function commandText(candidate) {
208
- if (typeof candidate === "string")
209
- return candidate;
210
- if (!Array.isArray(candidate) || !candidate.length || candidate.length > 256)
211
- return null;
212
- if (!candidate.every((part) => typeof part === "string"))
213
- return null;
214
- return candidate
215
- .map((part) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(part) ? part : `'${part.replaceAll("'", `'\\''`)}'`))
216
- .join(" ");
217
- }
218
208
  /** Normalise one stdin event into the command and when it runs. */
219
209
  export function shellEvent(input) {
220
210
  if (isCursorEvent(input)) {
@@ -285,10 +275,6 @@ function hookEvent(input, phase, args, runtime) {
285
275
  return null;
286
276
  return managedElsewhere(input, args, runtime) ? null : event;
287
277
  }
288
- /** `passport exec` records its own action, with its decision and credential. */
289
- function isPassportExec(command) {
290
- return /^\s*(?:\S*\/)?passport\s+exec\b/.test(command) || /^\s*'[^']*'\s+'[^']*'\s+exec\b/.test(command);
291
- }
292
278
  async function runAudit(args, runtime, deps) {
293
279
  if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
294
280
  return;
@@ -296,6 +282,10 @@ async function runAudit(args, runtime, deps) {
296
282
  const input = await readInput(runtime, budget);
297
283
  if (!input)
298
284
  return;
285
+ // Claude Code resumed, or the person typed: say what was approved meanwhile.
286
+ const managed = () => managedElsewhere(input, args, runtime);
287
+ if (await (await import("./cliHookNotice.js")).tellApproved(input, args, runtime, deps, budget, managed))
288
+ return;
299
289
  // A session started or ended: one marker, queued like any report.
300
290
  if (await (await import("./cliHookLifecycle.js")).lifecycle(input, args, runtime, deps))
301
291
  return;
@@ -303,8 +293,10 @@ async function runAudit(args, runtime, deps) {
303
293
  const event = hookEvent(input, "post", args, runtime);
304
294
  if (!event)
305
295
  return;
306
- if (isPassportExec(event.command))
296
+ const audited = auditedCommand(event.command);
297
+ if (!audited)
307
298
  return;
299
+ const { command, trashed } = audited;
308
300
  if (event.cursorImported && (await cursorHasOwnEntry(runtime, "audit")))
309
301
  return;
310
302
  const profile = localProfile(args, runtime.env);
@@ -313,16 +305,17 @@ async function runAudit(args, runtime, deps) {
313
305
  // check is drift (item 6).
314
306
  const scripts = scriptReader({ phase: "post", project: projectContext(policy), now: deps.budget?.scriptClock });
315
307
  const machine = { ...localMachine(workingFolder(input), runtime.env), scripts };
316
- const line = classifyLine(event.command, machine);
308
+ const line = classifyLine(command, machine);
317
309
  const findings = line.findings;
318
310
  saveScriptCache(scripts);
319
311
  // v2: the same decision the guard made, so the row says why it ran.
320
- const guardAt = guardAtFor(machine, input, runtime.env);
321
- const decision = policy?.version === 2 ? decideGuard(findings, policy, event.command, line.complete, guardAt) : null;
322
- const local = policy?.version === 2 && policy.autopilot.localCommands === true;
323
- // Where each command landed, even when the line got no decision.
324
- const decided = policy?.version === 2 ? (decision?.decided ?? decideEach(findings, policy, guardAt)) : undefined;
325
- let report = buildReport(input, findings, runtime.env, value(args, "client"), decided, local, scripts);
312
+ const key = context(input, runtime.env, value(args, "client"));
313
+ const { taken, backedUp } = auditBackups(findings, key, Boolean(trashed));
314
+ const guardAt = { ...guardAtFor(machine, input, runtime.env), ...taken };
315
+ const { decision, local, decided } = auditDecision(findings, policy, command, line.complete, guardAt);
316
+ let report = buildReport(input, findings, runtime.env, value(args, "client"), decided, local, scripts, backedUp);
317
+ if (report && trashed)
318
+ report = markTrashed(report, trashed.key);
326
319
  if (report && policy?.version === 2) {
327
320
  report = withStep({ ...report, ...autopilotDecision(decision) }, input, policy);
328
321
  }
@@ -478,10 +471,15 @@ async function runGuard(args, runtime, deps) {
478
471
  const scripts = scriptReader({ phase: "pre", project: projectContext(policy), now: deps.budget?.scriptClock });
479
472
  const machine = { ...localMachine(workingFolder(input), runtime.env), scripts };
480
473
  const line = classifyLine(event.command, machine);
481
- const decision = decideGuard(line.findings, policy, event.command, line.complete, guardAtFor(machine, input, runtime.env));
482
- const local = policy?.version === 2 && policy.autopilot.localCommands === true;
483
474
  const declared = value(args, "client");
484
475
  const client = outputClient(event, detectRuntime(input, runtime.env, declared));
476
+ // Which deletes will have a backup on this computer, so the rules decide knowing it.
477
+ const backups = guardLocalBackups(event.command, line, policy, {
478
+ ...{ ...guardAtFor(machine, input, runtime.env), machine, key: context(input, runtime.env, declared) },
479
+ rewrite: client === "claude-code" && !event.cursorImported
480
+ });
481
+ let decision = backups.decision;
482
+ const local = policy?.version === 2 && policy.autopilot.localCommands === true;
485
483
  const mode = detectMode(input, runtime.env).mode;
486
484
  const canReport = Boolean(profile) && !runtime.env.PASSPORT_AGENT_KEY && !runtime.env.PASSPORT_ENDPOINT;
487
485
  // A sign-in for a CLI whose key Passport holds (any agent), or the rewrite to exec (Claude Code).
@@ -498,6 +496,10 @@ async function runGuard(args, runtime, deps) {
498
496
  : null;
499
497
  if (rewritten)
500
498
  return void runtime.stdout.write(`${JSON.stringify(rewritten)}\n`);
499
+ const kept = await backups.keep(clock(), record(input.tool_input), deps.invocation, runtime.env);
500
+ if (kept.output)
501
+ return void runtime.stdout.write(`${JSON.stringify(kept.output)}\n`);
502
+ decision = kept.decision;
501
503
  const base = decision && !event.cursorImported ? buildDecisionReport(input, decision, runtime.env, declared, local) : null;
502
504
  const localAt = clock();
503
505
  const plan = await planGuard(decision, policy, {
@@ -523,6 +525,7 @@ async function runGuard(args, runtime, deps) {
523
525
  });
524
526
  if (plan.output)
525
527
  runtime.stdout.write(`${JSON.stringify(plan.output)}\n`);
528
+ await (await import("./cliHookNotice.js")).rememberGuardAsk(plan, client, sessionOfInput(input), clock());
526
529
  saveScriptCache(scripts);
527
530
  const runtimeName = detectRuntime(input, runtime.env, declared);
528
531
  // Coverage: count what the guard saw, once even when Cursor runs both copies.
@@ -574,6 +577,8 @@ export async function hook(args, runtime, deps = {}) {
574
577
  const action = args.positionals[0];
575
578
  if (action === "status")
576
579
  return (await import("./cliHookStatus.js")).hookStatus(args, runtime);
580
+ if (action === "trash")
581
+ return (await import("./localTrash.js")).trashHook(args.positionals.slice(1), runtime);
577
582
  if (action === "install" || action === "uninstall") {
578
583
  const { hookRegistration } = await import("./cliHookInstall.js");
579
584
  return hookRegistration(action, value(args, "client"), args, runtime);