agentmast 0.0.0-stage → 0.1.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.
Files changed (38) hide show
  1. package/dist/bin.js +153 -0
  2. package/dist/bot-PIWTZVU6.js +215 -0
  3. package/dist/bus-NKXT3JWW.js +168 -0
  4. package/dist/chunk-FRKDGPVA.js +216 -0
  5. package/dist/chunk-IU75ISXR.js +67 -0
  6. package/dist/chunk-LOCISTVR.js +125 -0
  7. package/dist/chunk-QCSXSHRA.js +16 -0
  8. package/dist/chunk-TV3CPBRC.js +62 -0
  9. package/dist/chunk-VDPOIHPJ.js +40 -0
  10. package/dist/chunk-WBDMHW7H.js +153 -0
  11. package/dist/config-OOQXKXZZ.js +12 -0
  12. package/dist/hook-transport-RLSLV56I.js +11 -0
  13. package/dist/hook.js +11 -0
  14. package/dist/hooks-AALI75O7.js +231 -0
  15. package/dist/local-state-4SIAMX2F.js +17 -0
  16. package/dist/pairing-SAMT2H37.js +119 -0
  17. package/dist/replay-4LHZWBSJ.js +81 -0
  18. package/dist/server-XMPT35QI.js +487 -0
  19. package/dist/video-RJZII4N6.js +153 -0
  20. package/dist/web/assets/index-CMw6GB5R.css +1 -0
  21. package/dist/web/assets/index-DXwpAjuO.js +48 -0
  22. package/dist/web/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  23. package/dist/web/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  24. package/dist/web/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  25. package/dist/web/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  26. package/dist/web/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  27. package/dist/web/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  28. package/dist/web/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  29. package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  30. package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  31. package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  32. package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  33. package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  34. package/dist/web/index.html +14 -0
  35. package/dist/web/licenses/Inter.txt +93 -0
  36. package/dist/web/licenses/JetBrains-Mono.txt +93 -0
  37. package/package.json +34 -4
  38. package/README.md +0 -3
@@ -0,0 +1,487 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ DEFAULT_APPROVAL_TIMEOUT_SEC,
4
+ HOOK_APPROVAL_WAIT_MS,
5
+ MAX_APPROVAL_TIMEOUT_SEC
6
+ } from "./chunk-QCSXSHRA.js";
7
+ import {
8
+ MAX_APPROVAL_REPLY_LENGTH,
9
+ TOKEN_FIELDS
10
+ } from "./chunk-LOCISTVR.js";
11
+
12
+ // src/daemon/server.ts
13
+ import { createReadStream, existsSync, statSync } from "fs";
14
+ import { createServer } from "http";
15
+ import { extname as extname2, join, normalize } from "path";
16
+ import { randomUUID, timingSafeEqual } from "crypto";
17
+ import { WebSocketServer } from "ws";
18
+
19
+ // src/tokens/transcripts.ts
20
+ import { constants } from "fs";
21
+ import { open } from "fs/promises";
22
+ import { extname, isAbsolute } from "path";
23
+
24
+ // src/tokens/usage.ts
25
+ function object(value) {
26
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
27
+ }
28
+ function count(value) {
29
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
30
+ }
31
+ function tokenCount(input, output, cacheRead, cacheCreation) {
32
+ const values = [input, output, cacheRead, cacheCreation];
33
+ const usage = {};
34
+ TOKEN_FIELDS.forEach((field, i) => {
35
+ const value = count(values[i]);
36
+ if (value !== void 0) usage[field] = value;
37
+ });
38
+ return usage;
39
+ }
40
+ function createUsageReader(kind) {
41
+ const messages = /* @__PURE__ */ new Map();
42
+ const totals = {};
43
+ const contributors = { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 };
44
+ let codexUsage = {};
45
+ return {
46
+ consume(line) {
47
+ let row;
48
+ try {
49
+ row = object(JSON.parse(line));
50
+ } catch {
51
+ return;
52
+ }
53
+ if (kind === "codex") {
54
+ if (row?.type !== "event_msg") return;
55
+ const event = object(row.payload);
56
+ if (event?.type !== "token_count") return;
57
+ const native2 = object(object(event.info)?.total_token_usage);
58
+ if (!native2) return;
59
+ const reportedInput = count(native2.input_tokens);
60
+ const cacheRead = count(native2.cached_input_tokens);
61
+ const cacheWrite = count(native2.cache_write_input_tokens);
62
+ const input = reportedInput === void 0 ? void 0 : reportedInput - (cacheRead ?? 0) - (cacheWrite ?? 0);
63
+ if (input !== void 0 && input < 0) return;
64
+ const next2 = tokenCount(input, native2.output_tokens, cacheRead, cacheWrite);
65
+ if (Object.keys(next2).length) codexUsage = next2;
66
+ return;
67
+ }
68
+ if (row?.type !== "assistant" || row.isSidechain === true) return;
69
+ const message = object(row.message);
70
+ const native = object(message?.usage);
71
+ if (!native || typeof message?.id !== "string" || !message.id || message.model === "<synthetic>") return;
72
+ const next = tokenCount(native.input_tokens, native.output_tokens, native.cache_read_input_tokens, native.cache_creation_input_tokens);
73
+ if (!Object.keys(next).length) return;
74
+ const key = JSON.stringify([message.id, typeof row.requestId === "string" ? row.requestId : null]);
75
+ const previous = messages.get(key);
76
+ messages.set(key, next);
77
+ for (const field of TOKEN_FIELDS) {
78
+ const before = previous?.[field];
79
+ const after = next[field];
80
+ contributors[field] += Number(after !== void 0) - Number(before !== void 0);
81
+ if (contributors[field]) totals[field] = (totals[field] ?? 0) + (after ?? 0) - (before ?? 0);
82
+ else delete totals[field];
83
+ }
84
+ },
85
+ totals() {
86
+ return kind === "codex" ? { ...codexUsage } : { ...totals };
87
+ }
88
+ };
89
+ }
90
+
91
+ // src/tokens/transcripts.ts
92
+ var READ_SIZE = 256 * 1024;
93
+ var CHECKPOINT_SIZE = 128;
94
+ var MAX_LINE_SIZE = 16 * 1024 * 1024;
95
+ var POLL_INTERVAL_MS = 1e3;
96
+ var END_GRACE_MS = 1e4;
97
+ var TRANSCRIPT_IDLE_MS = 30 * 6e4;
98
+ var TranscriptCursor = class {
99
+ constructor(kind, path) {
100
+ this.kind = kind;
101
+ this.path = path;
102
+ this.reader = createUsageReader(kind);
103
+ }
104
+ kind;
105
+ path;
106
+ offset = 0;
107
+ fileId;
108
+ mtime;
109
+ checkpoint = Buffer.alloc(0);
110
+ fragments = [];
111
+ lineSize = 0;
112
+ reader;
113
+ async read() {
114
+ const file = await open(this.path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0));
115
+ try {
116
+ const stat = await file.stat();
117
+ if (!stat.isFile()) return;
118
+ const fileId = `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
119
+ let rewritten = fileId !== this.fileId || stat.size < this.offset;
120
+ if (!rewritten && this.checkpoint.length && (stat.size !== this.offset || stat.mtimeMs !== this.mtime)) {
121
+ if (stat.size === this.offset) rewritten = true;
122
+ else {
123
+ const previous = Buffer.allocUnsafe(this.checkpoint.length);
124
+ const { bytesRead } = await file.read(previous, 0, previous.length, this.offset - previous.length);
125
+ rewritten = bytesRead !== previous.length || !previous.equals(this.checkpoint);
126
+ }
127
+ }
128
+ this.mtime = stat.mtimeMs;
129
+ if (rewritten) {
130
+ this.offset = 0;
131
+ this.fileId = fileId;
132
+ this.checkpoint = Buffer.alloc(0);
133
+ this.lineSize = 0;
134
+ this.fragments = [];
135
+ this.reader = createUsageReader(this.kind);
136
+ }
137
+ if (this.offset === stat.size) return this.reader.totals();
138
+ const bytes = Buffer.allocUnsafe(READ_SIZE);
139
+ while (this.offset < stat.size) {
140
+ const length = Math.min(bytes.length, stat.size - this.offset);
141
+ const { bytesRead } = await file.read(bytes, 0, length, this.offset);
142
+ if (!bytesRead) break;
143
+ this.offset += bytesRead;
144
+ const chunk = bytes.subarray(0, bytesRead);
145
+ this.consume(chunk);
146
+ this.checkpoint = Buffer.from(chunk.subarray(-CHECKPOINT_SIZE));
147
+ }
148
+ return this.reader.totals();
149
+ } finally {
150
+ await file.close();
151
+ }
152
+ }
153
+ consume(bytes) {
154
+ let start = 0;
155
+ for (let end = bytes.indexOf(10); end !== -1; end = bytes.indexOf(10, start)) {
156
+ const line = bytes.subarray(start, end);
157
+ if (this.lineSize + line.length <= MAX_LINE_SIZE) {
158
+ const complete = this.fragments.length ? Buffer.concat([...this.fragments, line]) : line;
159
+ this.reader.consume(complete.toString("utf8"));
160
+ }
161
+ this.fragments = [];
162
+ this.lineSize = 0;
163
+ start = end + 1;
164
+ }
165
+ if (start === bytes.length || this.lineSize > MAX_LINE_SIZE) return;
166
+ const tail = bytes.subarray(start);
167
+ this.lineSize += tail.length;
168
+ if (this.lineSize <= MAX_LINE_SIZE) this.fragments.push(Buffer.from(tail));
169
+ else this.fragments = [];
170
+ }
171
+ };
172
+ var TranscriptUsage = class {
173
+ constructor(publish) {
174
+ this.publish = publish;
175
+ }
176
+ publish;
177
+ sources = /* @__PURE__ */ new Map();
178
+ timer;
179
+ track(event, path) {
180
+ const { kind, type, sessionId } = event;
181
+ if (kind !== "claude-code" && kind !== "codex") return;
182
+ const now = Date.now();
183
+ let source = this.sources.get(sessionId);
184
+ if (typeof path === "string" && isAbsolute(path) && extname(path).toLowerCase() === ".jsonl" && source?.path !== path) {
185
+ source = { path, kind, cursor: new TranscriptCursor(kind, path), published: source?.published, lastActivityAt: now };
186
+ this.sources.set(sessionId, source);
187
+ }
188
+ if (!source) return;
189
+ source.lastActivityAt = now;
190
+ if (type === "session_end") source.endedAt = now;
191
+ else if (type === "session_start" || type === "prompt") delete source.endedAt;
192
+ this.timer ??= setInterval(() => this.poll(), POLL_INTERVAL_MS).unref();
193
+ if (type === "session_start" || type === "stop" || type === "session_end" || !source.published) void this.sample(sessionId, source);
194
+ }
195
+ close() {
196
+ clearInterval(this.timer);
197
+ this.timer = void 0;
198
+ this.sources.clear();
199
+ }
200
+ poll() {
201
+ const now = Date.now();
202
+ for (const [id, source] of this.sources) {
203
+ const expiresAt = source.endedAt === void 0 ? source.lastActivityAt + TRANSCRIPT_IDLE_MS : source.endedAt + END_GRACE_MS;
204
+ if (expiresAt <= now) this.sources.delete(id);
205
+ else void this.sample(id, source);
206
+ }
207
+ if (this.sources.size === 0) this.close();
208
+ }
209
+ async sample(sessionId, source) {
210
+ if (source.reading) return;
211
+ source.reading = true;
212
+ try {
213
+ const usage = await source.cursor.read();
214
+ if (!usage || this.sources.get(sessionId) !== source) return;
215
+ if (source.published && !TOKEN_FIELDS.some((field) => usage[field] !== source.published?.[field])) return;
216
+ source.published = usage;
217
+ source.lastActivityAt = Date.now();
218
+ this.publish({ sessionId, kind: source.kind, type: "usage", usageMode: "total", usage, ts: Date.now() });
219
+ } catch {
220
+ } finally {
221
+ source.reading = false;
222
+ }
223
+ }
224
+ };
225
+
226
+ // src/daemon/zcode-approvals.ts
227
+ var ZCodeApprovals = class {
228
+ approvals = /* @__PURE__ */ new Map();
229
+ timer = setInterval(() => this.expire(), 6e4).unref();
230
+ key(sessionId, payload) {
231
+ if (!payload || typeof payload !== "object") return;
232
+ const { id, fingerprint } = payload;
233
+ if (typeof id !== "string" || !id.trim() || id.length > 512) return;
234
+ if (typeof fingerprint !== "string" || !/^[\da-f]{64}$/.test(fingerprint)) return;
235
+ return JSON.stringify([sessionId, id, fingerprint]);
236
+ }
237
+ getOrCreate(key, create) {
238
+ const now = Date.now();
239
+ const current = this.approvals.get(key);
240
+ if (current && (current.expiresAt === void 0 || current.expiresAt > now)) return current;
241
+ const entry = create();
242
+ this.approvals.set(key, entry);
243
+ void entry.decision.then(() => {
244
+ entry.expiresAt = Date.now() + HOOK_APPROVAL_WAIT_MS;
245
+ });
246
+ return entry;
247
+ }
248
+ close() {
249
+ clearInterval(this.timer);
250
+ this.approvals.clear();
251
+ }
252
+ expire() {
253
+ const now = Date.now();
254
+ for (const [key, approval] of this.approvals) {
255
+ if (approval.expiresAt !== void 0 && approval.expiresAt <= now) this.approvals.delete(key);
256
+ }
257
+ }
258
+ };
259
+
260
+ // src/daemon/server.ts
261
+ var MIME = {
262
+ ".html": "text/html; charset=utf-8",
263
+ ".js": "text/javascript; charset=utf-8",
264
+ ".css": "text/css; charset=utf-8",
265
+ ".svg": "image/svg+xml",
266
+ ".png": "image/png",
267
+ ".ico": "image/x-icon",
268
+ ".json": "application/json",
269
+ ".woff2": "font/woff2"
270
+ };
271
+ function isAllowedOrigin(origin, port) {
272
+ if (!origin) return false;
273
+ try {
274
+ const url = new URL(origin);
275
+ return url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) && url.port === String(port) && url.origin === origin;
276
+ } catch {
277
+ return false;
278
+ }
279
+ }
280
+ function isAllowedHost(host, port) {
281
+ return [`localhost:${port}`, `127.0.0.1:${port}`, `[::1]:${port}`].includes(host ?? "");
282
+ }
283
+ function validToken(value, expected) {
284
+ if (typeof value !== "string" || !expected) return false;
285
+ const a = Buffer.from(value), b = Buffer.from(expected);
286
+ return a.length === b.length && timingSafeEqual(a, b);
287
+ }
288
+ function send(res, status, body) {
289
+ if (res.writableEnded || res.destroyed) return;
290
+ if (body === void 0) {
291
+ res.writeHead(status).end();
292
+ return;
293
+ }
294
+ res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
295
+ }
296
+ async function readJson(req, limit = 1e6) {
297
+ const chunks = [];
298
+ let size = 0;
299
+ for await (const c of req) {
300
+ size += c.length;
301
+ if (size > limit) throw new Error("payload too large");
302
+ chunks.push(c);
303
+ }
304
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
305
+ }
306
+ function readDecision(approvalId, value) {
307
+ if (typeof approvalId !== "string" || !approvalId || !value || typeof value !== "object") return;
308
+ const { action, text } = value;
309
+ if (action === "approve" || action === "reject" || action === "defer") return { approvalId, action };
310
+ if (action === "reply" && typeof text === "string" && text.length <= MAX_APPROVAL_REPLY_LENGTH && text.trim()) {
311
+ return { approvalId, action, text: text.trim() };
312
+ }
313
+ }
314
+ function startServer(opts) {
315
+ const { bus } = opts;
316
+ const transcripts = bus.mode === "live" ? new TranscriptUsage((event) => bus.ingest(event)) : void 0;
317
+ const zcodeApprovals = bus.mode === "live" ? new ZCodeApprovals() : void 0;
318
+ const approvalTimeoutSec = opts.approvalTimeoutSec ?? DEFAULT_APPROVAL_TIMEOUT_SEC;
319
+ if (!Number.isFinite(approvalTimeoutSec) || approvalTimeoutSec <= 0 || approvalTimeoutSec > MAX_APPROVAL_TIMEOUT_SEC) {
320
+ throw new Error(`Approval timeout must be greater than 0 and at most ${MAX_APPROVAL_TIMEOUT_SEC} seconds`);
321
+ }
322
+ const host = opts.host ?? "127.0.0.1";
323
+ let webClients = 0;
324
+ let sawFirstClient = false;
325
+ const server = createServer(async (req, res) => {
326
+ const port = server.address().port;
327
+ if (!isAllowedHost(req.headers.host, port)) return send(res, 421, { error: "host not allowed" });
328
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
329
+ const path = url.pathname;
330
+ if (path.startsWith("/api/")) {
331
+ const tokenAuth = validToken(req.headers["x-agentdeck-token"], opts.token);
332
+ const originAuth = isAllowedOrigin(req.headers.origin, port);
333
+ if (req.headers.origin && !originAuth) return send(res, 403, { error: "origin not allowed" });
334
+ if (req.method === "POST" && (path === "/api/events" || path === "/api/approvals" ? !tokenAuth : !originAuth)) return send(res, 403, { error: "authentication required" });
335
+ if (req.method === "POST" && !(req.headers["content-type"] ?? "").includes("application/json")) {
336
+ return send(res, 415, { error: "content-type must be application/json" });
337
+ }
338
+ try {
339
+ return await handleApi(req, res, path);
340
+ } catch (err) {
341
+ return send(res, 400, { error: err.message });
342
+ }
343
+ }
344
+ return serveStatic(res, path);
345
+ });
346
+ async function handleApi(req, res, path) {
347
+ if (req.method === "GET" && path === "/api/health") return send(res, 200, { ok: true, mode: bus.mode });
348
+ if (req.method === "GET" && path === "/api/state") return send(res, 200, bus.snapshot());
349
+ if (req.method === "GET" && path === "/api/tokens/datasets") return send(res, 200, bus.listDatasets());
350
+ if (req.method === "POST" && path === "/api/events") {
351
+ const { transcriptPath, ...ev } = await readJson(req);
352
+ if (!ev.sessionId || !ev.type) return send(res, 400, { error: "sessionId and type are required" });
353
+ const event = { ...ev, kind: ev.kind ?? "generic", ts: ev.ts ?? Date.now() };
354
+ bus.ingest(event);
355
+ transcripts?.track(event, transcriptPath);
356
+ return send(res, 202, { ok: true });
357
+ }
358
+ if (req.method === "POST" && path === "/api/approvals") {
359
+ const body = await readJson(req);
360
+ if (!body || typeof body.sessionId !== "string" || !body.sessionId || typeof body.summary !== "string" || !body.summary || typeof body.detail?.tool !== "string" || !body.detail.tool) return send(res, 400, { error: "invalid approval request" });
361
+ const { sessionId, summary, detail, tool } = body;
362
+ const title = typeof body.title === "string" ? body.title : void 0;
363
+ const cwd = typeof body.cwd === "string" ? body.cwd : void 0;
364
+ const origin = body.origin === "codex" || body.origin === "zcode" ? body.origin : void 0;
365
+ if (origin && bus.mode !== "live") return send(res, 204);
366
+ if (res.destroyed) return;
367
+ const key = origin === "zcode" ? zcodeApprovals?.key(sessionId, body.zcodeTool) : void 0;
368
+ if (origin === "zcode" && !key) {
369
+ bus.ingest({ sessionId, kind: "zcode", ts: Date.now(), type: "notify", notifyKind: "permission_prompt", title, cwd, tool });
370
+ return send(res, 204);
371
+ }
372
+ const timeoutSec = typeof body.timeoutSec === "number" && Number.isFinite(body.timeoutSec) && body.timeoutSec > 0 ? Math.min(approvalTimeoutSec, body.timeoutSec) : approvalTimeoutSec;
373
+ const create = () => {
374
+ const id = randomUUID();
375
+ const decision2 = bus.requestApproval({
376
+ id,
377
+ sessionId,
378
+ summary,
379
+ detail,
380
+ origin,
381
+ timeoutSec,
382
+ title,
383
+ cwd,
384
+ risk: origin ? "unrated" : body.risk === "low" || body.risk === "high" ? body.risk : "medium",
385
+ turnId: typeof body.turnId === "string" ? body.turnId : void 0
386
+ }, tool);
387
+ return { id, decision: decision2, waiters: 0 };
388
+ };
389
+ const approval = key && zcodeApprovals ? zcodeApprovals.getOrCreate(key, create) : create();
390
+ approval.waiters++;
391
+ res.once("close", () => {
392
+ approval.waiters--;
393
+ if (!res.writableEnded && approval.waiters === 0) {
394
+ bus.decide({ approvalId: approval.id, action: "reject", by: "cancelled" });
395
+ }
396
+ });
397
+ const decision = await approval.decision;
398
+ if (decision.action === "defer" || decision.by === "timeout" || decision.by === "session_end" || decision.by === "cancelled") {
399
+ return send(res, 204);
400
+ }
401
+ return send(res, 200, decision);
402
+ }
403
+ const m = path.match(/^\/api\/approvals\/([\w-]+)\/decide$/);
404
+ if (req.method === "POST" && m) {
405
+ const decision = readDecision(m[1], await readJson(req));
406
+ if (!decision) return send(res, 400, { error: "invalid decision" });
407
+ const ok = bus.decide({ ...decision, by: "web" });
408
+ return send(res, ok ? 200 : 404, ok ? { ok } : { error: "approval not found or already handled" });
409
+ }
410
+ return send(res, 404, { error: "not found" });
411
+ }
412
+ function serveStatic(res, path) {
413
+ const dir = opts.webDir;
414
+ if (!dir || !existsSync(join(dir, "index.html"))) {
415
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
416
+ return res.end("AgentDeck daemon is running. Web UI not built \u2014 run `npm run build`, or use the Vite dev server.");
417
+ }
418
+ const safe = normalize(decodeURIComponent(path)).replace(/^(\.\.[/\\])+/, "");
419
+ let file = join(dir, safe);
420
+ if (!file.startsWith(dir) || !existsSync(file) || statSync(file).isDirectory()) file = join(dir, "index.html");
421
+ res.writeHead(200, { "content-type": MIME[extname2(file)] ?? "application/octet-stream" });
422
+ createReadStream(file).pipe(res);
423
+ }
424
+ const wss = new WebSocketServer({ noServer: true });
425
+ server.on("upgrade", (req, socket, head) => {
426
+ const port = server.address().port;
427
+ const origin = isAllowedOrigin(req.headers.origin, port);
428
+ const token = validToken(req.headers["x-agentdeck-token"], opts.token);
429
+ if (!isAllowedHost(req.headers.host, port) || req.url !== "/ws" || req.headers.origin && !origin || !origin && !token) {
430
+ socket.write("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
431
+ socket.destroy();
432
+ return;
433
+ }
434
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req, origin ? "web" : "pty"));
435
+ });
436
+ wss.on("connection", (ws, _req, role) => {
437
+ webClients++;
438
+ ws.send(JSON.stringify(bus.snapshot()));
439
+ for (const ds of bus.listDatasets()) ws.send(JSON.stringify({ type: "token_dataset", dataset: ds }));
440
+ const unsub = bus.subscribe((msg) => {
441
+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg));
442
+ });
443
+ ws.on("message", (raw) => {
444
+ let msg;
445
+ try {
446
+ msg = JSON.parse(String(raw));
447
+ } catch {
448
+ return;
449
+ }
450
+ if (role !== "web" || !msg) return;
451
+ if (msg.type === "decide") {
452
+ const decision = readDecision(msg.decision?.approvalId, msg.decision);
453
+ if (!decision) return;
454
+ const by = bus.mode === "demo" && msg.source === "phone_mock" ? "telegram" : "web";
455
+ if (!bus.decide({ ...decision, by })) ws.send(JSON.stringify({ type: "toast", text: "This approval is no longer pending." }));
456
+ }
457
+ if (msg.type === "demo_restart" && bus.mode === "demo") opts.onClientMessage?.(msg, ws);
458
+ });
459
+ ws.on("close", () => {
460
+ webClients--;
461
+ unsub();
462
+ });
463
+ if (!sawFirstClient) {
464
+ sawFirstClient = true;
465
+ opts.onFirstWebClient?.();
466
+ }
467
+ });
468
+ return new Promise((resolve, reject) => {
469
+ server.once("error", reject);
470
+ server.listen(opts.port, host, () => {
471
+ const port = server.address().port;
472
+ resolve({
473
+ url: `http://${host}:${port}`,
474
+ close: () => {
475
+ zcodeApprovals?.close();
476
+ transcripts?.close();
477
+ wss.close();
478
+ server.close();
479
+ },
480
+ clients: () => webClients
481
+ });
482
+ });
483
+ });
484
+ }
485
+ export {
486
+ startServer
487
+ };
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/scenarios/datasets.ts
4
+ var RATES = { input: 3, output: 15, cacheRead: 0.3, cacheCreation: 3.75 };
5
+ function simulatedVariant(id, label, usageAt) {
6
+ const totals = { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 };
7
+ const samples = [{ t: 0, cumulative: 0 }];
8
+ let costUsd = 0;
9
+ for (let turn = 0; turn < 24; turn++) {
10
+ const jitter = 1 + 0.12 * Math.sin(turn * 1.7);
11
+ const usage = usageAt(turn);
12
+ for (const field of Object.keys(RATES)) {
13
+ const count = Math.round(usage[field] * jitter);
14
+ totals[field] += count;
15
+ costUsd += count * RATES[field] / 1e6;
16
+ }
17
+ samples.push({ t: (turn + 1) * 25, cumulative: costUsd });
18
+ }
19
+ return { id, label, samples, totals: { ...totals, costUsd } };
20
+ }
21
+ function simulatedRefactorDataset() {
22
+ const baseline = simulatedVariant("baseline", "Full context", (turn) => ({
23
+ input: 14e3 + 3500 * turn,
24
+ output: 720,
25
+ cacheRead: 12e3 + 3400 * turn,
26
+ cacheCreation: 4300
27
+ }));
28
+ const trimmed = simulatedVariant("trimmed", "Trimmed", (turn) => ({
29
+ input: 3100 + 130 * turn,
30
+ output: 680,
31
+ cacheRead: 4800 + 360 * turn,
32
+ cacheCreation: 1400
33
+ }));
34
+ return {
35
+ id: "sim-refactor",
36
+ task: "Refactor billing module + add tests",
37
+ model: "Claude Sonnet",
38
+ metric: "cost_usd",
39
+ limitBudget: Math.ceil(baseline.totals.costUsd / 0.88 * 100) / 100,
40
+ measured: false,
41
+ variants: [baseline, trimmed]
42
+ };
43
+ }
44
+
45
+ // src/scenarios/video.ts
46
+ var sessions = [
47
+ { id: "s1", kind: "claude-code", title: "api-refactor", cwd: "~/acme/api" },
48
+ { id: "s2", kind: "claude-code", title: "billing-tests", cwd: "~/acme/billing" },
49
+ { id: "s3", kind: "codex", title: "web-dashboard", cwd: "~/acme/web" },
50
+ { id: "s4", kind: "claude-code", title: "docs-i18n", cwd: "~/acme/docs" }
51
+ ];
52
+ var actions = {
53
+ s1: [
54
+ ["Read", { file_path: "src/routes/orders.ts" }],
55
+ ["Grep", { pattern: "legacyAuth(" }],
56
+ ["Edit", { file_path: "src/routes/orders.ts" }],
57
+ ["Bash", { command: "pnpm tsc --noEmit" }],
58
+ ["Edit", { file_path: "src/middleware/auth.ts" }],
59
+ ["Bash", { command: "pnpm test routes" }]
60
+ ],
61
+ s2: [
62
+ ["Read", { file_path: "billing/invoice.py" }],
63
+ ["Write", { file_path: "tests/test_invoice.py" }],
64
+ ["Bash", { command: "pytest -q tests/test_invoice.py" }],
65
+ ["Edit", { file_path: "billing/tax.py" }],
66
+ ["Bash", { command: "pytest -q" }]
67
+ ],
68
+ s3: [
69
+ ["Read", { file_path: "app/settings/page.tsx" }],
70
+ ["Edit", { file_path: "app/settings/page.tsx" }],
71
+ ["Bash", { command: "npm run lint" }],
72
+ ["Read", { file_path: "lib/config.ts" }]
73
+ ],
74
+ s4: [
75
+ ["Glob", { pattern: "docs/**/*.md" }],
76
+ ["Write", { file_path: "docs/zh-CN/getting-started.md" }],
77
+ ["Write", { file_path: "docs/ja/getting-started.md" }],
78
+ ["Edit", { file_path: "docs/.vitepress/config.ts" }],
79
+ ["Write", { file_path: "docs/es/getting-started.md" }]
80
+ ]
81
+ };
82
+ var steps = [];
83
+ var ev = (at, e) => steps.push({ at, event: e });
84
+ var prompts = {
85
+ s1: "Replace legacyAuth with the new session middleware",
86
+ s2: "Raise billing test coverage to 90%",
87
+ s3: "Add a settings page with feature flags",
88
+ s4: "Translate getting-started into zh-CN / ja / es"
89
+ };
90
+ sessions.forEach((s, i) => {
91
+ ev(0.05 * i, { sessionId: s.id, type: "session_start" });
92
+ ev(0.2 + 0.1 * i, { sessionId: s.id, type: "prompt", text: prompts[s.id] });
93
+ });
94
+ function activity(id, from, to, every, offset = 0) {
95
+ const list = actions[id];
96
+ let k = 0;
97
+ for (let t = from + offset; t < to; t += every, k++) {
98
+ const [name, input] = list[k % list.length];
99
+ ev(t, { sessionId: id, type: "tool_pre", tool: { name, input } });
100
+ ev(t + 0.3, { sessionId: id, type: "usage", usage: { input: 3800 + k * 977 % 2400, output: 300 + k * 131 % 400 } });
101
+ }
102
+ }
103
+ activity("s1", 0.6, 26, 1.6);
104
+ activity("s2", 0.8, 3.4, 0.9);
105
+ activity("s2", 10.2, 26, 1.8, 0.3);
106
+ activity("s3", 0.7, 4.4, 1);
107
+ activity("s3", 14.6, 26, 1.7);
108
+ activity("s4", 0.9, 26, 1.4, 0.2);
109
+ steps.push({
110
+ at: 3.5,
111
+ approval: {
112
+ id: "demo-push",
113
+ sessionId: "s2",
114
+ risk: "high",
115
+ summary: "Force-push to main",
116
+ detail: { tool: "Bash", command: "git push --force origin main" },
117
+ tool: { name: "Bash", input: { command: "git push --force origin main" } }
118
+ }
119
+ });
120
+ steps.push({
121
+ at: 4.5,
122
+ approval: {
123
+ id: "demo-env",
124
+ sessionId: "s3",
125
+ risk: "medium",
126
+ summary: "Edit secrets file .env",
127
+ detail: { tool: "Edit", filePath: ".env", diffPreview: "+ FEATURE_FLAGS_KEY=sk_live_\u2026" },
128
+ tool: { name: "Edit", input: { file_path: ".env" } }
129
+ }
130
+ });
131
+ steps.push({ at: 9.5, decide: { approvalId: "demo-push", action: "approve" } });
132
+ var envReply = { approvalId: "demo-env", text: "\u522B\u52A8 .env\uFF0C\u6539 .env.example" };
133
+ steps.push({ at: 12, phoneReply: { ...envReply, duration: 0.8 } });
134
+ steps.push({ at: 13, decide: { ...envReply, action: "reply" } });
135
+ ev(14, { sessionId: "s3", type: "tool_pre", tool: { name: "Edit", input: { file_path: ".env.example" } } });
136
+ steps.push({ at: 16, tokenRace: { datasetId: "sim-refactor", duration: 9.5 } });
137
+ sessions.forEach((s, i) => {
138
+ ev(26 + 0.35 * i, { sessionId: s.id, type: "stop" });
139
+ ev(27 + 0.35 * i, { sessionId: s.id, type: "session_end" });
140
+ });
141
+ var videoScenario = {
142
+ id: "video",
143
+ title: "30s demo: 4 agents, remote approval, token race",
144
+ duration: 30,
145
+ sessions,
146
+ datasets: [simulatedRefactorDataset()],
147
+ timeline: steps
148
+ };
149
+ var scenarios = { video: videoScenario };
150
+ export {
151
+ scenarios,
152
+ videoScenario
153
+ };