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,212 @@
1
+ /**
2
+ * The screen indicator: a ring of glow plus a top-centre pill on the monitor that
3
+ * hosts the window being driven, held for a whole run rather than one action.
4
+ *
5
+ * Every entry point here is fire-and-forget by contract. The overlay is a
6
+ * convenience for the person at the keyboard; a missing, crashed, or refusing
7
+ * overlay process must never turn into a failed desktop action, so nothing in
8
+ * this module may reject into its caller.
9
+ */
10
+
11
+ /**
12
+ * The overlay palette lives here, not in the renderer: colour is plugin data, so
13
+ * changing the look is one edit in one place and the worker only consumes what it
14
+ * is handed. `ringFrom`/`ringTo` fade along the ring, `pill*` paint the capsule.
15
+ * The card icon deliberately keeps the host's own artwork colours instead: the
16
+ * icon belongs to the Plugin page, the glow belongs to the user's screen.
17
+ */
18
+ export const PALETTE = {
19
+ ringFrom: '#D9CCF7',
20
+ ringTo: '#C0A8EE',
21
+ pillBg: '#241B3A',
22
+ pillBorder: '#CDBCF3',
23
+ pillText: '#E7DEFF',
24
+ };
25
+
26
+ /**
27
+ * The pill's second line: target app name plus the run's progress. `store.step` has always
28
+ * recorded the latest step's label and the `counters.stepsRun` total, but the subtext only ever
29
+ * carried the app name, so the person at the keyboard could not see how far the batch had gotten.
30
+ * The count must come from the counter, not from `steps.length`: the store trims `steps` (200 cap)
31
+ * and the display would freeze at that cap forever in a long run. Without a target, or before the
32
+ * first step, this degrades to exactly the old shape (bare app name, or '' for no target). The
33
+ * worker renders `subtext` as a free string (truncated at 120 chars), so this needs no renderer
34
+ * change — same deal as the palette above: plugin-owned overlay data, one edit in one place.
35
+ */
36
+ export function composeSubtext(store) {
37
+ const appName = store?.target?.appName ?? '';
38
+ if (!appName) return '';
39
+ const last = store.steps?.[store.steps.length - 1];
40
+ const run = store.counters?.stepsRun ?? 0;
41
+ if (!last?.label || run === 0) return appName;
42
+ return `${appName} · ${last.label}(${run} 步)`;
43
+ }
44
+
45
+ export class ActivityWindow {
46
+ constructor({ indicator, resolveBounds, resolveLabel, resolveMode, logger, onState, canEnd, leaseMs = 300000, beatMs = 30000 }) {
47
+ this.indicator = indicator;
48
+ this.resolveBounds = resolveBounds;
49
+ this.resolveLabel = resolveLabel;
50
+ this.resolveMode = resolveMode;
51
+ this.logger = logger ?? (() => {});
52
+ this.onState = onState ?? (() => {});
53
+ // While one tool command is in flight (busy), lease expiry defers instead of dropping the
54
+ // capsule mid-action. Without it a shrunken DSH_NATIVE_UIA_LEASE_MS could expire inside a
55
+ // long OCR/wait/batch and paint 已停止 while the model is demonstrably still working.
56
+ this.canEnd = canEnd ?? (() => true);
57
+ this.leaseMs = leaseMs;
58
+ /** Rendering keep-alive ONLY: a beat repaints the capsule but never renews the lease. */
59
+ this.beatMs = beatMs;
60
+ this.active = false;
61
+ this.phase = 'hidden';
62
+ this.timer = null;
63
+ this.heartbeat = null;
64
+ this.failures = 0;
65
+ }
66
+
67
+ /** A mutating desktop action started (or continued) the current run.
68
+ * `opts.visible` marks an action that glides the physical cursor (a pixel click/drag/scroll),
69
+ * so the halo must follow it even when the session's default mode is background. */
70
+ claim(opts) {
71
+ const mode = opts?.visible ? 'foreground' : (this.resolveMode?.() ?? 'background');
72
+ if (this.active) {
73
+ this.#renewLease();
74
+ // The only phase a live window can be off is `stopped` (the run was killed): a new action
75
+ // restarts the capsule in place, so paint acting again instead of sending a bare beat.
76
+ if (this.phase !== 'acting') {
77
+ this.phase = 'acting';
78
+ void this.#send('phase', { phase: 'acting', subtext: this.resolveLabel?.() ?? '', mode });
79
+ return;
80
+ }
81
+ void this.#send('beat', { subtext: this.resolveLabel?.() ?? '', mode });
82
+ return;
83
+ }
84
+ this.active = true;
85
+ this.phase = 'acting';
86
+ this.onState(true);
87
+ const bounds = this.resolveBounds?.() ?? null;
88
+ void this.#send('show', {
89
+ ...(bounds !== null ? { bounds } : {}),
90
+ phase: 'acting',
91
+ subtext: this.resolveLabel?.() ?? '',
92
+ mode,
93
+ idleHideMs: this.leaseMs + 30000,
94
+ });
95
+ this.#renewLease();
96
+ this.#startHeartbeat();
97
+ }
98
+
99
+ /**
100
+ * A read-only step (snapshot, window list, capture, parse) happened inside a run.
101
+ *
102
+ * Observation must not *start* the indicator — a session that only reads never lights the
103
+ * screen — but while a run is already on, a model that spends a long time looking (thinking,
104
+ * re-reading a tree, waiting on a vision model) must not lose the overlay: the previous
105
+ * design renewed the lease only on the next *mutating* action, so any long think gap let the
106
+ * lease expire and the capsule (with its 御屏 label) vanished mid-run.
107
+ */
108
+ observe() {
109
+ if (!this.active) return;
110
+ this.#renewLease();
111
+ void this.#send('beat', { subtext: this.resolveLabel?.() ?? '' });
112
+ }
113
+
114
+ /**
115
+ * Capture the desktop without capturing our own indicator. The indicator is an always-on-top WPF
116
+ * window, so desktop GDI capture quite correctly includes it; that is wrong for evidence and can
117
+ * become recursive when the screenshot preview itself is visible. Hide only the pixels for this
118
+ * read, keep the logical run alive, then restore the same phase immediately afterwards.
119
+ */
120
+ async withoutIndicator(fn) {
121
+ const wasActive = this.active;
122
+ if (!wasActive) return fn();
123
+ await this.#send('phase', { phase: 'hidden' });
124
+ // Give WPF one dispatcher turn to commit the hidden HWND before GDI samples the desktop.
125
+ await new Promise((resolve) => setTimeout(resolve, 50));
126
+ try {
127
+ return await fn();
128
+ } finally {
129
+ if (this.active) {
130
+ await this.#send('phase', {
131
+ phase: this.phase === 'stopped' ? 'stopped' : 'acting',
132
+ subtext: this.resolveLabel?.() ?? '',
133
+ mode: this.resolveMode?.() ?? 'background',
134
+ });
135
+ }
136
+ }
137
+ }
138
+
139
+ /** The run ended: flash, then the server collapses it. */
140
+ async end({ reason = 'done' } = {}) {
141
+ if (!this.active) return;
142
+ this.active = false;
143
+ this.#clearLease();
144
+ this.#stopHeartbeat();
145
+ this.phase = 'stopped';
146
+ this.onState(false);
147
+ await this.#send('phase', { phase: 'stopped' });
148
+ this.logger(`指示器已收尾(${reason})`);
149
+ }
150
+
151
+ dispose() {
152
+ this.#clearLease();
153
+ this.#stopHeartbeat();
154
+ this.active = false;
155
+ return this.#send('shutdown', {}, { swallow: false });
156
+ }
157
+
158
+ #renewLease() {
159
+ this.#clearLease();
160
+ const fire = () => {
161
+ // A single command still in flight is not a dead run: re-arm and check again one lease out.
162
+ if (this.active && this.canEnd() === false) { this.#renewLease(); return; }
163
+ void this.end({ reason: '租约到期,自最后一次工具调用起已超时' });
164
+ };
165
+ const timer = setTimeout(fire, this.leaseMs);
166
+ timer.unref?.();
167
+ this.timer = timer;
168
+ }
169
+
170
+ #clearLease() {
171
+ if (this.timer !== null) clearTimeout(this.timer);
172
+ this.timer = null;
173
+ }
174
+
175
+ /**
176
+ * Keep the capsule visibly rendered between actions.
177
+ *
178
+ * The beat feeds only the RENDERER's `idleHideMs` watchdog (every command resets it), so the
179
+ * overlay does not blink out between clicks while the Node side still considers the run alive.
180
+ * It deliberately does NOT renew the Node lease: the lease measures real model activity (its
181
+ * renewals come from claim() and observe()), and when that runs out the run is over. A beat
182
+ * that re-armed the lease made the capsule immortal — the design bug behind "agent 用完后指示层
183
+ * 不会停止": a run the model never closed with computer_done beat forever and never went out.
184
+ */
185
+ #startHeartbeat() {
186
+ this.#stopHeartbeat();
187
+ const timer = setInterval(() => {
188
+ if (!this.active) { this.#stopHeartbeat(); return; }
189
+ void this.#send('beat', { subtext: this.resolveLabel?.() ?? '' });
190
+ }, this.beatMs);
191
+ timer.unref?.();
192
+ this.heartbeat = timer;
193
+ }
194
+
195
+ #stopHeartbeat() {
196
+ if (this.heartbeat !== null) clearInterval(this.heartbeat);
197
+ this.heartbeat = null;
198
+ }
199
+
200
+ async #send(cmd, args, { swallow = true } = {}) {
201
+ if (this.indicator === null || this.indicator === undefined) return false;
202
+ const payload = (cmd === 'show' || cmd === 'phase' || cmd === 'beat') ? { ...args, palette: PALETTE } : args;
203
+ try {
204
+ await this.indicator.call(cmd, payload, { timeoutMs: 4000 });
205
+ return true;
206
+ } catch (error) {
207
+ this.failures++;
208
+ if (this.failures <= 3 || !swallow) this.logger(`指示器 ${cmd} 失败:${error?.message ?? error}`, 'warn');
209
+ return false;
210
+ }
211
+ }
212
+ }
@@ -0,0 +1,145 @@
1
+ import { createServer } from 'node:http';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { existsSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { resolve, sep } from 'node:path';
6
+
7
+ const CONTROL_HTML = fileURLToPath(new URL('../web/control.html', import.meta.url));
8
+ /** Cross-origin pages cannot set this header without a preflight the browser will not skip. */
9
+ const API_HEADER = 'x-dsh-cua';
10
+
11
+ function json(res, code, body) {
12
+ const text = JSON.stringify(body);
13
+ res.writeHead(code, {
14
+ 'content-type': 'application/json; charset=utf-8',
15
+ 'content-length': Buffer.byteLength(text),
16
+ 'cache-control': 'no-store',
17
+ });
18
+ res.end(text);
19
+ }
20
+
21
+ export class Dashboard {
22
+ clients = new Set();
23
+
24
+ constructor({ host, port, store, policy, commands, dataDir }) {
25
+ this.host = host;
26
+ this.port = port;
27
+ this.store = store;
28
+ this.policy = policy;
29
+ this.commands = commands;
30
+ this.dataDir = resolve(dataDir);
31
+ this.server = createServer((req, res) => void this.#handle(req, res));
32
+ for (const event of ['state', 'step', 'blocked', 'screenshot', 'log']) {
33
+ this.store.on(event, (payload) => this.#broadcast(event, payload));
34
+ }
35
+ }
36
+
37
+ listen() {
38
+ return new Promise((promiseResolve, promiseReject) => {
39
+ const onError = (error) => promiseReject(error);
40
+ this.server.once('error', onError);
41
+ this.server.listen(this.port, this.host, () => {
42
+ this.server.removeListener('error', onError);
43
+ this.url = `http://${this.host}:${this.port}/control.html`;
44
+ promiseResolve(this.url);
45
+ });
46
+ });
47
+ }
48
+
49
+ #broadcast(event, payload) {
50
+ const frame = `event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`;
51
+ // Cheap defense-in-depth, measured: Node's http layer already absorbs a write to a destroyed
52
+ // socket (no uncaughtException, the 'close' handler below removes the client). What this adds
53
+ // is not crash safety — it drops a failing client immediately instead of waiting for 'close',
54
+ // and keeps the fan-out loop itself off any future change that throws synchronously.
55
+ for (const res of [...this.clients]) {
56
+ try {
57
+ res.write(frame);
58
+ } catch {
59
+ this.clients.delete(res);
60
+ }
61
+ }
62
+ }
63
+
64
+ async #readBody(req) {
65
+ const chunks = [];
66
+ let size = 0;
67
+ for await (const chunk of req) {
68
+ size += chunk.length;
69
+ if (size > 64 * 1024) throw new Error('body too large');
70
+ chunks.push(chunk);
71
+ }
72
+ return Buffer.concat(chunks).toString('utf8');
73
+ }
74
+
75
+ async #handle(req, res) {
76
+ const url = new URL(req.url ?? '/', `http://${this.host}`);
77
+ try {
78
+ if (url.pathname === '/control.html' || url.pathname === '/') {
79
+ const html = await readFile(CONTROL_HTML);
80
+ if (!this.pageServed) {
81
+ this.pageServed = true;
82
+ this.store.line('面板页面已被取走:客户端组件已加载');
83
+ }
84
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
85
+ res.end(html);
86
+ return;
87
+ }
88
+ if (url.pathname === '/api/state') {
89
+ json(res, 200, this.store.snapshot(this.policy));
90
+ return;
91
+ }
92
+ if (url.pathname === '/api/stream') {
93
+ res.writeHead(200, {
94
+ 'content-type': 'text/event-stream',
95
+ 'cache-control': 'no-cache',
96
+ connection: 'keep-alive',
97
+ });
98
+ res.write(`event: state\ndata: ${JSON.stringify(this.store.snapshot(this.policy))}\n\n`);
99
+ this.clients.add(res);
100
+ const keepAlive = setInterval(() => res.write(': ping\n\n'), 15000);
101
+ keepAlive.unref?.();
102
+ req.on('close', () => {
103
+ clearInterval(keepAlive);
104
+ this.clients.delete(res);
105
+ });
106
+ return;
107
+ }
108
+ if (url.pathname === '/api/screenshot') {
109
+ const shot = this.store.screenshot;
110
+ if (shot === null || !existsSync(shot.path)) {
111
+ json(res, 404, { ok: false, error: 'no screenshot captured yet' });
112
+ return;
113
+ }
114
+ const inside = resolve(shot.path).startsWith(this.dataDir + sep);
115
+ if (!inside) {
116
+ json(res, 403, { ok: false, error: 'screenshot is outside the plugin data directory' });
117
+ return;
118
+ }
119
+ const bytes = await readFile(shot.path);
120
+ res.writeHead(200, { 'content-type': 'image/png', 'content-length': bytes.length, 'cache-control': 'no-store' });
121
+ res.end(bytes);
122
+ return;
123
+ }
124
+ if (url.pathname === '/api/action') {
125
+ if (req.headers[API_HEADER] !== '1') {
126
+ json(res, 403, { ok: false, error: `missing required ${API_HEADER}: 1 header` });
127
+ return;
128
+ }
129
+ const body = JSON.parse((await this.#readBody(req)) || '{}');
130
+ const outcome = await this.commands.action(body);
131
+ json(res, outcome.ok === false ? 400 : 200, outcome);
132
+ return;
133
+ }
134
+ json(res, 404, { ok: false, error: `unknown endpoint ${url.pathname}` });
135
+ } catch (error) {
136
+ json(res, 500, { ok: false, error: String(error?.message ?? error) });
137
+ }
138
+ }
139
+
140
+ close() {
141
+ for (const res of this.clients) res.end();
142
+ this.clients.clear();
143
+ this.server.close();
144
+ }
145
+ }
package/src/guard.js ADDED
@@ -0,0 +1,191 @@
1
+ /**
2
+ * The single place that decides whether a desktop action may reach the machine.
3
+ * The worker holds no policy at all, and batched steps are checked here before
4
+ * `commit_batch`, so one guard covers interactive calls and replayed recipes.
5
+ */
6
+
7
+ const RISKY_ACTIONS = new Set(['invoke', 'toggle', 'select', 'close_window']);
8
+
9
+ const SHUTDOWN = /(?:\b(?:shut\s*down|shutdown|power\s*off|restart|reboot|sign\s*out|log\s*off|logoff|log\s*out|hibernate)\b|关机|注销|重启|休眠|退出登录)/i;
10
+ // A window's close affordance is called 关闭 / Close / ✕ in real UIA trees, not "关闭程序". Without
11
+ // this family an `invoke` on it sailed through the old pattern and closed whole applications - the
12
+ // name table looked like a boundary while the most obvious bypass sat inside it (2026-10-17).
13
+ // Deliberately NOT matched: 取消/cancel (dismisses a dialog without ending the app) and any name
14
+ // carrying 对话框/提示 (closing a message box is normal work).
15
+ const EXIT = /(?:^(?:exit|quit|close\s*(?:app|application|program))\b|^(?:close|关闭|✕|✖|×)$|退出(?:程序|应用)|关闭(?:程序|应用|窗口))/i;
16
+ const DELETE = /(?:\b(?:delete|remove|discard|erase|empty\s+recycle\s+bin|shred)\b|删除|彻底删除|清空回收站|丢弃)/i;
17
+
18
+ const DENY_EXECUTABLES = /^(?:shutdown|logoff|taskkill|psshutdown|restart|poweroff)\.exe$/i;
19
+
20
+ const CATEGORIES = {
21
+ shutdown: {
22
+ refusal: '系统关机或注销会话',
23
+ advice: '请让用户自己执行关机、重启或注销。',
24
+ },
25
+ exit: {
26
+ refusal: '退出应用程序',
27
+ advice: '不要关闭整个程序;只处理你用完的那个对话框或窗口,或者让用户自己退出。',
28
+ },
29
+ delete: {
30
+ refusal: '破坏性删除',
31
+ advice: '改走可撤销的路子(选中后按退格、重命名或移动),或者请用户自己确认删除。',
32
+ },
33
+ loop: {
34
+ refusal: '同批内连续重复同一滚动动作且没有任何结果校验(疑似无效滚动循环)',
35
+ advice: '先重新 snapshot/find_text 观察列表是否真的滚动了;或给滚动步加 verify:{type:"scroll_percent_changed"},滚动无效果时批次会停下来。',
36
+ },
37
+ };
38
+
39
+ function text(descriptor) {
40
+ return [descriptor?.name, descriptor?.automationId, descriptor?.className, descriptor?.label, descriptor?.title]
41
+ .filter((v) => typeof v === 'string' && v !== '')
42
+ .join(' ');
43
+ }
44
+
45
+ function categoryOf(descriptor, action) {
46
+ const hay = `${text(descriptor)} ${descriptor?.command ?? ''}`.trim();
47
+ if (hay === '') return null;
48
+ if (SHUTDOWN.test(hay)) return 'shutdown';
49
+ if (action === 'close_window') return null;
50
+ if (EXIT.test(hay)) return 'exit';
51
+ if (DELETE.test(hay)) return 'delete';
52
+ return null;
53
+ }
54
+
55
+ function denied(category) {
56
+ return { verdict: 'deny', category, refusal: CATEGORIES[category].refusal, advice: CATEGORIES[category].advice };
57
+ }
58
+
59
+ // A raw hotkey has no element descriptor to feed the name table, so the two combos that end an
60
+ // app or lock the session are matched on the combo text itself. Everything else falls through to
61
+ // the same categoryOf hay pipeline (SHUTDOWN/EXIT/DELETE never match an ordinary combo like
62
+ // ctrl+c, so it stays allowed). The refusal wording stays in CATEGORIES instead of being
63
+ // hand-written inside the tool: guard.js is the only policy decision point.
64
+ const KEY_LOCK = /(?:^|\+)win\+l(?:\+|$)/;
65
+ const KEY_EXIT = /(?:^|\+)alt\+f4(?:\+|$)/;
66
+
67
+ /**
68
+ * Same policy vocabulary as classify(), for keyboard combos.
69
+ * @param {string} combo - lowercased key combo, e.g. "ctrl+shift+s"
70
+ */
71
+ export function classifyKeys(combo) {
72
+ const hay = String(combo ?? '').trim().toLowerCase();
73
+ if (hay === '') return { verdict: 'allow' };
74
+ if (KEY_LOCK.test(hay)) return denied('shutdown'); // win+l locks the session
75
+ if (KEY_EXIT.test(hay)) return denied('exit'); // alt+f4 closes the focused app
76
+ const category = categoryOf({ name: hay, command: hay }, 'invoke');
77
+ if (category === null) return { verdict: 'allow' };
78
+ return denied(category);
79
+ }
80
+
81
+ /**
82
+ * @param {{action: string, descriptor?: object}} request - descriptor is the UIA
83
+ * element the worker resolved for this step, never model-authored prose.
84
+ * @returns {{verdict: 'allow'} | {verdict: 'deny', category: string, refusal: string, advice: string}}
85
+ */
86
+ export function classify(request) {
87
+ // Steps authored in free JSON can carry any case ("Invoke"); RISKY_ACTIONS is lowercase, so the
88
+ // one policy gate must normalise before matching or a case variant sails past the text refusal.
89
+ const action = String(request.action ?? '').toLowerCase();
90
+ if (!RISKY_ACTIONS.has(action)) return { verdict: 'allow' };
91
+ const category = categoryOf(request.descriptor, action);
92
+ if (category === null) return { verdict: 'allow' };
93
+ const meta = CATEGORIES[category];
94
+ return { verdict: 'deny', category, refusal: meta.refusal, advice: meta.advice };
95
+ }
96
+
97
+ // AndroidWorld 的「动作缓存不记结果导致无限滚动」在御屏的对应形态:同一滚动步(键 =
98
+ // action + 目标 + value)在批内"连续"重复 ≥3 次且这一段里没有任何 verify。刻意收窄到滚动族:
99
+ // 连点/重试同一条 invoke 是正常工作(确认对话框、双击),不拦;要求"连续"是因为
100
+ // 滚动-点击-滚动-点击是轮询式操作,不是卡死的滚动;重复段里出现任一 verify 就整段放行,
101
+ // 因为 verify 未命中会硬停批次(verify_failed → break),循环已被结果校验兜住。
102
+ const SCROLL_ACTIONS = new Set(['scroll_up', 'scroll_down', 'pointer_scroll']);
103
+ const LOOP_REPEATS = 3;
104
+
105
+ function loopKey(step) {
106
+ return `${String(step?.action ?? '').toLowerCase()}|${JSON.stringify(step?.ref ?? step?.by ?? null)}|${String(step?.value ?? '')}`;
107
+ }
108
+
109
+ /**
110
+ * 防循环护栏:批内同一滚动步连续重复 ≥3 次且重复段内没有任何 verify 时,在第 3 次出现处拒绝。
111
+ * @param {Array<{action?: string, ref?: string, by?: object, value?: unknown, verify?: object}>} steps
112
+ * @returns {{verdict: 'deny', category: 'loop', refusal: string, advice: string, index: number} | null}
113
+ */
114
+ function classifyLoop(steps) {
115
+ const list = Array.isArray(steps) ? steps : [];
116
+ let prevKey = null;
117
+ let run = 0;
118
+ let runHasVerify = false;
119
+ for (let i = 0; i < list.length; i++) {
120
+ const step = list[i] ?? {};
121
+ if (!SCROLL_ACTIONS.has(String(step.action ?? '').toLowerCase())) {
122
+ prevKey = null;
123
+ run = 0;
124
+ runHasVerify = false;
125
+ continue;
126
+ }
127
+ const key = loopKey(step);
128
+ if (key === prevKey) {
129
+ run += 1;
130
+ if (step?.verify != null) runHasVerify = true;
131
+ } else {
132
+ prevKey = key;
133
+ run = 1;
134
+ runHasVerify = step?.verify != null;
135
+ }
136
+ if (run >= LOOP_REPEATS && !runHasVerify) return { ...denied('loop'), index: i };
137
+ }
138
+ return null;
139
+ }
140
+
141
+ /**
142
+ * Batch pre-check shared by computer_run and computer_replay: the one "check every step,
143
+ * stop at the first deny" loop. The loop guard runs first (it is a shape check on the steps
144
+ * themselves, before any descriptor exists), then per-step policy. Callers keep their own
145
+ * refusal wording and store.step bookkeeping; this returns the first deny tagged with its
146
+ * index, or null when every step is allowed. Action normalisation happens inside classify(),
147
+ * so raw step values go in as-is.
148
+ * @param {Array<{action?: string}>} steps
149
+ * @param {Array<object|undefined>} descriptors - UIA descriptors resolved by prepare_batch, aligned with steps
150
+ * @returns {{verdict: 'deny', category: string, refusal: string, advice: string, index: number} | null}
151
+ */
152
+ export function classifyBatch(steps, descriptors) {
153
+ const list = Array.isArray(steps) ? steps : [];
154
+ const loop = classifyLoop(list);
155
+ if (loop !== null) return loop;
156
+ for (let i = 0; i < list.length; i++) {
157
+ const outcome = classify({ action: list[i]?.action, descriptor: descriptors?.[i] });
158
+ if (outcome.verdict === 'deny') return { ...outcome, index: i };
159
+ }
160
+ return null;
161
+ }
162
+
163
+ /** Closing an application window is the same category as quitting it. */
164
+ export function classifyClose(descriptor) {
165
+ const category = descriptor?.ownedByPlugin === true ? null : 'exit';
166
+ if (category === null) return { verdict: 'allow' };
167
+ return { verdict: 'deny', category, refusal: CATEGORIES[category].refusal, advice: CATEGORIES[category].advice };
168
+ }
169
+
170
+ export function classifyLaunch(app) {
171
+ const leaf = String(app ?? '').trim().split(/[\\/]/).pop() ?? '';
172
+ if (DENY_EXECUTABLES.test(leaf)) {
173
+ return { verdict: 'deny', category: 'shutdown', refusal: CATEGORIES.shutdown.refusal, advice: CATEGORIES.shutdown.advice };
174
+ }
175
+ return { verdict: 'allow' };
176
+ }
177
+
178
+ export const POLICY = {
179
+ mode: 'dev',
180
+ deniedCategories: ['shutdown', 'logoff', 'restart', 'exit', 'delete'],
181
+ approvable: false,
182
+ // The note names the CURRENT mode, so it is written from the activation env — the same switch
183
+ // the store sets and the worker choke point enforces. A static string would go stale the moment
184
+ // read-only mode is on. Read-only layers on top: the hard-refuse categories and the
185
+ // non-approvable rule are unchanged, delivery is additionally refused wholesale.
186
+ note: process.env.DSH_NATIVE_UIA_READ_ONLY === '1'
187
+ ? '只读观察模式(DSH_NATIVE_UIA_READ_ONLY=1):快照/find_text/parse/ocr 等观察照常,投递类动作在咽喉点一律拒绝(read_only_mode)。下列硬拒分类照旧,仍不可批准。'
188
+ : '硬拒不可批准:用户选择拦住的这几类,对任何调用方都拦住,配方回放也一样。',
189
+ };
190
+
191
+ export { RISKY_ACTIONS };