dsh-native-uia 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +663 -2
- package/client/client.js +269 -0
- package/cordis.patch.yml +10 -0
- package/icon.svg +11 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -4
- package/scripts/bench-live.mjs +157 -0
- package/scripts/check-lease.mjs +308 -0
- package/scripts/install.mjs +154 -0
- package/scripts/lib/dsh-tools-stub.mjs +14 -0
- package/scripts/lib/load-tools-source.mjs +25 -0
- package/scripts/lib/sources.mjs +62 -0
- package/scripts/load-tools.mjs +74 -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 +192 -0
- package/scripts/regression-worker.ps1 +1071 -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-style.mjs +46 -0
- package/scripts/verify-live.mjs +104 -0
- package/scripts/verify-locator.mjs +52 -0
- package/scripts/verify.mjs +2110 -0
- package/src/activity-window.js +276 -0
- package/src/dashboard.js +103 -0
- package/src/guard.js +201 -0
- package/src/index.js +525 -0
- package/src/native-uia-remote.js +80 -0
- package/src/notes.js +83 -0
- package/src/state.js +267 -0
- package/src/themes.js +74 -0
- package/src/tools/defs/act.js +533 -0
- package/src/tools/defs/lifecycle.js +205 -0
- package/src/tools/defs/observe.js +309 -0
- package/src/tools/defs/pointer.js +298 -0
- package/src/tools/format.js +301 -0
- package/src/tools/index.js +128 -0
- package/src/tools/ocr.js +91 -0
- package/src/tools/recipes.js +44 -0
- package/src/tools/runtime.js +42 -0
- package/src/worker-client.js +268 -0
- package/worker/assets/dsh-whale.path +1 -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 +2963 -0
- package/worker/lib/01-core.ps1 +64 -0
- package/worker/lib/02-uia.ps1 +221 -0
- package/worker/lib/03-window.ps1 +194 -0
- package/worker/lib/04-match.ps1 +435 -0
- package/worker/lib/05-value.ps1 +149 -0
- package/worker/lib/06-snapshot.ps1 +345 -0
- package/worker/lib/07-action.ps1 +291 -0
- package/worker/lib/08-command.ps1 +1485 -0
- package/worker/lib/09-pointer.ps1 +840 -0
- package/worker/lib/10-dispatch.ps1 +134 -0
- package/worker/ps-stdio.ps1 +173 -0
- package/worker/uia-worker.ps1 +599 -0
|
@@ -0,0 +1,276 @@
|
|
|
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: '#2A2E34',
|
|
20
|
+
ringTo: '#000000',
|
|
21
|
+
pillBg: '#0B0D10',
|
|
22
|
+
pillBorder: '#A9B4C4',
|
|
23
|
+
pillText: '#F2F5FA',
|
|
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, resolvePalette, resolveStyle, resolveMist, logger, onState, canEnd, leaseMs = 300000, beatMs = 30000 }) {
|
|
47
|
+
this.indicator = indicator;
|
|
48
|
+
this.resolveBounds = resolveBounds;
|
|
49
|
+
this.resolveLabel = resolveLabel;
|
|
50
|
+
this.resolveMode = resolveMode;
|
|
51
|
+
// The panel can change both while a run is live; reading them at send time is what makes the
|
|
52
|
+
// switch immediate instead of "after this run".
|
|
53
|
+
this.resolvePalette = resolvePalette;
|
|
54
|
+
this.resolveStyle = resolveStyle;
|
|
55
|
+
this.resolveMist = resolveMist;
|
|
56
|
+
this.logger = logger ?? (() => {});
|
|
57
|
+
this.onState = onState ?? (() => {});
|
|
58
|
+
// While one tool command is in flight (busy), lease expiry defers instead of dropping the
|
|
59
|
+
// capsule mid-action. Without it a shrunken DSH_NATIVE_UIA_LEASE_MS could expire inside a
|
|
60
|
+
// long OCR/wait/batch and paint 已停止 while the model is demonstrably still working.
|
|
61
|
+
this.canEnd = canEnd ?? (() => true);
|
|
62
|
+
this.leaseMs = leaseMs;
|
|
63
|
+
/** Rendering keep-alive ONLY: a beat repaints the capsule but never renews the lease. */
|
|
64
|
+
this.beatMs = beatMs;
|
|
65
|
+
this.active = false;
|
|
66
|
+
this.phase = 'hidden';
|
|
67
|
+
this.timer = null;
|
|
68
|
+
this.heartbeat = null;
|
|
69
|
+
this.failures = 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A mutating desktop action started (or continued) the current run.
|
|
73
|
+
* `opts.visible` marks an action that glides the physical cursor (a pixel click/drag/scroll),
|
|
74
|
+
* so the halo must follow it even when the session's default mode is background. */
|
|
75
|
+
claim(opts) {
|
|
76
|
+
const mode = opts?.visible ? 'foreground' : (this.resolveMode?.() ?? 'background');
|
|
77
|
+
if (this.active) {
|
|
78
|
+
this.#renewLease();
|
|
79
|
+
// The only phase a live window can be off is `stopped` (the run was killed): a new action
|
|
80
|
+
// restarts the capsule in place, so paint acting again instead of sending a bare beat.
|
|
81
|
+
if (this.phase !== 'acting') {
|
|
82
|
+
this.phase = 'acting';
|
|
83
|
+
void this.#send('phase', { phase: 'acting', subtext: this.resolveLabel?.() ?? '', mode });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
void this.#send('beat', { subtext: this.resolveLabel?.() ?? '', mode });
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
this.active = true;
|
|
90
|
+
this.phase = 'acting';
|
|
91
|
+
this.onState(true);
|
|
92
|
+
const bounds = this.resolveBounds?.() ?? null;
|
|
93
|
+
void this.#send('show', {
|
|
94
|
+
...(bounds !== null ? { bounds } : {}),
|
|
95
|
+
phase: 'acting',
|
|
96
|
+
subtext: this.resolveLabel?.() ?? '',
|
|
97
|
+
mode,
|
|
98
|
+
idleHideMs: this.leaseMs + 30000,
|
|
99
|
+
});
|
|
100
|
+
this.#renewLease();
|
|
101
|
+
this.#startHeartbeat();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* A read-only step (snapshot, window list, capture, parse) happened inside a run.
|
|
106
|
+
*
|
|
107
|
+
* Observation must not *start* the indicator — a session that only reads never lights the
|
|
108
|
+
* screen — but while a run is already on, a model that spends a long time looking (thinking,
|
|
109
|
+
* re-reading a tree, waiting on a vision model) must not lose the overlay: the previous
|
|
110
|
+
* design renewed the lease only on the next *mutating* action, so any long think gap let the
|
|
111
|
+
* lease expire and the capsule (with its 御屏 label) vanished mid-run.
|
|
112
|
+
*/
|
|
113
|
+
observe() {
|
|
114
|
+
if (!this.active) return;
|
|
115
|
+
this.#renewLease();
|
|
116
|
+
void this.#send('beat', { subtext: this.resolveLabel?.() ?? '' });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Capture the desktop without capturing our own indicator. The indicator is an always-on-top WPF
|
|
121
|
+
* window, so desktop GDI capture quite correctly includes it; that is wrong for evidence and can
|
|
122
|
+
* become recursive when the screenshot preview itself is visible. Hide only the pixels for this
|
|
123
|
+
* read, keep the logical run alive, then restore the same phase immediately afterwards.
|
|
124
|
+
*/
|
|
125
|
+
async withoutIndicator(fn) {
|
|
126
|
+
const wasActive = this.active;
|
|
127
|
+
if (!wasActive) return fn();
|
|
128
|
+
await this.#send('phase', { phase: 'hidden' });
|
|
129
|
+
// Give WPF one dispatcher turn to commit the hidden HWND before GDI samples the desktop.
|
|
130
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
131
|
+
try {
|
|
132
|
+
return await fn();
|
|
133
|
+
} finally {
|
|
134
|
+
if (this.active) {
|
|
135
|
+
await this.#send('phase', {
|
|
136
|
+
phase: this.phase === 'stopped' ? 'stopped' : 'acting',
|
|
137
|
+
subtext: this.resolveLabel?.() ?? '',
|
|
138
|
+
mode: this.resolveMode?.() ?? 'background',
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The run ended: flash, then the server collapses it. */
|
|
145
|
+
async end({ reason = 'done' } = {}) {
|
|
146
|
+
if (!this.active) return;
|
|
147
|
+
this.active = false;
|
|
148
|
+
this.#clearLease();
|
|
149
|
+
this.#stopHeartbeat();
|
|
150
|
+
this.phase = 'stopped';
|
|
151
|
+
this.onState(false);
|
|
152
|
+
await this.#send('phase', { phase: 'stopped' });
|
|
153
|
+
this.logger(`指示器已收尾(${reason})`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
dispose() {
|
|
157
|
+
this.#clearLease();
|
|
158
|
+
this.#stopHeartbeat();
|
|
159
|
+
this.active = false;
|
|
160
|
+
return this.#send('shutdown', {}, { swallow: false });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
#renewLease() {
|
|
164
|
+
this.#clearLease();
|
|
165
|
+
const fire = () => {
|
|
166
|
+
// A single command still in flight is not a dead run: re-arm and check again one lease out.
|
|
167
|
+
if (this.active && this.canEnd() === false) { this.#renewLease(); return; }
|
|
168
|
+
void this.end({ reason: '租约到期,自最后一次工具调用起已超时' });
|
|
169
|
+
};
|
|
170
|
+
const timer = setTimeout(fire, this.leaseMs);
|
|
171
|
+
timer.unref?.();
|
|
172
|
+
this.timer = timer;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
#clearLease() {
|
|
176
|
+
if (this.timer !== null) clearTimeout(this.timer);
|
|
177
|
+
this.timer = null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Keep the capsule visibly rendered between actions.
|
|
182
|
+
*
|
|
183
|
+
* The beat feeds only the RENDERER's `idleHideMs` watchdog (every command resets it), so the
|
|
184
|
+
* overlay does not blink out between clicks while the Node side still considers the run alive.
|
|
185
|
+
* It deliberately does NOT renew the Node lease: the lease measures real model activity (its
|
|
186
|
+
* renewals come from claim() and observe()), and when that runs out the run is over. A beat
|
|
187
|
+
* that re-armed the lease made the capsule immortal — the design bug behind "agent 用完后指示层
|
|
188
|
+
* 不会停止": a run the model never closed with computer_done beat forever and never went out.
|
|
189
|
+
*/
|
|
190
|
+
#startHeartbeat() {
|
|
191
|
+
this.#stopHeartbeat();
|
|
192
|
+
const timer = setInterval(() => {
|
|
193
|
+
if (!this.active) { this.#stopHeartbeat(); return; }
|
|
194
|
+
void this.#send('beat', { subtext: this.resolveLabel?.() ?? '' });
|
|
195
|
+
}, this.beatMs);
|
|
196
|
+
timer.unref?.();
|
|
197
|
+
this.heartbeat = timer;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
#stopHeartbeat() {
|
|
201
|
+
if (this.heartbeat !== null) clearInterval(this.heartbeat);
|
|
202
|
+
this.heartbeat = null;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Re-send the current phase with today's theme/style. Called when the person changes either from
|
|
207
|
+
* the plugin page: without it the new look would only appear on the next claim/beat, which can be
|
|
208
|
+
* half a minute away and reads as "the switch did nothing".
|
|
209
|
+
*/
|
|
210
|
+
async refresh() {
|
|
211
|
+
if (!this.active) return false;
|
|
212
|
+
return this.#send('phase', {
|
|
213
|
+
phase: this.phase === 'stopped' ? 'stopped' : 'acting',
|
|
214
|
+
subtext: this.resolveLabel?.() ?? '',
|
|
215
|
+
mode: this.resolveMode?.() ?? 'background',
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Show the capsule for a few seconds so a look change can be SEEN.
|
|
221
|
+
*
|
|
222
|
+
* `refresh()` only repaints a capsule that a run already put on screen. With no run active there
|
|
223
|
+
* is nothing to repaint, so choosing a shape or a palette on the plugin page changed the stored
|
|
224
|
+
* value and left the screen empty -- the person had no way to tell the switch had done anything
|
|
225
|
+
* until the next desktop action, which might be minutes away. This paints the real capsule with
|
|
226
|
+
* the real palette and shape for `ms`, then lets it fade out on its own.
|
|
227
|
+
*
|
|
228
|
+
* It is a PREVIEW, not a run: it claims no lease, starts no heartbeat, sets no `active` flag, and
|
|
229
|
+
* touches no run state, so an idle session stays idle and the model's channel is unaffected. If a
|
|
230
|
+
* run is live this does nothing at all -- `refresh()` is the right call there, and a preview on
|
|
231
|
+
* top of a live capsule would only flicker.
|
|
232
|
+
*/
|
|
233
|
+
async preview({ ms = 2600 } = {}) {
|
|
234
|
+
if (this.active) return false;
|
|
235
|
+
const bounds = this.resolveBounds?.() ?? null;
|
|
236
|
+
const shown = await this.#send('show', {
|
|
237
|
+
...(bounds !== null ? { bounds } : {}),
|
|
238
|
+
phase: 'acting',
|
|
239
|
+
subtext: this.resolveLabel?.() ?? '',
|
|
240
|
+
mode: this.resolveMode?.() ?? 'background',
|
|
241
|
+
// The renderer's own idle watchdog hides it; this is the same mechanism, just short.
|
|
242
|
+
idleHideMs: ms,
|
|
243
|
+
}, { swallow: false });
|
|
244
|
+
if (!shown) return false;
|
|
245
|
+
// The window is shown by the renderer's idle timer; `stopped` is the fade-out the person sees
|
|
246
|
+
// at the end of a run, and it is the honest way to end a preview too (no fake run state).
|
|
247
|
+
const hideAt = setTimeout(() => {
|
|
248
|
+
void this.#send('phase', { phase: 'stopped' });
|
|
249
|
+
}, ms);
|
|
250
|
+
hideAt.unref?.();
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async #send(cmd, args, { swallow = true } = {}) {
|
|
255
|
+
if (this.indicator === null || this.indicator === undefined) return false;
|
|
256
|
+
const payload = (cmd === 'show' || cmd === 'phase' || cmd === 'beat')
|
|
257
|
+
? {
|
|
258
|
+
...args,
|
|
259
|
+
palette: this.resolvePalette?.() ?? PALETTE,
|
|
260
|
+
style: this.resolveStyle?.() ?? 'orb',
|
|
261
|
+
// The smoke is part of the capsule tree, so it rides with the look on every command the
|
|
262
|
+
// renderer rebuilds from. Read at send time, so a switch applies to the capsule already on
|
|
263
|
+
// screen without waiting for the next run.
|
|
264
|
+
mist: this.resolveMist?.() !== false,
|
|
265
|
+
}
|
|
266
|
+
: args;
|
|
267
|
+
try {
|
|
268
|
+
await this.indicator.call(cmd, payload, { timeoutMs: 4000 });
|
|
269
|
+
return true;
|
|
270
|
+
} catch (error) {
|
|
271
|
+
this.failures++;
|
|
272
|
+
if (this.failures <= 3 || !swallow) this.logger(`指示器 ${cmd} 失败:${error?.message ?? error}`, 'warn');
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
package/src/dashboard.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
|
|
3
|
+
/** Cross-origin pages cannot set this header without a preflight the browser will not skip. */
|
|
4
|
+
const API_HEADER = 'x-dsh-cua';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The panel lives in the app renderer (the plugin's own detail page), whose origin is not this
|
|
8
|
+
* loopback port, so every read it makes is a cross-origin fetch. The port binds 127.0.0.1 only,
|
|
9
|
+
* and writes still need API_HEADER — CORS here buys the panel its reads, not open control.
|
|
10
|
+
*/
|
|
11
|
+
const CORS = {
|
|
12
|
+
'access-control-allow-origin': '*',
|
|
13
|
+
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
14
|
+
'access-control-allow-headers': `content-type, ${API_HEADER}`,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
function json(res, code, body) {
|
|
18
|
+
const text = JSON.stringify(body);
|
|
19
|
+
res.writeHead(code, {
|
|
20
|
+
'content-type': 'application/json; charset=utf-8',
|
|
21
|
+
'content-length': Buffer.byteLength(text),
|
|
22
|
+
'cache-control': 'no-store',
|
|
23
|
+
...CORS,
|
|
24
|
+
});
|
|
25
|
+
res.end(text);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The loopback state service the plugin-page panel polls. It serves two reads and one write and
|
|
30
|
+
* nothing else: the full snapshot stays available for diagnostics, the summary is what the panel
|
|
31
|
+
* draws, and every state change a person can make from it goes through /api/action.
|
|
32
|
+
*/
|
|
33
|
+
export class Dashboard {
|
|
34
|
+
constructor({ host, port, store, policy, commands, config }) {
|
|
35
|
+
this.host = host;
|
|
36
|
+
this.port = port;
|
|
37
|
+
this.store = store;
|
|
38
|
+
this.policy = policy;
|
|
39
|
+
this.commands = commands;
|
|
40
|
+
/** Facts the plugin page reports but cannot change there (bind, read-only, timeouts). */
|
|
41
|
+
this.config = config;
|
|
42
|
+
this.server = createServer((req, res) => void this.#handle(req, res));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
listen() {
|
|
46
|
+
return new Promise((promiseResolve, promiseReject) => {
|
|
47
|
+
const onError = (error) => promiseReject(error);
|
|
48
|
+
this.server.once('error', onError);
|
|
49
|
+
this.server.listen(this.port, this.host, () => {
|
|
50
|
+
this.server.removeListener('error', onError);
|
|
51
|
+
this.url = `http://${this.host}:${this.port}`;
|
|
52
|
+
promiseResolve(this.url);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async #readBody(req) {
|
|
58
|
+
const chunks = [];
|
|
59
|
+
let size = 0;
|
|
60
|
+
for await (const chunk of req) {
|
|
61
|
+
size += chunk.length;
|
|
62
|
+
if (size > 64 * 1024) throw new Error('body too large');
|
|
63
|
+
chunks.push(chunk);
|
|
64
|
+
}
|
|
65
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async #handle(req, res) {
|
|
69
|
+
const url = new URL(req.url ?? '/', `http://${this.host}`);
|
|
70
|
+
try {
|
|
71
|
+
if (req.method === 'OPTIONS') {
|
|
72
|
+
res.writeHead(204, CORS);
|
|
73
|
+
res.end();
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (url.pathname === '/api/state') {
|
|
77
|
+
json(res, 200, this.store.snapshot(this.policy));
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (url.pathname === '/api/summary') {
|
|
81
|
+
json(res, 200, { ...this.store.summary(), config: this.config?.() ?? null });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (url.pathname === '/api/action' && req.method === 'POST') {
|
|
85
|
+
if (req.headers[API_HEADER] !== '1') {
|
|
86
|
+
json(res, 403, { ok: false, error: `missing required ${API_HEADER}: 1 header` });
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const body = JSON.parse((await this.#readBody(req)) || '{}');
|
|
90
|
+
const outcome = await this.commands.action(body);
|
|
91
|
+
json(res, outcome.ok === false ? 400 : 200, outcome);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
json(res, 404, { ok: false, error: `unknown endpoint ${url.pathname}` });
|
|
95
|
+
} catch (error) {
|
|
96
|
+
json(res, 500, { ok: false, error: String(error?.message ?? error) });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
close() {
|
|
101
|
+
this.server.close();
|
|
102
|
+
}
|
|
103
|
+
}
|
package/src/guard.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
/**
|
|
60
|
+
* A category is always a hard refusal: the policy has no interactive verdict left.
|
|
61
|
+
* @param {string} category - key of CATEGORIES
|
|
62
|
+
*/
|
|
63
|
+
function verdictFor(category) {
|
|
64
|
+
return denied(category);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// A raw hotkey has no element descriptor to feed the name table, so the two combos that end an
|
|
68
|
+
// app or lock the session are matched on the combo text itself. Everything else falls through to
|
|
69
|
+
// the same categoryOf hay pipeline (SHUTDOWN/EXIT/DELETE never match an ordinary combo like
|
|
70
|
+
// ctrl+c, so it stays allowed). The refusal wording stays in CATEGORIES instead of being
|
|
71
|
+
// hand-written inside the tool: guard.js is the only policy decision point.
|
|
72
|
+
const KEY_LOCK = /(?:^|\+)win\+l(?:\+|$)/;
|
|
73
|
+
const KEY_EXIT = /(?:^|\+)alt\+f4(?:\+|$)/;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Same policy vocabulary as classify(), for keyboard combos.
|
|
77
|
+
* @param {string} combo - lowercased key combo, e.g. "ctrl+shift+s"
|
|
78
|
+
*/
|
|
79
|
+
export function classifyKeys(combo) {
|
|
80
|
+
const hay = String(combo ?? '').trim().toLowerCase();
|
|
81
|
+
if (hay === '') return { verdict: 'allow' };
|
|
82
|
+
if (KEY_LOCK.test(hay)) return denied('shutdown'); // win+l locks the session
|
|
83
|
+
if (KEY_EXIT.test(hay)) return denied('exit'); // alt+f4 closes the focused app
|
|
84
|
+
const category = categoryOf({ name: hay, command: hay }, 'invoke');
|
|
85
|
+
if (category === null) return { verdict: 'allow' };
|
|
86
|
+
return denied(category);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @param {{action: string, descriptor?: object}} request - descriptor is the UIA
|
|
91
|
+
* element the worker resolved for this step, never model-authored prose.
|
|
92
|
+
* @returns {{verdict: 'allow'} | {verdict: 'deny', category: string, refusal: string, advice: string}}
|
|
93
|
+
*/
|
|
94
|
+
export function classify(request) {
|
|
95
|
+
// Steps authored in free JSON can carry any case ("Invoke"); RISKY_ACTIONS is lowercase, so the
|
|
96
|
+
// one policy gate must normalise before matching or a case variant sails past the text refusal.
|
|
97
|
+
const action = String(request.action ?? '').toLowerCase();
|
|
98
|
+
if (!RISKY_ACTIONS.has(action)) return { verdict: 'allow' };
|
|
99
|
+
const category = categoryOf(request.descriptor, action);
|
|
100
|
+
if (category === null) return { verdict: 'allow' };
|
|
101
|
+
return verdictFor(category);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// AndroidWorld 的「动作缓存不记结果导致无限滚动」在御屏的对应形态:同一滚动步(键 =
|
|
105
|
+
// action + 目标 + value)在批内"连续"重复 ≥3 次且这一段里没有任何 verify。刻意收窄到滚动族:
|
|
106
|
+
// 连点/重试同一条 invoke 是正常工作(确认对话框、双击),不拦;要求"连续"是因为
|
|
107
|
+
// 滚动-点击-滚动-点击是轮询式操作,不是卡死的滚动;重复段里出现任一 verify 就整段放行,
|
|
108
|
+
// 因为 verify 未命中会硬停批次(verify_failed → break),循环已被结果校验兜住。
|
|
109
|
+
const SCROLL_ACTIONS = new Set(['scroll_up', 'scroll_down', 'pointer_scroll']);
|
|
110
|
+
const LOOP_REPEATS = 3;
|
|
111
|
+
|
|
112
|
+
function loopKey(step) {
|
|
113
|
+
return `${String(step?.action ?? '').toLowerCase()}|${JSON.stringify(step?.ref ?? step?.by ?? null)}|${String(step?.value ?? '')}`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 防循环护栏:批内同一滚动步连续重复 ≥3 次且重复段内没有任何 verify 时,在第 3 次出现处拒绝。
|
|
118
|
+
* @param {Array<{action?: string, ref?: string, by?: object, value?: unknown, verify?: object}>} steps
|
|
119
|
+
* @returns {{verdict: 'deny', category: 'loop', refusal: string, advice: string, index: number} | null}
|
|
120
|
+
*/
|
|
121
|
+
function classifyLoop(steps) {
|
|
122
|
+
const list = Array.isArray(steps) ? steps : [];
|
|
123
|
+
let prevKey = null;
|
|
124
|
+
let run = 0;
|
|
125
|
+
let runHasVerify = false;
|
|
126
|
+
for (let i = 0; i < list.length; i++) {
|
|
127
|
+
const step = list[i] ?? {};
|
|
128
|
+
if (!SCROLL_ACTIONS.has(String(step.action ?? '').toLowerCase())) {
|
|
129
|
+
prevKey = null;
|
|
130
|
+
run = 0;
|
|
131
|
+
runHasVerify = false;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
const key = loopKey(step);
|
|
135
|
+
if (key === prevKey) {
|
|
136
|
+
run += 1;
|
|
137
|
+
if (step?.verify != null) runHasVerify = true;
|
|
138
|
+
} else {
|
|
139
|
+
prevKey = key;
|
|
140
|
+
run = 1;
|
|
141
|
+
runHasVerify = step?.verify != null;
|
|
142
|
+
}
|
|
143
|
+
if (run >= LOOP_REPEATS && !runHasVerify) return { ...denied('loop'), index: i };
|
|
144
|
+
}
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Batch pre-check shared by computer_run and computer_replay: the one "check every step,
|
|
150
|
+
* stop at the first deny" loop. The loop guard runs first (it is a shape check on the steps
|
|
151
|
+
* themselves, before any descriptor exists), then per-step policy. Callers keep their own
|
|
152
|
+
* refusal wording and store.step bookkeeping; this returns the first deny tagged with its
|
|
153
|
+
* index, or null when every step is allowed. Action normalisation happens inside classify(),
|
|
154
|
+
* so raw step values go in as-is.
|
|
155
|
+
* @param {Array<{action?: string}>} steps
|
|
156
|
+
* @param {Array<object|undefined>} descriptors - UIA descriptors resolved by prepare_batch, aligned with steps
|
|
157
|
+
* @returns {{verdict: 'deny', category: string, refusal: string, advice: string, index: number} | null}
|
|
158
|
+
*/
|
|
159
|
+
export function classifyBatch(steps, descriptors) {
|
|
160
|
+
const list = Array.isArray(steps) ? steps : [];
|
|
161
|
+
const loop = classifyLoop(list);
|
|
162
|
+
if (loop !== null) return loop;
|
|
163
|
+
for (let i = 0; i < list.length; i++) {
|
|
164
|
+
const outcome = classify({ action: list[i]?.action, descriptor: descriptors?.[i] });
|
|
165
|
+
if (outcome.verdict === 'deny') return { ...outcome, index: i };
|
|
166
|
+
}
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Closing an application window is the same category as quitting it. */
|
|
171
|
+
export function classifyClose(descriptor) {
|
|
172
|
+
const category = descriptor?.ownedByPlugin === true ? null : 'exit';
|
|
173
|
+
if (category === null) return { verdict: 'allow' };
|
|
174
|
+
return { verdict: 'deny', category, refusal: CATEGORIES[category].refusal, advice: CATEGORIES[category].advice };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function classifyLaunch(app) {
|
|
178
|
+
const leaf = String(app ?? '').trim().split(/[\\/]/).pop() ?? '';
|
|
179
|
+
if (DENY_EXECUTABLES.test(leaf)) {
|
|
180
|
+
return { verdict: 'deny', category: 'shutdown', refusal: CATEGORIES.shutdown.refusal, advice: CATEGORIES.shutdown.advice };
|
|
181
|
+
}
|
|
182
|
+
return { verdict: 'allow' };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export const POLICY = {
|
|
186
|
+
mode: 'dev',
|
|
187
|
+
deniedCategories: ['shutdown', 'logoff', 'restart', 'exit', 'delete'],
|
|
188
|
+
// Every refusal is final: nothing here can be turned into a button, and there is no interactive
|
|
189
|
+
// verdict at all. The former "hold for a person at the keyboard" family is gone -- it drew a
|
|
190
|
+
// permission prompt on the capsule, which is not a channel this plugin owns.
|
|
191
|
+
approvable: false,
|
|
192
|
+
// The note names the CURRENT mode, so it is written from the activation env — the same switch
|
|
193
|
+
// the store sets and the worker choke point enforces. A static string would go stale the moment
|
|
194
|
+
// read-only mode is on. Read-only layers on top: the hard-refuse categories and the
|
|
195
|
+
// non-approvable rule are unchanged, delivery is additionally refused wholesale.
|
|
196
|
+
note: process.env.DSH_NATIVE_UIA_READ_ONLY === '1'
|
|
197
|
+
? '只读观察模式(DSH_NATIVE_UIA_READ_ONLY=1):快照/find_text/parse/ocr 等观察照常,投递类动作在咽喉点一律拒绝(read_only_mode)。下列硬拒分类照旧,仍不可批准。'
|
|
198
|
+
: '硬拒不可批准:用户选择拦住的这几类,对任何调用方都拦住,配方回放也一样。策略只有放行与硬拒两种结论,没有需要人工按键的中间态。',
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
export { RISKY_ACTIONS };
|