dsh-native-uia 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +663 -2
  3. package/client/client.js +269 -0
  4. package/cordis.patch.yml +10 -0
  5. package/icon.svg +11 -0
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/package.json +75 -4
  9. package/scripts/bench-live.mjs +157 -0
  10. package/scripts/check-lease.mjs +308 -0
  11. package/scripts/install.mjs +154 -0
  12. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  13. package/scripts/lib/load-tools-source.mjs +25 -0
  14. package/scripts/lib/sources.mjs +62 -0
  15. package/scripts/load-tools.mjs +74 -0
  16. package/scripts/measure-parse.mjs +77 -0
  17. package/scripts/regression-halt-latch.mjs +100 -0
  18. package/scripts/regression-quality.mjs +207 -0
  19. package/scripts/regression-tools.mjs +192 -0
  20. package/scripts/regression-worker.ps1 +1071 -0
  21. package/scripts/smoke.mjs +158 -0
  22. package/scripts/verify-capture-scale.mjs +37 -0
  23. package/scripts/verify-live-clipboard.mjs +108 -0
  24. package/scripts/verify-live-style.mjs +46 -0
  25. package/scripts/verify-live.mjs +104 -0
  26. package/scripts/verify-locator.mjs +52 -0
  27. package/scripts/verify.mjs +2110 -0
  28. package/src/activity-window.js +276 -0
  29. package/src/dashboard.js +103 -0
  30. package/src/guard.js +201 -0
  31. package/src/index.js +525 -0
  32. package/src/native-uia-remote.js +80 -0
  33. package/src/notes.js +83 -0
  34. package/src/state.js +267 -0
  35. package/src/themes.js +74 -0
  36. package/src/tools/defs/act.js +533 -0
  37. package/src/tools/defs/lifecycle.js +205 -0
  38. package/src/tools/defs/observe.js +309 -0
  39. package/src/tools/defs/pointer.js +298 -0
  40. package/src/tools/format.js +301 -0
  41. package/src/tools/index.js +128 -0
  42. package/src/tools/ocr.js +91 -0
  43. package/src/tools/recipes.js +44 -0
  44. package/src/tools/runtime.js +42 -0
  45. package/src/worker-client.js +268 -0
  46. package/worker/assets/dsh-whale.path +1 -0
  47. package/worker/bin/build-ocr.ps1 +41 -0
  48. package/worker/bin/ocr.cs +69 -0
  49. package/worker/bin/ocr.exe +0 -0
  50. package/worker/indicator-server.ps1 +2963 -0
  51. package/worker/lib/01-core.ps1 +64 -0
  52. package/worker/lib/02-uia.ps1 +221 -0
  53. package/worker/lib/03-window.ps1 +194 -0
  54. package/worker/lib/04-match.ps1 +435 -0
  55. package/worker/lib/05-value.ps1 +149 -0
  56. package/worker/lib/06-snapshot.ps1 +345 -0
  57. package/worker/lib/07-action.ps1 +291 -0
  58. package/worker/lib/08-command.ps1 +1485 -0
  59. package/worker/lib/09-pointer.ps1 +840 -0
  60. package/worker/lib/10-dispatch.ps1 +134 -0
  61. package/worker/ps-stdio.ps1 +173 -0
  62. package/worker/uia-worker.ps1 +599 -0
@@ -0,0 +1,298 @@
1
+ import { classifyKeys } from '../../guard.js';
2
+ import { defineTool } from '@deepseek-ai/dsh-tools';
3
+ import { STR, INT, BOOL, text, str, aborted, DISARMED_MSG } from '../runtime.js';
4
+ import { stuckNote } from '../format.js';
5
+
6
+ /**
7
+ * Tools of the pointer domain. Every one takes the shared `d` bundle built by registerTools: the
8
+ * register wrapper (idle touch + dispose tracking), the worker, the store and the run's finish
9
+ * hook. Policy is never decided here — `d.refuse` renders what guard.js already judged.
10
+ */
11
+ export function registerPointer(d) {
12
+ const { worker, store, register, refuse, touch, ensureArmed } = d;
13
+ // The activation permission gate: every delivery tool calls this first with its exec.agent. The
14
+ // FIRST call in the session draws the host question card (input-box上方), the verdict is cached,
15
+ // and a refusal ends the tool with an honest message instead of touching the desktop.
16
+ const gate = async (exec) => {
17
+ if (await ensureArmed(exec?.agent, exec?.signal)) return true;
18
+ return DISARMED_MSG;
19
+ };
20
+ const GATE_MSG = DISARMED_MSG;
21
+ // One normaliser for every tool that takes held keys: array or "ctrl+shift" string both work, and
22
+ // the worker re-validates (an unknown modifier becomes bad_arg there, not a silent no-op here).
23
+ const normMods = (value) => {
24
+ if (value === undefined || value === null || value === '') return [];
25
+ const list = Array.isArray(value) ? value : String(value).split('+');
26
+ return list.map((m) => String(m).trim().toLowerCase()).filter(Boolean);
27
+ };
28
+ // The blocks below keep their original indentation so the gate regexes (which were written
29
+ // against the single-file source) still match the concatenated view byte for byte.
30
+
31
+
32
+ // ---- physical (foreground) action tools: the human-action set -------------------------------
33
+ // These drive the real cursor/keyboard and are visible. Coordinates are physical screen pixels, the
34
+ // same space snapshot rects and find_text centers use. Every click/drag/scroll MUST name the window
35
+ // it lands in (expect.windowId) so it can never click blind across the whole desktop, and the point
36
+ // is run through the same destructive-text guard by resolving what is actually under it first.
37
+ const classifyPoint = async (x, y) => {
38
+ const t = await worker.call('pointer_target', { x, y });
39
+ const under = t?.under ?? t;
40
+ return classify({ action: 'invoke', descriptor: { title: under?.title, className: under?.class ?? under?.hitClass, name: under?.app } });
41
+ };
42
+ 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);
44
+
45
+
46
+ d.disposers.push(register(defineTool({
47
+ 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.',
49
+ 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 },
52
+ button: { type: 'string', enum: ['left', 'right', 'middle'], description: 'default left' },
53
+ double: { ...BOOL, description: 'double-click' },
54
+ triple: { ...BOOL, description: 'triple-click (select a paragraph / whole line); implies not double' },
55
+ modifiers: { type: 'array', items: { type: 'string' }, description: 'held during the click: ctrl / shift / alt / win — e.g. ["ctrl"] to add to a selection' },
56
+ durationMs: { ...INT, description: 'cursor glide time (default auto by distance)' },
57
+ },
58
+ output: { schema: STR, render: (_a, v) => text(v) },
59
+ timeoutMs: 30000,
60
+ async execute(args, exec) {
61
+ 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);
65
+ const outcome = await classifyPoint(x, y);
66
+ if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_click', ...args });
67
+ 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
+ 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)}` });
70
+ const held = r.mods ? ` 按住 ${r.mods}` : '';
71
+ const kind = r.triple ? ' 三击' : r.double ? ' 双击' : '';
72
+ // Same point, same button, over and over: the third repeat is a stuck loop, not a retry.
73
+ const tally = store.noteAttempt(`click:${x},${y}:${args.button ?? 'left'}`, true);
74
+ const stuck = stuckNote('repeat', tally.total);
75
+ return `已点击 (${x},${y}) ${args.button || 'left'}${kind}${held},耗时 ${r.ms}ms,落点窗口 "${str(r.under?.title ?? '', 50)}"${stuck}`;
76
+ },
77
+ })));
78
+
79
+
80
+ d.disposers.push(register(defineTool({
81
+ 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.',
83
+ parameters: {
84
+ windowId: { ...STR, required: true },
85
+ fromX: { ...INT, required: true }, fromY: { ...INT, required: true },
86
+ toX: { ...INT, required: true }, toY: { ...INT, required: true },
87
+ button: { type: 'string', enum: ['left', 'right', 'middle'] },
88
+ durationMs: { ...INT },
89
+ },
90
+ output: { schema: STR, render: (_a, v) => text(v) },
91
+ timeoutMs: 30000,
92
+ async execute(args, exec) {
93
+ 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);
98
+ 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) } });
100
+ 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`;
103
+ },
104
+ })));
105
+
106
+
107
+ d.disposers.push(register(defineTool({
108
+ 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.',
110
+ parameters: {
111
+ windowId: { ...STR, required: true },
112
+ x: { ...INT, required: true }, y: { ...INT, required: true },
113
+ direction: { type: 'string', enum: ['up', 'down', 'left', 'right'] },
114
+ clicks: { ...INT, description: 'wheel notches, 1..50' },
115
+ modifiers: { type: 'array', items: { type: 'string' }, description: 'held during the scroll: ["ctrl"] = zoom, ["shift"] = horizontal pan' },
116
+ },
117
+ output: { schema: STR, render: (_a, v) => text(v) },
118
+ timeoutMs: 20000,
119
+ async execute(args, exec) {
120
+ 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);
124
+ const outcome = await classifyPoint(x, y);
125
+ if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_scroll', ...args });
126
+ const r = await worker.call('pointer_scroll', { x, y, direction: args.direction, clicks: args.clicks, mods: normMods(args.modifiers), expect: { windowId: String(args.windowId) } });
127
+ store.actionDone(1);
128
+ store.step({ label: `滚动 ${args.direction || 'down'} @(${x},${y})`, kind: 'pointer', status: 'passed', ms: r.ms });
129
+ const held = r.mods ? `(按住 ${r.mods})` : '';
130
+ return `已在 (${x},${y}) ${args.direction || 'down'} 滚动 ${r.clicks} 格${held},耗时 ${r.ms}ms`;
131
+ },
132
+ })));
133
+
134
+
135
+ d.disposers.push(register(defineTool({
136
+ name: 'computer_type',
137
+ description: 'Type text into the focused control. Click the input first (computer_click) or pass windowId to focus it. Default via="keyboard" sends per-character Unicode events and does not touch the clipboard. For long text (>500 chars) or text containing newlines use via:"clipboard": the full text is written with Set-Clipboard and delivered as one ctrl+v paste — note it OVERWRITES the user\'s clipboard and does not restore it. After typing, computer_wait {type:"value_equals", ref} gives a deterministic check that the content landed.',
138
+ parameters: {
139
+ text: { ...STR, required: true, description: 'text to type, up to 4000 chars' },
140
+ via: { type: 'string', enum: ['keyboard', 'clipboard'], description: 'keyboard (default) = per-character events; clipboard = Set-Clipboard + ctrl+v, overwrites the user clipboard and does not restore; prefer for >500 chars or text with newlines' },
141
+ windowId: { ...STR, description: 'optional: raise+focus this window before typing' },
142
+ },
143
+ output: { schema: STR, render: (_a, v) => text(v) },
144
+ timeoutMs: 20000,
145
+ async execute(args, exec) {
146
+ await aborted(exec.signal);
147
+ if (!(await gate(exec))) return GATE_MSG;
148
+ const t = String(args.text ?? '');
149
+ if (t === '') return 'text 为空';
150
+ const via = args.via === 'clipboard' ? 'clipboard' : 'keyboard';
151
+ const r = await worker.call('type_text', { text: t, windowId: args.windowId ? String(args.windowId) : '', via });
152
+ store.actionDone(1);
153
+ store.step({ label: `输入 ${str(t, 24)} (${t.length} 字)`, kind: 'pointer', status: 'passed', ms: r.ms });
154
+ // The clipboard path is one paste, not 8000 key events — the honest answer names the channel
155
+ // AND the side effect the caller accepted (the clipboard is overwritten, not restored).
156
+ return via === 'clipboard'
157
+ ? `已通过剪贴板粘贴 ${t.length} 个字符(Set-Clipboard + ctrl+v),耗时 ${r.ms}ms。原剪贴板内容已被覆盖且未恢复;可用 computer_wait {type:"value_equals", ref} 确认内容已落盘。`
158
+ : `已输入 ${t.length} 个字符,耗时 ${r.ms}ms(SendInput 接受 ${r.sent} 个按键事件)`;
159
+ },
160
+ })));
161
+
162
+
163
+ d.disposers.push(register(defineTool({
164
+ name: 'computer_key',
165
+ description: 'Press one key or a hotkey combo on the physical keyboard: "enter", "tab", "esc", "f5", "down", "ctrl+c", "ctrl+shift+s", "alt+tab". Letters/digits and named keys (see worker) supported.',
166
+ parameters: {
167
+ keys: { ...STR, required: true, description: 'single key or modifiers joined by +, e.g. "ctrl+c"' },
168
+ repeat: { ...INT, description: 'press the combo N times in one call (1..100, default 1) — tab/tab/tab without three round trips' },
169
+ holdMs: { ...INT, description: 'hold the main key down this long before releasing (1..30000, default 15) — space to pan, shift to range-select' },
170
+ },
171
+ output: { schema: STR, render: (_a, v) => text(v) },
172
+ timeoutMs: 15000,
173
+ async execute(args, exec) {
174
+ await aborted(exec.signal);
175
+ if (!(await gate(exec))) return GATE_MSG;
176
+ const combo = String(args.keys ?? '').trim().toLowerCase();
177
+ if (combo === '') return 'keys 为空';
178
+ // The combo has no UIA descriptor to feed the name table, so classification runs on the combo
179
+ // text itself — in guard.js, like every other policy decision: the session-ending combos deny
180
+ // there with the shared CATEGORIES wording, ordinary combos pass. No policy is matched here.
181
+ const outcome = classifyKeys(combo);
182
+ if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_key', keys: combo });
183
+ const r = await worker.call('key', { keys: combo, repeat: args.repeat, holdMs: args.holdMs });
184
+ store.actionDone(1);
185
+ // Clipboard reads are gated on "the model itself copied something this run", and this is the
186
+ // only place that can create that permission: a ctrl+c the model pressed. It is not a grant
187
+ // for the user's earlier clipboard content; it says the CURRENT buffer came from a copy we
188
+ // just performed, so reading it back is reading our own action's result.
189
+ if (/(?:^|\+)ctrl\+c(?:\+|$)/.test(combo) || /(?:^|\+)ctrl\+insert(?:\+|$)/.test(combo)) {
190
+ store.ctrlCAt = Date.now();
191
+ }
192
+ store.step({ label: `按键 ${combo}${r.repeat > 1 ? ` ×${r.repeat}` : ''}`, kind: 'pointer', status: 'passed', ms: r.ms });
193
+ return `已按下 ${combo}${r.repeat > 1 ? ` ${r.repeat} 次` : ''},耗时 ${r.ms ?? '?'}ms`;
194
+ },
195
+ })));
196
+
197
+ d.disposers.push(register(defineTool({
198
+ name: 'computer_mouse',
199
+ 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
+ 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' },
204
+ button: { type: 'string', enum: ['left', 'right', 'middle'], description: 'down/up only, default left' },
205
+ durationMs: { ...INT, description: 'move only: glide time (default auto by distance)' },
206
+ windowId: { ...STR, description: 'gates the point: the window that must be under the cursor / destination' },
207
+ },
208
+ output: { schema: STR, render: (_a, v) => text(v) },
209
+ timeoutMs: 30000,
210
+ async execute(args, exec) {
211
+ await aborted(exec.signal);
212
+ if (!(await gate(exec))) return GATE_MSG;
213
+ const action = String(args.action ?? 'position').toLowerCase();
214
+ // Every cursor-moving/pressing branch needs the target gate. The worker refuses an unnamed
215
+ // target on purpose (that is what stops a stray physical click), so say so here instead of
216
+ // forwarding windowId:'' and surfacing the worker's generic refusal. Named `targetNeeded`
217
+ // because `gate` is this domain's permission helper and a local would shadow it.
218
+ const targetNeeded = args.windowId === undefined || String(args.windowId) === ''
219
+ ? 'computer_mouse 的 move/down/up 需要 windowId:它声明光标下应当是哪个窗口,worker 用它挡住误落到别的窗口上的点击。只是想读光标位置用 action:"position"。'
220
+ : null;
221
+ if (action === 'move') {
222
+ if (targetNeeded) return targetNeeded;
223
+ const bad = needPoint(args); if (bad) return bad;
224
+ const { x, y } = pointArgs(args);
225
+ const outcome = await classifyPoint(x, y);
226
+ if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_mouse', ...args });
227
+ const r = await worker.call('pointer_mouse', { action, x, y, durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
228
+ store.actionDone(1);
229
+ store.step({ label: `悬停 (${r.atCursor?.x},${r.atCursor?.y})`, kind: 'pointer', status: 'passed', ms: r.ms, detail: `hover=${str(r.hover?.title ?? r.hover?.class, 40)}` });
230
+ return `光标已移到 (${r.atCursor?.x},${r.atCursor?.y}),耗时 ${r.ms}ms,下方窗口 "${str(r.hover?.title ?? '', 50)}"(悬停才出现的菜单/提示现在会展开)`;
231
+ }
232
+ if (action === 'position') {
233
+ const r = await worker.call('pointer_mouse', { action });
234
+ return `光标在 (${r.x},${r.y}),屏幕 ${r.screen?.w}x${r.screen?.h},下方窗口 "${str(r.under?.title ?? r.under?.class ?? '', 50)}"`;
235
+ }
236
+ // down / up: the worker checks that the declared window holds at the cursor, and the store
237
+ // tracks the pairing so a dangling press is visible instead of silent.
238
+ if (targetNeeded) return targetNeeded;
239
+ const r = await worker.call('pointer_mouse', { action, button: args.button, expect: { windowId: String(args.windowId) } });
240
+ store.actionDone(1);
241
+ const button = args.button ?? 'left';
242
+ if (action === 'down') {
243
+ store.holdButton(button);
244
+ store.step({ label: `按下 ${button} @(${r.atCursor?.x},${r.atCursor?.y})`, kind: 'pointer', status: 'passed', ms: r.ms });
245
+ return `已按下 ${button} 键于 (${r.atCursor?.x},${r.atCursor?.y}),它保持按下;用完必须用 action:"up" 释放。`;
246
+ }
247
+ const wasHeld = store.releaseButton(button);
248
+ store.step({ label: `释放 ${button} @(${r.atCursor?.x},${r.atCursor?.y})`, kind: 'pointer', status: 'passed', ms: r.ms });
249
+ return wasHeld
250
+ ? `已释放 ${button} 键于 (${r.atCursor?.x},${r.atCursor?.y})`
251
+ : `已释放 ${button} 键于 (${r.atCursor?.x},${r.atCursor?.y})(本轮没有记录到对应按下,释放仍已发送)`;
252
+ },
253
+ })));
254
+
255
+ d.disposers.push(register(defineTool({
256
+ name: 'computer_clipboard',
257
+ description: 'The Windows text clipboard. write replaces it (max 20000 chars), clear empties it, read returns the text — but read is gated to "this run copied it itself": it only answers after a computer_key ctrl+c, so the user\'s earlier clipboard contents are not exposed to a run that never asked for them. Use it to move long text between apps without 4000 tiny key events, or to capture what an app just copied.',
258
+ parameters: {
259
+ op: { type: 'string', enum: ['read', 'write', 'clear'], required: true, description: 'read | write | clear' },
260
+ text: { ...STR, description: 'write only: the text to place on the clipboard' },
261
+ },
262
+ output: { schema: STR, render: (_a, v) => text(v) },
263
+ timeoutMs: 15000,
264
+ async execute(args, exec) {
265
+ await aborted(exec.signal);
266
+ const op = String(args.op ?? '').toLowerCase();
267
+ // write/clear mutate shared state, so they pass the permission gate; read stays ungated (it
268
+ // already has its own stricter ctrl+c precondition).
269
+ if (op !== 'read' && !(await gate(exec))) return GATE_MSG;
270
+ if (op === 'read') {
271
+ if (!store.ctrlCAt) {
272
+ return '剪贴板读取被拦:本轮还没有自己按过 ctrl+c。先用 computer_key keys:"ctrl+c" 复制目标内容(或让用户自己复制后由用户告知),再读;这样读到的才是本轮的产物,而不是用户之前的剪贴板。';
273
+ }
274
+ const r = await worker.call('clipboard_read', {}, { timeoutMs: 9000 });
275
+ if (r.empty === true) return '剪贴板里现在是空文本(或只有非文本内容)';
276
+ const clipped = r.truncated === true ? `,已截断到 20000 字符(原长 ${r.length})` : '';
277
+ store.step({ label: '读取剪贴板', kind: 'pointer', status: 'passed', detail: `${r.length} 字符` });
278
+ return `剪贴板文本(${r.length} 字符${clipped}):\n${r.text}`;
279
+ }
280
+ if (op === 'write') {
281
+ const payload = String(args.text ?? '');
282
+ if (payload === '') return 'write 需要 text(要写进剪贴板的内容)';
283
+ const r = await worker.call('clipboard_write', { text: payload }, { timeoutMs: 9000 });
284
+ store.actionDone(1);
285
+ store.step({ label: '写入剪贴板', kind: 'pointer', status: 'passed', detail: `${r.length} 字符` });
286
+ return `已写入剪贴板 ${r.length} 字符(替换了原有内容;需要粘贴时用 computer_key keys:"ctrl+v")`;
287
+ }
288
+ if (op === 'clear') {
289
+ const r = await worker.call('clipboard_clear', {}, { timeoutMs: 9000 });
290
+ store.actionDone(1);
291
+ store.step({ label: '清空剪贴板', kind: 'pointer', status: 'passed' });
292
+ return r.cleared === true ? '剪贴板已清空' : '剪贴板清空没有回执,按未确认处理';
293
+ }
294
+ return 'op 必须是 read | write | clear';
295
+ },
296
+ })));
297
+
298
+ }
@@ -0,0 +1,301 @@
1
+ import { str } from './runtime.js';
2
+
3
+ export function renderWindows(windows) {
4
+ if (windows.length === 0) return '当前没有可见窗口';
5
+ return windows
6
+ .map((w) => `${w.windowId} pid=${w.pid} ${str(w.appName, 20)} "${str(w.title, 60)}" ${Math.round(w.rect?.w ?? 0)}x${Math.round(w.rect?.h ?? 0)}${w.isForeground ? ' [foreground]' : ''}`)
7
+ .join('\n');
8
+ }
9
+
10
+ // Only the patterns that change what the model can DO with the node. The full UIA list is noise:
11
+ // "ScrollItem,Transform,ItemContainer,Window" appears on hundreds of rows and no decision depends
12
+ // on it, while Invoke/Value/Toggle/SelectionItem/ExpandCollapse/RangeValue/Scroll are exactly the
13
+ // verbs computer_act accepts. Dropping the rest cut the rendered tree by roughly a third without
14
+ // removing a single actionable fact — the model reads a smaller tree and finds the control faster.
15
+ export const ACTIONABLE = new Set([
16
+ 'Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'RangeValue', 'Scroll', 'Text',
17
+ 'GridItem', 'Selection', 'ItemContainer',
18
+ ]);
19
+
20
+ // The verbs a model can actually put in computer_act; narrower than ACTIONABLE, which also carries
21
+ // read-only patterns. A node listed here is one the model can act on without a second look.
22
+ export const ACT_VERBS = new Set(['Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'RangeValue', 'Scroll']);
23
+
24
+ /**
25
+ * A one-line map of what is actionable, printed before the tree.
26
+ *
27
+ * In a 200-node snapshot only ~22% of nodes accept an action, and they are scattered through
28
+ * chrome the model has to read past. Naming them up front (ref + type + name) means the model can
29
+ * often pick its target from this line and go straight to computer_act, instead of scanning the
30
+ * whole tree — fewer tokens spent and fewer wrong-element guesses. Capped so it cannot become its
31
+ * own wall of text.
32
+ */
33
+ export function renderActionables(nodes, max = 24) {
34
+ const acts = nodes.filter((n) => (n.patterns ?? []).some((p) => ACT_VERBS.has(p)));
35
+ if (acts.length === 0) return '';
36
+ // Each entry is a complete "ref + controlType + name" metadata row: two same-named buttons used
37
+ // to render byte-identical, and a model reading only this line could not tell them apart. The
38
+ // center coordinate doubles as the by.nearPoint input, so same-name disambiguation no longer
39
+ // needs a second find_text pass over the whole tree.
40
+ const shown = acts.slice(0, max).map((n) => {
41
+ const c = n.rect && n.rect.w > 0 ? ` @(${Math.round(n.rect.x + n.rect.w / 2)},${Math.round(n.rect.y + n.rect.h / 2)})` : '';
42
+ return `${n.ref} ${n.controlType}${n.name && n.name.trim() ? ` "${str(n.name, 24)}"` : ''}${c}`;
43
+ });
44
+ const rest = acts.length > shown.length ? ` …另 ${acts.length - shown.length} 个` : '';
45
+ return `可操作元素 ${acts.length} 个(@=中心坐标,同名时可直接填进 by.nearPoint 消歧):${shown.join('、')}${rest}\n`;
46
+ }
47
+
48
+ export function renderTree(nodes, { compact = false, elide = true } = {}) {
49
+ if (nodes.length === 0) return '快照返回 0 个元素';
50
+ const shown = elide ? elideRedundantContainers(nodes) : nodes;
51
+ const lines = shown.length > 0 ? shown : nodes;
52
+ return lines
53
+ .map((n) => {
54
+ const pad = ' '.repeat(Math.min(n.depth ?? 0, 10));
55
+ const acts = (n.patterns ?? []).filter((p) => ACTIONABLE.has(p));
56
+ // `disabled` and `offscreen` are the two flags that change whether acting makes sense; the
57
+ // compact form still carries them because they are decision-relevant, unlike class names.
58
+ const flags = [n.enabled === false ? 'disabled' : '', n.isOffscreen === true ? 'offscreen' : ''].filter(Boolean).join(' ');
59
+ const value = n.value === undefined || n.value === '' ? '' : ` val="${str(n.value, compact ? 24 : 40)}"`;
60
+ const pat = acts.length === 0 ? '' : ` [${acts.join(',')}]`;
61
+ const name = str(n.name, compact ? 32 : 48);
62
+ return `${pad}${n.ref} ${n.controlType} "${name}"${value}${pat}${flags ? ` ${flags}` : ''}`;
63
+ })
64
+ .join('\n');
65
+ }
66
+
67
+ /**
68
+ * Per-verb inline verify suggestions for the "nothing observable changed" branches of
69
+ * renderEffect. The type set is aligned with the worker's verify evaluator (Eval-Once — the same
70
+ * evaluator serves act's verify channel and wait), and a verb only gets the types whose effect it
71
+ * can actually make observable: set_value/text_append end in the element's reading, toggle shows
72
+ * up as a reading change or in IsEnabled. Button verbs (invoke/expand/collapse/...) have no
73
+ * assertable reading, so suggesting value_changed for them would only produce verify checks that
74
+ * never match — those keep the plain re-observe advice.
75
+ */
76
+ export const VERIFY_HINT = {
77
+ set_value: ['value_equals'],
78
+ text_append: ['value_equals'],
79
+ toggle: ['value_changed', 'enabled_is'],
80
+ };
81
+
82
+ /**
83
+ * Say what the action demonstrably changed, instead of letting "no error" read as "it worked".
84
+ * Act-effect verification is the load-bearing idea in recent GUI-agent work (verify the effect
85
+ * rather than trust the click). We only claim what the worker actually observed: a verify matcher
86
+ * fired, the element's value changed, or nothing observable changed — the last case is a hint to
87
+ * add a verify condition (for verbs with an observable effect, one call settles it) or re-observe,
88
+ * not a failure, because most buttons legitimately change no element property.
89
+ */
90
+ export function renderEffect(r) {
91
+ if (r.performed !== true) return '';
92
+ if (r.verify) return r.verify.matched === true ? ' 效果=校验命中' : ' 效果=校验未命中';
93
+ const hint = VERIFY_HINT[String(r.action ?? '')];
94
+ const tip = hint
95
+ ? `;如需确定性判据,加 verify:{type:"${hint[0]}"}${hint[1] ? `(或 ${hint[1]})` : ''}`
96
+ : '';
97
+ const hasValue = (r.before ?? '') !== '' || (r.after ?? '') !== '';
98
+ if (!hasValue) return ` 效果=无可观测属性变化(已送达${tip})`;
99
+ return r.before === r.after ? ` 效果=属性未变(已送达${tip})` : ' 效果=属性已变';
100
+ }
101
+
102
+ // Single source for the not_executed wording: the worker only ships the status (uia-worker.ps1
103
+ // keeps an English placeholder because this file is parsed as ANSI there), and BOTH batch tools
104
+ // render the tail through renderResults — one constant here keeps computer_run and computer_replay
105
+ // from drifting apart.
106
+ export const NOT_EXECUTED_TEXT = '未执行:前序步骤失败/被取消';
107
+
108
+ export function renderResults(results, performed) {
109
+ const lines = results.map((r) => {
110
+ // 'not_executed' is the worker's placeholder for steps a stop/cancel never reached: every
111
+ // planned step must appear in the reply with the same fixed wording, so the model can see
112
+ // WHICH tail was skipped instead of inferring it from performedCount alone.
113
+ const notExecuted = r.status === 'not_executed';
114
+ const mark = r.status === 'passed' ? '通过' : notExecuted ? '未执行' : r.status;
115
+ const verify = r.verify ? ` 校验=${r.verify.matched === true ? '命中' : '未命中'}(${r.verify.type ?? '?'})` : '';
116
+ const delivered = r.performed === true && r.status !== 'passed' ? '(动作已执行,勿直接重试)' : '';
117
+ // commit re-resolves every by-step right before acting, so this per-step verdict is the
118
+ // truth closest to the moment of the action — render it inline instead of dropping it.
119
+ const locator = r.degraded === true ? ` 定位=${r.matchedBy ?? '?'}(${Math.round((Number(r.score) || 0) * 100)}%)` : '';
120
+ const detail = notExecuted ? NOT_EXECUTED_TEXT : r.detail;
121
+ return `${mark} 第 ${r.index} 步 ${r.action ?? ''} ${r.ref ?? ''}${delivered} 耗时 ${r.ms ?? '?'}ms${verify}${locator}${renderEffect(r)}${detail ? ` ${str(detail, 90)}` : ''}`;
122
+ });
123
+ const unverified = results.filter((r) => r.performed === true && !r.verify).length;
124
+ const tail = unverified > 0
125
+ ? `\nperformedCount=${performed}(其中 ${unverified} 步没有校验条件:结果只代表已送达,不代表界面已按预期改变)`
126
+ : `\nperformedCount=${performed}`;
127
+ // Four-state tally so the model does not re-count the lines itself: a batch reply used to give
128
+ // only performedCount, and 成功/失败/校验未命中/未执行 had to be inferred per row. '校验未命中'
129
+ // keeps the existing contract wording: the action WAS delivered — do not blindly retry it.
130
+ const passedCount = results.filter((r) => r.status === 'passed').length;
131
+ const verifyMissedCount = results.filter((r) => r.status === 'verify_failed').length;
132
+ const notExecutedCount = results.filter((r) => r.status === 'not_executed').length;
133
+ const failedResults = results.filter((r) => r.status !== 'passed' && r.status !== 'verify_failed' && r.status !== 'not_executed');
134
+ const firstFail = failedResults[0];
135
+ const firstReason = firstFail ? `(首条原因:第 ${firstFail.index} 步 ${str(firstFail.detail, 60)})` : '';
136
+ const tally = `批次汇总:通过 ${passedCount} / 失败 ${failedResults.length}${firstReason} / 校验未命中 ${verifyMissedCount} / 未执行 ${notExecutedCount}`;
137
+ return `${lines.join('\n')}${tail}\n${tally}`;
138
+ }
139
+
140
+ /**
141
+ * One line per stop, and the wording must MATCH THE REASON. A failed/verify_failed stop means
142
+ * "the desktop drifted: re-observe and continue". status='cancelled' is the opposite instruction —
143
+ * the user pressed Esc to STOP, so the model must pause and ask, not auto-resume. The worker
144
+ * always reported that status; the run path just dropped it on the floor and printed the
145
+ * "continue" wording for both.
146
+ */
147
+ export function stoppedNote(committed) {
148
+ const stoppedAt = committed?.stoppedAt;
149
+ if (stoppedAt === null || stoppedAt === undefined) return '';
150
+ if (committed.status === 'cancelled') {
151
+ return `\n用户按 Esc 终止了本轮(第 ${stoppedAt} 步及其后的步骤未执行):请暂停并向用户确认是否继续,不要自动续跑。`;
152
+ }
153
+ return `\n在第 ${stoppedAt} 步停下:先重新 computer_snapshot 再继续,桌面状态可能已经和你规划时不一样了。`;
154
+ }
155
+
156
+ /**
157
+ * One observation-metadata line for snapshot/find_text heads: where the desktop foreground is,
158
+ * where the UIA focus sits, and whether that focus lives in the observed window (pid comparison,
159
+ * advisory — a multi-process host can misreport). The next observation after a click/type carries
160
+ * free proof of whether the action took effect: the focus moved into (or out of) the window. Every
161
+ * field is advisory — the worker omits any of them when its probe fails, and this renders only
162
+ * what arrived. A focus outside the target window gets the one-line fix. Everything goes through
163
+ * str() so a long window title cannot blow the line. Deliberately NOT exported: the
164
+ * regression harness (scripts/lib/load-tools-source.mjs) strips only known exports, so an export
165
+ * here would break every loader consumer — it picks these up through its return expression.
166
+ */
167
+ export function observationLine(result) {
168
+ const fg = result?.foreground;
169
+ const focus = result?.focus;
170
+ const parts = [];
171
+ if (fg && (String(fg.title ?? '').trim() !== '' || String(fg.class ?? '').trim() !== '')) {
172
+ parts.push(`前台="${str(fg.title ?? fg.class, 40)}"${fg.isTarget === false ? '(非目标窗)' : ''}`);
173
+ }
174
+ if (focus && (String(focus.name ?? '').trim() !== '' || String(focus.controlType ?? '').trim() !== '')) {
175
+ const where = result.focusInWindow === true ? '(在本窗)' : result.focusInWindow === false ? '(不在本窗)' : '';
176
+ const advice = result.focusInWindow === false ? '——焦点不在目标窗,需要输入/焦点类动作时先 resolve_window 或带 windowId 聚焦' : '';
177
+ parts.push(`焦点=${focus.controlType ?? '?'} "${str(focus.name ?? '', 24)}"${where}${advice}`);
178
+ }
179
+ if (parts.length === 0) return '';
180
+ const ms = Number(result?.ms);
181
+ const msPart = Number.isFinite(ms) && ms > 0 ? ` 采集 ${Math.round(ms)}ms` : '';
182
+ return `\n${parts.join(' ')}${msPart}`;
183
+ }
184
+
185
+ /**
186
+ * The batch-window diff note: newWindows is the worker's before/after top-level hwnd diff
187
+ * around phase 2. The indicator overlay's own pid is filtered here as well as worker-side — a
188
+ * worker that never learned the pid can still report our own capsule (it lights asynchronously at
189
+ * activity.claim), and a self-report of the overlay would be exactly the noise this warning exists
190
+ * to prevent; the fixed overlay window title is excluded too. Empty input renders '' — no diff,
191
+ * no line. Not exported (see observationLine): the harness takes it via its return expression.
192
+ */
193
+ export function newWindowNote(newWindows, indicatorPid) {
194
+ const rows = (Array.isArray(newWindows) ? newWindows : [])
195
+ .filter((w) => w && !(indicatorPid !== undefined && indicatorPid !== null && Number(w.pid) === Number(indicatorPid)))
196
+ .filter((w) => String(w.title ?? '') !== 'dsh-yuping-indicator');
197
+ if (rows.length === 0) return '';
198
+ const listed = rows.slice(0, 5).map((w) => `"${str(w.title ?? w.class ?? '?', 40)}"(pid=${w.pid ?? '?'})`).join('、');
199
+ const rest = rows.length > 5 ? ` …另 ${rows.length - 5} 个` : '';
200
+ return `\n⚠ 批次期间出现新窗口:${listed}${rest}——先确认是否弹窗/对话框并处理,避免它的按钮文本混进下一次定位。`;
201
+ }
202
+
203
+ export function preparationFailure(prepared, stepCount) {
204
+ const descriptors = prepared.descriptors ?? [];
205
+ const errors = descriptors.filter((d) => d.error || d.code);
206
+ if (prepared.allResolved === true && descriptors.length === stepCount && errors.length === 0) return '';
207
+ return `批量预检失败,尚未执行任何动作(performedCount=0)。\n${errors.map((d) => `第 ${d.index} 步:${d.code ?? 'unresolved'} ${d.error ?? ''}`).join('\n') || '预检未完整返回所有步骤。'}\n先用 find_text / snapshot 更新定位。后续目标若由前一步才生成,请拆成两批执行;动态名称可使用稳定片段和 nameExact:false。`;
208
+ }
209
+
210
+ /**
211
+ * A descriptor that only resolved by relaxing the match is not a failure — it is a warning that
212
+ * the UI text moved. Saying so turns a silent drift (the classic "回放点错还报成功") into an
213
+ * explicit instruction to re-check with find_text before trusting the batch.
214
+ *
215
+ * Two stages report drift: prepare_batch resolves once (its descriptors), and commit_batch
216
+ * re-resolves every by-step right before acting (its per-step locator fields). The commit verdict
217
+ * is the one closest to the moment of the action, so it wins; prepare-only drift is still reported
218
+ * with its stage named, instead of the caller reading a stale prepare judgement after commit.
219
+ */
220
+ /**
221
+ * The repetition watchdog's voice. Repeating one action is sometimes right (a retry after a lag),
222
+ * so the first two are silent; past that the honest reading is "this approach is not working", and
223
+ * the model is told to change method or declare the run blocked instead of burning the session.
224
+ */
225
+ export function stuckNote(kind, count) {
226
+ if (kind === 'verify' && count >= 3) {
227
+ return `\n⚠ 同一个目标同一动作已连续 ${count} 次校验未命中:这条路大概率不通。停止重复调用——重新 computer_snapshot 观察界面(元素可能已换、值已被别处改动),或改用别的元素/动作;确实被卡住就用 computer_done outcome="blocked" 说明原因。`;
228
+ }
229
+ if (kind === 'repeat' && count >= 4) {
230
+ return `\n⚠ 同一动作已重复 ${count} 次且没有新证据:继续重复不会有新结果。先观察一次(snapshot / find_text),再换目标或换方法;被卡住就 computer_done outcome="blocked"。`;
231
+ }
232
+ return '';
233
+ }
234
+
235
+ export function locatorNotes(descriptors, results = []) {
236
+ const fmt = (d) => `第 ${d.index} 步 ${d.matchedBy ?? '降级'}(${Math.round((Number(d.score) || 0) * 100)}%)`;
237
+ const drift = (rows) => (rows ?? []).filter((d) => d && d.degraded === true);
238
+ const commitDrift = drift(results);
239
+ const prepDrift = drift(descriptors).filter((d) => !commitDrift.some((r) => r.index === d.index));
240
+ const parts = [];
241
+ if (commitDrift.length > 0) parts.push(`动作时重解析 ${commitDrift.map(fmt).join('、')}`);
242
+ if (prepDrift.length > 0) parts.push(`预检时 ${prepDrift.map(fmt).join('、')}`);
243
+ if (parts.length === 0) return '';
244
+ const total = commitDrift.length + prepDrift.length;
245
+ return `\n⚠ 定位降级 ${total} 步:${parts.join(';')}。这些步骤的文字与配方不一致,只按归一化/ID 命中;执行前用 find_text 复核。`;
246
+ }
247
+
248
+ export function snapshotNotes(snap) {
249
+ const notes = [];
250
+ if (snap.truncated) notes.push('元素树已截断,可收紧过滤条件或提高 maxNodes。');
251
+ if (snap.partialReason) notes.push(`元素树仅部分可读:${Array.isArray(snap.partialReason) ? snap.partialReason.join(';') : snap.partialReason}`);
252
+ return notes.length ? `\n⚠ ${notes.join(' ')}` : '';
253
+ }
254
+
255
+ /**
256
+ * Drop pass-through containers from the RENDERED view only (refs stay valid: they were minted
257
+ * worker-side). A chain of unnamed Pane/Group/Document nodes exists to carry layout, not to be
258
+ * acted on, and it costs indentation on every child. Measured motivation: accessibility-tree
259
+ * redundancy is the dominant cost for GUI agents, and removing it raised success while cutting
260
+ * tokens sharply (A11y-Compressor, ACL 2026). Only nodes with no name AND no actionable verb are
261
+ * removed, so nothing the model can act on disappears.
262
+ */
263
+ // Exported so the find_text ladder and any consumer share ONE definition of "a container whose
264
+ // click only focuses the window" — a second copy had already drifted into a different order.
265
+ export const PASS_THROUGH = new Set(['Pane', 'Group', 'Document', 'Custom', 'Window']);
266
+
267
+ // Navigation rows and real commands, shared by find_text ranking and computer_parse's operable
268
+ // list, so the two observation channels cannot drift into disagreeing about what counts as
269
+ // clickable. NAVIGATION rows carry SelectionItem and so "look" actionable, but they are sidebar
270
+ // navigation, not the control a model is after.
271
+ export const NAVIGATION = new Set(['TreeItem', 'ListItem', 'DataItem']);
272
+ export const COMMANDS = new Set(['Button', 'MenuItem', 'Tab', 'TabItem', 'CheckBox', 'RadioButton', 'ComboBox', 'Edit', 'SplitButton', 'Hyperlink', 'Slider', 'Spinner']);
273
+
274
+ /**
275
+ * One ranking for both channels that list clickable things (5 = least clickable):
276
+ * find_text sorts its hits by it and computer_parse sorts its operable list by it. Kept as one
277
+ * function because the tiers used to exist twice and had already started to diverge.
278
+ */
279
+ export function rankMatch(m) {
280
+ if (m.isOffscreen === true) return 5; // unreachable without scrolling
281
+ if (PASS_THROUGH.has(String(m.controlType))) return 4; // containers: clicking only focuses the window
282
+ if (NAVIGATION.has(String(m.controlType))) return 3; // sidebar/list rows: navigation, not the target
283
+ if (COMMANDS.has(String(m.controlType)) && (m.patterns ?? []).some((p) => ACT_VERBS.has(p))) return 0; // a real command with a working pattern
284
+ if ((m.patterns ?? []).some((p) => ACT_VERBS.has(p))) return 1; // actionable but an unusual control type
285
+ return 2; // plain Text: readable, not clickable
286
+ }
287
+
288
+ export function elideRedundantContainers(nodes) {
289
+ const out = [];
290
+ const effByDepth = [];
291
+ for (const node of nodes) {
292
+ const depth = Math.max(0, Math.min(20, Number(node.depth ?? 0)));
293
+ const parentEff = depth === 0 ? -1 : (effByDepth[depth - 1] ?? depth - 1);
294
+ const unnamed = String(node.name ?? '').trim() === '';
295
+ const acts = (node.patterns ?? []).filter((p) => ACT_VERBS.has(p));
296
+ const redundant = unnamed && acts.length === 0 && PASS_THROUGH.has(String(node.controlType));
297
+ effByDepth[depth] = parentEff + (redundant ? 0 : 1);
298
+ if (!redundant) out.push({ ...node, depth: Math.max(0, effByDepth[depth]) });
299
+ }
300
+ return out;
301
+ }