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
@@ -1,9 +1,11 @@
1
1
  import { existsSync, mkdirSync, watch } from "node:fs";
2
2
  import { join, resolve, sep } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import { PLUGIN_ID, PLUGIN_TOOL_NAME, wizardSchema } from "@engenty-wizards/shared/definition";
4
+ import { FIELD_KINDS, PLUGIN_ID, PLUGIN_TOOL_NAME, wizardSchema, } from "@engenty-wizards/shared/definition";
5
+ import { BUILT_IN_RUNNERS, OUTPUT_KINDS, RESERVED_PATHS, RUNNER_ID, } from "@engenty-wizards/shared/runners";
5
6
  import { generateText, Output } from "ai";
6
7
  import { createJiti } from "jiti";
8
+ import { z } from "zod";
7
9
  import { readPage } from "../agents/website.js";
8
10
  import { packageRoot } from "../cli/home.js";
9
11
  import { pluginConnections } from "../connectors/plugin-connections.js";
@@ -11,7 +13,7 @@ import { db, onTenantOpen } from "../db/client.js";
11
13
  import { parseDocument } from "../documents/parse.js";
12
14
  import { env } from "../env.js";
13
15
  import { managed } from "../manage.js";
14
- import { ModelUnavailableError, textModel } from "../models.js";
16
+ import { conversationAccess, ModelUnavailableError, textModel } from "../models.js";
15
17
  import { putIndexEntry, removeIndexEntries } from "../services/project-index.js";
16
18
  import { originData } from "../services/space-origin.js";
17
19
  import { safeFetch } from "../tools/net-guard.js";
@@ -20,6 +22,7 @@ import { migrateOpenTenants, migratePlugins } from "./migrations.js";
20
22
  import { proModulesDir, proSources } from "./pro-state.js";
21
23
  import { publicUrlOf } from "./public.js";
22
24
  import { announceChange, compileRoute, dropPlugin, emptyRecord, loadedPlugin, loadedPlugins, setPlugin, } from "./registry.js";
25
+ import { runsApiFor } from "./runs.js";
23
26
  /**
24
27
  * Loading plugins (docs/content/dev/plugins). A plugin's server half is TypeScript or JavaScript read
25
28
  * from its file as it is: no build step, and a reload reads the files again. What a plugin
@@ -34,6 +37,7 @@ const own = (specifier) => fileURLToPath(import.meta.resolve(specifier));
34
37
  /** The longer name first: an alias also matches what begins with it. */
35
38
  function aliases() {
36
39
  return {
40
+ "@engenty-wizards/plugin-sdk/thread": own("@engenty-wizards/plugin-sdk/thread"),
37
41
  "@engenty-wizards/plugin-sdk": own("@engenty-wizards/plugin-sdk"),
38
42
  "drizzle-orm/sqlite-core": own("drizzle-orm/sqlite-core"),
39
43
  "drizzle-orm": own("drizzle-orm"),
@@ -51,6 +55,26 @@ async function importFactory(entry) {
51
55
  }
52
56
  /** A job runs at most this often. */
53
57
  const MIN_EVERY_MS = 60_000;
58
+ /** The built-in runners and the sub-paths of a wizard's address that are something else. */
59
+ const RESERVED_RUNNER_IDS = new Set([...BUILT_IN_RUNNERS.map((r) => r.id), ...RESERVED_PATHS]);
60
+ /** What a plugin says about a runner, checked: the lists hold known kinds only. */
61
+ const runnerInfoSchema = z.object({
62
+ id: z.string().regex(RUNNER_ID, 'lower case, digits and "-", at most 24 characters'),
63
+ label: z.object({ de: z.string().min(1), en: z.string().min(1) }),
64
+ kind: z.enum(["page", "channel"]),
65
+ capabilities: z.object({
66
+ input: z.array(z.enum(FIELD_KINDS)),
67
+ output: z.object({
68
+ shows: z.array(z.enum(OUTPUT_KINDS)),
69
+ pictures: z.array(z.enum(OUTPUT_KINDS)),
70
+ }),
71
+ asks: z.array(z.enum(["confirm", "login"])),
72
+ review: z.array(z.enum(["accept", "regenerate", "edit"])),
73
+ waits: z.boolean(),
74
+ handoff: z.array(z.enum(["screen", "thread", "sms", "push"])),
75
+ }),
76
+ plugin: z.string(),
77
+ });
54
78
  function apiFor(record) {
55
79
  const { source } = record;
56
80
  const tag = `[plugin ${source.id}]`;
@@ -107,7 +131,28 @@ function apiFor(record) {
107
131
  registerPublicRoute(route) {
108
132
  record.publicRoutes.push(compileRoute(route));
109
133
  },
134
+ registerRunner(runner) {
135
+ const info = runnerInfoSchema.parse({ ...runner, plugin: source.id });
136
+ if (record.runners.has(info.id) || RESERVED_RUNNER_IDS.has(info.id)) {
137
+ throw new Error(`Runner "${info.id}" is taken.`);
138
+ }
139
+ if (info.kind === "page" && typeof runner.page !== "function") {
140
+ throw new Error(`Runner "${info.id}": a page runner needs a page.`);
141
+ }
142
+ record.runners.set(info.id, { info, page: runner.page, problem: runner.problem });
143
+ },
110
144
  publicUrl: (path) => publicUrlOf(source.id, path),
145
+ runs: runsApiFor(source.id),
146
+ speech: {
147
+ async conversation() {
148
+ const access = await conversationAccess().catch((err) => {
149
+ throw err instanceof ModelUnavailableError
150
+ ? Object.assign(err, { name: "ModelUnavailableError", status: 503, code: "no_model" })
151
+ : err;
152
+ });
153
+ return { provider: "openai", ...access };
154
+ },
155
+ },
111
156
  every(name, everyMs, handler) {
112
157
  named("Job", name);
113
158
  if (record.jobs.has(name)) {
@@ -209,6 +254,7 @@ async function load(source) {
209
254
  record.assistantTools.clear();
210
255
  record.assistantPages = [];
211
256
  record.publicRoutes = [];
257
+ record.runners.clear();
212
258
  record.jobs.clear();
213
259
  record.starters.clear();
214
260
  record.listeners = {};
@@ -19,6 +19,7 @@ export function emptyRecord(source) {
19
19
  assistantTools: new Map(),
20
20
  assistantPages: [],
21
21
  publicRoutes: [],
22
+ runners: new Map(),
22
23
  jobs: new Map(),
23
24
  starters: new Map(),
24
25
  listeners: {},
@@ -0,0 +1,205 @@
1
+ import { createHash } from "node:crypto";
2
+ import { wizardLang } from "@engenty-wizards/shared/definition";
3
+ import { noteText } from "@engenty-wizards/shared/run";
4
+ import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
5
+ import { db, schema, withTenant } from "../db/client.js";
6
+ import { answerAsk } from "../engine/asks.js";
7
+ import { subscribe } from "../engine/events.js";
8
+ import { cancel, createRun, goBack, NoCreditsError, RunInputError, retry, reviewStep, submitPage, } from "../engine/runner.js";
9
+ import { saveAsset } from "../files/storage.js";
10
+ import { wizardUnavailable } from "../limits.js";
11
+ import { transcribeAudio } from "../media/transcribe.js";
12
+ import { ModelUnavailableError } from "../model-errors.js";
13
+ import { runTicket } from "../secrets/signing.js";
14
+ import { notFound, ServiceError } from "../services/errors.js";
15
+ import { runnerSettingsOf, runnersOf } from "../services/runners.js";
16
+ import { pluginRun, refusedInput, runReportOf, waitRun } from "../services/runs.js";
17
+ import { shareUrl } from "../services/wizards.js";
18
+ import { visitorOverLimit } from "../tenants/control.js";
19
+ import { currentTenant } from "../tenants/tenant.js";
20
+ /**
21
+ * `wizards.server.runs`: the functions behind the MCP tools, for a plugin's door. A run started
22
+ * here is a live run of the published wizard for a person of that door; the plugin keeps who
23
+ * the person is, the runtime keeps a hash of it as the run's visitor, so what the wizard
24
+ * remembers is theirs on the run page too.
25
+ */
26
+ /** A person of a door as the run's visitor: a hash, never the number or the account itself. */
27
+ function visitorOf(person) {
28
+ return `p:${createHash("sha256").update(`${person.channel}:${person.id}`).digest("hex").slice(0, 32)}`;
29
+ }
30
+ export function runsApiFor(pluginId) {
31
+ return {
32
+ async start(input) {
33
+ const w = await db.query.wizard.findFirst({
34
+ where: and(eq(schema.wizard.tenantId, currentTenant()), "token" in input
35
+ ? eq(schema.wizard.shareToken, input.token)
36
+ : eq(schema.wizard.id, input.wizardId)),
37
+ });
38
+ if (!w || w.publishedVersion === null) {
39
+ throw notFound();
40
+ }
41
+ const reason = await wizardUnavailable(w);
42
+ if (reason) {
43
+ throw new ServiceError("refused", reason);
44
+ }
45
+ const visitorId = visitorOf(input.person);
46
+ if (await visitorOverLimit(visitorId, null)) {
47
+ throw new ServiceError("refused", "This person started many runs lately. Try again in an hour.");
48
+ }
49
+ const version = await db.query.wizardVersion.findFirst({
50
+ where: and(eq(schema.wizardVersion.wizardId, w.id), eq(schema.wizardVersion.version, w.publishedVersion)),
51
+ });
52
+ if (!version) {
53
+ throw notFound();
54
+ }
55
+ const runId = await createRun({
56
+ wizardId: w.id,
57
+ definition: version.definition,
58
+ files: version.files,
59
+ version: w.publishedVersion,
60
+ mode: "live",
61
+ visitorId,
62
+ runner: input.runner ?? pluginId,
63
+ }).catch((err) => {
64
+ if (err instanceof ModelUnavailableError) {
65
+ throw new ServiceError("refused", err.message);
66
+ }
67
+ if (err instanceof NoCreditsError) {
68
+ throw new ServiceError("no_credits", "The wizard's credits are used up.");
69
+ }
70
+ throw err;
71
+ });
72
+ const first = version.definition.steps[0];
73
+ let refused = null;
74
+ if (first?.type === "page" && input.answers && Object.keys(input.answers).length) {
75
+ const answers = input.answers;
76
+ const values = Object.fromEntries(first.fields.filter((f) => f.id in answers).map((f) => [f.id, answers[f.id]]));
77
+ try {
78
+ await submitPage(runId, first.id, values);
79
+ }
80
+ catch (err) {
81
+ if (!(err instanceof RunInputError)) {
82
+ throw err;
83
+ }
84
+ refused = err.errors;
85
+ }
86
+ }
87
+ return { runId, ticket: runTicket(runId), refused };
88
+ },
89
+ async report(runId, options) {
90
+ const run = await waitRun(() => pluginRun(runId), options?.waitSeconds ?? 0);
91
+ return (await runReportOf(run, options?.draft));
92
+ },
93
+ async wizards(runner) {
94
+ const rows = await db.query.wizard.findMany({
95
+ where: and(eq(schema.wizard.tenantId, currentTenant()), isNotNull(schema.wizard.publishedVersion)),
96
+ orderBy: asc(schema.wizard.createdAt),
97
+ });
98
+ const available = await runnersOf();
99
+ const offered = rows.filter((w) => runnerSettingsOf(w, available).enabled.includes(runner));
100
+ const versions = offered.length
101
+ ? await db.query.wizardVersion.findMany({
102
+ where: inArray(schema.wizardVersion.wizardId, offered.map((w) => w.id)),
103
+ })
104
+ : [];
105
+ return offered.flatMap((w) => {
106
+ const version = versions.find((v) => v.wizardId === w.id && v.version === w.publishedVersion);
107
+ return version
108
+ ? [
109
+ {
110
+ wizardId: w.id,
111
+ token: w.shareToken,
112
+ title: version.definition.title,
113
+ lang: wizardLang(version.definition),
114
+ },
115
+ ]
116
+ : [];
117
+ });
118
+ },
119
+ async answerPage(runId, stepId, values) {
120
+ await pluginRun(runId);
121
+ await submitPage(runId, stepId, values).catch(refusedInput);
122
+ },
123
+ async review(runId, stepId, action) {
124
+ await pluginRun(runId);
125
+ await reviewStep(runId, stepId, action).catch(refusedInput);
126
+ },
127
+ async answerAsk(runId, askId, answer) {
128
+ await pluginRun(runId);
129
+ if (!answerAsk(runId, askId, answer === "allow" ? { type: "done" } : { type: "skip" })) {
130
+ throw new ServiceError("refused", "This question is no longer open.");
131
+ }
132
+ },
133
+ async control(runId, action) {
134
+ await pluginRun(runId);
135
+ const command = { back: goBack, retry, cancel }[action];
136
+ await command(runId).catch(refusedInput);
137
+ },
138
+ subscribe(runId, listener) {
139
+ // The listener runs inside the tenant the subscription was made in, as the events do.
140
+ const tenantId = currentTenant();
141
+ return subscribe(runId, (signal) => {
142
+ const event = signal.event;
143
+ const shaped = {
144
+ runId: signal.runId,
145
+ event: event
146
+ ? {
147
+ id: event.id,
148
+ at: event.at,
149
+ stepId: event.stepId,
150
+ type: event.type,
151
+ message: event.message,
152
+ note: event.note
153
+ ? {
154
+ code: event.note.code,
155
+ text: { de: noteText(event.note, "de"), en: noteText(event.note, "en") },
156
+ }
157
+ : null,
158
+ }
159
+ : null,
160
+ };
161
+ void withTenant(tenantId, () => listener(shaped));
162
+ });
163
+ },
164
+ async handoffUrl(runId) {
165
+ const run = await pluginRun(runId);
166
+ const w = await db.query.wizard.findFirst({ where: eq(schema.wizard.id, run.wizardId) });
167
+ if (!w) {
168
+ throw notFound();
169
+ }
170
+ return `${shareUrl(w.shareToken)}/${run.id}?rt=${encodeURIComponent(runTicket(run.id))}`;
171
+ },
172
+ async upload(runId, file) {
173
+ await pluginRun(runId);
174
+ const asset = await saveAsset({
175
+ runId,
176
+ kind: file.mime.startsWith("image/") ? "image" : "file",
177
+ mime: file.mime,
178
+ name: file.name,
179
+ data: file.data instanceof Uint8Array ? file.data : new Uint8Array(file.data),
180
+ });
181
+ return { assetId: asset.id };
182
+ },
183
+ async transcribe(runId, file) {
184
+ const run = await pluginRun(runId);
185
+ if (run.status === "done" || run.status === "cancelled" || run.status === "failed") {
186
+ throw new ServiceError("refused", "The run is over.");
187
+ }
188
+ const bytes = file.data instanceof Uint8Array ? file.data : new Uint8Array(file.data);
189
+ if (!bytes.length || bytes.length > 10_000_000) {
190
+ throw new ServiceError("invalid", "A recording of up to 10 MB.");
191
+ }
192
+ const { text } = await transcribeAudio({
193
+ bytes,
194
+ mediaType: file.mime.split(";")[0].trim() || "audio/ogg",
195
+ call: { runId: run.id },
196
+ }).catch((err) => {
197
+ if (err instanceof ModelUnavailableError) {
198
+ throw new ServiceError("refused", err.message);
199
+ }
200
+ throw err;
201
+ });
202
+ return { text };
203
+ },
204
+ };
205
+ }
@@ -8,26 +8,30 @@ import { streamSSE } from "hono/streaming";
8
8
  import { nanoid } from "nanoid";
9
9
  import { z } from "zod";
10
10
  import { principalOf } from "../auth/index.js";
11
+ import { MARK_FOCUSED_PERSONAL } from "../browser/snapshot.js";
11
12
  import { ConnectError, connectionViews, connectWithCredentials, disconnect, finishOAuth, oauthStateRun, startOAuth, } from "../connectors/index.js";
12
13
  import { finishPluginOAuth, pluginStateTenant } from "../connectors/plugin-connections.js";
13
14
  import { db, schema, withTenant } from "../db/client.js";
14
15
  import { answerAsk, pendingAsk } from "../engine/asks.js";
15
- import { signalChanged, subscribe } from "../engine/events.js";
16
+ import { emitEvent, signalChanged, subscribe } from "../engine/events.js";
16
17
  import { pushAvailable, setPushDevice } from "../engine/push.js";
17
18
  import { liveResources } from "../engine/resources.js";
18
19
  import { cancel, createRun, goBack, NoCreditsError, projectIdOf, RunConflict, RunInputError, retry, reviewStep, runView, submitPage, } from "../engine/runner.js";
19
20
  import { basePath, env } from "../env.js";
20
21
  import { loadAsset, saveAsset } from "../files/storage.js";
21
22
  import { reverseGeocode } from "../geocode.js";
22
- import { hashIp, verifyTurnstile, wizardUnavailable } from "../limits.js";
23
+ import { allowed, hashIp, verifyTurnstile, wizardUnavailable } from "../limits.js";
24
+ import { mintConversation } from "../media/conversation.js";
25
+ import { transcribeAudio } from "../media/transcribe.js";
23
26
  import { ModelUnavailableError } from "../model-errors.js";
24
27
  import { listDownload, renderDownload, stepHtml } from "../render/downloads.js";
25
28
  import { HTML_RESPONSE_CSP } from "../render/guard.js";
26
29
  import { runTicketValid, verifySignedUrl } from "../secrets/signing.js";
27
30
  import { brandView } from "../services/brand.js";
28
31
  import { ServiceError } from "../services/errors.js";
32
+ import { publicRunners, servePageRunner } from "../services/runners.js";
29
33
  import { sharedRun, shareImage, shareRun, shareView, unshareRun } from "../services/shares.js";
30
- import { isIconFile, wizardIcon } from "../services/wizard-icon.js";
34
+ import { isIconFile, wizardAvatarSvg, wizardIcon } from "../services/wizard-icon.js";
31
35
  import { clearStore, deleteRows, listRows, listSecrets, readStoreFile, StoreError, saveRows, scopeOf, storeFiles, updateRow, } from "../store/index.js";
32
36
  import { tenantOfLink, tenantOfRun, tenantStatus, tokenOfCode, visitorOverLimit, } from "../tenants/control.js";
33
37
  import { byteRange, uploadLimit, wizardManifest } from "./delivery.js";
@@ -151,6 +155,22 @@ function codeMissed(ip) {
151
155
  codeMisses.delete(codeMisses.keys().next().value);
152
156
  }
153
157
  }
158
+ /** A plugin's page runner behind a wizard's address, or 404 where the wizard does not offer it. */
159
+ async function pageRunner(c, rest) {
160
+ const w = await db.query.wizard.findFirst({
161
+ where: eq(schema.wizard.shareToken, c.req.param("token") ?? ""),
162
+ });
163
+ if (!w || w.publishedVersion === null) {
164
+ return c.json({ error: "not found" }, 404);
165
+ }
166
+ const version = await db.query.wizardVersion.findFirst({
167
+ where: and(eq(schema.wizardVersion.wizardId, w.id), eq(schema.wizardVersion.version, w.publishedVersion)),
168
+ });
169
+ const served = version
170
+ ? await servePageRunner(w, version.definition, c.req.param("runner") ?? "", rest, c.req.raw)
171
+ : null;
172
+ return served ?? c.json({ error: "not found" }, 404);
173
+ }
154
174
  export const publicRoutes = new Hono()
155
175
  // A wizard's ID, typed into the mobile app: answers its share token.
156
176
  .get("/codes/:code", async (c) => {
@@ -190,6 +210,7 @@ export const publicRoutes = new Hono()
190
210
  turnstileSiteKey: env.turnstile.siteKey || null,
191
211
  available: !reason,
192
212
  unavailableReason: reason,
213
+ runners: await publicRunners(w, def),
193
214
  };
194
215
  return c.json(body);
195
216
  })
@@ -240,6 +261,10 @@ export const publicRoutes = new Hono()
240
261
  throw err;
241
262
  }
242
263
  })
264
+ // A plugin's page runner for this wizard: what `/w/<token>/<runner>` serves built, reached here from source.
265
+ .all("/wizards/:token/runners/:runner", (c) => pageRunner(c, ""))
266
+ .all("/wizards/:token/runners/:runner/*", (c) => pageRunner(c, c.req.path.slice(c.req.path.indexOf(`/runners/${c.req.param("runner")}`) +
267
+ `/runners/${c.req.param("runner")}`.length)))
243
268
  // A published wizard as an app of its own: added to a phone's home screen it opens on its link.
244
269
  .get("/wizards/:token/manifest.webmanifest", async (c) => {
245
270
  const w = await db.query.wizard.findFirst({
@@ -257,6 +282,22 @@ export const publicRoutes = new Hono()
257
282
  "content-type": "application/manifest+json; charset=utf-8",
258
283
  "cache-control": "public, max-age=300",
259
284
  });
285
+ })
286
+ // Its engenty as the chat button a website shows it behind (`embed.js`).
287
+ .get("/wizards/:token/avatar.svg", async (c) => {
288
+ const w = await db.query.wizard.findFirst({
289
+ where: eq(schema.wizard.shareToken, c.req.param("token")),
290
+ });
291
+ if (!w || w.publishedVersion === null) {
292
+ return c.notFound();
293
+ }
294
+ const version = await db.query.wizardVersion.findFirst({
295
+ where: and(eq(schema.wizardVersion.wizardId, w.id), eq(schema.wizardVersion.version, w.publishedVersion)),
296
+ });
297
+ return c.body(wizardAvatarSvg(version.definition.avatar), 200, {
298
+ "content-type": "image/svg+xml; charset=utf-8",
299
+ "cache-control": "public, max-age=3600",
300
+ });
260
301
  })
261
302
  // Its icon: the wizard's engenty on its hue with its name; the studio's where none can be drawn.
262
303
  .get("/wizards/:token/icons/:file", async (c) => {
@@ -415,6 +456,61 @@ export const runRoutes = new Hono()
415
456
  }
416
457
  await cancel(run.id);
417
458
  return c.json({ ok: true });
459
+ })
460
+ // A live conversation on the run: the secret the browser opens the session with.
461
+ .post("/:id/talk", async (c) => {
462
+ const run = await accessibleRun(c, c.req.param("id"));
463
+ if (!run) {
464
+ return c.json({ error: "not found" }, 404);
465
+ }
466
+ if (run.status === "done" || run.status === "cancelled" || run.status === "failed") {
467
+ return c.json({ error: "Der Durchlauf ist beendet." }, 409);
468
+ }
469
+ if (!allowed(`talk:${run.id}`, 20, 3600_000)) {
470
+ return c.json({ error: "Bitte später noch einmal." }, 429);
471
+ }
472
+ try {
473
+ const view = await viewOf(run);
474
+ return c.json(await mintConversation(view));
475
+ }
476
+ catch (err) {
477
+ if (err instanceof ModelUnavailableError) {
478
+ return c.json({ error: err.message }, 403);
479
+ }
480
+ console.error("[talk]", err);
481
+ return c.json({ error: err.message }, 502);
482
+ }
483
+ })
484
+ // What the person says into the chat's composer, written down — where the browser cannot do it itself.
485
+ .post("/:id/transcribe", async (c) => {
486
+ const run = await accessibleRun(c, c.req.param("id"));
487
+ if (!run) {
488
+ return c.json({ error: "not found" }, 404);
489
+ }
490
+ if (run.status === "done" || run.status === "cancelled" || run.status === "failed") {
491
+ return c.json({ error: "Der Durchlauf ist beendet." }, 409);
492
+ }
493
+ if (!allowed(`transcribe:${run.id}`, 60, 3600_000)) {
494
+ return c.json({ error: "Bitte später noch einmal." }, 429);
495
+ }
496
+ const file = (await c.req.formData()).get("file");
497
+ if (!(file instanceof File) || !file.size || file.size > 10_000_000) {
498
+ return c.json({ error: "Bitte eine Aufnahme bis 10 MB." }, 400);
499
+ }
500
+ try {
501
+ const { text } = await transcribeAudio({
502
+ bytes: new Uint8Array(await file.arrayBuffer()),
503
+ mediaType: file.type.split(";")[0].trim() || "audio/webm",
504
+ call: { runId: run.id },
505
+ });
506
+ return c.json({ text });
507
+ }
508
+ catch (err) {
509
+ if (err instanceof ModelUnavailableError) {
510
+ return c.json({ error: err.message }, 403);
511
+ }
512
+ throw err;
513
+ }
418
514
  })
419
515
  .post("/:id/uploads", async (c) => {
420
516
  const run = await accessibleRun(c, c.req.param("id"));
@@ -489,35 +585,121 @@ export const runRoutes = new Hono()
489
585
  }
490
586
  return c.json({ ok: true });
491
587
  })
492
- // The page the wizard's browser shows: the person sees what they are asked to sign in to.
493
- .get("/:id/browser/screen", async (c) => {
588
+ // Who drives the wizard's browser: the wizard, or the person who took it over.
589
+ .get("/:id/browser/seat", async (c) => {
494
590
  const run = await accessibleRun(c, c.req.param("id"));
495
- const page = run?.status === "running" ? liveResources(run.id)?.openPage() : null;
496
- if (!page) {
497
- return c.notFound();
591
+ const resources = run?.status === "running" ? liveResources(run.id) : null;
592
+ if (!resources?.openPage()) {
593
+ return c.json({ error: "not found" }, 404);
498
594
  }
499
- const jpeg = await page.screenshot({ type: "jpeg", quality: 70 }).catch(() => null);
500
- if (!jpeg) {
595
+ return c.json({ seat: resources.seatHolder() });
596
+ })
597
+ // The person takes the wizard's browser over, or hands it back. While they hold it, the
598
+ // wizard's browser steps wait.
599
+ .post("/:id/browser/seat", async (c) => {
600
+ const run = await accessibleRun(c, c.req.param("id"));
601
+ const resources = run?.status === "running" ? liveResources(run.id) : null;
602
+ if (!(run && resources?.openPage())) {
603
+ return c.json({ error: "Der Wizard hat gerade keinen Browser offen." }, 409);
604
+ }
605
+ const { to } = z.object({ to: z.enum(["person", "agent"]) }).parse(await c.req.json());
606
+ if (resources.seatHolder() !== to) {
607
+ resources.setSeat(to);
608
+ await emitEvent(run.id, run.cursor, "info", {
609
+ code: to === "person" ? "personDrives" : "agentDrives",
610
+ }).catch(() => undefined);
611
+ }
612
+ return c.json({ seat: to });
613
+ })
614
+ // The wizard's browser as it works, as a picture that keeps changing (MJPEG, for an <img>):
615
+ // a new frame whenever the page repaints, at most about five a second. Ends with the run's
616
+ // browser.
617
+ .get("/:id/browser/live", async (c) => {
618
+ const run = await accessibleRun(c, c.req.param("id"));
619
+ const resources = run?.status === "running" ? liveResources(run.id) : null;
620
+ if (!resources?.openPage()) {
501
621
  return c.notFound();
502
622
  }
503
- const size = page.viewportSize() ?? { width: 1280, height: 900 };
504
- return c.body(new Uint8Array(jpeg), 200, {
505
- "content-type": "image/jpeg",
506
- "cache-control": "no-store",
507
- "x-page-width": String(size.width),
508
- "x-page-height": String(size.height),
623
+ const boundary = "frame";
624
+ const encoder = new TextEncoder();
625
+ let stop = () => undefined;
626
+ const body = new ReadableStream({
627
+ start(controller) {
628
+ let latest = null;
629
+ let sentAt = 0;
630
+ let timer = null;
631
+ const send = () => {
632
+ timer = null;
633
+ if (!latest) {
634
+ return;
635
+ }
636
+ sentAt = Date.now();
637
+ const head = `--${boundary}\r\nContent-Type: image/jpeg\r\nContent-Length: ${latest.length}\r\n\r\n`;
638
+ try {
639
+ controller.enqueue(encoder.encode(head));
640
+ controller.enqueue(new Uint8Array(latest));
641
+ controller.enqueue(encoder.encode("\r\n"));
642
+ }
643
+ catch {
644
+ stop();
645
+ }
646
+ latest = null;
647
+ };
648
+ const unwatch = resources.watchBrowser((frame) => {
649
+ if (!frame) {
650
+ stop();
651
+ try {
652
+ controller.close();
653
+ }
654
+ catch {
655
+ // already closed by the viewer
656
+ }
657
+ return;
658
+ }
659
+ latest = frame;
660
+ if (!timer) {
661
+ timer = setTimeout(send, Math.max(0, 200 - (Date.now() - sentAt)));
662
+ }
663
+ });
664
+ stop = () => {
665
+ if (timer) {
666
+ clearTimeout(timer);
667
+ }
668
+ unwatch();
669
+ };
670
+ },
671
+ cancel() {
672
+ stop();
673
+ },
674
+ });
675
+ c.req.raw.signal.addEventListener("abort", () => stop());
676
+ return new Response(body, {
677
+ headers: {
678
+ "content-type": `multipart/x-mixed-replace; boundary=${boundary}`,
679
+ "cache-control": "no-store",
680
+ "x-accel-buffering": "no",
681
+ },
509
682
  });
510
683
  })
511
- // While the wizard waits for a sign-in, the person can use its page: click, type, scroll.
684
+ // While the wizard waits for a sign-in, or the person took its browser over, they use its
685
+ // page: click, type, scroll. What they type is theirs: no reading of the page gives it to a
686
+ // model.
512
687
  .post("/:id/browser/act", async (c) => {
513
688
  const run = await accessibleRun(c, c.req.param("id"));
514
- const page = run && pendingAsk(run.id) ? liveResources(run.id)?.openPage() : null;
515
- if (!page) {
689
+ const resources = run ? liveResources(run.id) : null;
690
+ const theirs = run && (pendingAsk(run.id) || resources?.seatHolder() === "person");
691
+ const page = theirs ? resources?.openPage() : null;
692
+ if (!(run && resources && page)) {
516
693
  return c.json({ error: "Der Wizard wartet gerade nicht auf dich." }, 409);
517
694
  }
695
+ resources.touchSeat();
518
696
  const act = z
519
697
  .discriminatedUnion("type", [
520
- z.object({ type: z.literal("click"), x: z.number().min(0), y: z.number().min(0) }),
698
+ z.object({
699
+ type: z.literal("click"),
700
+ fx: z.number().min(0).max(1),
701
+ fy: z.number().min(0).max(1),
702
+ }),
521
703
  z.object({ type: z.literal("type"), text: z.string().max(500) }),
522
704
  z.object({ type: z.literal("key"), key: z.enum(["Enter", "Tab", "Backspace", "Escape"]) }),
523
705
  z.object({ type: z.literal("scroll"), dy: z.number().min(-2000).max(2000) }),
@@ -530,13 +712,15 @@ export const runRoutes = new Hono()
530
712
  .context()
531
713
  .waitForEvent("page", { timeout: 1500 })
532
714
  .catch(() => null);
533
- await page.mouse.click(act.x, act.y);
715
+ const size = page.viewportSize() ?? { width: 1280, height: 900 };
716
+ await page.mouse.click(act.fx * size.width, act.fy * size.height);
534
717
  const opened = await popup;
535
718
  if (opened) {
536
- liveResources(run.id)?.adopt(opened);
719
+ resources.adopt(opened);
537
720
  }
538
721
  }
539
722
  else if (act.type === "type") {
723
+ await page.evaluate(MARK_FOCUSED_PERSONAL).catch(() => undefined);
540
724
  await page.keyboard.type(act.text);
541
725
  }
542
726
  else if (act.type === "key") {
@@ -41,6 +41,7 @@ import { profileSchema, saveProfile, userProfile } from "../services/profile.js"
41
41
  import { addProjectFile, fileView, orderProjectFiles, projectFile, projectFileContent, projectFiles, reindexProjectFile, removeProjectFile, updateProjectFile, } from "../services/project-files.js";
42
42
  import { documentText, queueIndex, searchKnowledge } from "../services/project-index.js";
43
43
  import { createProject, deleteProject, listProjects, maskedServers, ownedProject, projectLimitOrNull, projectPatchSchema, updateProject, } from "../services/projects.js";
44
+ import { runnersOf, wizardRunners } from "../services/runners.js";
44
45
  import { listResults, listRuns, startTestRun } from "../services/runs.js";
45
46
  import { addCategoryValue, categoryRow, categoryValue, deleteCategory, deleteCategoryValue, mergeCategoryValues, orderCategoryValues, putCategory, renameCategoryValue, setItemCategory, updateCategory, } from "../services/space-categories.js";
46
47
  import { addTableRow, createPage, createTable, deletePage, deleteTable, deleteTableRows, getPage, getTable, listSpaceData, orderSubPages, updatePage, updateTable, updateTableRow, } from "../services/space-data.js";
@@ -786,11 +787,14 @@ export const studio = new Hono()
786
787
  shareEnabled: z.boolean().optional(),
787
788
  dailyRunLimit: z.number().int().min(1).max(10_000).optional(),
788
789
  projectId: z.string().optional(),
790
+ runners: z.object({ default: z.string(), enabled: z.array(z.string()).max(20) }).optional(),
789
791
  })
790
792
  .parse(await c.req.json());
791
793
  await updateWizardSettings(c.get("user").id, c.req.param("id"), patch);
792
794
  // The copy in the cloud of a linked account is shared the same way.
793
- if (patch.shareEnabled !== undefined || patch.dailyRunLimit !== undefined) {
795
+ if (patch.shareEnabled !== undefined ||
796
+ patch.dailyRunLimit !== undefined ||
797
+ patch.runners !== undefined) {
794
798
  await pushSharing(c.get("user").id, c.req.param("id"));
795
799
  }
796
800
  return c.json({ ok: true });
@@ -820,6 +824,13 @@ export const studio = new Hono()
820
824
  .get("/wizards/:id/estimate", async (c) => {
821
825
  const w = await ownedWizard(c.get("user").id, c.req.param("id"));
822
826
  return c.json(await estimateRun(w.id, null, w.draft, await stepsWithoutModel(w.draft)));
827
+ })
828
+ // The runners this tenant has: the home's channel filter and the icons on its cards.
829
+ .get("/runners", async (c) => c.json(await runnersOf()))
830
+ // The runners this tenant has, how each fits the draft, and how the wizard is offered.
831
+ .get("/wizards/:id/runners", async (c) => {
832
+ const w = await ownedWizard(c.get("user").id, c.req.param("id"));
833
+ return c.json(await wizardRunners(w));
823
834
  })
824
835
  // The models the draft needs that this runtime cannot serve, by class, with the steps that call them.
825
836
  .get("/wizards/:id/models", async (c) => {