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.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +663 -2
  3. package/client/client.js +269 -0
  4. package/cordis.patch.yml +10 -0
  5. package/icon.svg +11 -0
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/package.json +75 -4
  9. package/scripts/bench-live.mjs +157 -0
  10. package/scripts/check-lease.mjs +308 -0
  11. package/scripts/install.mjs +154 -0
  12. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  13. package/scripts/lib/load-tools-source.mjs +25 -0
  14. package/scripts/lib/sources.mjs +62 -0
  15. package/scripts/load-tools.mjs +74 -0
  16. package/scripts/measure-parse.mjs +77 -0
  17. package/scripts/regression-halt-latch.mjs +100 -0
  18. package/scripts/regression-quality.mjs +207 -0
  19. package/scripts/regression-tools.mjs +192 -0
  20. package/scripts/regression-worker.ps1 +1071 -0
  21. package/scripts/smoke.mjs +158 -0
  22. package/scripts/verify-capture-scale.mjs +37 -0
  23. package/scripts/verify-live-clipboard.mjs +108 -0
  24. package/scripts/verify-live-style.mjs +46 -0
  25. package/scripts/verify-live.mjs +104 -0
  26. package/scripts/verify-locator.mjs +52 -0
  27. package/scripts/verify.mjs +2110 -0
  28. package/src/activity-window.js +276 -0
  29. package/src/dashboard.js +103 -0
  30. package/src/guard.js +201 -0
  31. package/src/index.js +525 -0
  32. package/src/native-uia-remote.js +80 -0
  33. package/src/notes.js +83 -0
  34. package/src/state.js +267 -0
  35. package/src/themes.js +74 -0
  36. package/src/tools/defs/act.js +533 -0
  37. package/src/tools/defs/lifecycle.js +205 -0
  38. package/src/tools/defs/observe.js +309 -0
  39. package/src/tools/defs/pointer.js +298 -0
  40. package/src/tools/format.js +301 -0
  41. package/src/tools/index.js +128 -0
  42. package/src/tools/ocr.js +91 -0
  43. package/src/tools/recipes.js +44 -0
  44. package/src/tools/runtime.js +42 -0
  45. package/src/worker-client.js +268 -0
  46. package/worker/assets/dsh-whale.path +1 -0
  47. package/worker/bin/build-ocr.ps1 +41 -0
  48. package/worker/bin/ocr.cs +69 -0
  49. package/worker/bin/ocr.exe +0 -0
  50. package/worker/indicator-server.ps1 +2963 -0
  51. package/worker/lib/01-core.ps1 +64 -0
  52. package/worker/lib/02-uia.ps1 +221 -0
  53. package/worker/lib/03-window.ps1 +194 -0
  54. package/worker/lib/04-match.ps1 +435 -0
  55. package/worker/lib/05-value.ps1 +149 -0
  56. package/worker/lib/06-snapshot.ps1 +345 -0
  57. package/worker/lib/07-action.ps1 +291 -0
  58. package/worker/lib/08-command.ps1 +1485 -0
  59. package/worker/lib/09-pointer.ps1 +840 -0
  60. package/worker/lib/10-dispatch.ps1 +134 -0
  61. package/worker/ps-stdio.ps1 +173 -0
  62. package/worker/uia-worker.ps1 +599 -0
package/src/notes.js ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Per-application notes: the one thing a stateless model cannot keep between runs. A finished task
3
+ * can leave one short line ("this app's UIA tree is empty, drive it with computer_parse"), and the
4
+ * next run sees it when it meets the same application again.
5
+ *
6
+ * Storage is one JSON file per app under <dataDir>/notes, because a single shared file turns two
7
+ * concurrent runs into a last-writer-wins race. Reads are best-effort: a broken or missing file
8
+ * produces no hint rather than failing an observation.
9
+ */
10
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+
13
+ const MAX_NOTES = 5;
14
+
15
+ /**
16
+ * App names come from the worker (a process name like "mspaint"), but the model may pass anything.
17
+ * Only a conservative charset reaches the filesystem: no separators, no dots, no spaces.
18
+ * @param {string} app
19
+ */
20
+ export function appKey(app) {
21
+ const key = String(app ?? '').trim().toLowerCase().replace(/[^a-z0-9_-]/g, '');
22
+ return key.slice(0, 40);
23
+ }
24
+
25
+ function fileOf(dir, key) {
26
+ return join(dir, 'notes', `${key}.json`);
27
+ }
28
+
29
+ /**
30
+ * @param {string} dir - dataDir
31
+ * @param {string} app - raw app name
32
+ * @param {string} note - one line
33
+ * @returns {{saved: boolean, app: string, count: number, reason?: string}}
34
+ */
35
+ export function saveNote(dir, app, note) {
36
+ const key = appKey(app);
37
+ const text = String(note ?? '').trim().slice(0, 300);
38
+ if (key === '') return { saved: false, app: '', count: 0, reason: 'app 名字不可用' };
39
+ if (text === '') return { saved: false, app: key, count: 0, reason: 'note 是空的' };
40
+ const file = fileOf(dir, key);
41
+ let list = [];
42
+ try {
43
+ const old = JSON.parse(readFileSync(file, 'utf8'));
44
+ if (Array.isArray(old?.notes)) list = old.notes;
45
+ } catch { /* first note for this app */ }
46
+ // Newest first, and the same sentence is not stored twice: a repeated run of the same task must
47
+ // not push the useful older lines out of the cap.
48
+ list = [{ text, at: new Date().toISOString() }, ...list.filter((n) => n?.text !== text)].slice(0, MAX_NOTES);
49
+ try {
50
+ mkdirSync(join(dir, 'notes'), { recursive: true });
51
+ writeFileSync(file, JSON.stringify({ app: key, notes: list }, null, 2));
52
+ return { saved: true, app: key, count: list.length };
53
+ } catch (error) {
54
+ return { saved: false, app: key, count: list.length, reason: String(error?.message ?? error) };
55
+ }
56
+ }
57
+
58
+ /**
59
+ * @param {string} dir - dataDir
60
+ * @param {string} app - raw app name
61
+ * @returns {string[]} newest first, empty when nothing is known
62
+ */
63
+ export function notesFor(dir, app) {
64
+ const key = appKey(app);
65
+ if (key === '') return [];
66
+ try {
67
+ const parsed = JSON.parse(readFileSync(fileOf(dir, key), 'utf8'));
68
+ return Array.isArray(parsed?.notes) ? parsed.notes.map((n) => String(n?.text ?? '')).filter(Boolean) : [];
69
+ } catch {
70
+ return [];
71
+ }
72
+ }
73
+
74
+ /**
75
+ * A one-line hint for an observation, or '' when this app has nothing recorded.
76
+ * @param {string} dir - dataDir
77
+ * @param {string} app
78
+ */
79
+ export function noteHint(dir, app) {
80
+ const list = notesFor(dir, app);
81
+ if (list.length === 0) return '';
82
+ return `\n笔记(${appKey(app)}):${list.map((t) => `「${t}」`).join(' ')}`;
83
+ }
package/src/state.js ADDED
@@ -0,0 +1,267 @@
1
+ import { EventEmitter } from 'node:events';
2
+
3
+ const LIMITS = { steps: 200, log: 300, blocked: 120, windows: 80, tree: 900 };
4
+
5
+ function trim(list, max) {
6
+ while (list.length > max) list.shift();
7
+ }
8
+
9
+ export class Store extends EventEmitter {
10
+ windows = [];
11
+ tree = [];
12
+ steps = [];
13
+ blocked = [];
14
+ log = [];
15
+ target = null;
16
+ killed = false;
17
+ // When the kill latch was armed (ms epoch). index.js uses the age to decide whether a mutating
18
+ // command is the one the person stopped or their next instruction — see HALT_LATCH_MS there.
19
+ killedAt = 0;
20
+ // Read-only observation mode: read once at activation from DSH_NATIVE_UIA_READ_ONLY=1. The
21
+ // desktop worker refuses every ACTION_COMMANDS delivery at the call() choke point (error code
22
+ // read_only_mode); the observation whitelist (snapshot/find_text/parse/ocr) stays available.
23
+ // guard.POLICY.note names the mode from the same env switch.
24
+ readOnly = process.env.DSH_NATIVE_UIA_READ_ONLY === '1';
25
+ pointerMode = 'background';
26
+ // Overlay look: picked on the plugin page, persisted in settings.json, and sent with every
27
+ // indicator command. The catalog lives in themes.js; these are only the selected ids.
28
+ themeId = 'brand';
29
+ styleId = 'orb';
30
+ // The thin smoke at the capsule's inner lip is decoration, not information: it carries no state
31
+ // and the capsule is fully legible without it. So it is the person's choice, persisted like the
32
+ // other look settings. Default on -- it is the intended look, and a default-off decoration is a
33
+ // feature nobody finds.
34
+ mistOn = true;
35
+ // Whether the activation permission request was granted. False = every delivery command is
36
+ // refused at the worker choke point, exactly like read-only mode; observation stays available so
37
+ // the person can see what the plugin WOULD control before deciding. Read at the choke point, not
38
+ // cached in the client, so a future re-ask (panel button) applies to the next call immediately.
39
+ armed = false;
40
+ running = false;
41
+ visionRoute = false;
42
+ counters = { stepsRun: 0, actions: 0, blocked: 0, refused: 0, stepMsTotal: 0, stepSamples: 0 };
43
+ // Mouse buttons currently held down by computer_mouse action:"down". A dangling press is a stuck
44
+ // desktop (every later click becomes a drag), so it is tracked here and released on run end.
45
+ heldButtons = new Set();
46
+ // Repetition watchdog: signature -> {total, misses}. A model that keeps clicking the same point
47
+ // (or re-invoking the same ref after a missed verify) needs to be told to change approach; the
48
+ // alternative is an unbounded loop that looks like progress in the step list.
49
+ attempts = new Map();
50
+ // When the model last pressed ctrl+c (epoch ms, 0 = never). clipboard read is allowed only after
51
+ // this, so a run cannot read whatever the user happened to have copied before it started.
52
+ ctrlCAt = 0;
53
+
54
+ noteAttempt(sig, ok) {
55
+ const key = String(sig);
56
+ const cur = this.attempts.get(key) ?? { total: 0, misses: 0 };
57
+ cur.total += 1;
58
+ cur.misses = ok ? 0 : cur.misses + 1;
59
+ if (this.attempts.size > 80 && !this.attempts.has(key)) this.attempts.clear();
60
+ this.attempts.set(key, cur);
61
+ return cur;
62
+ }
63
+
64
+ clearAttempts() {
65
+ this.attempts.clear();
66
+ }
67
+
68
+ /* Views shared by snapshot() and the state-class SSE frames: a partial frame must carry
69
+ the same mapped shape a full snapshot delivers, or the panel would render two dialects.
70
+ The emits used to carry {reason} only — the live stream kept the panel "fresh"
71
+ (refreshing lastEventAt and suppressing the polling fallback) while delivering nothing
72
+ the page could render, so windows/tree/target/killed/busy/pointerMode froze during live. */
73
+ #targetView() {
74
+ return this.target === null ? null : {
75
+ windowId: this.target.windowId,
76
+ appName: this.target.appName,
77
+ title: this.target.title,
78
+ };
79
+ }
80
+
81
+ #windowsView() {
82
+ return this.windows.map((w) => ({
83
+ windowId: w.windowId,
84
+ appName: w.appName,
85
+ title: w.title,
86
+ pid: w.pid,
87
+ rect: w.rect,
88
+ isForeground: w.isForeground === true,
89
+ }));
90
+ }
91
+
92
+ #treeView() {
93
+ return this.tree.map((n) => ({
94
+ ref: n.ref,
95
+ controlType: n.controlType,
96
+ name: n.name ?? '',
97
+ className: n.className ?? '',
98
+ depth: n.depth ?? 0,
99
+ patterns: n.patterns ?? [],
100
+ enabled: n.enabled !== false,
101
+ isOffscreen: n.isOffscreen === true,
102
+ rect: n.rect ?? null,
103
+ }));
104
+ }
105
+
106
+ setTarget(window) {
107
+ this.target = window ?? null;
108
+ this.emit('state', { reason: 'target', target: this.#targetView() });
109
+ }
110
+
111
+ setWindows(windows) {
112
+ this.windows = windows.slice(0, LIMITS.windows);
113
+ this.emit('state', { reason: 'windows', windows: this.#windowsView() });
114
+ }
115
+
116
+ setTree(nodes, meta) {
117
+ this.tree = nodes.slice(0, LIMITS.tree);
118
+ this.treeMeta = meta ?? null;
119
+ this.emit('state', { reason: 'tree', tree: this.#treeView() });
120
+ }
121
+
122
+ step(step) {
123
+ this.steps.push({ id: `s${this.steps.length + 1}`, at: Date.now(), ...step });
124
+ trim(this.steps, LIMITS.steps);
125
+ this.counters.stepsRun++;
126
+ if (typeof step.ms === 'number') {
127
+ this.counters.stepMsTotal += step.ms;
128
+ this.counters.stepSamples++;
129
+ }
130
+ this.emit('step', this.steps[this.steps.length - 1]);
131
+ return this.steps[this.steps.length - 1];
132
+ }
133
+
134
+ actionDone(n = 1) {
135
+ this.counters.actions += n;
136
+ }
137
+
138
+ holdButton(button) {
139
+ this.heldButtons.add(String(button || 'left'));
140
+ return true;
141
+ }
142
+
143
+ releaseButton(button) {
144
+ return this.heldButtons.delete(String(button || 'left'));
145
+ }
146
+
147
+ block(entry) {
148
+ this.blocked.push({ id: `b${this.blocked.length + 1}`, at: Date.now(), ...entry });
149
+ trim(this.blocked, LIMITS.blocked);
150
+ this.counters.blocked++;
151
+ this.emit('blocked', this.blocked[this.blocked.length - 1]);
152
+ return this.blocked[this.blocked.length - 1];
153
+ }
154
+
155
+ line(text, level = 'info') {
156
+ this.log.push({ at: Date.now(), level, text });
157
+ trim(this.log, LIMITS.log);
158
+ this.emit('log', this.log[this.log.length - 1]);
159
+ }
160
+
161
+ setKilled(value) {
162
+ this.killed = value;
163
+ // Arming records WHEN. The kill latch refuses only the command that was in flight at the
164
+ // stop instant; index.js reads this age to tell "the stopped command" from "the person's next
165
+ // instruction". Without the timestamp every arm looked infinitely old or brand new.
166
+ if (value === true) this.killedAt = Date.now();
167
+ this.emit('state', { reason: 'killed', killed: this.killed });
168
+ }
169
+
170
+ setPointerMode(value) {
171
+ if (value !== 'background' && value !== 'auto' && value !== 'foreground') return false;
172
+ this.pointerMode = value;
173
+ this.emit('state', { reason: 'pointerMode', pointerMode: value });
174
+ return true;
175
+ }
176
+
177
+ setTheme(value) {
178
+ if (typeof value !== 'string' || value === '') return false;
179
+ this.themeId = value;
180
+ this.emit('state', { reason: 'theme', theme: value });
181
+ return true;
182
+ }
183
+
184
+ setStyle(value) {
185
+ if (typeof value !== 'string' || value === '') return false;
186
+ this.styleId = value;
187
+ this.emit('state', { reason: 'style', style: value });
188
+ return true;
189
+ }
190
+
191
+ setMist(value) {
192
+ // Strict on purpose: a settings file holding "false" as a string must not turn the smoke back on.
193
+ if (typeof value !== 'boolean') return false;
194
+ this.mistOn = value;
195
+ this.emit('state', { reason: 'mist', mist: value });
196
+ return true;
197
+ }
198
+
199
+ snapshot(policy) {
200
+ const c = this.counters;
201
+ return {
202
+ session: {
203
+ busy: this.busy === true,
204
+ running: this.running === true,
205
+ killed: this.killed,
206
+ pointerMode: this.pointerMode,
207
+ theme: this.themeId,
208
+ style: this.styleId,
209
+ mist: this.mistOn === true,
210
+ armed: this.armed === true,
211
+ target: this.#targetView(),
212
+ policy,
213
+ remoteChannel: this.remoteChannel ?? 'pending',
214
+ stats: {
215
+ stepsRun: c.stepsRun,
216
+ actions: c.actions,
217
+ blocked: c.blocked,
218
+ refused: c.refused,
219
+ avgStepMs: c.stepSamples > 0 ? Math.round(c.stepMsTotal / c.stepSamples) : 0,
220
+ visionRoute: this.visionRoute,
221
+ },
222
+ },
223
+ windows: this.#windowsView(),
224
+ tree: this.#treeView(),
225
+ steps: this.steps.map((s) => ({
226
+ id: s.id,
227
+ label: s.label,
228
+ kind: s.kind ?? 'action',
229
+ status: s.status,
230
+ ms: s.ms ?? null,
231
+ verify: s.verify ?? null,
232
+ detail: s.detail ?? null,
233
+ })),
234
+ blocked: this.blocked.map((b) => ({
235
+ id: b.id,
236
+ reason: b.reason,
237
+ raw: b.raw ?? null,
238
+ at: new Date(b.at).toISOString().slice(11, 19),
239
+ })),
240
+ log: this.log.map((l) => ({ at: new Date(l.at).toISOString().slice(11, 19), level: l.level, text: l.text })),
241
+ };
242
+ }
243
+
244
+ /**
245
+ * What the plugin-page panel polls: the run's state plus its most recent step and log lines.
246
+ * Deliberately not a slice of snapshot(): the panel does not draw the element tree, and polling
247
+ * a 900-node tree every couple of seconds would be paid for nothing.
248
+ */
249
+ summary() {
250
+ const last = this.steps[this.steps.length - 1] ?? null;
251
+ return {
252
+ running: this.running === true,
253
+ busy: this.busy === true,
254
+ killed: this.killed,
255
+ pointerMode: this.pointerMode,
256
+ theme: this.themeId,
257
+ style: this.styleId,
258
+ mist: this.mistOn === true,
259
+ armed: this.armed === true,
260
+ target: this.#targetView(),
261
+ steps: this.counters.stepsRun,
262
+ blocked: this.counters.blocked,
263
+ lastStep: last === null ? null : { label: last.label ?? '', status: last.status ?? '' },
264
+ log: this.log.slice(-3).map((l) => ({ at: new Date(l.at).toISOString().slice(11, 19), level: l.level, text: l.text })),
265
+ };
266
+ }
267
+ }
package/src/themes.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The overlay's public theming surface: two ambient palettes and four capsule shapes.
3
+ *
4
+ * Colour lives here, not in the renderer and not in the panel: the panel draws names and swatches
5
+ * from this list, the activity window sends the chosen palette with every overlay command, and the
6
+ * indicator worker only consumes what it is handed.
7
+ *
8
+ * The shape is a separate axis and is chosen from STYLES; a theme changes the AMBIENT only, so the
9
+ * capsule shell keeps the same black body and silver hairline in both themes, because the shell
10
+ * colour is not up for change yet.
11
+ */
12
+
13
+ /**
14
+ * Two palettes. `ring*` paints the screen-edge glow; `pill*` stays identical in both.
15
+ *
16
+ * `brand` is the brand black: a near-black ramp, which is what the name means and what the shell
17
+ * already is. It is deliberately dark -- the ambient is a dark rim that reads as a vignette on a
18
+ * light wallpaper, not as a bright line. `graphite` is the silver one, and the two are chosen for
19
+ * different walls.
20
+ *
21
+ * The bug that made "switching does nothing" was NOT these numbers: the renderer built its ring
22
+ * from `pillBorder` (identical in both palettes) instead of from `ringFrom`/`ringTo`, so no value
23
+ * here could ever reach the screen. That is fixed in Build-Ring; these are the values it now uses.
24
+ */
25
+ export const THEMES = Object.freeze([
26
+ Object.freeze({ id: 'brand', name: '品牌黑', ringFrom: '#2A2E34', ringTo: '#000000', pillBg: '#0B0D10', pillBorder: '#A9B4C4', pillText: '#F2F5FA' }),
27
+ // Cool blue-silver: the bright one, for a dark desktop where a dark rim would vanish.
28
+ Object.freeze({ id: 'graphite', name: '石墨银', ringFrom: '#E6EBF2', ringTo: '#8593AA', pillBg: '#0B0D10', pillBorder: '#A9B4C4', pillText: '#F2F5FA' }),
29
+ ]);
30
+
31
+ /**
32
+ * The capsule shapes the worker can actually build.
33
+ *
34
+ * This list is the panel's catalog, so it has to match `Build-Pill` in the worker exactly: an id
35
+ * the worker cannot build is a switch that silently does nothing, and an id missing here is a shape
36
+ * the person cannot reach at all -- which is what happened when only `orb` was listed while the
37
+ * renderer already had four.
38
+ *
39
+ * `compact` says which heights the worker gives it (44 DIP single line, 56 DIP with the second
40
+ * line), so the panel does not have to describe sizes in prose.
41
+ */
42
+ export const STYLES = Object.freeze([
43
+ // `orb` is the historical id; the mark has been the DSH whale for a long time, and "光球" (the
44
+ // glass bead it started as) described something that is no longer drawn. The name the person
45
+ // reads is the whale, so the label says so. The id stays: it is persisted in settings.json and
46
+ // pinned by the gates.
47
+ Object.freeze({ id: 'orb', name: '深黑', compact: true, hint: '深黑壳,白鲸直接画在壳上' }),
48
+ Object.freeze({ id: 'wave', name: '声波', compact: true, hint: '三根声波条' }),
49
+ Object.freeze({ id: 'mark', name: '标块', compact: true, hint: '浅色圆角块 + 深鲸' }),
50
+ Object.freeze({ id: 'inverse', name: '反白', compact: true, hint: '白壳黑字,浅色壁纸' }),
51
+ ]);
52
+
53
+ export const DEFAULT_THEME = 'brand';
54
+ export const DEFAULT_STYLE = 'orb';
55
+
56
+ export function themeOf(id) {
57
+ return THEMES.find((t) => t.id === id) ?? THEMES[0];
58
+ }
59
+
60
+ export function styleOf(id) {
61
+ return STYLES.find((s) => s.id === id) ?? STYLES[0];
62
+ }
63
+
64
+ /** The exact five colours the indicator's Apply-Palette understands. */
65
+ export function paletteOf(id) {
66
+ const t = themeOf(id);
67
+ return {
68
+ ringFrom: t.ringFrom,
69
+ ringTo: t.ringTo,
70
+ pillBg: t.pillBg,
71
+ pillBorder: t.pillBorder,
72
+ pillText: t.pillText,
73
+ };
74
+ }