passcontrol 1.4.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/LICENSE +3 -1
- package/README.md +10 -1
- package/bin/passcontrol.mjs +266 -8
- package/cli/budget-format.mjs +37 -0
- package/cli/claude-code.mjs +179 -0
- package/cli/client-events-upload.mjs +212 -0
- package/cli/config.mjs +35 -1
- package/cli/declared-session.mjs +32 -4
- package/cli/delegation.d.mts +60 -0
- package/cli/delegation.mjs +192 -0
- package/cli/menu.mjs +4 -0
- package/cli/otlp-logs.mjs +96 -0
- package/cli/profiles.mjs +92 -0
- package/cli/protocols.mjs +3 -1
- package/cli/sidecar.mjs +441 -21
- package/cli/statusline.mjs +223 -1
- package/cli/subscription-gate.mjs +213 -0
- package/cli/tool-gate.mjs +152 -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/visa-client.mjs +5 -1
- package/cli/watch-feed.mjs +345 -0
- package/cli/watch.mjs +640 -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 +7 -0
package/cli/watch.mjs
ADDED
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
// `passcontrol watch` (F6): a full-screen board of the calls a sidecar relays, live.
|
|
2
|
+
//
|
|
3
|
+
// Claude Code and Codex split work across sub-agents, and until now a person saw what
|
|
4
|
+
// that cost only afterwards. The board shows each call as it happens: time, declared
|
|
5
|
+
// session, declared sub-agent, model, BOARDED / DENIED / ERROR, and latency, under the
|
|
6
|
+
// agent's budget.
|
|
7
|
+
//
|
|
8
|
+
// What it is not:
|
|
9
|
+
// * not complete: a call that does not go through this sidecar is not on it;
|
|
10
|
+
// * not a control: it reads, it never stops anything (the dashboard does that);
|
|
11
|
+
// * not a record: it writes nothing to disk. The feed is in the sidecar's memory
|
|
12
|
+
// (cli/watch-feed.mjs) and the budget is asked for and held here, in memory,
|
|
13
|
+
// never cached to a file the way the status line's is.
|
|
14
|
+
//
|
|
15
|
+
// Everything a cell shows came over a socket, so the renderer trusts none of it:
|
|
16
|
+
// fields are held to the feed's own patterns on arrival, and every cell is stripped
|
|
17
|
+
// of control characters again before it is drawn.
|
|
18
|
+
import http from "node:http";
|
|
19
|
+
import { formatUsd, limitReached, panelRows } from "./budget-format.mjs";
|
|
20
|
+
import { WATCH_PATH } from "./watch-feed.mjs";
|
|
21
|
+
import { heldUsageWindow, resetTime, usageWindowText } from "./usage-window.mjs";
|
|
22
|
+
|
|
23
|
+
const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
24
|
+
const MODEL = /^[A-Za-z0-9._:/@-]{1,100}$/;
|
|
25
|
+
const CODE = /^[a-z][a-z0-9_]{1,47}$/;
|
|
26
|
+
const PROVIDER = /^[a-z0-9-]{1,32}$/;
|
|
27
|
+
// "seen" is a call the client reported (subscription mode), not one the sidecar relayed.
|
|
28
|
+
const OUTCOMES = new Set(["boarded", "denied", "error", "seen"]);
|
|
29
|
+
const MAX_ROWS = 500;
|
|
30
|
+
const MAX_LINE = 64 * 1024;
|
|
31
|
+
export const BUDGET_EVERY_MS = 20_000;
|
|
32
|
+
const BUDGET_TIMEOUT_MS = 3_000;
|
|
33
|
+
const RECONNECT_MS = [500, 1000, 2000, 4000, 5000];
|
|
34
|
+
// Something other than a feed answered. Through a sidecar from before `watch`, that
|
|
35
|
+
// request went on to the GATEWAY with a visa (it forwards every path) and came back
|
|
36
|
+
// as the login page; on Cloud each one costs the gateway a session check. So a
|
|
37
|
+
// wrong answer is asked again once a minute, not every few seconds.
|
|
38
|
+
const WRONG_ANSWER_MS = 60_000;
|
|
39
|
+
const BUSY_MS = 10_000;
|
|
40
|
+
|
|
41
|
+
/** How long to wait before asking for the feed again, after `error` on try `attempt`. */
|
|
42
|
+
export function retryDelay(error, attempt) {
|
|
43
|
+
if (error.kind === "unreachable" || error.kind === "closed") return RECONNECT_MS[Math.min(attempt, RECONNECT_MS.length - 1)];
|
|
44
|
+
if (error.kind === "busy") return BUSY_MS;
|
|
45
|
+
return WRONG_ANSWER_MS;
|
|
46
|
+
}
|
|
47
|
+
const REDRAW_MS = 60;
|
|
48
|
+
const MIN_WIDTH = 40;
|
|
49
|
+
|
|
50
|
+
// ── The feed, as a client ────────────────────────────────────────────────────
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Subscribes to a sidecar's feed. `onEvent(event, rawLine)` for every line, the hello
|
|
54
|
+
* included; `onError({ kind, ... })` once, when it ends or never starts. kinds:
|
|
55
|
+
* unreachable, closed, not-feed (an older sidecar, or something else on the port),
|
|
56
|
+
* off (bound off loopback), refused, busy.
|
|
57
|
+
*/
|
|
58
|
+
export function openFeed({ port, host = "127.0.0.1", onEvent, onError = () => {} }) {
|
|
59
|
+
let done = false;
|
|
60
|
+
let greeted = false;
|
|
61
|
+
let buffer = "";
|
|
62
|
+
let req;
|
|
63
|
+
const fail = (error) => {
|
|
64
|
+
if (done) return;
|
|
65
|
+
done = true;
|
|
66
|
+
req?.destroy();
|
|
67
|
+
onError(error);
|
|
68
|
+
};
|
|
69
|
+
req = http.get({ host, port, path: WATCH_PATH, headers: { accept: "application/x-ndjson" }, agent: false }, (res) => {
|
|
70
|
+
res.setEncoding("utf8");
|
|
71
|
+
const type = String(res.headers["content-type"] ?? "");
|
|
72
|
+
if (res.statusCode !== 200 || !type.startsWith("application/x-ndjson")) {
|
|
73
|
+
let body = "";
|
|
74
|
+
res.on("data", (chunk) => {
|
|
75
|
+
if (body.length < 4096) body += chunk;
|
|
76
|
+
});
|
|
77
|
+
const settle = () => {
|
|
78
|
+
let code = null;
|
|
79
|
+
try {
|
|
80
|
+
code = JSON.parse(body)?.error ?? null;
|
|
81
|
+
} catch {
|
|
82
|
+
// Not ours.
|
|
83
|
+
}
|
|
84
|
+
const kind = { watch_off: "off", watch_refused: "refused", watch_busy: "busy" }[code] ?? "not-feed";
|
|
85
|
+
fail({ kind, status: res.statusCode });
|
|
86
|
+
};
|
|
87
|
+
res.on("end", settle);
|
|
88
|
+
res.on("close", settle);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
res.on("data", (chunk) => {
|
|
92
|
+
if (done) return;
|
|
93
|
+
buffer += chunk;
|
|
94
|
+
let newline;
|
|
95
|
+
while ((newline = buffer.indexOf("\n")) !== -1) {
|
|
96
|
+
const line = buffer.slice(0, newline);
|
|
97
|
+
buffer = buffer.slice(newline + 1);
|
|
98
|
+
let event;
|
|
99
|
+
try {
|
|
100
|
+
event = JSON.parse(line);
|
|
101
|
+
} catch {
|
|
102
|
+
return fail({ kind: "not-feed", status: 200 });
|
|
103
|
+
}
|
|
104
|
+
if (!greeted) {
|
|
105
|
+
if (event?.type !== "hello" || event.feed !== "passcontrol-watch") return fail({ kind: "not-feed", status: 200 });
|
|
106
|
+
greeted = true;
|
|
107
|
+
}
|
|
108
|
+
onEvent(event, line);
|
|
109
|
+
if (done) return;
|
|
110
|
+
}
|
|
111
|
+
if (buffer.length > MAX_LINE) fail({ kind: "not-feed", status: 200 });
|
|
112
|
+
});
|
|
113
|
+
res.on("close", () => fail({ kind: "closed" }));
|
|
114
|
+
});
|
|
115
|
+
req.on("error", (e) => fail({ kind: "unreachable", message: e?.code ?? e?.message }));
|
|
116
|
+
return {
|
|
117
|
+
destroy() {
|
|
118
|
+
done = true;
|
|
119
|
+
req.destroy();
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ── State ────────────────────────────────────────────────────────────────────
|
|
125
|
+
|
|
126
|
+
export function createBoardState() {
|
|
127
|
+
return { run: null, rows: [], feed: { state: "connecting" }, budget: null, window: null };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const held = (pattern, value) => (typeof value === "string" && pattern.test(value) ? value : null);
|
|
131
|
+
const count = (value) => (Number.isFinite(value) && value >= 0 ? Math.round(value) : null);
|
|
132
|
+
|
|
133
|
+
/** A feed event, held to the feed's own patterns. Anything else is dropped. */
|
|
134
|
+
export function applyEvent(state, event) {
|
|
135
|
+
if (!event || typeof event !== "object") return state;
|
|
136
|
+
if (event.type === "hello") {
|
|
137
|
+
const run = held(DECLARED, event.run);
|
|
138
|
+
// A new sidecar run numbers its calls from 1 again: the old rows are another run's.
|
|
139
|
+
if (state.run !== run) state.rows = [];
|
|
140
|
+
state.run = run;
|
|
141
|
+
state.feed = { state: "live" };
|
|
142
|
+
return state;
|
|
143
|
+
}
|
|
144
|
+
if (event.type === "call") {
|
|
145
|
+
if (!Number.isInteger(event.seq) || event.seq < 1) return state;
|
|
146
|
+
const row = {
|
|
147
|
+
seq: event.seq,
|
|
148
|
+
at: count(event.at),
|
|
149
|
+
ses: held(DECLARED, event.ses),
|
|
150
|
+
agent: held(DECLARED, event.agent),
|
|
151
|
+
parent: held(DECLARED, event.parent),
|
|
152
|
+
model: held(MODEL, event.model),
|
|
153
|
+
provider: held(PROVIDER, event.provider),
|
|
154
|
+
outcome: OUTCOMES.has(event.outcome) ? event.outcome : "error",
|
|
155
|
+
code: held(CODE, event.code),
|
|
156
|
+
status: Number.isInteger(event.status) ? event.status : null,
|
|
157
|
+
ttfb: count(event.ttfb),
|
|
158
|
+
ms: count(event.ms),
|
|
159
|
+
cost: count(event.cost),
|
|
160
|
+
};
|
|
161
|
+
const existing = state.rows.findIndex((r) => r.seq === row.seq);
|
|
162
|
+
if (existing === -1) state.rows.push(row);
|
|
163
|
+
else state.rows[existing] = { ...row, ms: row.ms ?? state.rows[existing].ms };
|
|
164
|
+
if (state.rows.length > MAX_ROWS) state.rows.splice(0, state.rows.length - MAX_ROWS);
|
|
165
|
+
return state;
|
|
166
|
+
}
|
|
167
|
+
if (event.type === "window") {
|
|
168
|
+
const window = heldUsageWindow(event);
|
|
169
|
+
if (window) state.window = window;
|
|
170
|
+
return state;
|
|
171
|
+
}
|
|
172
|
+
if (event.type === "end") {
|
|
173
|
+
const row = state.rows.find((r) => r.seq === event.seq);
|
|
174
|
+
const ms = count(event.ms);
|
|
175
|
+
if (row && ms !== null) row.ms = ms;
|
|
176
|
+
return state;
|
|
177
|
+
}
|
|
178
|
+
return state;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ── Rendering (pure) ─────────────────────────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
// C0, DEL, C1, zero-width and bidi controls: nothing that could move the cursor,
|
|
184
|
+
// recolour the screen, or reorder what a person reads.
|
|
185
|
+
const UNSAFE_RANGES = [[0x00, 0x1f], [0x7f, 0x9f], [0x200b, 0x200f], [0x2028, 0x202e], [0x2060, 0x206f], [0xfeff, 0xfeff]];
|
|
186
|
+
// Built from code points: the characters themselves are invisible in source, and a
|
|
187
|
+
// literal one in a regular expression is a parse error waiting for an editor.
|
|
188
|
+
const hex4 = (n) => `\\u${n.toString(16).padStart(4, "0")}`;
|
|
189
|
+
const UNSAFE = new RegExp(`[${UNSAFE_RANGES.map(([a, b]) => `${hex4(a)}-${hex4(b)}`).join("")}]`, "g");
|
|
190
|
+
|
|
191
|
+
/** A cell's text, with every control character removed. */
|
|
192
|
+
export function clean(value) {
|
|
193
|
+
return String(value ?? "").replace(UNSAFE, "");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function fit(text, width) {
|
|
197
|
+
const s = clean(text);
|
|
198
|
+
if (width <= 0) return "";
|
|
199
|
+
return s.length > width ? `${s.slice(0, width - 1)}…` : s.padEnd(width);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function fitRight(text, width) {
|
|
203
|
+
const s = clean(text);
|
|
204
|
+
return s.length > width ? `${s.slice(0, width - 1)}…` : s.padStart(width);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Long ids differ at the end (a0000000000000002 vs …3): keep both ends. */
|
|
208
|
+
function middle(text, width) {
|
|
209
|
+
const s = clean(text);
|
|
210
|
+
if (s.length <= width) return s.padEnd(width);
|
|
211
|
+
const head = Math.ceil((width - 1) / 2);
|
|
212
|
+
const tail = Math.floor((width - 1) / 2);
|
|
213
|
+
return `${s.slice(0, head)}…${tail > 0 ? s.slice(-tail) : ""}`;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function formatMs(ms) {
|
|
217
|
+
if (ms === null || ms === undefined) return "";
|
|
218
|
+
if (ms < 1000) return `${ms}ms`;
|
|
219
|
+
if (ms < 10_000) return `${(ms / 1000).toFixed(2)}s`;
|
|
220
|
+
if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
|
|
221
|
+
const minutes = Math.floor(ms / 60_000);
|
|
222
|
+
const seconds = Math.floor((ms % 60_000) / 1000);
|
|
223
|
+
return `${minutes}m${String(seconds).padStart(2, "0")}s`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const localTime = (at) => new Date(at).toTimeString().slice(0, 8);
|
|
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
|
+
|
|
235
|
+
function statusText(row) {
|
|
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";
|
|
239
|
+
if (row.outcome === "denied") return row.code ? `DENIED ${row.code}` : "DENIED";
|
|
240
|
+
return `ERROR ${row.code ?? row.status ?? ""}`.trimEnd();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function latencyText(row, now) {
|
|
244
|
+
if (row.ms !== null) return formatMs(row.ms);
|
|
245
|
+
// Still streaming: how long so far, marked as not final.
|
|
246
|
+
return row.at !== null ? `${formatMs(Math.max(0, now - row.at))}…` : "…";
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function sessionText(row, run) {
|
|
250
|
+
if (!row.ses) return "—";
|
|
251
|
+
return row.ses === run ? "(run)" : row.ses.slice(0, 8);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function agentText(row, width) {
|
|
255
|
+
if (!row.agent) return "main".padEnd(width);
|
|
256
|
+
return row.parent ? `↳${middle(row.agent, width - 1)}` : middle(row.agent, width);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Column widths for a terminal `width` wide; the session column goes first when narrow. */
|
|
260
|
+
function columns(width) {
|
|
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;
|
|
264
|
+
const fixed = 8 + (withSession ? 8 : 0) + 12 + 7;
|
|
265
|
+
const gaps = (withSession ? 5 : 4) * 2;
|
|
266
|
+
const rest = Math.max(10, width - fixed - gaps);
|
|
267
|
+
const model = Math.ceil(rest / 2);
|
|
268
|
+
return { withSession, time: 8, session: 8, agent: 12, model, status: rest - model, latency: 7 };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const SGR = { bold: "\x1b[1m", dim: "\x1b[2m", green: "\x1b[32m", red: "\x1b[31m", yellow: "\x1b[33m", reverse: "\x1b[7m", reset: "\x1b[0m" };
|
|
272
|
+
const paint = (color, style, text) => (color ? `${SGR[style]}${text}${SGR.reset}` : text);
|
|
273
|
+
|
|
274
|
+
const BAR_STYLE = { boarded: "green", denied: "red", error: "yellow" };
|
|
275
|
+
|
|
276
|
+
/** One board row, `width` wide at most. */
|
|
277
|
+
function rowLine(row, cols, { run, now, formatTime, color }) {
|
|
278
|
+
const cells = [fit(row.at !== null ? formatTime(row.at) : "", cols.time)];
|
|
279
|
+
if (cols.withSession) cells.push(fit(sessionText(row, run), cols.session));
|
|
280
|
+
cells.push(agentText(row, cols.agent));
|
|
281
|
+
cells.push(fit(row.model ?? "—", cols.model));
|
|
282
|
+
const status = fit(statusText(row), cols.status);
|
|
283
|
+
cells.push(BAR_STYLE[row.outcome] ? paint(color, BAR_STYLE[row.outcome], status) : status);
|
|
284
|
+
cells.push(fitRight(latencyText(row, now), cols.latency));
|
|
285
|
+
return cells.join(" ");
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function budgetFraction(self) {
|
|
289
|
+
const b = self?.budget ?? {};
|
|
290
|
+
const ratio = (used, limit) => {
|
|
291
|
+
const u = Number(used);
|
|
292
|
+
const l = Number(limit);
|
|
293
|
+
return Number.isFinite(u) && Number.isFinite(l) && l > 0 ? Math.min(1, Math.max(0, u / l)) : null;
|
|
294
|
+
};
|
|
295
|
+
if (b.period && !b.period.unknown) return ratio(b.period.used_microcents, b.period.limit_microcents);
|
|
296
|
+
if (b.cost) return ratio(b.cost.used_microcents, b.cost.limit_microcents);
|
|
297
|
+
if (b.tokens) return ratio(b.tokens.used, b.tokens.limit);
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function budgetLine(budget, width, { color, formatTime }) {
|
|
302
|
+
if (!budget) return "Budget checking…";
|
|
303
|
+
if (budget.kind === "stopped") {
|
|
304
|
+
return paint(color, "red", "REFUSING CALLS · its owner suspended this agent, or the kill switch is on");
|
|
305
|
+
}
|
|
306
|
+
if (budget.kind === "unavailable") return `Budget unavailable (${clean(budget.reason)})`;
|
|
307
|
+
const [label, value] = panelRows(budget.self)[0];
|
|
308
|
+
const fraction = budgetFraction(budget.self);
|
|
309
|
+
const barWidth = width >= 100 ? 24 : width >= 72 ? 16 : 8;
|
|
310
|
+
let bar = "";
|
|
311
|
+
if (fraction !== null) {
|
|
312
|
+
const filled = Math.round(fraction * barWidth);
|
|
313
|
+
const style = fraction >= 1 ? "red" : fraction >= 0.8 ? "yellow" : "green";
|
|
314
|
+
bar = `[${paint(color, style, "█".repeat(filled))}${"░".repeat(barWidth - filled)}] `;
|
|
315
|
+
}
|
|
316
|
+
const reached = limitReached(budget.self) ? ` · ${paint(color, "red", "LIMIT REACHED")}` : "";
|
|
317
|
+
const line = `${clean(label).padEnd(9)} ${bar}${clean(value)}${reached}`;
|
|
318
|
+
// When it was asked is the first thing to go when the line is too long.
|
|
319
|
+
const checked = budget.checkedAt ? ` · checked ${formatTime(budget.checkedAt)}` : "";
|
|
320
|
+
return visibleLength(line + checked) <= width ? line + checked : line;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Subscription mode: how much of Anthropic's 5-hour and 7-day allowance is used, as
|
|
324
|
+
// Claude Code last told the status line (cli/usage-window.mjs). Shown, never enforced.
|
|
325
|
+
function windowLine(window, now) {
|
|
326
|
+
const text = usageWindowText(window, { formatTime: (s) => resetTime(s, now) });
|
|
327
|
+
return text ? `${"Window".padEnd(9)} ${text}` : "";
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function feedText(feed, port) {
|
|
331
|
+
switch (feed?.state) {
|
|
332
|
+
case "live":
|
|
333
|
+
return "live";
|
|
334
|
+
case "connecting":
|
|
335
|
+
return "connecting…";
|
|
336
|
+
case "down":
|
|
337
|
+
return "not connected";
|
|
338
|
+
default:
|
|
339
|
+
return "";
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** The visible length of a line: what is left once our own SGR codes are removed. */
|
|
344
|
+
export function visibleLength(line) {
|
|
345
|
+
return line.replace(/\x1b\[[0-9;]*m/g, "").length;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Cuts a line to `width` visible columns, keeping our colour codes balanced. */
|
|
349
|
+
function clip(line, width) {
|
|
350
|
+
if (visibleLength(line) <= width) return line;
|
|
351
|
+
let out = "";
|
|
352
|
+
let shown = 0;
|
|
353
|
+
for (let i = 0; i < line.length && shown < width; ) {
|
|
354
|
+
const sgr = /^\x1b\[[0-9;]*m/.exec(line.slice(i));
|
|
355
|
+
if (sgr) {
|
|
356
|
+
out += sgr[0];
|
|
357
|
+
i += sgr[0].length;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
out += line[i];
|
|
361
|
+
shown += 1;
|
|
362
|
+
i += 1;
|
|
363
|
+
}
|
|
364
|
+
return out.includes("\x1b[") ? `${out}${SGR.reset}` : out;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* The whole board as `height` lines, none wider than `width`. Pure: the same state,
|
|
369
|
+
* size and clock give the same lines.
|
|
370
|
+
*/
|
|
371
|
+
/**
|
|
372
|
+
* The full-screen frame draw() writes: home, each board line, clear the rest.
|
|
373
|
+
*
|
|
374
|
+
* One column narrower than the window. A line that fills the last column leaves the
|
|
375
|
+
* cursor ON that column (the terminal's pending-wrap state), and the ESC[K after it
|
|
376
|
+
* erases from the cursor, so the line's last character vanished ("LATENC").
|
|
377
|
+
*/
|
|
378
|
+
export function screenFrame(state, { columns, rows, port, color = false, now, formatTime }) {
|
|
379
|
+
const lines = renderBoard(state, { width: Math.max(1, columns - 1), height: rows, port, color, now, formatTime });
|
|
380
|
+
return `\x1b[H${lines.map((l) => `${l}\x1b[K`).join("\r\n")}\x1b[J`;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export function renderBoard(state, { width, height, port, now = Date.now(), formatTime = localTime, color = false }) {
|
|
384
|
+
const w = Math.max(1, Math.floor(width));
|
|
385
|
+
const h = Math.max(1, Math.floor(height));
|
|
386
|
+
if (w < MIN_WIDTH || h < 6) {
|
|
387
|
+
const lines = [`Window too small (min ${MIN_WIDTH}×6)`];
|
|
388
|
+
while (lines.length < h) lines.push("");
|
|
389
|
+
return lines.slice(0, h).map((l) => clip(l, w));
|
|
390
|
+
}
|
|
391
|
+
const cols = columns(w);
|
|
392
|
+
const rows = state.rows;
|
|
393
|
+
const tally = { boarded: 0, denied: 0, error: 0, seen: 0 };
|
|
394
|
+
for (const r of rows) tally[r.outcome] += 1;
|
|
395
|
+
const counts = rows.length
|
|
396
|
+
? `${rows.length} call${rows.length === 1 ? "" : "s"}: ${tally.seen ? `${tally.seen} seen, ` : ""}${tally.boarded} boarded, ${tally.denied} denied${tally.error ? `, ${tally.error} error` : ""}`
|
|
397
|
+
: "no calls yet";
|
|
398
|
+
const lines = [
|
|
399
|
+
`${paint(color, "bold", "PassControl watch")} · sidecar :${port} · ${feedText(state.feed, port)} · ${counts}`,
|
|
400
|
+
budgetLine(state.budget, w, { color, formatTime }),
|
|
401
|
+
// Why the board is not live, on a line of its own so it is never cut off the end
|
|
402
|
+
// of the header. Older rows stay below it: they happened.
|
|
403
|
+
state.feed?.state === "down"
|
|
404
|
+
? paint(color, "yellow", clean(state.feed.message ?? `waiting for the sidecar on :${port}`))
|
|
405
|
+
: windowLine(state.window, now),
|
|
406
|
+
];
|
|
407
|
+
const header = ["TIME".padEnd(cols.time)];
|
|
408
|
+
if (cols.withSession) header.push("SESSION".padEnd(cols.session));
|
|
409
|
+
header.push("SUB-AGENT".padEnd(cols.agent), "MODEL".padEnd(cols.model), "STATUS".padEnd(cols.status), "LATENCY".padStart(cols.latency));
|
|
410
|
+
lines.push(paint(color, "dim", header.join(" ")));
|
|
411
|
+
|
|
412
|
+
const space = h - lines.length - 1;
|
|
413
|
+
if (rows.length === 0) {
|
|
414
|
+
lines.push(` Point an agent at http://127.0.0.1:${port}/api/v1/anthropic (or /openai); its calls appear here.`);
|
|
415
|
+
} else {
|
|
416
|
+
// Newest first: what just happened is what a person is looking for.
|
|
417
|
+
for (const row of rows.slice(-space).reverse()) {
|
|
418
|
+
lines.push(rowLine(row, cols, { run: state.run, now, formatTime, color }));
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
while (lines.length < h - 1) lines.push("");
|
|
422
|
+
lines.push(paint(color, "dim", "q quit · newest first · read-only · calls that skip this sidecar are not shown"));
|
|
423
|
+
return lines.slice(0, h).map((line) => clip(line, w).trimEnd());
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** A finished call as one plain line, for a board whose output is not a terminal. */
|
|
427
|
+
export function plainLine(row, { run, formatTime = localTime }) {
|
|
428
|
+
const cols = columns(100);
|
|
429
|
+
return rowLine(row, cols, { run, now: Date.now(), formatTime, color: false }).trimEnd();
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// ── The budget, held in memory ───────────────────────────────────────────────
|
|
433
|
+
|
|
434
|
+
/** GET /api/v1/self through the sidecar, which holds a warm visa. Never throws, never writes. */
|
|
435
|
+
export async function fetchBudget({ port, host = "127.0.0.1", fetch: fetchImpl = globalThis.fetch, now = Date.now, timeoutMs = BUDGET_TIMEOUT_MS }) {
|
|
436
|
+
const controller = new AbortController();
|
|
437
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
438
|
+
try {
|
|
439
|
+
let response;
|
|
440
|
+
try {
|
|
441
|
+
response = await fetchImpl(`http://${host}:${port}/api/v1/self`, { headers: { accept: "application/json" }, signal: controller.signal });
|
|
442
|
+
} catch {
|
|
443
|
+
return { kind: "unavailable", reason: controller.signal.aborted ? "no answer from the sidecar" : "sidecar not running" };
|
|
444
|
+
}
|
|
445
|
+
// The gateway's one opaque refusal for a suspended agent and a kill switch.
|
|
446
|
+
if (response.status === 403) return { kind: "stopped" };
|
|
447
|
+
if (response.status === 429) return { kind: "unavailable", reason: "asked too often; trying again shortly" };
|
|
448
|
+
if (!response.ok) return { kind: "unavailable", reason: `HTTP ${response.status}` };
|
|
449
|
+
const self = await response.json().catch(() => null);
|
|
450
|
+
if (typeof self?.budget !== "object" || self.budget === null) return { kind: "unavailable", reason: "unreadable answer" };
|
|
451
|
+
return { kind: "ok", self, checkedAt: now() };
|
|
452
|
+
} catch {
|
|
453
|
+
return { kind: "unavailable", reason: "unavailable" };
|
|
454
|
+
} finally {
|
|
455
|
+
clearTimeout(timer);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// ── The terminal ─────────────────────────────────────────────────────────────
|
|
460
|
+
|
|
461
|
+
const ENTER = "\x1b[?1049h\x1b[?25l";
|
|
462
|
+
export const LEAVE = "\x1b[?25h\x1b[?1049l";
|
|
463
|
+
|
|
464
|
+
function downMessage(error, port) {
|
|
465
|
+
switch (error.kind) {
|
|
466
|
+
case "unreachable":
|
|
467
|
+
return `no sidecar on :${port} yet · start one with: passcontrol sidecar --port ${port}`;
|
|
468
|
+
case "closed":
|
|
469
|
+
return `the sidecar on :${port} stopped · waiting for it`;
|
|
470
|
+
case "off":
|
|
471
|
+
return "this sidecar is bound off loopback, so it serves no watch feed";
|
|
472
|
+
case "refused":
|
|
473
|
+
return "the sidecar refused the feed request";
|
|
474
|
+
case "busy":
|
|
475
|
+
return "too many boards are already watching this sidecar";
|
|
476
|
+
default:
|
|
477
|
+
return `whatever answers on :${port} serves no watch feed · a sidecar started before \`watch\` existed needs a restart`;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Runs the board until q, Ctrl-C or a signal. Resolves the exit code. Full-screen
|
|
483
|
+
* on a terminal; one line per finished call otherwise.
|
|
484
|
+
*/
|
|
485
|
+
export function runWatch({
|
|
486
|
+
port,
|
|
487
|
+
host = "127.0.0.1",
|
|
488
|
+
out = process.stdout,
|
|
489
|
+
input = process.stdin,
|
|
490
|
+
signals = process,
|
|
491
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
492
|
+
budgetEveryMs = BUDGET_EVERY_MS,
|
|
493
|
+
color = !process.env.NO_COLOR,
|
|
494
|
+
}) {
|
|
495
|
+
const tty = Boolean(out.isTTY);
|
|
496
|
+
const state = createBoardState();
|
|
497
|
+
const timers = new Set();
|
|
498
|
+
let feed = null;
|
|
499
|
+
let attempt = 0;
|
|
500
|
+
let finished = false;
|
|
501
|
+
let drawTimer = null;
|
|
502
|
+
let resolveExit;
|
|
503
|
+
const exited = new Promise((resolve) => (resolveExit = resolve));
|
|
504
|
+
const printed = new Set();
|
|
505
|
+
let lastBudgetText = null;
|
|
506
|
+
let lastFeedText = null;
|
|
507
|
+
|
|
508
|
+
const later = (fn, ms) => {
|
|
509
|
+
const t = setTimeout(() => {
|
|
510
|
+
timers.delete(t);
|
|
511
|
+
fn();
|
|
512
|
+
}, ms);
|
|
513
|
+
timers.add(t);
|
|
514
|
+
return t;
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
function draw() {
|
|
518
|
+
drawTimer = null;
|
|
519
|
+
if (finished) return;
|
|
520
|
+
if (tty) {
|
|
521
|
+
out.write(screenFrame(state, { columns: out.columns || 80, rows: out.rows || 24, port, color }));
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
const feedLine = state.feed?.state === "down" ? clean(state.feed.message ?? "") : state.feed?.state === "live" ? "connected" : null;
|
|
525
|
+
if (feedLine && feedLine !== lastFeedText) {
|
|
526
|
+
lastFeedText = feedLine;
|
|
527
|
+
out.write(`${feedLine}\n`);
|
|
528
|
+
}
|
|
529
|
+
const budget = budgetLine(state.budget, 100, { color: false, formatTime: localTime });
|
|
530
|
+
if (state.budget && budget !== lastBudgetText) {
|
|
531
|
+
lastBudgetText = budget;
|
|
532
|
+
out.write(`${budget}\n`);
|
|
533
|
+
}
|
|
534
|
+
for (const row of state.rows) {
|
|
535
|
+
const key = `${state.run}:${row.seq}`;
|
|
536
|
+
if (row.ms === null || printed.has(key)) continue;
|
|
537
|
+
printed.add(key);
|
|
538
|
+
out.write(`${plainLine(row, { run: state.run })}\n`);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// A sub-agent fan-out arrives as a burst: one redraw per burst, not per event.
|
|
543
|
+
const schedule = () => {
|
|
544
|
+
if (!drawTimer && !finished) drawTimer = later(draw, REDRAW_MS);
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
function connect() {
|
|
548
|
+
if (finished) return;
|
|
549
|
+
feed = openFeed({
|
|
550
|
+
port,
|
|
551
|
+
host,
|
|
552
|
+
onEvent: (event) => {
|
|
553
|
+
if (event.type === "hello") attempt = 0;
|
|
554
|
+
applyEvent(state, event);
|
|
555
|
+
schedule();
|
|
556
|
+
},
|
|
557
|
+
onError: (error) => {
|
|
558
|
+
if (finished) return;
|
|
559
|
+
state.feed = { state: "down", message: downMessage(error, port) };
|
|
560
|
+
schedule();
|
|
561
|
+
later(connect, retryDelay(error, attempt++));
|
|
562
|
+
},
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
async function pollBudget() {
|
|
567
|
+
if (finished) return;
|
|
568
|
+
state.budget = await fetchBudget({ port, host, fetch: fetchImpl });
|
|
569
|
+
schedule();
|
|
570
|
+
if (!finished) later(pollBudget, budgetEveryMs);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const onResize = () => schedule();
|
|
574
|
+
const onKey = (data) => {
|
|
575
|
+
const text = String(data);
|
|
576
|
+
if (text.includes("\x03") || text.includes("q") || text.includes("Q")) finish(0);
|
|
577
|
+
};
|
|
578
|
+
const onSignal = () => finish(0);
|
|
579
|
+
const onExit = () => restore();
|
|
580
|
+
const onCrash = (error) => {
|
|
581
|
+
restore();
|
|
582
|
+
process.stderr.write(`passcontrol watch: ${error?.stack ?? error}\n`);
|
|
583
|
+
process.exit(1);
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
let restored = false;
|
|
587
|
+
function restore() {
|
|
588
|
+
if (restored || !tty) return;
|
|
589
|
+
restored = true;
|
|
590
|
+
try {
|
|
591
|
+
input.setRawMode?.(false);
|
|
592
|
+
} catch {
|
|
593
|
+
// Not a terminal any more.
|
|
594
|
+
}
|
|
595
|
+
out.write(LEAVE);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
function finish(code) {
|
|
599
|
+
if (finished) return;
|
|
600
|
+
finished = true;
|
|
601
|
+
for (const t of timers) clearTimeout(t);
|
|
602
|
+
timers.clear();
|
|
603
|
+
clearInterval(tick);
|
|
604
|
+
feed?.destroy();
|
|
605
|
+
restore();
|
|
606
|
+
out.off?.("resize", onResize);
|
|
607
|
+
input.off?.("data", onKey);
|
|
608
|
+
input.pause?.();
|
|
609
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) signals.off?.(signal, onSignal);
|
|
610
|
+
signals.off?.("exit", onExit);
|
|
611
|
+
signals.off?.("uncaughtException", onCrash);
|
|
612
|
+
resolveExit(code);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) signals.on?.(signal, onSignal);
|
|
616
|
+
signals.on?.("exit", onExit);
|
|
617
|
+
signals.on?.("uncaughtException", onCrash);
|
|
618
|
+
if (tty) {
|
|
619
|
+
out.write(ENTER);
|
|
620
|
+
try {
|
|
621
|
+
input.setRawMode?.(true);
|
|
622
|
+
} catch {
|
|
623
|
+
// Input is not a terminal: q will not reach us, Ctrl-C still does as a signal.
|
|
624
|
+
}
|
|
625
|
+
input.resume?.();
|
|
626
|
+
input.on?.("data", onKey);
|
|
627
|
+
// Windows has no SIGWINCH; the stream's own event works everywhere.
|
|
628
|
+
out.on?.("resize", onResize);
|
|
629
|
+
} else {
|
|
630
|
+
out.write(`PassControl watch · sidecar :${port} · one line per finished call\n`);
|
|
631
|
+
}
|
|
632
|
+
// Streaming rows show their time so far, and "checked" ages: redraw each second.
|
|
633
|
+
const tick = setInterval(() => {
|
|
634
|
+
if (tty && state.rows.some((r) => r.ms === null)) schedule();
|
|
635
|
+
}, 1000);
|
|
636
|
+
draw();
|
|
637
|
+
connect();
|
|
638
|
+
pollBudget();
|
|
639
|
+
return exited;
|
|
640
|
+
}
|
package/package.json
CHANGED
package/sdk/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { PassControl } from "./passcontrol.js";
|
|
2
|
-
export type { PassControlOptions, ProviderId } from "./passcontrol.js";
|
|
2
|
+
export type { PassControlOptions, PassControlDelegationOptions, DelegateOptions, ProviderId } from "./passcontrol.js";
|
|
3
|
+
export { createDelegationLink, checkDelegationChain, verifyReceiptDelegation, generateWorkerKey, delegationChainHash, DELEGATION_TYP, } from "../cli/delegation.mjs";
|
|
3
4
|
export { ControlClient, ControlApiError } from "./control.js";
|
|
4
5
|
export type { ControlClientOptions, WriteOpts } from "./control.js";
|
|
5
6
|
export { verifyReceipt, verifyAgentToken, verifyStatement, verifyInclusion, matchesIssuer, RECEIPT_TYP, AGENT_TOKEN_TYP, STATEMENT_TYP, SUPPORTED_VER, STATEMENT_SUPPORTED_VER, } from "./verify.js";
|
package/sdk/index.js
CHANGED
|
@@ -16,5 +16,8 @@
|
|
|
16
16
|
// Self-hosting and want a flat copy? This folder is self-contained — vendor the
|
|
17
17
|
// whole `sdk/` directory; it only needs @noble/curves + the platform fetch/crypto.
|
|
18
18
|
export { PassControl } from "./passcontrol.js";
|
|
19
|
+
// Signed delegation (Bet D): sign a link for a worker, and check a worker's receipt
|
|
20
|
+
// against the chain that authorised it.
|
|
21
|
+
export { createDelegationLink, checkDelegationChain, verifyReceiptDelegation, generateWorkerKey, delegationChainHash, DELEGATION_TYP, } from "../cli/delegation.mjs";
|
|
19
22
|
export { ControlClient, ControlApiError } from "./control.js";
|
|
20
23
|
export { verifyReceipt, verifyAgentToken, verifyStatement, verifyInclusion, matchesIssuer, RECEIPT_TYP, AGENT_TOKEN_TYP, STATEMENT_TYP, SUPPORTED_VER, STATEMENT_SUPPORTED_VER, } from "./verify.js";
|