wizards 0.2.55 → 0.2.57

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 (123) hide show
  1. package/README.md +2 -2
  2. package/apps/runtime/dist/cli/autostart.js +1 -1
  3. package/apps/runtime/dist/cli/machine.js +5 -48
  4. package/apps/runtime/dist/cli/report.js +1 -1
  5. package/apps/runtime/dist/db/control-schema.js +13 -0
  6. package/apps/runtime/dist/db/migrations/control/0008_runner.sql +8 -0
  7. package/apps/runtime/dist/db/migrations/control/meta/0008_snapshot.json +505 -0
  8. package/apps/runtime/dist/db/migrations/control/meta/_journal.json +7 -0
  9. package/apps/runtime/dist/db/migrations/tenant/0014_run_answer.sql +2 -0
  10. package/apps/runtime/dist/db/migrations/tenant/meta/0014_snapshot.json +3154 -0
  11. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +7 -0
  12. package/apps/runtime/dist/db/schema.js +4 -0
  13. package/apps/runtime/dist/docs/dev/index.md +4 -4
  14. package/apps/runtime/dist/docs/dev/plugins/connections.md +4 -3
  15. package/apps/runtime/dist/docs/dev/plugins/events.md +1 -0
  16. package/apps/runtime/dist/docs/dev/plugins/examples.md +10 -9
  17. package/apps/runtime/dist/docs/dev/plugins/index.md +4 -3
  18. package/apps/runtime/dist/docs/dev/plugins/layout.md +2 -1
  19. package/apps/runtime/dist/docs/dev/plugins/meta.json +0 -1
  20. package/apps/runtime/dist/docs/dev/plugins/quick-start.md +4 -3
  21. package/apps/runtime/dist/docs/dev/plugins/reference.md +36 -14
  22. package/apps/runtime/dist/docs/dev/plugins/reloading.md +5 -5
  23. package/apps/runtime/dist/docs/dev/plugins/routes.md +30 -6
  24. package/apps/runtime/dist/docs/dev/plugins/runners.md +15 -10
  25. package/apps/runtime/dist/docs/dev/plugins/server.md +16 -7
  26. package/apps/runtime/dist/docs/dev/plugins/shipping.md +4 -26
  27. package/apps/runtime/dist/docs/dev/plugins/space.md +66 -53
  28. package/apps/runtime/dist/docs/dev/plugins/starters.md +10 -7
  29. package/apps/runtime/dist/docs/dev/plugins/studio.md +33 -12
  30. package/apps/runtime/dist/docs/dev/plugins/styling.md +19 -9
  31. package/apps/runtime/dist/docs/dev/plugins/tables.md +6 -4
  32. package/apps/runtime/dist/docs/dev/plugins/tools.md +22 -12
  33. package/apps/runtime/dist/docs/dev/wizard-format.md +3 -2
  34. package/apps/runtime/dist/docs/user/ai-apps.md +3 -1
  35. package/apps/runtime/dist/docs/user/assistant.md +5 -3
  36. package/apps/runtime/dist/docs/user/build-a-wizard.md +14 -2
  37. package/apps/runtime/dist/docs/user/command-line.md +16 -14
  38. package/apps/runtime/dist/docs/user/connectors.md +17 -12
  39. package/apps/runtime/dist/docs/user/data.md +14 -9
  40. package/apps/runtime/dist/docs/user/first-start.md +13 -6
  41. package/apps/runtime/dist/docs/user/index.md +2 -1
  42. package/apps/runtime/dist/docs/user/install.md +19 -11
  43. package/apps/runtime/dist/docs/user/models.md +44 -22
  44. package/apps/runtime/dist/docs/user/plugins.md +9 -4
  45. package/apps/runtime/dist/docs/user/run.md +14 -9
  46. package/apps/runtime/dist/docs/user/server.md +7 -5
  47. package/apps/runtime/dist/docs/user/space.md +15 -8
  48. package/apps/runtime/dist/docs/user/steps.md +33 -13
  49. package/apps/runtime/dist/docs/user/test-and-share.md +41 -25
  50. package/apps/runtime/dist/docs/user/troubleshooting.md +15 -7
  51. package/apps/runtime/dist/docs/user/wordpress.md +59 -49
  52. package/apps/runtime/dist/engine/asks.js +53 -33
  53. package/apps/runtime/dist/engine/events.js +45 -1
  54. package/apps/runtime/dist/engine/owner.js +32 -0
  55. package/apps/runtime/dist/engine/runner.js +131 -97
  56. package/apps/runtime/dist/env.js +25 -3
  57. package/apps/runtime/dist/harness/apple.js +36 -21
  58. package/apps/runtime/dist/harness/claude.js +1 -1
  59. package/apps/runtime/dist/harness/model.js +2 -2
  60. package/apps/runtime/dist/index.js +13 -2
  61. package/apps/runtime/dist/limits.js +7 -4
  62. package/apps/runtime/dist/media/conversation.js +6 -5
  63. package/apps/runtime/dist/model-errors.js +22 -1
  64. package/apps/runtime/dist/models.js +30 -7
  65. package/apps/runtime/dist/plugins/pro-keys.js +1 -1
  66. package/apps/runtime/dist/plugins/pro-state.js +1 -1
  67. package/apps/runtime/dist/plugins/pro.js +1 -1
  68. package/apps/runtime/dist/plugins/runs.js +20 -15
  69. package/apps/runtime/dist/render/browser-path.js +54 -0
  70. package/apps/runtime/dist/routes/runs.js +67 -38
  71. package/apps/runtime/dist/routes/studio.js +7 -3
  72. package/apps/runtime/dist/services/api.js +3 -1
  73. package/apps/runtime/dist/services/package-file.js +8 -8
  74. package/apps/runtime/dist/services/runs.js +7 -8
  75. package/apps/runtime/dist/tenants/control.js +85 -7
  76. package/apps/runtime/dist/update.js +1 -1
  77. package/apps/web/dist/assets/AboutDialog-DEZCEQlN.js +1 -0
  78. package/apps/web/dist/assets/{ChangelogDialog-BLmJABe4.js → ChangelogDialog-CgnnJj4G.js} +1 -1
  79. package/apps/web/dist/assets/{ChatView-YAiOT6mt.js → ChatView-BnnKdwk4.js} +1 -1
  80. package/apps/web/dist/assets/{EditorPage-C0zMXwlF.js → EditorPage-CeDWjq4z.js} +2 -2
  81. package/apps/web/dist/assets/{FlowPreview-B4lbmeha.js → FlowPreview-Du028FI3.js} +1 -1
  82. package/apps/web/dist/assets/{Harness-_riwRD-c.js → Harness-CEPy4MEp.js} +1 -1
  83. package/apps/web/dist/assets/{Marketplace-B0Nki6J6.js → Marketplace-ms58DQJ9.js} +2 -2
  84. package/apps/web/dist/assets/{NewWizardPage-DkvGgROv.js → NewWizardPage-CEQSNXeZ.js} +1 -1
  85. package/apps/web/dist/assets/{ProjectPage-CFRIPset.js → ProjectPage-CXDpKoK2.js} +1 -1
  86. package/apps/web/dist/assets/{PublicRunner-QJuQB7ff.js → PublicRunner-DMmtmzBX.js} +1 -1
  87. package/apps/web/dist/assets/{ReadOnly-DiOfNtVr.js → ReadOnly-zQecD9OB.js} +1 -1
  88. package/apps/web/dist/assets/{RunDrawer-LjUX3yIv.js → RunDrawer-BIojYB0g.js} +1 -1
  89. package/apps/web/dist/assets/{RunnerView-DkJVfUeG.js → RunnerView-D8OGEoMl.js} +1 -1
  90. package/apps/web/dist/assets/SettingsPage-BlMZL4_d.js +1 -0
  91. package/apps/web/dist/assets/SetupPage-Doz9T3kv.js +1 -0
  92. package/apps/web/dist/assets/{SharePage-CCimr8XT.js → SharePage-DOJXdsyi.js} +1 -1
  93. package/apps/web/dist/assets/{brand-CwLcF9JR.js → brand-DIKyySmf.js} +1 -1
  94. package/apps/web/dist/assets/changelog-B1jhC7Fv.js +1 -0
  95. package/apps/web/dist/assets/{circle-alert-BEDKtkJy.js → circle-alert-B9b9Vb9k.js} +1 -1
  96. package/apps/web/dist/assets/{esm-BCwno33N.js → esm-D6fM9MdG.js} +1 -1
  97. package/apps/web/dist/assets/{index-Dq-Wj6Yo.js → index-nfRuCdVt.js} +4 -4
  98. package/apps/web/dist/assets/{lock-Ce2ofIWG.js → lock-BNvsUKTg.js} +1 -1
  99. package/apps/web/dist/assets/session-CSbo-pmx.js +1 -0
  100. package/apps/web/dist/assets/{settings-menu-DX0JnPBR.js → settings-menu-BGfn4LJE.js} +1 -1
  101. package/apps/web/dist/assets/{ui-mkL5nF_f.js → ui-FW7ypPI6.js} +1 -1
  102. package/apps/web/dist/assets/{upload-BfrqabpO.js → upload-MQ_24gSb.js} +1 -1
  103. package/apps/web/dist/assets/{volume-2-C3GeMqc-.js → volume-2-B1mj20eS.js} +1 -1
  104. package/apps/web/dist/index.html +6 -6
  105. package/apps/web/dist/install.sh +2 -2
  106. package/apps/web/dist/mcp/flow.html +1 -1
  107. package/modules/calls/dist/client.css +1 -1
  108. package/modules/sms/dist/client.css +1 -1
  109. package/modules/whatsapp/dist/client.css +1 -1
  110. package/node_modules/@engenty-wizards/shared/dist/definition.js +1 -0
  111. package/node_modules/@engenty-wizards/shared/dist/engenty/data-tables/columns.js +1 -0
  112. package/node_modules/@engenty-wizards/shared/dist/fit.js +1 -0
  113. package/node_modules/@engenty-wizards/shared/dist/run.d.ts +152 -2
  114. package/node_modules/@engenty-wizards/shared/dist/run.js +135 -1
  115. package/node_modules/@engenty-wizards/shared/dist/store.js +1 -0
  116. package/node_modules/@engenty-wizards/shared/dist/surface.js +1 -0
  117. package/package.json +2 -2
  118. package/apps/runtime/dist/docs/dev/plugins/pro-modules.md +0 -59
  119. package/apps/web/dist/assets/AboutDialog-BelD7JCn.js +0 -1
  120. package/apps/web/dist/assets/SettingsPage-BKZ1KLfP.js +0 -1
  121. package/apps/web/dist/assets/SetupPage-Rqlo16Lk.js +0 -1
  122. package/apps/web/dist/assets/changelog-Bg5ZBu5p.js +0 -1
  123. package/apps/web/dist/assets/session-BuVghS-e.js +0 -1
@@ -1,62 +1,82 @@
1
- import { eq } from "drizzle-orm";
1
+ import { eq, sql } from "drizzle-orm";
2
2
  import { nanoid } from "nanoid";
3
3
  import { db, schema } from "../db/client.js";
4
4
  import { signalChanged } from "./events.js";
5
5
  import { pushRun } from "./push.js";
6
6
  /** How long a step waits for the person before it goes on without them. */
7
7
  const ASK_TIMEOUT_MS = 15 * 60_000;
8
- /** Runs nobody watches (an MCP client drives them): a question there would wait for no one. */
9
- export const unattended = new Set();
10
- const waiting = new Map();
8
+ /** How often the waiting step looks for the answer in the row. */
9
+ const ASK_POLL_MS = 1000;
11
10
  async function setAsk(runId, ask) {
12
- await db.update(schema.run).set({ ask, updatedAt: new Date() }).where(eq(schema.run.id, runId));
11
+ await db
12
+ .update(schema.run)
13
+ .set({ ask, answer: null, updatedAt: new Date() })
14
+ .where(eq(schema.run.id, runId));
13
15
  signalChanged(runId);
14
16
  }
15
17
  /**
16
18
  * Puts a question to the person and waits. The run stays "running": the step is in the middle
17
- * of its work and goes on with the answer. One question per run at a time.
19
+ * of its work and goes on with the answer. One question per run at a time. The question and the
20
+ * answer go through the run's row: the web that takes the answer need not be the process that
21
+ * asked.
18
22
  */
19
23
  export async function askPerson(runId, ask, signal) {
20
- if (waiting.has(runId)) {
24
+ const open = await db.query.run.findFirst({
25
+ where: eq(schema.run.id, runId),
26
+ columns: { ask: true },
27
+ });
28
+ if (open?.ask) {
21
29
  throw new Error("The wizard is already waiting for the person.");
22
30
  }
23
31
  const full = { ...ask, id: nanoid(10), at: new Date().toISOString() };
24
- const result = new Promise((resolve) => {
25
- const finish = (r) => {
26
- clearTimeout(timer);
27
- signal.removeEventListener("abort", onAbort);
28
- resolve(r);
29
- };
30
- const onAbort = () => finish({ type: "skip" });
31
- const timer = setTimeout(() => finish({ type: "timeout" }), ASK_TIMEOUT_MS);
32
- signal.addEventListener("abort", onAbort, { once: true });
33
- waiting.set(runId, { ask: full, settle: finish });
34
- });
35
32
  await setAsk(runId, full);
36
33
  void pushRun(runId, "asks");
34
+ const until = Date.now() + ASK_TIMEOUT_MS;
37
35
  try {
38
- return await result;
36
+ while (!signal.aborted) {
37
+ if (Date.now() >= until) {
38
+ return { type: "timeout" };
39
+ }
40
+ const row = await db.query.run.findFirst({
41
+ where: eq(schema.run.id, runId),
42
+ columns: { answer: true },
43
+ });
44
+ if (row?.answer?.askId === full.id) {
45
+ return row.answer.answer;
46
+ }
47
+ await new Promise((resolve) => {
48
+ const timer = setTimeout(done, ASK_POLL_MS);
49
+ function done() {
50
+ clearTimeout(timer);
51
+ signal.removeEventListener("abort", done);
52
+ resolve();
53
+ }
54
+ signal.addEventListener("abort", done, { once: true });
55
+ });
56
+ }
57
+ return { type: "skip" };
39
58
  }
40
59
  finally {
41
- waiting.delete(runId);
42
60
  await setAsk(runId, null).catch(() => undefined);
43
61
  }
44
62
  }
45
63
  /** The question a run is waiting on, if any. */
46
- export function pendingAsk(runId) {
47
- return waiting.get(runId)?.ask ?? null;
64
+ export async function pendingAsk(runId) {
65
+ const row = await db.query.run.findFirst({
66
+ where: eq(schema.run.id, runId),
67
+ columns: { ask: true },
68
+ });
69
+ return row?.ask ?? null;
48
70
  }
49
- export function answerAsk(runId, askId, answer) {
50
- const entry = waiting.get(runId);
51
- if (!entry || entry.ask.id !== askId) {
52
- return false;
53
- }
54
- entry.settle(answer);
55
- return true;
71
+ /** Leaves the answer for the waiting step; false when that question is no longer open. */
72
+ export async function answerAsk(runId, askId, answer) {
73
+ const result = await db
74
+ .update(schema.run)
75
+ .set({ answer: { askId, answer } })
76
+ .where(sql `${schema.run.id} = ${runId} AND json_extract(${schema.run.ask}, '$.id') = ${askId}`);
77
+ return result.rowsAffected > 0;
56
78
  }
57
- /** A question left in the row by a server that stopped: nobody is waiting for it any more. */
79
+ /** A run a runner takes starts its step afresh: a question left in the row has no one waiting. */
58
80
  export async function clearStaleAsk(runId) {
59
- if (!waiting.has(runId)) {
60
- await db.update(schema.run).set({ ask: null }).where(eq(schema.run.id, runId));
61
- }
81
+ await db.update(schema.run).set({ ask: null, answer: null }).where(eq(schema.run.id, runId));
62
82
  }
@@ -1,7 +1,7 @@
1
1
  import { AsyncResource } from "node:async_hooks";
2
2
  import { EventEmitter } from "node:events";
3
3
  import { noteText } from "@engenty-wizards/shared/run";
4
- import { and, desc, eq, gt } from "drizzle-orm";
4
+ import { and, desc, eq, gt, sql } from "drizzle-orm";
5
5
  import { db, schema } from "../db/client.js";
6
6
  const bus = new EventEmitter();
7
7
  bus.setMaxListeners(0);
@@ -42,6 +42,50 @@ export function subscribe(runId, listener) {
42
42
  bus.on(runId, bound);
43
43
  return () => bus.off(runId, bound);
44
44
  }
45
+ /** How often a watcher looks at the row for what another process changed. */
46
+ const WATCH_POLL_MS = 1000;
47
+ /**
48
+ * Tells of every change on a run: at once when this process made it, within a second when the
49
+ * runner (another process) wrote to the row or added an event. Call it in the run's tenant.
50
+ */
51
+ export function watchRun(runId, listener) {
52
+ const unsubscribe = subscribe(runId, listener);
53
+ let last = null;
54
+ let busy = false;
55
+ const look = async () => {
56
+ if (busy) {
57
+ return;
58
+ }
59
+ busy = true;
60
+ try {
61
+ const [row] = await db
62
+ .select({
63
+ updatedAt: schema.run.updatedAt,
64
+ event: sql `(select max(${schema.runEvent.id}) from ${schema.runEvent} where ${schema.runEvent.runId} = ${runId})`,
65
+ })
66
+ .from(schema.run)
67
+ .where(eq(schema.run.id, runId));
68
+ const mark = row ? `${row.updatedAt.getTime()}:${row.event ?? 0}` : null;
69
+ if (last !== null && mark !== last) {
70
+ listener();
71
+ }
72
+ last = mark;
73
+ }
74
+ catch {
75
+ // The next look tells.
76
+ }
77
+ finally {
78
+ busy = false;
79
+ }
80
+ };
81
+ const timer = setInterval(() => void look(), WATCH_POLL_MS);
82
+ timer.unref();
83
+ void look();
84
+ return () => {
85
+ clearInterval(timer);
86
+ unsubscribe();
87
+ };
88
+ }
45
89
  export async function recentEvents(runId, afterId = 0, limit = 40) {
46
90
  const rows = await db
47
91
  .select()
@@ -0,0 +1,32 @@
1
+ import { ownerUrl } from "../tenants/control.js";
2
+ /**
3
+ * Hands a request on to the runner holding the run — what only the process with the run's
4
+ * browser can answer. The runner serves the same routes and checks the same cookie; the caller's
5
+ * headers go along. Null: nobody holds the run, or the runner named no address (RUNNER_URL).
6
+ */
7
+ export async function fromOwner(c, runId) {
8
+ const base = await ownerUrl(runId);
9
+ if (!base) {
10
+ return null;
11
+ }
12
+ const here = new URL(c.req.url);
13
+ const headers = new Headers(c.req.raw.headers);
14
+ headers.delete("host");
15
+ headers.delete("content-length");
16
+ const method = c.req.method;
17
+ const body = method === "GET" || method === "HEAD" ? undefined : await c.req.raw.arrayBuffer();
18
+ try {
19
+ const res = await fetch(`${base}${here.pathname}${here.search}`, {
20
+ method,
21
+ headers,
22
+ body,
23
+ redirect: "manual",
24
+ signal: AbortSignal.timeout(15_000),
25
+ });
26
+ return new Response(res.body, { status: res.status, headers: res.headers });
27
+ }
28
+ catch (err) {
29
+ console.error(`[run ${runId}] the runner did not answer:`, err);
30
+ return null;
31
+ }
32
+ }
@@ -1,5 +1,7 @@
1
1
  import { marginOf, } from "@engenty-wizards/shared/decision";
2
2
  import { branchValues, cardsFromData, conditionsOf, dataRef, followRules, formatsFor, isDecidedField, LIST_FORMATS, listRef, loopKey, MAX_SHOWN_FIELDS, optionsFromData, otherwiseOf, pageNeeds, whenHolds, wizardLang, } from "@engenty-wizards/shared/definition";
3
+ import { noteText, } from "@engenty-wizards/shared/run";
4
+ import { CONVERSATION_RUNNERS, DEFAULT_RUNNER_SETTINGS } from "@engenty-wizards/shared/runners";
3
5
  import { eq } from "drizzle-orm";
4
6
  import { nanoid } from "nanoid";
5
7
  import { connectionViews } from "../connectors/index.js";
@@ -10,14 +12,15 @@ import { env } from "../env.js";
10
12
  import { saveAsset } from "../files/storage.js";
11
13
  import { managed, tenantInfo } from "../manage.js";
12
14
  import { hasFfmpeg } from "../media/ffmpeg.js";
15
+ import { NotedError, noteOf } from "../model-errors.js";
13
16
  import { conversationAvailable, freeTierRefusal, freeTierText, ModelUnavailableError, noteFreeTierRefusal, } from "../models.js";
14
17
  import { runEnded } from "../plugins/events.js";
15
18
  import { projectFiles } from "../services/project-files.js";
16
19
  import { projectProfile } from "../services/projects.js";
17
20
  import { listRows, scopeOf } from "../store/index.js";
18
- import { activeRuns, indexRun, markRunActive } from "../tenants/control.js";
21
+ import { claimRun, disownRuns, heartbeatRuns, indexRun, restRun, waitingRuns, wakeRun, } from "../tenants/control.js";
19
22
  import { currentTenant } from "../tenants/tenant.js";
20
- import { askPerson, clearStaleAsk, unattended } from "./asks.js";
23
+ import { askPerson, clearStaleAsk } from "./asks.js";
21
24
  import { decide } from "./decide.js";
22
25
  import { emitEvent, recentEvents, signalChanged } from "./events.js";
23
26
  import { readPageInput } from "./input.js";
@@ -27,13 +30,13 @@ import { releaseResources, resourcesFor } from "./resources.js";
27
30
  import { runAutomaticStep } from "./steps.js";
28
31
  import { answersAsText, resolveRef } from "./template.js";
29
32
  import { StepError } from "./types.js";
30
- /** A command the run cannot take in its current state. */
31
- export class RunConflict extends Error {
33
+ /** A command the run cannot take in its current state; a note where the person may read it. */
34
+ export class RunConflict extends NotedError {
32
35
  }
33
- export class RunInputError extends Error {
36
+ export class RunInputError extends NotedError {
34
37
  errors;
35
38
  constructor(errors) {
36
- super("Bitte die markierten Felder prüfen.");
39
+ super({ code: "checkFields" });
37
40
  this.errors = errors;
38
41
  }
39
42
  }
@@ -42,10 +45,15 @@ export class NoCreditsError extends Error {
42
45
  super("Dieser Wizard hat gerade kein Guthaben mehr. Bitte später erneut versuchen.");
43
46
  }
44
47
  }
48
+ /** The runs this process drives right now, with the handle that stops each. */
45
49
  const active = new Map();
46
- // --- a tenant's runs that work at the same time ---------------------------------
47
- // Runs beyond the limit wait in line; nothing is refused.
48
- const slots = new Map();
50
+ // --- the line ------------------------------------------------------------------
51
+ // A run that wants work is marked in the control database (`wakeRun`); a runner claims it there,
52
+ // so several processes share one line. A tenant's runs beyond its limit stay in line; nothing is
53
+ // refused. See docs/plans/runner-process.md.
54
+ /** How often a runner looks at the line, and how often it reports on the runs it holds. */
55
+ const POLL_MS = 2000;
56
+ const HEARTBEAT_MS = 10_000;
49
57
  async function concurrencyLimit(tenant) {
50
58
  if (!managed) {
51
59
  return env.limits.concurrentRuns;
@@ -53,45 +61,6 @@ async function concurrencyLimit(tenant) {
53
61
  const info = await tenantInfo(tenant).catch(() => null);
54
62
  return info?.limits.concurrentRuns || env.limits.concurrentRuns;
55
63
  }
56
- async function acquireSlot(tenant, signal) {
57
- const limit = await concurrencyLimit(tenant);
58
- let slot = slots.get(tenant);
59
- if (!slot) {
60
- slot = { busy: 0, waiting: [] };
61
- slots.set(tenant, slot);
62
- }
63
- if (slot.busy < limit) {
64
- slot.busy++;
65
- return true;
66
- }
67
- const queue = slot.waiting;
68
- return new Promise((resolve) => {
69
- const go = () => {
70
- signal.removeEventListener("abort", stop);
71
- resolve(true);
72
- };
73
- const stop = () => {
74
- queue.splice(queue.indexOf(go), 1);
75
- resolve(false);
76
- };
77
- queue.push(go);
78
- signal.addEventListener("abort", stop, { once: true });
79
- });
80
- }
81
- function releaseSlot(tenant) {
82
- const slot = slots.get(tenant);
83
- if (!slot) {
84
- return;
85
- }
86
- const next = slot.waiting.shift();
87
- if (next) {
88
- // The slot passes straight to the next run in line.
89
- next();
90
- }
91
- else {
92
- slot.busy--;
93
- }
94
- }
95
64
  async function loadRun(runId) {
96
65
  return db.query.run.findFirst({ where: eq(schema.run.id, runId) });
97
66
  }
@@ -157,6 +126,16 @@ function friendly(err) {
157
126
  }
158
127
  return `Dieser Schritt ist fehlgeschlagen: ${msg.slice(0, 300)}`;
159
128
  }
129
+ /**
130
+ * A step that failed ends the run. A failure with a note (Apple Intelligence's) goes into the log
131
+ * as that note, so a runner shows it in its language; the run's error is in the wizard's.
132
+ */
133
+ async function failRun(run, stepId, err) {
134
+ const note = noteOf(err);
135
+ const message = note ? noteText(note, wizardLang(run.definition)) : friendly(err);
136
+ await emitEvent(run.id, stepId, "error", note ?? message);
137
+ await updateRun(run.id, { status: "failed", error: message });
138
+ }
160
139
  // --- creating & driving ------------------------------------------------------
161
140
  export async function createRun(input) {
162
141
  const id = nanoid(18);
@@ -185,6 +164,7 @@ export async function createRun(input) {
185
164
  userId: input.userId ?? null,
186
165
  ipHash: input.ipHash ?? null,
187
166
  origin: input.origin ?? null,
167
+ unattended: input.unattended ?? false,
188
168
  status: first.type === "page" ? "waiting_input" : "running",
189
169
  cursor: first.id,
190
170
  state,
@@ -199,37 +179,97 @@ export async function createRun(input) {
199
179
  }
200
180
  return id;
201
181
  }
182
+ /**
183
+ * Puts the run to work: in line in the control database, and — when this process is a runner —
184
+ * taken at once if the tenant has a slot. The web alone leaves it for a runner's next look.
185
+ */
202
186
  export function kick(runId) {
187
+ const tenant = currentTenant();
188
+ void wakeRun(runId)
189
+ .then(() => {
190
+ if (env.role !== "web") {
191
+ return take(runId, tenant);
192
+ }
193
+ })
194
+ .catch((err) => console.error(`[run ${runId}]`, err));
195
+ }
196
+ /** Claims the run for this process and drives it; nothing when another holds it or the tenant is full. */
197
+ async function take(runId, tenant) {
203
198
  if (active.has(runId)) {
204
199
  return;
205
200
  }
201
+ if (!(await claimRun(runId, tenant, await concurrencyLimit(tenant)))) {
202
+ return;
203
+ }
206
204
  const abort = new AbortController();
207
205
  active.set(runId, abort);
208
- const tenant = currentTenant();
209
- const work = async () => {
210
- await markRunActive(runId, true);
211
- if (!(await acquireSlot(tenant, abort.signal))) {
212
- return;
213
- }
214
- try {
215
- await drive(runId, abort.signal);
216
- }
217
- finally {
218
- releaseSlot(tenant);
219
- }
220
- };
221
- work()
206
+ // The heartbeat keeps the claim and hears of a cancel the web wrote while a step works.
207
+ const beat = setInterval(() => {
208
+ void heartbeatRuns([runId]).catch(() => undefined);
209
+ void withTenant(tenant, () => loadRun(runId))
210
+ .then((run) => {
211
+ if (run && run.status !== "running") {
212
+ abort.abort();
213
+ }
214
+ })
215
+ .catch(() => undefined);
216
+ }, HEARTBEAT_MS);
217
+ beat.unref();
218
+ await withTenant(tenant, () => drive(runId, abort.signal))
222
219
  .catch(async (err) => {
223
220
  console.error(`[run ${runId}]`, err);
224
- await updateRun(runId, { status: "failed", error: friendly(err) }).catch(() => undefined);
221
+ await withTenant(tenant, () => updateRun(runId, { status: "failed", error: friendly(err) })).catch(() => undefined);
225
222
  })
226
223
  .finally(async () => {
224
+ clearInterval(beat);
227
225
  active.delete(runId);
228
- await markRunActive(runId, false).catch(() => undefined);
229
- await releaseResources(runId);
230
- signalChanged(runId);
226
+ await withTenant(tenant, () => releaseResources(runId));
227
+ // A run the shutdown stopped goes back in line for the next runner; the rest is done for now.
228
+ if (!stopping) {
229
+ await restRun(runId).catch(() => undefined);
230
+ }
231
+ withTenant(tenant, () => signalChanged(runId));
232
+ // A slot came free: the next run of the line need not wait for the poll.
233
+ void lookAtLine();
231
234
  });
232
235
  }
236
+ let stopping = false;
237
+ let looking = false;
238
+ /** Takes what waits in line, run by run; each claim counts the tenant's limit by itself. */
239
+ async function lookAtLine() {
240
+ if (looking || stopping) {
241
+ return;
242
+ }
243
+ looking = true;
244
+ try {
245
+ for (const r of await waitingRuns()) {
246
+ if (stopping) {
247
+ return;
248
+ }
249
+ await take(r.runId, r.tenantId).catch((err) => console.error(`[line ${r.runId}]`, err));
250
+ }
251
+ }
252
+ catch (err) {
253
+ console.error("[line]", err);
254
+ }
255
+ finally {
256
+ looking = false;
257
+ }
258
+ }
259
+ /** A runner: looks at the line every POLL_MS, from now on. Runs a stopped process left behind are in it. */
260
+ export function startRunner() {
261
+ const timer = setInterval(() => void lookAtLine(), POLL_MS);
262
+ timer.unref();
263
+ void lookAtLine();
264
+ }
265
+ /** Stops the runs this process holds and hands them back to the line. */
266
+ export async function stopRunner() {
267
+ stopping = true;
268
+ for (const abort of active.values()) {
269
+ abort.abort();
270
+ }
271
+ await disownRuns().catch(() => undefined);
272
+ }
233
273
  /** What conditions read in this run: answers, outputs, and how many rows each stored list has. */
234
274
  async function flowValues(run, state) {
235
275
  const counts = {};
@@ -309,9 +349,7 @@ async function makeContext(run, project, state, signal) {
309
349
  projectFiles: (await projectFiles(project.id)).filter((f) => f.status === "ready"),
310
350
  signal,
311
351
  resources,
312
- ask: (ask) => unattended.has(run.id)
313
- ? Promise.resolve(null)
314
- : askPerson(run.id, { ...ask, stepId }, signal),
352
+ ask: (ask) => run.unattended ? Promise.resolve(null) : askPerson(run.id, { ...ask, stepId }, signal),
315
353
  emit: (type, message, asset) => emitEvent(run.id, run.cursor, type, message, asset),
316
354
  call: { runId: run.id, stepId },
317
355
  chargeUsd: (usd) => addLocalCost(run.id, stepId, usd),
@@ -463,6 +501,7 @@ async function decidePageFields(run, page, state, signal) {
463
501
  .map((f) => f.id);
464
502
  }
465
503
  async function drive(runId, signal) {
504
+ // The step starts afresh here: a question another process left in the row has no one waiting.
466
505
  await clearStaleAsk(runId);
467
506
  while (!signal.aborted) {
468
507
  const run = await loadRun(runId);
@@ -487,9 +526,7 @@ async function drive(runId, signal) {
487
526
  return;
488
527
  }
489
528
  console.error(`[run ${runId} deciding ${deciding.id}]`, err);
490
- const message = friendly(err);
491
- await emitEvent(runId, deciding.id, "error", message);
492
- await updateRun(runId, { status: "failed", error: message });
529
+ await failRun(run, deciding.id, err);
493
530
  return;
494
531
  }
495
532
  continue;
@@ -516,9 +553,7 @@ async function drive(runId, signal) {
516
553
  return;
517
554
  }
518
555
  console.error(`[run ${runId} fields of ${step.id}]`, err);
519
- const message = friendly(err);
520
- await emitEvent(runId, step.id, "error", message);
521
- await updateRun(runId, { status: "failed", error: message });
556
+ await failRun(run, step.id, err);
522
557
  return;
523
558
  }
524
559
  continue;
@@ -561,27 +596,11 @@ async function drive(runId, signal) {
561
596
  }
562
597
  console.error(`[run ${runId} step ${step.id}]`, err);
563
598
  await noteFreeTierRefusal(err);
564
- const message = friendly(err);
565
- await emitEvent(runId, step.id, "error", message);
566
- await updateRun(runId, { status: "failed", error: message });
599
+ await failRun(run, step.id, err);
567
600
  return;
568
601
  }
569
602
  }
570
603
  }
571
- /** Runs a restart left mid-step go on where they were. */
572
- export async function resumeInterruptedRuns() {
573
- for (const r of await activeRuns()) {
574
- await withTenant(r.tenantId, async () => {
575
- const run = await loadRun(r.runId);
576
- if (run?.status === "running") {
577
- kick(r.runId);
578
- }
579
- else {
580
- await markRunActive(r.runId, false);
581
- }
582
- }).catch((err) => console.error(`[resume ${r.runId}]`, err));
583
- }
584
- }
585
604
  // --- commands ----------------------------------------------------------------
586
605
  async function requireWaiting(runId, stepId) {
587
606
  const run = await loadRun(runId);
@@ -589,10 +608,10 @@ async function requireWaiting(runId, stepId) {
589
608
  throw new RunConflict("Run not found");
590
609
  }
591
610
  if (run.status !== "waiting_input" && run.status !== "done") {
592
- throw new RunConflict("Der Wizard arbeitet gerade.");
611
+ throw new RunConflict({ code: "runBusy" });
593
612
  }
594
613
  if (run.cursor !== stepId) {
595
- throw new RunConflict("Diese Seite ist nicht mehr aktuell.");
614
+ throw new RunConflict({ code: "pageOutdated" });
596
615
  }
597
616
  return run;
598
617
  }
@@ -695,12 +714,12 @@ export async function goBack(runId) {
695
714
  const run = await loadRun(runId);
696
715
  if (!run ||
697
716
  (run.status !== "waiting_input" && run.status !== "done" && run.status !== "failed")) {
698
- throw new RunConflict("Der Wizard arbeitet gerade.");
717
+ throw new RunConflict({ code: "runBusy" });
699
718
  }
700
719
  const state = structuredClone(run.state);
701
720
  const previous = state.history.pop();
702
721
  if (!previous) {
703
- throw new RunConflict("Kein vorheriger Schritt.");
722
+ throw new RunConflict({ code: "noStepBefore" });
704
723
  }
705
724
  // A decision that failed belongs to the step left behind.
706
725
  delete state.deciding;
@@ -769,6 +788,21 @@ function prefillOf(step, run, closed) {
769
788
  }
770
789
  return out;
771
790
  }
791
+ /**
792
+ * Whether a run may hold a live conversation: a speech model is set up, and the wizard has live
793
+ * voice or video switched on. Its owner's test run always may.
794
+ */
795
+ export async function talkAllowed(run) {
796
+ if (!(await conversationAvailable())) {
797
+ return false;
798
+ }
799
+ if (run.mode === "test") {
800
+ return true;
801
+ }
802
+ const w = await db.query.wizard.findFirst({ where: eq(schema.wizard.id, run.wizardId) });
803
+ const { enabled } = w?.runners ?? DEFAULT_RUNNER_SETTINGS;
804
+ return enabled.some((id) => CONVERSATION_RUNNERS.includes(id));
805
+ }
772
806
  export async function runView(run, brand) {
773
807
  const def = run.definition;
774
808
  const step = stepOf(def, run.cursor) ?? null;
@@ -822,7 +856,7 @@ export async function runView(run, brand) {
822
856
  intro: def.intro,
823
857
  },
824
858
  lang: wizardLang(def),
825
- talk: await conversationAvailable(),
859
+ talk: await talkAllowed(run),
826
860
  step,
827
861
  answered: run.state.history.map((id) => stepOf(def, id)).filter((s) => Boolean(s)),
828
862
  values: run.state.values,
@@ -1,7 +1,9 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { randomBytes } from "node:crypto";
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { hostname } from "node:os";
4
5
  import { join, resolve } from "node:path";
6
+ import { findChrome } from "./render/browser-path.js";
5
7
  /** Load `.env.local` then `.env` without overriding the real environment. */
6
8
  function loadEnvFiles() {
7
9
  for (const name of [".env.local", ".env"]) {
@@ -91,6 +93,13 @@ const port = num("API_PORT", 24368);
91
93
  /** From source the Vite dev server on :5181 serves the pages; built, this server does. */
92
94
  const fromSource = import.meta.url.endsWith(".ts");
93
95
  const sandboxImage = str("SANDBOX_IMAGE", "engenty-sandbox:latest");
96
+ function role() {
97
+ const given = str("RUNTIME_ROLE", "all");
98
+ if (given !== "web" && given !== "runner" && given !== "all") {
99
+ throw new Error(`RUNTIME_ROLE must be web, runner or all, not "${given}"`);
100
+ }
101
+ return given;
102
+ }
94
103
  export const env = {
95
104
  production: process.env.NODE_ENV === "production",
96
105
  /** Running from source: Vite serves the pages, this server only `/api`. */
@@ -98,6 +107,17 @@ export const env = {
98
107
  port,
99
108
  /** Listen address; a runtime that runs alone stays on the loopback interface. */
100
109
  host: str("API_HOST", manageUrl ? "0.0.0.0" : "127.0.0.1"),
110
+ /**
111
+ * What this process does: `web` serves the studio and the API and wakes runs, `runner` takes
112
+ * the runs that wait and drives them, `all` does both (a runtime that runs alone).
113
+ */
114
+ role: role(),
115
+ runner: {
116
+ /** This runner's name in the control database; a new one each start. */
117
+ id: `${hostname()}-${randomBytes(3).toString("hex")}`,
118
+ /** Where the web reaches this runner (the browser's screen of a run it holds). */
119
+ url: str("RUNNER_URL").replace(/\/$/, ""),
120
+ },
101
121
  /** The origin people open, e.g. https://wizards.localhost — auth callbacks and links use it. */
102
122
  appUrl: str("APP_URL", fromSource ? "http://localhost:5181" : `http://localhost:${port}`).replace(/\/$/, ""),
103
123
  /** More host names this server answers under, besides APP_URL's and the loopback names. */
@@ -185,9 +205,11 @@ export const env = {
185
205
  geocoderUrl: str("GEOCODER_URL"),
186
206
  /** CDP endpoint of a Chromium (the engenty-browser image); else a local Chrome is launched. */
187
207
  browserCdpUrl: str("BROWSER_CDP_URL"),
188
- chromePath: str("CHROME_PATH", process.platform === "darwin"
189
- ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
190
- : "/usr/bin/chromium"),
208
+ /** The browser the setup and `wizards doctor` found (render/browser-path.ts). */
209
+ chromePath: str("CHROME_PATH", findChrome({ PATH: process.env.PATH }) ??
210
+ (process.platform === "darwin"
211
+ ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
212
+ : "/usr/bin/chromium")),
191
213
  /** Encodes widget animations to MP4; without it widgets offer no video. */
192
214
  ffmpegPath: str("FFMPEG_PATH", "ffmpeg"),
193
215
  /** What runs an agent's shell and code: a Docker container, an agentOS VM, or nothing. */