@acryldev/agent-panel 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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/client/describe.ts +101 -0
  3. package/client/driver-pick.ts +22 -0
  4. package/client/frame.ts +51 -0
  5. package/client/main.ts +707 -0
  6. package/client/markdown.ts +219 -0
  7. package/headless.ts +220 -0
  8. package/index.ts +523 -0
  9. package/launch.ts +67 -0
  10. package/lib/client/describe.ts +101 -0
  11. package/lib/client/driver-pick.ts +22 -0
  12. package/lib/client/frame.ts +51 -0
  13. package/lib/client/main.ts +707 -0
  14. package/lib/client/markdown.ts +219 -0
  15. package/lib/headless-B_RGxZFU.js +252 -0
  16. package/lib/headless-B_RGxZFU.js.map +1 -0
  17. package/lib/headless.js +2 -0
  18. package/lib/index.js +562 -0
  19. package/lib/index.js.map +1 -0
  20. package/lib/mount.js +25 -0
  21. package/lib/mount.js.map +1 -0
  22. package/lib/registry.js +13 -0
  23. package/lib/registry.js.map +1 -0
  24. package/lib/types/headless.d.ts +22 -0
  25. package/lib/types/index.d.ts +22 -0
  26. package/lib/types/launch.d.ts +18 -0
  27. package/lib/types/mount.d.ts +12 -0
  28. package/lib/types/registry.d.ts +10 -0
  29. package/lib/types/tsdown.config.d.ts +2 -0
  30. package/lib/types/visitors.d.ts +82 -0
  31. package/mount.ts +27 -0
  32. package/package.json +62 -3
  33. package/plugin.json +28 -0
  34. package/registry.ts +17 -0
  35. package/scripts/copy-assets.mjs +5 -0
  36. package/test/client-guards.test.ts +13 -0
  37. package/test/describe.test.ts +105 -0
  38. package/test/driver-pick.test.ts +24 -0
  39. package/test/frame.test.ts +35 -0
  40. package/test/launch.test.ts +90 -0
  41. package/test/markdown.test.ts +79 -0
  42. package/test/panel-client.test.ts +150 -0
  43. package/test/panel.test.ts +534 -0
  44. package/test/socket.test.ts +209 -0
  45. package/test/visitors.test.ts +112 -0
  46. package/test/why.test.ts +61 -0
  47. package/tsconfig.json +21 -0
  48. package/tsdown.config.ts +23 -0
  49. package/visitors.ts +231 -0
  50. package/README.md +0 -3
package/lib/index.js ADDED
@@ -0,0 +1,562 @@
1
+ import { i as headlessDriver, n as availableHeadless, s as whyNotChat, t as agentDriver } from "./headless-B_RGxZFU.js";
2
+ import { mountedBase, mountedPrefix } from "./mount.js";
3
+ import { provideDrivers } from "./registry.js";
4
+ import { appendFileSync, mkdirSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { clientModules } from "@acryldev/node-server/client-modules";
7
+ import { Acryl } from "@acryldev/router";
8
+ import { streamSSE } from "@acryldev/router/helpers";
9
+ import { pageAuthority } from "@acryldev/router/middleware";
10
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
11
+ //#region visitors.ts
12
+ /**
13
+ * Who uses the panel, and what each one may do.
14
+ *
15
+ * - In development one person does, the app's owner: every page of the app shares one token and one run, so a run asked in the frame is followed from any tab of the app.
16
+ * - As the Assistant every visitor of the app is their own: a visitor is known by an HttpOnly cookie that the panel's session sets, and has their own token, their own run and
17
+ * their own limits. A visitor never sees, follows or stops another visitor's run, and never waits for one.
18
+ *
19
+ * The Assistant spends the owner's model key for anyone who opens the app, so its asks are bounded: per visitor per hour, for all visitors per day, runs at once, and the length of
20
+ * a question. The agent's own step budget bounds each run.
21
+ */
22
+ /** The cookie that names a visitor of the Assistant. HttpOnly: the page's scripts never read it. */
23
+ const VISITOR_COOKIE = "acryl-visitor";
24
+ const DEFAULT_LIMITS = {
25
+ perVisitorPerHour: 20,
26
+ perDay: 300,
27
+ concurrent: 4,
28
+ messageLength: 1e3
29
+ };
30
+ /** The question length the development panel accepts (one person, who owns the key). */
31
+ const OWNER_MESSAGE_LENGTH = 8e3;
32
+ const HOUR_MS = 3600 * 1e3;
33
+ const DAY_MS = 24 * HOUR_MS;
34
+ /** Visitors kept at most; the one seen longest ago without a run going is let go first. */
35
+ const DEFAULT_CAPACITY = 5e3;
36
+ const newSecret = () => randomBytes(24).toString("base64url");
37
+ /** The value of one cookie in a `Cookie` header. */
38
+ function cookieValue(header, name) {
39
+ if (header === void 0 || header === null) return void 0;
40
+ for (const part of header.split(";")) {
41
+ const at = part.indexOf("=");
42
+ if (at === -1) continue;
43
+ if (part.slice(0, at).trim() === name) return part.slice(at + 1).trim();
44
+ }
45
+ }
46
+ /** Whether two secrets are the same, in constant time. */
47
+ function sameSecret(presented, expected) {
48
+ if (typeof presented !== "string") return false;
49
+ const a = Buffer.from(presented);
50
+ const b = Buffer.from(expected);
51
+ return a.length === b.length && timingSafeEqual(a, b);
52
+ }
53
+ const minutes = (ms) => {
54
+ const count = Math.max(1, Math.ceil(ms / 6e4));
55
+ return `${String(count)} minute${count === 1 ? "" : "s"}`;
56
+ };
57
+ var Visitors = class {
58
+ shared;
59
+ limits;
60
+ now;
61
+ capacity;
62
+ byId = /* @__PURE__ */ new Map();
63
+ /** When every ask of the last day started, across visitors. */
64
+ day = [];
65
+ owner;
66
+ constructor(options) {
67
+ this.shared = options.shared;
68
+ this.limits = {
69
+ ...DEFAULT_LIMITS,
70
+ ...options.limits
71
+ };
72
+ this.now = options.now ?? Date.now;
73
+ this.capacity = options.capacity ?? DEFAULT_CAPACITY;
74
+ this.owner = this.shared ? this.make() : void 0;
75
+ }
76
+ /** The visitor a request belongs to: the owner in development, else the one its cookie names; `undefined` when it names none this app knows. */
77
+ of(cookieHeader) {
78
+ if (this.owner !== void 0) return this.owner;
79
+ const id = cookieValue(cookieHeader, VISITOR_COOKIE);
80
+ const visitor = id === void 0 ? void 0 : this.byId.get(id);
81
+ if (visitor !== void 0) visitor.lastSeen = this.now();
82
+ return visitor;
83
+ }
84
+ /**
85
+ * The visitor of a session request, made when the request names none. `setCookie` is the header to answer with, only for a new visitor: HttpOnly, SameSite=Strict, the whole
86
+ * app (`Path=/`), a day long, and Secure when the page came over https.
87
+ */
88
+ session(cookieHeader, secure) {
89
+ const known = this.of(cookieHeader);
90
+ if (known !== void 0) return { visitor: known };
91
+ const visitor = this.make();
92
+ this.keep(visitor);
93
+ return {
94
+ visitor,
95
+ setCookie: `${VISITOR_COOKIE}=${visitor.id}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${String(DAY_MS / 1e3)}${secure ? "; Secure" : ""}`
96
+ };
97
+ }
98
+ /** Whether `presented` is this visitor's token. */
99
+ accepts(visitor, presented) {
100
+ return visitor !== void 0 && sameSecret(presented, visitor.token);
101
+ }
102
+ /** Whether any visitor holds this token (a terminal driver checks a request with no other context). */
103
+ knows(cookieHeader, presented) {
104
+ return this.accepts(this.of(cookieHeader), presented);
105
+ }
106
+ /** The question's length check, which comes before anything is counted. */
107
+ checkMessage(message) {
108
+ const most = this.shared ? OWNER_MESSAGE_LENGTH : this.limits.messageLength;
109
+ if (message === "" || message.length > most) return {
110
+ error: `write a message of at most ${String(most)} characters`,
111
+ status: 400
112
+ };
113
+ }
114
+ /**
115
+ * Whether this visitor may start a run now. The visitor's own run going is refused first (409); then, for the Assistant, the visitor's hour, the runs going at once and the
116
+ * day. An admitted ask is counted.
117
+ */
118
+ admit(visitor) {
119
+ if (visitor.current !== void 0 && !visitor.current.ended) return {
120
+ error: "a run is already going; wait for it to end",
121
+ status: 409
122
+ };
123
+ if (this.shared) return void 0;
124
+ const now = this.now();
125
+ prune(visitor.asks, now - HOUR_MS);
126
+ prune(this.day, now - DAY_MS);
127
+ const hour = visitor.asks[0];
128
+ if (visitor.asks.length >= this.limits.perVisitorPerHour && hour !== void 0) return {
129
+ error: `You have asked ${String(this.limits.perVisitorPerHour)} questions this hour. Ask again in ${minutes(hour + HOUR_MS - now)}.`,
130
+ status: 429
131
+ };
132
+ let going = 0;
133
+ for (const other of this.byId.values()) if (other.current !== void 0 && !other.current.ended) going += 1;
134
+ if (going >= this.limits.concurrent) return {
135
+ error: "The assistant is helping other people right now. Ask again in a moment.",
136
+ status: 503
137
+ };
138
+ const first = this.day[0];
139
+ if (this.day.length >= this.limits.perDay && first !== void 0) return {
140
+ error: `The assistant has answered all the questions it can today. It is back in ${minutes(first + DAY_MS - now)}.`,
141
+ status: 429
142
+ };
143
+ visitor.asks.push(now);
144
+ this.day.push(now);
145
+ }
146
+ /** How many visitors are kept (for tests and diagnostics). */
147
+ get size() {
148
+ return this.owner === void 0 ? this.byId.size : 1;
149
+ }
150
+ make() {
151
+ const id = newSecret();
152
+ return {
153
+ id,
154
+ token: newSecret(),
155
+ tag: createHash("sha256").update(id).digest("hex").slice(0, 12),
156
+ current: void 0,
157
+ asks: [],
158
+ lastSeen: this.now()
159
+ };
160
+ }
161
+ /** Keep a new visitor; past the capacity, let go of the visitors seen longest ago that have no run going. */
162
+ keep(visitor) {
163
+ if (this.byId.size >= this.capacity) {
164
+ const idle = [...this.byId.values()].filter((other) => other.current === void 0 || other.current.ended).sort((a, b) => a.lastSeen - b.lastSeen);
165
+ for (const other of idle.slice(0, this.byId.size - this.capacity + 1)) this.byId.delete(other.id);
166
+ }
167
+ this.byId.set(visitor.id, visitor);
168
+ }
169
+ };
170
+ /** Drop the times up to `since` from the front of an ascending list: an ask exactly an hour (or a day) old is out of the window. */
171
+ function prune(times, since) {
172
+ let drop = 0;
173
+ while (drop < times.length && (times[drop] ?? 0) <= since) drop += 1;
174
+ if (drop > 0) times.splice(0, drop);
175
+ }
176
+ //#endregion
177
+ //#region index.ts
178
+ /**
179
+ * The built-in agent (spec 049 slice 14): a chat panel inside the running app. The person says what they want; the app's own agent (`driver: 'agent'`) or a coding
180
+ * agent started in the app folder (`'claude'`, `'codex'`, `'pi'`) builds it through the door, and when a plugin was installed or removed the page reloads, so the new feature
181
+ * shows with no restart. The drivers are entries of the `drivers` service this plugin provides (`@acryldev/drivers`): chat drivers here, and other plugins (`driver-pty`) add more.
182
+ *
183
+ * - A middleware appends one script tag (`/api/agent-panel/panel.js`) to every HTML response of the routes mounted after it, so no page is edited.
184
+ * - `GET /api/agent-panel/session` gives the page the drivers it may use and a token; `POST /api/agent-panel/ask` runs one message and answers server-sent events:
185
+ * `text`, `tool`, `change`, `done`, `error`.
186
+ * - Only the app's own page may ask (a same-origin request carrying the token), one run at a time, and every ask is written to `.acryl/audit/agent-panel.jsonl`.
187
+ * - Who asks (`visitors.ts`): in development one person, the owner, whose pages share one token and one run. As the Assistant each visitor has their own token, run and
188
+ * replay, named by an HttpOnly cookie: no visitor sees, follows or stops another's run, and the asks are bounded (per visitor per hour, per day, runs at once).
189
+ * - The routes live under the app's mount: the root of the app's own server, or the frame's prefix (`/app`) when the frame hosts it, where the host's own
190
+ * `/api` routes would otherwise answer first. The row's `mount` config names it.
191
+ * - Development only: the plugin does nothing with `NODE_ENV=production` or `ACRYL_DOOR=off`, except as the Assistant (`assistant: true`): then it runs in production too,
192
+ * docked open on the right, with the app's own agent only. The app gives that agent the page tools alone and a page-only door, so it uses the app for a visitor and
193
+ * cannot change it (src/app.ts, `ACRYL_ASSISTANT=on`). In the ACRYL frame's canvas the panel follows the frame's view: Build hides it, and Preview shows it only as
194
+ * the Assistant and only when the app's production environment names one (`assistantInProduction` in the session).
195
+ */
196
+ const name = "agent-panel";
197
+ const inject = [
198
+ "router",
199
+ "agent",
200
+ "extensions",
201
+ "appInstance"
202
+ ];
203
+ /** The panel's own routes, fixed relative to the app's mount. */
204
+ const PANEL_PATH = "/api/agent-panel";
205
+ /** The one driver the Assistant offers its visitors: the app's own agent, held to the page tools. */
206
+ const ASSISTANT_DRIVER = "agent";
207
+ const CLIENT_DIR = join(import.meta.dirname, "client");
208
+ /** Whether the page came over https (directly, or through a proxy that says so): the visitor cookie is then Secure. */
209
+ const overHttps = (url, headers) => url.startsWith("https:") || headers.get("x-forwarded-proto")?.split(",")[0]?.trim() === "https";
210
+ /** The panel's routes under a checked mount: empty, or an absolute path such as `/app` with no trailing slash (the `routerHttp.mount` rule). */
211
+ const panelPrefix = (mount) => mountedPrefix(mount, PANEL_PATH, "agent-panel");
212
+ /** Whether a request comes from the app's own page: a browser says so itself (`Sec-Fetch-Site: same-origin`), or the Origin is the Host. */
213
+ function fromOwnPage(headers) {
214
+ const site = headers.get("sec-fetch-site");
215
+ if (site !== null) return site === "same-origin";
216
+ const origin = headers.get("origin");
217
+ const host = headers.get("host");
218
+ return origin !== null && host !== null && new URL(origin).host === host;
219
+ }
220
+ function apply(ctx, config = {}) {
221
+ const assistant = config.assistant === true;
222
+ if (process.env.ACRYL_DOOR === "off" || process.env.NODE_ENV === "production" && !assistant) return;
223
+ const PREFIX = panelPrefix(config.mount);
224
+ const MOUNT = mountedBase(config.mount, "agent-panel");
225
+ const root = ctx.appInstance.root;
226
+ const visitors = new Visitors({
227
+ shared: !assistant,
228
+ ...config.limits === void 0 ? {} : { limits: config.limits }
229
+ });
230
+ /** The visitor of a request that must carry its token, or `undefined` when it does not come from the app's own page with the right one. */
231
+ const caller = (headers, presented) => {
232
+ if (!fromOwnPage(headers)) return void 0;
233
+ const visitor = visitors.of(headers.get("cookie"));
234
+ return visitors.accepts(visitor, presented) ? visitor : void 0;
235
+ };
236
+ const auditFile = join(root, ".acryl", "audit", "agent-panel.jsonl");
237
+ const audit = (entry) => {
238
+ try {
239
+ mkdirSync(dirname(auditFile), { recursive: true });
240
+ appendFileSync(auditFile, `${JSON.stringify({
241
+ at: (/* @__PURE__ */ new Date()).toISOString(),
242
+ ...entry
243
+ })}\n`);
244
+ } catch {}
245
+ };
246
+ const registry = provideDrivers(ctx, (headers) => !assistant && caller(headers, headers.get("x-agent-panel-token")) !== void 0);
247
+ const offered = () => registry.list().filter((driver) => !assistant || driver.name === ASSISTANT_DRIVER);
248
+ ctx.effect(() => registry.register(agentDriver(ctx)));
249
+ if (!assistant) for (const program of availableHeadless(config.drivers)) ctx.effect(() => registry.register(headlessDriver(program, root)));
250
+ const tag = `<script type="module" src="${PREFIX}/panel.js"><\/script>`;
251
+ const addScript = async (c, next) => {
252
+ await next();
253
+ if (!(c.res.headers.get("content-type") ?? "").includes("text/html")) return;
254
+ const html = await c.res.text();
255
+ if (html.includes(`${PREFIX}/panel.js`)) {
256
+ c.res = new Response(html, c.res);
257
+ return;
258
+ }
259
+ const headers = new Headers(c.res.headers);
260
+ headers.delete("content-length");
261
+ c.res = new Response(html.includes("</body>") ? html.replace("</body>", `${tag}</body>`) : html + tag, {
262
+ status: c.res.status,
263
+ headers
264
+ });
265
+ };
266
+ const router = ctx.router;
267
+ const wrapped = typeof router.wrap === "function";
268
+ if (wrapped) router.wrap?.(addScript);
269
+ const app = new Acryl().use("*", async (c, next) => {
270
+ if (wrapped) return next();
271
+ await addScript(c, next);
272
+ }).get(`${PANEL_PATH}/panel.js`, (c) => c.body(`import { start } from '${PREFIX}/client/main.ts'\nstart(${JSON.stringify(PREFIX)})\n`, 200, {
273
+ "content-type": "text/javascript; charset=utf-8",
274
+ "cache-control": "no-cache"
275
+ })).route(`${PANEL_PATH}/client`, clientModules({
276
+ root: CLIENT_DIR,
277
+ mount: `${PREFIX}/client`
278
+ })).get(`${PANEL_PATH}/session`, (c) => {
279
+ if (!fromOwnPage(c.req.raw.headers)) return c.json({ error: "only the app's own page may use the panel" }, 403);
280
+ const { visitor, setCookie } = visitors.session(c.req.header("cookie"), overHttps(c.req.url, c.req.raw.headers));
281
+ if (setCookie !== void 0) c.header("set-cookie", setCookie);
282
+ return c.json({
283
+ token: visitor.token,
284
+ ...assistant ? { assistant: true } : {},
285
+ ...process.env.ACRYL_ASSISTANT === "on" ? { assistantInProduction: true } : {},
286
+ drivers: offered().map((driver) => ({
287
+ name: driver.name,
288
+ kind: driver.kind,
289
+ ...driver.kind === "terminal" ? { view: driver.view } : {}
290
+ }))
291
+ });
292
+ }).post(`${PANEL_PATH}/ask`, async (c) => {
293
+ const visitor = caller(c.req.raw.headers, c.req.header("x-agent-panel-token"));
294
+ if (visitor === void 0) return c.json({ error: "only the app's own page may ask" }, 403);
295
+ const body = await c.req.json().catch(() => ({}));
296
+ const checked = checkAsk(visitor, body.message, body.driver);
297
+ if ("error" in checked) return c.json({ error: checked.error }, checked.status);
298
+ const run = startRun(visitor, checked.driverName, checked.message, checked.driver, pageOf(body.page));
299
+ return follow(c, run, false);
300
+ }).post(`${PANEL_PATH}/stop`, (c) => {
301
+ const visitor = caller(c.req.raw.headers, c.req.header("x-agent-panel-token"));
302
+ if (visitor === void 0) return c.json({ error: "only the app's own page may stop a run" }, 403);
303
+ visitor.current?.cancel.abort();
304
+ return c.json({ ok: true });
305
+ }).get(`${PANEL_PATH}/run`, (c) => {
306
+ const visitor = caller(c.req.raw.headers, c.req.header("x-agent-panel-token"));
307
+ if (visitor === void 0) return c.json({ error: "only the app's own page may read the run" }, 403);
308
+ return visitor.current === void 0 ? c.json({ run: null }) : follow(c, visitor.current, true);
309
+ });
310
+ /**
311
+ * What `/ask` and the socket's `ask` both check: a message of a sensible size, a chat driver that is here, and no run of this visitor going; for the Assistant also its
312
+ * limits (an admitted ask is counted).
313
+ */
314
+ const checkAsk = (visitor, rawMessage, rawDriver) => {
315
+ const message = typeof rawMessage === "string" ? rawMessage.trim() : "";
316
+ const driverName = typeof rawDriver === "string" ? rawDriver : "agent";
317
+ const tooLong = visitors.checkMessage(message);
318
+ if (tooLong !== void 0) return tooLong;
319
+ const driver = offered().find((one) => one.name === driverName);
320
+ if (driver?.kind !== "chat") {
321
+ const chat = offered().filter((d) => d.kind === "chat").map((d) => d.name).join(", ");
322
+ const why = whyNotChat(driverName, driver?.kind);
323
+ return {
324
+ error: `the driver "${driverName}" is not available here${why === void 0 ? "" : `: ${why}`} (chat drivers: ${chat})`,
325
+ status: 400
326
+ };
327
+ }
328
+ const refused = visitors.admit(visitor);
329
+ if (refused !== void 0) {
330
+ if (assistant) audit({
331
+ ask: "refused",
332
+ visitor: visitor.tag,
333
+ status: refused.status
334
+ });
335
+ return refused;
336
+ }
337
+ return {
338
+ message,
339
+ driverName,
340
+ driver
341
+ };
342
+ };
343
+ let runs = 0;
344
+ /** The door's id of the page that asked, when it sent one that looks like it. */
345
+ const pageOf = (raw) => typeof raw === "string" && /^[A-Za-z0-9-]{1,80}$/u.test(raw) ? raw : void 0;
346
+ const startRun = (visitor, driverName, message, driver, page) => {
347
+ runs += 1;
348
+ const run = {
349
+ id: runs,
350
+ driver: driverName,
351
+ message,
352
+ startedAt: Date.now(),
353
+ events: [],
354
+ followers: /* @__PURE__ */ new Set(),
355
+ cancel: new AbortController(),
356
+ ended: false
357
+ };
358
+ visitor.current = run;
359
+ const who = assistant ? { visitor: visitor.tag } : {};
360
+ const emit = (event, data) => {
361
+ const item = {
362
+ event,
363
+ data
364
+ };
365
+ run.events.push(item);
366
+ for (const follower of [...run.followers]) follower(item);
367
+ };
368
+ let changed = false;
369
+ const off = ctx.on("extensions/changed", (extension, action) => {
370
+ changed = true;
371
+ emit("change", {
372
+ extension,
373
+ action
374
+ });
375
+ });
376
+ const unloadStops = ctx.effect(() => () => run.cancel.abort(), `agent-panel: run ${runs}`);
377
+ audit({
378
+ ask: "start",
379
+ ...who,
380
+ driver: driverName,
381
+ characters: message.length
382
+ });
383
+ const releasePage = (page === void 0 ? void 0 : ctx.get("door"))?.driveFor(page);
384
+ (async () => {
385
+ try {
386
+ for await (const { event, data } of driver.start({
387
+ message,
388
+ signal: run.cancel.signal,
389
+ ...page === void 0 ? {} : { page }
390
+ })) emit(event, data);
391
+ emit("done", { changed });
392
+ } catch (error) {
393
+ emit("error", { message: error instanceof Error ? error.message : String(error) });
394
+ } finally {
395
+ off();
396
+ releasePage?.();
397
+ run.ended = true;
398
+ run.endedAt = Date.now();
399
+ audit({
400
+ ask: "end",
401
+ ...who,
402
+ driver: driverName,
403
+ changed
404
+ });
405
+ for (const follower of [...run.followers]) follower({
406
+ event: "end",
407
+ data: {}
408
+ });
409
+ unloadStops();
410
+ }
411
+ })();
412
+ return run;
413
+ };
414
+ /**
415
+ * Follow a run into `write`: a `run` event (what it is, whether it already ended) when `announce`, the events so far, then the new ones until it ends. Following does not keep the
416
+ * run alive. `detach` stops following (the page went away); `done` settles when the run ended or the following was detached.
417
+ */
418
+ const pump = (run, announce, write) => {
419
+ const queue = [...run.events];
420
+ if (announce) queue.unshift({
421
+ event: "run",
422
+ data: {
423
+ id: run.id,
424
+ driver: run.driver,
425
+ message: run.message,
426
+ startedAt: run.startedAt,
427
+ ended: run.ended,
428
+ endedAt: run.endedAt ?? null
429
+ }
430
+ });
431
+ let wake;
432
+ const follower = (item) => {
433
+ queue.push(item);
434
+ wake?.();
435
+ };
436
+ if (!run.ended) run.followers.add(follower);
437
+ let open = true;
438
+ return {
439
+ done: (async () => {
440
+ try {
441
+ while (open) {
442
+ const item = queue.shift();
443
+ if (item === void 0) {
444
+ if (run.ended) break;
445
+ await new Promise((resolve) => {
446
+ wake = resolve;
447
+ });
448
+ wake = void 0;
449
+ continue;
450
+ }
451
+ if (item.event === "end") break;
452
+ await write(item.event, item.data);
453
+ }
454
+ } finally {
455
+ run.followers.delete(follower);
456
+ }
457
+ })(),
458
+ detach: () => {
459
+ open = false;
460
+ run.followers.delete(follower);
461
+ wake?.();
462
+ }
463
+ };
464
+ };
465
+ /** Follow a run as server-sent events. */
466
+ const follow = (c, run, announce) => streamSSE(c, async (stream) => {
467
+ const following = pump(run, announce, (event, data) => stream.writeSSE({
468
+ event,
469
+ data: JSON.stringify(data)
470
+ }));
471
+ stream.onAbort(following.detach);
472
+ await following.done;
473
+ });
474
+ ctx.inject(["nodeServer"], (inner) => {
475
+ let upgrade;
476
+ try {
477
+ upgrade = inner.nodeServer.upgrades();
478
+ } catch {
479
+ return;
480
+ }
481
+ const ws = new Acryl();
482
+ const own = async (c, next) => {
483
+ const authority = pageAuthority(c);
484
+ const origin = c.req.header("origin");
485
+ const site = c.req.header("sec-fetch-site");
486
+ if (authority === void 0 || origin === void 0 || origin !== authority.origin || site !== void 0 && site !== "same-origin") return c.json({ error: "only the app's own page may use the panel" }, 403);
487
+ await next();
488
+ };
489
+ ws.get(`${PREFIX}/run/ws`, own, upgrade((c) => {
490
+ const visitor = visitors.of(c.req.header("cookie"));
491
+ let authed = false;
492
+ let following;
493
+ let hello;
494
+ return {
495
+ onOpen(_event, ws) {
496
+ hello = setTimeout(() => ws.close(4401, "no token"), 5e3);
497
+ },
498
+ onMessage(event, ws) {
499
+ if (typeof event.data !== "string") return;
500
+ let message;
501
+ try {
502
+ message = JSON.parse(event.data);
503
+ } catch {
504
+ return;
505
+ }
506
+ if (!authed) {
507
+ if (message.t !== "hello" || !visitors.accepts(visitor, message.token)) {
508
+ ws.close(4401, "token");
509
+ return;
510
+ }
511
+ authed = true;
512
+ if (hello !== void 0) clearTimeout(hello);
513
+ ws.send(JSON.stringify({
514
+ e: "accepted",
515
+ d: {}
516
+ }));
517
+ return;
518
+ }
519
+ const send = (e, d) => {
520
+ ws.send(JSON.stringify({
521
+ e,
522
+ d
523
+ }));
524
+ };
525
+ if (visitor === void 0) return;
526
+ if (message.t === "stop") {
527
+ visitor.current?.cancel.abort();
528
+ return;
529
+ }
530
+ if (following !== void 0) return;
531
+ const watch = (run, announce) => {
532
+ const pumped = pump(run, announce, send);
533
+ following = pumped;
534
+ pumped.done.then(() => ws.close(1e3, "run ended"));
535
+ };
536
+ if (message.t === "ask") {
537
+ const checked = checkAsk(visitor, message.message, message.driver);
538
+ if ("error" in checked) {
539
+ send("error", { message: checked.error });
540
+ ws.close(1e3, "refused");
541
+ return;
542
+ }
543
+ watch(startRun(visitor, checked.driverName, checked.message, checked.driver, pageOf(message.page)), false);
544
+ } else if (message.t === "follow") if (visitor.current === void 0) {
545
+ send("idle", {});
546
+ ws.close(1e3, "no run");
547
+ } else watch(visitor.current, true);
548
+ },
549
+ onClose() {
550
+ if (hello !== void 0) clearTimeout(hello);
551
+ following?.detach();
552
+ }
553
+ };
554
+ }, { textOnly: true }));
555
+ inner.router.route("/", ws);
556
+ });
557
+ ctx.router.route(MOUNT === "" ? "/" : MOUNT, app);
558
+ }
559
+ //#endregion
560
+ export { apply, fromOwnPage, inject, name };
561
+
562
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../visitors.ts","../index.ts"],"sourcesContent":["/**\n * Who uses the panel, and what each one may do.\n *\n * - In development one person does, the app's owner: every page of the app shares one token and one run, so a run asked in the frame is followed from any tab of the app.\n * - As the Assistant every visitor of the app is their own: a visitor is known by an HttpOnly cookie that the panel's session sets, and has their own token, their own run and\n * their own limits. A visitor never sees, follows or stops another visitor's run, and never waits for one.\n *\n * The Assistant spends the owner's model key for anyone who opens the app, so its asks are bounded: per visitor per hour, for all visitors per day, runs at once, and the length of\n * a question. The agent's own step budget bounds each run.\n */\nimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto'\n\n/** The cookie that names a visitor of the Assistant. HttpOnly: the page's scripts never read it. */\nexport const VISITOR_COOKIE = 'acryl-visitor'\n\n/** The Assistant's limits; each one has a default. */\nexport interface AssistantLimits {\n /** Questions one visitor may ask in an hour. */\n readonly perVisitorPerHour?: number\n /** Questions all visitors together may ask in a day: every one of them spends the owner's model key. */\n readonly perDay?: number\n /** Runs going at once, across visitors. */\n readonly concurrent?: number\n /** Characters in one question. */\n readonly messageLength?: number\n}\n\nexport const DEFAULT_LIMITS: Required<AssistantLimits> = {\n perVisitorPerHour: 20,\n perDay: 300,\n concurrent: 4,\n messageLength: 1000,\n}\n\n/** The question length the development panel accepts (one person, who owns the key). */\nconst OWNER_MESSAGE_LENGTH = 8000\nconst HOUR_MS = 60 * 60 * 1000\nconst DAY_MS = 24 * HOUR_MS\n/** Visitors kept at most; the one seen longest ago without a run going is let go first. */\nconst DEFAULT_CAPACITY = 5000\n\n/** What a visitor's run must say about itself. */\nexport interface RunState {\n readonly ended: boolean\n}\n\nexport interface Visitor<R extends RunState> {\n readonly id: string\n readonly token: string\n /** The visitor in the audit: a short hash, never the cookie itself. */\n readonly tag: string\n /** The visitor's latest run, going or ended (what a page that loads shows again). */\n current: R | undefined\n /** When this visitor's asks of the last hour started. */\n readonly asks: number[]\n lastSeen: number\n}\n\n/** Why an ask is refused, with the HTTP status to answer. */\nexport interface Refusal {\n readonly error: string\n readonly status: 400 | 409 | 429 | 503\n}\n\nexport interface VisitorsOptions {\n /** One visitor for every page (development); otherwise one per cookie (the Assistant). */\n readonly shared: boolean\n readonly limits?: AssistantLimits\n readonly now?: () => number\n readonly capacity?: number\n}\n\nconst newSecret = (): string => randomBytes(24).toString('base64url')\n\n/** The value of one cookie in a `Cookie` header. */\nexport function cookieValue(header: string | undefined | null, name: string): string | undefined {\n if (header === undefined || header === null) return undefined\n for (const part of header.split(';')) {\n const at = part.indexOf('=')\n if (at === -1) continue\n if (part.slice(0, at).trim() === name) return part.slice(at + 1).trim()\n }\n return undefined\n}\n\n/** Whether two secrets are the same, in constant time. */\nexport function sameSecret(presented: unknown, expected: string): boolean {\n if (typeof presented !== 'string') return false\n const a = Buffer.from(presented)\n const b = Buffer.from(expected)\n return a.length === b.length && timingSafeEqual(a, b)\n}\n\nconst minutes = (ms: number): string => {\n const count = Math.max(1, Math.ceil(ms / 60_000))\n return `${String(count)} minute${count === 1 ? '' : 's'}`\n}\n\nexport class Visitors<R extends RunState> {\n private readonly shared: boolean\n private readonly limits: Required<AssistantLimits>\n private readonly now: () => number\n private readonly capacity: number\n private readonly byId = new Map<string, Visitor<R>>()\n /** When every ask of the last day started, across visitors. */\n private readonly day: number[] = []\n private readonly owner: Visitor<R> | undefined\n\n constructor(options: VisitorsOptions) {\n this.shared = options.shared\n this.limits = { ...DEFAULT_LIMITS, ...options.limits }\n this.now = options.now ?? Date.now\n this.capacity = options.capacity ?? DEFAULT_CAPACITY\n this.owner = this.shared ? this.make() : undefined\n }\n\n /** The visitor a request belongs to: the owner in development, else the one its cookie names; `undefined` when it names none this app knows. */\n of(cookieHeader: string | undefined | null): Visitor<R> | undefined {\n if (this.owner !== undefined) return this.owner\n const id = cookieValue(cookieHeader, VISITOR_COOKIE)\n const visitor = id === undefined ? undefined : this.byId.get(id)\n if (visitor !== undefined) visitor.lastSeen = this.now()\n return visitor\n }\n\n /**\n * The visitor of a session request, made when the request names none. `setCookie` is the header to answer with, only for a new visitor: HttpOnly, SameSite=Strict, the whole\n * app (`Path=/`), a day long, and Secure when the page came over https.\n */\n session(\n cookieHeader: string | undefined | null,\n secure: boolean,\n ): { visitor: Visitor<R>; setCookie?: string } {\n const known = this.of(cookieHeader)\n if (known !== undefined) return { visitor: known }\n const visitor = this.make()\n this.keep(visitor)\n const setCookie = `${VISITOR_COOKIE}=${visitor.id}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${String(DAY_MS / 1000)}${secure ? '; Secure' : ''}`\n return { visitor, setCookie }\n }\n\n /** Whether `presented` is this visitor's token. */\n accepts(visitor: Visitor<R> | undefined, presented: unknown): visitor is Visitor<R> {\n return visitor !== undefined && sameSecret(presented, visitor.token)\n }\n\n /** Whether any visitor holds this token (a terminal driver checks a request with no other context). */\n knows(cookieHeader: string | undefined | null, presented: unknown): boolean {\n return this.accepts(this.of(cookieHeader), presented)\n }\n\n /** The question's length check, which comes before anything is counted. */\n checkMessage(message: string): Refusal | undefined {\n const most = this.shared ? OWNER_MESSAGE_LENGTH : this.limits.messageLength\n if (message === '' || message.length > most)\n return { error: `write a message of at most ${String(most)} characters`, status: 400 }\n return undefined\n }\n\n /**\n * Whether this visitor may start a run now. The visitor's own run going is refused first (409); then, for the Assistant, the visitor's hour, the runs going at once and the\n * day. An admitted ask is counted.\n */\n admit(visitor: Visitor<R>): Refusal | undefined {\n if (visitor.current !== undefined && !visitor.current.ended)\n return { error: 'a run is already going; wait for it to end', status: 409 }\n if (this.shared) return undefined\n const now = this.now()\n prune(visitor.asks, now - HOUR_MS)\n prune(this.day, now - DAY_MS)\n const hour = visitor.asks[0]\n if (visitor.asks.length >= this.limits.perVisitorPerHour && hour !== undefined)\n return {\n error: `You have asked ${String(this.limits.perVisitorPerHour)} questions this hour. Ask again in ${minutes(hour + HOUR_MS - now)}.`,\n status: 429,\n }\n let going = 0\n for (const other of this.byId.values())\n if (other.current !== undefined && !other.current.ended) going += 1\n if (going >= this.limits.concurrent)\n return {\n error: 'The assistant is helping other people right now. Ask again in a moment.',\n status: 503,\n }\n const first = this.day[0]\n if (this.day.length >= this.limits.perDay && first !== undefined)\n return {\n error: `The assistant has answered all the questions it can today. It is back in ${minutes(first + DAY_MS - now)}.`,\n status: 429,\n }\n visitor.asks.push(now)\n this.day.push(now)\n return undefined\n }\n\n /** How many visitors are kept (for tests and diagnostics). */\n get size(): number {\n return this.owner === undefined ? this.byId.size : 1\n }\n\n private make(): Visitor<R> {\n const id = newSecret()\n return {\n id,\n token: newSecret(),\n tag: createHash('sha256').update(id).digest('hex').slice(0, 12),\n current: undefined,\n asks: [],\n lastSeen: this.now(),\n }\n }\n\n /** Keep a new visitor; past the capacity, let go of the visitors seen longest ago that have no run going. */\n private keep(visitor: Visitor<R>): void {\n if (this.byId.size >= this.capacity) {\n const idle = [...this.byId.values()]\n .filter((other) => other.current === undefined || other.current.ended)\n .sort((a, b) => a.lastSeen - b.lastSeen)\n for (const other of idle.slice(0, this.byId.size - this.capacity + 1))\n this.byId.delete(other.id)\n }\n this.byId.set(visitor.id, visitor)\n }\n}\n\n/** Drop the times up to `since` from the front of an ascending list: an ask exactly an hour (or a day) old is out of the window. */\nfunction prune(times: number[], since: number): void {\n let drop = 0\n while (drop < times.length && (times[drop] ?? 0) <= since) drop += 1\n if (drop > 0) times.splice(0, drop)\n}\n","/**\n * The built-in agent (spec 049 slice 14): a chat panel inside the running app. The person says what they want; the app's own agent (`driver: 'agent'`) or a coding\n * agent started in the app folder (`'claude'`, `'codex'`, `'pi'`) builds it through the door, and when a plugin was installed or removed the page reloads, so the new feature\n * shows with no restart. The drivers are entries of the `drivers` service this plugin provides (`@acryldev/drivers`): chat drivers here, and other plugins (`driver-pty`) add more.\n *\n * - A middleware appends one script tag (`/api/agent-panel/panel.js`) to every HTML response of the routes mounted after it, so no page is edited.\n * - `GET /api/agent-panel/session` gives the page the drivers it may use and a token; `POST /api/agent-panel/ask` runs one message and answers server-sent events:\n * `text`, `tool`, `change`, `done`, `error`.\n * - Only the app's own page may ask (a same-origin request carrying the token), one run at a time, and every ask is written to `.acryl/audit/agent-panel.jsonl`.\n * - Who asks (`visitors.ts`): in development one person, the owner, whose pages share one token and one run. As the Assistant each visitor has their own token, run and\n * replay, named by an HttpOnly cookie: no visitor sees, follows or stops another's run, and the asks are bounded (per visitor per hour, per day, runs at once).\n * - The routes live under the app's mount: the root of the app's own server, or the frame's prefix (`/app`) when the frame hosts it, where the host's own\n * `/api` routes would otherwise answer first. The row's `mount` config names it.\n * - Development only: the plugin does nothing with `NODE_ENV=production` or `ACRYL_DOOR=off`, except as the Assistant (`assistant: true`): then it runs in production too,\n * docked open on the right, with the app's own agent only. The app gives that agent the page tools alone and a page-only door, so it uses the app for a visitor and\n * cannot change it (src/app.ts, `ACRYL_ASSISTANT=on`). In the ACRYL frame's canvas the panel follows the frame's view: Build hides it, and Preview shows it only as\n * the Assistant and only when the app's production environment names one (`assistantInProduction` in the session).\n */\nimport { appendFileSync, mkdirSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type {} from '@acryldev/agent'\nimport type { ChatDriver, Driver } from '@acryldev/drivers'\nimport type {} from '@acryldev/extensions'\nimport { clientModules } from '@acryldev/node-server/client-modules'\nimport { Acryl, type MiddlewareHandler } from '@acryldev/router'\nimport { streamSSE, type UpgradeWebSocket } from '@acryldev/router/helpers'\nimport { pageAuthority } from '@acryldev/router/middleware'\nimport type { Context } from '@deepseek-ai/cordis'\nimport {\n agentDriver,\n availableHeadless,\n type HeadlessName,\n headlessDriver,\n whyNotChat,\n} from './headless.ts'\nimport { mountedBase, mountedPrefix } from './mount.ts'\nimport { provideDrivers } from './registry.ts'\nimport { type AssistantLimits, type Visitor, Visitors } from './visitors.ts'\n\nexport type {\n ChatDriver,\n ChatEvent,\n Driver,\n Drivers,\n TerminalDriver,\n TerminalSession,\n} from '@acryldev/drivers'\n\nexport const name = 'agent-panel'\nexport const inject = ['router', 'agent', 'extensions', 'appInstance']\n\n/** The panel's own routes, fixed relative to the app's mount. */\nconst PANEL_PATH = '/api/agent-panel'\n\n/** The one driver the Assistant offers its visitors: the app's own agent, held to the page tools. */\nconst ASSISTANT_DRIVER = 'agent'\n\n/** The slice of the door the panel uses; the door is optional (it is a development plugin, and a different row). */\ninterface DoorPort {\n driveFor(windowId: string): () => void\n}\nconst CLIENT_DIR = join(import.meta.dirname, 'client')\n\nexport interface PanelConfig {\n /** Headless coding agents to offer besides the app's own agent; default: the ones found on the machine. */\n drivers?: readonly HeadlessName[]\n /**\n * The URL prefix the app is mounted at: empty on the app's own server, `/app` when the ACRYL frame hosts it (the same prefix `makeApp` and\n * `routerHttp.mount` take). The panel's routes, script tag and client live under it, so they belong to the app and are served wherever it is.\n */\n mount?: string\n /** The Assistant: a production panel for the app's visitors, with the app's own agent only (no coding agent, no terminal). Runs with `NODE_ENV=production`. */\n assistant?: boolean\n /** The Assistant's limits on what visitors may ask (`visitors.ts` has the defaults); the development panel has none but one run at a time. */\n limits?: AssistantLimits\n}\n\n/** Whether the page came over https (directly, or through a proxy that says so): the visitor cookie is then Secure. */\nconst overHttps = (url: string, headers: Headers): boolean =>\n url.startsWith('https:') || headers.get('x-forwarded-proto')?.split(',')[0]?.trim() === 'https'\n\n/** The panel's routes under a checked mount: empty, or an absolute path such as `/app` with no trailing slash (the `routerHttp.mount` rule). */\nconst panelPrefix = (mount: string | undefined): string =>\n mountedPrefix(mount, PANEL_PATH, 'agent-panel')\n\n/** Whether a request comes from the app's own page: a browser says so itself (`Sec-Fetch-Site: same-origin`), or the Origin is the Host. */\nexport function fromOwnPage(headers: Headers): boolean {\n const site = headers.get('sec-fetch-site')\n if (site !== null) return site === 'same-origin'\n const origin = headers.get('origin')\n const host = headers.get('host')\n return origin !== null && host !== null && new URL(origin).host === host\n}\n\nexport function apply(ctx: Context, config: PanelConfig = {}): void {\n const assistant = config.assistant === true\n if (process.env.ACRYL_DOOR === 'off' || (process.env.NODE_ENV === 'production' && !assistant))\n return\n const PREFIX = panelPrefix(config.mount)\n // The panel's routes mount at the app's own mount and keep the fixed path inside (`/app` + `/api/agent-panel/...`); the frame's router prefixes the\n // mount path itself, so a prefix inside the routes too would become `/app/app/...`. PREFIX stays absolute for the page's script tag and client URLs.\n const MOUNT = mountedBase(config.mount, 'agent-panel')\n const root = ctx.appInstance.root\n const visitors = new Visitors<Run>({\n shared: !assistant,\n ...(config.limits === undefined ? {} : { limits: config.limits }),\n })\n /** The visitor of a request that must carry its token, or `undefined` when it does not come from the app's own page with the right one. */\n const caller = (headers: Headers, presented: unknown): Visitor<Run> | undefined => {\n if (!fromOwnPage(headers)) return undefined\n const visitor = visitors.of(headers.get('cookie'))\n return visitors.accepts(visitor, presented) ? visitor : undefined\n }\n const auditFile = join(root, '.acryl', 'audit', 'agent-panel.jsonl')\n const audit = (entry: Record<string, unknown>): void => {\n try {\n mkdirSync(dirname(auditFile), { recursive: true })\n appendFileSync(auditFile, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\\n`)\n } catch {\n // The audit never stops a run.\n }\n }\n // The Assistant's visitors use the app's own agent and nothing else: no plugin's driver (a terminal, a coding agent) is open to them, whatever plugins the app mounts.\n const registry = provideDrivers(\n ctx,\n (headers) => !assistant && caller(headers, headers.get('x-agent-panel-token')) !== undefined,\n )\n const offered = (): Driver[] =>\n registry.list().filter((driver) => !assistant || driver.name === ASSISTANT_DRIVER)\n ctx.effect(() => registry.register(agentDriver(ctx)))\n if (!assistant)\n for (const program of availableHeadless(config.drivers))\n ctx.effect(() => registry.register(headlessDriver(program, root)))\n\n const tag = `<script type=\"module\" src=\"${PREFIX}/panel.js\"></script>`\n const addScript = async (c: { res: Response }, next: () => Promise<void>): Promise<void> => {\n await next()\n if (!(c.res.headers.get('content-type') ?? '').includes('text/html')) return\n const html = await c.res.text()\n if (html.includes(`${PREFIX}/panel.js`)) {\n c.res = new Response(html, c.res)\n return\n }\n const headers = new Headers(c.res.headers)\n headers.delete('content-length')\n c.res = new Response(\n html.includes('</body>') ? html.replace('</body>', `${tag}</body>`) : html + tag,\n { status: c.res.status, headers },\n )\n }\n // The script tag on every HTML page the app answers, whenever the plugin that serves the page was mounted (a plugin an agent built loads at boot, before this one, after a restart).\n // An app whose router copy is older has no `wrap`: the tag is then added to the pages of the routes mounted after this plugin only.\n const router = ctx.router as unknown as { wrap?: (middleware: typeof addScript) => unknown }\n const wrapped = typeof router.wrap === 'function'\n if (wrapped) router.wrap?.(addScript)\n const app = new Acryl()\n .use('*', async (c, next) => {\n if (wrapped) return next()\n await addScript(c, next)\n })\n .get(`${PANEL_PATH}/panel.js`, (c) =>\n c.body(\n `import { start } from '${PREFIX}/client/main.ts'\\nstart(${JSON.stringify(PREFIX)})\\n`,\n 200,\n {\n 'content-type': 'text/javascript; charset=utf-8',\n 'cache-control': 'no-cache',\n },\n ),\n )\n .route(`${PANEL_PATH}/client`, clientModules({ root: CLIENT_DIR, mount: `${PREFIX}/client` }))\n .get(`${PANEL_PATH}/session`, (c) => {\n if (!fromOwnPage(c.req.raw.headers))\n return c.json({ error: \"only the app's own page may use the panel\" }, 403)\n const { visitor, setCookie } = visitors.session(\n c.req.header('cookie'),\n overHttps(c.req.url, c.req.raw.headers),\n )\n if (setCookie !== undefined) c.header('set-cookie', setCookie)\n return c.json({\n token: visitor.token,\n ...(assistant ? { assistant: true } : {}),\n // The frame's Preview shows the app as production would. This is the fact that lets its page show the Assistant when the app's production\n // environment names it (ACRYL_ASSISTANT=on), even though the frame host itself runs in development and never mounts the Assistant row.\n ...(process.env.ACRYL_ASSISTANT === 'on' ? { assistantInProduction: true } : {}),\n // A terminal driver names the browser module that draws its view and the prefix its endpoints live under: the plugin that owns the view\n // also knows where the app is mounted, so the panel never guesses either.\n drivers: offered().map((driver) => ({\n name: driver.name,\n kind: driver.kind,\n ...(driver.kind === 'terminal' ? { view: driver.view } : {}),\n })),\n })\n })\n .post(`${PANEL_PATH}/ask`, async (c) => {\n const visitor = caller(c.req.raw.headers, c.req.header('x-agent-panel-token'))\n if (visitor === undefined) return c.json({ error: \"only the app's own page may ask\" }, 403)\n const body = (await c.req.json().catch(() => ({}))) as {\n message?: unknown\n driver?: unknown\n page?: unknown\n }\n const checked = checkAsk(visitor, body.message, body.driver)\n if ('error' in checked) return c.json({ error: checked.error }, checked.status)\n const run = startRun(\n visitor,\n checked.driverName,\n checked.message,\n checked.driver,\n pageOf(body.page),\n )\n return follow(c, run, false)\n })\n // Stop: the only thing that cancels a run. A page that goes away (a reload, a move to another page, a closed tab) does not: the agent goes on, and the page picks it up again.\n .post(`${PANEL_PATH}/stop`, (c) => {\n const visitor = caller(c.req.raw.headers, c.req.header('x-agent-panel-token'))\n if (visitor === undefined)\n return c.json({ error: \"only the app's own page may stop a run\" }, 403)\n // A visitor's own run, never another's.\n visitor.current?.cancel.abort()\n return c.json({ ok: true })\n })\n // The latest run, for a page that just loaded: what was asked, then every event so far, then the rest as it happens (until the run ends).\n .get(`${PANEL_PATH}/run`, (c) => {\n const visitor = caller(c.req.raw.headers, c.req.header('x-agent-panel-token'))\n if (visitor === undefined)\n return c.json({ error: \"only the app's own page may read the run\" }, 403)\n return visitor.current === undefined\n ? c.json({ run: null })\n : follow(c, visitor.current, true)\n })\n /**\n * What `/ask` and the socket's `ask` both check: a message of a sensible size, a chat driver that is here, and no run of this visitor going; for the Assistant also its\n * limits (an admitted ask is counted).\n */\n const checkAsk = (\n visitor: Visitor<Run>,\n rawMessage: unknown,\n rawDriver: unknown,\n ):\n | { message: string; driverName: string; driver: ChatDriver }\n | { error: string; status: 400 | 409 | 429 | 503 } => {\n const message = typeof rawMessage === 'string' ? rawMessage.trim() : ''\n const driverName = typeof rawDriver === 'string' ? rawDriver : 'agent'\n const tooLong = visitors.checkMessage(message)\n if (tooLong !== undefined) return tooLong\n const driver = offered().find((one) => one.name === driverName)\n if (driver?.kind !== 'chat') {\n const chat = offered()\n .filter((d) => d.kind === 'chat')\n .map((d) => d.name)\n .join(', ')\n const why = whyNotChat(driverName, driver?.kind)\n return {\n error: `the driver \"${driverName}\" is not available here${why === undefined ? '' : `: ${why}`} (chat drivers: ${chat})`,\n status: 400,\n }\n }\n const refused = visitors.admit(visitor)\n if (refused !== undefined) {\n if (assistant) audit({ ask: 'refused', visitor: visitor.tag, status: refused.status })\n return refused\n }\n return { message, driverName, driver }\n }\n /** One run of an agent: its events as they came, and who is following. It lives in the app, not in a page. */\n interface Run {\n readonly id: number\n readonly driver: string\n readonly message: string\n readonly startedAt: number\n readonly events: Array<{ event: string; data: unknown }>\n readonly followers: Set<(item: { event: string; data: unknown }) => void>\n readonly cancel: AbortController\n ended: boolean\n endedAt?: number\n }\n let runs = 0\n /** The door's id of the page that asked, when it sent one that looks like it. */\n const pageOf = (raw: unknown): string | undefined =>\n typeof raw === 'string' && /^[A-Za-z0-9-]{1,80}$/u.test(raw) ? raw : undefined\n const startRun = (\n visitor: Visitor<Run>,\n driverName: string,\n message: string,\n driver: ChatDriver,\n page?: string,\n ): Run => {\n runs += 1\n const run: Run = {\n id: runs,\n driver: driverName,\n message,\n startedAt: Date.now(),\n events: [],\n followers: new Set(),\n cancel: new AbortController(),\n ended: false,\n }\n visitor.current = run\n const who = assistant ? { visitor: visitor.tag } : {}\n const emit = (event: string, data: unknown): void => {\n const item = { event, data }\n run.events.push(item)\n for (const follower of [...run.followers]) follower(item)\n }\n let changed = false\n const off = ctx.on('extensions/changed', (extension: string, action: string) => {\n changed = true\n emit('change', { extension, action })\n })\n // The run ends when the plugin unloads; the effect goes when the run ends, so runs do not pile up on the plugin.\n const unloadStops = ctx.effect(() => () => run.cancel.abort(), `agent-panel: run ${runs}`)\n audit({ ask: 'start', ...who, driver: driverName, characters: message.length })\n // The agent's door calls name no window: while this run goes, they are for the page whose panel asked, not for another tab or window that happens to be open.\n const door = page === undefined ? undefined : (ctx.get('door') as DoorPort | undefined)\n const releasePage = door?.driveFor(page as string)\n void (async () => {\n try {\n for await (const { event, data } of driver.start({\n message,\n signal: run.cancel.signal,\n ...(page === undefined ? {} : { page }),\n }))\n emit(event, data)\n emit('done', { changed })\n } catch (error) {\n emit('error', { message: error instanceof Error ? error.message : String(error) })\n } finally {\n off()\n releasePage?.()\n run.ended = true\n run.endedAt = Date.now()\n audit({ ask: 'end', ...who, driver: driverName, changed })\n for (const follower of [...run.followers]) follower({ event: 'end', data: {} })\n void unloadStops()\n }\n })()\n return run\n }\n /**\n * Follow a run into `write`: a `run` event (what it is, whether it already ended) when `announce`, the events so far, then the new ones until it ends. Following does not keep the\n * run alive. `detach` stops following (the page went away); `done` settles when the run ended or the following was detached.\n */\n const pump = (\n run: Run,\n announce: boolean,\n write: (event: string, data: unknown) => void | Promise<void>,\n ): { done: Promise<void>; detach(): void } => {\n const queue: Array<{ event: string; data: unknown }> = [...run.events]\n if (announce)\n queue.unshift({\n event: 'run',\n data: {\n id: run.id,\n driver: run.driver,\n message: run.message,\n startedAt: run.startedAt,\n ended: run.ended,\n endedAt: run.endedAt ?? null,\n },\n })\n let wake: (() => void) | undefined\n const follower = (item: { event: string; data: unknown }): void => {\n queue.push(item)\n wake?.()\n }\n if (!run.ended) run.followers.add(follower)\n let open = true\n const done = (async () => {\n try {\n while (open) {\n const item = queue.shift()\n if (item === undefined) {\n if (run.ended) break\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n wake = undefined\n continue\n }\n if (item.event === 'end') break\n await write(item.event, item.data)\n }\n } finally {\n run.followers.delete(follower)\n }\n })()\n return {\n done,\n detach: () => {\n open = false\n run.followers.delete(follower)\n wake?.()\n },\n }\n }\n /** Follow a run as server-sent events. */\n const follow = (c: Parameters<typeof streamSSE>[0], run: Run, announce: boolean): Response =>\n streamSSE(c, async (stream) => {\n const following = pump(run, announce, (event, data) =>\n stream.writeSSE({ event, data: JSON.stringify(data) }),\n )\n stream.onAbort(following.detach)\n await following.done\n })\n // The same runs over a WebSocket, which is not one of the browser's six connections per host: a page that streams its own state in two windows, with a run going, would otherwise\n // queue the panel's Stop and the door's answers behind them. A WebSocket has no CORS and cannot set a header, so the Origin must be this app's own and the first frame carries the\n // token. Frames: up `{ t: 'hello', token }`, then `{ t: 'ask', message, driver }`, `{ t: 'follow' }` or `{ t: 'stop' }`; down `{ e: <event>, d: <data> }`, as the stream's events.\n // The server row comes after this plugin in a blend, so the WebSocket form is mounted when the server appears (and not at all without one that upgrades or without the `ws` package).\n ctx.inject(['nodeServer'], (inner) => {\n let upgrade: UpgradeWebSocket\n try {\n upgrade = (\n inner as unknown as { nodeServer: { upgrades(): UpgradeWebSocket } }\n ).nodeServer.upgrades()\n } catch {\n return\n }\n const ws = new Acryl()\n const own: MiddlewareHandler = async (c, next) => {\n const authority = pageAuthority(c)\n const origin = c.req.header('origin')\n const site = c.req.header('sec-fetch-site')\n if (\n authority === undefined ||\n origin === undefined ||\n origin !== authority.origin ||\n (site !== undefined && site !== 'same-origin')\n )\n return c.json({ error: \"only the app's own page may use the panel\" }, 403)\n await next()\n }\n ws.get(\n `${PREFIX}/run/ws`,\n own,\n upgrade(\n (c) => {\n // The visitor the socket's cookie names (the owner in development): its hello must carry that visitor's token, and it reaches that visitor's runs only.\n const visitor = visitors.of(c.req.header('cookie'))\n let authed = false\n let following: { detach(): void } | undefined\n let hello: NodeJS.Timeout | undefined\n return {\n onOpen(_event, ws) {\n hello = setTimeout(() => ws.close(4401, 'no token'), 5000)\n },\n onMessage(event, ws) {\n if (typeof event.data !== 'string') return\n let message: {\n t?: unknown\n token?: unknown\n message?: unknown\n driver?: unknown\n page?: unknown\n }\n try {\n message = JSON.parse(event.data) as typeof message\n } catch {\n return\n }\n if (!authed) {\n if (message.t !== 'hello' || !visitors.accepts(visitor, message.token)) {\n ws.close(4401, 'token')\n return\n }\n authed = true\n if (hello !== undefined) clearTimeout(hello)\n // The page waits for this before it counts the socket as open: a token it was given by an earlier start of the app is refused (4401) and it asks for a new one.\n ws.send(JSON.stringify({ e: 'accepted', d: {} }))\n return\n }\n const send = (e: string, d: unknown): void => {\n ws.send(JSON.stringify({ e, d }))\n }\n if (visitor === undefined) return\n if (message.t === 'stop') {\n visitor.current?.cancel.abort()\n return\n }\n if (following !== undefined) return\n const watch = (run: Run, announce: boolean): void => {\n const pumped = pump(run, announce, send)\n following = pumped\n void pumped.done.then(() => ws.close(1000, 'run ended'))\n }\n if (message.t === 'ask') {\n const checked = checkAsk(visitor, message.message, message.driver)\n if ('error' in checked) {\n send('error', { message: checked.error })\n ws.close(1000, 'refused')\n return\n }\n watch(\n startRun(\n visitor,\n checked.driverName,\n checked.message,\n checked.driver,\n pageOf(message.page),\n ),\n false,\n )\n } else if (message.t === 'follow') {\n if (visitor.current === undefined) {\n send('idle', {})\n ws.close(1000, 'no run')\n } else watch(visitor.current, true)\n }\n },\n onClose() {\n if (hello !== undefined) clearTimeout(hello)\n following?.detach()\n },\n }\n },\n { textOnly: true },\n ),\n )\n inner.router.route('/', ws)\n })\n ctx.router.route(MOUNT === '' ? '/' : MOUNT, app)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAaA,MAAa,iBAAiB;AAc9B,MAAa,iBAA4C;CACvD,mBAAmB;CACnB,QAAQ;CACR,YAAY;CACZ,eAAe;AACjB;;AAGA,MAAM,uBAAuB;AAC7B,MAAM,UAAU,OAAU;AAC1B,MAAM,SAAS,KAAK;;AAEpB,MAAM,mBAAmB;AAiCzB,MAAM,kBAA0B,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;;AAGpE,SAAgB,YAAY,QAAmC,MAAkC;CAC/F,IAAI,WAAW,KAAA,KAAa,WAAW,MAAM,OAAO,KAAA;CACpD,KAAK,MAAM,QAAQ,OAAO,MAAM,GAAG,GAAG;EACpC,MAAM,KAAK,KAAK,QAAQ,GAAG;EAC3B,IAAI,OAAO,IAAI;EACf,IAAI,KAAK,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,MAAM,MAAM,OAAO,KAAK,MAAM,KAAK,CAAC,CAAC,CAAC,KAAK;CACxE;AAEF;;AAGA,SAAgB,WAAW,WAAoB,UAA2B;CACxE,IAAI,OAAO,cAAc,UAAU,OAAO;CAC1C,MAAM,IAAI,OAAO,KAAK,SAAS;CAC/B,MAAM,IAAI,OAAO,KAAK,QAAQ;CAC9B,OAAO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