passcontrol 1.4.0 → 1.5.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.
@@ -14,7 +14,7 @@
14
14
  // older budget that might read as current.
15
15
  import fs from "node:fs";
16
16
  import path from "node:path";
17
- import { statusLine } from "./budget-format.mjs";
17
+ import { limitReached, panelRows, statusLine } from "./budget-format.mjs";
18
18
 
19
19
  export const STATUSLINE_TTL_MS = 20_000;
20
20
  const TIMEOUT_MS = 1_500;
@@ -87,3 +87,127 @@ export async function statuslineText({
87
87
  clearTimeout(timer);
88
88
  }
89
89
  }
90
+
91
+ // The session id Claude Code declares on every call, held to what the gateway
92
+ // accepts as declared (lib/client-lineage.ts), so nothing else is ever sent on.
93
+ const DECLARED_SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
94
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
95
+
96
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
97
+
98
+ /**
99
+ * Where Claude Code sends its calls, from its own ANTHROPIC_BASE_URL (the plugin's
100
+ * hook inherits Claude Code's environment): `{ port }` for a sidecar on this
101
+ * machine, `{ remote: host }` for anything else, null when it is not set. A
102
+ * dedicated Claude Code agent's sidecar is not on the default port, and asking the
103
+ * default one would report a different agent.
104
+ */
105
+ export function sidecarFromBaseUrl(baseUrl) {
106
+ if (typeof baseUrl !== "string" || !baseUrl.trim()) return null;
107
+ let url;
108
+ try {
109
+ url = new URL(baseUrl);
110
+ } catch {
111
+ return null;
112
+ }
113
+ if (!LOOPBACK.has(url.hostname)) return { remote: url.host };
114
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
115
+ return Number.isInteger(port) && port > 0 && port < 65536 ? { port } : null;
116
+ }
117
+
118
+ /** The panel for a session whose calls do not pass through a PassControl sidecar. */
119
+ export function notInPathText(remoteHost) {
120
+ return [
121
+ "PassControl · not in the path of this session",
122
+ "",
123
+ ` Claude Code sends its calls to ${remoteHost}, not through a PassControl`,
124
+ " sidecar, so PassControl neither sees nor limits them. To route them:",
125
+ " passcontrol configure claude-code --write",
126
+ ].join("\n");
127
+ }
128
+
129
+ const row = ([label, value]) => ` ${label.padEnd(11)} ${value}`;
130
+
131
+ /**
132
+ * `passcontrol statusline --panel`: what `/passcontrol` shows in Claude Code (F3).
133
+ * The plugin's hook prints it without calling the model, so it answers while the
134
+ * gateway refuses every call. Always asks: never answered from the status line's
135
+ * cache, where a "fine" from before the stop could still sit. Never throws.
136
+ */
137
+ export async function statusPanelText({
138
+ port,
139
+ host = "127.0.0.1",
140
+ gateway,
141
+ session = null,
142
+ fetch: fetchImpl = globalThis.fetch,
143
+ timeoutMs = TIMEOUT_MS,
144
+ }) {
145
+ const dashboard = `${String(gateway ?? "").replace(/\/+$/, "")}/dashboard`;
146
+ const headers = { accept: "application/json" };
147
+ if (typeof session === "string" && DECLARED_SESSION.test(session)) headers["x-claude-code-session-id"] = session;
148
+
149
+ const controller = new AbortController();
150
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
151
+ try {
152
+ let response;
153
+ try {
154
+ response = await fetchImpl(`http://${host}:${port}/api/v1/self`, { headers, signal: controller.signal });
155
+ } catch {
156
+ if (controller.signal.aborted) return "PassControl · no answer from the sidecar\n\n It did not answer in time. Try again in a moment.";
157
+ return [
158
+ `PassControl · sidecar not running on port ${port}`,
159
+ "",
160
+ " If Claude Code is set to send its calls through PassControl, they fail",
161
+ " until it runs. Start it with: passcontrol sidecar",
162
+ ].join("\n");
163
+ }
164
+ if (response.status === 403) {
165
+ const body = await response.json().catch(() => ({}));
166
+ if (typeof body?.message === "string" && body.message.includes("stopped this session")) {
167
+ return [
168
+ "PassControl · REFUSING CALLS from this session",
169
+ "",
170
+ " The agent's owner stopped this session, so nothing you type here",
171
+ " reaches the model. Other sessions of this agent are not affected,",
172
+ " and a new session is not stopped. The owner can resume this one",
173
+ " from the agent's Sessions view.",
174
+ "",
175
+ row(["Dashboard", dashboard]),
176
+ ].join("\n");
177
+ }
178
+ // The gateway's one opaque answer for both: it does not say which fired.
179
+ return [
180
+ "PassControl · REFUSING CALLS",
181
+ "",
182
+ " The gateway is refusing this agent's calls: its owner suspended it, or",
183
+ " the kill switch is on. Nothing you type here reaches the model until",
184
+ " it is lifted.",
185
+ "",
186
+ row(["Dashboard", dashboard]),
187
+ ].join("\n");
188
+ }
189
+ if (response.status === 429) return "PassControl · asked too often\n\n Try again in a minute.";
190
+ if (!response.ok) return `PassControl · unavailable (HTTP ${response.status})`;
191
+ let self;
192
+ try {
193
+ self = await response.json();
194
+ } catch {
195
+ return "PassControl · unreadable answer";
196
+ }
197
+ if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
198
+ const agentId = typeof self.agent_id === "string" && UUID.test(self.agent_id) ? self.agent_id : null;
199
+ const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : ""}`;
200
+ return [
201
+ title,
202
+ "",
203
+ ...panelRows(self).map(row),
204
+ row(["Calls", `through the sidecar on :${port}`]),
205
+ "",
206
+ row(["Agent page", agentId ? `${dashboard}/agents/${agentId}` : dashboard]),
207
+ ].join("\n");
208
+ } catch {
209
+ return "PassControl · unavailable";
210
+ } finally {
211
+ clearTimeout(timer);
212
+ }
213
+ }
@@ -53,7 +53,11 @@ export function createVisaClient({
53
53
  });
54
54
 
55
55
  if (!response.ok) {
56
- throw new Error(formatChallengeError(response.status, await response.text()));
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,275 @@
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
+ /** The gateway's budget read, which the board and the status line poll: not a call. */
86
+ export function isBudgetRead(path) {
87
+ return /^\/api\/v1\/self(\?|$)/.test(String(path ?? ""));
88
+ }
89
+
90
+ /** Reads at most `limit` bytes of a (cloned) body, then cancels it. Never throws. */
91
+ export async function peekText(body, limit = REFUSAL_PEEK_BYTES) {
92
+ if (!body) return "";
93
+ const reader = body.getReader();
94
+ const chunks = [];
95
+ let size = 0;
96
+ try {
97
+ while (size < limit) {
98
+ const { done, value } = await reader.read();
99
+ if (done) break;
100
+ chunks.push(value);
101
+ size += value.length;
102
+ }
103
+ } catch {
104
+ // An aborted body has no code to read.
105
+ } finally {
106
+ reader.cancel().catch(() => {});
107
+ }
108
+ return Buffer.concat(chunks.map((c) => Buffer.from(c))).subarray(0, limit).toString("utf8");
109
+ }
110
+
111
+ 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})$/;
112
+ const LOOPBACK_NAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
113
+
114
+ function hostIsThisListener(hostHeader, port) {
115
+ if (typeof hostHeader !== "string") return false;
116
+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(hostHeader.trim().toLowerCase());
117
+ return Boolean(match && LOOPBACK_NAMES.has(match[1]) && Number(match[2]) === port);
118
+ }
119
+
120
+ function answer(res, status, error, message) {
121
+ const body = JSON.stringify({ error, message });
122
+ res.writeHead(status, {
123
+ "content-type": "application/json",
124
+ "content-length": Buffer.byteLength(body),
125
+ "cache-control": "no-store",
126
+ "x-content-type-options": "nosniff",
127
+ connection: "close",
128
+ });
129
+ res.end(body);
130
+ }
131
+
132
+ /**
133
+ * @param {{ runId: string, capacity?: number, maxSubscribers?: number, enabled?: boolean, now?: () => number }} options
134
+ */
135
+ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, enabled = true, now = () => Date.now() }) {
136
+ const ring = [];
137
+ const subscribers = new Set();
138
+ let seq = 0;
139
+
140
+ function send(res, line) {
141
+ try {
142
+ // A subscriber whose socket is backed up is dropped: buffering for it would
143
+ // grow without bound, and waiting for it would slow calls.
144
+ res.write(line);
145
+ if ((res.writableLength ?? 0) > MAX_BUFFERED_BYTES) drop(res);
146
+ } catch {
147
+ drop(res);
148
+ }
149
+ }
150
+
151
+ function drop(res) {
152
+ subscribers.delete(res);
153
+ try {
154
+ res.destroy();
155
+ } catch {
156
+ // Already gone.
157
+ }
158
+ }
159
+
160
+ function broadcast(event) {
161
+ if (subscribers.size === 0) return;
162
+ let line;
163
+ try {
164
+ line = `${JSON.stringify(event)}\n`;
165
+ } catch {
166
+ return;
167
+ }
168
+ for (const res of [...subscribers]) send(res, line);
169
+ }
170
+
171
+ function remember(record) {
172
+ ring.push(record);
173
+ if (ring.length > capacity) ring.splice(0, ring.length - capacity);
174
+ }
175
+
176
+ /**
177
+ * A call the board will show. `settle` announces it once its outcome is known;
178
+ * `finish` records the total time when the response is done. Either order works:
179
+ * a call that finishes before it is settled is announced with its total.
180
+ * Never throws.
181
+ */
182
+ function begin({ startedAt = now(), lineage = null, model = null, provider = null } = {}) {
183
+ const record = {
184
+ type: "call",
185
+ seq: ++seq,
186
+ at: startedAt,
187
+ ses: held(DECLARED, lineage?.session),
188
+ agent: held(DECLARED, lineage?.agent),
189
+ parent: held(DECLARED, lineage?.parent),
190
+ model: held(MODEL, model),
191
+ provider: held(PROVIDER, provider),
192
+ outcome: null,
193
+ code: null,
194
+ status: null,
195
+ ttfb: null,
196
+ ms: null,
197
+ };
198
+ let announced = false;
199
+ return {
200
+ settle({ outcome, code = null, status, ttfb = null }) {
201
+ try {
202
+ if (announced) return;
203
+ announced = true;
204
+ record.outcome = ["boarded", "denied", "error"].includes(outcome) ? outcome : "error";
205
+ record.code = held(CODE, code);
206
+ record.status = Number.isInteger(status) ? status : null;
207
+ record.ttfb = Math.max(0, Math.round(Number.isFinite(ttfb) ? ttfb : now() - record.at));
208
+ remember(record);
209
+ broadcast(record);
210
+ } catch {
211
+ // The feed is never the reason a call fails.
212
+ }
213
+ },
214
+ finish() {
215
+ try {
216
+ if (record.ms !== null) return;
217
+ record.ms = Math.max(0, Math.round(now() - record.at));
218
+ if (announced) broadcast({ type: "end", seq: record.seq, ms: record.ms });
219
+ } catch {
220
+ // As above.
221
+ }
222
+ },
223
+ };
224
+ }
225
+
226
+ /** A call whose outcome and end are known at once (refusals, upstream failures). */
227
+ function record({ outcome, code = null, status, lineage = null, model = null, provider = null, startedAt = now() }) {
228
+ const call = begin({ startedAt, lineage, model, provider });
229
+ call.finish();
230
+ call.settle({ outcome, code, status, ttfb: now() - startedAt });
231
+ }
232
+
233
+ /** Adds a subscriber, replaying the ring. Exposed for tests; `serve` is the way in. */
234
+ function attach(res) {
235
+ subscribers.add(res);
236
+ send(res, `${JSON.stringify({ type: "hello", feed: "passcontrol-watch", v: 1, run: runId })}\n`);
237
+ for (const r of ring) if (subscribers.has(res)) send(res, `${JSON.stringify(r)}\n`);
238
+ try {
239
+ res.on("close", () => subscribers.delete(res));
240
+ } catch {
241
+ subscribers.delete(res);
242
+ }
243
+ }
244
+
245
+ /** Answers a request for `/_passcontrol/...`. `port` is the listener's bound port. */
246
+ function serve(req, res, { port }) {
247
+ req.resume();
248
+ const pathname = String(req.url ?? "").split("?")[0];
249
+ if (pathname !== WATCH_PATH) return answer(res, 404, "not_found", "Nothing is served here.");
250
+ if (!enabled) {
251
+ return answer(res, 404, "watch_off", "This sidecar is bound off loopback, so it serves no watch feed.");
252
+ }
253
+ if (req.method !== "GET") return answer(res, 405, "method_not_allowed", "The watch feed answers GET only.");
254
+ const loopbackPeer = LOOPBACK_PEER.test(String(req.socket?.remoteAddress ?? ""));
255
+ if (!loopbackPeer || req.headers.origin !== undefined || !hostIsThisListener(req.headers.host, port)) {
256
+ return answer(res, 403, "watch_refused", "The watch feed is for `passcontrol watch` on this machine only.");
257
+ }
258
+ if (subscribers.size >= maxSubscribers) {
259
+ return answer(res, 503, "watch_busy", `Already ${maxSubscribers} boards watching this sidecar.`);
260
+ }
261
+ res.writeHead(200, {
262
+ "content-type": "application/x-ndjson",
263
+ "cache-control": "no-store",
264
+ "x-content-type-options": "nosniff",
265
+ });
266
+ res.socket?.setNoDelay?.(true);
267
+ attach(res);
268
+ }
269
+
270
+ function close() {
271
+ for (const res of [...subscribers]) drop(res);
272
+ }
273
+
274
+ return { begin, record, serve, attach, close, subscriberCount: () => subscribers.size };
275
+ }