@weavetab/plugin-realtime 0.0.0-stage → 0.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,114 @@
1
- # Temporary Holding Version
1
+ # @weavetab/plugin-realtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Weavetab plugin for pages that change faster than an LLM can look at them. Four tools, one `/` command, one `@` mention, and one hook:
4
+
5
+ | | what it does |
6
+ |---|---|
7
+ | `browser_map` hook | appends `{new 180ms, 64px from click}` to elements that appeared recently, so two identical "Confirm" buttons stop being ambiguous |
8
+ | `realtime_canvas` | records Canvas2D draw calls for a few frames and returns entities with bbox and px/frame velocity |
9
+ | `realtime_reflex` | registers a rule that runs inside the page every animation frame, no LLM round-trip |
10
+ | `realtime_autopilot` | bounded click loop for short sub-goals ("accept cookies") |
11
+ | `realtime_status` | state of the above; can block until reflexes finish |
12
+ | `/realtime_watch` | MCP Prompt (`/realtime_watch goal=... mode=auto`) that snapshots live tab state and guides the agent through arming a 60Hz DOM or canvas reflex |
13
+ | `@realtime_feed` | MCP Resource (`realtime://feed`) returning active reflexes, newly mutated DOM elements with click distance, and tracked Canvas2D entities |
14
+
15
+ Nothing in `@weavetab/mcp` or `@weavetab/sdk` is modified. It only uses the plugin hooks and the CDP session Weavetab already hands to plugins.
16
+
17
+ ## Install
18
+
19
+ ```
20
+ npm install @weavetab/plugin-realtime
21
+ ```
22
+
23
+ Requires Weavetab `>=2.6.1` and Node `>=18`. The plugin declares `cdp.evaluate`, `cdp.input`, `tools.add`, `prompts.add`, `resources.add`, `hooks.onBeforeAction/onAfterAction` and a `network` permission for `127.0.0.1`/`localhost` (only used by `model_url`).
24
+
25
+ ## Causal tags
26
+
27
+ A `MutationObserver` is injected into the page on the first tool call after each navigation and records when nodes were added. After `browser_map`, lines for elements added within the last `causalWindowMs` (default 4000, set in the plugin config) get a tag, plus the distance from the last pointer click if there was one in the last 15 s:
28
+
29
+ ```
30
+ [w:1] button "Confirm"
31
+ [w:2] button "Confirm" {new 210ms, 48px from click}
32
+ ```
33
+
34
+ Limits:
35
+ - Only nodes added **after** the probe was installed can be tagged. Whatever was on the page before the first tool call is never "new".
36
+ - The tag looks elements up through the `data-wt-id` attribute Weavetab's walker writes. Elements inside shadow roots that `document.querySelector` can't reach are left untagged.
37
+ - A framework that re-renders a node makes it look new. That is accurate, it is a new node.
38
+
39
+ ## realtime_canvas
40
+
41
+ `action: "sample"` (default) watches `frames` frames (2–15, default 6) and returns:
42
+
43
+ ```json
44
+ {
45
+ "frames": 6, "fps": 60,
46
+ "canvases": [{ "i": 0, "id": null, "w": 400, "h": 120, "left": 8, "top": 8, "sx": 1, "sy": 1 }],
47
+ "entities": [{ "sig": "rect|20x20|#ff0000", "canvas": 0, "x": 85, "y": 40, "w": 20, "h": 20, "vx": 5, "vy": 0 }],
48
+ "groups": [{ "sig": "img|16x16|tile.png", "count": 120, "moving": 0 }],
49
+ "background_fills": 1
50
+ }
51
+ ```
52
+
53
+ Coordinates are canvas pixels. Viewport position is `left + x * sx`, `top + y * sy`. `sig` is `kind|WxH|key` where key is the fill colour, text, or image file name (and source rect for sprite sheets). Velocity comes from nearest-neighbour matching of same-signature draws across frames. Signatures with more than 6 instances are summarised under `groups`. Full-canvas rect fills are counted in `background_fills` instead of listed.
54
+
55
+ `attach` starts recording early, `detach` restores `CanvasRenderingContext2D.prototype` and `requestAnimationFrame`.
56
+
57
+ What it cannot see:
58
+ - **WebGL / WebGPU.** Only the 2D context is hooked.
59
+ - Draws made outside a `requestAnimationFrame` callback, and games that cached `requestAnimationFrame` or a context method before attaching.
60
+ - Arcs are recorded only when they are full circles and get filled/stroked. `drawImage` of offscreen canvases that are not in the document is ignored.
61
+ - Text position ignores `textAlign`.
62
+
63
+ ## realtime_reflex
64
+
65
+ ```jsonc
66
+ // click a button the moment a new "Claim" button shows up
67
+ { "action": "add",
68
+ "when": { "selector": "button", "text": "claim", "only_new": true },
69
+ "do": { "type": "click" }, "max_hits": 1 }
70
+
71
+ // jump when the cactus is close (signatures come from realtime_canvas)
72
+ { "action": "add",
73
+ "when": { "canvas": { "names": { "p": "rect|20x20|#ff0000", "o": "rect|10x30|#00ff00" },
74
+ "js": "gap(E.p[0], E.o[0]) < 50" } },
75
+ "do": { "type": "key", "key": "Space" }, "cooldown_ms": 300, "max_hits": 20 }
76
+ ```
77
+
78
+ In `canvas.js`, `E.<name>` is an array of `{x, y, w, h, vx, vy}` for that signature in the last completed frame. `dist(a, b)` is centre distance, `gap(a, b)` is `b.x - (a.x + a.w)`; both return `Infinity` if either argument is `undefined`, so a missing obstacle does not kill the rule. Any other exception disables the rule and shows up as `error` in `realtime_status`.
79
+
80
+ Defaults: `cooldown_ms` 100, `max_hits` 50, `ttl_ms` 30000 (max 600000). `stop_selector` ends the rule when that selector exists. Actions: `click` (selector triggers only), `click_xy` (viewport coordinates), `key` (`hold_ms` default 40), `js`.
81
+
82
+ Limits you should know before relying on it:
83
+ - **Events are synthetic.** Anything that checks `event.isTrusted` ignores them. Keys go to `document.activeElement` (the body if nothing is focused), so a game that listens on an unfocused canvas will not see them.
84
+ - The loop runs on `requestAnimationFrame`, which browsers pause in hidden or background tabs.
85
+ - Canvas rules react to the last completed frame, so expect up to one frame of lag.
86
+ - Rules live in the page. Navigation wipes them.
87
+ - `when.canvas.js` and `do.js` are sent as source through CDP, so page CSP without `unsafe-eval` does not block them. They run with full page privileges, same as `browser_eval`.
88
+
89
+ ## realtime_autopilot
90
+
91
+ Loop of: collect visible, un-occluded clickables, pick one, click it with real CDP mouse events, wait for the DOM to go quiet, repeat. Stops on `stop_when_selector`, `stop_when_text`, `stop_when_url` (regex), `max_steps` (default 8, max 25) or `no_match`.
92
+
93
+ Ranking is a heuristic, not a planner: each goal word (3+ letters, common filler dropped) that prefix-matches a word in the label scores 3. Elements that appeared in the last 3 s get +2, elements inside an open dialog +3 (others −3), elements within 250 px of the last click +1. Below 3 total, the loop stops with `no_match`. A button whose click changed neither the DOM nor the URL is not clicked again.
94
+
95
+ Labels matching `delete|remove|pay|purchase|place order|sign out|log out|unsubscribe|deactivate` are skipped unless the goal contains one of those words. `avoid_labels` adds your own regex.
96
+
97
+ `model_url` (optional) points at an OpenAI-compatible `/v1/chat/completions` endpoint (llama.cpp server, Ollama, LM Studio). The top 12 candidates are sent with the goal and the reply must contain `{"pick": n|null, "done": bool}`. Any HTTP error, timeout (`model_timeout_ms`, default 1500) or unparsable reply falls back to the ranker for the rest of the run and is reported as `model_error`. Needle (Cactus) has not been tested against this; it is a tool-calling model with its own interface and is not assumed to speak this protocol.
98
+
99
+ Offscreen elements are not considered. Scroll first.
100
+
101
+ ## Development
102
+
103
+ ```
104
+ npm install
105
+ npm run build
106
+ npm test
107
+ npx weavetab preflight
108
+ ```
109
+
110
+ `npm test` drives a real headless Chrome through CDP (set `CHROME_PATH` if it is not in a default location; the browser tests are skipped when none is found). It covers the tags, canvas sampling, both reflex trigger types, and the autopilot guards.
111
+
112
+ ## License
113
+
114
+ Apache-2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,18 @@
1
+ type Args = {
2
+ goal: string;
3
+ max_steps?: number;
4
+ stop_when_selector?: string;
5
+ stop_when_text?: string;
6
+ stop_when_url?: string;
7
+ avoid_labels?: string;
8
+ model_url?: string;
9
+ model?: string;
10
+ model_timeout_ms?: number;
11
+ };
12
+ export declare function autopilotTool(sess: any, a: Args): Promise<{
13
+ model_error?: string | undefined;
14
+ stopped: string;
15
+ steps: unknown[];
16
+ url: any;
17
+ }>;
18
+ export {};
@@ -0,0 +1,171 @@
1
+ import { run, arm } from "./page.js";
2
+ const NOISE = new Set("the and then until all any click press tap button link please that this with from into when once done after before for".split(" "));
3
+ const RISKY = /delete|remove|\bpay\b|purchase|place order|sign out|log ?out|unsubscribe|deactivate/i;
4
+ const COLLECT = `(() => {
5
+ const rt = window.__wt_rt, now = performance.now();
6
+ const sel = 'button, a[href], input[type=button], input[type=submit], input[type=checkbox], input[type=radio], summary, [role=button], [role=link], [role=menuitem], [role=tab], [role=checkbox], [onclick]';
7
+ const dlg = [...document.querySelectorAll('dialog[open], [role=dialog], [role=alertdialog], [aria-modal=true]')]
8
+ .find((d) => d.getBoundingClientRect().width > 0);
9
+ const els = window.__wt_ap = [];
10
+ const cands = [];
11
+ for (const el of document.querySelectorAll(sel)) {
12
+ const r = el.getBoundingClientRect();
13
+ if (r.width < 2 || r.height < 2 || r.bottom < 0 || r.right < 0 || r.top > innerHeight || r.left > innerWidth) continue;
14
+ const s = getComputedStyle(el);
15
+ if (s.visibility === 'hidden' || s.display === 'none') continue;
16
+ const x = r.left + r.width / 2, y = r.top + r.height / 2;
17
+ const top = document.elementFromPoint(x, y);
18
+ if (!top || !(top === el || el.contains(top) || top.contains(el))) continue;
19
+ let born;
20
+ for (let n = el; n && born === undefined; n = n.parentElement) born = rt.born.get(n);
21
+ const label = (el.getAttribute('aria-label') || el.innerText || el.value || el.title || '').trim().replace(/\\s+/g, ' ').slice(0, 60);
22
+ els.push(el);
23
+ cands.push({ i: els.length - 1, label, role: el.getAttribute('role') || el.tagName.toLowerCase(), x, y,
24
+ age: born === undefined ? null : Math.round(now - born), dlg: Boolean(dlg && dlg.contains(el)),
25
+ off: Boolean(el.disabled || el.getAttribute('aria-disabled') === 'true') });
26
+ }
27
+ const c = rt.click && now - rt.click.t < 15000 ? rt.click : null;
28
+ return { cands, hasDlg: Boolean(dlg), click: c && { x: c.x, y: c.y }, url: location.href, t: now };
29
+ })()`;
30
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
31
+ // a click that navigates kills the execution context for a moment
32
+ async function steady(fn) {
33
+ for (let n = 0;; n++) {
34
+ try {
35
+ return await fn();
36
+ }
37
+ catch (e) {
38
+ if (n >= 8 || !/context|destroyed|detached|navigat/i.test(e?.message || ""))
39
+ throw e;
40
+ await sleep(120);
41
+ }
42
+ }
43
+ }
44
+ function words(s) {
45
+ return s.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3 && !NOISE.has(w));
46
+ }
47
+ function score(c, goal, hasDlg, click) {
48
+ const lab = words(c.label);
49
+ let hit = 0;
50
+ for (const g of goal)
51
+ if (lab.some((t) => t.startsWith(g) || g.startsWith(t)))
52
+ hit++;
53
+ if (!hit)
54
+ return 0;
55
+ let s = hit * 3;
56
+ if (c.age != null && c.age <= 3000)
57
+ s += 2;
58
+ if (hasDlg)
59
+ s += c.dlg ? 3 : -3;
60
+ if (click && Math.hypot(c.x - click.x, c.y - click.y) < 250)
61
+ s += 1;
62
+ return s;
63
+ }
64
+ async function askModel(a, list) {
65
+ const lines = list.map((c, n) => `${n}: [${c.role}] "${c.label}"${c.age != null && c.age <= 3000 ? " (new)" : ""}${c.dlg ? " (dialog)" : ""}`);
66
+ const res = await fetch(a.model_url, {
67
+ method: "POST",
68
+ headers: { "content-type": "application/json" },
69
+ signal: AbortSignal.timeout(a.model_timeout_ms ?? 1500),
70
+ body: JSON.stringify({
71
+ model: a.model || "local",
72
+ temperature: 0,
73
+ max_tokens: 40,
74
+ messages: [
75
+ { role: "system", content: 'You pick the next click in a browser. Reply with JSON only: {"pick": <number or null>, "done": <true|false>}.' },
76
+ { role: "user", content: `Goal: ${a.goal}\nClickable elements:\n${lines.join("\n")}` },
77
+ ],
78
+ }),
79
+ });
80
+ if (!res.ok)
81
+ throw new Error(`model http ${res.status}`);
82
+ const body = await res.json();
83
+ const txt = body?.choices?.[0]?.message?.content ?? "";
84
+ const m = /\{[\s\S]*\}/.exec(txt);
85
+ if (!m)
86
+ throw new Error("model gave no json");
87
+ const out = JSON.parse(m[0]);
88
+ const pick = Number.isInteger(out.pick) && out.pick >= 0 && out.pick < list.length ? out.pick : null;
89
+ return { pick, done: out.done === true };
90
+ }
91
+ export async function autopilotTool(sess, a) {
92
+ const goal = words(a.goal);
93
+ if (!goal.length && !a.model_url)
94
+ throw new Error("goal has no usable words");
95
+ const extra = a.avoid_labels ? new RegExp(a.avoid_labels, "i") : null;
96
+ const riskOk = RISKY.test(a.goal);
97
+ const dead = new Set();
98
+ const steps = [];
99
+ let modelErr;
100
+ let stopped = "max_steps";
101
+ const cap = Math.min(Math.max(a.max_steps ?? 8, 1), 25);
102
+ const stopNow = () => steady(() => run(sess, `((sel, txt, re) => {
103
+ if (sel) { const e = document.querySelector(sel); if (e) { const r = e.getBoundingClientRect(); if (r.width || r.height) return 'selector'; } }
104
+ if (txt && document.body.innerText.toLowerCase().includes(txt)) return 'text';
105
+ if (re && new RegExp(re).test(location.href)) return 'url';
106
+ return null;
107
+ })(${JSON.stringify(a.stop_when_selector ?? null)}, ${JSON.stringify(a.stop_when_text?.toLowerCase() ?? null)}, ${JSON.stringify(a.stop_when_url ?? null)})`));
108
+ for (let n = 1; n <= cap; n++) {
109
+ await steady(() => arm(sess));
110
+ const hit = await stopNow();
111
+ if (hit) {
112
+ stopped = hit;
113
+ break;
114
+ }
115
+ const pg = await steady(() => run(sess, COLLECT));
116
+ const keyOf = (c) => `${c.role}|${c.label}|${Math.round(c.x / 10)}|${Math.round(c.y / 10)}`;
117
+ const pool = pg.cands.filter((c) => !c.off && !dead.has(keyOf(c)) && !(extra && extra.test(c.label)) && !(!riskOk && RISKY.test(c.label)));
118
+ const ranked = pool
119
+ .map((c) => ({ c, s: score(c, goal, pg.hasDlg, pg.click) }))
120
+ .sort((p, q) => q.s - p.s);
121
+ let pick;
122
+ let how = "scorer";
123
+ let sc = 0;
124
+ if (a.model_url && !modelErr) {
125
+ try {
126
+ const list = ranked.slice(0, 12).map((r) => r.c);
127
+ const m = await askModel(a, list);
128
+ if (m.done) {
129
+ stopped = "model_done";
130
+ break;
131
+ }
132
+ if (m.pick == null) {
133
+ stopped = "no_match";
134
+ break;
135
+ }
136
+ pick = list[m.pick];
137
+ how = "model";
138
+ }
139
+ catch (e) {
140
+ modelErr = e?.message || String(e);
141
+ }
142
+ }
143
+ if (!pick) {
144
+ if (!ranked.length || ranked[0].s < 3) {
145
+ stopped = "no_match";
146
+ break;
147
+ }
148
+ pick = ranked[0].c;
149
+ sc = ranked[0].s;
150
+ }
151
+ const pre = pg.t;
152
+ for (const type of ["mouseMoved", "mousePressed", "mouseReleased"]) {
153
+ await sess.Input.dispatchMouseEvent({ type, x: pick.x, y: pick.y, button: "left", clickCount: type === "mouseMoved" ? 0 : 1 });
154
+ }
155
+ await sleep(80);
156
+ let quiet = false;
157
+ for (let w = 0; w < 8 && !quiet; w++) {
158
+ const st = await steady(() => run(sess, "window.__wt_rt ? performance.now() - window.__wt_rt.lastMut : 1e9"));
159
+ quiet = st >= 120;
160
+ if (!quiet)
161
+ await sleep(60);
162
+ }
163
+ const after = await steady(() => run(sess, "[location.href, window.__wt_rt ? window.__wt_rt.lastMut : 1e9]"));
164
+ const changed = after[0] !== pg.url || after[1] > pre;
165
+ if (!changed)
166
+ dead.add(keyOf(pick));
167
+ steps.push({ n, label: pick.label, via: how, score: how === "scorer" ? sc : undefined, changed });
168
+ }
169
+ const url = await steady(() => run(sess, "location.href"));
170
+ return { stopped, steps, url, ...(modelErr ? { model_error: modelErr } : {}) };
171
+ }
@@ -0,0 +1,5 @@
1
+ export declare function canvasTool(sess: any, a: {
2
+ action: "sample" | "attach" | "detach";
3
+ frames?: number;
4
+ }): Promise<any>;
5
+ export declare function canvasSnap(sess: any): Promise<any>;