@mostra/runtime 0.0.0-stage → 0.2.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 (115) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +39 -2
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +236 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/builder/child/main.d.ts +1 -0
  7. package/dist/builder/child/main.js +1408 -0
  8. package/dist/builder/child/main.js.map +1 -0
  9. package/dist/child-xrHmytks.js +49 -0
  10. package/dist/child-xrHmytks.js.map +1 -0
  11. package/dist/deps/child/install.d.ts +1 -0
  12. package/dist/deps/child/install.js +33 -0
  13. package/dist/deps/child/install.js.map +1 -0
  14. package/dist/index.d.ts +221 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +3 -0
  17. package/dist/instance-CzBkUyHu.js +15920 -0
  18. package/dist/instance-CzBkUyHu.js.map +1 -0
  19. package/dist/types-NjNy7gXX.js +57 -0
  20. package/dist/types-NjNy7gXX.js.map +1 -0
  21. package/package.json +87 -3
  22. package/src/actions/index.ts +622 -0
  23. package/src/addressing/index.ts +281 -0
  24. package/src/bin.ts +240 -0
  25. package/src/builder/child/dev.ts +383 -0
  26. package/src/builder/child/fields.ts +363 -0
  27. package/src/builder/child/main.ts +47 -0
  28. package/src/builder/child/plugins.ts +195 -0
  29. package/src/builder/child/scan.ts +459 -0
  30. package/src/builder/child/spa.ts +348 -0
  31. package/src/builder/coverage.ts +72 -0
  32. package/src/builder/index.ts +406 -0
  33. package/src/builder/types.ts +180 -0
  34. package/src/deps/child/install.ts +30 -0
  35. package/src/deps/index.ts +918 -0
  36. package/src/deps/installer.ts +321 -0
  37. package/src/deps/lock.ts +82 -0
  38. package/src/deps/scan.ts +266 -0
  39. package/src/deps/specifier.ts +64 -0
  40. package/src/deps/warm.ts +57 -0
  41. package/src/dev/index.ts +518 -0
  42. package/src/faults.ts +65 -0
  43. package/src/gate.ts +55 -0
  44. package/src/gateway/actions.ts +268 -0
  45. package/src/gateway/browser.ts +650 -0
  46. package/src/gateway/capabilities.ts +760 -0
  47. package/src/gateway/controls.ts +91 -0
  48. package/src/gateway/dev.ts +119 -0
  49. package/src/gateway/http.ts +229 -0
  50. package/src/gateway/identity.ts +101 -0
  51. package/src/gateway/index.ts +1299 -0
  52. package/src/gateway/integrity.ts +117 -0
  53. package/src/gateway/listener.ts +217 -0
  54. package/src/gateway/routes.ts +197 -0
  55. package/src/gateway/serve.ts +138 -0
  56. package/src/gc/index.ts +451 -0
  57. package/src/home/acquire.ts +276 -0
  58. package/src/home/index.ts +16 -0
  59. package/src/home/paths.ts +192 -0
  60. package/src/home/platform.ts +34 -0
  61. package/src/home/record.ts +76 -0
  62. package/src/home/settings.ts +113 -0
  63. package/src/index.ts +30 -0
  64. package/src/instance/index.ts +979 -0
  65. package/src/interaction/ephemeral.ts +300 -0
  66. package/src/interaction/events.ts +355 -0
  67. package/src/interaction/fields.ts +392 -0
  68. package/src/interaction/index.ts +1013 -0
  69. package/src/interaction/outbox.ts +493 -0
  70. package/src/interaction/policy.ts +26 -0
  71. package/src/interaction/results.ts +341 -0
  72. package/src/interaction/runs.ts +313 -0
  73. package/src/interaction/signals.ts +120 -0
  74. package/src/interaction/submissions.ts +585 -0
  75. package/src/interaction/subscriptions.ts +258 -0
  76. package/src/interaction/viewers.ts +187 -0
  77. package/src/interaction/wait.ts +201 -0
  78. package/src/ledger/index.ts +442 -0
  79. package/src/ledger/migrations.ts +596 -0
  80. package/src/ledger/requests.ts +105 -0
  81. package/src/ledger/types.ts +28 -0
  82. package/src/live/index.ts +573 -0
  83. package/src/log.ts +316 -0
  84. package/src/processes/child.ts +67 -0
  85. package/src/processes/environment.ts +64 -0
  86. package/src/processes/identity.ts +191 -0
  87. package/src/processes/index.ts +19 -0
  88. package/src/processes/manager.ts +543 -0
  89. package/src/protocol-server/client.ts +94 -0
  90. package/src/protocol-server/index.ts +91 -0
  91. package/src/protocol-server/server.ts +518 -0
  92. package/src/protocol-server/streams.ts +81 -0
  93. package/src/publish/checks.ts +92 -0
  94. package/src/publish/digest.ts +87 -0
  95. package/src/publish/index.ts +23 -0
  96. package/src/publish/manifest.ts +409 -0
  97. package/src/publish/methods.ts +96 -0
  98. package/src/publish/publisher.ts +913 -0
  99. package/src/publish/source.ts +272 -0
  100. package/src/publish/tar.ts +110 -0
  101. package/src/registry/index.ts +481 -0
  102. package/src/registry/store.ts +136 -0
  103. package/src/secrets/index.ts +223 -0
  104. package/src/service/idle.ts +64 -0
  105. package/src/service/index.ts +3 -0
  106. package/src/service/unit.ts +250 -0
  107. package/src/verify/fields.ts +125 -0
  108. package/src/verify/index.ts +913 -0
  109. package/src/verify/regression.ts +157 -0
  110. package/src/verify/runner.ts +230 -0
  111. package/src/verify/sandbox.ts +407 -0
  112. package/src/verify/typecheck.ts +371 -0
  113. package/src/workers/index.ts +17 -0
  114. package/src/workers/launcher.ts +260 -0
  115. package/src/workers/pool.ts +708 -0
@@ -0,0 +1,650 @@
1
+ /**
2
+ * The browser protocol's interaction routes (INTERFACES §4, D106): `fields`, `submit`, `signal`,
3
+ * `events` (SSE) and `events/poll` on an artifact's origin. They run behind the route table's
4
+ * checks (session, CSRF, scope; `routes.ts`), act as the session's viewer (D104), and hand every
5
+ * change to the interaction core, so a page and a host go through one path.
6
+ */
7
+ import {
8
+ BROWSER_PROTOCOL_REVISIONS,
9
+ ChooseRequest,
10
+ type Diagnostic,
11
+ type EphemeralMessage,
12
+ type EventRecord,
13
+ FieldsRequest,
14
+ FollowRequest,
15
+ RpcError,
16
+ refusal,
17
+ ShellSubmitRequest,
18
+ SignalRequest,
19
+ type StreamSnapshot,
20
+ type SubmissionSummary,
21
+ SubmitRequest,
22
+ ViewId,
23
+ } from "@mostra/protocol";
24
+ import type * as z from "zod";
25
+ import {
26
+ type EphemeralBus,
27
+ type Interaction,
28
+ type PageIdentity,
29
+ SubmitConflict,
30
+ } from "../interaction/index.ts";
31
+ import type { Log } from "../log.ts";
32
+ import type { Capabilities } from "./capabilities.ts";
33
+ import { BASE_HEADERS, isRefusal, jsonResponse, readJsonObject } from "./http.ts";
34
+ import type { RouteContext } from "./routes.ts";
35
+
36
+ /** The largest `fields` body: a mutation may carry up to a whole document (DATA_MODEL §5). */
37
+ export const FIELDS_BODY_MAX: number = 17 * 1024 * 1024;
38
+
39
+ /** The largest `signal` body: a 64 KiB payload and its envelope. */
40
+ const SIGNAL_BODY_MAX: number = 80 * 1024;
41
+
42
+ /** How often an idle event stream sends a comment, so proxies and browsers keep it open. */
43
+ export const HEARTBEAT_MS = 15_000;
44
+
45
+ /** The longest a poll waits for an event (D47), in seconds. */
46
+ export const POLL_MAX_WAIT_S = 25;
47
+
48
+ /** Events per stream message batch. */
49
+ const BATCH = 100;
50
+
51
+ /** The HTTP status of each diagnostic a browser route answers. */
52
+ const STATUS: Readonly<Record<string, number>> = {
53
+ MOSTRA_HOST_INVALID_PARAMS: 400,
54
+ MOSTRA_FIELD_ID_INVALID: 400,
55
+ MOSTRA_SUBMIT_SIGNAL_INVALID: 400,
56
+ MOSTRA_FIELD_TOO_LARGE: 413,
57
+ MOSTRA_SUBMIT_VIEW_INVALID: 403,
58
+ MOSTRA_SUBMIT_ALREADY: 409,
59
+ MOSTRA_SUBMIT_REVISION_MOVED: 409,
60
+ MOSTRA_SUBMIT_POLICY_NONE: 409,
61
+ MOSTRA_SUBMIT_CHANNEL_DENIED: 403,
62
+ MOSTRA_FIELD_MUTATION_ID_REUSED: 409,
63
+ MOSTRA_HOST_CURSOR_COMPACTED: 410,
64
+ MOSTRA_HOME_DISK_FULL: 507,
65
+ MOSTRA_HOME_GONE: 503,
66
+ MOSTRA_HYGIENE_SCOPE_DENIED: 403,
67
+ };
68
+
69
+ /** Options for {@link browserRoutes}. */
70
+ export interface BrowserRoutesOptions {
71
+ readonly interaction: Interaction;
72
+ readonly capabilities: Capabilities;
73
+ readonly log: Log;
74
+ /**
75
+ * The browser-protocol revisions served, oldest first: every revision Mostra ever shipped
76
+ * (`BROWSER_PROTOCOL_REVISIONS`, VR-10), and in tests a newer one the release doesn't have yet.
77
+ */
78
+ readonly revisions?: readonly string[];
79
+ /** A version of an artifact by number, for the carry-over route. */
80
+ readonly versionOf: (
81
+ artifactId: string,
82
+ number: number,
83
+ ) => { readonly id: string; readonly number: number } | undefined;
84
+ /**
85
+ * Run and live updates for pages (WP-08): a stream sends them as `event: run` and `event: live`
86
+ * without an `id`, a poll as its `ephemeral` (LL-04). Absent: neither carries any.
87
+ */
88
+ readonly bus?: EphemeralBus;
89
+ /** Tells a host with a `trustedControls` port that a trusted control was used (D108). */
90
+ readonly activated: (event: {
91
+ readonly artifactId: string;
92
+ readonly control: "submit" | "choose";
93
+ readonly viewerId: string;
94
+ readonly viewId: string;
95
+ readonly detail: Readonly<Record<string, string>>;
96
+ }) => void;
97
+ }
98
+
99
+ /** A refusal or a diagnostic as the browser gets it. */
100
+ function answer(
101
+ diagnostic: Diagnostic,
102
+ status: number,
103
+ extra: Record<string, unknown> = {},
104
+ ): Response {
105
+ return jsonResponse({ ...diagnostic, ...extra }, { status });
106
+ }
107
+
108
+ function malformed(message: string): Response {
109
+ return answer(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", message).diagnostic, 400);
110
+ }
111
+
112
+ /** Turns an interaction refusal into its response; anything else is a defect for `onError`. */
113
+ function failure(error: unknown): Response {
114
+ if (error instanceof SubmitConflict) {
115
+ return answer(error.diagnostic, 409, { submission: error.submission });
116
+ }
117
+ if (error instanceof RpcError)
118
+ return answer(error.diagnostic, STATUS[error.diagnostic.code] ?? 500);
119
+ throw error;
120
+ }
121
+
122
+ /** The revision a route was called at, when this gateway serves it (FAILURE_MODEL §7). */
123
+ function revisionServed(context: RouteContext, revisions: readonly string[]): Response | undefined {
124
+ const rev = context.params["rev"];
125
+ if (rev !== undefined && revisions.includes(rev)) return undefined;
126
+ return answer(
127
+ refusal(
128
+ "MOSTRA_HYGIENE_NOT_SERVED",
129
+ `This gateway serves browser-protocol revisions ${revisions.join(", ")}, not ${String(rev)}.`,
130
+ 404,
131
+ ).diagnostic,
132
+ 404,
133
+ );
134
+ }
135
+
136
+ /** Reads and validates a JSON body against a schema. */
137
+ async function body<T>(
138
+ context: RouteContext,
139
+ schema: z.ZodType<T>,
140
+ maxBytes?: number,
141
+ ): Promise<T | Response> {
142
+ const raw = await readJsonObject(context.request, maxBytes);
143
+ if (isRefusal(raw)) return answer(raw.diagnostic, raw.status);
144
+ const parsed = schema.safeParse(raw);
145
+ if (parsed.success) return parsed.data;
146
+ const [issue] = parsed.error.issues;
147
+ return malformed(
148
+ `The request body doesn't match the browser protocol at ${issue?.path.join(".") || "(root)"}: ${issue?.message ?? "invalid"}.`,
149
+ );
150
+ }
151
+
152
+ /**
153
+ * The cursor a stream or poll resumes from: the newer of `?cursor=` and `Last-Event-ID`. An
154
+ * `EventSource` reconnects to the URL it opened, query included, and adds `Last-Event-ID` with
155
+ * the last event it received, which is never older; taking the newer never repeats an event
156
+ * (Claude review finding 3).
157
+ */
158
+ function cursorOf(request: Request): number | undefined | "invalid" {
159
+ const url = new URL(request.url);
160
+ let resume: number | undefined;
161
+ for (const value of [url.searchParams.get("cursor"), request.headers.get("last-event-id")]) {
162
+ if (value === null || value === "") continue;
163
+ if (!/^(0|[1-9][0-9]{0,15})$/.test(value)) return "invalid";
164
+ resume = Math.max(resume ?? 0, Number(value));
165
+ }
166
+ return resume;
167
+ }
168
+
169
+ /** A route handler. */
170
+ type Handler = (context: RouteContext) => Response | Promise<Response>;
171
+
172
+ /** The handlers of the browser protocol's interaction routes. */
173
+ export interface BrowserRoutes {
174
+ readonly fields: Handler;
175
+ readonly submit: Handler;
176
+ readonly signal: Handler;
177
+ readonly stream: Handler;
178
+ readonly poll: Handler;
179
+ /** The shell's trusted Submit (the `shell` channel, D40), on the shell origin. */
180
+ readonly shellSubmit: Handler;
181
+ /** The shell's trusted Choose (D65, D113), on the shell origin. */
182
+ readonly choose: Handler;
183
+ /** "Always follow this artifact" (D63), on the shell origin. */
184
+ readonly follow: Handler;
185
+ /** The viewer's answers a version doesn't carry over (D42, D109), on the shell origin. */
186
+ readonly carry: Handler;
187
+ }
188
+
189
+ /** The browser protocol's interaction routes' handlers. */
190
+ export function browserRoutes(options: BrowserRoutesOptions): BrowserRoutes {
191
+ const { interaction, capabilities, log } = options;
192
+ const served: readonly string[] = options.revisions ?? BROWSER_PROTOCOL_REVISIONS;
193
+ const knownRevision = (context: RouteContext): Response | undefined =>
194
+ revisionServed(context, served);
195
+
196
+ const pageOf = (context: RouteContext): PageIdentity => {
197
+ const session = context.session;
198
+ const artifactId = context.artifactId;
199
+ if (!session || artifactId === undefined) throw new Error("session route without a session");
200
+ return {
201
+ artifactId,
202
+ viewerId: interaction.viewerOf(session.viewerId),
203
+ // A page names only views its own link opened (Claude review finding 11).
204
+ tokenId: session.grant.tokenId,
205
+ scopes: session.grant.scopes,
206
+ };
207
+ };
208
+
209
+ /** The view a stream or poll is for, checked against the page (D104). */
210
+ const viewOf = (context: RouteContext, page: PageIdentity): Response | undefined => {
211
+ const view = new URL(context.request.url).searchParams.get("view");
212
+ if (view === null || !ViewId.is(view)) return malformed("The stream needs the page's `view`.");
213
+ try {
214
+ interaction.checkView(page, view);
215
+ } catch (error) {
216
+ return failure(error);
217
+ }
218
+ return undefined;
219
+ };
220
+
221
+ /** The page's view, from the query (checked by {@link viewOf} first). */
222
+ const viewIdOf = (context: RouteContext): string =>
223
+ new URL(context.request.url).searchParams.get("view") ?? "";
224
+
225
+ /** The most ephemeral messages a stream holds for a slow reader; older ones are dropped. */
226
+ const EPHEMERAL_HELD = 1000;
227
+
228
+ const fields = async (context: RouteContext): Promise<Response> => {
229
+ const refused = knownRevision(context);
230
+ if (refused) return refused;
231
+ const request = await body(context, FieldsRequest, FIELDS_BODY_MAX);
232
+ if (request instanceof Response) return request;
233
+ try {
234
+ return jsonResponse(
235
+ interaction.mutate(pageOf(context), {
236
+ viewId: request.viewId,
237
+ scope: request.scope,
238
+ mutationId: request.mutationId,
239
+ baseRevision: Number(request.baseRevision),
240
+ ops: request.ops,
241
+ }),
242
+ );
243
+ } catch (error) {
244
+ return failure(error);
245
+ }
246
+ };
247
+
248
+ const submit = async (context: RouteContext): Promise<Response> => {
249
+ const refused = knownRevision(context);
250
+ if (refused) return refused;
251
+ const request = await body(context, SubmitRequest);
252
+ if (request instanceof Response) return request;
253
+ try {
254
+ return jsonResponse(
255
+ interaction.submit(pageOf(context), {
256
+ viewId: request.viewId,
257
+ expectedRevision: Number(request.expectedRevision),
258
+ channel: "artifact",
259
+ }),
260
+ );
261
+ } catch (error) {
262
+ return failure(error);
263
+ }
264
+ };
265
+
266
+ const signal = async (context: RouteContext): Promise<Response> => {
267
+ const refused = knownRevision(context);
268
+ if (refused) return refused;
269
+ const request = await body(context, SignalRequest, SIGNAL_BODY_MAX);
270
+ if (request instanceof Response) return request;
271
+ try {
272
+ const cursor = interaction.signal(pageOf(context), {
273
+ viewId: request.viewId,
274
+ name: request.name,
275
+ ...(request.payload !== undefined ? { payload: request.payload } : {}),
276
+ });
277
+ return jsonResponse({ cursor });
278
+ } catch (error) {
279
+ return failure(error);
280
+ }
281
+ };
282
+
283
+ /** Whether the session's link still works; a revoked link ends its streams. */
284
+ const live = (context: RouteContext): boolean => {
285
+ const tokenId = context.session?.grant.tokenId;
286
+ return tokenId !== undefined && capabilities.grant(tokenId)?.live === true;
287
+ };
288
+
289
+ /** The page's events after a cursor; a compacted cursor gets a fresh snapshot instead. */
290
+ const next = (
291
+ page: PageIdentity,
292
+ after: number,
293
+ ): { events: EventRecord[]; cursor: number } | { snapshot: StreamSnapshot } => {
294
+ try {
295
+ const read = interaction.pageEvents(page, after, BATCH);
296
+ return { events: read.events, cursor: Number(read.cursor) };
297
+ } catch (error) {
298
+ if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_HOST_CURSOR_COMPACTED") {
299
+ return { snapshot: interaction.pageSnapshot(page) };
300
+ }
301
+ throw error;
302
+ }
303
+ };
304
+
305
+ const stream = (context: RouteContext): Response => {
306
+ const refused = knownRevision(context);
307
+ if (refused) return refused;
308
+ const page = pageOf(context);
309
+ const badView = viewOf(context, page);
310
+ if (badView) return badView;
311
+ const resume = cursorOf(context.request);
312
+ if (resume === "invalid") return malformed("`cursor` must be an event cursor.");
313
+ const encoder = new TextEncoder();
314
+ // Pull-based: a page of events is read only when the client took the last one, so a slow
315
+ // reader or a long backlog never makes the gateway buffer more than a page, and every page
316
+ // yields to the event loop (Claude review finding 6).
317
+ let cursor = resume ?? -1;
318
+ let open = true;
319
+ let dirty = false;
320
+ let wake: (() => void) | undefined;
321
+ const unsubscribe = interaction.onCommit(() => {
322
+ dirty = true;
323
+ wake?.();
324
+ });
325
+ // Run and live updates for this view: lossy by design (a page reads what it missed), so a
326
+ // slow reader drops the oldest rather than making the gateway hold more.
327
+ // Held as messages and coalesced while the reader is behind (Opus review 12): a newer live
328
+ // value replaces an older one of its source, and a run's deltas merge.
329
+ const held: EphemeralMessage[] = [];
330
+ const heldText = (): string =>
331
+ held
332
+ .splice(0)
333
+ .map(
334
+ (message) =>
335
+ `event: ${message.kind}\ndata: ${JSON.stringify(message.kind === "run" ? message.run : message.live)}\n\n`,
336
+ )
337
+ .join("");
338
+ const unlisten =
339
+ options.bus?.listen(page.artifactId, viewIdOf(context), (message) => {
340
+ options.bus?.coalesce(page.artifactId, viewIdOf(context), held, message);
341
+ if (held.length > EPHEMERAL_HELD) held.splice(0, held.length - EPHEMERAL_HELD);
342
+ wake?.();
343
+ }) ?? (() => {});
344
+ const close = (controller?: ReadableStreamDefaultController<Uint8Array>): void => {
345
+ if (!open) return;
346
+ open = false;
347
+ unsubscribe();
348
+ unlisten();
349
+ wake?.();
350
+ context.request.signal.removeEventListener("abort", aborted);
351
+ try {
352
+ controller?.close();
353
+ } catch {
354
+ // Already closed by the client.
355
+ }
356
+ };
357
+ const aborted = (): void => close();
358
+ context.request.signal.addEventListener("abort", aborted, { once: true });
359
+ const snapshotText = (value: StreamSnapshot): string => {
360
+ cursor = Number(value.cursor);
361
+ return `id: ${value.cursor}\nevent: snapshot\ndata: ${JSON.stringify(value)}\n\n`;
362
+ };
363
+ const body = new ReadableStream<Uint8Array>(
364
+ {
365
+ start(controller) {
366
+ let text = "retry: 2000\n\n";
367
+ if (resume === undefined) text += snapshotText(interaction.pageSnapshot(page));
368
+ controller.enqueue(encoder.encode(text));
369
+ },
370
+ async pull(controller) {
371
+ await new Promise((resolve) => setImmediate(resolve));
372
+ for (;;) {
373
+ if (!open) return;
374
+ if (!live(context)) {
375
+ close(controller);
376
+ return;
377
+ }
378
+ dirty = false;
379
+ let read: ReturnType<typeof next>;
380
+ try {
381
+ read = next(page, cursor);
382
+ } catch (error) {
383
+ log.error("gateway.stream_failed", { error });
384
+ close(controller);
385
+ return;
386
+ }
387
+ if ("snapshot" in read) {
388
+ controller.enqueue(encoder.encode(snapshotText(read.snapshot)));
389
+ return;
390
+ }
391
+ cursor = read.cursor;
392
+ const ephemeral = heldText();
393
+ if (read.events.length > 0 || ephemeral !== "") {
394
+ controller.enqueue(
395
+ encoder.encode(
396
+ read.events
397
+ .map(
398
+ (event) =>
399
+ `id: ${event.cursor}\nevent: mostra\ndata: ${JSON.stringify(event)}\n\n`,
400
+ )
401
+ .join("") + ephemeral,
402
+ ),
403
+ );
404
+ return;
405
+ }
406
+ // Nothing new: wait for a commit or an update, or send a heartbeat after a while.
407
+ if (dirty || held.length > 0) continue;
408
+ const woke = await new Promise<"commit" | "heartbeat">((resolve) => {
409
+ const timer = setTimeout(() => resolve("heartbeat"), HEARTBEAT_MS);
410
+ timer.unref?.();
411
+ wake = () => {
412
+ clearTimeout(timer);
413
+ resolve("commit");
414
+ };
415
+ if (held.length > 0) wake();
416
+ });
417
+ wake = undefined;
418
+ if (woke === "heartbeat" && open) {
419
+ controller.enqueue(encoder.encode(": keepalive\n\n"));
420
+ return;
421
+ }
422
+ }
423
+ },
424
+ cancel() {
425
+ close();
426
+ },
427
+ },
428
+ new CountQueuingStrategy({ highWaterMark: 1 }),
429
+ );
430
+ return new Response(body, {
431
+ headers: {
432
+ ...BASE_HEADERS,
433
+ "content-type": "text/event-stream; charset=utf-8",
434
+ "cache-control": "no-store",
435
+ "x-accel-buffering": "no",
436
+ },
437
+ });
438
+ };
439
+
440
+ const poll = async (context: RouteContext): Promise<Response> => {
441
+ const refused = knownRevision(context);
442
+ if (refused) return refused;
443
+ const page = pageOf(context);
444
+ const badView = viewOf(context, page);
445
+ if (badView) return badView;
446
+ const resume = cursorOf(context.request);
447
+ if (resume === "invalid") return malformed("`cursor` must be an event cursor.");
448
+ const waitParam = new URL(context.request.url).searchParams.get("wait");
449
+ const waitS = waitParam === null ? POLL_MAX_WAIT_S : Number(waitParam);
450
+ if (!Number.isInteger(waitS) || waitS < 0 || waitS > POLL_MAX_WAIT_S) {
451
+ return malformed(`\`wait\` must be a whole number of seconds from 0 to ${POLL_MAX_WAIT_S}.`);
452
+ }
453
+ const viewId = viewIdOf(context);
454
+ const bus = options.bus;
455
+ // Polling views collect their run and live updates between polls (LL-04).
456
+ // Taking what is queued also starts the queue, so updates during the wait are kept.
457
+ let early = bus?.drain(page.artifactId, viewId) ?? [];
458
+ const withEphemeral = <T extends object>(value: T): T & { ephemeral?: unknown[] } => {
459
+ const ephemeral = [...early, ...(bus?.drain(page.artifactId, viewId) ?? [])];
460
+ early = [];
461
+ return ephemeral.length > 0 ? { ...value, ephemeral } : value;
462
+ };
463
+ if (resume === undefined) {
464
+ const snapshot = interaction.pageSnapshot(page);
465
+ return jsonResponse(withEphemeral({ cursor: snapshot.cursor, events: [], snapshot }));
466
+ }
467
+ const revoked = (): Response =>
468
+ answer(
469
+ refusal(
470
+ "MOSTRA_HYGIENE_TOKEN_REVOKED",
471
+ "The link this page came from was revoked or has expired.",
472
+ 410,
473
+ ).diagnostic,
474
+ 410,
475
+ );
476
+ const once = () => {
477
+ const read = next(page, resume);
478
+ return "snapshot" in read
479
+ ? { cursor: read.snapshot.cursor, events: [], snapshot: read.snapshot }
480
+ : { cursor: String(read.cursor), events: read.events };
481
+ };
482
+ try {
483
+ const first = once();
484
+ if (first.events.length > 0 || "snapshot" in first || waitS === 0 || early.length > 0) {
485
+ return jsonResponse(withEphemeral(first));
486
+ }
487
+ let ended = false;
488
+ const stopWaiting = new AbortController();
489
+ const result = await new Promise<ReturnType<typeof once>>((resolve, reject) => {
490
+ let done = false;
491
+ const finish = (value?: ReturnType<typeof once>): void => {
492
+ if (done) return;
493
+ done = true;
494
+ clearTimeout(timer);
495
+ unsubscribe();
496
+ context.request.signal.removeEventListener("abort", aborted);
497
+ // A failing read here (the ledger closing at shutdown, say) answers this request; it
498
+ // never escapes the timer as an uncaught exception (Claude review finding 8).
499
+ try {
500
+ resolve(value ?? once());
501
+ } catch (error) {
502
+ reject(error);
503
+ }
504
+ };
505
+ const aborted = (): void => finish(first);
506
+ const unsubscribe = interaction.onCommit(() =>
507
+ setImmediate(() => {
508
+ if (done) return;
509
+ // A revoked or expired link ends the poll before it reads anything more.
510
+ if (!live(context)) {
511
+ ended = true;
512
+ finish(first);
513
+ return;
514
+ }
515
+ try {
516
+ const value = once();
517
+ if (value.events.length > 0 || "snapshot" in value) finish(value);
518
+ } catch (error) {
519
+ done = true;
520
+ clearTimeout(timer);
521
+ unsubscribe();
522
+ reject(error);
523
+ }
524
+ }),
525
+ );
526
+ const timer = setTimeout(() => finish(), waitS * 1000);
527
+ context.request.signal.addEventListener("abort", aborted, { once: true });
528
+ // A run or live update for this view answers the poll too.
529
+ void bus?.wait(page.artifactId, viewId, waitS * 1000, stopWaiting.signal).then(() => {
530
+ if (!done) finish(first);
531
+ });
532
+ });
533
+ stopWaiting.abort();
534
+ // The link is checked again at the end: nothing read after it died leaves (HY-03).
535
+ if (ended || !live(context)) return revoked();
536
+ return jsonResponse(withEphemeral(result));
537
+ } catch (error) {
538
+ return failure(error);
539
+ }
540
+ };
541
+
542
+ // ── The shell's own routes (WP-07) ─────────────────────────────────────────────────────
543
+ // They run on the shell origin behind the shell's session, its exact Origin and its CSRF
544
+ // token, none of which an artifact's page holds: only the trusted page can call them (SH-02).
545
+
546
+ const shellSubmit = async (context: RouteContext): Promise<Response> => {
547
+ const refused = knownRevision(context);
548
+ if (refused) return refused;
549
+ const request = await body(context, ShellSubmitRequest);
550
+ if (request instanceof Response) return request;
551
+ const page = pageOf(context);
552
+ let submission: SubmissionSummary & { readonly duplicate?: true };
553
+ try {
554
+ submission = interaction.submit(page, {
555
+ viewId: request.viewId,
556
+ expectedRevision: Number(request.expectedRevision),
557
+ channel: "shell",
558
+ });
559
+ } catch (error) {
560
+ return failure(error);
561
+ }
562
+ if (submission.duplicate !== true) {
563
+ options.activated({
564
+ artifactId: page.artifactId,
565
+ control: "submit",
566
+ viewerId: page.viewerId,
567
+ viewId: request.viewId,
568
+ detail: { submissionId: submission.id },
569
+ });
570
+ }
571
+ return jsonResponse(submission);
572
+ };
573
+
574
+ const choose = async (context: RouteContext): Promise<Response> => {
575
+ const refused = knownRevision(context);
576
+ if (refused) return refused;
577
+ const request = await body(context, ChooseRequest);
578
+ if (request instanceof Response) return request;
579
+ const page = pageOf(context);
580
+ try {
581
+ const result = interaction.choose(page, {
582
+ viewId: request.viewId,
583
+ mutationId: request.mutationId,
584
+ baseRevision: Number(request.baseRevision),
585
+ reviewSetId: request.reviewSetId,
586
+ candidateId: request.candidateId,
587
+ ...(request.label !== undefined ? { label: request.label } : {}),
588
+ });
589
+ if (result.applied.length > 0) {
590
+ options.activated({
591
+ artifactId: page.artifactId,
592
+ control: "choose",
593
+ viewerId: page.viewerId,
594
+ viewId: request.viewId,
595
+ detail: { reviewSetId: request.reviewSetId, candidateId: request.candidateId },
596
+ });
597
+ }
598
+ return jsonResponse(result);
599
+ } catch (error) {
600
+ return failure(error);
601
+ }
602
+ };
603
+
604
+ const follow = async (context: RouteContext): Promise<Response> => {
605
+ const refused = knownRevision(context);
606
+ if (refused) return refused;
607
+ const request = await body(context, FollowRequest);
608
+ if (request instanceof Response) return request;
609
+ try {
610
+ interaction.setFollowing(pageOf(context), request.follow);
611
+ return jsonResponse({ follow: request.follow });
612
+ } catch (error) {
613
+ return failure(error);
614
+ }
615
+ };
616
+
617
+ const carry = (context: RouteContext): Response => {
618
+ const refused = knownRevision(context);
619
+ if (refused) return refused;
620
+ const page = pageOf(context);
621
+ const wanted = Number(new URL(context.request.url).searchParams.get("version"));
622
+ if (!Number.isSafeInteger(wanted) || wanted < 1) {
623
+ return malformed("`version` must be a version number.");
624
+ }
625
+ // A link that names a version learns nothing of another (D97 item 9).
626
+ const pinned = context.session?.grant.pinnedVersion;
627
+ if (pinned !== undefined && wanted !== pinned) {
628
+ return answer(
629
+ refusal("MOSTRA_HYGIENE_SCOPE_DENIED", `This link opens version ${pinned} only.`)
630
+ .diagnostic,
631
+ 403,
632
+ );
633
+ }
634
+ const version = options.versionOf(page.artifactId, wanted);
635
+ if (!version) {
636
+ return answer(
637
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", `This artifact has no version ${wanted}.`, 404)
638
+ .diagnostic,
639
+ 404,
640
+ );
641
+ }
642
+ try {
643
+ return jsonResponse(interaction.carryOver(page, version));
644
+ } catch (error) {
645
+ return failure(error);
646
+ }
647
+ };
648
+
649
+ return { fields, submit, signal, stream, poll, shellSubmit, choose, follow, carry };
650
+ }