@operad-io/engine 0.1.1 → 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 (80) hide show
  1. package/config.schema.json +2 -1
  2. package/package.json +1 -1
  3. package/src/config/config.ts +74 -45
  4. package/src/flow/types.ts +4 -0
  5. package/src/flow/validate.ts +5 -0
  6. package/src/http/index.ts +2 -0
  7. package/src/http/plugins.ts +66 -0
  8. package/src/http/server.ts +342 -48
  9. package/src/kernel/decide.ts +115 -30
  10. package/src/kernel/state.ts +9 -0
  11. package/src/kernel/types.ts +25 -40
  12. package/src/log/open-log.ts +2 -5
  13. package/src/log/sqlite.ts +127 -85
  14. package/src/log/types.ts +35 -9
  15. package/src/loop/code-watch.ts +108 -2
  16. package/src/loop/older-code.ts +3 -4
  17. package/src/loop/serve.ts +122 -95
  18. package/src/notify/notify.ts +2 -6
  19. package/src/platform/atomic-write.ts +163 -0
  20. package/src/platform/file-lock.ts +43 -21
  21. package/src/platform/index.ts +2 -0
  22. package/src/platform/kept-workers.ts +290 -0
  23. package/src/platform/process-group.ts +11 -3
  24. package/src/platform/sqlite-open.ts +20 -6
  25. package/src/platform/sqlite-schema.ts +30 -0
  26. package/src/platform/step-reap.ts +33 -18
  27. package/src/platform/watch.ts +1 -11
  28. package/src/plugin/action-schema.ts +59 -1
  29. package/src/plugin/choice-info.ts +133 -0
  30. package/src/plugin/context.ts +279 -0
  31. package/src/plugin/declared-flows.ts +3 -10
  32. package/src/plugin/errors.ts +9 -0
  33. package/src/plugin/freeze.ts +12 -0
  34. package/src/plugin/harness.ts +28 -0
  35. package/src/plugin/index.ts +8 -7
  36. package/src/plugin/install.ts +265 -17
  37. package/src/plugin/keys.ts +2 -12
  38. package/src/plugin/load.ts +47 -23
  39. package/src/plugin/logger.ts +14 -0
  40. package/src/plugin/open-store.ts +0 -6
  41. package/src/plugin/question-form.ts +323 -0
  42. package/src/plugin/registry.ts +512 -76
  43. package/src/plugin/secrets.ts +14 -24
  44. package/src/plugin/semver.ts +52 -0
  45. package/src/plugin/settings.ts +1 -9
  46. package/src/plugin/sqlite-store.ts +94 -64
  47. package/src/plugin/store.ts +5 -0
  48. package/src/plugin/types.ts +566 -21
  49. package/src/plugin/validate.ts +396 -26
  50. package/src/runner/answer.ts +26 -68
  51. package/src/runner/ask.ts +227 -28
  52. package/src/runner/cancel.ts +10 -7
  53. package/src/runner/grants.ts +2 -2
  54. package/src/runner/index.ts +1 -3
  55. package/src/runner/limits.ts +2 -2
  56. package/src/runner/runner.ts +15 -14
  57. package/src/runner/service.ts +52 -19
  58. package/src/runner/step-worker.ts +9 -0
  59. package/src/testing/answer.ts +69 -0
  60. package/src/testing/clock-manual.ts +152 -0
  61. package/src/testing/config.ts +16 -0
  62. package/src/testing/fs.ts +172 -0
  63. package/src/testing/home.ts +43 -0
  64. package/src/testing/index.ts +19 -0
  65. package/src/testing/types.ts +2 -0
  66. package/src/testing/world.ts +9 -2
  67. package/src/trigger/kernel.ts +13 -46
  68. package/src/trigger/rules.ts +22 -12
  69. package/src/trigger/types.ts +2 -6
  70. package/src/util.ts +99 -0
  71. package/src/views/event-line.ts +22 -0
  72. package/src/views/history.ts +36 -19
  73. package/src/views/live-logs.ts +313 -0
  74. package/src/views/pending.ts +23 -5
  75. package/src/views/presentation.ts +629 -81
  76. package/src/views/running.ts +5 -5
  77. package/src/views/settings.ts +205 -66
  78. package/src/views/types.ts +3 -2
  79. package/src/views/uploads.ts +15 -7
  80. package/triggers.schema.json +4 -0
@@ -4,13 +4,15 @@
4
4
  * starts this; no other command opens the port.
5
5
  */
6
6
 
7
+ import type { PluginAdmin } from "./plugins.ts";
7
8
  import { randomBytes } from "node:crypto";
8
9
  import type { HttpConfig } from "../config/config.ts";
9
10
  import type { LogBackend } from "../log/types.ts";
10
11
  import { messageOf } from "../plugin/errors.ts";
11
12
  import type { PluginRegistry } from "../plugin/registry.ts";
12
- import type { Actor } from "../plugin/types.ts";
13
+ import type { Actor, AskQuestionAnswer } from "../plugin/types.ts";
13
14
  import type { Kernel } from "../trigger/kernel.ts";
15
+ import { eventLine, fitsEventLine } from "../views/event-line.ts";
14
16
  import { listPending } from "../views/pending.ts";
15
17
  import {
16
18
  DEFAULT_MAX_EVENT_IDS,
@@ -19,7 +21,7 @@ import {
19
21
  type Views,
20
22
  } from "../views/presentation.ts";
21
23
  import { listRunning } from "../views/running.ts";
22
- import { findAttachment, Uploads, UploadTooLargeError, MAX_UPLOAD_BYTES } from "../views/uploads.ts";
24
+ import { Uploads, UploadTooLargeError, MAX_UPLOAD_BYTES } from "../views/uploads.ts";
23
25
  import { listTypes } from "../views/types.ts";
24
26
  import { validateListenAddresses } from "./address.ts";
25
27
  import {
@@ -48,6 +50,8 @@ export const DEFAULT_TOKEN_CHECK_MS = 1_000;
48
50
  /** The largest JSON request body `serve` accepts, in bytes. */
49
51
  export const MAX_REQUEST_BODY_BYTES = 1024 * 1024;
50
52
 
53
+ export { MAX_SSE_EVENT_BYTES } from "../views/event-line.ts";
54
+
51
55
  /** How often a running server removes the uploads no action used. */
52
56
  export const DEFAULT_UPLOAD_SWEEP_MS = 10 * 60 * 1000;
53
57
 
@@ -58,6 +62,8 @@ export interface HttpServerOptions {
58
62
  readonly log: LogBackend;
59
63
  readonly registry: PluginRegistry;
60
64
  readonly kernel?: Kernel | undefined;
65
+ /** Lists and switches plugins for `/v1/plugins`; without it the endpoint is `404`. */
66
+ readonly plugins?: PluginAdmin | undefined;
61
67
  readonly onLog?: ((message: string) => void) | undefined;
62
68
  /** Called once per address with the URL it listens on. */
63
69
  readonly onListen?: ((url: string) => void) | undefined;
@@ -107,44 +113,180 @@ export interface EventEntry {
107
113
  readonly id: string;
108
114
  }
109
115
 
116
+ type HubEvent =
117
+ | { readonly kind: "change"; readonly entry: EventEntry }
118
+ | { readonly kind: "live"; readonly event: ViewEvent }
119
+ | { readonly kind: "reset" };
120
+
121
+ type HubListener = (event: HubEvent) => void;
122
+ type HubFailure = ((error: unknown) => void) | undefined;
123
+
124
+ /** The first delay before the hub re-opens a source that failed or ended. */
125
+ export const DEFAULT_EVENT_RETRY_MIN_MS = 250;
126
+
127
+ /** The longest such delay; the hub keeps retrying at this pace. */
128
+ export const DEFAULT_EVENT_RETRY_MAX_MS = 5_000;
129
+
130
+ /** The restart delay: double each failure, never past the cap. */
131
+ export function eventRetryDelay(
132
+ attempt: number,
133
+ minMs = DEFAULT_EVENT_RETRY_MIN_MS,
134
+ maxMs = DEFAULT_EVENT_RETRY_MAX_MS,
135
+ ): number {
136
+ const low = Math.max(0, minMs);
137
+ const high = Math.max(low, maxMs);
138
+ const step = Math.min(Math.max(0, Math.trunc(attempt)), 30);
139
+ return Math.min(high, low * 2 ** step);
140
+ }
141
+
142
+ /** Waits before a retry; unref'd so a stopped hub does not hold the process up. */
143
+ function waitForRestart(ms: number): Promise<void> {
144
+ return new Promise<void>((resolve) => {
145
+ (setTimeout(resolve, ms) as { unref?: () => void }).unref?.();
146
+ });
147
+ }
148
+
149
+ export interface EventHubOptions {
150
+ /** Waits `ms` before re-opening a failed source; tests inject it. */
151
+ readonly wait?: ((ms: number) => Promise<void>) | undefined;
152
+ readonly retryMinMs?: number | undefined;
153
+ readonly retryMaxMs?: number | undefined;
154
+ /** The clock; a source that stayed open at least the longest wait is healthy. */
155
+ readonly clock?: (() => number) | undefined;
156
+ }
157
+
110
158
  /** The bounded stream of ids every event client resumes from. */
111
159
  export class EventHub {
112
160
  private readonly entries: EventEntry[] = [];
113
161
  private readonly max: number;
114
- private readonly listeners = new Set<(entry: EventEntry) => void>();
115
- private readonly iterator: AsyncIterator<ViewEvent>;
162
+ private readonly listeners = new Map<HubListener, HubFailure>();
163
+ private readonly events: () => AsyncIterable<ViewEvent>;
164
+ private readonly onLog: (message: string) => void;
165
+ private iterator: AsyncIterator<ViewEvent> | undefined;
116
166
  /** Random once per process: an id from another boot never resumes here. */
117
167
  private readonly bootId = randomBytes(8).toString("hex");
118
168
  private seq = 0;
169
+ /** The first id after the last source restart; older ids cannot resume. */
170
+ private resetFrom = 0;
171
+ /** Whether this outage already told the open streams to reset. */
172
+ private resetAnnounced = false;
173
+ private readonly wait: (ms: number) => Promise<void>;
174
+ private readonly retryMinMs: number;
175
+ private readonly retryMaxMs: number;
176
+ /** An open at least this long counts as healthy and starts the wait over. */
177
+ private readonly healthyMs: number;
178
+ private readonly clock: () => number;
119
179
  private stopped = false;
120
180
 
121
181
  constructor(
122
- events: AsyncIterable<ViewEvent>,
182
+ events: () => AsyncIterable<ViewEvent>,
123
183
  max: number,
124
184
  onLog: (message: string) => void,
185
+ options: EventHubOptions = {},
125
186
  ) {
126
187
  this.max = Math.max(1, max);
127
- this.iterator = events[Symbol.asyncIterator]();
128
- void this.pump(onLog);
188
+ this.events = events;
189
+ this.onLog = onLog;
190
+ this.wait = options.wait ?? waitForRestart;
191
+ this.retryMinMs = options.retryMinMs ?? DEFAULT_EVENT_RETRY_MIN_MS;
192
+ this.retryMaxMs = options.retryMaxMs ?? DEFAULT_EVENT_RETRY_MAX_MS;
193
+ this.healthyMs = Math.max(Math.max(0, this.retryMinMs), this.retryMaxMs);
194
+ this.clock = options.clock ?? Date.now;
195
+ void this.pump();
129
196
  }
130
197
 
131
- private async pump(onLog: (message: string) => void): Promise<void> {
132
- try {
133
- while (!this.stopped) {
134
- const next = await this.iterator.next();
135
- if (next.done) break;
136
- this.seq += 1;
137
- const entry: EventEntry = {
138
- seq: this.seq,
139
- event: `${this.bootId}-${this.seq}`,
140
- id: next.value.id,
141
- };
142
- this.entries.push(entry);
143
- if (this.entries.length > this.max) this.entries.shift();
144
- for (const listener of [...this.listeners]) listener(entry);
198
+ /**
199
+ * Reads the source to its end, then re-opens it. A source that fails or ends
200
+ * at once on every open waits longer each time, up to the cap, so it cannot
201
+ * spin through the event loop; only a source that stayed open at least as
202
+ * long as the longest wait starts over, so one that hands over an event and
203
+ * dies on every open keeps backing off instead of retrying at the minimum.
204
+ */
205
+ private async pump(): Promise<void> {
206
+ let attempt = 0;
207
+ while (!this.stopped) {
208
+ let failure: unknown;
209
+ let ended = false;
210
+ const openedAt = this.clock();
211
+ try {
212
+ const iterator = this.events()[Symbol.asyncIterator]();
213
+ this.iterator = iterator;
214
+ while (!this.stopped) {
215
+ const next = await iterator.next();
216
+ if (next.done) {
217
+ ended = true;
218
+ break;
219
+ }
220
+ this.publish(next.value);
221
+ }
222
+ } catch (error) {
223
+ failure = error;
224
+ }
225
+ if (this.stopped) return;
226
+ if (this.clock() - openedAt >= this.healthyMs) attempt = 0;
227
+ const delay = eventRetryDelay(attempt, this.retryMinMs, this.retryMaxMs);
228
+ attempt += 1;
229
+ this.onLog(
230
+ ended
231
+ ? `http events: the source ended; re-opening it in ${delay} ms`
232
+ : `http events: ${messageOf(failure)}; re-opening it in ${delay} ms`,
233
+ );
234
+ this.restart();
235
+ await this.wait(delay);
236
+ }
237
+ }
238
+
239
+ private publish(value: ViewEvent): void {
240
+ if (value.section !== undefined) {
241
+ // A live part is for the clients connected now; it is not replayed on a
242
+ // reconnect, where the section read gives the whole current tail again.
243
+ // A part too large for one line is dropped, never cut and never a second
244
+ // change: the kernel announces the object's growth change within its own
245
+ // window, and that change asks the client to read the open section again.
246
+ if (fitsEventLine(value)) this.notify({ kind: "live", event: value });
247
+ return;
248
+ }
249
+ this.resetAnnounced = false;
250
+ this.seq += 1;
251
+ const entry: EventEntry = {
252
+ seq: this.seq,
253
+ event: `${this.bootId}-${this.seq}`,
254
+ id: value.id,
255
+ };
256
+ this.entries.push(entry);
257
+ if (this.entries.length > this.max) this.entries.shift();
258
+ this.notify({ kind: "change", entry });
259
+ }
260
+
261
+ /**
262
+ * A source that failed or ended cannot replay what happened while it was
263
+ * gone. Open streams get a reset, and no id from before the break resumes.
264
+ */
265
+ private restart(): void {
266
+ this.resetFrom = this.seq + 1;
267
+ this.entries.length = 0;
268
+ // Repeated failures without a change in between carry no new gap, so one
269
+ // reset per outage is enough; repeating it would make every client re-read
270
+ // its state once per retry.
271
+ if (this.resetAnnounced) return;
272
+ this.resetAnnounced = true;
273
+ this.notify({ kind: "reset" });
274
+ }
275
+
276
+ /** One failing subscriber is dropped; it does not stop the others. */
277
+ private notify(event: HubEvent): void {
278
+ for (const [listener, fail] of [...this.listeners]) {
279
+ try {
280
+ listener(event);
281
+ } catch (error) {
282
+ this.listeners.delete(listener);
283
+ this.onLog(`http events: a subscriber failed: ${messageOf(error)}`);
284
+ try {
285
+ fail?.(error);
286
+ } catch (failure) {
287
+ this.onLog(`http events: a subscriber could not be closed: ${messageOf(failure)}`);
288
+ }
145
289
  }
146
- } catch (error) {
147
- if (!this.stopped) onLog(`http events: ${messageOf(error)}`);
148
290
  }
149
291
  }
150
292
 
@@ -159,6 +301,7 @@ export class EventHub {
159
301
  if (parsed === undefined || parsed.bootId !== this.bootId) {
160
302
  return { reset: true, replay: [] };
161
303
  }
304
+ if (parsed.seq < this.resetFrom) return { reset: true, replay: [] };
162
305
  const oldest = this.entries[0]?.seq;
163
306
  const latest = this.entries.at(-1)?.seq;
164
307
  if (oldest === undefined || latest === undefined) {
@@ -173,8 +316,8 @@ export class EventHub {
173
316
  };
174
317
  }
175
318
 
176
- subscribe(listener: (entry: EventEntry) => void): () => void {
177
- this.listeners.add(listener);
319
+ subscribe(listener: HubListener, onFailure?: (error: unknown) => void): () => void {
320
+ this.listeners.set(listener, onFailure);
178
321
  return () => {
179
322
  this.listeners.delete(listener);
180
323
  };
@@ -182,7 +325,7 @@ export class EventHub {
182
325
 
183
326
  stop(): void {
184
327
  this.stopped = true;
185
- void this.iterator.return?.();
328
+ void this.iterator?.return?.();
186
329
  }
187
330
  }
188
331
 
@@ -272,6 +415,8 @@ function viewErrorStatus(kind: ViewError["kind"]): number {
272
415
  case "not-available":
273
416
  case "confirm":
274
417
  return 409;
418
+ case "refused":
419
+ return 422;
275
420
  case "timeout":
276
421
  return 504;
277
422
  default:
@@ -325,11 +470,19 @@ function urlFor(address: string, port: number): string {
325
470
  : `http://${address}:${port}`;
326
471
  }
327
472
 
473
+ const RESET_EVENT = "event: reset\ndata: {}\n\n";
474
+
475
+ /** A change event whose data line fits; an id too long to send becomes a reset. */
328
476
  function formatEvent(entry: EventEntry): string {
329
- return `id: ${entry.event}\ndata: ${JSON.stringify({ id: entry.id })}\n\n`;
477
+ const line = eventLine({ id: entry.id });
478
+ return line === undefined
479
+ ? RESET_EVENT
480
+ : `id: ${entry.event}\n${line}\n\n`;
330
481
  }
331
482
 
332
- const RESET_EVENT = "event: reset\ndata: {}\n\n";
483
+ function formatTailEvent(event: ViewEvent): string {
484
+ return `event: tail\ndata: ${JSON.stringify(event)}\n\n`;
485
+ }
333
486
 
334
487
  export function eventResponse(
335
488
  request: Request,
@@ -393,7 +546,11 @@ export function eventResponse(
393
546
  const snapshot = hub.snapshot(resumeFrom);
394
547
  if (snapshot.reset) push(RESET_EVENT);
395
548
  else for (const entry of snapshot.replay) push(formatEvent(entry));
396
- unsubscribe = hub.subscribe((entry) => push(formatEvent(entry)));
549
+ unsubscribe = hub.subscribe((event) => {
550
+ if (event.kind === "reset") push(RESET_EVENT);
551
+ else if (event.kind === "live") push(formatTailEvent(event.event));
552
+ else push(formatEvent(event.entry));
553
+ }, finish);
397
554
  untrack = track(token, finish);
398
555
  // An immediate comment flushes the response headers; the client then has
399
556
  // a stream even when nothing changes for a while.
@@ -548,6 +705,127 @@ function createHandler(
548
705
  return json(await listRunning(options.log, options.clock, options.views));
549
706
  }
550
707
 
708
+ const setupOf = /^\/v1\/plugins\/([^/]+)\/setup$/.exec(path);
709
+ if (setupOf !== null) {
710
+ const admin = options.plugins;
711
+ if (admin?.setup === undefined) return errorResponse(404, "not-found", "no such endpoint");
712
+ if (method !== "GET") return errorResponse(405, "method", "this endpoint takes GET");
713
+ const name = decodeURIComponent(setupOf[1] ?? "");
714
+ const found = await admin.setup(name);
715
+ if (found === undefined) return errorResponse(404, "not-found", `plugin "${name}" has no setup guide`);
716
+ return json({ setup: found });
717
+ }
718
+
719
+ if (path === "/v1/plugins") {
720
+ const admin = options.plugins;
721
+ if (admin === undefined) return errorResponse(404, "not-found", "no such endpoint");
722
+ if (method === "GET") return json({ plugins: await admin.list() });
723
+ if (method !== "POST") {
724
+ return errorResponse(405, "method", "this endpoint takes GET or POST");
725
+ }
726
+ const body = await readBody(request);
727
+ if (!isRecord(body)) {
728
+ return errorResponse(400, "args", "the body must be an object");
729
+ }
730
+ const { install, name, enabled, confirmed } = body;
731
+ if (confirmed !== undefined && typeof confirmed !== "boolean") {
732
+ return errorResponse(400, "args", "confirmed must be a boolean");
733
+ }
734
+ const actor: Actor = { via: clientName(request.headers.get(CLIENT_HEADER)), id: token.label };
735
+ if (install !== undefined) {
736
+ if (typeof install !== "string" || install.trim().length === 0) {
737
+ return errorResponse(400, "args", "install must be a non-empty package name");
738
+ }
739
+ try {
740
+ const plugin = await admin.install(install, { confirmed: confirmed === true, actor });
741
+ onLog(`http: plugin installed from "${install}" via ${actor.via} as ${actor.id}`);
742
+ return json({ plugin });
743
+ } catch (error) {
744
+ if (error instanceof ViewError) {
745
+ onLog(`http: plugin "${install}" refused (${viewErrorStatus(error.kind)}): ${error.message}`);
746
+ throw error;
747
+ }
748
+ onLog(`http: plugin "${install}" refused (422): ${messageOf(error)}`);
749
+ return errorResponse(422, "refused", messageOf(error));
750
+ }
751
+ }
752
+ if (typeof name !== "string" || name.length === 0) {
753
+ return errorResponse(400, "args", "the body needs a name or an install");
754
+ }
755
+ if (typeof enabled !== "boolean") {
756
+ return errorResponse(400, "args", "enabled must be true or false");
757
+ }
758
+ try {
759
+ const plugin = await admin.set(name, enabled, { confirmed: confirmed === true, actor });
760
+ // A switch belongs in the lasting log like an action's caller, even
761
+ // though it changes config.json rather than an object.
762
+ try {
763
+ await options.log.appendGlobal({
764
+ kind: "plugin_switched",
765
+ payload: {
766
+ name: plugin.name,
767
+ enabled: plugin.enabled,
768
+ actor: { via: actor.via, id: actor.id },
769
+ },
770
+ cause: `plugin:${plugin.name}`,
771
+ });
772
+ } catch (error) {
773
+ onLog(`http: could not record the switch of "${plugin.name}": ${messageOf(error)}`);
774
+ }
775
+ onLog(`http: plugin "${name}" ${enabled ? "enabled" : "disabled"} via ${actor.via} as ${actor.id}`);
776
+ return json({ plugin });
777
+ } catch (error) {
778
+ if (error instanceof ViewError) {
779
+ onLog(`http: plugin "${name}" refused (${viewErrorStatus(error.kind)}): ${error.message}`);
780
+ throw error;
781
+ }
782
+ onLog(`http: plugin "${name}" refused (422): ${messageOf(error)}`);
783
+ return errorResponse(422, "refused", messageOf(error));
784
+ }
785
+ }
786
+
787
+ if (path === "/v1/commands") {
788
+ if (method !== "POST") {
789
+ return errorResponse(405, "method", "this endpoint takes POST");
790
+ }
791
+ const body = await readBody(request);
792
+ if (!isRecord(body)) {
793
+ return errorResponse(400, "args", "the body must be an object");
794
+ }
795
+ const { plugin, verb, args, input } = body;
796
+ if (typeof plugin !== "string" || plugin.length === 0) {
797
+ return errorResponse(400, "args", "the body needs a plugin");
798
+ }
799
+ if (typeof verb !== "string" || verb.length === 0) {
800
+ return errorResponse(400, "args", "the body needs a verb");
801
+ }
802
+ if (args !== undefined && (!Array.isArray(args) || !args.every((item) => typeof item === "string"))) {
803
+ return errorResponse(400, "args", "args must be an array of strings");
804
+ }
805
+ if (input !== undefined && typeof input !== "string") {
806
+ return errorResponse(400, "args", "input must be a string");
807
+ }
808
+ const commandArgs = args === undefined ? [] : (args as readonly string[]);
809
+ try {
810
+ // A served command never reads the serve process's own stdin: an
811
+ // omitted input is an empty one.
812
+ const run = await options.registry.runCommand([plugin, verb, ...commandArgs], {
813
+ input: input ?? "",
814
+ });
815
+ if (run === undefined) {
816
+ return errorResponse(
817
+ 404,
818
+ "not-found",
819
+ `no loaded plugin "${plugin}" declares the verb "${verb}"`,
820
+ );
821
+ }
822
+ return json({ plugin: run.plugin, verb: run.command, value: run.value });
823
+ } catch (error) {
824
+ onLog(`http: command "${plugin} ${verb}" refused: ${messageOf(error)}`);
825
+ return errorResponse(422, "refused", messageOf(error));
826
+ }
827
+ }
828
+
551
829
  if (path === "/v1/settings") {
552
830
  if (method === "GET") {
553
831
  const scope = url.searchParams.get("scope") ?? undefined;
@@ -573,20 +851,28 @@ function createHandler(
573
851
  if (confirmed !== undefined && typeof confirmed !== "boolean") {
574
852
  return errorResponse(400, "args", "confirmed must be a boolean");
575
853
  }
576
- return json(
577
- await options.views.set(name, body.value, {
578
- ...(scope === undefined ? {} : { scope }),
579
- confirmed: confirmed === true,
580
- }),
581
- );
854
+ try {
855
+ return json(
856
+ await options.views.set(name, body.value, {
857
+ ...(scope === undefined ? {} : { scope }),
858
+ confirmed: confirmed === true,
859
+ }),
860
+ );
861
+ } catch (error) {
862
+ // The body was checked above; a value or file the settings schema
863
+ // refuses is unprocessable, not a malformed request.
864
+ if (error instanceof ViewError && error.kind === "args") {
865
+ return errorResponse(422, "args", error.message);
866
+ }
867
+ throw error;
868
+ }
582
869
  }
583
870
 
584
871
  if (path.startsWith("/v1/attachments/")) {
585
872
  if (method !== "GET") {
586
873
  return errorResponse(405, "method", "this endpoint takes GET");
587
874
  }
588
- const found = await findAttachment(
589
- options.home,
875
+ const found = await options.views.file(
590
876
  path.slice("/v1/attachments/".length).split("/").map(decodeSegment),
591
877
  );
592
878
  if (found === undefined) return errorResponse(404, "not-found", "no such attachment");
@@ -650,8 +936,18 @@ function createHandler(
650
936
  if (typeof waitId !== "string" || waitId.length === 0) {
651
937
  return errorResponse(400, "args", "the body needs a waitId");
652
938
  }
653
- if (typeof choice !== "string" || choice.length === 0) {
654
- return errorResponse(400, "args", "the body needs a choice");
939
+ const answers = body.answers;
940
+ if (answers !== undefined && !Array.isArray(answers)) {
941
+ return errorResponse(400, "args", "answers must be a list");
942
+ }
943
+ if (
944
+ (choice === undefined || typeof choice !== "string" || choice.length === 0) &&
945
+ answers === undefined
946
+ ) {
947
+ return errorResponse(400, "args", "the body needs a choice or answers");
948
+ }
949
+ if (choice !== undefined && (typeof choice !== "string" || choice.length === 0)) {
950
+ return errorResponse(400, "args", "choice must be a string");
655
951
  }
656
952
  const note = body.note;
657
953
  if (note !== undefined && typeof note !== "string") {
@@ -666,7 +962,10 @@ function createHandler(
666
962
  await options.views.answer({
667
963
  runId,
668
964
  waitId,
669
- choice,
965
+ choice: typeof choice === "string" ? choice : undefined,
966
+ ...(answers === undefined
967
+ ? {}
968
+ : { answers: answers as unknown as readonly AskQuestionAnswer[] }),
670
969
  ...(note === undefined ? {} : { note }),
671
970
  ...(confirmed === true ? { confirmed: true } : {}),
672
971
  surface: "http",
@@ -804,10 +1103,12 @@ export async function startHttpServer(
804
1103
  const token = await ensureHttpToken(options.home);
805
1104
 
806
1105
  const onLog = options.onLog ?? (() => undefined);
1106
+ const wait = options.wait ?? waitForRestart;
807
1107
  const hub = new EventHub(
808
- options.views.events(),
1108
+ () => options.views.events(),
809
1109
  options.maxEventIds ?? DEFAULT_MAX_EVENT_IDS,
810
1110
  onLog,
1111
+ { wait },
811
1112
  );
812
1113
  const streams = new StreamRegistry();
813
1114
  const uploads = new Uploads({
@@ -824,13 +1125,6 @@ export async function startHttpServer(
824
1125
  const handler = createHandler(options, uploads, hub, streams, onLog);
825
1126
  const servers: { readonly address: string; readonly server: ReturnType<typeof Bun.serve> }[] = [];
826
1127
  const listener = options.listener ?? Bun.serve;
827
- const wait =
828
- options.wait ??
829
- ((ms: number) =>
830
- new Promise<void>((resolve) => {
831
- // Unref'd: a stop that finished in time must not keep the process up.
832
- (setTimeout(resolve, ms) as { unref?: () => void }).unref?.();
833
- }));
834
1128
  const stopTimeoutMs = options.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS;
835
1129
 
836
1130
  /**