passcontrol 1.5.0 → 1.6.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 -4
- package/bin/passcontrol.mjs +164 -5
- package/cli/agent-note.mjs +169 -0
- package/cli/budget-format.mjs +101 -8
- package/cli/claude-code.mjs +226 -2
- package/cli/client-events-upload.mjs +212 -0
- package/cli/codex-hooks.mjs +246 -0
- package/cli/config.mjs +3 -0
- package/cli/login.mjs +16 -1
- package/cli/mcp/README.md +2 -1
- package/cli/menu.mjs +1 -0
- package/cli/otlp-logs.mjs +96 -0
- package/cli/selftest.mjs +10 -0
- package/cli/sidecar.mjs +301 -5
- package/cli/statusline.mjs +107 -9
- package/cli/subscription-gate.mjs +270 -0
- package/cli/tool-gate.mjs +157 -0
- package/cli/tool-rules.d.mts +28 -0
- package/cli/tool-rules.mjs +206 -0
- package/cli/usage-window.mjs +66 -0
- package/cli/watch-feed.mjs +77 -7
- package/cli/watch.mjs +56 -12
- package/package.json +1 -1
|
@@ -0,0 +1,270 @@
|
|
|
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
|
+
// The agent's own note (1.6.0, cli/agent-note.mjs) rides on the prompt hook when its
|
|
38
|
+
// URL opts in: `?note=1` in this mode, `?note=only` when Claude Code goes through the
|
|
39
|
+
// sidecar with an API key, where the gateway already enforces and the hook only ever
|
|
40
|
+
// adds the note. It is built from the latest answer and sent per session only when
|
|
41
|
+
// its signature changes; a stop always wins over it.
|
|
42
|
+
//
|
|
43
|
+
// Honest limit: hooks run inside Claude Code, so this is a guard rail for the user's
|
|
44
|
+
// own sessions, not a boundary against a client that skips them.
|
|
45
|
+
|
|
46
|
+
import { agentNote } from "./agent-note.mjs";
|
|
47
|
+
|
|
48
|
+
export const HOOK_PATH = "/_passcontrol/hook";
|
|
49
|
+
|
|
50
|
+
const GATED = new Set(["UserPromptSubmit", "PreToolUse", "PostToolBatch"]);
|
|
51
|
+
// What the gateway accepts as a declared session (lib/client-lineage.ts).
|
|
52
|
+
const DECLARED_SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
53
|
+
|
|
54
|
+
// Claude Code's timeout on the prompt and next-model-call hooks (cli/claude-code.mjs).
|
|
55
|
+
// Past it the action goes ahead with no warning at all, so the sidecar's read of
|
|
56
|
+
// /api/v1/self ends a second earlier and says why. 2 s was too short: a Cloud answer
|
|
57
|
+
// on a cold start took longer, and a stop was missed with "did not answer in time".
|
|
58
|
+
export const GATE_HOOK_TIMEOUT_S = 5;
|
|
59
|
+
export const SELF_READ_TIMEOUT_MS = (GATE_HOOK_TIMEOUT_S - 1) * 1000;
|
|
60
|
+
|
|
61
|
+
export const GATE_FRESH_MS = 5_000;
|
|
62
|
+
export const GATE_SESSION_FRESH_MS = 15_000;
|
|
63
|
+
export const GATE_MAX_STALE_MS = 60_000;
|
|
64
|
+
const MAX_SESSIONS = 512;
|
|
65
|
+
const WARN_EVERY_MS = 60_000;
|
|
66
|
+
|
|
67
|
+
function stopText(state, dashboardUrl) {
|
|
68
|
+
const where = dashboardUrl ? ` Lift it from ${dashboardUrl}` : "";
|
|
69
|
+
if (state === "session_stopped") {
|
|
70
|
+
return `PassControl: the agent's owner stopped this session, so nothing more runs in it.${where ? `${where} (the agent's Sessions view).` : ""}`;
|
|
71
|
+
}
|
|
72
|
+
return `PassControl: this agent is stopped — its owner suspended it, or the kill switch is on.${where ? `${where}.` : ""}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function blockFor(event, reason) {
|
|
76
|
+
const end = { continue: false, stopReason: reason };
|
|
77
|
+
if (event === "PreToolUse") {
|
|
78
|
+
return {
|
|
79
|
+
...end,
|
|
80
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason },
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
return { ...end, decision: "block", reason };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @param {{
|
|
88
|
+
* readSelf: (session: string | null) => Promise<{ state: "open" | "stopped" | "session_stopped" | "unknown", reason?: string }>,
|
|
89
|
+
* dashboardUrl?: string,
|
|
90
|
+
* now?: () => number,
|
|
91
|
+
* freshMs?: number,
|
|
92
|
+
* sessionFreshMs?: number,
|
|
93
|
+
* maxStaleMs?: number,
|
|
94
|
+
* maxSessions?: number,
|
|
95
|
+
* }} options
|
|
96
|
+
*/
|
|
97
|
+
export function createStopGate({
|
|
98
|
+
readSelf,
|
|
99
|
+
dashboardUrl = "",
|
|
100
|
+
now = () => Date.now(),
|
|
101
|
+
freshMs = GATE_FRESH_MS,
|
|
102
|
+
sessionFreshMs = GATE_SESSION_FRESH_MS,
|
|
103
|
+
maxStaleMs = GATE_MAX_STALE_MS,
|
|
104
|
+
maxSessions = MAX_SESSIONS,
|
|
105
|
+
}) {
|
|
106
|
+
// The last KNOWN answers (never "unknown"). The agent's: "open" | "stopped".
|
|
107
|
+
// A session's: "open" | "session_stopped", or "behind" when it was last asked while
|
|
108
|
+
// the whole agent was stopped, which hides whether the session is stopped on its own.
|
|
109
|
+
let agent = null;
|
|
110
|
+
// The agent's tool rules as the last answer that carried them gave them.
|
|
111
|
+
let rules = null;
|
|
112
|
+
// The limits from the latest open answer, for the note; and each session's last note.
|
|
113
|
+
let latest = null;
|
|
114
|
+
const noted = new Map();
|
|
115
|
+
const sessions = new Map();
|
|
116
|
+
const inflight = new Map();
|
|
117
|
+
const warnedAt = new Map();
|
|
118
|
+
|
|
119
|
+
function remember(map, key, value) {
|
|
120
|
+
map.delete(key);
|
|
121
|
+
map.set(key, value);
|
|
122
|
+
while (map.size > maxSessions) map.delete(map.keys().next().value);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// One answer can settle both: a session's "open" says the agent is running too, a
|
|
126
|
+
// "session_stopped" is only ever given to a running agent, and "stopped" is agent-wide.
|
|
127
|
+
function record(session, state) {
|
|
128
|
+
const at = now();
|
|
129
|
+
if (state === "open" || state === "session_stopped") agent = { state: "open", at };
|
|
130
|
+
if (state === "stopped") agent = { state: "stopped", at };
|
|
131
|
+
if (session !== null) remember(sessions, session, { state: state === "stopped" ? "behind" : state, at });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function ask(session) {
|
|
135
|
+
const key = session ?? "";
|
|
136
|
+
if (inflight.has(key)) return inflight.get(key);
|
|
137
|
+
const pending = (async () => {
|
|
138
|
+
let answer;
|
|
139
|
+
try {
|
|
140
|
+
answer = await readSelf(session);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
answer = { state: "unknown", reason: error?.message ?? "error" };
|
|
143
|
+
}
|
|
144
|
+
answer ??= { state: "unknown", reason: "no answer" };
|
|
145
|
+
if (answer.state === "open" && answer.self) latest = { self: answer.self, at: now() };
|
|
146
|
+
if (answer.state === "open") {
|
|
147
|
+
rules = { read: answer.toolRules && typeof answer.toolRules === "object" ? answer.toolRules : { state: "none" }, at: now() };
|
|
148
|
+
}
|
|
149
|
+
if (["open", "stopped"].includes(answer.state) || (session !== null && answer.state === "session_stopped")) {
|
|
150
|
+
record(session, answer.state);
|
|
151
|
+
}
|
|
152
|
+
return answer;
|
|
153
|
+
})();
|
|
154
|
+
inflight.set(key, pending);
|
|
155
|
+
try {
|
|
156
|
+
return await pending;
|
|
157
|
+
} finally {
|
|
158
|
+
inflight.delete(key);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function warnOnce(key, reason) {
|
|
163
|
+
const last = warnedAt.get(key);
|
|
164
|
+
if (last !== undefined && now() - last < WARN_EVERY_MS) return {};
|
|
165
|
+
remember(warnedAt, key, now());
|
|
166
|
+
return {
|
|
167
|
+
systemMessage: `PassControl could not check this agent's stops (${String(reason ?? "no answer").slice(0, 80)}), so this goes ahead. Is \`passcontrol sidecar\` running?`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const age = (entry) => (entry ? now() - entry.at : Infinity);
|
|
172
|
+
|
|
173
|
+
/** The note for this session's prompt, when it opted in and something changed since the last. */
|
|
174
|
+
function noteFor(sessionKey, mode) {
|
|
175
|
+
if (!latest || age(latest) > maxStaleMs) return null;
|
|
176
|
+
const freshRules = rules && age(rules) <= maxStaleMs ? rules.read : null;
|
|
177
|
+
const n = agentNote({ self: latest.self, rules: freshRules, mode, nowMs: now() });
|
|
178
|
+
if (!n || noted.get(sessionKey) === n.signature) return null;
|
|
179
|
+
remember(noted, sessionKey, n.signature);
|
|
180
|
+
return { hookEventName: "UserPromptSubmit", additionalContext: n.text };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* @param {object} input Claude Code's hook input.
|
|
185
|
+
* @param {{ note?: "api" | "subscription" | null }} [options] the prompt hook's opt-in.
|
|
186
|
+
*/
|
|
187
|
+
async function decide(input, { note = null } = {}) {
|
|
188
|
+
const event = input?.hook_event_name;
|
|
189
|
+
if (note === "api") {
|
|
190
|
+
// Only the note, never a stop or a warning: the gateway refuses these calls itself.
|
|
191
|
+
if (event !== "UserPromptSubmit") return {};
|
|
192
|
+
if (age(latest) >= freshMs) await ask(null);
|
|
193
|
+
const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : "";
|
|
194
|
+
const out = noteFor(session, "api");
|
|
195
|
+
return out ? { hookSpecificOutput: out } : {};
|
|
196
|
+
}
|
|
197
|
+
const out = await gateDecision(input, event);
|
|
198
|
+
if (note === "subscription" && event === "UserPromptSubmit" && out.continue !== false) {
|
|
199
|
+
const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : "";
|
|
200
|
+
const extra = noteFor(session, "subscription");
|
|
201
|
+
if (extra) return { ...out, hookSpecificOutput: extra };
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function gateDecision(input, event) {
|
|
207
|
+
if (!GATED.has(event)) return {};
|
|
208
|
+
const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : null;
|
|
209
|
+
|
|
210
|
+
// A session asked behind an agent-wide stop is due again as soon as the agent
|
|
211
|
+
// is known to be running: its own stop may still stand.
|
|
212
|
+
const sessionDue = () => {
|
|
213
|
+
if (session === null) return false;
|
|
214
|
+
const own = sessions.get(session);
|
|
215
|
+
return age(own) >= sessionFreshMs || (own?.state === "behind" && agent?.state === "open");
|
|
216
|
+
};
|
|
217
|
+
let reason = null;
|
|
218
|
+
let askedAgent = false;
|
|
219
|
+
if (sessionDue()) reason = (await ask(session)).reason ?? null;
|
|
220
|
+
else if (age(agent) >= freshMs) {
|
|
221
|
+
askedAgent = true;
|
|
222
|
+
reason = (await ask(null)).reason ?? null;
|
|
223
|
+
if (sessionDue()) reason = (await ask(session)).reason ?? reason;
|
|
224
|
+
}
|
|
225
|
+
if (event === "PreToolUse" && !askedAgent && age(rules) >= freshMs) await ask(null);
|
|
226
|
+
|
|
227
|
+
// Act on what is known and still trusted; fail open, visibly, on anything else.
|
|
228
|
+
const trusted = (entry) => entry && age(entry) <= maxStaleMs;
|
|
229
|
+
const a = trusted(agent) ? agent : null;
|
|
230
|
+
const s = session === null ? null : sessions.get(session);
|
|
231
|
+
const sTrusted = trusted(s) ? s : null;
|
|
232
|
+
if (a?.state === "stopped") return blockFor(event, stopText("stopped", dashboardUrl));
|
|
233
|
+
if (sTrusted?.state === "session_stopped") return blockFor(event, stopText("session_stopped", dashboardUrl));
|
|
234
|
+
if (a?.state === "open" && (session === null || sTrusted?.state === "open")) return {};
|
|
235
|
+
return warnOnce(session ?? "", reason ?? "no answer");
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** The tool rules from the latest answer, or null once they are older than `maxStaleMs`. */
|
|
239
|
+
function toolRules() {
|
|
240
|
+
return rules && age(rules) <= maxStaleMs ? rules : null;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return { decide, toolRules };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Maps the gateway's answer to GET /api/v1/self onto a gate state. The gateway's
|
|
248
|
+
* 403 is deliberately opaque between suspend and kill switch; a stopped session is
|
|
249
|
+
* the one it names.
|
|
250
|
+
*/
|
|
251
|
+
export async function selfAnswerState(response) {
|
|
252
|
+
if (response.ok) {
|
|
253
|
+
const body = await response.json().catch(() => null);
|
|
254
|
+
const toolRules = body && typeof body === "object" ? body.tool_rules : undefined;
|
|
255
|
+
const answer = toolRules && typeof toolRules === "object" ? { state: "open", toolRules } : { state: "open" };
|
|
256
|
+
// The limits and the soft pause, for the agent's note; nothing else from the answer is kept.
|
|
257
|
+
if (body && typeof body === "object" && body.budget && typeof body.budget === "object") {
|
|
258
|
+
const kept = (v) => (v && typeof v === "object" ? v : null);
|
|
259
|
+
answer.self = { budget: body.budget, pace: kept(body.pace), pause: kept(body.pause) };
|
|
260
|
+
}
|
|
261
|
+
return answer;
|
|
262
|
+
}
|
|
263
|
+
if (response.status === 403) {
|
|
264
|
+
const body = await response.json().catch(() => ({}));
|
|
265
|
+
const message = typeof body?.message === "string" ? body.message : "";
|
|
266
|
+
return { state: message.includes("stopped this session") ? "session_stopped" : "stopped" };
|
|
267
|
+
}
|
|
268
|
+
await response.body?.cancel().catch(() => {});
|
|
269
|
+
return { state: "unknown", reason: `gateway answered HTTP ${response.status}` };
|
|
270
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
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
|
+
// Said with every rule's refusal: told only "the tool rules refuse this", Claude
|
|
57
|
+
// Code went looking for the rule in the local PassControl config, which has none.
|
|
58
|
+
const rulesLive = dashboardUrl
|
|
59
|
+
? `Tool rules are set on the agent's page at ${dashboardUrl}, not on this machine.`
|
|
60
|
+
: "Tool rules are set on the agent's dashboard page, not on this machine.";
|
|
61
|
+
|
|
62
|
+
function record(input, decision, ruleIndex, waitMs) {
|
|
63
|
+
try {
|
|
64
|
+
onDecision({
|
|
65
|
+
session: declared(input.session_id),
|
|
66
|
+
agent: declared(input.agent_id),
|
|
67
|
+
tool: String(input.tool_name ?? "").slice(0, 128),
|
|
68
|
+
decision,
|
|
69
|
+
ruleIndex,
|
|
70
|
+
waitMs,
|
|
71
|
+
});
|
|
72
|
+
} catch {
|
|
73
|
+
// A record is a record; it never changes the answer.
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @param {object} input Claude Code's PreToolUse hook input.
|
|
79
|
+
* @param {{ read: { state: string, document?: unknown }, at: number } | null} rulesEntry
|
|
80
|
+
* The rules from the latest trusted /self read, or null.
|
|
81
|
+
* @param {number | null} hookTimeoutS What the hook's URL says it waits; null when it does not say.
|
|
82
|
+
*/
|
|
83
|
+
async function decide(input, rulesEntry, hookTimeoutS) {
|
|
84
|
+
if (input?.hook_event_name !== "PreToolUse") return {};
|
|
85
|
+
const read = rulesEntry?.read;
|
|
86
|
+
if (read?.state === "none") return {};
|
|
87
|
+
if (read?.state === "invalid") {
|
|
88
|
+
record(input, "rules_invalid", null, 0);
|
|
89
|
+
return verdict("deny", `PassControl: this agent's tool rules cannot be read here, so no tool runs until they are fixed${where}.`);
|
|
90
|
+
}
|
|
91
|
+
const parsed = read?.state === "ok" ? parseToolRules(read.document) : null;
|
|
92
|
+
if (!parsed) {
|
|
93
|
+
if (warnedAt !== null && now() - warnedAt < WARN_EVERY_MS) return {};
|
|
94
|
+
warnedAt = now();
|
|
95
|
+
return { systemMessage: "PassControl could not read this agent's tool rules yet, so this goes ahead. Is `passcontrol sidecar` running?" };
|
|
96
|
+
}
|
|
97
|
+
if (!parsed.ok) {
|
|
98
|
+
record(input, "rules_invalid", null, 0);
|
|
99
|
+
return verdict("deny", `PassControl: this agent's tool rules cannot be read here, so no tool runs until they are fixed${where}.`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const hit = evaluateToolRules(parsed, input);
|
|
103
|
+
if (hit.effect === null) return {};
|
|
104
|
+
const rule = `rule ${hit.ruleIndex + 1}`;
|
|
105
|
+
if (hit.effect === "deny") {
|
|
106
|
+
record(input, "deny", hit.ruleIndex, 0);
|
|
107
|
+
return verdict("deny", `PassControl: the agent's tool rules refuse this (${rule}: ${short(hit.subject)}). ${rulesLive}`);
|
|
108
|
+
}
|
|
109
|
+
if (hit.effect === "ask") {
|
|
110
|
+
record(input, "ask", hit.ruleIndex, 0);
|
|
111
|
+
return verdict("ask", `PassControl: the agent's tool rules ask you to confirm this (${rule}: ${short(hit.subject)}). ${rulesLive}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ask_owner
|
|
115
|
+
const waitS = hookTimeoutS === null ? 0 : Math.min(parsed.approvalWaitS, hookTimeoutS - HOOK_MARGIN_S);
|
|
116
|
+
if (waitS < MIN_WAIT_S) {
|
|
117
|
+
record(input, "owner_unavailable", hit.ruleIndex, 0);
|
|
118
|
+
return verdict(
|
|
119
|
+
"deny",
|
|
120
|
+
`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.`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
const started = now();
|
|
124
|
+
let answer;
|
|
125
|
+
try {
|
|
126
|
+
answer = await askOwner(input, { ruleIndex: hit.ruleIndex, subject: hit.subject, session: declared(input.session_id), waitMs: waitS * 1000 });
|
|
127
|
+
} catch {
|
|
128
|
+
answer = { state: "unavailable" };
|
|
129
|
+
}
|
|
130
|
+
const waited = Math.max(0, now() - started);
|
|
131
|
+
switch (answer?.state) {
|
|
132
|
+
case "approved":
|
|
133
|
+
record(input, "owner_approved", hit.ruleIndex, waited);
|
|
134
|
+
return {};
|
|
135
|
+
case "denied":
|
|
136
|
+
record(input, "owner_denied", hit.ruleIndex, waited);
|
|
137
|
+
return verdict("deny", `PassControl: the agent's owner said no to this (${rule}). ${rulesLive}`);
|
|
138
|
+
case "timeout":
|
|
139
|
+
record(input, "owner_timeout", hit.ruleIndex, waited);
|
|
140
|
+
return verdict("deny", `PassControl: the agent's owner did not answer within ${waitS} s, so this was not run (${rule}).`);
|
|
141
|
+
case "full":
|
|
142
|
+
record(input, "owner_unavailable", hit.ruleIndex, waited);
|
|
143
|
+
return verdict("deny", `PassControl: too many questions are already waiting for the agent's owner, so this was not run (${rule}).`);
|
|
144
|
+
case "too_large":
|
|
145
|
+
record(input, "owner_unavailable", hit.ruleIndex, waited);
|
|
146
|
+
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.`);
|
|
147
|
+
case "refused":
|
|
148
|
+
record(input, "owner_unavailable", hit.ruleIndex, waited);
|
|
149
|
+
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.`);
|
|
150
|
+
default:
|
|
151
|
+
record(input, "owner_unavailable", hit.ruleIndex, waited);
|
|
152
|
+
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.`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return { decide };
|
|
157
|
+
}
|
|
@@ -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
|
+
}
|