passcontrol 1.5.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.
@@ -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;
@@ -0,0 +1,206 @@
1
+ // Tool rules for subscription mode (Phase 2).
2
+ //
3
+ // An agent's `tool_rules` (agents.tool_rules, migration 0085) add friction to what
4
+ // Claude Code's tools may do, from the PreToolUse hook:
5
+ //
6
+ // { "rules": [ { "tool": "Bash", "command": "git push*", "effect": "ask_owner" },
7
+ // { "tool": "Write", "path": "/etc/*", "effect": "deny" },
8
+ // { "tool": "WebFetch", "domain": "*.example.com", "effect": "ask" },
9
+ // { "tool": "mcp__github__*", "effect": "ask_owner" } ],
10
+ // "approval_wait_s": 120 }
11
+ //
12
+ // `deny` refuses the tool, `ask` hands it to Claude Code's own terminal prompt, and
13
+ // `ask_owner` waits for the owner's yes through the gateway's approval flow. There is
14
+ // no `allow`: rules only add friction, and allowing stays Claude Code's own permission
15
+ // system. Every matching rule counts and the strictest wins, so order never matters.
16
+ //
17
+ // One file for both sides: the sidecar decides with it, and the gateway imports it to
18
+ // re-check that a tool it is asked to put to the owner really is under an `ask_owner`
19
+ // rule. The two can never disagree.
20
+ //
21
+ // Patterns are globs where `*` is any run of characters and everything else is
22
+ // literal. No regex is built from what a tenant writes, and matching is a handful of
23
+ // native substring searches, never backtracking.
24
+ //
25
+ // Honest limit: these are guard rails for the owner's own sessions. `sh -c`, an alias,
26
+ // a script file or a different tool gets round a command rule.
27
+
28
+ export const TOOL_RULE_EFFECTS = ["deny", "ask_owner", "ask"];
29
+ const STRICTNESS = { deny: 3, ask_owner: 2, ask: 1 };
30
+
31
+ export const DEFAULT_APPROVAL_WAIT_S = 120;
32
+ export const TOOL_RULE_LIMITS = {
33
+ rules: 100,
34
+ patternLen: 300,
35
+ toolLen: 128,
36
+ /** Claude Code's http hook default is 600 s; the sidecar must answer before it. */
37
+ minWaitS: 10,
38
+ maxWaitS: 540,
39
+ };
40
+
41
+ /** The tools whose input names a file or directory, and where. */
42
+ const PATH_FIELDS = {
43
+ Read: ["file_path"],
44
+ Edit: ["file_path"],
45
+ MultiEdit: ["file_path"],
46
+ Write: ["file_path"],
47
+ NotebookEdit: ["notebook_path"],
48
+ Glob: ["path"],
49
+ Grep: ["path"],
50
+ };
51
+ const SEARCH_TOOLS = new Set(["Glob", "Grep"]);
52
+
53
+ const RULE_KEYS = new Set(["tool", "command", "path", "domain", "effect"]);
54
+ const DOC_KEYS = new Set(["rules", "approval_wait_s"]);
55
+ const TOOL_NAME = /^[A-Za-z0-9_.-]+\*?$/;
56
+ const DOMAIN = /^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*$/;
57
+
58
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
59
+ const isPattern = (v) => typeof v === "string" && v.length > 0 && v.length <= TOOL_RULE_LIMITS.patternLen;
60
+
61
+ /** `*` matches any run of characters (including none); everything else matches itself. */
62
+ export function globMatch(pattern, text) {
63
+ const parts = pattern.split("*");
64
+ if (parts.length === 1) return pattern === text;
65
+ const first = parts[0];
66
+ const last = parts[parts.length - 1];
67
+ if (!text.startsWith(first)) return false;
68
+ if (text.length - first.length < last.length || !text.endsWith(last)) return false;
69
+ // Leftmost-first is exact for a star-only glob: an earlier match never leaves
70
+ // less room for what follows than a later one would.
71
+ let at = first.length;
72
+ const end = text.length - last.length;
73
+ for (let i = 1; i < parts.length - 1; i += 1) {
74
+ const part = parts[i];
75
+ if (part === "") continue;
76
+ const found = text.indexOf(part, at);
77
+ if (found === -1 || found + part.length > end) return false;
78
+ at = found + part.length;
79
+ }
80
+ return true;
81
+ }
82
+
83
+ function parseRule(value) {
84
+ if (!isRecord(value) || Object.keys(value).some((k) => !RULE_KEYS.has(k))) return null;
85
+ const { tool, effect } = value;
86
+ if (typeof tool !== "string" || tool.length > TOOL_RULE_LIMITS.toolLen || !TOOL_NAME.test(tool)) return null;
87
+ if (!TOOL_RULE_EFFECTS.includes(effect)) return null;
88
+ const conditions = ["command", "path", "domain"].filter((k) => k in value);
89
+ if (conditions.length > 1) return null;
90
+ const rule = { tool, effect };
91
+ if (conditions.length === 0) return rule;
92
+ // A condition belongs to one named tool: a wildcard tool has no single input shape.
93
+ if (tool.endsWith("*")) return null;
94
+ const kind = conditions[0];
95
+ const pattern = value[kind];
96
+ if (!isPattern(pattern)) return null;
97
+ if (kind === "command" && tool !== "Bash") return null;
98
+ if (kind === "path") {
99
+ if (!(tool in PATH_FIELDS)) return null;
100
+ const normal = pattern.replace(/\\/g, "/");
101
+ if (!normal.startsWith("/") && !/^[A-Za-z]:\//.test(normal) && !normal.startsWith("*")) return null;
102
+ return { ...rule, path: normal };
103
+ }
104
+ if (kind === "domain" && (tool !== "WebFetch" || !DOMAIN.test(pattern.toLowerCase()))) return null;
105
+ return { ...rule, [kind]: kind === "domain" ? pattern.toLowerCase() : pattern };
106
+ }
107
+
108
+ /**
109
+ * The stored document, validated whole. `null` (never set) is no rules. Anything this
110
+ * build does not understand is `{ ok: false }`: the caller refuses the agent's tools
111
+ * rather than guess which rule was meant.
112
+ */
113
+ export function parseToolRules(value) {
114
+ if (value === null || value === undefined) return { ok: true, rules: [], approvalWaitS: DEFAULT_APPROVAL_WAIT_S };
115
+ if (!isRecord(value) || Object.keys(value).some((k) => !DOC_KEYS.has(k))) return { ok: false };
116
+ if (!Array.isArray(value.rules) || value.rules.length > TOOL_RULE_LIMITS.rules) return { ok: false };
117
+ let approvalWaitS = DEFAULT_APPROVAL_WAIT_S;
118
+ if ("approval_wait_s" in value) {
119
+ const s = value.approval_wait_s;
120
+ if (!Number.isInteger(s) || s < TOOL_RULE_LIMITS.minWaitS || s > TOOL_RULE_LIMITS.maxWaitS) return { ok: false };
121
+ approvalWaitS = s;
122
+ }
123
+ const rules = [];
124
+ for (const candidate of value.rules) {
125
+ const rule = parseRule(candidate);
126
+ if (!rule) return { ok: false };
127
+ rules.push(rule);
128
+ }
129
+ return { ok: true, rules, approvalWaitS };
130
+ }
131
+
132
+ /** `/a/b/../c` → `/a/c`, backslashes to `/`. Not the filesystem: no symlinks. */
133
+ function normalisePath(raw) {
134
+ const unified = raw.replace(/\\/g, "/");
135
+ const drive = /^[A-Za-z]:/.exec(unified)?.[0] ?? "";
136
+ const rest = unified.slice(drive.length);
137
+ const out = [];
138
+ for (const segment of rest.split("/")) {
139
+ if (segment === "" || segment === ".") continue;
140
+ if (segment === "..") out.pop();
141
+ else out.push(segment);
142
+ }
143
+ return `${drive}/${out.join("/")}`;
144
+ }
145
+
146
+ function commandPieces(command) {
147
+ return command
148
+ .split(/&&|\|\||[;|\n]/)
149
+ .map((piece) => piece.trim())
150
+ .filter(Boolean);
151
+ }
152
+
153
+ function toolMatches(pattern, name) {
154
+ return pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : pattern === name;
155
+ }
156
+
157
+ /**
158
+ * What the rules say about one PreToolUse input: `{ effect: null }` when nothing
159
+ * matches, otherwise the strictest matching rule, its index, and what it matched (the
160
+ * command piece, the normalised path, the host, or the tool's name).
161
+ *
162
+ * Input a rule needs but cannot read (no command, a URL that does not parse) counts as
163
+ * matching that rule: a rule the owner wrote is not skipped because the input was odd.
164
+ */
165
+ export function evaluateToolRules(parsed, input) {
166
+ const name = typeof input?.tool_name === "string" ? input.tool_name : "";
167
+ const toolInput = isRecord(input?.tool_input) ? input.tool_input : {};
168
+ let best = null;
169
+ parsed.rules.forEach((rule, ruleIndex) => {
170
+ if (!toolMatches(rule.tool, name)) return;
171
+ const subject = subjectFor(rule, name, toolInput, input);
172
+ if (subject === undefined) return;
173
+ if (!best || STRICTNESS[rule.effect] > STRICTNESS[best.effect]) best = { effect: rule.effect, ruleIndex, subject };
174
+ });
175
+ return best ?? { effect: null };
176
+ }
177
+
178
+ // The matched text, `undefined` when the rule does not apply to this input.
179
+ function subjectFor(rule, name, toolInput, input) {
180
+ if (rule.command !== undefined) {
181
+ if (typeof toolInput.command !== "string") return "";
182
+ return commandPieces(toolInput.command).find((piece) => globMatch(rule.command, piece));
183
+ }
184
+ if (rule.path !== undefined) {
185
+ let raw;
186
+ for (const field of PATH_FIELDS[name] ?? []) if (typeof toolInput[field] === "string") raw = toolInput[field];
187
+ if (raw === undefined && SEARCH_TOOLS.has(name) && typeof input?.cwd === "string") raw = input.cwd;
188
+ if (raw === undefined) return "";
189
+ const path = normalisePath(raw);
190
+ return globMatch(rule.path, path) ? path : undefined;
191
+ }
192
+ if (rule.domain !== undefined) {
193
+ let host;
194
+ try {
195
+ host = new URL(String(toolInput.url)).hostname.toLowerCase();
196
+ } catch {
197
+ return "";
198
+ }
199
+ if (rule.domain.startsWith("*.")) {
200
+ const base = rule.domain.slice(2);
201
+ return host === base || host.endsWith(`.${base}`) ? host : undefined;
202
+ }
203
+ return host === rule.domain ? host : undefined;
204
+ }
205
+ return name;
206
+ }
@@ -0,0 +1,66 @@
1
+ // Subscription mode's limit (Phase 1): Anthropic's usage
2
+ // window.
3
+ //
4
+ // A Pro/Max subscription pays a flat fee, so dollars are not what runs out: the
5
+ // 5-hour and 7-day allowances are. Claude Code passes how much of each is used to its
6
+ // status-line command on stdin, as `rate_limits` (Pro/Max only, and only after the
7
+ // session's first response; code.claude.com/docs/en/statusline, read 2026-10-11).
8
+ // `passcontrol statusline` reads it from there, shows it, and hands it to the sidecar
9
+ // on WINDOW_PATH, so `watch` and `/passcontrol` can show it too.
10
+ //
11
+ // It is shown, never enforced (the owner's choice on 2026-10-11): Anthropic enforces
12
+ // its own window, and the number is the client's report.
13
+
14
+ export const WINDOW_PATH = "/_passcontrol/window";
15
+
16
+ // Seconds since the epoch, from 2001 to 2286: anything else is not a reset time.
17
+ const isEpochSeconds = (v) => Number.isInteger(v) && v > 1_000_000_000 && v < 10_000_000_000;
18
+ // A percentage of an allowance. Over 100 is allowed: a window can be overrun.
19
+ const isPct = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1000;
20
+
21
+ function one(raw, pctKey, resetKey) {
22
+ if (!raw || typeof raw !== "object" || !isPct(raw[pctKey])) return null;
23
+ return { usedPct: raw[pctKey], resetsAt: isEpochSeconds(raw[resetKey]) ? raw[resetKey] : null };
24
+ }
25
+
26
+ function both(fiveHour, sevenDay) {
27
+ return fiveHour || sevenDay ? { fiveHour, sevenDay } : null;
28
+ }
29
+
30
+ /** The window from Claude Code's status-line input, or null. Never throws. */
31
+ export function readUsageWindow(input) {
32
+ const limits = input && typeof input === "object" ? input.rate_limits : null;
33
+ if (!limits || typeof limits !== "object") return null;
34
+ return both(one(limits.five_hour, "used_percentage", "resets_at"), one(limits.seven_day, "used_percentage", "resets_at"));
35
+ }
36
+
37
+ /** A window in this module's own shape, held to it again: what the sidecar accepts. */
38
+ export function heldUsageWindow(value) {
39
+ if (!value || typeof value !== "object") return null;
40
+ return both(one(value.fiveHour, "usedPct", "resetsAt"), one(value.sevenDay, "usedPct", "resetsAt"));
41
+ }
42
+
43
+ const pad2 = (n) => String(n).padStart(2, "0");
44
+ const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
45
+
46
+ /** A reset time as the local clock reads it, with the weekday when it is not today. */
47
+ export function resetTime(epochSeconds, now = Date.now()) {
48
+ const at = new Date(epochSeconds * 1000);
49
+ const clock = `${pad2(at.getHours())}:${pad2(at.getMinutes())}`;
50
+ return at.toDateString() === new Date(now).toDateString() ? clock : `${DAYS[at.getDay()]} ${clock}`;
51
+ }
52
+
53
+ /**
54
+ * `5h 24% (resets 21:40) · 7d 41% (resets Tue 09:00)`, or with `short`, `5h 24% · 7d 41%`.
55
+ * Empty for no window.
56
+ */
57
+ export function usageWindowText(window, { short = false, formatTime = resetTime } = {}) {
58
+ const held = heldUsageWindow(window);
59
+ if (!held) return "";
60
+ const part = (label, w) => {
61
+ if (!w) return null;
62
+ const resets = !short && w.resetsAt ? ` (resets ${formatTime(w.resetsAt)})` : "";
63
+ return `${label} ${Math.round(w.usedPct)}%${resets}`;
64
+ };
65
+ return [part("5h", held.fiveHour), part("7d", held.sevenDay)].filter(Boolean).join(" · ");
66
+ }