wizards 0.2.41 → 0.2.43

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 (165) 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-8qS5utcR.js +1 -0
  38. package/apps/web/dist/assets/ChatView-Bx1KVCEf.js +10 -0
  39. package/apps/web/dist/assets/{CreditsDialog-DnI1-cxI.js → CreditsDialog-BCuDsatt.js} +1 -1
  40. package/apps/web/dist/assets/EditorPage-_Sbj-mSD.js +3 -0
  41. package/apps/web/dist/assets/{FlowPreview-8sN-J3Wt.js → FlowPreview-COgjib4H.js} +1 -1
  42. package/apps/web/dist/assets/{Harness-BQIznJjo.js → Harness-BaxjV1Ng.js} +2 -2
  43. package/apps/web/dist/assets/HomePage-BlD0wZB0.js +1 -0
  44. package/apps/web/dist/assets/ImportWizard-BZDtNJg1.js +1 -0
  45. package/apps/web/dist/assets/NewWizardPage-Ci_x__p9.js +2 -0
  46. package/apps/web/dist/assets/ProjectPage-NwFut2Z-.js +2 -0
  47. package/apps/web/dist/assets/PublicRunner-rHdvK18v.js +1 -0
  48. package/apps/web/dist/assets/RunDrawer-Dp-JowDX.js +4 -0
  49. package/apps/web/dist/assets/RunnerView-DSlReODC.js +2 -0
  50. package/apps/web/dist/assets/SettingsPage-2Bw-D3hC.js +1 -0
  51. package/apps/web/dist/assets/SetupPage-DHESCsTb.js +1 -0
  52. package/apps/web/dist/assets/SharePage-DdJ-qD-B.js +1 -0
  53. package/apps/web/dist/assets/ThemeSwitch-BkodFy16.js +1 -0
  54. package/apps/web/dist/assets/arrow-right-pf8p4FIz.js +1 -0
  55. package/apps/web/dist/assets/changelog-cmQb-lZW.js +1 -0
  56. package/apps/web/dist/assets/{circle-alert-BAwp-sT4.js → circle-alert-Gn4D6etf.js} +1 -1
  57. package/apps/web/dist/assets/{copy-DbRfBUN6.js → copy-C3D7PBYL.js} +1 -1
  58. package/apps/web/dist/assets/{definition-pJhOorRU.js → definition-AlI4g-wR.js} +2 -2
  59. package/apps/web/dist/assets/{external-link-Ckgj8QwI.js → external-link-M3mEgZA-.js} +1 -1
  60. package/apps/web/dist/assets/globe-BnaeE83w.js +1 -0
  61. package/apps/web/dist/assets/{image-D9msyNQi.js → image-BuasG4Jr.js} +1 -1
  62. package/apps/web/dist/assets/index-BdrX1tJ4.js +78 -0
  63. package/apps/web/dist/assets/index-D6vcOCCh.css +1 -0
  64. package/apps/web/dist/assets/{lock-B5ky3SKB.js → lock-CrB_z7n3.js} +1 -1
  65. package/apps/web/dist/assets/{meta-BZ2z-OsJ.js → meta-CT4LmQ7g.js} +1 -1
  66. package/apps/web/dist/assets/mouse-pointer-click-BurvPVO8.js +1 -0
  67. package/apps/web/dist/assets/{pen-line-nCoUBOra.js → pen-line-BA6l84zC.js} +1 -1
  68. package/apps/web/dist/assets/{refresh-cw-Q00Jfvvq.js → refresh-cw-DEKCEuIO.js} +1 -1
  69. package/apps/web/dist/assets/{session-CjfNwKNU.js → session-DCcgTTmG.js} +1 -1
  70. package/apps/web/dist/assets/{settings-menu-DA3a4Ys5.js → settings-menu-C9fE9M0f.js} +1 -1
  71. package/apps/web/dist/assets/star-BwhVXiJM.js +1 -0
  72. package/apps/web/dist/assets/{trash-BlT75Cyj.js → trash-WwlTeE_V.js} +1 -1
  73. package/apps/web/dist/assets/{type-BmqZVGnw.js → type-kpWj7Zf1.js} +1 -1
  74. package/apps/web/dist/assets/ui-Wxaw_APn.js +9 -0
  75. package/apps/web/dist/assets/{video-BGwhi8uR.js → video-U-idAC66.js} +1 -1
  76. package/apps/web/dist/assets/volume-2-BwidpioC.js +1 -0
  77. package/apps/web/dist/assets/{wand-sparkles-7vcrrSnD.js → wand-sparkles-DaINku4r.js} +1 -1
  78. package/apps/web/dist/embed.js +119 -4
  79. package/apps/web/dist/index.html +13 -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-D3nkBHzo.js +0 -1
  147. package/apps/web/dist/assets/EditorPage-Bl6kef8d.js +0 -3
  148. package/apps/web/dist/assets/HomePage-BRz-wGtK.js +0 -1
  149. package/apps/web/dist/assets/ImportWizard-B2STI62b.js +0 -1
  150. package/apps/web/dist/assets/NewWizardPage-3Bl7JPTj.js +0 -2
  151. package/apps/web/dist/assets/ProjectPage-CuurGBsI.js +0 -2
  152. package/apps/web/dist/assets/PublicRunner-DDFg4Dfr.js +0 -1
  153. package/apps/web/dist/assets/RunDrawer-CMr7z8PZ.js +0 -4
  154. package/apps/web/dist/assets/RunnerView-DyMVB56S.js +0 -2
  155. package/apps/web/dist/assets/SettingsPage-VeFv2IjG.js +0 -1
  156. package/apps/web/dist/assets/SetupPage-Db4fhE5q.js +0 -1
  157. package/apps/web/dist/assets/SharePage-zCPxDPTo.js +0 -1
  158. package/apps/web/dist/assets/ThemeSwitch-BOlH2F42.js +0 -1
  159. package/apps/web/dist/assets/arrow-right-CtFLf9GU.js +0 -1
  160. package/apps/web/dist/assets/changelog-BKYvAkhc.js +0 -1
  161. package/apps/web/dist/assets/index-CBRcxIRM.js +0 -78
  162. package/apps/web/dist/assets/index-gTcC8eX6.css +0 -1
  163. package/apps/web/dist/assets/star-CUJ_2U_I.js +0 -1
  164. package/apps/web/dist/assets/ui-CPp6zNQ9.js +0 -9
  165. package/apps/web/dist/assets/volume-2-BjoY3RjZ.js +0 -1
@@ -1,43 +1,70 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { createTool } from "@mastra/core/tools";
3
+ import { generateText } from "ai";
3
4
  import { z } from "zod";
5
+ import { classifierClient } from "../browser/fast/classifier.js";
6
+ import { runFastLoop } from "../browser/fast/run.js";
7
+ import { createFieldText } from "../browser/fast/text-helper.js";
8
+ import { nodeScript, PAGE_SCRIPT, settleScript, targetScript, } from "../browser/snapshot.js";
9
+ import { env } from "../env.js";
10
+ import { costOf, textModel } from "../models.js";
4
11
  import { assertPublicUrl } from "./net-guard.js";
5
- import { attempt, clip } from "./shared.js";
6
- const ref = (n) => `[data-wz-ref="${n}"]`;
7
- /** The page as an agent reads it: its text and its interactive elements, numbered. */
8
- export async function pageSnapshot(page) {
9
- const data = await page.evaluate(() => {
10
- const els = Array.from(document.querySelectorAll("a[href], button, input, textarea, select, [role=button], [role=link], [contenteditable=true]")).filter((el) => {
11
- const r = el.getBoundingClientRect();
12
- return r.width > 0 && r.height > 0 && el.type !== "hidden";
13
- });
14
- for (const old of Array.from(document.querySelectorAll("[data-wz-ref]"))) {
15
- old.removeAttribute("data-wz-ref");
12
+ import { attempt } from "./shared.js";
13
+ /** The page as an agent step reads it; retried while the page is between two documents. */
14
+ export async function readPage(page) {
15
+ for (let attempt = 0; attempt < 5; attempt++) {
16
+ const view = await page.evaluate(PAGE_SCRIPT).catch(() => null);
17
+ if (view) {
18
+ return view;
16
19
  }
17
- const items = els.slice(0, 120).map((el, i) => {
18
- el.setAttribute("data-wz-ref", String(i));
19
- const input = el;
20
- const button = ["submit", "button", "reset"].includes(input.type);
21
- const field = (el.tagName === "INPUT" && !button) || el.tagName === "TEXTAREA";
22
- // What stands in a field may be something the person typed: the model learns that a
23
- // field is filled, never with what.
24
- const label = el.getAttribute("aria-label") ||
25
- input.placeholder ||
26
- (field ? "" : el.innerText || (button ? input.value : "")) ||
27
- el.getAttribute("name") ||
28
- "";
29
- const tag = el.tagName.toLowerCase();
30
- const kind = tag === "input" ? `input(${input.type || "text"})` : tag;
31
- const filled = field && input.value ? " (filled)" : "";
32
- return `[${i}] ${kind} ${label.trim().replace(/\s+/g, " ").slice(0, 80)}${filled}`;
33
- });
34
- return { text: document.body?.innerText ?? "", items };
35
- });
20
+ await page.waitForLoadState("domcontentloaded", { timeout: 5000 }).catch(() => undefined);
21
+ await new Promise((r) => setTimeout(r, 200));
22
+ }
36
23
  return {
37
24
  url: page.url(),
38
- title: await page.title(),
39
- text: clip(data.text, 6000),
40
- elements: data.items.join("\n"),
25
+ title: "",
26
+ text: "",
27
+ items: [],
28
+ omitted: 0,
29
+ scroll: { y: 0, height: 0, viewport: 0 },
30
+ };
31
+ }
32
+ function line(item) {
33
+ const parts = [`[${item.ref}]`, item.role, JSON.stringify(item.label)];
34
+ if (item.kind === "fill") {
35
+ parts.push(item.value ? `= ${JSON.stringify(item.value)}` : "(empty)");
36
+ }
37
+ else if (item.kind === "password") {
38
+ parts.push(item.value ? "(filled)" : "(empty)");
39
+ }
40
+ else if (item.kind === "select") {
41
+ const more = item.more_options ? ` | … ${item.more_options} more` : "";
42
+ parts.push(`= ${JSON.stringify(item.value ?? "")}; options: ${(item.options ?? []).join(" | ")}${more}`);
43
+ }
44
+ for (const key of ["checked", "selected", "expanded"]) {
45
+ if (item[key] !== undefined) {
46
+ parts.push(`${key}=${item[key]}`);
47
+ }
48
+ }
49
+ if (item.dialog) {
50
+ parts.push("(dialog)");
51
+ }
52
+ return parts.join(" ");
53
+ }
54
+ /**
55
+ * The page as the model gets it: one line per control, named by its [number] — a dialog or
56
+ * banner first, marked (dialog) — then the page's visible text.
57
+ */
58
+ export function pageForModel(view) {
59
+ const more = view.omitted
60
+ ? `\n… ${view.omitted} more not listed: close what is open, scroll, or read the page again.`
61
+ : "";
62
+ return {
63
+ url: view.url,
64
+ title: view.title,
65
+ elements: view.items.map(line).join("\n") + more,
66
+ text: view.text,
67
+ scroll: `${view.scroll.y} of ${view.scroll.height} px, ${view.scroll.viewport} px in view`,
41
68
  };
42
69
  }
43
70
  function originOf(url) {
@@ -55,7 +82,14 @@ function found(wait) {
55
82
  p.catch(() => undefined);
56
83
  return p;
57
84
  }
58
- const settle = (page) => page.waitForLoadState("domcontentloaded", { timeout: 10_000 }).catch(() => undefined);
85
+ /**
86
+ * Lets the page come to rest after an input: no DOM changes and no animation for a moment, or
87
+ * the next document loaded where the input navigated.
88
+ */
89
+ async function settle(page) {
90
+ await page.evaluate(settleScript(null)).catch(() => undefined);
91
+ await page.waitForLoadState("domcontentloaded", { timeout: 10_000 }).catch(() => undefined);
92
+ }
59
93
  /**
60
94
  * Fetches a URL with the browser's sign-in, outside any page. Page requests pass the context's
61
95
  * host guard; this one does not, so every redirect hop is checked here.
@@ -75,8 +109,55 @@ async function signedInGet(page, url) {
75
109
  }
76
110
  throw new Error("Too many redirects.");
77
111
  }
112
+ /** Why a [number] cannot be used, for the model. */
113
+ function targetError(n, target) {
114
+ switch (target.error) {
115
+ case "covered":
116
+ return `[${n}] is covered by "${target.by}". Deal with that first — a cookie or consent banner: click its least consent (only necessary / reject all).`;
117
+ case "disabled":
118
+ return `[${n}] is disabled right now.`;
119
+ case "gone":
120
+ return `[${n}] is not on the page any more. Use the numbers of the page below.`;
121
+ default:
122
+ return `[${n}] cannot be seen on the page.`;
123
+ }
124
+ }
125
+ /**
126
+ * Where to put the pointer for a [number]: scrolled into view and not covered by anything — so
127
+ * a click never lands on whatever lies over it.
128
+ */
129
+ function pointAt(page, n) {
130
+ return page.evaluate(targetScript(n)).catch(() => ({ error: "gone" }));
131
+ }
132
+ /** The element a [number] names, for what Playwright does best (fill, select). */
133
+ async function handleOf(page, n) {
134
+ const handle = await page.evaluateHandle(nodeScript(n)).catch(() => null);
135
+ return handle?.asElement() ?? null;
136
+ }
137
+ /** Clicks at a point; a tab the click opens is where the agent goes on. */
138
+ async function clickAt(ctx, page, point) {
139
+ const opened = [];
140
+ const onPage = (p) => {
141
+ opened.push(p);
142
+ };
143
+ page.context().on("page", onPage);
144
+ try {
145
+ await page.mouse.click(point.x, point.y);
146
+ await settle(page);
147
+ }
148
+ finally {
149
+ page.context().off("page", onPage);
150
+ }
151
+ const popup = opened.at(-1);
152
+ if (popup) {
153
+ ctx.resources.adopt(popup);
154
+ await popup.waitForLoadState("domcontentloaded", { timeout: 10_000 }).catch(() => undefined);
155
+ return popup;
156
+ }
157
+ return page;
158
+ }
78
159
  const credentialField = z.object({
79
- ref: z.number().describe("The field's [number] from your latest page snapshot."),
160
+ ref: z.number().describe("The field's [number] from your latest page."),
80
161
  label: z.string().min(1).max(60).describe("What the person sees, e.g. E-Mail."),
81
162
  kind: z
82
163
  .enum(["username", "password", "otp", "text"])
@@ -84,7 +165,8 @@ const credentialField = z.object({
84
165
  });
85
166
  /**
86
167
  * Types the person's values into the page. A password goes only into a password input, and
87
- * only while the page is still the site the person was shown. Failures are codes: a browser
168
+ * only while the page is still the site the person was shown. Each field is marked as the
169
+ * person's, so no reading of the page gives its value to a model. Failures are codes: a browser
88
170
  * error message could quote the value it failed to type.
89
171
  */
90
172
  async function fillCredentials(page, origin, fields, values) {
@@ -97,13 +179,13 @@ async function fillCredentials(page, origin, fields, values) {
97
179
  if (typeof value !== "string" || !value) {
98
180
  continue;
99
181
  }
100
- const locator = page.locator(ref(field.ref)).first();
101
- const element = await locator
102
- .evaluate((el) => ({ tag: el.tagName, type: el.type ?? "" }), undefined, {
103
- timeout: 5000,
104
- })
105
- .catch(() => null);
106
- if (!element) {
182
+ const handle = await handleOf(page, field.ref);
183
+ const element = handle
184
+ ? await handle
185
+ .evaluate((el) => ({ tag: el.tagName, type: el.type ?? "" }))
186
+ .catch(() => null)
187
+ : null;
188
+ if (!(handle && element)) {
107
189
  return { error: "field_missing" };
108
190
  }
109
191
  if (element.tag !== "INPUT" && element.tag !== "TEXTAREA") {
@@ -113,7 +195,12 @@ async function fillCredentials(page, origin, fields, values) {
113
195
  return { error: "not_a_password_field" };
114
196
  }
115
197
  try {
116
- await locator.fill(value, { timeout: 10_000 });
198
+ await handle.evaluate((el) => {
199
+ const w = window;
200
+ w.__wzPersonal ??= new WeakSet();
201
+ w.__wzPersonal.add(el);
202
+ });
203
+ await handle.fill(value, { timeout: 10_000 });
117
204
  }
118
205
  catch {
119
206
  return { error: "fill_failed" };
@@ -124,9 +211,44 @@ async function fillCredentials(page, origin, fields, values) {
124
211
  }
125
212
  const NOBODY = "Nobody is at the keyboard for this run, so a sign-in cannot be asked for. Go on without it and report what the person has to do.";
126
213
  const DECLINED = "The person did not sign in. Do not ask again for this site; go on without it and say in your result what is missing and what the person can do.";
127
- export function browserTools(ctx, assets, files) {
214
+ const TOOK_OVER = "The person took the browser over and has handed it back; nothing you asked for was done. The page may have changed — here it is as it stands now. Go on from here.";
215
+ const RUN_FAST_DESCRIPTION = "Hand a small, concrete browser sub-goal to the fast executor: on the CURRENT page it reads the visible controls, picks one element per step with a classifier (no language model), types field values taken from your goal, and repeats until the goal is visibly satisfied or it is unsure. Use it for mechanical sequences — click a cookie banner away, fill and submit a form, pick a date in a calendar, choose an autocomplete suggestion, set filters and dropdowns, open a matching result. Give one page's worth of work per call with every value spelled out (dates, names, filters); it never invents data. Returns status `done`, or `uncertain`/`blocked`/`budget`/`error` with the page and a note naming the step it could not decide. Then do THAT ONE step with the other browser_* tools and call browser_run_fast again with the same goal — do not finish the rest by hand. Open the page with browser_open first; it does not open URLs.";
216
+ /** One line of at most 60 characters, for the run's log. */
217
+ function short(text) {
218
+ const one = text.trim().replace(/\s+/g, " ");
219
+ return one.length > 60 ? `${one.slice(0, 59)}…` : one;
220
+ }
221
+ /** What a step of the fast loop did, for the run's log. */
222
+ function fastStepNote(step) {
223
+ const name = short(step.target_label ?? "");
224
+ switch (step.operation) {
225
+ case "CLICK":
226
+ return name ? { code: "clicksOn", params: { name } } : { code: "clicks" };
227
+ case "TYPE_TEXT":
228
+ return { code: "types" };
229
+ case "SELECT":
230
+ return name ? { code: "selects", params: { option: name } } : null;
231
+ case "SCROLL_UP":
232
+ case "SCROLL_DOWN":
233
+ return { code: "scrolls" };
234
+ case "WAIT":
235
+ return { code: "waitsForPage" };
236
+ default:
237
+ return null;
238
+ }
239
+ }
240
+ export async function browserTools(ctx, assets, files) {
128
241
  const page = () => ctx.resources.browserPage();
129
242
  const tools = {};
243
+ /** What each [number] was called on the latest reading, for the run's log. */
244
+ const names = new Map();
245
+ const read = async (p) => {
246
+ const view = await readPage(p);
247
+ for (const item of view.items) {
248
+ names.set(item.ref, item.label);
249
+ }
250
+ return pageForModel(view);
251
+ };
130
252
  // There is one page. A model may ask for several browser actions at once; they run one after
131
253
  // the other, in the order asked — else a navigation would cut a download short.
132
254
  let queue = Promise.resolve();
@@ -135,60 +257,204 @@ export function browserTools(ctx, assets, files) {
135
257
  queue = next;
136
258
  return next;
137
259
  };
260
+ // While the person drives the browser, nothing the agent asks for happens; when they hand it
261
+ // back, the agent gets the page as they left it instead.
262
+ const acting = (run) => inTurn(async () => {
263
+ if (await ctx.resources.agentTurn(ctx.signal)) {
264
+ return { note: TOOK_OVER, page: await read(await page()) };
265
+ }
266
+ return run();
267
+ });
268
+ const atRef = async (p, n) => {
269
+ const target = await pointAt(p, n);
270
+ return "error" in target ? { error: targetError(n, target), page: await read(p) } : target;
271
+ };
138
272
  tools.browser_open = createTool({
139
273
  id: "browser_open",
140
- description: "Open a URL in the browser and return its text plus numbered interactive elements. Sites the person signed in to on an earlier run may still be signed in.",
274
+ description: "Open a URL in the browser and return the page: its controls, each with a [number], and its text. A cookie banner in the way: click its least consent (only necessary / reject all) first. Sites the person signed in to on an earlier run may still be signed in.",
141
275
  inputSchema: z.object({ url: z.string() }),
142
- execute: ({ url }) => inTurn(async () => {
276
+ execute: ({ url }) => acting(async () => {
143
277
  const safe = await assertPublicUrl(url);
144
- await ctx.emit("tool", { code: "opens", params: { name: safe.hostname } });
278
+ // The page first, so whoever watches the browser on this line finds one.
145
279
  const p = await page();
280
+ await ctx.emit("tool", { code: "opens", params: { name: safe.hostname } });
146
281
  await p.goto(safe.toString(), { waitUntil: "domcontentloaded", timeout: 30_000 });
147
282
  await p.waitForLoadState("networkidle", { timeout: 5000 }).catch(() => undefined);
148
- return pageSnapshot(p);
283
+ return read(p);
149
284
  }),
150
285
  });
286
+ tools.browser_read = createTool({
287
+ id: "browser_read",
288
+ description: "Read the current page again: its controls with their [numbers] and its text. A number stays with its element as long as the element is on the page.",
289
+ inputSchema: z.object({}),
290
+ execute: () => acting(async () => read(await page())),
291
+ });
151
292
  tools.browser_click = createTool({
152
293
  id: "browser_click",
153
- description: "Click an element by its [number] from the last snapshot.",
294
+ description: "Click an element by its [number]. It is scrolled into view first; a click on something covered by a banner or dialog is refused and names what covers it.",
154
295
  inputSchema: z.object({ ref: z.number() }),
155
- execute: ({ ref: n }) => inTurn(async () => {
296
+ execute: ({ ref: n }) => acting(async () => {
156
297
  const p = await page();
157
- await ctx.emit("tool", { code: "clicks" });
158
- const popup = p
159
- .context()
160
- .waitForEvent("page", { timeout: 3000 })
161
- .catch(() => null);
162
- await p.locator(ref(n)).first().click({ timeout: 10_000 });
163
- const opened = await popup;
164
- if (opened) {
165
- ctx.resources.adopt(opened);
166
- await settle(opened);
167
- return pageSnapshot(opened);
298
+ const target = await atRef(p, n);
299
+ if ("error" in target) {
300
+ return target;
168
301
  }
169
- await settle(p);
170
- return pageSnapshot(p);
302
+ const name = short(names.get(n) ?? "");
303
+ await ctx.emit("tool", name ? { code: "clicksOn", params: { name } } : { code: "clicks" });
304
+ return read(await clickAt(ctx, p, target));
171
305
  }),
172
306
  });
173
307
  tools.browser_type = createTool({
174
308
  id: "browser_type",
175
- description: "Type text into an input by its [number]; set submit to press Enter afterwards. Never for passwords or codes — those the person enters through browser_request_credentials.",
309
+ description: "Type text into a field by its [number], replacing what is in it; set submit to press Enter afterwards. Never for passwords or codes — those the person enters through browser_request_credentials.",
176
310
  inputSchema: z.object({ ref: z.number(), text: z.string(), submit: z.boolean().optional() }),
177
- execute: ({ ref: n, text, submit }) => inTurn(async () => {
311
+ execute: ({ ref: n, text, submit }) => acting(async () => {
178
312
  const p = await page();
179
- await ctx.emit("tool", { code: "types" });
180
- const el = p.locator(ref(n)).first();
313
+ const target = await atRef(p, n);
314
+ if ("error" in target) {
315
+ return target;
316
+ }
317
+ const el = await handleOf(p, n);
318
+ if (!el) {
319
+ return { error: targetError(n, { error: "gone" }), page: await read(p) };
320
+ }
321
+ if ((await el.evaluate((e) => e.type)) === "password") {
322
+ return {
323
+ error: `[${n}] is a password field: the person fills it through browser_request_credentials.`,
324
+ };
325
+ }
326
+ const said = short(text);
327
+ await ctx.emit("tool", said ? { code: "typesText", params: { text: said } } : { code: "types" });
181
328
  await el.fill(text, { timeout: 10_000 });
182
329
  if (submit) {
183
330
  await el.press("Enter");
184
- await settle(p);
185
331
  }
186
- return pageSnapshot(p);
332
+ await settle(p);
333
+ return read(ctx.resources.openPage() ?? p);
334
+ }),
335
+ });
336
+ tools.browser_select = createTool({
337
+ id: "browser_select",
338
+ description: "Choose an option in a dropdown (a select element) by its [number] and the option's name as the page lists it. For a dropdown the page draws itself (no options listed), click it open and click the option instead.",
339
+ inputSchema: z.object({ ref: z.number(), option: z.string() }),
340
+ execute: ({ ref: n, option }) => acting(async () => {
341
+ const p = await page();
342
+ const target = await atRef(p, n);
343
+ if ("error" in target) {
344
+ return target;
345
+ }
346
+ const el = await handleOf(p, n);
347
+ if (!el) {
348
+ return { error: targetError(n, { error: "gone" }), page: await read(p) };
349
+ }
350
+ await ctx.emit("tool", { code: "selects", params: { option: short(option) } });
351
+ const chosen = (await el.selectOption({ label: option }, { timeout: 5000 }).catch(() => null)) ??
352
+ (await el.selectOption(option, { timeout: 5000 }).catch(() => null));
353
+ if (!chosen?.length) {
354
+ return { error: `[${n}] has no option "${option}".`, page: await read(p) };
355
+ }
356
+ await settle(p);
357
+ return read(ctx.resources.openPage() ?? p);
358
+ }),
359
+ });
360
+ tools.browser_scroll = createTool({
361
+ id: "browser_scroll",
362
+ description: "Scroll the page down or up by most of a screen, or bring the element with this [number] into view. For results further down, lists that load as you scroll, and footers.",
363
+ inputSchema: z.object({
364
+ direction: z.enum(["down", "up"]).optional(),
365
+ ref: z.number().optional(),
366
+ }),
367
+ execute: ({ direction, ref: n }) => acting(async () => {
368
+ const p = await page();
369
+ await ctx.emit("tool", { code: "scrolls" });
370
+ if (n !== undefined) {
371
+ const target = await atRef(p, n);
372
+ if ("error" in target) {
373
+ return target;
374
+ }
375
+ }
376
+ else {
377
+ const size = p.viewportSize() ?? { width: 1280, height: 900 };
378
+ await p.mouse.move(Math.floor(size.width / 2), Math.floor(size.height / 2));
379
+ await p.mouse.wheel(0, (direction === "up" ? -0.8 : 0.8) * size.height);
380
+ }
381
+ await settle(p);
382
+ return read(p);
383
+ }),
384
+ });
385
+ tools.browser_press = createTool({
386
+ id: "browser_press",
387
+ description: "Press a key on the page: Enter to send, Escape to close a popup, Tab to move on, the arrows to move through a list of suggestions.",
388
+ inputSchema: z.object({
389
+ key: z.enum([
390
+ "Enter",
391
+ "Escape",
392
+ "Tab",
393
+ "Backspace",
394
+ "ArrowDown",
395
+ "ArrowUp",
396
+ "ArrowLeft",
397
+ "ArrowRight",
398
+ "PageDown",
399
+ "PageUp",
400
+ "Space",
401
+ ]),
402
+ }),
403
+ execute: ({ key }) => acting(async () => {
404
+ const p = await page();
405
+ await ctx.emit("tool", { code: "presses", params: { key } });
406
+ await p.keyboard.press(key === "Space" ? " " : key);
407
+ await settle(p);
408
+ return read(ctx.resources.openPage() ?? p);
409
+ }),
410
+ });
411
+ tools.browser_back = createTool({
412
+ id: "browser_back",
413
+ description: "Go back to the previous page, like the browser's back button.",
414
+ inputSchema: z.object({}),
415
+ execute: () => acting(async () => {
416
+ const p = await page();
417
+ await ctx.emit("tool", { code: "goesBack" });
418
+ const went = await p
419
+ .goBack({ waitUntil: "domcontentloaded", timeout: 20_000 })
420
+ .catch(() => null);
421
+ if (!went) {
422
+ return { error: "There is no page to go back to.", page: await read(p) };
423
+ }
424
+ return read(p);
425
+ }),
426
+ });
427
+ tools.browser_wait = createTool({
428
+ id: "browser_wait",
429
+ description: "Wait for the page: until a text appears on it (results that load, a confirmation), or for a few seconds. Then returns the page.",
430
+ inputSchema: z.object({
431
+ text: z.string().optional().describe("Wait until this text is on the page."),
432
+ seconds: z.number().min(1).max(15).optional().describe("How long at most; default 5."),
433
+ }),
434
+ execute: ({ text, seconds }) => acting(async () => {
435
+ const p = await page();
436
+ await ctx.emit("tool", { code: "waitsForPage" });
437
+ const ms = (seconds ?? 5) * 1000;
438
+ let note;
439
+ if (text) {
440
+ const appeared = await p
441
+ .getByText(text)
442
+ .first()
443
+ .waitFor({ timeout: ms })
444
+ .then(() => true)
445
+ .catch(() => false);
446
+ note = appeared ? undefined : `"${text}" did not appear within ${ms / 1000} s.`;
447
+ }
448
+ else {
449
+ await p.waitForTimeout(ms);
450
+ }
451
+ await settle(p);
452
+ return { ...(note ? { note } : {}), page: await read(p) };
187
453
  }),
188
454
  });
189
455
  tools.browser_screenshot = createTool({
190
456
  id: "browser_screenshot",
191
- description: "Look at the current page: returns a picture of it to you. Use it when the text snapshot is not enough (charts, a layout you cannot make sense of, a captcha or cookie wall). Set save to also hand the picture to the person as part of the result.",
457
+ description: "Look at the current page: returns a picture of it to you. Use it when the text is not enough (charts, a layout you cannot make sense of, a captcha or cookie wall). Set save to also hand the picture to the person as part of the result.",
192
458
  inputSchema: z.object({ save: z.boolean().optional(), name: z.string().optional() }),
193
459
  execute: ({ save, name }) => inTurn(async () => {
194
460
  const p = await page();
@@ -228,10 +494,10 @@ export function browserTools(ctx, assets, files) {
228
494
  return { error: "no_site", note: "Open the site's sign-in page first." };
229
495
  }
230
496
  for (const field of input.fields) {
231
- if (!(await p.locator(ref(field.ref)).count())) {
497
+ if (!(await handleOf(p, field.ref))) {
232
498
  return {
233
499
  error: "fields_not_found",
234
- note: `[${field.ref}] is not on the page any more. Open or re-read the page and ask again with its numbers.`,
500
+ note: `[${field.ref}] is not on the page any more. Read the page again and ask with its numbers.`,
235
501
  };
236
502
  }
237
503
  }
@@ -263,15 +529,14 @@ export function browserTools(ctx, assets, files) {
263
529
  if ("error" in result) {
264
530
  return {
265
531
  error: result.error,
266
- note: "Nothing you can read was entered. Re-read the page and ask again with its current numbers.",
532
+ note: "Nothing you can read was entered. Read the page again and ask with its current numbers.",
267
533
  };
268
534
  }
269
535
  if (result.filled.length && input.submitRef !== undefined) {
270
- await current
271
- .locator(ref(input.submitRef))
272
- .first()
273
- .click({ timeout: 10_000 })
274
- .catch(() => undefined);
536
+ const target = await pointAt(current, input.submitRef);
537
+ if (!("error" in target)) {
538
+ await clickAt(ctx, current, target).catch(() => undefined);
539
+ }
275
540
  }
276
541
  await settle(current);
277
542
  await current.waitForLoadState("networkidle", { timeout: 5000 }).catch(() => undefined);
@@ -280,11 +545,11 @@ export function browserTools(ctx, assets, files) {
280
545
  if (answer.remember) {
281
546
  await ctx.resources.keepSession().catch(() => undefined);
282
547
  }
283
- return { status: "done", note, page: await pageSnapshot(current) };
548
+ return { status: "done", note, page: await read(ctx.resources.openPage() ?? current) };
284
549
  };
285
550
  tools.browser_request_credentials = createTool({
286
551
  id: "browser_request_credentials",
287
- description: "THE way to get a login into a page: ask the person to enter a username, e-mail, password or one-time code into fields on your current page, WITHOUT you seeing it. The person gets a picture of the page, the site's address and a form; what they type goes straight into the page, never to you. Give each field's [number] from your latest snapshot, and submit_ref to press the sign-in or next button afterwards. A login spread over several pages (e-mail, then password, then code) is one call per page. WAITS for the person. Never ask for a password any other way.",
552
+ description: "THE way to get a login into a page: ask the person to enter a username, e-mail, password or one-time code into fields on your current page, WITHOUT you seeing it. The person sees the page live, the site's address and a form; what they type goes straight into the page, never to you. Give each field's [number] from your latest page, and submit_ref to press the sign-in or next button afterwards. A login spread over several pages (e-mail, then password, then code) is one call per page. WAITS for the person. Never ask for a password any other way.",
288
553
  inputSchema: z.object({
289
554
  reason: z
290
555
  .string()
@@ -297,11 +562,11 @@ export function browserTools(ctx, assets, files) {
297
562
  .optional()
298
563
  .describe("[number] of the button to press once the fields are filled."),
299
564
  }),
300
- execute: ({ reason, fields, submit_ref }) => inTurn(() => handOver({ reason, fields, submitRef: submit_ref })),
565
+ execute: ({ reason, fields, submit_ref }) => acting(() => handOver({ reason, fields, submitRef: submit_ref })),
301
566
  });
302
567
  tools.browser_request_user = createTool({
303
568
  id: "browser_request_user",
304
- description: "Hand the page to the person for something no form can do: a captcha, 'continue with Google', a passkey, a cookie wall you cannot get past. They click and type in a picture of the page and say when they are done. For a plain login form use browser_request_credentials instead. WAITS for the person.",
569
+ description: "Hand the page to the person for something no form can do: a captcha, 'continue with Google', a passkey, a cookie wall you cannot get past. They click and type in the live page and say when they are done. For a plain login form use browser_request_credentials instead. WAITS for the person.",
305
570
  inputSchema: z.object({
306
571
  reason: z
307
572
  .string()
@@ -309,7 +574,7 @@ export function browserTools(ctx, assets, files) {
309
574
  .max(300)
310
575
  .describe("One sentence for the person, in their language: what to do on the page."),
311
576
  }),
312
- execute: ({ reason }) => inTurn(() => handOver({ reason, fields: [] })),
577
+ execute: ({ reason }) => acting(() => handOver({ reason, fields: [] })),
313
578
  });
314
579
  tools.browser_download = createTool({
315
580
  id: "browser_download",
@@ -322,15 +587,15 @@ export function browserTools(ctx, assets, files) {
322
587
  .describe("Where to keep it, e.g. invoices/2026-09/2026-09-03_Notion_INV-123.pdf"),
323
588
  source: z.string().optional().describe("Where it came from, in words, for the person."),
324
589
  }),
325
- execute: ({ ref: n, url, path, source }) => inTurn(async () => {
590
+ execute: ({ ref: n, url, path, source }) => acting(async () => {
326
591
  const p = await page();
327
- await ctx.emit("tool", {
328
- code: "downloads",
329
- params: { name: path.split("/").pop() ?? "" },
330
- });
331
592
  let data;
332
593
  let mime;
333
594
  if (url) {
595
+ await ctx.emit("tool", {
596
+ code: "downloads",
597
+ params: { name: path.split("/").pop() ?? "" },
598
+ });
334
599
  const res = await signedInGet(p, new URL(url, p.url()).toString());
335
600
  if (!res.ok()) {
336
601
  return { error: `The server answered ${res.status()}.` };
@@ -339,10 +604,18 @@ export function browserTools(ctx, assets, files) {
339
604
  mime = res.headers()["content-type"]?.split(";")[0];
340
605
  }
341
606
  else if (n !== undefined) {
607
+ const target = await atRef(p, n);
608
+ if ("error" in target) {
609
+ return target;
610
+ }
611
+ await ctx.emit("tool", {
612
+ code: "downloads",
613
+ params: { name: path.split("/").pop() ?? "" },
614
+ });
342
615
  // A click may start a download, open the file in a new tab, or both.
343
616
  const download = found(p.waitForEvent("download", { timeout: 12_000 }));
344
617
  const popup = found(p.context().waitForEvent("page", { timeout: 5000 }));
345
- await p.locator(ref(n)).first().click({ timeout: 10_000 });
618
+ await p.mouse.click(target.x, target.y);
346
619
  const opened = await Promise.race([popup, download.then(() => null)]).catch(() => null);
347
620
  const got = await Promise.any([
348
621
  download,
@@ -354,16 +627,13 @@ export function browserTools(ctx, assets, files) {
354
627
  }
355
628
  else {
356
629
  // No download event: the click opened the file in a tab (a PDF viewer).
357
- const target = opened ?? p;
358
- await settle(target);
359
- const res = await signedInGet(p, target.url());
630
+ const shown = opened ?? p;
631
+ await settle(shown);
632
+ const res = await signedInGet(p, shown.url());
360
633
  mime = res.headers()["content-type"]?.split(";")[0];
361
634
  if (!res.ok() || mime === "text/html") {
362
635
  await opened?.close().catch(() => undefined);
363
- return {
364
- error: "The click did not give a file.",
365
- page: await pageSnapshot(p),
366
- };
636
+ return { error: "The click did not give a file.", page: await read(p) };
367
637
  }
368
638
  data = await res.body();
369
639
  await opened?.close().catch(() => undefined);
@@ -382,5 +652,64 @@ export function browserTools(ctx, assets, files) {
382
652
  return { saved: kept.path, mime: kept.mime, size: kept.size };
383
653
  }),
384
654
  });
655
+ // The fast loop, where a decision model can be reached: a classifier picks each step.
656
+ const classifier = env.browserFastLoop
657
+ ? await classifierClient(ctx.signal)
658
+ : null;
659
+ if (classifier) {
660
+ const fieldText = createFieldText({
661
+ spans: { client: classifier },
662
+ ask: async (instructions, prompt) => {
663
+ const resolved = await textModel("classifier", ctx.call);
664
+ const result = await generateText({
665
+ model: resolved.model,
666
+ system: instructions,
667
+ prompt,
668
+ temperature: 0,
669
+ maxOutputTokens: 1024,
670
+ abortSignal: ctx.signal,
671
+ });
672
+ await ctx.chargeUsd(costOf(resolved, result.usage));
673
+ return result.text;
674
+ },
675
+ });
676
+ tools.browser_run_fast = createTool({
677
+ id: "browser_run_fast",
678
+ description: RUN_FAST_DESCRIPTION,
679
+ inputSchema: z.object({
680
+ goal: z
681
+ .string()
682
+ .min(1)
683
+ .max(2000)
684
+ .describe("The sub-goal for the current page, with every concrete value it needs (e.g. 'Close the cookie banner with only the necessary cookies, type lego millennium falcon into the search and search')."),
685
+ max_steps: z.number().int().min(1).max(100).optional().describe("Step budget; default 40."),
686
+ }),
687
+ execute: ({ goal, max_steps }) => acting(async () => {
688
+ const p = await page();
689
+ await ctx.emit("tool", { code: "fastLoop", params: { goal: short(goal) } });
690
+ const result = await runFastLoop({
691
+ client: classifier,
692
+ fieldText,
693
+ goal,
694
+ maxSteps: max_steps ?? 40,
695
+ minMargin: 0.1,
696
+ page: p,
697
+ shouldStop: () => ctx.signal.aborted || ctx.resources.seatHolder() === "person",
698
+ onStep: (step) => {
699
+ const note = fastStepNote(step);
700
+ if (note) {
701
+ ctx.emit("tool", note).catch(() => undefined);
702
+ }
703
+ },
704
+ });
705
+ return {
706
+ status: result.status,
707
+ note: result.note,
708
+ steps: result.history.map((h) => `${h.step}. ${h.operation} ${h.action}${h.text ? ` = "${h.text}"` : ""}${h.page_changed === false ? " (nothing changed)" : ""}`),
709
+ page: await read(ctx.resources.openPage() ?? p),
710
+ };
711
+ }),
712
+ });
713
+ }
385
714
  return tools;
386
715
  }