dsh-native-uia 0.2.0 → 0.6.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 (55) hide show
  1. package/README.md +81 -398
  2. package/client/client.js +236 -48
  3. package/cordis.patch.yml +7 -8
  4. package/locale/en.json +2 -2
  5. package/locale/zh.json +2 -2
  6. package/package.json +8 -17
  7. package/scripts/check-lease.mjs +1 -1
  8. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  9. package/scripts/lib/load-tools-source.mjs +17 -16
  10. package/scripts/lib/sources.mjs +62 -0
  11. package/scripts/load-tools.mjs +74 -0
  12. package/scripts/measure-parse.mjs +2 -2
  13. package/scripts/regression-tools.mjs +155 -6
  14. package/scripts/regression-worker.ps1 +29 -0
  15. package/scripts/verify-live-style.mjs +46 -0
  16. package/scripts/verify-live.mjs +12 -18
  17. package/scripts/verify.mjs +953 -192
  18. package/src/activity-window.js +71 -7
  19. package/src/dashboard.js +27 -69
  20. package/src/guard.js +39 -10
  21. package/src/index.js +187 -77
  22. package/src/notes.js +83 -0
  23. package/src/state.js +97 -10
  24. package/src/themes.js +66 -0
  25. package/src/tools/defs/act.js +671 -0
  26. package/src/tools/defs/lifecycle.js +205 -0
  27. package/src/tools/defs/observe.js +325 -0
  28. package/src/tools/defs/pointer.js +328 -0
  29. package/src/tools/format.js +338 -0
  30. package/src/tools/index.js +125 -0
  31. package/src/tools/ocr.js +91 -0
  32. package/src/tools/recipes.js +49 -0
  33. package/src/tools/runtime.js +42 -0
  34. package/src/worker-client.js +32 -10
  35. package/worker/assets/dsh-whale.path +1 -0
  36. package/worker/indicator-server.ps1 +1107 -72
  37. package/worker/lib/01-core.ps1 +64 -0
  38. package/worker/lib/02-uia.ps1 +224 -0
  39. package/worker/lib/03-window.ps1 +194 -0
  40. package/worker/lib/04-match.ps1 +435 -0
  41. package/worker/lib/05-value.ps1 +254 -0
  42. package/worker/lib/06-snapshot.ps1 +412 -0
  43. package/worker/lib/07-action.ps1 +329 -0
  44. package/worker/lib/08-command.ps1 +1495 -0
  45. package/worker/lib/09-pointer.ps1 +840 -0
  46. package/worker/lib/10-dispatch.ps1 +132 -0
  47. package/worker/ps-stdio.ps1 +7 -2
  48. package/worker/uia-worker.ps1 +599 -4220
  49. package/locale/desktop/en.json +0 -6
  50. package/locale/desktop/zh.json +0 -6
  51. package/scripts/regression-halt-latch.mjs +0 -100
  52. package/src/native-uia-remote.js +0 -80
  53. package/src/panel-face.js +0 -14
  54. package/src/tools.js +0 -1482
  55. package/web/control.html +0 -1413
@@ -0,0 +1,338 @@
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', 'ScrollItem', '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
+ // RangeValue and ScrollItem joined when set_range / scroll_to became real verbs: before that they
23
+ // would have promised actions that did not exist.
24
+ export const ACT_VERBS = new Set(['Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'Scroll', 'RangeValue', 'ScrollItem']);
25
+
26
+ /**
27
+ * A one-line map of what is actionable, printed before the tree.
28
+ *
29
+ * In a 200-node snapshot only ~22% of nodes accept an action, and they are scattered through
30
+ * chrome the model has to read past. Naming them up front (ref + type + name) means the model can
31
+ * often pick its target from this line and go straight to computer_act, instead of scanning the
32
+ * whole tree — fewer tokens spent and fewer wrong-element guesses. Capped so it cannot become its
33
+ * own wall of text.
34
+ */
35
+ export function renderActionables(nodes, max = 24) {
36
+ const acts = nodes.filter((n) => (n.patterns ?? []).some((p) => ACT_VERBS.has(p)));
37
+ if (acts.length === 0) return '';
38
+ // Each entry is a complete "ref + controlType + name" metadata row: two same-named buttons used
39
+ // to render byte-identical, and a model reading only this line could not tell them apart. The
40
+ // center coordinate doubles as the by.nearPoint input, so same-name disambiguation no longer
41
+ // needs a second find_text pass over the whole tree.
42
+ const shown = acts.slice(0, max).map((n) => {
43
+ 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)})` : '';
44
+ return `${n.ref} ${n.controlType}${n.name && n.name.trim() ? ` "${str(n.name, 24)}"` : ''}${c}`;
45
+ });
46
+ const rest = acts.length > shown.length ? ` …另 ${acts.length - shown.length} 个` : '';
47
+ return `可操作元素 ${acts.length} 个(@=中心坐标,同名时可直接填进 by.nearPoint 消歧):${shown.join('、')}${rest}\n`;
48
+ }
49
+
50
+ /**
51
+ * The node's own state, in the same line as the node.
52
+ *
53
+ * Before this, a snapshot carried one string per node (`value`), so a checked and an unchecked
54
+ * checkbox rendered identically, a selected tab looked like any other tab, an expanded tree node
55
+ * and a collapsed one were the same row, and a slider at 40% said "40" with no range to judge it
56
+ * against. These come from the worker's cached patterns, so they cost no extra round-trip.
57
+ */
58
+ function stateText(st) {
59
+ if (!st || typeof st !== 'object') return '';
60
+ const bits = [];
61
+ if (st.toggle) bits.push(String(st.toggle));
62
+ if (st.selected === true) bits.push('选中');
63
+ if (st.expanded) bits.push(String(st.expanded));
64
+ if (st.range && Number.isFinite(Number(st.range.value))) {
65
+ const r = st.range;
66
+ const range = Number.isFinite(Number(r.min)) && Number.isFinite(Number(r.max))
67
+ ? `/${Math.round(Number(r.min))}-${Math.round(Number(r.max))}`
68
+ : '';
69
+ bits.push(`${Math.round(Number(r.value))}${range}`);
70
+ }
71
+ if (st.scroll) {
72
+ const axis = (v) => (Number(v) >= 0 ? `${Math.round(Number(v))}%` : '-');
73
+ bits.push(`滚动 ${axis(st.scroll.h)}/${axis(st.scroll.v)}`);
74
+ }
75
+ if (bits.length === 0) return '';
76
+ return ` {${bits.join(' ')}}`;
77
+ }
78
+
79
+ export function renderTree(nodes, { compact = false, elide = true } = {}) {
80
+ if (nodes.length === 0) return '快照返回 0 个元素';
81
+ const shown = elide ? elideRedundantContainers(nodes) : nodes;
82
+ const lines = shown.length > 0 ? shown : nodes;
83
+ return lines
84
+ .map((n) => {
85
+ const pad = ' '.repeat(Math.min(n.depth ?? 0, 10));
86
+ const acts = (n.patterns ?? []).filter((p) => ACTIONABLE.has(p));
87
+ // `disabled` and `offscreen` are the two flags that change whether acting makes sense; the
88
+ // compact form still carries them because they are decision-relevant, unlike class names.
89
+ const flags = [n.enabled === false ? 'disabled' : '', n.isOffscreen === true ? 'offscreen' : ''].filter(Boolean).join(' ');
90
+ const st = stateText(n.state);
91
+ // A toggle/expand node's state already IS its value (the worker reads ToggleState as the
92
+ // value); printing both would make one fact look like two.
93
+ const value = n.value === undefined || n.value === '' || (st && (n.state?.toggle === n.value || n.state?.expanded === n.value))
94
+ ? ''
95
+ : ` val="${str(n.value, compact ? 24 : 40)}"`;
96
+ const pat = acts.length === 0 ? '' : ` [${acts.join(',')}]`;
97
+ const name = str(n.name, compact ? 32 : 48);
98
+ // Where the walk stopped, per node: this is the exact element to drill into with root=<ref>.
99
+ const cut = n.cut === true ? ' [cut]' : '';
100
+ return `${pad}${n.ref} ${n.controlType} "${name}"${value}${st}${pat}${flags ? ` ${flags}` : ''}${cut}`;
101
+ })
102
+ .join('\n');
103
+ }
104
+
105
+ /**
106
+ * Per-verb inline verify suggestions for the "nothing observable changed" branches of
107
+ * renderEffect. The type set is aligned with the worker's verify evaluator (Eval-Once — the same
108
+ * evaluator serves act's verify channel and wait), and a verb only gets the types whose effect it
109
+ * can actually make observable: set_value/text_append end in the element's reading, toggle shows
110
+ * up as a reading change or in IsEnabled. Button verbs (invoke/expand/collapse/...) have no
111
+ * assertable reading, so suggesting value_changed for them would only produce verify checks that
112
+ * never match — those keep the plain re-observe advice.
113
+ */
114
+ export const VERIFY_HINT = {
115
+ set_value: ['value_equals'],
116
+ text_append: ['value_equals'],
117
+ toggle: ['value_changed', 'enabled_is'],
118
+ };
119
+
120
+ /**
121
+ * Say what the action demonstrably changed, instead of letting "no error" read as "it worked".
122
+ * Act-effect verification is the load-bearing idea in recent GUI-agent work (verify the effect
123
+ * rather than trust the click). We only claim what the worker actually observed: a verify matcher
124
+ * fired, the element's value changed, or nothing observable changed — the last case is a hint to
125
+ * add a verify condition (for verbs with an observable effect, one call settles it) or re-observe,
126
+ * not a failure, because most buttons legitimately change no element property.
127
+ */
128
+ export function renderEffect(r) {
129
+ if (r.performed !== true) return '';
130
+ if (r.verify) return r.verify.matched === true ? ' 效果=校验命中' : ' 效果=校验未命中';
131
+ const hint = VERIFY_HINT[String(r.action ?? '')];
132
+ const tip = hint
133
+ ? `;如需确定性判据,加 verify:{type:"${hint[0]}"}${hint[1] ? `(或 ${hint[1]})` : ''}`
134
+ : '';
135
+ const hasValue = (r.before ?? '') !== '' || (r.after ?? '') !== '';
136
+ if (!hasValue) return ` 效果=无可观测属性变化(已送达${tip})`;
137
+ return r.before === r.after ? ` 效果=属性未变(已送达${tip})` : ' 效果=属性已变';
138
+ }
139
+
140
+ // Single source for the not_executed wording: the worker ships only the status, and BOTH batch
141
+ // tools render the tail through renderResults — one constant here keeps computer_run and
142
+ // computer_replay from drifting apart.
143
+ export const NOT_EXECUTED_TEXT = '未执行:前序步骤失败/被取消';
144
+
145
+ export function renderResults(results, performed) {
146
+ const lines = results.map((r) => {
147
+ // 'not_executed' is the worker's placeholder for steps a stop/cancel never reached: every
148
+ // planned step must appear in the reply with the same fixed wording, so the model can see
149
+ // WHICH tail was skipped instead of inferring it from performedCount alone.
150
+ const notExecuted = r.status === 'not_executed';
151
+ const mark = r.status === 'passed' ? '通过' : notExecuted ? '未执行' : r.status;
152
+ const verify = r.verify ? ` 校验=${r.verify.matched === true ? '命中' : '未命中'}(${r.verify.type ?? '?'})` : '';
153
+ const delivered = r.performed === true && r.status !== 'passed' ? '(动作已执行,勿直接重试)' : '';
154
+ // commit re-resolves every by-step right before acting, so this per-step verdict is the
155
+ // truth closest to the moment of the action — render it inline instead of dropping it.
156
+ const locator = r.degraded === true ? ` 定位=${r.matchedBy ?? '?'}(${Math.round((Number(r.score) || 0) * 100)}%)` : '';
157
+ const detail = notExecuted ? NOT_EXECUTED_TEXT : r.detail;
158
+ return `${mark} 第 ${r.index} 步 ${r.action ?? ''} ${r.ref ?? ''}${delivered} 耗时 ${r.ms ?? '?'}ms${verify}${locator}${renderEffect(r)}${detail ? ` ${str(detail, 90)}` : ''}`;
159
+ });
160
+ const unverified = results.filter((r) => r.performed === true && !r.verify).length;
161
+ const tail = unverified > 0
162
+ ? `\nperformedCount=${performed}(其中 ${unverified} 步没有校验条件:结果只代表已送达,不代表界面已按预期改变)`
163
+ : `\nperformedCount=${performed}`;
164
+ // Four-state tally so the model does not re-count the lines itself: a batch reply used to give
165
+ // only performedCount, and 成功/失败/校验未命中/未执行 had to be inferred per row. '校验未命中'
166
+ // keeps the existing contract wording: the action WAS delivered — do not blindly retry it.
167
+ const passedCount = results.filter((r) => r.status === 'passed').length;
168
+ const verifyMissedCount = results.filter((r) => r.status === 'verify_failed').length;
169
+ const notExecutedCount = results.filter((r) => r.status === 'not_executed').length;
170
+ const failedResults = results.filter((r) => r.status !== 'passed' && r.status !== 'verify_failed' && r.status !== 'not_executed');
171
+ const firstFail = failedResults[0];
172
+ const firstReason = firstFail ? `(首条原因:第 ${firstFail.index} 步 ${str(firstFail.detail, 60)})` : '';
173
+ const tally = `批次汇总:通过 ${passedCount} / 失败 ${failedResults.length}${firstReason} / 校验未命中 ${verifyMissedCount} / 未执行 ${notExecutedCount}`;
174
+ return `${lines.join('\n')}${tail}\n${tally}`;
175
+ }
176
+
177
+ /**
178
+ * One line per stop, and the wording must MATCH THE REASON. A failed/verify_failed stop means
179
+ * "the desktop drifted: re-observe and continue". status='cancelled' is the opposite instruction —
180
+ * the user pressed Esc to STOP, so the model must pause and ask, not auto-resume. The worker
181
+ * always reported that status; the run path just dropped it on the floor and printed the
182
+ * "continue" wording for both.
183
+ */
184
+ export function stoppedNote(committed) {
185
+ const stoppedAt = committed?.stoppedAt;
186
+ if (stoppedAt === null || stoppedAt === undefined) return '';
187
+ if (committed.status === 'cancelled') {
188
+ return `\n用户按 Esc 终止了本轮(第 ${stoppedAt} 步及其后的步骤未执行):请暂停并向用户确认是否继续,不要自动续跑。`;
189
+ }
190
+ return `\n在第 ${stoppedAt} 步停下:先重新 computer_snapshot 再继续,桌面状态可能已经和你规划时不一样了。`;
191
+ }
192
+
193
+ /**
194
+ * One observation-metadata line for snapshot/find_text heads: where the desktop foreground is,
195
+ * where the UIA focus sits, and whether that focus lives in the observed window (pid comparison,
196
+ * advisory — a multi-process host can misreport). The next observation after a click/type carries
197
+ * free proof of whether the action took effect: the focus moved into (or out of) the window. Every
198
+ * field is advisory — the worker omits any of them when its probe fails, and this renders only
199
+ * what arrived. A focus outside the target window gets the one-line fix. Everything goes through
200
+ * str() so a long window title cannot blow the line. Deliberately NOT exported: the
201
+ * regression harness (scripts/lib/load-tools-source.mjs) strips only known exports, so an export
202
+ * here would break every loader consumer — it picks these up through its return expression.
203
+ */
204
+ export function observationLine(result) {
205
+ const fg = result?.foreground;
206
+ const focus = result?.focus;
207
+ const parts = [];
208
+ if (fg && (String(fg.title ?? '').trim() !== '' || String(fg.class ?? '').trim() !== '')) {
209
+ parts.push(`前台="${str(fg.title ?? fg.class, 40)}"${fg.isTarget === false ? '(非目标窗)' : ''}`);
210
+ }
211
+ if (focus && (String(focus.name ?? '').trim() !== '' || String(focus.controlType ?? '').trim() !== '')) {
212
+ const where = result.focusInWindow === true ? '(在本窗)' : result.focusInWindow === false ? '(不在本窗)' : '';
213
+ const advice = result.focusInWindow === false ? '——焦点不在目标窗,需要输入/焦点类动作时先 resolve_window 或带 windowId 聚焦' : '';
214
+ parts.push(`焦点=${focus.controlType ?? '?'} "${str(focus.name ?? '', 24)}"${where}${advice}`);
215
+ }
216
+ if (parts.length === 0) return '';
217
+ const ms = Number(result?.ms);
218
+ const msPart = Number.isFinite(ms) && ms > 0 ? ` 采集 ${Math.round(ms)}ms` : '';
219
+ return `\n${parts.join(' ')}${msPart}`;
220
+ }
221
+
222
+ /**
223
+ * The batch-window diff note: newWindows is the worker's before/after top-level hwnd diff
224
+ * around phase 2. The indicator overlay's own pid is filtered here as well as worker-side — a
225
+ * worker that never learned the pid can still report our own capsule (it lights asynchronously at
226
+ * activity.claim), and a self-report of the overlay would be exactly the noise this warning exists
227
+ * to prevent; the fixed overlay window title is excluded too. Empty input renders '' — no diff,
228
+ * no line. Not exported (see observationLine): the harness takes it via its return expression.
229
+ */
230
+ export function newWindowNote(newWindows, indicatorPid) {
231
+ const rows = (Array.isArray(newWindows) ? newWindows : [])
232
+ .filter((w) => w && !(indicatorPid !== undefined && indicatorPid !== null && Number(w.pid) === Number(indicatorPid)))
233
+ .filter((w) => String(w.title ?? '') !== 'dsh-yuping-indicator');
234
+ if (rows.length === 0) return '';
235
+ const listed = rows.slice(0, 5).map((w) => `"${str(w.title ?? w.class ?? '?', 40)}"(pid=${w.pid ?? '?'})`).join('、');
236
+ const rest = rows.length > 5 ? ` …另 ${rows.length - 5} 个` : '';
237
+ return `\n⚠ 批次期间出现新窗口:${listed}${rest}——先确认是否弹窗/对话框并处理,避免它的按钮文本混进下一次定位。`;
238
+ }
239
+
240
+ export function preparationFailure(prepared, stepCount) {
241
+ const descriptors = prepared.descriptors ?? [];
242
+ const errors = descriptors.filter((d) => d.error || d.code);
243
+ if (prepared.allResolved === true && descriptors.length === stepCount && errors.length === 0) return '';
244
+ return `批量预检失败,尚未执行任何动作(performedCount=0)。\n${errors.map((d) => `第 ${d.index} 步:${d.code ?? 'unresolved'} ${d.error ?? ''}`).join('\n') || '预检未完整返回所有步骤。'}\n先用 find_text / snapshot 更新定位。后续目标若由前一步才生成,请拆成两批执行;动态名称可使用稳定片段和 nameExact:false。`;
245
+ }
246
+
247
+ /**
248
+ * A descriptor that only resolved by relaxing the match is not a failure — it is a warning that
249
+ * the UI text moved. Saying so turns a silent drift (the classic "回放点错还报成功") into an
250
+ * explicit instruction to re-check with find_text before trusting the batch.
251
+ *
252
+ * Two stages report drift: prepare_batch resolves once (its descriptors), and commit_batch
253
+ * re-resolves every by-step right before acting (its per-step locator fields). The commit verdict
254
+ * is the one closest to the moment of the action, so it wins; prepare-only drift is still reported
255
+ * with its stage named, instead of the caller reading a stale prepare judgement after commit.
256
+ */
257
+ /**
258
+ * The repetition watchdog's voice. Repeating one action is sometimes right (a retry after a lag),
259
+ * so the first two are silent; past that the honest reading is "this approach is not working", and
260
+ * the model is told to change method or declare the run blocked instead of burning the session.
261
+ */
262
+ export function stuckNote(kind, count) {
263
+ if (kind === 'verify' && count >= 3) {
264
+ return `\n⚠ 同一个目标同一动作已连续 ${count} 次校验未命中:这条路大概率不通。停止重复调用——重新 computer_snapshot 观察界面(元素可能已换、值已被别处改动),或改用别的元素/动作;确实被卡住就用 computer_done outcome="blocked" 说明原因。`;
265
+ }
266
+ if (kind === 'repeat' && count >= 4) {
267
+ return `\n⚠ 同一动作已重复 ${count} 次且没有新证据:继续重复不会有新结果。先观察一次(snapshot / find_text),再换目标或换方法;被卡住就 computer_done outcome="blocked"。`;
268
+ }
269
+ return '';
270
+ }
271
+
272
+ export function locatorNotes(descriptors, results = []) {
273
+ const fmt = (d) => `第 ${d.index} 步 ${d.matchedBy ?? '降级'}(${Math.round((Number(d.score) || 0) * 100)}%)`;
274
+ const drift = (rows) => (rows ?? []).filter((d) => d && d.degraded === true);
275
+ const commitDrift = drift(results);
276
+ const prepDrift = drift(descriptors).filter((d) => !commitDrift.some((r) => r.index === d.index));
277
+ const parts = [];
278
+ if (commitDrift.length > 0) parts.push(`动作时重解析 ${commitDrift.map(fmt).join('、')}`);
279
+ if (prepDrift.length > 0) parts.push(`预检时 ${prepDrift.map(fmt).join('、')}`);
280
+ if (parts.length === 0) return '';
281
+ const total = commitDrift.length + prepDrift.length;
282
+ return `\n⚠ 定位降级 ${total} 步:${parts.join(';')}。这些步骤的文字与配方不一致,只按归一化/ID 命中;执行前用 find_text 复核。`;
283
+ }
284
+
285
+ export function snapshotNotes(snap) {
286
+ const notes = [];
287
+ if (snap.truncated) notes.push('元素树已截断,可收紧过滤条件或提高 maxNodes。');
288
+ if (snap.partialReason) notes.push(`元素树仅部分可读:${Array.isArray(snap.partialReason) ? snap.partialReason.join(';') : snap.partialReason}`);
289
+ return notes.length ? `\n⚠ ${notes.join(' ')}` : '';
290
+ }
291
+
292
+ /**
293
+ * Drop pass-through containers from the RENDERED view only (refs stay valid: they were minted
294
+ * worker-side). A chain of unnamed Pane/Group/Document nodes exists to carry layout, not to be
295
+ * acted on, and it costs indentation on every child. Measured motivation: accessibility-tree
296
+ * redundancy is the dominant cost for GUI agents, and removing it raised success while cutting
297
+ * tokens sharply (A11y-Compressor, ACL 2026). Only nodes with no name AND no actionable verb are
298
+ * removed, so nothing the model can act on disappears.
299
+ */
300
+ // Exported so the find_text ladder and any consumer share ONE definition of "a container whose
301
+ // click only focuses the window" — a second copy had already drifted into a different order.
302
+ export const PASS_THROUGH = new Set(['Pane', 'Group', 'Document', 'Custom', 'Window']);
303
+
304
+ // Navigation rows and real commands, shared by find_text ranking and computer_parse's operable
305
+ // list, so the two observation channels cannot drift into disagreeing about what counts as
306
+ // clickable. NAVIGATION rows carry SelectionItem and so "look" actionable, but they are sidebar
307
+ // navigation, not the control a model is after.
308
+ export const NAVIGATION = new Set(['TreeItem', 'ListItem', 'DataItem']);
309
+ export const COMMANDS = new Set(['Button', 'MenuItem', 'Tab', 'TabItem', 'CheckBox', 'RadioButton', 'ComboBox', 'Edit', 'SplitButton', 'Hyperlink', 'Slider', 'Spinner']);
310
+
311
+ /**
312
+ * One ranking for both channels that list clickable things (5 = least clickable):
313
+ * find_text sorts its hits by it and computer_parse sorts its operable list by it. Kept as one
314
+ * function because the tiers used to exist twice and had already started to diverge.
315
+ */
316
+ export function rankMatch(m) {
317
+ if (m.isOffscreen === true) return 5; // unreachable without scrolling
318
+ if (PASS_THROUGH.has(String(m.controlType))) return 4; // containers: clicking only focuses the window
319
+ if (NAVIGATION.has(String(m.controlType))) return 3; // sidebar/list rows: navigation, not the target
320
+ if (COMMANDS.has(String(m.controlType)) && (m.patterns ?? []).some((p) => ACT_VERBS.has(p))) return 0; // a real command with a working pattern
321
+ if ((m.patterns ?? []).some((p) => ACT_VERBS.has(p))) return 1; // actionable but an unusual control type
322
+ return 2; // plain Text: readable, not clickable
323
+ }
324
+
325
+ export function elideRedundantContainers(nodes) {
326
+ const out = [];
327
+ const effByDepth = [];
328
+ for (const node of nodes) {
329
+ const depth = Math.max(0, Math.min(20, Number(node.depth ?? 0)));
330
+ const parentEff = depth === 0 ? -1 : (effByDepth[depth - 1] ?? depth - 1);
331
+ const unnamed = String(node.name ?? '').trim() === '';
332
+ const acts = (node.patterns ?? []).filter((p) => ACT_VERBS.has(p));
333
+ const redundant = unnamed && acts.length === 0 && PASS_THROUGH.has(String(node.controlType));
334
+ effByDepth[depth] = parentEff + (redundant ? 0 : 1);
335
+ if (!redundant) out.push({ ...node, depth: Math.max(0, effByDepth[depth]) });
336
+ }
337
+ return out;
338
+ }
@@ -0,0 +1,125 @@
1
+ import { POLICY } from '../guard.js';
2
+ import { join } from 'node:path';
3
+ import { idleTimeoutMs } from './runtime.js';
4
+ import { NOT_EXECUTED_TEXT } from './format.js';
5
+ import { saveRecipe, listRecipes, loadRecipe } from './recipes.js';
6
+ import { registerObserve } from './defs/observe.js';
7
+ import { registerAct } from './defs/act.js';
8
+ import { registerPointer } from './defs/pointer.js';
9
+ import { registerLifecycle } from './defs/lifecycle.js';
10
+
11
+ export function registerTools(ctx, { worker, store, dataDir, owned, finishRun: finishRunInner, activity, ensureArmed }) {
12
+ const recipeDir = join(dataDir, 'recipes');
13
+ const disposers = [];
14
+
15
+ /**
16
+ * Turn-end without a turn hook.
17
+ *
18
+ * The host exposes no public "the agent finished this turn" event a plugin can subscribe to
19
+ * (afterResponse is ACP-internal), so the run cannot be closed from a callback. What IS
20
+ * observable is the thing that actually matters: whether the model is still driving the
21
+ * desktop. Every tool call in this file goes through `touch()`, so a model that stops calling
22
+ * tools starts a countdown instead of leaving the capsule up until the 300 s lease expires —
23
+ * the "agent 用完御屏后不会主动关闭" complaint. The lease stays the outer backstop; this is the
24
+ * faster inner one, and it fires only while a run is actually lit.
25
+ *
26
+ * Deliberately NOT a heartbeat: it never renews anything. It is armed by work and disarmed by
27
+ * finishing, so an idle session cannot keep the overlay alive.
28
+ */
29
+ // `|| 20000` keeps a malformed env value (NaN) from making setTimeout fire immediately and tear
30
+ // down a run the moment it starts; the floor keeps negative values from doing the same.
31
+ const idleMs = idleTimeoutMs();
32
+ let idleTimer = null;
33
+ const disarmIdle = () => {
34
+ if (idleTimer !== null) clearTimeout(idleTimer);
35
+ idleTimer = null;
36
+ };
37
+ const touch = () => {
38
+ disarmIdle();
39
+ // Only arm while the overlay is lit: a read-only session that never started a run must not
40
+ // schedule a teardown for a run that does not exist.
41
+ if (store.running !== true) return;
42
+ idleTimer = setTimeout(fireIdle, idleMs);
43
+ idleTimer.unref?.();
44
+ };
45
+ const fireIdle = () => {
46
+ idleTimer = null;
47
+ if (store.running !== true) return;
48
+ // A command still in flight (40 s OCR, a long run) is not silence: without this guard the
49
+ // timer fired under a live action, finished the run out from under it, and the next action
50
+ // re-claimed — the capsule visibly flickered. Re-arm once; the wrapper's touch() after the
51
+ // command returns re-arms it properly anyway.
52
+ if (store.busy === true) {
53
+ idleTimer = setTimeout(fireIdle, idleMs);
54
+ idleTimer.unref?.();
55
+ return;
56
+ }
57
+ store.line(`工具调用已静默 ${Math.round(idleMs / 1000)} 秒,自动收尾本轮`, 'info');
58
+ void finishRun({ summary: '', reason: 'idle' });
59
+ };
60
+
61
+ const refuse = (outcome, extra) => {
62
+ store.counters.refused++;
63
+ const entry = store.block({
64
+ reason: `策略拒绝:${outcome.refusal}`,
65
+ raw: extra ?? null,
66
+ });
67
+ // One wording for every refusal: the policy has no interactive verdict, so a refusal always
68
+ // means "this will not happen through this plugin".
69
+ return `[已拦截 ${entry.id}] ${outcome.refusal} 被本插件策略禁止。${outcome.advice}`;
70
+ };
71
+
72
+ /**
73
+ * One registration point, so "did the model touch the desktop?" is answered once for all
74
+ * twenty-one tools instead of in every execute(). The wrapper keeps the original `this`, the
75
+ * marker that `defineTool` puts on the definition, and the return value; it only observes.
76
+ */
77
+ const register = (definition) => {
78
+ const execute = definition.execute;
79
+ if (typeof execute === 'function') {
80
+ definition.execute = async function wrapped(args, exec) {
81
+ touch();
82
+ try {
83
+ return await execute.call(this, args, exec);
84
+ } finally {
85
+ touch();
86
+ }
87
+ };
88
+ }
89
+ return ctx.tools.register(definition);
90
+ };
91
+
92
+ // A held mouse button outliving the run turns the whole desktop into a drag surface, so every
93
+ // path that ends a run (computer_done, the panel's stop, idle self-close) releases first. The
94
+ // wrapper is the only place that sees all of them.
95
+ const releaseHeldButtons = async () => {
96
+ for (const button of [...store.heldButtons]) {
97
+ try { await worker.call('pointer_mouse', { action: 'up', button }, { timeoutMs: 4000 }); } catch { /* worker gone: nothing to release */ }
98
+ store.heldButtons.delete(button);
99
+ }
100
+ };
101
+ const finishRun = async (args) => {
102
+ await releaseHeldButtons();
103
+ store.clearAttempts?.();
104
+ // The host always supplies the owner callback; the test fixtures do not, and computer_done has
105
+ // always tolerated that (a run with no owner simply has nothing to collapse).
106
+ if (typeof finishRunInner !== 'function') return undefined;
107
+ return finishRunInner(args);
108
+ };
109
+
110
+ const d = { ctx, worker, store, dataDir, owned, finishRun, activity, ensureArmed, recipeDir, register, refuse, touch, disarmIdle, saveRecipe, listRecipes, loadRecipe, disposers };
111
+ registerObserve(d);
112
+ registerAct(d);
113
+ registerPointer(d);
114
+ registerLifecycle(d);
115
+
116
+ return () => {
117
+ void releaseHeldButtons();
118
+ for (const dispose of disposers) dispose();
119
+ disposers.length = 0;
120
+ };
121
+ }
122
+
123
+ export { POLICY };
124
+ export { NOT_EXECUTED_TEXT };
125
+ export { idleTimeoutMs };
@@ -0,0 +1,91 @@
1
+ import { text } from './runtime.js';
2
+
3
+ export const CJK = /[\u2e80-\u9fff\uff00-\uffef\u3000-\u303f]/;
4
+ export const isCjk = (ch) => ch !== undefined && ch !== '' && CJK.test(ch);
5
+
6
+ /**
7
+ * Windows OCR emits one "word" per CJK character. Rendered raw, a single line of Chinese prose
8
+ * became dozens of one-character click targets — 542 words / 409 targets on one measured window —
9
+ * and each target is meaningless to click or to read. Rebuild visual lines from the bounding boxes
10
+ * so one target is one phrase.
11
+ *
12
+ * Grouping is deliberately conservative: same line (>=60% vertical overlap), horizontal gap no
13
+ * larger than 2.0 character widths (so separate columns never merge), and only the few recent
14
+ * lines are considered (so interleaved baselines cannot chain unrelated rows together).
15
+ */
16
+ export function groupOcrWords(words, { maxGapFactor = 2.0, lineOverlap = 0.6 } = {}) {
17
+ const usable = (words ?? []).filter((w) => w
18
+ && Number.isFinite(w.cx) && Number.isFinite(w.cy)
19
+ && w.rect && w.rect.w > 0 && w.rect.h > 0
20
+ && String(w.text ?? '').trim() !== '');
21
+ const sorted = usable.slice().sort((a, b) => (a.rect.y - b.rect.y) || (a.rect.x - b.rect.x));
22
+ const lines = [];
23
+ for (const w of sorted) {
24
+ const unit = Math.max(4, Math.min(w.rect.h, w.rect.w));
25
+ let best = null;
26
+ for (let i = lines.length - 1; i >= 0 && i >= lines.length - 4; i--) {
27
+ const candidate = lines[i];
28
+ const overlap = Math.min(candidate.rect.y + candidate.rect.h, w.rect.y + w.rect.h) - Math.max(candidate.rect.y, w.rect.y);
29
+ const minH = Math.min(candidate.rect.h, w.rect.h);
30
+ if (minH <= 0 || overlap / minH < lineOverlap) continue;
31
+ const gap = w.rect.x - (candidate.rect.x + candidate.rect.w);
32
+ if (gap > unit * maxGapFactor || gap < -unit * 2) continue;
33
+ best = candidate; break;
34
+ }
35
+ if (best === null) {
36
+ lines.push({ text: String(w.text), rect: { ...w.rect }, members: [{ cx: w.cx, cy: w.cy }] });
37
+ continue;
38
+ }
39
+ const prev = best.text;
40
+ const prevChar = prev.slice(-1);
41
+ const nextChar = String(w.text)[0];
42
+ const needsSpace = !isCjk(prevChar) && !isCjk(nextChar) && !/\s$/.test(prev);
43
+ best.text = prev + (needsSpace ? ' ' : '') + String(w.text);
44
+ best.members.push({ cx: w.cx, cy: w.cy });
45
+ const right = Math.max(best.rect.x + best.rect.w, w.rect.x + w.rect.w);
46
+ const bottom = Math.max(best.rect.y + best.rect.h, w.rect.y + w.rect.h);
47
+ best.rect.x = Math.min(best.rect.x, w.rect.x);
48
+ best.rect.y = Math.min(best.rect.y, w.rect.y);
49
+ best.rect.w = right - best.rect.x;
50
+ best.rect.h = bottom - best.rect.y;
51
+ }
52
+ return lines.map((l) => ({
53
+ text: l.text,
54
+ words: l.members.length,
55
+ members: l.members,
56
+ rect: l.rect,
57
+ cx: Math.round(l.rect.x + l.rect.w / 2),
58
+ cy: Math.round(l.rect.y + l.rect.h / 2),
59
+ }));
60
+ }
61
+
62
+ /**
63
+ * Decide which OCR text is NOT already addressable through the element tree, and where to click.
64
+ * Exported as a pure function so the same rule is used by the tool, the unit tests and the live
65
+ * A/B measurement — a rule that only exists inside a tool handler cannot be tested or compared.
66
+ */
67
+ // Exported so the measurement script compares against the SAME cover set the tool uses — a
68
+ // second copy in scripts/ had already become a divergence risk (measure-parse used to duplicate
69
+ // this list verbatim).
70
+ export const OCR_COVER = new Set(['Button', 'Edit', 'Text', 'Hyperlink', 'ListItem', 'MenuItem', 'CheckBox', 'RadioButton', 'TabItem', 'ComboBox', 'Slider', 'Spinner', 'TreeItem', 'DataItem', 'HeaderItem', 'Link']);
71
+
72
+ export function ocrCoverers(nodes) {
73
+ return (nodes ?? []).filter((n) => OCR_COVER.has(String(n.controlType))
74
+ && String(n.name ?? '').trim() !== ''
75
+ && n.rect && n.rect.w > 0 && n.rect.h > 0
76
+ && n.isOffscreen !== true);
77
+ }
78
+
79
+ export function ocrTargets(nodes, words) {
80
+ const coverers = ocrCoverers(nodes);
81
+ const inRect = (r, x, y) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
82
+ const covered = (x, y) => coverers.some((n) => inRect(n.rect, x, y));
83
+ const grouped = groupOcrWords(words);
84
+ const targets = [];
85
+ for (const ln of grouped) {
86
+ const open = (ln.members ?? []).filter((m) => !covered(m.cx, m.cy));
87
+ if (open.length === 0) continue;
88
+ targets.push({ text: ln.text, words: ln.words, openWords: open.length, cx: open[0].cx, cy: open[0].cy, rect: ln.rect });
89
+ }
90
+ return { grouped, targets, coverers };
91
+ }
@@ -0,0 +1,49 @@
1
+ import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ export function substitute(value, params) {
5
+ if (typeof value !== 'string') return value;
6
+ return value.replace(/\{\{([a-zA-Z0-9_]+)\}\}/g, (all, key) => (params[key] === undefined ? all : String(params[key])));
7
+ }
8
+
9
+ export async function saveRecipe(dir, recipe) {
10
+ await mkdir(dir, { recursive: true });
11
+ const slug = String(recipe.goal).toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'recipe';
12
+ const name = `${slug}-${Date.now()}`;
13
+ await writeFile(join(dir, `${name}.json`), JSON.stringify({ ...recipe, createdAt: new Date().toISOString() }, null, 2), 'utf8');
14
+ // Recipes are the one directory here that only ever grew: every passing batch adds one, nothing
15
+ // removed them, and each carries the full step list. Captures were already pruned to the newest
16
+ // twelve; do the same for recipes so a long-lived install cannot fill the disk. Best-effort:
17
+ // a failed prune must never fail the batch the user asked for.
18
+ //
19
+ // Ordered by the timestamp in the name, NOT lexicographically: names are `<slug>-<epoch>`, so a
20
+ // plain string sort groups by slug and would delete the newest recipe of one app while keeping
21
+ // the oldest of another.
22
+ try {
23
+ const keep = Math.max(1, Number(process.env.DSH_NATIVE_UIA_RECIPE_KEEP ?? 50));
24
+ const names = (await readdir(dir)).filter((n) => n.endsWith('.json'));
25
+ const stamp = (n) => Number(/(\d{10,})\.json$/.exec(n)?.[1] ?? 0);
26
+ names.sort((a, b) => stamp(b) - stamp(a));
27
+ for (const stale of names.slice(keep)) {
28
+ try { await unlink(join(dir, stale)); } catch { /* already gone */ }
29
+ }
30
+ } catch { /* readdir/unlink failed; the recipe is still saved */ }
31
+ return name;
32
+ }
33
+
34
+ export async function listRecipes(dir) {
35
+ try {
36
+ const names = await readdir(dir);
37
+ return names.filter((n) => n.endsWith('.json')).map((n) => n.slice(0, -5));
38
+ } catch {
39
+ return [];
40
+ }
41
+ }
42
+
43
+ export async function loadRecipe(dir, name) {
44
+ try {
45
+ return JSON.parse(await readFile(join(dir, `${name}.json`), 'utf8'));
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
@@ -0,0 +1,42 @@
1
+
2
+
3
+ export const STR = { type: 'string' };
4
+ export const INT = { type: 'integer' };
5
+ export const BOOL = { type: 'boolean' };
6
+ export const JSON_ARR = { type: 'array', items: { type: 'json' } };
7
+
8
+ export function text(value) {
9
+ return [{ type: 'text', text: value }];
10
+ }
11
+
12
+ export function str(value, max = 60) {
13
+ const s = String(value ?? '').replace(/\s+/g, ' ').trim();
14
+ return s.length > max ? `${s.slice(0, max - 1)}~` : s;
15
+ }
16
+
17
+ export function windowOf(store, windowId) {
18
+ return store.windows.find((w) => w.windowId === String(windowId)) ?? null;
19
+ }
20
+
21
+ export async function aborted(signal) {
22
+ if (signal?.aborted === true) {
23
+ const error = new Error('cancelled by the caller; any action already delivered to the desktop is not rolled back');
24
+ error.code = 'cancelled';
25
+ throw error;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * The idle self-close window, in ms. One definition because two readers need the same number: the
31
+ * countdown itself, and the config block on the plugin page that reports what is in force.
32
+ */
33
+ export function idleTimeoutMs() {
34
+ return Math.max(1000, Number(process.env.DSH_NATIVE_UIA_IDLE_MS ?? 20000) || 20000);
35
+ }
36
+
37
+ /**
38
+ * The single source for the permission-gate refusal wording. Three tool domains (act, pointer,
39
+ * lifecycle) end a disallowed delivery with this same sentence — it was duplicated seven times
40
+ * before, which is exactly how the copies drift apart.
41
+ */
42
+ export const DISARMED_MSG = '桌面控制未获准:本次会话只保留观察。请在输入框上方的请求卡片上选择「允许」,或把需要操控桌面的步骤交回给用户执行。';