passcontrol 1.4.0 → 1.5.1

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.
@@ -14,7 +14,8 @@
14
14
  // older budget that might read as current.
15
15
  import fs from "node:fs";
16
16
  import path from "node:path";
17
- import { statusLine } from "./budget-format.mjs";
17
+ import { limitReached, panelRows, statusLine } from "./budget-format.mjs";
18
+ import { heldUsageWindow, readUsageWindow, usageWindowText, WINDOW_PATH } from "./usage-window.mjs";
18
19
 
19
20
  export const STATUSLINE_TTL_MS = 20_000;
20
21
  const TIMEOUT_MS = 1_500;
@@ -87,3 +88,224 @@ export async function statuslineText({
87
88
  clearTimeout(timer);
88
89
  }
89
90
  }
91
+
92
+ // Claude Code writes one JSON object to the command's stdin. It may not close the
93
+ // stream promptly, so the object is taken as soon as it parses, and after this long
94
+ // the line is printed without it.
95
+ const STDIN_WAIT_MS = 300;
96
+ const STDIN_LIMIT = 256 * 1024;
97
+
98
+ /** Claude Code's status-line input, or null. Never throws, never waits past `waitMs`. */
99
+ export function readStatusInput(stream = process.stdin, waitMs = STDIN_WAIT_MS) {
100
+ if (!stream || stream.isTTY) return Promise.resolve(null);
101
+ return new Promise((resolve) => {
102
+ let text = "";
103
+ let done = false;
104
+ const finish = (value) => {
105
+ if (done) return;
106
+ done = true;
107
+ clearTimeout(timer);
108
+ stream.removeAllListeners?.("data");
109
+ // An open stdin would keep the process alive after the line is printed.
110
+ stream.destroy?.();
111
+ resolve(value);
112
+ };
113
+ const parse = () => {
114
+ try {
115
+ const parsed = JSON.parse(text);
116
+ return parsed && typeof parsed === "object" ? parsed : null;
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ };
121
+ const timer = setTimeout(() => finish(parse() ?? null), waitMs);
122
+ try {
123
+ stream.setEncoding?.("utf8");
124
+ stream.on("data", (chunk) => {
125
+ text += chunk;
126
+ if (text.length > STDIN_LIMIT) return finish(null);
127
+ const parsed = parse();
128
+ if (parsed !== undefined) finish(parsed);
129
+ });
130
+ stream.on("end", () => finish(parse() ?? null));
131
+ stream.on("error", () => finish(null));
132
+ } catch {
133
+ finish(null);
134
+ }
135
+ });
136
+ }
137
+
138
+ /**
139
+ * Hands the usage window to the sidecar, for `watch` and `/passcontrol`. Best effort:
140
+ * a sidecar that is not running only means the boards do not show it.
141
+ */
142
+ export async function postUsageWindow({ port, host = "127.0.0.1", window, fetch: fetchImpl = globalThis.fetch, timeoutMs = 500 }) {
143
+ if (!window) return;
144
+ try {
145
+ const response = await fetchImpl(`http://${host}:${port}${WINDOW_PATH}`, {
146
+ method: "POST",
147
+ headers: { "content-type": "application/json" },
148
+ body: JSON.stringify(window),
149
+ signal: AbortSignal.timeout(timeoutMs),
150
+ });
151
+ await response.body?.cancel().catch(() => {});
152
+ } catch {
153
+ // Nothing to tell anyone: the status line still shows the window.
154
+ }
155
+ }
156
+
157
+ /**
158
+ * The status line with the usage window, when Claude Code sent one: the budget line
159
+ * may come from the cache, the window is always this run's. Never throws.
160
+ */
161
+ export async function statuslineWithWindow({ input, port, host = "127.0.0.1", fetch: fetchImpl = globalThis.fetch, budgetLine }) {
162
+ const window = readUsageWindow(input);
163
+ const [line] = await Promise.all([budgetLine(), postUsageWindow({ port, host, window, fetch: fetchImpl })]);
164
+ const text = usageWindowText(window, { short: true });
165
+ return text ? `${line} · ${text}` : line;
166
+ }
167
+
168
+ // The session id Claude Code declares on every call, held to what the gateway
169
+ // accepts as declared (lib/client-lineage.ts), so nothing else is ever sent on.
170
+ const DECLARED_SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
171
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
172
+
173
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
174
+
175
+ /**
176
+ * Where Claude Code sends its calls, from its own ANTHROPIC_BASE_URL (the plugin's
177
+ * hook inherits Claude Code's environment): `{ port }` for a sidecar on this
178
+ * machine, `{ remote: host }` for anything else, null when it is not set. A
179
+ * dedicated Claude Code agent's sidecar is not on the default port, and asking the
180
+ * default one would report a different agent.
181
+ */
182
+ export function sidecarFromBaseUrl(baseUrl) {
183
+ if (typeof baseUrl !== "string" || !baseUrl.trim()) return null;
184
+ let url;
185
+ try {
186
+ url = new URL(baseUrl);
187
+ } catch {
188
+ return null;
189
+ }
190
+ if (!LOOPBACK.has(url.hostname)) return { remote: url.host };
191
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
192
+ return Number.isInteger(port) && port > 0 && port < 65536 ? { port } : null;
193
+ }
194
+
195
+ /** The panel for a session whose calls do not pass through a PassControl sidecar. */
196
+ export function notInPathText(remoteHost) {
197
+ return [
198
+ "PassControl · not in the path of this session",
199
+ "",
200
+ ` Claude Code sends its calls to ${remoteHost}, not through a PassControl`,
201
+ " sidecar, so PassControl neither sees nor limits them. To route them:",
202
+ " passcontrol configure claude-code --write",
203
+ ].join("\n");
204
+ }
205
+
206
+ const row = ([label, value]) => ` ${label.padEnd(11)} ${value}`;
207
+
208
+ /** The usage window the sidecar holds, as short text, or "". Never throws. */
209
+ async function readSidecarWindow({ host, port, fetch: fetchImpl, signal }) {
210
+ try {
211
+ const response = await fetchImpl(`http://${host}:${port}${WINDOW_PATH}`, { headers: { accept: "application/json" }, signal });
212
+ if (!response.ok) {
213
+ await response.body?.cancel().catch(() => {});
214
+ return "";
215
+ }
216
+ return usageWindowText(heldUsageWindow(await response.json()), { short: true });
217
+ } catch {
218
+ return "";
219
+ }
220
+ }
221
+
222
+ /**
223
+ * `passcontrol statusline --panel`: what `/passcontrol` shows in Claude Code (F3).
224
+ * The plugin's hook prints it without calling the model, so it answers while the
225
+ * gateway refuses every call. Always asks: never answered from the status line's
226
+ * cache, where a "fine" from before the stop could still sit. Never throws.
227
+ */
228
+ export async function statusPanelText({
229
+ port,
230
+ host = "127.0.0.1",
231
+ gateway,
232
+ session = null,
233
+ subscription = false,
234
+ fetch: fetchImpl = globalThis.fetch,
235
+ timeoutMs = TIMEOUT_MS,
236
+ }) {
237
+ const dashboard = `${String(gateway ?? "").replace(/\/+$/, "")}/dashboard`;
238
+ const headers = { accept: "application/json" };
239
+ if (typeof session === "string" && DECLARED_SESSION.test(session)) headers["x-claude-code-session-id"] = session;
240
+
241
+ const controller = new AbortController();
242
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
243
+ try {
244
+ let response;
245
+ try {
246
+ response = await fetchImpl(`http://${host}:${port}/api/v1/self`, { headers, signal: controller.signal });
247
+ } catch {
248
+ if (controller.signal.aborted) return "PassControl · no answer from the sidecar\n\n It did not answer in time. Try again in a moment.";
249
+ // On a subscription the calls never pass the sidecar, so they go ahead without
250
+ // it: what stops is PassControl checking the stops and showing the calls.
251
+ const consequence = subscription
252
+ ? [
253
+ " This session's calls still go ahead, but PassControl does not check",
254
+ " the agent's stops or show its calls until it runs. Start it with:",
255
+ " passcontrol sidecar",
256
+ ]
257
+ : [" If Claude Code is set to send its calls through PassControl, they fail", " until it runs. Start it with: passcontrol sidecar"];
258
+ return [`PassControl · sidecar not running on port ${port}`, "", ...consequence].join("\n");
259
+ }
260
+ if (response.status === 403) {
261
+ const body = await response.json().catch(() => ({}));
262
+ if (typeof body?.message === "string" && body.message.includes("stopped this session")) {
263
+ return [
264
+ "PassControl · REFUSING CALLS from this session",
265
+ "",
266
+ " The agent's owner stopped this session, so nothing you type here",
267
+ " reaches the model. Other sessions of this agent are not affected,",
268
+ " and a new session is not stopped. The owner can resume this one",
269
+ " from the agent's Sessions view.",
270
+ "",
271
+ row(["Dashboard", dashboard]),
272
+ ].join("\n");
273
+ }
274
+ // The gateway's one opaque answer for both: it does not say which fired.
275
+ return [
276
+ "PassControl · REFUSING CALLS",
277
+ "",
278
+ " The gateway is refusing this agent's calls: its owner suspended it, or",
279
+ " the kill switch is on. Nothing you type here reaches the model until",
280
+ " it is lifted.",
281
+ "",
282
+ row(["Dashboard", dashboard]),
283
+ ].join("\n");
284
+ }
285
+ if (response.status === 429) return "PassControl · asked too often\n\n Try again in a minute.";
286
+ if (!response.ok) return `PassControl · unavailable (HTTP ${response.status})`;
287
+ let self;
288
+ try {
289
+ self = await response.json();
290
+ } catch {
291
+ return "PassControl · unreadable answer";
292
+ }
293
+ if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
294
+ const agentId = typeof self.agent_id === "string" && UUID.test(self.agent_id) ? self.agent_id : null;
295
+ const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : ""}`;
296
+ const window = subscription ? await readSidecarWindow({ host, port, fetch: fetchImpl, signal: controller.signal }) : "";
297
+ return [
298
+ title,
299
+ "",
300
+ ...panelRows(self).map(row),
301
+ ...(window ? [row(["Window", window])] : []),
302
+ row(["Calls", subscription ? "reported by Claude Code (subscription), not proxied" : `through the sidecar on :${port}`]),
303
+ "",
304
+ row(["Agent page", agentId ? `${dashboard}/agents/${agentId}` : dashboard]),
305
+ ].join("\n");
306
+ } catch {
307
+ return "PassControl · unavailable";
308
+ } finally {
309
+ clearTimeout(timer);
310
+ }
311
+ }
@@ -0,0 +1,213 @@
1
+ // Subscription mode's Stop (Phase 1).
2
+ //
3
+ // A Claude Pro/Max session signs in to Claude Code with the user's own account and
4
+ // talks to Anthropic directly: Anthropic's terms forbid anything that intermediates
5
+ // that login, so PassControl is not in the network path and the gateway cannot
6
+ // refuse the calls. The stops still reach the session, through Claude Code's hooks.
7
+ // `passcontrol configure claude-code --subscription` points three of them at the
8
+ // sidecar's loopback listener:
9
+ //
10
+ // UserPromptSubmit before a prompt is sent → { decision: "block" }
11
+ // PreToolUse before a tool runs → permissionDecision "deny"
12
+ // PostToolBatch before the next model call → { decision: "block" }
13
+ //
14
+ // and each of those also returns `continue: false`, which ends the turn: a stop means
15
+ // the agent stops, not that it keeps thinking with its tools taken away.
16
+ //
17
+ // The state comes from the gateway's GET /api/v1/self, which evaluates the kill
18
+ // switch, suspend and the declared session's stop exactly as for a model call. A hook
19
+ // fires on every tool call, and /self allows 60 a minute per AGENT, shared by every
20
+ // session and by the status line, `watch` and `/passcontrol`. So the agent-wide answer
21
+ // (kill switch, suspend) is asked once for all sessions, every `freshMs`; a session's
22
+ // own stop is asked per session, every `sessionFreshMs`; and concurrent hooks share one
23
+ // request. That is at most 12 + 4 per session a minute at the defaults.
24
+ //
25
+ // When the state cannot be read, the action goes ahead (fail-open, the owner's choice
26
+ // on 2026-10-11 and the kill switch's own default), with a warning shown at most once
27
+ // a minute per session. A stop seen within `maxStaleMs` is held through a gateway blip:
28
+ // failing open is for "never knew", not for "knew it was stopped a moment ago".
29
+ //
30
+ // Each /self answer also carries the agent's tool rules (Phase 2, `?include=tool_rules`),
31
+ // kept here for the tool gate (cli/tool-gate.mjs), so the rules never cost a call of
32
+ // their own. Every read asks for them, so an "open" answer without them comes from a
33
+ // gateway that has none to give (one from before Phase 2): no rules, not unknown ones.
34
+ // A refusal carries no rules, so a PreToolUse refreshes them with the agent-wide ask
35
+ // once they are `freshMs` old.
36
+ //
37
+ // Honest limit: hooks run inside Claude Code, so this is a guard rail for the user's
38
+ // own sessions, not a boundary against a client that skips them.
39
+
40
+ export const HOOK_PATH = "/_passcontrol/hook";
41
+
42
+ const GATED = new Set(["UserPromptSubmit", "PreToolUse", "PostToolBatch"]);
43
+ // What the gateway accepts as a declared session (lib/client-lineage.ts).
44
+ const DECLARED_SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
45
+
46
+ export const GATE_FRESH_MS = 5_000;
47
+ export const GATE_SESSION_FRESH_MS = 15_000;
48
+ export const GATE_MAX_STALE_MS = 60_000;
49
+ const MAX_SESSIONS = 512;
50
+ const WARN_EVERY_MS = 60_000;
51
+
52
+ function stopText(state, dashboardUrl) {
53
+ const where = dashboardUrl ? ` Lift it from ${dashboardUrl}` : "";
54
+ if (state === "session_stopped") {
55
+ return `PassControl: the agent's owner stopped this session, so nothing more runs in it.${where ? `${where} (the agent's Sessions view).` : ""}`;
56
+ }
57
+ return `PassControl: this agent is stopped — its owner suspended it, or the kill switch is on.${where ? `${where}.` : ""}`;
58
+ }
59
+
60
+ function blockFor(event, reason) {
61
+ const end = { continue: false, stopReason: reason };
62
+ if (event === "PreToolUse") {
63
+ return {
64
+ ...end,
65
+ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason },
66
+ };
67
+ }
68
+ return { ...end, decision: "block", reason };
69
+ }
70
+
71
+ /**
72
+ * @param {{
73
+ * readSelf: (session: string | null) => Promise<{ state: "open" | "stopped" | "session_stopped" | "unknown", reason?: string }>,
74
+ * dashboardUrl?: string,
75
+ * now?: () => number,
76
+ * freshMs?: number,
77
+ * sessionFreshMs?: number,
78
+ * maxStaleMs?: number,
79
+ * maxSessions?: number,
80
+ * }} options
81
+ */
82
+ export function createStopGate({
83
+ readSelf,
84
+ dashboardUrl = "",
85
+ now = () => Date.now(),
86
+ freshMs = GATE_FRESH_MS,
87
+ sessionFreshMs = GATE_SESSION_FRESH_MS,
88
+ maxStaleMs = GATE_MAX_STALE_MS,
89
+ maxSessions = MAX_SESSIONS,
90
+ }) {
91
+ // The last KNOWN answers (never "unknown"). The agent's: "open" | "stopped".
92
+ // A session's: "open" | "session_stopped", or "behind" when it was last asked while
93
+ // the whole agent was stopped, which hides whether the session is stopped on its own.
94
+ let agent = null;
95
+ // The agent's tool rules as the last answer that carried them gave them.
96
+ let rules = null;
97
+ const sessions = new Map();
98
+ const inflight = new Map();
99
+ const warnedAt = new Map();
100
+
101
+ function remember(map, key, value) {
102
+ map.delete(key);
103
+ map.set(key, value);
104
+ while (map.size > maxSessions) map.delete(map.keys().next().value);
105
+ }
106
+
107
+ // One answer can settle both: a session's "open" says the agent is running too, a
108
+ // "session_stopped" is only ever given to a running agent, and "stopped" is agent-wide.
109
+ function record(session, state) {
110
+ const at = now();
111
+ if (state === "open" || state === "session_stopped") agent = { state: "open", at };
112
+ if (state === "stopped") agent = { state: "stopped", at };
113
+ if (session !== null) remember(sessions, session, { state: state === "stopped" ? "behind" : state, at });
114
+ }
115
+
116
+ async function ask(session) {
117
+ const key = session ?? "";
118
+ if (inflight.has(key)) return inflight.get(key);
119
+ const pending = (async () => {
120
+ let answer;
121
+ try {
122
+ answer = await readSelf(session);
123
+ } catch (error) {
124
+ answer = { state: "unknown", reason: error?.message ?? "error" };
125
+ }
126
+ answer ??= { state: "unknown", reason: "no answer" };
127
+ if (answer.state === "open") {
128
+ rules = { read: answer.toolRules && typeof answer.toolRules === "object" ? answer.toolRules : { state: "none" }, at: now() };
129
+ }
130
+ if (["open", "stopped"].includes(answer.state) || (session !== null && answer.state === "session_stopped")) {
131
+ record(session, answer.state);
132
+ }
133
+ return answer;
134
+ })();
135
+ inflight.set(key, pending);
136
+ try {
137
+ return await pending;
138
+ } finally {
139
+ inflight.delete(key);
140
+ }
141
+ }
142
+
143
+ function warnOnce(key, reason) {
144
+ const last = warnedAt.get(key);
145
+ if (last !== undefined && now() - last < WARN_EVERY_MS) return {};
146
+ remember(warnedAt, key, now());
147
+ return {
148
+ systemMessage: `PassControl could not check this agent's stops (${String(reason ?? "no answer").slice(0, 80)}), so this goes ahead. Is \`passcontrol sidecar\` running?`,
149
+ };
150
+ }
151
+
152
+ const age = (entry) => (entry ? now() - entry.at : Infinity);
153
+
154
+ async function decide(input) {
155
+ const event = input?.hook_event_name;
156
+ if (!GATED.has(event)) return {};
157
+ const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : null;
158
+
159
+ // A session asked behind an agent-wide stop is due again as soon as the agent
160
+ // is known to be running: its own stop may still stand.
161
+ const sessionDue = () => {
162
+ if (session === null) return false;
163
+ const own = sessions.get(session);
164
+ return age(own) >= sessionFreshMs || (own?.state === "behind" && agent?.state === "open");
165
+ };
166
+ let reason = null;
167
+ let askedAgent = false;
168
+ if (sessionDue()) reason = (await ask(session)).reason ?? null;
169
+ else if (age(agent) >= freshMs) {
170
+ askedAgent = true;
171
+ reason = (await ask(null)).reason ?? null;
172
+ if (sessionDue()) reason = (await ask(session)).reason ?? reason;
173
+ }
174
+ if (event === "PreToolUse" && !askedAgent && age(rules) >= freshMs) await ask(null);
175
+
176
+ // Act on what is known and still trusted; fail open, visibly, on anything else.
177
+ const trusted = (entry) => entry && age(entry) <= maxStaleMs;
178
+ const a = trusted(agent) ? agent : null;
179
+ const s = session === null ? null : sessions.get(session);
180
+ const sTrusted = trusted(s) ? s : null;
181
+ if (a?.state === "stopped") return blockFor(event, stopText("stopped", dashboardUrl));
182
+ if (sTrusted?.state === "session_stopped") return blockFor(event, stopText("session_stopped", dashboardUrl));
183
+ if (a?.state === "open" && (session === null || sTrusted?.state === "open")) return {};
184
+ return warnOnce(session ?? "", reason ?? "no answer");
185
+ }
186
+
187
+ /** The tool rules from the latest answer, or null once they are older than `maxStaleMs`. */
188
+ function toolRules() {
189
+ return rules && age(rules) <= maxStaleMs ? rules : null;
190
+ }
191
+
192
+ return { decide, toolRules };
193
+ }
194
+
195
+ /**
196
+ * Maps the gateway's answer to GET /api/v1/self onto a gate state. The gateway's
197
+ * 403 is deliberately opaque between suspend and kill switch; a stopped session is
198
+ * the one it names.
199
+ */
200
+ export async function selfAnswerState(response) {
201
+ if (response.ok) {
202
+ const body = await response.json().catch(() => null);
203
+ const toolRules = body && typeof body === "object" ? body.tool_rules : undefined;
204
+ return toolRules && typeof toolRules === "object" ? { state: "open", toolRules } : { state: "open" };
205
+ }
206
+ if (response.status === 403) {
207
+ const body = await response.json().catch(() => ({}));
208
+ const message = typeof body?.message === "string" ? body.message : "";
209
+ return { state: message.includes("stopped this session") ? "session_stopped" : "stopped" };
210
+ }
211
+ await response.body?.cancel().catch(() => {});
212
+ return { state: "unknown", reason: `gateway answered HTTP ${response.status}` };
213
+ }
@@ -0,0 +1,152 @@
1
+ // Subscription mode's tool rules at Claude Code's PreToolUse hook
2
+ // (Phase 2 design).
3
+ //
4
+ // The stop gate (cli/subscription-gate.mjs) answers first: a stopped agent or session
5
+ // ends the turn whatever the rules say. When it lets the tool through, this decides
6
+ // from the agent's tool rules (cli/tool-rules.mjs), which arrive with the stop gate's
7
+ // own /self reads:
8
+ //
9
+ // deny → permissionDecision "deny": the tool does not run, Claude is told why
10
+ // and the turn goes on.
11
+ // ask → permissionDecision "ask": Claude Code's own terminal prompt.
12
+ // ask_owner → held while the gateway asks the owner. A yes answers nothing, so
13
+ // Claude Code's normal permission flow still decides; a no, no answer
14
+ // in time, or no way to ask, denies. The human the owner put in the
15
+ // way is never removed by a fault.
16
+ //
17
+ // Claude Code lets a tool RUN when its http hook times out, so a hold must end before
18
+ // the hook does: the hook's URL says how long it waits (`?t=600`, written by
19
+ // configure), the wait ends 30 s before that, and a hook that does not say (a Phase 1
20
+ // install, 5 s) refuses an `ask_owner` tool at once instead of timing out into a yes.
21
+ //
22
+ // Rules never read (the sidecar just started, the gateway is down) fail open with a
23
+ // warning, as stops do. Rules this build cannot read deny every tool: the owner wrote
24
+ // them, and a guess at what they meant would be worse.
25
+ //
26
+ // Each outcome that is not a plain pass is handed to `onDecision` for the agent's
27
+ // page: tool name, decision, rule number and wait. Never the command, path or URL.
28
+ import { evaluateToolRules, parseToolRules } from "./tool-rules.mjs";
29
+
30
+ /** The wait ends this long before Claude Code would give up on the hook. */
31
+ export const HOOK_MARGIN_S = 30;
32
+ const MIN_WAIT_S = 10;
33
+ const WARN_EVERY_MS = 60_000;
34
+ const SUBJECT_MAX = 120;
35
+ const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
36
+
37
+ const declared = (v) => (typeof v === "string" && DECLARED.test(v) ? v : null);
38
+ const short = (text) => (text.length > SUBJECT_MAX ? `${text.slice(0, SUBJECT_MAX - 1)}…` : text);
39
+
40
+ function verdict(permissionDecision, reason) {
41
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision, permissionDecisionReason: reason } };
42
+ }
43
+
44
+ /**
45
+ * @param {{
46
+ * askOwner: (input: object, ask: { ruleIndex: number, subject: string, session: string | null, waitMs: number }) =>
47
+ * Promise<{ state: "approved" | "denied" | "timeout" | "unavailable" | "full" | "refused" | "too_large" }>,
48
+ * onDecision?: (record: { session: string | null, agent: string | null, tool: string, decision: string, ruleIndex: number | null, waitMs: number }) => void,
49
+ * now?: () => number,
50
+ * dashboardUrl?: string,
51
+ * }} options
52
+ */
53
+ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Date.now(), dashboardUrl = "" }) {
54
+ let warnedAt = null;
55
+ const where = dashboardUrl ? ` on ${dashboardUrl}` : " on the agent's dashboard page";
56
+
57
+ function record(input, decision, ruleIndex, waitMs) {
58
+ try {
59
+ onDecision({
60
+ session: declared(input.session_id),
61
+ agent: declared(input.agent_id),
62
+ tool: String(input.tool_name ?? "").slice(0, 128),
63
+ decision,
64
+ ruleIndex,
65
+ waitMs,
66
+ });
67
+ } catch {
68
+ // A record is a record; it never changes the answer.
69
+ }
70
+ }
71
+
72
+ /**
73
+ * @param {object} input Claude Code's PreToolUse hook input.
74
+ * @param {{ read: { state: string, document?: unknown }, at: number } | null} rulesEntry
75
+ * The rules from the latest trusted /self read, or null.
76
+ * @param {number | null} hookTimeoutS What the hook's URL says it waits; null when it does not say.
77
+ */
78
+ async function decide(input, rulesEntry, hookTimeoutS) {
79
+ if (input?.hook_event_name !== "PreToolUse") return {};
80
+ const read = rulesEntry?.read;
81
+ if (read?.state === "none") return {};
82
+ if (read?.state === "invalid") {
83
+ record(input, "rules_invalid", null, 0);
84
+ return verdict("deny", `PassControl: this agent's tool rules cannot be read here, so no tool runs until they are fixed${where}.`);
85
+ }
86
+ const parsed = read?.state === "ok" ? parseToolRules(read.document) : null;
87
+ if (!parsed) {
88
+ if (warnedAt !== null && now() - warnedAt < WARN_EVERY_MS) return {};
89
+ warnedAt = now();
90
+ return { systemMessage: "PassControl could not read this agent's tool rules yet, so this goes ahead. Is `passcontrol sidecar` running?" };
91
+ }
92
+ if (!parsed.ok) {
93
+ record(input, "rules_invalid", null, 0);
94
+ return verdict("deny", `PassControl: this agent's tool rules cannot be read here, so no tool runs until they are fixed${where}.`);
95
+ }
96
+
97
+ const hit = evaluateToolRules(parsed, input);
98
+ if (hit.effect === null) return {};
99
+ const rule = `rule ${hit.ruleIndex + 1}`;
100
+ if (hit.effect === "deny") {
101
+ record(input, "deny", hit.ruleIndex, 0);
102
+ return verdict("deny", `PassControl: the agent's tool rules refuse this (${rule}: ${short(hit.subject)}).`);
103
+ }
104
+ if (hit.effect === "ask") {
105
+ record(input, "ask", hit.ruleIndex, 0);
106
+ return verdict("ask", `PassControl: the agent's tool rules ask you to confirm this (${rule}: ${short(hit.subject)}).`);
107
+ }
108
+
109
+ // ask_owner
110
+ const waitS = hookTimeoutS === null ? 0 : Math.min(parsed.approvalWaitS, hookTimeoutS - HOOK_MARGIN_S);
111
+ if (waitS < MIN_WAIT_S) {
112
+ record(input, "owner_unavailable", hit.ruleIndex, 0);
113
+ return verdict(
114
+ "deny",
115
+ `PassControl: this needs the agent's owner to say yes (${rule}), and Claude Code's hook would give up before the answer. Run \`passcontrol configure claude-code --subscription --write\`, then try again.`
116
+ );
117
+ }
118
+ const started = now();
119
+ let answer;
120
+ try {
121
+ answer = await askOwner(input, { ruleIndex: hit.ruleIndex, subject: hit.subject, session: declared(input.session_id), waitMs: waitS * 1000 });
122
+ } catch {
123
+ answer = { state: "unavailable" };
124
+ }
125
+ const waited = Math.max(0, now() - started);
126
+ switch (answer?.state) {
127
+ case "approved":
128
+ record(input, "owner_approved", hit.ruleIndex, waited);
129
+ return {};
130
+ case "denied":
131
+ record(input, "owner_denied", hit.ruleIndex, waited);
132
+ return verdict("deny", `PassControl: the agent's owner said no to this (${rule}).`);
133
+ case "timeout":
134
+ record(input, "owner_timeout", hit.ruleIndex, waited);
135
+ return verdict("deny", `PassControl: the agent's owner did not answer within ${waitS} s, so this was not run (${rule}).`);
136
+ case "full":
137
+ record(input, "owner_unavailable", hit.ruleIndex, waited);
138
+ return verdict("deny", `PassControl: too many questions are already waiting for the agent's owner, so this was not run (${rule}).`);
139
+ case "too_large":
140
+ record(input, "owner_unavailable", hit.ruleIndex, waited);
141
+ return verdict("deny", `PassControl: this needs the agent's owner to say yes (${rule}), and it is too large to show them in full, so it was not run.`);
142
+ case "refused":
143
+ record(input, "owner_unavailable", hit.ruleIndex, waited);
144
+ return verdict("deny", `PassControl: the gateway did not agree this needs the owner (the rules may have just changed), so it was not run. Try again.`);
145
+ default:
146
+ record(input, "owner_unavailable", hit.ruleIndex, waited);
147
+ return verdict("deny", `PassControl: this needs the agent's owner to say yes (${rule}), and they could not be reached, so it was not run.`);
148
+ }
149
+ }
150
+
151
+ return { decide };
152
+ }
@@ -0,0 +1,28 @@
1
+ export type ToolRuleEffect = "deny" | "ask_owner" | "ask";
2
+ export interface ToolRule {
3
+ tool: string;
4
+ effect: ToolRuleEffect;
5
+ command?: string;
6
+ path?: string;
7
+ domain?: string;
8
+ }
9
+ export type ParsedToolRules = { ok: true; rules: ToolRule[]; approvalWaitS: number } | { ok: false };
10
+ export interface ToolRuleInput {
11
+ tool_name?: unknown;
12
+ tool_input?: unknown;
13
+ cwd?: unknown;
14
+ }
15
+ export type ToolRuleVerdict = { effect: null } | { effect: ToolRuleEffect; ruleIndex: number; subject: string };
16
+
17
+ export const TOOL_RULE_EFFECTS: readonly ToolRuleEffect[];
18
+ export const DEFAULT_APPROVAL_WAIT_S: number;
19
+ export const TOOL_RULE_LIMITS: {
20
+ rules: number;
21
+ patternLen: number;
22
+ toolLen: number;
23
+ minWaitS: number;
24
+ maxWaitS: number;
25
+ };
26
+ export function globMatch(pattern: string, text: string): boolean;
27
+ export function parseToolRules(value: unknown): ParsedToolRules;
28
+ export function evaluateToolRules(parsed: { rules: ToolRule[] }, input: ToolRuleInput): ToolRuleVerdict;