@engenty/wizards-runtime 0.16.0 → 0.16.2

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 (102) hide show
  1. package/apps/runtime/dist/assistant/knows.js +3 -1
  2. package/apps/runtime/dist/cli/move-files.js +27 -11
  3. package/apps/runtime/dist/db/control-schema.js +7 -0
  4. package/apps/runtime/dist/db/migrations/control/0014_run_index_generation.sql +1 -0
  5. package/apps/runtime/dist/db/migrations/control/0015_run_index_wake.sql +3 -0
  6. package/apps/runtime/dist/db/migrations/control/meta/0014_snapshot.json +629 -0
  7. package/apps/runtime/dist/db/migrations/control/meta/0015_snapshot.json +650 -0
  8. package/apps/runtime/dist/db/migrations/control/meta/_journal.json +14 -0
  9. package/apps/runtime/dist/db/migrations/tenant/0056_run_claim_rev.sql +2 -0
  10. package/apps/runtime/dist/db/migrations/tenant/0057_run_wake_at.sql +1 -0
  11. package/apps/runtime/dist/db/migrations/tenant/meta/0056_snapshot.json +6520 -0
  12. package/apps/runtime/dist/db/migrations/tenant/meta/0057_snapshot.json +6527 -0
  13. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +14 -0
  14. package/apps/runtime/dist/db/schema.js +17 -3
  15. package/apps/runtime/dist/documents/parse.js +9 -0
  16. package/apps/runtime/dist/elements/knowledge.js +1 -0
  17. package/apps/runtime/dist/engine/runner.js +344 -52
  18. package/apps/runtime/dist/env.js +18 -0
  19. package/apps/runtime/dist/mounts/mounts.js +3 -0
  20. package/apps/runtime/dist/plugins/runs.js +3 -0
  21. package/apps/runtime/dist/prompts/mcp.md +3 -0
  22. package/apps/runtime/dist/routes/runs.js +17 -14
  23. package/apps/runtime/dist/services/api.js +1 -1
  24. package/apps/runtime/dist/services/knowledge.js +2 -1
  25. package/apps/runtime/dist/services/manage-reports.js +2 -0
  26. package/apps/runtime/dist/services/query-vectors.js +60 -0
  27. package/apps/runtime/dist/services/relevance.js +12 -0
  28. package/apps/runtime/dist/services/runs.js +16 -2
  29. package/apps/runtime/dist/services/space-index.js +22 -6
  30. package/apps/runtime/dist/services/work-files.js +25 -1
  31. package/apps/runtime/dist/sharing/index.js +3 -0
  32. package/apps/runtime/dist/tenants/control.js +46 -14
  33. package/apps/web/dist/assets/{AboutDialog-0q4P80yv.js → AboutDialog-BCcD8hKm.js} +1 -1
  34. package/apps/web/dist/assets/{BlockEditor-CUYFH_CU.js → BlockEditor-DgaUm2pR.js} +1 -1
  35. package/apps/web/dist/assets/CapabilitiesPage-DuJJV1ll.js +2 -0
  36. package/apps/web/dist/assets/{ChangelogDialog-CDN7kMs1.js → ChangelogDialog-B08elwyr.js} +1 -1
  37. package/apps/web/dist/assets/{CodeEditor-D-Y16fdk.js → CodeEditor-BiyOk_SC.js} +1 -1
  38. package/apps/web/dist/assets/EditorPage-EMFTHEYD.js +3 -0
  39. package/apps/web/dist/assets/{FlowPreview-DXnk7m9P.js → FlowPreview-DF_6TvZ0.js} +1 -1
  40. package/apps/web/dist/assets/{LangSwitch-Dkd0FBIH.js → LangSwitch-Ba4OWLzJ.js} +1 -1
  41. package/apps/web/dist/assets/Marketplace-DqziLf66.js +2 -0
  42. package/apps/web/dist/assets/{NewWizardChannels-Czool7s1.js → NewWizardChannels-CsIGp0nZ.js} +1 -1
  43. package/apps/web/dist/assets/NewWizardPage-CzQAkKMy.js +7 -0
  44. package/apps/web/dist/assets/OnboardingPage-B9gr2OX5.js +1 -0
  45. package/apps/web/dist/assets/PreviewPane-DSOV3o-1.js +7 -0
  46. package/apps/web/dist/assets/PublicRunner-BVs8-Vu3.js +1 -0
  47. package/apps/web/dist/assets/{ReadOnly-B7MUySpC.js → ReadOnly--4CIJCDD.js} +1 -1
  48. package/apps/web/dist/assets/SettingsPage-z2u8lSe2.js +2 -0
  49. package/apps/web/dist/assets/SetupPage-9Zk-KUGA.js +1 -0
  50. package/apps/web/dist/assets/{SharePage-UwEJBIzq.js → SharePage-D_Ab0gjr.js} +1 -1
  51. package/apps/web/dist/assets/SkillEditor-DvtameHg.js +1 -0
  52. package/apps/web/dist/assets/{Skills-Bv6XbKxc.js → Skills-Cf1Kl4Fy.js} +6 -6
  53. package/apps/web/dist/assets/SpacePage-CyqVzX9b.js +2 -0
  54. package/apps/web/dist/assets/{UpdateCheck-C7I43zFZ.js → UpdateCheck-DweZBVP6.js} +2 -2
  55. package/apps/web/dist/assets/changelog-C85v9OWg.js +1 -0
  56. package/apps/web/dist/assets/{code-editor-Ca5EAxmd.js → code-editor-B1RbFTAZ.js} +2 -2
  57. package/apps/web/dist/assets/connection-sign-in-CaVvh5GQ.js +1 -0
  58. package/apps/web/dist/assets/{host-D5hNHbhF.js → host-CKS5U5Vg.js} +18 -18
  59. package/apps/web/dist/assets/i18n-Bymk5Ev-.js +55 -0
  60. package/apps/web/dist/assets/{index-CyBrvupM.js → index-Ckcn5vy7.js} +4 -4
  61. package/apps/web/dist/assets/{read-aloud-Bfp9_bUY.js → read-aloud-Bq88XUHC.js} +1 -1
  62. package/apps/web/dist/assets/{runners-CUpBpSji.js → runners-DvYVe9Dt.js} +1 -1
  63. package/apps/web/dist/assets/session-D2bjiA3P.js +2 -0
  64. package/apps/web/dist/assets/theme-CNJIC2be.js +12 -0
  65. package/apps/web/dist/assets/ui-Mplfhz_Z.js +16 -0
  66. package/apps/web/dist/assets/{useMutation-1fV4Nnxq.js → useMutation-8QRM-z4M.js} +1 -1
  67. package/apps/web/dist/assets/{viewers-ChriFcRy.js → viewers-CEocUV_2.js} +2 -2
  68. package/apps/web/dist/index.html +11 -11
  69. package/apps/web/dist/mcp/flow.html +65 -65
  70. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +8 -2
  71. package/node_modules/@engenty/wizards/dist/plugin/thread.js +30 -0
  72. package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +168 -0
  73. package/node_modules/@engenty/wizards-shared/dist/definition.js +52 -0
  74. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +6 -0
  75. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +6 -0
  76. package/node_modules/@engenty/wizards-shared/dist/fit.d.ts +2 -0
  77. package/node_modules/@engenty/wizards-shared/dist/fit.js +4 -0
  78. package/node_modules/@engenty/wizards-shared/dist/knowledge.d.ts +5 -0
  79. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +8 -1
  80. package/node_modules/@engenty/wizards-shared/dist/run.js +8 -0
  81. package/node_modules/@engenty/wizards-shared/dist/runner-texts.d.ts +7 -1
  82. package/node_modules/@engenty/wizards-shared/dist/runner-texts.js +6 -0
  83. package/package.json +1 -1
  84. package/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugin/plugin.json +1 -1
  86. package/apps/web/dist/assets/CapabilitiesPage-BlZP8DYb.js +0 -2
  87. package/apps/web/dist/assets/EditorPage-CrMVsgUt.js +0 -3
  88. package/apps/web/dist/assets/Marketplace-Cty40VwG.js +0 -2
  89. package/apps/web/dist/assets/NewWizardPage-CfVe_4a2.js +0 -7
  90. package/apps/web/dist/assets/OnboardingPage-D3SEpTmt.js +0 -1
  91. package/apps/web/dist/assets/PreviewPane-CQDKQO6z.js +0 -7
  92. package/apps/web/dist/assets/PublicRunner-BDZNnlQw.js +0 -1
  93. package/apps/web/dist/assets/SettingsPage-Bgurv3l2.js +0 -2
  94. package/apps/web/dist/assets/SetupPage-C3km8vqv.js +0 -1
  95. package/apps/web/dist/assets/SkillEditor-BaEiqqXl.js +0 -1
  96. package/apps/web/dist/assets/SpacePage-D9PXLSU_.js +0 -2
  97. package/apps/web/dist/assets/changelog-DwgWiSZb.js +0 -1
  98. package/apps/web/dist/assets/connection-sign-in-hI3HXhq4.js +0 -1
  99. package/apps/web/dist/assets/i18n-BBzMbGoo.js +0 -55
  100. package/apps/web/dist/assets/session-CMQo8P-G.js +0 -2
  101. package/apps/web/dist/assets/theme-CdX0marK.js +0 -11
  102. package/apps/web/dist/assets/ui-BCfu5sia.js +0 -16
@@ -1,11 +1,12 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import { createHash } from "node:crypto";
2
3
  import { marginOf, } from "@engenty/wizards-shared/decision";
3
- import { branchValues, cardsFromData, conditionsOf, dataRef, followRules, formatsFor, isDecidedField, LIST_FORMATS, listRef, loopKey, MAX_SHOWN_FIELDS, optionsFromData, otherwiseOf, pageNeeds, textLang, whenHolds, wizardLang, } from "@engenty/wizards-shared/definition";
4
- import { note, saidText, } from "@engenty/wizards-shared/run";
4
+ import { branchValues, cardsFromData, conditionsOf, dataRef, followRules, formatsFor, isDecidedField, LIST_FORMATS, listRef, loopKey, MAX_SHOWN_FIELDS, optionsFromData, otherwiseOf, pageNeeds, textLang, waitDurationMs, whenHolds, wizardLang, } from "@engenty/wizards-shared/definition";
5
+ import { CAN_GO_BACK, note, saidText, } from "@engenty/wizards-shared/run";
5
6
  import { CONVERSATION_RUNNERS, DEFAULT_RUNNER_SETTINGS } from "@engenty/wizards-shared/runners";
6
7
  import { fitData } from "@engenty/wizards-shared/shape";
7
8
  import { machineTranslated, translateDefinition } from "@engenty/wizards-shared/translation";
8
- import { eq } from "drizzle-orm";
9
+ import { and, eq, lt, sql } from "drizzle-orm";
9
10
  import { nanoid } from "nanoid";
10
11
  import { currentImpersonator } from "../auth/impersonation.js";
11
12
  import { grantNote, grantOf, kindOf } from "../broker/index.js";
@@ -16,6 +17,7 @@ import { addLocalCost, canSpend, releaseRun, reserveForRun, syncRunCost, } from
16
17
  import { estimateRun } from "../credits/estimate.js";
17
18
  import { db, schema, withTenant } from "../db/client.js";
18
19
  import { env } from "../env.js";
20
+ import { feature, remoteFeatures } from "../features.js";
19
21
  import { saveAsset } from "../files/storage.js";
20
22
  import { managed, tenantInfo } from "../manage.js";
21
23
  import { hasFfmpeg } from "../media/ffmpeg.js";
@@ -31,7 +33,7 @@ import { spaceProfile } from "../services/spaces.js";
31
33
  import { storedTranslation } from "../services/translations.js";
32
34
  import { latestShareJob } from "../sharing/state.js";
33
35
  import { listRows, listSecrets, scopeOf } from "../store/index.js";
34
- import { claimRun, disownRuns, heartbeatRuns, indexRun, markLine, restRun, waitingRuns, wakeRun, } from "../tenants/control.js";
36
+ import { claimRun, disownRuns, heartbeatRuns, indexRun, markLine, restRun, setWake, waitingRuns, wakeDue, wakeRun, } from "../tenants/control.js";
35
37
  import { currentTenant } from "../tenants/tenant.js";
36
38
  import { askPerson, clearStaleAsk } from "./asks.js";
37
39
  import { decide } from "./decide.js";
@@ -42,7 +44,7 @@ import { pushRun } from "./push.js";
42
44
  import { blockingMessage, closedChoices, maskedNote, missingModelsSaid, openValue, stepsWithoutModel, tierRefusalSaid, } from "./requirements.js";
43
45
  import { releaseResources, resourcesFor } from "./resources.js";
44
46
  import { outputSchema, runAutomaticStep } from "./steps.js";
45
- import { answersAsText, resolveRef } from "./template.js";
47
+ import { answersAsText, renderTemplate, resolveRef } from "./template.js";
46
48
  import { StepError } from "./types.js";
47
49
  /** A command the run cannot take in its current state; a note where the person may read it. */
48
50
  export class RunConflict extends NotedError {
@@ -65,6 +67,17 @@ export class GuestBudgetError extends NotedError {
65
67
  super(note("guestBudget"));
66
68
  }
67
69
  }
70
+ /** A step past its deadline (`env.runner.stepDeadlines`): it fails, and its slot comes free. */
71
+ class StepDeadline extends NotedError {
72
+ constructor() {
73
+ super(note("stepTookTooLong"));
74
+ }
75
+ }
76
+ /** Another runner claimed the run while this one drove it: this drive ends, without a word on the run. */
77
+ class LostClaim extends Error {
78
+ }
79
+ /** The run this drive works on and its claim; empty outside `drive`. */
80
+ const driving = new AsyncLocalStorage();
68
81
  /** The runs this process drives right now, with the handle that stops each. */
69
82
  const active = new Map();
70
83
  // --- the line ------------------------------------------------------------------
@@ -74,6 +87,8 @@ const active = new Map();
74
87
  /** How often a runner looks at the line, and how often it reports on the runs it holds. */
75
88
  const POLL_MS = 2000;
76
89
  const HEARTBEAT_MS = 10_000;
90
+ /** A run holding a slot this long goes into the log, once: what real steps take. It stops nothing. */
91
+ const LONG_HOLD_MS = 60 * 60_000;
77
92
  async function concurrencyLimit(tenant) {
78
93
  if (!managed) {
79
94
  return env.limits.concurrentRuns;
@@ -85,6 +100,13 @@ async function concurrencyLimit(tenant) {
85
100
  });
86
101
  return info?.limits.concurrentRuns || env.limits.concurrentRuns;
87
102
  }
103
+ /** Puts a claim on the run's own row; an older claim that arrives late changes nothing. */
104
+ async function holdRun(runId, generation) {
105
+ await db
106
+ .update(schema.run)
107
+ .set({ claim: generation })
108
+ .where(and(eq(schema.run.id, runId), lt(schema.run.claim, generation)));
109
+ }
88
110
  async function loadRun(runId) {
89
111
  return db.query.run.findFirst({ where: eq(schema.run.id, runId) });
90
112
  }
@@ -115,11 +137,30 @@ async function dataSpaceOf(run, space) {
115
137
  }
116
138
  return client;
117
139
  }
118
- async function updateRun(runId, patch) {
119
- await db
140
+ /**
141
+ * Writes the run. Inside its drive the write needs the drive's claim; with `seen`, a person's write
142
+ * needs the `rev` it read, and a wait's write the status it came from: a cancel wins over either. A
143
+ * step may start or answer other runs: only its own run's claim counts.
144
+ */
145
+ async function updateRun(runId, patch, seen) {
146
+ const holder = driving.getStore();
147
+ const held = holder?.runId === runId ? holder : undefined;
148
+ const result = await db
120
149
  .update(schema.run)
121
- .set({ ...patch, updatedAt: new Date() })
122
- .where(eq(schema.run.id, runId));
150
+ .set({ ...patch, rev: sql `${schema.run.rev} + 1`, updatedAt: new Date() })
151
+ .where(and(eq(schema.run.id, runId), held ? eq(schema.run.claim, held.generation) : undefined, seen && ("rev" in seen ? eq(schema.run.rev, seen.rev) : eq(schema.run.status, seen.status))));
152
+ if (result.rowsAffected === 0) {
153
+ if (held) {
154
+ throw new LostClaim();
155
+ }
156
+ if (seen) {
157
+ throw new RunConflict({ code: "runBusy" });
158
+ }
159
+ }
160
+ // A run that sleeps holds no credits: it reserves again when it wakes.
161
+ if (patch.status === "sleeping") {
162
+ await releaseRun(runId);
163
+ }
123
164
  // A run that ended needs no credits held for it any more.
124
165
  if (patch.status === "done" || patch.status === "failed" || patch.status === "cancelled") {
125
166
  await releaseRun(runId);
@@ -195,6 +236,10 @@ export async function createRun(input) {
195
236
  const id = nanoid(18);
196
237
  const first = input.definition.steps[0];
197
238
  const state = { values: {}, outputs: {}, history: [], notes: {} };
239
+ // Off, nothing starts that would need the clock; a run that already waits goes on.
240
+ if (input.definition.steps.some((s) => s.type === "wait") && !(await durableRunsOn())) {
241
+ throw new ModelUnavailableError(note("waitsOff"));
242
+ }
198
243
  // A step every run passes through needs a model this runtime cannot serve: refuse before anything is held.
199
244
  const blocked = blockingMessage(await missingModelsSaid(input.definition));
200
245
  if (blocked) {
@@ -288,48 +333,89 @@ export function kick(runId) {
288
333
  })
289
334
  .catch((err) => console.error(`[run ${runId}]`, err));
290
335
  }
291
- /** Claims the run for this process and drives it; nothing when another holds it or the tenant is full. */
292
- async function take(runId, tenant) {
293
- if (active.has(runId)) {
294
- return;
336
+ /** The claim in the control database, and on the run's own row, where this process's writes need it. */
337
+ async function claimAndHold(runId, tenant) {
338
+ const generation = await claimRun(runId, tenant, await concurrencyLimit(tenant));
339
+ if (generation !== null) {
340
+ await withTenant(tenant, () => holdRun(runId, generation));
295
341
  }
296
- if (!(await claimRun(runId, tenant, await concurrencyLimit(tenant)))) {
342
+ return generation;
343
+ }
344
+ /**
345
+ * Claims the run for this process and starts driving it; nothing when another holds it, or the
346
+ * tenant or this process is full. Answers once the run is claimed: driving takes as long as the
347
+ * steps do, and the line goes on meanwhile.
348
+ */
349
+ async function take(runId, tenant) {
350
+ if (active.has(runId) || active.size >= env.runner.maxRuns) {
297
351
  return;
298
352
  }
353
+ // The slot counts from here, so takes at the same moment stay under the cap.
299
354
  const abort = new AbortController();
300
355
  active.set(runId, abort);
301
- // The heartbeat keeps the claim and hears of a cancel the web wrote while a step works.
356
+ let generation = null;
357
+ try {
358
+ generation = await claimAndHold(runId, tenant);
359
+ }
360
+ finally {
361
+ // A claim that could not be held passes on with its silence (RUNNER_STALE_MS).
362
+ if (generation === null) {
363
+ active.delete(runId);
364
+ }
365
+ }
366
+ if (generation !== null) {
367
+ void driveClaimed(runId, tenant, generation, abort);
368
+ }
369
+ }
370
+ /** Drives a claimed run to its next wait, and gives it back. */
371
+ async function driveClaimed(runId, tenant, generation, abort) {
372
+ const heldSince = Date.now();
373
+ let longHoldReported = false;
374
+ // The heartbeat keeps the claim, and hears of a cancel the web wrote or of a newer claim while a
375
+ // step works.
302
376
  const beat = setInterval(() => {
303
377
  void heartbeatRuns([runId]).catch((err) => console.warn(`[run ${runId}] heartbeat:`, err));
304
378
  // At work all along: the admin app hears it now and then, so a long step is not stuck.
305
379
  void withTenant(tenant, () => reportRun(runId, "running")).catch(() => undefined);
306
380
  void withTenant(tenant, () => loadRun(runId))
307
381
  .then((run) => {
308
- if (run && run.status !== "running") {
382
+ // A run woken from its wait is still `sleeping` for the moment its drive reserves credits.
383
+ const working = run?.status === "running" || run?.status === "sleeping";
384
+ if (run && (!working || run.claim !== generation)) {
309
385
  abort.abort();
310
386
  }
387
+ if (run && !longHoldReported && Date.now() - heldSince >= LONG_HOLD_MS) {
388
+ longHoldReported = true;
389
+ const step = stepOf(run.definition, run.cursor);
390
+ console.warn(`[run ${runId}] has held a slot for ${Math.round((Date.now() - heldSince) / 60_000)} min: tenant ${tenant}, step ${run.cursor} (${step?.type}).`);
391
+ }
311
392
  })
312
393
  .catch((err) => console.warn(`[run ${runId}] cancel check:`, err));
313
394
  }, HEARTBEAT_MS);
314
395
  beat.unref();
315
- await withTenant(tenant, () => drive(runId, abort.signal))
316
- .catch(async (err) => {
396
+ await driving
397
+ .run({ runId, generation }, () => withTenant(tenant, () => drive(runId, abort.signal)).catch(async (err) => {
398
+ if (err instanceof LostClaim) {
399
+ console.warn(`[run ${runId}] another runner holds it now; this one stops.`);
400
+ return;
401
+ }
317
402
  console.error(`[run ${runId}]`, err);
318
403
  await withTenant(tenant, async () => {
319
404
  const run = await loadRun(runId);
320
405
  const lang = run ? textLang(wizardLang(run.definition)) : "en";
321
406
  await updateRun(runId, { status: "failed", error: saidText(friendly(err), lang) });
322
407
  }).catch((e) => console.error(`[run ${runId}] marking it failed:`, e));
323
- })
408
+ }))
324
409
  .finally(async () => {
325
410
  clearInterval(beat);
326
- active.delete(runId);
327
411
  // What fails here leaves the rest of the cleanup to run.
328
412
  await withTenant(tenant, () => releaseResources(runId)).catch((err) => console.error(`[run ${runId}] releasing its resources:`, err));
329
413
  // A run the shutdown stopped goes back in line for the next runner; the rest is done for now.
330
414
  if (!stopping) {
331
415
  await restRun(runId).catch((err) => console.error(`[run ${runId}] rest:`, err));
332
416
  }
417
+ // Only now: a take that came earlier would be rested here, its resources released.
418
+ active.delete(runId);
333
419
  void withTenant(tenant, () => signalChanged(runId)).catch((err) => console.error(`[run ${runId}] signal:`, err));
334
420
  // A slot came free: the next run of the line need not wait for the poll.
335
421
  void lookAtLine();
@@ -397,6 +483,23 @@ export function startRunner() {
397
483
  }, POLL_MS);
398
484
  timer.unref();
399
485
  void lookAtLine();
486
+ const clock = setInterval(() => void lookAtClock(), env.runner.clockMs);
487
+ clock.unref();
488
+ void lookAtClock();
489
+ }
490
+ /** The clock: what came due goes in line, and the line need not wait for its next look. */
491
+ async function lookAtClock() {
492
+ if (stopping) {
493
+ return;
494
+ }
495
+ try {
496
+ if (await wakeDue()) {
497
+ await lookAtLine();
498
+ }
499
+ }
500
+ catch (err) {
501
+ console.warn("[clock]", err.message);
502
+ }
400
503
  }
401
504
  /** Stops the runs this process holds and hands them back to the line. */
402
505
  export async function stopRunner() {
@@ -646,6 +749,143 @@ async function decidePageFields(run, page, state, signal) {
646
749
  .slice(0, Math.max(0, room))
647
750
  .map((f) => f.id);
648
751
  }
752
+ async function durableRunsOn() {
753
+ return feature("durableRuns", await remoteFeatures().catch(() => null));
754
+ }
755
+ /**
756
+ * Does a step's work under its deadline. Past it the work hears `deadline` on the signal it was
757
+ * given, and the answer is a StepDeadline even if the work never ends: a hung step gives its slot
758
+ * back. A stop of the run itself passes through to the work.
759
+ */
760
+ async function withDeadline(stepType, signal, work) {
761
+ if (!(await durableRunsOn())) {
762
+ return work(signal);
763
+ }
764
+ const minutes = env.runner.stepDeadlines[stepType] ?? env.runner.stepDeadlines.default;
765
+ const limit = new AbortController();
766
+ const stop = () => limit.abort(signal.reason);
767
+ if (signal.aborted) {
768
+ stop();
769
+ }
770
+ signal.addEventListener("abort", stop, { once: true });
771
+ let timer;
772
+ const past = new Promise((_, reject) => {
773
+ timer = setTimeout(() => {
774
+ // In this order: what the abort makes the work throw comes second.
775
+ reject(new StepDeadline());
776
+ limit.abort("deadline");
777
+ }, minutes * 60_000);
778
+ timer.unref();
779
+ });
780
+ try {
781
+ return await Promise.race([work(limit.signal), past]);
782
+ }
783
+ finally {
784
+ clearTimeout(timer);
785
+ signal.removeEventListener("abort", stop);
786
+ }
787
+ }
788
+ /** A run that waits is kept past its start: its wait, and the same time to come back for it. */
789
+ function keptUntil(run, wakeAt) {
790
+ if (!run.expiresAt) {
791
+ return null;
792
+ }
793
+ const kept = wakeAt.getTime() + env.limits.resultTtlDays * 86_400_000;
794
+ return new Date(Math.max(run.expiresAt.getTime(), kept));
795
+ }
796
+ /** When a wait ends; an `until` that says no date fails the run with what it says. */
797
+ function wakeTimeOf(run, step) {
798
+ if (!step.until) {
799
+ return new Date(Date.now() + waitDurationMs(step.for ?? "1m"));
800
+ }
801
+ const said = renderTemplate(step.until, {
802
+ def: run.definition,
803
+ state: run.state,
804
+ brand: {},
805
+ }).trim();
806
+ const wakeAt = new Date(said);
807
+ if (Number.isNaN(wakeAt.getTime())) {
808
+ throw new NotedError(note("waitDateUnreadable", { date: said }));
809
+ }
810
+ return wakeAt;
811
+ }
812
+ /**
813
+ * A `wait` is reached: the run leaves every process and stays as a row. False: the time has gone
814
+ * by already, and the run goes on at once.
815
+ */
816
+ async function enterWait(run, step) {
817
+ const wakeAt = wakeTimeOf(run, step);
818
+ await emitEvent(run.id, step.id, "step_started", step.title);
819
+ if (wakeAt.getTime() <= Date.now()) {
820
+ await finishWait(run, step, await waitOver(run, step));
821
+ return false;
822
+ }
823
+ await setWake(run.id, wakeAt);
824
+ await updateRun(run.id, { status: "sleeping", wakeAt, expiresAt: keptUntil(run, wakeAt), error: null }, { status: "running" });
825
+ return true;
826
+ }
827
+ /** The wait is behind the run: its output, and the way on. */
828
+ async function waitOver(run, step) {
829
+ const state = structuredClone(run.state);
830
+ state.outputs[step.id] = { json: { waited: true }, at: new Date().toISOString() };
831
+ return { state, cursor: await advance(run, step.id, state) };
832
+ }
833
+ async function finishWait(run, step, { state, cursor }) {
834
+ await updateRun(run.id, { state, cursor, status: cursor ? "running" : "done", wakeAt: null, error: null }, { status: run.status });
835
+ await emitEvent(run.id, step.id, "step_done", step.title);
836
+ }
837
+ /** Holds the credits a run needs to go on; what it says when they are refused, else null. */
838
+ async function holdAgain(run) {
839
+ const estimate = await estimateRun(run.wizardId, run.version, run.definition, await stepsWithoutModel(run.definition));
840
+ const held = await reserveForRun(run.id, estimate.reserve, guestRun(run));
841
+ return held === true
842
+ ? null
843
+ : note(held === "guest_budget" ? "guestBudget" : "wizardRunOutCredits");
844
+ }
845
+ /**
846
+ * A run that sleeps is woken: true when it goes on, false when it does not. The row decides, not
847
+ * the wake: one that comes early or twice puts the time back and changes nothing. What else may
848
+ * end a wait slots in here.
849
+ */
850
+ async function wakeFromWait(run) {
851
+ const step = stepOf(run.definition, run.cursor);
852
+ if (step?.type !== "wait") {
853
+ await updateRun(run.id, { status: "running", wakeAt: null }, { status: "sleeping" });
854
+ return true;
855
+ }
856
+ if (run.wakeAt && run.wakeAt.getTime() > Date.now()) {
857
+ await setWake(run.id, run.wakeAt);
858
+ return false;
859
+ }
860
+ const over = await waitOver(run, step);
861
+ const next = stepOf(run.definition, over.cursor);
862
+ let refused = null;
863
+ // A sleeping run gave its hold back, and a hold lapses anyway: it holds again before it spends.
864
+ if (next && next.type !== "result") {
865
+ try {
866
+ refused = await holdAgain(run);
867
+ }
868
+ catch (err) {
869
+ // The Manage-App out of reach is no refusal: the time stays due, the clock tries again.
870
+ console.warn(`[run ${run.id}] holding credits on wake:`, err.message);
871
+ await setWake(run.id, run.wakeAt ?? new Date());
872
+ return false;
873
+ }
874
+ }
875
+ if (!refused) {
876
+ await finishWait(run, step, over);
877
+ return true;
878
+ }
879
+ // The wait is over either way: "try again" goes on from the next step and does not wait again.
880
+ await emitEvent(run.id, step.id, "error", refused);
881
+ await updateRun(run.id, {
882
+ ...over,
883
+ status: "failed",
884
+ wakeAt: null,
885
+ error: saidText(refused, textLang(wizardLang(run.definition))),
886
+ }, { status: "sleeping" });
887
+ return false;
888
+ }
649
889
  async function drive(runId, signal) {
650
890
  // The step starts afresh here: a question or a device call another process left has no one
651
891
  // waiting.
@@ -653,6 +893,12 @@ async function drive(runId, signal) {
653
893
  await clearDeviceCalls(runId);
654
894
  while (!signal.aborted) {
655
895
  const run = await loadRun(runId);
896
+ if (run?.status === "sleeping") {
897
+ if (!(await wakeFromWait(run))) {
898
+ return;
899
+ }
900
+ continue;
901
+ }
656
902
  if (run?.status !== "running") {
657
903
  return;
658
904
  }
@@ -662,7 +908,7 @@ async function drive(runId, signal) {
662
908
  if (deciding) {
663
909
  const state = structuredClone(run.state);
664
910
  try {
665
- const cursor = await decideBranch(run, deciding, state, signal);
911
+ const cursor = await withDeadline("decision", signal, (limit) => decideBranch(run, deciding, state, limit));
666
912
  if (signal.aborted) {
667
913
  return;
668
914
  }
@@ -673,6 +919,9 @@ async function drive(runId, signal) {
673
919
  if (signal.aborted) {
674
920
  return;
675
921
  }
922
+ if (err instanceof LostClaim) {
923
+ throw err;
924
+ }
676
925
  console.error(`[run ${runId} deciding ${deciding.id}]`, err);
677
926
  await failRun(run, deciding.id, err);
678
927
  return;
@@ -688,7 +937,7 @@ async function drive(runId, signal) {
688
937
  if (step.type === "page" && step.fields.some(isDecidedField) && !run.state.pages?.[step.id]) {
689
938
  const state = structuredClone(run.state);
690
939
  try {
691
- const shown = await decidePageFields(run, step, state, signal);
940
+ const shown = await withDeadline("decision", signal, (limit) => decidePageFields(run, step, state, limit));
692
941
  if (signal.aborted) {
693
942
  return;
694
943
  }
@@ -700,6 +949,9 @@ async function drive(runId, signal) {
700
949
  if (signal.aborted) {
701
950
  return;
702
951
  }
952
+ if (err instanceof LostClaim) {
953
+ throw err;
954
+ }
703
955
  console.error(`[run ${runId} fields of ${step.id}]`, err);
704
956
  await failRun(run, step.id, err);
705
957
  return;
@@ -710,6 +962,21 @@ async function drive(runId, signal) {
710
962
  await updateRun(runId, { status: "done" });
711
963
  return;
712
964
  }
965
+ if (step.type === "wait") {
966
+ try {
967
+ if (await enterWait(run, step)) {
968
+ return;
969
+ }
970
+ }
971
+ catch (err) {
972
+ if (err instanceof LostClaim) {
973
+ throw err;
974
+ }
975
+ await failRun(run, step.id, err);
976
+ return;
977
+ }
978
+ continue;
979
+ }
713
980
  if (step.type === "page" || step.type === "review") {
714
981
  await updateRun(runId, { status: "waiting_input" });
715
982
  // A step that ran is over and the next one is the person's: a phone in a pocket hears it.
@@ -726,29 +993,32 @@ async function drive(runId, signal) {
726
993
  const space = await loadSpace(run);
727
994
  const state = structuredClone(run.state);
728
995
  try {
729
- const ctx = await makeContext(run, space, state, signal);
730
- // A guest's answers are checked once before any model works on them, and what a step
731
- // wrote for a guest before it is kept (docs/plans/guest-content-guards.md).
732
- const guest = guestRun(run) && (await guestChecksOn());
733
- if (guest) {
734
- const answers = [answersAsText(ctx.scope), ...Object.values(state.notes)].join("\n");
735
- const hash = createHash("sha256").update(answers).digest("base64url").slice(0, 24);
736
- if (state.inputChecked !== hash) {
737
- await checkGuestInput({ text: answers, call: ctx.call, signal });
738
- state.inputChecked = hash;
996
+ const output = await withDeadline(step.type, signal, async (limit) => {
997
+ const ctx = await makeContext(run, space, state, limit);
998
+ // A guest's answers are checked once before any model works on them, and what a step
999
+ // wrote for a guest before it is kept (docs/plans/guest-content-guards.md).
1000
+ const guest = guestRun(run) && (await guestChecksOn());
1001
+ if (guest) {
1002
+ const answers = [answersAsText(ctx.scope), ...Object.values(state.notes)].join("\n");
1003
+ const hash = createHash("sha256").update(answers).digest("base64url").slice(0, 24);
1004
+ if (state.inputChecked !== hash) {
1005
+ await checkGuestInput({ text: answers, call: ctx.call, signal: limit });
1006
+ state.inputChecked = hash;
1007
+ }
739
1008
  }
740
- }
741
- const output = await runAutomaticStep(step, ctx);
1009
+ const made = await runAutomaticStep(step, ctx);
1010
+ if (guest && !limit.aborted) {
1011
+ await checkGuestText({
1012
+ text: made.text || (made.json ? JSON.stringify(made.json) : ""),
1013
+ call: ctx.call,
1014
+ signal: limit,
1015
+ });
1016
+ }
1017
+ return made;
1018
+ });
742
1019
  if (signal.aborted) {
743
1020
  return;
744
1021
  }
745
- if (guest) {
746
- await checkGuestText({
747
- text: output.text || (output.json ? JSON.stringify(output.json) : ""),
748
- call: ctx.call,
749
- signal,
750
- });
751
- }
752
1022
  await syncRunCost(runId);
753
1023
  state.outputs[step.id] = output;
754
1024
  delete state.notes[step.id];
@@ -765,6 +1035,9 @@ async function drive(runId, signal) {
765
1035
  if (signal.aborted) {
766
1036
  return;
767
1037
  }
1038
+ if (err instanceof LostClaim) {
1039
+ throw err;
1040
+ }
768
1041
  console.error(`[run ${runId} step ${step.id}]`, err);
769
1042
  await noteFreeTierRefusal(err);
770
1043
  await failRun(run, step.id, err);
@@ -847,7 +1120,7 @@ export async function submitPage(runId, stepId, input) {
847
1120
  }
848
1121
  state.history.push(stepId);
849
1122
  const cursor = await advance(run, stepId, state);
850
- await updateRun(runId, { state, cursor, status: "running", error: null });
1123
+ await updateRun(runId, { state, cursor, status: "running", error: null }, run);
851
1124
  kick(runId);
852
1125
  }
853
1126
  /** Edited data of a json step is kept up to this size. */
@@ -889,7 +1162,18 @@ export async function editOutput(runId, stepId, data) {
889
1162
  }
890
1163
  const state = structuredClone(run.state);
891
1164
  state.outputs[stepId] = editedJson(run.definition, stepId, output, data);
892
- await updateRun(runId, { state });
1165
+ await updateRun(runId, { state }, run);
1166
+ }
1167
+ /**
1168
+ * Keeps something a person's request added to the run's state, nothing else about the run moves.
1169
+ * False: the run moved since `run` was read, and nothing is written.
1170
+ */
1171
+ export async function writeRunState(run, state) {
1172
+ const result = await db
1173
+ .update(schema.run)
1174
+ .set({ state, rev: sql `${schema.run.rev} + 1` })
1175
+ .where(and(eq(schema.run.id, run.id), eq(schema.run.rev, run.rev)));
1176
+ return result.rowsAffected > 0;
893
1177
  }
894
1178
  export async function reviewStep(runId, stepId, action) {
895
1179
  const run = await requireWaiting(runId, stepId);
@@ -917,7 +1201,7 @@ export async function reviewStep(runId, stepId, action) {
917
1201
  }
918
1202
  state.history.push(stepId);
919
1203
  const cursor = await advance(run, stepId, state);
920
- await updateRun(runId, { state, cursor, status: "running", error: null });
1204
+ await updateRun(runId, { state, cursor, status: "running", error: null }, run);
921
1205
  kick(runId);
922
1206
  return;
923
1207
  }
@@ -932,14 +1216,13 @@ export async function reviewStep(runId, stepId, action) {
932
1216
  else {
933
1217
  delete state.redo?.[action.target];
934
1218
  }
935
- await updateRun(runId, { state, cursor: action.target, status: "running", error: null });
1219
+ await updateRun(runId, { state, cursor: action.target, status: "running", error: null }, run);
936
1220
  await emitEvent(runId, action.target, "info", "Wird neu erstellt …");
937
1221
  kick(runId);
938
1222
  }
939
1223
  export async function goBack(runId) {
940
1224
  const run = await loadRun(runId);
941
- if (!run ||
942
- (run.status !== "waiting_input" && run.status !== "done" && run.status !== "failed")) {
1225
+ if (!run || !CAN_GO_BACK.has(run.status)) {
943
1226
  throw new RunConflict({ code: "runBusy" });
944
1227
  }
945
1228
  const state = structuredClone(run.state);
@@ -949,19 +1232,26 @@ export async function goBack(runId) {
949
1232
  }
950
1233
  // A decision that failed belongs to the step left behind.
951
1234
  delete state.deciding;
952
- await updateRun(runId, { state, cursor: previous, status: "waiting_input", error: null });
1235
+ await updateRun(runId, { state, cursor: previous, status: "waiting_input", error: null }, run);
953
1236
  }
954
1237
  export async function retry(runId) {
955
1238
  const run = await loadRun(runId);
956
1239
  if (run?.status !== "failed") {
957
1240
  throw new RunConflict("Nothing to retry");
958
1241
  }
959
- await updateRun(runId, { status: "running", error: null });
1242
+ // A failure gave the run's hold back: a refusal on wake must not be walked around here.
1243
+ const refused = (await durableRunsOn()) ? await holdAgain(run) : null;
1244
+ if (refused) {
1245
+ throw new RunConflict(refused);
1246
+ }
1247
+ await updateRun(runId, { status: "running", error: null }, run);
960
1248
  kick(runId);
961
1249
  }
962
1250
  export async function cancel(runId) {
963
1251
  active.get(runId)?.abort();
964
- await updateRun(runId, { status: "cancelled" });
1252
+ await updateRun(runId, { status: "cancelled", wakeAt: null });
1253
+ // After the row: a crash in between gives a wake that finds the run over, never a lost cancel.
1254
+ await setWake(runId, null);
965
1255
  }
966
1256
  // --- view --------------------------------------------------------------------
967
1257
  /** The formats a deliverable can really be downloaded in: a still widget has no video. */
@@ -1092,6 +1382,7 @@ export async function runView(run, brand, hide = new Set()) {
1092
1382
  return {
1093
1383
  id: run.id,
1094
1384
  status: run.status,
1385
+ wakeAt: run.status === "sleeping" ? (run.wakeAt?.toISOString() ?? null) : null,
1095
1386
  mode: run.mode,
1096
1387
  wizard: {
1097
1388
  title: def.title,
@@ -1109,7 +1400,8 @@ export async function runView(run, brand, hide = new Set()) {
1109
1400
  results: run.state.translated?.[run.lang] ?? {},
1110
1401
  }
1111
1402
  : null,
1112
- talk: await talkAllowed(run),
1403
+ // Nobody to talk to while it sleeps, and nothing to say.
1404
+ talk: run.status !== "sleeping" && (await talkAllowed(run)),
1113
1405
  step,
1114
1406
  answered: run.state.history.map((id) => stepOf(def, id)).filter((s) => Boolean(s)),
1115
1407
  values: run.state.values,
@@ -1130,7 +1422,7 @@ export async function runView(run, brand, hide = new Set()) {
1130
1422
  .filter(([, o]) => o)),
1131
1423
  shown,
1132
1424
  progress: { done: run.status === "done" ? def.steps.length : index, total: def.steps.length },
1133
- canBack: run.state.history.length > 0 && run.status !== "running",
1425
+ canBack: run.state.history.length > 0 && CAN_GO_BACK.has(run.status),
1134
1426
  error: run.error,
1135
1427
  // A step's own words as it starts ("working") are the wizard's: in its translation too.
1136
1428
  events: (await recentEvents(run.id, 0, 30)).map((ev) => memory?.[ev.message] && !ev.note ? { ...ev, message: memory[ev.message].text } : ev),
@@ -31,6 +31,11 @@ const num = (key, fallback) => {
31
31
  const v = Number(process.env[key]);
32
32
  return Number.isFinite(v) && v > 0 ? v : fallback;
33
33
  };
34
+ /** `a=1,b=2.5`: positive numbers by name; anything else is left out. */
35
+ const minutesByName = (key) => Object.fromEntries(list(key)
36
+ .map((item) => item.split("="))
37
+ .map(([name, value]) => [name?.trim(), Number(value)])
38
+ .filter(([name, value]) => name && Number.isFinite(value) && value > 0));
34
39
  const dataDir = resolve(str("DATA_DIR", "data"));
35
40
  /**
36
41
  * Signs cookies and links and derives the store's encryption key. A runtime that runs alone
@@ -97,6 +102,19 @@ export const env = {
97
102
  * nothing knows the runner stopped taking runs. Empty = no ping.
98
103
  */
99
104
  heartbeatUrl: str("HEARTBEAT_URL"),
105
+ /** The runs one process drives at once; the rest stay in line for its next free slot. */
106
+ maxRuns: num("RUNNER_MAX_RUNS", 16),
107
+ /** How often the clock looks for runs whose wait is over. */
108
+ clockMs: num("RUNNER_CLOCK_MS", 60_000),
109
+ /**
110
+ * The longest a step may work, in minutes. `RUNNER_STEP_DEADLINES=default=480,agent=240`: per
111
+ * step type, `default` for the rest. Generous until real step lengths are in.
112
+ */
113
+ stepDeadlines: {
114
+ default: 8 * 60,
115
+ "motion-graphics": 12 * 60,
116
+ ...minutesByName("RUNNER_STEP_DEADLINES"),
117
+ },
100
118
  },
101
119
  appUrl,
102
120
  /**