passport-bridge 0.13.2 → 0.14.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 +92 -17
- package/dist/cli.js +4 -3
- package/dist/cliArgs.d.ts +1 -1
- package/dist/cliArgs.js +21 -5
- package/dist/cliAutopilot.d.ts +60 -0
- package/dist/cliAutopilot.js +389 -0
- package/dist/cliAutopilotPolicy.d.ts +94 -0
- package/dist/cliAutopilotPolicy.js +193 -0
- package/dist/cliClient.d.ts +7 -0
- package/dist/cliClient.js +36 -19
- package/dist/cliHook.d.ts +20 -9
- package/dist/cliHook.js +125 -32
- package/dist/cliHookClassify.d.ts +3 -0
- package/dist/cliHookClassify.js +2 -1
- package/dist/cliHookDecide.d.ts +89 -0
- package/dist/cliHookDecide.js +167 -0
- package/dist/cliHookEnvironment.d.ts +55 -0
- package/dist/cliHookEnvironment.js +219 -0
- package/dist/cliHookGuard.d.ts +61 -12
- package/dist/cliHookGuard.js +211 -24
- package/dist/cliHookInstall.js +19 -4
- package/dist/cliHookMode.d.ts +31 -0
- package/dist/cliHookMode.js +50 -0
- package/dist/cliHookRedact.d.ts +16 -0
- package/dist/cliHookRedact.js +136 -0
- package/dist/cliInit.d.ts +4 -1
- package/dist/cliInit.js +10 -3
- package/dist/cliLogin.js +18 -2
- package/dist/cliOffline.js +9 -9
- package/dist/cliOutput.js +11 -5
- package/dist/cliPolicy.d.ts +11 -3
- package/dist/cliPolicy.js +5 -2
- package/dist/cliPolicyV2.d.ts +18 -0
- package/dist/cliPolicyV2.js +234 -0
- package/dist/cliSetupOrg.d.ts +15 -0
- package/dist/cliSetupOrg.js +241 -0
- package/dist/cliSupport.d.ts +4 -0
- package/dist/cliSupport.js +12 -9
- package/dist/completion.js +12 -3
- package/dist/doctor.js +3 -3
- package/dist/enrollment.d.ts +18 -0
- package/dist/enrollment.js +79 -0
- package/dist/hookPlugin.d.ts +7 -0
- package/dist/hookPlugin.js +54 -0
- package/dist/initAgents.d.ts +3 -1
- package/dist/initAgents.js +7 -3
- package/dist/initAutopilotStep.d.ts +24 -0
- package/dist/initAutopilotStep.js +257 -0
- package/dist/initLocalSteps.d.ts +3 -0
- package/dist/initLocalSteps.js +30 -5
- package/dist/initState.d.ts +24 -0
- package/dist/initUi.js +5 -0
- package/dist/passport.js +27 -3
- package/dist/pluginPin.d.ts +7 -0
- package/dist/pluginPin.js +7 -0
- package/dist/universalUrl.d.ts +28 -0
- package/dist/universalUrl.js +59 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Autopilot from the terminal:
|
|
3
|
+
*
|
|
4
|
+
* passport wait <approval-id> [--timeout <sec>] wait for a person to decide
|
|
5
|
+
* passport rules test "<command>" [--environment <kind>]
|
|
6
|
+
* passport sessions [--status running|idle|ended]
|
|
7
|
+
*
|
|
8
|
+
* plus the Autopilot lines `passport status` adds. Every command here uses the
|
|
9
|
+
* member API with a saved profile; agent keys have no person to wait for.
|
|
10
|
+
* `rules test` classifies the command on this machine and sends only the
|
|
11
|
+
* vendor and verb (and the environment kind), never the command line.
|
|
12
|
+
*/
|
|
13
|
+
import { bool, value } from "./cliArgs.js";
|
|
14
|
+
import { OTHER_APPS, PRESET_LABEL, PRESET_ROWS, rowLabel } from "./cliAutopilotPolicy.js";
|
|
15
|
+
import { memberApi } from "./cliClient.js";
|
|
16
|
+
import { classifyCommand } from "./cliHookClassify.js";
|
|
17
|
+
import { ENV_KINDS, ENV_LABEL, environmentHintWith, isEnvKind } from "./cliHookEnvironment.js";
|
|
18
|
+
import { decideGuard, guardLabel } from "./cliHookGuard.js";
|
|
19
|
+
import { readCliPolicy } from "./cliPolicy.js";
|
|
20
|
+
import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, sanitize, sleep, timeoutMs } from "./cliSupport.js";
|
|
21
|
+
/** Long enough to be useful, short enough for an agent's default 2-minute
|
|
22
|
+
* command timeout. */
|
|
23
|
+
export const WAIT_DEFAULT_SECONDS = 100;
|
|
24
|
+
const WAIT_POLL_SECONDS = 30;
|
|
25
|
+
const APPROVAL_ID = /^[A-Za-z0-9_-]{1,80}$/;
|
|
26
|
+
function api(args, runtime, deps, waitMs = 0) {
|
|
27
|
+
if (deps.api)
|
|
28
|
+
return deps.api;
|
|
29
|
+
const auth = resolveCliAuth(args, runtime.env);
|
|
30
|
+
if (auth.kind !== "profile") {
|
|
31
|
+
return failure("This needs a member profile. Agent keys have no person to ask.", 6, "member_profile_required", {
|
|
32
|
+
hint: "Run: passport login"
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
return memberApi({
|
|
36
|
+
auth,
|
|
37
|
+
caller: callerFrom(args, runtime.env),
|
|
38
|
+
timeoutMs: Math.max(timeoutMs(args), waitMs),
|
|
39
|
+
signal: runtime.signal
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
async function json(response, fallback) {
|
|
43
|
+
if (response.status === 401 || response.status === 403) {
|
|
44
|
+
return failure(await safeApiError(response, "Passport refused this profile."), 2, "auth", {
|
|
45
|
+
hint: "Run: passport login"
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
if (response.status === 404) {
|
|
49
|
+
await response.body?.cancel().catch(() => undefined);
|
|
50
|
+
return failure(fallback, 1, "not_found");
|
|
51
|
+
}
|
|
52
|
+
if (!response.ok)
|
|
53
|
+
return failure(await safeApiError(response, "Passport couldn't answer."), 1, "server");
|
|
54
|
+
return readBoundedJson(response);
|
|
55
|
+
}
|
|
56
|
+
function text(raw, max = 200) {
|
|
57
|
+
if (typeof raw !== "string")
|
|
58
|
+
return undefined;
|
|
59
|
+
const cleaned = raw.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
|
|
60
|
+
return cleaned ? cleaned.slice(0, max) : undefined;
|
|
61
|
+
}
|
|
62
|
+
function waitOutcome(id, body) {
|
|
63
|
+
const status = body.status;
|
|
64
|
+
const message = text(body.message);
|
|
65
|
+
// The server names who decided: approver, approvedBy, decidedBy, or by.
|
|
66
|
+
const by = text(body.approver) ?? text(body.approvedBy) ?? text(body.decidedBy) ?? text(body.by);
|
|
67
|
+
const scope = typeof body.scope === "string" ? body.scope : undefined;
|
|
68
|
+
if (status === "allowed" || status === "approved") {
|
|
69
|
+
// "Approved by Ramish." or "Now allowed by your rules.", then the next step.
|
|
70
|
+
const lead = message ?? `Approved${by ? ` by ${by}` : ""}.`;
|
|
71
|
+
const human = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
|
|
72
|
+
return {
|
|
73
|
+
json: {
|
|
74
|
+
approvalId: id,
|
|
75
|
+
status: "approved",
|
|
76
|
+
...(scope ? { scope } : {}),
|
|
77
|
+
...(by ? { decidedBy: by } : {}),
|
|
78
|
+
message: human
|
|
79
|
+
},
|
|
80
|
+
human,
|
|
81
|
+
essential: true
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
if (status === "denied" || status === "declined") {
|
|
85
|
+
const human = message ?? `Declined${by ? ` by ${by}` : ""}.`;
|
|
86
|
+
return failure(human, 5, "approval_denied", { approvalId: id });
|
|
87
|
+
}
|
|
88
|
+
if (status === "expired") {
|
|
89
|
+
return failure(message ?? "Expired. The agent can ask again.", 5, "approval_expired", { approvalId: id });
|
|
90
|
+
}
|
|
91
|
+
if (status === "missing") {
|
|
92
|
+
return failure(`No approval request ${id}. Check the id, or ask again.`, 6, "unknown_approval", { approvalId: id });
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
export async function wait(args, runtime, deps = {}) {
|
|
97
|
+
const id = args.positionals[0];
|
|
98
|
+
if (!id || !APPROVAL_ID.test(id))
|
|
99
|
+
return failure("passport wait needs an approval id, like apr_123.", 6, "usage");
|
|
100
|
+
const totalSeconds = value(args, "timeout") ? Number(value(args, "timeout")) : WAIT_DEFAULT_SECONDS;
|
|
101
|
+
const now = deps.now ?? Date.now;
|
|
102
|
+
const deadline = now() + totalSeconds * 1000;
|
|
103
|
+
const client = api(args, runtime, deps, (WAIT_POLL_SECONDS + 10) * 1000);
|
|
104
|
+
let announced = false;
|
|
105
|
+
for (;;) {
|
|
106
|
+
const left = Math.ceil((deadline - now()) / 1000);
|
|
107
|
+
const poll = Math.max(1, Math.min(WAIT_POLL_SECONDS, left));
|
|
108
|
+
const response = await client.fetchApi(`/api/my/approvals/${encodeURIComponent(id)}/wait?timeout=${poll}`, {
|
|
109
|
+
method: "GET",
|
|
110
|
+
headers: { accept: "application/json" },
|
|
111
|
+
signal: AbortSignal.any([runtime.signal, AbortSignal.timeout((poll + 10) * 1000)])
|
|
112
|
+
});
|
|
113
|
+
if (response.status === 404) {
|
|
114
|
+
// "No such approval." from a server that waits; anything else is an older server.
|
|
115
|
+
const message = await safeApiError(response, "");
|
|
116
|
+
if (/approval/i.test(message))
|
|
117
|
+
return waitOutcome(id, { status: "missing" });
|
|
118
|
+
return failure("This Passport server can't wait on approvals yet. Check Approvals on the web.", 1, "not_found");
|
|
119
|
+
}
|
|
120
|
+
const body = await json(response, "Passport couldn't find that approval.");
|
|
121
|
+
const outcome = waitOutcome(id, body);
|
|
122
|
+
if (outcome)
|
|
123
|
+
return outcome;
|
|
124
|
+
if (now() >= deadline) {
|
|
125
|
+
return failure(`Still waiting for approval. Run \`passport wait ${id}\` again, or continue with other work.`, 4, "approval_pending", {
|
|
126
|
+
approvalId: id,
|
|
127
|
+
next: [{ argv: ["passport", "wait", id], description: "Keep waiting for this approval." }]
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (!announced && !bool(args, "quiet") && !bool(args, "json")) {
|
|
131
|
+
runtime.stderr.write(`Waiting for a decision on ${id} (up to ${totalSeconds} seconds)...\n`);
|
|
132
|
+
announced = true;
|
|
133
|
+
}
|
|
134
|
+
// A server that answers at once instead of holding the request is polled gently.
|
|
135
|
+
if (response.headers.get("x-passport-long-poll") === "0")
|
|
136
|
+
await sleep(2_000, runtime.signal);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// ---- passport rules test ----------------------------------------------------
|
|
140
|
+
const DECISION_WORDS = { allow: "Runs", ask: "Asks first", block: "Blocked" };
|
|
141
|
+
const CLASS_WORDS = {
|
|
142
|
+
read: "Read",
|
|
143
|
+
change: "Change",
|
|
144
|
+
delete: "Delete",
|
|
145
|
+
irreversible: "Irreversible"
|
|
146
|
+
};
|
|
147
|
+
function ageText(ms) {
|
|
148
|
+
const minutes = Math.round(ms / 60_000);
|
|
149
|
+
if (minutes < 1)
|
|
150
|
+
return "just now";
|
|
151
|
+
if (minutes < 60)
|
|
152
|
+
return `${minutes} min ago`;
|
|
153
|
+
const hours = Math.round(minutes / 60);
|
|
154
|
+
return hours < 48 ? `${hours} h ago` : `${Math.round(hours / 24)} days ago`;
|
|
155
|
+
}
|
|
156
|
+
function ruleTestLines(label, result, source) {
|
|
157
|
+
if (result.decision === "none") {
|
|
158
|
+
return [
|
|
159
|
+
label,
|
|
160
|
+
" No decision: Passport doesn't decide this command, so your agent's own prompt applies.",
|
|
161
|
+
...(source ? [` ${source}`] : [])
|
|
162
|
+
];
|
|
163
|
+
}
|
|
164
|
+
const explanation = text(result.explanation) ?? `${DECISION_WORDS[result.decision]}${result.cause ? `: ${result.cause.label}` : ""}.`;
|
|
165
|
+
const environment = result.environment
|
|
166
|
+
? `${rowLabel(result.environment)}${result.environmentAssumed ? " (assumed)" : ""}`
|
|
167
|
+
: undefined;
|
|
168
|
+
return [
|
|
169
|
+
label,
|
|
170
|
+
` ${explanation}`,
|
|
171
|
+
...(environment ? [` Environment: ${environment}`] : []),
|
|
172
|
+
...(result.actionClass ? [` Class: ${CLASS_WORDS[result.actionClass]}`] : []),
|
|
173
|
+
` ${source}`
|
|
174
|
+
];
|
|
175
|
+
}
|
|
176
|
+
function localTest(command, policy, environment) {
|
|
177
|
+
const findings = classifyCommand(command).map((finding) => environment && finding.vendor
|
|
178
|
+
? { ...finding, args: [...(finding.args ?? []), "--environment", environment] }
|
|
179
|
+
: finding);
|
|
180
|
+
const decision = decideGuard(findings, policy, command);
|
|
181
|
+
if (!decision)
|
|
182
|
+
return null;
|
|
183
|
+
return {
|
|
184
|
+
decision: decision.verdict === "deny" ? "block" : decision.verdict,
|
|
185
|
+
...(decision.cause ? { cause: decision.cause } : {}),
|
|
186
|
+
...(decision.environment ? { environment: decision.environment } : {}),
|
|
187
|
+
...(decision.environmentSource === "assumed" ? { environmentAssumed: true } : {}),
|
|
188
|
+
...(decision.actionClass ? { actionClass: decision.actionClass } : {})
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
export async function rules(args, runtime, deps = {}) {
|
|
192
|
+
const [action, command] = args.positionals;
|
|
193
|
+
if (action !== "test" || !command?.trim()) {
|
|
194
|
+
return failure('Use: passport rules test "<command>" [--environment production|staging|development]', 6, "usage");
|
|
195
|
+
}
|
|
196
|
+
const environmentFlag = value(args, "environment");
|
|
197
|
+
if (environmentFlag !== undefined && !isEnvKind(environmentFlag)) {
|
|
198
|
+
return failure("--environment must be production, staging, or development.", 6, "usage");
|
|
199
|
+
}
|
|
200
|
+
const environment = environmentFlag;
|
|
201
|
+
const findings = classifyCommand(command).filter((finding) => finding.vendor);
|
|
202
|
+
const label = findings.length ? guardLabel(findings[0]) : "This command";
|
|
203
|
+
if (!findings.length) {
|
|
204
|
+
const result = { decision: "none" };
|
|
205
|
+
return { json: { command: null, ...result }, human: ruleTestLines(label, result, "").filter(Boolean).join("\n") };
|
|
206
|
+
}
|
|
207
|
+
const profile = (() => {
|
|
208
|
+
try {
|
|
209
|
+
const auth = resolveCliAuth(args, runtime.env);
|
|
210
|
+
return auth.kind === "profile" ? auth.profile : undefined;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
})();
|
|
216
|
+
const cached = profile ? readCliPolicy(profile) : null;
|
|
217
|
+
const local = localTest(command, cached, environment);
|
|
218
|
+
const hint = findings[0].vendor
|
|
219
|
+
? environmentHintWith(findings[0].vendor, findings[0].args ?? [], cached?.version === 2
|
|
220
|
+
? {
|
|
221
|
+
flags: cached.autopilot.environmentFlags,
|
|
222
|
+
known: cached.autopilot.environments
|
|
223
|
+
}
|
|
224
|
+
: {})
|
|
225
|
+
: undefined;
|
|
226
|
+
const placed = environment ?? (hint && hint.source !== "assumed" ? hint.kind : undefined);
|
|
227
|
+
// The server knows grants, every rule, and the workspace's environments.
|
|
228
|
+
let result = null;
|
|
229
|
+
let source = "";
|
|
230
|
+
if (profile || deps.api) {
|
|
231
|
+
try {
|
|
232
|
+
const client = api(args, runtime, deps);
|
|
233
|
+
const response = await client.fetchApi("/api/my/rules/test", {
|
|
234
|
+
method: "POST",
|
|
235
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
236
|
+
body: JSON.stringify({ command: label, ...(placed ? { environment: placed } : {}) }),
|
|
237
|
+
signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
|
|
238
|
+
});
|
|
239
|
+
if (response.ok) {
|
|
240
|
+
result = await readBoundedJson(response);
|
|
241
|
+
source = "Decided by your workspace's rules.";
|
|
242
|
+
}
|
|
243
|
+
else
|
|
244
|
+
await response.body?.cancel().catch(() => undefined);
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
if (runtime.signal.aborted)
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (!result) {
|
|
252
|
+
result = local ?? { decision: "none" };
|
|
253
|
+
source = cached
|
|
254
|
+
? `Decided on this computer from rules synced ${ageText(Math.max(0, Date.now() - cached.fetchedAt))}.`
|
|
255
|
+
: "Decided on this computer from built-in rules. Run passport status to sync yours.";
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
json: { command: label, ...result, source: source.startsWith("Decided by") ? "server" : "local" },
|
|
259
|
+
human: ruleTestLines(label, result, source).join("\n")
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
const CLIENT_NAMES = {
|
|
263
|
+
"claude-code": "Claude Code",
|
|
264
|
+
codex: "Codex",
|
|
265
|
+
cursor: "Cursor",
|
|
266
|
+
copilot: "Copilot",
|
|
267
|
+
cli: "Passport CLI"
|
|
268
|
+
};
|
|
269
|
+
function count(raw) {
|
|
270
|
+
return typeof raw === "number" && Number.isFinite(raw) && raw >= 0 ? Math.trunc(raw) : 0;
|
|
271
|
+
}
|
|
272
|
+
function when(ms, now) {
|
|
273
|
+
if (typeof ms !== "number")
|
|
274
|
+
return "";
|
|
275
|
+
const date = new Date(ms);
|
|
276
|
+
const sameDay = new Date(now).toDateString() === date.toDateString();
|
|
277
|
+
const time = date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
|
|
278
|
+
return sameDay ? time : `${date.toLocaleDateString("en-US", { month: "short", day: "numeric" })} ${time}`;
|
|
279
|
+
}
|
|
280
|
+
export function sessionLine(row, now, unicode = true) {
|
|
281
|
+
const status = row.status === "running" ? "Running" : row.status === "idle" ? "Idle" : "Ended";
|
|
282
|
+
const dot = row.status === "running" ? (unicode ? "● " : "* ") : " ";
|
|
283
|
+
const client = text(row.client, 40) ?? "agent";
|
|
284
|
+
const name = CLIENT_NAMES[client] ?? client;
|
|
285
|
+
const folder = text(row.folder, 40) ?? "";
|
|
286
|
+
const counts = row.counts ?? {};
|
|
287
|
+
const parts = [`${count(counts.ran)} ran`, `${count(counts.asked)} asked`];
|
|
288
|
+
if (count(counts.blocked))
|
|
289
|
+
parts.push(`${count(counts.blocked)} blocked`);
|
|
290
|
+
const environments = Array.isArray(row.environments)
|
|
291
|
+
? row.environments.filter(isEnvKind).map((env) => ENV_LABEL[env])
|
|
292
|
+
: [];
|
|
293
|
+
const waiting = count(row.waiting) ? ` Waiting for you (${count(row.waiting)})` : "";
|
|
294
|
+
return [
|
|
295
|
+
`${dot}${status.padEnd(7)}`,
|
|
296
|
+
name.padEnd(12),
|
|
297
|
+
folder.padEnd(18),
|
|
298
|
+
`started ${when(row.startedAt, now)}`.padEnd(18),
|
|
299
|
+
parts.join(" · "),
|
|
300
|
+
environments.length ? ` ${environments.join(", ")}` : ""
|
|
301
|
+
]
|
|
302
|
+
.join(" ")
|
|
303
|
+
.trimEnd()
|
|
304
|
+
.concat(waiting);
|
|
305
|
+
}
|
|
306
|
+
export async function sessions(args, runtime, deps = {}) {
|
|
307
|
+
const status = value(args, "status");
|
|
308
|
+
if (status !== undefined && !["running", "idle", "ended"].includes(status)) {
|
|
309
|
+
return failure("--status must be running, idle, or ended.", 6, "usage");
|
|
310
|
+
}
|
|
311
|
+
const client = api(args, runtime, deps);
|
|
312
|
+
const response = await client.fetchApi(`/api/my/agent-sessions${status ? `?status=${status}` : ""}`, {
|
|
313
|
+
method: "GET",
|
|
314
|
+
headers: { accept: "application/json" },
|
|
315
|
+
signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
|
|
316
|
+
});
|
|
317
|
+
const page = await json(response, "This Passport server doesn't have sessions yet.");
|
|
318
|
+
const rows = (Array.isArray(page.sessions) ? page.sessions : []).slice(0, 50);
|
|
319
|
+
const now = (deps.now ?? Date.now)();
|
|
320
|
+
const human = rows.length
|
|
321
|
+
? rows.map((row) => sessionLine(row, now)).join("\n")
|
|
322
|
+
: "No sessions yet. Start your agent and its actions will show up here.";
|
|
323
|
+
return { json: { sessions: rows, nextCursor: page.nextCursor ?? null }, human };
|
|
324
|
+
}
|
|
325
|
+
function isPresetName(value) {
|
|
326
|
+
return value === "careful" || value === "balanced" || value === "handsoff";
|
|
327
|
+
}
|
|
328
|
+
function presetMap(raw) {
|
|
329
|
+
if (!raw || typeof raw !== "object")
|
|
330
|
+
return null;
|
|
331
|
+
const body = raw;
|
|
332
|
+
const out = {};
|
|
333
|
+
for (const env of ENV_KINDS) {
|
|
334
|
+
const preset = body[env];
|
|
335
|
+
if (!isPresetName(preset))
|
|
336
|
+
return null;
|
|
337
|
+
out[env] = preset;
|
|
338
|
+
}
|
|
339
|
+
if (isPresetName(body[OTHER_APPS]))
|
|
340
|
+
out[OTHER_APPS] = body[OTHER_APPS];
|
|
341
|
+
return out;
|
|
342
|
+
}
|
|
343
|
+
/** Read presets and floors for `passport status`. Never throws. */
|
|
344
|
+
export async function autopilotStatus(fetchApi, profile, signal, now = Date.now()) {
|
|
345
|
+
const cached = profile ? readCliPolicy(profile) : null;
|
|
346
|
+
const cache = {
|
|
347
|
+
version: cached?.version ?? null,
|
|
348
|
+
fetchedAt: cached?.fetchedAt ?? null,
|
|
349
|
+
ageMs: cached ? Math.max(0, now - cached.fetchedAt) : null
|
|
350
|
+
};
|
|
351
|
+
try {
|
|
352
|
+
const response = await fetchApi("/api/my/autopilot", {
|
|
353
|
+
method: "GET",
|
|
354
|
+
headers: { accept: "application/json" },
|
|
355
|
+
signal
|
|
356
|
+
});
|
|
357
|
+
if (!response.ok) {
|
|
358
|
+
await response.body?.cancel().catch(() => undefined);
|
|
359
|
+
return { presets: null, floors: null, cache };
|
|
360
|
+
}
|
|
361
|
+
const body = await readBoundedJson(response);
|
|
362
|
+
const floors = {};
|
|
363
|
+
for (const row of PRESET_ROWS) {
|
|
364
|
+
const floor = body.floors?.[row];
|
|
365
|
+
floors[row] = isPresetName(floor) ? floor : null;
|
|
366
|
+
}
|
|
367
|
+
const reason = text(body.floors?.reason, 120);
|
|
368
|
+
return { presets: presetMap(body.presets), floors, ...(reason ? { floorReason: reason } : {}), cache };
|
|
369
|
+
}
|
|
370
|
+
catch {
|
|
371
|
+
return { presets: null, floors: null, cache };
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
export function autopilotLines(status) {
|
|
375
|
+
const lines = [];
|
|
376
|
+
if (status.presets) {
|
|
377
|
+
const presets = status.presets;
|
|
378
|
+
const rows = PRESET_ROWS.filter((row) => presets[row]);
|
|
379
|
+
lines.push(`Autopilot: ${rows.map((row) => `${rowLabel(row)} ${PRESET_LABEL[presets[row]]}`).join(" · ")}`);
|
|
380
|
+
const floors = PRESET_ROWS.filter((row) => status.floors?.[row]).map((row) => `${rowLabel(row)} at least ${PRESET_LABEL[status.floors[row]]}`);
|
|
381
|
+
if (floors.length)
|
|
382
|
+
lines.push(`Team floors: ${floors.join(" · ")}${status.floorReason ? ` (${sanitize(status.floorReason)})` : ""}`);
|
|
383
|
+
}
|
|
384
|
+
const { cache } = status;
|
|
385
|
+
lines.push(cache.fetchedAt === null
|
|
386
|
+
? "Rules on this computer: not synced yet"
|
|
387
|
+
: `Rules on this computer: synced ${ageText(cache.ageMs ?? 0)}${cache.version === 1 ? " (older server: asks before destructive commands only)" : ""}`);
|
|
388
|
+
return lines;
|
|
389
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Autopilot decisions on this machine, from the cached cli-policy v2.
|
|
3
|
+
*
|
|
4
|
+
* The same order the server uses (docs: autopilot map, section 4):
|
|
5
|
+
* 1. Block rules → Blocked.
|
|
6
|
+
* 2. (Grants given in this session live on the server; unattended runs ask it.)
|
|
7
|
+
* 3. The most specific exception (action > app > class), strictest across
|
|
8
|
+
* scopes, never looser than the team floor.
|
|
9
|
+
* 4. The environment preset, bounded by the floor, applied to the class.
|
|
10
|
+
* 5. Irreversible actions ask unless step 3 allowed them.
|
|
11
|
+
*
|
|
12
|
+
* Every decision carries its cause, and every cause reads as one line.
|
|
13
|
+
*/
|
|
14
|
+
import { type EnvKind } from "./cliHookEnvironment.js";
|
|
15
|
+
export declare const PRESETS: readonly ["careful", "balanced", "handsoff"];
|
|
16
|
+
export type Preset = (typeof PRESETS)[number];
|
|
17
|
+
export declare const ACTION_CLASSES: readonly ["read", "change", "delete", "irreversible"];
|
|
18
|
+
export type ActionClass = (typeof ACTION_CLASSES)[number];
|
|
19
|
+
export type Decision = "allow" | "ask" | "block";
|
|
20
|
+
export type CauseKind = "block" | "grant" | "rule" | "floor" | "preset" | "default";
|
|
21
|
+
export type Cause = {
|
|
22
|
+
kind: CauseKind;
|
|
23
|
+
id?: string;
|
|
24
|
+
label: string;
|
|
25
|
+
};
|
|
26
|
+
/** A CLI-relevant rule, flattened by the server (`CliPolicyRule`). */
|
|
27
|
+
export type CliRule = {
|
|
28
|
+
id: string;
|
|
29
|
+
decision: Decision;
|
|
30
|
+
vendor?: string;
|
|
31
|
+
verb?: string;
|
|
32
|
+
/** An app rule: matches every command of that platform's CLI. */
|
|
33
|
+
appKey?: string;
|
|
34
|
+
actionClass?: ActionClass;
|
|
35
|
+
environment: EnvKind | "any";
|
|
36
|
+
/** "me", "workspace", or "team:<name>": who the rule belongs to. */
|
|
37
|
+
scope?: string;
|
|
38
|
+
/** The server's owner words: "Your rule", "Engineering team rule". */
|
|
39
|
+
owner?: string;
|
|
40
|
+
/** The server's whole cause line, used as is when present. */
|
|
41
|
+
label?: string;
|
|
42
|
+
};
|
|
43
|
+
/** A flag that names an environment: `--prod` names one itself, `--environment`
|
|
44
|
+
* takes the name as its value. */
|
|
45
|
+
export type EnvironmentFlag = {
|
|
46
|
+
flag: string;
|
|
47
|
+
value?: EnvKind;
|
|
48
|
+
};
|
|
49
|
+
export type AutopilotPolicy = {
|
|
50
|
+
presets: Record<EnvKind, Preset>;
|
|
51
|
+
floors: Record<EnvKind, Preset | null>;
|
|
52
|
+
rules: CliRule[];
|
|
53
|
+
/** Verbs that are irreversible wherever they run. */
|
|
54
|
+
irreversible: Record<string, string[]>;
|
|
55
|
+
/** Verbs that are irreversible only in Production. */
|
|
56
|
+
irreversibleInProduction?: Record<string, string[]>;
|
|
57
|
+
/** Write verbs a safety pack counts as deletes. */
|
|
58
|
+
deletes?: Record<string, string[]>;
|
|
59
|
+
environmentFlags?: Record<string, EnvironmentFlag[]>;
|
|
60
|
+
/** Environments the workspace has placed, by vendor and name. */
|
|
61
|
+
environments?: Array<{
|
|
62
|
+
vendor: string;
|
|
63
|
+
name: string;
|
|
64
|
+
kind: EnvKind;
|
|
65
|
+
}>;
|
|
66
|
+
};
|
|
67
|
+
/** The platform a vendor CLI acts on, so its rules and environments line up
|
|
68
|
+
* with the same platform's MCP app (server `cliPlatform`). */
|
|
69
|
+
export declare function platformOf(vendor: string): string;
|
|
70
|
+
/** The preset card's rows: the three environments, plus "Other apps" (apps
|
|
71
|
+
* with no environments) when the server sends it. */
|
|
72
|
+
export declare const OTHER_APPS = "other";
|
|
73
|
+
export type PresetRow = EnvKind | typeof OTHER_APPS;
|
|
74
|
+
export declare const PRESET_ROWS: PresetRow[];
|
|
75
|
+
export declare function rowLabel(row: string): string;
|
|
76
|
+
export declare const PRESET_LABEL: Record<Preset, string>;
|
|
77
|
+
export declare const DEFAULT_PRESETS: Record<EnvKind, Preset>;
|
|
78
|
+
export declare function stricterPreset(a: Preset, b: Preset | null | undefined): Preset;
|
|
79
|
+
export declare function presetStrictness(preset: Preset): number;
|
|
80
|
+
export declare function presetDecision(preset: Preset, actionClass: ActionClass): Decision;
|
|
81
|
+
export type ActionFacts = {
|
|
82
|
+
vendor: string;
|
|
83
|
+
/** The vendor-map verb, e.g. `volume delete` or `push --force`. */
|
|
84
|
+
verb: string;
|
|
85
|
+
actionClass: ActionClass;
|
|
86
|
+
environment: EnvKind;
|
|
87
|
+
};
|
|
88
|
+
export type LocalDecision = {
|
|
89
|
+
decision: Decision;
|
|
90
|
+
cause: Cause;
|
|
91
|
+
};
|
|
92
|
+
/** The server's `decideAction`, minus grants (only the server knows them). */
|
|
93
|
+
export declare function decideAction(policy: AutopilotPolicy, facts: ActionFacts): LocalDecision;
|
|
94
|
+
export declare function decisionRank(decision: Decision): number;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Autopilot decisions on this machine, from the cached cli-policy v2.
|
|
3
|
+
*
|
|
4
|
+
* The same order the server uses (docs: autopilot map, section 4):
|
|
5
|
+
* 1. Block rules → Blocked.
|
|
6
|
+
* 2. (Grants given in this session live on the server; unattended runs ask it.)
|
|
7
|
+
* 3. The most specific exception (action > app > class), strictest across
|
|
8
|
+
* scopes, never looser than the team floor.
|
|
9
|
+
* 4. The environment preset, bounded by the floor, applied to the class.
|
|
10
|
+
* 5. Irreversible actions ask unless step 3 allowed them.
|
|
11
|
+
*
|
|
12
|
+
* Every decision carries its cause, and every cause reads as one line.
|
|
13
|
+
*/
|
|
14
|
+
import { ENV_LABEL } from "./cliHookEnvironment.js";
|
|
15
|
+
export const PRESETS = ["careful", "balanced", "handsoff"];
|
|
16
|
+
export const ACTION_CLASSES = ["read", "change", "delete", "irreversible"];
|
|
17
|
+
/** The platform a vendor CLI acts on, so its rules and environments line up
|
|
18
|
+
* with the same platform's MCP app (server `cliPlatform`). */
|
|
19
|
+
export function platformOf(vendor) {
|
|
20
|
+
if (vendor === "git" || vendor === "gh")
|
|
21
|
+
return "github";
|
|
22
|
+
if (vendor === "wrangler")
|
|
23
|
+
return "cloudflare";
|
|
24
|
+
if (vendor === "neonctl" || vendor === "neon")
|
|
25
|
+
return "neon";
|
|
26
|
+
return vendor;
|
|
27
|
+
}
|
|
28
|
+
/** The preset card's rows: the three environments, plus "Other apps" (apps
|
|
29
|
+
* with no environments) when the server sends it. */
|
|
30
|
+
export const OTHER_APPS = "other";
|
|
31
|
+
export const PRESET_ROWS = ["production", "staging", "development", OTHER_APPS];
|
|
32
|
+
export function rowLabel(row) {
|
|
33
|
+
return row === OTHER_APPS ? "Other apps" : (ENV_LABEL[row] ?? row);
|
|
34
|
+
}
|
|
35
|
+
export const PRESET_LABEL = {
|
|
36
|
+
careful: "Careful",
|
|
37
|
+
balanced: "Balanced",
|
|
38
|
+
handsoff: "Hands-off"
|
|
39
|
+
};
|
|
40
|
+
/** What each preset does, per class. Irreversible always asks. */
|
|
41
|
+
const PRESET_TABLE = {
|
|
42
|
+
careful: { read: "allow", change: "ask", delete: "ask", irreversible: "ask" },
|
|
43
|
+
balanced: { read: "allow", change: "allow", delete: "ask", irreversible: "ask" },
|
|
44
|
+
handsoff: { read: "allow", change: "allow", delete: "allow", irreversible: "ask" }
|
|
45
|
+
};
|
|
46
|
+
export const DEFAULT_PRESETS = {
|
|
47
|
+
production: "careful",
|
|
48
|
+
staging: "balanced",
|
|
49
|
+
development: "handsoff"
|
|
50
|
+
};
|
|
51
|
+
const STRICTNESS = { careful: 2, balanced: 1, handsoff: 0 };
|
|
52
|
+
const DECISION_RANK = { allow: 0, ask: 1, block: 2 };
|
|
53
|
+
export function stricterPreset(a, b) {
|
|
54
|
+
return b && STRICTNESS[b] > STRICTNESS[a] ? b : a;
|
|
55
|
+
}
|
|
56
|
+
export function presetStrictness(preset) {
|
|
57
|
+
return STRICTNESS[preset];
|
|
58
|
+
}
|
|
59
|
+
export function presetDecision(preset, actionClass) {
|
|
60
|
+
return PRESET_TABLE[preset][actionClass];
|
|
61
|
+
}
|
|
62
|
+
const CLASS_PLURAL = {
|
|
63
|
+
read: "reads",
|
|
64
|
+
change: "changes",
|
|
65
|
+
delete: "deletes",
|
|
66
|
+
irreversible: "irreversible actions"
|
|
67
|
+
};
|
|
68
|
+
const CLASS_SEVERITY = { read: 0, change: 1, delete: 2, irreversible: 3 };
|
|
69
|
+
const LEVEL_ACTION = 3;
|
|
70
|
+
const LEVEL_APP = 2;
|
|
71
|
+
const LEVEL_CLASS = 1;
|
|
72
|
+
function ruleLevel(rule) {
|
|
73
|
+
if (rule.vendor !== undefined && rule.verb !== undefined)
|
|
74
|
+
return LEVEL_ACTION;
|
|
75
|
+
if (rule.appKey !== undefined)
|
|
76
|
+
return LEVEL_APP;
|
|
77
|
+
if (rule.actionClass !== undefined)
|
|
78
|
+
return LEVEL_CLASS;
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
function appMatches(key, facts) {
|
|
82
|
+
return key === platformOf(facts.vendor) || key === facts.vendor || key === `cli:${facts.vendor}`;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The server's `ruleMatches`: ask and block rules on a class also cover more
|
|
86
|
+
* severe classes ("no changes" stops deletes too); an allow covers only its
|
|
87
|
+
* own class, and only an action-level allow lets an irreversible action run.
|
|
88
|
+
*/
|
|
89
|
+
function ruleMatches(rule, facts) {
|
|
90
|
+
if (rule.environment !== "any" && rule.environment !== facts.environment)
|
|
91
|
+
return false;
|
|
92
|
+
const level = ruleLevel(rule);
|
|
93
|
+
if (level === 0)
|
|
94
|
+
return false;
|
|
95
|
+
if (level === LEVEL_ACTION) {
|
|
96
|
+
if (rule.vendor !== facts.vendor || rule.verb !== facts.verb)
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
else if (rule.appKey !== undefined && !appMatches(rule.appKey, facts)) {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
if (rule.actionClass !== undefined) {
|
|
103
|
+
const own = CLASS_SEVERITY[facts.actionClass];
|
|
104
|
+
const ruled = CLASS_SEVERITY[rule.actionClass];
|
|
105
|
+
if (rule.decision === "allow" ? own !== ruled : own < ruled)
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
if (rule.decision === "allow" && facts.actionClass === "irreversible" && level !== LEVEL_ACTION)
|
|
109
|
+
return false;
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
function matchText(rule) {
|
|
113
|
+
if (rule.vendor !== undefined && rule.verb !== undefined)
|
|
114
|
+
return `${rule.vendor} ${rule.verb}`;
|
|
115
|
+
if (rule.appKey && rule.actionClass)
|
|
116
|
+
return `${rule.appKey} ${CLASS_PLURAL[rule.actionClass]}`;
|
|
117
|
+
if (rule.appKey)
|
|
118
|
+
return `${rule.appKey} actions`;
|
|
119
|
+
return rule.actionClass ? CLASS_PLURAL[rule.actionClass] : "actions";
|
|
120
|
+
}
|
|
121
|
+
/** "Team rule, no deletes in Production"; the server's own label when it sent one. */
|
|
122
|
+
function ruleLabel(rule) {
|
|
123
|
+
if (rule.label)
|
|
124
|
+
return rule.label;
|
|
125
|
+
const owner = rule.owner
|
|
126
|
+
? rule.owner
|
|
127
|
+
: rule.scope === "me"
|
|
128
|
+
? "Your rule"
|
|
129
|
+
: rule.scope === "workspace"
|
|
130
|
+
? "Workspace rule"
|
|
131
|
+
: rule.scope
|
|
132
|
+
? "Team rule"
|
|
133
|
+
: "Rule";
|
|
134
|
+
const verb = rule.decision === "allow" ? "always run" : rule.decision === "ask" ? "ask before" : "no";
|
|
135
|
+
const where = rule.environment === "any" ? "" : ` in ${ENV_LABEL[rule.environment]}`;
|
|
136
|
+
// cli-policy v2 doesn't say whose rule it is; don't guess.
|
|
137
|
+
if (owner === "Rule")
|
|
138
|
+
return `A rule says ${verb} ${matchText(rule)}${where}`;
|
|
139
|
+
return `${owner}, ${verb} ${matchText(rule)}${where}`;
|
|
140
|
+
}
|
|
141
|
+
function presetLabel(env, preset, actionClass, decision) {
|
|
142
|
+
if (actionClass === "read")
|
|
143
|
+
return "Reads always run";
|
|
144
|
+
if (actionClass === "irreversible")
|
|
145
|
+
return "Irreversible actions always ask";
|
|
146
|
+
if (decision === "allow")
|
|
147
|
+
return `${ENV_LABEL[env]} is ${PRESET_LABEL[preset]}`;
|
|
148
|
+
return `${ENV_LABEL[env]} ${CLASS_PLURAL[actionClass]} ask first (${PRESET_LABEL[preset]})`;
|
|
149
|
+
}
|
|
150
|
+
function floorLabel(env, preset) {
|
|
151
|
+
return `Your team requires ${PRESET_LABEL[preset]} or stricter in ${ENV_LABEL[env]}`;
|
|
152
|
+
}
|
|
153
|
+
function mostSpecific(rules) {
|
|
154
|
+
const top = Math.max(...rules.map(ruleLevel));
|
|
155
|
+
return rules.filter((rule) => ruleLevel(rule) === top);
|
|
156
|
+
}
|
|
157
|
+
function stricter(a, b) {
|
|
158
|
+
return DECISION_RANK[b] > DECISION_RANK[a] ? b : a;
|
|
159
|
+
}
|
|
160
|
+
/** The server's `decideAction`, minus grants (only the server knows them). */
|
|
161
|
+
export function decideAction(policy, facts) {
|
|
162
|
+
const matching = policy.rules.filter((rule) => ruleMatches(rule, facts));
|
|
163
|
+
// 1. Block rules, any scope. The most specific one names the cause.
|
|
164
|
+
const blocks = matching.filter((rule) => rule.decision === "block");
|
|
165
|
+
if (blocks.length) {
|
|
166
|
+
const rule = mostSpecific(blocks)[0];
|
|
167
|
+
return { decision: "block", cause: { kind: "block", id: rule.id, label: ruleLabel(rule) } };
|
|
168
|
+
}
|
|
169
|
+
const floor = policy.floors[facts.environment] ?? null;
|
|
170
|
+
const floorDecision = floor ? presetDecision(floor, facts.actionClass) : undefined;
|
|
171
|
+
// 3. The most specific exception, strictest across scopes, bounded by the floor.
|
|
172
|
+
const exceptions = matching.filter((rule) => rule.decision !== "block");
|
|
173
|
+
if (exceptions.length) {
|
|
174
|
+
const rule = mostSpecific(exceptions).reduce((best, next) => DECISION_RANK[next.decision] > DECISION_RANK[best.decision] ? next : best);
|
|
175
|
+
if (floor && floorDecision && stricter(rule.decision, floorDecision) !== rule.decision) {
|
|
176
|
+
return { decision: floorDecision, cause: { kind: "floor", label: floorLabel(facts.environment, floor) } };
|
|
177
|
+
}
|
|
178
|
+
return { decision: rule.decision, cause: { kind: "rule", id: rule.id, label: ruleLabel(rule) } };
|
|
179
|
+
}
|
|
180
|
+
// 4 + 5. The environment preset, raised to the floor; irreversible always asks.
|
|
181
|
+
const own = policy.presets[facts.environment] ?? DEFAULT_PRESETS[facts.environment];
|
|
182
|
+
const ownDecision = presetDecision(own, facts.actionClass);
|
|
183
|
+
if (floor && floorDecision && stricter(ownDecision, floorDecision) !== ownDecision) {
|
|
184
|
+
return { decision: floorDecision, cause: { kind: "floor", label: floorLabel(facts.environment, floor) } };
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
decision: ownDecision,
|
|
188
|
+
cause: { kind: "preset", label: presetLabel(facts.environment, own, facts.actionClass, ownDecision) }
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
export function decisionRank(decision) {
|
|
192
|
+
return DECISION_RANK[decision];
|
|
193
|
+
}
|