passcontrol 1.3.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.
- package/LICENSE +3 -1
- package/README.md +10 -1
- package/bin/passcontrol.mjs +455 -10
- package/cli/budget-format.mjs +113 -0
- package/cli/claude-code.mjs +80 -16
- package/cli/config.mjs +36 -2
- package/cli/declared-session.mjs +61 -0
- package/cli/delegation.d.mts +60 -0
- package/cli/delegation.mjs +192 -0
- package/cli/journal.mjs +84 -0
- package/cli/mcp/README.md +4 -1
- package/cli/mcp/gateway.mjs +13 -0
- package/cli/mcp/server.mjs +27 -0
- package/cli/menu.mjs +7 -0
- package/cli/profiles.mjs +92 -0
- package/cli/protocols.d.mts +2 -0
- package/cli/protocols.mjs +17 -1
- package/cli/sidecar.mjs +194 -20
- package/cli/statusline.mjs +213 -0
- package/cli/verify.mjs +215 -5
- package/cli/visa-client.mjs +5 -1
- package/cli/watch-feed.mjs +275 -0
- package/cli/watch.mjs +601 -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 +115 -0
- package/sdk/verify.js +219 -1
package/cli/sidecar.mjs
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import http from "node:http";
|
|
2
3
|
import net from "node:net";
|
|
3
4
|
import { Readable } from "node:stream";
|
|
4
5
|
import { bareGatewayOrigin, fail, ok, step, warn } from "./config.mjs";
|
|
5
6
|
import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./proxy-policy.mjs";
|
|
6
7
|
import { createVisaClient } from "./visa-client.mjs";
|
|
8
|
+
import { declaredLineage, declaredSession } from "./declared-session.mjs";
|
|
9
|
+
import { defaultJournalDir, openJournal } from "./journal.mjs";
|
|
10
|
+
import { createWatchFeed, isBudgetRead, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
|
|
7
11
|
|
|
8
12
|
// Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
|
|
9
13
|
// and friends only appear once something is used as a FORWARD proxy, which is
|
|
@@ -107,6 +111,15 @@ export function createSidecar({
|
|
|
107
111
|
refreshSkewSeconds = 30,
|
|
108
112
|
allowConnectHosts = [],
|
|
109
113
|
onRefusal = (verdict) => warn(`${verdict.code}: ${verdict.message} → ${verdict.help}`),
|
|
114
|
+
// This run's id: stamped on every forwarded request as `x-passcontrol-run`, the
|
|
115
|
+
// fallback session for a client that declares none (lib/client-lineage.ts).
|
|
116
|
+
runId = randomUUID(),
|
|
117
|
+
// cli/journal.mjs, or null for `--no-journal`.
|
|
118
|
+
journal = null,
|
|
119
|
+
// `passcontrol watch`'s feed (cli/watch-feed.mjs). Off when bound off loopback.
|
|
120
|
+
watchFeed = isLoopbackBindHost(host),
|
|
121
|
+
watchCapacity = 200,
|
|
122
|
+
watchMaxSubscribers = 8,
|
|
110
123
|
}) {
|
|
111
124
|
// The upstream URL below is built from this, not from the argument: the
|
|
112
125
|
// sidecar forwards a bearer visa on every proxied request, so its destination
|
|
@@ -123,6 +136,13 @@ export function createSidecar({
|
|
|
123
136
|
|
|
124
137
|
// Used only to print the governed base URL back in a refusal. Read from the
|
|
125
138
|
// live listener when there is one so the advice names the port actually bound.
|
|
139
|
+
const feed = createWatchFeed({ runId, capacity: watchCapacity, maxSubscribers: watchMaxSubscribers, enabled: watchFeed });
|
|
140
|
+
const lineageOf = (headers) =>
|
|
141
|
+
declaredLineage((name) => {
|
|
142
|
+
const v = headers?.[name];
|
|
143
|
+
return Array.isArray(v) ? v[0] : v;
|
|
144
|
+
}, runId);
|
|
145
|
+
|
|
126
146
|
const localBaseUrl = () => {
|
|
127
147
|
const address = server?.listening ? server.address() : null;
|
|
128
148
|
return `http://${host}:${address?.port ?? port}`;
|
|
@@ -143,6 +163,8 @@ export function createSidecar({
|
|
|
143
163
|
if (!isStripped(k) && typeof v === "string") headers[k] = v;
|
|
144
164
|
}
|
|
145
165
|
headers["authorization"] = `Bearer ${visa}`;
|
|
166
|
+
// Set after the copy, so a client cannot name the run: only the sidecar can.
|
|
167
|
+
headers["x-passcontrol-run"] = runId;
|
|
146
168
|
headers["x-passcontrol-proof"] = visas.createProof(visa, req.method, new URL(path, origin));
|
|
147
169
|
headers["accept-encoding"] = "identity";
|
|
148
170
|
return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
|
|
@@ -155,40 +177,107 @@ export function createSidecar({
|
|
|
155
177
|
// URL — codeload for an archive download — passes through untouched.
|
|
156
178
|
const toLocal = (value) => value.split(`${origin}/api/v1/`).join(`${localBaseUrl()}/api/v1/`);
|
|
157
179
|
|
|
158
|
-
|
|
180
|
+
// `watch` is the board's handle on this call ({ call, startedAt }), or null for one
|
|
181
|
+
// the board does not show. Its outcome is read from the status and, for an error,
|
|
182
|
+
// from a capped peek at a CLONE of the body, so the client's bytes are untouched
|
|
183
|
+
// and nothing here waits on the peek.
|
|
184
|
+
function writeResponse(res, upstream, reqHeaders, watch = null) {
|
|
185
|
+
// At the headers, not at the end of the body: a streamed call whose client
|
|
186
|
+
// disconnects mid-stream still produced a receipt, and the user's record of
|
|
187
|
+
// it must not depend on how long they kept reading. With the session the call
|
|
188
|
+
// declared, read as the gateway reads it, so a seal is checked against its own.
|
|
189
|
+
journal?.record(
|
|
190
|
+
upstream.headers.get("x-passcontrol-receipt-id"),
|
|
191
|
+
upstream.status,
|
|
192
|
+
declaredSession((name) => {
|
|
193
|
+
const v = reqHeaders?.[name];
|
|
194
|
+
return Array.isArray(v) ? v[0] : v;
|
|
195
|
+
}, runId)
|
|
196
|
+
);
|
|
159
197
|
const outHeaders = {};
|
|
160
198
|
upstream.headers.forEach((v, k) => {
|
|
161
199
|
const name = k.toLowerCase();
|
|
162
200
|
if (STRIP_RES.has(name)) return;
|
|
163
201
|
outHeaders[k] = name === "link" || name === "location" ? toLocal(v) : v;
|
|
164
202
|
});
|
|
203
|
+
let peek = null;
|
|
204
|
+
if (watch) {
|
|
205
|
+
const ttfb = Date.now() - watch.startedAt;
|
|
206
|
+
const status = upstream.status;
|
|
207
|
+
res.on("close", () => watch.call.finish());
|
|
208
|
+
if (status < 400) watch.call.settle({ outcome: "boarded", status, ttfb });
|
|
209
|
+
else if (!upstream.body) watch.call.settle({ outcome: "error", status, ttfb });
|
|
210
|
+
else {
|
|
211
|
+
try {
|
|
212
|
+
peek = upstream.clone().body;
|
|
213
|
+
} catch {
|
|
214
|
+
watch.call.settle({ outcome: "error", status, ttfb });
|
|
215
|
+
}
|
|
216
|
+
if (peek) {
|
|
217
|
+
peekText(peek).then((text) => {
|
|
218
|
+
const code = refusalCode(text);
|
|
219
|
+
watch.call.settle({ outcome: code ? "denied" : "error", code, status, ttfb });
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
165
224
|
res.writeHead(upstream.status, outHeaders);
|
|
166
225
|
if (upstream.body) Readable.fromWeb(upstream.body).pipe(res);
|
|
167
226
|
else res.end();
|
|
168
227
|
}
|
|
169
228
|
|
|
229
|
+
/** Begins the board's record of a forwarded call, unless it is the budget read. */
|
|
230
|
+
function watchCall(req, path, body, startedAt) {
|
|
231
|
+
if (isBudgetRead(path)) return null;
|
|
232
|
+
try {
|
|
233
|
+
return { startedAt, call: feed.begin({ startedAt, lineage: lineageOf(req.headers), model: requestModel(body), provider: providerOf(path) }) };
|
|
234
|
+
} catch {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** A forwarded call that failed before the gateway answered: shown, then answered 502. */
|
|
240
|
+
function upstreamFailed(res, watch, req, path, e) {
|
|
241
|
+
if (!res.headersSent) {
|
|
242
|
+
if (watch) {
|
|
243
|
+
watch.call.settle({ outcome: "error", code: "sidecar_upstream_error", status: 502 });
|
|
244
|
+
watch.call.finish();
|
|
245
|
+
} else if (!isBudgetRead(path)) {
|
|
246
|
+
feed.record({ outcome: "error", code: "sidecar_upstream_error", status: 502, lineage: lineageOf(req.headers), provider: providerOf(path) });
|
|
247
|
+
}
|
|
248
|
+
res.writeHead(502, { "content-type": "application/json" });
|
|
249
|
+
res.end(JSON.stringify({ error: "sidecar_upstream_error", message: e.message }));
|
|
250
|
+
} else {
|
|
251
|
+
res.end();
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
170
255
|
const server = http.createServer(async (req, res) => {
|
|
256
|
+
// The sidecar's own paths: answered here, never forwarded with a visa.
|
|
257
|
+
if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
|
|
258
|
+
feed.serve(req, res, { port: server.address()?.port });
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const startedAt = Date.now();
|
|
171
262
|
// Judge the destination before reading the body: a refused host should not
|
|
172
263
|
// get to make the sidecar buffer megabytes on its way to a 403.
|
|
173
264
|
const verdict = classifyProxyRequest({ url: req.url, gatewayOrigin: origin, localBaseUrl: localBaseUrl() });
|
|
174
265
|
if (!verdict.allow) {
|
|
175
266
|
req.resume();
|
|
176
267
|
onRefusal(verdict);
|
|
268
|
+
feed.record({ outcome: "denied", code: verdict.code, status: verdict.status, lineage: lineageOf(req.headers), startedAt });
|
|
177
269
|
writeRefusal(res, verdict);
|
|
178
270
|
return;
|
|
179
271
|
}
|
|
180
272
|
|
|
273
|
+
let watch = null;
|
|
181
274
|
try {
|
|
182
275
|
const body = await readBody(req);
|
|
276
|
+
watch = watchCall(req, verdict.path, body, startedAt);
|
|
183
277
|
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, body, visa));
|
|
184
|
-
writeResponse(res, upstream);
|
|
278
|
+
writeResponse(res, upstream, req.headers, watch);
|
|
185
279
|
} catch (e) {
|
|
186
|
-
|
|
187
|
-
res.writeHead(502, { "content-type": "application/json" });
|
|
188
|
-
res.end(JSON.stringify({ error: "sidecar_upstream_error", message: e.message }));
|
|
189
|
-
} else {
|
|
190
|
-
res.end();
|
|
191
|
-
}
|
|
280
|
+
upstreamFailed(res, watch, req, verdict.path, e);
|
|
192
281
|
}
|
|
193
282
|
});
|
|
194
283
|
|
|
@@ -217,24 +306,24 @@ export function createSidecar({
|
|
|
217
306
|
const probe = url.pathname === "/";
|
|
218
307
|
const mapped = `/api/v1/local${probe ? "/api/version" : url.pathname}${probe ? "" : url.search}`;
|
|
219
308
|
const method = probe ? "GET" : req.method;
|
|
309
|
+
const startedAt = Date.now();
|
|
310
|
+
let watch = null;
|
|
220
311
|
try {
|
|
221
312
|
const body = probe ? null : await readBody(req);
|
|
222
313
|
if (probe) req.resume();
|
|
314
|
+
watch = watchCall(req, mapped, body, startedAt);
|
|
223
315
|
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream({ method, headers: req.headers }, mapped, body, visa));
|
|
224
316
|
if (req.method === "HEAD") {
|
|
317
|
+
watch?.call.settle({ outcome: upstream.status < 400 ? "boarded" : "error", status: upstream.status, ttfb: Date.now() - startedAt });
|
|
318
|
+
watch?.call.finish();
|
|
225
319
|
res.writeHead(upstream.status);
|
|
226
320
|
res.end();
|
|
227
321
|
await upstream.body?.cancel().catch(() => {});
|
|
228
322
|
return;
|
|
229
323
|
}
|
|
230
|
-
writeResponse(res, upstream);
|
|
324
|
+
writeResponse(res, upstream, req.headers, watch);
|
|
231
325
|
} catch (e) {
|
|
232
|
-
|
|
233
|
-
res.writeHead(502, { "content-type": "application/json" });
|
|
234
|
-
res.end(JSON.stringify({ error: "sidecar_upstream_error", message: e.message }));
|
|
235
|
-
} else {
|
|
236
|
-
res.end();
|
|
237
|
-
}
|
|
326
|
+
upstreamFailed(res, watch, req, mapped, e);
|
|
238
327
|
}
|
|
239
328
|
});
|
|
240
329
|
|
|
@@ -253,6 +342,7 @@ export function createSidecar({
|
|
|
253
342
|
});
|
|
254
343
|
if (!verdict.allow) {
|
|
255
344
|
onRefusal(verdict);
|
|
345
|
+
feed.record({ outcome: "denied", code: verdict.code, status: verdict.status, lineage: lineageOf(req.headers) });
|
|
256
346
|
writeConnectRefusal(clientSocket, verdict);
|
|
257
347
|
return;
|
|
258
348
|
}
|
|
@@ -270,6 +360,7 @@ export function createSidecar({
|
|
|
270
360
|
clientSocket.destroy();
|
|
271
361
|
return;
|
|
272
362
|
}
|
|
363
|
+
feed.record({ outcome: "error", code: "tunnel_unreachable", status: 502, lineage: lineageOf(req.headers) });
|
|
273
364
|
writeConnectRefusal(clientSocket, {
|
|
274
365
|
status: 502,
|
|
275
366
|
code: "tunnel_unreachable",
|
|
@@ -280,7 +371,7 @@ export function createSidecar({
|
|
|
280
371
|
clientSocket.on("close", () => upstream.destroy());
|
|
281
372
|
});
|
|
282
373
|
|
|
283
|
-
return { server, ollamaServer, getVisa: visas.getVisa };
|
|
374
|
+
return { server, ollamaServer, getVisa: visas.getVisa, runId, feed };
|
|
284
375
|
}
|
|
285
376
|
|
|
286
377
|
/**
|
|
@@ -303,7 +394,17 @@ export function assertBindHost(host, allowNonLoopback = false) {
|
|
|
303
394
|
export function startSidecar(opts) {
|
|
304
395
|
const { gateway, port = 8788, host = "127.0.0.1", allowNonLoopback = false, allowConnectHosts = [], ollamaPort = null } = opts;
|
|
305
396
|
assertBindHost(host, allowNonLoopback);
|
|
306
|
-
const
|
|
397
|
+
const runId = randomUUID();
|
|
398
|
+
// On unless the operator said --no-journal (D3). See cli/journal.mjs.
|
|
399
|
+
const journal = opts.noJournal
|
|
400
|
+
? null
|
|
401
|
+
: openJournal({
|
|
402
|
+
dir: opts.journalDir ?? defaultJournalDir(),
|
|
403
|
+
runId,
|
|
404
|
+
onError: (e) =>
|
|
405
|
+
warn(`journal: could not write ${journal.path} (${e.message}). Calls are unaffected; this run is no longer being recorded.`),
|
|
406
|
+
});
|
|
407
|
+
const { server, ollamaServer, getVisa, feed } = createSidecar({ ...opts, runId, journal });
|
|
307
408
|
if (ollamaPort != null) {
|
|
308
409
|
ollamaServer.listen(ollamaPort, host, () => {
|
|
309
410
|
step(`Ollama API (local models) on http://${host}:${ollamaPort}: set OLLAMA_HOST=${host}:${ollamaPort}`);
|
|
@@ -314,6 +415,16 @@ export function startSidecar(opts) {
|
|
|
314
415
|
step(`Listening on http://${host}:${port}`);
|
|
315
416
|
step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
|
|
316
417
|
step("API key = anything (ignored). Visa is minted + refreshed automatically.");
|
|
418
|
+
step(
|
|
419
|
+
journal
|
|
420
|
+
? `Journal: ${journal.path} (receipt ids, times, statuses and declared sessions only; --no-journal turns it off)`
|
|
421
|
+
: "Journal: off (--no-journal). Session seals cannot be checked against this run."
|
|
422
|
+
);
|
|
423
|
+
step(
|
|
424
|
+
isLoopbackBindHost(host)
|
|
425
|
+
? `Watch live: passcontrol watch --port ${port} (this machine only; held in memory, never written)`
|
|
426
|
+
: "Watch: off, because this sidecar is bound off loopback."
|
|
427
|
+
);
|
|
317
428
|
// Said at startup rather than only in a refusal, because the whole point of
|
|
318
429
|
// HTTPS_PROXY is that nobody reads the docs first.
|
|
319
430
|
step("HTTPS_PROXY: CONNECT to a provider is refused, not tunnelled — PassControl cannot");
|
|
@@ -326,9 +437,72 @@ export function startSidecar(opts) {
|
|
|
326
437
|
? `CONNECT allowlist: ${allowConnectHosts.join(", ")} (provider hosts are never eligible).\n`
|
|
327
438
|
: "CONNECT allowlist: none — only the gateway.\n"
|
|
328
439
|
);
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
440
|
+
warmVisa({
|
|
441
|
+
getVisa,
|
|
442
|
+
gateway,
|
|
443
|
+
// Closed rather than process.exit(): stderr to a pipe is written
|
|
444
|
+
// asynchronously, and exit() can drop the reason this just printed.
|
|
445
|
+
onRefused: () => {
|
|
446
|
+
process.exitCode = 1;
|
|
447
|
+
// A watching board holds its connection open, and close() waits for it.
|
|
448
|
+
feed.close();
|
|
449
|
+
server.close();
|
|
450
|
+
if (ollamaServer.listening) ollamaServer.close();
|
|
451
|
+
setTimeout(() => process.exit(1), 1000).unref();
|
|
452
|
+
},
|
|
453
|
+
});
|
|
332
454
|
});
|
|
333
455
|
return server;
|
|
334
456
|
}
|
|
457
|
+
|
|
458
|
+
/** Waits between attempts to mint the first visa: backoff, then every 30 seconds. */
|
|
459
|
+
export const WARM_RETRY_MS = [1000, 2000, 4000, 8000, 15000, 30000];
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* A gateway that answered and refused the passport: any 4xx except 408 and 429,
|
|
463
|
+
* which mean "not now". No status (no connection) and 5xx mean "not up yet".
|
|
464
|
+
*/
|
|
465
|
+
export function isPassportRefusal(error) {
|
|
466
|
+
const status = error?.status;
|
|
467
|
+
return typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* The first visa (sprint T2). A sidecar is often started before its gateway, by
|
|
472
|
+
* `passcontrol start` or a login script, so a gateway that is not answering is
|
|
473
|
+
* waited for, on screen; a refusal ends the process, because retrying it can only
|
|
474
|
+
* fail again and a sidecar that cannot mint must not look like it is running.
|
|
475
|
+
* Resolves true once warmed, false after a refusal (onRefused has run).
|
|
476
|
+
*/
|
|
477
|
+
export async function warmVisa({
|
|
478
|
+
getVisa,
|
|
479
|
+
gateway,
|
|
480
|
+
onRefused,
|
|
481
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
482
|
+
log = { ok, warn, fail },
|
|
483
|
+
delays = WARM_RETRY_MS,
|
|
484
|
+
}) {
|
|
485
|
+
for (let attempt = 0; ; attempt++) {
|
|
486
|
+
try {
|
|
487
|
+
await getVisa();
|
|
488
|
+
log.ok(attempt === 0 ? "visa warmed" : `visa warmed: ${gateway} is answering now`);
|
|
489
|
+
return true;
|
|
490
|
+
} catch (error) {
|
|
491
|
+
if (isPassportRefusal(error)) {
|
|
492
|
+
log.fail(`could not mint a visa: ${error.message}`);
|
|
493
|
+
onRefused(error);
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
const delay = delays[Math.min(attempt, delays.length - 1)];
|
|
497
|
+
if (attempt === 0) {
|
|
498
|
+
log.warn(
|
|
499
|
+
`${gateway} is not answering yet (${error.message}). Waiting for it, and retrying on its own; ` +
|
|
500
|
+
"calls made before it answers get a 502."
|
|
501
|
+
);
|
|
502
|
+
} else if (attempt % 10 === 0) {
|
|
503
|
+
log.warn(`still waiting for ${gateway} (${error.message})`);
|
|
504
|
+
}
|
|
505
|
+
await sleep(delay);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// `passcontrol statusline`: the agent's budget as one line in Claude Code's status
|
|
2
|
+
// line (1.4.0 candidate 2).
|
|
3
|
+
//
|
|
4
|
+
// Claude Code runs the command after every assistant message, debounced 300ms, and
|
|
5
|
+
// cancels a run still going when the next one starts (code.claude.com/docs/en/statusline,
|
|
6
|
+
// read 2026-10-08). So:
|
|
7
|
+
// * a good answer is cached for TTL_MS and reused, so a busy session asks the
|
|
8
|
+
// gateway a few times a minute rather than every message;
|
|
9
|
+
// * it asks through the running sidecar, which already holds a warm visa: minting
|
|
10
|
+
// a visa per run would spend the passport's challenge allowance (20 a window),
|
|
11
|
+
// the same allowance the sidecar refreshes from;
|
|
12
|
+
// * it never throws. Every outcome is one line, and the caller exits 0.
|
|
13
|
+
// Only a good answer is cached. A failure is shown as the failure, never as an
|
|
14
|
+
// older budget that might read as current.
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { limitReached, panelRows, statusLine } from "./budget-format.mjs";
|
|
18
|
+
|
|
19
|
+
export const STATUSLINE_TTL_MS = 20_000;
|
|
20
|
+
const TIMEOUT_MS = 1_500;
|
|
21
|
+
|
|
22
|
+
function readCache(file, nowMs, ttlMs) {
|
|
23
|
+
try {
|
|
24
|
+
const cached = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
25
|
+
if (typeof cached?.line === "string" && typeof cached.at === "number" && nowMs - cached.at >= 0 && nowMs - cached.at < ttlMs) {
|
|
26
|
+
return cached.line;
|
|
27
|
+
}
|
|
28
|
+
} catch {
|
|
29
|
+
// No cache, or an unreadable one: ask.
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function writeCache(file, nowMs, line) {
|
|
35
|
+
try {
|
|
36
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
37
|
+
fs.writeFileSync(file, JSON.stringify({ at: nowMs, line }), { mode: 0o600 });
|
|
38
|
+
fs.chmodSync(file, 0o600);
|
|
39
|
+
} catch {
|
|
40
|
+
// A cache that cannot be written only costs the next run a request.
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The line to print. Never throws. */
|
|
45
|
+
export async function statuslineText({
|
|
46
|
+
port,
|
|
47
|
+
host = "127.0.0.1",
|
|
48
|
+
cacheFile,
|
|
49
|
+
now = () => Date.now(),
|
|
50
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
51
|
+
timeoutMs = TIMEOUT_MS,
|
|
52
|
+
ttlMs = STATUSLINE_TTL_MS,
|
|
53
|
+
}) {
|
|
54
|
+
const cached = readCache(cacheFile, now(), ttlMs);
|
|
55
|
+
if (cached) return cached;
|
|
56
|
+
|
|
57
|
+
const controller = new AbortController();
|
|
58
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
59
|
+
try {
|
|
60
|
+
let response;
|
|
61
|
+
try {
|
|
62
|
+
response = await fetchImpl(`http://${host}:${port}/api/v1/self`, {
|
|
63
|
+
headers: { accept: "application/json" },
|
|
64
|
+
signal: controller.signal,
|
|
65
|
+
});
|
|
66
|
+
} catch {
|
|
67
|
+
return controller.signal.aborted
|
|
68
|
+
? "PassControl · no answer from the sidecar"
|
|
69
|
+
: `PassControl · sidecar not running on port ${port}`;
|
|
70
|
+
}
|
|
71
|
+
// The gateway's opaque refusal covers both a suspended agent and a kill switch.
|
|
72
|
+
if (response.status === 403) return "PassControl · agent stopped";
|
|
73
|
+
if (!response.ok) return `PassControl · unavailable (HTTP ${response.status})`;
|
|
74
|
+
let self;
|
|
75
|
+
try {
|
|
76
|
+
self = await response.json();
|
|
77
|
+
} catch {
|
|
78
|
+
return controller.signal.aborted ? "PassControl · no answer from the sidecar" : "PassControl · unreadable answer";
|
|
79
|
+
}
|
|
80
|
+
if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
|
|
81
|
+
const line = statusLine(self);
|
|
82
|
+
writeCache(cacheFile, now(), line);
|
|
83
|
+
return line;
|
|
84
|
+
} catch {
|
|
85
|
+
return "PassControl · unavailable";
|
|
86
|
+
} finally {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
}
|
|
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
|
+
}
|