dsh-native-uia 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +431 -2
- package/client/client.js +81 -0
- package/cordis.patch.yml +11 -0
- package/icon.svg +11 -0
- package/locale/desktop/en.json +6 -0
- package/locale/desktop/zh.json +6 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +80 -4
- package/scripts/bench-live.mjs +157 -0
- package/scripts/check-lease.mjs +308 -0
- package/scripts/install.mjs +154 -0
- package/scripts/lib/load-tools-source.mjs +24 -0
- package/scripts/measure-parse.mjs +77 -0
- package/scripts/regression-halt-latch.mjs +100 -0
- package/scripts/regression-quality.mjs +207 -0
- package/scripts/regression-tools.mjs +88 -0
- package/scripts/regression-worker.ps1 +1042 -0
- package/scripts/smoke.mjs +158 -0
- package/scripts/verify-capture-scale.mjs +37 -0
- package/scripts/verify-live-clipboard.mjs +108 -0
- package/scripts/verify-live.mjs +110 -0
- package/scripts/verify-locator.mjs +52 -0
- package/scripts/verify.mjs +1459 -0
- package/src/activity-window.js +212 -0
- package/src/dashboard.js +145 -0
- package/src/guard.js +191 -0
- package/src/index.js +377 -0
- package/src/native-uia-remote.js +80 -0
- package/src/panel-face.js +14 -0
- package/src/state.js +177 -0
- package/src/tools.js +1482 -0
- package/src/worker-client.js +246 -0
- package/web/control.html +1413 -0
- package/worker/bin/build-ocr.ps1 +41 -0
- package/worker/bin/ocr.cs +69 -0
- package/worker/bin/ocr.exe +0 -0
- package/worker/indicator-server.ps1 +1928 -0
- package/worker/ps-stdio.ps1 +168 -0
- package/worker/uia-worker.ps1 +4220 -0
package/src/tools.js
ADDED
|
@@ -0,0 +1,1482 @@
|
|
|
1
|
+
import { writeFile, readdir, readFile, mkdir, unlink } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
4
|
+
import { classify, classifyBatch, classifyClose, classifyLaunch, classifyKeys, POLICY } from './guard.js';
|
|
5
|
+
|
|
6
|
+
const STR = { type: 'string' };
|
|
7
|
+
const INT = { type: 'integer' };
|
|
8
|
+
const BOOL = { type: 'boolean' };
|
|
9
|
+
const JSON_ARR = { type: 'array', items: { type: 'json' } };
|
|
10
|
+
|
|
11
|
+
function text(value) {
|
|
12
|
+
return [{ type: 'text', text: value }];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function str(value, max = 60) {
|
|
16
|
+
const s = String(value ?? '').replace(/\s+/g, ' ').trim();
|
|
17
|
+
return s.length > max ? `${s.slice(0, max - 1)}~` : s;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function windowOf(store, windowId) {
|
|
21
|
+
return store.windows.find((w) => w.windowId === String(windowId)) ?? null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function renderWindows(windows) {
|
|
25
|
+
if (windows.length === 0) return '当前没有可见窗口';
|
|
26
|
+
return windows
|
|
27
|
+
.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]' : ''}`)
|
|
28
|
+
.join('\n');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Only the patterns that change what the model can DO with the node. The full UIA list is noise:
|
|
32
|
+
// "ScrollItem,Transform,ItemContainer,Window" appears on hundreds of rows and no decision depends
|
|
33
|
+
// on it, while Invoke/Value/Toggle/SelectionItem/ExpandCollapse/RangeValue/Scroll are exactly the
|
|
34
|
+
// verbs computer_act accepts. Dropping the rest cut the rendered tree by roughly a third without
|
|
35
|
+
// removing a single actionable fact — the model reads a smaller tree and finds the control faster.
|
|
36
|
+
const ACTIONABLE = new Set([
|
|
37
|
+
'Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'RangeValue', 'Scroll', 'Text',
|
|
38
|
+
'GridItem', 'Selection', 'ItemContainer',
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
// The verbs a model can actually put in computer_act; narrower than ACTIONABLE, which also carries
|
|
42
|
+
// read-only patterns. A node listed here is one the model can act on without a second look.
|
|
43
|
+
const ACT_VERBS = new Set(['Invoke', 'Value', 'Toggle', 'SelectionItem', 'ExpandCollapse', 'RangeValue', 'Scroll']);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A one-line map of what is actionable, printed before the tree.
|
|
47
|
+
*
|
|
48
|
+
* In a 200-node snapshot only ~22% of nodes accept an action, and they are scattered through
|
|
49
|
+
* chrome the model has to read past. Naming them up front (ref + type + name) means the model can
|
|
50
|
+
* often pick its target from this line and go straight to computer_act, instead of scanning the
|
|
51
|
+
* whole tree — fewer tokens spent and fewer wrong-element guesses. Capped so it cannot become its
|
|
52
|
+
* own wall of text.
|
|
53
|
+
*/
|
|
54
|
+
function renderActionables(nodes, max = 24) {
|
|
55
|
+
const acts = nodes.filter((n) => (n.patterns ?? []).some((p) => ACT_VERBS.has(p)));
|
|
56
|
+
if (acts.length === 0) return '';
|
|
57
|
+
// Each entry is a complete "ref + controlType + name" metadata row: two same-named buttons used
|
|
58
|
+
// to render byte-identical, and a model reading only this line could not tell them apart. The
|
|
59
|
+
// center coordinate doubles as the by.nearPoint input, so same-name disambiguation no longer
|
|
60
|
+
// needs a second find_text pass over the whole tree.
|
|
61
|
+
const shown = acts.slice(0, max).map((n) => {
|
|
62
|
+
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)})` : '';
|
|
63
|
+
return `${n.ref} ${n.controlType}${n.name && n.name.trim() ? ` "${str(n.name, 24)}"` : ''}${c}`;
|
|
64
|
+
});
|
|
65
|
+
const rest = acts.length > shown.length ? ` …另 ${acts.length - shown.length} 个` : '';
|
|
66
|
+
return `可操作元素 ${acts.length} 个(@=中心坐标,同名时可直接填进 by.nearPoint 消歧):${shown.join('、')}${rest}\n`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function renderTree(nodes, { compact = false, elide = true } = {}) {
|
|
70
|
+
if (nodes.length === 0) return '快照返回 0 个元素';
|
|
71
|
+
const shown = elide ? elideRedundantContainers(nodes) : nodes;
|
|
72
|
+
const lines = shown.length > 0 ? shown : nodes;
|
|
73
|
+
return lines
|
|
74
|
+
.map((n) => {
|
|
75
|
+
const pad = ' '.repeat(Math.min(n.depth ?? 0, 10));
|
|
76
|
+
const acts = (n.patterns ?? []).filter((p) => ACTIONABLE.has(p));
|
|
77
|
+
// `disabled` and `offscreen` are the two flags that change whether acting makes sense; the
|
|
78
|
+
// compact form still carries them because they are decision-relevant, unlike class names.
|
|
79
|
+
const flags = [n.enabled === false ? 'disabled' : '', n.isOffscreen === true ? 'offscreen' : ''].filter(Boolean).join(' ');
|
|
80
|
+
const value = n.value === undefined || n.value === '' ? '' : ` val="${str(n.value, compact ? 24 : 40)}"`;
|
|
81
|
+
const pat = acts.length === 0 ? '' : ` [${acts.join(',')}]`;
|
|
82
|
+
const name = str(n.name, compact ? 32 : 48);
|
|
83
|
+
return `${pad}${n.ref} ${n.controlType} "${name}"${value}${pat}${flags ? ` ${flags}` : ''}`;
|
|
84
|
+
})
|
|
85
|
+
.join('\n');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Per-verb inline verify suggestions for the "nothing observable changed" branches of
|
|
90
|
+
* renderEffect. The type set is aligned with the worker's verify evaluator (Eval-Once — the same
|
|
91
|
+
* evaluator serves act's verify channel and wait), and a verb only gets the types whose effect it
|
|
92
|
+
* can actually make observable: set_value/text_append end in the element's reading, toggle shows
|
|
93
|
+
* up as a reading change or in IsEnabled. Button verbs (invoke/expand/collapse/...) have no
|
|
94
|
+
* assertable reading, so suggesting value_changed for them would only produce verify checks that
|
|
95
|
+
* never match — those keep the plain re-observe advice.
|
|
96
|
+
*/
|
|
97
|
+
const VERIFY_HINT = {
|
|
98
|
+
set_value: ['value_equals'],
|
|
99
|
+
text_append: ['value_equals'],
|
|
100
|
+
toggle: ['value_changed', 'enabled_is'],
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Say what the action demonstrably changed, instead of letting "no error" read as "it worked".
|
|
105
|
+
* Act-effect verification is the load-bearing idea in recent GUI-agent work (verify the effect
|
|
106
|
+
* rather than trust the click). We only claim what the worker actually observed: a verify matcher
|
|
107
|
+
* fired, the element's value changed, or nothing observable changed — the last case is a hint to
|
|
108
|
+
* add a verify condition (for verbs with an observable effect, one call settles it) or re-observe,
|
|
109
|
+
* not a failure, because most buttons legitimately change no element property.
|
|
110
|
+
*/
|
|
111
|
+
function renderEffect(r) {
|
|
112
|
+
if (r.performed !== true) return '';
|
|
113
|
+
if (r.verify) return r.verify.matched === true ? ' 效果=校验命中' : ' 效果=校验未命中';
|
|
114
|
+
const hint = VERIFY_HINT[String(r.action ?? '')];
|
|
115
|
+
const tip = hint
|
|
116
|
+
? `;如需确定性判据,加 verify:{type:"${hint[0]}"}${hint[1] ? `(或 ${hint[1]})` : ''}`
|
|
117
|
+
: '';
|
|
118
|
+
const hasValue = (r.before ?? '') !== '' || (r.after ?? '') !== '';
|
|
119
|
+
if (!hasValue) return ` 效果=无可观测属性变化(已送达${tip})`;
|
|
120
|
+
return r.before === r.after ? ` 效果=属性未变(已送达${tip})` : ' 效果=属性已变';
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Single source for the not_executed wording: the worker only ships the status (uia-worker.ps1
|
|
124
|
+
// keeps an English placeholder because this file is parsed as ANSI there), and BOTH batch tools
|
|
125
|
+
// render the tail through renderResults — one constant here keeps computer_run and computer_replay
|
|
126
|
+
// from drifting apart.
|
|
127
|
+
export const NOT_EXECUTED_TEXT = '未执行:前序步骤失败/被取消';
|
|
128
|
+
|
|
129
|
+
function renderResults(results, performed) {
|
|
130
|
+
const lines = results.map((r) => {
|
|
131
|
+
// 'not_executed' is the worker's placeholder for steps a stop/cancel never reached: every
|
|
132
|
+
// planned step must appear in the reply with the same fixed wording, so the model can see
|
|
133
|
+
// WHICH tail was skipped instead of inferring it from performedCount alone.
|
|
134
|
+
const notExecuted = r.status === 'not_executed';
|
|
135
|
+
const mark = r.status === 'passed' ? '通过' : notExecuted ? '未执行' : r.status;
|
|
136
|
+
const verify = r.verify ? ` 校验=${r.verify.matched === true ? '命中' : '未命中'}(${r.verify.type ?? '?'})` : '';
|
|
137
|
+
const delivered = r.performed === true && r.status !== 'passed' ? '(动作已执行,勿直接重试)' : '';
|
|
138
|
+
// commit re-resolves every by-step right before acting, so this per-step verdict is the
|
|
139
|
+
// truth closest to the moment of the action — render it inline instead of dropping it.
|
|
140
|
+
const locator = r.degraded === true ? ` 定位=${r.matchedBy ?? '?'}(${Math.round((Number(r.score) || 0) * 100)}%)` : '';
|
|
141
|
+
const detail = notExecuted ? NOT_EXECUTED_TEXT : r.detail;
|
|
142
|
+
return `${mark} 第 ${r.index} 步 ${r.action ?? ''} ${r.ref ?? ''}${delivered} 耗时 ${r.ms ?? '?'}ms${verify}${locator}${renderEffect(r)}${detail ? ` ${str(detail, 90)}` : ''}`;
|
|
143
|
+
});
|
|
144
|
+
const unverified = results.filter((r) => r.performed === true && !r.verify).length;
|
|
145
|
+
const tail = unverified > 0
|
|
146
|
+
? `\nperformedCount=${performed}(其中 ${unverified} 步没有校验条件:结果只代表已送达,不代表界面已按预期改变)`
|
|
147
|
+
: `\nperformedCount=${performed}`;
|
|
148
|
+
// Four-state tally so the model does not re-count the lines itself: a batch reply used to give
|
|
149
|
+
// only performedCount, and 成功/失败/校验未命中/未执行 had to be inferred per row. '校验未命中'
|
|
150
|
+
// keeps the existing contract wording: the action WAS delivered — do not blindly retry it.
|
|
151
|
+
const passedCount = results.filter((r) => r.status === 'passed').length;
|
|
152
|
+
const verifyMissedCount = results.filter((r) => r.status === 'verify_failed').length;
|
|
153
|
+
const notExecutedCount = results.filter((r) => r.status === 'not_executed').length;
|
|
154
|
+
const failedResults = results.filter((r) => r.status !== 'passed' && r.status !== 'verify_failed' && r.status !== 'not_executed');
|
|
155
|
+
const firstFail = failedResults[0];
|
|
156
|
+
const firstReason = firstFail ? `(首条原因:第 ${firstFail.index} 步 ${str(firstFail.detail, 60)})` : '';
|
|
157
|
+
const tally = `批次汇总:通过 ${passedCount} / 失败 ${failedResults.length}${firstReason} / 校验未命中 ${verifyMissedCount} / 未执行 ${notExecutedCount}`;
|
|
158
|
+
return `${lines.join('\n')}${tail}\n${tally}`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* One line per stop, and the wording must MATCH THE REASON. A failed/verify_failed stop means
|
|
163
|
+
* "the desktop drifted: re-observe and continue". status='cancelled' is the opposite instruction —
|
|
164
|
+
* the user pressed Esc to STOP, so the model must pause and ask, not auto-resume. The worker
|
|
165
|
+
* always reported that status; the run path just dropped it on the floor and printed the
|
|
166
|
+
* "continue" wording for both.
|
|
167
|
+
*/
|
|
168
|
+
function stoppedNote(committed) {
|
|
169
|
+
const stoppedAt = committed?.stoppedAt;
|
|
170
|
+
if (stoppedAt === null || stoppedAt === undefined) return '';
|
|
171
|
+
if (committed.status === 'cancelled') {
|
|
172
|
+
return `\n用户按 Esc 终止了本轮(第 ${stoppedAt} 步及其后的步骤未执行):请暂停并向用户确认是否继续,不要自动续跑。`;
|
|
173
|
+
}
|
|
174
|
+
return `\n在第 ${stoppedAt} 步停下:先重新 computer_snapshot 再继续,桌面状态可能已经和你规划时不一样了。`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* One observation-metadata line for snapshot/find_text heads: where the desktop foreground is,
|
|
179
|
+
* where the UIA focus sits, and whether that focus lives in the observed window (pid comparison,
|
|
180
|
+
* advisory — a multi-process host can misreport). The next observation after a click/type carries
|
|
181
|
+
* free proof of whether the action took effect: the focus moved into (or out of) the window. Every
|
|
182
|
+
* field is advisory — the worker omits any of them when its probe fails, and this renders only
|
|
183
|
+
* what arrived. A focus outside the target window gets the one-line fix. Everything goes through
|
|
184
|
+
* str() so a long window title cannot blow the line. Deliberately NOT exported: the
|
|
185
|
+
* regression harness (scripts/lib/load-tools-source.mjs) strips only known exports, so an export
|
|
186
|
+
* here would break every loader consumer — it picks these up through its return expression.
|
|
187
|
+
*/
|
|
188
|
+
function observationLine(result) {
|
|
189
|
+
const fg = result?.foreground;
|
|
190
|
+
const focus = result?.focus;
|
|
191
|
+
const parts = [];
|
|
192
|
+
if (fg && (String(fg.title ?? '').trim() !== '' || String(fg.class ?? '').trim() !== '')) {
|
|
193
|
+
parts.push(`前台="${str(fg.title ?? fg.class, 40)}"${fg.isTarget === false ? '(非目标窗)' : ''}`);
|
|
194
|
+
}
|
|
195
|
+
if (focus && (String(focus.name ?? '').trim() !== '' || String(focus.controlType ?? '').trim() !== '')) {
|
|
196
|
+
const where = result.focusInWindow === true ? '(在本窗)' : result.focusInWindow === false ? '(不在本窗)' : '';
|
|
197
|
+
const advice = result.focusInWindow === false ? '——焦点不在目标窗,需要输入/焦点类动作时先 resolve_window 或带 windowId 聚焦' : '';
|
|
198
|
+
parts.push(`焦点=${focus.controlType ?? '?'} "${str(focus.name ?? '', 24)}"${where}${advice}`);
|
|
199
|
+
}
|
|
200
|
+
if (parts.length === 0) return '';
|
|
201
|
+
const ms = Number(result?.ms);
|
|
202
|
+
const msPart = Number.isFinite(ms) && ms > 0 ? ` 采集 ${Math.round(ms)}ms` : '';
|
|
203
|
+
return `\n${parts.join(' ')}${msPart}`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* The batch-window diff note: newWindows is the worker's before/after top-level hwnd diff
|
|
208
|
+
* around phase 2. The indicator overlay's own pid is filtered here as well as worker-side — a
|
|
209
|
+
* worker that never learned the pid can still report our own capsule (it lights asynchronously at
|
|
210
|
+
* activity.claim), and a self-report of the overlay would be exactly the noise this warning exists
|
|
211
|
+
* to prevent; the fixed overlay window title is excluded too. Empty input renders '' — no diff,
|
|
212
|
+
* no line. Not exported (see observationLine): the harness takes it via its return expression.
|
|
213
|
+
*/
|
|
214
|
+
function newWindowNote(newWindows, indicatorPid) {
|
|
215
|
+
const rows = (Array.isArray(newWindows) ? newWindows : [])
|
|
216
|
+
.filter((w) => w && !(indicatorPid !== undefined && indicatorPid !== null && Number(w.pid) === Number(indicatorPid)))
|
|
217
|
+
.filter((w) => String(w.title ?? '') !== 'dsh-yuping-indicator');
|
|
218
|
+
if (rows.length === 0) return '';
|
|
219
|
+
const listed = rows.slice(0, 5).map((w) => `"${str(w.title ?? w.class ?? '?', 40)}"(pid=${w.pid ?? '?'})`).join('、');
|
|
220
|
+
const rest = rows.length > 5 ? ` …另 ${rows.length - 5} 个` : '';
|
|
221
|
+
return `\n⚠ 批次期间出现新窗口:${listed}${rest}——先确认是否弹窗/对话框并处理,避免它的按钮文本混进下一次定位。`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function preparationFailure(prepared, stepCount) {
|
|
225
|
+
const descriptors = prepared.descriptors ?? [];
|
|
226
|
+
const errors = descriptors.filter((d) => d.error || d.code);
|
|
227
|
+
if (prepared.allResolved === true && descriptors.length === stepCount && errors.length === 0) return '';
|
|
228
|
+
return `批量预检失败,尚未执行任何动作(performedCount=0)。\n${errors.map((d) => `第 ${d.index} 步:${d.code ?? 'unresolved'} ${d.error ?? ''}`).join('\n') || '预检未完整返回所有步骤。'}\n先用 find_text / snapshot 更新定位。后续目标若由前一步才生成,请拆成两批执行;动态名称可使用稳定片段和 nameExact:false。`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Rebuild a replayable `by` descriptor from a resolved element descriptor, using the SAME selector
|
|
233
|
+
* quality rules find_text already applies (worker: name >200 chars → 200-char prefix +
|
|
234
|
+
* nameExact:false, automationId carried as the stable anchor). The old rebuild used the display
|
|
235
|
+
* name, which the worker truncates at 160 chars and suffixes with '~' — such a name can never
|
|
236
|
+
* satisfy strict equality or normalized matching, so a recipe for any long-named element without
|
|
237
|
+
* an automationId could save "successfully" and only fail on replay.
|
|
238
|
+
*/
|
|
239
|
+
function recipeBy(d) {
|
|
240
|
+
if (!d) return null;
|
|
241
|
+
const by = {};
|
|
242
|
+
// fullName is the UNtruncated element name the worker attaches only when truncation happened;
|
|
243
|
+
// otherwise name is already the exact name (TruncStr never touches ≤160).
|
|
244
|
+
const full = String(d.fullName ?? d.name ?? '').trim();
|
|
245
|
+
if (full !== '') {
|
|
246
|
+
if (full.length > 200) {
|
|
247
|
+
by.name = full.slice(0, 200);
|
|
248
|
+
by.nameExact = false;
|
|
249
|
+
} else {
|
|
250
|
+
by.name = full;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (d.controlType) by.controlType = String(d.controlType);
|
|
254
|
+
if (d.className) by.className = String(d.className);
|
|
255
|
+
if (d.automationId) by.automationId = String(d.automationId);
|
|
256
|
+
return Object.keys(by).length > 0 ? by : null;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* A descriptor that only resolved by relaxing the match is not a failure — it is a warning that
|
|
261
|
+
* the UI text moved. Saying so turns a silent drift (the classic "回放点错还报成功") into an
|
|
262
|
+
* explicit instruction to re-check with find_text before trusting the batch.
|
|
263
|
+
*
|
|
264
|
+
* Two stages report drift: prepare_batch resolves once (its descriptors), and commit_batch
|
|
265
|
+
* re-resolves every by-step right before acting (its per-step locator fields). The commit verdict
|
|
266
|
+
* is the one closest to the moment of the action, so it wins; prepare-only drift is still reported
|
|
267
|
+
* with its stage named, instead of the caller reading a stale prepare judgement after commit.
|
|
268
|
+
*/
|
|
269
|
+
function locatorNotes(descriptors, results = []) {
|
|
270
|
+
const fmt = (d) => `第 ${d.index} 步 ${d.matchedBy ?? '降级'}(${Math.round((Number(d.score) || 0) * 100)}%)`;
|
|
271
|
+
const drift = (rows) => (rows ?? []).filter((d) => d && d.degraded === true);
|
|
272
|
+
const commitDrift = drift(results);
|
|
273
|
+
const prepDrift = drift(descriptors).filter((d) => !commitDrift.some((r) => r.index === d.index));
|
|
274
|
+
const parts = [];
|
|
275
|
+
if (commitDrift.length > 0) parts.push(`动作时重解析 ${commitDrift.map(fmt).join('、')}`);
|
|
276
|
+
if (prepDrift.length > 0) parts.push(`预检时 ${prepDrift.map(fmt).join('、')}`);
|
|
277
|
+
if (parts.length === 0) return '';
|
|
278
|
+
const total = commitDrift.length + prepDrift.length;
|
|
279
|
+
return `\n⚠ 定位降级 ${total} 步:${parts.join(';')}。这些步骤的文字与配方不一致,只按归一化/ID 命中;执行前用 find_text 复核。`;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function snapshotNotes(snap) {
|
|
283
|
+
const notes = [];
|
|
284
|
+
if (snap.truncated) notes.push('元素树已截断,可收紧过滤条件或提高 maxNodes。');
|
|
285
|
+
if (snap.partialReason) notes.push(`元素树仅部分可读:${Array.isArray(snap.partialReason) ? snap.partialReason.join(';') : snap.partialReason}`);
|
|
286
|
+
return notes.length ? `\n⚠ ${notes.join(' ')}` : '';
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const CJK = /[\u2e80-\u9fff\uff00-\uffef\u3000-\u303f]/;
|
|
290
|
+
const isCjk = (ch) => ch !== undefined && ch !== '' && CJK.test(ch);
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Windows OCR emits one "word" per CJK character. Rendered raw, a single line of Chinese prose
|
|
294
|
+
* became dozens of one-character click targets — 542 words / 409 targets on one measured window —
|
|
295
|
+
* and each target is meaningless to click or to read. Rebuild visual lines from the bounding boxes
|
|
296
|
+
* so one target is one phrase.
|
|
297
|
+
*
|
|
298
|
+
* Grouping is deliberately conservative: same line (>=60% vertical overlap), horizontal gap no
|
|
299
|
+
* larger than 1.6 character widths (so separate columns never merge), and only the few recent
|
|
300
|
+
* lines are considered (so interleaved baselines cannot chain unrelated rows together).
|
|
301
|
+
*/
|
|
302
|
+
function groupOcrWords(words, { maxGapFactor = 2.0, lineOverlap = 0.6 } = {}) {
|
|
303
|
+
const usable = (words ?? []).filter((w) => w
|
|
304
|
+
&& Number.isFinite(w.cx) && Number.isFinite(w.cy)
|
|
305
|
+
&& w.rect && w.rect.w > 0 && w.rect.h > 0
|
|
306
|
+
&& String(w.text ?? '').trim() !== '');
|
|
307
|
+
const sorted = usable.slice().sort((a, b) => (a.rect.y - b.rect.y) || (a.rect.x - b.rect.x));
|
|
308
|
+
const lines = [];
|
|
309
|
+
for (const w of sorted) {
|
|
310
|
+
const unit = Math.max(4, Math.min(w.rect.h, w.rect.w));
|
|
311
|
+
let best = null;
|
|
312
|
+
for (let i = lines.length - 1; i >= 0 && i >= lines.length - 4; i--) {
|
|
313
|
+
const candidate = lines[i];
|
|
314
|
+
const overlap = Math.min(candidate.rect.y + candidate.rect.h, w.rect.y + w.rect.h) - Math.max(candidate.rect.y, w.rect.y);
|
|
315
|
+
const minH = Math.min(candidate.rect.h, w.rect.h);
|
|
316
|
+
if (minH <= 0 || overlap / minH < lineOverlap) continue;
|
|
317
|
+
const gap = w.rect.x - (candidate.rect.x + candidate.rect.w);
|
|
318
|
+
if (gap > unit * maxGapFactor || gap < -unit * 2) continue;
|
|
319
|
+
best = candidate; break;
|
|
320
|
+
}
|
|
321
|
+
if (best === null) {
|
|
322
|
+
lines.push({ text: String(w.text), rect: { ...w.rect }, members: [{ cx: w.cx, cy: w.cy }] });
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
const prev = best.text;
|
|
326
|
+
const prevChar = prev.slice(-1);
|
|
327
|
+
const nextChar = String(w.text)[0];
|
|
328
|
+
const needsSpace = !isCjk(prevChar) && !isCjk(nextChar) && !/\s$/.test(prev);
|
|
329
|
+
best.text = prev + (needsSpace ? ' ' : '') + String(w.text);
|
|
330
|
+
best.members.push({ cx: w.cx, cy: w.cy });
|
|
331
|
+
const right = Math.max(best.rect.x + best.rect.w, w.rect.x + w.rect.w);
|
|
332
|
+
const bottom = Math.max(best.rect.y + best.rect.h, w.rect.y + w.rect.h);
|
|
333
|
+
best.rect.x = Math.min(best.rect.x, w.rect.x);
|
|
334
|
+
best.rect.y = Math.min(best.rect.y, w.rect.y);
|
|
335
|
+
best.rect.w = right - best.rect.x;
|
|
336
|
+
best.rect.h = bottom - best.rect.y;
|
|
337
|
+
}
|
|
338
|
+
return lines.map((l) => ({
|
|
339
|
+
text: l.text,
|
|
340
|
+
words: l.members.length,
|
|
341
|
+
members: l.members,
|
|
342
|
+
rect: l.rect,
|
|
343
|
+
cx: Math.round(l.rect.x + l.rect.w / 2),
|
|
344
|
+
cy: Math.round(l.rect.y + l.rect.h / 2),
|
|
345
|
+
}));
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Drop pass-through containers from the RENDERED view only (refs stay valid: they were minted
|
|
350
|
+
* worker-side). A chain of unnamed Pane/Group/Document nodes exists to carry layout, not to be
|
|
351
|
+
* acted on, and it costs indentation on every child. Measured motivation: accessibility-tree
|
|
352
|
+
* redundancy is the dominant cost for GUI agents, and removing it raised success while cutting
|
|
353
|
+
* tokens sharply (A11y-Compressor, ACL 2026). Only nodes with no name AND no actionable verb are
|
|
354
|
+
* removed, so nothing the model can act on disappears.
|
|
355
|
+
*/
|
|
356
|
+
// Exported so the find_text ladder and any consumer share ONE definition of "a container whose
|
|
357
|
+
// click only focuses the window" — a second copy had already drifted into a different order.
|
|
358
|
+
export const PASS_THROUGH = new Set(['Pane', 'Group', 'Document', 'Custom', 'Window']);
|
|
359
|
+
|
|
360
|
+
// Navigation rows and real commands, shared by find_text ranking and computer_parse's operable
|
|
361
|
+
// list, so the two observation channels cannot drift into disagreeing about what counts as
|
|
362
|
+
// clickable. NAVIGATION rows carry SelectionItem and so "look" actionable, but they are sidebar
|
|
363
|
+
// navigation, not the control a model is after.
|
|
364
|
+
const NAVIGATION = new Set(['TreeItem', 'ListItem', 'DataItem']);
|
|
365
|
+
const COMMANDS = new Set(['Button', 'MenuItem', 'Tab', 'TabItem', 'CheckBox', 'RadioButton', 'ComboBox', 'Edit', 'SplitButton', 'Hyperlink', 'Slider', 'Spinner']);
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* One ranking for both channels that list clickable things (5 = least clickable):
|
|
369
|
+
* find_text sorts its hits by it and computer_parse sorts its operable list by it. Kept as one
|
|
370
|
+
* function because the tiers used to exist twice and had already started to diverge.
|
|
371
|
+
*/
|
|
372
|
+
function rankMatch(m) {
|
|
373
|
+
if (m.isOffscreen === true) return 5; // unreachable without scrolling
|
|
374
|
+
if (PASS_THROUGH.has(String(m.controlType))) return 4; // containers: clicking only focuses the window
|
|
375
|
+
if (NAVIGATION.has(String(m.controlType))) return 3; // sidebar/list rows: navigation, not the target
|
|
376
|
+
if (COMMANDS.has(String(m.controlType)) && (m.patterns ?? []).some((p) => ACT_VERBS.has(p))) return 0; // a real command with a working pattern
|
|
377
|
+
if ((m.patterns ?? []).some((p) => ACT_VERBS.has(p))) return 1; // actionable but an unusual control type
|
|
378
|
+
return 2; // plain Text: readable, not clickable
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function elideRedundantContainers(nodes) {
|
|
382
|
+
const out = [];
|
|
383
|
+
const effByDepth = [];
|
|
384
|
+
for (const node of nodes) {
|
|
385
|
+
const depth = Math.max(0, Math.min(20, Number(node.depth ?? 0)));
|
|
386
|
+
const parentEff = depth === 0 ? -1 : (effByDepth[depth - 1] ?? depth - 1);
|
|
387
|
+
const unnamed = String(node.name ?? '').trim() === '';
|
|
388
|
+
const acts = (node.patterns ?? []).filter((p) => ACT_VERBS.has(p));
|
|
389
|
+
const redundant = unnamed && acts.length === 0 && PASS_THROUGH.has(String(node.controlType));
|
|
390
|
+
effByDepth[depth] = parentEff + (redundant ? 0 : 1);
|
|
391
|
+
if (!redundant) out.push({ ...node, depth: Math.max(0, effByDepth[depth]) });
|
|
392
|
+
}
|
|
393
|
+
return out;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Decide which OCR text is NOT already addressable through the element tree, and where to click.
|
|
398
|
+
* Exported as a pure function so the same rule is used by the tool, the unit tests and the live
|
|
399
|
+
* A/B measurement — a rule that only exists inside a tool handler cannot be tested or compared.
|
|
400
|
+
*/
|
|
401
|
+
// Exported so the measurement script compares against the SAME cover set the tool uses — a
|
|
402
|
+
// second copy in scripts/ had already become a divergence risk (measure-parse used to duplicate
|
|
403
|
+
// this list verbatim).
|
|
404
|
+
export const OCR_COVER = new Set(['Button', 'Edit', 'Text', 'Hyperlink', 'ListItem', 'MenuItem', 'CheckBox', 'RadioButton', 'TabItem', 'ComboBox', 'Slider', 'Spinner', 'TreeItem', 'DataItem', 'HeaderItem', 'Link']);
|
|
405
|
+
function ocrCoverers(nodes) {
|
|
406
|
+
return (nodes ?? []).filter((n) => OCR_COVER.has(String(n.controlType))
|
|
407
|
+
&& String(n.name ?? '').trim() !== ''
|
|
408
|
+
&& n.rect && n.rect.w > 0 && n.rect.h > 0
|
|
409
|
+
&& n.isOffscreen !== true);
|
|
410
|
+
}
|
|
411
|
+
function ocrTargets(nodes, words) {
|
|
412
|
+
const coverers = ocrCoverers(nodes);
|
|
413
|
+
const inRect = (r, x, y) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
|
|
414
|
+
const covered = (x, y) => coverers.some((n) => inRect(n.rect, x, y));
|
|
415
|
+
const grouped = groupOcrWords(words);
|
|
416
|
+
const targets = [];
|
|
417
|
+
for (const ln of grouped) {
|
|
418
|
+
const open = (ln.members ?? []).filter((m) => !covered(m.cx, m.cy));
|
|
419
|
+
if (open.length === 0) continue;
|
|
420
|
+
targets.push({ text: ln.text, words: ln.words, openWords: open.length, cx: open[0].cx, cy: open[0].cy, rect: ln.rect });
|
|
421
|
+
}
|
|
422
|
+
return { grouped, targets, coverers };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function aborted(signal) {
|
|
426
|
+
if (signal?.aborted === true) {
|
|
427
|
+
const error = new Error('cancelled by the caller; any action already delivered to the desktop is not rolled back');
|
|
428
|
+
error.code = 'cancelled';
|
|
429
|
+
throw error;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export function registerTools(ctx, { worker, store, dataDir, owned, finishRun, activity }) {
|
|
434
|
+
const recipeDir = join(dataDir, 'recipes');
|
|
435
|
+
const disposers = [];
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Turn-end without a turn hook.
|
|
439
|
+
*
|
|
440
|
+
* The host exposes no public "the agent finished this turn" event a plugin can subscribe to
|
|
441
|
+
* (afterResponse is ACP-internal), so the run cannot be closed from a callback. What IS
|
|
442
|
+
* observable is the thing that actually matters: whether the model is still driving the
|
|
443
|
+
* desktop. Every tool call in this file goes through `touch()`, so a model that stops calling
|
|
444
|
+
* tools starts a countdown instead of leaving the capsule up until the 300 s lease expires —
|
|
445
|
+
* the "agent 用完御屏后不会主动关闭" complaint. The lease stays the outer backstop; this is the
|
|
446
|
+
* faster inner one, and it fires only while a run is actually lit.
|
|
447
|
+
*
|
|
448
|
+
* Deliberately NOT a heartbeat: it never renews anything. It is armed by work and disarmed by
|
|
449
|
+
* finishing, so an idle session cannot keep the overlay alive.
|
|
450
|
+
*/
|
|
451
|
+
// `|| 20000` keeps a malformed env value (NaN) from making setTimeout fire immediately and tear
|
|
452
|
+
// down a run the moment it starts; the floor keeps negative values from doing the same.
|
|
453
|
+
const idleMs = Math.max(1000, Number(process.env.DSH_NATIVE_UIA_IDLE_MS ?? 20000) || 20000);
|
|
454
|
+
let idleTimer = null;
|
|
455
|
+
const disarmIdle = () => {
|
|
456
|
+
if (idleTimer !== null) clearTimeout(idleTimer);
|
|
457
|
+
idleTimer = null;
|
|
458
|
+
};
|
|
459
|
+
const touch = () => {
|
|
460
|
+
disarmIdle();
|
|
461
|
+
// Only arm while the overlay is lit: a read-only session that never started a run must not
|
|
462
|
+
// schedule a teardown for a run that does not exist.
|
|
463
|
+
if (store.running !== true) return;
|
|
464
|
+
idleTimer = setTimeout(fireIdle, idleMs);
|
|
465
|
+
idleTimer.unref?.();
|
|
466
|
+
};
|
|
467
|
+
const fireIdle = () => {
|
|
468
|
+
idleTimer = null;
|
|
469
|
+
if (store.running !== true) return;
|
|
470
|
+
// A command still in flight (40 s OCR, a long run) is not silence: without this guard the
|
|
471
|
+
// timer fired under a live action, finished the run out from under it, and the next action
|
|
472
|
+
// re-claimed — the capsule visibly flickered. Re-arm once; the wrapper's touch() after the
|
|
473
|
+
// command returns re-arms it properly anyway.
|
|
474
|
+
if (store.busy === true) {
|
|
475
|
+
idleTimer = setTimeout(fireIdle, idleMs);
|
|
476
|
+
idleTimer.unref?.();
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
store.line(`工具调用已静默 ${Math.round(idleMs / 1000)} 秒,自动收尾本轮`, 'info');
|
|
480
|
+
void finishRun({ summary: '', reason: 'idle' });
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
const refuse = (outcome, extra) => {
|
|
484
|
+
store.counters.refused++;
|
|
485
|
+
const entry = store.block({
|
|
486
|
+
reason: `策略拒绝:${outcome.refusal}`,
|
|
487
|
+
raw: extra ?? null,
|
|
488
|
+
});
|
|
489
|
+
return `[已拦截 ${entry.id}] ${outcome.refusal} 被本插件策略禁止。${outcome.advice}`;
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* One registration point, so "did the model touch the desktop?" is answered once for all
|
|
494
|
+
* eighteen tools instead of in every execute(). The wrapper keeps the original `this`, the
|
|
495
|
+
* marker that `defineTool` puts on the definition, and the return value; it only observes.
|
|
496
|
+
*/
|
|
497
|
+
const register = (definition) => {
|
|
498
|
+
const execute = definition.execute;
|
|
499
|
+
if (typeof execute === 'function') {
|
|
500
|
+
definition.execute = async function wrapped(args, exec) {
|
|
501
|
+
touch();
|
|
502
|
+
try {
|
|
503
|
+
return await execute.call(this, args, exec);
|
|
504
|
+
} finally {
|
|
505
|
+
touch();
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
return ctx.tools.register(definition);
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
disposers.push(register(defineTool({
|
|
513
|
+
name: 'computer_windows',
|
|
514
|
+
description: 'List the visible top-level windows on this desktop with their windowId, process and title. Call this before any other desktop work.',
|
|
515
|
+
parameters: {
|
|
516
|
+
app: { ...STR, description: 'Optional case-insensitive filter on process name or title' },
|
|
517
|
+
},
|
|
518
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
519
|
+
isConcurrencySafe: true,
|
|
520
|
+
async execute(args, exec) {
|
|
521
|
+
await aborted(exec.signal);
|
|
522
|
+
const result = await worker.call('list_windows', {});
|
|
523
|
+
let windows = result.windows ?? result ?? [];
|
|
524
|
+
if (args.app) {
|
|
525
|
+
const needle = String(args.app).toLowerCase();
|
|
526
|
+
windows = windows.filter((w) => `${w.appName} ${w.title}`.toLowerCase().includes(needle));
|
|
527
|
+
}
|
|
528
|
+
store.setWindows(windows);
|
|
529
|
+
return renderWindows(windows);
|
|
530
|
+
},
|
|
531
|
+
})));
|
|
532
|
+
|
|
533
|
+
disposers.push(register(defineTool({
|
|
534
|
+
name: 'computer_snapshot',
|
|
535
|
+
description: 'Read a window UI Automation tree and return its interactive elements with short refs (e1, e2, ...). Refs belong to one revision of one window: a newer snapshot invalidates the older refs. This is the primary observation channel and needs no vision model. Rhythm on large windows: take a shallow pass first (depth=4-5) to see the structural skeleton, locate the target container, then either computer_find_text into it or dig deeper with a higher depth/maxNodes — a deep pass over a big tree burns both latency and tokens.',
|
|
536
|
+
parameters: {
|
|
537
|
+
windowId: { ...STR, required: true, description: 'windowId from computer_windows' },
|
|
538
|
+
controlType: { ...STR, description: 'Keep only these control types, e.g. "Button,Edit,MenuItem"' },
|
|
539
|
+
nameContains: { ...STR, description: 'Keep only elements whose name contains this text' },
|
|
540
|
+
includeOffscreen: { ...BOOL, description: 'Include offscreen elements (default false)' },
|
|
541
|
+
depth: { ...INT, description: 'Max tree depth to walk. Omit = worker default 30 (near-full depth, not infinite). Recommended rhythm: depth=4-5 for a skeleton pass on a large window, then find_text into the located container or raise depth/maxNodes to dig into it.' },
|
|
542
|
+
maxNodes: { ...INT, description: 'Node budget for one snapshot (default 200). Raise it only when a truncated tree actually hid the control you need.' },
|
|
543
|
+
compact: { ...BOOL, description: 'Tighter rendering: shorter names and values. Use on large trees you are only scanning.' },
|
|
544
|
+
},
|
|
545
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
546
|
+
isConcurrencySafe: true,
|
|
547
|
+
async execute(args, exec) {
|
|
548
|
+
await aborted(exec.signal);
|
|
549
|
+
// 200, not 300: every node costs a COM round-trip (~5-18 ms) AND tokens, and the tail of a
|
|
550
|
+
// big tree is usually chrome the model never acts on. A truncated tree says so and names the
|
|
551
|
+
// two ways out (tighter filter or a higher maxNodes), so the default trades a rare extra call
|
|
552
|
+
// for a materially faster, smaller snapshot on the common case.
|
|
553
|
+
const result = await worker.call('snapshot', {
|
|
554
|
+
windowId: args.windowId,
|
|
555
|
+
maxNodes: args.maxNodes ?? 200,
|
|
556
|
+
// Pass-through: JSON.stringify drops the key when depth is omitted, so the worker keeps
|
|
557
|
+
// its own default (maxDepth=30) — an omitted argument changes nothing downstream.
|
|
558
|
+
maxDepth: args.depth,
|
|
559
|
+
filter: {
|
|
560
|
+
controlType: args.controlType,
|
|
561
|
+
nameContains: args.nameContains,
|
|
562
|
+
includeOffscreen: args.includeOffscreen,
|
|
563
|
+
},
|
|
564
|
+
});
|
|
565
|
+
const nodes = result.nodes ?? [];
|
|
566
|
+
store.setTree(nodes, { windowId: args.windowId, revision: result.revision });
|
|
567
|
+
store.setTarget(windowOf(store, args.windowId) ?? { windowId: args.windowId });
|
|
568
|
+
const head = `窗口 ${args.windowId} 第 ${result.revision} 版:${nodes.length} 个元素${result.truncated === true ? '(已截断——收紧过滤条件、用 find_text 定位、提高 maxNodes,或先浅 depth=4-5 看骨架再局部深挖)' : ''}`;
|
|
569
|
+
// 位置元数据(前台/焦点/采集耗时):动作后下一次观察的焦点变化即零成本「动作生效证据」,
|
|
570
|
+
// 焦点不在目标窗时附一句修正指引。全部为 advisory 字段,worker 探测失败时不渲染。
|
|
571
|
+
return `${head}${observationLine(result)}${snapshotNotes(result)}\n${renderActionables(nodes)}${renderTree(nodes, { compact: args.compact === true })}`;
|
|
572
|
+
},
|
|
573
|
+
})));
|
|
574
|
+
|
|
575
|
+
disposers.push(register(defineTool({
|
|
576
|
+
name: 'computer_find_text',
|
|
577
|
+
description: 'Find elements by visible text in one window WITHOUT pulling the whole tree: returns each match with its clickable screen center and a `by` descriptor. Use it to locate one control in a big window (a full snapshot would be huge), to get coordinates for computer_click, or to build computer_run steps whose `by` survives layout drift. This is the named command the click guidance refers to ("find_text center"). Cost note: it enumerates the window\'s whole element tree (about 1-3 ms per element), so on a window with thousands of elements prefer a specific text fragment; a budget/max overrun returns the collected hits marked truncated with the total match count.',
|
|
578
|
+
parameters: {
|
|
579
|
+
windowId: { ...STR, required: true, description: 'windowId from computer_windows' },
|
|
580
|
+
text: { ...STR, required: true, description: 'text to look for in element names/values' },
|
|
581
|
+
exact: { ...BOOL, description: 'exact match instead of substring (default false)' },
|
|
582
|
+
max: { ...INT, description: 'max matches to return (default 60)' },
|
|
583
|
+
},
|
|
584
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
585
|
+
isConcurrencySafe: true,
|
|
586
|
+
async execute(args, exec) {
|
|
587
|
+
await aborted(exec.signal);
|
|
588
|
+
const text0 = String(args.text ?? '');
|
|
589
|
+
if (text0 === '') return 'computer_find_text 需要非空 text';
|
|
590
|
+
const result = await worker.call('find_text', {
|
|
591
|
+
windowId: args.windowId,
|
|
592
|
+
text: text0,
|
|
593
|
+
exact: args.exact === true,
|
|
594
|
+
max: args.max,
|
|
595
|
+
});
|
|
596
|
+
const matches = result.matches ?? [];
|
|
597
|
+
if (matches.length === 0) {
|
|
598
|
+
const zeroTail = result.truncated === true
|
|
599
|
+
? '(注意:搜索在请求预算内没有扫完整棵树,已有命中已随截断丢弃——收紧 text、换更独特的片段,或分窗口再搜)'
|
|
600
|
+
: '';
|
|
601
|
+
return `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素:没有包含 "${str(text0, 40)}" 的元素${args.exact === true ? '(精确匹配模式)' : ''}${zeroTail}`;
|
|
602
|
+
}
|
|
603
|
+
// Ranking, not just filtering. Searching "插件" in this very window returns the window's own
|
|
604
|
+
// Pane and Document first — both carry the title, both are 1941x1243, and clicking either just
|
|
605
|
+
// focuses the window. The real Button was third. A model reading top-down picks match #1 and
|
|
606
|
+
// "misses the click" even though the coordinates were perfect.
|
|
607
|
+
//
|
|
608
|
+
// The ranking is a small explicit cost, most important first:
|
|
609
|
+
// 1. offscreen last — a hit outside the viewport cannot be clicked without scrolling, so it
|
|
610
|
+
// must never outrank something already visible;
|
|
611
|
+
// 2. containers (Pane/Document/Window/Group) last — clicking them only focuses the window;
|
|
612
|
+
// 3. TreeItem/ListItem demoted — a sidebar session title carries SelectionItem and so
|
|
613
|
+
// "looks actionable", but it is navigation, not the control the model is after;
|
|
614
|
+
// 4. real commands (Button/MenuItem/Tab/CheckBox/...) first.
|
|
615
|
+
// Text is deliberately NOT actionable: it carries the Text pattern, and treating that as an
|
|
616
|
+
// action made every paragraph of the chat log compete with the menu item being searched for.
|
|
617
|
+
// The tiers themselves live in the module-level rankMatch() so find_text and computer_parse
|
|
618
|
+
// sort by ONE shared ranking (they used to be two copies and could drift).
|
|
619
|
+
const CONTAINERS = PASS_THROUGH;
|
|
620
|
+
const isContainer = (m) => CONTAINERS.has(String(m.controlType));
|
|
621
|
+
const actionable = (m) => (m.patterns ?? []).some((p) => ACT_VERBS.has(p));
|
|
622
|
+
const ranked = [...matches].map((m, i) => ({ m, i }))
|
|
623
|
+
.sort((a, b) => {
|
|
624
|
+
const d = rankMatch(a.m) - rankMatch(b.m);
|
|
625
|
+
return d !== 0 ? d : a.i - b.i; // stable: keep the scan order inside a tier
|
|
626
|
+
})
|
|
627
|
+
.map((x) => x.m);
|
|
628
|
+
const lines = ranked.map((m, i) => {
|
|
629
|
+
const flags = [m.enabled === false ? 'disabled' : '', m.isOffscreen === true ? 'offscreen' : ''].filter(Boolean).join(' ');
|
|
630
|
+
// Say out loud when a hit is a container: "这个点了只是聚焦窗口" is exactly the mistake the
|
|
631
|
+
// ranking is trying to prevent, and a label survives whatever order the model reads in.
|
|
632
|
+
const hint = isContainer(m) && !actionable(m) ? ' ←容器,click 只会聚焦窗口' : '';
|
|
633
|
+
const acts = (m.patterns ?? []).filter((p) => ACT_VERBS.has(p));
|
|
634
|
+
const actStr = acts.length === 0 ? '' : ` 可作=${acts.join(',')}`;
|
|
635
|
+
// Same-name collisions are the other half of "点不准": this window has both a Button "插件"
|
|
636
|
+
// and a Text "插件", and clicking the Text does nothing visible. When other hits share this
|
|
637
|
+
// exact name, name the count and say which one to take.
|
|
638
|
+
const twins = ranked.filter((o) => o !== m && o.name === m.name).length;
|
|
639
|
+
const twinHint = twins > 0
|
|
640
|
+
? (actionable(m) ? ` (同名 ${twins + 1} 个,这个可操作)` : ` (同名 ${twins + 1} 个,这个不可操作——别选它)`)
|
|
641
|
+
: '';
|
|
642
|
+
const refStr = m.ref ? ` ref=${m.ref}` : '';
|
|
643
|
+
return `${i + 1}. ${m.controlType} "${str(m.name, 48)}" 中心=(${m.center?.x},${m.center?.y})${refStr}${actStr}${m.className ? ` class=${str(m.className, 24)}` : ''}${flags ? ` ${flags}` : ''}${hint}${twinHint} by=${JSON.stringify(m.by)}`;
|
|
644
|
+
});
|
|
645
|
+
const head = `窗口 ${args.windowId}(第 ${result.revision ?? '?'} 版)扫描 ${result.scanned ?? '?'} 个元素,命中 ${matches.length} 个"${str(text0, 40)}"${args.exact === true ? '(精确)' : ''}(可见命令元素在前,容器/侧栏行/屏外元素在后):`;
|
|
646
|
+
// Observation parity with snapshot's truncation report: the worker now counts EVERY match
|
|
647
|
+
// (matchedTotal) and flags max/budget cuts, so silently dropped hits become visible. The
|
|
648
|
+
// ranking happens on the returned subset, so dropped hits cannot be rescued here — the
|
|
649
|
+
// caller must tighten text or raise max.
|
|
650
|
+
const truncNote = result.truncated === true
|
|
651
|
+
? `\n⚠ 命中总数 ${result.matchedTotal ?? '?'} 个,只返回了前 ${matches.length} 个(max/请求预算截断)。收紧 text、提高 max,或用更独特的片段缩小范围。`
|
|
652
|
+
: '';
|
|
653
|
+
// 位置元数据,与 snapshot 头部同一条渲染通道(见 observationLine)。
|
|
654
|
+
return `${head}${truncNote}${observationLine(result)}\n${lines.join('\n')}\n带 ref 的项可直接用 computer_act;没有 ref 的用 computer_click 传中心坐标;by 描述符可放进 computer_run/computer_replay 的 steps。`;
|
|
655
|
+
},
|
|
656
|
+
})));
|
|
657
|
+
|
|
658
|
+
disposers.push(register(defineTool({
|
|
659
|
+
name: 'computer_parse',
|
|
660
|
+
description: 'One fused, actionable view of a window for a model that cannot see the screen: the UIA tree PLUS OCR of the rendered pixels. Text that Windows OCR reads but no named UIA element already covers is appended as clickable pseudo-targets (screen x,y). This is how you drive self-drawn / UIA-hostile apps (canvas UIs, custom toolkits, some Electron/Qt/Java apps, games) where computer_snapshot returns almost nothing. Use the listed x,y with computer_click; use a ref with computer_act for real UIA elements. Adds no model — OCR is the OS component, the shim is ~7 KB.',
|
|
661
|
+
parameters: {
|
|
662
|
+
windowId: { ...STR, required: true, description: 'windowId from computer_windows' },
|
|
663
|
+
maxNodes: { ...INT, description: 'UIA node budget (default 300)' },
|
|
664
|
+
includeUia: { ...BOOL, description: 'also list the UIA interactive elements (default true)' },
|
|
665
|
+
},
|
|
666
|
+
output: { schema: STR, render: (_a, v) => text(v) },
|
|
667
|
+
timeoutMs: 45000,
|
|
668
|
+
async execute(args, exec) {
|
|
669
|
+
await aborted(exec.signal);
|
|
670
|
+
const winId = String(args.windowId);
|
|
671
|
+
const snap = await worker.call('snapshot', { windowId: winId, maxNodes: args.maxNodes });
|
|
672
|
+
store.setTree(snap.nodes ?? [], { windowId: winId, revision: snap.revision });
|
|
673
|
+
store.setTarget(windowOf(store, winId) ?? { windowId: winId });
|
|
674
|
+
let ocr = null;
|
|
675
|
+
let ocrError = '';
|
|
676
|
+
try {
|
|
677
|
+
ocr = await worker.call('ocr', { windowId: winId }, { timeoutMs: 40000 });
|
|
678
|
+
} catch (error) {
|
|
679
|
+
await aborted(exec.signal);
|
|
680
|
+
ocrError = `${error.code ?? 'ocr_failed'}: ${error.message ?? error}`;
|
|
681
|
+
}
|
|
682
|
+
const nodes = snap.nodes ?? [];
|
|
683
|
+
const words = ocr?.words ?? [];
|
|
684
|
+
// Only a real control or label "covers" text. A big container (Window/Pane/Document/Group)
|
|
685
|
+
// merely encloses the whole client area — if it counted, OCR would be suppressed on exactly
|
|
686
|
+
const { grouped, targets: gapLines } = ocrTargets(nodes, words);
|
|
687
|
+
const lines = [];
|
|
688
|
+
lines.push(`窗口 ${winId}(第 ${snap.revision ?? '?'} 版):UIA ${nodes.length} 元素 / OCR ${words.length} 词合并为 ${grouped.length} 行,其中 ${gapLines.length} 行有 UIA 没读到的可点文字。${snapshotNotes(snap)}`);
|
|
689
|
+
if (ocrError) lines.push(`⚠ OCR 不可用(${str(ocrError, 240)}),以下 UIA 结果仍然可用。`);
|
|
690
|
+
if (gapLines.length > 0) {
|
|
691
|
+
lines.push('— OCR 可点击目标(computer_click 传这些 x,y;一行一个目标,点是没被 UIA 覆盖的那部分)—');
|
|
692
|
+
for (const g of gapLines.slice(0, 120)) {
|
|
693
|
+
const partial = g.openWords < g.words ? ` (${g.words - g.openWords}/${g.words} 字已被 UIA 覆盖)` : '';
|
|
694
|
+
lines.push(` "${str(g.text, 60)}" (${g.cx},${g.cy})${partial}`);
|
|
695
|
+
}
|
|
696
|
+
if (gapLines.length > 120) lines.push(` …另 ${gapLines.length - 120} 行省略`);
|
|
697
|
+
}
|
|
698
|
+
if (args.includeUia !== false) {
|
|
699
|
+
// Same vocabulary as find_text: only nodes carrying a verb the model can actually issue are
|
|
700
|
+
// operable, ranked by the shared rankMatch (commands first, navigation/container rows and
|
|
701
|
+
// offscreen last). The old filter took ANY pattern-bearing node — Text paragraphs and the
|
|
702
|
+
// enclosing Pane competed with buttons, and in auto mode acting on one fell through to a
|
|
703
|
+
// physical pixel click on the paragraph's center.
|
|
704
|
+
const inter = nodes
|
|
705
|
+
.filter((n) => (n.patterns ?? []).some((p) => ACT_VERBS.has(p)))
|
|
706
|
+
.sort((a, b) => rankMatch(a) - rankMatch(b));
|
|
707
|
+
const off = inter.filter((n) => n.isOffscreen === true).length;
|
|
708
|
+
lines.push(`— UIA 可操作元素 ${inter.length} 个(命令控件在前,导航行/容器靠后,屏外最后;与 find_text 同一排序)${off > 0 ? `(其中 ${off} 个屏外,坐标不可直接点,需先滚动或调整窗口)` : ''}(computer_act 传 ref)—`);
|
|
709
|
+
for (const n of inter.slice(0, 80)) {
|
|
710
|
+
const c = n.rect ? `(${Math.round(n.rect.x + n.rect.w / 2)},${Math.round(n.rect.y + n.rect.h / 2)})` : '';
|
|
711
|
+
const off = n.isOffscreen === true ? ' 屏外' : '';
|
|
712
|
+
lines.push(` ${n.ref ?? '-'} ${n.controlType} "${str(n.name, 40)}" ${c}${off}`);
|
|
713
|
+
}
|
|
714
|
+
if (inter.length > 80) lines.push(` …另 ${inter.length - 80} 个省略`);
|
|
715
|
+
}
|
|
716
|
+
return lines.join('\n');
|
|
717
|
+
},
|
|
718
|
+
})));
|
|
719
|
+
|
|
720
|
+
disposers.push(register(defineTool({
|
|
721
|
+
name: 'computer_act',
|
|
722
|
+
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.',
|
|
723
|
+
parameters: {
|
|
724
|
+
windowId: { ...STR, required: true },
|
|
725
|
+
ref: { ...STR, required: true, description: 'Element ref from the newest snapshot of this window' },
|
|
726
|
+
action: { type: 'string', enum: ['invoke', 'set_value', 'toggle', 'select', 'expand', 'collapse', 'scroll_up', 'scroll_down', 'focus', 'text_append'], required: true },
|
|
727
|
+
value: { ...STR, description: 'Text for set_value / text_append' },
|
|
728
|
+
revision: { ...INT, description: 'The revision the ref came from; omit to use the newest snapshot' },
|
|
729
|
+
verify: { type: 'json', description: 'Optional {type, expect, timeoutMs} check run locally right after the action' },
|
|
730
|
+
},
|
|
731
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
732
|
+
timeoutMs: 60000,
|
|
733
|
+
async execute(args, exec) {
|
|
734
|
+
await aborted(exec.signal);
|
|
735
|
+
const label = `${args.action} ${args.ref}${args.value ? ` "${str(args.value, 30)}"` : ''}`;
|
|
736
|
+
const described = await worker.call('describe', { ref: args.ref });
|
|
737
|
+
const outcome = classify({ action: args.action, descriptor: described });
|
|
738
|
+
if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_act', ...args, descriptor: described });
|
|
739
|
+
const result = await worker.call('act', {
|
|
740
|
+
ref: args.ref,
|
|
741
|
+
action: args.action,
|
|
742
|
+
value: args.value,
|
|
743
|
+
revision: args.revision,
|
|
744
|
+
verify: args.verify,
|
|
745
|
+
mode: store.pointerMode,
|
|
746
|
+
// Node's 30 s default is the only hard cap otherwise: the worker widens its own budget to
|
|
747
|
+
// args.timeoutMs+2500, so a verify window near the tool cap would hit the Node timeout
|
|
748
|
+
// first and the late reply would be dropped as an unknown id.
|
|
749
|
+
}, { timeoutMs: 68000 });
|
|
750
|
+
store.actionDone(1);
|
|
751
|
+
// A missed verify must not read as a passed step: applied stays true (the action WAS
|
|
752
|
+
// delivered), but the step status, the opening word and the follow-up advice all have to
|
|
753
|
+
// say "delivered, not confirmed" — otherwise the model retries a click that may already
|
|
754
|
+
// have fired (the batch path hard-stops on verify_failed; the single path used to sail on).
|
|
755
|
+
const verifyMissed = result.verify != null && result.verify.matched !== true;
|
|
756
|
+
store.step({
|
|
757
|
+
label,
|
|
758
|
+
status: verifyMissed ? 'verify_failed' : (result.status ?? (result.applied === false ? 'failed' : 'passed')),
|
|
759
|
+
ms: result.ms,
|
|
760
|
+
verify: result.verify?.type ? `${result.verify.type}:${result.verify.matched === true ? 'matched' : 'unmatched'}` : null,
|
|
761
|
+
detail: result.detail,
|
|
762
|
+
});
|
|
763
|
+
// Only show before/after when the element actually has a value to show. A Button reports an
|
|
764
|
+
// empty Value, and printing before="" after="" invites the reader to think "nothing changed".
|
|
765
|
+
const hasValue = (v) => v !== undefined && v !== null && String(v) !== '';
|
|
766
|
+
const state = (hasValue(result.before) || hasValue(result.after))
|
|
767
|
+
? ` before=${JSON.stringify(result.before ?? null)} after=${JSON.stringify(result.after ?? null)}`
|
|
768
|
+
: '';
|
|
769
|
+
// The verify verdict in the same Chinese shape the batch path renders (the old English
|
|
770
|
+
// "verify=value_equals:unmatched" detail was a third format for the same data), plus the
|
|
771
|
+
// observed reading the worker captured while waiting — that is what tells "还没生效" apart
|
|
772
|
+
// from "值就不对".
|
|
773
|
+
const verifyText = result.verify ? ` 校验=${result.verify.matched === true ? '命中' : '未命中'}(${result.verify.type ?? '?'})` : '';
|
|
774
|
+
const effect = result.verify ? (result.verify.matched === true ? ' 效果=校验命中' : ' 效果=校验未命中') : '';
|
|
775
|
+
const observed = verifyMissed && result.verify.observed !== undefined && result.verify.observed !== null
|
|
776
|
+
? ` 当前读数=${JSON.stringify(result.verify.observed)}`
|
|
777
|
+
: '';
|
|
778
|
+
const missNote = verifyMissed
|
|
779
|
+
? '\n⚠ 校验未命中(动作已送达):可原样重试一次;仍不生效就用 computer_find_text 重新定位(同名元素加 nth)或重新 computer_snapshot 后再操作,不要连续盲重试。'
|
|
780
|
+
: '';
|
|
781
|
+
// A warning must name a real failure. before===after is NOT one: `before`/`after` read the
|
|
782
|
+
// element's Value, and a Button has no Value at all — so every successful invoke on a normal
|
|
783
|
+
// button reported before="" after="" and got flagged as "no state change". The honest test is
|
|
784
|
+
// the element's own capabilities: if it exposes no pattern for this verb, the call could not
|
|
785
|
+
// have done anything; if it does, the pattern ran and the caller should verify with `verify`
|
|
786
|
+
// (or a fresh snapshot) rather than be told its action was a no-op.
|
|
787
|
+
// Only patterns the managed UIA client can actually obtain (they must exist in the worker's
|
|
788
|
+
// $patternTypes table, which has no LegacyIAccessible entry — there is no managed type for
|
|
789
|
+
// it, so listing it here made the invoke/set_value checks pass on a name GetPattern could
|
|
790
|
+
// never resolve; the same logic rules out ScrollItem, which the worker's scroll path does
|
|
791
|
+
// not fetch either). focus is deliberately absent: it needs no pattern at all (plain
|
|
792
|
+
// SetFocus), and requiring one made every focus call read as incapable.
|
|
793
|
+
const NEEDED = {
|
|
794
|
+
invoke: ['Invoke'],
|
|
795
|
+
set_value: ['Value'],
|
|
796
|
+
text_append: ['Value'],
|
|
797
|
+
toggle: ['Toggle'],
|
|
798
|
+
select: ['SelectionItem'],
|
|
799
|
+
expand: ['ExpandCollapse'],
|
|
800
|
+
collapse: ['ExpandCollapse'],
|
|
801
|
+
scroll_up: ['Scroll'],
|
|
802
|
+
scroll_down: ['Scroll'],
|
|
803
|
+
};
|
|
804
|
+
const have = Array.isArray(described?.availablePatterns) ? described.availablePatterns : [];
|
|
805
|
+
const need = NEEDED[String(args.action)] ?? [];
|
|
806
|
+
const capable = need.length === 0 || need.some((p) => have.includes(p));
|
|
807
|
+
const noop = result.applied === false || !capable;
|
|
808
|
+
// Two different failures get two different words: "applied=false" is the worker saying the
|
|
809
|
+
// action was NOT delivered; a missing pattern in the capability table means it WAS delivered
|
|
810
|
+
// (via=uia) but may have done nothing — saying "已执行…没有真正执行" to that case read as a
|
|
811
|
+
// contradiction, so the honest wording names the uncertainty instead.
|
|
812
|
+
const warn = noop
|
|
813
|
+
? (result.applied === false
|
|
814
|
+
? `\n⚠ 这一步没有真正执行:worker 报告动作未送达(applied=false)。`
|
|
815
|
+
: `\n⚠ 能力存疑:${args.ref}(${described?.controlType ?? '未知类型'})的能力表里没有 ${args.action} 所需的 pattern(需要 ${need.join(' 或 ')}),它支持 [${have.join(',') || '无'}]。`
|
|
816
|
+
+ `动作已按 ${result.via ?? 'uia'} 送达,但可能没有生效——请加 verify 或重新快照确认界面后再继续;`
|
|
817
|
+
+ `或改用支持该动作的元素(例如这类元素通常用 focus 或直接 click 坐标)。`)
|
|
818
|
+
: '';
|
|
819
|
+
return `${result.applied === false ? '未执行' : verifyMissed ? '⚠ 校验未命中(动作已送达,勿直接重试)' : '已执行'} ${label},耗时 ${result.ms ?? '?'}ms${state}${verifyText}${effect}${observed}${result.detail && !result.verify ? ` ${str(result.detail, 160)}` : ''}${missNote}${warn}`;
|
|
820
|
+
},
|
|
821
|
+
})));
|
|
822
|
+
|
|
823
|
+
disposers.push(register(defineTool({
|
|
824
|
+
name: 'computer_run',
|
|
825
|
+
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. 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.',
|
|
826
|
+
parameters: {
|
|
827
|
+
windowId: { ...STR, required: true },
|
|
828
|
+
goal: { ...STR, required: true, description: 'One sentence describing the outcome this batch produces; stored with the recipe' },
|
|
829
|
+
steps: { ...JSON_ARR, required: true, description: '[{ref|by, action, value?, verify?, timeoutMs?}]' },
|
|
830
|
+
saveRecipe: { ...BOOL, description: 'Save a replayable recipe when every step passes (default true)' },
|
|
831
|
+
},
|
|
832
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
833
|
+
timeoutMs: 180000,
|
|
834
|
+
async execute(args, exec) {
|
|
835
|
+
await aborted(exec.signal);
|
|
836
|
+
const steps = Array.isArray(args.steps) ? args.steps : [];
|
|
837
|
+
if (steps.length === 0) return 'computer_run 需要非空的 steps 数组';
|
|
838
|
+
const prepared = await worker.call('prepare_batch', { steps, windowId: args.windowId }, { timeoutMs: 188000 });
|
|
839
|
+
const prepError = preparationFailure(prepared, steps.length);
|
|
840
|
+
if (prepError) {
|
|
841
|
+
store.step({ label: `批量「${str(args.goal, 40)}」`, kind: 'batch', status: 'failed', detail: prepError });
|
|
842
|
+
return prepError;
|
|
843
|
+
}
|
|
844
|
+
const descriptors = prepared.descriptors ?? [];
|
|
845
|
+
const batchDeny = classifyBatch(steps, descriptors);
|
|
846
|
+
if (batchDeny) {
|
|
847
|
+
store.step({ label: `批量「${str(args.goal, 40)}」`, kind: 'batch', status: 'blocked', detail: `第 ${batchDeny.index} 步:${batchDeny.refusal}` });
|
|
848
|
+
return `${refuse(batchDeny, { tool: 'computer_run', goal: args.goal, stepIndex: batchDeny.index, step: steps[batchDeny.index], descriptor: descriptors[batchDeny.index] ?? null })}\n这一批一个动作都没执行(performedCount=0)。`
|
|
849
|
+
+ '\n去掉或替换被拒的那一步,再重新提交整批。';
|
|
850
|
+
}
|
|
851
|
+
// commit_batch Err 之前裸抛给模型:控制页 step 缺一条记录,自纠引导只能靠模型自己猜。
|
|
852
|
+
// 按 code 翻译成下一步该做什么。
|
|
853
|
+
let committed;
|
|
854
|
+
try {
|
|
855
|
+
// indicatorPid lets the worker's window diff exclude our own overlay capsule (it lights
|
|
856
|
+
// asynchronously at claim, so a cold first batch can genuinely "see" it appear). 0 when
|
|
857
|
+
// the overlay is down — the diff then just reports what it saw.
|
|
858
|
+
committed = await worker.call('commit_batch', { revision: prepared.revision, steps, windowId: args.windowId, mode: store.pointerMode, indicatorPid: activity?.indicator?.proc?.pid ?? 0 }, { timeoutMs: 188000 });
|
|
859
|
+
} catch (error) {
|
|
860
|
+
const code = String(error?.code ?? '');
|
|
861
|
+
// 用户在批次在飞时按 Esc / 控制页终止(index.js 的 Esc 路径与 kill 同一收尾:关掉 worker),
|
|
862
|
+
// 在飞的 commit_batch 以 WorkerDeadError 落到这里。这批不是「一个动作都没有执行」:
|
|
863
|
+
// 已送达的步骤不回滚,剩余步骤不再执行,也绝不能回话「通过」或落配方。
|
|
864
|
+
if (code === 'worker_dead') {
|
|
865
|
+
const byUser = store.killed === true;
|
|
866
|
+
const detail = `${byUser ? '用户已终止本轮(Esc/控制页)' : 'worker 进程中途停止'}:批次在飞时被打断,剩余步骤不再执行,已完成的动作不回滚。先 computer_snapshot 重新观察桌面,再决定怎么继续。`;
|
|
867
|
+
store.step({ label: `批量「${str(args.goal, 40)}」`, kind: 'batch', status: 'failed', detail });
|
|
868
|
+
return detail;
|
|
869
|
+
}
|
|
870
|
+
const guide = code === 'stale_revision' || code === 'revision_mismatch'
|
|
871
|
+
? '批次修订号已过期(界面在此期间更新过,一个动作都没有执行)。直接重新发起同样的 computer_run 即可——会自动重新 prepare,不需要手动刷新。'
|
|
872
|
+
: code === 'descriptor_unresolved'
|
|
873
|
+
? '至少一个步骤的描述符解析不到元素,一个动作都没有执行。先用 find_text / computer_snapshot 更新定位;目标若由前一步才生成,请拆成两批执行。'
|
|
874
|
+
: code === 'unknown_window'
|
|
875
|
+
? `窗口 ${args.windowId} 已不存在或尚未登记。先用 computer_windows / computer_resolve_window 拿到有效 windowId 再重发。`
|
|
876
|
+
: `commit_batch 失败(${code || 'worker_error'}):${error?.message ?? error}。一个动作都没有执行;先重新观察窗口再重试。`;
|
|
877
|
+
const detail = `批量未执行(performedCount=0):${guide}`;
|
|
878
|
+
store.step({ label: `批量「${str(args.goal, 40)}」`, kind: 'batch', status: 'failed', detail });
|
|
879
|
+
return detail;
|
|
880
|
+
}
|
|
881
|
+
// 轻点 Esc 未必来得及杀掉 worker:单线程的 worker 把排队的 shutdown 命令放在批次之后,
|
|
882
|
+
// 批次可能先跑完、结果正常返回。此时 killed 闩锁仍亮着,是「用户在本批在飞期间要求停止」
|
|
883
|
+
// 的唯一可靠信号——必须挡住配方落盘,并把回话从「通过」改成「已终止」。
|
|
884
|
+
const userStopped = store.killed === true;
|
|
885
|
+
const results = committed.results ?? [];
|
|
886
|
+
for (const r of results) {
|
|
887
|
+
store.step({ label: `第 ${r.index} 步 ${r.action} ${r.ref ?? ''}`, status: r.status, ms: r.ms, verify: r.verify, detail: r.detail });
|
|
888
|
+
}
|
|
889
|
+
store.actionDone(committed.performedCount ?? results.filter((r) => r.performed === true).length);
|
|
890
|
+
const allPassed = !userStopped && committed.stoppedAt === null && results.length === steps.length && results.every((r) => r.status === 'passed');
|
|
891
|
+
let recipeNote = '';
|
|
892
|
+
if (allPassed && args.saveRecipe !== false) {
|
|
893
|
+
const name = await saveRecipe(recipeDir, {
|
|
894
|
+
goal: args.goal,
|
|
895
|
+
window: descriptors[0]?.ownerWindow ?? windowOf(store, args.windowId),
|
|
896
|
+
revision: prepared.revision,
|
|
897
|
+
steps: steps.map((step, i) => ({
|
|
898
|
+
action: step.action,
|
|
899
|
+
value: step.value,
|
|
900
|
+
verify: step.verify,
|
|
901
|
+
by: step.by ? structuredClone(step.by) : recipeBy(descriptors[i]),
|
|
902
|
+
})),
|
|
903
|
+
});
|
|
904
|
+
recipeNote = `\n已存配方:${name}(之后用 computer_replay 回放)`;
|
|
905
|
+
}
|
|
906
|
+
const cancelledNote = (userStopped || committed.status === 'cancelled')
|
|
907
|
+
? '\n用户已终止本轮(Esc/控制页):已完成的动作不回滚。'
|
|
908
|
+
: '';
|
|
909
|
+
// stoppedNote branches on committed.status: a user Esc gets "pause and ask", not the
|
|
910
|
+
// "re-observe and continue" wording a failed/verify_failed stop gets.
|
|
911
|
+
const stopped = stoppedNote(committed);
|
|
912
|
+
// A dialog that popped mid-batch must not wait for the model's next observation —
|
|
913
|
+
// render the hwnd diff (worker already excluded our overlay pid; this filters again).
|
|
914
|
+
return `${renderResults(results, committed.performedCount ?? 0)}${stopped}${cancelledNote}${recipeNote}${newWindowNote(committed.newWindows, activity?.indicator?.proc?.pid ?? 0)}${locatorNotes(descriptors, results)}`;
|
|
915
|
+
},
|
|
916
|
+
})));
|
|
917
|
+
|
|
918
|
+
disposers.push(register(defineTool({
|
|
919
|
+
name: 'computer_capture',
|
|
920
|
+
description: 'Capture the screen as a PNG while it stays in the background: scope="window" (default) captures one window, scope="screen" captures the whole desktop across every monitor. Pixels are a fallback channel for canvas-drawn or accessibility-hostile surfaces; prefer computer_snapshot. The PNG is downscaled to maxDim, so the result includes a coordinateMap to convert image pixels to screen pixels for computer_click. Pass maxDim=0 for native 1:1 physical pixels.',
|
|
921
|
+
parameters: {
|
|
922
|
+
windowId: { ...STR, description: 'windowId for scope="window" (required there); ignored for scope="screen"' },
|
|
923
|
+
scope: { type: 'string', enum: ['window', 'screen'], description: 'window (default) = one window; screen = the whole desktop, all monitors' },
|
|
924
|
+
maxDim: { ...INT, description: 'cap the LONGER edge in px to bound tokens; not a target width. Omitted = native 1:1 (scale 1, real pixels) for both scopes. Pass a number to trade size for tokens; 0 means native 1:1 explicitly.' },
|
|
925
|
+
},
|
|
926
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
927
|
+
timeoutMs: 60000,
|
|
928
|
+
async execute(args, exec) {
|
|
929
|
+
await aborted(exec.signal);
|
|
930
|
+
const scope = args.scope === 'screen' ? 'screen' : 'window';
|
|
931
|
+
const capArgs = {};
|
|
932
|
+
// Both scopes default to native 1:1: a silently downscaled capture reads as "the screen was
|
|
933
|
+
// cut off" and forces the model to do scale arithmetic. Passing maxDim opts into downscaling.
|
|
934
|
+
if (typeof args.maxDim === 'number' && Number.isFinite(args.maxDim)) capArgs.maxDim = args.maxDim;
|
|
935
|
+
if (scope === 'screen') {
|
|
936
|
+
// nothing else to prepare; the worker measures the virtual screen itself
|
|
937
|
+
} else {
|
|
938
|
+
if (args.windowId === undefined || String(args.windowId) === '') {
|
|
939
|
+
return 'scope="window" 需要 windowId;要截整个桌面请传 scope="screen"。';
|
|
940
|
+
}
|
|
941
|
+
capArgs.windowId = String(args.windowId);
|
|
942
|
+
}
|
|
943
|
+
// A DESKTOP capture samples the composited screen, so it would contain our own topmost
|
|
944
|
+
// indicator (and, when the preview is open, a recursive screenshot of itself). Hide it for
|
|
945
|
+
// exactly the GDI sampling window, then restore the same run phase.
|
|
946
|
+
// A WINDOW capture uses PrintWindow(hwnd), which renders that window alone and therefore
|
|
947
|
+
// never contains the overlay — suspending there would only add a visible flicker for nothing.
|
|
948
|
+
const capture = () => worker.call(scope === 'screen' ? 'capture_screen' : 'capture', capArgs, { timeoutMs: 45000 });
|
|
949
|
+
const result = scope === 'screen' && activity?.withoutIndicator
|
|
950
|
+
? await activity.withoutIndicator(capture)
|
|
951
|
+
: await capture();
|
|
952
|
+
const png = Buffer.from(result.pngBase64 ?? '', 'base64');
|
|
953
|
+
const file = join(dataDir, `${scope === 'screen' ? 'screen' : 'capture'}-${Date.now()}.png`);
|
|
954
|
+
await mkdir(dataDir, { recursive: true });
|
|
955
|
+
await writeFile(file, png);
|
|
956
|
+
store.setScreenshot({ path: file, windowId: args.windowId, scope, width: result.width, height: result.height, method: result.method, blank: result.blank === true, bytes: png.length });
|
|
957
|
+
// Captures are throwaway observations, but each call wrote a new timestamped file with no
|
|
958
|
+
// cleanup — unbounded growth on a tight disk. Prune to the newest few (best-effort: a failed
|
|
959
|
+
// delete must never fail the capture the user asked for).
|
|
960
|
+
try {
|
|
961
|
+
const names = (await readdir(dataDir)).filter((n) => /^(capture|screen)-\d+\.png$/.test(n)).sort();
|
|
962
|
+
for (const stale of names.slice(0, Math.max(0, names.length - 12))) {
|
|
963
|
+
try { await unlink(join(dataDir, stale)); } catch { /* gone already */ }
|
|
964
|
+
}
|
|
965
|
+
} catch { /* readdir failed; leave captures as-is */ }
|
|
966
|
+
// Say what the mapping MEANS, not what it usually means. At scale 1 the image pixels ARE
|
|
967
|
+
// screen pixels, so "已缩放、不能直接当屏幕坐标点" was flatly wrong and pushed the model to
|
|
968
|
+
// do arithmetic it did not need (or to distrust a perfect coordinate).
|
|
969
|
+
const native = result.scaleX === 1 && result.scaleY === 1;
|
|
970
|
+
const mapLine = result.coordinateMap
|
|
971
|
+
? (native
|
|
972
|
+
? `\n截图像素 = 屏幕像素(scale 1,原生 1:1):${result.coordinateMap}。可以直接点击图像中的坐标。`
|
|
973
|
+
: `\n截图像素→屏幕坐标(给 computer_click 用):${result.coordinateMap}。截图 ${result.imageWidth}x${result.imageHeight} 已缩放,需按地图换算。`)
|
|
974
|
+
: '';
|
|
975
|
+
// A blank capture used to be reported as a success with a tiny image, which reads as "the
|
|
976
|
+
// screen is small" instead of "this surface could not be painted". Say which it is.
|
|
977
|
+
const blank = result.blank === true
|
|
978
|
+
? '\n⚠ 截图是空白的:这个表面没法用当前方式绘制(窗口最小化/被遮挡,或会话已锁屏)。元素树仍是可信通道;整屏可用 scope="screen"。'
|
|
979
|
+
: '';
|
|
980
|
+
const sizeNote = result.screenRect
|
|
981
|
+
? `\n屏幕实际尺寸(实测,非硬编码):${result.screenRect.w}x${result.screenRect.h},原点 (${result.screenRect.x},${result.screenRect.y})。`
|
|
982
|
+
: '';
|
|
983
|
+
return `已截取 ${scope === 'screen' ? '整个桌面' : `窗口 ${args.windowId}`} ${result.width}x${result.height},方式 ${result.method}(${png.length} 字节)\n路径:${file}${sizeNote}${mapLine}${blank}\n如果你的模型路由声明了 image 输入,对这个路径调用 read_image 就能看像素;元素树仍然是主通道。`;
|
|
984
|
+
},
|
|
985
|
+
})));
|
|
986
|
+
|
|
987
|
+
disposers.push(register(defineTool({
|
|
988
|
+
name: 'computer_launch',
|
|
989
|
+
description: 'Start an application and wait until its window appears (polled). Returns its windowId.',
|
|
990
|
+
parameters: {
|
|
991
|
+
app: { ...STR, required: true, description: 'Executable, store alias (notepad, calc, mspaint), URI, or absolute path' },
|
|
992
|
+
args: { ...JSON_ARR, description: 'Argument list' },
|
|
993
|
+
timeoutMs: { ...INT, description: 'How long to wait for the window to appear (default 8000). Effective cap ~60s: a longer value is cut off by this tool budget.' },
|
|
994
|
+
},
|
|
995
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
996
|
+
timeoutMs: 60000,
|
|
997
|
+
async execute(args, exec) {
|
|
998
|
+
await aborted(exec.signal);
|
|
999
|
+
const outcome = classifyLaunch(args.app);
|
|
1000
|
+
if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_launch', app: args.app });
|
|
1001
|
+
// Pass the tool budget down: the worker widens its own budget to args.timeoutMs+2500, so
|
|
1002
|
+
// with the Node default (30 s) as the only cap, any wait over ~27.5 s died on the Node side
|
|
1003
|
+
// and the late "window appeared" reply was dropped as an unknown id.
|
|
1004
|
+
let result;
|
|
1005
|
+
try {
|
|
1006
|
+
result = await worker.call('launch', { app: args.app, args: args.args, timeoutMs: args.timeoutMs }, { timeoutMs: 68000 });
|
|
1007
|
+
} catch (error) {
|
|
1008
|
+
if (error.code !== 'timeout') throw error;
|
|
1009
|
+
// Node gave up while the worker was still polling: the window may be up by now. Probe
|
|
1010
|
+
// resolve_window once by the app's leaf name — if it hits, the launch DID succeed and must
|
|
1011
|
+
// still be claimed and reported, otherwise the model retries a launch that already worked
|
|
1012
|
+
// and the window can never be closed (owned was never set). Best effort: a probe failure
|
|
1013
|
+
// rethrows the original timeout.
|
|
1014
|
+
const leaf = String(args.app).trim().split(/[\\/]/).pop()?.replace(/\.[A-Za-z0-9]{1,8}$/i, '') ?? '';
|
|
1015
|
+
if (leaf !== '') {
|
|
1016
|
+
await aborted(exec.signal);
|
|
1017
|
+
try {
|
|
1018
|
+
const win = await worker.call('resolve_window', { title: leaf, timeoutMs: 3000 }, { timeoutMs: 12000 });
|
|
1019
|
+
if (win?.windowId) {
|
|
1020
|
+
owned.set(`${worker.epoch}:${win.windowId}`, { hwnd: win.hwnd, pid: win.pid });
|
|
1021
|
+
store.step({ label: `启动 ${str(args.app, 24)}`, kind: 'lifecycle', status: 'passed', ms: win.appearedMs ?? 0, detail: `pid=${win.pid} window=${win.windowId}(launch 等待超时后补查确认)` });
|
|
1022
|
+
return `已启动 ${args.app}:pid=${win.pid} windowId=${win.windowId}(launch 等待超时,经 resolve_window 补查确认窗口已出现并认领)`;
|
|
1023
|
+
}
|
|
1024
|
+
} catch { /* probe failed; fall through and report the original timeout */ }
|
|
1025
|
+
}
|
|
1026
|
+
throw error;
|
|
1027
|
+
}
|
|
1028
|
+
// Close authority is claimed per window identity inside one worker session.
|
|
1029
|
+
// A Win11 store app can fold a new document into a window the user already
|
|
1030
|
+
// owns under the same process, so a pid-keyed claim would hand the model
|
|
1031
|
+
// permission to close unrelated user documents.
|
|
1032
|
+
if (result.matchedBy === 'new-window' && result.windowId !== undefined) {
|
|
1033
|
+
owned.set(`${worker.epoch}:${result.windowId}`, { hwnd: result.hwnd, pid: result.ownerPid ?? result.pid });
|
|
1034
|
+
}
|
|
1035
|
+
store.step({ label: `启动 ${str(args.app, 24)}`, kind: 'lifecycle', status: 'passed', ms: result.appearedMs, detail: `pid=${result.pid} window=${result.windowId}` });
|
|
1036
|
+
return `已启动 ${args.app}:pid=${result.pid} windowId=${result.windowId} 窗口出现耗时=${result.appearedMs}ms`;
|
|
1037
|
+
},
|
|
1038
|
+
})));
|
|
1039
|
+
|
|
1040
|
+
disposers.push(register(defineTool({
|
|
1041
|
+
name: 'computer_close',
|
|
1042
|
+
description: 'Close a window you opened in this session. Application exit is blocked by policy, so a window the plugin did not launch cannot be closed.',
|
|
1043
|
+
parameters: {
|
|
1044
|
+
windowId: { ...STR, required: true },
|
|
1045
|
+
},
|
|
1046
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
1047
|
+
timeoutMs: 30000,
|
|
1048
|
+
async execute(args) {
|
|
1049
|
+
const win = windowOf(store, args.windowId);
|
|
1050
|
+
// A mistyped/stale windowId is a parameter error, not a policy refusal: windowOf returning
|
|
1051
|
+
// null made ownedNow false and classifyClose wrapped "no such window" as 退出应用程序 — the
|
|
1052
|
+
// model read a permission problem where the real answer is "get a valid id first", and the
|
|
1053
|
+
// control page got a non-policy block row. Split the two cases before classifying.
|
|
1054
|
+
if (win === null) {
|
|
1055
|
+
return `windowId ${args.windowId} 不在当前窗口列表里——先 computer_windows 拿有效 id(窗口是刚启动或改过标题的话,用 computer_resolve_window 重新解析)。`;
|
|
1056
|
+
}
|
|
1057
|
+
const claim = owned.get(`${worker.epoch}:${args.windowId}`);
|
|
1058
|
+
const ownedNow = claim !== undefined && (claim.hwnd === undefined || win.hwnd === claim.hwnd);
|
|
1059
|
+
const outcome = classifyClose({ ...win, ownedByPlugin: ownedNow });
|
|
1060
|
+
if (outcome.verdict === 'deny') {
|
|
1061
|
+
const note = ownedNow
|
|
1062
|
+
? ''
|
|
1063
|
+
: `\n说明:窗口 ${args.windowId}(pid=${win.pid})不是本插件本轮启动的,所以不能由本插件关闭;应用退出请让用户自己操作。`;
|
|
1064
|
+
return refuse(outcome, { tool: 'computer_close', windowId: args.windowId, window: win }) + note;
|
|
1065
|
+
}
|
|
1066
|
+
const result = await worker.call('close_window', { windowId: args.windowId });
|
|
1067
|
+
store.step({ label: `关闭窗口 ${args.windowId}`, kind: 'lifecycle', status: 'passed', ms: result.ms, detail: result.method });
|
|
1068
|
+
return `已关闭窗口 ${args.windowId},方式 ${result.method ?? 'WM_CLOSE'}`;
|
|
1069
|
+
},
|
|
1070
|
+
})));
|
|
1071
|
+
|
|
1072
|
+
disposers.push(register(defineTool({
|
|
1073
|
+
name: 'computer_wait',
|
|
1074
|
+
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}. element_appears/element_gone take a `by` descriptor and need no ref; every other type must name its target with `ref` or `by`, otherwise the wait has nothing to measure and fails with "target missing". 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.',
|
|
1075
|
+
parameters: {
|
|
1076
|
+
windowId: { ...STR, required: true },
|
|
1077
|
+
condition: { type: 'json', required: true, description: '{type, expect?, by?, ref?} — see the tool description for which types need a target' },
|
|
1078
|
+
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.' },
|
|
1079
|
+
},
|
|
1080
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
1081
|
+
timeoutMs: 90000,
|
|
1082
|
+
async execute(args) {
|
|
1083
|
+
const cond = args.condition ?? {};
|
|
1084
|
+
const type = String(cond.type ?? '');
|
|
1085
|
+
// Catch the mistake before the worker burns its whole timeout: the four measurement types
|
|
1086
|
+
// read a property of ONE element, so without ref/by there is nothing to measure. The old
|
|
1087
|
+
// path returned "matched:false, error:element_gone" after waiting the full budget, which
|
|
1088
|
+
// reads as "the element disappeared" rather than "you never named one".
|
|
1089
|
+
const needsTarget = ['name_contains', 'value_equals', 'value_changed', 'no_change', 'enabled_is'].includes(type);
|
|
1090
|
+
const hasTarget = [cond.ref, cond.by].some((v) => v !== undefined && v !== null && (typeof v === 'string' ? v !== '' : true));
|
|
1091
|
+
if (needsTarget && !hasTarget) {
|
|
1092
|
+
return `条件 type="${type}" 需要指定 ref 或 by(它要读某个元素的属性来判定)。
|
|
1093
|
+
例如:{type:"name_contains", by:{controlType:"Button", name:"确定"}, expect:"确定"}
|
|
1094
|
+
或先 snapshot 拿到 ref,再用 {type:"value_equals", ref:"e12", expect:"..."}。
|
|
1095
|
+
如果只是想等元素出现/消失,用 type:"element_appears" 或 "element_gone"(它们只需要 by)。`;
|
|
1096
|
+
}
|
|
1097
|
+
// Pass the budget down (tool cap 90s + 8s headroom): the worker widens its own budget to
|
|
1098
|
+
// args.timeoutMs+2500, so with the Node 30 s default a long wait died on the Node side while
|
|
1099
|
+
// the worker kept polling, and the late reply was dropped.
|
|
1100
|
+
const result = await worker.call('wait', { windowId: args.windowId, condition: cond, timeoutMs: args.timeoutMs ?? 10000 }, { timeoutMs: 98000 });
|
|
1101
|
+
const detail = [];
|
|
1102
|
+
if (result.observed !== undefined) detail.push(`observed=${JSON.stringify(result.observed)}`);
|
|
1103
|
+
if (result.error !== undefined) detail.push(`error=${result.error}`);
|
|
1104
|
+
if (result.observedName !== undefined) detail.push(`name=${JSON.stringify(result.observedName)}`);
|
|
1105
|
+
const tail = detail.length === 0 ? '' : `(${detail.join(' ')})`;
|
|
1106
|
+
const verdict = result.matched === true ? '条件命中' : '等待超时';
|
|
1107
|
+
// A timeout with "target missing" means the target was never resolvable, not that it was slow.
|
|
1108
|
+
const shape = result.matched !== true && result.error === 'element_gone'
|
|
1109
|
+
? ':目标元素始终没解析到——检查 by 描述符是否与元素实际的名字/类型一致'
|
|
1110
|
+
: '';
|
|
1111
|
+
return `${verdict},耗时 ${result.ms}ms${tail}${shape}`;
|
|
1112
|
+
},
|
|
1113
|
+
})));
|
|
1114
|
+
|
|
1115
|
+
disposers.push(register(defineTool({
|
|
1116
|
+
name: 'computer_resolve_window',
|
|
1117
|
+
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.',
|
|
1118
|
+
parameters: {
|
|
1119
|
+
windowId: { ...STR, description: 'a known windowId to re-resolve (e.g. "w1")' },
|
|
1120
|
+
pid: { ...INT, description: 'process id to match' },
|
|
1121
|
+
title: { ...STR, description: 'window title substring (case-insensitive)' },
|
|
1122
|
+
titleRegex: { ...STR, description: 'regular expression to match the title against' },
|
|
1123
|
+
class: { ...STR, description: 'window class name substring' },
|
|
1124
|
+
titleExact: { ...BOOL, description: 'title must equal the given string instead of containing it' },
|
|
1125
|
+
timeoutMs: { ...INT, description: 'how long to keep polling for the window to appear (default 4000, max bounded by the tool budget)' },
|
|
1126
|
+
},
|
|
1127
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
1128
|
+
isConcurrencySafe: true,
|
|
1129
|
+
async execute(args, exec) {
|
|
1130
|
+
await aborted(exec.signal);
|
|
1131
|
+
const given = [args.windowId, args.pid, args.title, args.titleRegex, args.class].some((v) => v !== undefined && String(v) !== '');
|
|
1132
|
+
if (!given) return 'computer_resolve_window 需要 windowId / pid / title / titleRegex / class 之一';
|
|
1133
|
+
const result = await worker.call('resolve_window', {
|
|
1134
|
+
windowId: args.windowId ? String(args.windowId) : '',
|
|
1135
|
+
pid: args.pid,
|
|
1136
|
+
title: args.title,
|
|
1137
|
+
titleRegex: args.titleRegex,
|
|
1138
|
+
class: args.class,
|
|
1139
|
+
titleExact: args.titleExact === true,
|
|
1140
|
+
timeoutMs: args.timeoutMs,
|
|
1141
|
+
// The worker widens its budget to args.timeoutMs+2500; keep that inside the Node default
|
|
1142
|
+
// instead of letting a huge caller timeout die on this side.
|
|
1143
|
+
}, { timeoutMs: Math.min((Number(args.timeoutMs) || 4000) + 8000, 28000) });
|
|
1144
|
+
store.setTarget(result);
|
|
1145
|
+
// Window state decides the next move: a minimized window has no usable screen rect (pixel
|
|
1146
|
+
// coordinates from a stale snapshot point at nothing), and a background window cannot take
|
|
1147
|
+
// focus/pixel actions without being raised first. Name the state and the fix in one line.
|
|
1148
|
+
const states = [result.isForeground ? '前台' : '不在前台', result.isMinimized === true ? '已最小化' : ''].filter(Boolean).join('、');
|
|
1149
|
+
const advice = result.isMinimized === true
|
|
1150
|
+
? '(已最小化,建议先最大化/恢复窗口再取坐标或做像素操作)'
|
|
1151
|
+
: (result.isForeground ? '' : '(当前不在前台;需要 focus 或像素路径时先把它带到前台)');
|
|
1152
|
+
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}`;
|
|
1153
|
+
},
|
|
1154
|
+
})));
|
|
1155
|
+
|
|
1156
|
+
disposers.push(register(defineTool({
|
|
1157
|
+
name: 'computer_replay',
|
|
1158
|
+
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.',
|
|
1159
|
+
parameters: {
|
|
1160
|
+
name: { ...STR, required: true, description: 'Recipe name from computer_run output, or list them with names="list"' },
|
|
1161
|
+
params: { type: 'json', description: 'Values substituted for {{placeholders}} in the recipe step values' },
|
|
1162
|
+
names: { ...STR, description: 'Pass "list" to see the saved recipes instead of running one' },
|
|
1163
|
+
},
|
|
1164
|
+
output: { schema: STR, render: (_args, value) => text(value) },
|
|
1165
|
+
timeoutMs: 180000,
|
|
1166
|
+
async execute(args, exec) {
|
|
1167
|
+
await aborted(exec.signal);
|
|
1168
|
+
if (args.names === 'list') {
|
|
1169
|
+
const names = await listRecipes(recipeDir);
|
|
1170
|
+
return names.length === 0 ? '还没有保存任何配方' : names.join('\n');
|
|
1171
|
+
}
|
|
1172
|
+
if (!args.name) return 'computer_replay 需要 name,或者用 names="list" 先看清单';
|
|
1173
|
+
const recipe = await loadRecipe(recipeDir, args.name);
|
|
1174
|
+
if (recipe === null) return `没有名为 "${args.name}" 的配方(用 names="list" 查看)`;
|
|
1175
|
+
const steps = recipe.steps.map((step) => ({
|
|
1176
|
+
action: step.action,
|
|
1177
|
+
value: substitute(step.value, args.params ?? {}),
|
|
1178
|
+
verify: step.verify,
|
|
1179
|
+
by: step.by,
|
|
1180
|
+
}));
|
|
1181
|
+
const windowId = recipe.window?.windowId ?? null;
|
|
1182
|
+
const prepared = await worker.call('prepare_batch', { steps, windowId, rebindBy: true });
|
|
1183
|
+
const prepError = preparationFailure(prepared, steps.length);
|
|
1184
|
+
if (prepError) {
|
|
1185
|
+
// A failed replay used to return invisibly to the control page: without a store.step the
|
|
1186
|
+
// console showed nothing about the replay the model just attempted.
|
|
1187
|
+
store.step({ label: `回放 ${args.name}`, kind: 'batch', status: 'failed', detail: prepError });
|
|
1188
|
+
return prepError;
|
|
1189
|
+
}
|
|
1190
|
+
const descriptors = prepared.descriptors ?? [];
|
|
1191
|
+
const batchDeny = classifyBatch(steps, descriptors);
|
|
1192
|
+
if (batchDeny) return refuse(batchDeny, { tool: 'computer_replay', recipe: args.name, stepIndex: batchDeny.index, descriptor: descriptors[batchDeny.index] ?? null });
|
|
1193
|
+
let committed;
|
|
1194
|
+
try {
|
|
1195
|
+
// mode rides on every act/commit_batch (the worker's declared contract): without it a
|
|
1196
|
+
// replay after a control-page kill always ran background and UIA-hostile elements lost
|
|
1197
|
+
// their pixel fallback.
|
|
1198
|
+
committed = await worker.call('commit_batch', { revision: prepared.revision, steps, windowId, mode: store.pointerMode, indicatorPid: activity?.indicator?.proc?.pid ?? 0 });
|
|
1199
|
+
} catch (error) {
|
|
1200
|
+
// 与 computer_run 同一条在飞批次被终止路径(Esc/控制页关 worker):worker_dead 不裸抛,
|
|
1201
|
+
// 已送达的步骤不回滚,剩余步骤不再执行。其余 Err(revision/descriptor/unknown_window)
|
|
1202
|
+
// 也按 code 翻译成自纠指引,而不是把裸 WorkerCommandError 丢给模型。
|
|
1203
|
+
if (!['worker_dead', 'stale_revision', 'revision_mismatch', 'descriptor_unresolved', 'unknown_window'].includes(String(error?.code ?? ''))) throw error;
|
|
1204
|
+
const code = String(error?.code ?? '');
|
|
1205
|
+
// worker_dead 是「在飞回放被打断」,与「一个动作都没有执行」的预检类错误不同框:
|
|
1206
|
+
// performedCount 未知,不能套「回放未执行(performedCount=0)」的话术。
|
|
1207
|
+
if (code === 'worker_dead') {
|
|
1208
|
+
const byUser = store.killed === true;
|
|
1209
|
+
const detail = `${byUser ? '用户已终止本轮(Esc/控制页)' : 'worker 进程中途停止'}:回放在飞时被打断,剩余步骤不再执行,已完成的动作不回滚。先 computer_snapshot 重新观察桌面,再决定是否重放。`;
|
|
1210
|
+
store.step({ label: `回放 ${args.name}`, kind: 'batch', status: 'failed', detail });
|
|
1211
|
+
return detail;
|
|
1212
|
+
}
|
|
1213
|
+
const guide = code === 'stale_revision' || code === 'revision_mismatch'
|
|
1214
|
+
? '配方修订号已过期(界面在此期间更新过,一个动作都没有执行)。直接重新发起同样的 computer_replay 即可——会自动重新 prepare。'
|
|
1215
|
+
: code === 'descriptor_unresolved'
|
|
1216
|
+
? '配方里至少一个步骤解析不到元素,一个动作都没有执行。先 computer_find_text / computer_snapshot 找到目标,必要时用 computer_run 重新执行并保存新配方。'
|
|
1217
|
+
: code === 'unknown_window'
|
|
1218
|
+
? '配方记录的窗口已不存在或尚未登记。先用 computer_windows / computer_resolve_window 找到该应用的新 windowId。'
|
|
1219
|
+
: `${error?.message ?? error}。`;
|
|
1220
|
+
const detail = `回放未执行(performedCount=0):${guide}`;
|
|
1221
|
+
store.step({ label: `回放 ${args.name}`, kind: 'batch', status: 'failed', detail });
|
|
1222
|
+
return detail;
|
|
1223
|
+
}
|
|
1224
|
+
const replayResults = committed.results ?? [];
|
|
1225
|
+
for (const r of replayResults) {
|
|
1226
|
+
store.step({ label: `回放 ${args.name} 第 ${r.index} 步 ${r.action}`, status: r.status, ms: r.ms, verify: r.verify, detail: r.detail });
|
|
1227
|
+
}
|
|
1228
|
+
store.actionDone(committed.performedCount ?? 0);
|
|
1229
|
+
const replayCancelled = (store.killed === true || committed.status === 'cancelled')
|
|
1230
|
+
? '\n用户已终止本轮(Esc/控制页):已完成的动作不回滚。'
|
|
1231
|
+
: '';
|
|
1232
|
+
// A replay that stopped mid-way is the moment the recipe's locators are proven stale — the
|
|
1233
|
+
// one event that should feed the new positions BACK into the recipe (sediment was one-way).
|
|
1234
|
+
// Descriptors that only matched by relaxing the match carry the fresh identity; write them
|
|
1235
|
+
// into the failed recipe so the next replay starts from the updated locator.
|
|
1236
|
+
let rebindNote = '';
|
|
1237
|
+
if ((committed.stoppedAt ?? null) !== null && committed.status !== 'cancelled') {
|
|
1238
|
+
let touched = 0;
|
|
1239
|
+
for (const d of descriptors) {
|
|
1240
|
+
if (d && d.matchedBy && d.matchedBy !== 'strict' && Number.isInteger(d.index) && recipe.steps[d.index]) {
|
|
1241
|
+
const by = recipeBy(d);
|
|
1242
|
+
if (by) { recipe.steps[d.index].by = by; touched++; }
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
if (touched > 0) {
|
|
1246
|
+
try {
|
|
1247
|
+
await writeFile(join(recipeDir, `${args.name}.json`), JSON.stringify({ ...recipe, updatedAt: new Date().toISOString() }, null, 2), 'utf8');
|
|
1248
|
+
rebindNote = `\n已把 ${touched} 步的新定位写回配方「${args.name}」(下次回放从新位置解析)。`;
|
|
1249
|
+
} catch { /* best-effort sediment: a failed write must not fail the replay report */ }
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
// Same stop wording as computer_run, including the Esc branch: a replay that stops must
|
|
1253
|
+
// tell the model to re-observe (or pause for the user) instead of just listing the tail.
|
|
1254
|
+
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)}`;
|
|
1255
|
+
},
|
|
1256
|
+
})));
|
|
1257
|
+
|
|
1258
|
+
// ---- physical (foreground) action tools: the human-action set -------------------------------
|
|
1259
|
+
// These drive the real cursor/keyboard and are visible. Coordinates are physical screen pixels, the
|
|
1260
|
+
// same space snapshot rects and find_text centers use. Every click/drag/scroll MUST name the window
|
|
1261
|
+
// it lands in (expect.windowId) so it can never click blind across the whole desktop, and the point
|
|
1262
|
+
// is run through the same destructive-text guard by resolving what is actually under it first.
|
|
1263
|
+
const classifyPoint = async (x, y) => {
|
|
1264
|
+
const t = await worker.call('pointer_target', { x, y });
|
|
1265
|
+
const under = t?.under ?? t;
|
|
1266
|
+
return classify({ action: 'invoke', descriptor: { title: under?.title, className: under?.class ?? under?.hitClass, name: under?.app } });
|
|
1267
|
+
};
|
|
1268
|
+
const pointArgs = (args) => ({ x: Number(args.x), y: Number(args.y) });
|
|
1269
|
+
const needPoint = (args) => (typeof args.x !== 'number' || typeof args.y !== 'number' ? '需要数值坐标 x、y(物理像素,和快照 rect / find_text center 同一坐标空间)' : null);
|
|
1270
|
+
|
|
1271
|
+
disposers.push(register(defineTool({
|
|
1272
|
+
name: 'computer_click',
|
|
1273
|
+
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.',
|
|
1274
|
+
parameters: {
|
|
1275
|
+
windowId: { ...STR, required: true, description: 'The window you expect to be under (x,y); used as the target gate' },
|
|
1276
|
+
x: { ...INT, required: true }, y: { ...INT, required: true },
|
|
1277
|
+
button: { type: 'string', enum: ['left', 'right', 'middle'], description: 'default left' },
|
|
1278
|
+
double: { ...BOOL, description: 'double-click' },
|
|
1279
|
+
durationMs: { ...INT, description: 'cursor glide time (default auto by distance)' },
|
|
1280
|
+
},
|
|
1281
|
+
output: { schema: STR, render: (_a, v) => text(v) },
|
|
1282
|
+
timeoutMs: 30000,
|
|
1283
|
+
async execute(args, exec) {
|
|
1284
|
+
await aborted(exec.signal);
|
|
1285
|
+
const bad = needPoint(args); if (bad) return bad;
|
|
1286
|
+
const { x, y } = pointArgs(args);
|
|
1287
|
+
const outcome = await classifyPoint(x, y);
|
|
1288
|
+
if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_click', ...args });
|
|
1289
|
+
const r = await worker.call('pointer_click', { x, y, button: args.button, double: args.double, durationMs: args.durationMs, expect: { windowId: String(args.windowId) } });
|
|
1290
|
+
store.actionDone(1);
|
|
1291
|
+
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)}` });
|
|
1292
|
+
return `已点击 (${x},${y}) ${args.button || 'left'}${args.double ? ' 双击' : ''},耗时 ${r.ms}ms,落点窗口 "${str(r.under?.title ?? '', 50)}"`;
|
|
1293
|
+
},
|
|
1294
|
+
})));
|
|
1295
|
+
|
|
1296
|
+
disposers.push(register(defineTool({
|
|
1297
|
+
name: 'computer_drag',
|
|
1298
|
+
description: 'Press at (fromX,fromY), move to (toX,toY), release — for sliders, repositioning, marquee-select. Both endpoints must be inside windowId.',
|
|
1299
|
+
parameters: {
|
|
1300
|
+
windowId: { ...STR, required: true },
|
|
1301
|
+
fromX: { ...INT, required: true }, fromY: { ...INT, required: true },
|
|
1302
|
+
toX: { ...INT, required: true }, toY: { ...INT, required: true },
|
|
1303
|
+
button: { type: 'string', enum: ['left', 'right', 'middle'] },
|
|
1304
|
+
durationMs: { ...INT },
|
|
1305
|
+
},
|
|
1306
|
+
output: { schema: STR, render: (_a, v) => text(v) },
|
|
1307
|
+
timeoutMs: 30000,
|
|
1308
|
+
async execute(args, exec) {
|
|
1309
|
+
await aborted(exec.signal);
|
|
1310
|
+
const nums = [args.fromX, args.fromY, args.toX, args.toY];
|
|
1311
|
+
if (nums.some((n) => typeof n !== 'number')) return '需要数值 fromX/fromY/toX/toY';
|
|
1312
|
+
const outcome = await classifyPoint(args.fromX, args.fromY);
|
|
1313
|
+
if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_drag', ...args });
|
|
1314
|
+
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) } });
|
|
1315
|
+
store.actionDone(1);
|
|
1316
|
+
store.step({ label: `拖拽 (${args.fromX},${args.fromY})→(${args.toX},${args.toY})`, kind: 'pointer', status: 'passed', ms: r.ms });
|
|
1317
|
+
return `已拖拽 (${args.fromX},${args.fromY}) → (${args.toX},${args.toY}),耗时 ${r.ms ?? '?'}ms`;
|
|
1318
|
+
},
|
|
1319
|
+
})));
|
|
1320
|
+
|
|
1321
|
+
disposers.push(register(defineTool({
|
|
1322
|
+
name: 'computer_scroll',
|
|
1323
|
+
description: 'Scroll the mouse wheel at a physical (x,y): direction up|down|left|right, clicks = notches (default 3). windowId gates the point.',
|
|
1324
|
+
parameters: {
|
|
1325
|
+
windowId: { ...STR, required: true },
|
|
1326
|
+
x: { ...INT, required: true }, y: { ...INT, required: true },
|
|
1327
|
+
direction: { type: 'string', enum: ['up', 'down', 'left', 'right'] },
|
|
1328
|
+
clicks: { ...INT, description: 'wheel notches, 1..50' },
|
|
1329
|
+
},
|
|
1330
|
+
output: { schema: STR, render: (_a, v) => text(v) },
|
|
1331
|
+
timeoutMs: 20000,
|
|
1332
|
+
async execute(args, exec) {
|
|
1333
|
+
await aborted(exec.signal);
|
|
1334
|
+
const bad = needPoint(args); if (bad) return bad;
|
|
1335
|
+
const { x, y } = pointArgs(args);
|
|
1336
|
+
const outcome = await classifyPoint(x, y);
|
|
1337
|
+
if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_scroll', ...args });
|
|
1338
|
+
const r = await worker.call('pointer_scroll', { x, y, direction: args.direction, clicks: args.clicks, expect: { windowId: String(args.windowId) } });
|
|
1339
|
+
store.actionDone(1);
|
|
1340
|
+
store.step({ label: `滚动 ${args.direction || 'down'} @(${x},${y})`, kind: 'pointer', status: 'passed', ms: r.ms });
|
|
1341
|
+
return `已在 (${x},${y}) ${args.direction || 'down'} 滚动 ${r.clicks} 格,耗时 ${r.ms}ms`;
|
|
1342
|
+
},
|
|
1343
|
+
})));
|
|
1344
|
+
|
|
1345
|
+
disposers.push(register(defineTool({
|
|
1346
|
+
name: 'computer_type',
|
|
1347
|
+
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.',
|
|
1348
|
+
parameters: {
|
|
1349
|
+
text: { ...STR, required: true, description: 'text to type, up to 4000 chars' },
|
|
1350
|
+
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' },
|
|
1351
|
+
windowId: { ...STR, description: 'optional: raise+focus this window before typing' },
|
|
1352
|
+
},
|
|
1353
|
+
output: { schema: STR, render: (_a, v) => text(v) },
|
|
1354
|
+
timeoutMs: 20000,
|
|
1355
|
+
async execute(args, exec) {
|
|
1356
|
+
await aborted(exec.signal);
|
|
1357
|
+
const t = String(args.text ?? '');
|
|
1358
|
+
if (t === '') return 'text 为空';
|
|
1359
|
+
const via = args.via === 'clipboard' ? 'clipboard' : 'keyboard';
|
|
1360
|
+
const r = await worker.call('type_text', { text: t, windowId: args.windowId ? String(args.windowId) : '', via });
|
|
1361
|
+
store.actionDone(1);
|
|
1362
|
+
store.step({ label: `输入 ${str(t, 24)} (${t.length} 字)`, kind: 'pointer', status: 'passed', ms: r.ms });
|
|
1363
|
+
// The clipboard path is one paste, not 8000 key events — the honest answer names the channel
|
|
1364
|
+
// AND the side effect the caller accepted (the clipboard is overwritten, not restored).
|
|
1365
|
+
return via === 'clipboard'
|
|
1366
|
+
? `已通过剪贴板粘贴 ${t.length} 个字符(Set-Clipboard + ctrl+v),耗时 ${r.ms}ms。原剪贴板内容已被覆盖且未恢复;可用 computer_wait {type:"value_equals", ref} 确认内容已落盘。`
|
|
1367
|
+
: `已输入 ${t.length} 个字符,耗时 ${r.ms}ms(SendInput 接受 ${r.sent} 个按键事件)`;
|
|
1368
|
+
},
|
|
1369
|
+
})));
|
|
1370
|
+
|
|
1371
|
+
disposers.push(register(defineTool({
|
|
1372
|
+
name: 'computer_key',
|
|
1373
|
+
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.',
|
|
1374
|
+
parameters: {
|
|
1375
|
+
keys: { ...STR, required: true, description: 'single key or modifiers joined by +, e.g. "ctrl+c"' },
|
|
1376
|
+
},
|
|
1377
|
+
output: { schema: STR, render: (_a, v) => text(v) },
|
|
1378
|
+
timeoutMs: 15000,
|
|
1379
|
+
async execute(args, exec) {
|
|
1380
|
+
await aborted(exec.signal);
|
|
1381
|
+
const combo = String(args.keys ?? '').trim().toLowerCase();
|
|
1382
|
+
if (combo === '') return 'keys 为空';
|
|
1383
|
+
// The combo has no UIA descriptor to feed the name table, so classification runs on the combo
|
|
1384
|
+
// text itself — in guard.js, like every other policy decision: the session-ending combos deny
|
|
1385
|
+
// there with the shared CATEGORIES wording, ordinary combos pass. No policy is matched here.
|
|
1386
|
+
const outcome = classifyKeys(combo);
|
|
1387
|
+
if (outcome.verdict === 'deny') return refuse(outcome, { tool: 'computer_key', keys: combo });
|
|
1388
|
+
const r = await worker.call('key', { keys: combo });
|
|
1389
|
+
store.actionDone(1);
|
|
1390
|
+
store.step({ label: `按键 ${combo}`, kind: 'pointer', status: 'passed', ms: r.ms });
|
|
1391
|
+
return `已按下 ${combo},耗时 ${r.ms ?? '?'}ms`;
|
|
1392
|
+
},
|
|
1393
|
+
})));
|
|
1394
|
+
|
|
1395
|
+
disposers.push(register(defineTool({
|
|
1396
|
+
name: 'computer_done',
|
|
1397
|
+
description: 'Call this as your FINAL step to end the run. It dismisses the on-screen control overlay immediately instead of leaving it up until the idle lease expires. Do not rely on the overlay timing out on its own. outcome declares HOW the run ends: done = the task completed; blocked = you could NOT finish because something outside your control is in the way (permission refused, focus keeps being stolen, target never becomes visible); failed = you tried and give up. When you recognise the task is infeasible or the channel is stuck, declaring outcome=blocked/failed with a one-line reason is better than retrying the same failing action forever.',
|
|
1398
|
+
parameters: {
|
|
1399
|
+
summary: { ...STR, description: 'optional one-line summary of what was accomplished (or attempted)' },
|
|
1400
|
+
outcome: { type: 'string', enum: ['done', 'blocked', 'failed'], description: 'how the run ends (default done)' },
|
|
1401
|
+
reason: { ...STR, description: 'with outcome=blocked/failed: one line naming what is in the way' },
|
|
1402
|
+
},
|
|
1403
|
+
output: { schema: STR, render: (_a, v) => text(v) },
|
|
1404
|
+
timeoutMs: 10000,
|
|
1405
|
+
async execute(args) {
|
|
1406
|
+
const summary = str(args.summary ?? '', 80);
|
|
1407
|
+
const reason = str(args.reason ?? '', 80);
|
|
1408
|
+
const outcome = args.outcome === 'blocked' || args.outcome === 'failed' ? args.outcome : 'done';
|
|
1409
|
+
// The overlay belongs to index.js (one owner). This tool only declares the run finished and
|
|
1410
|
+
// lets the owner collapse it, so this file holds no reference to the on-screen capsule.
|
|
1411
|
+
disarmIdle();
|
|
1412
|
+
if (typeof finishRun === 'function') {
|
|
1413
|
+
await finishRun({ summary, outcome });
|
|
1414
|
+
}
|
|
1415
|
+
// A finished run must not keep advertising the window it was driving: the panel read
|
|
1416
|
+
// `target` forever after the run ended, so the next session opened showing a stale
|
|
1417
|
+
// "目标窗口". Clearing it here is what makes "done" mean done in the state snapshot too.
|
|
1418
|
+
store.setTarget(null);
|
|
1419
|
+
// Three endings get three words: only outcome=done may say 已完成 — a blocked/failed run
|
|
1420
|
+
// rendered as "任务完成" taught the panel (and the model's own next turn) a lie. The panel
|
|
1421
|
+
// already colours both 'blocked' and 'failed' steps as bad (control.html isBad), so the
|
|
1422
|
+
// status values below need no panel change.
|
|
1423
|
+
const tail = reason ? `(原因:${reason})` : summary ? `(${summary})` : '';
|
|
1424
|
+
const verdicts = {
|
|
1425
|
+
done: { status: 'passed', label: '任务完成,收起指示层', text: `已完成并收起御屏指示层${summary ? `(${summary})` : ''}。` },
|
|
1426
|
+
blocked: { status: 'blocked', label: '受阻未完成,收起指示层', text: `受阻未完成,已收起御屏指示层${tail}:不要继续重试同一动作,向用户如实说明受阻原因。` },
|
|
1427
|
+
failed: { status: 'failed', label: '失败放弃,收起指示层', text: `失败放弃,已收起御屏指示层${tail}:不要继续重试同一动作,向用户如实说明失败经过。` },
|
|
1428
|
+
};
|
|
1429
|
+
const verdict = verdicts[outcome];
|
|
1430
|
+
store.step({ label: verdict.label, kind: 'lifecycle', status: verdict.status, detail: summary || reason });
|
|
1431
|
+
return verdict.text;
|
|
1432
|
+
},
|
|
1433
|
+
})));
|
|
1434
|
+
|
|
1435
|
+
return () => {
|
|
1436
|
+
for (const dispose of disposers) dispose();
|
|
1437
|
+
disposers.length = 0;
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
function substitute(value, params) {
|
|
1442
|
+
if (typeof value !== 'string') return value;
|
|
1443
|
+
return value.replace(/\{\{([a-zA-Z0-9_]+)\}\}/g, (all, key) => (params[key] === undefined ? all : String(params[key])));
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
async function saveRecipe(dir, recipe) {
|
|
1447
|
+
await mkdir(dir, { recursive: true });
|
|
1448
|
+
const slug = String(recipe.goal).toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'recipe';
|
|
1449
|
+
const name = `${slug}-${Date.now()}`;
|
|
1450
|
+
await writeFile(join(dir, `${name}.json`), JSON.stringify({ ...recipe, createdAt: new Date().toISOString() }, null, 2), 'utf8');
|
|
1451
|
+
// Recipes are the one directory here that only ever grew: every passing batch adds one, nothing
|
|
1452
|
+
// removed them, and each carries the full step list. Captures were already pruned to the newest
|
|
1453
|
+
// twelve; do the same for recipes so a long-lived install cannot fill the disk. Best-effort:
|
|
1454
|
+
// a failed prune must never fail the batch the user asked for.
|
|
1455
|
+
try {
|
|
1456
|
+
const names = (await readdir(dir)).filter((n) => n.endsWith('.json')).sort();
|
|
1457
|
+
const keep = Math.max(1, Number(process.env.DSH_NATIVE_UIA_RECIPE_KEEP ?? 50));
|
|
1458
|
+
for (const stale of names.slice(0, Math.max(0, names.length - keep))) {
|
|
1459
|
+
try { await unlink(join(dir, stale)); } catch { /* already gone */ }
|
|
1460
|
+
}
|
|
1461
|
+
} catch { /* readdir/unlink failed; the recipe is still saved */ }
|
|
1462
|
+
return name;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
async function listRecipes(dir) {
|
|
1466
|
+
try {
|
|
1467
|
+
const names = await readdir(dir);
|
|
1468
|
+
return names.filter((n) => n.endsWith('.json')).map((n) => n.slice(0, -5));
|
|
1469
|
+
} catch {
|
|
1470
|
+
return [];
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
async function loadRecipe(dir, name) {
|
|
1475
|
+
try {
|
|
1476
|
+
return JSON.parse(await readFile(join(dir, `${name}.json`), 'utf8'));
|
|
1477
|
+
} catch {
|
|
1478
|
+
return null;
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
export { POLICY };
|