dsh-native-uia 0.4.0 → 0.6.1

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.
@@ -1,4 +1,4 @@
1
- import { classify, classifyBatch } from '../../guard.js';
1
+ import { classify, classifyBatch, classifyKeys } from '../../guard.js';
2
2
  import { noteHint } from '../../notes.js';
3
3
  import { writeFile } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
@@ -19,12 +19,12 @@ export function registerAct(d) {
19
19
 
20
20
  d.disposers.push(register(defineTool({
21
21
  name: 'computer_act',
22
- description: 'Perform one UI Automation action on one element by its ref from a current snapshot: invoke | set_value | toggle | select | expand | collapse | scroll_up | scroll_down | focus | text_append. Delivered in the background: the cursor does not move and focus is not stolen.',
22
+ description: 'Perform one UI Automation action on one element by its ref from a current snapshot: invoke | set_value | toggle | select | deselect | add_to_selection | expand | collapse | scroll_up | scroll_down | scroll_to | set_range | focus | text_append. Delivered in the background: the cursor does not move and focus is not stolen. deselect/add_to_selection extend a multi-select list; scroll_to uses ScrollItem.ScrollIntoView (the provider moves the exact container); set_range takes a number in `value` and clamps to the control Min/Max.',
23
23
  parameters: {
24
24
  windowId: { ...STR, required: true },
25
25
  ref: { ...STR, required: true, description: 'Element ref from the newest snapshot of this window' },
26
- action: { type: 'string', enum: ['invoke', 'set_value', 'toggle', 'select', 'expand', 'collapse', 'scroll_up', 'scroll_down', 'focus', 'text_append'], required: true },
27
- value: { ...STR, description: 'Text for set_value / text_append' },
26
+ action: { type: 'string', enum: ['invoke', 'set_value', 'toggle', 'select', 'deselect', 'add_to_selection', 'expand', 'collapse', 'scroll_up', 'scroll_down', 'scroll_to', 'set_range', 'focus', 'text_append'], required: true },
27
+ value: { ...STR, description: 'Text for set_value / text_append; a number for set_range (e.g. "40" or "0.5")' },
28
28
  revision: { ...INT, description: 'The revision the ref came from; omit to use the newest snapshot' },
29
29
  verify: { type: 'json', description: 'Optional {type, expect, timeoutMs} check run locally right after the action' },
30
30
  scrollIntoView: { ...BOOL, description: 'when the element is offscreen, scroll it into view first (default true); false acts without moving the viewport' },
@@ -104,10 +104,14 @@ export function registerAct(d) {
104
104
  text_append: ['Value'],
105
105
  toggle: ['Toggle'],
106
106
  select: ['SelectionItem'],
107
+ deselect: ['SelectionItem'],
108
+ add_to_selection: ['SelectionItem'],
107
109
  expand: ['ExpandCollapse'],
108
110
  collapse: ['ExpandCollapse'],
109
111
  scroll_up: ['Scroll'],
110
112
  scroll_down: ['Scroll'],
113
+ scroll_to: ['ScrollItem'],
114
+ set_range: ['RangeValue'],
111
115
  };
112
116
  const have = Array.isArray(described?.availablePatterns) ? described.availablePatterns : [];
113
117
  const need = NEEDED[String(args.action)] ?? [];
@@ -136,6 +140,104 @@ export function registerAct(d) {
136
140
  })));
137
141
 
138
142
 
143
+ // Steps the batch can only run one at a time (lazy): they act on pixels/keys, not on a ref of a
144
+ // resolvable element, so the classic "resolve every target, then commit against one revision"
145
+ // shape cannot express them. Every one still goes through the same policy table and the same
146
+ // per-step stop rule as a UIA step.
147
+ const POINTER_STEPS = new Set(['click', 'double_click', 'right_click', 'hover', 'type', 'key', 'scroll', 'drag', 'wait']);
148
+ const modsOf = (value) => {
149
+ if (value === undefined || value === null || value === '') return [];
150
+ return (Array.isArray(value) ? value : String(value).split('+')).map((m) => String(m).trim().toLowerCase()).filter(Boolean);
151
+ };
152
+ // One target resolver for pointer steps: a ref (centre from its live rect) or explicit x,y.
153
+ // Returns {error} instead of throwing so the step result can say what was wrong.
154
+ const pointOfStep = async (step, fallbackWindow) => {
155
+ if (step.ref !== undefined && step.ref !== null && String(step.ref) !== '') {
156
+ let d = null;
157
+ try { d = await worker.call('describe', { ref: String(step.ref) }); } catch (error) {
158
+ return { error: `ref ${step.ref} 解析失败(${error?.code ?? 'worker_error'}):${error?.message ?? error}` };
159
+ }
160
+ const r = d?.rect;
161
+ if (!r || !(r.w > 0) || !(r.h > 0)) return { error: `ref ${step.ref} 没有可点矩形(元素不可见或没有布局框)` };
162
+ return { x: Math.round(r.x + r.w / 2), y: Math.round(r.y + r.h / 2), windowId: String(d?.windowId ?? fallbackWindow ?? ''), descriptor: d };
163
+ }
164
+ if (typeof step.x === 'number' && typeof step.y === 'number') {
165
+ const wid = String(step.windowId ?? fallbackWindow ?? '');
166
+ let under = null;
167
+ try {
168
+ const t = await worker.call('pointer_target', { x: step.x, y: step.y });
169
+ under = t?.under ?? t;
170
+ } catch { under = null; }
171
+ return {
172
+ x: step.x, y: step.y, windowId: wid,
173
+ descriptor: { title: under?.title, className: under?.class ?? under?.hitClass, name: under?.app },
174
+ };
175
+ }
176
+ return { error: '这一步需要 ref(推荐)或 x,y' };
177
+ };
178
+ const runPointerStep = async (step, fallbackWindow) => {
179
+ const action = String(step.action ?? '').toLowerCase();
180
+ const started = Date.now();
181
+ const done = (detail, performed = 1) => ({ status: 'passed', ms: Date.now() - started, detail, performed });
182
+ if (action === 'wait') {
183
+ const cond = step.condition ?? step.verify ?? null;
184
+ if (cond === null) return { status: 'failed', detail: 'wait 步需要 condition(与 computer_wait 的 condition 同形)' };
185
+ const r = await worker.call('wait', { windowId: step.windowId ?? '', condition: cond, timeoutMs: step.timeoutMs ?? 10000 }, { timeoutMs: 98000 });
186
+ return {
187
+ status: r.matched === true ? 'passed' : 'failed',
188
+ ms: Date.now() - started,
189
+ detail: r.matched === true ? `条件命中${r.observed !== undefined ? ` observed=${JSON.stringify(r.observed)}` : ''}` : `等待超时(${r.error ?? 'no match'})`,
190
+ performed: 0,
191
+ };
192
+ }
193
+ if (action === 'key') {
194
+ const combo = String(step.keys ?? '').trim().toLowerCase();
195
+ if (combo === '') return { status: 'failed', detail: 'key 步需要 keys(如 "ctrl+s")' };
196
+ // Same policy as computer_key: the combo text goes through guard's keyboard table.
197
+ const verdict = classifyKeys(combo);
198
+ if (verdict.verdict === 'deny') return { status: 'blocked', detail: verdict.refusal, performed: 0 };
199
+ const r = await worker.call('key', { keys: combo, repeat: step.repeat, holdMs: step.holdMs });
200
+ if (/(?:^|\+)ctrl\+c(?:\+|$)/.test(combo)) store.ctrlCAt = Date.now();
201
+ return done(`按键 ${combo}${r?.repeat > 1 ? ` ×${r.repeat}` : ''}`, 1);
202
+ }
203
+ if (action === 'type') {
204
+ const text0 = String(step.text ?? step.value ?? '');
205
+ if (text0 === '') return { status: 'failed', detail: 'type 步需要 text' };
206
+ const via = step.via === 'clipboard' ? 'clipboard' : 'keyboard';
207
+ await worker.call('type_text', { text: text0, windowId: step.windowId ? String(step.windowId) : '', via });
208
+ return done(`输入 ${text0.length} 字(${via}${via === 'clipboard' ? ',已覆盖剪贴板' : ''})`, 1);
209
+ }
210
+ const pt = await pointOfStep(step, fallbackWindow);
211
+ if (pt.error) return { status: 'failed', detail: pt.error, performed: 0 };
212
+ if (pt.windowId === '') return { status: 'failed', detail: '这一步没有窗口可归属:给 ref 或 windowId', performed: 0 };
213
+ // The same destructive-target table the pointer tools use: a coordinate or a ref both resolve
214
+ // to what is actually at that point, and an entry the policy refuses never gets a press.
215
+ const verdict = classify({ action: 'invoke', descriptor: pt.descriptor ?? {} });
216
+ if (verdict.verdict === 'deny') return { status: 'blocked', detail: verdict.refusal, performed: 0 };
217
+ const expect = { windowId: pt.windowId };
218
+ if (action === 'click' || action === 'double_click' || action === 'right_click') {
219
+ const button = action === 'right_click' ? 'right' : (step.button ?? 'left');
220
+ const double = action === 'double_click' || step.double === true;
221
+ await worker.call('pointer_click', { x: pt.x, y: pt.y, button, double, triple: step.triple === true, mods: modsOf(step.modifiers), durationMs: step.durationMs, expect });
222
+ return done(`点击 ${pt.x},${pt.y} ${button}${double ? ' 双击' : ''}`, 1);
223
+ }
224
+ if (action === 'hover') {
225
+ await worker.call('pointer_mouse', { action: 'move', x: pt.x, y: pt.y, durationMs: step.durationMs, expect });
226
+ return done(`悬停 ${pt.x},${pt.y}`, 1);
227
+ }
228
+ if (action === 'scroll') {
229
+ const r = await worker.call('pointer_scroll', { x: pt.x, y: pt.y, direction: step.direction, clicks: step.clicks, mods: modsOf(step.modifiers), expect });
230
+ return done(`滚动 ${step.direction ?? 'down'} ${r?.clicks ?? step.clicks ?? 3} 格 @${pt.x},${pt.y}`, 1);
231
+ }
232
+ if (action === 'drag') {
233
+ const end = await pointOfStep({ ref: step.toRef, x: step.toX, y: step.toY }, fallbackWindow);
234
+ if (end.error) return { status: 'failed', detail: `终点:${end.error}`, performed: 0 };
235
+ await worker.call('pointer_drag', { from: { x: pt.x, y: pt.y }, to: { x: end.x, y: end.y }, button: step.button, durationMs: step.durationMs, expect });
236
+ return done(`拖拽 ${pt.x},${pt.y} → ${end.x},${end.y}`, 1);
237
+ }
238
+ return { status: 'failed', detail: `未知的指针步骤 ${action}`, performed: 0 };
239
+ };
240
+
139
241
  // Lazy mode: resolve → policy-check → deliver each step on its own, so step N+1 may target UI that
140
242
  // step N just created (menu items, dialogs, a row that only exists after a search). The classic
141
243
  // batch must resolve every target up front and therefore cannot express that flow at all.
@@ -155,6 +257,29 @@ export function registerAct(d) {
155
257
  if (store.killed === true) { stopReason = '用户已终止本轮(Esc/面板)'; stopIndex = i; break; }
156
258
  const one = [steps[i]];
157
259
  const label = `第 ${i + 1} 步 ${steps[i]?.action ?? '?'}`;
260
+ // A pointer/keyboard step runs on its own and skips the resolve/commit pair entirely: it has no
261
+ // element to resolve against one revision, and its target may be the UI the previous step just
262
+ // created. Same stop rule, same policy table, one line in the panel.
263
+ if (POINTER_STEPS.has(String(steps[i]?.action ?? '').toLowerCase())) {
264
+ let pr;
265
+ try {
266
+ pr = await runPointerStep(steps[i], args.windowId);
267
+ } catch (error) {
268
+ pr = { status: 'failed', performed: 0, detail: `执行失败(${error?.code ?? 'worker_error'}):${error?.message ?? error}` };
269
+ }
270
+ descriptors.push(null);
271
+ results.push({ index: i, action: String(steps[i].action), status: pr.status, ms: pr.ms, detail: pr.detail, performed: pr.performed === 1 });
272
+ performed += pr.performed ?? 0;
273
+ store.step({ label, status: pr.status, ms: pr.ms, detail: pr.detail });
274
+ if (pr.status !== 'passed') {
275
+ stopReason = pr.status === 'blocked'
276
+ ? `策略拒绝:${pr.detail}`
277
+ : `第 ${i + 1} 步未通过(${pr.status}):${pr.detail}`;
278
+ stopIndex = i;
279
+ break;
280
+ }
281
+ continue;
282
+ }
158
283
  let prep = null;
159
284
  try {
160
285
  prep = await worker.call('prepare_batch', { steps: one, windowId: args.windowId }, { timeoutMs: 60000 });
@@ -202,8 +327,12 @@ export function registerAct(d) {
202
327
  }
203
328
  store.actionDone(performed);
204
329
  const allPassed = stopIndex === -1 && results.length === steps.length && results.every((r) => r.status === 'passed');
205
- let recipeNote = '';
206
- if (allPassed && args.saveRecipe !== false) {
330
+ // A mixed batch is not saved as a recipe: its pointer steps target coordinates or whatever is at
331
+ // a point, and a recipe replayed on another layout would click the wrong place. The UIA path
332
+ // keeps saving because its by-descriptors survive layout drift.
333
+ const mixed = steps.some((s) => POINTER_STEPS.has(String(s?.action ?? '').toLowerCase()));
334
+ let recipeNote = mixed && args.saveRecipe !== false ? '\n(含指针步骤的批次不存配方:坐标会随布局漂移,回放会点错位置)' : '';
335
+ if (allPassed && args.saveRecipe !== false && !mixed) {
207
336
  const name = await saveRecipe(recipeDir, {
208
337
  goal: args.goal,
209
338
  window: descriptors[0]?.ownerWindow ?? windowOf(store, args.windowId),
@@ -226,11 +355,11 @@ export function registerAct(d) {
226
355
 
227
356
  d.disposers.push(register(defineTool({
228
357
  name: 'computer_run',
229
- description: 'Execute a planned batch of desktop actions in one call. All targets must already exist before the batch starts; split a menu-opening action from actions on its newly created items — or set lazy:true, which resolves and delivers one step at a time so a later step can target what an earlier step just created. Use refs or by descriptors with name, nameExact (default true), controlType, className, automationId, nth or nearPoint. For changing labels, use a stable substring with nameExact:false. Every step is policy-checked; performedCount counts delivered actions even if their verification fails.',
358
+ description: 'Execute a planned batch of desktop actions in one call. All targets must already exist before the batch starts; split a menu-opening action from actions on its newly created items — or set lazy:true, which resolves and delivers one step at a time so a later step can target what an earlier step just created. UIA steps use refs or by descriptors with name, nameExact (default true), controlType, className, automationId, nth or nearPoint. In lazy mode the batch also accepts pointer steps: click / double_click / right_click / hover (target by ref or x,y), type (text, via), key (keys, repeat), scroll (direction, clicks), drag (ref or fromX/fromY → toRef or toX/toY), wait (condition) — so one call can click a field, type, press enter, and verify, stopping at the first failure. Every step is policy-checked; performedCount counts delivered actions even if their verification fails. A batch containing pointer steps is not saved as a recipe (coordinates drift).',
230
359
  parameters: {
231
360
  windowId: { ...STR, required: true },
232
361
  goal: { ...STR, required: true, description: 'One sentence describing the outcome this batch produces; stored with the recipe' },
233
- steps: { ...JSON_ARR, required: true, description: '[{ref|by, action, value?, verify?, timeoutMs?}]' },
362
+ steps: { ...JSON_ARR, required: true, description: '[{ref|by, action, value?, verify?, timeoutMs?}] — with lazy:true also [{action:"click"|"double_click"|"right_click"|"hover", ref|x,y, ...}]、[{action:"type", text, via?}]、[{action:"key", keys, repeat?, holdMs?}]、[{action:"scroll", ref|x,y, direction?, clicks?}]、[{action:"drag", ref|fromX,fromY, toRef|toX,toY}]、[{action:"wait", condition, timeoutMs?}]' },
234
363
  lazy: { ...BOOL, description: 'resolve→check→deliver each step separately (default false). Costs one round trip per step; use it when step N+1 targets UI that step N creates (menu items, dialogs)' },
235
364
  saveRecipe: { ...BOOL, description: 'Save a replayable recipe when every step passes (default true)' },
236
365
  },
@@ -243,6 +372,15 @@ export function registerAct(d) {
243
372
  }
244
373
  const steps = Array.isArray(args.steps) ? args.steps : [];
245
374
  if (steps.length === 0) return 'computer_run 需要非空的 steps 数组';
375
+ const mixed = [...new Set(steps.filter((s) => POINTER_STEPS.has(String(s?.action ?? '').toLowerCase())).map((s) => String(s.action)))];
376
+ if (mixed.length > 0 && args.lazy !== true) {
377
+ // Not a policy refusal: the classic batch resolves every target BEFORE it performs anything
378
+ // and then commits against ONE revision. A pointer/keyboard step has no element to resolve
379
+ // and may target what an earlier step creates, so it can only run in the per-step path.
380
+ return `这一批里有指针/键盘步骤(${mixed.join('、')}),非 lazy 批次做不到:它要求所有目标在执行前就已存在,并把每一步对同一个 revision 校验,而指针步骤没有可解析的元素。\n`
381
+ + '两种改法:加 `lazy: true` 用逐段模式重跑这一批(每步单独解析、执行、校验,后一步可以用前一步刚做出来的界面);'
382
+ + '或者把这些步骤拆出去交给 computer_click / computer_type / computer_key / computer_wait,UIA 步骤留在这一批。';
383
+ }
246
384
  if (args.lazy === true) return runLazy(args, steps, exec);
247
385
  const prepared = await worker.call('prepare_batch', { steps, windowId: args.windowId }, { timeoutMs: 188000 });
248
386
  const prepError = preparationFailure(prepared, steps.length);
@@ -458,8 +596,8 @@ export function registerAct(d) {
458
596
  const prepared = await worker.call('prepare_batch', { steps, windowId, rebindBy: true });
459
597
  const prepError = preparationFailure(prepared, steps.length);
460
598
  if (prepError) {
461
- // A failed replay used to return invisibly to the control page: without a store.step the
462
- // console showed nothing about the replay the model just attempted.
599
+ // A failed replay must leave a step in the store: without one the panel showed nothing
600
+ // about the replay the model just attempted.
463
601
  store.step({ label: `回放 ${args.name}`, kind: 'batch', status: 'failed', detail: prepError });
464
602
  return prepError;
465
603
  }
@@ -469,7 +607,7 @@ export function registerAct(d) {
469
607
  let committed;
470
608
  try {
471
609
  // mode rides on every act/commit_batch (the worker's declared contract): without it a
472
- // replay after a control-page kill always ran background and UIA-hostile elements lost
610
+ // replay after an Esc stop always ran background and UIA-hostile elements lost
473
611
  // their pixel fallback.
474
612
  committed = await worker.call('commit_batch', { revision: prepared.revision, steps, windowId, mode: store.pointerMode, indicatorPid: activity?.indicator?.proc?.pid ?? 0 });
475
613
  } catch (error) {
@@ -181,8 +181,8 @@ export function registerLifecycle(d) {
181
181
  store.setTarget(null);
182
182
  // Three endings get three words: only outcome=done may say 已完成 — a blocked/failed run
183
183
  // rendered as "任务完成" taught the panel (and the model's own next turn) a lie. The panel
184
- // already colours both 'blocked' and 'failed' steps as bad (control.html isBad), so the
185
- // status values below need no panel change.
184
+ // already draws both 'blocked' and 'failed' steps as bad, so the status values below need no
185
+ // panel change.
186
186
  const tail = reason ? `(原因:${reason})` : summary ? `(${summary})` : '';
187
187
  const verdicts = {
188
188
  done: { status: 'passed', label: '任务完成,收起指示层', text: `已完成并收起御屏指示层${summary ? `(${summary})` : ''}。` },
@@ -43,14 +43,16 @@ export function registerObserve(d) {
43
43
 
44
44
  d.disposers.push(register(defineTool({
45
45
  name: 'computer_snapshot',
46
- description: 'Read a window UI Automation tree and return its interactive elements with short refs (e1, e2, ...). Refs belong to one revision of one window: a newer snapshot invalidates the older refs. This is the primary observation channel and needs no vision model. Rhythm on large windows: take a shallow pass first (depth=4-5) to see the structural skeleton, locate the target container, then either computer_find_text into it or dig deeper with a higher depth/maxNodes — a deep pass over a big tree burns both latency and tokens.',
46
+ description: 'Read a window UI Automation tree and return its elements with short refs (e1, e2, ...) plus each one\'s state (toggle/selected/expanded/range/scroll). Refs belong to one revision of one window: a newer whole-window snapshot invalidates older refs (a root=<ref> subtree pass does not). This is the primary observation channel and needs no vision model. Rhythm on large windows: take a shallow pass first (depth=4-5) to see the structural skeleton, then either computer_find_text with within=<container ref> or computer_snapshot root=<container ref> to dig into exactly that container — a deep pass over a whole big tree burns both latency and tokens. If the tree stops at a Pane with nothing inside, try view="raw": ControlView hides plumbing elements that raw exposes.',
47
47
  parameters: {
48
48
  windowId: { ...STR, required: true, description: 'windowId from computer_windows' },
49
49
  controlType: { ...STR, description: 'Keep only these control types, e.g. "Button,Edit,MenuItem"' },
50
50
  nameContains: { ...STR, description: 'Keep only elements whose name contains this text' },
51
51
  includeOffscreen: { ...BOOL, description: 'Include offscreen elements (default false)' },
52
- depth: { ...INT, description: 'Max tree depth to walk. Omit = worker default 30 (near-full depth, not infinite). Recommended rhythm: depth=4-5 for a skeleton pass on a large window, then find_text into the located container or raise depth/maxNodes to dig into it.' },
52
+ depth: { ...INT, description: 'Max tree depth to walk. Omit = worker default 30 (near-full depth, not infinite). Recommended rhythm: depth=4-5 for a skeleton pass on a large window, then root=<ref> or find_text within=<ref> to dig into the located container.' },
53
53
  maxNodes: { ...INT, description: 'Node budget for one snapshot (default 200). Raise it only when a truncated tree actually hid the control you need.' },
54
+ view: { type: 'string', enum: ['control', 'raw', 'content'], description: 'Which UIA view to walk. control (default) = the curated tree providers publish for assistive tech; raw = every element including the plumbing panes ControlView hides (often 3-10x more nodes, walker-paced, so keep depth/maxNodes tight); content = content elements only.' },
55
+ root: { ...STR, description: 'Optional ref to walk only that element\'s subtree. Refs minted by the pass join the current revision, so a skeleton snapshot stays usable. This is the cheap way to open one container: root=<container ref> instead of raising depth over the whole window.' },
54
56
  compact: { ...BOOL, description: 'Tighter rendering: shorter names and values. Use on large trees you are only scanning.' },
55
57
  },
56
58
  output: { schema: STR, render: (_args, value) => text(value) },
@@ -67,6 +69,8 @@ export function registerObserve(d) {
67
69
  // Pass-through: JSON.stringify drops the key when depth is omitted, so the worker keeps
68
70
  // its own default (maxDepth=30) — an omitted argument changes nothing downstream.
69
71
  maxDepth: args.depth,
72
+ view: args.view,
73
+ root: args.root,
70
74
  filter: {
71
75
  controlType: args.controlType,
72
76
  nameContains: args.nameContains,
@@ -76,7 +80,14 @@ export function registerObserve(d) {
76
80
  const nodes = result.nodes ?? [];
77
81
  store.setTree(nodes, { windowId: args.windowId, revision: result.revision });
78
82
  store.setTarget(windowOf(store, args.windowId) ?? { windowId: args.windowId });
79
- const head = `窗口 ${args.windowId} 第 ${result.revision} 版:${nodes.length} 个元素${result.truncated === true ? '(已截断——收紧过滤条件、用 find_text 定位、提高 maxNodes,或先浅 depth=4-5 看骨架再局部深挖)' : ''}`;
83
+ // Say which tree this actually is. A raw-view pass and a subtree pass read completely
84
+ // differently from a full control-view snapshot, and a model that does not know which one it
85
+ // holds mis-reads "only 8 elements" as "this window has 8 elements".
86
+ const scopeNote = [
87
+ result.subtree === true ? `子树 root=${result.rootRef ?? args.root}` : '',
88
+ result.view && result.view !== 'control' ? `视图=${result.view}` : '',
89
+ ].filter(Boolean).join(',');
90
+ const head = `窗口 ${args.windowId} 第 ${result.revision} 版:${nodes.length} 个元素${scopeNote ? `(${scopeNote})` : ''}${result.truncated === true ? '(已截断——收紧过滤条件、用 find_text 的 within 定位、用 root 深挖子容器、提高 maxNodes/深 depth,或先浅 depth=4-5 看骨架)' : ''}`;
80
91
  // 位置元数据(前台/焦点/采集耗时):动作后下一次观察的焦点变化即零成本「动作生效证据」,
81
92
  // 焦点不在目标窗时附一句修正指引。全部为 advisory 字段,worker 探测失败时不渲染。
82
93
  // 底部这一行是提示注入防线:屏幕上的任何文本都只是被观察的数据(聊天、网页、文档都可能
@@ -88,11 +99,12 @@ export function registerObserve(d) {
88
99
 
89
100
  d.disposers.push(register(defineTool({
90
101
  name: 'computer_find_text',
91
- description: 'Find elements by visible text in one window WITHOUT pulling the whole tree: returns each match with its clickable screen center and a `by` descriptor. Use it to locate one control in a big window (a full snapshot would be huge), to get coordinates for computer_click, or to build computer_run steps whose `by` survives layout drift. This is the named command the click guidance refers to ("find_text center"). Cost note: it enumerates the window\'s whole element tree (about 1-3 ms per element), so on a window with thousands of elements prefer a specific text fragment; a budget/max overrun returns the collected hits marked truncated with the total match count.',
102
+ description: 'Find elements by visible text in one window (or inside one container) WITHOUT pulling the whole tree: returns each match with its clickable screen center and a `by` descriptor. Use it to locate one control in a big window (a full snapshot would be huge), to get coordinates for computer_click, or to build computer_run steps whose `by` survives layout drift. This is the named command the click guidance refers to ("find_text center"). Pass within=<container ref> to search only that subtree — that is what turns a shallow skeleton pass into a cheap drill-down. Cost note: it enumerates the whole element tree of the scope (about 1-3 ms per element), so on a window with thousands of elements prefer a specific text fragment or a within scope; a budget/max overrun returns the collected hits marked truncated with the total match count.',
92
103
  parameters: {
93
104
  windowId: { ...STR, required: true, description: 'windowId from computer_windows' },
94
105
  text: { ...STR, required: true, description: 'text to look for in element names/values' },
95
106
  exact: { ...BOOL, description: 'exact match instead of substring (default false)' },
107
+ within: { ...STR, description: 'Optional ref: search only that element\'s subtree (the container a skeleton snapshot located). Cheaper and more precise than scanning the whole window.' },
96
108
  max: { ...INT, description: 'max matches to return (default 60)' },
97
109
  },
98
110
  output: { schema: STR, render: (_args, value) => text(value) },
@@ -105,14 +117,18 @@ export function registerObserve(d) {
105
117
  windowId: args.windowId,
106
118
  text: text0,
107
119
  exact: args.exact === true,
120
+ within: args.within,
108
121
  max: args.max,
109
122
  });
110
123
  const matches = result.matches ?? [];
124
+ // The scope belongs in every reply, including the zero-hit one: "扫描 4 个元素,没有命中" reads
125
+ // as "the text does not exist" unless the line also says the search only covered one container.
126
+ const scopeText = result.within ? `(范围 within=${result.within} 的子树)` : '';
111
127
  if (matches.length === 0) {
112
128
  const zeroTail = result.truncated === true
113
129
  ? '(注意:搜索在请求预算内没有扫完整棵树,已有命中已随截断丢弃——收紧 text、换更独特的片段,或分窗口再搜)'
114
130
  : '';
115
- return `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素:没有包含 "${str(text0, 40)}" 的元素${args.exact === true ? '(精确匹配模式)' : ''}${zeroTail}`;
131
+ return `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素${scopeText}:没有包含 "${str(text0, 40)}" 的元素${args.exact === true ? '(精确匹配模式)' : ''}${zeroTail}`;
116
132
  }
117
133
  // Ranking, not just filtering. Searching "插件" in this very window returns the window's own
118
134
  // Pane and Document first — both carry the title, both are 1941x1243, and clicking either just
@@ -156,7 +172,7 @@ export function registerObserve(d) {
156
172
  const refStr = m.ref ? ` ref=${m.ref}` : '';
157
173
  return `${i + 1}. ${m.controlType} "${str(m.name, 48)}" 中心=(${m.center?.x},${m.center?.y})${refStr}${actStr}${m.className ? ` class=${str(m.className, 24)}` : ''}${flags ? ` ${flags}` : ''}${hint}${twinHint} by=${JSON.stringify(m.by)}`;
158
174
  });
159
- const head = `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素,命中 ${matches.length} 个"${str(text0, 40)}"${args.exact === true ? '(精确)' : ''}(可见命令元素在前,容器/侧栏行/屏外元素在后):`;
175
+ const head = `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素${scopeText},命中 ${matches.length} 个"${str(text0, 40)}"${args.exact === true ? '(精确)' : ''}(可见命令元素在前,容器/侧栏行/屏外元素在后):`;
160
176
  // Observation parity with snapshot's truncation report: the worker now counts EVERY match
161
177
  // (matchedTotal) and flags max/budget cuts, so silently dropped hits become visible. The
162
178
  // ranking happens on the returned subset, so dropped hits cannot be rescued here — the
@@ -17,7 +17,6 @@ export function registerPointer(d) {
17
17
  if (await ensureArmed(exec?.agent, exec?.signal)) return true;
18
18
  return DISARMED_MSG;
19
19
  };
20
- const GATE_MSG = DISARMED_MSG;
21
20
  // One normaliser for every tool that takes held keys: array or "ctrl+shift" string both work, and
22
21
  // the worker re-validates (an unknown modifier becomes bad_arg there, not a silent no-op here).
23
22
  const normMods = (value) => {
@@ -40,15 +39,36 @@ export function registerPointer(d) {
40
39
  return classify({ action: 'invoke', descriptor: { title: under?.title, className: under?.class ?? under?.hitClass, name: under?.app } });
41
40
  };
42
41
  const pointArgs = (args) => ({ x: Number(args.x), y: Number(args.y) });
43
- const needPoint = (args) => (typeof args.x !== 'number' || typeof args.y !== 'number' ? '需要数值坐标 x、y(物理像素,和快照 rect / find_text center 同一坐标空间)' : null);
42
+ // A ref is a better pointer target than arithmetic: the centre comes from the element's own rect,
43
+ // read fresh through the worker's describe (Resolve-Ref re-binds and refuses a stale ref), so a
44
+ // row that moved or a list that scrolled cannot turn into a click at the old coordinates. x/y
45
+ // stays for surfaces with no element at all (canvas, OCR hit).
46
+ const refPoint = async (ref) => {
47
+ const d = await worker.call('describe', { ref: String(ref) });
48
+ const r = d?.rect;
49
+ if (!r || !(r.w > 0) || !(r.h > 0)) return null;
50
+ return { x: Math.round(r.x + r.w / 2), y: Math.round(r.y + r.h / 2), controlType: d.controlType, name: d.name };
51
+ };
52
+ const resolvePoint = async (args) => {
53
+ if (args.ref !== undefined && String(args.ref) !== '') {
54
+ const p = await refPoint(args.ref);
55
+ if (p === null) return { error: `ref ${args.ref} 没有可点的矩形(元素已不可见或没有布局框):改用 x,y,或重新 computer_snapshot 后再操作` };
56
+ return p;
57
+ }
58
+ if (typeof args.x !== 'number' || typeof args.y !== 'number') {
59
+ return { error: '需要 ref(推荐,中心由元素 rect 现算)或数值坐标 x、y(物理像素,和快照 rect / find_text center 同一坐标空间)' };
60
+ }
61
+ return pointArgs(args);
62
+ };
44
63
 
45
64
 
46
65
  d.disposers.push(register(defineTool({
47
66
  name: 'computer_click',
48
- description: 'Move the real cursor to a physical (x,y) and click. Use for apps whose controls are not in the UIA tree (self-drawn UIs like WeChat) or when you want the action to be visible. Coordinates come from a snapshot element rect center, find_text center, or a screenshot you can see. windowId is required and the click is refused if that window is not actually under the point.',
67
+ description: 'Move the real cursor and click. Target it EITHER with ref (preferred: the centre is computed from the element\'s own rect on this call, so a moved row or a scrolled list still lands correctly) OR with physical (x,y) for surfaces that have no element (canvas, OCR hit, screenshot). Use it for self-drawn UIs (WeChat), for right/double/triple clicks, or when the action must be visible. windowId is required and the click is refused if that window is not actually under the point.',
49
68
  parameters: {
50
- windowId: { ...STR, required: true, description: 'The window you expect to be under (x,y); used as the target gate' },
51
- x: { ...INT, required: true }, y: { ...INT, required: true },
69
+ windowId: { ...STR, required: true, description: 'The window you expect to be under the point; used as the target gate' },
70
+ ref: { ...STR, description: 'Element ref from the newest snapshot of this window — alternative to x,y; the (x,y) is derived from its current rect' },
71
+ x: { ...INT, description: 'physical x (omit when passing ref)' }, y: { ...INT, description: 'physical y (omit when passing ref)' },
52
72
  button: { type: 'string', enum: ['left', 'right', 'middle'], description: 'default left' },
53
73
  double: { ...BOOL, description: 'double-click' },
54
74
  triple: { ...BOOL, description: 'triple-click (select a paragraph / whole line); implies not double' },
@@ -59,31 +79,35 @@ export function registerPointer(d) {
59
79
  timeoutMs: 30000,
60
80
  async execute(args, exec) {
61
81
  await aborted(exec.signal);
62
- if (!(await gate(exec))) return GATE_MSG;
63
- const bad = needPoint(args); if (bad) return bad;
64
- const { x, y } = pointArgs(args);
82
+ if (!(await gate(exec))) return DISARMED_MSG;
83
+ const p = await resolvePoint(args);
84
+ if (p.error) return p.error;
85
+ const { x, y } = p;
65
86
  const outcome = await classifyPoint(x, y);
66
87
  if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_click', ...args });
67
88
  const r = await worker.call('pointer_click', { x, y, button: args.button, double: args.double, triple: args.triple, mods: normMods(args.modifiers), durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
68
89
  store.actionDone(1);
69
- store.step({ label: `点击 (${x},${y})`, kind: 'pointer', status: 'passed', ms: r.ms, detail: `via=${r.via} under=${str(r.under?.title ?? r.under?.class, 40)}` });
90
+ store.step({ label: `点击 ${args.ref ? args.ref : ''}(${x},${y})`, kind: 'pointer', status: 'passed', ms: r.ms, detail: `via=${r.via} under=${str(r.under?.title ?? r.under?.class, 40)}` });
70
91
  const held = r.mods ? ` 按住 ${r.mods}` : '';
71
92
  const kind = r.triple ? ' 三击' : r.double ? ' 双击' : '';
93
+ const on = args.ref ? ` ${args.ref}${p.name ? `「${str(p.name, 30)}」` : ''}` : '';
72
94
  // Same point, same button, over and over: the third repeat is a stuck loop, not a retry.
73
95
  const tally = store.noteAttempt(`click:${x},${y}:${args.button ?? 'left'}`, true);
74
96
  const stuck = stuckNote('repeat', tally.total);
75
- return `已点击 (${x},${y}) ${args.button || 'left'}${kind}${held},耗时 ${r.ms}ms,落点窗口 "${str(r.under?.title ?? '', 50)}"${stuck}`;
97
+ return `已点击${on} (${x},${y}) ${args.button || 'left'}${kind}${held},耗时 ${r.ms}ms,落点窗口 "${str(r.under?.title ?? '', 50)}"${stuck}`;
76
98
  },
77
99
  })));
78
100
 
79
101
 
80
102
  d.disposers.push(register(defineTool({
81
103
  name: 'computer_drag',
82
- description: 'Press at (fromX,fromY), move to (toX,toY), release — for sliders, repositioning, marquee-select. Both endpoints must be inside windowId.',
104
+ description: 'Press at a start point, move to an end point, release — for sliders, repositioning, marquee-select. Either point can be a ref (centre derived from its current rect) or explicit physical coordinates; both must be inside windowId.',
83
105
  parameters: {
84
106
  windowId: { ...STR, required: true },
85
- fromX: { ...INT, required: true }, fromY: { ...INT, required: true },
86
- toX: { ...INT, required: true }, toY: { ...INT, required: true },
107
+ ref: { ...STR, description: 'ref to press at (alternative to fromX/fromY)' },
108
+ fromX: { ...INT, description: 'physical start x (omit when passing ref)' }, fromY: { ...INT, description: 'physical start y (omit when passing ref)' },
109
+ toRef: { ...STR, description: 'ref to release at (alternative to toX/toY)' },
110
+ toX: { ...INT, description: 'physical end x (omit when passing toRef)' }, toY: { ...INT, description: 'physical end y (omit when passing toRef)' },
87
111
  button: { type: 'string', enum: ['left', 'right', 'middle'] },
88
112
  durationMs: { ...INT },
89
113
  },
@@ -91,25 +115,28 @@ export function registerPointer(d) {
91
115
  timeoutMs: 30000,
92
116
  async execute(args, exec) {
93
117
  await aborted(exec.signal);
94
- if (!(await gate(exec))) return GATE_MSG;
95
- const nums = [args.fromX, args.fromY, args.toX, args.toY];
96
- if (nums.some((n) => typeof n !== 'number')) return '需要数值 fromX/fromY/toX/toY';
97
- const outcome = await classifyPoint(args.fromX, args.fromY);
118
+ if (!(await gate(exec))) return DISARMED_MSG;
119
+ const from = await resolvePoint({ ref: args.ref, x: args.fromX, y: args.fromY });
120
+ if (from.error) return `起点:${from.error}`;
121
+ const to = await resolvePoint({ ref: args.toRef, x: args.toX, y: args.toY });
122
+ if (to.error) return `终点:${to.error}`;
123
+ const outcome = await classifyPoint(from.x, from.y);
98
124
  if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_drag', ...args });
99
- const r = await worker.call('pointer_drag', { from: { x: args.fromX, y: args.fromY }, to: { x: args.toX, y: args.toY }, button: args.button, durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
125
+ const r = await worker.call('pointer_drag', { from: { x: from.x, y: from.y }, to: { x: to.x, y: to.y }, button: args.button, durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
100
126
  store.actionDone(1);
101
- store.step({ label: `拖拽 (${args.fromX},${args.fromY})→(${args.toX},${args.toY})`, kind: 'pointer', status: 'passed', ms: r.ms });
102
- return `已拖拽 (${args.fromX},${args.fromY}) → (${args.toX},${args.toY}),耗时 ${r.ms ?? '?'}ms`;
127
+ store.step({ label: `拖拽 (${from.x},${from.y})→(${to.x},${to.y})`, kind: 'pointer', status: 'passed', ms: r.ms });
128
+ return `已拖拽 (${from.x},${from.y}) → (${to.x},${to.y}),耗时 ${r.ms ?? '?'}ms`;
103
129
  },
104
130
  })));
105
131
 
106
132
 
107
133
  d.disposers.push(register(defineTool({
108
134
  name: 'computer_scroll',
109
- description: 'Scroll the mouse wheel at a physical (x,y): direction up|down|left|right, clicks = notches (default 3). windowId gates the point.',
135
+ description: 'Scroll the mouse wheel at a point: direction up|down|left|right, clicks = notches (default 3). The point is either a ref (its rect centre) or physical (x,y); windowId gates it.',
110
136
  parameters: {
111
137
  windowId: { ...STR, required: true },
112
- x: { ...INT, required: true }, y: { ...INT, required: true },
138
+ ref: { ...STR, description: 'ref whose centre to scroll over (alternative to x,y)' },
139
+ x: { ...INT, description: 'physical x (omit when passing ref)' }, y: { ...INT, description: 'physical y (omit when passing ref)' },
113
140
  direction: { type: 'string', enum: ['up', 'down', 'left', 'right'] },
114
141
  clicks: { ...INT, description: 'wheel notches, 1..50' },
115
142
  modifiers: { type: 'array', items: { type: 'string' }, description: 'held during the scroll: ["ctrl"] = zoom, ["shift"] = horizontal pan' },
@@ -118,9 +145,10 @@ export function registerPointer(d) {
118
145
  timeoutMs: 20000,
119
146
  async execute(args, exec) {
120
147
  await aborted(exec.signal);
121
- if (!(await gate(exec))) return GATE_MSG;
122
- const bad = needPoint(args); if (bad) return bad;
123
- const { x, y } = pointArgs(args);
148
+ if (!(await gate(exec))) return DISARMED_MSG;
149
+ const p = await resolvePoint(args);
150
+ if (p.error) return p.error;
151
+ const { x, y } = p;
124
152
  const outcome = await classifyPoint(x, y);
125
153
  if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_scroll', ...args });
126
154
  const r = await worker.call('pointer_scroll', { x, y, direction: args.direction, clicks: args.clicks, mods: normMods(args.modifiers), expect: { windowId: String(args.windowId) } });
@@ -144,7 +172,7 @@ export function registerPointer(d) {
144
172
  timeoutMs: 20000,
145
173
  async execute(args, exec) {
146
174
  await aborted(exec.signal);
147
- if (!(await gate(exec))) return GATE_MSG;
175
+ if (!(await gate(exec))) return DISARMED_MSG;
148
176
  const t = String(args.text ?? '');
149
177
  if (t === '') return 'text 为空';
150
178
  const via = args.via === 'clipboard' ? 'clipboard' : 'keyboard';
@@ -172,7 +200,7 @@ export function registerPointer(d) {
172
200
  timeoutMs: 15000,
173
201
  async execute(args, exec) {
174
202
  await aborted(exec.signal);
175
- if (!(await gate(exec))) return GATE_MSG;
203
+ if (!(await gate(exec))) return DISARMED_MSG;
176
204
  const combo = String(args.keys ?? '').trim().toLowerCase();
177
205
  if (combo === '') return 'keys 为空';
178
206
  // The combo has no UIA descriptor to feed the name table, so classification runs on the combo
@@ -198,9 +226,10 @@ export function registerPointer(d) {
198
226
  name: 'computer_mouse',
199
227
  description: 'Everything a click cannot express: hover (action:"move" and release nothing), press-and-hold across calls (action:"down" then a later action:"up" — marquee select, staged drag, holding a scrollbar), and reading where the cursor is (action:"position"). down/up act at the current cursor; the store tracks the pairing so a dangling press is visible.',
200
228
  parameters: {
201
- action: { type: 'string', enum: ['move', 'down', 'up', 'position'], required: true, description: 'move = hover to (x,y); down/up = press or release a button at the current cursor; position = read the cursor' },
202
- x: { ...INT, description: 'move only: physical x' },
203
- y: { ...INT, description: 'move only: physical y' },
229
+ action: { type: 'string', enum: ['move', 'down', 'up', 'position'], required: true, description: 'move = hover to a ref or (x,y); down/up = press or release a button at the current cursor; position = read the cursor' },
230
+ ref: { ...STR, description: 'move only: hover this element (its rect centre) instead of x,y' },
231
+ x: { ...INT, description: 'move only: physical x (omit when passing ref)' },
232
+ y: { ...INT, description: 'move only: physical y (omit when passing ref)' },
204
233
  button: { type: 'string', enum: ['left', 'right', 'middle'], description: 'down/up only, default left' },
205
234
  durationMs: { ...INT, description: 'move only: glide time (default auto by distance)' },
206
235
  windowId: { ...STR, description: 'gates the point: the window that must be under the cursor / destination' },
@@ -209,7 +238,7 @@ export function registerPointer(d) {
209
238
  timeoutMs: 30000,
210
239
  async execute(args, exec) {
211
240
  await aborted(exec.signal);
212
- if (!(await gate(exec))) return GATE_MSG;
241
+ if (!(await gate(exec))) return DISARMED_MSG;
213
242
  const action = String(args.action ?? 'position').toLowerCase();
214
243
  // Every cursor-moving/pressing branch needs the target gate. The worker refuses an unnamed
215
244
  // target on purpose (that is what stops a stray physical click), so say so here instead of
@@ -220,8 +249,9 @@ export function registerPointer(d) {
220
249
  : null;
221
250
  if (action === 'move') {
222
251
  if (targetNeeded) return targetNeeded;
223
- const bad = needPoint(args); if (bad) return bad;
224
- const { x, y } = pointArgs(args);
252
+ const p = await resolvePoint(args);
253
+ if (p.error) return p.error;
254
+ const { x, y } = p;
225
255
  const outcome = await classifyPoint(x, y);
226
256
  if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_mouse', ...args });
227
257
  const r = await worker.call('pointer_mouse', { action, x, y, durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
@@ -266,7 +296,7 @@ export function registerPointer(d) {
266
296
  const op = String(args.op ?? '').toLowerCase();
267
297
  // write/clear mutate shared state, so they pass the permission gate; read stays ungated (it
268
298
  // already has its own stricter ctrl+c precondition).
269
- if (op !== 'read' && !(await gate(exec))) return GATE_MSG;
299
+ if (op !== 'read' && !(await gate(exec))) return DISARMED_MSG;
270
300
  if (op === 'read') {
271
301
  if (!store.ctrlCAt) {
272
302
  return '剪贴板读取被拦:本轮还没有自己按过 ctrl+c。先用 computer_key keys:"ctrl+c" 复制目标内容(或让用户自己复制后由用户告知),再读;这样读到的才是本轮的产物,而不是用户之前的剪贴板。';
@@ -295,4 +325,4 @@ export function registerPointer(d) {
295
325
  },
296
326
  })));
297
327
 
298
- }
328
+ }