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.
@@ -0,0 +1,66 @@
1
+ // Subscription mode's limit (Phase 1): Anthropic's usage
2
+ // window.
3
+ //
4
+ // A Pro/Max subscription pays a flat fee, so dollars are not what runs out: the
5
+ // 5-hour and 7-day allowances are. Claude Code passes how much of each is used to its
6
+ // status-line command on stdin, as `rate_limits` (Pro/Max only, and only after the
7
+ // session's first response; code.claude.com/docs/en/statusline, read 2026-10-11).
8
+ // `passcontrol statusline` reads it from there, shows it, and hands it to the sidecar
9
+ // on WINDOW_PATH, so `watch` and `/passcontrol` can show it too.
10
+ //
11
+ // It is shown, never enforced (the owner's choice on 2026-10-11): Anthropic enforces
12
+ // its own window, and the number is the client's report.
13
+
14
+ export const WINDOW_PATH = "/_passcontrol/window";
15
+
16
+ // Seconds since the epoch, from 2001 to 2286: anything else is not a reset time.
17
+ const isEpochSeconds = (v) => Number.isInteger(v) && v > 1_000_000_000 && v < 10_000_000_000;
18
+ // A percentage of an allowance. Over 100 is allowed: a window can be overrun.
19
+ const isPct = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1000;
20
+
21
+ function one(raw, pctKey, resetKey) {
22
+ if (!raw || typeof raw !== "object" || !isPct(raw[pctKey])) return null;
23
+ return { usedPct: raw[pctKey], resetsAt: isEpochSeconds(raw[resetKey]) ? raw[resetKey] : null };
24
+ }
25
+
26
+ function both(fiveHour, sevenDay) {
27
+ return fiveHour || sevenDay ? { fiveHour, sevenDay } : null;
28
+ }
29
+
30
+ /** The window from Claude Code's status-line input, or null. Never throws. */
31
+ export function readUsageWindow(input) {
32
+ const limits = input && typeof input === "object" ? input.rate_limits : null;
33
+ if (!limits || typeof limits !== "object") return null;
34
+ return both(one(limits.five_hour, "used_percentage", "resets_at"), one(limits.seven_day, "used_percentage", "resets_at"));
35
+ }
36
+
37
+ /** A window in this module's own shape, held to it again: what the sidecar accepts. */
38
+ export function heldUsageWindow(value) {
39
+ if (!value || typeof value !== "object") return null;
40
+ return both(one(value.fiveHour, "usedPct", "resetsAt"), one(value.sevenDay, "usedPct", "resetsAt"));
41
+ }
42
+
43
+ const pad2 = (n) => String(n).padStart(2, "0");
44
+ const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
45
+
46
+ /** A reset time as the local clock reads it, with the weekday when it is not today. */
47
+ export function resetTime(epochSeconds, now = Date.now()) {
48
+ const at = new Date(epochSeconds * 1000);
49
+ const clock = `${pad2(at.getHours())}:${pad2(at.getMinutes())}`;
50
+ return at.toDateString() === new Date(now).toDateString() ? clock : `${DAYS[at.getDay()]} ${clock}`;
51
+ }
52
+
53
+ /**
54
+ * `5h 24% (resets 21:40) · 7d 41% (resets Tue 09:00)`, or with `short`, `5h 24% · 7d 41%`.
55
+ * Empty for no window.
56
+ */
57
+ export function usageWindowText(window, { short = false, formatTime = resetTime } = {}) {
58
+ const held = heldUsageWindow(window);
59
+ if (!held) return "";
60
+ const part = (label, w) => {
61
+ if (!w) return null;
62
+ const resets = !short && w.resetsAt ? ` (resets ${formatTime(w.resetsAt)})` : "";
63
+ return `${label} ${Math.round(w.usedPct)}%${resets}`;
64
+ };
65
+ return [part("5h", held.fiveHour), part("7d", held.sevenDay)].filter(Boolean).join(" · ");
66
+ }
@@ -82,9 +82,12 @@ export function providerOf(path) {
82
82
  return match ? held(PROVIDER, match[1]) : null;
83
83
  }
84
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 ?? ""));
85
+ /**
86
+ * Gateway paths that are not model calls: the budget read the board and the status
87
+ * line poll, and the upload of calls a client reported (cli/client-events-upload.mjs).
88
+ */
89
+ export function isNotACall(path) {
90
+ return /^\/api\/v1\/(self|client-events)(\?|$)/.test(String(path ?? ""));
88
91
  }
89
92
 
90
93
  /** Reads at most `limit` bytes of a (cloned) body, then cancels it. Never throws. */
@@ -117,7 +120,18 @@ function hostIsThisListener(hostHeader, port) {
117
120
  return Boolean(match && LOOPBACK_NAMES.has(match[1]) && Number(match[2]) === port);
118
121
  }
119
122
 
120
- function answer(res, status, error, message) {
123
+ /**
124
+ * The checks every one of the sidecar's own endpoints makes before answering: a
125
+ * loopback peer, no Origin (a browser's cross-origin request carries one), and a Host
126
+ * naming this loopback listener and port exactly (DNS rebinding). The watch feed and
127
+ * subscription mode's hook endpoint share them.
128
+ */
129
+ export function isLocalCaller(req, port) {
130
+ const loopbackPeer = LOOPBACK_PEER.test(String(req.socket?.remoteAddress ?? ""));
131
+ return loopbackPeer && req.headers.origin === undefined && hostIsThisListener(req.headers.host, port);
132
+ }
133
+
134
+ export function answer(res, status, error, message) {
121
135
  const body = JSON.stringify({ error, message });
122
136
  res.writeHead(status, {
123
137
  "content-type": "application/json",
@@ -136,6 +150,8 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
136
150
  const ring = [];
137
151
  const subscribers = new Set();
138
152
  let seq = 0;
153
+ // Subscription mode's usage window (cli/usage-window.mjs): only the latest matters.
154
+ let usageWindow = null;
139
155
 
140
156
  function send(res, line) {
141
157
  try {
@@ -194,6 +210,7 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
194
210
  status: null,
195
211
  ttfb: null,
196
212
  ms: null,
213
+ cost: null,
197
214
  };
198
215
  let announced = false;
199
216
  return {
@@ -223,6 +240,49 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
223
240
  };
224
241
  }
225
242
 
243
+ /**
244
+ * A call the CLIENT reported (subscription mode: Claude Code's own telemetry,
245
+ * cli/otlp-logs.mjs). It never passed this sidecar, so it is SEEN, not boarded, and
246
+ * its cost is the client's API-equivalent estimate in USD millionths. Never throws.
247
+ */
248
+ function report({ at = now(), lineage = null, model = null, provider = null, outcome = "seen", status = null, ms = null, cost = null }) {
249
+ try {
250
+ const record = {
251
+ type: "call",
252
+ seq: ++seq,
253
+ at: Number.isFinite(at) ? at : now(),
254
+ ses: held(DECLARED, lineage?.session),
255
+ agent: held(DECLARED, lineage?.agent),
256
+ parent: held(DECLARED, lineage?.parent),
257
+ model: held(MODEL, model),
258
+ provider: held(PROVIDER, provider),
259
+ outcome: outcome === "seen" ? "seen" : "error",
260
+ code: null,
261
+ status: Number.isInteger(status) ? status : null,
262
+ ttfb: null,
263
+ ms: Number.isInteger(ms) && ms >= 0 ? ms : null,
264
+ cost: Number.isInteger(cost) && cost >= 0 ? cost : null,
265
+ };
266
+ remember(record);
267
+ broadcast(record);
268
+ } catch {
269
+ // The feed is never the reason anything fails.
270
+ }
271
+ }
272
+
273
+ /**
274
+ * The latest usage window, already held to its shape by the caller. Replaces the
275
+ * last one and tells every board. Never throws.
276
+ */
277
+ function setWindow(window) {
278
+ try {
279
+ usageWindow = { type: "window", fiveHour: window.fiveHour, sevenDay: window.sevenDay, at: now() };
280
+ broadcast(usageWindow);
281
+ } catch {
282
+ // As above.
283
+ }
284
+ }
285
+
226
286
  /** A call whose outcome and end are known at once (refusals, upstream failures). */
227
287
  function record({ outcome, code = null, status, lineage = null, model = null, provider = null, startedAt = now() }) {
228
288
  const call = begin({ startedAt, lineage, model, provider });
@@ -234,6 +294,7 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
234
294
  function attach(res) {
235
295
  subscribers.add(res);
236
296
  send(res, `${JSON.stringify({ type: "hello", feed: "passcontrol-watch", v: 1, run: runId })}\n`);
297
+ if (usageWindow && subscribers.has(res)) send(res, `${JSON.stringify(usageWindow)}\n`);
237
298
  for (const r of ring) if (subscribers.has(res)) send(res, `${JSON.stringify(r)}\n`);
238
299
  try {
239
300
  res.on("close", () => subscribers.delete(res));
@@ -251,8 +312,7 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
251
312
  return answer(res, 404, "watch_off", "This sidecar is bound off loopback, so it serves no watch feed.");
252
313
  }
253
314
  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)) {
315
+ if (!isLocalCaller(req, port)) {
256
316
  return answer(res, 403, "watch_refused", "The watch feed is for `passcontrol watch` on this machine only.");
257
317
  }
258
318
  if (subscribers.size >= maxSubscribers) {
@@ -271,5 +331,15 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
271
331
  for (const res of [...subscribers]) drop(res);
272
332
  }
273
333
 
274
- return { begin, record, serve, attach, close, subscriberCount: () => subscribers.size };
334
+ return {
335
+ begin,
336
+ record,
337
+ report,
338
+ setWindow,
339
+ window: () => usageWindow,
340
+ serve,
341
+ attach,
342
+ close,
343
+ subscriberCount: () => subscribers.size,
344
+ };
275
345
  }
package/cli/watch.mjs CHANGED
@@ -16,14 +16,16 @@
16
16
  // fields are held to the feed's own patterns on arrival, and every cell is stripped
17
17
  // of control characters again before it is drawn.
18
18
  import http from "node:http";
19
- import { formatUsd, limitReached, panelRows } from "./budget-format.mjs";
19
+ import { formatUsd, limitReached, panelRows, paused } from "./budget-format.mjs";
20
20
  import { WATCH_PATH } from "./watch-feed.mjs";
21
+ import { heldUsageWindow, resetTime, usageWindowText } from "./usage-window.mjs";
21
22
 
22
23
  const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
23
24
  const MODEL = /^[A-Za-z0-9._:/@-]{1,100}$/;
24
25
  const CODE = /^[a-z][a-z0-9_]{1,47}$/;
25
26
  const PROVIDER = /^[a-z0-9-]{1,32}$/;
26
- const OUTCOMES = new Set(["boarded", "denied", "error"]);
27
+ // "seen" is a call the client reported (subscription mode), not one the sidecar relayed.
28
+ const OUTCOMES = new Set(["boarded", "denied", "error", "seen"]);
27
29
  const MAX_ROWS = 500;
28
30
  const MAX_LINE = 64 * 1024;
29
31
  export const BUDGET_EVERY_MS = 20_000;
@@ -122,7 +124,7 @@ export function openFeed({ port, host = "127.0.0.1", onEvent, onError = () => {}
122
124
  // ── State ────────────────────────────────────────────────────────────────────
123
125
 
124
126
  export function createBoardState() {
125
- return { run: null, rows: [], feed: { state: "connecting" }, budget: null };
127
+ return { run: null, rows: [], feed: { state: "connecting" }, budget: null, window: null };
126
128
  }
127
129
 
128
130
  const held = (pattern, value) => (typeof value === "string" && pattern.test(value) ? value : null);
@@ -154,6 +156,7 @@ export function applyEvent(state, event) {
154
156
  status: Number.isInteger(event.status) ? event.status : null,
155
157
  ttfb: count(event.ttfb),
156
158
  ms: count(event.ms),
159
+ cost: count(event.cost),
157
160
  };
158
161
  const existing = state.rows.findIndex((r) => r.seq === row.seq);
159
162
  if (existing === -1) state.rows.push(row);
@@ -161,6 +164,11 @@ export function applyEvent(state, event) {
161
164
  if (state.rows.length > MAX_ROWS) state.rows.splice(0, state.rows.length - MAX_ROWS);
162
165
  return state;
163
166
  }
167
+ if (event.type === "window") {
168
+ const window = heldUsageWindow(event);
169
+ if (window) state.window = window;
170
+ return state;
171
+ }
164
172
  if (event.type === "end") {
165
173
  const row = state.rows.find((r) => r.seq === event.seq);
166
174
  const ms = count(event.ms);
@@ -217,8 +225,17 @@ export function formatMs(ms) {
217
225
 
218
226
  const localTime = (at) => new Date(at).toTimeString().slice(0, 8);
219
227
 
228
+ /** USD millionths, as one call's cost: four decimals under a dollar. */
229
+ export function formatMicroUsd(micros) {
230
+ if (micros === null || micros === undefined) return "";
231
+ const dollars = micros / 1_000_000;
232
+ return `$${dollars < 1 ? dollars.toFixed(4) : dollars.toFixed(2)}`;
233
+ }
234
+
220
235
  function statusText(row) {
221
236
  if (row.outcome === "boarded") return "BOARDED";
237
+ // Reported by Claude Code, never relayed: its cost is API-equivalent, not charged.
238
+ if (row.outcome === "seen") return row.cost !== null ? `SEEN ${formatMicroUsd(row.cost)}` : "SEEN";
222
239
  if (row.outcome === "denied") return row.code ? `DENIED ${row.code}` : "DENIED";
223
240
  return `ERROR ${row.code ?? row.status ?? ""}`.trimEnd();
224
241
  }
@@ -241,8 +258,9 @@ function agentText(row, width) {
241
258
 
242
259
  /** Column widths for a terminal `width` wide; the session column goes first when narrow. */
243
260
  function columns(width) {
244
- // Below 80 columns the model and the refusal's reason need the room more.
245
- const withSession = width >= 80;
261
+ // Below an 80-column window the model and the refusal's reason need the room more.
262
+ // 79, not 80: screenFrame draws one column narrower than the window.
263
+ const withSession = width >= 79;
246
264
  const fixed = 8 + (withSession ? 8 : 0) + 12 + 7;
247
265
  const gaps = (withSession ? 5 : 4) * 2;
248
266
  const rest = Math.max(10, width - fixed - gaps);
@@ -261,7 +279,8 @@ function rowLine(row, cols, { run, now, formatTime, color }) {
261
279
  if (cols.withSession) cells.push(fit(sessionText(row, run), cols.session));
262
280
  cells.push(agentText(row, cols.agent));
263
281
  cells.push(fit(row.model ?? "—", cols.model));
264
- cells.push(paint(color, BAR_STYLE[row.outcome], fit(statusText(row), cols.status)));
282
+ const status = fit(statusText(row), cols.status);
283
+ cells.push(BAR_STYLE[row.outcome] ? paint(color, BAR_STYLE[row.outcome], status) : status);
265
284
  cells.push(fitRight(latencyText(row, now), cols.latency));
266
285
  return cells.join(" ");
267
286
  }
@@ -294,13 +313,25 @@ function budgetLine(budget, width, { color, formatTime }) {
294
313
  const style = fraction >= 1 ? "red" : fraction >= 0.8 ? "yellow" : "green";
295
314
  bar = `[${paint(color, style, "█".repeat(filled))}${"░".repeat(barWidth - filled)}] `;
296
315
  }
297
- const reached = limitReached(budget.self) ? ` · ${paint(color, "red", "LIMIT REACHED")}` : "";
316
+ // A pause is the owner's line doing its job, so not the red of a spent limit.
317
+ const reached = limitReached(budget.self)
318
+ ? ` · ${paint(color, "red", "LIMIT REACHED")}`
319
+ : paused(budget.self)
320
+ ? ` · ${paint(color, "yellow", "PAUSED")}`
321
+ : "";
298
322
  const line = `${clean(label).padEnd(9)} ${bar}${clean(value)}${reached}`;
299
323
  // When it was asked is the first thing to go when the line is too long.
300
324
  const checked = budget.checkedAt ? ` · checked ${formatTime(budget.checkedAt)}` : "";
301
325
  return visibleLength(line + checked) <= width ? line + checked : line;
302
326
  }
303
327
 
328
+ // Subscription mode: how much of Anthropic's 5-hour and 7-day allowance is used, as
329
+ // Claude Code last told the status line (cli/usage-window.mjs). Shown, never enforced.
330
+ function windowLine(window, now) {
331
+ const text = usageWindowText(window, { formatTime: (s) => resetTime(s, now) });
332
+ return text ? `${"Window".padEnd(9)} ${text}` : "";
333
+ }
334
+
304
335
  function feedText(feed, port) {
305
336
  switch (feed?.state) {
306
337
  case "live":
@@ -342,6 +373,18 @@ function clip(line, width) {
342
373
  * The whole board as `height` lines, none wider than `width`. Pure: the same state,
343
374
  * size and clock give the same lines.
344
375
  */
376
+ /**
377
+ * The full-screen frame draw() writes: home, each board line, clear the rest.
378
+ *
379
+ * One column narrower than the window. A line that fills the last column leaves the
380
+ * cursor ON that column (the terminal's pending-wrap state), and the ESC[K after it
381
+ * erases from the cursor, so the line's last character vanished ("LATENC").
382
+ */
383
+ export function screenFrame(state, { columns, rows, port, color = false, now, formatTime }) {
384
+ const lines = renderBoard(state, { width: Math.max(1, columns - 1), height: rows, port, color, now, formatTime });
385
+ return `\x1b[H${lines.map((l) => `${l}\x1b[K`).join("\r\n")}\x1b[J`;
386
+ }
387
+
345
388
  export function renderBoard(state, { width, height, port, now = Date.now(), formatTime = localTime, color = false }) {
346
389
  const w = Math.max(1, Math.floor(width));
347
390
  const h = Math.max(1, Math.floor(height));
@@ -352,17 +395,19 @@ export function renderBoard(state, { width, height, port, now = Date.now(), form
352
395
  }
353
396
  const cols = columns(w);
354
397
  const rows = state.rows;
355
- const tally = { boarded: 0, denied: 0, error: 0 };
398
+ const tally = { boarded: 0, denied: 0, error: 0, seen: 0 };
356
399
  for (const r of rows) tally[r.outcome] += 1;
357
400
  const counts = rows.length
358
- ? `${rows.length} call${rows.length === 1 ? "" : "s"}: ${tally.boarded} boarded, ${tally.denied} denied${tally.error ? `, ${tally.error} error` : ""}`
401
+ ? `${rows.length} call${rows.length === 1 ? "" : "s"}: ${tally.seen ? `${tally.seen} seen, ` : ""}${tally.boarded} boarded, ${tally.denied} denied${tally.error ? `, ${tally.error} error` : ""}`
359
402
  : "no calls yet";
360
403
  const lines = [
361
404
  `${paint(color, "bold", "PassControl watch")} · sidecar :${port} · ${feedText(state.feed, port)} · ${counts}`,
362
405
  budgetLine(state.budget, w, { color, formatTime }),
363
406
  // Why the board is not live, on a line of its own so it is never cut off the end
364
407
  // of the header. Older rows stay below it: they happened.
365
- state.feed?.state === "down" ? paint(color, "yellow", clean(state.feed.message ?? `waiting for the sidecar on :${port}`)) : "",
408
+ state.feed?.state === "down"
409
+ ? paint(color, "yellow", clean(state.feed.message ?? `waiting for the sidecar on :${port}`))
410
+ : windowLine(state.window, now),
366
411
  ];
367
412
  const header = ["TIME".padEnd(cols.time)];
368
413
  if (cols.withSession) header.push("SESSION".padEnd(cols.session));
@@ -478,8 +523,7 @@ export function runWatch({
478
523
  drawTimer = null;
479
524
  if (finished) return;
480
525
  if (tty) {
481
- const lines = renderBoard(state, { width: out.columns || 80, height: out.rows || 24, port, color });
482
- out.write(`\x1b[H${lines.map((l) => `${l}\x1b[K`).join("\r\n")}\x1b[J`);
526
+ out.write(screenFrame(state, { columns: out.columns || 80, rows: out.rows || 24, port, color }));
483
527
  return;
484
528
  }
485
529
  const feedLine = state.feed?.state === "down" ? clean(state.feed.message ?? "") : state.feed?.state === "live" ? "connected" : null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://passcontrol.vertias.eu",