passport-bridge 0.13.2 → 0.15.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 +113 -17
- package/dist/cli.js +4 -3
- package/dist/cliAnswered.d.ts +38 -0
- package/dist/cliAnswered.js +217 -0
- package/dist/cliArgs.d.ts +1 -1
- package/dist/cliArgs.js +44 -8
- package/dist/cliAutopilot.d.ts +77 -0
- package/dist/cliAutopilot.js +490 -0
- package/dist/cliAutopilotPolicy.d.ts +106 -0
- package/dist/cliAutopilotPolicy.js +209 -0
- package/dist/cliClient.d.ts +7 -0
- package/dist/cliClient.js +36 -19
- package/dist/cliExec.d.ts +62 -0
- package/dist/cliExec.js +409 -0
- package/dist/cliHook.d.ts +25 -27
- package/dist/cliHook.js +199 -86
- package/dist/cliHookClassify.d.ts +26 -0
- package/dist/cliHookClassify.js +12 -1
- package/dist/cliHookDecide.d.ts +91 -0
- package/dist/cliHookDecide.js +173 -0
- package/dist/cliHookEnvironment.d.ts +55 -0
- package/dist/cliHookEnvironment.js +219 -0
- package/dist/cliHookGuard.d.ts +63 -12
- package/dist/cliHookGuard.js +290 -29
- package/dist/cliHookInput.d.ts +27 -0
- package/dist/cliHookInput.js +47 -0
- package/dist/cliHookInstall.js +35 -4
- package/dist/cliHookLocal.d.ts +79 -0
- package/dist/cliHookLocal.js +467 -0
- package/dist/cliHookMode.d.ts +31 -0
- package/dist/cliHookMode.js +50 -0
- package/dist/cliHookParse.d.ts +33 -0
- package/dist/cliHookParse.js +144 -30
- package/dist/cliHookRedact.d.ts +16 -0
- package/dist/cliHookRedact.js +136 -0
- package/dist/cliHookRewrite.d.ts +45 -0
- package/dist/cliHookRewrite.js +135 -0
- package/dist/cliInit.d.ts +4 -1
- package/dist/cliInit.js +11 -3
- package/dist/cliKeys.d.ts +67 -0
- package/dist/cliKeys.js +426 -0
- package/dist/cliLogin.js +19 -3
- package/dist/cliOffline.js +9 -9
- package/dist/cliOutput.js +17 -5
- package/dist/cliPolicy.d.ts +13 -3
- package/dist/cliPolicy.js +5 -2
- package/dist/cliPolicyRefresh.d.ts +7 -0
- package/dist/cliPolicyRefresh.js +20 -0
- package/dist/cliPolicyV2.d.ts +18 -0
- package/dist/cliPolicyV2.js +257 -0
- package/dist/cliSetupOrg.d.ts +15 -0
- package/dist/cliSetupOrg.js +253 -0
- package/dist/cliSupport.d.ts +4 -0
- package/dist/cliSupport.js +12 -9
- package/dist/cliSync.d.ts +14 -0
- package/dist/cliSync.js +63 -0
- package/dist/completion.js +19 -3
- package/dist/doctor.js +3 -3
- package/dist/enrollment.d.ts +18 -0
- package/dist/enrollment.js +79 -0
- package/dist/execMarker.d.ts +7 -0
- package/dist/execMarker.js +66 -0
- package/dist/execVendors.d.ts +34 -0
- package/dist/execVendors.js +221 -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 +283 -0
- package/dist/initKeysStep.d.ts +2 -0
- package/dist/initKeysStep.js +67 -0
- package/dist/initLocalSteps.d.ts +3 -0
- package/dist/initLocalSteps.js +31 -6
- package/dist/initState.d.ts +24 -0
- package/dist/initUi.js +5 -0
- package/dist/keysLocal.d.ts +56 -0
- package/dist/keysLocal.js +494 -0
- package/dist/localCommands.d.ts +39 -0
- package/dist/localCommands.js +534 -0
- package/dist/localFiles.d.ts +22 -0
- package/dist/localFiles.js +272 -0
- package/dist/localGit.d.ts +24 -0
- package/dist/localGit.js +270 -0
- package/dist/localNetwork.d.ts +16 -0
- package/dist/localNetwork.js +185 -0
- package/dist/localShared.d.ts +99 -0
- package/dist/localShared.js +173 -0
- package/dist/localTools.d.ts +52 -0
- package/dist/localTools.js +643 -0
- package/dist/nativeSync.d.ts +89 -0
- package/dist/nativeSync.js +376 -0
- package/dist/passport.js +42 -5
- 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,77 @@
|
|
|
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 { type ParsedArgs } from "./cliArgs.js";
|
|
14
|
+
import { type Preset, type PresetRow } from "./cliAutopilotPolicy.js";
|
|
15
|
+
import { type MemberApi } from "./cliClient.js";
|
|
16
|
+
import { type LocalMachine } from "./cliHookLocal.js";
|
|
17
|
+
import { type EnvKind } from "./cliHookEnvironment.js";
|
|
18
|
+
import { type CommandResult, type Runtime } from "./cliSupport.js";
|
|
19
|
+
/** Long enough to be useful, short enough for an agent's default 2-minute
|
|
20
|
+
* command timeout. */
|
|
21
|
+
export declare const WAIT_DEFAULT_SECONDS = 100;
|
|
22
|
+
export type AutopilotDependencies = {
|
|
23
|
+
api?: MemberApi;
|
|
24
|
+
now?: () => number;
|
|
25
|
+
/** The machine `rules test` reads paths on; tests pass a pretend one. */
|
|
26
|
+
machine?: LocalMachine;
|
|
27
|
+
};
|
|
28
|
+
export declare function wait(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
|
|
29
|
+
export declare function rules(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
|
|
30
|
+
type SessionRow = {
|
|
31
|
+
id?: unknown;
|
|
32
|
+
client?: unknown;
|
|
33
|
+
folder?: unknown;
|
|
34
|
+
status?: unknown;
|
|
35
|
+
startedAt?: unknown;
|
|
36
|
+
lastActivityAt?: unknown;
|
|
37
|
+
counts?: {
|
|
38
|
+
ran?: unknown;
|
|
39
|
+
asked?: unknown;
|
|
40
|
+
approved?: unknown;
|
|
41
|
+
declined?: unknown;
|
|
42
|
+
blocked?: unknown;
|
|
43
|
+
};
|
|
44
|
+
environments?: unknown;
|
|
45
|
+
waiting?: unknown;
|
|
46
|
+
};
|
|
47
|
+
export declare function sessionLine(row: SessionRow, now: number, unicode?: boolean): string;
|
|
48
|
+
export declare function sessions(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
|
|
49
|
+
export type AutopilotStatus = {
|
|
50
|
+
/** The three environments, and "other" (Other apps) when the server has it. */
|
|
51
|
+
presets: (Record<EnvKind, Preset> & Partial<Record<PresetRow, Preset>>) | null;
|
|
52
|
+
floors: Partial<Record<PresetRow, Preset | null>> | null;
|
|
53
|
+
floorReason?: string;
|
|
54
|
+
cache: {
|
|
55
|
+
version: 1 | 2 | null;
|
|
56
|
+
fetchedAt: number | null;
|
|
57
|
+
ageMs: number | null;
|
|
58
|
+
};
|
|
59
|
+
/** "Answered for you" today: across your computers when Passport keeps the
|
|
60
|
+
* count, else this computer's own. */
|
|
61
|
+
answered?: {
|
|
62
|
+
today: number;
|
|
63
|
+
source: "workspace" | "this-computer";
|
|
64
|
+
};
|
|
65
|
+
/** Agents whose own allowlist Passport keeps in sync, with how many entries. */
|
|
66
|
+
allowlists?: Array<{
|
|
67
|
+
agent: string;
|
|
68
|
+
name: string;
|
|
69
|
+
entries: number;
|
|
70
|
+
}>;
|
|
71
|
+
};
|
|
72
|
+
/** Local midnight, so "today" is the person's today wherever the server is. */
|
|
73
|
+
export declare function localMidnight(now: number): number;
|
|
74
|
+
/** Read presets and floors for `passport status`. Never throws. */
|
|
75
|
+
export declare function autopilotStatus(fetchApi: (path: string, init: RequestInit) => Promise<Response>, profile: string | undefined, signal: AbortSignal, now?: number): Promise<AutopilotStatus>;
|
|
76
|
+
export declare function autopilotLines(status: AutopilotStatus): string[];
|
|
77
|
+
export {};
|
|
@@ -0,0 +1,490 @@
|
|
|
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 { classifyLine, localMachine } from "./cliHookLocal.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, agentKeyOk = false) {
|
|
27
|
+
if (deps.api)
|
|
28
|
+
return deps.api;
|
|
29
|
+
const auth = resolveCliAuth(args, runtime.env);
|
|
30
|
+
if (auth.kind !== "profile" && !agentKeyOk) {
|
|
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
|
+
// A cloud agent waits on the approval its own `passport exec` opened; the
|
|
104
|
+
// request went to its owner.
|
|
105
|
+
const agentKey = !deps.api && Boolean(runtime.env.PASSPORT_AGENT_KEY);
|
|
106
|
+
const client = api(args, runtime, deps, (WAIT_POLL_SECONDS + 10) * 1000, true);
|
|
107
|
+
const base = agentKey ? "/api/my/exec/approvals/" : "/api/my/approvals/";
|
|
108
|
+
let announced = false;
|
|
109
|
+
for (;;) {
|
|
110
|
+
const left = Math.ceil((deadline - now()) / 1000);
|
|
111
|
+
const poll = Math.max(1, Math.min(WAIT_POLL_SECONDS, left));
|
|
112
|
+
const response = await client.fetchApi(`${base}${encodeURIComponent(id)}/wait?timeout=${poll}`, {
|
|
113
|
+
method: "GET",
|
|
114
|
+
headers: { accept: "application/json" },
|
|
115
|
+
signal: AbortSignal.any([runtime.signal, AbortSignal.timeout((poll + 10) * 1000)])
|
|
116
|
+
});
|
|
117
|
+
if (response.status === 404) {
|
|
118
|
+
// "No such approval." from a server that waits; anything else is an older server.
|
|
119
|
+
const message = await safeApiError(response, "");
|
|
120
|
+
if (/approval/i.test(message))
|
|
121
|
+
return waitOutcome(id, { status: "missing" });
|
|
122
|
+
return failure("This Passport server can't wait on approvals yet. Check Approvals on the web.", 1, "not_found");
|
|
123
|
+
}
|
|
124
|
+
const body = await json(response, "Passport couldn't find that approval.");
|
|
125
|
+
const outcome = waitOutcome(id, body);
|
|
126
|
+
if (outcome)
|
|
127
|
+
return outcome;
|
|
128
|
+
if (now() >= deadline) {
|
|
129
|
+
return failure(`Still waiting for approval. Run \`passport wait ${id}\` again, or continue with other work.`, 4, "approval_pending", {
|
|
130
|
+
approvalId: id,
|
|
131
|
+
next: [{ argv: ["passport", "wait", id], description: "Keep waiting for this approval." }]
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
if (!announced && !bool(args, "quiet") && !bool(args, "json")) {
|
|
135
|
+
runtime.stderr.write(`Waiting for a decision on ${id} (up to ${totalSeconds} seconds)...\n`);
|
|
136
|
+
announced = true;
|
|
137
|
+
}
|
|
138
|
+
// A server that answers at once instead of holding the request is polled gently.
|
|
139
|
+
if (response.headers.get("x-passport-long-poll") === "0")
|
|
140
|
+
await sleep(2_000, runtime.signal);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// ---- passport rules test ----------------------------------------------------
|
|
144
|
+
const DECISION_WORDS = { allow: "Runs", ask: "Asks first", block: "Blocked" };
|
|
145
|
+
const CLASS_WORDS = {
|
|
146
|
+
read: "Read",
|
|
147
|
+
change: "Change",
|
|
148
|
+
delete: "Delete",
|
|
149
|
+
irreversible: "Irreversible"
|
|
150
|
+
};
|
|
151
|
+
function ageText(ms) {
|
|
152
|
+
const minutes = Math.round(ms / 60_000);
|
|
153
|
+
if (minutes < 1)
|
|
154
|
+
return "just now";
|
|
155
|
+
if (minutes < 60)
|
|
156
|
+
return `${minutes} min ago`;
|
|
157
|
+
const hours = Math.round(minutes / 60);
|
|
158
|
+
return hours < 48 ? `${hours} h ago` : `${Math.round(hours / 24)} days ago`;
|
|
159
|
+
}
|
|
160
|
+
function ruleTestLines(label, result, source) {
|
|
161
|
+
if (result.decision === "none") {
|
|
162
|
+
return [
|
|
163
|
+
label,
|
|
164
|
+
" No decision: Passport doesn't decide this command, so your agent's own prompt applies.",
|
|
165
|
+
...(source ? [` ${source}`] : [])
|
|
166
|
+
];
|
|
167
|
+
}
|
|
168
|
+
const explanation = text(result.explanation) ?? `${DECISION_WORDS[result.decision]}${result.cause ? `: ${result.cause.label}` : ""}.`;
|
|
169
|
+
const environment = result.environment
|
|
170
|
+
? `${rowLabel(result.environment)}${result.environmentAssumed ? " (assumed)" : ""}`
|
|
171
|
+
: undefined;
|
|
172
|
+
return [
|
|
173
|
+
label,
|
|
174
|
+
` ${explanation}`,
|
|
175
|
+
...(environment ? [` Environment: ${environment}`] : []),
|
|
176
|
+
...(result.actionClass ? [` Class: ${CLASS_WORDS[result.actionClass]}`] : []),
|
|
177
|
+
` ${source}`
|
|
178
|
+
];
|
|
179
|
+
}
|
|
180
|
+
/** Place every finding in the environment the person picked. */
|
|
181
|
+
function inEnvironment(findings, environment) {
|
|
182
|
+
if (!environment)
|
|
183
|
+
return findings;
|
|
184
|
+
return findings.map((finding) => !finding.vendor
|
|
185
|
+
? finding
|
|
186
|
+
: finding.local
|
|
187
|
+
? { ...finding, local: { ...finding.local, environment } }
|
|
188
|
+
: { ...finding, pushEnvironment: undefined, args: [...(finding.args ?? []), "--environment", environment] });
|
|
189
|
+
}
|
|
190
|
+
function localTest(command, findings, complete, policy) {
|
|
191
|
+
const decision = decideGuard(findings, policy, command, complete);
|
|
192
|
+
if (!decision)
|
|
193
|
+
return null;
|
|
194
|
+
return {
|
|
195
|
+
decision: decision.verdict === "deny" ? "block" : decision.verdict,
|
|
196
|
+
...(decision.cause ? { cause: decision.cause } : {}),
|
|
197
|
+
...(decision.environment ? { environment: decision.environment } : {}),
|
|
198
|
+
...(decision.environmentSource === "assumed" ? { environmentAssumed: true } : {}),
|
|
199
|
+
...(decision.actionClass ? { actionClass: decision.actionClass } : {})
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* What `rules test` sends: an everyday command as what it is (program, verb,
|
|
204
|
+
* class, place), never its words; a vendor command as its label.
|
|
205
|
+
*/
|
|
206
|
+
function testBody(lead, label, cached, environment) {
|
|
207
|
+
if (lead.local) {
|
|
208
|
+
const finding = { vendor: lead.vendor, verb: lead.verb ?? "invoke", risk: lead.risk };
|
|
209
|
+
return { finding: { ...finding, environment: environment ?? lead.local.environment } };
|
|
210
|
+
}
|
|
211
|
+
const hint = lead.vendor
|
|
212
|
+
? environmentHintWith(lead.vendor, lead.args ?? [], cached?.version === 2 ? { flags: cached.autopilot.environmentFlags, known: cached.autopilot.environments } : {})
|
|
213
|
+
: undefined;
|
|
214
|
+
const placed = environment ?? lead.pushEnvironment ?? (hint && hint.source !== "assumed" ? hint.kind : undefined);
|
|
215
|
+
return { command: label, ...(placed ? { environment: placed } : {}) };
|
|
216
|
+
}
|
|
217
|
+
/** The workspace's answer, or null to decide on this computer. */
|
|
218
|
+
async function askServer(body, args, runtime, deps) {
|
|
219
|
+
try {
|
|
220
|
+
const client = api(args, runtime, deps);
|
|
221
|
+
const response = await client.fetchApi("/api/my/rules/test", {
|
|
222
|
+
method: "POST",
|
|
223
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
224
|
+
body: JSON.stringify(body),
|
|
225
|
+
signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
|
|
226
|
+
});
|
|
227
|
+
if (!response.ok) {
|
|
228
|
+
await response.body?.cancel().catch(() => undefined);
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
const answer = await readBoundedJson(response);
|
|
232
|
+
// Only an answer with a decision counts; anything else falls back to this computer.
|
|
233
|
+
return answer && ["allow", "ask", "block", "none"].includes(answer.decision) ? answer : null;
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
if (runtime.signal.aborted)
|
|
237
|
+
throw error;
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
export async function rules(args, runtime, deps = {}) {
|
|
242
|
+
const [action, command] = args.positionals;
|
|
243
|
+
if (action !== "test" || !command?.trim()) {
|
|
244
|
+
return failure('Use: passport rules test "<command>" [--environment production|staging|development]', 6, "usage");
|
|
245
|
+
}
|
|
246
|
+
const environmentFlag = value(args, "environment");
|
|
247
|
+
if (environmentFlag !== undefined && !isEnvKind(environmentFlag)) {
|
|
248
|
+
return failure("--environment must be production, staging, or development.", 6, "usage");
|
|
249
|
+
}
|
|
250
|
+
const environment = environmentFlag;
|
|
251
|
+
// Paths are read where you run this, like the hook reads the agent's folder.
|
|
252
|
+
const line = classifyLine(command, deps.machine ?? localMachine(process.cwd(), runtime.env));
|
|
253
|
+
const all = inEnvironment(line.findings, environment);
|
|
254
|
+
const findings = all.filter((finding) => finding.vendor);
|
|
255
|
+
if (!findings.length) {
|
|
256
|
+
const result = { decision: "none" };
|
|
257
|
+
return {
|
|
258
|
+
json: { command: null, ...result },
|
|
259
|
+
human: ruleTestLines("This command", result, "").filter(Boolean).join("\n")
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
const profile = (() => {
|
|
263
|
+
try {
|
|
264
|
+
const auth = resolveCliAuth(args, runtime.env);
|
|
265
|
+
return auth.kind === "profile" ? auth.profile : undefined;
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
})();
|
|
271
|
+
const cached = profile ? readCliPolicy(profile) : null;
|
|
272
|
+
const decided = decideGuard(all, cached, command, line.complete);
|
|
273
|
+
// The command that decides: the strictest one the rules spoke about.
|
|
274
|
+
const lead = decided?.findings[0] ?? findings[0];
|
|
275
|
+
const label = guardLabel(lead);
|
|
276
|
+
const local = localTest(command, all, line.complete, cached);
|
|
277
|
+
// The server knows grants, every rule, and the workspace's environments.
|
|
278
|
+
const asked = profile || deps.api ? await askServer(testBody(lead, label, cached, environment), args, runtime, deps) : null;
|
|
279
|
+
let result = asked;
|
|
280
|
+
let source = result ? "Decided by your workspace's rules." : "";
|
|
281
|
+
if (!result) {
|
|
282
|
+
result = local ?? { decision: "none" };
|
|
283
|
+
source = cached
|
|
284
|
+
? `Decided on this computer from rules synced ${ageText(Math.max(0, Date.now() - cached.fetchedAt))}.`
|
|
285
|
+
: "Decided on this computer from built-in rules. Run passport status to sync yours.";
|
|
286
|
+
}
|
|
287
|
+
return {
|
|
288
|
+
json: { command: label, ...result, source: source.startsWith("Decided by") ? "server" : "local" },
|
|
289
|
+
human: ruleTestLines(label, result, source).join("\n")
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
const CLIENT_NAMES = {
|
|
293
|
+
"claude-code": "Claude Code",
|
|
294
|
+
codex: "Codex",
|
|
295
|
+
cursor: "Cursor",
|
|
296
|
+
copilot: "Copilot",
|
|
297
|
+
cli: "Passport CLI"
|
|
298
|
+
};
|
|
299
|
+
function count(raw) {
|
|
300
|
+
return typeof raw === "number" && Number.isFinite(raw) && raw >= 0 ? Math.trunc(raw) : 0;
|
|
301
|
+
}
|
|
302
|
+
function when(ms, now) {
|
|
303
|
+
if (typeof ms !== "number")
|
|
304
|
+
return "";
|
|
305
|
+
const date = new Date(ms);
|
|
306
|
+
const sameDay = new Date(now).toDateString() === date.toDateString();
|
|
307
|
+
const time = date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
|
|
308
|
+
return sameDay ? time : `${date.toLocaleDateString("en-US", { month: "short", day: "numeric" })} ${time}`;
|
|
309
|
+
}
|
|
310
|
+
export function sessionLine(row, now, unicode = true) {
|
|
311
|
+
const status = row.status === "running" ? "Running" : row.status === "idle" ? "Idle" : "Ended";
|
|
312
|
+
const dot = row.status === "running" ? (unicode ? "● " : "* ") : " ";
|
|
313
|
+
const client = text(row.client, 40) ?? "agent";
|
|
314
|
+
const name = CLIENT_NAMES[client] ?? client;
|
|
315
|
+
const folder = text(row.folder, 40) ?? "";
|
|
316
|
+
const counts = row.counts ?? {};
|
|
317
|
+
const parts = [`${count(counts.ran)} ran`, `${count(counts.asked)} asked`];
|
|
318
|
+
if (count(counts.blocked))
|
|
319
|
+
parts.push(`${count(counts.blocked)} blocked`);
|
|
320
|
+
const environments = Array.isArray(row.environments)
|
|
321
|
+
? row.environments.filter(isEnvKind).map((env) => ENV_LABEL[env])
|
|
322
|
+
: [];
|
|
323
|
+
const waiting = count(row.waiting) ? ` Waiting for you (${count(row.waiting)})` : "";
|
|
324
|
+
return [
|
|
325
|
+
`${dot}${status.padEnd(7)}`,
|
|
326
|
+
name.padEnd(12),
|
|
327
|
+
folder.padEnd(18),
|
|
328
|
+
`started ${when(row.startedAt, now)}`.padEnd(18),
|
|
329
|
+
parts.join(" · "),
|
|
330
|
+
environments.length ? ` ${environments.join(", ")}` : ""
|
|
331
|
+
]
|
|
332
|
+
.join(" ")
|
|
333
|
+
.trimEnd()
|
|
334
|
+
.concat(waiting);
|
|
335
|
+
}
|
|
336
|
+
export async function sessions(args, runtime, deps = {}) {
|
|
337
|
+
const status = value(args, "status");
|
|
338
|
+
if (status !== undefined && !["running", "idle", "ended"].includes(status)) {
|
|
339
|
+
return failure("--status must be running, idle, or ended.", 6, "usage");
|
|
340
|
+
}
|
|
341
|
+
const client = api(args, runtime, deps);
|
|
342
|
+
const response = await client.fetchApi(`/api/my/agent-sessions${status ? `?status=${status}` : ""}`, {
|
|
343
|
+
method: "GET",
|
|
344
|
+
headers: { accept: "application/json" },
|
|
345
|
+
signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
|
|
346
|
+
});
|
|
347
|
+
const page = await json(response, "This Passport server doesn't have sessions yet.");
|
|
348
|
+
const rows = (Array.isArray(page.sessions) ? page.sessions : []).slice(0, 50);
|
|
349
|
+
const now = (deps.now ?? Date.now)();
|
|
350
|
+
const human = rows.length
|
|
351
|
+
? rows.map((row) => sessionLine(row, now)).join("\n")
|
|
352
|
+
: "No sessions yet. Start your agent and its actions will show up here.";
|
|
353
|
+
return { json: { sessions: rows, nextCursor: page.nextCursor ?? null }, human };
|
|
354
|
+
}
|
|
355
|
+
function isPresetName(value) {
|
|
356
|
+
return value === "careful" || value === "balanced" || value === "handsoff";
|
|
357
|
+
}
|
|
358
|
+
function presetMap(raw) {
|
|
359
|
+
if (!raw || typeof raw !== "object")
|
|
360
|
+
return null;
|
|
361
|
+
const body = raw;
|
|
362
|
+
const out = {};
|
|
363
|
+
for (const env of ENV_KINDS) {
|
|
364
|
+
const preset = body[env];
|
|
365
|
+
if (!isPresetName(preset))
|
|
366
|
+
return null;
|
|
367
|
+
out[env] = preset;
|
|
368
|
+
}
|
|
369
|
+
if (isPresetName(body[OTHER_APPS]))
|
|
370
|
+
out[OTHER_APPS] = body[OTHER_APPS];
|
|
371
|
+
return out;
|
|
372
|
+
}
|
|
373
|
+
/** Local midnight, so "today" is the person's today wherever the server is. */
|
|
374
|
+
export function localMidnight(now) {
|
|
375
|
+
const date = new Date(now);
|
|
376
|
+
date.setHours(0, 0, 0, 0);
|
|
377
|
+
return date.getTime();
|
|
378
|
+
}
|
|
379
|
+
async function answeredStatus(fetchApi, profile, signal, now) {
|
|
380
|
+
const { answeredToday } = await import("./cliAnswered.js");
|
|
381
|
+
const local = profile ? answeredToday(profile, now) : 0;
|
|
382
|
+
try {
|
|
383
|
+
const response = await fetchApi(`/api/my/stats?range=24h&todayStart=${localMidnight(now)}`, {
|
|
384
|
+
method: "GET",
|
|
385
|
+
headers: { accept: "application/json" },
|
|
386
|
+
signal
|
|
387
|
+
});
|
|
388
|
+
if (response.ok) {
|
|
389
|
+
const body = await readBoundedJson(response);
|
|
390
|
+
const today = body.answered?.today;
|
|
391
|
+
// Batches reach Passport every few minutes; never show less than this computer counted.
|
|
392
|
+
if (typeof today === "number" && Number.isFinite(today))
|
|
393
|
+
return { today: Math.max(today, local), source: "workspace" };
|
|
394
|
+
}
|
|
395
|
+
else
|
|
396
|
+
await response.body?.cancel().catch(() => undefined);
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
/* This computer's own count. */
|
|
400
|
+
}
|
|
401
|
+
return { today: local, source: "this-computer" };
|
|
402
|
+
}
|
|
403
|
+
async function allowlistStatus() {
|
|
404
|
+
try {
|
|
405
|
+
const { readManifest } = await import("./nativeSync.js");
|
|
406
|
+
const manifest = readManifest();
|
|
407
|
+
if (!manifest)
|
|
408
|
+
return undefined;
|
|
409
|
+
const names = {
|
|
410
|
+
"claude-code": "Claude Code",
|
|
411
|
+
codex: "Codex",
|
|
412
|
+
"cursor-cli": "Cursor CLI",
|
|
413
|
+
cursor: "Cursor"
|
|
414
|
+
};
|
|
415
|
+
return Object.entries(manifest.agents).map(([agent, entry]) => ({
|
|
416
|
+
agent,
|
|
417
|
+
name: names[agent] ?? agent,
|
|
418
|
+
entries: entry?.entries.length ?? 0
|
|
419
|
+
}));
|
|
420
|
+
}
|
|
421
|
+
catch {
|
|
422
|
+
return undefined;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
/** Read presets and floors for `passport status`. Never throws. */
|
|
426
|
+
export async function autopilotStatus(fetchApi, profile, signal, now = Date.now()) {
|
|
427
|
+
const cached = profile ? readCliPolicy(profile) : null;
|
|
428
|
+
const cache = {
|
|
429
|
+
version: cached?.version ?? null,
|
|
430
|
+
fetchedAt: cached?.fetchedAt ?? null,
|
|
431
|
+
ageMs: cached ? Math.max(0, now - cached.fetchedAt) : null
|
|
432
|
+
};
|
|
433
|
+
try {
|
|
434
|
+
const response = await fetchApi("/api/my/autopilot", {
|
|
435
|
+
method: "GET",
|
|
436
|
+
headers: { accept: "application/json" },
|
|
437
|
+
signal
|
|
438
|
+
});
|
|
439
|
+
if (!response.ok) {
|
|
440
|
+
await response.body?.cancel().catch(() => undefined);
|
|
441
|
+
return { presets: null, floors: null, cache };
|
|
442
|
+
}
|
|
443
|
+
const body = await readBoundedJson(response);
|
|
444
|
+
const floors = {};
|
|
445
|
+
for (const row of PRESET_ROWS) {
|
|
446
|
+
const floor = body.floors?.[row];
|
|
447
|
+
floors[row] = isPresetName(floor) ? floor : null;
|
|
448
|
+
}
|
|
449
|
+
const reason = text(body.floors?.reason, 120);
|
|
450
|
+
const answered = await answeredStatus(fetchApi, profile, signal, now);
|
|
451
|
+
const allowlists = await allowlistStatus();
|
|
452
|
+
return {
|
|
453
|
+
presets: presetMap(body.presets),
|
|
454
|
+
floors,
|
|
455
|
+
...(reason ? { floorReason: reason } : {}),
|
|
456
|
+
cache,
|
|
457
|
+
...(answered ? { answered } : {}),
|
|
458
|
+
...(allowlists ? { allowlists } : {})
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
return { presets: null, floors: null, cache };
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
export function autopilotLines(status) {
|
|
466
|
+
const lines = [];
|
|
467
|
+
if (status.presets) {
|
|
468
|
+
const presets = status.presets;
|
|
469
|
+
const rows = PRESET_ROWS.filter((row) => presets[row]);
|
|
470
|
+
lines.push(`Autopilot: ${rows.map((row) => `${rowLabel(row)} ${PRESET_LABEL[presets[row]]}`).join(" · ")}`);
|
|
471
|
+
const floors = PRESET_ROWS.filter((row) => status.floors?.[row]).map((row) => `${rowLabel(row)} at least ${PRESET_LABEL[status.floors[row]]}`);
|
|
472
|
+
if (floors.length)
|
|
473
|
+
lines.push(`Team floors: ${floors.join(" · ")}${status.floorReason ? ` (${sanitize(status.floorReason)})` : ""}`);
|
|
474
|
+
}
|
|
475
|
+
const { cache } = status;
|
|
476
|
+
lines.push(cache.fetchedAt === null
|
|
477
|
+
? "Rules on this computer: not synced yet"
|
|
478
|
+
: `Rules on this computer: synced ${ageText(cache.ageMs ?? 0)}${cache.version === 1 ? " (older server: asks before destructive commands only)" : ""}`);
|
|
479
|
+
if (status.answered) {
|
|
480
|
+
const count = status.answered.today;
|
|
481
|
+
lines.push(`Answered for you: ${count.toLocaleString("en-US")} ${count === 1 ? "prompt" : "prompts"} today${status.answered.source === "this-computer" ? " on this computer" : ""}`);
|
|
482
|
+
}
|
|
483
|
+
if (status.allowlists) {
|
|
484
|
+
const synced = status.allowlists.filter((entry) => entry.entries > 0);
|
|
485
|
+
lines.push(synced.length
|
|
486
|
+
? `Agent allowlists: ${synced.map((entry) => `${entry.name} (${entry.entries})`).join(", ")}, kept in sync by passport sync`
|
|
487
|
+
: "Agent allowlists: on, nothing to add yet");
|
|
488
|
+
}
|
|
489
|
+
return lines;
|
|
490
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
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: ActionEnv | "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
|
+
/** Where an action runs: an environment, or "other" (Other apps: apps
|
|
50
|
+
* without environments, and this computer outside the project). */
|
|
51
|
+
export type ActionEnv = EnvKind | "other";
|
|
52
|
+
export type AutopilotPolicy = {
|
|
53
|
+
presets: Record<EnvKind, Preset> & {
|
|
54
|
+
other?: Preset;
|
|
55
|
+
};
|
|
56
|
+
floors: Record<EnvKind, Preset | null> & {
|
|
57
|
+
other?: Preset | null;
|
|
58
|
+
};
|
|
59
|
+
rules: CliRule[];
|
|
60
|
+
/** Verbs that are irreversible wherever they run. */
|
|
61
|
+
irreversible: Record<string, string[]>;
|
|
62
|
+
/** Verbs that are irreversible only in Production. */
|
|
63
|
+
irreversibleInProduction?: Record<string, string[]>;
|
|
64
|
+
/** Write verbs a safety pack counts as deletes. */
|
|
65
|
+
deletes?: Record<string, string[]>;
|
|
66
|
+
environmentFlags?: Record<string, EnvironmentFlag[]>;
|
|
67
|
+
/** Environments the workspace has placed, by vendor and name. */
|
|
68
|
+
environments?: Array<{
|
|
69
|
+
vendor: string;
|
|
70
|
+
name: string;
|
|
71
|
+
kind: EnvKind;
|
|
72
|
+
}>;
|
|
73
|
+
/** The server decides everyday commands too (Phase 1.5): reports and
|
|
74
|
+
* decide requests may carry them. */
|
|
75
|
+
localCommands?: boolean;
|
|
76
|
+
};
|
|
77
|
+
/** The platform a vendor CLI acts on, so its rules and environments line up
|
|
78
|
+
* with the same platform's MCP app (server `cliPlatform`). */
|
|
79
|
+
export declare function platformOf(vendor: string): string;
|
|
80
|
+
/** The preset card's rows: the three environments, plus "Other apps" (apps
|
|
81
|
+
* with no environments) when the server sends it. */
|
|
82
|
+
export declare const OTHER_APPS = "other";
|
|
83
|
+
export type PresetRow = EnvKind | typeof OTHER_APPS;
|
|
84
|
+
export declare const PRESET_ROWS: PresetRow[];
|
|
85
|
+
export declare function rowLabel(row: string): string;
|
|
86
|
+
export declare const PRESET_LABEL: Record<Preset, string>;
|
|
87
|
+
export declare const DEFAULT_PRESETS: Record<ActionEnv, Preset>;
|
|
88
|
+
/** "Production", "Other apps". */
|
|
89
|
+
export declare function envLabel(env: ActionEnv): string;
|
|
90
|
+
export declare function stricterPreset(a: Preset, b: Preset | null | undefined): Preset;
|
|
91
|
+
export declare function presetStrictness(preset: Preset): number;
|
|
92
|
+
export declare function presetDecision(preset: Preset, actionClass: ActionClass): Decision;
|
|
93
|
+
export type ActionFacts = {
|
|
94
|
+
vendor: string;
|
|
95
|
+
/** The vendor-map verb, e.g. `volume delete` or `push --force`. */
|
|
96
|
+
verb: string;
|
|
97
|
+
actionClass: ActionClass;
|
|
98
|
+
environment: ActionEnv;
|
|
99
|
+
};
|
|
100
|
+
export type LocalDecision = {
|
|
101
|
+
decision: Decision;
|
|
102
|
+
cause: Cause;
|
|
103
|
+
};
|
|
104
|
+
/** The server's `decideAction`, minus grants (only the server knows them). */
|
|
105
|
+
export declare function decideAction(policy: AutopilotPolicy, facts: ActionFacts): LocalDecision;
|
|
106
|
+
export declare function decisionRank(decision: Decision): number;
|