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
package/cli/sidecar.mjs
CHANGED
|
@@ -7,7 +7,12 @@ import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./pro
|
|
|
7
7
|
import { createVisaClient } from "./visa-client.mjs";
|
|
8
8
|
import { declaredLineage, declaredSession } from "./declared-session.mjs";
|
|
9
9
|
import { defaultJournalDir, openJournal } from "./journal.mjs";
|
|
10
|
-
import { createWatchFeed,
|
|
10
|
+
import { answer, createWatchFeed, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
|
|
11
|
+
import { createStopGate, HOOK_PATH, SELF_READ_TIMEOUT_MS, selfAnswerState } from "./subscription-gate.mjs";
|
|
12
|
+
import { createToolGate } from "./tool-gate.mjs";
|
|
13
|
+
import { OTLP_LOGS_PATH, readClaudeCodeEvents } from "./otlp-logs.mjs";
|
|
14
|
+
import { CLIENT_EVENTS_PATH, CLIENT_EVENTS_SOURCE, createCallUploader } from "./client-events-upload.mjs";
|
|
15
|
+
import { heldUsageWindow, WINDOW_PATH } from "./usage-window.mjs";
|
|
11
16
|
|
|
12
17
|
// Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
|
|
13
18
|
// and friends only appear once something is used as a FORWARD proxy, which is
|
|
@@ -46,6 +51,30 @@ function isStripped(name) {
|
|
|
46
51
|
const STRIP_RES = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
|
|
47
52
|
|
|
48
53
|
const STATUS_TEXT = { 400: "Bad Request", 403: "Forbidden", 502: "Bad Gateway" };
|
|
54
|
+
// An OTLP log export batches every event of a few seconds; Claude Code's run ~30 KB.
|
|
55
|
+
const OTLP_BODY_LIMIT = 4 * 1024 * 1024;
|
|
56
|
+
// Sessions whose calls this sidecar relays, remembered so their telemetry is not
|
|
57
|
+
// counted a second time. Bounded: the oldest is forgotten first.
|
|
58
|
+
const RELAYED_SESSIONS_MAX = 1000;
|
|
59
|
+
|
|
60
|
+
// Claude Code's hook input carries the tool's input (a whole file for Write), so it
|
|
61
|
+
// is not small; past this it is refused rather than buffered.
|
|
62
|
+
const HOOK_BODY_LIMIT = 1024 * 1024;
|
|
63
|
+
|
|
64
|
+
// How long Claude Code waits for the hook, as configure wrote it into the URL
|
|
65
|
+
// (`?t=600`); null for a hook that does not say (a Phase 1 install).
|
|
66
|
+
function hookTimeoutS(url) {
|
|
67
|
+
const t = new URL(url ?? "/", "http://127.0.0.1").searchParams.get("t");
|
|
68
|
+
return t !== null && /^\d{1,4}$/.test(t) && Number(t) > 0 ? Number(t) : null;
|
|
69
|
+
}
|
|
70
|
+
// The agent's opt-in note (1.6.0): `?note=1` on subscription mode's prompt hook,
|
|
71
|
+
// `?note=only` on API mode's, which only ever adds the note.
|
|
72
|
+
function hookNote(url) {
|
|
73
|
+
const note = new URL(url ?? "/", "http://127.0.0.1").searchParams.get("note");
|
|
74
|
+
return note === "1" ? "subscription" : note === "only" ? "api" : null;
|
|
75
|
+
}
|
|
76
|
+
// A usage window is two numbers and two times.
|
|
77
|
+
const WINDOW_BODY_LIMIT = 4 * 1024;
|
|
49
78
|
|
|
50
79
|
/**
|
|
51
80
|
* A header value is a single line of printable ASCII, always.
|
|
@@ -120,6 +149,9 @@ export function createSidecar({
|
|
|
120
149
|
watchFeed = isLoopbackBindHost(host),
|
|
121
150
|
watchCapacity = 200,
|
|
122
151
|
watchMaxSubscribers = 8,
|
|
152
|
+
// Subscription mode, Phase 1b: upload the calls Claude Code reports to the
|
|
153
|
+
// gateway's agent page (cli/client-events-upload.mjs). `--no-report-calls` turns it off.
|
|
154
|
+
reportCalls = true,
|
|
123
155
|
}) {
|
|
124
156
|
// The upstream URL below is built from this, not from the argument: the
|
|
125
157
|
// sidecar forwards a bearer visa on every proxied request, so its destination
|
|
@@ -143,6 +175,264 @@ export function createSidecar({
|
|
|
143
175
|
return Array.isArray(v) ? v[0] : v;
|
|
144
176
|
}, runId);
|
|
145
177
|
|
|
178
|
+
// Subscription mode's Stop (cli/subscription-gate.mjs): Claude Code's hooks ask
|
|
179
|
+
// here, and the answer comes from the gateway's /api/v1/self, read with this
|
|
180
|
+
// sidecar's visa and the session the hook names.
|
|
181
|
+
async function readSelf(session) {
|
|
182
|
+
// One deadline over the whole read, a visa mint included: past the hook's own
|
|
183
|
+
// timeout the action goes ahead with no warning. A mint cut short here is not
|
|
184
|
+
// aborted (the proxy shares it); it finishes and is cached for the next read.
|
|
185
|
+
const signal = AbortSignal.timeout(SELF_READ_TIMEOUT_MS);
|
|
186
|
+
const deadline = new Promise((_, reject) => {
|
|
187
|
+
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
|
188
|
+
});
|
|
189
|
+
deadline.catch(() => {});
|
|
190
|
+
try {
|
|
191
|
+
const response = await Promise.race([deadline, visas.fetchWithVisa((visa) => {
|
|
192
|
+
// The tool rules ride on every gate read (Phase 2): no call of their own.
|
|
193
|
+
const path = "/api/v1/self?include=tool_rules";
|
|
194
|
+
const headers = {
|
|
195
|
+
accept: "application/json",
|
|
196
|
+
authorization: `Bearer ${visa}`,
|
|
197
|
+
"x-passcontrol-run": runId,
|
|
198
|
+
"x-passcontrol-proof": visas.createProof(visa, "GET", new URL(path, origin)),
|
|
199
|
+
"accept-encoding": "identity",
|
|
200
|
+
};
|
|
201
|
+
if (session) headers["x-claude-code-session-id"] = session;
|
|
202
|
+
return fetch(`${origin}${path}`, { headers, signal });
|
|
203
|
+
})]);
|
|
204
|
+
return await Promise.race([deadline, selfAnswerState(response)]);
|
|
205
|
+
} catch (error) {
|
|
206
|
+
return { state: "unknown", reason: error?.name === "TimeoutError" ? "the gateway did not answer in time" : (error?.message ?? "error") };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const stopGate = createStopGate({ readSelf, dashboardUrl: `${origin}/dashboard` });
|
|
210
|
+
|
|
211
|
+
// Phase 2's `ask_owner` tool rules: the gateway asks the owner (their alert
|
|
212
|
+
// destination is in its Vault) and holds each request a few seconds; this asks
|
|
213
|
+
// again until the owner answers or the tool gate's wait runs out.
|
|
214
|
+
const TOOL_APPROVALS_PATH = "/api/v1/tool-approvals";
|
|
215
|
+
const APPROVAL_REQUEST_TIMEOUT_MS = 25_000;
|
|
216
|
+
const APPROVAL_RETRY_MS = 1_000;
|
|
217
|
+
async function askOwner(input, { session, waitMs }) {
|
|
218
|
+
const deadline = Date.now() + waitMs;
|
|
219
|
+
const body = JSON.stringify({ session: session ?? undefined, tool_name: input.tool_name, tool_input: input.tool_input, cwd: input.cwd });
|
|
220
|
+
while (Date.now() < deadline - 500) {
|
|
221
|
+
let response;
|
|
222
|
+
try {
|
|
223
|
+
response = await visas.fetchWithVisa((visa) => {
|
|
224
|
+
const headers = {
|
|
225
|
+
"content-type": "application/json",
|
|
226
|
+
authorization: `Bearer ${visa}`,
|
|
227
|
+
"x-passcontrol-run": runId,
|
|
228
|
+
"x-passcontrol-proof": visas.createProof(visa, "POST", new URL(TOOL_APPROVALS_PATH, origin)),
|
|
229
|
+
"accept-encoding": "identity",
|
|
230
|
+
};
|
|
231
|
+
if (session) headers["x-claude-code-session-id"] = session;
|
|
232
|
+
return fetch(`${origin}${TOOL_APPROVALS_PATH}`, {
|
|
233
|
+
method: "POST",
|
|
234
|
+
headers,
|
|
235
|
+
body,
|
|
236
|
+
signal: AbortSignal.timeout(Math.min(APPROVAL_REQUEST_TIMEOUT_MS, Math.max(1_000, deadline - Date.now()))),
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
} catch {
|
|
240
|
+
// The gateway did not answer this round: ask again while there is time.
|
|
241
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(APPROVAL_RETRY_MS, Math.max(0, deadline - Date.now()))));
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
const answered = await response.json().catch(() => ({}));
|
|
245
|
+
if (response.status === 409) return { state: "refused" };
|
|
246
|
+
if (response.status === 413) return { state: "too_large" };
|
|
247
|
+
if (response.status !== 200) return { state: "unavailable" };
|
|
248
|
+
if (["approved", "denied", "full"].includes(answered?.state)) return { state: answered.state };
|
|
249
|
+
if (answered?.state !== "pending") return { state: "unavailable" };
|
|
250
|
+
}
|
|
251
|
+
return { state: "timeout" };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// The reported calls go to the gateway as this agent, straight from here: never
|
|
255
|
+
// through this sidecar's own listener, so they are never a call on the board.
|
|
256
|
+
const UPLOAD_TIMEOUT_MS = 10_000;
|
|
257
|
+
async function sendReportedCalls(events) {
|
|
258
|
+
const response = await visas.fetchWithVisa((visa) =>
|
|
259
|
+
fetch(`${origin}${CLIENT_EVENTS_PATH}`, {
|
|
260
|
+
method: "POST",
|
|
261
|
+
headers: {
|
|
262
|
+
"content-type": "application/json",
|
|
263
|
+
authorization: `Bearer ${visa}`,
|
|
264
|
+
"x-passcontrol-run": runId,
|
|
265
|
+
"x-passcontrol-proof": visas.createProof(visa, "POST", new URL(CLIENT_EVENTS_PATH, origin)),
|
|
266
|
+
"accept-encoding": "identity",
|
|
267
|
+
},
|
|
268
|
+
body: JSON.stringify({ source: CLIENT_EVENTS_SOURCE, events }),
|
|
269
|
+
signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
|
|
270
|
+
})
|
|
271
|
+
);
|
|
272
|
+
const body = await response.json().catch(() => ({}));
|
|
273
|
+
return { status: response.status, error: body?.error, retryAfterS: Number(response.headers.get("retry-after")) };
|
|
274
|
+
}
|
|
275
|
+
const uploader = reportCalls ? createCallUploader({ send: sendReportedCalls }) : null;
|
|
276
|
+
// Its decisions reach the agent's page with the reported calls (same opt-out).
|
|
277
|
+
const toolGate = createToolGate({
|
|
278
|
+
askOwner,
|
|
279
|
+
dashboardUrl: `${origin}/dashboard`,
|
|
280
|
+
onDecision: (record) => uploader?.add({ kind: "tool_decision", at: Date.now(), ...record }),
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
const relayedSessions = new Set();
|
|
284
|
+
function rememberRelayed(headers) {
|
|
285
|
+
const session = lineageOf(headers)?.session;
|
|
286
|
+
if (!session || relayedSessions.has(session)) return;
|
|
287
|
+
relayedSessions.add(session);
|
|
288
|
+
if (relayedSessions.size > RELAYED_SESSIONS_MAX) relayedSessions.delete(relayedSessions.values().next().value);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Reads a local caller's body up to `limit`; resolves null when it is over. */
|
|
292
|
+
function readLocalBody(req, limit) {
|
|
293
|
+
return new Promise((resolve) => {
|
|
294
|
+
const chunks = [];
|
|
295
|
+
let size = 0;
|
|
296
|
+
let over = false;
|
|
297
|
+
req.on("data", (c) => {
|
|
298
|
+
size += c.length;
|
|
299
|
+
if (size > limit) over = true;
|
|
300
|
+
else chunks.push(c);
|
|
301
|
+
});
|
|
302
|
+
req.on("end", () => resolve(over ? null : Buffer.concat(chunks)));
|
|
303
|
+
req.on("error", () => resolve(null));
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Subscription mode's telemetry (cli/otlp-logs.mjs): Claude Code's log exporter
|
|
308
|
+
// posts here. Answered as an OTLP collector does, `{}` on success.
|
|
309
|
+
async function serveOtlpLogs(req, res) {
|
|
310
|
+
const port = server.address()?.port;
|
|
311
|
+
if (req.method !== "POST") {
|
|
312
|
+
req.resume();
|
|
313
|
+
return answer(res, 405, "method_not_allowed", "The telemetry endpoint answers POST only.");
|
|
314
|
+
}
|
|
315
|
+
if (!isLocalCaller(req, port)) {
|
|
316
|
+
req.resume();
|
|
317
|
+
return answer(res, 403, "telemetry_refused", "The telemetry endpoint is for Claude Code on this machine only.");
|
|
318
|
+
}
|
|
319
|
+
if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
|
|
320
|
+
req.resume();
|
|
321
|
+
return answer(res, 415, "telemetry_protocol", "Send OTLP as JSON: set OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=http/json.");
|
|
322
|
+
}
|
|
323
|
+
const raw = await readLocalBody(req, OTLP_BODY_LIMIT);
|
|
324
|
+
if (raw === null) return answer(res, 413, "telemetry_too_large", "Log export over 4 MB.");
|
|
325
|
+
let body;
|
|
326
|
+
try {
|
|
327
|
+
body = JSON.parse(raw.toString("utf8"));
|
|
328
|
+
} catch {
|
|
329
|
+
return answer(res, 400, "telemetry_not_json", "The log export is not JSON.");
|
|
330
|
+
}
|
|
331
|
+
for (const event of readClaudeCodeEvents(body)) {
|
|
332
|
+
if (event.session && relayedSessions.has(event.session)) continue;
|
|
333
|
+
feed.report({
|
|
334
|
+
at: event.at ?? Date.now(),
|
|
335
|
+
lineage: { session: event.session, agent: event.agent },
|
|
336
|
+
model: event.model,
|
|
337
|
+
provider: "anthropic",
|
|
338
|
+
outcome: event.kind === "api_request" ? "seen" : "error",
|
|
339
|
+
status: event.status,
|
|
340
|
+
ms: event.durationMs,
|
|
341
|
+
cost: event.costMicros,
|
|
342
|
+
});
|
|
343
|
+
uploader?.add(event);
|
|
344
|
+
}
|
|
345
|
+
res.writeHead(200, { "content-type": "application/json", "content-length": 2, "cache-control": "no-store" });
|
|
346
|
+
res.end("{}");
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Subscription mode's usage window (cli/usage-window.mjs): the status line posts
|
|
350
|
+
// what Claude Code told it; `watch` gets it on the feed, `/passcontrol` asks for it.
|
|
351
|
+
async function serveWindow(req, res) {
|
|
352
|
+
const port = server.address()?.port;
|
|
353
|
+
if (req.method !== "GET" && req.method !== "POST") {
|
|
354
|
+
req.resume();
|
|
355
|
+
return answer(res, 405, "method_not_allowed", "The usage-window endpoint answers GET and POST only.");
|
|
356
|
+
}
|
|
357
|
+
if (!isLocalCaller(req, port)) {
|
|
358
|
+
req.resume();
|
|
359
|
+
return answer(res, 403, "window_refused", "The usage-window endpoint is for this machine only.");
|
|
360
|
+
}
|
|
361
|
+
if (req.method === "GET") {
|
|
362
|
+
req.resume();
|
|
363
|
+
const current = feed.window();
|
|
364
|
+
if (!current) return answer(res, 404, "window_unknown", "No usage window reported yet.");
|
|
365
|
+
const body = JSON.stringify({ fiveHour: current.fiveHour, sevenDay: current.sevenDay, at: current.at });
|
|
366
|
+
res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
|
|
367
|
+
return res.end(body);
|
|
368
|
+
}
|
|
369
|
+
const raw = await readLocalBody(req, WINDOW_BODY_LIMIT);
|
|
370
|
+
let window = null;
|
|
371
|
+
try {
|
|
372
|
+
window = raw === null ? null : heldUsageWindow(JSON.parse(raw.toString("utf8")));
|
|
373
|
+
} catch {
|
|
374
|
+
window = null;
|
|
375
|
+
}
|
|
376
|
+
if (!window) return answer(res, 400, "window_invalid", "Expected a usage window: { fiveHour, sevenDay }.");
|
|
377
|
+
feed.setWindow(window);
|
|
378
|
+
res.writeHead(204, { "cache-control": "no-store" });
|
|
379
|
+
res.end();
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function serveHook(req, res) {
|
|
383
|
+
const port = server.address()?.port;
|
|
384
|
+
if (req.method !== "POST") {
|
|
385
|
+
req.resume();
|
|
386
|
+
return answer(res, 405, "method_not_allowed", "The hook endpoint answers POST only.");
|
|
387
|
+
}
|
|
388
|
+
if (!isLocalCaller(req, port)) {
|
|
389
|
+
req.resume();
|
|
390
|
+
return answer(res, 403, "hook_refused", "The hook endpoint is for Claude Code on this machine only.");
|
|
391
|
+
}
|
|
392
|
+
const chunks = [];
|
|
393
|
+
let size = 0;
|
|
394
|
+
let tooBig = false;
|
|
395
|
+
req.on("data", (c) => {
|
|
396
|
+
size += c.length;
|
|
397
|
+
if (size > HOOK_BODY_LIMIT) tooBig = true;
|
|
398
|
+
else chunks.push(c);
|
|
399
|
+
});
|
|
400
|
+
req.on("end", async () => {
|
|
401
|
+
if (tooBig) return answer(res, 413, "hook_too_large", "Hook input over 1 MB.");
|
|
402
|
+
let input;
|
|
403
|
+
try {
|
|
404
|
+
input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
405
|
+
} catch {
|
|
406
|
+
input = null;
|
|
407
|
+
}
|
|
408
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) {
|
|
409
|
+
return answer(res, 400, "hook_not_json", "Expected Claude Code's hook input, a JSON object.");
|
|
410
|
+
}
|
|
411
|
+
let out;
|
|
412
|
+
try {
|
|
413
|
+
out = await stopGate.decide(input, { note: hookNote(req.url) });
|
|
414
|
+
} catch {
|
|
415
|
+
out = {};
|
|
416
|
+
}
|
|
417
|
+
// A stop ends the turn whatever the tool rules say; otherwise a PreToolUse is
|
|
418
|
+
// the tool gate's, which needs to know how long Claude Code waits for this hook.
|
|
419
|
+
if (out.continue !== false && input.hook_event_name === "PreToolUse") {
|
|
420
|
+
let tool;
|
|
421
|
+
try {
|
|
422
|
+
tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url));
|
|
423
|
+
} catch {
|
|
424
|
+
tool = {};
|
|
425
|
+
}
|
|
426
|
+
const messages = [out.systemMessage, tool.systemMessage].filter(Boolean);
|
|
427
|
+
out = { ...tool, ...(messages.length ? { systemMessage: messages.join("\n") } : {}) };
|
|
428
|
+
}
|
|
429
|
+
const body = JSON.stringify(out);
|
|
430
|
+
res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
|
|
431
|
+
res.end(body);
|
|
432
|
+
});
|
|
433
|
+
req.on("error", () => res.destroy());
|
|
434
|
+
}
|
|
435
|
+
|
|
146
436
|
const localBaseUrl = () => {
|
|
147
437
|
const address = server?.listening ? server.address() : null;
|
|
148
438
|
return `http://${host}:${address?.port ?? port}`;
|
|
@@ -226,9 +516,10 @@ export function createSidecar({
|
|
|
226
516
|
else res.end();
|
|
227
517
|
}
|
|
228
518
|
|
|
229
|
-
/** Begins the board's record of a forwarded call, unless it is the budget read. */
|
|
519
|
+
/** Begins the board's record of a forwarded call, unless it is not a call (the budget read, an upload). */
|
|
230
520
|
function watchCall(req, path, body, startedAt) {
|
|
231
|
-
if (
|
|
521
|
+
if (isNotACall(path)) return null;
|
|
522
|
+
rememberRelayed(req.headers);
|
|
232
523
|
try {
|
|
233
524
|
return { startedAt, call: feed.begin({ startedAt, lineage: lineageOf(req.headers), model: requestModel(body), provider: providerOf(path) }) };
|
|
234
525
|
} catch {
|
|
@@ -242,7 +533,7 @@ export function createSidecar({
|
|
|
242
533
|
if (watch) {
|
|
243
534
|
watch.call.settle({ outcome: "error", code: "sidecar_upstream_error", status: 502 });
|
|
244
535
|
watch.call.finish();
|
|
245
|
-
} else if (!
|
|
536
|
+
} else if (!isNotACall(path)) {
|
|
246
537
|
feed.record({ outcome: "error", code: "sidecar_upstream_error", status: 502, lineage: lineageOf(req.headers), provider: providerOf(path) });
|
|
247
538
|
}
|
|
248
539
|
res.writeHead(502, { "content-type": "application/json" });
|
|
@@ -255,6 +546,10 @@ export function createSidecar({
|
|
|
255
546
|
const server = http.createServer(async (req, res) => {
|
|
256
547
|
// The sidecar's own paths: answered here, never forwarded with a visa.
|
|
257
548
|
if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
|
|
549
|
+
const localPath = String(req.url).split("?")[0];
|
|
550
|
+
if (localPath === HOOK_PATH) return serveHook(req, res);
|
|
551
|
+
if (localPath === OTLP_LOGS_PATH) return serveOtlpLogs(req, res);
|
|
552
|
+
if (localPath === WINDOW_PATH) return serveWindow(req, res);
|
|
258
553
|
feed.serve(req, res, { port: server.address()?.port });
|
|
259
554
|
return;
|
|
260
555
|
}
|
|
@@ -371,7 +666,8 @@ export function createSidecar({
|
|
|
371
666
|
clientSocket.on("close", () => upstream.destroy());
|
|
372
667
|
});
|
|
373
668
|
|
|
374
|
-
|
|
669
|
+
server.on("close", () => uploader?.close());
|
|
670
|
+
return { server, ollamaServer, getVisa: visas.getVisa, runId, feed, uploader };
|
|
375
671
|
}
|
|
376
672
|
|
|
377
673
|
/**
|
package/cli/statusline.mjs
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
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 { limitReached, panelRows, statusLine } from "./budget-format.mjs";
|
|
17
|
+
import { limitReached, panelRows, paused, statusLine } from "./budget-format.mjs";
|
|
18
|
+
import { heldUsageWindow, readUsageWindow, usageWindowText, WINDOW_PATH } from "./usage-window.mjs";
|
|
18
19
|
|
|
19
20
|
export const STATUSLINE_TTL_MS = 20_000;
|
|
20
21
|
const TIMEOUT_MS = 1_500;
|
|
@@ -88,6 +89,82 @@ export async function statuslineText({
|
|
|
88
89
|
}
|
|
89
90
|
}
|
|
90
91
|
|
|
92
|
+
// Claude Code writes one JSON object to the command's stdin. It may not close the
|
|
93
|
+
// stream promptly, so the object is taken as soon as it parses, and after this long
|
|
94
|
+
// the line is printed without it.
|
|
95
|
+
const STDIN_WAIT_MS = 300;
|
|
96
|
+
const STDIN_LIMIT = 256 * 1024;
|
|
97
|
+
|
|
98
|
+
/** Claude Code's status-line input, or null. Never throws, never waits past `waitMs`. */
|
|
99
|
+
export function readStatusInput(stream = process.stdin, waitMs = STDIN_WAIT_MS) {
|
|
100
|
+
if (!stream || stream.isTTY) return Promise.resolve(null);
|
|
101
|
+
return new Promise((resolve) => {
|
|
102
|
+
let text = "";
|
|
103
|
+
let done = false;
|
|
104
|
+
const finish = (value) => {
|
|
105
|
+
if (done) return;
|
|
106
|
+
done = true;
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
stream.removeAllListeners?.("data");
|
|
109
|
+
// An open stdin would keep the process alive after the line is printed.
|
|
110
|
+
stream.destroy?.();
|
|
111
|
+
resolve(value);
|
|
112
|
+
};
|
|
113
|
+
const parse = () => {
|
|
114
|
+
try {
|
|
115
|
+
const parsed = JSON.parse(text);
|
|
116
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
117
|
+
} catch {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
const timer = setTimeout(() => finish(parse() ?? null), waitMs);
|
|
122
|
+
try {
|
|
123
|
+
stream.setEncoding?.("utf8");
|
|
124
|
+
stream.on("data", (chunk) => {
|
|
125
|
+
text += chunk;
|
|
126
|
+
if (text.length > STDIN_LIMIT) return finish(null);
|
|
127
|
+
const parsed = parse();
|
|
128
|
+
if (parsed !== undefined) finish(parsed);
|
|
129
|
+
});
|
|
130
|
+
stream.on("end", () => finish(parse() ?? null));
|
|
131
|
+
stream.on("error", () => finish(null));
|
|
132
|
+
} catch {
|
|
133
|
+
finish(null);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Hands the usage window to the sidecar, for `watch` and `/passcontrol`. Best effort:
|
|
140
|
+
* a sidecar that is not running only means the boards do not show it.
|
|
141
|
+
*/
|
|
142
|
+
export async function postUsageWindow({ port, host = "127.0.0.1", window, fetch: fetchImpl = globalThis.fetch, timeoutMs = 500 }) {
|
|
143
|
+
if (!window) return;
|
|
144
|
+
try {
|
|
145
|
+
const response = await fetchImpl(`http://${host}:${port}${WINDOW_PATH}`, {
|
|
146
|
+
method: "POST",
|
|
147
|
+
headers: { "content-type": "application/json" },
|
|
148
|
+
body: JSON.stringify(window),
|
|
149
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
150
|
+
});
|
|
151
|
+
await response.body?.cancel().catch(() => {});
|
|
152
|
+
} catch {
|
|
153
|
+
// Nothing to tell anyone: the status line still shows the window.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The status line with the usage window, when Claude Code sent one: the budget line
|
|
159
|
+
* may come from the cache, the window is always this run's. Never throws.
|
|
160
|
+
*/
|
|
161
|
+
export async function statuslineWithWindow({ input, port, host = "127.0.0.1", fetch: fetchImpl = globalThis.fetch, budgetLine }) {
|
|
162
|
+
const window = readUsageWindow(input);
|
|
163
|
+
const [line] = await Promise.all([budgetLine(), postUsageWindow({ port, host, window, fetch: fetchImpl })]);
|
|
164
|
+
const text = usageWindowText(window, { short: true });
|
|
165
|
+
return text ? `${line} · ${text}` : line;
|
|
166
|
+
}
|
|
167
|
+
|
|
91
168
|
// The session id Claude Code declares on every call, held to what the gateway
|
|
92
169
|
// accepts as declared (lib/client-lineage.ts), so nothing else is ever sent on.
|
|
93
170
|
const DECLARED_SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
@@ -128,6 +205,20 @@ export function notInPathText(remoteHost) {
|
|
|
128
205
|
|
|
129
206
|
const row = ([label, value]) => ` ${label.padEnd(11)} ${value}`;
|
|
130
207
|
|
|
208
|
+
/** The usage window the sidecar holds, as short text, or "". Never throws. */
|
|
209
|
+
async function readSidecarWindow({ host, port, fetch: fetchImpl, signal }) {
|
|
210
|
+
try {
|
|
211
|
+
const response = await fetchImpl(`http://${host}:${port}${WINDOW_PATH}`, { headers: { accept: "application/json" }, signal });
|
|
212
|
+
if (!response.ok) {
|
|
213
|
+
await response.body?.cancel().catch(() => {});
|
|
214
|
+
return "";
|
|
215
|
+
}
|
|
216
|
+
return usageWindowText(heldUsageWindow(await response.json()), { short: true });
|
|
217
|
+
} catch {
|
|
218
|
+
return "";
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
131
222
|
/**
|
|
132
223
|
* `passcontrol statusline --panel`: what `/passcontrol` shows in Claude Code (F3).
|
|
133
224
|
* The plugin's hook prints it without calling the model, so it answers while the
|
|
@@ -139,6 +230,7 @@ export async function statusPanelText({
|
|
|
139
230
|
host = "127.0.0.1",
|
|
140
231
|
gateway,
|
|
141
232
|
session = null,
|
|
233
|
+
subscription = false,
|
|
142
234
|
fetch: fetchImpl = globalThis.fetch,
|
|
143
235
|
timeoutMs = TIMEOUT_MS,
|
|
144
236
|
}) {
|
|
@@ -154,12 +246,16 @@ export async function statusPanelText({
|
|
|
154
246
|
response = await fetchImpl(`http://${host}:${port}/api/v1/self`, { headers, signal: controller.signal });
|
|
155
247
|
} catch {
|
|
156
248
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
249
|
+
// On a subscription the calls never pass the sidecar, so they go ahead without
|
|
250
|
+
// it: what stops is PassControl checking the stops and showing the calls.
|
|
251
|
+
const consequence = subscription
|
|
252
|
+
? [
|
|
253
|
+
" This session's calls still go ahead, but PassControl does not check",
|
|
254
|
+
" the agent's stops or show its calls until it runs. Start it with:",
|
|
255
|
+
" passcontrol sidecar",
|
|
256
|
+
]
|
|
257
|
+
: [" If Claude Code is set to send its calls through PassControl, they fail", " until it runs. Start it with: passcontrol sidecar"];
|
|
258
|
+
return [`PassControl · sidecar not running on port ${port}`, "", ...consequence].join("\n");
|
|
163
259
|
}
|
|
164
260
|
if (response.status === 403) {
|
|
165
261
|
const body = await response.json().catch(() => ({}));
|
|
@@ -196,12 +292,14 @@ export async function statusPanelText({
|
|
|
196
292
|
}
|
|
197
293
|
if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
|
|
198
294
|
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" : ""}`;
|
|
295
|
+
const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : paused(self) ? " · PAUSED" : ""}`;
|
|
296
|
+
const window = subscription ? await readSidecarWindow({ host, port, fetch: fetchImpl, signal: controller.signal }) : "";
|
|
200
297
|
return [
|
|
201
298
|
title,
|
|
202
299
|
"",
|
|
203
300
|
...panelRows(self).map(row),
|
|
204
|
-
row(["
|
|
301
|
+
...(window ? [row(["Window", window])] : []),
|
|
302
|
+
row(["Calls", subscription ? "reported by Claude Code (subscription), not proxied" : `through the sidecar on :${port}`]),
|
|
205
303
|
"",
|
|
206
304
|
row(["Agent page", agentId ? `${dashboard}/agents/${agentId}` : dashboard]),
|
|
207
305
|
].join("\n");
|