passport-bridge 0.18.0 → 0.20.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 +5 -3
- package/dist/approvalLines.d.ts +17 -0
- package/dist/approvalLines.js +40 -0
- package/dist/approvalNote.d.ts +20 -0
- package/dist/approvalNote.js +33 -0
- package/dist/cliArgs.js +1 -0
- package/dist/cliAutopilotPolicy.d.ts +34 -9
- package/dist/cliAutopilotPolicy.js +32 -1
- package/dist/cliHook.js +32 -11
- package/dist/cliHookDecide.d.ts +14 -0
- package/dist/cliHookDecide.js +62 -4
- package/dist/cliHookDeliver.d.ts +8 -1
- package/dist/cliHookDeliver.js +3 -3
- package/dist/cliHookGuard.d.ts +12 -5
- package/dist/cliHookGuard.js +26 -35
- package/dist/cliHookHold.d.ts +91 -0
- package/dist/cliHookHold.js +168 -0
- package/dist/cliHookInstall.d.ts +8 -1
- package/dist/cliHookInstall.js +58 -12
- package/dist/cliHookKey.d.ts +25 -0
- package/dist/cliHookKey.js +160 -0
- package/dist/cliHookRedact.d.ts +13 -0
- package/dist/cliHookRedact.js +60 -0
- package/dist/cliHookVendors.d.ts +3 -0
- package/dist/cliHookVendors.js +7 -0
- package/dist/cliHookVendorsMore.d.ts +3 -4
- package/dist/cliHookVendorsMore.js +3 -9
- package/dist/cliKeysShim.d.ts +1 -1
- package/dist/cliMain.js +18 -0
- package/dist/cliOutput.js +2 -2
- package/dist/cliPolicyV2.js +61 -19
- package/dist/cliWait.d.ts +7 -8
- package/dist/cliWait.js +50 -19
- package/dist/doctor.js +14 -0
- package/dist/holdNotice.d.ts +23 -0
- package/dist/holdNotice.js +73 -0
- package/dist/launcherFastPath.js +11 -4
- package/dist/pluginPin.d.ts +1 -1
- package/dist/pluginPin.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -66,7 +66,7 @@ passport run github_search_issues '{"query":"SSO"}'
|
|
|
66
66
|
| `prompts [name] [--set k=v] [--out <file>]` | List or get MCP prompts. |
|
|
67
67
|
| `scan [--path <dir>] [--verbose] [--check]` | Find keys your agents can reach on this computer and what each can do, without an account. Signed in, also report the MCP servers set up in your agents to your workspace and exit 5 when its policy doesn't allow one. `--check` scans files only (not the shell environment), never reports, and exits 5 on a high or medium key. |
|
|
68
68
|
| `hook` | Records the CLIs agents run and, with `--guard`, decides each one before it runs from your Autopilot rules (`install`, `uninstall`, `status`). |
|
|
69
|
-
| `wait <approval-id> [--timeout <s>]` | Wait for a person to decide an approval request
|
|
69
|
+
| `wait <approval-id> [--timeout <s>]` | Wait for a person to decide an approval request, until they do or it expires. Agents run it in the background. |
|
|
70
70
|
| `rules test "<command>" [--environment <kind>]` | What Autopilot decides for a command, why, and which environment it acts on. |
|
|
71
71
|
| `sessions [--status running\|idle\|ended]` | Your agents' recent sessions with what Passport decided. |
|
|
72
72
|
| `undo <action-id>\|--last [--option <id>] [--yes]` | Undo an action Passport took a backup before, within 7 days. See [Undo](#undo). |
|
|
@@ -254,13 +254,15 @@ An ask becomes one Activity row. In Claude Code, with the audit hook registered,
|
|
|
254
254
|
- Codex: the same events in `~/.codex/hooks.json` (`CODEX_HOME` honored). Codex sends every shell command as `tool_name: "Bash"` with the model's raw command string in `tool_input.command` (never shell-wrapped), so it is read exactly like Claude Code's; its `apply_patch` tool is a file edit, not a shell command, and isn't recorded. Codex supports deny only (an ask fails the hook open, and its allow rewrites commands), so an ask is a deny there that says why (`Codex can't ask from a hook, so Passport blocked it. Approve it in Passport or run it yourself.`), recorded as a block. With a member profile and Autopilot, it goes to Passport like an unattended ask: an approval request, then the waiting line. Trust the hooks in Codex's `/hooks`.
|
|
255
255
|
- Cursor: `beforeShellExecution`/`afterShellExecution` in `~/.cursor/hooks.json`. Cursor also imports Claude Code's hooks by default; that imported copy records nothing when Passport's own Cursor entry exists, so rows aren't doubled.
|
|
256
256
|
|
|
257
|
+
**Hold for approval** (`src/cliHookHold.ts`). When nobody is at the keyboard and Passport opens an approval request, the guard holds for a person before answering: `hook install --guard` and `init` write `passport hook guard --hold 25` with the entry's `timeout` at 40 seconds for Claude Code (`--hold <0-45>` changes it; `0` writes today's entry; `hook install` also fixes a timeout that's too short). At runtime the hold is capped by the timeout Claude Code enforces on that entry, read from its settings, and an entry the guard can't find means no hold. If someone approves in time, the guard asks Passport again with the same request, which consumes the approval once and re-checks every rule, and only that allow runs the original command, with no retry. Anything else (no decision, a decline, expiry, an error, or a slow answer) declines the command with one line: who decides, when the request expires, and `Run "passport wait <id>" as a background command; it exits when someone decides. Then run this command again.` A decline during the hold carries the person's note. An entry without `--hold` never holds, because Claude Code runs a command when its hook outlives the timeout; `PASSPORT_HOOK_HOLD` can shorten a hold, never lengthen it. Codex never holds (its hook can't run an approved command), and neither does Cursor (what it does when a hook outlives its timeout isn't documented). Managed installs (`init --org`) don't hold yet, since a person's older CLI wouldn't know the flag. A guard from before the hold (no `--hold`, or a timeout too short for it) is named once a day, and once per CLI version, after an interactive command on a terminal: `Approvals can now continue automatically. Run: passport hook install --apply` (stderr; never from the hook, piped, or with `--json`). `passport doctor` shows the same as a warning, and `hook install --apply` keeps an existing guard current without `--guard`. Each approval binds to a normalized command key (`src/cliHookKey.ts`): every word and redirect target is redacted first, then quoting, pipes into read-only filters whose flags are all on that filter's harmless list, `2>&1`, output sent to /dev/null, and a trailing `|| true` are ignored, so an equivalent retry matches the same request. A key that still shows anything the summary hides falls back to the summary, and a key over 400 characters is sent as a SHA-256 of the whole key.
|
|
258
|
+
|
|
257
259
|
**Guard health** (`src/cliGuardHealth.ts`, states and fixes in `src/cliGuardState.ts`, a checked copy of `shared/guardContract.ts`). `passport hook status` and `passport status` show each agent's guard in the web's words, **On**, **Off**, **Outdated**, **Not trusted**, or **Locked**, and each problem's fix (on a terminal the command goes on its own `Run:` line): `passport hook install --agent <agent> --guard --apply`, `npx passport-bridge@latest init`, or `Open Codex → /hooks and trust Passport's hooks.` At most once a day (`$PASSPORT_HOME/guard/.<profile>.heartbeat`) the CLI sends `POST /api/my/guard-health` with `{cliVersion, launcherTarget?, clients: [{client, present, mode, guard, plugin, codexTrust?, locked?, disabledEnv?}]}`: flags only, never a command, path, or value. It goes from a guard run with at least 300 ms of its budget left (a hook's first one waits a day), from `passport exec`, and from `passport status`. Codex trust (`src/cliCodexTrust.ts`) compares `trusted_hash` in `~/.codex/config.toml` `[hooks.state."<hooks.json>:pre_tool_use:<group>:<handler>"]` with Codex's own hash of Passport's guard entry: SHA-256 of the sorted-key JSON of `{event_name, matcher?, hooks: [{type, command, timeout (600 when unset), async, statusMessage?, additionalContextLimit? (when not 2500)}]}`, as in openai/codex `hook_hash`/`version_for_toml`, checked against codex-cli 0.146.0's `hooks/list`. Missing is **Not trusted**, a different hash is **Not trusted** (modified), `enabled = false` is **Off**. **Locked** means managed settings hold Passport's guard: `/Library/Application Support/ClaudeCode/managed-settings.json` (and `managed-settings.d/`), `/etc/claude-code/…`, `/etc/codex/requirements.toml`, `/Library/Application Support/Cursor/hooks.json`, or `/etc/cursor/hooks.json` (`PASSPORT_MANAGED_ROOT` points tests elsewhere).
|
|
258
260
|
|
|
259
261
|
**Coverage** (`src/cliSeen.ts`). The guard counts every command it saw, per agent per day, one character per command in `$PASSPORT_HOME/seen/<profile>.<agent>.<day>.log` (an app's action, not checked, or neither), and Cursor's imported copy of Claude Code's hook doesn't count twice. Counts go in their own batches, at most every five minutes, as `seen: {batch, day, count, governed, opaque}` on `POST /api/my/cli-activity`, never inside a report that can expire. `passport status` prints `Checked: 94% of commands Passport saw this week`.
|
|
260
262
|
|
|
261
263
|
**When Passport can't be reached.** A local run, block, or attended ask stands as decided. When the guard needs Passport (an unattended ask, Codex, or a Production action someone else approves) and it doesn't answer within the budget, the environment's `offline` setting from cli-policy v2 decides: ask, block, or allow (ask everywhere by default). An ask nobody can answer (unattended, or Codex) blocks, a second-person action is always blocked, and allow never covers an irreversible action or an ask from a team floor, team or workspace rule, approver rule, or approved exception. A policy synced more than 7 days ago uses the default. The reason ends with one line saying why, such as `Nobody is here to approve it and Passport couldn't be reached, so it's blocked.`
|
|
262
264
|
|
|
263
|
-
**App access.** The person's pass for the app a `passport exec` CLI acts on (Railway for `railway`, GitHub for `gh`, and so on) comes with cli-policy v2 as `appAccess
|
|
265
|
+
**App access.** The person's pass for the app a `passport exec` CLI acts on (Railway for `railway`, GitHub for `gh`, and so on) comes with cli-policy v2 as `access`, one record per CLI whose app limits the person (an older server's `appAccess` map is read the same way). The guard applies it before any rule, and no rule or exception lifts it. No access blocks every command of that CLI with `You don't have access to Railway in Passport. Ask an admin.` and a link to the app's Access tab; read-only blocks everything but reads. `passport exec` says the same (exit 5, cause `no_access`, with `Access: <link>`). A CLI whose app isn't in the workspace keeps working from its key.
|
|
264
266
|
|
|
265
267
|
`src/cliPolicy.ts` caches the member's CLI policy (`GET /api/my/cli-policy`) at `$PASSPORT_HOME/cli-policy/<profile>.json` (mode 600). Servers with Autopilot send version 2 (`src/cliPolicyV2.ts`: presets, floors, CLI rules, irreversible and delete verbs, environment flags, placed environments); older servers send version 1, and then the guard keeps its earlier shape: ask or deny before destructive verbs, never allow, no server call, and reports without the Autopilot fields. `passport login` and `passport status` refresh it and `passport logout` removes it. A 404 or error keeps the previous copy; with no copy the guard asks before every destructive verb. `PASSPORT_HOOK_DISABLED=1` turns both hooks off.
|
|
266
268
|
|
|
@@ -282,7 +284,7 @@ passport actions sync # propose this repository's .passport/actions.toml
|
|
|
282
284
|
- `env` lists where commands in this folder land, read the way each vendor's own CLI reads it (`src/envResolve.ts`; order: flag, the folder's link, the vendor's default, the workspace's saved mapping, the whole-word naming rule, else Production). Link readers: `src/envLinksHosting.ts` (Railway `~/.railway/config.json`, Vercel `.vercel/project.json` / `repo.json`, Supabase `supabase/.temp/project-ref`, Wrangler config, Netlify `.netlify/state.json`, Firebase `.firebaserc` + configstore, Convex `CONVEX_DEPLOYMENT`, Neon `.neon`), `src/envLinksCloud.ts` (Fly, Heroku git remotes, kubeconfig, AWS profile, gcloud configuration, Terraform workspace, Stripe key mode), and `src/envDatabase.ts` (database URLs: only `DATABASE_URL`, `DIRECT_URL`, `POSTGRES_URL*`, `DATABASE_URL_UNPOOLED`, reduced to a host-derived key; the URL, user, and password never leave the function). Files are read fresh for every command, size-capped, and a link file symlinked out of the project is ignored (`src/envLinkFs.ts`). For a placed id its mapping decides, and a different name in the link file is treated as a rename (sent as the new label, which the server stores). A name in a link file never loosens anything: an unplaced id is named only by a label the server confirmed through the connected app (`resources[].confirmed`), which the naming rule then reads (`source: "name"`, shown as `Staging (from its name)`); without one, or when it says nothing, it is assumed Production. The table keeps its columns when every row fits the terminal and stacks each row otherwise. Findings to a server that sends `resources` in cli-policy v2 carry `{kind, source, resourceKey?, label?, platform?, flag?, via}`. `env set` calls `PUT /api/my/environments/:platform/:key`; members may only say Production.
|
|
283
285
|
|
|
284
286
|
- `rules test` classifies the command here and sends only its app and verb (and the environment kind) to `POST /api/my/rules/test`, never the command line. An everyday command goes as a finding (`{finding: {vendor, verb, risk, environment}}`), because only this computer can place its paths. It prints the decision, its cause, the environment, and the class. Without a server answer it decides from this computer's copy and says how old it is. `--environment` picks one when the flags don't say.
|
|
285
|
-
- `wait` long-polls `GET /api/my/approvals/<id>/wait
|
|
287
|
+
- `wait` long-polls `GET /api/my/approvals/<id>/wait` (30 s per request), after a short first look that names who decides, until a person decides or the request expires; `--timeout <s>` caps it. Agents run it as a background command and are woken when it exits. Once Passport says the request is still pending (never for one that doesn't exist or is already decided), on a terminal it prints the approval link and one live line (`Waiting for Erin · 1:32 left`); piped, `Waiting for a decision on <id> (until it expires at 14:05).` and `Open in Passport: <url>`. Ctrl-C exits 4 with `The request is still open. Keep waiting any time.` and `Run: passport wait <id>`. Approved: `Approved by Ramish (once). Run the command again.`, or `… for this session. Matching commands in this session run without asking.` (exit 0). Declined: the person's note, cleaned and labelled, `Declined by Ramish. Their note: "Use staging first"` (exit 5, cause `approval_denied`). Expired: `Expired at 14:05 with no decision. Run the command again to ask again.` (exit 5, cause `approval_expired`). Still waiting at `--timeout`: exit 4 with the same command as `next`.
|
|
286
288
|
- `sessions` lists recent sessions (`GET /api/my/agent-sessions`): status, agent, folder, start, `42 ran · 2 asked · 1 blocked`, environments touched, and `Waiting for you` when approvals are pending.
|
|
287
289
|
- `sync` writes the allows Passport is sure of into each agent's own permission settings, so those prompts disappear offline and in Codex (`src/nativeSync.ts`). Only reads, test runners, builds and type checks, linters that only check, `git status`, `git add`, and `git commit`, checked against the person's rules. Formatters, fixing linters, `mv`/`cp`, and package scripts stay with the hook, which sees what they touch; deletes, installs, pushes, and Production never sync. Claude Code: `Bash(npm test *)` in `permissions.allow` of `~/.claude/settings.json`. Codex: `prefix_rule(pattern = ["npm", "test"], decision = "allow")` in `~/.codex/rules/passport.rules`, a file Passport owns. Cursor CLI: `Shell(npm:test*)` in `permissions.allow` of `~/.cursor/cli-config.json`. Cursor: `npm test` in `terminalAllowlist` of `~/.cursor/permissions.json`, only when that list already exists there (defining it replaces Cursor's in-app list). Entries Passport added are listed in `$PASSPORT_HOME/native-sync.json`; an entry you had before is never claimed or removed, and a file Passport can't parse exactly (JSONC) is left alone. Sync runs on `init`, `init --org`, every rules refresh, and `passport sync`; `hook uninstall`, `sync --remove`, and signing out of the last profile take the entries out.
|
|
288
290
|
- `status` is one screen, like `gh auth status`, with a label per row (`You` with the name you signed in as, `Computer`, `Guard`, `Autopilot`, `Apps`, `Keys`, `Shims`, `This folder`, `Allowlists`, `CLI`); under 60 columns each label gets its own row, and piped it never wraps. `Guard` lists each agent's guard (`✓ Claude Code On`, `! Codex Not trusted`) with its fix on the line under it, the coverage line, and sends the daily guard report when due. It also adds today's speed line, `Passport added 0.3 s and asked you twice today. 412 actions ran on their own.` (across your computers when the server keeps speed numbers, else `(this computer)`), and `Answered for you: N prompts today` (allows the hook gave in Claude Code and Cursor, and Codex commands Passport synced, counted only when the agent would have prompted) and which agents' allowlists are synced. Under the presets, one line per exception that lets something run your presets would ask about, in the web's words: `! 1 exception: deletes run in Production without asking, even without a backup.` Counts are appended locally (`$PASSPORT_HOME/answered/`) and sent in batches at most every five minutes as `answered: {batch, count}` on `POST /api/my/cli-activity`.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the agent reads about an approval request, from the hook's hold and
|
|
3
|
+
* from `passport wait`: who decides and when it expires, a decline with the
|
|
4
|
+
* person's note, or an expiry. Light on purpose: `passport wait` loads it.
|
|
5
|
+
*/
|
|
6
|
+
/** `Declined by Erin. Their note: "Use staging"`, rebuilt from parts so nothing else rides along. */
|
|
7
|
+
export declare function declinedFrom(message: unknown): string;
|
|
8
|
+
/** "14:05" today, or "14:05 tomorrow", or a date further out; in this computer's time. */
|
|
9
|
+
export declare function expiryTime(expiresAt: number, now: number): string;
|
|
10
|
+
/**
|
|
11
|
+
* What the agent reads when the hold ends with no decision: who decides, when
|
|
12
|
+
* the request expires, and to wait in the background, then run it again.
|
|
13
|
+
* Starts "Waiting for approval from <who>. Run `passport wait" like the
|
|
14
|
+
* server's own line, so `waitingParts` still reads it.
|
|
15
|
+
*/
|
|
16
|
+
export declare function pendingMessage(approvalId: string, who: string | undefined, expiresAt: number | undefined, now: number): string;
|
|
17
|
+
export declare const EXPIRED_MESSAGE = "Expired with no decision. Run the command again to ask again.";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the agent reads about an approval request, from the hook's hold and
|
|
3
|
+
* from `passport wait`: who decides and when it expires, a decline with the
|
|
4
|
+
* person's note, or an expiry. Light on purpose: `passport wait` loads it.
|
|
5
|
+
*/
|
|
6
|
+
import { cleanLine, declineNoteSuffix } from "./approvalNote.js";
|
|
7
|
+
/** `Declined by Erin. Their note: "Use staging"`, rebuilt from parts so nothing else rides along. */
|
|
8
|
+
export function declinedFrom(message) {
|
|
9
|
+
const text = cleanLine(message, 320);
|
|
10
|
+
// `Declined by Erin. Their note: "…"`, or an older server's `Declined by Erin: …`.
|
|
11
|
+
const match = text?.match(/^Declined by (.{1,80}?)\. Their note: "(.*)"$/) ??
|
|
12
|
+
text?.match(/^Declined by (.{1,80}?)(?:: "?(.*?)"?)?\.?$/);
|
|
13
|
+
if (!match)
|
|
14
|
+
return "Declined.";
|
|
15
|
+
return `Declined by ${match[1]}${declineNoteSuffix(match[2])}`;
|
|
16
|
+
}
|
|
17
|
+
/** "14:05" today, or "14:05 tomorrow", or a date further out; in this computer's time. */
|
|
18
|
+
export function expiryTime(expiresAt, now) {
|
|
19
|
+
const at = new Date(expiresAt);
|
|
20
|
+
const clock = `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}`;
|
|
21
|
+
const today = new Date(now);
|
|
22
|
+
const startOfDay = (date) => new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
|
|
23
|
+
const days = Math.round((startOfDay(at) - startOfDay(today)) / 86_400_000);
|
|
24
|
+
if (days <= 0)
|
|
25
|
+
return clock;
|
|
26
|
+
if (days === 1)
|
|
27
|
+
return `${clock} tomorrow`;
|
|
28
|
+
return `${clock} on ${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, "0")}-${String(at.getDate()).padStart(2, "0")}`;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* What the agent reads when the hold ends with no decision: who decides, when
|
|
32
|
+
* the request expires, and to wait in the background, then run it again.
|
|
33
|
+
* Starts "Waiting for approval from <who>. Run `passport wait" like the
|
|
34
|
+
* server's own line, so `waitingParts` still reads it.
|
|
35
|
+
*/
|
|
36
|
+
export function pendingMessage(approvalId, who, expiresAt, now) {
|
|
37
|
+
const expires = expiresAt !== undefined && expiresAt > now ? ` (it expires at ${expiryTime(expiresAt, now)})` : "";
|
|
38
|
+
return `Waiting for approval from ${who ?? "your approver"}. Run \`passport wait ${approvalId}\` as a background command; it exits when someone decides${expires}. Then run this command again.`;
|
|
39
|
+
}
|
|
40
|
+
export const EXPIRED_MESSAGE = "Expired with no decision. Run the command again to ask again.";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A decline note is the approver's own words, relayed to the agent verbatim.
|
|
3
|
+
* Before it is stored or shown, anything that could disguise it goes: control
|
|
4
|
+
* characters and terminal escapes, bidi overrides, and zero-width characters.
|
|
5
|
+
* Whitespace collapses and the note keeps at most 200 characters.
|
|
6
|
+
*
|
|
7
|
+
* A checked copy of shared/approvalNote.ts (the CLI can't import shared/).
|
|
8
|
+
*/
|
|
9
|
+
export declare const APPROVAL_NOTE_MAX = 200;
|
|
10
|
+
/** One line with nothing hidden in it, at most `max` characters, or undefined when nothing is left. */
|
|
11
|
+
export declare function cleanLine(raw: unknown, max: number): string | undefined;
|
|
12
|
+
/** The note as it may be stored and relayed, or undefined when nothing is left. */
|
|
13
|
+
export declare function cleanApprovalNote(raw: unknown): string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* After "Declined by Erin": `. Their note: "Not during the freeze."`, or "."
|
|
16
|
+
* with no note. The note is labelled as the approver's words, and its own
|
|
17
|
+
* double quotes and backticks become single quotes, so it can't close the
|
|
18
|
+
* quotes or read as a command.
|
|
19
|
+
*/
|
|
20
|
+
export declare function declineNoteSuffix(raw: unknown): string;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A decline note is the approver's own words, relayed to the agent verbatim.
|
|
3
|
+
* Before it is stored or shown, anything that could disguise it goes: control
|
|
4
|
+
* characters and terminal escapes, bidi overrides, and zero-width characters.
|
|
5
|
+
* Whitespace collapses and the note keeps at most 200 characters.
|
|
6
|
+
*
|
|
7
|
+
* A checked copy of shared/approvalNote.ts (the CLI can't import shared/).
|
|
8
|
+
*/
|
|
9
|
+
export const APPROVAL_NOTE_MAX = 200;
|
|
10
|
+
// Terminal escapes first (CSI, OSC, and lone ESC pairs), then single characters.
|
|
11
|
+
const ESCAPES = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b[@-_]?|\u009b[0-?]*[ -/]*[@-~]/g;
|
|
12
|
+
const INVISIBLE = /[\u0000-\u0008\u000e-\u001f\u007f-\u009f\u00ad\u061c\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufeff\ufff9-\ufffb]/g;
|
|
13
|
+
/** One line with nothing hidden in it, at most `max` characters, or undefined when nothing is left. */
|
|
14
|
+
export function cleanLine(raw, max) {
|
|
15
|
+
if (typeof raw !== "string")
|
|
16
|
+
return undefined;
|
|
17
|
+
const cleaned = raw.replace(ESCAPES, "").replace(INVISIBLE, "").replace(/\s+/g, " ").trim();
|
|
18
|
+
return cleaned ? Array.from(cleaned).slice(0, max).join("").trim() : undefined;
|
|
19
|
+
}
|
|
20
|
+
/** The note as it may be stored and relayed, or undefined when nothing is left. */
|
|
21
|
+
export function cleanApprovalNote(raw) {
|
|
22
|
+
return cleanLine(raw, APPROVAL_NOTE_MAX);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* After "Declined by Erin": `. Their note: "Not during the freeze."`, or "."
|
|
26
|
+
* with no note. The note is labelled as the approver's words, and its own
|
|
27
|
+
* double quotes and backticks become single quotes, so it can't close the
|
|
28
|
+
* quotes or read as a command.
|
|
29
|
+
*/
|
|
30
|
+
export function declineNoteSuffix(raw) {
|
|
31
|
+
const note = cleanApprovalNote(raw)?.replace(/["`]/g, "'");
|
|
32
|
+
return note ? `. Their note: "${note}"` : ".";
|
|
33
|
+
}
|
package/dist/cliArgs.js
CHANGED
|
@@ -50,6 +50,7 @@ const FLAGS = {
|
|
|
50
50
|
client: { kind: "value", commands: ["login", "setup", "hook", "exec"] },
|
|
51
51
|
apply: { kind: "boolean", commands: ["setup", "hook"] },
|
|
52
52
|
guard: { kind: "boolean", commands: ["hook"] },
|
|
53
|
+
hold: { kind: "value", commands: ["hook"] },
|
|
53
54
|
"no-open": { kind: "boolean", commands: ["login", "init"] },
|
|
54
55
|
yes: { kind: "boolean", commands: ["init", "setup", "keys", "undo"] },
|
|
55
56
|
// `init --org` is setup for MDM; `setup --org` still runs it for one release.
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
* Autopilot decisions on this machine, from the cached cli-policy v2.
|
|
3
3
|
*
|
|
4
4
|
* The same order the server uses (docs: autopilot map, section 4):
|
|
5
|
+
* 0. The access ceiling: the person's pass for the app the CLI acts on.
|
|
6
|
+
* No access blocks every command, Read-only runs only reads. Nothing
|
|
7
|
+
* below lifts it.
|
|
5
8
|
* 1. Block rules → Blocked.
|
|
6
9
|
* 2. (Grants given in this session live on the server; unattended runs ask it.)
|
|
7
10
|
* 3. The most specific exception (action > app > class), strictest across
|
|
@@ -17,7 +20,7 @@ export type Preset = (typeof PRESETS)[number];
|
|
|
17
20
|
export declare const ACTION_CLASSES: readonly ["read", "change", "delete", "irreversible"];
|
|
18
21
|
export type ActionClass = (typeof ACTION_CLASSES)[number];
|
|
19
22
|
export type Decision = "allow" | "ask" | "block";
|
|
20
|
-
export type CauseKind = "block" | "grant" | "rule" | "floor" | "preset" | "default";
|
|
23
|
+
export type CauseKind = "access" | "block" | "grant" | "rule" | "floor" | "preset" | "default";
|
|
21
24
|
export type Cause = {
|
|
22
25
|
kind: CauseKind;
|
|
23
26
|
id?: string;
|
|
@@ -74,11 +77,28 @@ export type RuleException = {
|
|
|
74
77
|
actionClass?: ActionClass;
|
|
75
78
|
environment: ActionEnv | "any";
|
|
76
79
|
};
|
|
77
|
-
/**
|
|
78
|
-
|
|
79
|
-
|
|
80
|
+
/**
|
|
81
|
+
* One access ceiling record (cli-policy v2 `access`, shared `CliAccessRecord`):
|
|
82
|
+
* the person's pass for the app a vendor CLI acts on, sent only when it limits
|
|
83
|
+
* them. No record means no ceiling.
|
|
84
|
+
*/
|
|
85
|
+
export type AccessRecord = {
|
|
86
|
+
layer: "access";
|
|
87
|
+
/** The vendor CLI it governs, e.g. `railway` or `flyctl`. */
|
|
88
|
+
vendor: string;
|
|
89
|
+
appKey: string;
|
|
90
|
+
/** The app's name, "Railway". */
|
|
80
91
|
app: string;
|
|
92
|
+
pass: "none" | "readonly";
|
|
93
|
+
/** The cause line: "No access to Railway in Passport". */
|
|
81
94
|
cause: string;
|
|
95
|
+
/** What the person and the agent read. */
|
|
96
|
+
message: string;
|
|
97
|
+
/** The app's Access tab, when the server sent a valid link. */
|
|
98
|
+
link?: string;
|
|
99
|
+
};
|
|
100
|
+
/** What a person reads when the access ceiling blocks: the message and the Access link. */
|
|
101
|
+
export type AccessBlock = {
|
|
82
102
|
message: string;
|
|
83
103
|
link?: string;
|
|
84
104
|
};
|
|
@@ -131,10 +151,10 @@ export type AutopilotPolicy = {
|
|
|
131
151
|
/** What the guard does per environment when Passport can't be reached
|
|
132
152
|
* (Batch A). Absent from older servers: built-in defaults apply. */
|
|
133
153
|
offline?: Record<ActionEnv, "ask" | "block" | "allow">;
|
|
134
|
-
/** The
|
|
135
|
-
*
|
|
136
|
-
* only reads. A vendor without
|
|
137
|
-
|
|
154
|
+
/** The access ceiling (cli-policy v2 `access`): one record per vendor CLI
|
|
155
|
+
* whose app limits this person. No access blocks every command, Read-only
|
|
156
|
+
* runs only reads. A vendor without a record has no ceiling. */
|
|
157
|
+
access?: AccessRecord[];
|
|
138
158
|
/** Resources the workspace placed, by id (Phase 4.5). Present only when the
|
|
139
159
|
* server reads where a finding lands, so findings may carry it. */
|
|
140
160
|
resources?: Array<{
|
|
@@ -186,9 +206,14 @@ export type ActionFacts = {
|
|
|
186
206
|
export type LocalDecision = {
|
|
187
207
|
decision: Decision;
|
|
188
208
|
cause: Cause;
|
|
209
|
+
/** Blocked by the access ceiling: what the person reads. */
|
|
210
|
+
access?: AccessBlock;
|
|
189
211
|
};
|
|
212
|
+
/** The access record for a vendor CLI, under either spelling (`fly`, `flyctl`). */
|
|
213
|
+
export declare function accessRecordFor(policy: AutopilotPolicy, vendor: string): AccessRecord | undefined;
|
|
190
214
|
/** The server's `decideAction`, minus grants (only the server knows them).
|
|
191
|
-
* The
|
|
215
|
+
* The access ceiling comes first and nothing lifts it; the second-person rule
|
|
216
|
+
* turns a Production run into an ask the server owns. */
|
|
192
217
|
export declare function decideAction(policy: AutopilotPolicy, facts: ActionFacts): LocalDecision;
|
|
193
218
|
/** Whether an ask needs someone other than the person at the keyboard. */
|
|
194
219
|
export declare function needsSecondPerson(cause: Cause | undefined): boolean;
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
* Autopilot decisions on this machine, from the cached cli-policy v2.
|
|
3
3
|
*
|
|
4
4
|
* The same order the server uses (docs: autopilot map, section 4):
|
|
5
|
+
* 0. The access ceiling: the person's pass for the app the CLI acts on.
|
|
6
|
+
* No access blocks every command, Read-only runs only reads. Nothing
|
|
7
|
+
* below lifts it.
|
|
5
8
|
* 1. Block rules → Blocked.
|
|
6
9
|
* 2. (Grants given in this session live on the server; unattended runs ask it.)
|
|
7
10
|
* 3. The most specific exception (action > app > class), strictest across
|
|
@@ -12,6 +15,7 @@
|
|
|
12
15
|
* Every decision carries its cause, and every cause reads as one line.
|
|
13
16
|
*/
|
|
14
17
|
import { ENV_LABEL } from "./cliHookEnvironment.js";
|
|
18
|
+
import { vendorKeys } from "./cliHookVendors.js";
|
|
15
19
|
export const PRESETS = ["careful", "balanced", "handsoff"];
|
|
16
20
|
export const ACTION_CLASSES = ["read", "change", "delete", "irreversible"];
|
|
17
21
|
/**
|
|
@@ -253,9 +257,36 @@ function mostSpecific(rules) {
|
|
|
253
257
|
function stricter(a, b) {
|
|
254
258
|
return DECISION_RANK[b] > DECISION_RANK[a] ? b : a;
|
|
255
259
|
}
|
|
260
|
+
/** The access record for a vendor CLI, under either spelling (`fly`, `flyctl`). */
|
|
261
|
+
export function accessRecordFor(policy, vendor) {
|
|
262
|
+
const records = policy.access;
|
|
263
|
+
if (!records?.length)
|
|
264
|
+
return undefined;
|
|
265
|
+
for (const key of vendorKeys(vendor)) {
|
|
266
|
+
const record = records.find((entry) => entry.vendor === key);
|
|
267
|
+
if (record)
|
|
268
|
+
return record;
|
|
269
|
+
}
|
|
270
|
+
return undefined;
|
|
271
|
+
}
|
|
272
|
+
/** The access ceiling: No access blocks every command, Read-only blocks all but reads. */
|
|
273
|
+
function accessCeiling(policy, facts) {
|
|
274
|
+
const record = accessRecordFor(policy, facts.vendor);
|
|
275
|
+
if (!record || (record.pass === "readonly" && facts.actionClass === "read"))
|
|
276
|
+
return null;
|
|
277
|
+
return {
|
|
278
|
+
decision: "block",
|
|
279
|
+
cause: { kind: "access", label: record.cause },
|
|
280
|
+
access: { message: record.message, ...(record.link ? { link: record.link } : {}) }
|
|
281
|
+
};
|
|
282
|
+
}
|
|
256
283
|
/** The server's `decideAction`, minus grants (only the server knows them).
|
|
257
|
-
* The
|
|
284
|
+
* The access ceiling comes first and nothing lifts it; the second-person rule
|
|
285
|
+
* turns a Production run into an ask the server owns. */
|
|
258
286
|
export function decideAction(policy, facts) {
|
|
287
|
+
const ceiling = accessCeiling(policy, facts);
|
|
288
|
+
if (ceiling)
|
|
289
|
+
return ceiling;
|
|
259
290
|
const decided = decideByRules(policy, facts);
|
|
260
291
|
const classes = policy.secondPerson?.classes ?? [];
|
|
261
292
|
if (decided.decision !== "allow" || facts.environment !== "production" || !classes.includes(facts.actionClass)) {
|
package/dist/cliHook.js
CHANGED
|
@@ -20,6 +20,7 @@ import { classifyLine, localMachine, workingFolder, worthReporting } from "./cli
|
|
|
20
20
|
import { codexAskBlocked, planGuard } from "./cliHookDecide.js";
|
|
21
21
|
import { decideGuard, guardMachineOf } from "./cliHookGuard.js";
|
|
22
22
|
import { detectMode } from "./cliHookMode.js";
|
|
23
|
+
import { cappedHold, holdSeconds } from "./cliHookHold.js";
|
|
23
24
|
import { readInput } from "./cliHookInput.js";
|
|
24
25
|
import { budgetSignal, expiredAsks, HOOK_BUDGET_MS, HOOK_RUNTIMES, leftovers, localProfile, localSelection, profileApi, queueAfterCommand, reportSender, runFlush, startFlushIfDue } from "./cliHookDeliver.js";
|
|
25
26
|
export { HOOK_BUDGET_MS, HOOK_RUNTIMES, legacyReport } from "./cliHookDeliver.js";
|
|
@@ -140,7 +141,7 @@ function reportable(findings, decided = [], local = false) {
|
|
|
140
141
|
const entry = decided.find((candidate) => candidate.finding === finding);
|
|
141
142
|
return {
|
|
142
143
|
vendor: finding.vendor,
|
|
143
|
-
verb: safeVerb(finding.verb),
|
|
144
|
+
verb: safeVerb(finding.verbKey ?? finding.verb),
|
|
144
145
|
risk: finding.risk,
|
|
145
146
|
...(entry?.reported ? { environment: entry.reported } : {}),
|
|
146
147
|
...entry?.placement,
|
|
@@ -276,7 +277,7 @@ function isPassportExec(command) {
|
|
|
276
277
|
async function runAudit(args, runtime, deps) {
|
|
277
278
|
if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
|
|
278
279
|
return;
|
|
279
|
-
const budget = budgetSignal(runtime);
|
|
280
|
+
const budget = budgetSignal(runtime, deps);
|
|
280
281
|
const input = await readInput(runtime, budget);
|
|
281
282
|
if (!input)
|
|
282
283
|
return;
|
|
@@ -292,7 +293,7 @@ async function runAudit(args, runtime, deps) {
|
|
|
292
293
|
const policy = profile ? readCliPolicy(profile) : null;
|
|
293
294
|
// The post-hook reads the same scripts again: a change since the guard's
|
|
294
295
|
// check is drift (item 6).
|
|
295
|
-
const scripts = scriptReader({ phase: "post", project: projectContext(policy) });
|
|
296
|
+
const scripts = scriptReader({ phase: "post", project: projectContext(policy), now: deps.budget?.scriptClock });
|
|
296
297
|
const machine = { ...localMachine(workingFolder(input), runtime.env), scripts };
|
|
297
298
|
const line = classifyLine(event.command, machine);
|
|
298
299
|
const findings = line.findings;
|
|
@@ -352,7 +353,7 @@ function outputClient(event, runtime) {
|
|
|
352
353
|
* allow, or an ask parked until the command runs). */
|
|
353
354
|
async function guardReport(base, plan, context) {
|
|
354
355
|
if (plan.server && base)
|
|
355
|
-
return serverDecidedReport(base, plan.server, context.now);
|
|
356
|
+
return serverDecidedReport(base, plan.server, context.now, plan.held);
|
|
356
357
|
// Offline, this computer's answer replaces the local Ask on the record.
|
|
357
358
|
const decided = base && plan.offline && plan.verdict ? { ...base, decision: plan.verdict } : base;
|
|
358
359
|
const report = decided && context.v2 && decided.decision === "allow" ? null : codexAskBlocked(decided);
|
|
@@ -371,9 +372,18 @@ async function guardReport(base, plan, context) {
|
|
|
371
372
|
* earlier) is parked for the run's own row; a waiting request is "asked"; a
|
|
372
373
|
* declined one is "asked, not run"; a block is a block.
|
|
373
374
|
*/
|
|
374
|
-
function serverDecidedReport(base, server, now) {
|
|
375
|
+
function serverDecidedReport(base, server, now, held) {
|
|
375
376
|
if (server.decision === "none")
|
|
376
377
|
return null;
|
|
378
|
+
// Held, and approved in time: "asked first, then ran", once the run reports.
|
|
379
|
+
if (held === "approved") {
|
|
380
|
+
const asked = { ...base, decision: "ask" };
|
|
381
|
+
if (base.toolUseId && holdAsk(base.runtime, base.sessionId, base.toolUseId, asked, now))
|
|
382
|
+
return null;
|
|
383
|
+
return { ...asked, ran: true };
|
|
384
|
+
}
|
|
385
|
+
if (held === "declined" || held === "expired")
|
|
386
|
+
return { ...base, decision: "ask", ran: false };
|
|
377
387
|
if (server.decision === "allow") {
|
|
378
388
|
if (base.toolUseId)
|
|
379
389
|
holdAsk(base.runtime, base.sessionId, base.toolUseId, { ...base, decision: "allow" }, now);
|
|
@@ -402,12 +412,14 @@ function answeredWith(decision, plan) {
|
|
|
402
412
|
async function afterAnswer(profile, context) {
|
|
403
413
|
const { timing, plan, decision, clock } = context;
|
|
404
414
|
const asked = plan.server !== null || plan.offline;
|
|
415
|
+
// A hold is a person's time, counted as an approval wait, not the guard's.
|
|
416
|
+
const answeredAt = timing.answeredAt - (plan.heldMs ?? 0);
|
|
405
417
|
(await import("./cliSpeed.js")).noteGuard(profile, {
|
|
406
418
|
client: context.runtimeName,
|
|
407
|
-
totalMs:
|
|
419
|
+
totalMs: answeredAt - timing.began,
|
|
408
420
|
readMs: timing.readAt - timing.began,
|
|
409
|
-
localMs: timing.localAt - timing.readAt + (asked ? 0 :
|
|
410
|
-
serverMs: asked ?
|
|
421
|
+
localMs: timing.localAt - timing.readAt + (asked ? 0 : answeredAt - timing.localAt),
|
|
422
|
+
serverMs: asked ? answeredAt - timing.localAt : 0,
|
|
411
423
|
decision: answeredWith(decision, plan),
|
|
412
424
|
offline: plan.offline
|
|
413
425
|
}, timing.answeredAt);
|
|
@@ -432,7 +444,7 @@ async function runGuard(args, runtime, deps) {
|
|
|
432
444
|
const clock = deps.now ?? Date.now;
|
|
433
445
|
const startedAt = clock();
|
|
434
446
|
const began = startOf(deps);
|
|
435
|
-
const budget = budgetSignal(runtime);
|
|
447
|
+
const budget = budgetSignal(runtime, deps);
|
|
436
448
|
const input = await readInput(runtime, budget);
|
|
437
449
|
if (!input || budget.aborted)
|
|
438
450
|
return;
|
|
@@ -444,7 +456,7 @@ async function runGuard(args, runtime, deps) {
|
|
|
444
456
|
const { profile, byDefault } = localSelection(args, runtime.env);
|
|
445
457
|
const policy = profile ? readCliPolicy(profile) : null;
|
|
446
458
|
// The project's own scripts are read inside the budget (item 6).
|
|
447
|
-
const scripts = scriptReader({ phase: "pre", project: projectContext(policy) });
|
|
459
|
+
const scripts = scriptReader({ phase: "pre", project: projectContext(policy), now: deps.budget?.scriptClock });
|
|
448
460
|
const machine = { ...localMachine(workingFolder(input), runtime.env), scripts };
|
|
449
461
|
const line = classifyLine(event.command, machine);
|
|
450
462
|
const decision = decideGuard(line.findings, policy, event.command, line.complete, guardMachineOf(machine, workingFolder(input), runtime.env));
|
|
@@ -478,7 +490,16 @@ async function runGuard(args, runtime, deps) {
|
|
|
478
490
|
command: event.command,
|
|
479
491
|
budget,
|
|
480
492
|
deadline: startedAt + HOOK_BUDGET_MS - PRINT_RESERVE_MS,
|
|
481
|
-
now: deps.now ?? Date.now
|
|
493
|
+
now: deps.now ?? Date.now,
|
|
494
|
+
hold: async () => {
|
|
495
|
+
const seconds = holdSeconds(value(args, "hold"), runtime.env);
|
|
496
|
+
if (seconds <= 0)
|
|
497
|
+
return 0;
|
|
498
|
+
// Never longer than the timeout Claude Code will enforce on this entry.
|
|
499
|
+
const { guardEntryOf } = await import("./cliHookInstall.js");
|
|
500
|
+
return cappedHold(seconds, guardEntryOf("claude-code", runtime.env));
|
|
501
|
+
},
|
|
502
|
+
holdSignal: runtime.signal
|
|
482
503
|
});
|
|
483
504
|
if (plan.output)
|
|
484
505
|
runtime.stdout.write(`${JSON.stringify(plan.output)}\n`);
|
package/dist/cliHookDecide.d.ts
CHANGED
|
@@ -36,6 +36,8 @@ export type CliDecideRequest = {
|
|
|
36
36
|
environment?: string;
|
|
37
37
|
} & Record<string, string>>;
|
|
38
38
|
commandSummary?: string;
|
|
39
|
+
/** The governed part, normalized and redacted (`cliHookKey.ts`): equivalent retries share it. */
|
|
40
|
+
commandKey?: string;
|
|
39
41
|
};
|
|
40
42
|
export type ServerDecision = {
|
|
41
43
|
decision: "allow" | "ask" | "block" | "none";
|
|
@@ -46,6 +48,9 @@ export type ServerDecision = {
|
|
|
46
48
|
approvalId?: string;
|
|
47
49
|
/** What to tell the agent, e.g. "Waiting for approval from Ramish. …" */
|
|
48
50
|
message?: string;
|
|
51
|
+
/** A pending approval: when it expires, and who decides. */
|
|
52
|
+
expiresAt?: number;
|
|
53
|
+
waitingFor?: string;
|
|
49
54
|
};
|
|
50
55
|
type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
|
|
51
56
|
/** Validate what the server said. Anything unexpected is no answer at all. */
|
|
@@ -64,6 +69,10 @@ export type GuardPlan = {
|
|
|
64
69
|
offline: boolean;
|
|
65
70
|
/** Offline: what this computer decided in place of the local Ask. */
|
|
66
71
|
verdict?: GuardDecision["verdict"];
|
|
72
|
+
/** How the hold ended, when the guard held for a person (`cliHookHold.ts`). */
|
|
73
|
+
held?: "approved" | "declined" | "expired" | "pending";
|
|
74
|
+
/** How long it held: a person's time, kept out of the guard's own speed. */
|
|
75
|
+
heldMs?: number;
|
|
67
76
|
};
|
|
68
77
|
/** Codex can't ask from a hook, so an ask it read is recorded as the block it was. */
|
|
69
78
|
export declare function codexAskBlocked<T extends {
|
|
@@ -111,6 +120,11 @@ export declare function planGuard(decision: GuardDecision | null, policy: Cached
|
|
|
111
120
|
budget: AbortSignal;
|
|
112
121
|
deadline: number;
|
|
113
122
|
now: () => number;
|
|
123
|
+
/** Seconds to hold for a person after an approval request opens (0: don't);
|
|
124
|
+
* asked only when a request opens, since it reads the agent's settings. */
|
|
125
|
+
hold?: () => Promise<number>;
|
|
126
|
+
/** Ends the hold early (the process is stopping). */
|
|
127
|
+
holdSignal?: AbortSignal;
|
|
114
128
|
}): Promise<GuardPlan & {
|
|
115
129
|
api?: ApiCall;
|
|
116
130
|
}>;
|
package/dist/cliHookDecide.js
CHANGED
|
@@ -20,12 +20,13 @@ import { readBoundedJson } from "./boundedResponse.js";
|
|
|
20
20
|
import { isEnvKind } from "./cliHookEnvironment.js";
|
|
21
21
|
import { askMessage, guardOutput, waitingMessage } from "./cliHookGuard.js";
|
|
22
22
|
import { OFFLINE_CACHE_MAX_MS, OFFLINE_DEFAULT, OFFLINE_NOTES, offlineDecision } from "./cliGuardState.js";
|
|
23
|
+
import { commandKey } from "./cliHookKey.js";
|
|
23
24
|
import { redactCommand } from "./cliHookRedact.js";
|
|
24
25
|
export const CLI_DECIDE_PATH = "/api/my/cli/decide";
|
|
25
26
|
const MAX_RESPONSE_BYTES = 16 * 1024;
|
|
26
27
|
const MAX_FINDINGS = 8;
|
|
27
28
|
const ID = /^[A-Za-z0-9_-]{1,80}$/;
|
|
28
|
-
const CAUSE_KINDS = new Set(["block", "grant", "rule", "floor", "preset", "default"]);
|
|
29
|
+
const CAUSE_KINDS = new Set(["access", "block", "grant", "rule", "floor", "preset", "default"]);
|
|
29
30
|
const CLASSES = new Set(["read", "change", "delete", "irreversible"]);
|
|
30
31
|
function line(raw, max) {
|
|
31
32
|
if (typeof raw !== "string")
|
|
@@ -56,6 +57,10 @@ export function parseServerDecision(raw) {
|
|
|
56
57
|
const approvalId = typeof body.approvalId === "string" && ID.test(body.approvalId) ? body.approvalId : undefined;
|
|
57
58
|
const explanation = line(body.explanation, 240);
|
|
58
59
|
const message = line(body.message, 400);
|
|
60
|
+
const waitingFor = line(body.waitingFor, 80);
|
|
61
|
+
const expiresAt = typeof body.expiresAt === "number" && Number.isSafeInteger(body.expiresAt) && body.expiresAt > 0
|
|
62
|
+
? body.expiresAt
|
|
63
|
+
: undefined;
|
|
59
64
|
return {
|
|
60
65
|
decision,
|
|
61
66
|
...(cause ? { cause } : {}),
|
|
@@ -65,7 +70,9 @@ export function parseServerDecision(raw) {
|
|
|
65
70
|
? { actionClass: body.actionClass }
|
|
66
71
|
: {}),
|
|
67
72
|
...(approvalId ? { approvalId } : {}),
|
|
68
|
-
...(message ? { message } : {})
|
|
73
|
+
...(message ? { message } : {}),
|
|
74
|
+
...(expiresAt !== undefined ? { expiresAt } : {}),
|
|
75
|
+
...(waitingFor ? { waitingFor } : {})
|
|
69
76
|
};
|
|
70
77
|
}
|
|
71
78
|
const VERB_TOKEN = /^-{0,2}[A-Za-z0-9][A-Za-z0-9._:+-]{0,39}$/;
|
|
@@ -91,6 +98,7 @@ export function decideRequest(decision, context, command, local = false) {
|
|
|
91
98
|
...entry.placement
|
|
92
99
|
}));
|
|
93
100
|
const summary = redactCommand(command);
|
|
101
|
+
const key = commandKey(command);
|
|
94
102
|
return {
|
|
95
103
|
runtime: context.runtime,
|
|
96
104
|
...(context.sessionId ? { sessionId: context.sessionId } : {}),
|
|
@@ -98,7 +106,8 @@ export function decideRequest(decision, context, command, local = false) {
|
|
|
98
106
|
...(context.folder ? { folder: context.folder } : {}),
|
|
99
107
|
interactive: false,
|
|
100
108
|
findings,
|
|
101
|
-
...(summary ? { commandSummary: summary } : {})
|
|
109
|
+
...(summary ? { commandSummary: summary } : {}),
|
|
110
|
+
...(key ? { commandKey: key } : {})
|
|
102
111
|
};
|
|
103
112
|
}
|
|
104
113
|
/** Ask the server, or null when it couldn't answer in time. Never throws. */
|
|
@@ -257,5 +266,54 @@ export async function planGuard(decision, policy, context) {
|
|
|
257
266
|
...(api ? { api } : {})
|
|
258
267
|
};
|
|
259
268
|
}
|
|
260
|
-
return
|
|
269
|
+
return api
|
|
270
|
+
? heldPlan(decision, server, request, api, context)
|
|
271
|
+
: { output: serverOutput(context.client, decision, server), server, offline: false };
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* The server's answer as a plan. A request a person can answer: hold for them (Claude Code and Cursor run
|
|
275
|
+
* the original command when they approve in time); otherwise, or when the
|
|
276
|
+
* hold ends undecided, say how to wait. Every path but a fresh allow denies.
|
|
277
|
+
*/
|
|
278
|
+
async function heldPlan(decision, server, request, api, context) {
|
|
279
|
+
const waiting = server.decision === "ask" && server.approvalId && server.waitingFor ? server : null;
|
|
280
|
+
if (!waiting)
|
|
281
|
+
return { output: serverOutput(context.client, decision, server), server, offline: false, api };
|
|
282
|
+
const hold = await import("./cliHookHold.js");
|
|
283
|
+
const pending = (who, expiresAt, approvalId) => guardOutput(context.client, { ...decision, verdict: "deny" }, {
|
|
284
|
+
waiting: hold.pendingMessage(approvalId ?? waiting.approvalId, who ?? waiting.waitingFor, expiresAt ?? waiting.expiresAt, context.now())
|
|
285
|
+
});
|
|
286
|
+
// Only Claude Code holds: Codex can't run an approved command from a hook,
|
|
287
|
+
// and Cursor's behaviour past a hook's timeout isn't documented.
|
|
288
|
+
const seconds = context.client === "claude-code" && context.hold ? await context.hold().catch(() => 0) : 0;
|
|
289
|
+
if (seconds <= 0)
|
|
290
|
+
return { output: pending(), server, offline: false, api };
|
|
291
|
+
const began = context.now();
|
|
292
|
+
const outcome = await hold.holdForDecision(api, waiting.approvalId, (signal) => decideOnServer(api, request, signal), {
|
|
293
|
+
seconds,
|
|
294
|
+
signal: context.holdSignal ?? new AbortController().signal,
|
|
295
|
+
now: context.now
|
|
296
|
+
});
|
|
297
|
+
const heldMs = Math.max(0, context.now() - began);
|
|
298
|
+
const plan = { offline: false, api, held: outcome.kind, heldMs };
|
|
299
|
+
if (outcome.kind === "approved") {
|
|
300
|
+
return { ...plan, output: serverOutput(context.client, decision, outcome.server), server: outcome.server };
|
|
301
|
+
}
|
|
302
|
+
if (outcome.kind === "declined") {
|
|
303
|
+
return outcome.server
|
|
304
|
+
? { ...plan, output: serverOutput(context.client, decision, outcome.server), server: outcome.server }
|
|
305
|
+
: {
|
|
306
|
+
...plan,
|
|
307
|
+
output: guardOutput(context.client, { ...decision, verdict: "deny" }, { waiting: outcome.message }),
|
|
308
|
+
server
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
if (outcome.kind === "expired") {
|
|
312
|
+
return {
|
|
313
|
+
...plan,
|
|
314
|
+
output: guardOutput(context.client, { ...decision, verdict: "deny" }, { waiting: hold.EXPIRED_MESSAGE }),
|
|
315
|
+
server
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
return { ...plan, output: pending(outcome.waitingFor, outcome.expiresAt, outcome.approvalId), server };
|
|
261
319
|
}
|
package/dist/cliHookDeliver.d.ts
CHANGED
|
@@ -89,6 +89,13 @@ export type HookDependencies = {
|
|
|
89
89
|
/** Network seam for the default delivery and the policy refresh. */
|
|
90
90
|
fetch?: typeof fetch;
|
|
91
91
|
now?: () => number;
|
|
92
|
+
/** The hook's budget clocks. By default the overall budget is a
|
|
93
|
+
* `HOOK_BUDGET_MS` timer and script reading runs on `performance.now`; a test
|
|
94
|
+
* that compares decisions supplies its own so host load cannot change one. */
|
|
95
|
+
budget?: {
|
|
96
|
+
signal: AbortSignal;
|
|
97
|
+
scriptClock: () => number;
|
|
98
|
+
};
|
|
92
99
|
/** How the guard's rewrite starts `passport`; found on PATH by default. */
|
|
93
100
|
invocation?: string;
|
|
94
101
|
};
|
|
@@ -121,7 +128,7 @@ type Send = (report: CliHookReport) => Promise<void>;
|
|
|
121
128
|
export declare function reportSender(args: ParsedArgs, runtime: Runtime, signal: AbortSignal, deps: HookDependencies): Promise<Send | null>;
|
|
122
129
|
/** Parked asks nobody claimed in time: the prompt was declined, or nothing ran. */
|
|
123
130
|
export declare function expiredAsks(now: number): CliHookReport[];
|
|
124
|
-
export declare function budgetSignal(runtime: Runtime): AbortSignal;
|
|
131
|
+
export declare function budgetSignal(runtime: Runtime, deps?: HookDependencies): AbortSignal;
|
|
125
132
|
/** Never wait on the network after a command: queue the report, and a
|
|
126
133
|
* detached flush sends it. */
|
|
127
134
|
export declare function queueAfterCommand(report: CliHookReport | null, args: ParsedArgs, runtime: Runtime, runtimeName: string, now: number): Promise<void>;
|