@glittering0717/ai-browser 2.4.1 → 2.4.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glittering0717/ai-browser",
3
- "version": "2.4.1",
3
+ "version": "2.4.3",
4
4
  "description": "AI-native browser — renders pixels for humans, structured semantic-tree API for agents. No screenshots, no OCR, no coordinate guessing.",
5
5
  "main": "src/main/index.js",
6
6
  "bin": {
@@ -64,6 +64,8 @@
64
64
  "network": "node e2e/network_ws.cjs",
65
65
  "value": "node e2e/value_ws.cjs",
66
66
  "canvas": "node e2e/canvas_ws.cjs",
67
+ "appmodel": "node e2e/app_model_ws.cjs",
68
+ "lifecycle": "node e2e/lifecycle_ws.cjs",
67
69
  "focus": "node e2e/focus_ws.cjs",
68
70
  "interact": "node e2e/interact_ws.cjs",
69
71
  "upload": "node e2e/upload_ws.cjs",
@@ -2,12 +2,16 @@
2
2
 
3
3
  ## canvas(纯绘制,没有 DOM 节点)
4
4
 
5
- 读内容**不要 OCR**。canvas 里的文本来自 `fillText` 调用,能被直接截获。
6
-
7
- - 前提:浏览器启动时带 `AI_BROWSER_CANVAS_HOOK=1`(默认关,因为要挂 CDP 绘制层)。
8
- - `browse_canvas {operation:"list"}` → 拿到 canvas 与 `canvas_id`
9
- - `browse_canvas {operation:"read", canvas_id}` → 文本 + 坐标 + 字体
10
- - **WebGL 是黑盒**:捕获不到文本,只能 `browse_canvas {operation:"capture"}` 拿 PNG,自己承担视觉成本。
5
+ **先找应用模型,再退到绘制层。**「图是 canvas」不等于「没有结构」:
6
+
7
+ 1. **`browse_capabilities {deep:true}`** —— 扫库指纹(fabric / Konva / paper / Excalidraw /
8
+ CodeMirror / Monaco)。实例即使**关在闭包里**也能抓出来(hook 原型方法 + 一条合成事件)。
9
+ 命中就给 `read_expr`(**顶层可求值的完整表达式**,直接喂 `browse_evaluate`)。
10
+ 有模型 → 读整张图的结构(图形类型/坐标/尺寸/文本),写完能**回读校验**。**这是首选。**
11
+ 2. 没有已知库 → `browse_canvas {operation:"list"}` + `read` 截获 `fillText` 文本
12
+ (需 `AI_BROWSER_CANVAS_HOOK=1`;**WebGL 是黑盒**,捕获不到文本,只能 `capture` 拿 PNG,
13
+ 自己承担视觉成本)。纯 canvas 应用**不要 OCR**。
14
+ 3. 都没有 → 只能靠坐标动作 + 帧指纹确认"画面变了",但**读不出"画的是什么"**(如实告知,别假装)。
11
15
 
12
16
  在 canvas 上落点用坐标动作,不要找元素:
13
17
 
@@ -0,0 +1,556 @@
1
+ // main/app_model_source.js — 「页面把模型关在闭包里」的通用解法
2
+ //
3
+ // 背景(2026-10-30 两轮实测,第二轮推翻了第一轮):draw.yunser.com 与
4
+ // suxieban.com 先后被判成「纯 canvas、没有应用模型」。复测证明这个判断是**错的**:
5
+ // suxieban 是 fabric 5.2.1(`getObjects` / `toJSON` / `toSVG` / `loadFromJSON` 全在),
6
+ // yunser 有 `window.DrawBoard` 构造器(`getState` / `loadState` / `save` 全在)。
7
+ // 判错的不是站点,是找法:capability_probe 扫的是 **window 上的对象**,
8
+ // 而这两个站把实例关在闭包里,window 上只留了库本身(`window.fabric`)或构造器。
9
+ //
10
+ // 所以这里做三件事,缺一不可:
11
+ // 1. 按「库指纹」认库(DOM class / 全局构造器 / 版本号),不靠猜 window 上的名字
12
+ // 2. 在库的原型上挂一个**只记 this** 的 tee,再派发一条合成 mousemove,让页面
13
+ // 自己的代码走一趟 —— 实例就落到手里。不接管行为:Reflect.apply 原样执行
14
+ // 3. 每个库一个 read(list),只调 getter,返回同一形状的 items
15
+ //
16
+ // 为什么不能只 hook 不认库:hook 抓到的 `this` 在压缩产物里是 `zz` / `t` 这种
17
+ // 构造器,不认识它就是一堆魔法字段。认库才知道「去哪读」。
18
+ //
19
+ // 这个模块只产字符串 + 纯函数,不依赖 Electron,可在纯 Node / jsdom 下单测。
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // 每库一个读取器。签名统一为 read(list) —— list 永远是「实例数组」,
23
+ // 单个实例的库就是长度 1。统一成数组是为了 Konva.stages / paper.projects
24
+ // 这类本身就是注册表的库不必特殊处理。
25
+ //
26
+ // ⚠️ 这些函数会被 String() 内联进页面执行,**不能引用本文件作用域里的任何变量**。
27
+ // 这也是测试能直接拿同一个函数喂假对象的原因:实现与判据共用一份代码。
28
+ // ---------------------------------------------------------------------------
29
+
30
+ export function readFabric(list) {
31
+ var items = [];
32
+ var total = 0;
33
+ var supports = [];
34
+ var errored = null;
35
+ for (var i = 0; i < list.length; i++) {
36
+ var inst = list[i];
37
+ var objs;
38
+ try { objs = inst.getObjects() || []; } catch (e) { errored = String(e && e.message || e); continue; }
39
+ total += objs.length;
40
+ for (var j = 0; j < objs.length; j++) {
41
+ var o = objs[j];
42
+ var it = { type: String(o.type || '?') };
43
+ it.x = Math.round(Number(o.left) || 0);
44
+ it.y = Math.round(Number(o.top) || 0);
45
+ it.w = Math.round((Number(o.width) || 0) * (Number(o.scaleX) || 1));
46
+ it.h = Math.round((Number(o.height) || 0) * (Number(o.scaleY) || 1));
47
+ if (o.text !== undefined && o.text !== null) it.text = String(o.text).slice(0, 120);
48
+ if (typeof o.fill === 'string') it.fill = o.fill;
49
+ if (typeof o.stroke === 'string') it.stroke = o.stroke;
50
+ if (o.angle) it.angle = Math.round(o.angle);
51
+ items.push(it);
52
+ }
53
+ if (!supports.length) {
54
+ var probe = ['getObjects', 'toJSON', 'toSVG', 'loadFromJSON', 'add', 'remove', 'getActiveObject', 'setActiveObject'];
55
+ for (var k = 0; k < probe.length; k++) {
56
+ if (typeof inst[probe[k]] === 'function') supports.push(probe[k]);
57
+ }
58
+ }
59
+ }
60
+ return { kind: 'objects', count: total, items: items, supports: supports, error: errored };
61
+ }
62
+
63
+ export function readKonva(list) {
64
+ var items = [];
65
+ var total = 0;
66
+ for (var i = 0; i < list.length; i++) {
67
+ var st = list[i];
68
+ var layers = [];
69
+ try { layers = st.getLayers() || []; } catch (e) { continue; }
70
+ for (var a = 0; a < layers.length; a++) {
71
+ var kids = [];
72
+ try { kids = layers[a].getChildren() || []; } catch (e) { continue; }
73
+ for (var b = 0; b < kids.length; b++) {
74
+ var n = kids[b];
75
+ total++;
76
+ var it = { type: String((n.getClassName && n.getClassName()) || n.className || '?') };
77
+ try { it.x = Math.round(n.x()); it.y = Math.round(n.y()); } catch (e) {}
78
+ try { if (typeof n.text === 'function' && n.text()) it.text = String(n.text()).slice(0, 120); } catch (e) {}
79
+ items.push(it);
80
+ }
81
+ }
82
+ }
83
+ return { kind: 'nodes', count: total, items: items, supports: ['getLayers', 'getChildren', 'find', 'toJSON'] };
84
+ }
85
+
86
+ export function readPaper(list) {
87
+ var items = [];
88
+ var total = 0;
89
+ for (var i = 0; i < list.length; i++) {
90
+ var proj = list[i];
91
+ var layer = proj && proj.activeLayer;
92
+ var kids = (layer && layer.children) || [];
93
+ total += kids.length;
94
+ for (var j = 0; j < kids.length; j++) {
95
+ var c = kids[j];
96
+ var it = { type: String((c.className || '?')).toLowerCase() };
97
+ try {
98
+ // position 是逻辑坐标,bounds 是**含描边的外框**。先取 position,
99
+ // bounds 只补尺寸 —— 反过来会让一条 1px 描边的线整体偏半个线宽。
100
+ if (c.position) { it.x = Math.round(c.position.x); it.y = Math.round(c.position.y); }
101
+ if (c.bounds) {
102
+ if (it.x === undefined) { it.x = Math.round(c.bounds.x); it.y = Math.round(c.bounds.y); }
103
+ it.w = Math.round(c.bounds.width); it.h = Math.round(c.bounds.height);
104
+ }
105
+ } catch (e) {}
106
+ try { if (c.content) it.text = String(c.content).slice(0, 120); } catch (e) {}
107
+ items.push(it);
108
+ }
109
+ }
110
+ return { kind: 'items', count: total, items: items, supports: ['activeLayer', 'project.exportJSON'] };
111
+ }
112
+
113
+ export function readCodeMirror(list) {
114
+ var items = [];
115
+ for (var i = 0; i < list.length; i++) {
116
+ var cm = list[i];
117
+ var v = '';
118
+ try { v = String(cm.getValue()); } catch (e) {}
119
+ items.push({ type: 'text', chars: v.length, text: v.slice(0, 2000) });
120
+ }
121
+ return { kind: 'text', count: items.length, items: items, supports: ['getValue', 'setValue', 'getDoc', 'replaceRange'] };
122
+ }
123
+
124
+ export function readMonaco(list) {
125
+ var items = [];
126
+ for (var i = 0; i < list.length; i++) {
127
+ var m = list[i];
128
+ var v = '';
129
+ try { v = String(m.getValue()); } catch (e) {}
130
+ var uri = '';
131
+ try { uri = String(m.uri && m.uri.toString ? m.uri.toString() : ''); } catch (e) {}
132
+ items.push({ type: 'text', uri: uri, chars: v.length, text: v.slice(0, 2000) });
133
+ }
134
+ return { kind: 'text', count: items.length, items: items, supports: ['getValue', 'setValue', 'getModel', 'applyEdits'] };
135
+ }
136
+
137
+ export function readExcalidraw(list) {
138
+ var items = [];
139
+ var total = 0;
140
+ var errors = null;
141
+ for (var i = 0; i < list.length; i++) {
142
+ var ex = list[i];
143
+ var els = [];
144
+ try { els = ex.getSceneElements() || []; } catch (e) { errors = String(e && e.message || e); continue; }
145
+ total += els.length;
146
+ for (var j = 0; j < els.length; j++) {
147
+ var e2 = els[j];
148
+ var it = { type: String(e2.type || '?') };
149
+ it.x = Math.round(Number(e2.x) || 0);
150
+ it.y = Math.round(Number(e2.y) || 0);
151
+ it.w = Math.round(Number(e2.width) || 0);
152
+ it.h = Math.round(Number(e2.height) || 0);
153
+ if (typeof e2.text === 'string' && e2.text) it.text = e2.text.slice(0, 120);
154
+ items.push(it);
155
+ }
156
+ }
157
+ var sup = [];
158
+ var probe = ['getSceneElements', 'updateScene', 'getAppState', 'history', 'scrollToContent'];
159
+ if (list[0]) {
160
+ for (var p = 0; p < probe.length; p++) {
161
+ if (typeof list[0][probe[p]] === 'function') sup.push(probe[p]);
162
+ }
163
+ }
164
+ return { kind: 'elements', count: total, items: items, supports: sup, error: errors };
165
+ }
166
+
167
+ // ---------------------------------------------------------------------------
168
+ // 适配器表 —— 每条都写明「怎么认出来」「实例从哪来」「怎么读」。
169
+ //
170
+ // acquire 只有两种取值:
171
+ // 'hook' → 原型 tee + 合成鼠标(实例在闭包里,只能等页面自己走一趟)
172
+ // 'expr' → 页面里现成的注册表 / DOM 属性 / 全局 API(不需要碰任何原型)
173
+ //
174
+ // 能用 'expr' 的一律用 'expr':不包装原型就没有副作用,也不需要卸载。
175
+ // ---------------------------------------------------------------------------
176
+ export const ADAPTERS = [
177
+ {
178
+ id: 'fabric',
179
+ // 双重指纹:DOM class(lower-canvas / canvas-container)+ 全局库对象。
180
+ // 只看 class 会误判那些用了 fabric 但删了 class 的站点;只看 window.fabric
181
+ // 会误判引了库却没初始化的页面。
182
+ detect: '!!(window.fabric && window.fabric.Canvas && window.fabric.Canvas.prototype && document.querySelector("canvas.lower-canvas"))',
183
+ version: '(window.fabric && window.fabric.version) || null',
184
+ acquire: 'hook',
185
+ hookProto: 'window.fabric.Canvas.prototype',
186
+ // ```__onMouseMove`` 是 fabric 5 的真正事件入口。只 hook `_onMouseMove`
187
+ // 实测完全抓不到(那一个是内层实现,DOM 上绑的是双下划线那个)。
188
+ hookMethods: ['__onMouseMove', '_onMouseMove', 'renderAll', 'requestRenderAll', 'renderTopLayer', 'add', 'remove', 'setActiveObject'],
189
+ read: readFabric,
190
+ readExpr: '.getObjects()',
191
+ writeHint: 'add(new fabric.Rect({...})) / loadFromJSON(snapshot) / remove(obj) — then re-read getObjects()',
192
+ },
193
+ {
194
+ id: 'konva',
195
+ detect: '!!(window.Konva && window.Konva.stages && window.Konva.stages.length)',
196
+ version: '(window.Konva && window.Konva.version) || null',
197
+ acquire: 'expr',
198
+ // Konva 自己维护了全局 stage 注册表,不必 hook。
199
+ acquireExpr: 'window.Konva.stages',
200
+ read: readKonva,
201
+ readExpr: 'window.Konva.stages',
202
+ writeHint: 'new Konva.Rect({...}).addTo(layer); layer.batchDraw()',
203
+ },
204
+ {
205
+ id: 'paper',
206
+ detect: '!!(window.paper && window.paper.projects && window.paper.projects.length)',
207
+ version: '(window.paper && window.paper.version) || null',
208
+ acquire: 'expr',
209
+ acquireExpr: 'window.paper.projects',
210
+ read: readPaper,
211
+ readExpr: 'window.paper.projects',
212
+ writeHint: 'new paper.Path.Rectangle({...}); paper.project.view.update()',
213
+ },
214
+ {
215
+ id: 'excalidraw',
216
+ detect: '!!(window.excalidraw && window.excalidraw.$excalidraw && typeof window.excalidraw.$excalidraw.getSceneElements === "function")',
217
+ version: null,
218
+ acquire: 'expr',
219
+ acquireExpr: '[window.excalidraw.$excalidraw]',
220
+ read: readExcalidraw,
221
+ readExpr: 'window.excalidraw.$excalidraw.getSceneElements()',
222
+ writeHint: 'updateScene({elements:[...]}) — 官方站 window 上没有模型,这条路只在「站点把它包出来」时成立',
223
+ },
224
+ {
225
+ id: 'codemirror',
226
+ detect: '!!document.querySelector(".CodeMirror")',
227
+ version: null,
228
+ acquire: 'expr',
229
+ // CM5 把实例挂在宿主元素上(el.CodeMirror),这是官方约定,不必 hook。
230
+ acquireExpr: '(function(){var n=document.querySelectorAll(".CodeMirror"),o=[];for(var i=0;i<n.length;i++){if(n[i].CodeMirror)o.push(n[i].CodeMirror)}return o})()',
231
+ read: readCodeMirror,
232
+ readExpr: 'document.querySelector(".CodeMirror").CodeMirror.getValue()',
233
+ writeHint: 'setValue(text) — 写完回读 getValue()',
234
+ },
235
+ {
236
+ id: 'monaco',
237
+ detect: '!!(window.monaco && window.monaco.editor && typeof window.monaco.editor.getModels === "function")',
238
+ version: null,
239
+ acquire: 'expr',
240
+ // 全局 API 直接给全部 model,是所有编辑器里最省事的一个。
241
+ acquireExpr: 'window.monaco.editor.getModels()',
242
+ read: readMonaco,
243
+ readExpr: 'window.monaco.editor.getModels()',
244
+ writeHint: 'model.setValue(text) / model.applyEdits([...])',
245
+ },
246
+ ];
247
+
248
+ // 未命中任何库时给的兜底指引。写进输出,而不是让 agent 自己发明。
249
+ // 页面里的总账本名。Node 侧拼 read_expr 时要用同一个字符串 ——
250
+ // 两处各写一份,改了一个漏另一个,read_expr 就会指向一个不存在的对象。
251
+ export const HUB_GLOBAL = '__aiAppModel';
252
+
253
+ export const GENERIC_HINT =
254
+ 'no known library matched. Two things to try before falling back to gestures: '
255
+ + '(1) the site may still export structure — look for an export/save entry (JSON, SVG, or a PNG-per-layer '
256
+ + 'snapshot like draw.yunser.com\'s getDataUrl) and read the file instead of the pixels; '
257
+ + '(2) instances are often closed over — tee ONE prototype method the page calls on its own: '
258
+ + 'const P=SomeLib.prototype; const o=P.someHotMethod; P.someHotMethod=function(){window.__x=this;return o.apply(this,arguments)}; '
259
+ + 'then dispatch one synthetic mousemove/resize so the page calls it, and read window.__x. '
260
+ + 'Never call an unknown method just to force it.';
261
+
262
+ /**
263
+ * 页面内探针脚本。
264
+ *
265
+ * 两阶段是刻意的:先把所有 hook 装完,再**只派发一次**合成鼠标。
266
+ * 逐适配器边装边触发会在同一画布上重复派发,页面会收到多次 hover。
267
+ */
268
+ export function buildAppModelSource(opts = {}) {
269
+ const maxItems = Math.max(1, Math.min(500, Number(opts.maxItems) || 200));
270
+
271
+ const specs = ADAPTERS.map((a) => {
272
+ // read_expr 必须是**能在页面顶层直接求值**的完整表达式。
273
+ //
274
+ // 这里踩过一次:`hook` 类的适配器只给了后缀(`.getObjects()`),于是
275
+ // read_expr 交出去的值是 ".getObjects()" —— agent 照着喂 ui.evaluate,
276
+ // `this` 是 undefined,当场 TypeError,而探针一路 PASS。e2e 的 AM-E13
277
+ // 就是为这条存在的:它真的把 read_expr 喂给 ui.evaluate。
278
+ //
279
+ // 三元包一层是因为 hits 可能被 restore() 清空或页面导航后消失 ——
280
+ // 那种情况下表达式要返回 null(可判断),而不是抛错。
281
+ let readExpr = null;
282
+ if (a.readExpr) {
283
+ if (a.acquire === 'hook') {
284
+ const base = `window.${HUB_GLOBAL}.hits.${a.id}[0]`;
285
+ readExpr = `(window.${HUB_GLOBAL} && window.${HUB_GLOBAL}.hits.${a.id} && ${base} ? ${base}${a.readExpr} : null)`;
286
+ } else {
287
+ readExpr = a.readExpr;
288
+ }
289
+ }
290
+ return {
291
+ id: a.id,
292
+ detect: a.detect,
293
+ version: a.version,
294
+ acquire: a.acquire,
295
+ acquireExpr: a.acquireExpr || null,
296
+ hookProto: a.hookProto || null,
297
+ hookMethods: a.hookMethods || [],
298
+ readSrc: String(a.read),
299
+ readExpr: readExpr,
300
+ writeHint: a.writeHint || null,
301
+ };
302
+ });
303
+
304
+ return `(function () {
305
+ "use strict";
306
+ var SPECS = ${JSON.stringify(specs)};
307
+ var MAX_ITEMS = ${maxItems};
308
+ var HUB_KEY = ${JSON.stringify(HUB_GLOBAL)};
309
+ try {
310
+ var G = window;
311
+ var HUB = G[HUB_KEY];
312
+ if (!HUB || HUB.v !== 1) {
313
+ HUB = G[HUB_KEY] = {
314
+ v: 1,
315
+ hits: {}, // id -> [instances]
316
+ orig: {}, // id -> { proto, methods: { name: fn } },供 restore
317
+ pokes: 0
318
+ };
319
+ }
320
+
321
+ // 真正把原型还回去。此前这里只写了 delete window.__aiAppModel,那只是
322
+ // 丢掉账本、tee 仍挂在原型上 —— 自述的「可卸载」与执行器不一致,
323
+ // 和语义树 advertise 假动作是同一类错误(宁可少说,也绝不撒谎)。
324
+ HUB.restore = function () {
325
+ var restored = 0;
326
+ for (var id in HUB.orig) {
327
+ var rec = HUB.orig[id];
328
+ if (!rec || !rec.proto) continue;
329
+ for (var m in rec.methods) {
330
+ try { rec.proto[m] = rec.methods[m]; restored++; } catch (e) {}
331
+ }
332
+ }
333
+ HUB.hits = {};
334
+ HUB.orig = {};
335
+ return restored;
336
+ };
337
+
338
+ function pushHit(id, inst) {
339
+ if (!inst) return;
340
+ var list = HUB.hits[id] || (HUB.hits[id] = []);
341
+ for (var i = 0; i < list.length; i++) if (list[i] === inst) return;
342
+ if (list.length < 8) list.push(inst);
343
+ }
344
+
345
+ // 只记 this,随后原样转发。参数、返回值、异常、this 一律不变 ——
346
+ // 包装失败的代价必须小于「不包装」,所以任何一步出错都退回直接调用。
347
+ function wrap(proto, name, id) {
348
+ var orig = proto[name];
349
+ if (typeof orig !== "function") return false;
350
+ if (orig.__aiAmTeed) return true;
351
+ var tee = function () {
352
+ try { pushHit(id, this); } catch (e) {}
353
+ return orig.apply(this, arguments);
354
+ };
355
+ tee.__aiAmTeed = true;
356
+ try { proto[name] = tee; } catch (e) { return false; }
357
+ var rec = HUB.orig[id] || (HUB.orig[id] = { proto: proto, methods: {} });
358
+ if (!rec.methods[name]) rec.methods[name] = orig;
359
+ return true;
360
+ }
361
+
362
+ // 幂等 + 自愈:页面自己重定义原型方法时,我们的 tee 会被覆盖。
363
+ // 每次调用都检查一遍,缺了就补 —— 否则「装过一次」的标记会让后续调用永远抓不到。
364
+ function ensureHooks(spec) {
365
+ var proto = null;
366
+ try { proto = eval(spec.hookProto); } catch (e) { return { ok: false, error: "hookProto threw: " + (e && e.message) }; }
367
+ if (!proto) return { ok: false, error: "hookProto resolved to null" };
368
+ var hit = [], miss = [];
369
+ for (var i = 0; i < spec.hookMethods.length; i++) {
370
+ var m = spec.hookMethods[i];
371
+ if (typeof proto[m] !== "function") { miss.push(m); continue; }
372
+ if (wrap(proto, m, spec.id)) hit.push(m);
373
+ }
374
+ return { ok: hit.length > 0, methods: hit, missing: miss };
375
+ }
376
+
377
+ // 一条合成 mousemove 足以让页面自己的代码走一趟原型(fabric 的方法没被
378
+ // bind 成实例属性,所以合成事件也能到达 tee)。优先 upper-canvas:那是
379
+ // fabric 的事件层,lower-canvas 只负责画。
380
+ function poke(maxCanvas) {
381
+ var order = [];
382
+ var up = document.querySelectorAll("canvas.upper-canvas");
383
+ for (var i = 0; i < up.length; i++) order.push(up[i]);
384
+ var all = document.querySelectorAll("canvas");
385
+ for (var j = 0; j < all.length && order.length < maxCanvas; j++) {
386
+ if (order.indexOf(all[j]) < 0) order.push(all[j]);
387
+ }
388
+ var n = 0;
389
+ for (var k = 0; k < order.length && n < maxCanvas; k++) {
390
+ var r;
391
+ try { r = order[k].getBoundingClientRect(); } catch (e) { continue; }
392
+ if (!(r.width > 4 && r.height > 4)) continue;
393
+ try {
394
+ order[k].dispatchEvent(new MouseEvent("mousemove", {
395
+ clientX: r.left + r.width / 2,
396
+ clientY: r.top + r.height / 2,
397
+ bubbles: true, cancelable: true, view: window
398
+ }));
399
+ n++;
400
+ } catch (e) {}
401
+ }
402
+ HUB.pokes += n;
403
+ return n;
404
+ }
405
+
406
+ // ---- 阶段一:检测 + 装 hook(不读任何状态) ----
407
+ var found = [];
408
+ for (var s = 0; s < SPECS.length; s++) {
409
+ var spec = SPECS[s];
410
+ var present = false;
411
+ try { present = !!eval(spec.detect); } catch (e) { present = false; }
412
+ if (!present) continue;
413
+ var ver = null;
414
+ if (spec.version) { try { ver = eval(spec.version); } catch (e) {} }
415
+ var hookInfo = null;
416
+ if (spec.acquire === "hook") hookInfo = ensureHooks(spec);
417
+ found.push({ spec: spec, version: ver, hookInfo: hookInfo, acquired: false });
418
+ }
419
+
420
+ // ---- 阶段二:只派发一次 ----
421
+ var needPoke = false;
422
+ for (var f2 = 0; f2 < found.length; f2++) {
423
+ var h = found[f2].hookInfo;
424
+ if (h && h.ok) { needPoke = true; break; }
425
+ }
426
+ var poked = needPoke ? poke(4) : 0;
427
+
428
+ // ---- 阶段三:取实例 + 读 ----
429
+ var out = { ok: true, libs: [], poked: poked, considered: SPECS.length };
430
+ for (var g = 0; g < found.length; g++) {
431
+ var rec = found[g];
432
+ var sp = rec.spec;
433
+ var list = null;
434
+ var acquireNote = null;
435
+ if (sp.acquire === "expr") {
436
+ try { list = eval(sp.acquireExpr); } catch (e) { acquireNote = "acquireExpr threw: " + (e && e.message); }
437
+ } else {
438
+ list = HUB.hits[sp.id] || null;
439
+ if (!list || !list.length) {
440
+ acquireNote = rec.hookInfo && !rec.hookInfo.ok
441
+ ? "hook failed: " + (rec.hookInfo.error || ("no methods matched (" + (rec.hookInfo.missing || []).join(", ") + ")"))
442
+ : "hook installed but the page did not call it after one synthetic mousemove";
443
+ }
444
+ }
445
+ if (!list) list = [];
446
+ if (!list.length) {
447
+ out.libs.push({
448
+ lib: sp.id, version: rec.version, acquired: false,
449
+ hook: rec.hookInfo, note: acquireNote,
450
+ read_expr: null, write_hint: sp.writeHint
451
+ });
452
+ continue;
453
+ }
454
+ var raw = null;
455
+ var readErr = null;
456
+ try {
457
+ var fn = eval("(" + sp.readSrc + ")");
458
+ raw = fn(list);
459
+ } catch (e) { readErr = String(e && e.message || e); }
460
+
461
+ var items = (raw && raw.items) || [];
462
+ var truncated = items.length > MAX_ITEMS;
463
+ if (truncated) items = items.slice(0, MAX_ITEMS);
464
+
465
+ out.libs.push({
466
+ lib: sp.id,
467
+ version: rec.version,
468
+ acquired: true,
469
+ instance_count: list.length,
470
+ hook: rec.hookInfo,
471
+ kind: (raw && raw.kind) || "unknown",
472
+ count: (raw && raw.count) || 0,
473
+ items: items,
474
+ truncated: truncated,
475
+ // supports 是**实测探测**的结果(对实例逐个 typeof),不是硬编码清单。
476
+ // 「广告的动作必须在执行器里真有」这条纪律同样适用于这里。
477
+ supports: (raw && raw.supports) || [],
478
+ error: readErr || (raw && raw.error) || null,
479
+ read_expr: sp.readExpr,
480
+ write_hint: sp.writeHint
481
+ });
482
+ }
483
+
484
+ out.installed = Object.keys(HUB.hits).filter(function (k) { return HUB.hits[k] && HUB.hits[k].length; });
485
+ // 只对 hook 类适配器有意义(expr 类从不碰原型)。expr 类站点执行它是空操作。
486
+ out.uninstall = "window." + HUB_KEY + ".restore()";
487
+ return out;
488
+ } catch (e) {
489
+ return { ok: false, error: String(e && e.message || e) };
490
+ }
491
+ })()`;
492
+ }
493
+
494
+ /**
495
+ * 归一化 + 给调用方的下一步。
496
+ *
497
+ * 这里做三件 Node 侧才有的事:把「读到了几个库」折成一句可判断的话、
498
+ * 在**没命中任何库**时给出可执行的兜底、把 read_expr 的失效条件写清楚
499
+ * (钩子活在当前文档里,导航即消失 —— 不标出来,agent 会在下一页照抄一个 null)。
500
+ */
501
+ export function summarize(raw, opts = {}) {
502
+ if (!raw || typeof raw !== 'object') return { ok: false, error: 'probe returned no object' };
503
+ if (raw.ok === false) return { ok: false, error: raw.error || 'probe failed' };
504
+
505
+ const libs = Array.isArray(raw.libs) ? raw.libs : [];
506
+ const acquired = libs.filter((l) => l && l.acquired);
507
+ const notes = [];
508
+
509
+ if (!libs.length) {
510
+ notes.push(GENERIC_HINT);
511
+ } else if (!acquired.length) {
512
+ for (const l of libs) {
513
+ notes.push(`${l.lib}: detected but not acquired — ${l.note || l.error || 'unknown reason'}`);
514
+ }
515
+ notes.push(
516
+ 'the library is present but its instance never surfaced. Next: ui.evaluate to tee ONE method '
517
+ + 'the page calls on its own (e.g. a render/update/mousemove handler on the library prototype), '
518
+ + 'then move the pointer over the canvas and read the captured `this`.'
519
+ );
520
+ }
521
+
522
+ return {
523
+ ok: true,
524
+ poked: Number(raw.poked) || 0,
525
+ // 诚实标注探针自身的副作用:合成 mousemove 会让页面跑一遍 hover 逻辑。
526
+ // 「读取不得打扰页面」是目标而不是既成事实,做了什么要说出来。
527
+ side_effect: raw.poked > 0
528
+ ? `dispatched ${raw.poked} synthetic mousemove(s) to visible canvas(es) to surface closed-over instances`
529
+ : null,
530
+ libs: libs.map((l) => ({
531
+ lib: l.lib,
532
+ version: l.version || null,
533
+ acquired: !!l.acquired,
534
+ kind: l.kind || null,
535
+ count: l.count || 0,
536
+ instance_count: l.instance_count || 0,
537
+ truncated: !!l.truncated,
538
+ supports: l.supports || [],
539
+ items: opts.include_items === false ? undefined : (l.items || []),
540
+ read_expr: l.acquired ? l.read_expr : null,
541
+ write_hint: l.write_hint || null,
542
+ error: l.error || null,
543
+ note: l.note || null,
544
+ hook: l.hook || null,
545
+ })),
546
+ installed: Array.isArray(raw.installed) ? raw.installed : [],
547
+ // 钩子与实例引用都活在**当前文档**里。
548
+ stale_after_navigation: true,
549
+ notes,
550
+ discipline: 'read is proven by the probe itself; any write through read_expr/write_hint must be '
551
+ + 'followed by another ui.app_model (or ui.snapshot + ui.diff) — a library call returning without '
552
+ + 'throwing is not evidence that the scene changed',
553
+ };
554
+ }
555
+
556
+ export default buildAppModelSource;
@@ -195,6 +195,61 @@ export async function probeCapabilities(pageManager, opts = {}) {
195
195
  }
196
196
 
197
197
  const route = recommend({ flat, dom, endpoints, coverage: (treeCtx && treeCtx.page_coverage) || null });
198
+
199
+ // ---- deep:window 上没有模型 ≠ 没有模型 ----
200
+ //
201
+ // 这一步存在的唯一理由是**两次假阴性**:suxieban(fabric 5.2.1)与
202
+ // yunser(window.DrawBoard)都被这个探针报成 "no app object on window",
203
+ // agent 于是降级到 L3 指针手势 + 帧指纹 —— 而两个站都有完整读写能力。
204
+ // 实例在闭包里,扫 window 永远扫不到。
205
+ //
206
+ // 只在**没有 window 模型时**才往下挖:已经有 L1_structured_data 的页面
207
+ // 再挖一遍只是重复劳动,还会平白派发一次合成鼠标。
208
+ let appModel = null;
209
+ if (opts.deep) {
210
+ const hasWindowModel = route.routes.some((r) => r.route === 'L1_structured_data');
211
+ if (hasWindowModel) {
212
+ appModel = { ok: true, skipped: 'window already exposes an app object — see L1_structured_data' };
213
+ } else if (typeof pageManager.appModel !== 'function') {
214
+ appModel = { ok: false, error: 'app_model probe unavailable in this build' };
215
+ } else {
216
+ try {
217
+ appModel = await pageManager.appModel({ tab: tid, max_items: opts.max_items });
218
+ } catch (e) {
219
+ appModel = { ok: false, error: e && e.message ? e.message : String(e) };
220
+ }
221
+ const hits = (appModel && appModel.ok && Array.isArray(appModel.libs))
222
+ ? appModel.libs.filter((l) => l && l.acquired) : [];
223
+ if (hits.length) {
224
+ const first = hits[0];
225
+ // 命中之后把其它首选全部降级。
226
+ //
227
+ // 实测(suxieban,179 个 DOM 元素 + fabric 画布):L2_semantic_tree
228
+ // 基于 "!graphObj && rich" 也把自己标成 preferred,于是 recommended
229
+ // 变成 ["L1_app_object_model","L2_semantic_tree"] 两个并列首选 ——
230
+ // 调用方看不出哪个更省力。既然模型读得到,就走模型那条,L2 保留在
231
+ // routes 里(它仍然可用,只是不是第一选择)。
232
+ for (const rt of route.routes) if (rt.route !== 'L1_app_object_model') rt.preferred = false;
233
+ route.routes.unshift({
234
+ route: 'L1_app_object_model',
235
+ preferred: true,
236
+ why: `${first.lib}${first.version ? ' ' + first.version : ''} instance found holding ${first.count} ${first.kind || 'item'}(s), even though window exposes no app object — the instance is closed over, so the plain-window scan was a false negative on this page`,
237
+ evidence: {
238
+ libs: hits.map((l) => `${l.lib}${l.version ? '@' + l.version : ''} `
239
+ + `(${l.count} ${l.kind || 'items'}; supports: ${(l.supports || []).slice(0, 6).join('/') || 'none probed'})`),
240
+ read_expr: first.read_expr,
241
+ // 探针自己干了什么要说出来:合成鼠标会让页面跑一遍 hover 逻辑。
242
+ side_effect: appModel.side_effect || null,
243
+ },
244
+ how: `ui.evaluate "${first.read_expr}" to read the scene; write through `
245
+ + `${first.write_hint || "the library's own API"}, then read the same expression again — `
246
+ + 'a library call returning without throwing is not evidence that the scene changed',
247
+ });
248
+ route.recommended = ['L1_app_object_model'];
249
+ }
250
+ }
251
+ }
252
+
198
253
  return {
199
254
  ok: true,
200
255
  tab: tid,
@@ -223,6 +278,9 @@ export async function probeCapabilities(pageManager, opts = {}) {
223
278
  app_globals: (dom && dom.globals) || [],
224
279
  endpoints,
225
280
  route,
281
+ // null = 没有要求 deep;{skipped} = 有 window 模型不必挖;
282
+ // 其余见 app_model_source.js 的 summarize 契约。
283
+ app_model: appModel,
226
284
  };
227
285
  }
228
286