driverkit 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 (159) hide show
  1. package/CONTROLS.md +578 -0
  2. package/README.md +104 -2
  3. package/dist/agent/backend.d.ts +69 -0
  4. package/dist/agent/backend.d.ts.map +1 -0
  5. package/dist/agent/backend.js +130 -0
  6. package/dist/agent/backend.js.map +1 -0
  7. package/dist/agent/control.d.ts +148 -0
  8. package/dist/agent/control.d.ts.map +1 -0
  9. package/dist/agent/control.js +342 -0
  10. package/dist/agent/control.js.map +1 -0
  11. package/dist/agent/index.d.ts +9 -0
  12. package/dist/agent/index.d.ts.map +1 -0
  13. package/dist/agent/index.js +6 -0
  14. package/dist/agent/index.js.map +1 -0
  15. package/dist/agent/loop.d.ts +136 -0
  16. package/dist/agent/loop.d.ts.map +1 -0
  17. package/dist/agent/loop.js +824 -0
  18. package/dist/agent/loop.js.map +1 -0
  19. package/dist/agent/render.d.ts +173 -0
  20. package/dist/agent/render.d.ts.map +1 -0
  21. package/dist/agent/render.js +425 -0
  22. package/dist/agent/render.js.map +1 -0
  23. package/dist/agent/tools.d.ts +138 -0
  24. package/dist/agent/tools.d.ts.map +1 -0
  25. package/dist/agent/tools.js +622 -0
  26. package/dist/agent/tools.js.map +1 -0
  27. package/dist/agent/types.d.ts +566 -0
  28. package/dist/agent/types.d.ts.map +1 -0
  29. package/dist/agent/types.js +32 -0
  30. package/dist/agent/types.js.map +1 -0
  31. package/dist/browser/budget.d.ts +92 -0
  32. package/dist/browser/budget.d.ts.map +1 -0
  33. package/dist/browser/budget.js +151 -0
  34. package/dist/browser/budget.js.map +1 -0
  35. package/dist/browser/connect.d.ts +368 -0
  36. package/dist/browser/connect.d.ts.map +1 -0
  37. package/dist/browser/connect.js +1038 -0
  38. package/dist/browser/connect.js.map +1 -0
  39. package/dist/browser/elsewhere.d.ts +89 -0
  40. package/dist/browser/elsewhere.d.ts.map +1 -0
  41. package/dist/browser/elsewhere.js +91 -0
  42. package/dist/browser/elsewhere.js.map +1 -0
  43. package/dist/browser/frames.d.ts +85 -0
  44. package/dist/browser/frames.d.ts.map +1 -0
  45. package/dist/browser/frames.js +11 -0
  46. package/dist/browser/frames.js.map +1 -0
  47. package/dist/browser/index.d.ts +8 -0
  48. package/dist/browser/index.d.ts.map +1 -0
  49. package/dist/browser/index.js +9 -0
  50. package/dist/browser/index.js.map +1 -0
  51. package/dist/check/check.d.ts +171 -0
  52. package/dist/check/check.d.ts.map +1 -0
  53. package/dist/check/check.js +666 -0
  54. package/dist/check/check.js.map +1 -0
  55. package/dist/check/index.d.ts +3 -0
  56. package/dist/check/index.d.ts.map +1 -0
  57. package/dist/check/index.js +2 -0
  58. package/dist/check/index.js.map +1 -0
  59. package/dist/check/types.d.ts +149 -0
  60. package/dist/check/types.d.ts.map +1 -0
  61. package/dist/check/types.js +29 -0
  62. package/dist/check/types.js.map +1 -0
  63. package/dist/controls/controls.d.ts +198 -0
  64. package/dist/controls/controls.d.ts.map +1 -0
  65. package/dist/controls/controls.js +742 -0
  66. package/dist/controls/controls.js.map +1 -0
  67. package/dist/controls/dom.d.ts +108 -0
  68. package/dist/controls/dom.d.ts.map +1 -0
  69. package/dist/controls/dom.js +56 -0
  70. package/dist/controls/dom.js.map +1 -0
  71. package/dist/controls/index.d.ts +26 -0
  72. package/dist/controls/index.d.ts.map +1 -0
  73. package/dist/controls/index.js +23 -0
  74. package/dist/controls/index.js.map +1 -0
  75. package/dist/controls/rows.d.ts +66 -0
  76. package/dist/controls/rows.d.ts.map +1 -0
  77. package/dist/controls/rows.js +127 -0
  78. package/dist/controls/rows.js.map +1 -0
  79. package/dist/core/index.d.ts +3 -0
  80. package/dist/core/index.d.ts.map +1 -0
  81. package/dist/core/index.js +15 -0
  82. package/dist/core/index.js.map +1 -0
  83. package/dist/core/registry.d.ts +192 -0
  84. package/dist/core/registry.d.ts.map +1 -0
  85. package/dist/core/registry.js +2799 -0
  86. package/dist/core/registry.js.map +1 -0
  87. package/dist/core/types.d.ts +2468 -0
  88. package/dist/core/types.d.ts.map +1 -0
  89. package/dist/core/types.js +19 -0
  90. package/dist/core/types.js.map +1 -0
  91. package/dist/otel/index.d.ts +122 -0
  92. package/dist/otel/index.d.ts.map +1 -0
  93. package/dist/otel/index.js +157 -0
  94. package/dist/otel/index.js.map +1 -0
  95. package/dist/react/index.d.ts +191 -0
  96. package/dist/react/index.d.ts.map +1 -0
  97. package/dist/react/index.js +547 -0
  98. package/dist/react/index.js.map +1 -0
  99. package/dist/react/runtime.d.ts +95 -0
  100. package/dist/react/runtime.d.ts.map +1 -0
  101. package/dist/react/runtime.js +54 -0
  102. package/dist/react/runtime.js.map +1 -0
  103. package/dist/react/store.d.ts +333 -0
  104. package/dist/react/store.d.ts.map +1 -0
  105. package/dist/react/store.js +695 -0
  106. package/dist/react/store.js.map +1 -0
  107. package/dist/relay/auth.d.ts +244 -0
  108. package/dist/relay/auth.d.ts.map +1 -0
  109. package/dist/relay/auth.js +391 -0
  110. package/dist/relay/auth.js.map +1 -0
  111. package/dist/relay/frames.d.ts +141 -0
  112. package/dist/relay/frames.d.ts.map +1 -0
  113. package/dist/relay/frames.js +20 -0
  114. package/dist/relay/frames.js.map +1 -0
  115. package/dist/relay/index.d.ts +8 -0
  116. package/dist/relay/index.d.ts.map +1 -0
  117. package/dist/relay/index.js +4 -0
  118. package/dist/relay/index.js.map +1 -0
  119. package/dist/relay/relay.d.ts +277 -0
  120. package/dist/relay/relay.d.ts.map +1 -0
  121. package/dist/relay/relay.js +1026 -0
  122. package/dist/relay/relay.js.map +1 -0
  123. package/dist/relay/serve.d.ts +33 -0
  124. package/dist/relay/serve.d.ts.map +1 -0
  125. package/dist/relay/serve.js +86 -0
  126. package/dist/relay/serve.js.map +1 -0
  127. package/dist/widget/chat.d.ts +290 -0
  128. package/dist/widget/chat.d.ts.map +1 -0
  129. package/dist/widget/chat.js +486 -0
  130. package/dist/widget/chat.js.map +1 -0
  131. package/dist/widget/css.d.ts +49 -0
  132. package/dist/widget/css.d.ts.map +1 -0
  133. package/dist/widget/css.js +532 -0
  134. package/dist/widget/css.js.map +1 -0
  135. package/dist/widget/dom.d.ts +143 -0
  136. package/dist/widget/dom.d.ts.map +1 -0
  137. package/dist/widget/dom.js +27 -0
  138. package/dist/widget/dom.js.map +1 -0
  139. package/dist/widget/highlight.d.ts +64 -0
  140. package/dist/widget/highlight.d.ts.map +1 -0
  141. package/dist/widget/highlight.js +136 -0
  142. package/dist/widget/highlight.js.map +1 -0
  143. package/dist/widget/index.d.ts +9 -0
  144. package/dist/widget/index.d.ts.map +1 -0
  145. package/dist/widget/index.js +20 -0
  146. package/dist/widget/index.js.map +1 -0
  147. package/dist/widget/position.d.ts +166 -0
  148. package/dist/widget/position.d.ts.map +1 -0
  149. package/dist/widget/position.js +497 -0
  150. package/dist/widget/position.js.map +1 -0
  151. package/dist/widget/settings.d.ts +116 -0
  152. package/dist/widget/settings.d.ts.map +1 -0
  153. package/dist/widget/settings.js +117 -0
  154. package/dist/widget/settings.js.map +1 -0
  155. package/dist/widget/widget.d.ts +442 -0
  156. package/dist/widget/widget.d.ts.map +1 -0
  157. package/dist/widget/widget.js +2005 -0
  158. package/dist/widget/widget.js.map +1 -0
  159. package/package.json +153 -4
@@ -0,0 +1,1038 @@
1
+ /**
2
+ * driverkit/browser — the page side.
3
+ *
4
+ * One function. It holds an `EventSource` open, answers `call` frames by
5
+ * handing them to the driver `mount()` returned, and POSTs the `Result` back.
6
+ * It makes no decisions: it does not validate args, does not check `rev`, does
7
+ * not refuse. The driver owns all of that, and PROTOCOL.md's reason is the one
8
+ * that matters -- a second place that validates is a second set of rules, and
9
+ * the in-page chatbot calling `driver.call()` directly would get the other one.
10
+ *
11
+ * No dependencies and no framework. `EventSource` and `fetch` are built in,
12
+ * which is half of why the protocol is SSE in the first place.
13
+ */
14
+ /** `EventSource.CLOSED`. Spelled out because the fake need not define statics. */
15
+ const CLOSED = 2;
16
+ /**
17
+ * How many times one `result` is re-sent after a 409 before it is given up on.
18
+ *
19
+ * Bounded, because the failure this guards against is symmetrical. A result
20
+ * dropped on the floor costs the agent the relay's whole deadline waiting for
21
+ * an answer that already exists; a result re-sent forever costs it a tab that
22
+ * reconnects in a loop and never answers anything. Two is enough for the case
23
+ * this is for -- the relay dropped the tab between the `call` going out and the
24
+ * `result` coming back, and one reconnect fixes that -- and anything more is a
25
+ * relay that is not coming back.
26
+ */
27
+ const RESULT_RETRIES = 2;
28
+ /**
29
+ * How long a 409 retry waits for the new stream to open before going anyway.
30
+ *
31
+ * It has to be bounded. Everything queued behind the retried result waits on
32
+ * this, so an unbounded wait on a stream that never opens is a tab that never
33
+ * answers anything again -- a worse failure than the dropped result this is
34
+ * fixing. On expiry the retry goes out regardless, takes another 409, and
35
+ * spends one of its `RESULT_RETRIES`.
36
+ */
37
+ const RECONNECT_WAIT_MS = 3_000;
38
+ /**
39
+ * How many times one frame is re-sent after a 401 with a fresh credential.
40
+ *
41
+ * One, because the case this is for is a token that lapsed between the stream
42
+ * opening and this POST, and one refresh fixes that. A second attempt would
43
+ * only help if the FIRST refresh also produced a dead token, which is a
44
+ * misconfiguration -- a wrong audience, a key the relay does not have -- and a
45
+ * misconfiguration retried in a loop is a page making a request per attempt
46
+ * and never answering anything.
47
+ */
48
+ const AUTH_RETRIES = 1;
49
+ /**
50
+ * The `sessionStorage` key the anonymous secret lives under.
51
+ *
52
+ * Separate from the tab id's key: an explicitly passed `tab` is deliberately
53
+ * NOT written back, and an anonymous credential still has to be remembered
54
+ * across the page's own reconnects or every reconnect would be a new visitor.
55
+ */
56
+ const ANON_KEY = "driverkit:anon";
57
+ export function connect(driver, options) {
58
+ const relay = options.relay.replace(/\/+$/, "");
59
+ const debounceMs = options.debounceMs ?? 250;
60
+ const backoffMs = options.backoffMs ?? 500;
61
+ const maxBackoffMs = options.maxBackoffMs ?? 10_000;
62
+ const onError = options.onError ?? (() => { });
63
+ const ES = options.EventSource ?? globalThis.EventSource;
64
+ const post = options.fetch ?? globalThis.fetch?.bind(globalThis);
65
+ const storage = options.storage === null
66
+ ? null
67
+ : (options.storage ?? globalThis.sessionStorage ?? null);
68
+ const page = options.document ?? globalThis.document;
69
+ const place = options.location ?? globalThis.location;
70
+ // `globalThis` IS the window in a page, and in Node it is a global with an
71
+ // `addEventListener` that exists and never fires either of these -- which is
72
+ // harmless and is why this needs no environment check.
73
+ const focusEvents = options.window ??
74
+ (typeof globalThis.addEventListener === "function"
75
+ ? globalThis
76
+ : undefined);
77
+ const wantsFocus = options.focus !== false;
78
+ const wantsTiming = options.timing !== false;
79
+ /** `options.now?.()` and never a detached `options.now ?? Date.now`, the rule
80
+ * the loop's clock already follows: a method pulled off an object and called
81
+ * bare loses its receiver, and a fake clock reading a private field throws. */
82
+ const nowMs = () => options.now?.() ?? Date.now();
83
+ if (!ES)
84
+ throw new Error("driverkit: no EventSource. Pass options.EventSource.");
85
+ if (!post)
86
+ throw new Error("driverkit: no fetch. Pass options.fetch.");
87
+ // Before anything is opened, for the reason a relay with remote access and
88
+ // no way to identify callers refuses to start rather than serving: this is
89
+ // the moment the app becomes drivable by something that is not in the room.
90
+ //
91
+ // Kinds first, and the order is an argument rather than a style: the commit
92
+ // check reads `kind`, so a manifest with silent verbs cannot be assessed by
93
+ // it at all. "Declare your kinds" and then "now say who approves these
94
+ // three commits" is two true sentences in the order they can be acted on;
95
+ // the other order asks about a list that is not yet known to be complete.
96
+ requireDeclaredKinds(driver);
97
+ requireApprovalPolicy(driver);
98
+ const tab = options.tab ?? remembered(storage, options.app, options.randomUUID, onError);
99
+ const tokenIn = options.tokenIn ?? "query";
100
+ const mintToken = typeof options.token === "function"
101
+ ? options.token
102
+ : options.token !== undefined
103
+ ? () => options.token
104
+ : options.anonymous
105
+ ? () => anonCredential(storage, options.app, onError)
106
+ : null;
107
+ let live = true;
108
+ /**
109
+ * The credential in hand, refreshed by `refresh()`.
110
+ *
111
+ * Kept rather than fetched per request so that the common case -- a static
112
+ * string, or no credential at all -- opens its stream synchronously inside
113
+ * the `connect()` call that asked for it, exactly as it did before tokens
114
+ * existed.
115
+ */
116
+ let credential =
117
+ // Synchronous only: an async getter is awaited by `open()` instead. The
118
+ // cast is safe because the two synchronous branches of `mintToken` above
119
+ // are the only ones reachable here.
120
+ mintToken && typeof options.token !== "function" ? mintToken() : undefined;
121
+ let opening = false;
122
+ let source = null;
123
+ let delay = backoffMs;
124
+ let debounce = null;
125
+ let reopen = null;
126
+ let watch = null;
127
+ /** The focus state the relay was last told, so an event that does not move
128
+ * it costs nothing. `undefined` before the first push and in an environment
129
+ * that reports no focus at all. */
130
+ let pushedFocus;
131
+ /** How to drop the three focus listeners, set only when they were added. */
132
+ let stopFocus = null;
133
+ const url = (path) => `${relay}${path}?tab=${encodeURIComponent(tab)}`;
134
+ /**
135
+ * The `/dk/events` URL, with the credential if it travels in the query.
136
+ *
137
+ * Only the stream URL ever carries it. The `/dk/result` POSTs put it in
138
+ * `X-DK-Token`, where no access log will write it down.
139
+ */
140
+ const streamUrl = () => credential !== undefined && tokenIn === "query"
141
+ ? `${url("/dk/events")}&dk_token=${encodeURIComponent(credential)}`
142
+ : url("/dk/events");
143
+ /** Fetch a fresh credential. Resolves even on failure; see the comment. */
144
+ async function refresh() {
145
+ if (!mintToken)
146
+ return;
147
+ try {
148
+ credential = await mintToken();
149
+ }
150
+ catch (err) {
151
+ // Reported and then ignored, keeping whatever we had. A token endpoint
152
+ // that is briefly down must not take the tab down with it: the stream we
153
+ // already hold is still bound to this principal in the relay, and a
154
+ // slightly stale token is a better bet than no attempt at all. The relay
155
+ // answers 401 if it has really lapsed, and that path retries.
156
+ onError(err);
157
+ }
158
+ }
159
+ const outbox = [];
160
+ let draining = false;
161
+ /** Resolved by the stream's `open` listener. See `reconnect`. */
162
+ let openWaiters = [];
163
+ function up(frame) {
164
+ if (!live)
165
+ return;
166
+ const entry = { frame, tries: 0, stale: 0 };
167
+ // `hello` jumps the queue, and only `hello` does. It is the frame that
168
+ // makes this tab exist in the relay's registry -- `ingest` 409s every frame
169
+ // for a tab it has no stream for, `hello` included -- so everything already
170
+ // waiting needs it to have landed first. Appending it would mean a `result`
171
+ // that took a 409 gets re-sent against the same empty registry it was just
172
+ // refused by, which is a retry that cannot succeed.
173
+ if (frame.t === "hello")
174
+ outbox.unshift(entry);
175
+ else
176
+ outbox.push(entry);
177
+ if (!draining)
178
+ void drain();
179
+ }
180
+ /**
181
+ * Send what is queued, oldest first, until it is empty.
182
+ *
183
+ * `drain` runs synchronously as far as the first POST, so the common case --
184
+ * an idle outbox -- still issues its request inside the `up()` call that
185
+ * queued it, exactly as the old one-POST-per-frame code did.
186
+ */
187
+ async function drain() {
188
+ draining = true;
189
+ try {
190
+ while (live && outbox.length) {
191
+ const entry = outbox[0];
192
+ // Removal is by identity, not `shift()`. A `hello` may have been
193
+ // unshifted ahead of this entry while its POST was in the air, and
194
+ // `shift()` would then drop the wrong frame.
195
+ const forget = () => {
196
+ const at = outbox.indexOf(entry);
197
+ if (at !== -1)
198
+ outbox.splice(at, 1);
199
+ };
200
+ let status;
201
+ try {
202
+ // `?tab=` as well as the body field: PROTOCOL.md's frame shapes name
203
+ // the tab only in `hello`, so a relay that reads one and not the
204
+ // other still works. Belt and braces on the field the whole
205
+ // correlation depends on.
206
+ const answer = await post(url("/dk/result"), {
207
+ method: "POST",
208
+ headers: {
209
+ "content-type": "application/json",
210
+ // A HEADER, never the query string. `fetch` can set one, so
211
+ // there is no reason for a token to be written into an access
212
+ // log here -- unlike the `EventSource` URL, which has no choice.
213
+ ...(credential === undefined ? {} : { "x-dk-token": credential }),
214
+ },
215
+ body: JSON.stringify(entry.frame),
216
+ });
217
+ status = answer?.status;
218
+ }
219
+ catch (err) {
220
+ // The POST never completed: offline, DNS, a relay that is not
221
+ // listening. Not retried here -- there is no status to tell a
222
+ // transient failure from a permanent one, and `EventSource` is about
223
+ // to notice the same outage and run the reconnect path anyway.
224
+ forget();
225
+ onError(err);
226
+ continue;
227
+ }
228
+ if (status === undefined || status < 400) {
229
+ forget();
230
+ continue;
231
+ }
232
+ if (status === 401) {
233
+ // THE MID-SESSION EXPIRY PATH, and the reason `token` is a getter.
234
+ //
235
+ // The relay authenticates the stream once, at open, and the binding
236
+ // it made lasts as long as the stream -- so a lapsed token does not
237
+ // disconnect this tab and does not lose the calls in flight. But
238
+ // `/dk/result` is a new request and carries its own credential, so
239
+ // the symptom of expiry is exactly this: a tab that still receives
240
+ // `call` frames and cannot answer them.
241
+ //
242
+ // Mint a fresh one and send the same bytes again. Bounded, because a
243
+ // token endpoint answering with a credential the relay will not
244
+ // accept -- a wrong audience, a key the relay does not have -- is a
245
+ // misconfiguration, and retrying it forever is a page that never
246
+ // answers anything while making a request per attempt.
247
+ if (!mintToken || entry.stale >= AUTH_RETRIES) {
248
+ forget();
249
+ onError(new Error(`driverkit: the relay rejected this tab's credential on a \`${entry.frame.t}\` ` +
250
+ (mintToken
251
+ ? `frame after ${entry.stale} refreshes. Check the token's audience and key.`
252
+ : "frame, and no `token` option was given to refresh it.")));
253
+ continue;
254
+ }
255
+ entry.stale += 1;
256
+ await refresh();
257
+ continue;
258
+ }
259
+ if (status === 409) {
260
+ // PROTOCOL.md: "409 means the frame was fine and the relay's state is
261
+ // what made it unacceptable. A tab that gets 409 may reasonably
262
+ // reconnect and retry." The relay has dropped this tab -- its stream
263
+ // closed and the registry entry went with it -- so reconnecting is
264
+ // the whole of the fix, and it is the one status where re-sending the
265
+ // same bytes can work.
266
+ //
267
+ // `fetch` resolves on 409, which is why ignoring the status was not a
268
+ // missing nicety: the answer the agent is holding a request open for
269
+ // was lost here silently, and the agent waited out the relay's full
270
+ // 15-second deadline for a result that already existed.
271
+ const again = entry.frame.t === "result" && entry.tries < RESULT_RETRIES;
272
+ if (again) {
273
+ entry.tries += 1;
274
+ }
275
+ else {
276
+ forget();
277
+ // Only a `result` is worth a noise. A `hello` or a `snapshot` is
278
+ // superseded by the `hello` the reconnect below sends, which
279
+ // carries a newer snapshot than the one that just 409'd -- re-
280
+ // sending the stale one would push an older `rev` after a newer
281
+ // one, which is the one thing a watcher cannot recover from.
282
+ if (entry.frame.t === "result") {
283
+ onError(new Error(`driverkit: relay still 409s result \`${entry.frame.id}\` after ${entry.tries} reconnects; ` +
284
+ `the agent will see it as a timeout`));
285
+ }
286
+ }
287
+ await reconnect();
288
+ continue;
289
+ }
290
+ // 400 and anything else. PROTOCOL.md: "400 means the frame could never
291
+ // have been accepted by anyone... a tab that gets 400 has a bug." So it
292
+ // is loud and it is never retried: re-sending a frame the relay has
293
+ // already judged malformed is a loop with no exit, and the bug is here.
294
+ forget();
295
+ onError(new Error(`driverkit: relay answered ${status} to a \`${entry.frame.t}\` frame. ` +
296
+ `A 4xx on /dk/result that is not a 409 is a bug in this tab, not in the relay.`));
297
+ }
298
+ }
299
+ finally {
300
+ draining = false;
301
+ }
302
+ }
303
+ /**
304
+ * Drop this stream and bring up a new one, resolving once `hello` is queued.
305
+ *
306
+ * Not just `open()`: the registry entry the 409 is about belongs to a stream
307
+ * the relay has already forgotten, and a tab that kept holding it would wait
308
+ * for a `call` frame down a pipe nothing is writing to.
309
+ *
310
+ * It resolves on the new stream's `open` rather than on a timer because the
311
+ * `open` listener is what sends `hello`, and the retried result must go out
312
+ * behind that `hello`. The queue does the rest: `hello` is unshifted ahead of
313
+ * the retry, and the loop above awaits each POST, so the ordering is
314
+ * structural rather than a guessed delay.
315
+ */
316
+ function reconnect() {
317
+ if (!live)
318
+ return Promise.resolve();
319
+ if (source) {
320
+ const old = source;
321
+ source = null;
322
+ try {
323
+ old.close();
324
+ }
325
+ catch (err) {
326
+ onError(err);
327
+ }
328
+ if (reopen) {
329
+ clearTimeout(reopen);
330
+ reopen = null;
331
+ }
332
+ open();
333
+ }
334
+ else if (!reopen) {
335
+ // No stream and nothing scheduled: the error path has already given up,
336
+ // or two 409s arrived and the first one's reconnect is what closed this.
337
+ open();
338
+ }
339
+ // Otherwise a reopen is already on a timer -- the backoff path's. Waiting
340
+ // for it rather than racing it, because two streams for one tab id is a
341
+ // supersede, and superseding the stream we are waiting on is a loop.
342
+ return new Promise((resolve) => {
343
+ let settled = false;
344
+ const finish = () => {
345
+ if (settled)
346
+ return;
347
+ settled = true;
348
+ resolve();
349
+ };
350
+ openWaiters.push(finish);
351
+ const timer = setTimeout(finish, RECONNECT_WAIT_MS);
352
+ timer.unref?.();
353
+ });
354
+ }
355
+ /** The url as it is NOW, or an explicit one the app passed. Spelled once
356
+ * because `hello` and every push must agree about it; two copies is how the
357
+ * reconnect path comes to report something the push path does not. */
358
+ function whereNow() {
359
+ return options.url === undefined ? urlFromPage(place) : { url: options.url };
360
+ }
361
+ /** The focus as it is NOW, or nothing at all when the app opted out or the
362
+ * environment is not a page. An absent field means "did not say"; see
363
+ * `TabFocus`. */
364
+ function focusNow() {
365
+ if (!wantsFocus)
366
+ return {};
367
+ const focus = focusOf(page);
368
+ return focus === undefined ? {} : { focus };
369
+ }
370
+ function hello() {
371
+ const frame = {
372
+ t: "hello",
373
+ tab,
374
+ ...(options.app === undefined ? {} : { app: options.app }),
375
+ manifest: driver.manifest(),
376
+ snapshot: driver.snapshot(),
377
+ ...(options.title === undefined ? { ...titleFromPage(page) } : { title: options.title }),
378
+ ...whereNow(),
379
+ // In `hello` as well as in the pushes, because `hello` is the only frame
380
+ // a tab that never moves ever sends. A tab opened and left alone would
381
+ // otherwise have no focus at all in `/dk/tabs`, which is the listing a
382
+ // client reads before it has seen a single push.
383
+ ...focusNow(),
384
+ };
385
+ up(frame);
386
+ }
387
+ /**
388
+ * The verb kinds this app declared, read off the manifest once.
389
+ *
390
+ * The manifest is the static half and is guaranteed not to vary between two
391
+ * calls, so this is cached rather than rebuilt per call -- but keyed on
392
+ * `version`, because a hand-written driver is free to be stranger than the
393
+ * core's and a stale map would decide `canTime` with yesterday's kinds.
394
+ */
395
+ let kinds = null;
396
+ function kindOf(name) {
397
+ const manifest = driver.manifest();
398
+ if (kinds === null || kinds.version !== manifest.version) {
399
+ kinds = {
400
+ version: manifest.version,
401
+ of: new Map(manifest.verbs.map((v) => [v.name, v.kind])),
402
+ };
403
+ }
404
+ return kinds.of.get(name);
405
+ }
406
+ /**
407
+ * Whether this tab can state this call's duration without a person in it.
408
+ *
409
+ * THE WHOLE HONESTY ARGUMENT, and it is about WHERE the measurement is taken
410
+ * rather than about arithmetic afterwards. The clock brackets
411
+ * `driver.call()`, which is the same bracket the in-page loop uses -- so
412
+ * everything the page does outside that call is outside the figure for free.
413
+ * What is INSIDE it, and invisible from here, is a person:
414
+ *
415
+ * `ask` IS a question put to somebody. Its whole duration is a human
416
+ * reading and typing, so a `tookMs` for one would be a false
417
+ * claim about the app with no true part to it at all.
418
+ * `commit` may be held by the core's approval gate, which is the
419
+ * configuration `mountWidget` creates through
420
+ * `DriverApproval.adopt`. `policy` is a LIVE read for exactly
421
+ * this reason: the same driver answers `none` before a panel
422
+ * mounts and `adopted` after, and only `hook` and `adopted` can
423
+ * put a question in front of anybody -- `unattended` answers
424
+ * itself and `none` is no gate.
425
+ *
426
+ * Everything else -- a `read`, a `describe`, a commit nobody is asked about,
427
+ * a verb that declared no `kind` at all and so is never gated by the core --
428
+ * is the app's own work and is reported.
429
+ *
430
+ * `waited` settles all of it: a host that counts its own person-time has the
431
+ * figure this cannot see, so it is subtracted and the call is timed whatever
432
+ * its kind. Without one, the answer here is silence, which PROTOCOL.md pins
433
+ * as UNKNOWN rather than zero. A tab that waits on a person inside a verb
434
+ * BODY is beyond anything this can know and must report it through `waited`
435
+ * or pass `timing: false`; that is stated in PROTOCOL.md as a must and is the
436
+ * one case left where a wrong figure is reachable.
437
+ */
438
+ function canTime(name) {
439
+ if (options.waited !== undefined)
440
+ return true;
441
+ const kind = kindOf(name);
442
+ if (kind === "ask")
443
+ return false;
444
+ if (kind !== "commit")
445
+ return true;
446
+ const policy = driver.approval?.policy;
447
+ return policy !== "hook" && policy !== "adopted";
448
+ }
449
+ /**
450
+ * The two fields a `result` frame carries about its own elapsed time, or
451
+ * nothing at all.
452
+ *
453
+ * Both figures are whole milliseconds and both are floored at zero.
454
+ * `Math.max(0, ...)` twice, because `waited` is reported by a host and a host
455
+ * that reports more wait than the call took is a host with a bug -- in which
456
+ * case the honest figure is the floor and not a negative number on the wire.
457
+ * A clock that went backwards lands in the same place; `renderDuration`
458
+ * refuses to print a negative duration either way, and this refuses to send
459
+ * one.
460
+ *
461
+ * `waitedMs` is sent only when somebody actually waited. Zero is the normal
462
+ * case and a key that says "no person, this time" on every call in every
463
+ * session is rent paid forever for a fact the absence already carries -- the
464
+ * same argument `renderDuration` makes for saying nothing about a fast call.
465
+ */
466
+ function timing(timed, started, waitedBefore) {
467
+ if (!timed)
468
+ return {};
469
+ const waited = Math.max(0, (options.waited?.() ?? 0) - waitedBefore);
470
+ const took = Math.max(0, Math.floor(nowMs() - started - waited));
471
+ // A broken clock, or a `waited` that returned something that is not a
472
+ // number, is a measurement that did not happen -- and the honest rendering
473
+ // of one of those is silence, not `null` on the wire for a relay to throw
474
+ // away at the other end.
475
+ if (!Number.isFinite(took))
476
+ return {};
477
+ return { tookMs: took, ...(waited > 0 ? { waitedMs: Math.floor(waited) } : {}) };
478
+ }
479
+ async function onCall(frame) {
480
+ // Read before the call and again after, with nothing of this function's own
481
+ // between the two reads: the pace of the loop, the POST that carries the
482
+ // answer and this tab's own error handling are all outside the bracket by
483
+ // construction. `timed` is null for a call this tab cannot speak for, and
484
+ // then no clock is read at all -- an app that opts out, or a question put to
485
+ // a person, costs exactly the bytes and the cycles it did before.
486
+ const timed = wantsTiming && canTime(frame.name);
487
+ const started = timed ? nowMs() : 0;
488
+ const waitedBefore = timed ? (options.waited?.() ?? 0) : 0;
489
+ let result;
490
+ try {
491
+ result = await driver.call(frame.name, frame.args ?? {},
492
+ // Only when the agent sent one. The core treats a present `rev` or
493
+ // `screen` as a check and an absent one as opting out of it, so passing
494
+ // `{ rev: undefined }` would be fine today and a trap the day somebody
495
+ // tightens that. `screen` is the agent's claim about which screen it
496
+ // read, checked by the core before `rev`; this hop is where it would
497
+ // otherwise be dropped, which would leave the field working in-page and
498
+ // silently doing nothing over the relay. `plan` is here for the same
499
+ // reason and with the most to lose by being missed: a commit that
500
+ // requires a token and is reached by a path that drops it is refused
501
+ // forever, and one reached by a path that invents one would be worse.
502
+ {
503
+ ...(frame.rev === undefined ? {} : { rev: frame.rev }),
504
+ ...(frame.screen === undefined ? {} : { screen: frame.screen }),
505
+ ...(frame.plan === undefined ? {} : { plan: frame.plan }),
506
+ });
507
+ }
508
+ catch (err) {
509
+ // `mount()`'s driver turns a throwing verb into `refused: "threw"`, so
510
+ // this is only reachable for a hand-written driver. Still answered
511
+ // rather than dropped: the agent is holding a request open on this id,
512
+ // and silence costs it the relay's full timeout.
513
+ onError(err);
514
+ result = {
515
+ ok: false,
516
+ refused: "threw",
517
+ hint: err instanceof Error ? err.message : String(err),
518
+ snapshot: driver.snapshot(),
519
+ };
520
+ }
521
+ up({ t: "result", id: frame.id, result, tab, ...timing(timed, started, waitedBefore) });
522
+ }
523
+ /**
524
+ * Bring up a stream, fetching a credential first when that takes a tick.
525
+ *
526
+ * Split from `start` so the common cases -- a static token, an anonymous
527
+ * secret out of `sessionStorage`, or no credential at all -- still open the
528
+ * stream synchronously inside the `connect()` call. Only an async `token`
529
+ * getter defers, and `opening` is what stops a `reconnect()` arriving in that
530
+ * window from opening a second stream for one tab id.
531
+ */
532
+ function open() {
533
+ if (!live || opening)
534
+ return;
535
+ if (typeof options.token !== "function") {
536
+ start();
537
+ return;
538
+ }
539
+ opening = true;
540
+ void (async () => {
541
+ await refresh();
542
+ opening = false;
543
+ start();
544
+ })();
545
+ }
546
+ function start() {
547
+ if (!live)
548
+ return;
549
+ const es = new ES(streamUrl());
550
+ source = es;
551
+ es.addEventListener("open", () => {
552
+ // Every open, not just the first. `EventSource` reconnects by itself and
553
+ // the relay has forgotten the tab by then -- the registry entry dropped
554
+ // when the stream closed -- so a `hello` that were sent once would leave
555
+ // a tab that is connected and unidentifiable. This re-send is the
556
+ // reconnect handling; the rest is the browser's.
557
+ delay = backoffMs;
558
+ // Before `hello`, so a reconnect presents a live credential. `/dk/events`
559
+ // was authenticated with whatever we had a moment ago; the POST that
560
+ // follows is a separate request and may be the one the old token no
561
+ // longer covers. Awaiting here is not an option -- this is an
562
+ // `EventSource` listener -- so the refresh runs beside the `hello`, and
563
+ // the 401 path above is what catches the race on the rare occasion the
564
+ // old token was already dead.
565
+ if (typeof options.token === "function")
566
+ void refresh();
567
+ hello();
568
+ // After `hello()`, never before. A 409 retry waiting here resumes on the
569
+ // next microtask and must find the `hello` already at the head of the
570
+ // outbox, or it goes out first and 409s again.
571
+ const waiting = openWaiters;
572
+ openWaiters = [];
573
+ for (const waiter of waiting)
574
+ waiter();
575
+ });
576
+ es.addEventListener("call", (event) => {
577
+ try {
578
+ const frame = JSON.parse(String(event.data));
579
+ if (frame?.t !== "call" || typeof frame.id !== "string")
580
+ throw new Error("not a call frame");
581
+ void onCall(frame);
582
+ }
583
+ catch (err) {
584
+ // Dropped, not crashed. A frame this page cannot parse is a relay from
585
+ // a newer version of the protocol, and taking the stream down over it
586
+ // would turn a forward-compatible addition into an outage.
587
+ onError(err);
588
+ }
589
+ });
590
+ es.addEventListener("error", () => {
591
+ // `error` fires on every blip, including the ones `EventSource` is about
592
+ // to retry by itself. Only a CLOSED stream is ours to restart; racing the
593
+ // browser's own retry would open two streams for one tab.
594
+ if (!live || es.readyState !== CLOSED)
595
+ return;
596
+ if (source === es)
597
+ source = null;
598
+ if (reopen)
599
+ return;
600
+ reopen = setTimeout(() => {
601
+ reopen = null;
602
+ open();
603
+ }, delay);
604
+ reopen.unref?.();
605
+ delay = Math.min(delay * 2, maxBackoffMs);
606
+ });
607
+ }
608
+ function changed() {
609
+ if (!live)
610
+ return;
611
+ if (debounce)
612
+ return; // Already coalescing; the flush reads the latest state.
613
+ debounce = setTimeout(() => {
614
+ debounce = null;
615
+ if (!live)
616
+ return;
617
+ // Read at flush time, not at call time. Ten `changed()` calls in one
618
+ // frame must produce one push of the FINAL state, not the first.
619
+ //
620
+ // The url and the focus ride along, and that is the cheap half of two
621
+ // fixes. `TabInfo.url` came from `hello` ALONE, so it was stale the
622
+ // moment the tab navigated -- and a single-page app navigates without
623
+ // reconnecting, so `hello` may never come again. A push is already going
624
+ // out whenever the page moves; carrying the current url on it costs one
625
+ // short string and makes the listing true. `focus` is the same shape of
626
+ // saving: the frame it needs was already there.
627
+ pushedFocus = focusNow().focus;
628
+ up({ t: "snapshot", snapshot: driver.snapshot(), tab, ...whereNow(), ...focusNow() });
629
+ }, debounceMs);
630
+ debounce.unref?.();
631
+ }
632
+ /**
633
+ * Watch the three events that move the focus state and push when it changes.
634
+ *
635
+ * ON A CHANGE AND NOT ON AN EVENT. `focus` fires on a window that was
636
+ * already focused, `visibilitychange` fires on its way to a state it was
637
+ * already in, and a person alt-tabbing between two applications would
638
+ * otherwise generate a push per keystroke -- each of which the relay
639
+ * force-forwards to every watcher, because a `snapshot` frame is the tab
640
+ * SAYING the page moved and the relay does not second-guess that. So the
641
+ * last pushed value is remembered and an event that does not move it is
642
+ * dropped here, before the debounce, where it costs nothing.
643
+ *
644
+ * It goes out through `changed()` rather than through its own frame, which is
645
+ * the decision worth naming: the protocol gains a field, not a frame. A tab
646
+ * that has focus news has a snapshot to send with it, the debounce
647
+ * coalesces the two, and a relay or a client written before this reads the
648
+ * same `snapshot` frame it always read and ignores one field.
649
+ */
650
+ // Gated on the page actually REPORTING a focus state, not merely on there
651
+ // being somewhere to listen. `globalThis` has an `addEventListener` in Node
652
+ // too, so without this every `connect()` in a test suite -- and in a server
653
+ // -- would register three listeners that can never fire.
654
+ if (wantsFocus && focusOf(page) !== undefined && (page?.addEventListener || focusEvents)) {
655
+ pushedFocus = focusOf(page);
656
+ const onFocusEvent = () => {
657
+ if (!live)
658
+ return;
659
+ if (focusOf(page) === pushedFocus)
660
+ return;
661
+ changed();
662
+ };
663
+ // `visibilitychange` is the document's; `focus` and `blur` are the
664
+ // window's and do not bubble to it. See `FocusEventsLike`.
665
+ page?.addEventListener?.("visibilitychange", onFocusEvent);
666
+ focusEvents?.addEventListener("focus", onFocusEvent);
667
+ focusEvents?.addEventListener("blur", onFocusEvent);
668
+ stopFocus = () => {
669
+ page?.removeEventListener?.("visibilitychange", onFocusEvent);
670
+ focusEvents?.removeEventListener?.("focus", onFocusEvent);
671
+ focusEvents?.removeEventListener?.("blur", onFocusEvent);
672
+ };
673
+ }
674
+ if (options.watchMs !== undefined) {
675
+ const every = Math.max(500, options.watchMs);
676
+ let seen = driver.snapshot().rev;
677
+ watch = setInterval(() => {
678
+ if (!live)
679
+ return;
680
+ try {
681
+ const rev = driver.snapshot().rev;
682
+ if (rev === seen)
683
+ return;
684
+ seen = rev;
685
+ changed();
686
+ }
687
+ catch (err) {
688
+ onError(err);
689
+ }
690
+ }, every);
691
+ watch.unref?.();
692
+ }
693
+ open();
694
+ return {
695
+ tab,
696
+ changed,
697
+ disconnect() {
698
+ live = false;
699
+ // Dropped rather than flushed. `disconnect` is the page saying it is done
700
+ // driving; POSTing answers to a relay nobody is listening to would be
701
+ // writing into the void, and a `drain` still awaiting a reconnect has to
702
+ // be let go or it holds a timer open past the teardown.
703
+ outbox.length = 0;
704
+ const waiting = openWaiters;
705
+ openWaiters = [];
706
+ for (const waiter of waiting)
707
+ waiter();
708
+ if (debounce)
709
+ clearTimeout(debounce);
710
+ if (reopen)
711
+ clearTimeout(reopen);
712
+ if (watch)
713
+ clearInterval(watch);
714
+ debounce = reopen = null;
715
+ watch = null;
716
+ // Removed, not left. These are on `document` and on the window, both of
717
+ // which outlive this connection, so a page that connects and disconnects
718
+ // -- a client-side route change, a React effect re-running -- would
719
+ // otherwise accumulate one set per connection and push through a closure
720
+ // whose stream is gone.
721
+ try {
722
+ stopFocus?.();
723
+ }
724
+ catch (err) {
725
+ onError(err);
726
+ }
727
+ stopFocus = null;
728
+ try {
729
+ source?.close();
730
+ }
731
+ catch (err) {
732
+ onError(err);
733
+ }
734
+ source = null;
735
+ },
736
+ };
737
+ }
738
+ /**
739
+ * Refuse to publish a driver that has not said what its verbs do.
740
+ *
741
+ * THE GAP THIS CLOSES. The core's gate fires on `kind === "commit"`, and the
742
+ * publish check below counts only DECLARED commits. So a verb with no `kind`
743
+ * that changes data went out to an outside agent with no gate in front of it
744
+ * and nobody complaining — the whole guarantee resting on the app having
745
+ * declared its kinds, which is the one thing nothing checked.
746
+ *
747
+ * WHY HERE AND NOT IN `mount()`. In-page leniency is deliberate and
748
+ * documented: `Verb.kind` is optional, an absent one makes no safety claim in
749
+ * either direction, and a half-written app with three undeclared verbs must
750
+ * still mount and still work. Nothing is published by mounting. Publishing to
751
+ * a relay is the act that hands an agent in another process the ability to
752
+ * change data, and it is already the place this library demands an explicit
753
+ * declaration rather than inferring one. So the demand is the same demand, one
754
+ * field over: say what your verbs do before strangers can call them.
755
+ *
756
+ * THE RULE: every verb in a published manifest declares a `kind`, unless the
757
+ * driver declared `approve: "unattended"`.
758
+ *
759
+ * Total, rather than the narrower rules that were available:
760
+ *
761
+ * "Only verbs that look like they change data." There is no such predicate.
762
+ * It would have to be a guess from the name — `delete-*`, `set-*` — which is
763
+ * the exact inference the controls layer refuses to make, for the exact
764
+ * reason: a near miss is how `set-view` gets gated and `finalize` does not.
765
+ * A rule that is wrong in both directions teaches an author to distrust it.
766
+ *
767
+ * "Only when no approver was declared at all." This is the tempting one and
768
+ * it is unsound. A declared hook does NOT cover an undeclared verb: the core
769
+ * asks only about `kind === "commit"`, so a driver with a perfectly good
770
+ * approval hook and one silent verb publishes that verb ungated. The narrow
771
+ * rule would accept precisely the configuration that is unsafe. Which is
772
+ * also why a `hook` policy does not satisfy this check.
773
+ *
774
+ * "Warn instead of throw." A warning on publish is a warning the author of
775
+ * the app is not reading, because the app works. The precedent in PROTOCOL.md
776
+ * is a refusal to start, and that is what a configuration which must not be
777
+ * reachable by accident looks like.
778
+ *
779
+ * WHY `"unattended"` SATISFIES IT. Because it is the same claim, said louder.
780
+ * A driver declaring `"unattended"` runs its declared commits with nobody in
781
+ * front of them; a silent verb on that driver is treated no differently from a
782
+ * verb that declared `commit`, so there is nothing left for this check to
783
+ * protect. Refusing it anyway would be demanding paperwork after the risk has
784
+ * already been accepted out loud — and it would leave an author who really does
785
+ * run unattended with no way to connect at all, which is how a safety check
786
+ * gets deleted rather than satisfied. `"unattended"` is the typed opt-out the
787
+ * core already defines for this exact decision; this reuses it rather than
788
+ * inventing a second one.
789
+ */
790
+ /**
791
+ * What the APP said at `mount()`, which is the only thing either check below
792
+ * accepts as a declaration.
793
+ *
794
+ * Not `policy`, which is who is asked right now and can be `adopted` — a
795
+ * dialog installed in the page after mount, by `mountWidget` in the ordinary
796
+ * case. That is a real gate while the panel is mounted and it is not a
797
+ * sentence anybody wrote in the app: it is gone when the panel unmounts, and
798
+ * it would make publishing a driver to the outside depend on whether a chat
799
+ * panel happened to be mounted first. The whole argument for these checks is
800
+ * three deliberate acts, so they read the declaration and nothing else.
801
+ *
802
+ * `declared` is absent on a hand-written `approval` from before it existed, and
803
+ * then `policy` IS the declaration — that driver has no `adopt` and nothing can
804
+ * have moved it. See `Driver.approval`.
805
+ */
806
+ function declaredPolicy(driver) {
807
+ return driver.approval?.declared ?? driver.approval?.policy ?? "none";
808
+ }
809
+ function requireDeclaredKinds(driver) {
810
+ if (declaredPolicy(driver) === "unattended")
811
+ return;
812
+ const manifest = driver.manifest();
813
+ const silent = manifest.verbs.filter((v) => v.kind === undefined).map((v) => v.name);
814
+ if (silent.length === 0)
815
+ return;
816
+ throw new Error(`driverkit: refusing to connect \`${manifest.app}\` to a relay. ` +
817
+ `${silent.length} of its ${manifest.verbs.length} verb(s) declare no \`kind\` — ` +
818
+ `${silent.slice(0, 6).join(", ")}${silent.length > 6 ? ", …" : ""} — so the core's ` +
819
+ `approval gate, which fires on \`kind: "commit"\`, cannot see them. A verb that changes ` +
820
+ `data and never said so is published to an agent in another process with nothing in ` +
821
+ `front of it. In-page this is allowed on purpose (an absent \`kind\` makes no claim); ` +
822
+ `publishing is where the claim has to be made. Pass ONE of these: ` +
823
+ `\`kind: "read" | "describe" | "commit"\` on each verb above — the honest answer, and it ` +
824
+ `is also what tells an agent which calls are free to try; or \`approve: "unattended"\` to ` +
825
+ `\`mount()\`, which says out loud that commits on this driver run with nobody watching ` +
826
+ `and takes every verb off this list. See Verb.kind and MountOptions.approve.`);
827
+ }
828
+ /**
829
+ * Refuse to publish a driver whose commits nobody has said who approves.
830
+ *
831
+ * THE GAP THIS CLOSES. The confirmation used to live in the agent loop's
832
+ * `onBeforeCommit`, which `mountWidget` defaults on, so the in-page panel
833
+ * asked a person and an agent arriving over this stream called
834
+ * `accept-selected` and it simply ran. A live tab was driven from a shell and
835
+ * 425 rows could have been committed with nothing in the way. The gate now
836
+ * lives in `mount()`'s `call`, where both paths converge — but a gate the app
837
+ * never installed is still no gate, so the declaration is required HERE, at
838
+ * the one act that makes the app reachable from outside the page.
839
+ *
840
+ * WHY A THROW. The precedent is PROTOCOL.md's: a relay with remote access
841
+ * turned on and no way to identify callers **refuses to start** rather than
842
+ * serving every connected tab to anyone who asks. Three deliberate acts to
843
+ * publish a relay, and by the same argument three to let an outside agent
844
+ * change data: write a `commit` verb, connect to a relay, and say who
845
+ * approves. The unsafe answer is still available — `approve: "unattended"` —
846
+ * and it is now a sentence somebody wrote rather than a field they left out.
847
+ *
848
+ * WHICH VERBS COUNT. Only a `commit` that has not declared `reversible`, which
849
+ * is the same line the widget's dialog draws and for the same reason: an
850
+ * absent `reversible` makes no claim, and a commit that has not said there is
851
+ * a way back is treated as one that has not got one. An app whose every commit
852
+ * declares `reversible` connects exactly as it did before. So does an app with
853
+ * no commit verbs at all, and so does a hand-written driver that declares
854
+ * `approval` itself.
855
+ *
856
+ * AND WHY A PANEL CANNOT SATISFY IT. `mountWidget` installs its dialog as the
857
+ * core's approver (`DriverApproval.adopt`), which makes the driver's live
858
+ * `policy` read `adopted` — a real gate, asked on this stream's calls too. It
859
+ * still does not satisfy this check, and that is deliberate twice over. It is
860
+ * not a declaration: it exists only while that panel is mounted, so a
861
+ * `connect()` that accepted it would publish commits that become ungated when
862
+ * somebody closes the assistant. And it would be ORDER-DEPENDENT — the same
863
+ * app starting or throwing according to whether `connect()` ran before or
864
+ * after `mountWidget` — which is the worst property a startup check can have.
865
+ * So an app that mounts the panel and connects to a relay declares the gate
866
+ * itself, and the documented wiring makes the panel that gate:
867
+ * `approve: (req) => panel.approve(req)`.
868
+ */
869
+ function requireApprovalPolicy(driver) {
870
+ if (declaredPolicy(driver) !== "none")
871
+ return;
872
+ const exposed = driver
873
+ .manifest()
874
+ .verbs.filter((v) => v.kind === "commit" && v.reversible !== true)
875
+ .map((v) => v.name);
876
+ if (exposed.length === 0)
877
+ return;
878
+ throw new Error(`driverkit: refusing to connect \`${driver.manifest().app}\` to a relay. It publishes ` +
879
+ `${exposed.length} commit verb(s) that have not declared \`reversible\` — ` +
880
+ `${exposed.slice(0, 6).join(", ")}${exposed.length > 6 ? ", …" : ""} — and \`mount()\` was ` +
881
+ `given no \`approve\`, so an agent on the other end of this stream would change data with ` +
882
+ `nothing in front of it. Pass ONE of these to \`mount()\`: ` +
883
+ `\`approve: (req) => …\`, an async hook that asks a person and returns true, false or a ` +
884
+ `reason; or \`approve: "unattended"\`, which says out loud that commits here run with ` +
885
+ `nobody watching. Declaring \`reversible: true\` on the commits the app really can undo ` +
886
+ `also takes them off this list. See MountOptions.approve.`);
887
+ }
888
+ /**
889
+ * The remembered tab id, or a fresh one.
890
+ *
891
+ * `sessionStorage`, not `localStorage`: the id names one open tab, and
892
+ * `localStorage` is shared across every tab on the origin, so two windows
893
+ * would claim one identity and the second `hello` would steal the first's
894
+ * stream. Keyed by app so two drivers in one page do not collide.
895
+ */
896
+ function remembered(storage, app, randomUUID, onError) {
897
+ const key = `driverkit:tab:${app ?? "-"}`;
898
+ try {
899
+ const found = storage?.getItem(key);
900
+ if (found)
901
+ return found;
902
+ }
903
+ catch (err) {
904
+ onError(err); // Private-mode storage throws on access rather than returning null.
905
+ }
906
+ const mint = randomUUID ??
907
+ (globalThis.crypto?.randomUUID ? () => globalThis.crypto.randomUUID() : null) ??
908
+ // A tab id is a capability, so the fallback still has to be unguessable;
909
+ // it is only here for an insecure origin, where `crypto` is absent.
910
+ (() => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`);
911
+ const id = mint();
912
+ try {
913
+ storage?.setItem(key, id);
914
+ }
915
+ catch (err) {
916
+ onError(err);
917
+ }
918
+ return id;
919
+ }
920
+ /**
921
+ * The remembered anonymous credential, or a fresh one.
922
+ *
923
+ * `sessionStorage`, like the tab id, and for the same reason plus one more: an
924
+ * anonymous session should not outlive the window, and `localStorage` would
925
+ * make one anonymous principal shared by every tab on the origin -- which is
926
+ * the single shared "anonymous" bucket this whole design exists to avoid.
927
+ *
928
+ * 256 bits from `crypto.getRandomValues`, because this string is the whole of
929
+ * an anonymous visitor's isolation: anybody who can guess it is that visitor.
930
+ * The fallback for an insecure origin with no `crypto` is deliberately loud
931
+ * rather than silent -- a guessable anonymous secret is worse than none, so a
932
+ * page served over plain HTTP is told rather than quietly weakened.
933
+ */
934
+ function anonCredential(storage, app, onError) {
935
+ const key = `${ANON_KEY}:${app ?? "-"}`;
936
+ try {
937
+ const found = storage?.getItem(key);
938
+ if (found)
939
+ return found;
940
+ }
941
+ catch (err) {
942
+ onError(err); // Private-mode storage throws on access rather than returning null.
943
+ }
944
+ const random = globalThis.crypto?.getRandomValues;
945
+ if (!random) {
946
+ throw new Error("driverkit: anonymous credentials need `crypto.getRandomValues`, which this origin " +
947
+ "does not have (an insecure origin, most likely). A guessable anonymous secret is " +
948
+ "one anonymous visitor able to drive another's screen, so this refuses rather than " +
949
+ "falling back to Math.random. Serve the page over HTTPS, or pass `token`.");
950
+ }
951
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
952
+ let base64 = "";
953
+ for (const byte of bytes)
954
+ base64 += String.fromCharCode(byte);
955
+ // base64url, unpadded, matching the relay's `anon1.` reader on both sides.
956
+ const secret = btoa(base64).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
957
+ const credential = `anon1.${secret}`;
958
+ try {
959
+ storage?.setItem(key, credential);
960
+ }
961
+ catch (err) {
962
+ onError(err);
963
+ }
964
+ return credential;
965
+ }
966
+ function titleFromPage(page) {
967
+ const title = page?.title;
968
+ return title ? { title } : {};
969
+ }
970
+ /**
971
+ * The url, path and query AND HASH.
972
+ *
973
+ * THE HASH USED TO BE DROPPED, and for a hash-routed app the hash is the
974
+ * entire route: every tab of such an app reported the same `/` in `/dk/tabs`,
975
+ * so the one field a person is shown to tell two tabs apart told them nothing.
976
+ * It was dropped to keep a fragment out of a listing, which is a real concern
977
+ * about the wrong field -- the token is the capability here, and it travels in
978
+ * a header or a query parameter, never in `location`.
979
+ *
980
+ * Still path-relative and never the origin, which is the part that was right:
981
+ * the relay knows the origin, and a full url in a listing is an inventory of
982
+ * where somebody has been.
983
+ */
984
+ export function urlFromPage(place) {
985
+ if (!place?.pathname)
986
+ return {};
987
+ return { url: `${place.pathname}${place.search ?? ""}${place.hash ?? ""}` };
988
+ }
989
+ /**
990
+ * The three focus states, from the two things a document can be asked.
991
+ *
992
+ * ```
993
+ * visibilityState hasFocus() answer
994
+ * "hidden" anything "hidden" a background tab
995
+ * "visible" true "focused" the person is looking at this
996
+ * "visible" false "visible" active tab, window not frontmost
997
+ * "visible" absent "visible" an engine with no hasFocus:
998
+ * the strongest honest answer
999
+ * absent absent undefined not a page; say nothing
1000
+ * ```
1001
+ *
1002
+ * `undefined` rather than a guess in the last row, and `TabFocus` says why it
1003
+ * must stay distinguishable from `"hidden"`: a client that read "I cannot
1004
+ * tell" as "not that one" would quietly become unable to drive a tab whose
1005
+ * page does not report.
1006
+ *
1007
+ * `hasFocus()` is called in a `try`, because this runs on a timer in a page
1008
+ * that may be mid-teardown and a throwing getter must not take the push with
1009
+ * it. A throw is read as "cannot tell", never as focused.
1010
+ */
1011
+ export function focusOf(page) {
1012
+ if (!page)
1013
+ return undefined;
1014
+ const visibility = page.visibilityState;
1015
+ const asks = typeof page.hasFocus === "function";
1016
+ if (visibility === undefined && !asks)
1017
+ return undefined;
1018
+ // Anything that is not the string `"visible"` is treated as hidden. The spec
1019
+ // has two values and has had others ("prerender", "unloaded"); none of them
1020
+ // is a tab a person is looking at, and a new one must not read as focused.
1021
+ if (visibility !== undefined && visibility !== "visible")
1022
+ return "hidden";
1023
+ if (!asks)
1024
+ return "visible";
1025
+ let focused;
1026
+ try {
1027
+ focused = page.hasFocus();
1028
+ }
1029
+ catch {
1030
+ focused = undefined;
1031
+ }
1032
+ if (focused === true)
1033
+ return "focused";
1034
+ if (focused === false)
1035
+ return "visible";
1036
+ return visibility === "visible" ? "visible" : undefined;
1037
+ }
1038
+ //# sourceMappingURL=connect.js.map