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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +431 -2
  3. package/client/client.js +81 -0
  4. package/cordis.patch.yml +11 -0
  5. package/icon.svg +11 -0
  6. package/locale/desktop/en.json +6 -0
  7. package/locale/desktop/zh.json +6 -0
  8. package/locale/en.json +6 -0
  9. package/locale/zh.json +6 -0
  10. package/package.json +80 -4
  11. package/scripts/bench-live.mjs +157 -0
  12. package/scripts/check-lease.mjs +308 -0
  13. package/scripts/install.mjs +154 -0
  14. package/scripts/lib/load-tools-source.mjs +24 -0
  15. package/scripts/measure-parse.mjs +77 -0
  16. package/scripts/regression-halt-latch.mjs +100 -0
  17. package/scripts/regression-quality.mjs +207 -0
  18. package/scripts/regression-tools.mjs +88 -0
  19. package/scripts/regression-worker.ps1 +1042 -0
  20. package/scripts/smoke.mjs +158 -0
  21. package/scripts/verify-capture-scale.mjs +37 -0
  22. package/scripts/verify-live-clipboard.mjs +108 -0
  23. package/scripts/verify-live.mjs +110 -0
  24. package/scripts/verify-locator.mjs +52 -0
  25. package/scripts/verify.mjs +1459 -0
  26. package/src/activity-window.js +212 -0
  27. package/src/dashboard.js +145 -0
  28. package/src/guard.js +191 -0
  29. package/src/index.js +377 -0
  30. package/src/native-uia-remote.js +80 -0
  31. package/src/panel-face.js +14 -0
  32. package/src/state.js +177 -0
  33. package/src/tools.js +1482 -0
  34. package/src/worker-client.js +246 -0
  35. package/web/control.html +1413 -0
  36. package/worker/bin/build-ocr.ps1 +41 -0
  37. package/worker/bin/ocr.cs +69 -0
  38. package/worker/bin/ocr.exe +0 -0
  39. package/worker/indicator-server.ps1 +1928 -0
  40. package/worker/ps-stdio.ps1 +168 -0
  41. package/worker/uia-worker.ps1 +4220 -0
@@ -0,0 +1,246 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const WORKER = fileURLToPath(new URL('../worker/uia-worker.ps1', import.meta.url));
5
+ const POWERSHELL = 'powershell.exe';
6
+ const NOISE_LIMIT = 32;
7
+
8
+ export class WorkerDeadError extends Error {
9
+ constructor(detail) {
10
+ super(`uia worker is not running (${detail})`);
11
+ this.name = 'WorkerDeadError';
12
+ this.code = 'worker_dead';
13
+ }
14
+ }
15
+
16
+ export class HaltedError extends Error {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = 'HaltedError';
20
+ this.code = 'halted';
21
+ }
22
+ }
23
+
24
+ /** Read-only observation mode (DSH_NATIVE_UIA_READ_ONLY=1, the store sets it at activation): every
25
+ * command that could put input on the desktop is refused at the call() choke point, while the
26
+ * whole observation whitelist keeps working. This is the plugin-side stand-in for the isolation +
27
+ * least-privilege consensus of unattended evaluation harnesses (OSWorld/AndroidWorld) when no VM
28
+ * exists — an honest approximation ("防手滑不是防对抗"): it stops delivery, not a determined caller. */
29
+ export class ReadOnlyError extends Error {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = 'ReadOnlyError';
33
+ this.code = 'read_only_mode';
34
+ }
35
+ }
36
+
37
+ /** Every command that can put input on the desktop, so the control page switches
38
+ * are enforced here rather than remembered per tool. The pixel/keyboard commands belong
39
+ * here too: they move the real cursor and type, so they must claim the activity overlay and
40
+ * honour the kill latch exactly like act/commit_batch do. */
41
+ const ACTION_COMMANDS = new Set([
42
+ 'act', 'commit_batch', 'launch', 'close_window',
43
+ 'pointer_click', 'pointer_drag', 'pointer_scroll', 'type_text', 'key',
44
+ // 'foreground' was removed with its worker command: no tool ever sent it, and an unsendable
45
+ // entry in the input whitelist is a policy blind spot (the worker command set dropped
46
+ // foreground/pointer_state/pointer_move/text_caret together).
47
+ ]);
48
+
49
+ /**
50
+ * Commands that mean "the model is looking at the desktop" for a live run, so they renew the
51
+ * overlay's lease. The lease renews ONLY here and in claim() — the plugin's own heartbeat feeding
52
+ * the renderer is not model activity and cannot extend it (that made runs immortal).
53
+ *
54
+ * This is a whitelist on purpose. Treating "not an action" as "an observation" looked equivalent
55
+ * and was not: the Esc watchdog polls `escape_pressed` every 40 ms, so the else-branch fired a
56
+ * beat ~25×/s. Each beat re-syncs the HWND, re-positions the pill and re-renders its text while
57
+ * the pulse timer is pushing new opacity values every 100 ms, and the two interleave into a
58
+ * visible flicker on the ring. Internal probes are not observations and must stay silent here.
59
+ */
60
+ const OBSERVE_COMMANDS = new Set([
61
+ 'list_windows', 'snapshot', 'describe', 'capture', 'ocr', 'wait', 'prepare_batch',
62
+ // A text search is a pure read of the tree — observation, exactly like a snapshot.
63
+ 'find_text',
64
+ // Resolving (or waiting for) a window only reads the desktop window list.
65
+ 'resolve_window',
66
+ // Resolves what currently sits under a point (used by the destructive-text guard before a
67
+ // click). It reads the desktop, it does not move the cursor, so it observes like a snapshot.
68
+ 'pointer_target',
69
+ ]);
70
+
71
+ export class CuaWorker {
72
+ id = 0;
73
+ epoch = 0;
74
+ noiseLines = 0;
75
+ proc = null;
76
+ pending = new Map();
77
+ buffer = '';
78
+ stderrTail = '';
79
+ stats = { started: 0, requests: 0, timeouts: 0, refused: 0, noise: 0, halted: 0, readOnlyRefused: 0 };
80
+
81
+ constructor({ script, onEvent, logger, halt, busy, onActionStart, onObserve, readOnly }) {
82
+ this.scriptPath = script ?? WORKER;
83
+ this.onEvent = onEvent ?? (() => {});
84
+ this.log = logger ?? (() => {});
85
+ this.halt = halt;
86
+ this.busy = busy;
87
+ this.onActionStart = onActionStart;
88
+ this.onObserve = onObserve;
89
+ // Fixed for the session's lifetime: the flag is read once from the env at activation (Store)
90
+ // and wired in by index.js, so a plain boolean is enough — unlike halt it needs no callback.
91
+ this.readOnly = readOnly === true;
92
+ }
93
+
94
+ get running() {
95
+ return this.proc !== null && this.proc.exitCode === null && !this.proc.killed;
96
+ }
97
+
98
+ start() {
99
+ if (this.running) return;
100
+ const proc = spawn(POWERSHELL, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', this.scriptPath], {
101
+ stdio: ['pipe', 'pipe', 'pipe'],
102
+ windowsHide: true,
103
+ });
104
+ this.proc = proc;
105
+ this.stats.started++;
106
+ this.epoch++;
107
+ proc.stdout.setEncoding('utf8');
108
+ proc.stderr.setEncoding('utf8');
109
+ proc.stdout.on('data', (chunk) => this.#onStdout(chunk));
110
+ proc.stderr.on('data', (chunk) => {
111
+ this.stderrTail = (this.stderrTail + chunk).slice(-8000);
112
+ });
113
+ proc.on('exit', (code, signal) => this.#onExit(`exit ${code ?? signal}`));
114
+ proc.on('error', (error) => this.#onExit(`spawn error ${error.message}`));
115
+ this.log(`worker 已派生(powershell,第 ${this.epoch} 代)`);
116
+ this.onEvent('worker', { epoch: this.epoch, started: true });
117
+ }
118
+
119
+ #onExit(reason) {
120
+ this.proc = null;
121
+ for (const [, entry] of this.pending) entry.reject(new WorkerDeadError(reason));
122
+ this.pending.clear();
123
+ this.onEvent('worker', { epoch: this.epoch, started: false, reason });
124
+ }
125
+
126
+ #onStdout(chunk) {
127
+ this.buffer += chunk;
128
+ let nl;
129
+ while ((nl = this.buffer.indexOf('\n')) >= 0) {
130
+ const line = this.buffer.slice(0, nl).trim();
131
+ this.buffer = this.buffer.slice(nl + 1);
132
+ if (line === '') continue;
133
+ let msg;
134
+ try {
135
+ msg = JSON.parse(line);
136
+ } catch {
137
+ this.noiseLines++;
138
+ this.stats.noise++;
139
+ if (this.noiseLines <= NOISE_LIMIT) this.log(`worker emitted non-JSON line: ${line.slice(0, 160)}`);
140
+ continue;
141
+ }
142
+ const entry = this.pending.get(msg.id);
143
+ if (entry === undefined) continue;
144
+ this.pending.delete(msg.id);
145
+ clearTimeout(entry.timer);
146
+ if (msg.ok === true) entry.resolve(msg.result);
147
+ else entry.reject(new WorkerCommandError(msg.error ?? 'worker error', msg.code ?? 'worker_error', msg));
148
+ }
149
+ }
150
+
151
+ async call(cmd, args = {}, { timeoutMs = 30000 } = {}) {
152
+ if (!this.running) this.start();
153
+ const id = ++this.id;
154
+ const line = JSON.stringify({ id, cmd, args });
155
+ this.stats.requests++;
156
+ const isAction = ACTION_COMMANDS.has(cmd);
157
+ if (isAction) {
158
+ // Read-only observation mode sits one layer ABOVE the halt latch: the refusal must not
159
+ // consume the one-shot latch (that message belongs to the first action after a real stop)
160
+ // and must never reach busy()/onActionStart — a read-only session claims nothing, so it
161
+ // never lights the overlay (the claim-lights/observe-renews two-state invariant holds).
162
+ if (this.readOnly === true) {
163
+ this.stats.readOnlyRefused++;
164
+ throw new ReadOnlyError(`当前为只读观察模式,快照/find_text/parse/ocr 可用,投递类动作一律拒绝(${cmd})`);
165
+ }
166
+ const message = typeof this.halt === 'function' ? this.halt() : null;
167
+ if (typeof message === 'string' && message !== '') {
168
+ this.stats.halted++;
169
+ throw new HaltedError(message);
170
+ }
171
+ this.busy?.(true);
172
+ try {
173
+ this.onActionStart?.(cmd);
174
+ } catch {
175
+ /* the indicator is a convenience; it may never fail the action it reports */
176
+ }
177
+ } else if (OBSERVE_COMMANDS.has(cmd)) {
178
+ // The same choke point that reports input also reports observation: a read-only step
179
+ // inside a live run must renew the overlay's lease, and this is the one place every
180
+ // command passes through. A reader that is not already part of a run is ignored by the
181
+ // receiver, so pure observation never lights the screen on its own. Only the whitelist
182
+ // reaches here — internal probes (escape_pressed and friends) stay silent.
183
+ try {
184
+ this.onObserve?.(cmd);
185
+ } catch {
186
+ /* observation reporting may never fail the read it decorates */
187
+ }
188
+ }
189
+ const promise = new Promise((resolve, reject) => {
190
+ const timer = setTimeout(() => {
191
+ if (!this.pending.delete(id)) return;
192
+ this.stats.timeouts++;
193
+ reject(new WorkerCommandError(`"${cmd}" timed out after ${timeoutMs} ms`, 'timeout', null));
194
+ }, timeoutMs);
195
+ timer.unref?.();
196
+ this.pending.set(id, { resolve, reject, timer, cmd });
197
+ this.proc.stdin.write(`${line}\n`, (error) => {
198
+ if (error !== null && error !== undefined) {
199
+ clearTimeout(timer);
200
+ this.pending.delete(id);
201
+ reject(new WorkerDeadError(`stdin write failed: ${error.message}`));
202
+ }
203
+ });
204
+ });
205
+ if (!isAction) return promise;
206
+ try {
207
+ return await promise;
208
+ } finally {
209
+ this.busy?.(false);
210
+ }
211
+ }
212
+
213
+ async shutdown({ killMs = 4000 } = {}) {
214
+ const proc = this.proc;
215
+ if (proc === null) return;
216
+ try {
217
+ await this.call('shutdown', {}, { timeoutMs: 5000 });
218
+ } catch {
219
+ /* the exit handler below covers a worker that died instead of answering */
220
+ }
221
+ await new Promise((done) => {
222
+ const timer = setTimeout(() => {
223
+ if (proc.exitCode === null) proc.kill('SIGTERM');
224
+ done();
225
+ }, killMs);
226
+ timer.unref?.();
227
+ proc.once('exit', () => {
228
+ clearTimeout(timer);
229
+ done();
230
+ });
231
+ });
232
+ }
233
+
234
+ get lastError() {
235
+ return this.stderrTail.slice(-2000);
236
+ }
237
+ }
238
+
239
+ export class WorkerCommandError extends Error {
240
+ constructor(message, code, detail) {
241
+ super(message);
242
+ this.name = 'WorkerCommandError';
243
+ this.code = code;
244
+ this.detail = detail;
245
+ }
246
+ }