dsh-native-uia 0.2.0 → 0.6.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 (55) hide show
  1. package/README.md +81 -398
  2. package/client/client.js +236 -48
  3. package/cordis.patch.yml +7 -8
  4. package/locale/en.json +2 -2
  5. package/locale/zh.json +2 -2
  6. package/package.json +8 -17
  7. package/scripts/check-lease.mjs +1 -1
  8. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  9. package/scripts/lib/load-tools-source.mjs +17 -16
  10. package/scripts/lib/sources.mjs +62 -0
  11. package/scripts/load-tools.mjs +74 -0
  12. package/scripts/measure-parse.mjs +2 -2
  13. package/scripts/regression-tools.mjs +155 -6
  14. package/scripts/regression-worker.ps1 +29 -0
  15. package/scripts/verify-live-style.mjs +46 -0
  16. package/scripts/verify-live.mjs +12 -18
  17. package/scripts/verify.mjs +953 -192
  18. package/src/activity-window.js +71 -7
  19. package/src/dashboard.js +27 -69
  20. package/src/guard.js +39 -10
  21. package/src/index.js +187 -77
  22. package/src/notes.js +83 -0
  23. package/src/state.js +97 -10
  24. package/src/themes.js +66 -0
  25. package/src/tools/defs/act.js +671 -0
  26. package/src/tools/defs/lifecycle.js +205 -0
  27. package/src/tools/defs/observe.js +325 -0
  28. package/src/tools/defs/pointer.js +328 -0
  29. package/src/tools/format.js +338 -0
  30. package/src/tools/index.js +125 -0
  31. package/src/tools/ocr.js +91 -0
  32. package/src/tools/recipes.js +49 -0
  33. package/src/tools/runtime.js +42 -0
  34. package/src/worker-client.js +32 -10
  35. package/worker/assets/dsh-whale.path +1 -0
  36. package/worker/indicator-server.ps1 +1107 -72
  37. package/worker/lib/01-core.ps1 +64 -0
  38. package/worker/lib/02-uia.ps1 +224 -0
  39. package/worker/lib/03-window.ps1 +194 -0
  40. package/worker/lib/04-match.ps1 +435 -0
  41. package/worker/lib/05-value.ps1 +254 -0
  42. package/worker/lib/06-snapshot.ps1 +412 -0
  43. package/worker/lib/07-action.ps1 +329 -0
  44. package/worker/lib/08-command.ps1 +1495 -0
  45. package/worker/lib/09-pointer.ps1 +840 -0
  46. package/worker/lib/10-dispatch.ps1 +132 -0
  47. package/worker/ps-stdio.ps1 +7 -2
  48. package/worker/uia-worker.ps1 +599 -4220
  49. package/locale/desktop/en.json +0 -6
  50. package/locale/desktop/zh.json +0 -6
  51. package/scripts/regression-halt-latch.mjs +0 -100
  52. package/src/native-uia-remote.js +0 -80
  53. package/src/panel-face.js +0 -14
  54. package/src/tools.js +0 -1482
  55. package/web/control.html +0 -1413
@@ -16,11 +16,11 @@
16
16
  * icon belongs to the Plugin page, the glow belongs to the user's screen.
17
17
  */
18
18
  export const PALETTE = {
19
- ringFrom: '#D9CCF7',
20
- ringTo: '#C0A8EE',
21
- pillBg: '#241B3A',
22
- pillBorder: '#CDBCF3',
23
- pillText: '#E7DEFF',
19
+ ringFrom: '#2A2E34',
20
+ ringTo: '#000000',
21
+ pillBg: '#0B0D10',
22
+ pillBorder: '#A9B4C4',
23
+ pillText: '#F2F5FA',
24
24
  };
25
25
 
26
26
  /**
@@ -43,11 +43,16 @@ export function composeSubtext(store) {
43
43
  }
44
44
 
45
45
  export class ActivityWindow {
46
- constructor({ indicator, resolveBounds, resolveLabel, resolveMode, logger, onState, canEnd, leaseMs = 300000, beatMs = 30000 }) {
46
+ constructor({ indicator, resolveBounds, resolveLabel, resolveMode, resolvePalette, resolveStyle, resolveMist, logger, onState, canEnd, leaseMs = 300000, beatMs = 30000 }) {
47
47
  this.indicator = indicator;
48
48
  this.resolveBounds = resolveBounds;
49
49
  this.resolveLabel = resolveLabel;
50
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;
51
56
  this.logger = logger ?? (() => {});
52
57
  this.onState = onState ?? (() => {});
53
58
  // While one tool command is in flight (busy), lease expiry defers instead of dropping the
@@ -197,9 +202,68 @@ export class ActivityWindow {
197
202
  this.heartbeat = null;
198
203
  }
199
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
+
200
254
  async #send(cmd, args, { swallow = true } = {}) {
201
255
  if (this.indicator === null || this.indicator === undefined) return false;
202
- const payload = (cmd === 'show' || cmd === 'phase' || cmd === 'beat') ? { ...args, palette: PALETTE } : args;
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;
203
267
  try {
204
268
  await this.indicator.call(cmd, payload, { timeoutMs: 4000 });
205
269
  return true;
package/src/dashboard.js CHANGED
@@ -1,37 +1,45 @@
1
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
2
 
7
- const CONTROL_HTML = fileURLToPath(new URL('../web/control.html', import.meta.url));
8
3
  /** Cross-origin pages cannot set this header without a preflight the browser will not skip. */
9
4
  const API_HEADER = 'x-dsh-cua';
10
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
+
11
17
  function json(res, code, body) {
12
18
  const text = JSON.stringify(body);
13
19
  res.writeHead(code, {
14
20
  'content-type': 'application/json; charset=utf-8',
15
21
  'content-length': Buffer.byteLength(text),
16
22
  'cache-control': 'no-store',
23
+ ...CORS,
17
24
  });
18
25
  res.end(text);
19
26
  }
20
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
+ */
21
33
  export class Dashboard {
22
- clients = new Set();
23
-
24
- constructor({ host, port, store, policy, commands, dataDir }) {
34
+ constructor({ host, port, store, policy, commands, config }) {
25
35
  this.host = host;
26
36
  this.port = port;
27
37
  this.store = store;
28
38
  this.policy = policy;
29
39
  this.commands = commands;
30
- this.dataDir = resolve(dataDir);
40
+ /** Facts the plugin page reports but cannot change there (bind, read-only, timeouts). */
41
+ this.config = config;
31
42
  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
43
  }
36
44
 
37
45
  listen() {
@@ -40,27 +48,12 @@ export class Dashboard {
40
48
  this.server.once('error', onError);
41
49
  this.server.listen(this.port, this.host, () => {
42
50
  this.server.removeListener('error', onError);
43
- this.url = `http://${this.host}:${this.port}/control.html`;
51
+ this.url = `http://${this.host}:${this.port}`;
44
52
  promiseResolve(this.url);
45
53
  });
46
54
  });
47
55
  }
48
56
 
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
57
  async #readBody(req) {
65
58
  const chunks = [];
66
59
  let size = 0;
@@ -75,53 +68,20 @@ export class Dashboard {
75
68
  async #handle(req, res) {
76
69
  const url = new URL(req.url ?? '/', `http://${this.host}`);
77
70
  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);
71
+ if (req.method === 'OPTIONS') {
72
+ res.writeHead(204, CORS);
73
+ res.end();
86
74
  return;
87
75
  }
88
76
  if (url.pathname === '/api/state') {
89
77
  json(res, 200, this.store.snapshot(this.policy));
90
78
  return;
91
79
  }
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);
80
+ if (url.pathname === '/api/summary') {
81
+ json(res, 200, { ...this.store.summary(), config: this.config?.() ?? null });
122
82
  return;
123
83
  }
124
- if (url.pathname === '/api/action') {
84
+ if (url.pathname === '/api/action' && req.method === 'POST') {
125
85
  if (req.headers[API_HEADER] !== '1') {
126
86
  json(res, 403, { ok: false, error: `missing required ${API_HEADER}: 1 header` });
127
87
  return;
@@ -138,8 +98,6 @@ export class Dashboard {
138
98
  }
139
99
 
140
100
  close() {
141
- for (const res of this.clients) res.end();
142
- this.clients.clear();
143
101
  this.server.close();
144
102
  }
145
103
  }
package/src/guard.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * `commit_batch`, so one guard covers interactive calls and replayed recipes.
5
5
  */
6
6
 
7
- const RISKY_ACTIONS = new Set(['invoke', 'toggle', 'select', 'close_window']);
7
+ const RISKY_ACTIONS = new Set(['invoke', 'toggle', 'select']);
8
8
 
9
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
10
  // A window's close affordance is called 关闭 / Close / ✕ in real UIA trees, not "关闭程序". Without
@@ -15,7 +15,16 @@ const SHUTDOWN = /(?:\b(?:shut\s*down|shutdown|power\s*off|restart|reboot|sign\s
15
15
  const EXIT = /(?:^(?:exit|quit|close\s*(?:app|application|program))\b|^(?:close|关闭|✕|✖|×)$|退出(?:程序|应用)|关闭(?:程序|应用|窗口))/i;
16
16
  const DELETE = /(?:\b(?:delete|remove|discard|erase|empty\s+recycle\s+bin|shred)\b|删除|彻底删除|清空回收站|丢弃)/i;
17
17
 
18
+ // The interpreter family. Refusing the six shutdown tools by name is worth nothing if `launch` will
19
+ // happily start cmd.exe, because one typed line there runs anything the name table below refuses —
20
+ // including the shutdown the person just denied. These are the shells and script hosts Windows
21
+ // ships, plus the process/task managers that can end an application without going through EXIT.
18
22
  const DENY_EXECUTABLES = /^(?:shutdown|logoff|taskkill|psshutdown|restart|poweroff)\.exe$/i;
23
+ const DENY_SHELLS = new Set([
24
+ 'cmd.exe', 'powershell.exe', 'pwsh.exe', 'wscript.exe', 'cscript.exe', 'mshta.exe',
25
+ 'rundll32.exe', 'regsvr32.exe', 'reg.exe', 'wsl.exe', 'bash.exe', 'wt.exe', 'conhost.exe',
26
+ 'taskmgr.exe', 'msconfig.exe', 'mmc.exe',
27
+ ]);
19
28
 
20
29
  const CATEGORIES = {
21
30
  shutdown: {
@@ -34,6 +43,10 @@ const CATEGORIES = {
34
43
  refusal: '同批内连续重复同一滚动动作且没有任何结果校验(疑似无效滚动循环)',
35
44
  advice: '先重新 snapshot/find_text 观察列表是否真的滚动了;或给滚动步加 verify:{type:"scroll_percent_changed"},滚动无效果时批次会停下来。',
36
45
  },
46
+ shell: {
47
+ refusal: '启动命令行或脚本宿主',
48
+ advice: '这类程序能把上面每一条拒收改写成一行命令,所以整族不开放;需要命令行的步骤请让用户自己开终端执行,应用请用它的正常入口启动。',
49
+ },
37
50
  };
38
51
 
39
52
  function text(descriptor) {
@@ -42,11 +55,10 @@ function text(descriptor) {
42
55
  .join(' ');
43
56
  }
44
57
 
45
- function categoryOf(descriptor, action) {
58
+ function categoryOf(descriptor) {
46
59
  const hay = `${text(descriptor)} ${descriptor?.command ?? ''}`.trim();
47
60
  if (hay === '') return null;
48
61
  if (SHUTDOWN.test(hay)) return 'shutdown';
49
- if (action === 'close_window') return null;
50
62
  if (EXIT.test(hay)) return 'exit';
51
63
  if (DELETE.test(hay)) return 'delete';
52
64
  return null;
@@ -56,6 +68,14 @@ function denied(category) {
56
68
  return { verdict: 'deny', category, refusal: CATEGORIES[category].refusal, advice: CATEGORIES[category].advice };
57
69
  }
58
70
 
71
+ /**
72
+ * A category is always a hard refusal: the policy has no interactive verdict left.
73
+ * @param {string} category - key of CATEGORIES
74
+ */
75
+ function verdictFor(category) {
76
+ return denied(category);
77
+ }
78
+
59
79
  // A raw hotkey has no element descriptor to feed the name table, so the two combos that end an
60
80
  // app or lock the session are matched on the combo text itself. Everything else falls through to
61
81
  // the same categoryOf hay pipeline (SHUTDOWN/EXIT/DELETE never match an ordinary combo like
@@ -73,7 +93,7 @@ export function classifyKeys(combo) {
73
93
  if (hay === '') return { verdict: 'allow' };
74
94
  if (KEY_LOCK.test(hay)) return denied('shutdown'); // win+l locks the session
75
95
  if (KEY_EXIT.test(hay)) return denied('exit'); // alt+f4 closes the focused app
76
- const category = categoryOf({ name: hay, command: hay }, 'invoke');
96
+ const category = categoryOf({ name: hay, command: hay });
77
97
  if (category === null) return { verdict: 'allow' };
78
98
  return denied(category);
79
99
  }
@@ -88,10 +108,9 @@ export function classify(request) {
88
108
  // one policy gate must normalise before matching or a case variant sails past the text refusal.
89
109
  const action = String(request.action ?? '').toLowerCase();
90
110
  if (!RISKY_ACTIONS.has(action)) return { verdict: 'allow' };
91
- const category = categoryOf(request.descriptor, action);
111
+ const category = categoryOf(request.descriptor);
92
112
  if (category === null) return { verdict: 'allow' };
93
- const meta = CATEGORIES[category];
94
- return { verdict: 'deny', category, refusal: meta.refusal, advice: meta.advice };
113
+ return verdictFor(category);
95
114
  }
96
115
 
97
116
  // AndroidWorld 的「动作缓存不记结果导致无限滚动」在御屏的对应形态:同一滚动步(键 =
@@ -170,14 +189,24 @@ export function classifyClose(descriptor) {
170
189
  export function classifyLaunch(app) {
171
190
  const leaf = String(app ?? '').trim().split(/[\\/]/).pop() ?? '';
172
191
  if (DENY_EXECUTABLES.test(leaf)) {
173
- return { verdict: 'deny', category: 'shutdown', refusal: CATEGORIES.shutdown.refusal, advice: CATEGORIES.shutdown.advice };
192
+ return denied('shutdown');
193
+ }
194
+ // Case-insensitive because Windows is: `CMD.EXE` is the same program.
195
+ if (DENY_SHELLS.has(leaf.toLowerCase())) {
196
+ return denied('shell');
174
197
  }
175
198
  return { verdict: 'allow' };
176
199
  }
177
200
 
178
201
  export const POLICY = {
179
202
  mode: 'dev',
180
- deniedCategories: ['shutdown', 'logoff', 'restart', 'exit', 'delete'],
203
+ // Every key that can appear in a verdict, and nothing else: this list is read by the panel and by
204
+ // the model-facing note, so a name here that no CATEGORIES entry defines is a claim about a rule
205
+ // that does not exist.
206
+ deniedCategories: ['shutdown', 'exit', 'delete', 'loop', 'shell'],
207
+ // Every refusal is final: nothing here can be turned into a button, and there is no interactive
208
+ // verdict at all. The former "hold for a person at the keyboard" family is gone -- it drew a
209
+ // permission prompt on the capsule, which is not a channel this plugin owns.
181
210
  approvable: false,
182
211
  // The note names the CURRENT mode, so it is written from the activation env — the same switch
183
212
  // the store sets and the worker choke point enforces. A static string would go stale the moment
@@ -185,7 +214,7 @@ export const POLICY = {
185
214
  // non-approvable rule are unchanged, delivery is additionally refused wholesale.
186
215
  note: process.env.DSH_NATIVE_UIA_READ_ONLY === '1'
187
216
  ? '只读观察模式(DSH_NATIVE_UIA_READ_ONLY=1):快照/find_text/parse/ocr 等观察照常,投递类动作在咽喉点一律拒绝(read_only_mode)。下列硬拒分类照旧,仍不可批准。'
188
- : '硬拒不可批准:用户选择拦住的这几类,对任何调用方都拦住,配方回放也一样。',
217
+ : '硬拒不可批准:用户选择拦住的这几类,对任何调用方都拦住,配方回放也一样。策略只有放行与硬拒两种结论,没有需要人工按键的中间态。',
189
218
  };
190
219
 
191
220
  export { RISKY_ACTIONS };