agent-yes 1.303.1 → 1.304.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 (184) hide show
  1. package/README.md +54 -0
  2. package/default.config.yaml +5 -5
  3. package/dist/{JsonlStore-BpYZZTap.js → JsonlStore-CB_0sfdT.js} +5 -4
  4. package/dist/{SUPPORTED_CLIS-Dq9Lq9WJ.js → SUPPORTED_CLIS-C_1IiOj3.js} +2 -2
  5. package/dist/SUPPORTED_CLIS-Do3GHAY1.js +12 -0
  6. package/dist/{agentShare-suB6yPgO.js → agentShare-BvpEm-Fr.js} +10 -9
  7. package/dist/{askCli-BU3CNCLU.js → askCli-KmMf-3wA.js} +6 -6
  8. package/dist/{browser-BmxN1Ur9.js → browser-BAFPmEvN.js} +2 -2
  9. package/dist/{callback-Ctj3_Wxp.js → callback-BiSUhjw7.js} +6 -6
  10. package/dist/callback-SqLD2mMX.js +17 -0
  11. package/dist/{callbackCore-DSJWhqAe.js → callbackCore-BZ_10zyc.js} +1 -1
  12. package/dist/{callbackCore-BesbQ6-Z.js → callbackCore-Deve5pv3.js} +1 -1
  13. package/dist/{channels-j5nWuzlQ.js → channels-Y36S0ccW.js} +2 -2
  14. package/dist/cli.js +118 -13
  15. package/dist/{cmdDsh-2LP0grim.js → cmdDsh-DZ8bLsH7.js} +1 -1
  16. package/dist/cmdKill-CzSBfWmx.js +116 -0
  17. package/dist/{cmdPs-wc1j85fi.js → cmdPs-DBt23Qz0.js} +11 -10
  18. package/dist/{cwdConflictWarn-skQSMwEh.js → cwdConflictWarn-y-epQyOj.js} +21 -5
  19. package/dist/{cwdPassthroughHint-BUbWMoz0.js → cwdPassthroughHint-CzWh0hrw.js} +1 -1
  20. package/dist/{expose-Dawq1LxC.js → expose-Bhsn5yUz.js} +2 -2
  21. package/dist/forceKill-BDqxx4uQ.js +44 -0
  22. package/dist/{forkNested-CavHyWzA.js → forkNested-3heLs5XC.js} +45 -5
  23. package/dist/{globalPidIndex-CRB5KtyL.js → globalPidIndex-BsjlId-h.js} +6 -5
  24. package/dist/{globalPidIndex-BftWlg2V.js → globalPidIndex-uoz8Esqz.js} +2 -2
  25. package/dist/{hist-Cs0KFSUW.js → hist-DY16wm7g.js} +1 -1
  26. package/dist/{identity-DA7YI9km.js → identity-C0MxfwI2.js} +1 -1
  27. package/dist/{identity-Bk-aG_xl.js → identity-Ckav3-Up.js} +1 -1
  28. package/dist/index.js +7 -7
  29. package/dist/{initMsg-CcTqFtsp.js → initMsg-BEVDWYnv.js} +1 -1
  30. package/dist/{initMsg-D9KJnfgC.js → initMsg-GPU52N-j.js} +1 -1
  31. package/dist/liagent/box-BSIrRRc_.js +2320 -0
  32. package/dist/liagent/box-DloywR57.d.ts +409 -0
  33. package/dist/liagent/box.d.ts +3 -0
  34. package/dist/liagent/box.js +3 -0
  35. package/dist/liagent/cli.d.ts +1 -0
  36. package/dist/liagent/cli.js +908 -0
  37. package/dist/liagent/client.d.ts +28 -0
  38. package/dist/liagent/client.js +240 -0
  39. package/dist/liagent/echo-BvzPSI0x.js +86 -0
  40. package/dist/liagent/echo-W2RcMEny.d.ts +38 -0
  41. package/dist/liagent/hub.d.ts +405 -0
  42. package/dist/liagent/hub.js +1831 -0
  43. package/dist/liagent/index.d.ts +14 -0
  44. package/dist/liagent/index.js +10 -0
  45. package/dist/liagent/liagent.js +339 -0
  46. package/dist/liagent/mic-audio-C3Shud_F.js +754 -0
  47. package/dist/liagent/mic-audio-DMCWtEI-.d.ts +317 -0
  48. package/dist/liagent/mic-button-CtZHFBSG.js +651 -0
  49. package/dist/liagent/mic-button-Y0ioPetQ.d.ts +248 -0
  50. package/dist/liagent/mic.d.ts +3 -0
  51. package/dist/liagent/mic.js +4 -0
  52. package/dist/liagent/progress-CJs08bXb.js +473 -0
  53. package/dist/liagent/progress-CfE-meHr.d.ts +205 -0
  54. package/dist/liagent/progress.d.ts +2 -0
  55. package/dist/liagent/progress.js +3 -0
  56. package/dist/liagent/protocol.d.ts +324 -0
  57. package/dist/liagent/protocol.js +504 -0
  58. package/dist/liagent/speech-rate-DXeJjRTc.js +42 -0
  59. package/dist/liagent/state-tree-BZCmAknI.js +353 -0
  60. package/dist/liagent/tree-BrR7NwMf.js +710 -0
  61. package/dist/liagent/tree-HB9RhX_H.d.ts +295 -0
  62. package/dist/liagent/tree.d.ts +2 -0
  63. package/dist/liagent/tree.js +4 -0
  64. package/dist/liagent/ui-strings-B03le3fh.d.ts +27 -0
  65. package/dist/liagent/ui-strings-CJIwW5Gf.js +794 -0
  66. package/dist/liagent/ui.d.ts +394 -0
  67. package/dist/liagent/ui.js +5 -0
  68. package/dist/liagent/voice-D7yeS9VM.js +802 -0
  69. package/dist/liagent/voice-Qo7SCgi8.d.ts +308 -0
  70. package/dist/liagent/voice.d.ts +3 -0
  71. package/dist/liagent/voice.js +4 -0
  72. package/dist/{notifyDaemon-C7GlfJ1E.js → notifyDaemon-DkUB7GV2.js} +10 -9
  73. package/dist/{openBrowser-1cIo4dJL.js → openBrowser-CQAOIrD6.js} +1 -1
  74. package/dist/oxmgrService-DlYHmqyI.js +37 -0
  75. package/dist/oxmgrService-o9L3I6FX.js +3 -0
  76. package/dist/{parentLink-DoEWVGld.js → parentLink-BcAYcO9L.js} +2 -2
  77. package/dist/{parentLink-B58V1RVd.js → parentLink-MBUD3oY2.js} +2 -2
  78. package/dist/{parentPingLoop-C73bbmCE.js → parentPingLoop-DDO592Wh.js} +5 -5
  79. package/dist/{pidStore-433kvh9D.js → pidStore-C50VPk3E.js} +3 -3
  80. package/dist/pidStore-COkPjpW8.js +6 -0
  81. package/dist/{procStats-BvmrBrOs.js → procStats-DwTxj3rs.js} +1 -1
  82. package/dist/{remotes-MfdV9M8u.js → remotes-BqLoB5GR.js} +2 -2
  83. package/dist/{remotes-DevcBeLl.js → remotes-BsMGvAay.js} +3 -3
  84. package/dist/{roomReplyAlias-DFqg_6IU.js → roomReplyAlias-B-v76TA8.js} +3 -3
  85. package/dist/roomReplyAlias-BzWUBkQy.js +6 -0
  86. package/dist/{rustBinary-7VK7oLlW.js → rustBinary-BrJ2p8wy.js} +2 -2
  87. package/dist/{rustBinary-BV4LxMMn.js → rustBinary-vpfpWj1q.js} +2 -2
  88. package/dist/{schedule-Dp0qkNO1.js → schedule-Bzjhl6-h.js} +15 -44
  89. package/dist/schedulesCli-CLqieyQZ.js +784 -0
  90. package/dist/senderAncestry-CVHeKk1Y.js +173 -0
  91. package/dist/senderAncestry-KhAUPCQs.js +3 -0
  92. package/dist/{serve-BpOIIOVc.js → serve-XwFYE0cE.js} +67 -69
  93. package/dist/{serveRust-CbBrcUrg.js → serveRust-BfWkeL6T.js} +31 -4
  94. package/dist/{setup-DdIBk6Iv.js → setup-D4-s2VZw.js} +5 -5
  95. package/dist/{share-w5oRbvlj.js → share-CbFetL5H.js} +1 -1
  96. package/dist/{share-DrS3LYqf.js → share-_TPYAGWC.js} +1 -1
  97. package/dist/{shareCmd-DDENkBW2.js → shareCmd-DUBsVI3e.js} +10 -10
  98. package/dist/spawnGate-Dfj9V76w.js +5 -0
  99. package/dist/{spawnGate-lr3tvA6U.js → spawnGate-Dj_WaS29.js} +3 -3
  100. package/dist/{subcommands-DxgvDmZX.js → subcommands-B7YZJL8n.js} +471 -307
  101. package/dist/subcommands-BZPxFgkT.js +15 -0
  102. package/dist/{systemPathLink-SjUzgSiq.js → systemPathLink-Y3iC7bYV.js} +1 -1
  103. package/dist/{terminal-C2h7tpe0.js → terminal-13cGj3h6.js} +2 -2
  104. package/dist/terminal.js +1 -1
  105. package/dist/{todoAutomation-TTp_Qz9G.js → todoAutomation-CKlrxuZv.js} +2 -2
  106. package/dist/{todoCli-BWm5nZE0.js → todoCli-CU9vSJSJ.js} +6 -6
  107. package/dist/{todoIdentity-BvXZKWJI.js → todoIdentity-CzS1e7VL.js} +2 -2
  108. package/dist/{todoStore-C9RTz0Vs.js → todoStore-msRCEUi1.js} +2 -2
  109. package/dist/{tray-BeRSozJz.js → tray-CLktEN3G.js} +1 -1
  110. package/dist/{trayApp-QQjqhDv1.js → trayApp-5_OlvQcz.js} +2 -2
  111. package/dist/trayApp-DkAPo0m6.js +5 -0
  112. package/dist/{ts-6LF7f4fx.js → ts-njuddXQz.js} +126 -57
  113. package/dist/{versionChecker-Bc62HNf6.js → versionChecker-BJycAanp.js} +2 -2
  114. package/dist/{webrtcLink-va_gAR77.js → webrtcLink-DcvacEci.js} +1 -1
  115. package/dist/{webrtcLink-SsInrVHU.js → webrtcLink-WxS1nTIs.js} +1 -1
  116. package/dist/{webrtcRemote-BlGyNZDC.js → webrtcRemote-C3xQyf3u.js} +2 -2
  117. package/dist/{widget-Crb5zeHL.js → widget-DmRwOlco.js} +3 -3
  118. package/dist/widgets.js +1 -1
  119. package/dist/{workspaceConfig-BLWB5Wu9.js → workspaceConfig-DBgsu81B.js} +1 -1
  120. package/dist/{ws-DIbwNz8Z.js → ws-ByO6JO6m.js} +3 -3
  121. package/dist/{ws-BRhPG1Vy.js → ws-D0-Jg88z.js} +9 -8
  122. package/lab/ui/index.html +1 -1
  123. package/lab/ui/lab/posts/2026-08-11-slack-term-safe-writes.md +1 -1
  124. package/package.json +73 -8
  125. package/ts/JsonlStore.ts +10 -3
  126. package/ts/cli-idle.bun.spec.ts +1 -1
  127. package/ts/cli-idle.spec.ts +1 -1
  128. package/ts/cli.ts +35 -0
  129. package/ts/cmdKill.bun.spec.ts +155 -0
  130. package/ts/cmdKill.spec.ts +155 -0
  131. package/ts/cmdKill.ts +183 -0
  132. package/ts/composerGuard.edges.spec.ts +91 -0
  133. package/ts/composerGuard.spec.ts +53 -6
  134. package/ts/composerGuard.ts +42 -13
  135. package/ts/conptyModeFilter.spec.ts +30 -0
  136. package/ts/conptyModeFilter.ts +53 -0
  137. package/ts/copyLiagent.ts +42 -0
  138. package/ts/cwdConflictWarn.io.spec.ts +50 -0
  139. package/ts/cwdConflictWarn.spec.ts +34 -1
  140. package/ts/cwdConflictWarn.ts +43 -5
  141. package/ts/cwdGuard.spec.ts +110 -0
  142. package/ts/cwdGuard.ts +118 -0
  143. package/ts/forceKill.ts +52 -0
  144. package/ts/forkNested.bun.spec.ts +41 -0
  145. package/ts/forkNested.spec.ts +41 -0
  146. package/ts/forkNested.ts +48 -1
  147. package/ts/globalPidIndex.edges.spec.ts +125 -0
  148. package/ts/globalPidIndex.ts +6 -2
  149. package/ts/index.ts +13 -1
  150. package/ts/interruptSend.bun.spec.ts +99 -0
  151. package/ts/interruptSend.spec.ts +99 -0
  152. package/ts/interruptSend.ts +51 -0
  153. package/ts/lockRegistry.spec.ts +49 -0
  154. package/ts/lsRenderCache.spec.ts +58 -0
  155. package/ts/needsInput.edges.spec.ts +23 -0
  156. package/ts/parseCliArgs.ts +7 -0
  157. package/ts/pushGatePlan.spec.ts +147 -0
  158. package/ts/roomReplyAlias.io.spec.ts +81 -0
  159. package/ts/schedule.ts +5 -1
  160. package/ts/schedules.bun.spec.ts +397 -0
  161. package/ts/schedules.spec.ts +397 -0
  162. package/ts/schedules.ts +517 -0
  163. package/ts/schedulesCli.ts +386 -0
  164. package/ts/sendControl.bun.spec.ts +12 -0
  165. package/ts/senderAncestry.ts +1 -3
  166. package/ts/serve.ts +22 -33
  167. package/ts/serveRust.spec.ts +29 -2
  168. package/ts/serveRust.ts +27 -2
  169. package/ts/sizeNego.bun.spec.ts +9 -2
  170. package/ts/sizeNego.spec.ts +9 -2
  171. package/ts/sizeNego.ts +10 -5
  172. package/ts/subcommands.spec.ts +348 -9
  173. package/ts/subcommands.ts +513 -93
  174. package/ts/suggestAgents.spec.ts +33 -0
  175. package/ts/terminal/browser.ts +1 -1
  176. package/ts/todoParse.spec.ts +22 -1
  177. package/ts/todoParse.ts +19 -0
  178. package/dist/SUPPORTED_CLIS-ByO5twge.js +0 -12
  179. package/dist/callback-D7qfh_7p.js +0 -16
  180. package/dist/pidStore-BRlKRHXY.js +0 -6
  181. package/dist/roomReplyAlias-DuEkSSDI.js +0 -6
  182. package/dist/spawnGate-DeQBTX-o.js +0 -5
  183. package/dist/subcommands-DmiswRy4.js +0 -14
  184. package/dist/trayApp-C4TAvRvU.js +0 -5
@@ -0,0 +1,1831 @@
1
+ import { APPROVAL_MS, CHAT_HISTORY, CHAT_MS, EVAL_GRANT_MS, MAX_EDITS, MAX_LABEL, PAGES_GONE_MS, PENDING_MS, ROOT_NODE, agentIdOf, cleanLabel, isPageId, isWithin, matchesTarget, mayAddress, nodePath, parseControllerMessage, parsePageMessage, routeTo, shortCode } from "./protocol.js";
2
+ import { t as OWNER_NAME } from "./state-tree-BZCmAknI.js";
3
+ import { C as parseTtl, E as progressKey, M as verifyProgressToken, S as parseProgressReport, T as progressEvent, _ as isPathId, a as PROGRESS_DONE_TTL_MS, c as PROGRESS_LOG_MAX, g as isOwnerTodo, i as PROGRESS_AUTO, j as mintProgressToken, l as PROGRESS_MAX_ENTRIES, p as autoNode, s as PROGRESS_LIMITS, v as isProgressId, w as pathParent, y as mergeProgress } from "./progress-CJs08bXb.js";
4
+
5
+ //#region src/progress-hub.ts
6
+ /**
7
+ * Set to "1" by routeProgress() once the host's `reader(req)` said yes; any a
8
+ * client sent is dropped first. A host that routes to the hub itself must do
9
+ * the same.
10
+ */
11
+ const PROGRESS_READER_HEADER = "x-liagent-progress-reader";
12
+ /** Writes allowed per window: per name, and for everyone together. */
13
+ const RATE = {
14
+ windowMs: 6e4,
15
+ perName: 30,
16
+ total: 120
17
+ };
18
+ /** A report is a few hundred bytes; anything much bigger is not one. */
19
+ const MAX_BODY = 4096;
20
+ /** The longest a minted token lives. */
21
+ const GRANT_MAX_MS = 10080 * 60 * 1e3;
22
+ const GRANT_DEFAULT = "8h";
23
+ /** The note a check-off writes. */
24
+ const RESOLVED_NOTE = "resolved by owner";
25
+ const PREFIX = "e:";
26
+ /** Log keys sort in the order the events happened: time, then a sequence number. */
27
+ const LOG = "l:";
28
+ const logKey = (at, seq) => `${LOG}${String(at).padStart(15, "0")}:${String(seq).padStart(6, "0")}`;
29
+ /**
30
+ * The checks routeProgress() makes before a token route reaches the hub. null = go
31
+ * on; otherwise the response. 403 from a browser (pages never use tokens),
32
+ * 503 while the secret is unset (so a writer sees why), 401 with no bearer.
33
+ */
34
+ function progressGate(req, secret) {
35
+ if (req.headers.get("origin")) return new Response("forbidden", { status: 403 });
36
+ if (!secret) return new Response("the state tree is not configured (no secret set)", { status: 503 });
37
+ if (!/^Bearer \S+$/.test(req.headers.get("authorization") ?? "")) return new Response("unauthorized", { status: 401 });
38
+ return null;
39
+ }
40
+ const json = (body, status = 200) => Response.json(body, { status });
41
+ const fail = (status, error, extra = {}) => json({
42
+ error,
43
+ ...extra
44
+ }, status);
45
+ var ProgressHub = class {
46
+ windows = /* @__PURE__ */ new Map();
47
+ seq = 0;
48
+ secret;
49
+ /**
50
+ * `env[secretVar]` (default PROGRESS_TOKEN) is the root secret: unset, every
51
+ * token route answers 401 (routeProgress answers 503 first).
52
+ */
53
+ constructor(ctx, env, now = Date.now, opts = {}) {
54
+ this.ctx = ctx;
55
+ this.now = now;
56
+ const v = env?.[opts.secretVar ?? "PROGRESS_TOKEN"];
57
+ this.secret = typeof v === "string" && v ? v : void 0;
58
+ }
59
+ async fetch(req) {
60
+ const path = new URL(req.url).pathname;
61
+ if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
62
+ if (req.headers.get(PROGRESS_READER_HEADER) !== "1") return new Response("forbidden", { status: 403 });
63
+ const pair = new WebSocketPair();
64
+ this.ctx.acceptWebSocket(pair[1]);
65
+ await this.sendSnapshot([pair[1]]);
66
+ return new Response(null, {
67
+ status: 101,
68
+ webSocket: pair[0]
69
+ });
70
+ }
71
+ const token = /^Bearer (\S+)$/.exec(req.headers.get("authorization") ?? "")?.[1] ?? "";
72
+ const auth = this.secret ? await verifyProgressToken(this.secret, token, this.now()) : null;
73
+ if (!auth) return fail(401, "unauthorized (wrong, forged or expired token)");
74
+ if (req.method === "GET") return json(await this.state());
75
+ if (req.method !== "POST") return fail(405, "GET or POST");
76
+ const body = await this.body(req);
77
+ if (body instanceof Response) return body;
78
+ if (path.endsWith("/grant")) return this.grant(auth, body);
79
+ if (path.endsWith("/resolve")) {
80
+ if (!auth.root) return fail(403, "only the owner (the root token) resolves");
81
+ const b = body;
82
+ if (!isProgressId(b.id)) return fail(400, "id is required");
83
+ const note = typeof b.note === "string" && b.note.trim() ? b.note.trim() : RESOLVED_NOTE;
84
+ return this.resolve(b.id, note.slice(0, PROGRESS_LIMITS.note));
85
+ }
86
+ const report = parseProgressReport(body);
87
+ if (report instanceof Error) return fail(400, report.message);
88
+ return this.write(auth, report);
89
+ }
90
+ async body(req) {
91
+ const raw = await req.text();
92
+ if (raw.length > MAX_BODY) return fail(413, "body too large");
93
+ try {
94
+ return JSON.parse(raw);
95
+ } catch {
96
+ return fail(400, "body must be JSON");
97
+ }
98
+ }
99
+ async all() {
100
+ return new Map([...(await this.ctx.storage.list({ prefix: PREFIX })).values()].map((e) => [e.id, e]));
101
+ }
102
+ /** The tree (newest first) and the log (oldest first). */
103
+ async state() {
104
+ return {
105
+ entries: [...(await this.all()).values()].sort((a, b) => b.at - a.at),
106
+ log: [...(await this.ctx.storage.list({ prefix: LOG })).values()]
107
+ };
108
+ }
109
+ async sendSnapshot(to = this.ctx.getWebSockets()) {
110
+ this.send(to, {
111
+ type: "snapshot",
112
+ ...await this.state()
113
+ });
114
+ }
115
+ send(to, msg) {
116
+ const data = JSON.stringify(msg);
117
+ for (const ws of to) try {
118
+ ws.send(data);
119
+ } catch {}
120
+ }
121
+ /** Counts one write; false = over the limit. */
122
+ allow(name) {
123
+ const t = this.now();
124
+ const hit = (key, max) => {
125
+ const w = this.windows.get(key);
126
+ if (!w || t - w.start >= RATE.windowMs) {
127
+ this.windows.set(key, {
128
+ start: t,
129
+ count: 1
130
+ });
131
+ return true;
132
+ }
133
+ if (w.count >= max) return false;
134
+ w.count++;
135
+ return true;
136
+ };
137
+ return hit("*", RATE.total) && hit(`n:${name}`, RATE.perName);
138
+ }
139
+ tooMany() {
140
+ const res = fail(429, "too many updates; slow down");
141
+ res.headers.set("retry-after", String(RATE.windowMs / 1e3));
142
+ return res;
143
+ }
144
+ /**
145
+ * Is `id` inside the subtree of `node`? Walks parents: a path's directory,
146
+ * otherwise the stored `parent` (`override` stands in for one node's).
147
+ */
148
+ covers(all, node, id, override) {
149
+ let x = id;
150
+ for (let i = 0; x !== void 0 && i < 64; i++) {
151
+ if (x === node) return true;
152
+ x = isPathId(x) ? pathParent(x) : x === override?.id ? override.parent : all.get(x)?.parent;
153
+ }
154
+ return false;
155
+ }
156
+ /** Would `parent` (through its own ancestors) lead back to `id`? */
157
+ loops(all, id, parent) {
158
+ return parent !== void 0 && this.covers(all, id, parent);
159
+ }
160
+ /** May this token write this report? A message for the 403, or null. */
161
+ refuse(all, auth, r, prev) {
162
+ if (auth.root) return null;
163
+ if (r.assignee.name !== auth.agent) return `this token is for ${auth.agent}; it cannot write as ${r.assignee.name}`;
164
+ const newParent = r.parent ?? prev?.parent;
165
+ if (isOwnerTodo(r.id) && !this.covers(all, auth.node, r.id)) {
166
+ if (prev && prev.creator !== auth.agent) return "this to-do was written by someone else";
167
+ const ref = r.ref ?? prev?.ref;
168
+ if (!ref || !this.covers(all, auth.node, ref)) return `a to-do for the owner needs a ref inside your scope (${auth.node})`;
169
+ return null;
170
+ }
171
+ if (prev) {
172
+ if (!this.covers(all, auth.node, r.id)) return `${r.id} is outside your scope (${auth.node})`;
173
+ if (newParent !== prev.parent) {
174
+ if (r.id === auth.node) return "you cannot move the root of your own scope";
175
+ if (!newParent || !this.covers(all, auth.node, newParent)) return `cannot move ${r.id} outside your scope (${auth.node})`;
176
+ }
177
+ if (!(prev.creator === auth.agent || prev.creator === PROGRESS_AUTO || auth.node !== r.id) && (r.status !== prev.status || r.pct !== void 0 && r.pct !== prev.pct || r.eta !== void 0 && r.eta !== prev.eta)) return `only ${prev.creator} (or a scope above) sets the status, pct and eta of ${r.id}`;
178
+ return null;
179
+ }
180
+ if (r.id === auth.node) return null;
181
+ if (!newParent) return `a new node in your scope needs a parent inside it (${auth.node})`;
182
+ if (!this.covers(all, auth.node, r.id, {
183
+ id: r.id,
184
+ parent: newParent
185
+ })) return `${r.id} is outside your scope (${auth.node})`;
186
+ return null;
187
+ }
188
+ async write(auth, r) {
189
+ const all = await this.all();
190
+ const prev = all.get(r.id);
191
+ const refused = this.refuse(all, auth, r, prev);
192
+ if (refused) return fail(403, refused);
193
+ const parent = r.parent ?? prev?.parent;
194
+ if (this.loops(all, r.id, parent)) return fail(400, `${parent} is inside ${r.id}: a loop`);
195
+ if (parent && !isPathId(parent) && !all.has(parent)) return fail(400, `unknown parent ${parent}`);
196
+ if (r.rev !== void 0 && prev && r.rev <= prev.rev) return fail(409, `stale rev ${r.rev}; ${r.id} is at ${prev.rev}`, { rev: prev.rev });
197
+ if (!this.allow(r.assignee.name)) return this.tooMany();
198
+ const t = this.now();
199
+ const missing = [];
200
+ for (let p = parent; p !== void 0 && isPathId(p) && !all.has(p); p = pathParent(p)) missing.unshift(autoNode(p, r.assignee.name, t));
201
+ const entry = mergeProgress(prev, r, t);
202
+ const events = [...missing.map((e) => progressEvent(e)), progressEvent(entry, r.note)];
203
+ const evicted = await this.store([...missing, entry], all);
204
+ for (const ev of events) await this.append(ev);
205
+ if (evicted) await this.sendSnapshot();
206
+ else for (const ev of events) this.send(this.ctx.getWebSockets(), ev);
207
+ return json({
208
+ ok: true,
209
+ entry,
210
+ readers: this.ctx.getWebSockets().length
211
+ });
212
+ }
213
+ /** Put nodes, making room past PROGRESS_MAX_ENTRIES; true if any were dropped. */
214
+ async store(entries, all) {
215
+ const fresh = entries.filter((e) => !all.has(e.id)).length;
216
+ const over = all.size + fresh - PROGRESS_MAX_ENTRIES;
217
+ let dropped = false;
218
+ if (over > 0) {
219
+ const keep = new Set(entries.map((e) => e.id));
220
+ const oldest = [...all.values()].filter((e) => !keep.has(e.id)).sort((a, b) => a.at - b.at);
221
+ const order = [...oldest.filter((e) => e.status === "done"), ...oldest.filter((e) => e.status !== "done")];
222
+ for (const e of order.slice(0, over)) {
223
+ await this.ctx.storage.delete(progressKey(e));
224
+ dropped = true;
225
+ }
226
+ }
227
+ for (const e of entries) {
228
+ await this.ctx.storage.put(progressKey(e), e);
229
+ if (e.status === "done") await this.schedule(e.at + PROGRESS_DONE_TTL_MS);
230
+ }
231
+ return dropped;
232
+ }
233
+ /** Append one event, dropping the oldest past PROGRESS_LOG_MAX. */
234
+ async append(ev) {
235
+ await this.ctx.storage.put(logKey(ev.at, this.seq++ % 1e6), ev);
236
+ const keys = [...(await this.ctx.storage.list({ prefix: LOG })).keys()];
237
+ for (const k of keys.slice(0, Math.max(0, keys.length - PROGRESS_LOG_MAX))) await this.ctx.storage.delete(k);
238
+ }
239
+ /**
240
+ * The owner checks off a node: done, `needs` cleared, the answer noted. An
241
+ * owner to-do also resolves the decision or approval it refs.
242
+ */
243
+ async resolve(id, note = RESOLVED_NOTE) {
244
+ const all = await this.all();
245
+ const target = all.get(id);
246
+ if (!target) return fail(404, `no node ${id}`);
247
+ if (!this.allow(OWNER_NAME)) return this.tooMany();
248
+ const done = [];
249
+ const close = (e) => {
250
+ const r = {
251
+ id: e.id,
252
+ assignee: {
253
+ type: "human",
254
+ name: OWNER_NAME
255
+ },
256
+ task: e.task,
257
+ status: "done",
258
+ needs: "",
259
+ note
260
+ };
261
+ done.push(mergeProgress(e, r, this.now()));
262
+ };
263
+ if (target.status !== "done") close(target);
264
+ const ref = isOwnerTodo(id) && target.ref ? all.get(target.ref) : void 0;
265
+ if (ref && ref.status !== "done" && (ref.kind === "decision" || ref.kind === "approval")) close(ref);
266
+ for (const e of done) {
267
+ const was = all.get(e.id);
268
+ const kept = {
269
+ ...e,
270
+ assignee: was.assignee,
271
+ creator: was.creator
272
+ };
273
+ await this.ctx.storage.put(progressKey(kept), kept);
274
+ await this.schedule(kept.at + PROGRESS_DONE_TTL_MS);
275
+ const ev = progressEvent(kept, note);
276
+ await this.append(ev);
277
+ this.send(this.ctx.getWebSockets(), ev);
278
+ }
279
+ return json({
280
+ ok: true,
281
+ resolved: done.map((e) => e.id)
282
+ });
283
+ }
284
+ /** Mint a token for `node` (inside the asking token's scope), signed with the root. */
285
+ async grant(auth, body) {
286
+ const b = body ?? {};
287
+ if (!isProgressId(b.node)) return fail(400, "node must be a node id");
288
+ if (typeof b.agent !== "string" || !b.agent.trim() || b.agent.length > PROGRESS_LIMITS.name) return fail(400, `agent must be a name of at most ${PROGRESS_LIMITS.name} characters`);
289
+ const ttl = parseTtl(typeof b.ttl === "string" ? b.ttl : GRANT_DEFAULT);
290
+ if (ttl instanceof Error) return fail(400, ttl.message);
291
+ if (!auth.root && !this.covers(await this.all(), auth.node, b.node)) return fail(403, `${b.node} is outside your scope (${auth.node})`);
292
+ const t = this.now();
293
+ const exp = Math.min(t + Math.min(ttl, GRANT_MAX_MS), auth.root ? Infinity : auth.exp);
294
+ const grant = {
295
+ node: b.node,
296
+ agent: b.agent.trim(),
297
+ exp,
298
+ via: auth.root ? "root" : auth.node
299
+ };
300
+ return json({
301
+ token: await mintProgressToken(this.secret, grant),
302
+ ...grant
303
+ });
304
+ }
305
+ /** Make sure the alarm goes off by `at` (one already due is the one running now). */
306
+ async schedule(at) {
307
+ const cur = await this.ctx.storage.getAlarm();
308
+ if (cur === null || cur > at || cur <= this.now()) await this.ctx.storage.setAlarm(at);
309
+ }
310
+ /** The Durable Object alarm: prune done nodes past their TTL and empty auto groups, then wait for the next. */
311
+ async alarm() {
312
+ const t = this.now();
313
+ const all = await this.all();
314
+ let pruned = 0;
315
+ let next = Infinity;
316
+ for (const e of all.values()) {
317
+ if (e.status !== "done") continue;
318
+ const due = e.at + PROGRESS_DONE_TTL_MS;
319
+ if (due <= t) {
320
+ all.delete(e.id);
321
+ await this.ctx.storage.delete(progressKey(e));
322
+ pruned++;
323
+ } else next = Math.min(next, due);
324
+ }
325
+ for (let again = pruned > 0; again;) {
326
+ again = false;
327
+ const parents = new Set([...all.values()].map((e) => e.parent));
328
+ for (const e of all.values()) if (e.creator === PROGRESS_AUTO && e.kind === "group" && !parents.has(e.id)) {
329
+ all.delete(e.id);
330
+ await this.ctx.storage.delete(progressKey(e));
331
+ again = true;
332
+ }
333
+ }
334
+ if (next !== Infinity) await this.ctx.storage.setAlarm(next);
335
+ if (pruned) await this.sendSnapshot();
336
+ }
337
+ /** The owner's page checks off a node: {type:"resolve", id, note?}. Nothing else is heard. */
338
+ async webSocketMessage(_ws, raw) {
339
+ let m;
340
+ try {
341
+ m = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw));
342
+ } catch {
343
+ return;
344
+ }
345
+ if (m?.type !== "resolve" || !isProgressId(m.id)) return;
346
+ const note = typeof m.note === "string" && m.note.trim() ? m.note.trim() : RESOLVED_NOTE;
347
+ await this.resolve(m.id, note.slice(0, PROGRESS_LIMITS.note));
348
+ }
349
+ webSocketClose(ws, code) {
350
+ try {
351
+ ws.close(code === 1005 ? 1e3 : code);
352
+ } catch {}
353
+ }
354
+ webSocketError(ws) {
355
+ this.webSocketClose(ws, 1011);
356
+ }
357
+ };
358
+ /**
359
+ * A ProgressHub class with these options baked in, to export from your Worker
360
+ * as the Durable Object: `export const ProgressHub = progressHub()`.
361
+ */
362
+ function progressHub(opts = {}) {
363
+ return class extends ProgressHub {
364
+ constructor(ctx, env) {
365
+ super(ctx, env, Date.now, opts);
366
+ }
367
+ };
368
+ }
369
+ /**
370
+ * Route a request to the progress hub if it is under `path`; null otherwise
371
+ * (so the site's own routes go on). A WebSocket is a reader: from an allowed
372
+ * Origin and only if `reader(req)` says so, marked with
373
+ * PROGRESS_READER_HEADER. Anything else is a writer (progressGate: no
374
+ * Origin, a secret set, a bearer token), forwarded without that header.
375
+ */
376
+ async function routeProgress(req, ns, opts) {
377
+ const url = new URL(req.url);
378
+ const path = (opts.path ?? "/api/progress").replace(/\/+$/, "");
379
+ if (url.pathname !== path && !url.pathname.startsWith(`${path}/`)) return null;
380
+ const headers = new Headers(req.headers);
381
+ headers.delete(PROGRESS_READER_HEADER);
382
+ const hub = ns.get(ns.idFromName(opts.name ?? "progress"));
383
+ if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") {
384
+ const refused = progressGate(req, opts.secret);
385
+ if (refused) return refused;
386
+ return hub.fetch(new Request(req, { headers }));
387
+ }
388
+ if (!pageOriginAllowed(req, opts.allowedOrigins)) return new Response("forbidden origin", { status: 403 });
389
+ let ok = false;
390
+ try {
391
+ ok = await opts.reader(req) === true;
392
+ } catch {
393
+ ok = false;
394
+ }
395
+ if (!ok) return new Response("forbidden", { status: 403 });
396
+ headers.set(PROGRESS_READER_HEADER, "1");
397
+ return hub.fetch(new Request(req, { headers }));
398
+ }
399
+
400
+ //#endregion
401
+ //#region src/hub.ts
402
+ /** The owner's chat thread; every other thread is a friend's user id. */
403
+ const OWNER_THREAD = "owner";
404
+ /** A user id usable as a thread and a storage key: no separators, bounded. */
405
+ const isUserId = (v) => typeof v === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(v) && v !== OWNER_THREAD;
406
+ /** Who a page is: set by routeChat() from the site's answer, never by the page. */
407
+ const IDENTITY_HEADERS = {
408
+ user: "x-liagent-user",
409
+ email: "x-liagent-email",
410
+ owner: "x-liagent-owner"
411
+ };
412
+ /** The agent's client IP, set by routeChat from cf-connecting-ip (never by the client). */
413
+ const IP_HEADER = "x-liagent-ip";
414
+ /** The header an agent resumes its chat grant with. */
415
+ const TOKEN_HEADER = "x-liagent-token";
416
+ /** A sleeping eval grant's pair id in the pages' state: "g:" + the start of its hash. */
417
+ const DORMANT = "g:";
418
+ const dormantPair = (hash) => `${DORMANT}${hash.slice(0, 40)}`;
419
+ const att = (ws) => {
420
+ try {
421
+ return ws.deserializeAttachment() ?? null;
422
+ } catch {
423
+ return null;
424
+ }
425
+ };
426
+ const send = (ws, msg) => {
427
+ try {
428
+ ws.send(JSON.stringify(msg));
429
+ } catch {}
430
+ };
431
+ const close = (ws, code, reason) => {
432
+ try {
433
+ ws.close(code, reason);
434
+ } catch {}
435
+ };
436
+ const info = ({ pair, code, label, at, until, scope, want, pages }) => until ? {
437
+ pair,
438
+ code,
439
+ label,
440
+ at,
441
+ until,
442
+ scope: scope ?? "eval",
443
+ pages: pages ?? "all"
444
+ } : want ? {
445
+ pair,
446
+ code,
447
+ label,
448
+ at,
449
+ scope: want
450
+ } : {
451
+ pair,
452
+ code,
453
+ label,
454
+ at
455
+ };
456
+ /** Whether a grant covers a page: "all" (or an older grant with no list), or by id. */
457
+ const covers = (pages, id) => pages === void 0 || pages === "all" || pages.includes(id);
458
+ const pageId = () => crypto.randomUUID().slice(0, 8);
459
+ const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
460
+ const hashToken = async (token) => hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)));
461
+ const log = (o) => console.log(JSON.stringify(o));
462
+ const nodeGrantKey = (from, to) => `ngrant:${from}>${to}`;
463
+ /** Where an agent listens, from its knock: `?node=` (a node path) and `?agent=`. */
464
+ const whereOf = (url) => {
465
+ const node = nodePath(url.searchParams.get("node") ?? void 0);
466
+ const assignee = agentIdOf(url.searchParams.get("agent") ?? void 0);
467
+ const out = {};
468
+ if (node && node !== ROOT_NODE) out.node = node;
469
+ if (assignee) out.assignee = assignee;
470
+ return out;
471
+ };
472
+ /** A history as one agent sees it: only the lines routed to its node. */
473
+ const forNode = (list, node) => node ? list.filter((m) => routeTo(node, m.to)) : list;
474
+ /** Whose a socket is: a page's thread, or the audience a controller was paired for. */
475
+ const audience = (a) => a.role === "page" ? a.thread : a.forUser ?? OWNER_THREAD;
476
+ const threadKeys = (thread) => thread === OWNER_THREAD ? {
477
+ seq: "seq",
478
+ prefix: "msg:"
479
+ } : {
480
+ seq: `t:${thread}:seq`,
481
+ prefix: `t:${thread}:msg:`
482
+ };
483
+ const msgKey = (thread, seq) => `${threadKeys(thread).prefix}${String(seq).padStart(12, "0")}`;
484
+ const friendKey = (userId) => `friend:${userId}`;
485
+ /** The pairing limits' keys: one per (audience, client IP), and one per audience. */
486
+ const knockKey = (who, ip) => ip === void 0 ? `${who}\n*` : `${who}\n${ip}`;
487
+ /** After the user denies a pairing, that audience takes no new request for this long. */
488
+ const PAIR_COOLDOWN_MS = 6e4;
489
+ /**
490
+ * At most PAIR_MAX pairing requests per audience and client IP per
491
+ * PAIR_WINDOW_MS, and PAIR_AUDIENCE_MAX per audience from all IPs together
492
+ * (which bounds the prompts the user sees). Keyed by IP too, so a stranger
493
+ * using up their own quota cannot lock the user's agent out. A request waits
494
+ * up to PENDING_MS (2 min), so the window must be longer than PAIR_MAX of
495
+ * those, or re-knocking as each lapses would never hit the cap.
496
+ */
497
+ const PAIR_MAX = 3;
498
+ const PAIR_AUDIENCE_MAX = 10;
499
+ const PAIR_WINDOW_MS = 15 * 6e4;
500
+ /** A friend's page may relabel at most once per this long; faster ones are dropped. */
501
+ const FRIEND_RELABEL_MS = 1e3;
502
+ /** A friend may hold at most this many page sockets at once. */
503
+ const FRIEND_MAX_PAGES = 8;
504
+ var ChatHub = class {
505
+ opts = {
506
+ eval: false,
507
+ friendChatMax: 30,
508
+ friendWindowMs: 10 * 6e4,
509
+ logContent: false
510
+ };
511
+ /** `{head}` for a log line, only when the hub logs content. */
512
+ head(text, n = 80) {
513
+ return this.opts.logContent ? { head: text.slice(0, n) } : {};
514
+ }
515
+ constructor(ctx, _env, now = Date.now, opts = {}) {
516
+ this.ctx = ctx;
517
+ this.now = now;
518
+ this.opts = {
519
+ ...this.opts,
520
+ ...stripUndefined(opts)
521
+ };
522
+ if (ctx.blockConcurrencyWhile) ctx.blockConcurrencyWhile(() => this.loadKnocks());
523
+ }
524
+ /**
525
+ * Every stored grant by hash: read once per instance (an evicted hub reads
526
+ * it again), then kept in step with each write. Only the listing of
527
+ * sleeping eval grants uses it; a resume always asks storage itself.
528
+ */
529
+ grants;
530
+ /**
531
+ * Pairing requests per (audience, IP) and per audience, to bound the
532
+ * prompts anyone can raise: the window's start and count, and when the
533
+ * user last denied one. Read synchronously from this map, written through
534
+ * to storage (`knock:<key>`), and loaded back when a hub wakes from
535
+ * hibernation (under blockConcurrencyWhile, before any event), so an
536
+ * evicted hub does not forget them. Where the host has no
537
+ * blockConcurrencyWhile they are kept in memory only.
538
+ */
539
+ knocks = /* @__PURE__ */ new Map();
540
+ setKnock(key, k) {
541
+ this.knocks.set(key, k);
542
+ this.ctx.storage.put(`knock:${key}`, k);
543
+ }
544
+ /** Load the stored counters; drop those whose window and cooldown have both passed. */
545
+ async loadKnocks() {
546
+ const t = this.now();
547
+ const m = await this.ctx.storage.list({ prefix: "knock:" });
548
+ for (const [k, v] of m) {
549
+ const key = k.slice(6);
550
+ if (t - v.start < PAIR_WINDOW_MS || v.deniedAt !== void 0 && t - v.deniedAt < PAIR_COOLDOWN_MS) this.knocks.set(key, v);
551
+ else await this.ctx.storage.delete(k);
552
+ }
553
+ }
554
+ /**
555
+ * Room for one more pairing request for audience `who` from client `ip`:
556
+ * false (and `ws` closed with 4429) if not. Per (audience, IP): a
557
+ * cooldown after the user denied that IP's request, and PAIR_MAX per
558
+ * window. Per audience: PAIR_AUDIENCE_MAX per window from all IPs. Without
559
+ * an IP (a hub not behind routeChat on Cloudflare), every request shares
560
+ * one key.
561
+ */
562
+ knockAllowed(ws, who, ip = "?") {
563
+ const t = this.now();
564
+ const fresh = (k) => !k || t - k.start >= PAIR_WINDOW_MS ? {
565
+ start: t,
566
+ count: 0,
567
+ deniedAt: k?.deniedAt
568
+ } : k;
569
+ const mine = fresh(this.knocks.get(knockKey(who, ip)));
570
+ const all = fresh(this.knocks.get(knockKey(who)));
571
+ if (mine.deniedAt && t - mine.deniedAt < PAIR_COOLDOWN_MS) {
572
+ send(ws, {
573
+ type: "error",
574
+ error: "a pairing was just denied: try again in a minute"
575
+ });
576
+ close(ws, 4429, "pairing cooling down");
577
+ return false;
578
+ }
579
+ if (mine.count >= PAIR_MAX || all.count >= PAIR_AUDIENCE_MAX) {
580
+ send(ws, {
581
+ type: "error",
582
+ error: "too many pairing requests: try again later"
583
+ });
584
+ close(ws, 4429, "pairing rate limit");
585
+ return false;
586
+ }
587
+ this.setKnock(knockKey(who, ip), {
588
+ ...mine,
589
+ count: mine.count + 1
590
+ });
591
+ this.setKnock(knockKey(who), {
592
+ ...all,
593
+ count: all.count + 1
594
+ });
595
+ return true;
596
+ }
597
+ loadingGrants;
598
+ loadGrants() {
599
+ if (this.grants) return Promise.resolve();
600
+ this.loadingGrants ??= this.ctx.storage.list({ prefix: "grant:" }).then((m) => {
601
+ this.grants = new Map([...m].map(([k, g]) => [k.slice(6), g]));
602
+ this.loadingGrants = void 0;
603
+ });
604
+ return this.loadingGrants;
605
+ }
606
+ async putGrant(hash, g) {
607
+ await this.loadGrants();
608
+ await this.ctx.storage.put(`grant:${hash}`, g);
609
+ this.grants?.set(hash, g);
610
+ }
611
+ async dropGrant(hash) {
612
+ await this.loadGrants();
613
+ await this.ctx.storage.delete(`grant:${hash}`);
614
+ this.grants?.delete(hash);
615
+ }
616
+ /** Open sockets of one role, optionally leaving one out (the one closing). */
617
+ sockets(role, except) {
618
+ const out = [];
619
+ for (const ws of this.ctx.getWebSockets()) {
620
+ if (ws === except || ws.readyState !== void 0 && ws.readyState > 1) continue;
621
+ const a = att(ws);
622
+ if (a?.role === role) out.push({
623
+ ws,
624
+ a
625
+ });
626
+ }
627
+ return out;
628
+ }
629
+ pages(thread, except) {
630
+ return this.sockets("page", except).filter((p) => p.a.thread === thread);
631
+ }
632
+ /**
633
+ * Owner-approved agents still in time. They hear every thread and may `say`
634
+ * to any. A pairing made for a friend is not one.
635
+ */
636
+ listeners(except) {
637
+ const t = this.now();
638
+ return this.sockets("controller", except).filter((c) => !c.a.forUser && c.a.until && c.a.until > t);
639
+ }
640
+ /** What one audience's pages see: its pairings, how many agents listen, its pages. */
641
+ state(who, except, self = "") {
642
+ const t = this.now();
643
+ let pending = null;
644
+ const sessions = [];
645
+ const held = /* @__PURE__ */ new Set();
646
+ for (const { a } of this.sockets("controller", except)) {
647
+ if (a.grant) held.add(a.grant);
648
+ if (audience(a) !== who) continue;
649
+ if (a.until) {
650
+ if (a.until > t) sessions.push(info(a));
651
+ } else if (t - a.at < PENDING_MS) pending = info(a);
652
+ }
653
+ if (who === OWNER_THREAD) {
654
+ for (const [hash, g] of this.grants ?? []) if (g.scope === "eval" && g.until > t && !held.has(hash)) sessions.push({
655
+ pair: dormantPair(hash),
656
+ code: "idle",
657
+ label: g.label,
658
+ at: g.at ?? 0,
659
+ until: g.until,
660
+ scope: "eval",
661
+ pages: g.pages ?? "all"
662
+ });
663
+ }
664
+ const pages = this.pages(who, except).map(({ a }) => ({
665
+ id: a.id,
666
+ label: a.label,
667
+ at: a.at
668
+ }));
669
+ const agents = this.listeners(except);
670
+ const nodes = [...new Set(agents.map((c) => c.a.node).filter((n) => !!n))].sort();
671
+ return {
672
+ type: "state",
673
+ pending,
674
+ sessions,
675
+ listeners: agents.length,
676
+ pages,
677
+ self,
678
+ ...nodes.length ? { nodes } : {}
679
+ };
680
+ }
681
+ /** Send every page its audience's state; `skip` is left out of the sending only. */
682
+ broadcast(except, skip) {
683
+ const by = /* @__PURE__ */ new Map();
684
+ for (const { ws, a } of this.sockets("page", except)) {
685
+ if (ws === skip) continue;
686
+ let s = by.get(a.thread);
687
+ if (!s) by.set(a.thread, s = this.state(a.thread, except));
688
+ send(ws, {
689
+ ...s,
690
+ self: a.id
691
+ });
692
+ }
693
+ }
694
+ controller(pair) {
695
+ return this.sockets("controller").find((c) => c.a.pair === pair);
696
+ }
697
+ /** One thread's kept chat, oldest first. */
698
+ async history(thread = OWNER_THREAD) {
699
+ return [...(await this.ctx.storage.list({
700
+ prefix: threadKeys(thread).prefix,
701
+ reverse: true,
702
+ limit: CHAT_HISTORY
703
+ })).values()].reverse().map((x) => ({
704
+ thread,
705
+ ...x
706
+ }));
707
+ }
708
+ /**
709
+ * Keep one message (dropping its thread's oldest past CHAT_HISTORY) and send
710
+ * it on. An agent's reply in the owner's thread goes live only to the pages
711
+ * of its grant (`only`); every page still gets it in its history.
712
+ */
713
+ async post(m, only) {
714
+ const { seq: seqKey } = threadKeys(m.thread);
715
+ const seq = (await this.ctx.storage.get(seqKey) ?? 0) + 1;
716
+ await this.ctx.storage.put(seqKey, seq);
717
+ await this.ctx.storage.put(msgKey(m.thread, seq), m);
718
+ if (seq > CHAT_HISTORY) await this.ctx.storage.delete(msgKey(m.thread, seq - CHAT_HISTORY));
719
+ const out = {
720
+ type: "chat",
721
+ message: m
722
+ };
723
+ for (const { ws, a } of this.pages(m.thread)) if (covers(only, a.id)) send(ws, out);
724
+ for (const { ws, a } of this.listeners()) {
725
+ const route = routeTo(a.node, m.to);
726
+ if (route) send(ws, route === "observed" ? {
727
+ ...out,
728
+ observed: true
729
+ } : out);
730
+ }
731
+ }
732
+ /**
733
+ * The agent polishes the owner's latest voice line (see "Voice edits"
734
+ * above). Every refusal is an {type:"error"} naming the rule it broke.
735
+ */
736
+ async edit(ws, c, m) {
737
+ const fail = (reason) => send(ws, {
738
+ type: "error",
739
+ error: reason,
740
+ reason
741
+ });
742
+ if (c.forUser) return fail("a pairing for a friend cannot edit");
743
+ const g = c.grant ? await this.ctx.storage.get(`grant:${c.grant}`) : void 0;
744
+ if (!g || g.until <= this.now()) return fail("edit needs a live chat grant from the owner");
745
+ const kept = await this.ctx.storage.list({
746
+ prefix: threadKeys(OWNER_THREAD).prefix,
747
+ reverse: true,
748
+ limit: CHAT_HISTORY
749
+ });
750
+ const latest = [...kept].find(([, x]) => x.from === "owner");
751
+ if (!latest || latest[1].id !== m.id) return fail([...kept].some(([, x]) => x.id === m.id) ? `message ${m.id} is not the owner's latest: only the latest may be polished` : `no message ${m.id} in the owner's thread (friends' lines can never be edited)`);
752
+ const [key, line] = latest;
753
+ if (line.source !== "stt") return fail(`message ${m.id} was typed, not spoken: only voice (stt) lines may be polished`);
754
+ const count = line.edited?.count ?? 0;
755
+ if (count >= MAX_EDITS) return fail(`message ${m.id} was already polished ${MAX_EDITS} times`);
756
+ if (m.text === line.text) return fail(`message ${m.id} already reads that way`);
757
+ const t = this.now();
758
+ const by = cleanLabel(c.assignee ?? c.label, 80) || "agent";
759
+ const raw = line.raw ?? line.text;
760
+ const edited = {
761
+ at: t,
762
+ by,
763
+ count: count + 1
764
+ };
765
+ await this.ctx.storage.put(key, {
766
+ ...line,
767
+ text: m.text,
768
+ raw,
769
+ edited
770
+ });
771
+ const out = {
772
+ type: "edited",
773
+ id: line.id,
774
+ thread: OWNER_THREAD,
775
+ text: m.text,
776
+ raw,
777
+ edited
778
+ };
779
+ log({
780
+ msg: "chat.edit",
781
+ pair: c.pair,
782
+ id: line.id,
783
+ by,
784
+ count: count + 1,
785
+ len: m.text.length,
786
+ ...this.head(m.text)
787
+ });
788
+ for (const { ws: p } of this.pages(OWNER_THREAD)) send(p, out);
789
+ let told = false;
790
+ for (const { ws: l, a } of this.listeners()) {
791
+ const route = routeTo(a.node, line.to);
792
+ if (!route) continue;
793
+ if (l === ws) told = true;
794
+ send(l, route === "observed" ? {
795
+ ...out,
796
+ observed: true
797
+ } : out);
798
+ }
799
+ if (!told) send(ws, out);
800
+ }
801
+ /** The live node grants (`ngrant:`), lapsed ones dropped as they are met. */
802
+ async nodeGrants() {
803
+ const t = this.now();
804
+ const out = [];
805
+ for (const [k, g] of await this.ctx.storage.list({ prefix: "ngrant:" })) if (g.until > t) out.push(g);
806
+ else await this.ctx.storage.delete(k);
807
+ return out;
808
+ }
809
+ /** Everyone who has used the chat, most recent first. */
810
+ async friends() {
811
+ return [...(await this.ctx.storage.list({ prefix: "friend:" })).entries()].map(([k, v]) => ({
812
+ userId: k.slice(7),
813
+ ...v
814
+ })).sort((a, b) => b.lastAt - a.lastAt);
815
+ }
816
+ /** A friend by user id or (any case) email. */
817
+ async findFriend(key) {
818
+ if (isUserId(key)) {
819
+ const rec = await this.ctx.storage.get(friendKey(key));
820
+ if (rec) return {
821
+ userId: key,
822
+ ...rec
823
+ };
824
+ }
825
+ const want = key.trim().toLowerCase();
826
+ return (await this.friends()).find((f) => f.email.toLowerCase() === want);
827
+ }
828
+ async fetch(req) {
829
+ const url = new URL(req.url);
830
+ if (url.pathname.startsWith("/internal/friends")) return this.friendsApi(req, url);
831
+ const control = url.pathname.endsWith("/control");
832
+ let who;
833
+ if (!control) {
834
+ const h = req.headers;
835
+ const userId = h.get(IDENTITY_HEADERS.user) ?? "";
836
+ const owner = h.get(IDENTITY_HEADERS.owner) === "1";
837
+ if (!owner && !isUserId(userId)) return new Response("forbidden", { status: 403 });
838
+ who = {
839
+ userId,
840
+ email: h.get(IDENTITY_HEADERS.email) ?? "",
841
+ owner
842
+ };
843
+ }
844
+ const pair = new WebSocketPair();
845
+ const ws = pair[1];
846
+ this.ctx.acceptWebSocket(ws);
847
+ if (control) await this.connectController(ws, url, req.headers.get(TOKEN_HEADER), req.headers.get(IP_HEADER) ?? void 0);
848
+ else await this.connectPage(ws, url, who);
849
+ return new Response(null, {
850
+ status: 101,
851
+ webSocket: pair[0]
852
+ });
853
+ }
854
+ /**
855
+ * The owner's friends API — route it only from an owner-only path of your
856
+ * own (routeChat never does):
857
+ * GET /internal/friends → {friends}
858
+ * GET /internal/friends/thread?user=id → {messages}
859
+ * POST /internal/friends {userId, action: "block" | "unblock"}
860
+ */
861
+ async friendsApi(req, url) {
862
+ if (req.method === "GET" && url.pathname.endsWith("/thread")) {
863
+ const user = url.searchParams.get("user");
864
+ if (!isUserId(user)) return Response.json({ error: "bad user" }, { status: 400 });
865
+ return Response.json({ messages: await this.history(user) });
866
+ }
867
+ if (req.method === "GET") return Response.json({ friends: await this.friends() });
868
+ if (req.method !== "POST") return new Response("method not allowed", { status: 405 });
869
+ let body;
870
+ try {
871
+ body = await req.json();
872
+ } catch {
873
+ return Response.json({ error: "bad json" }, { status: 400 });
874
+ }
875
+ if (!isUserId(body.userId) || body.action !== "block" && body.action !== "unblock") return Response.json({ error: "expected {userId, action: block|unblock}" }, { status: 400 });
876
+ const rec = await this.block(body.userId, body.action === "block");
877
+ if (!rec) return Response.json({ error: "no such chat user" }, { status: 404 });
878
+ return Response.json({
879
+ ok: true,
880
+ friend: {
881
+ userId: body.userId,
882
+ ...rec
883
+ }
884
+ });
885
+ }
886
+ /** Block (or unblock) a friend: blocking closes their pages and every pairing made for them. */
887
+ async block(userId, blocked) {
888
+ const rec = await this.ctx.storage.get(friendKey(userId));
889
+ if (!rec) return null;
890
+ const next = blocked ? {
891
+ ...rec,
892
+ blocked: true,
893
+ blockedAt: this.now()
894
+ } : {
895
+ ...rec,
896
+ blocked: false
897
+ };
898
+ await this.ctx.storage.put(friendKey(userId), next);
899
+ log({
900
+ msg: blocked ? "chat.block" : "chat.unblock",
901
+ userId
902
+ });
903
+ if (!blocked) return next;
904
+ for (const p of this.pages(userId)) {
905
+ send(p.ws, {
906
+ type: "friend-status",
907
+ status: "blocked"
908
+ });
909
+ close(p.ws, 4403, "blocked");
910
+ }
911
+ for (const c of this.sockets("controller")) if (c.a.forUser === userId) {
912
+ send(c.ws, { type: "revoked" });
913
+ close(c.ws, 4401, "revoke");
914
+ }
915
+ this.broadcast();
916
+ return next;
917
+ }
918
+ /**
919
+ * A page joins: it gets its own thread's history and its audience's state.
920
+ * A blocked friend is told and closed. With no identity (tests) it is the owner's.
921
+ */
922
+ async connectPage(ws, url, who) {
923
+ const label = cleanLabel(url.searchParams.get("label"), MAX_LABEL);
924
+ const asked = url.searchParams.get("page");
925
+ const id = isPageId(asked) && !this.sockets("page", ws).some((p) => p.a.id === asked) ? asked : pageId();
926
+ if (who && !who.owner) {
927
+ if (!isUserId(who.userId)) return close(ws, 4403, "no identity");
928
+ if ((await this.ctx.storage.get(friendKey(who.userId)))?.blocked) {
929
+ send(ws, {
930
+ type: "friend-status",
931
+ status: "blocked"
932
+ });
933
+ return close(ws, 4403, "blocked");
934
+ }
935
+ if (this.pages(who.userId, ws).length >= FRIEND_MAX_PAGES) {
936
+ send(ws, {
937
+ type: "error",
938
+ error: "too many open pages"
939
+ });
940
+ return close(ws, 4429, "too many pages");
941
+ }
942
+ ws.serializeAttachment({
943
+ role: "page",
944
+ id,
945
+ label,
946
+ at: this.now(),
947
+ thread: who.userId,
948
+ email: cleanLabel(who.email, 320)
949
+ });
950
+ send(ws, {
951
+ type: "friend-status",
952
+ status: "open"
953
+ });
954
+ } else ws.serializeAttachment({
955
+ role: "page",
956
+ id,
957
+ label,
958
+ at: this.now(),
959
+ thread: OWNER_THREAD
960
+ });
961
+ const a = att(ws);
962
+ if (a.thread === OWNER_THREAD && !this.grants) this.loadGrants().then(() => this.grants?.size && this.broadcast());
963
+ this.sweep();
964
+ this.broadcast(void 0, ws);
965
+ send(ws, this.state(a.thread, void 0, a.id));
966
+ send(ws, {
967
+ type: "history",
968
+ messages: await this.history(a.thread)
969
+ });
970
+ }
971
+ /**
972
+ * An agent knocks. `?for=<email>` asks a friend's pages for an eval pairing
973
+ * (owner grant and an eval hub only). With just a grant token it is back
974
+ * in chat scope at once. Otherwise it waits for the owner: one pending
975
+ * pairing per audience, and only with a page to ask.
976
+ */
977
+ async connectController(ws, url, token, ip) {
978
+ const forKey = url.searchParams.get("for")?.trim();
979
+ if (forKey) return this.pairForFriend(ws, url, forKey, token, ip);
980
+ if (token) return this.resume(ws, url, token);
981
+ const label = cleanLabel(url.searchParams.get("label"), 80) || "unnamed agent";
982
+ const sc = url.searchParams.get("scope");
983
+ const want = sc === "chat" || sc === "eval" ? sc : void 0;
984
+ if (want === "eval" && !this.opts.eval) {
985
+ send(ws, {
986
+ type: "error",
987
+ error: "eval is not enabled on this hub"
988
+ });
989
+ return close(ws, 4403, "no eval");
990
+ }
991
+ if (!this.clearPending(ws, OWNER_THREAD)) return;
992
+ if (this.pages(OWNER_THREAD, ws).length === 0) {
993
+ send(ws, {
994
+ type: "error",
995
+ error: "no owner page is open to approve this"
996
+ });
997
+ return close(ws, 4404, "no page");
998
+ }
999
+ if (!this.knockAllowed(ws, OWNER_THREAD, ip)) return;
1000
+ this.knock(ws, {
1001
+ label,
1002
+ ...want ? { want } : {},
1003
+ ...ip ? { ip } : {},
1004
+ ...whereOf(url)
1005
+ });
1006
+ }
1007
+ /** Make room for one audience's pairing: false (and `ws` closed) if one is still waiting. */
1008
+ clearPending(ws, who) {
1009
+ const t = this.now();
1010
+ for (const c of this.sockets("controller", ws)) {
1011
+ if (c.a.until || audience(c.a) !== who) continue;
1012
+ if (t - c.a.at < PENDING_MS) {
1013
+ send(ws, {
1014
+ type: "error",
1015
+ error: "another pairing request is waiting for an answer"
1016
+ });
1017
+ close(ws, 4429, "pairing busy");
1018
+ return false;
1019
+ }
1020
+ send(c.ws, { type: "expired" });
1021
+ close(c.ws, 4408, "pairing expired");
1022
+ }
1023
+ return true;
1024
+ }
1025
+ knock(ws, extra) {
1026
+ const a = {
1027
+ role: "controller",
1028
+ pair: crypto.randomUUID(),
1029
+ code: shortCode(crypto.getRandomValues(new Uint8Array(2))),
1030
+ at: this.now(),
1031
+ ...extra
1032
+ };
1033
+ ws.serializeAttachment(a);
1034
+ send(ws, {
1035
+ type: "pending",
1036
+ code: a.code,
1037
+ expiresIn: PENDING_MS,
1038
+ for: a.forEmail
1039
+ });
1040
+ log({
1041
+ msg: "chat.pair",
1042
+ pair: a.pair,
1043
+ code: a.code,
1044
+ label: a.label,
1045
+ for: a.forUser
1046
+ });
1047
+ this.broadcast();
1048
+ }
1049
+ /** The owner's live grant behind a token, or null (and a lapsed one deleted). */
1050
+ async liveGrant(token) {
1051
+ const hash = await hashToken(token.slice(0, 256));
1052
+ const g = await this.ctx.storage.get(`grant:${hash}`);
1053
+ if (g && g.until > this.now()) return {
1054
+ hash,
1055
+ g
1056
+ };
1057
+ if (g) await this.dropGrant(hash);
1058
+ return null;
1059
+ }
1060
+ /** An eval pairing on one friend's pages: the owner's agent asks, the friend answers. */
1061
+ async pairForFriend(ws, url, key, token, ip) {
1062
+ if (!this.opts.eval) {
1063
+ send(ws, {
1064
+ type: "error",
1065
+ error: "eval is not enabled on this hub"
1066
+ });
1067
+ return close(ws, 4403, "no eval");
1068
+ }
1069
+ const live = token ? await this.liveGrant(token) : null;
1070
+ if (!live) {
1071
+ send(ws, {
1072
+ type: "error",
1073
+ error: "pairing with a friend needs the owner's chat grant"
1074
+ });
1075
+ return close(ws, 4498, "grant invalid");
1076
+ }
1077
+ const f = await this.findFriend(key);
1078
+ if (!f || f.blocked) {
1079
+ send(ws, {
1080
+ type: "error",
1081
+ error: `no chat user ${key} (or blocked)`
1082
+ });
1083
+ return close(ws, 4404, "no such friend");
1084
+ }
1085
+ if (!this.clearPending(ws, f.userId)) return;
1086
+ if (this.pages(f.userId, ws).length === 0) {
1087
+ send(ws, {
1088
+ type: "error",
1089
+ error: `no page of ${f.email} is open`
1090
+ });
1091
+ return close(ws, 4404, "no page");
1092
+ }
1093
+ if (!this.knockAllowed(ws, f.userId, ip)) return;
1094
+ this.knock(ws, {
1095
+ label: cleanLabel(url.searchParams.get("label"), 80) || live.g.label,
1096
+ forUser: f.userId,
1097
+ forEmail: f.email,
1098
+ want: "eval",
1099
+ ...ip ? { ip } : {}
1100
+ });
1101
+ }
1102
+ /** Reconnecting with a grant token: chat scope again, no prompt — or 4498 if it is not live. */
1103
+ async resume(ws, url, token) {
1104
+ const live = await this.liveGrant(token);
1105
+ if (!live) {
1106
+ send(ws, {
1107
+ type: "error",
1108
+ error: "grant is not valid (expired or ended)"
1109
+ });
1110
+ return close(ws, 4498, "grant invalid");
1111
+ }
1112
+ const { hash, g } = live;
1113
+ const scope = g.scope === "eval" && this.opts.eval ? "eval" : "chat";
1114
+ const pages = scope === "eval" ? g.pages ?? "all" : "all";
1115
+ const a = {
1116
+ role: "controller",
1117
+ pair: crypto.randomUUID(),
1118
+ code: shortCode(crypto.getRandomValues(new Uint8Array(2))),
1119
+ label: cleanLabel(url.searchParams.get("label"), 80) || g.label,
1120
+ at: this.now(),
1121
+ until: g.until,
1122
+ scope,
1123
+ grant: hash,
1124
+ pages,
1125
+ ...whereOf(url)
1126
+ };
1127
+ ws.serializeAttachment(a);
1128
+ send(ws, {
1129
+ type: "approved",
1130
+ until: g.until,
1131
+ scope,
1132
+ pages,
1133
+ resumed: true
1134
+ });
1135
+ send(ws, {
1136
+ type: "history",
1137
+ messages: forNode(await this.history(), a.node)
1138
+ });
1139
+ log({
1140
+ msg: "chat.resume",
1141
+ pair: a.pair,
1142
+ label: a.label,
1143
+ scope
1144
+ });
1145
+ this.broadcast();
1146
+ }
1147
+ webSocketMessage(ws, raw) {
1148
+ this.sweep();
1149
+ const a = att(ws);
1150
+ if (a?.role === "page") return this.fromPage(ws, a, raw);
1151
+ if (a?.role === "controller") return this.fromController(ws, a, raw);
1152
+ }
1153
+ fromPage(ws, page, raw) {
1154
+ const m = parsePageMessage(raw);
1155
+ if (!m) return;
1156
+ const t = this.now();
1157
+ if (m.type === "chat") {
1158
+ log({
1159
+ msg: "chat.owner",
1160
+ page: page.label,
1161
+ thread: page.thread,
1162
+ len: m.text.length,
1163
+ ...this.head(m.text)
1164
+ });
1165
+ if (page.thread !== OWNER_THREAD) return this.friendChat(ws, page, m.id, m.text);
1166
+ return this.post({
1167
+ id: m.id,
1168
+ from: "owner",
1169
+ label: page.label,
1170
+ text: m.text,
1171
+ at: t,
1172
+ thread: OWNER_THREAD,
1173
+ ...m.to ? { to: m.to } : {},
1174
+ ...m.source ? { source: m.source } : {}
1175
+ });
1176
+ }
1177
+ if (m.type === "page") return this.relabel(ws, page, m.label);
1178
+ if (m.type === "end-page") {
1179
+ const target = this.pages(page.thread).find((p) => p.a.id === m.id);
1180
+ if (!target) return send(ws, this.state(page.thread, void 0, page.id));
1181
+ log({
1182
+ msg: "chat.end-page",
1183
+ id: m.id,
1184
+ label: target.a.label
1185
+ });
1186
+ close(target.ws, 4410, "page ended");
1187
+ return this.pageClosed(target.ws, target.a);
1188
+ }
1189
+ if ((m.type === "revoke" || m.type === "allow") && m.pair.startsWith(DORMANT)) {
1190
+ if (page.thread !== OWNER_THREAD) return send(ws, this.state(page.thread, void 0, page.id));
1191
+ return this.dormant(ws, page, m);
1192
+ }
1193
+ const c = this.controller(m.type === "result" ? m.to : m.pair);
1194
+ const mine = () => send(ws, this.state(page.thread, void 0, page.id));
1195
+ if (!c || audience(c.a) !== page.thread) return mine();
1196
+ if (m.type === "allow") {
1197
+ const pages = this.choosePages(page, m.pages);
1198
+ if (c.a.until) return c.a.until > t ? this.addPages(c.ws, c.a, pages) : mine();
1199
+ if (t - c.a.at >= PENDING_MS) return mine();
1200
+ if (c.a.forUser) return this.allowHour(c.ws, c.a, pages);
1201
+ return (c.a.want ? c.a.want === "chat" : m.scope === "chat") ? this.allowChat(c.ws, c.a, "all") : this.allowHour(c.ws, c.a, pages);
1202
+ }
1203
+ if (m.type === "deny" || m.type === "revoke") return this.end(m.type, c.ws, c.a);
1204
+ if (m.type !== "result" || !c.a.until || c.a.until <= t) return;
1205
+ const { type: _t, to: _to, ...rest } = m;
1206
+ send(c.ws, {
1207
+ type: "result",
1208
+ ...rest,
1209
+ page: page.label
1210
+ });
1211
+ }
1212
+ /**
1213
+ * A friend's message: no approval needed, but a blocked friend is closed
1214
+ * and more than friendChatMax in a window is dropped (and the page told).
1215
+ * Their first ever message tells the agents ({type:"friend-new"}).
1216
+ */
1217
+ async friendChat(ws, page, id, text) {
1218
+ const t = this.now();
1219
+ const userId = page.thread;
1220
+ const rec = await this.ctx.storage.get(friendKey(userId));
1221
+ if (rec?.blocked) {
1222
+ send(ws, {
1223
+ type: "friend-status",
1224
+ status: "blocked"
1225
+ });
1226
+ return close(ws, 4403, "blocked");
1227
+ }
1228
+ const rateKey = `rate:${userId}`;
1229
+ let rate = await this.ctx.storage.get(rateKey) ?? {
1230
+ start: t,
1231
+ count: 0
1232
+ };
1233
+ if (t - rate.start >= this.opts.friendWindowMs) rate = {
1234
+ start: t,
1235
+ count: 0
1236
+ };
1237
+ if (rate.count >= this.opts.friendChatMax) return send(ws, {
1238
+ type: "rate-limited",
1239
+ id,
1240
+ retryIn: rate.start + this.opts.friendWindowMs - t
1241
+ });
1242
+ await this.ctx.storage.put(rateKey, {
1243
+ start: rate.start,
1244
+ count: rate.count + 1
1245
+ });
1246
+ const email = rec?.email || page.email || "";
1247
+ await this.ctx.storage.put(friendKey(userId), {
1248
+ ...rec ?? { firstSeen: t },
1249
+ email,
1250
+ lastAt: t,
1251
+ count: (rec?.count ?? 0) + 1
1252
+ });
1253
+ if (!rec) {
1254
+ log({
1255
+ msg: "chat.friend-new",
1256
+ userId
1257
+ });
1258
+ for (const l of this.listeners()) send(l.ws, {
1259
+ type: "friend-new",
1260
+ userId,
1261
+ email,
1262
+ at: t
1263
+ });
1264
+ }
1265
+ return this.post({
1266
+ id,
1267
+ from: "friend",
1268
+ label: page.label,
1269
+ text,
1270
+ at: t,
1271
+ thread: userId,
1272
+ email
1273
+ });
1274
+ }
1275
+ /** The pages an Allow names: live ones of the answering page's audience; by default that page. */
1276
+ choosePages(page, asked) {
1277
+ if (asked === "all") return "all";
1278
+ const live = new Set(this.pages(page.thread).map((p) => p.a.id));
1279
+ const ids = (asked ?? []).filter((id) => live.has(id));
1280
+ return ids.length ? [...new Set(ids)] : [page.id];
1281
+ }
1282
+ /** Whether any live page of `thread` is covered by `pages`. */
1283
+ anyCovered(thread, pages, except) {
1284
+ if (pages === void 0 || pages === "all") return true;
1285
+ return this.pages(thread, except).some((p) => covers(pages, p.a.id));
1286
+ }
1287
+ /** Add pages to an approved agent's grant: every socket of it, and the stored grant. */
1288
+ async addPages(ws, a, more) {
1289
+ const merged = (cur) => more === "all" || cur === void 0 || cur === "all" ? "all" : [...new Set([...cur, ...more])];
1290
+ const pages = merged(a.pages);
1291
+ for (const o of this.sockets("controller")) if (o.ws === ws || a.grant !== void 0 && o.a.grant === a.grant) {
1292
+ o.ws.serializeAttachment({
1293
+ ...o.a,
1294
+ pages
1295
+ });
1296
+ send(o.ws, {
1297
+ type: "approved",
1298
+ until: o.a.until,
1299
+ scope: o.a.scope,
1300
+ pages,
1301
+ added: true
1302
+ });
1303
+ }
1304
+ if (a.grant) {
1305
+ const g = await this.ctx.storage.get(`grant:${a.grant}`);
1306
+ if (g) await this.putGrant(a.grant, {
1307
+ ...g,
1308
+ pages
1309
+ });
1310
+ }
1311
+ log({
1312
+ msg: "chat.add-pages",
1313
+ pair: a.pair,
1314
+ pages
1315
+ });
1316
+ this.broadcast();
1317
+ }
1318
+ /** A page reports client-side navigation: relabel it, update the lists, tell the agents. */
1319
+ relabel(ws, page, raw) {
1320
+ const label = cleanLabel(raw, MAX_LABEL);
1321
+ if (!label || label === page.label) return;
1322
+ const t = this.now();
1323
+ const friend = page.thread !== OWNER_THREAD;
1324
+ if (friend && page.relabelAt !== void 0 && t - page.relabelAt < FRIEND_RELABEL_MS) return;
1325
+ ws.serializeAttachment({
1326
+ ...page,
1327
+ label,
1328
+ ...friend ? { relabelAt: t } : {}
1329
+ });
1330
+ const ev = {
1331
+ type: "page-changed",
1332
+ label,
1333
+ thread: page.thread,
1334
+ at: t
1335
+ };
1336
+ for (const l of this.listeners()) send(l.ws, ev);
1337
+ for (const c of this.sockets("controller")) if (c.a.forUser === page.thread && c.a.until) send(c.ws, ev);
1338
+ this.broadcast();
1339
+ }
1340
+ /** A page went away: update the lists, and start the clock on grants it was the last page of. */
1341
+ pageClosed(ws, _page) {
1342
+ const done = this.sweep(ws);
1343
+ this.broadcast(ws);
1344
+ return done;
1345
+ }
1346
+ /**
1347
+ * Grants whose pages are all closed: note when that began, forget it when
1348
+ * a page of theirs is back, and after PAGES_GONE_MS tell the agent to pair
1349
+ * again (4409) and drop the grant. Run on every event (no timers).
1350
+ */
1351
+ sweep(except) {
1352
+ const t = this.now();
1353
+ for (const c of this.sockets("controller", except)) {
1354
+ const { pages } = c.a;
1355
+ if (!c.a.until || c.a.until <= t || pages === void 0 || pages === "all") continue;
1356
+ if (this.anyCovered(audience(c.a), pages, except)) {
1357
+ if (c.a.goneSince) c.ws.serializeAttachment({
1358
+ ...c.a,
1359
+ goneSince: void 0
1360
+ });
1361
+ continue;
1362
+ }
1363
+ if (!c.a.goneSince) {
1364
+ c.ws.serializeAttachment({
1365
+ ...c.a,
1366
+ goneSince: t
1367
+ });
1368
+ continue;
1369
+ }
1370
+ if (t - c.a.goneSince < PAGES_GONE_MS) continue;
1371
+ send(c.ws, {
1372
+ type: "error",
1373
+ error: c.a.grant ? "the pages this agent was allowed on are gone: this socket closes, but the grant stays; reconnect with its token when a page is back" : "the pages this agent was allowed on are gone: pair again"
1374
+ });
1375
+ close(c.ws, 4409, "pages gone");
1376
+ }
1377
+ }
1378
+ /** End (revoke) a sleeping eval grant, or add the answering page to it. */
1379
+ async dormant(ws, page, m) {
1380
+ await this.loadGrants();
1381
+ const prefix = m.pair.slice(2);
1382
+ const found = prefix.length === 40 ? [...this.grants ?? []].find(([h]) => h.startsWith(prefix)) : null;
1383
+ if (!found || found[1].scope !== "eval") return send(ws, this.state(page.thread, void 0, page.id));
1384
+ const [hash, g] = found;
1385
+ if (m.type === "revoke") {
1386
+ await this.dropGrant(hash);
1387
+ for (const c of this.sockets("controller")) if (c.a.grant === hash) {
1388
+ send(c.ws, { type: "revoked" });
1389
+ close(c.ws, 4401, "revoke");
1390
+ }
1391
+ log({
1392
+ msg: "chat.revoke",
1393
+ grant: "idle",
1394
+ label: g.label
1395
+ });
1396
+ return this.broadcast();
1397
+ }
1398
+ const more = this.choosePages(page, m.pages);
1399
+ const cur = g.pages ?? "all";
1400
+ const pages = more === "all" || cur === "all" ? "all" : [...new Set([...cur, ...more])];
1401
+ await this.putGrant(hash, {
1402
+ ...g,
1403
+ pages
1404
+ });
1405
+ log({
1406
+ msg: "chat.add-pages",
1407
+ grant: "idle",
1408
+ pages
1409
+ });
1410
+ this.broadcast();
1411
+ }
1412
+ /**
1413
+ * Allow for code. The user's: eval and chat for EVAL_GRANT_MS, with a grant
1414
+ * token the agent resumes with (pages and all). A friend's preview: eval
1415
+ * only, for APPROVAL_MS, on this socket only — no token. On a hub without
1416
+ * eval, an older agent's "8h" answer is an hour of chat on this socket.
1417
+ */
1418
+ async allowHour(ws, a, pages) {
1419
+ const t = this.now();
1420
+ if (a.forUser || !this.opts.eval) {
1421
+ const until = t + APPROVAL_MS;
1422
+ const scope = this.opts.eval ? "eval" : "chat";
1423
+ ws.serializeAttachment({
1424
+ ...a,
1425
+ until,
1426
+ scope,
1427
+ pages
1428
+ });
1429
+ send(ws, {
1430
+ type: "approved",
1431
+ until,
1432
+ scope,
1433
+ pages,
1434
+ for: a.forEmail
1435
+ });
1436
+ log({
1437
+ msg: "chat.allow",
1438
+ pair: a.pair,
1439
+ label: a.label,
1440
+ until,
1441
+ scope,
1442
+ for: a.forUser
1443
+ });
1444
+ this.broadcast();
1445
+ if (a.forUser) return;
1446
+ return send(ws, {
1447
+ type: "history",
1448
+ messages: forNode(await this.history(), a.node)
1449
+ });
1450
+ }
1451
+ const until = t + EVAL_GRANT_MS;
1452
+ const token = hex(crypto.getRandomValues(new Uint8Array(32)));
1453
+ const grant = await hashToken(token);
1454
+ await this.putGrant(grant, {
1455
+ label: a.label,
1456
+ until,
1457
+ scope: "eval",
1458
+ pages,
1459
+ at: t
1460
+ });
1461
+ ws.serializeAttachment({
1462
+ ...a,
1463
+ until,
1464
+ scope: "eval",
1465
+ pages,
1466
+ grant
1467
+ });
1468
+ send(ws, {
1469
+ type: "approved",
1470
+ until,
1471
+ scope: "eval",
1472
+ pages,
1473
+ token
1474
+ });
1475
+ log({
1476
+ msg: "chat.allow",
1477
+ pair: a.pair,
1478
+ label: a.label,
1479
+ until,
1480
+ scope: "eval"
1481
+ });
1482
+ this.broadcast();
1483
+ send(ws, {
1484
+ type: "history",
1485
+ messages: forNode(await this.history(), a.node)
1486
+ });
1487
+ }
1488
+ /** "Allow chat for 30 days": chat only, with a grant token the agent can resume with. */
1489
+ async allowChat(ws, a, pages) {
1490
+ const until = this.now() + CHAT_MS;
1491
+ const token = hex(crypto.getRandomValues(new Uint8Array(32)));
1492
+ const grant = await hashToken(token);
1493
+ await this.putGrant(grant, {
1494
+ label: a.label,
1495
+ until,
1496
+ pages,
1497
+ scope: "chat",
1498
+ at: this.now()
1499
+ });
1500
+ ws.serializeAttachment({
1501
+ ...a,
1502
+ until,
1503
+ scope: "chat",
1504
+ grant,
1505
+ pages
1506
+ });
1507
+ send(ws, {
1508
+ type: "approved",
1509
+ until,
1510
+ scope: "chat",
1511
+ pages,
1512
+ token
1513
+ });
1514
+ log({
1515
+ msg: "chat.allow",
1516
+ pair: a.pair,
1517
+ label: a.label,
1518
+ until,
1519
+ scope: "chat"
1520
+ });
1521
+ this.broadcast();
1522
+ send(ws, {
1523
+ type: "history",
1524
+ messages: forNode(await this.history(), a.node)
1525
+ });
1526
+ }
1527
+ /** Deny a pairing, or End a session — and with it the grant behind it, on every socket using it. */
1528
+ end(kind, ws, a) {
1529
+ if (kind === "deny") {
1530
+ const key = knockKey(audience(a), a.ip ?? "?");
1531
+ const t = this.now();
1532
+ this.setKnock(key, {
1533
+ ...this.knocks.get(key) ?? {
1534
+ start: t,
1535
+ count: 0
1536
+ },
1537
+ deniedAt: t
1538
+ });
1539
+ }
1540
+ const targets = a.grant ? this.sockets("controller").filter((c) => c.a.grant === a.grant) : [{
1541
+ ws,
1542
+ a
1543
+ }];
1544
+ for (const c of targets) {
1545
+ send(c.ws, { type: kind === "deny" ? "denied" : "revoked" });
1546
+ close(c.ws, kind === "deny" ? 4403 : 4401, kind);
1547
+ }
1548
+ log({
1549
+ msg: `chat.${kind}`,
1550
+ pair: a.pair,
1551
+ label: a.label
1552
+ });
1553
+ if (!a.grant) return this.broadcast(ws);
1554
+ return this.dropGrant(a.grant).then(() => this.broadcast(ws));
1555
+ }
1556
+ /** Where an agent's `say` goes: the owner's thread, or a friend's by user id or email. */
1557
+ async sayTarget(to) {
1558
+ if (!to || to === OWNER_THREAD) return { thread: OWNER_THREAD };
1559
+ const f = await this.findFriend(to);
1560
+ if (!f) return { error: `no chat thread for ${to}` };
1561
+ if (f.blocked) return { error: `${f.email} is blocked` };
1562
+ return {
1563
+ thread: f.userId,
1564
+ email: f.email
1565
+ };
1566
+ }
1567
+ /**
1568
+ * A node grant: senders within `from` may address nodes within `to`, for
1569
+ * `ms` (EVAL_GRANT_MS by default). Only an agent whose node holds both may
1570
+ * grant it or take it back; the root's always may.
1571
+ */
1572
+ async nodeGrant(ws, c, m) {
1573
+ const home = c.node ?? ROOT_NODE;
1574
+ if (!isWithin(m.from, home) || !isWithin(m.to, home)) {
1575
+ const reason = `out of scope: an agent at ${home} cannot grant ${m.from} → ${m.to}`;
1576
+ return send(ws, {
1577
+ type: "error",
1578
+ error: reason,
1579
+ reason
1580
+ });
1581
+ }
1582
+ const key = nodeGrantKey(m.from, m.to);
1583
+ if (m.type === "ungrant") {
1584
+ await this.ctx.storage.delete(key);
1585
+ log({
1586
+ msg: "chat.node-ungrant",
1587
+ from: m.from,
1588
+ to: m.to
1589
+ });
1590
+ return send(ws, {
1591
+ type: "ungranted",
1592
+ from: m.from,
1593
+ to: m.to
1594
+ });
1595
+ }
1596
+ const until = this.now() + (m.ms ?? EVAL_GRANT_MS);
1597
+ await this.ctx.storage.put(key, {
1598
+ from: m.from,
1599
+ to: m.to,
1600
+ until
1601
+ });
1602
+ log({
1603
+ msg: "chat.node-grant",
1604
+ from: m.from,
1605
+ to: m.to,
1606
+ until,
1607
+ by: home
1608
+ });
1609
+ send(ws, {
1610
+ type: "granted",
1611
+ from: m.from,
1612
+ to: m.to,
1613
+ until
1614
+ });
1615
+ }
1616
+ fromController(ws, c, raw) {
1617
+ const t = this.now();
1618
+ if (!c.until) return send(ws, {
1619
+ type: "error",
1620
+ error: "not approved yet"
1621
+ });
1622
+ if (c.until <= t) {
1623
+ send(ws, { type: "expired" });
1624
+ close(ws, 4408, "approval expired");
1625
+ return this.broadcast(ws);
1626
+ }
1627
+ const m = parseControllerMessage(raw);
1628
+ if (!m.ok) return send(ws, {
1629
+ type: "error",
1630
+ error: m.error
1631
+ });
1632
+ if (m.value.type === "busy") {
1633
+ if (c.forUser || m.value.on === false) return;
1634
+ return this.sayTarget(m.value.to).then((dest) => {
1635
+ if ("error" in dest) return send(ws, {
1636
+ type: "error",
1637
+ error: dest.error
1638
+ });
1639
+ const beat = {
1640
+ type: "busy",
1641
+ label: c.label,
1642
+ at: t
1643
+ };
1644
+ for (const p of this.pages(dest.thread)) if (dest.thread !== OWNER_THREAD || covers(c.pages, p.a.id)) send(p.ws, beat);
1645
+ });
1646
+ }
1647
+ if (m.value.type === "grant" || m.value.type === "ungrant") {
1648
+ if (c.forUser) return send(ws, {
1649
+ type: "error",
1650
+ error: "a pairing for a friend cannot chat"
1651
+ });
1652
+ return this.nodeGrant(ws, c, m.value);
1653
+ }
1654
+ if (m.value.type === "edit") return this.edit(ws, c, m.value);
1655
+ if (m.value.type === "say") {
1656
+ if (c.forUser) return send(ws, {
1657
+ type: "error",
1658
+ error: "a pairing for a friend cannot chat"
1659
+ });
1660
+ const { text, to, node, agentId } = m.value;
1661
+ const home = c.node ?? ROOT_NODE;
1662
+ const from = m.value.taskPath ?? home;
1663
+ if (!isWithin(from, home)) {
1664
+ const reason = `taskPath ${from} is outside this agent's node ${home}`;
1665
+ return send(ws, {
1666
+ type: "error",
1667
+ error: reason,
1668
+ reason
1669
+ });
1670
+ }
1671
+ if (node && to) {
1672
+ const reason = "address a thread or a node, not both";
1673
+ return send(ws, {
1674
+ type: "error",
1675
+ error: reason,
1676
+ reason
1677
+ });
1678
+ }
1679
+ const scoped = node ? this.nodeGrants().then((grants) => mayAddress(from, node, grants, t)) : Promise.resolve({ ok: true });
1680
+ return Promise.all([scoped, this.sayTarget(to)]).then(async ([scope, dest]) => {
1681
+ if (!scope.ok) return send(ws, {
1682
+ type: "error",
1683
+ error: scope.error,
1684
+ reason: scope.error
1685
+ });
1686
+ if ("error" in dest) return send(ws, {
1687
+ type: "error",
1688
+ error: dest.error
1689
+ });
1690
+ const who = agentId ?? c.assignee;
1691
+ const said = {
1692
+ id: crypto.randomUUID().slice(0, 8),
1693
+ from: "agent",
1694
+ label: c.label,
1695
+ text,
1696
+ at: t,
1697
+ ...dest,
1698
+ ...from !== ROOT_NODE ? { taskPath: from } : {},
1699
+ ...who ? { agentId: who } : {},
1700
+ ...node ? { to: node } : {}
1701
+ };
1702
+ log({
1703
+ msg: "chat.say",
1704
+ pair: c.pair,
1705
+ agent: c.label,
1706
+ thread: said.thread,
1707
+ len: text.length,
1708
+ ...this.head(text)
1709
+ });
1710
+ await this.post(said, said.thread === OWNER_THREAD ? c.pages : void 0);
1711
+ send(ws, {
1712
+ type: "said",
1713
+ id: said.id,
1714
+ thread: said.thread
1715
+ });
1716
+ });
1717
+ }
1718
+ if (c.scope === "chat") return send(ws, {
1719
+ type: "error",
1720
+ error: "this session is chat-only: it cannot eval"
1721
+ });
1722
+ if (!this.opts.eval) return send(ws, {
1723
+ type: "error",
1724
+ error: "eval is not enabled on this hub"
1725
+ });
1726
+ const id = crypto.randomUUID().slice(0, 8);
1727
+ const labels = [];
1728
+ for (const p of this.pages(audience(c))) {
1729
+ if (!covers(c.pages, p.a.id) || !matchesTarget(p.a.label, m.value.target)) continue;
1730
+ send(p.ws, {
1731
+ type: "eval",
1732
+ id,
1733
+ code: m.value.code,
1734
+ to: c.pair
1735
+ });
1736
+ labels.push(p.a.label);
1737
+ }
1738
+ log({
1739
+ msg: "chat.eval",
1740
+ id,
1741
+ pair: c.pair,
1742
+ agent: c.label,
1743
+ for: c.forUser,
1744
+ len: m.value.code.length,
1745
+ target: m.value.target,
1746
+ ...this.head(m.value.code, 200),
1747
+ delivered: labels.length
1748
+ });
1749
+ send(ws, {
1750
+ type: "sent",
1751
+ id,
1752
+ delivered: labels.length,
1753
+ labels
1754
+ });
1755
+ }
1756
+ webSocketClose(ws, code) {
1757
+ close(ws, code === 1005 ? 1e3 : code, "");
1758
+ const a = att(ws);
1759
+ if (a?.role === "controller") return this.broadcast(ws);
1760
+ if (a?.role === "page") return this.pageClosed(ws, a);
1761
+ }
1762
+ };
1763
+ function stripUndefined(o) {
1764
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1765
+ }
1766
+ /**
1767
+ * A ChatHub class with these options baked in, to export from your Worker as
1768
+ * the Durable Object: `export const ChatHub = chatHub({ eval: true })`.
1769
+ */
1770
+ function chatHub(opts = {}) {
1771
+ return class extends ChatHub {
1772
+ constructor(ctx, env) {
1773
+ super(ctx, env, Date.now, opts);
1774
+ }
1775
+ };
1776
+ }
1777
+ /**
1778
+ * Whether a page socket's Origin may connect: the request's own origin, or
1779
+ * one listed in `allowed`. A request with no Origin is not from a browser
1780
+ * page (browsers always send one on a WebSocket), so it can only use
1781
+ * credentials it already holds: it goes on to `identify` like any other.
1782
+ */
1783
+ function pageOriginAllowed(req, allowed = []) {
1784
+ const origin = req.headers.get("origin");
1785
+ if (origin === null) return true;
1786
+ return origin === new URL(req.url).origin || allowed.includes(origin);
1787
+ }
1788
+ /**
1789
+ * Route a request to the hub if it is one of its two sockets; null otherwise
1790
+ * (so the site's own routes go on). Pages are identified by the site and
1791
+ * their identity is passed in IDENTITY_HEADERS (any the client sent are
1792
+ * dropped). A page socket from a foreign Origin is refused (see
1793
+ * `allowedOrigins`); an agent socket is refused if it carries any Origin
1794
+ * (a web page).
1795
+ */
1796
+ async function routeChat(req, ns, opts) {
1797
+ const url = new URL(req.url);
1798
+ const pagePath = opts.pagePath ?? "/api/chat";
1799
+ const controlPath = opts.controlPath ?? `${pagePath}/control`;
1800
+ if (url.pathname !== pagePath && url.pathname !== controlPath) return null;
1801
+ if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("WebSocket only", { status: 426 });
1802
+ const headers = new Headers(req.headers);
1803
+ for (const h of Object.values(IDENTITY_HEADERS)) headers.delete(h);
1804
+ headers.delete(IP_HEADER);
1805
+ const hub = ns.get(ns.idFromName(opts.name ?? "chat"));
1806
+ const inner = new URL(url);
1807
+ if (url.pathname === controlPath) {
1808
+ if (req.headers.get("origin")) return new Response("forbidden", { status: 403 });
1809
+ const ip = req.headers.get("cf-connecting-ip");
1810
+ if (ip) headers.set(IP_HEADER, ip.slice(0, 64));
1811
+ inner.pathname = "/control";
1812
+ return hub.fetch(new Request(inner, { headers }));
1813
+ }
1814
+ if (!pageOriginAllowed(req, opts.allowedOrigins)) return new Response("forbidden origin", { status: 403 });
1815
+ let who = null;
1816
+ try {
1817
+ who = await opts.identify(req);
1818
+ } catch {
1819
+ who = null;
1820
+ }
1821
+ if (!who || !who.owner && !isUserId(who.userId)) return new Response("forbidden", { status: 403 });
1822
+ headers.set(IDENTITY_HEADERS.user, who.owner ? OWNER_THREAD : who.userId);
1823
+ headers.set(IDENTITY_HEADERS.email, who.email ?? "");
1824
+ headers.set(IDENTITY_HEADERS.owner, who.owner ? "1" : "0");
1825
+ inner.pathname = "/page";
1826
+ return hub.fetch(new Request(inner, { headers }));
1827
+ }
1828
+
1829
+ //#endregion
1830
+ export { ChatHub, FRIEND_MAX_PAGES, FRIEND_RELABEL_MS, GRANT_DEFAULT, GRANT_MAX_MS, IDENTITY_HEADERS, IP_HEADER, MAX_BODY, OWNER_THREAD, PAIR_AUDIENCE_MAX, PAIR_COOLDOWN_MS, PAIR_MAX, PAIR_WINDOW_MS, PROGRESS_READER_HEADER, ProgressHub, RATE, RESOLVED_NOTE, TOKEN_HEADER, chatHub, hashToken, isUserId, pageOriginAllowed, progressGate, progressHub, routeChat, routeProgress };
1831
+ //# sourceMappingURL=hub.js.map