passcontrol 1.5.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/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, isBudgetRead, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
10
+ import { answer, createWatchFeed, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
11
+ import { createStopGate, HOOK_PATH, 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,24 @@ 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
+ // A usage window is two numbers and two times.
71
+ const WINDOW_BODY_LIMIT = 4 * 1024;
49
72
 
50
73
  /**
51
74
  * A header value is a single line of printable ASCII, always.
@@ -120,6 +143,9 @@ export function createSidecar({
120
143
  watchFeed = isLoopbackBindHost(host),
121
144
  watchCapacity = 200,
122
145
  watchMaxSubscribers = 8,
146
+ // Subscription mode, Phase 1b: upload the calls Claude Code reports to the
147
+ // gateway's agent page (cli/client-events-upload.mjs). `--no-report-calls` turns it off.
148
+ reportCalls = true,
123
149
  }) {
124
150
  // The upstream URL below is built from this, not from the argument: the
125
151
  // sidecar forwards a bearer visa on every proxied request, so its destination
@@ -143,6 +169,257 @@ export function createSidecar({
143
169
  return Array.isArray(v) ? v[0] : v;
144
170
  }, runId);
145
171
 
172
+ // Subscription mode's Stop (cli/subscription-gate.mjs): Claude Code's hooks ask
173
+ // here, and the answer comes from the gateway's /api/v1/self, read with this
174
+ // sidecar's visa and the session the hook names.
175
+ const SELF_TIMEOUT_MS = 2_000;
176
+ async function readSelf(session) {
177
+ try {
178
+ const response = await visas.fetchWithVisa((visa) => {
179
+ // The tool rules ride on every gate read (Phase 2): no call of their own.
180
+ const path = "/api/v1/self?include=tool_rules";
181
+ const headers = {
182
+ accept: "application/json",
183
+ authorization: `Bearer ${visa}`,
184
+ "x-passcontrol-run": runId,
185
+ "x-passcontrol-proof": visas.createProof(visa, "GET", new URL(path, origin)),
186
+ "accept-encoding": "identity",
187
+ };
188
+ if (session) headers["x-claude-code-session-id"] = session;
189
+ return fetch(`${origin}${path}`, { headers, signal: AbortSignal.timeout(SELF_TIMEOUT_MS) });
190
+ });
191
+ return await selfAnswerState(response);
192
+ } catch (error) {
193
+ return { state: "unknown", reason: error?.name === "TimeoutError" ? "the gateway did not answer in time" : (error?.message ?? "error") };
194
+ }
195
+ }
196
+ const stopGate = createStopGate({ readSelf, dashboardUrl: `${origin}/dashboard` });
197
+
198
+ // Phase 2's `ask_owner` tool rules: the gateway asks the owner (their alert
199
+ // destination is in its Vault) and holds each request a few seconds; this asks
200
+ // again until the owner answers or the tool gate's wait runs out.
201
+ const TOOL_APPROVALS_PATH = "/api/v1/tool-approvals";
202
+ const APPROVAL_REQUEST_TIMEOUT_MS = 25_000;
203
+ const APPROVAL_RETRY_MS = 1_000;
204
+ async function askOwner(input, { session, waitMs }) {
205
+ const deadline = Date.now() + waitMs;
206
+ const body = JSON.stringify({ session: session ?? undefined, tool_name: input.tool_name, tool_input: input.tool_input, cwd: input.cwd });
207
+ while (Date.now() < deadline - 500) {
208
+ let response;
209
+ try {
210
+ response = await visas.fetchWithVisa((visa) => {
211
+ const headers = {
212
+ "content-type": "application/json",
213
+ authorization: `Bearer ${visa}`,
214
+ "x-passcontrol-run": runId,
215
+ "x-passcontrol-proof": visas.createProof(visa, "POST", new URL(TOOL_APPROVALS_PATH, origin)),
216
+ "accept-encoding": "identity",
217
+ };
218
+ if (session) headers["x-claude-code-session-id"] = session;
219
+ return fetch(`${origin}${TOOL_APPROVALS_PATH}`, {
220
+ method: "POST",
221
+ headers,
222
+ body,
223
+ signal: AbortSignal.timeout(Math.min(APPROVAL_REQUEST_TIMEOUT_MS, Math.max(1_000, deadline - Date.now()))),
224
+ });
225
+ });
226
+ } catch {
227
+ // The gateway did not answer this round: ask again while there is time.
228
+ await new Promise((resolve) => setTimeout(resolve, Math.min(APPROVAL_RETRY_MS, Math.max(0, deadline - Date.now()))));
229
+ continue;
230
+ }
231
+ const answered = await response.json().catch(() => ({}));
232
+ if (response.status === 409) return { state: "refused" };
233
+ if (response.status === 413) return { state: "too_large" };
234
+ if (response.status !== 200) return { state: "unavailable" };
235
+ if (["approved", "denied", "full"].includes(answered?.state)) return { state: answered.state };
236
+ if (answered?.state !== "pending") return { state: "unavailable" };
237
+ }
238
+ return { state: "timeout" };
239
+ }
240
+
241
+ // The reported calls go to the gateway as this agent, straight from here: never
242
+ // through this sidecar's own listener, so they are never a call on the board.
243
+ const UPLOAD_TIMEOUT_MS = 10_000;
244
+ async function sendReportedCalls(events) {
245
+ const response = await visas.fetchWithVisa((visa) =>
246
+ fetch(`${origin}${CLIENT_EVENTS_PATH}`, {
247
+ method: "POST",
248
+ headers: {
249
+ "content-type": "application/json",
250
+ authorization: `Bearer ${visa}`,
251
+ "x-passcontrol-run": runId,
252
+ "x-passcontrol-proof": visas.createProof(visa, "POST", new URL(CLIENT_EVENTS_PATH, origin)),
253
+ "accept-encoding": "identity",
254
+ },
255
+ body: JSON.stringify({ source: CLIENT_EVENTS_SOURCE, events }),
256
+ signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
257
+ })
258
+ );
259
+ const body = await response.json().catch(() => ({}));
260
+ return { status: response.status, error: body?.error, retryAfterS: Number(response.headers.get("retry-after")) };
261
+ }
262
+ const uploader = reportCalls ? createCallUploader({ send: sendReportedCalls }) : null;
263
+ // Its decisions reach the agent's page with the reported calls (same opt-out).
264
+ const toolGate = createToolGate({
265
+ askOwner,
266
+ dashboardUrl: `${origin}/dashboard`,
267
+ onDecision: (record) => uploader?.add({ kind: "tool_decision", at: Date.now(), ...record }),
268
+ });
269
+
270
+ const relayedSessions = new Set();
271
+ function rememberRelayed(headers) {
272
+ const session = lineageOf(headers)?.session;
273
+ if (!session || relayedSessions.has(session)) return;
274
+ relayedSessions.add(session);
275
+ if (relayedSessions.size > RELAYED_SESSIONS_MAX) relayedSessions.delete(relayedSessions.values().next().value);
276
+ }
277
+
278
+ /** Reads a local caller's body up to `limit`; resolves null when it is over. */
279
+ function readLocalBody(req, limit) {
280
+ return new Promise((resolve) => {
281
+ const chunks = [];
282
+ let size = 0;
283
+ let over = false;
284
+ req.on("data", (c) => {
285
+ size += c.length;
286
+ if (size > limit) over = true;
287
+ else chunks.push(c);
288
+ });
289
+ req.on("end", () => resolve(over ? null : Buffer.concat(chunks)));
290
+ req.on("error", () => resolve(null));
291
+ });
292
+ }
293
+
294
+ // Subscription mode's telemetry (cli/otlp-logs.mjs): Claude Code's log exporter
295
+ // posts here. Answered as an OTLP collector does, `{}` on success.
296
+ async function serveOtlpLogs(req, res) {
297
+ const port = server.address()?.port;
298
+ if (req.method !== "POST") {
299
+ req.resume();
300
+ return answer(res, 405, "method_not_allowed", "The telemetry endpoint answers POST only.");
301
+ }
302
+ if (!isLocalCaller(req, port)) {
303
+ req.resume();
304
+ return answer(res, 403, "telemetry_refused", "The telemetry endpoint is for Claude Code on this machine only.");
305
+ }
306
+ if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
307
+ req.resume();
308
+ return answer(res, 415, "telemetry_protocol", "Send OTLP as JSON: set OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=http/json.");
309
+ }
310
+ const raw = await readLocalBody(req, OTLP_BODY_LIMIT);
311
+ if (raw === null) return answer(res, 413, "telemetry_too_large", "Log export over 4 MB.");
312
+ let body;
313
+ try {
314
+ body = JSON.parse(raw.toString("utf8"));
315
+ } catch {
316
+ return answer(res, 400, "telemetry_not_json", "The log export is not JSON.");
317
+ }
318
+ for (const event of readClaudeCodeEvents(body)) {
319
+ if (event.session && relayedSessions.has(event.session)) continue;
320
+ feed.report({
321
+ at: event.at ?? Date.now(),
322
+ lineage: { session: event.session, agent: event.agent },
323
+ model: event.model,
324
+ provider: "anthropic",
325
+ outcome: event.kind === "api_request" ? "seen" : "error",
326
+ status: event.status,
327
+ ms: event.durationMs,
328
+ cost: event.costMicros,
329
+ });
330
+ uploader?.add(event);
331
+ }
332
+ res.writeHead(200, { "content-type": "application/json", "content-length": 2, "cache-control": "no-store" });
333
+ res.end("{}");
334
+ }
335
+
336
+ // Subscription mode's usage window (cli/usage-window.mjs): the status line posts
337
+ // what Claude Code told it; `watch` gets it on the feed, `/passcontrol` asks for it.
338
+ async function serveWindow(req, res) {
339
+ const port = server.address()?.port;
340
+ if (req.method !== "GET" && req.method !== "POST") {
341
+ req.resume();
342
+ return answer(res, 405, "method_not_allowed", "The usage-window endpoint answers GET and POST only.");
343
+ }
344
+ if (!isLocalCaller(req, port)) {
345
+ req.resume();
346
+ return answer(res, 403, "window_refused", "The usage-window endpoint is for this machine only.");
347
+ }
348
+ if (req.method === "GET") {
349
+ req.resume();
350
+ const current = feed.window();
351
+ if (!current) return answer(res, 404, "window_unknown", "No usage window reported yet.");
352
+ const body = JSON.stringify({ fiveHour: current.fiveHour, sevenDay: current.sevenDay, at: current.at });
353
+ res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
354
+ return res.end(body);
355
+ }
356
+ const raw = await readLocalBody(req, WINDOW_BODY_LIMIT);
357
+ let window = null;
358
+ try {
359
+ window = raw === null ? null : heldUsageWindow(JSON.parse(raw.toString("utf8")));
360
+ } catch {
361
+ window = null;
362
+ }
363
+ if (!window) return answer(res, 400, "window_invalid", "Expected a usage window: { fiveHour, sevenDay }.");
364
+ feed.setWindow(window);
365
+ res.writeHead(204, { "cache-control": "no-store" });
366
+ res.end();
367
+ }
368
+
369
+ function serveHook(req, res) {
370
+ const port = server.address()?.port;
371
+ if (req.method !== "POST") {
372
+ req.resume();
373
+ return answer(res, 405, "method_not_allowed", "The hook endpoint answers POST only.");
374
+ }
375
+ if (!isLocalCaller(req, port)) {
376
+ req.resume();
377
+ return answer(res, 403, "hook_refused", "The hook endpoint is for Claude Code on this machine only.");
378
+ }
379
+ const chunks = [];
380
+ let size = 0;
381
+ let tooBig = false;
382
+ req.on("data", (c) => {
383
+ size += c.length;
384
+ if (size > HOOK_BODY_LIMIT) tooBig = true;
385
+ else chunks.push(c);
386
+ });
387
+ req.on("end", async () => {
388
+ if (tooBig) return answer(res, 413, "hook_too_large", "Hook input over 1 MB.");
389
+ let input;
390
+ try {
391
+ input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
392
+ } catch {
393
+ input = null;
394
+ }
395
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
396
+ return answer(res, 400, "hook_not_json", "Expected Claude Code's hook input, a JSON object.");
397
+ }
398
+ let out;
399
+ try {
400
+ out = await stopGate.decide(input);
401
+ } catch {
402
+ out = {};
403
+ }
404
+ // A stop ends the turn whatever the tool rules say; otherwise a PreToolUse is
405
+ // the tool gate's, which needs to know how long Claude Code waits for this hook.
406
+ if (out.continue !== false && input.hook_event_name === "PreToolUse") {
407
+ let tool;
408
+ try {
409
+ tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url));
410
+ } catch {
411
+ tool = {};
412
+ }
413
+ const messages = [out.systemMessage, tool.systemMessage].filter(Boolean);
414
+ out = { ...tool, ...(messages.length ? { systemMessage: messages.join("\n") } : {}) };
415
+ }
416
+ const body = JSON.stringify(out);
417
+ res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
418
+ res.end(body);
419
+ });
420
+ req.on("error", () => res.destroy());
421
+ }
422
+
146
423
  const localBaseUrl = () => {
147
424
  const address = server?.listening ? server.address() : null;
148
425
  return `http://${host}:${address?.port ?? port}`;
@@ -226,9 +503,10 @@ export function createSidecar({
226
503
  else res.end();
227
504
  }
228
505
 
229
- /** Begins the board's record of a forwarded call, unless it is the budget read. */
506
+ /** Begins the board's record of a forwarded call, unless it is not a call (the budget read, an upload). */
230
507
  function watchCall(req, path, body, startedAt) {
231
- if (isBudgetRead(path)) return null;
508
+ if (isNotACall(path)) return null;
509
+ rememberRelayed(req.headers);
232
510
  try {
233
511
  return { startedAt, call: feed.begin({ startedAt, lineage: lineageOf(req.headers), model: requestModel(body), provider: providerOf(path) }) };
234
512
  } catch {
@@ -242,7 +520,7 @@ export function createSidecar({
242
520
  if (watch) {
243
521
  watch.call.settle({ outcome: "error", code: "sidecar_upstream_error", status: 502 });
244
522
  watch.call.finish();
245
- } else if (!isBudgetRead(path)) {
523
+ } else if (!isNotACall(path)) {
246
524
  feed.record({ outcome: "error", code: "sidecar_upstream_error", status: 502, lineage: lineageOf(req.headers), provider: providerOf(path) });
247
525
  }
248
526
  res.writeHead(502, { "content-type": "application/json" });
@@ -255,6 +533,10 @@ export function createSidecar({
255
533
  const server = http.createServer(async (req, res) => {
256
534
  // The sidecar's own paths: answered here, never forwarded with a visa.
257
535
  if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
536
+ const localPath = String(req.url).split("?")[0];
537
+ if (localPath === HOOK_PATH) return serveHook(req, res);
538
+ if (localPath === OTLP_LOGS_PATH) return serveOtlpLogs(req, res);
539
+ if (localPath === WINDOW_PATH) return serveWindow(req, res);
258
540
  feed.serve(req, res, { port: server.address()?.port });
259
541
  return;
260
542
  }
@@ -371,7 +653,8 @@ export function createSidecar({
371
653
  clientSocket.on("close", () => upstream.destroy());
372
654
  });
373
655
 
374
- return { server, ollamaServer, getVisa: visas.getVisa, runId, feed };
656
+ server.on("close", () => uploader?.close());
657
+ return { server, ollamaServer, getVisa: visas.getVisa, runId, feed, uploader };
375
658
  }
376
659
 
377
660
  /**
@@ -15,6 +15,7 @@
15
15
  import fs from "node:fs";
16
16
  import path from "node:path";
17
17
  import { limitReached, panelRows, 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
- 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");
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(() => ({}));
@@ -197,11 +293,13 @@ export async function statusPanelText({
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
295
  const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : ""}`;
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(["Calls", `through the sidecar on :${port}`]),
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");