wizards 0.2.42 → 0.2.44

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 (166) hide show
  1. package/apps/runtime/dist/app.js +37 -3
  2. package/apps/runtime/dist/authoring/guide.js +5 -2
  3. package/apps/runtime/dist/browser/fast/action-space.js +162 -0
  4. package/apps/runtime/dist/browser/fast/classifier.js +91 -0
  5. package/apps/runtime/dist/browser/fast/decide.js +171 -0
  6. package/apps/runtime/dist/browser/fast/driver.js +141 -0
  7. package/apps/runtime/dist/browser/fast/instructions.js +33 -0
  8. package/apps/runtime/dist/browser/fast/run.js +249 -0
  9. package/apps/runtime/dist/browser/fast/span-picker.js +153 -0
  10. package/apps/runtime/dist/browser/fast/text-helper.js +178 -0
  11. package/apps/runtime/dist/browser/snapshot.js +335 -0
  12. package/apps/runtime/dist/db/migrations/tenant/0011_runners.sql +2 -0
  13. package/apps/runtime/dist/db/migrations/tenant/meta/0011_snapshot.json +2956 -0
  14. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +7 -0
  15. package/apps/runtime/dist/db/schema.js +4 -0
  16. package/apps/runtime/dist/engine/resources.js +109 -0
  17. package/apps/runtime/dist/engine/runner.js +7 -3
  18. package/apps/runtime/dist/engine/steps.js +89 -10
  19. package/apps/runtime/dist/env.js +9 -0
  20. package/apps/runtime/dist/harness/claude.js +9 -1
  21. package/apps/runtime/dist/link-preview.js +4 -3
  22. package/apps/runtime/dist/mcp/tools.js +1 -1
  23. package/apps/runtime/dist/media/conversation.js +177 -0
  24. package/apps/runtime/dist/models.js +17 -0
  25. package/apps/runtime/dist/plugins/loader.js +48 -2
  26. package/apps/runtime/dist/plugins/registry.js +1 -0
  27. package/apps/runtime/dist/plugins/runs.js +205 -0
  28. package/apps/runtime/dist/routes/runs.js +206 -22
  29. package/apps/runtime/dist/routes/studio.js +12 -1
  30. package/apps/runtime/dist/services/cloud.js +1 -0
  31. package/apps/runtime/dist/services/runners.js +138 -0
  32. package/apps/runtime/dist/services/runs.js +83 -45
  33. package/apps/runtime/dist/services/wizard-icon.js +12 -0
  34. package/apps/runtime/dist/services/wizards.js +5 -1
  35. package/apps/runtime/dist/tools/browser.js +426 -97
  36. package/apps/runtime/dist/tools/index.js +50 -3
  37. package/apps/web/dist/assets/ChangelogDialog-C1_ZvuwE.js +1 -0
  38. package/apps/web/dist/assets/ChatView-DLG771z6.js +10 -0
  39. package/apps/web/dist/assets/{CreditsDialog-DPglouDr.js → CreditsDialog-Ce7Czhxq.js} +1 -1
  40. package/apps/web/dist/assets/EditorPage-CXx32-a7.js +3 -0
  41. package/apps/web/dist/assets/{FlowPreview-CQN5acxA.js → FlowPreview-DgZiepFR.js} +1 -1
  42. package/apps/web/dist/assets/{Harness-BFxUFB7B.js → Harness-ffZUxkbb.js} +2 -2
  43. package/apps/web/dist/assets/HomePage-B3RVPuUu.js +1 -0
  44. package/apps/web/dist/assets/ImportWizard-CHlCjPEo.js +1 -0
  45. package/apps/web/dist/assets/NewWizardPage-BQW7PoZq.js +2 -0
  46. package/apps/web/dist/assets/ProjectPage-D-_A4iZz.js +2 -0
  47. package/apps/web/dist/assets/PublicRunner-sbya6PXg.js +1 -0
  48. package/apps/web/dist/assets/RunDrawer-BgLxai9C.js +4 -0
  49. package/apps/web/dist/assets/RunnerView-BVm9fL62.js +2 -0
  50. package/apps/web/dist/assets/SettingsPage-Ce6k9xDs.js +1 -0
  51. package/apps/web/dist/assets/SetupPage-CLymFxat.js +1 -0
  52. package/apps/web/dist/assets/SharePage-1Ni5ejt6.js +1 -0
  53. package/apps/web/dist/assets/ThemeSwitch-DN42WOTx.js +1 -0
  54. package/apps/web/dist/assets/arrow-right-BgKM1Npq.js +1 -0
  55. package/apps/web/dist/assets/changelog-CH4sN8Dm.js +1 -0
  56. package/apps/web/dist/assets/{circle-alert-B0rwkpC7.js → circle-alert-D_6s0Xgw.js} +1 -1
  57. package/apps/web/dist/assets/{copy-DgbMaHoj.js → copy-BAtcCufT.js} +1 -1
  58. package/apps/web/dist/assets/definition-CfFlylCM.js +56 -0
  59. package/apps/web/dist/assets/{external-link-pP6YfR9-.js → external-link-DitV3n6l.js} +1 -1
  60. package/apps/web/dist/assets/globe-CoQ1BSyl.js +1 -0
  61. package/apps/web/dist/assets/{image-D2X6TWdq.js → image-B1a1ax-P.js} +1 -1
  62. package/apps/web/dist/assets/index-B8VsYgck.js +78 -0
  63. package/apps/web/dist/assets/index-mB3Du8ho.css +1 -0
  64. package/apps/web/dist/assets/{lock-BG4mi_lJ.js → lock-DSPinlFN.js} +1 -1
  65. package/apps/web/dist/assets/{meta-BD9yulXs.js → meta-Bpe6vzmM.js} +1 -1
  66. package/apps/web/dist/assets/mouse-pointer-click-SHJL7g1i.js +1 -0
  67. package/apps/web/dist/assets/{pen-line-D54vxrGl.js → pen-line-DgSzJ60H.js} +1 -1
  68. package/apps/web/dist/assets/{refresh-cw-DvTgdpdf.js → refresh-cw-CWRkEENy.js} +1 -1
  69. package/apps/web/dist/assets/{session-CT1AZIlE.js → session-C24kIPr-.js} +1 -1
  70. package/apps/web/dist/assets/{settings-menu-DJATAPGg.js → settings-menu-e8OMChHm.js} +1 -1
  71. package/apps/web/dist/assets/star-ClV5w6K4.js +1 -0
  72. package/apps/web/dist/assets/{trash-DAcf34LR.js → trash-t3O7FdUR.js} +1 -1
  73. package/apps/web/dist/assets/{type-BU0mWqf3.js → type-BbMmv2qL.js} +1 -1
  74. package/apps/web/dist/assets/ui-C4b__6Oo.js +9 -0
  75. package/apps/web/dist/assets/{video-C6qoFAAs.js → video-D04-GeyG.js} +1 -1
  76. package/apps/web/dist/assets/volume-2-FUU7z0rq.js +1 -0
  77. package/apps/web/dist/assets/{wand-sparkles-Bw4tu2An.js → wand-sparkles-BsD2e8V6.js} +1 -1
  78. package/apps/web/dist/embed.js +119 -4
  79. package/apps/web/dist/index.html +12 -11
  80. package/apps/web/dist/mcp/flow.html +45 -45
  81. package/modules/calls/dist/client.css +3 -0
  82. package/modules/calls/dist/client.js +1 -0
  83. package/modules/calls/engenty.plugin.json +8 -0
  84. package/modules/calls/migrations/0001_init.sql +26 -0
  85. package/modules/calls/package.json +25 -0
  86. package/modules/calls/src/openai.ts +155 -0
  87. package/modules/calls/src/plugin.ts +407 -0
  88. package/modules/calls/src/rules.ts +226 -0
  89. package/modules/calls/src/schema.ts +39 -0
  90. package/modules/calls/src/session.ts +353 -0
  91. package/modules/calls/src/store.ts +124 -0
  92. package/modules/calls/src/twilio.ts +90 -0
  93. package/modules/calls/tsconfig.json +10 -0
  94. package/modules/calls/ui/Settings.tsx +137 -0
  95. package/modules/calls/ui/app.ts +50 -0
  96. package/modules/calls/ui/messages.ts +81 -0
  97. package/modules/calls/ui/parts.tsx +36 -0
  98. package/modules/calls/ui/plugin.tsx +15 -0
  99. package/modules/sms/dist/client.css +3 -0
  100. package/modules/sms/dist/client.js +1 -0
  101. package/modules/sms/engenty.plugin.json +8 -0
  102. package/modules/sms/migrations/0001_init.sql +26 -0
  103. package/modules/sms/package.json +25 -0
  104. package/modules/sms/src/plugin.ts +324 -0
  105. package/modules/sms/src/schema.ts +26 -0
  106. package/modules/sms/src/store.ts +140 -0
  107. package/modules/sms/src/surface.ts +70 -0
  108. package/modules/sms/src/twilio.ts +130 -0
  109. package/modules/sms/tsconfig.json +10 -0
  110. package/modules/sms/ui/Settings.tsx +113 -0
  111. package/modules/sms/ui/Share.tsx +78 -0
  112. package/modules/sms/ui/app.ts +51 -0
  113. package/modules/sms/ui/messages.ts +72 -0
  114. package/modules/sms/ui/parts.tsx +36 -0
  115. package/modules/sms/ui/plugin.tsx +20 -0
  116. package/modules/whatsapp/dist/client.css +3 -0
  117. package/modules/whatsapp/dist/client.js +1 -0
  118. package/modules/whatsapp/engenty.plugin.json +8 -0
  119. package/modules/whatsapp/migrations/0001_init.sql +30 -0
  120. package/modules/whatsapp/package.json +25 -0
  121. package/modules/whatsapp/src/graph.ts +271 -0
  122. package/modules/whatsapp/src/inbound.ts +143 -0
  123. package/modules/whatsapp/src/plugin.ts +369 -0
  124. package/modules/whatsapp/src/schema.ts +32 -0
  125. package/modules/whatsapp/src/store.ts +156 -0
  126. package/modules/whatsapp/src/surface.ts +127 -0
  127. package/modules/whatsapp/tsconfig.json +10 -0
  128. package/modules/whatsapp/ui/Settings.tsx +141 -0
  129. package/modules/whatsapp/ui/Share.tsx +78 -0
  130. package/modules/whatsapp/ui/app.ts +54 -0
  131. package/modules/whatsapp/ui/messages.ts +82 -0
  132. package/modules/whatsapp/ui/parts.tsx +36 -0
  133. package/modules/whatsapp/ui/plugin.tsx +20 -0
  134. package/node_modules/@engenty-wizards/plugin-sdk/dist/index.d.ts +259 -0
  135. package/node_modules/@engenty-wizards/plugin-sdk/dist/studio.d.ts +17 -0
  136. package/node_modules/@engenty-wizards/plugin-sdk/dist/thread.d.ts +174 -0
  137. package/node_modules/@engenty-wizards/plugin-sdk/dist/thread.js +816 -0
  138. package/node_modules/@engenty-wizards/plugin-sdk/package.json +2 -1
  139. package/node_modules/@engenty-wizards/shared/dist/definition.d.ts +8 -0
  140. package/node_modules/@engenty-wizards/shared/dist/definition.js +21 -0
  141. package/node_modules/@engenty-wizards/shared/dist/run.d.ts +61 -3
  142. package/node_modules/@engenty-wizards/shared/dist/run.js +16 -0
  143. package/node_modules/@engenty-wizards/shared/dist/runners.d.ts +81 -0
  144. package/node_modules/@engenty-wizards/shared/dist/runners.js +146 -0
  145. package/package.json +1 -1
  146. package/apps/web/dist/assets/ChangelogDialog-BxRBTR8P.js +0 -1
  147. package/apps/web/dist/assets/EditorPage-BKAFzzWk.js +0 -3
  148. package/apps/web/dist/assets/HomePage-BZuwrr-b.js +0 -1
  149. package/apps/web/dist/assets/ImportWizard-JGMemER4.js +0 -1
  150. package/apps/web/dist/assets/NewWizardPage-BwHAsJwj.js +0 -2
  151. package/apps/web/dist/assets/ProjectPage--ijr1jPE.js +0 -2
  152. package/apps/web/dist/assets/PublicRunner-D9Oe-_vs.js +0 -1
  153. package/apps/web/dist/assets/RunDrawer-BfociUm2.js +0 -4
  154. package/apps/web/dist/assets/RunnerView-D2b84UTY.js +0 -2
  155. package/apps/web/dist/assets/SettingsPage-9rk9IRdr.js +0 -1
  156. package/apps/web/dist/assets/SetupPage-BUJh_v9q.js +0 -1
  157. package/apps/web/dist/assets/SharePage-sNJ_s1RE.js +0 -1
  158. package/apps/web/dist/assets/ThemeSwitch-NDTEeh0R.js +0 -1
  159. package/apps/web/dist/assets/arrow-right-C1xLSnNa.js +0 -1
  160. package/apps/web/dist/assets/changelog-BSVi9hHS.js +0 -1
  161. package/apps/web/dist/assets/definition-FVgbAXOo.js +0 -56
  162. package/apps/web/dist/assets/index-CBjgitjd.js +0 -78
  163. package/apps/web/dist/assets/index-gTcC8eX6.css +0 -1
  164. package/apps/web/dist/assets/star-CaOg5c-D.js +0 -1
  165. package/apps/web/dist/assets/ui-Bxf6zX5k.js +0 -9
  166. package/apps/web/dist/assets/volume-2-Dw4p9Ln4.js +0 -1
@@ -78,6 +78,13 @@
78
78
  "when": 1791469862548,
79
79
  "tag": "0010_plugin_connection",
80
80
  "breakpoints": true
81
+ },
82
+ {
83
+ "idx": 11,
84
+ "version": "6",
85
+ "when": 1791490942531,
86
+ "tag": "0011_runners",
87
+ "breakpoints": true
81
88
  }
82
89
  ]
83
90
  }
@@ -39,6 +39,8 @@ export const wizard = sqliteTable("wizard", {
39
39
  starterRevision: integer("starter_revision"),
40
40
  /** Bumped on every draft write; a write carrying an older one is refused. */
41
41
  revision: integer("revision").notNull().default(0),
42
+ /** How the wizard is offered: the runner its link opens, the ones switched on. Null: steps and chat. */
43
+ runners: text("runners", { mode: "json" }).$type(),
42
44
  createdAt: createdAt(),
43
45
  updatedAt: updatedAt(),
44
46
  }, (t) => [
@@ -95,6 +97,8 @@ export const run = sqliteTable("run", {
95
97
  files: text("files", { mode: "json" }).$type().notNull().default([]),
96
98
  version: integer("version"),
97
99
  mode: text("mode", { enum: ["test", "live"] }).notNull(),
100
+ /** The door the run came through: steps, chat, or a plugin's runner. Null: the page. */
101
+ runner: text("runner"),
98
102
  visitorId: text("visitor_id"),
99
103
  userId: text("user_id"),
100
104
  ipHash: text("ip_hash"),
@@ -3,6 +3,8 @@ import { createSandbox } from "../sandbox/index.js";
3
3
  import { getSecret, putSecret } from "../store/index.js";
4
4
  /** Sign-ins the person asked the wizard to keep, as Playwright storage state. */
5
5
  const SESSION_SLOT = "browser";
6
+ /** A person who took the browser over and does nothing on it this long hands it back. */
7
+ const SEAT_IDLE_MS = 3 * 60_000;
6
8
  /**
7
9
  * What a run holds while an agent works: a browser context and a sandbox, both made on first
8
10
  * use and released when the run stops running.
@@ -15,6 +17,13 @@ export class RunResources {
15
17
  scope = null;
16
18
  /** Changes the person allowed for the rest of this run, as "<connection>:<action>". */
17
19
  allowed = new Set();
20
+ watchers = new Set();
21
+ cast = null;
22
+ /** The latest picture of the page, for a watcher who comes in between two changes. */
23
+ frame = null;
24
+ seat = "agent";
25
+ seatBack = [];
26
+ seatIdle = null;
18
27
  constructor(runId) {
19
28
  this.runId = runId;
20
29
  }
@@ -38,6 +47,7 @@ export class RunResources {
38
47
  const context = await this.browserContext();
39
48
  if (!this.page || this.page.isClosed()) {
40
49
  this.page = await context.newPage();
50
+ void this.recast();
41
51
  }
42
52
  return this.page;
43
53
  }
@@ -48,6 +58,98 @@ export class RunResources {
48
58
  /** A link opened a new tab: the agent goes on there. */
49
59
  adopt(page) {
50
60
  this.page = page;
61
+ void this.recast();
62
+ }
63
+ /**
64
+ * Watches the browser as it works: the page's pictures as Chromium paints them, on whichever
65
+ * page the agent is on. Ends (null) when the run lets the browser go.
66
+ */
67
+ watchBrowser(watcher) {
68
+ this.watchers.add(watcher);
69
+ if (this.frame) {
70
+ watcher(this.frame);
71
+ }
72
+ void this.recast();
73
+ return () => {
74
+ this.watchers.delete(watcher);
75
+ if (!this.watchers.size) {
76
+ void this.stopCast();
77
+ }
78
+ };
79
+ }
80
+ seatHolder() {
81
+ return this.seat;
82
+ }
83
+ /**
84
+ * The person takes the browser over, or hands it back. While they hold it the agent's browser
85
+ * steps wait; a person who does nothing for a while hands it back by themselves.
86
+ */
87
+ setSeat(to) {
88
+ this.seat = to;
89
+ if (this.seatIdle) {
90
+ clearTimeout(this.seatIdle);
91
+ this.seatIdle = null;
92
+ }
93
+ if (to === "person") {
94
+ this.seatIdle = setTimeout(() => this.setSeat("agent"), SEAT_IDLE_MS);
95
+ return;
96
+ }
97
+ const waiting = this.seatBack;
98
+ this.seatBack = [];
99
+ for (const resume of waiting) {
100
+ resume();
101
+ }
102
+ }
103
+ /** The person did something on the page: their seat stays theirs a while longer. */
104
+ touchSeat() {
105
+ if (this.seat === "person") {
106
+ this.setSeat("person");
107
+ }
108
+ }
109
+ /** Waits while the person holds the browser; true when it had to. */
110
+ async agentTurn(signal) {
111
+ if (this.seat === "agent") {
112
+ return false;
113
+ }
114
+ await new Promise((resume) => {
115
+ this.seatBack.push(resume);
116
+ signal?.addEventListener("abort", () => resume(), { once: true });
117
+ });
118
+ return true;
119
+ }
120
+ /** Points the screencast at the agent's current page, while anyone watches. */
121
+ async recast() {
122
+ const page = this.openPage();
123
+ if (!(page && this.watchers.size) || this.cast?.page === page) {
124
+ return;
125
+ }
126
+ await this.stopCast();
127
+ const session = await page
128
+ .context()
129
+ .newCDPSession(page)
130
+ .catch(() => null);
131
+ if (!session) {
132
+ return;
133
+ }
134
+ this.cast = { page, session };
135
+ session.on("Page.screencastFrame", ({ data, sessionId }) => {
136
+ session.send("Page.screencastFrameAck", { sessionId }).catch(() => undefined);
137
+ if (this.cast?.session !== session) {
138
+ return;
139
+ }
140
+ this.frame = Buffer.from(data, "base64");
141
+ for (const watcher of this.watchers) {
142
+ watcher(this.frame);
143
+ }
144
+ });
145
+ await session
146
+ .send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 960, maxHeight: 720 })
147
+ .catch(() => undefined);
148
+ }
149
+ async stopCast() {
150
+ const cast = this.cast;
151
+ this.cast = null;
152
+ await cast?.session.detach().catch(() => undefined);
51
153
  }
52
154
  /** Keeps the browser's sign-ins for the person's next run (they ticked "remember"). */
53
155
  async keepSession() {
@@ -65,6 +167,13 @@ export class RunResources {
65
167
  this.context = null;
66
168
  this.page = null;
67
169
  this.sandbox = null;
170
+ this.frame = null;
171
+ this.setSeat("agent");
172
+ await this.stopCast();
173
+ for (const watcher of this.watchers) {
174
+ watcher(null);
175
+ }
176
+ this.watchers.clear();
68
177
  await context?.close().catch(() => undefined);
69
178
  await sandbox?.destroy().catch(() => undefined);
70
179
  }
@@ -1,5 +1,5 @@
1
1
  import { marginOf, } from "@engenty-wizards/shared/decision";
2
- import { branchValues, conditionsOf, dataRef, followRules, formatsFor, isDecidedField, LIST_FORMATS, listRef, loopKey, MAX_SHOWN_FIELDS, optionsFromData, otherwiseOf, pageNeeds, whenHolds, } from "@engenty-wizards/shared/definition";
2
+ import { branchValues, conditionsOf, dataRef, followRules, formatsFor, isDecidedField, LIST_FORMATS, listRef, loopKey, MAX_SHOWN_FIELDS, optionsFromData, otherwiseOf, pageNeeds, whenHolds, wizardLang, } from "@engenty-wizards/shared/definition";
3
3
  import { eq } from "drizzle-orm";
4
4
  import { nanoid } from "nanoid";
5
5
  import { connectionViews } from "../connectors/index.js";
@@ -10,7 +10,7 @@ import { env } from "../env.js";
10
10
  import { saveAsset } from "../files/storage.js";
11
11
  import { managed, tenantInfo } from "../manage.js";
12
12
  import { hasFfmpeg } from "../media/ffmpeg.js";
13
- import { freeTierRefusal, freeTierText, ModelUnavailableError, noteFreeTierRefusal, } from "../models.js";
13
+ import { conversationAvailable, freeTierRefusal, freeTierText, ModelUnavailableError, noteFreeTierRefusal, } from "../models.js";
14
14
  import { runEnded } from "../plugins/events.js";
15
15
  import { projectFiles } from "../services/project-files.js";
16
16
  import { projectProfile } from "../services/projects.js";
@@ -180,6 +180,7 @@ export async function createRun(input) {
180
180
  files: input.files,
181
181
  version: input.version,
182
182
  mode: input.mode,
183
+ runner: input.runner ?? null,
183
184
  visitorId: input.visitorId ?? null,
184
185
  userId: input.userId ?? null,
185
186
  ipHash: input.ipHash ?? null,
@@ -243,7 +244,7 @@ async function flowValues(run, state) {
243
244
  * page (its own earlier answers left out, so a revisit decides on what is typed now) and the
244
245
  * choices its `optionsFrom` fields find in the run.
245
246
  */
246
- async function pageContext(run, step) {
247
+ export async function pageContext(run, step) {
247
248
  const needs = pageNeeds(step.fields);
248
249
  const sourced = step.fields.filter((f) => f.optionsFrom);
249
250
  const decided = step.fields.some(isDecidedField) ? (run.state.pages?.[step.id]?.shown ?? []) : [];
@@ -812,7 +813,10 @@ export async function runView(run, brand) {
812
813
  avatar: def.avatar,
813
814
  intro: def.intro,
814
815
  },
816
+ lang: wizardLang(def),
817
+ talk: await conversationAvailable(),
815
818
  step,
819
+ answered: run.state.history.map((id) => stepOf(def, id)).filter((s) => Boolean(s)),
816
820
  values: run.state.values,
817
821
  prefill: step?.type === "page" ? prefillOf(step, run, closed) : {},
818
822
  ...(step?.type === "page" ? viewContext(await pageContext(run, step)) : {}),
@@ -74,8 +74,17 @@ const GROUND_RULES = [
74
74
  "Write in the language the person wrote their answers in; if unclear, German.",
75
75
  "Work economically. For web research: search first, open only the few pages you really need (at most five), then write.",
76
76
  ].join("\n");
77
+ /** How a step with the browser treats a site's consent banners. */
78
+ const BROWSER_RULES = [
79
+ "# BROWSER",
80
+ 'A cookie or consent banner is in the way: click it away first, before anything else on the page. Give the least consent the banner allows — "Only necessary", "Reject all", "Ablehnen", "Nur notwendige" — or close it; never "Accept all". If the only way past is to open its settings, untick everything optional there and save. Never take part in marketing, newsletter or tracking offers.',
81
+ "A banner that cannot be got past any other way: accept only what is needed to go on, and say so in your result.",
82
+ "Controls marked (dialog) lie over the page; a click on what they cover is refused until they are dealt with.",
83
+ "Where browser_run_fast is offered, hand it the mechanical stretches of a page (the banner, a search form, filters, dropdowns, a date) with every value spelled out, and keep reading results and deciding for yourself.",
84
+ "The person can take the browser over while you work; your next browser action then waits and gets the page as they left it.",
85
+ ].join("\n");
77
86
  // --- agent -------------------------------------------------------------------
78
- function outputSchema(step) {
87
+ export function outputSchema(step) {
79
88
  const fields = step.output.fields?.length
80
89
  ? step.output.fields
81
90
  : [{ id: "data", kind: "table", description: "The result as a table" }];
@@ -130,6 +139,69 @@ function tablesToRecords(value, fields) {
130
139
  }
131
140
  return out;
132
141
  }
142
+ /** A table cell as the step's schema takes it: a list joined by spaces, anything else as text. */
143
+ function fitCell(value) {
144
+ if (value === null || value === undefined) {
145
+ return null;
146
+ }
147
+ if (typeof value === "string" || typeof value === "number") {
148
+ return value;
149
+ }
150
+ if (Array.isArray(value) && value.every((v) => typeof v === "string" || typeof v === "number")) {
151
+ return value.join(" ");
152
+ }
153
+ return typeof value === "boolean" ? String(value) : JSON.stringify(value);
154
+ }
155
+ /**
156
+ * What the agent wrote as JSON itself — its last fenced block, else its answer or the object in
157
+ * it — fitted to the step's fields (a list in a table cell joined, a missing column empty) and
158
+ * checked against the schema. Null where none fits; then a model structures the text.
159
+ */
160
+ export function ownJson(text, schema, fields) {
161
+ const blocks = [...text.matchAll(/```(?:json)?[ \t]*\n([\s\S]*?)```/g)].map((m) => m[1]);
162
+ const open = text.indexOf("{");
163
+ const close = text.lastIndexOf("}");
164
+ const tries = [
165
+ ...blocks.reverse(),
166
+ text.trim(),
167
+ ...(open >= 0 && close > open ? [text.slice(open, close + 1)] : []),
168
+ ];
169
+ for (const candidate of tries) {
170
+ let value;
171
+ try {
172
+ value = JSON.parse(candidate);
173
+ }
174
+ catch {
175
+ continue;
176
+ }
177
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
178
+ continue;
179
+ }
180
+ const fitted = { ...value };
181
+ for (const f of fields) {
182
+ const v = fitted[f.id];
183
+ if (f.kind === "table" && f.columns?.length && Array.isArray(v)) {
184
+ fitted[f.id] = v.map((row) => row && typeof row === "object" && !Array.isArray(row)
185
+ ? Object.fromEntries(f.columns.map((c) => [c, fitCell(row[c])]))
186
+ : row);
187
+ }
188
+ else if (f.kind === "text" && typeof v === "number") {
189
+ fitted[f.id] = String(v);
190
+ }
191
+ else if (f.kind === "number" &&
192
+ typeof v === "string" &&
193
+ v.trim() &&
194
+ Number.isFinite(Number(v))) {
195
+ fitted[f.id] = Number(v);
196
+ }
197
+ }
198
+ const parsed = schema.safeParse(fitted);
199
+ if (parsed.success) {
200
+ return parsed.data;
201
+ }
202
+ }
203
+ return null;
204
+ }
133
205
  /** An agent step looks at this many photos itself; more are read one by one with read_document. */
134
206
  const MAX_SEEN = 8;
135
207
  /** Models that take pictures in a message: the installed clients and the large vendors' models. */
@@ -398,6 +470,7 @@ export async function runAgentStep(step, ctx) {
398
470
  : "Finish with everything the result needs in your final answer; it is turned into structured data afterwards.";
399
471
  const system = [
400
472
  GROUND_RULES,
473
+ step.tools.includes("browser") ? BROWSER_RULES : "",
401
474
  `Today is ${today(ctx)}.`,
402
475
  brandBlock(ctx),
403
476
  // Wissen: what the space holds for its wizards, and how to find and read it.
@@ -471,15 +544,21 @@ export async function runAgentStep(step, ctx) {
471
544
  return { text, assets: assets.length ? assets : undefined, at: new Date().toISOString() };
472
545
  }
473
546
  const { schema, fields } = outputSchema(step);
474
- const structurer = await textModel("classifier", ctx.call);
475
- const structured = await generateText({
476
- model: structurer.model,
477
- abortSignal: ctx.signal,
478
- output: Output.object({ schema }),
479
- prompt: `Turn this result into the requested structure. Keep every number and source exactly.\n\n${text}`,
480
- });
481
- await ctx.chargeUsd(costOf(structurer, structured.usage));
482
- const json = tablesToRecords(structured.output, fields);
547
+ // The agent mostly writes the JSON itself; a second model only structures what does not fit.
548
+ // Having it copy kilobytes of JSON again is slow and can fail on its own.
549
+ let output = ownJson(text, schema, fields);
550
+ if (!output) {
551
+ const structurer = await textModel("classifier", ctx.call);
552
+ const structured = await generateText({
553
+ model: structurer.model,
554
+ abortSignal: ctx.signal,
555
+ output: Output.object({ schema }),
556
+ prompt: `Turn this result into the requested structure. Keep every number and source exactly.\n\n${text}`,
557
+ });
558
+ await ctx.chargeUsd(costOf(structurer, structured.usage));
559
+ output = structured.output;
560
+ }
561
+ const json = tablesToRecords(output, fields);
483
562
  const surface = step.output.surface ? await composeSurface(step, json, ctx) : undefined;
484
563
  return {
485
564
  text,
@@ -93,6 +93,8 @@ const fromSource = import.meta.url.endsWith(".ts");
93
93
  const sandboxImage = str("SANDBOX_IMAGE", "engenty-sandbox:latest");
94
94
  export const env = {
95
95
  production: process.env.NODE_ENV === "production",
96
+ /** Running from source: Vite serves the pages, this server only `/api`. */
97
+ fromSource,
96
98
  port,
97
99
  /** Listen address; a runtime that runs alone stays on the loopback interface. */
98
100
  host: str("API_HOST", manageUrl ? "0.0.0.0" : "127.0.0.1"),
@@ -148,6 +150,8 @@ export const env = {
148
150
  },
149
151
  aiGatewayKey: str("AI_GATEWAY_API_KEY"),
150
152
  openaiKey: str("OPENAI_API_KEY"),
153
+ /** The realtime speech model of live conversations; empty: the runtime's default. */
154
+ conversationModel: str("CONVERSATION_MODEL"),
151
155
  anthropicKey: str("ANTHROPIC_API_KEY"),
152
156
  googleKey: str("GOOGLE_GENERATIVE_AI_API_KEY"),
153
157
  falKey: str("FAL_KEY"),
@@ -155,6 +159,11 @@ export const env = {
155
159
  replicateKey: str("REPLICATE_API_TOKEN"),
156
160
  /** TypeSafe's own API, for the classifier that checks what a search found (Jev). */
157
161
  typesafeKey: str("TYPESAFE_API_KEY"),
162
+ /**
163
+ * `off`: agent steps get no `browser_run_fast`, where a decision model would pick each click
164
+ * on a page. Otherwise they get it wherever a decision model can be reached.
165
+ */
166
+ browserFastLoop: str("BROWSER_FAST_LOOP") !== "off",
158
167
  ollamaUrl: str("OLLAMA_URL", "http://127.0.0.1:11434/v1"),
159
168
  /** What each model class runs on when this runtime resolves classes itself (own keys, Ollama). */
160
169
  models: {
@@ -113,7 +113,15 @@ class ClaudeCodeModel extends HarnessModel {
113
113
  throw failureOf(this.harness, stderr.trim() || `exit ${code}`);
114
114
  }
115
115
  if (event.is_error) {
116
- throw failureOf(this.harness, String(event.result ?? "error"));
116
+ // A failed run carries no result, only why (subtype) and sometimes what (errors).
117
+ const why = [
118
+ typeof event.result === "string" ? event.result : "",
119
+ event.subtype ?? "",
120
+ ...(event.errors ?? []).map((e) => (typeof e === "string" ? e : JSON.stringify(e))),
121
+ event.num_turns ? `after ${event.num_turns} turns` : "",
122
+ ].filter(Boolean);
123
+ console.warn("[claude] the client failed:", JSON.stringify(event).slice(0, 2000));
124
+ throw failureOf(this.harness, why.join(" – ") || "error");
117
125
  }
118
126
  return claudeAnswer(event);
119
127
  }
@@ -21,7 +21,8 @@ function tags(p) {
21
21
  }
22
22
  /**
23
23
  * Open Graph tags for shared links, so X, LinkedIn, WhatsApp and Slack show a card: a shared
24
- * result (`/s/<token>`) with its picture, a public wizard (`/w/<token>`) with its title.
24
+ * result (`/s/<token>`) with its picture, a public wizard (`/w/<token>`, as a chat
25
+ * `/w/<token>/chat`) with its title.
25
26
  */
26
27
  export async function linkPreview(path) {
27
28
  const share = path.match(/^\/s\/([A-Za-z0-9_-]+)\/?$/);
@@ -38,7 +39,7 @@ export async function linkPreview(path) {
38
39
  image: `${env.appUrl}/api/shares/${share[1]}/image`,
39
40
  });
40
41
  }
41
- const wizard = path.match(/^\/w\/([A-Za-z0-9_-]+)\/?$/);
42
+ const wizard = path.match(/^\/w\/([A-Za-z0-9_-]+)(\/chat)?\/?$/);
42
43
  if (wizard) {
43
44
  const w = await db.query.wizard.findFirst({ where: eq(schema.wizard.shareToken, wizard[1]) });
44
45
  if (!w || w.publishedVersion === null || !w.shareEnabled) {
@@ -51,7 +52,7 @@ export async function linkPreview(path) {
51
52
  ? tags({
52
53
  title: v.definition.title,
53
54
  description: v.definition.description,
54
- url: `${env.appUrl}/w/${wizard[1]}`,
55
+ url: `${env.appUrl}/w/${wizard[1]}${wizard[2] ?? ""}`,
55
56
  })
56
57
  : null;
57
58
  }
@@ -373,7 +373,7 @@ Returns the new revision and the issues.`,
373
373
  title: "Run wizard",
374
374
  description: `Start a run of a published wizard for the person, here in the chat. Spends credits like any run.
375
375
  Start it right away — no show_wizard first: the widget shows the wizard's pages and the person can answer there. What the person already said goes to the first page with answer_page, using the field ids in waitingFor. Then follow waitingFor:
376
- - page: ask the person for the fields with inChat=true, answer_page; fields with inChat=false (files, recordings, signatures) need the run page at browserUrl
376
+ - page: ask the person for the fields with inChat=true, in order, answer_page; fields with inChat=false (files, recordings, signatures) need the run page at browserUrl. A field with a when is asked only while its condition holds on the answers so far (shown says so for what is known now); fields the wizard decided against are not listed
377
377
  - review: show the outputs, then review_step
378
378
  - ask: answer_ask (allow/skip a change in a connected account) or the run page for a sign-in
379
379
  While status is running, get_run with waitSeconds. Hosts with MCP Apps also show the run as a widget the person can answer in.`,
@@ -0,0 +1,177 @@
1
+ import { conversationAccess } from "../models.js";
2
+ /**
3
+ * A live conversation with a wizard: the browser talks to a realtime speech model directly
4
+ * (audio both ways over WebRTC); this runtime only mints the short-lived secret the browser
5
+ * connects with, and writes the instructions and the tools the model drives the run with. The
6
+ * tools run in the browser against the run's own routes, so audio never touches the runtime.
7
+ */
8
+ const SECRETS_URL = "https://api.openai.com/v1/realtime/client_secrets";
9
+ const CALLS_URL = "https://api.openai.com/v1/realtime/calls";
10
+ /** How long a minted secret opens a session; the session itself goes on until it ends. */
11
+ const SECRET_TTL_SECONDS = 600;
12
+ /** The voice the wizard speaks with, by language. */
13
+ const VOICES = { de: "marin", en: "marin" };
14
+ /** What the model may do: one tool per command of the run page, run by the browser. */
15
+ export const CONVERSATION_TOOLS = [
16
+ {
17
+ type: "function",
18
+ name: "get_state",
19
+ description: "What the run waits for right now: the page with its fields (which are answered, which are still open, which need the screen), the review, or what the wizard is working on. Call it when unsure, and after the state changed.",
20
+ parameters: { type: "object", properties: {}, additionalProperties: false },
21
+ },
22
+ {
23
+ type: "function",
24
+ name: "set_field",
25
+ description: "Keeps the person's answer to one field of the current page. Call it once per field as soon as the person answered; for a choice give one of the options exactly.",
26
+ parameters: {
27
+ type: "object",
28
+ properties: {
29
+ field: { type: "string", description: "The field's id from the state." },
30
+ value: {
31
+ description: "The answer: a string, a number, true/false for a toggle, or an array of options for a multiple choice.",
32
+ },
33
+ },
34
+ required: ["field", "value"],
35
+ additionalProperties: false,
36
+ },
37
+ },
38
+ {
39
+ type: "function",
40
+ name: "submit_page",
41
+ description: "Sends the current page once every required field that can be answered by voice has a value. Fields that need the screen are filled there by the person; say so and wait.",
42
+ parameters: { type: "object", properties: {}, additionalProperties: false },
43
+ },
44
+ {
45
+ type: "function",
46
+ name: "accept_review",
47
+ description: "Accepts what the wizard made, when the person is happy with it.",
48
+ parameters: { type: "object", properties: {}, additionalProperties: false },
49
+ },
50
+ {
51
+ type: "function",
52
+ name: "regenerate",
53
+ description: "Asks the wizard to make one of the shown outputs again, with what should change.",
54
+ parameters: {
55
+ type: "object",
56
+ properties: {
57
+ target: { type: "string", description: "The step id of the output, from the state." },
58
+ note: { type: "string", description: "What should change, in the person's words." },
59
+ },
60
+ required: ["target", "note"],
61
+ additionalProperties: false,
62
+ },
63
+ },
64
+ {
65
+ type: "function",
66
+ name: "answer_ask",
67
+ description: "Answers the question a running step asks before it changes something in a connected account: allow it, or skip it.",
68
+ parameters: {
69
+ type: "object",
70
+ properties: { allow: { type: "boolean" } },
71
+ required: ["allow"],
72
+ additionalProperties: false,
73
+ },
74
+ },
75
+ {
76
+ type: "function",
77
+ name: "look",
78
+ description: "Takes a look through the person's camera right now: a picture of what they are showing arrives as the next message. Only while the camera is on; otherwise ask them to switch it on.",
79
+ parameters: { type: "object", properties: {}, additionalProperties: false },
80
+ },
81
+ {
82
+ type: "function",
83
+ name: "take_photo",
84
+ description: "Takes a photo with the person's camera and puts it into a photo field of the current page. Say 'hold it still' first. Only while the camera is on.",
85
+ parameters: {
86
+ type: "object",
87
+ properties: { field: { type: "string", description: "The id of the image field." } },
88
+ required: ["field"],
89
+ additionalProperties: false,
90
+ },
91
+ },
92
+ {
93
+ type: "function",
94
+ name: "go_back",
95
+ description: "Goes back to the page before, when the person wants to change an earlier answer.",
96
+ parameters: { type: "object", properties: {}, additionalProperties: false },
97
+ },
98
+ ];
99
+ /** The rules the model speaks by, in the wizard's language. */
100
+ export function conversationInstructions(view) {
101
+ const de = view.lang === "de";
102
+ const about = [
103
+ `${de ? "Du bist" : "You are"} ${view.wizard.title}.`,
104
+ view.wizard.description,
105
+ view.wizard.intro,
106
+ ]
107
+ .filter(Boolean)
108
+ .join(" ");
109
+ const rules = de
110
+ ? [
111
+ "Du führst ein Gespräch, das einen Wizard Schritt für Schritt ausfüllt. Die Person sieht den Wizard auch auf dem Bildschirm.",
112
+ "Sprich Deutsch, kurz und freundlich, wie am Telefon. Ein Satz, dann die nächste Frage.",
113
+ "Frag ein Feld nach dem anderen, in der Reihenfolge des Zustands. Nach jeder Antwort rufst du set_field auf. Sind alle Felder beantwortet, die du per Sprache füllen kannst, rufst du submit_page auf.",
114
+ "Bei einer Auswahl nennst du die Möglichkeiten (höchstens vier auf einmal) und gibst genau eine davon weiter.",
115
+ "E-Mail-Adressen, Links und Zahlen wiederholst du zur Bestätigung, bevor du sie weitergibst.",
116
+ "Ein Feld, das den Bildschirm braucht (ein Foto, eine Datei, eine Unterschrift, eine Verbindung), füllt die Person dort aus: sag das in einem Satz und warte auf den nächsten Zustand.",
117
+ "Während der Wizard arbeitet, sagst du in einem Satz, was er gerade tut, und wartest. Erfinde nichts.",
118
+ "Bei einer Prüfung liest du den Text kurz zusammengefasst vor und fragst, ob er passt. Dann accept_review, oder regenerate mit dem Wunsch der Person.",
119
+ "Am Ende sagst du, was entstanden ist und dass es auf dem Bildschirm liegt.",
120
+ "Ist die Kamera an, kannst du mit look sehen, was die Person zeigt, und mit take_photo ein Foto in ein Fotofeld legen; ein Fotofeld fragst du dann so: „Halte es in die Kamera, ich mache das Foto.“ Ist die Kamera aus, bitte die Person, sie einzuschalten, oder lass das Feld dem Bildschirm.",
121
+ ]
122
+ : [
123
+ "You hold a conversation that fills in a wizard step by step. The person also sees the wizard on the screen.",
124
+ "Speak English, short and friendly, as on the phone. One sentence, then the next question.",
125
+ "Ask one field at a time, in the order of the state. After each answer call set_field. When every field you can fill by voice is answered, call submit_page.",
126
+ "For a choice, name the options (at most four at a time) and pass exactly one of them on.",
127
+ "Read e-mail addresses, links and numbers back before passing them on.",
128
+ "A field that needs the screen (a photo, a file, a signature, a connection) is filled there by the person: say so in one sentence and wait for the next state.",
129
+ "While the wizard works, say in one sentence what it is doing and wait. Never make anything up.",
130
+ "At a review, sum the text up in a few words and ask whether it fits. Then accept_review, or regenerate with what the person wants changed.",
131
+ "At the end, say what was made and that it is on the screen.",
132
+ "With the camera on you can see what the person shows with look, and put a photo into a photo field with take_photo; ask for a photo field like this: 'Hold it to the camera, I will take the picture.' With the camera off, ask the person to switch it on, or leave the field to the screen.",
133
+ ];
134
+ return `${about}\n\n${rules.join("\n")}`;
135
+ }
136
+ /** Mints the secret a browser opens a session with. */
137
+ export async function mintConversation(view) {
138
+ const { apiKey, model } = await conversationAccess();
139
+ const res = await fetch(SECRETS_URL, {
140
+ method: "POST",
141
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
142
+ body: JSON.stringify({
143
+ expires_after: { anchor: "created_at", seconds: SECRET_TTL_SECONDS },
144
+ session: {
145
+ type: "realtime",
146
+ model,
147
+ instructions: conversationInstructions(view),
148
+ tools: CONVERSATION_TOOLS,
149
+ tool_choice: "auto",
150
+ audio: {
151
+ // What the person said, written down: the call screen shows it as captions.
152
+ input: { transcription: { model: "gpt-4o-mini-transcribe" } },
153
+ output: { voice: VOICES[view.lang] },
154
+ },
155
+ },
156
+ }),
157
+ signal: AbortSignal.timeout(15_000),
158
+ });
159
+ if (!res.ok) {
160
+ // The provider's answer goes to the log; the page hears only that it did not work, and why in a word.
161
+ const detail = (await res.text()).slice(0, 500);
162
+ console.error(`[talk] the provider refused the session (${res.status}):`, detail);
163
+ throw new Error(res.status === 401 || res.status === 403
164
+ ? "The conversation could not be started: the OpenAI API key was refused."
165
+ : `The conversation could not be started (${res.status}).`);
166
+ }
167
+ const body = (await res.json());
168
+ if (!body.value) {
169
+ throw new Error("The conversation could not be started: no secret came back.");
170
+ }
171
+ return {
172
+ clientSecret: body.value,
173
+ expiresAt: new Date((body.expires_at ?? Date.now() / 1000 + SECRET_TTL_SECONDS) * 1000).toISOString(),
174
+ model,
175
+ endpoint: `${CALLS_URL}?model=${encodeURIComponent(model)}`,
176
+ };
177
+ }
@@ -706,6 +706,23 @@ async function gatewayRefuses(key, id, cls) {
706
706
  gatewayProbes.set(at, { refused, at: Date.now() });
707
707
  return refused;
708
708
  }
709
+ /** The realtime speech model a live conversation runs on; a setting of the install may name another. */
710
+ const CONVERSATION_MODEL = env.conversationModel || "gpt-realtime";
711
+ /**
712
+ * What a live conversation with a wizard runs on: the tenant's own OpenAI key, until a class of
713
+ * its own exists on the Models page and on the account's credits.
714
+ */
715
+ export async function conversationAccess() {
716
+ const cfg = await config();
717
+ if (!cfg.keys.openai) {
718
+ throw new ModelUnavailableError("Für Sprachgespräche ist kein OpenAI API Key hinterlegt (Einstellungen → Modelle).");
719
+ }
720
+ return { apiKey: cfg.keys.openai, model: CONVERSATION_MODEL };
721
+ }
722
+ /** Whether a live conversation can be started here. */
723
+ export async function conversationAvailable() {
724
+ return Boolean((await config()).keys.openai);
725
+ }
709
726
  /** Why the own AI Gateway key cannot reach what a class runs on, or null. */
710
727
  async function gatewayProblem(cls, ref) {
711
728
  const { provider, id } = parse(ref);