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
@@ -2,13 +2,15 @@ import { existsSync } from "node:fs";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { BUILT_IN_RUNNERS, RUNNER_ID } from "@engenty-wizards/shared/runners";
5
6
  import { serveStatic } from "@hono/node-server/serve-static";
7
+ import { and, eq } from "drizzle-orm";
6
8
  import { Hono } from "hono";
7
9
  import { bodyLimit } from "hono/body-limit";
8
10
  import { HTTPException } from "hono/http-exception";
9
11
  import { ZodError } from "zod";
10
12
  import { authRoutes, principalOf } from "./auth/index.js";
11
- import { withTenant } from "./db/client.js";
13
+ import { db, schema, withTenant } from "./db/client.js";
12
14
  import { basePath, env } from "./env.js";
13
15
  import { linkPreview } from "./link-preview.js";
14
16
  import { discovery, managed } from "./manage.js";
@@ -27,6 +29,7 @@ import { wizardStream } from "./routes/wizard-stream.js";
27
29
  import { runTicketValid } from "./secrets/signing.js";
28
30
  import { asRole } from "./services/access.js";
29
31
  import { ServiceError } from "./services/errors.js";
32
+ import { servePageRunner } from "./services/runners.js";
30
33
  import { tenantOfLink, tenantStatus } from "./tenants/control.js";
31
34
  const app = new Hono();
32
35
  app.onError((err, c) => {
@@ -193,9 +196,37 @@ app.get(`/api/claude-plugin/${PLUGIN_NAME}.zip`, async (c) => {
193
196
  return c.body(new Uint8Array(zip), 200, { "content-type": "application/zip" });
194
197
  });
195
198
  app.all("/api/*", (c) => c.json({ error: "not found" }, 404));
196
- /** Link cards for `/w/<token>` and `/s/<token>`; the token names the tenant. */
199
+ /**
200
+ * `/w/<token>/<runner>`: a plugin's page runner, where the tenant has it and the wizard offers
201
+ * it; otherwise the next handler (the app's page, which knows `steps`, `chat` and run ids).
202
+ */
203
+ async function pluginRunnerPage(c, next) {
204
+ const token = c.req.param("token") ?? "";
205
+ const runnerId = c.req.param("runner") ?? "";
206
+ if (!RUNNER_ID.test(runnerId) || BUILT_IN_RUNNERS.some((r) => r.id === runnerId)) {
207
+ return next();
208
+ }
209
+ const tenant = await tenantOfLink(token, "wizard").catch(() => null);
210
+ if (!tenant) {
211
+ return next();
212
+ }
213
+ const served = await withTenant(tenant, async () => {
214
+ const w = await db.query.wizard.findFirst({ where: eq(schema.wizard.shareToken, token) });
215
+ if (!w || w.publishedVersion === null) {
216
+ return null;
217
+ }
218
+ const version = await db.query.wizardVersion.findFirst({
219
+ where: and(eq(schema.wizardVersion.wizardId, w.id), eq(schema.wizardVersion.version, w.publishedVersion)),
220
+ });
221
+ const head = `/w/${token}/${runnerId}`;
222
+ const rest = c.req.path.slice(c.req.path.indexOf(head) + head.length);
223
+ return version ? servePageRunner(w, version.definition, runnerId, rest, c.req.raw) : null;
224
+ });
225
+ return served ?? next();
226
+ }
227
+ /** Link cards for `/w/<token>`, `/w/<token>/chat` and `/s/<token>`; the token names the tenant. */
197
228
  async function previewFor(path) {
198
- const m = path.match(/^\/(w|s)\/([A-Za-z0-9_-]+)\/?$/);
229
+ const m = path.match(/^\/(w|s)\/([A-Za-z0-9_-]+)(?:\/chat)?\/?$/);
199
230
  const tenant = m ? await tenantOfLink(m[2], m[1] === "w" ? "wizard" : "result") : null;
200
231
  return tenant ? withTenant(tenant, () => linkPreview(path)) : null;
201
232
  }
@@ -214,6 +245,9 @@ if (existsSync(webDir)) {
214
245
  }
215
246
  app.use("/studio/*", serveStatic({ root: webDir, rewriteRequestPath: (path) => path.slice("/studio".length) }));
216
247
  app.get("/", (c) => c.redirect(`${basePath}/studio/`));
248
+ // A plugin's page runner lives at the wizard's address: `/w/<token>/<runner>`, before the app's page.
249
+ app.all("/w/:token/:runner/*", (c, next) => pluginRunnerPage(c, next));
250
+ app.all("/w/:token/:runner", (c, next) => pluginRunnerPage(c, next));
217
251
  app.get("*", async (c) => {
218
252
  if (!PAGES.test(c.req.path)) {
219
253
  return c.text("Not found", 404);
@@ -147,10 +147,13 @@ type AgentStep = {
147
147
  // project_list (by Kategorien), page_read / table_read / project_document (an item whole, by its path).
148
148
  // "pages" brings: page_read / page_write — Markdown pages of the space the wizard keeps for every run (notes, a log
149
149
  // that grows with append), shown to the admin under Space → Daten; page_read also reads Wissen by path.
150
- // "browser" brings: browser_open/click/type, browser_screenshot (the model looks at the page),
150
+ // "browser" brings: browser_open/read/click/type/select/scroll/press/back/wait, browser_screenshot (the model looks at the page),
151
+ // browser_run_fast (a decision model clicks through a page's mechanical part, where one is reached),
151
152
  // browser_request_credentials (the PERSON types a login into the page — the model never sees it; sign-ins can be remembered),
152
- // browser_request_user (the person solves a captcha or "continue with Google" in a picture of the page),
153
+ // browser_request_user (the person solves a captcha or "continue with Google" in the live page; they can also take the browser over any time),
153
154
  // browser_download (keeps a file from a signed-in site).
155
+ // It clicks cookie banners away by itself with the least consent (only necessary / reject all) —
156
+ // no need to say so in the instructions.
154
157
 
155
158
  type SurfaceStep = {
156
159
  type: "surface"
@@ -0,0 +1,162 @@
1
+ // From one observation to the classifier's two questions: an `operation`
2
+ // head — act on an element, scroll, wait, done, blocked — and one `target`
3
+ // head over every element the page offers. The element's kind names the
4
+ // operation (a field is typed into, an option is selected, everything else
5
+ // is clicked), so the classifier never has to split its mass between "click
6
+ // the field" and "type into the field" for the same element. One round trip;
7
+ // the answer is validated against exactly the ids that were offered. Ported
8
+ // from engenty-pro's fast loop.
9
+ import { NEXT_ACTION, TARGET } from "./instructions.js";
10
+ /** What the classifier may pick besides an element operation. */
11
+ export const CONTROL_OPERATIONS = ["DONE", "BLOCKED"];
12
+ /** The operation head's id for "interact with one element". */
13
+ export const ACT = "ACT";
14
+ /** The single target head's key in the questions and the answers. */
15
+ export const TARGET_HEAD = "target";
16
+ const KIND_TO_OPERATION = {
17
+ click: "CLICK",
18
+ fill: "TYPE_TEXT",
19
+ select: "SELECT",
20
+ };
21
+ /** The operation an observed element action executes. */
22
+ export function operationOf(action) {
23
+ return KIND_TO_OPERATION[action.kind] ?? null;
24
+ }
25
+ /**
26
+ * What makes two observed elements interchangeable for the classifier: a
27
+ * second "Search" button with the same role, label and state is the same
28
+ * step. Only the first such node is offered.
29
+ */
30
+ function duplicateKey(action) {
31
+ return JSON.stringify([
32
+ action.kind,
33
+ action.role ?? null,
34
+ action.label,
35
+ action.value ?? null,
36
+ action.current_value ?? null,
37
+ action.checked ?? null,
38
+ action.selected ?? null,
39
+ action.expanded ?? null,
40
+ ]);
41
+ }
42
+ /**
43
+ * One index per observed element, one operation per element. An editable
44
+ * field's companion "Open …" click is not offered: typing into the field is
45
+ * the step, and a picker that refuses typing is the planner's case.
46
+ */
47
+ export function buildActionSpace(actions) {
48
+ const elements = [];
49
+ const indices = new Map();
50
+ const editable = new Set();
51
+ const seen = new Set();
52
+ const targets = {};
53
+ const controls = {};
54
+ for (const action of actions) {
55
+ if (action.kind === "fill" && action.node !== undefined) {
56
+ editable.add(action.node);
57
+ }
58
+ }
59
+ for (const action of actions) {
60
+ const operation = operationOf(action);
61
+ if (!operation || action.node === undefined) {
62
+ controls[action.id.toUpperCase()] = action;
63
+ continue;
64
+ }
65
+ if (action.kind === "click" && editable.has(action.node)) {
66
+ continue;
67
+ }
68
+ if (action.kind !== "select") {
69
+ const key = duplicateKey(action);
70
+ if (seen.has(key)) {
71
+ continue;
72
+ }
73
+ seen.add(key);
74
+ }
75
+ let index = indices.get(action.node);
76
+ if (!index) {
77
+ index = String(elements.length + 1);
78
+ indices.set(action.node, index);
79
+ const element = {
80
+ index,
81
+ label: action.label.split(" → ")[0] ?? action.label,
82
+ operation,
83
+ };
84
+ for (const key of ["role", "value", "checked", "selected", "expanded"]) {
85
+ const value = action[key];
86
+ if (value !== undefined) {
87
+ element[key] = value;
88
+ }
89
+ }
90
+ if (action.kind === "select") {
91
+ element.value = action.current_value ?? "";
92
+ element.options = [];
93
+ }
94
+ elements.push(element);
95
+ }
96
+ const element = elements[Number(index) - 1];
97
+ let target = index;
98
+ if (action.kind === "select") {
99
+ if (!element.options) {
100
+ element.options = [];
101
+ }
102
+ const options = element.options;
103
+ target = `${index}:${options.length + 1}`;
104
+ options.push({
105
+ index: target,
106
+ label: action.label,
107
+ value: action.value ?? "",
108
+ });
109
+ }
110
+ targets[target] = action;
111
+ }
112
+ return { controls, elements, targets };
113
+ }
114
+ const ACT_LABEL = "Interact with one visible element: click a button, link, option, suggestion or calendar day; enter text in a field (a small helper supplies the value from the goal); or choose a dropdown value. The target question names the element.";
115
+ /** One criterion per target: the element as the classifier compares it. */
116
+ export function describeTarget(index, action) {
117
+ const entry = {
118
+ current_value: action.current_value ?? action.value ?? "",
119
+ element: `[${index}] ${action.label}`,
120
+ operation: operationOf(action) ?? "CLICK",
121
+ };
122
+ for (const key of ["role", "checked", "selected", "expanded"]) {
123
+ const value = action[key];
124
+ if (value !== undefined) {
125
+ entry[key] = value;
126
+ }
127
+ }
128
+ return entry;
129
+ }
130
+ /** The operation head plus, when the page offers any element, the target head. */
131
+ export function buildQuestions(space, goal) {
132
+ const operations = {};
133
+ const targetIds = Object.keys(space.targets);
134
+ if (targetIds.length > 0) {
135
+ operations[ACT] = ACT_LABEL;
136
+ }
137
+ for (const [id, action] of Object.entries(space.controls)) {
138
+ operations[id] = action.label;
139
+ }
140
+ operations.DONE = "Every requirement is visibly satisfied.";
141
+ operations.BLOCKED =
142
+ "No offered element can advance the goal (an offered confirmation or submit button means not blocked).";
143
+ const questions = {
144
+ operation: {
145
+ criteria: operations,
146
+ instructions: { goal, rules: NEXT_ACTION },
147
+ type: "choice",
148
+ },
149
+ };
150
+ if (targetIds.length > 0) {
151
+ const criteria = {};
152
+ for (const [index, action] of Object.entries(space.targets)) {
153
+ criteria[index] = describeTarget(index, action);
154
+ }
155
+ questions[TARGET_HEAD] = {
156
+ criteria,
157
+ instructions: { goal, rules: [NEXT_ACTION, TARGET] },
158
+ type: "choice",
159
+ };
160
+ }
161
+ return { operations, questions };
162
+ }
@@ -0,0 +1,91 @@
1
+ // The System One wire format as the fast loop asks it (https://docs.typesafe.ai/api): one POST
2
+ // with a `state` and typed questions, every question answered in the same call. Instructions and
3
+ // criteria may be structured, unlike a wizard's decision questions. Ported from engenty-pro's
4
+ // `@engenty/typesafe-client`; the way to the model is wizards' own `systemOneAccess()`.
5
+ import { systemOneAccess } from "../../models.js";
6
+ /** Probabilities are calibrated and must sum to one, within rounding. */
7
+ const SUM_TOLERANCE = 0.02;
8
+ function isUnitNumber(value) {
9
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
10
+ }
11
+ /**
12
+ * A choice answer the caller may act on. Rejects anything that does not
13
+ * name one of the offered ids, carries a distribution over exactly those
14
+ * ids, sums to one, and puts the chosen id at the top — so a malformed or
15
+ * truncated response can never become an action. Ported from jev-ultrafast
16
+ * `validate_choice`.
17
+ */
18
+ export function validateChoiceAnswer(answer, ids) {
19
+ const offered = new Set(ids);
20
+ const invalid = () => {
21
+ throw new Error("typesafe_invalid_choice: answer does not fit the question");
22
+ };
23
+ const a = answer;
24
+ if (a?.type !== "choice") {
25
+ return invalid();
26
+ }
27
+ const { choice, confidence, probabilities } = a;
28
+ if (typeof choice !== "string" ||
29
+ !offered.has(choice) ||
30
+ typeof probabilities !== "object" ||
31
+ probabilities === null ||
32
+ !isUnitNumber(confidence)) {
33
+ return invalid();
34
+ }
35
+ const keys = Object.keys(probabilities);
36
+ if (keys.length !== offered.size || !keys.every((k) => offered.has(k))) {
37
+ return invalid();
38
+ }
39
+ let sum = 0;
40
+ let max = 0;
41
+ for (const key of keys) {
42
+ const p = probabilities[key];
43
+ if (!isUnitNumber(p)) {
44
+ return invalid();
45
+ }
46
+ sum += p;
47
+ max = Math.max(max, p);
48
+ }
49
+ if (Math.abs(sum - 1) >= SUM_TOLERANCE) {
50
+ return invalid();
51
+ }
52
+ if ((probabilities[choice] ?? 0) < max - 1e-6) {
53
+ return invalid();
54
+ }
55
+ return a;
56
+ }
57
+ const RETRYABLE = new Set([429, 503, 529]);
58
+ /**
59
+ * The run's way to a decision model (credits, an AI Gateway key or a TypeSafe key), or null
60
+ * when there is none — then the fast loop is not offered.
61
+ */
62
+ export async function classifierClient(signal) {
63
+ const access = await systemOneAccess().catch(() => null);
64
+ if (!access) {
65
+ return null;
66
+ }
67
+ return {
68
+ async systemOne(request) {
69
+ const body = JSON.stringify({
70
+ ...request,
71
+ ...(access.model && !request.model ? { model: access.model } : {}),
72
+ });
73
+ for (let attempt = 1;; attempt++) {
74
+ const res = await fetch(access.url, {
75
+ method: "POST",
76
+ headers: { ...access.headers, "content-type": "application/json" },
77
+ body,
78
+ signal: signal
79
+ ? AbortSignal.any([signal, AbortSignal.timeout(25_000)])
80
+ : AbortSignal.timeout(25_000),
81
+ });
82
+ if (res.ok) {
83
+ return (await res.json());
84
+ }
85
+ if (!(RETRYABLE.has(res.status) && attempt < 2)) {
86
+ throw new Error(`The decision model answered ${res.status}.`);
87
+ }
88
+ }
89
+ },
90
+ };
91
+ }
@@ -0,0 +1,171 @@
1
+ // One classifier call per step: what to do (act / scroll / wait / done /
2
+ // blocked) and — speculatively, in the same call — which element. The
3
+ // answer is validated against exactly the ids that were offered before
4
+ // anything may execute. A close call gets one tiebreak question before
5
+ // the planner is asked. Ported from engenty-pro's fast loop.
6
+ import { ACT, buildActionSpace, buildQuestions, describeTarget, operationOf, TARGET_HEAD, } from "./action-space.js";
7
+ import { validateChoiceAnswer, } from "./classifier.js";
8
+ import { NEXT_ACTION, TIEBREAK } from "./instructions.js";
9
+ /**
10
+ * Every step the call scored, best first: ACT × each target, plus each
11
+ * control on its own. The target head must validate when ACT is the argmax
12
+ * (a protocol failure otherwise); an invalid target head under a losing ACT
13
+ * simply drops ACT from the ranking.
14
+ */
15
+ export function scoreSteps(operationAnswer, answers, space) {
16
+ const scored = [];
17
+ let targetAnswer = null;
18
+ for (const [operation, pOperation] of Object.entries(operationAnswer.probabilities)) {
19
+ if (operation !== ACT) {
20
+ const control = space.controls[operation];
21
+ scored.push({
22
+ choice: control ? control.id : operation,
23
+ joint: pOperation,
24
+ label: control ? control.label : operation,
25
+ operation,
26
+ probability: 1,
27
+ target: null,
28
+ });
29
+ continue;
30
+ }
31
+ try {
32
+ targetAnswer = validateChoiceAnswer(answers[TARGET_HEAD], Object.keys(space.targets));
33
+ }
34
+ catch (error) {
35
+ if (operation === operationAnswer.choice) {
36
+ throw error;
37
+ }
38
+ continue;
39
+ }
40
+ for (const [target, pTarget] of Object.entries(targetAnswer.probabilities)) {
41
+ const action = space.targets[target];
42
+ scored.push({
43
+ choice: action.id,
44
+ joint: pOperation * pTarget,
45
+ label: action.label,
46
+ operation: operationOf(action) ?? "CLICK",
47
+ probability: pTarget,
48
+ target,
49
+ });
50
+ }
51
+ }
52
+ return {
53
+ ranked: scored.sort((a, b) => b.joint - a.joint),
54
+ targetAnswer,
55
+ };
56
+ }
57
+ function stateFor(input) {
58
+ return {
59
+ elements: input.space.elements,
60
+ page: {
61
+ text: input.page.text,
62
+ title: input.page.title,
63
+ url: input.page.url,
64
+ },
65
+ recent_actions: input.history.slice(-10).map((h) => ({
66
+ action: h.action,
67
+ kind: h.kind,
68
+ page_changed: h.page_changed,
69
+ text: h.text,
70
+ value_after: h.value_after,
71
+ })),
72
+ };
73
+ }
74
+ /** Ask, validate, and map back to an observed action. */
75
+ export async function decide(input) {
76
+ const space = input.space ?? buildActionSpace(input.page.actions);
77
+ const { operations, questions } = buildQuestions(space, input.goal);
78
+ const startedAt = performance.now();
79
+ const result = await input.client.systemOne({
80
+ ...(input.model ? { model: input.model } : {}),
81
+ questions,
82
+ state: stateFor({ history: input.history, page: input.page, space }),
83
+ });
84
+ const latency_ms = Math.round(performance.now() - startedAt);
85
+ const operationAnswer = validateChoiceAnswer(result.answers.operation, Object.keys(operations));
86
+ const { ranked, targetAnswer } = scoreSteps(operationAnswer, result.answers, space);
87
+ const best = ranked[0];
88
+ if (!best) {
89
+ throw new Error("typesafe_invalid_choice: no scored step");
90
+ }
91
+ const runnerUp = ranked[1] ?? null;
92
+ return {
93
+ choice: best.choice,
94
+ confidence: operationAnswer.confidence,
95
+ latency_ms,
96
+ margin: best.joint - (runnerUp?.joint ?? 0),
97
+ model: result.model,
98
+ operation: best.operation,
99
+ operationProbabilities: operationAnswer.probabilities,
100
+ probability: best.target === null
101
+ ? (operationAnswer.probabilities[best.operation] ?? 0)
102
+ : best.probability,
103
+ runnerUp,
104
+ target: best.target,
105
+ targetConfidence: best.target === null ? null : (targetAnswer?.confidence ?? null),
106
+ usage: result.usage ?? null,
107
+ };
108
+ }
109
+ /** A tiebreak winner must hold at least this much of the three-way mass. */
110
+ export const TIEBREAK_MIN_PROBABILITY = 0.6;
111
+ /** A step as the tiebreak describes it: fuller than the target criterion. */
112
+ function describeStep(step, space) {
113
+ if (step.target !== null) {
114
+ const action = space.targets[step.target];
115
+ if (action) {
116
+ return {
117
+ ...describeTarget(step.target, action),
118
+ step: `${step.operation} → [${step.target}] ${action.label}`,
119
+ };
120
+ }
121
+ }
122
+ return { step: step.operation, what: step.label };
123
+ }
124
+ /**
125
+ * One more question when the best two steps are too close: this one or that
126
+ * one, or neither. Forced binary choices renormalise to 1, so NEITHER is
127
+ * what keeps an unsure classifier honest, and the winner must clear
128
+ * `TIEBREAK_MIN_PROBABILITY`. Never chained; the planner is the backstop.
129
+ */
130
+ export async function tiebreak(input) {
131
+ const { decision } = input;
132
+ if (!decision.runnerUp) {
133
+ return { latency_ms: 0, probability: 0, usage: null, winner: null };
134
+ }
135
+ const space = input.space ?? buildActionSpace(input.page.actions);
136
+ const best = {
137
+ label: decision.target
138
+ ? (space.targets[decision.target]?.label ?? decision.choice)
139
+ : (space.controls[decision.operation]?.label ?? decision.operation),
140
+ operation: decision.operation,
141
+ target: decision.target,
142
+ };
143
+ const startedAt = performance.now();
144
+ const result = await input.client.systemOne({
145
+ ...(input.model ? { model: input.model } : {}),
146
+ questions: {
147
+ tiebreak: {
148
+ criteria: {
149
+ NEITHER: "Neither step is the right next step for the goal.",
150
+ best: describeStep(best, space),
151
+ runner_up: describeStep(decision.runnerUp, space),
152
+ },
153
+ instructions: { goal: input.goal, rules: [NEXT_ACTION, TIEBREAK] },
154
+ type: "choice",
155
+ },
156
+ },
157
+ state: stateFor({ history: input.history, page: input.page, space }),
158
+ });
159
+ const latency_ms = Math.round(performance.now() - startedAt);
160
+ const answer = validateChoiceAnswer(result.answers.tiebreak, ["NEITHER", "best", "runner_up"]);
161
+ const probability = answer.probabilities[answer.choice] ?? 0;
162
+ const winner = answer.choice !== "NEITHER" && probability >= TIEBREAK_MIN_PROBABILITY
163
+ ? answer.choice
164
+ : null;
165
+ return {
166
+ latency_ms,
167
+ probability,
168
+ usage: result.usage ?? null,
169
+ winner,
170
+ };
171
+ }
@@ -0,0 +1,141 @@
1
+ // Observe and act on the run's browser page. Every
2
+ // input is preceded by a freshness check against the observation the
3
+ // decision was made on, and a hit-test at the element's centre — a stale or
4
+ // covered target is a `StalePageError`, never a click somewhere else.
5
+ // Ported from engenty-pro, which took it from jev-ultrafast `browser.py`; input goes through Playwright's
6
+ // mouse/keyboard (the same CDP `Input.*` events underneath).
7
+ import { createHash } from "node:crypto";
8
+ import { actTargetScript, MARKER_SCRIPT, nodeGuardScript, SNAPSHOT_SCRIPT, settleScript, } from "../snapshot.js";
9
+ export class StalePageError extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "StalePageError";
13
+ }
14
+ }
15
+ const OBSERVE_ATTEMPTS = 10;
16
+ const OBSERVE_RETRY_MS = 20;
17
+ function sameJson(a, b) {
18
+ return JSON.stringify(a) === JSON.stringify(b);
19
+ }
20
+ export function fingerprint(snapshot) {
21
+ const content = {
22
+ actions: snapshot.actions,
23
+ scroll: snapshot.scroll,
24
+ text: snapshot.text,
25
+ url: snapshot.url,
26
+ };
27
+ return createHash("sha256").update(JSON.stringify(content)).digest("hex");
28
+ }
29
+ export class FastLoopDriver {
30
+ afterInput = null;
31
+ page;
32
+ constructor(page) {
33
+ this.page = page;
34
+ }
35
+ async evaluate(expression) {
36
+ try {
37
+ return await this.page.evaluate(expression);
38
+ }
39
+ catch (error) {
40
+ // A navigation mid-evaluation detaches the execution context.
41
+ throw new StalePageError(`Document changed during evaluation: ${error instanceof Error ? error.message : String(error)}`);
42
+ }
43
+ }
44
+ /**
45
+ * Wait for the page to come to rest (see `settleScript`). Read-only; a
46
+ * navigation while waiting is fine, the next observation will see it.
47
+ */
48
+ async settle(action = null) {
49
+ try {
50
+ await this.page.evaluate(settleScript(action));
51
+ }
52
+ catch {
53
+ // Detached context = the page is navigating; observe() retries that.
54
+ }
55
+ }
56
+ /** A fresh, atomic observation. Retries briefly while the page is navigating. */
57
+ async observe() {
58
+ if (this.afterInput) {
59
+ const action = this.afterInput;
60
+ this.afterInput = null;
61
+ await this.settle(action);
62
+ }
63
+ for (let attempt = 0; attempt < OBSERVE_ATTEMPTS; attempt += 1) {
64
+ try {
65
+ const raw = await this.evaluate(SNAPSHOT_SCRIPT);
66
+ if (raw === null) {
67
+ throw new StalePageError("Document is navigating");
68
+ }
69
+ return { ...raw, fingerprint: fingerprint(raw) };
70
+ }
71
+ catch (error) {
72
+ if (!(error instanceof StalePageError) || attempt === OBSERVE_ATTEMPTS - 1) {
73
+ throw error;
74
+ }
75
+ await new Promise((resolve) => setTimeout(resolve, OBSERVE_RETRY_MS));
76
+ }
77
+ }
78
+ throw new StalePageError("Page did not settle");
79
+ }
80
+ /**
81
+ * Is the page still the one this snapshot describes? With an element
82
+ * action: is that exact element still what we saw (identity + semantics).
83
+ */
84
+ async fresh(page, action) {
85
+ if (action && (action.kind === "click" || action.kind === "select")) {
86
+ if (typeof action.node !== "number") {
87
+ return false;
88
+ }
89
+ const current = await this.evaluate(nodeGuardScript(action.node));
90
+ return sameJson(current, [page.page_key, page.guards[String(action.node)] ?? null]);
91
+ }
92
+ const marker = await this.evaluate(MARKER_SCRIPT);
93
+ return sameJson(marker, page.marker);
94
+ }
95
+ /** Execute one observed action. `text` is required for `fill`. */
96
+ async act(action, page, text = null) {
97
+ if (!(await this.fresh(page, action))) {
98
+ throw new StalePageError("Page changed since this decision. Observe again.");
99
+ }
100
+ switch (action.kind) {
101
+ case "wait":
102
+ // A WAIT is the classifier asking for the page to finish what it is
103
+ // doing: settle on the next observation like any input does.
104
+ break;
105
+ case "scroll": {
106
+ await this.page.mouse.move(Math.floor(page.w / 2), Math.floor(page.h * 0.8));
107
+ await this.page.mouse.wheel(0, action.delta ?? 560);
108
+ break;
109
+ }
110
+ case "click":
111
+ case "fill":
112
+ case "select": {
113
+ if (typeof action.node !== "number") {
114
+ throw new StalePageError("Invalid observed node");
115
+ }
116
+ // Code-owned node ids refer to observed elements, never model selectors.
117
+ const target = await this.evaluate(actTargetScript(action));
118
+ if (target === null) {
119
+ throw new StalePageError(action.kind === "select"
120
+ ? "Dropdown value was not applied; observe again."
121
+ : "Target changed or is covered. Observe again.");
122
+ }
123
+ if (action.kind !== "select") {
124
+ await this.page.mouse.click(target.x, target.y);
125
+ if (action.kind === "fill") {
126
+ if (text === null) {
127
+ throw new Error("fill_without_text");
128
+ }
129
+ // Select-all is Cmd+A in a local runtime on a Mac.
130
+ await this.page.keyboard.press("ControlOrMeta+a");
131
+ await this.page.keyboard.insertText(text);
132
+ }
133
+ }
134
+ break;
135
+ }
136
+ default:
137
+ throw new Error(`unknown_action_kind: ${String(action.kind)}`);
138
+ }
139
+ this.afterInput = action;
140
+ }
141
+ }