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,533 @@
1
+ import { classify, classifyBatch } from '../../guard.js';
2
+ import { noteHint } from '../../notes.js';
3
+ import { writeFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { defineTool } from '@deepseek-ai/dsh-tools';
6
+ import { STR, INT, BOOL, JSON_ARR, text, str, windowOf, aborted, DISARMED_MSG } from '../runtime.js';
7
+ import { renderResults, stoppedNote, newWindowNote, preparationFailure, locatorNotes, stuckNote } from '../format.js';
8
+ import { substitute, saveRecipe, listRecipes, loadRecipe } from '../recipes.js';
9
+
10
+ /**
11
+ * Tools of the act domain. Every one takes the shared `d` bundle built by registerTools: the
12
+ * register wrapper (idle touch + dispose tracking), the worker, the store and the run's finish
13
+ * hook. Policy is never decided here — `d.refuse` renders what guard.js already judged.
14
+ */
15
+ export function registerAct(d) {
16
+ const { worker, store, dataDir, activity, ensureArmed, recipeDir, register, refuse, saveRecipe, listRecipes, loadRecipe } = d;
17
+ // The blocks below keep their original indentation so the gate regexes (which were written
18
+ // against the single-file source) still match the concatenated view byte for byte.
19
+
20
+ d.disposers.push(register(defineTool({
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.',
23
+ parameters: {
24
+ windowId: { ...STR, required: true },
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' },
28
+ revision: { ...INT, description: 'The revision the ref came from; omit to use the newest snapshot' },
29
+ verify: { type: 'json', description: 'Optional {type, expect, timeoutMs} check run locally right after the action' },
30
+ scrollIntoView: { ...BOOL, description: 'when the element is offscreen, scroll it into view first (default true); false acts without moving the viewport' },
31
+ },
32
+ output: { schema: STR, render: (_args, value) => text(value) },
33
+ timeoutMs: 60000,
34
+ async execute(args, exec) {
35
+ await aborted(exec.signal);
36
+ // First delivery in the session asks the permission card (through ctx.userQuestions, with
37
+ // this call's agent so the ask routes to THIS conversation's UI). Refused/unanswered = the
38
+ // tool ends with an honest refusal instead of touching the desktop.
39
+ if (!await ensureArmed(exec.agent)) {
40
+ return DISARMED_MSG;
41
+ }
42
+ const label = `${args.action} ${args.ref}${args.value ? ` "${str(args.value, 30)}"` : ''}`;
43
+ const described = await worker.call('describe', { ref: args.ref });
44
+ const outcome = classify({ action: args.action, descriptor: described });
45
+ if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_act', ...args, descriptor: described });
46
+ const result = await worker.call('act', {
47
+ ref: args.ref,
48
+ action: args.action,
49
+ value: args.value,
50
+ revision: args.revision,
51
+ verify: args.verify,
52
+ noScrollIntoView: args.scrollIntoView === false,
53
+ mode: store.pointerMode,
54
+ // Node's 30 s default is the only hard cap otherwise: the worker widens its own budget to
55
+ // args.timeoutMs+2500, so a verify window near the tool cap would hit the Node timeout
56
+ // first and the late reply would be dropped as an unknown id.
57
+ }, { timeoutMs: 68000 });
58
+ store.actionDone(1);
59
+ // A missed verify must not read as a passed step: applied stays true (the action WAS
60
+ // delivered), but the step status, the opening word and the follow-up advice all have to
61
+ // say "delivered, not confirmed" — otherwise the model retries a click that may already
62
+ // have fired (the batch path hard-stops on verify_failed; the single path used to sail on).
63
+ const verifyMissed = result.verify != null && result.verify.matched !== true;
64
+ store.step({
65
+ label,
66
+ status: verifyMissed ? 'verify_failed' : (result.status ?? (result.applied === false ? 'failed' : 'passed')),
67
+ ms: result.ms,
68
+ verify: result.verify?.type ? `${result.verify.type}:${result.verify.matched === true ? 'matched' : 'unmatched'}` : null,
69
+ detail: result.detail,
70
+ });
71
+ // Only show before/after when the element actually has a value to show. A Button reports an
72
+ // empty Value, and printing before="" after="" invites the reader to think "nothing changed".
73
+ const hasValue = (v) => v !== undefined && v !== null && String(v) !== '';
74
+ const state = (hasValue(result.before) || hasValue(result.after))
75
+ ? ` before=${JSON.stringify(result.before ?? null)} after=${JSON.stringify(result.after ?? null)}`
76
+ : '';
77
+ // The verify verdict in the same Chinese shape the batch path renders (the old English
78
+ // "verify=value_equals:unmatched" detail was a third format for the same data), plus the
79
+ // observed reading the worker captured while waiting — that is what tells "还没生效" apart
80
+ // from "值就不对".
81
+ const verifyText = result.verify ? ` 校验=${result.verify.matched === true ? '命中' : '未命中'}(${result.verify.type ?? '?'})` : '';
82
+ const effect = result.verify ? (result.verify.matched === true ? ' 效果=校验命中' : ' 效果=校验未命中') : '';
83
+ const observed = verifyMissed && result.verify.observed !== undefined && result.verify.observed !== null
84
+ ? ` 当前读数=${JSON.stringify(result.verify.observed)}`
85
+ : '';
86
+ const missNote = verifyMissed
87
+ ? '\n⚠ 校验未命中(动作已送达):可原样重试一次;仍不生效就用 computer_find_text 重新定位(同名元素加 nth)或重新 computer_snapshot 后再操作,不要连续盲重试。'
88
+ : '';
89
+ // A warning must name a real failure. before===after is NOT one: `before`/`after` read the
90
+ // element's Value, and a Button has no Value at all — so every successful invoke on a normal
91
+ // button reported before="" after="" and got flagged as "no state change". The honest test is
92
+ // the element's own capabilities: if it exposes no pattern for this verb, the call could not
93
+ // have done anything; if it does, the pattern ran and the caller should verify with `verify`
94
+ // (or a fresh snapshot) rather than be told its action was a no-op.
95
+ // Only patterns the managed UIA client can actually obtain (they must exist in the worker's
96
+ // $patternTypes table, which has no LegacyIAccessible entry — there is no managed type for
97
+ // it, so listing it here made the invoke/set_value checks pass on a name GetPattern could
98
+ // never resolve; the same logic rules out ScrollItem, which the worker's scroll path does
99
+ // not fetch either). focus is deliberately absent: it needs no pattern at all (plain
100
+ // SetFocus), and requiring one made every focus call read as incapable.
101
+ const NEEDED = {
102
+ invoke: ['Invoke'],
103
+ set_value: ['Value'],
104
+ text_append: ['Value'],
105
+ toggle: ['Toggle'],
106
+ select: ['SelectionItem'],
107
+ expand: ['ExpandCollapse'],
108
+ collapse: ['ExpandCollapse'],
109
+ scroll_up: ['Scroll'],
110
+ scroll_down: ['Scroll'],
111
+ };
112
+ const have = Array.isArray(described?.availablePatterns) ? described.availablePatterns : [];
113
+ const need = NEEDED[String(args.action)] ?? [];
114
+ const capable = need.length === 0 || need.some((p) => have.includes(p));
115
+ const noop = result.applied === false || !capable;
116
+ // Two different failures get two different words: "applied=false" is the worker saying the
117
+ // action was NOT delivered; a missing pattern in the capability table means it WAS delivered
118
+ // (via=uia) but may have done nothing — saying "已执行…没有真正执行" to that case read as a
119
+ // contradiction, so the honest wording names the uncertainty instead.
120
+ const warn = noop
121
+ ? (result.applied === false
122
+ ? `\n⚠ 这一步没有真正执行:worker 报告动作未送达(applied=false)。`
123
+ : `\n⚠ 能力存疑:${args.ref}(${described?.controlType ?? '未知类型'})的能力表里没有 ${args.action} 所需的 pattern(需要 ${need.join(' 或 ')}),它支持 [${have.join(',') || '无'}]。`
124
+ + `动作已按 ${result.via ?? 'uia'} 送达,但可能没有生效——请加 verify 或重新快照确认界面后再继续;`
125
+ + `或改用支持该动作的元素(例如这类元素通常用 focus 或直接 click 坐标)。`)
126
+ : '';
127
+ // An offscreen target is normal in long lists: the worker scrolls it into view before acting,
128
+ // and saying so keeps the fresh snapshot (new scroll position) from looking unexplained.
129
+ const scrollNote = result.scrolled === true ? ' 已先滚动到可见位置' : '';
130
+ // Repetition watchdog: a missed verify on the same ref+action is retried at most twice for
131
+ // free; the third time the reply says the approach is not working instead of inviting a loop.
132
+ const tally = store.noteAttempt(`act:${args.action}:${args.ref}`, !verifyMissed && result.applied !== false);
133
+ const stuck = stuckNote(verifyMissed ? 'verify' : 'repeat', verifyMissed ? tally.misses : tally.total);
134
+ return `${result.applied === false ? '未执行' : verifyMissed ? '⚠ 校验未命中(动作已送达,勿直接重试)' : '已执行'} ${label},耗时 ${result.ms ?? '?'}ms${scrollNote}${state}${verifyText}${effect}${observed}${result.detail && !result.verify ? ` ${str(result.detail, 160)}` : ''}${missNote}${warn}${stuck}`;
135
+ },
136
+ })));
137
+
138
+
139
+ // Lazy mode: resolve → policy-check → deliver each step on its own, so step N+1 may target UI that
140
+ // step N just created (menu items, dialogs, a row that only exists after a search). The classic
141
+ // batch must resolve every target up front and therefore cannot express that flow at all.
142
+ const runLazy = async (args, steps, exec) => {
143
+ // Same gate as computer_act: the first delivery of the session asks via the permission card.
144
+ if (!await ensureArmed(exec?.agent, exec.signal)) {
145
+ return DISARMED_MSG;
146
+ }
147
+ const results = [];
148
+ const descriptors = [];
149
+ const newWindows = [];
150
+ let performed = 0;
151
+ let stopReason = '';
152
+ let stopIndex = -1;
153
+ for (let i = 0; i < steps.length; i++) {
154
+ await aborted(exec.signal);
155
+ if (store.killed === true) { stopReason = '用户已终止本轮(Esc/面板)'; stopIndex = i; break; }
156
+ const one = [steps[i]];
157
+ const label = `第 ${i + 1} 步 ${steps[i]?.action ?? '?'}`;
158
+ let prep = null;
159
+ try {
160
+ prep = await worker.call('prepare_batch', { steps: one, windowId: args.windowId }, { timeoutMs: 60000 });
161
+ } catch (error) {
162
+ const detail = `resolve 失败(${error?.code ?? 'worker_error'}):${error?.message ?? error}。这一步没有执行。`;
163
+ results.push({ index: i, action: steps[i]?.action, status: 'failed', detail });
164
+ store.step({ label, kind: 'batch', status: 'failed', detail });
165
+ stopReason = detail; stopIndex = i; break;
166
+ }
167
+ const prepError = preparationFailure(prep, 1);
168
+ if (prepError) {
169
+ results.push({ index: i, action: steps[i]?.action, status: 'failed', detail: prepError });
170
+ store.step({ label, kind: 'batch', status: 'failed', detail: prepError });
171
+ stopReason = prepError; stopIndex = i; break;
172
+ }
173
+ const desc = prep.descriptors ?? [];
174
+ descriptors.push(desc[0] ?? null);
175
+ const single = classify({ action: steps[i]?.action, descriptor: desc[0] });
176
+ const deny = single.verdict === 'deny' ? { ...single, index: 0 } : null;
177
+ if (deny) {
178
+ const detail = `策略拒绝:${deny.refusal}`;
179
+ results.push({ index: i, action: steps[i]?.action, status: 'blocked', detail });
180
+ store.step({ label, kind: 'batch', status: 'blocked', detail });
181
+ stopReason = `${refuse(deny, { tool: 'computer_run', goal: args.goal, stepIndex: i, step: steps[i], descriptor: desc[0] ?? null })}`;
182
+ stopIndex = i; break;
183
+ }
184
+ let commit = null;
185
+ try {
186
+ commit = await worker.call('commit_batch', { revision: prep.revision, steps: one, windowId: args.windowId, mode: store.pointerMode, indicatorPid: activity?.indicator?.proc?.pid ?? 0 }, { timeoutMs: 60000 });
187
+ } catch (error) {
188
+ const code = String(error?.code ?? '');
189
+ const detail = code === 'worker_dead'
190
+ ? `${store.killed === true ? '用户已终止本轮(Esc/面板)' : 'worker 进程中途停止'}:这一步在飞时被打断,已完成动作不回滚。`
191
+ : `deliver 失败(${code || 'worker_error'}):${error?.message ?? error}。这一步未送达。`;
192
+ results.push({ index: i, action: steps[i]?.action, status: 'failed', detail });
193
+ store.step({ label, kind: 'batch', status: 'failed', detail });
194
+ stopReason = detail; stopIndex = i; break;
195
+ }
196
+ const r = (commit.results ?? [])[0] ?? { status: 'failed', detail: 'no result' };
197
+ results.push({ ...r, index: i });
198
+ if (Array.isArray(commit.newWindows)) newWindows.push(...commit.newWindows);
199
+ performed += commit.performedCount ?? (r.performed === true ? 1 : 0);
200
+ store.step({ label: `${label} ${r.ref ?? ''}`, status: r.status, ms: r.ms, verify: r.verify, detail: r.detail });
201
+ if (r.status !== 'passed') { stopReason = `第 ${i + 1} 步未通过(${r.status})`; stopIndex = i; break; }
202
+ }
203
+ store.actionDone(performed);
204
+ const allPassed = stopIndex === -1 && results.length === steps.length && results.every((r) => r.status === 'passed');
205
+ let recipeNote = '';
206
+ if (allPassed && args.saveRecipe !== false) {
207
+ const name = await saveRecipe(recipeDir, {
208
+ goal: args.goal,
209
+ window: descriptors[0]?.ownerWindow ?? windowOf(store, args.windowId),
210
+ revision: null,
211
+ steps: steps.map((step, i) => ({
212
+ action: step.action,
213
+ value: step.value,
214
+ verify: step.verify,
215
+ by: step.by ? structuredClone(step.by) : recipeBy(descriptors[i] ?? {}),
216
+ })),
217
+ });
218
+ recipeNote = `\n已存配方:${name}(之后用 computer_replay 回放)`;
219
+ }
220
+ const stop = stopIndex === -1
221
+ ? ''
222
+ : `\n逐段执行在第 ${stopIndex + 1} 步停止:${str(stopReason, 200)}\n剩余 ${steps.length - stopIndex - 1} 步未执行;已送达的动作不回滚,重新观察后从第 ${stopIndex + 1} 步续跑。`;
223
+ const mode = '\n(逐段模式:每步单独解析与校验,后一步可以用前一步刚创建的元素)';
224
+ return `${renderResults(results, performed)}${stop}${recipeNote}${newWindowNote(newWindows, activity?.indicator?.proc?.pid ?? 0)}${locatorNotes(descriptors, results)}${mode}`;
225
+ };
226
+
227
+ d.disposers.push(register(defineTool({
228
+ 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.',
230
+ parameters: {
231
+ windowId: { ...STR, required: true },
232
+ 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?}]' },
234
+ 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
+ saveRecipe: { ...BOOL, description: 'Save a replayable recipe when every step passes (default true)' },
236
+ },
237
+ output: { schema: STR, render: (_args, value) => text(value) },
238
+ timeoutMs: 180000,
239
+ async execute(args, exec) {
240
+ await aborted(exec.signal);
241
+ if (!await ensureArmed(exec?.agent, exec.signal)) {
242
+ return DISARMED_MSG;
243
+ }
244
+ const steps = Array.isArray(args.steps) ? args.steps : [];
245
+ if (steps.length === 0) return 'computer_run 需要非空的 steps 数组';
246
+ if (args.lazy === true) return runLazy(args, steps, exec);
247
+ const prepared = await worker.call('prepare_batch', { steps, windowId: args.windowId }, { timeoutMs: 188000 });
248
+ const prepError = preparationFailure(prepared, steps.length);
249
+ if (prepError) {
250
+ store.step({ label: `批量「${str(args.goal, 40)}」`, kind: 'batch', status: 'failed', detail: prepError });
251
+ return prepError;
252
+ }
253
+ const descriptors = prepared.descriptors ?? [];
254
+ const batchDeny = classifyBatch(steps, descriptors);
255
+ if (batchDeny) {
256
+ store.step({ label: `批量「${str(args.goal, 40)}」`, kind: 'batch', status: 'blocked', detail: `第 ${batchDeny.index} 步:${batchDeny.refusal}` });
257
+ return `${refuse(batchDeny, { tool: 'computer_run', goal: args.goal, stepIndex: batchDeny.index, step: steps[batchDeny.index], descriptor: descriptors[batchDeny.index] ?? null })}\n这一批一个动作都没执行(performedCount=0)。`
258
+ + '\n去掉或替换被拒的那一步,再重新提交整批。';
259
+ }
260
+ // commit_batch Err 之前裸抛给模型:面板 step 缺一条记录,自纠引导只能靠模型自己猜。
261
+ // 按 code 翻译成下一步该做什么。
262
+ let committed;
263
+ try {
264
+ // indicatorPid lets the worker's window diff exclude our own overlay capsule (it lights
265
+ // asynchronously at claim, so a cold first batch can genuinely "see" it appear). 0 when
266
+ // the overlay is down — the diff then just reports what it saw.
267
+ committed = await worker.call('commit_batch', { revision: prepared.revision, steps, windowId: args.windowId, mode: store.pointerMode, indicatorPid: activity?.indicator?.proc?.pid ?? 0 }, { timeoutMs: 188000 });
268
+ } catch (error) {
269
+ const code = String(error?.code ?? '');
270
+ // 用户在批次在飞时按 Esc / 面板终止(index.js 的 Esc 路径与 kill 同一收尾:关掉 worker),
271
+ // 在飞的 commit_batch 以 WorkerDeadError 落到这里。这批不是「一个动作都没有执行」:
272
+ // 已送达的步骤不回滚,剩余步骤不再执行,也绝不能回话「通过」或落配方。
273
+ if (code === 'worker_dead') {
274
+ const byUser = store.killed === true;
275
+ const detail = `${byUser ? '用户已终止本轮(Esc/面板)' : 'worker 进程中途停止'}:批次在飞时被打断,剩余步骤不再执行,已完成的动作不回滚。先 computer_snapshot 重新观察桌面,再决定怎么继续。`;
276
+ store.step({ label: `批量「${str(args.goal, 40)}」`, kind: 'batch', status: 'failed', detail });
277
+ return detail;
278
+ }
279
+ const guide = code === 'stale_revision' || code === 'revision_mismatch'
280
+ ? '批次修订号已过期(界面在此期间更新过,一个动作都没有执行)。直接重新发起同样的 computer_run 即可——会自动重新 prepare,不需要手动刷新。'
281
+ : code === 'descriptor_unresolved'
282
+ ? '至少一个步骤的描述符解析不到元素,一个动作都没有执行。先用 find_text / computer_snapshot 更新定位;目标若由前一步才生成,请拆成两批执行。'
283
+ : code === 'unknown_window'
284
+ ? `窗口 ${args.windowId} 已不存在或尚未登记。先用 computer_windows / computer_resolve_window 拿到有效 windowId 再重发。`
285
+ : `commit_batch 失败(${code || 'worker_error'}):${error?.message ?? error}。一个动作都没有执行;先重新观察窗口再重试。`;
286
+ const detail = `批量未执行(performedCount=0):${guide}`;
287
+ store.step({ label: `批量「${str(args.goal, 40)}」`, kind: 'batch', status: 'failed', detail });
288
+ return detail;
289
+ }
290
+ // 轻点 Esc 未必来得及杀掉 worker:单线程的 worker 把排队的 shutdown 命令放在批次之后,
291
+ // 批次可能先跑完、结果正常返回。此时 killed 闩锁仍亮着,是「用户在本批在飞期间要求停止」
292
+ // 的唯一可靠信号——必须挡住配方落盘,并把回话从「通过」改成「已终止」。
293
+ const userStopped = store.killed === true;
294
+ const results = committed.results ?? [];
295
+ for (const r of results) {
296
+ store.step({ label: `第 ${r.index} 步 ${r.action} ${r.ref ?? ''}`, status: r.status, ms: r.ms, verify: r.verify, detail: r.detail });
297
+ }
298
+ store.actionDone(committed.performedCount ?? results.filter((r) => r.performed === true).length);
299
+ const allPassed = !userStopped && committed.stoppedAt === null && results.length === steps.length && results.every((r) => r.status === 'passed');
300
+ let recipeNote = '';
301
+ if (allPassed && args.saveRecipe !== false) {
302
+ const name = await saveRecipe(recipeDir, {
303
+ goal: args.goal,
304
+ window: descriptors[0]?.ownerWindow ?? windowOf(store, args.windowId),
305
+ revision: prepared.revision,
306
+ steps: steps.map((step, i) => ({
307
+ action: step.action,
308
+ value: step.value,
309
+ verify: step.verify,
310
+ by: step.by ? structuredClone(step.by) : recipeBy(descriptors[i]),
311
+ })),
312
+ });
313
+ recipeNote = `\n已存配方:${name}(之后用 computer_replay 回放)`;
314
+ }
315
+ const cancelledNote = (userStopped || committed.status === 'cancelled')
316
+ ? '\n用户已终止本轮(Esc/面板):已完成的动作不回滚。'
317
+ : '';
318
+ // stoppedNote branches on committed.status: a user Esc gets "pause and ask", not the
319
+ // "re-observe and continue" wording a failed/verify_failed stop gets.
320
+ const stopped = stoppedNote(committed);
321
+ // A dialog that popped mid-batch must not wait for the model's next observation —
322
+ // render the hwnd diff (worker already excluded our overlay pid; this filters again).
323
+ return `${renderResults(results, committed.performedCount ?? 0)}${stopped}${cancelledNote}${recipeNote}${newWindowNote(committed.newWindows, activity?.indicator?.proc?.pid ?? 0)}${locatorNotes(descriptors, results)}`;
324
+ },
325
+ })));
326
+
327
+
328
+ d.disposers.push(register(defineTool({
329
+ name: 'computer_wait',
330
+ description: 'Wait for a desktop condition instead of guessing sleeps: {type:"element_appears"|"element_gone"|"name_contains"|"value_equals"|"value_changed"|"no_change"|"enabled_is", by|ref, expect} for elements, or {type:"window_appears"|"window_gone"|"window_title_contains", titleContains?|class?|pid?} for windows. element_appears/element_gone take a `by` descriptor and need no ref; every other element type must name its target with `ref` or `by`, otherwise the wait has nothing to measure and fails with "target missing". window_appears returns the new windowId, so you can act without a second resolve. Resolves locally inside the worker. Example: after a submit action, {type:"no_change", ref:"e5"} means "the UI has settled" — it matches when the element keeps its current value for the whole window, so you stop guessing sleep durations before taking the next observation.',
331
+ parameters: {
332
+ windowId: { ...STR, description: 'window to observe; not needed for window_appears, required for window_title_contains and every element type' },
333
+ condition: { type: 'json', required: true, description: '{type, expect?, by?, ref?, titleContains?, class?, pid?} — see the tool description for which types need a target' },
334
+ timeoutMs: { ...INT, description: 'How long to keep polling the condition (default 10000). Effective cap ~90s: a longer value is cut off by this tool budget.' },
335
+ },
336
+ output: { schema: STR, render: (_args, value) => text(value) },
337
+ timeoutMs: 90000,
338
+ async execute(args) {
339
+ const cond = args.condition ?? {};
340
+ const type = String(cond.type ?? '');
341
+ const isWindowType = ['window_appears', 'window_gone', 'window_title_contains'].includes(type);
342
+ // Catch the mistake before the worker burns its whole timeout: the four measurement types
343
+ // read a property of ONE element, so without ref/by there is nothing to measure. The old
344
+ // path returned "matched:false, error:element_gone" after waiting the full budget, which
345
+ // reads as "the element disappeared" rather than "you never named one".
346
+ const needsTarget = ['name_contains', 'value_equals', 'value_changed', 'no_change', 'enabled_is'].includes(type);
347
+ const hasTarget = [cond.ref, cond.by].some((v) => v !== undefined && v !== null && (typeof v === 'string' ? v !== '' : true));
348
+ if (needsTarget && !hasTarget) {
349
+ return `条件 type="${type}" 需要指定 ref 或 by(它要读某个元素的属性来判定)。
350
+ 例如:{type:"name_contains", by:{controlType:"Button", name:"确定"}, expect:"确定"}
351
+ 或先 snapshot 拿到 ref,再用 {type:"value_equals", ref:"e12", expect:"..."}。
352
+ 如果只是想等元素出现/消失,用 type:"element_appears" 或 "element_gone"(它们只需要 by)。`;
353
+ }
354
+ // Window waits: window_appears needs no windowId (the point is that the window does not exist
355
+ // yet), window_title_contains does (it reads one window's title), window_gone accepts either.
356
+ if (type === 'window_title_contains' && (args.windowId === undefined || String(args.windowId) === '')) {
357
+ return 'window_title_contains 需要 windowId:它读的是某个已知窗口的标题。等新窗口出现用 window_appears。';
358
+ }
359
+ if (!isWindowType && (args.windowId === undefined || String(args.windowId) === '')) {
360
+ return `条件 type="${type}" 需要 windowId(元素类条件要在某个窗口里解析)。`;
361
+ }
362
+ // Pass the budget down (tool cap 90s + 8s headroom): the worker widens its own budget to
363
+ // args.timeoutMs+2500, so with the Node 30 s default a long wait died on the Node side while
364
+ // the worker kept polling, and the late reply was dropped.
365
+ const result = await worker.call('wait', { windowId: args.windowId, condition: cond, timeoutMs: args.timeoutMs ?? 10000 }, { timeoutMs: 98000 });
366
+ const detail = [];
367
+ if (result.observed !== undefined) detail.push(`observed=${JSON.stringify(result.observed)}`);
368
+ if (result.error !== undefined) detail.push(`error=${result.error}`);
369
+ if (result.observedName !== undefined) detail.push(`name=${JSON.stringify(result.observedName)}`);
370
+ const tail = detail.length === 0 ? '' : `(${detail.join(' ')})`;
371
+ const verdict = result.matched === true ? '条件命中' : '等待超时';
372
+ // A timeout with "target missing" means the target was never resolvable, not that it was slow.
373
+ const shape = result.matched !== true && result.error === 'element_gone'
374
+ ? ':目标元素始终没解析到——检查 by 描述符是否与元素实际的名字/类型一致'
375
+ : '';
376
+ const found = result.windowId ? `,窗口=${result.windowId}${result.title ? ` "${str(result.title, 40)}"` : ''}` : '';
377
+ if (found) store.setTarget(windowOf(store, result.windowId) ?? { windowId: String(result.windowId), title: result.title });
378
+ const advised = isWindowType && result.matched !== true && type !== 'window_gone'
379
+ ? ':窗口没出现——确认应用真的启动了(computer_launch / 用户手动打开),而不是只查错了标题。'
380
+ : '';
381
+ return `${verdict},耗时 ${result.ms}ms${tail}${found}${shape}${advised}`;
382
+ },
383
+ })));
384
+
385
+
386
+ d.disposers.push(register(defineTool({
387
+ name: 'computer_resolve_window',
388
+ description: 'Resolve (or wait for) a window by pid, title, class, or titleRegex and get its current windowId. Use it after a window restarts, retitles, or when a snapshot-era windowId went stale: windowIds are per-worker-generation, so a relaunched app gets a new one. This is the lookup the worker error messages refer to.',
389
+ parameters: {
390
+ windowId: { ...STR, description: 'a known windowId to re-resolve (e.g. "w1")' },
391
+ pid: { ...INT, description: 'process id to match' },
392
+ title: { ...STR, description: 'window title substring (case-insensitive)' },
393
+ titleRegex: { ...STR, description: 'regular expression to match the title against' },
394
+ class: { ...STR, description: 'window class name substring' },
395
+ titleExact: { ...BOOL, description: 'title must equal the given string instead of containing it' },
396
+ timeoutMs: { ...INT, description: 'how long to keep polling for the window to appear (default 4000, max bounded by the tool budget)' },
397
+ },
398
+ output: { schema: STR, render: (_args, value) => text(value) },
399
+ isConcurrencySafe: true,
400
+ async execute(args, exec) {
401
+ await aborted(exec.signal);
402
+ const given = [args.windowId, args.pid, args.title, args.titleRegex, args.class].some((v) => v !== undefined && String(v) !== '');
403
+ if (!given) return 'computer_resolve_window 需要 windowId / pid / title / titleRegex / class 之一';
404
+ const result = await worker.call('resolve_window', {
405
+ windowId: args.windowId ? String(args.windowId) : '',
406
+ pid: args.pid,
407
+ title: args.title,
408
+ titleRegex: args.titleRegex,
409
+ class: args.class,
410
+ titleExact: args.titleExact === true,
411
+ timeoutMs: args.timeoutMs,
412
+ // The worker widens its budget to args.timeoutMs+2500; keep that inside the Node default
413
+ // instead of letting a huge caller timeout die on this side.
414
+ }, { timeoutMs: Math.min((Number(args.timeoutMs) || 4000) + 8000, 28000) });
415
+ store.setTarget(result);
416
+ // Window state decides the next move: a minimized window has no usable screen rect (pixel
417
+ // coordinates from a stale snapshot point at nothing), and a background window cannot take
418
+ // focus/pixel actions without being raised first. Name the state and the fix in one line.
419
+ const states = [result.isForeground ? '前台' : '不在前台', result.isMinimized === true ? '已最小化' : ''].filter(Boolean).join('、');
420
+ const advice = result.isMinimized === true
421
+ ? '(已最小化,建议先最大化/恢复窗口再取坐标或做像素操作)'
422
+ : (result.isForeground ? '' : '(当前不在前台;需要 focus 或像素路径时先把它带到前台)');
423
+ return `已解析窗口 ${result.windowId}:pid=${result.pid} "${str(result.title, 50)}" ${Math.round(result.rect?.w ?? 0)}x${Math.round(result.rect?.h ?? 0)}${states ? ` [${states}]` : ''}${advice}${noteHint(dataDir, result.appName ?? '')}`;
424
+ },
425
+ })));
426
+
427
+
428
+ d.disposers.push(register(defineTool({
429
+ name: 'computer_replay',
430
+ description: 'Re-run a saved recipe from a previous successful batch. Element identity is resolved by descriptor, so it survives layout drift; every step still passes the same policy check.',
431
+ parameters: {
432
+ name: { ...STR, required: true, description: 'Recipe name from computer_run output, or list them with names="list"' },
433
+ params: { type: 'json', description: 'Values substituted for {{placeholders}} in the recipe step values' },
434
+ names: { ...STR, description: 'Pass "list" to see the saved recipes instead of running one' },
435
+ },
436
+ output: { schema: STR, render: (_args, value) => text(value) },
437
+ timeoutMs: 180000,
438
+ async execute(args, exec) {
439
+ await aborted(exec.signal);
440
+ if (args.names === 'list') {
441
+ const names = await listRecipes(recipeDir);
442
+ return names.length === 0 ? '还没有保存任何配方' : names.join('\n');
443
+ }
444
+ if (!args.name) return 'computer_replay 需要 name,或者用 names="list" 先看清单';
445
+ // Replay delivers real input like any other tool: it passes the permission gate too.
446
+ if (!await ensureArmed(exec?.agent, exec.signal)) {
447
+ return DISARMED_MSG;
448
+ }
449
+ const recipe = await loadRecipe(recipeDir, args.name);
450
+ if (recipe === null) return `没有名为 "${args.name}" 的配方(用 names="list" 查看)`;
451
+ const steps = recipe.steps.map((step) => ({
452
+ action: step.action,
453
+ value: substitute(step.value, args.params ?? {}),
454
+ verify: step.verify,
455
+ by: step.by,
456
+ }));
457
+ const windowId = recipe.window?.windowId ?? null;
458
+ const prepared = await worker.call('prepare_batch', { steps, windowId, rebindBy: true });
459
+ const prepError = preparationFailure(prepared, steps.length);
460
+ 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.
463
+ store.step({ label: `回放 ${args.name}`, kind: 'batch', status: 'failed', detail: prepError });
464
+ return prepError;
465
+ }
466
+ const descriptors = prepared.descriptors ?? [];
467
+ const batchDeny = classifyBatch(steps, descriptors);
468
+ if (batchDeny) return refuse(batchDeny, { tool: 'computer_replay', recipe: args.name, stepIndex: batchDeny.index, descriptor: descriptors[batchDeny.index] ?? null });
469
+ let committed;
470
+ try {
471
+ // 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
473
+ // their pixel fallback.
474
+ committed = await worker.call('commit_batch', { revision: prepared.revision, steps, windowId, mode: store.pointerMode, indicatorPid: activity?.indicator?.proc?.pid ?? 0 });
475
+ } catch (error) {
476
+ // 与 computer_run 同一条在飞批次被终止路径(Esc/面板关 worker):worker_dead 不裸抛,
477
+ // 已送达的步骤不回滚,剩余步骤不再执行。其余 Err(revision/descriptor/unknown_window)
478
+ // 也按 code 翻译成自纠指引,而不是把裸 WorkerCommandError 丢给模型。
479
+ if (!['worker_dead', 'stale_revision', 'revision_mismatch', 'descriptor_unresolved', 'unknown_window'].includes(String(error?.code ?? ''))) throw error;
480
+ const code = String(error?.code ?? '');
481
+ // worker_dead 是「在飞回放被打断」,与「一个动作都没有执行」的预检类错误不同框:
482
+ // performedCount 未知,不能套「回放未执行(performedCount=0)」的话术。
483
+ if (code === 'worker_dead') {
484
+ const byUser = store.killed === true;
485
+ const detail = `${byUser ? '用户已终止本轮(Esc/面板)' : 'worker 进程中途停止'}:回放在飞时被打断,剩余步骤不再执行,已完成的动作不回滚。先 computer_snapshot 重新观察桌面,再决定是否重放。`;
486
+ store.step({ label: `回放 ${args.name}`, kind: 'batch', status: 'failed', detail });
487
+ return detail;
488
+ }
489
+ const guide = code === 'stale_revision' || code === 'revision_mismatch'
490
+ ? '配方修订号已过期(界面在此期间更新过,一个动作都没有执行)。直接重新发起同样的 computer_replay 即可——会自动重新 prepare。'
491
+ : code === 'descriptor_unresolved'
492
+ ? '配方里至少一个步骤解析不到元素,一个动作都没有执行。先 computer_find_text / computer_snapshot 找到目标,必要时用 computer_run 重新执行并保存新配方。'
493
+ : code === 'unknown_window'
494
+ ? '配方记录的窗口已不存在或尚未登记。先用 computer_windows / computer_resolve_window 找到该应用的新 windowId。'
495
+ : `${error?.message ?? error}。`;
496
+ const detail = `回放未执行(performedCount=0):${guide}`;
497
+ store.step({ label: `回放 ${args.name}`, kind: 'batch', status: 'failed', detail });
498
+ return detail;
499
+ }
500
+ const replayResults = committed.results ?? [];
501
+ for (const r of replayResults) {
502
+ store.step({ label: `回放 ${args.name} 第 ${r.index} 步 ${r.action}`, status: r.status, ms: r.ms, verify: r.verify, detail: r.detail });
503
+ }
504
+ store.actionDone(committed.performedCount ?? 0);
505
+ const replayCancelled = (store.killed === true || committed.status === 'cancelled')
506
+ ? '\n用户已终止本轮(Esc/面板):已完成的动作不回滚。'
507
+ : '';
508
+ // A replay that stopped mid-way is the moment the recipe's locators are proven stale — the
509
+ // one event that should feed the new positions BACK into the recipe (sediment was one-way).
510
+ // Descriptors that only matched by relaxing the match carry the fresh identity; write them
511
+ // into the failed recipe so the next replay starts from the updated locator.
512
+ let rebindNote = '';
513
+ if ((committed.stoppedAt ?? null) !== null && committed.status !== 'cancelled') {
514
+ let touched = 0;
515
+ for (const d of descriptors) {
516
+ if (d && d.matchedBy && d.matchedBy !== 'strict' && Number.isInteger(d.index) && recipe.steps[d.index]) {
517
+ const by = recipeBy(d);
518
+ if (by) { recipe.steps[d.index].by = by; touched++; }
519
+ }
520
+ }
521
+ if (touched > 0) {
522
+ try {
523
+ await writeFile(join(recipeDir, `${args.name}.json`), JSON.stringify({ ...recipe, updatedAt: new Date().toISOString() }, null, 2), 'utf8');
524
+ rebindNote = `\n已把 ${touched} 步的新定位写回配方「${args.name}」(下次回放从新位置解析)。`;
525
+ } catch { /* best-effort sediment: a failed write must not fail the replay report */ }
526
+ }
527
+ }
528
+ // Same stop wording as computer_run, including the Esc branch: a replay that stops must
529
+ // tell the model to re-observe (or pause for the user) instead of just listing the tail.
530
+ return `回放「${args.name}」(目标:${str(recipe.goal, 70)})\n${renderResults(replayResults, committed.performedCount ?? 0)}${stoppedNote(committed)}${replayCancelled}${rebindNote}${newWindowNote(committed.newWindows, activity?.indicator?.proc?.pid ?? 0)}${locatorNotes(descriptors, replayResults)}`;
531
+ },
532
+ })));
533
+ }