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.
- package/LICENSE +3 -1
- package/README.md +10 -1
- package/bin/passcontrol.mjs +266 -8
- package/cli/budget-format.mjs +37 -0
- package/cli/claude-code.mjs +179 -0
- package/cli/client-events-upload.mjs +212 -0
- package/cli/config.mjs +35 -1
- package/cli/declared-session.mjs +32 -4
- package/cli/delegation.d.mts +60 -0
- package/cli/delegation.mjs +192 -0
- package/cli/menu.mjs +4 -0
- package/cli/otlp-logs.mjs +96 -0
- package/cli/profiles.mjs +92 -0
- package/cli/protocols.mjs +3 -1
- package/cli/sidecar.mjs +441 -21
- package/cli/statusline.mjs +223 -1
- package/cli/subscription-gate.mjs +213 -0
- package/cli/tool-gate.mjs +152 -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/visa-client.mjs +5 -1
- package/cli/watch-feed.mjs +345 -0
- package/cli/watch.mjs +640 -0
- package/package.json +1 -1
- package/sdk/index.d.ts +2 -1
- package/sdk/index.js +3 -0
- package/sdk/passcontrol.d.ts +46 -0
- package/sdk/passcontrol.js +47 -2
- package/sdk/verify.d.ts +7 -0
|
@@ -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
|
+
}
|
package/cli/visa-client.mjs
CHANGED
|
@@ -53,7 +53,11 @@ export function createVisaClient({
|
|
|
53
53
|
});
|
|
54
54
|
|
|
55
55
|
if (!response.ok) {
|
|
56
|
-
|
|
56
|
+
// The status travels with the error: the sidecar waits out a gateway that is
|
|
57
|
+
// not answering yet (5xx) and stops at once on one that refuses (4xx).
|
|
58
|
+
throw Object.assign(new Error(formatChallengeError(response.status, await response.text())), {
|
|
59
|
+
status: response.status,
|
|
60
|
+
});
|
|
57
61
|
}
|
|
58
62
|
|
|
59
63
|
const data = await response.json();
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
// The sidecar's live feed for `passcontrol watch` (F6): one event per call it relays,
|
|
2
|
+
// served on the sidecar's own loopback listener and kept in memory only.
|
|
3
|
+
//
|
|
4
|
+
// What it carries is what the board shows and nothing else: when, the declared
|
|
5
|
+
// session and sub-agent, the model id, the provider, BOARDED / DENIED / ERROR with
|
|
6
|
+
// the gateway's refusal CODE (never its message), the status, and the latency. No
|
|
7
|
+
// prompt, no response, no message text, no path beyond the provider's name. Nothing
|
|
8
|
+
// is written to disk: the journal (cli/journal.mjs) stays receipt ids only, as D3
|
|
9
|
+
// promised, and this ring buffer dies with the process.
|
|
10
|
+
//
|
|
11
|
+
// Who may read it. The sidecar holds a passport, so it is already bound to loopback
|
|
12
|
+
// by `assertBindHost`; the feed adds the checks a browser would otherwise get around:
|
|
13
|
+
// * GET only, from a loopback peer;
|
|
14
|
+
// * a Host header naming this loopback listener and port exactly, so a page that
|
|
15
|
+
// rebinds its own hostname to 127.0.0.1 is refused (DNS rebinding);
|
|
16
|
+
// * no Origin header, which a browser sends on a cross-origin request;
|
|
17
|
+
// * no CORS grant, ever.
|
|
18
|
+
// A sidecar bound off loopback (`allowNonLoopback`) serves no feed at all.
|
|
19
|
+
//
|
|
20
|
+
// It must never slow or break a call: every write is guarded, a subscriber that
|
|
21
|
+
// cannot keep up is dropped rather than buffered for, and nothing on the proxy
|
|
22
|
+
// path waits on a subscriber.
|
|
23
|
+
|
|
24
|
+
export const WATCH_PATH = "/_passcontrol/watch";
|
|
25
|
+
/** Paths under this prefix are the sidecar's own and are never forwarded. */
|
|
26
|
+
export const LOCAL_PREFIX = "/_passcontrol/";
|
|
27
|
+
|
|
28
|
+
const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
29
|
+
// A model id as the providers and routers spell them: claude-opus-5-5,
|
|
30
|
+
// gpt-5.1-codex, openrouter/anthropic/claude-sonnet-5.5, qwen3:8b, meta-llama/Llama-3@q4.
|
|
31
|
+
const MODEL = /^[A-Za-z0-9._:/@-]{1,100}$/;
|
|
32
|
+
// The gateway's refusal codes are lower-case snake case (`errR(status, code)`).
|
|
33
|
+
const CODE = /^[a-z][a-z0-9_]{1,47}$/;
|
|
34
|
+
const PROVIDER = /^[a-z0-9-]{1,32}$/;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Bodies larger than this are not parsed for their model: the row shows none. The
|
|
38
|
+
* sidecar already holds the whole body to forward it; parsing it costs about 0.6 ms
|
|
39
|
+
* at 500 KB and 4.5 ms at this cap (measured 2026-10-11, M-series Mac), against a
|
|
40
|
+
* model call that takes seconds.
|
|
41
|
+
*/
|
|
42
|
+
const MODEL_PARSE_LIMIT = 4 * 1024 * 1024;
|
|
43
|
+
/** How much of an error body is read to find a refusal code. */
|
|
44
|
+
const REFUSAL_PEEK_BYTES = 8 * 1024;
|
|
45
|
+
/**
|
|
46
|
+
* A subscriber with more than this queued and unsent is dropped. Bytes, not
|
|
47
|
+
* write()'s return value: the replay alone passes the socket's 16 KB high-water
|
|
48
|
+
* mark, and a board that is merely starting up is not a board that cannot keep up.
|
|
49
|
+
*/
|
|
50
|
+
const MAX_BUFFERED_BYTES = 1024 * 1024;
|
|
51
|
+
|
|
52
|
+
const held = (pattern, value) => (typeof value === "string" && pattern.test(value) ? value : null);
|
|
53
|
+
|
|
54
|
+
/** The request's top-level `model`, if it is a well-formed model id. */
|
|
55
|
+
export function requestModel(body) {
|
|
56
|
+
if (!body || body.length === 0 || body.length > MODEL_PARSE_LIMIT) return null;
|
|
57
|
+
try {
|
|
58
|
+
const parsed = JSON.parse(body.toString("utf8"));
|
|
59
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? held(MODEL, parsed.model) : null;
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The gateway's refusal code from an error body, or null. The gateway's own
|
|
67
|
+
* refusals are `{ "error": "<code>" }` with a string; a provider's errors carry an
|
|
68
|
+
* object there, and an Ollama-style string is prose, which fails the pattern.
|
|
69
|
+
*/
|
|
70
|
+
export function refusalCode(text) {
|
|
71
|
+
try {
|
|
72
|
+
const parsed = JSON.parse(text);
|
|
73
|
+
return held(CODE, parsed?.error);
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** `/api/v1/<provider>/...` → provider, else null. */
|
|
80
|
+
export function providerOf(path) {
|
|
81
|
+
const match = /^\/api\/v1\/([^/?#]+)/.exec(String(path ?? ""));
|
|
82
|
+
return match ? held(PROVIDER, match[1]) : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Gateway paths that are not model calls: the budget read the board and the status
|
|
87
|
+
* line poll, and the upload of calls a client reported (cli/client-events-upload.mjs).
|
|
88
|
+
*/
|
|
89
|
+
export function isNotACall(path) {
|
|
90
|
+
return /^\/api\/v1\/(self|client-events)(\?|$)/.test(String(path ?? ""));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Reads at most `limit` bytes of a (cloned) body, then cancels it. Never throws. */
|
|
94
|
+
export async function peekText(body, limit = REFUSAL_PEEK_BYTES) {
|
|
95
|
+
if (!body) return "";
|
|
96
|
+
const reader = body.getReader();
|
|
97
|
+
const chunks = [];
|
|
98
|
+
let size = 0;
|
|
99
|
+
try {
|
|
100
|
+
while (size < limit) {
|
|
101
|
+
const { done, value } = await reader.read();
|
|
102
|
+
if (done) break;
|
|
103
|
+
chunks.push(value);
|
|
104
|
+
size += value.length;
|
|
105
|
+
}
|
|
106
|
+
} catch {
|
|
107
|
+
// An aborted body has no code to read.
|
|
108
|
+
} finally {
|
|
109
|
+
reader.cancel().catch(() => {});
|
|
110
|
+
}
|
|
111
|
+
return Buffer.concat(chunks.map((c) => Buffer.from(c))).subarray(0, limit).toString("utf8");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const LOOPBACK_PEER = /^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;
|
|
115
|
+
const LOOPBACK_NAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
116
|
+
|
|
117
|
+
function hostIsThisListener(hostHeader, port) {
|
|
118
|
+
if (typeof hostHeader !== "string") return false;
|
|
119
|
+
const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(hostHeader.trim().toLowerCase());
|
|
120
|
+
return Boolean(match && LOOPBACK_NAMES.has(match[1]) && Number(match[2]) === port);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The checks every one of the sidecar's own endpoints makes before answering: a
|
|
125
|
+
* loopback peer, no Origin (a browser's cross-origin request carries one), and a Host
|
|
126
|
+
* naming this loopback listener and port exactly (DNS rebinding). The watch feed and
|
|
127
|
+
* subscription mode's hook endpoint share them.
|
|
128
|
+
*/
|
|
129
|
+
export function isLocalCaller(req, port) {
|
|
130
|
+
const loopbackPeer = LOOPBACK_PEER.test(String(req.socket?.remoteAddress ?? ""));
|
|
131
|
+
return loopbackPeer && req.headers.origin === undefined && hostIsThisListener(req.headers.host, port);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function answer(res, status, error, message) {
|
|
135
|
+
const body = JSON.stringify({ error, message });
|
|
136
|
+
res.writeHead(status, {
|
|
137
|
+
"content-type": "application/json",
|
|
138
|
+
"content-length": Buffer.byteLength(body),
|
|
139
|
+
"cache-control": "no-store",
|
|
140
|
+
"x-content-type-options": "nosniff",
|
|
141
|
+
connection: "close",
|
|
142
|
+
});
|
|
143
|
+
res.end(body);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* @param {{ runId: string, capacity?: number, maxSubscribers?: number, enabled?: boolean, now?: () => number }} options
|
|
148
|
+
*/
|
|
149
|
+
export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, enabled = true, now = () => Date.now() }) {
|
|
150
|
+
const ring = [];
|
|
151
|
+
const subscribers = new Set();
|
|
152
|
+
let seq = 0;
|
|
153
|
+
// Subscription mode's usage window (cli/usage-window.mjs): only the latest matters.
|
|
154
|
+
let usageWindow = null;
|
|
155
|
+
|
|
156
|
+
function send(res, line) {
|
|
157
|
+
try {
|
|
158
|
+
// A subscriber whose socket is backed up is dropped: buffering for it would
|
|
159
|
+
// grow without bound, and waiting for it would slow calls.
|
|
160
|
+
res.write(line);
|
|
161
|
+
if ((res.writableLength ?? 0) > MAX_BUFFERED_BYTES) drop(res);
|
|
162
|
+
} catch {
|
|
163
|
+
drop(res);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function drop(res) {
|
|
168
|
+
subscribers.delete(res);
|
|
169
|
+
try {
|
|
170
|
+
res.destroy();
|
|
171
|
+
} catch {
|
|
172
|
+
// Already gone.
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function broadcast(event) {
|
|
177
|
+
if (subscribers.size === 0) return;
|
|
178
|
+
let line;
|
|
179
|
+
try {
|
|
180
|
+
line = `${JSON.stringify(event)}\n`;
|
|
181
|
+
} catch {
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
for (const res of [...subscribers]) send(res, line);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function remember(record) {
|
|
188
|
+
ring.push(record);
|
|
189
|
+
if (ring.length > capacity) ring.splice(0, ring.length - capacity);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* A call the board will show. `settle` announces it once its outcome is known;
|
|
194
|
+
* `finish` records the total time when the response is done. Either order works:
|
|
195
|
+
* a call that finishes before it is settled is announced with its total.
|
|
196
|
+
* Never throws.
|
|
197
|
+
*/
|
|
198
|
+
function begin({ startedAt = now(), lineage = null, model = null, provider = null } = {}) {
|
|
199
|
+
const record = {
|
|
200
|
+
type: "call",
|
|
201
|
+
seq: ++seq,
|
|
202
|
+
at: startedAt,
|
|
203
|
+
ses: held(DECLARED, lineage?.session),
|
|
204
|
+
agent: held(DECLARED, lineage?.agent),
|
|
205
|
+
parent: held(DECLARED, lineage?.parent),
|
|
206
|
+
model: held(MODEL, model),
|
|
207
|
+
provider: held(PROVIDER, provider),
|
|
208
|
+
outcome: null,
|
|
209
|
+
code: null,
|
|
210
|
+
status: null,
|
|
211
|
+
ttfb: null,
|
|
212
|
+
ms: null,
|
|
213
|
+
cost: null,
|
|
214
|
+
};
|
|
215
|
+
let announced = false;
|
|
216
|
+
return {
|
|
217
|
+
settle({ outcome, code = null, status, ttfb = null }) {
|
|
218
|
+
try {
|
|
219
|
+
if (announced) return;
|
|
220
|
+
announced = true;
|
|
221
|
+
record.outcome = ["boarded", "denied", "error"].includes(outcome) ? outcome : "error";
|
|
222
|
+
record.code = held(CODE, code);
|
|
223
|
+
record.status = Number.isInteger(status) ? status : null;
|
|
224
|
+
record.ttfb = Math.max(0, Math.round(Number.isFinite(ttfb) ? ttfb : now() - record.at));
|
|
225
|
+
remember(record);
|
|
226
|
+
broadcast(record);
|
|
227
|
+
} catch {
|
|
228
|
+
// The feed is never the reason a call fails.
|
|
229
|
+
}
|
|
230
|
+
},
|
|
231
|
+
finish() {
|
|
232
|
+
try {
|
|
233
|
+
if (record.ms !== null) return;
|
|
234
|
+
record.ms = Math.max(0, Math.round(now() - record.at));
|
|
235
|
+
if (announced) broadcast({ type: "end", seq: record.seq, ms: record.ms });
|
|
236
|
+
} catch {
|
|
237
|
+
// As above.
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* A call the CLIENT reported (subscription mode: Claude Code's own telemetry,
|
|
245
|
+
* cli/otlp-logs.mjs). It never passed this sidecar, so it is SEEN, not boarded, and
|
|
246
|
+
* its cost is the client's API-equivalent estimate in USD millionths. Never throws.
|
|
247
|
+
*/
|
|
248
|
+
function report({ at = now(), lineage = null, model = null, provider = null, outcome = "seen", status = null, ms = null, cost = null }) {
|
|
249
|
+
try {
|
|
250
|
+
const record = {
|
|
251
|
+
type: "call",
|
|
252
|
+
seq: ++seq,
|
|
253
|
+
at: Number.isFinite(at) ? at : now(),
|
|
254
|
+
ses: held(DECLARED, lineage?.session),
|
|
255
|
+
agent: held(DECLARED, lineage?.agent),
|
|
256
|
+
parent: held(DECLARED, lineage?.parent),
|
|
257
|
+
model: held(MODEL, model),
|
|
258
|
+
provider: held(PROVIDER, provider),
|
|
259
|
+
outcome: outcome === "seen" ? "seen" : "error",
|
|
260
|
+
code: null,
|
|
261
|
+
status: Number.isInteger(status) ? status : null,
|
|
262
|
+
ttfb: null,
|
|
263
|
+
ms: Number.isInteger(ms) && ms >= 0 ? ms : null,
|
|
264
|
+
cost: Number.isInteger(cost) && cost >= 0 ? cost : null,
|
|
265
|
+
};
|
|
266
|
+
remember(record);
|
|
267
|
+
broadcast(record);
|
|
268
|
+
} catch {
|
|
269
|
+
// The feed is never the reason anything fails.
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The latest usage window, already held to its shape by the caller. Replaces the
|
|
275
|
+
* last one and tells every board. Never throws.
|
|
276
|
+
*/
|
|
277
|
+
function setWindow(window) {
|
|
278
|
+
try {
|
|
279
|
+
usageWindow = { type: "window", fiveHour: window.fiveHour, sevenDay: window.sevenDay, at: now() };
|
|
280
|
+
broadcast(usageWindow);
|
|
281
|
+
} catch {
|
|
282
|
+
// As above.
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** A call whose outcome and end are known at once (refusals, upstream failures). */
|
|
287
|
+
function record({ outcome, code = null, status, lineage = null, model = null, provider = null, startedAt = now() }) {
|
|
288
|
+
const call = begin({ startedAt, lineage, model, provider });
|
|
289
|
+
call.finish();
|
|
290
|
+
call.settle({ outcome, code, status, ttfb: now() - startedAt });
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Adds a subscriber, replaying the ring. Exposed for tests; `serve` is the way in. */
|
|
294
|
+
function attach(res) {
|
|
295
|
+
subscribers.add(res);
|
|
296
|
+
send(res, `${JSON.stringify({ type: "hello", feed: "passcontrol-watch", v: 1, run: runId })}\n`);
|
|
297
|
+
if (usageWindow && subscribers.has(res)) send(res, `${JSON.stringify(usageWindow)}\n`);
|
|
298
|
+
for (const r of ring) if (subscribers.has(res)) send(res, `${JSON.stringify(r)}\n`);
|
|
299
|
+
try {
|
|
300
|
+
res.on("close", () => subscribers.delete(res));
|
|
301
|
+
} catch {
|
|
302
|
+
subscribers.delete(res);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Answers a request for `/_passcontrol/...`. `port` is the listener's bound port. */
|
|
307
|
+
function serve(req, res, { port }) {
|
|
308
|
+
req.resume();
|
|
309
|
+
const pathname = String(req.url ?? "").split("?")[0];
|
|
310
|
+
if (pathname !== WATCH_PATH) return answer(res, 404, "not_found", "Nothing is served here.");
|
|
311
|
+
if (!enabled) {
|
|
312
|
+
return answer(res, 404, "watch_off", "This sidecar is bound off loopback, so it serves no watch feed.");
|
|
313
|
+
}
|
|
314
|
+
if (req.method !== "GET") return answer(res, 405, "method_not_allowed", "The watch feed answers GET only.");
|
|
315
|
+
if (!isLocalCaller(req, port)) {
|
|
316
|
+
return answer(res, 403, "watch_refused", "The watch feed is for `passcontrol watch` on this machine only.");
|
|
317
|
+
}
|
|
318
|
+
if (subscribers.size >= maxSubscribers) {
|
|
319
|
+
return answer(res, 503, "watch_busy", `Already ${maxSubscribers} boards watching this sidecar.`);
|
|
320
|
+
}
|
|
321
|
+
res.writeHead(200, {
|
|
322
|
+
"content-type": "application/x-ndjson",
|
|
323
|
+
"cache-control": "no-store",
|
|
324
|
+
"x-content-type-options": "nosniff",
|
|
325
|
+
});
|
|
326
|
+
res.socket?.setNoDelay?.(true);
|
|
327
|
+
attach(res);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function close() {
|
|
331
|
+
for (const res of [...subscribers]) drop(res);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return {
|
|
335
|
+
begin,
|
|
336
|
+
record,
|
|
337
|
+
report,
|
|
338
|
+
setWindow,
|
|
339
|
+
window: () => usageWindow,
|
|
340
|
+
serve,
|
|
341
|
+
attach,
|
|
342
|
+
close,
|
|
343
|
+
subscriberCount: () => subscribers.size,
|
|
344
|
+
};
|
|
345
|
+
}
|