gz-laya-pilot 0.1.0 → 0.1.2

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 (95) hide show
  1. package/NOTICE.md +20 -2
  2. package/README.md +54 -2
  3. package/dist/agent/bridge.d.ts +21 -0
  4. package/dist/agent/bridge.js +158 -0
  5. package/dist/agent/bridge.js.map +1 -0
  6. package/dist/agent/report.d.ts +54 -0
  7. package/dist/agent/report.js +100 -0
  8. package/dist/agent/report.js.map +1 -0
  9. package/dist/agent/run.d.ts +19 -0
  10. package/dist/agent/run.js +121 -0
  11. package/dist/agent/run.js.map +1 -0
  12. package/dist/agent/schema.d.ts +42 -0
  13. package/dist/agent/schema.js +9 -0
  14. package/dist/agent/schema.js.map +1 -0
  15. package/dist/agent/worker.d.ts +1 -0
  16. package/dist/agent/worker.js +102 -0
  17. package/dist/agent/worker.js.map +1 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +7 -0
  20. package/dist/cli.js.map +1 -0
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +2 -0
  23. package/dist/index.js.map +1 -1
  24. package/package.json +14 -6
  25. package/src/agent/bridge.ts +180 -0
  26. package/src/agent/report.ts +139 -0
  27. package/src/agent/run.ts +136 -0
  28. package/src/agent/schema.ts +38 -0
  29. package/src/agent/worker.ts +114 -0
  30. package/src/cli.ts +5 -0
  31. package/src/index.ts +3 -0
  32. package/vendor/.gitattributes +5 -0
  33. package/vendor/UPSTREAM.json +168 -0
  34. package/vendor/laya-pilot/LICENSE +21 -0
  35. package/vendor/laya-pilot/README.en.md +116 -0
  36. package/vendor/laya-pilot/README.md +116 -0
  37. package/vendor/laya-pilot/ROADMAP.md +21 -0
  38. package/vendor/laya-pilot/config.example.json +14 -0
  39. package/vendor/laya-pilot/docs/architecture.md +21 -0
  40. package/vendor/laya-pilot/docs/browser-use-evaluation.md +32 -0
  41. package/vendor/laya-pilot/docs/demo.png +0 -0
  42. package/vendor/laya-pilot/docs/local-runtime.md +88 -0
  43. package/vendor/laya-pilot/docs/pr1-selection.md +33 -0
  44. package/vendor/laya-pilot/docs/retry-policy.md +14 -0
  45. package/vendor/laya-pilot/examples/demo-cases.xlsx +0 -0
  46. package/vendor/laya-pilot/examples/demo-server.mjs +19 -0
  47. package/vendor/laya-pilot/examples/demo.html +733 -0
  48. package/vendor/laya-pilot/lib/auth-state.mjs +141 -0
  49. package/vendor/laya-pilot/lib/browser-provider.mjs +43 -0
  50. package/vendor/laya-pilot/lib/diagnostics.mjs +210 -0
  51. package/vendor/laya-pilot/lib/discovery.mjs +474 -0
  52. package/vendor/laya-pilot/lib/dom.mjs +539 -0
  53. package/vendor/laya-pilot/lib/engine.mjs +879 -0
  54. package/vendor/laya-pilot/lib/form.mjs +377 -0
  55. package/vendor/laya-pilot/lib/language.mjs +273 -0
  56. package/vendor/laya-pilot/lib/model.mjs +271 -0
  57. package/vendor/laya-pilot/lib/page-capabilities.mjs +356 -0
  58. package/vendor/laya-pilot/lib/page-exploration.mjs +372 -0
  59. package/vendor/laya-pilot/lib/page-session.mjs +69 -0
  60. package/vendor/laya-pilot/lib/pending-writes.mjs +50 -0
  61. package/vendor/laya-pilot/lib/planner.mjs +127 -0
  62. package/vendor/laya-pilot/lib/project-config.mjs +95 -0
  63. package/vendor/laya-pilot/lib/readiness.mjs +179 -0
  64. package/vendor/laya-pilot/lib/related-records.mjs +328 -0
  65. package/vendor/laya-pilot/lib/replay-model.mjs +44 -0
  66. package/vendor/laya-pilot/lib/run-state.mjs +133 -0
  67. package/vendor/laya-pilot/lib/test-data.mjs +128 -0
  68. package/vendor/laya-pilot/lib/workflow-policy.mjs +68 -0
  69. package/vendor/laya-pilot/lib/workflow.mjs +2321 -0
  70. package/vendor/laya-pilot/lib/workflow_excel.py +462 -0
  71. package/vendor/laya-pilot/requirements-local.txt +2 -0
  72. package/vendor/laya-pilot/requirements.txt +1 -0
  73. package/vendor/laya-pilot/runner.mjs +452 -0
  74. package/vendor/laya-pilot/tests/api.test.mjs +98 -0
  75. package/vendor/laya-pilot/tests/browser/runtime.test.mjs +847 -0
  76. package/vendor/laya-pilot/tests/config.test.mjs +109 -0
  77. package/vendor/laya-pilot/tests/diagnostics.test.mjs +91 -0
  78. package/vendor/laya-pilot/tests/discovery.test.mjs +76 -0
  79. package/vendor/laya-pilot/tests/fixtures/local-model/laya.py +28 -0
  80. package/vendor/laya-pilot/tests/fixtures/local-model/torch.py +5 -0
  81. package/vendor/laya-pilot/tests/guards.test.mjs +43 -0
  82. package/vendor/laya-pilot/tests/language.test.mjs +39 -0
  83. package/vendor/laya-pilot/tests/planner.test.mjs +129 -0
  84. package/vendor/laya-pilot/tests/readiness.test.mjs +118 -0
  85. package/vendor/laya-pilot/tests/real-model.smoke.mjs +74 -0
  86. package/vendor/laya-pilot/tests/replay-model.test.mjs +90 -0
  87. package/vendor/laya-pilot/tests/retries.test.mjs +270 -0
  88. package/vendor/laya-pilot/tests/run-state.test.mjs +162 -0
  89. package/vendor/laya-pilot/tests/selected-pr1.test.mjs +309 -0
  90. package/vendor/laya-pilot/tests/test-data.test.mjs +83 -0
  91. package/vendor/laya-pilot/tests/test_workflow_excel.py +162 -0
  92. package/vendor/laya-pilot/tests/worker_test.py +33 -0
  93. package/vendor/laya-pilot/tests/workflow.test.mjs +98 -0
  94. package/vendor/laya-pilot/worker.py +135 -0
  95. package/vendor/patches/0001-native-field-recipes.patch +3009 -0
@@ -0,0 +1,539 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { Halt, norm } from './language.mjs';
3
+ const ATTR = 'data-laya-live-ref';
4
+ export async function observe(page) {
5
+ const nonce = randomBytes(5).toString('hex'),
6
+ controls = [];
7
+ const frames = page.frames();
8
+ for (let fi = 0; fi < frames.length; fi++) {
9
+ const items = await frames[fi]
10
+ .evaluate(
11
+ ({ nonce, fi, attr }) => {
12
+ const visible = (e) => {
13
+ const s = getComputedStyle(e),
14
+ r = e.getBoundingClientRect();
15
+ let left = r.left,
16
+ right = r.right,
17
+ top = r.top,
18
+ bottom = r.bottom;
19
+ // Collapsed disclosure content may retain nonzero boxes.
20
+ // Do not offer controls clipped by overflow:hidden/clip;
21
+ // scrollable containers remain usable by Playwright.
22
+ for (let p = e.parentElement; p; p = p.parentElement) {
23
+ const style = getComputedStyle(p),
24
+ box = p.getBoundingClientRect();
25
+ if (['hidden', 'clip'].includes(style.overflowX)) {
26
+ left = Math.max(left, box.left);
27
+ right = Math.min(right, box.right);
28
+ }
29
+ if (['hidden', 'clip'].includes(style.overflowY)) {
30
+ top = Math.max(top, box.top);
31
+ bottom = Math.min(bottom, box.bottom);
32
+ }
33
+ }
34
+ return (
35
+ s.display !== 'none' &&
36
+ s.visibility !== 'hidden' &&
37
+ r.width > 0 &&
38
+ r.height > 0 &&
39
+ right > left &&
40
+ bottom > top &&
41
+ !e.closest('[inert],[aria-hidden="true"]')
42
+ );
43
+ };
44
+ const text = (e) =>
45
+ (e?.innerText || e?.textContent || '').replace(/\s+/g, ' ').trim();
46
+ const regionSelector =
47
+ 'aside,[role="complementary"],section[aria-label],section[aria-labelledby],[role="region"],main,[role="main"],header,[role="banner"],nav,[role="navigation"]';
48
+ const describeRegion = (e) =>
49
+ e
50
+ ? {
51
+ role:
52
+ e.getAttribute('role') ||
53
+ {
54
+ aside: 'complementary',
55
+ main: 'main',
56
+ header: 'banner',
57
+ nav: 'navigation',
58
+ section: 'region',
59
+ }[e.tagName.toLowerCase()],
60
+ name: (
61
+ (e.getAttribute('aria-labelledby') || '')
62
+ .split(/\s+/)
63
+ .map((id) => text(e.getRootNode().getElementById(id)))
64
+ .join(' ')
65
+ .trim() ||
66
+ e.getAttribute('aria-label') ||
67
+ ''
68
+ )
69
+ .replace(/\s+/g, ' ')
70
+ .trim(),
71
+ }
72
+ : null;
73
+ const roots = [document];
74
+ for (let i = 0; i < roots.length; i++)
75
+ for (const e of roots[i].querySelectorAll('*'))
76
+ if (e.shadowRoot) roots.push(e.shadowRoot);
77
+ const regions = roots
78
+ .flatMap((root) => [...root.querySelectorAll(regionSelector)])
79
+ .filter(visible)
80
+ .map(describeRegion);
81
+ const selector =
82
+ 'button,a[href],input:not([type="hidden"]),textarea,select,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="option"],[role="combobox"],[role="checkbox"],[role="radio"],[role="switch"],[tabindex],[contenteditable="true"],summary';
83
+ let elements = roots
84
+ .flatMap((root) => [...root.querySelectorAll(selector)])
85
+ .filter(visible);
86
+ // Some enterprise navigation bars have clickable divs with no ARIA roles.
87
+ const pointer = roots
88
+ .flatMap((root) => [...root.querySelectorAll('div,span,li')])
89
+ .filter(
90
+ (e) =>
91
+ visible(e) &&
92
+ getComputedStyle(e).cursor === 'pointer' &&
93
+ text(e).length > 0 &&
94
+ text(e).length < 45 &&
95
+ !e.closest(selector) &&
96
+ !e.querySelector(selector) &&
97
+ ![...e.children].some(
98
+ (c) => getComputedStyle(c).cursor === 'pointer',
99
+ ),
100
+ );
101
+ // Icon actions may have a label and pointer cursor without a
102
+ // tabindex. Keep labelled leaf icons, not decorative children
103
+ // of an already-discovered native button.
104
+ const icons = roots
105
+ .flatMap((root) => [...root.querySelectorAll('i[aria-label]')])
106
+ .filter(
107
+ (e) =>
108
+ visible(e) &&
109
+ getComputedStyle(e).cursor === 'pointer' &&
110
+ !e.closest(selector),
111
+ );
112
+ elements = [...new Set([...elements, ...pointer, ...icons])];
113
+ // A menuitem wrapping its same-named link is one action, not two Laya
114
+ // candidates. Keep the inner native control and retain distinct siblings.
115
+ elements = elements.filter(
116
+ (e) =>
117
+ !(
118
+ e.getAttribute('role') === 'menuitem' &&
119
+ [...e.querySelectorAll('a[href],button')].some(
120
+ (child) => visible(child) && text(child) === text(e),
121
+ )
122
+ ),
123
+ );
124
+ const modals = roots
125
+ .flatMap((root) => [
126
+ ...root.querySelectorAll(
127
+ 'dialog[open],[role="dialog"],[role="alertdialog"],[data-slot="dialog-content"],[data-slot="alert-dialog-content"],.ant-drawer-open .ant-drawer-content,.el-dialog,[data-laya-editor-root]',
128
+ ),
129
+ ])
130
+ .filter(visible);
131
+ const modal = modals.at(-1);
132
+ // Options can be portaled outside their owning dialog.
133
+ if (modal)
134
+ elements = elements.filter(
135
+ (e) =>
136
+ modal.contains(e) ||
137
+ e.closest(
138
+ '[role="listbox"],.ant-select-dropdown,.el-select-dropdown',
139
+ ),
140
+ );
141
+ return elements
142
+ .slice(0, 800)
143
+ .map((e, i) => {
144
+ const tag = e.tagName.toLowerCase(),
145
+ type = e.getAttribute('type') || '';
146
+ let role =
147
+ e.getAttribute('role') ||
148
+ {
149
+ button: 'button',
150
+ a: 'link',
151
+ textarea: 'textbox',
152
+ select: 'combobox',
153
+ summary: 'button',
154
+ }[tag] ||
155
+ (tag === 'input'
156
+ ? {
157
+ checkbox: 'checkbox',
158
+ radio: 'radio',
159
+ number: 'spinbutton',
160
+ password: 'password',
161
+ }[type] || 'textbox'
162
+ : 'button');
163
+ const labelled = (e.getAttribute('aria-labelledby') || '')
164
+ .split(/\s+/)
165
+ .map((id) => text(document.getElementById(id)))
166
+ .join(' ')
167
+ .trim();
168
+ const labels = e.labels ? [...e.labels].map(text).join(' ') : '';
169
+ const parentLabel = text(
170
+ e.closest('.ant-form-item,.el-form-item')?.querySelector('label'),
171
+ );
172
+ let sibLabel = '';
173
+ if (['input', 'textarea', 'select'].includes(tag)) {
174
+ let n = e.previousElementSibling;
175
+ while (n) {
176
+ if (/^label$/i.test(n.tagName)) {
177
+ sibLabel = text(n);
178
+ break;
179
+ }
180
+ n = n.previousElementSibling;
181
+ }
182
+ if (!sibLabel) {
183
+ n = e.parentElement?.previousElementSibling || null;
184
+ while (n) {
185
+ if (/^label$/i.test(n.tagName)) {
186
+ sibLabel = text(n);
187
+ break;
188
+ }
189
+ n = n.previousElementSibling;
190
+ }
191
+ }
192
+ }
193
+ const selectBox = e.closest(
194
+ '.ant-select,.tntd-rc-select,.el-select,[role="combobox"]',
195
+ );
196
+ const selectHint =
197
+ text(
198
+ selectBox?.querySelector(
199
+ '.ant-select-selection__placeholder,.ant-select-selection-placeholder,.tntd-rc-select-selection-placeholder,.el-input__inner',
200
+ ),
201
+ ) || text(selectBox);
202
+ const ownText = ['input', 'textarea'].includes(tag) ? '' : text(e);
203
+ // Icon-only native buttons inherit their labelled child icon.
204
+ // Keep the button as the target rather than a decorative SVG.
205
+ const iconLabel = ['button', 'link'].includes(role)
206
+ ? e
207
+ .querySelector('i[aria-label],svg[aria-label]')
208
+ ?.getAttribute('aria-label') || ''
209
+ : '';
210
+ const tooltip = e.getAttribute('data-laya-tooltip-label') || '';
211
+ const tooltipAction = tooltip.match(/不支持(.+?)(?:操作)?$/)?.[1];
212
+ const name = (
213
+ tooltipAction ||
214
+ tooltip ||
215
+ e.getAttribute('aria-label') ||
216
+ labelled ||
217
+ labels ||
218
+ parentLabel ||
219
+ sibLabel ||
220
+ e.getAttribute('placeholder') ||
221
+ e.getAttribute('title') ||
222
+ ownText ||
223
+ iconLabel ||
224
+ selectHint ||
225
+ e.getAttribute('name') ||
226
+ ''
227
+ )
228
+ .replace(/^\*\s*/, '')
229
+ .slice(0, 130);
230
+ const row = e.closest('tr,[role="row"],[role="treeitem"]'),
231
+ group = e.closest('fieldset,[role="group"],form');
232
+ const region = describeRegion(e.closest(regionSelector));
233
+ const regionAmbiguous =
234
+ !!region &&
235
+ regions.filter(
236
+ (r) => r.role === region.role && r.name === region.name,
237
+ ).length !== 1;
238
+ const rowKey = row?.getAttribute('data-row-key') || '';
239
+ // Fixed operation columns have rows containing only icons. Join their live
240
+ // data-row-key to the main table, rather than mistaking all icons for one row.
241
+ const peers = rowKey
242
+ ? [...document.querySelectorAll('tr[data-row-key]')].filter(
243
+ (r) => r.getAttribute('data-row-key') === rowKey,
244
+ )
245
+ : [];
246
+ const rowText = [
247
+ ...new Set([text(row), ...peers.map(text)].filter(Boolean)),
248
+ ]
249
+ .sort((a, b) => b.length - a.length)
250
+ .join(' | ');
251
+ const context = row
252
+ ? rowText.slice(0, 500)
253
+ : text(group?.querySelector('legend,h1,h2,h3')).slice(0, 70);
254
+ const ref = nonce + '-' + fi + '-' + i;
255
+ e.setAttribute(attr, ref);
256
+ return {
257
+ ref,
258
+ frame: fi,
259
+ tag,
260
+ role,
261
+ name,
262
+ tooltip,
263
+ rowKey,
264
+ placeholder: e.getAttribute('placeholder') || '',
265
+ context,
266
+ region,
267
+ regionAmbiguous,
268
+ expanded: e.hasAttribute('aria-expanded')
269
+ ? e.getAttribute('aria-expanded') === 'true'
270
+ : null,
271
+ inPanel: !!e.closest('[role="tabpanel"]'),
272
+ disabled:
273
+ e.matches(':disabled') ||
274
+ e.hasAttribute('disabled') ||
275
+ e.getAttribute('aria-disabled') === 'true' ||
276
+ !!e.closest(
277
+ '.ant-select-disabled,[aria-disabled="true"],.disabled,.is-disabled',
278
+ ) ||
279
+ (role === 'menuitem' &&
280
+ !!e.querySelector(
281
+ 'a[disabled],button[disabled],a.disabled,button.disabled',
282
+ )),
283
+ readonly: e.readOnly === true,
284
+ selected:
285
+ e.getAttribute('aria-selected') === 'true' ||
286
+ e.classList.contains('ant-menu-item-selected') ||
287
+ !!e.closest('.ant-menu-item-selected'),
288
+ checked:
289
+ e.checked === true || e.getAttribute('aria-checked') === 'true',
290
+ href: e.getAttribute('href') || '',
291
+ value:
292
+ type === 'password'
293
+ ? '[REDACTED]'
294
+ : ('value' in e ? String(e.value) : '').slice(0, 160),
295
+ };
296
+ })
297
+ .filter((x) => x.name || x.role === 'password');
298
+ },
299
+ { nonce, fi, attr: ATTR },
300
+ )
301
+ .catch(() => []);
302
+ controls.push(...items);
303
+ }
304
+ return { url: page.url(), controls, frames };
305
+ }
306
+ export function score(target, c) {
307
+ const t = norm(target),
308
+ n = norm(c.name),
309
+ p = norm(c.placeholder),
310
+ context = norm(c.context);
311
+ if (!t) return 0;
312
+ let s = n === t ? 120 : n.includes(t) ? 85 : t.includes(n) && n.length > 1 ? 65 : 0;
313
+ if (p && p.includes(t)) s = Math.max(s, 75);
314
+ if (context.includes(t)) s += 30;
315
+ const a = new Set([...t]);
316
+ s += ([...new Set([...n])].filter((x) => a.has(x)).length / Math.max(1, a.size)) * 12;
317
+ return s;
318
+ }
319
+ export async function discoverRowLabels(page, rowKey) {
320
+ let snap = await observe(page);
321
+ const icons = snap.controls.filter((c) => c.rowKey === rowKey && /^图标[::]/.test(c.name));
322
+ // Only hover real DOM controls, never click an unknown icon to discover it.
323
+ for (const icon of icons.slice(0, 12)) {
324
+ const loc = snap.frames[icon.frame].locator(`[${ATTR}="${icon.ref}"]`);
325
+ try {
326
+ await page.mouse.move(0, 0);
327
+ const tips = snap.frames[icon.frame].locator(
328
+ '[role="tooltip"]:visible,.ant-tooltip:visible,.el-tooltip__popper:visible',
329
+ );
330
+ await tips
331
+ .first()
332
+ .waitFor({ state: 'hidden', timeout: 900 })
333
+ .catch(() => {});
334
+ await loc.hover({ timeout: 1500 });
335
+ await tips
336
+ .first()
337
+ .waitFor({ state: 'visible', timeout: 650 })
338
+ .catch(() => {});
339
+ await page.waitForTimeout(350);
340
+ const labels = [
341
+ ...new Set((await tips.allTextContents()).map((s) => s.trim()).filter(Boolean)),
342
+ ];
343
+ if (labels.length === 1 && labels[0].length < 100)
344
+ await loc.evaluate(
345
+ (e, label) => e.setAttribute('data-laya-tooltip-label', label),
346
+ labels[0],
347
+ );
348
+ } catch {}
349
+ }
350
+ await page.mouse.move(0, 0);
351
+ return observe(page);
352
+ }
353
+ export async function target(
354
+ page,
355
+ laya,
356
+ intent,
357
+ {
358
+ kind = 'click',
359
+ value,
360
+ meta = {},
361
+ rowKey,
362
+ allowDisabled = false,
363
+ minProbability = 0.68,
364
+ minMargin = 0.18,
365
+ } = {},
366
+ ) {
367
+ let snap = await observe(page);
368
+ // Global toolbar icons need the same live tooltip discovery as row actions.
369
+ // Do it only when the requested action has no named match in its scope.
370
+ const scoped = snap.controls.filter((c) => c.rowKey === (rowKey || ''));
371
+ if (
372
+ ['click', 'hover'].includes(kind) &&
373
+ !scoped.some((c) => score(intent, c) >= 65) &&
374
+ scoped.some((c) => /^图标[::]/.test(c.name))
375
+ )
376
+ snap = await discoverRowLabels(page, rowKey || '');
377
+ // Bounded observation retries accommodate late asynchronous rendering; no action is retried.
378
+ for (let i = 0; i < 8 && !snap.controls.some((c) => score(intent, c) >= 65); i++) {
379
+ await page.waitForTimeout(250);
380
+ snap = await observe(page);
381
+ }
382
+ let candidates = snap.controls.filter(
383
+ (c) => c.role !== 'password' && (allowDisabled || !c.disabled),
384
+ );
385
+ if (rowKey) candidates = candidates.filter((c) => c.rowKey === rowKey);
386
+ if (['fill', 'clear', 'value', 'empty'].includes(kind))
387
+ candidates = candidates.filter(
388
+ (c) => ['textbox', 'spinbutton'].includes(c.role) && !c.readonly,
389
+ );
390
+ if (kind === 'select')
391
+ candidates = candidates.filter((c) => c.role === 'combobox' || c.tag === 'select');
392
+ if (['check', 'uncheck', 'checked'].includes(kind))
393
+ candidates = candidates.filter((c) => ['checkbox', 'radio', 'switch'].includes(c.role));
394
+ if (kind === 'option')
395
+ candidates = candidates.filter(
396
+ (c) => c.role === 'option' || c.role === 'menuitem' || c.role === 'button',
397
+ );
398
+ const ranked = candidates
399
+ .map((c) => ({ ...c, rank: score(intent, c) }))
400
+ .sort((a, b) => b.rank - a.rank);
401
+ const unique = [];
402
+ for (const c of ranked) {
403
+ // A nested accessible input within its combobox is not a second target.
404
+ if (
405
+ unique.some(
406
+ (x) =>
407
+ x.name === c.name &&
408
+ x.context === c.context &&
409
+ x.role === c.role &&
410
+ x.frame === c.frame &&
411
+ x.href === c.href,
412
+ )
413
+ )
414
+ continue;
415
+ unique.push(c);
416
+ }
417
+ if (!unique.length)
418
+ throw new Halt('页面控件不足', `当前页面没有可用于${kind}的控件:${intent}`);
419
+ const shortlist = unique.slice(0, 5);
420
+ if (
421
+ ranked.length >= 2 &&
422
+ ranked[0].rank >= 100 &&
423
+ ranked[1].rank === ranked[0].rank &&
424
+ ranked[0].name === ranked[1].name &&
425
+ ranked[0].context !== ranked[1].context &&
426
+ !norm(intent).includes(norm(ranked[0].context))
427
+ )
428
+ throw new Halt('目标不唯一', `多个区域存在“${intent}”,请在步骤写明记录名称或区域。`);
429
+ const en = /[a-z]/i.test(intent) && !/[\u4e00-\u9fff]/.test(intent);
430
+ const prefix = en
431
+ ? {
432
+ fill: 'Fill ',
433
+ clear: 'Clear ',
434
+ select: 'Select ',
435
+ option: 'Choose ',
436
+ check: 'Check ',
437
+ uncheck: 'Uncheck ',
438
+ hover: 'Hover over ',
439
+ click: 'Click ',
440
+ }[kind] || 'Find '
441
+ : {
442
+ fill: '填写',
443
+ clear: '清空',
444
+ select: '选择',
445
+ option: '选择',
446
+ check: '勾选',
447
+ uncheck: '取消勾选',
448
+ hover: '悬停在',
449
+ click: '点击',
450
+ }[kind] || '查看';
451
+ const keyed = shortlist.map((c, i) => ({
452
+ key:
453
+ c.name.slice(0, 36) +
454
+ (shortlist.filter((x) => x.name === c.name).length > 1
455
+ ? ' [' + (c.context.slice(0, 16) || c.role) + '] #' + i
456
+ : ''),
457
+ control: c,
458
+ }));
459
+ const criteria = Object.fromEntries(
460
+ keyed.map(({ key, control: c }) => [key, prefix + c.name.slice(0, 38)]),
461
+ );
462
+ const stopKey = en ? 'Stop' : '停止';
463
+ criteria[stopKey] = en ? 'Do not perform any action' : '不执行';
464
+ const decision = await laya.choose(prefix + intent, criteria, {
465
+ ...meta,
466
+ phase: 'target',
467
+ url: snap.url,
468
+ candidate_count: snap.controls.length,
469
+ candidates: shortlist.map(({ ref, ...c }) => c),
470
+ });
471
+ if (decision.choice === stopKey)
472
+ throw new Halt('Laya无法判断', `Laya未找到匹配控件:${intent}`);
473
+ const c = keyed.find((x) => x.key === decision.choice)?.control;
474
+ if (!c) throw new Halt('模型结果无效', '模型返回无法映射到当前DOM的目标');
475
+ if (
476
+ (decision.probabilities?.[decision.choice] || 0) < minProbability ||
477
+ decision.margin < minMargin
478
+ )
479
+ throw new Halt('Laya选择不确定', `目标“${intent}”的候选评分或差距不足,停止本步。`);
480
+ const locator = snap.frames[c.frame].locator(`[${ATTR}="${c.ref}"]`);
481
+ if ((await locator.count()) !== 1 || !(await locator.isVisible()))
482
+ throw new Halt('DOM已变化', '决定完成后DOM已变化,当前步骤停止,避免误点。');
483
+ // Distinct identical controls require an explicit row/region, not a guessed index.
484
+ const identical = ranked.filter(
485
+ (x) => x.name === c.name && x.role === c.role && x.context === c.context,
486
+ );
487
+ if (identical.length > 1) {
488
+ let nested = true;
489
+ for (const other of identical) {
490
+ if (other.ref === c.ref) continue;
491
+ const rel = await snap.frames[c.frame].evaluate(
492
+ ({ a, b, attr }) => {
493
+ const x = document.querySelector(`[${attr}="${a}"]`),
494
+ y = document.querySelector(`[${attr}="${b}"]`);
495
+ return x && y && (x.contains(y) || y.contains(x));
496
+ },
497
+ { a: c.ref, b: other.ref, attr: ATTR },
498
+ );
499
+ if (!rel) nested = false;
500
+ }
501
+ if (!nested)
502
+ throw new Halt('目标不唯一', `存在多个同名同上下文控件“${c.name}”,需要补充区域。`);
503
+ }
504
+ return { locator, control: c, decision };
505
+ }
506
+ export async function settle(page, ms = 250) {
507
+ await page.waitForLoadState('domcontentloaded', { timeout: 5000 }).catch(() => {});
508
+ await page.waitForTimeout(ms);
509
+ // Avoid networkidle: polling/WebSocket applications may never become idle.
510
+ await page
511
+ .locator('[aria-busy="true"]:visible,.ant-spin-spinning:visible,.el-loading-mask:visible')
512
+ .first()
513
+ .waitFor({ state: 'hidden', timeout: 5000 })
514
+ .catch(() => {});
515
+ }
516
+ export async function assertionTarget(page, name, kind, { rowKey } = {}) {
517
+ const snap = await observe(page);
518
+ let items = snap.controls.filter((c) => c.role !== 'password');
519
+ if (rowKey) items = items.filter((c) => c.rowKey === rowKey);
520
+ if (['empty', 'value'].includes(kind))
521
+ items = items.filter((c) => ['textbox', 'spinbutton', 'combobox'].includes(c.role));
522
+ if (kind === 'checked')
523
+ items = items.filter((c) => ['checkbox', 'radio', 'switch'].includes(c.role));
524
+ if (kind === 'selected') items = items.filter((c) => c.role === 'tab');
525
+ const exact = items.filter((c) => norm(c.name) === norm(name));
526
+ const matches = exact.length
527
+ ? exact
528
+ : items.filter(
529
+ (c) => norm(c.placeholder) === norm(name) || norm(c.name) === norm('请输入' + name),
530
+ );
531
+ if (matches.length !== 1)
532
+ throw new Halt(
533
+ '断言目标不唯一',
534
+ `预期中的“${name}”对应${matches.length}个明确控件,无法证明断言`,
535
+ );
536
+ const control = matches[0],
537
+ locator = snap.frames[control.frame].locator(`[${ATTR}="${control.ref}"]`);
538
+ return { control, locator };
539
+ }