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
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Focused check of the overlay lease fix (no real indicator, no desktop):
3
+ *
4
+ * 1. a run that only observes keeps its lease — the bug was that the lease renewed only on the
5
+ * next *mutating* action, so a long think gap dropped the capsule mid-run;
6
+ * 2. the heartbeat beats on its own while a run is active;
7
+ * 3. observation before any action never claims (a read-only session must not light the screen);
8
+ * 4. end() stops the lease and the heartbeat.
9
+ *
10
+ * Run: node scripts/check-lease.mjs
11
+ */
12
+ import assert from 'node:assert';
13
+ import { ActivityWindow } from '../src/activity-window.js';
14
+
15
+ function fakeIndicator() {
16
+ const calls = [];
17
+ return {
18
+ calls,
19
+ async call(cmd, args) {
20
+ calls.push({ cmd, args });
21
+ return { ok: true };
22
+ },
23
+ };
24
+ }
25
+
26
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27
+
28
+ // --- 1 + 2: observation-only run survives a gap far longer than the old 90 s lease -------------
29
+ {
30
+ const indicator = fakeIndicator();
31
+ // Tiny timings so the test runs in milliseconds: lease 300 ms, beat 60 ms — the same ratios as
32
+ // production (300 s / 30 s) with the same code path.
33
+ const activity = new ActivityWindow({ indicator, leaseMs: 300, beatMs: 60 });
34
+ activity.claim();
35
+ assert.equal(activity.active, true, 'claim did not activate the window');
36
+ assert.equal(indicator.calls[0].cmd, 'show', 'claim did not show the overlay');
37
+
38
+ // Observed steps only (what computer_snapshot / computer_windows do inside a run).
39
+ for (let i = 0; i < 8; i++) {
40
+ await sleep(50);
41
+ activity.observe(); // renews the lease...
42
+ }
43
+ await sleep(120); // ...and the heartbeat covers the gaps between them
44
+
45
+ assert.equal(activity.active, true, 'a long observation-only stretch dropped the run (the bug)');
46
+ const beats = indicator.calls.filter((c) => c.cmd === 'beat').length;
47
+ assert(beats >= 3, `heartbeat did not fire: only ${beats} beat(s)`);
48
+ assert(!indicator.calls.some((c) => c.cmd === 'phase' && c.args.phase === 'stopped'), 'the run was收尾 while it was still observing');
49
+
50
+ await activity.end({ reason: 'test' });
51
+ const stopped = indicator.calls.find((c) => c.cmd === 'phase' && c.args.phase === 'stopped');
52
+ assert(stopped !== undefined, 'end() did not send the stopped phase');
53
+ const after = indicator.calls.length;
54
+ await sleep(150);
55
+ assert.equal(indicator.calls.length, after, 'end() left a timer running (heartbeat or lease)');
56
+ console.log('✅ 观察期不再掉租约:心跳持续、end() 收尾后无残留定时器');
57
+ }
58
+
59
+ // --- 3: pure observation must not light the overlay -------------------------------------------
60
+ {
61
+ const indicator = fakeIndicator();
62
+ const activity = new ActivityWindow({ indicator, leaseMs: 200, beatMs: 50 });
63
+ activity.observe();
64
+ activity.observe();
65
+ await sleep(80);
66
+ assert.equal(activity.active, false, 'observe() claimed a run that never acted');
67
+ assert.equal(indicator.calls.length, 0, 'observe() talked to the overlay before any action');
68
+ console.log('✅ 只读会话不点亮指示层(observe 前无 action 时静默)');
69
+ }
70
+
71
+ // --- 4: an unclaimed end() is a no-op (never sends a stray phase) ------------------------------
72
+ {
73
+ const indicator = fakeIndicator();
74
+ const activity = new ActivityWindow({ indicator, leaseMs: 200, beatMs: 50 });
75
+ await activity.end({ reason: 'nothing was running' });
76
+ assert.equal(indicator.calls.length, 0, 'end() on an inactive window still sent a command');
77
+ console.log('✅ 未激活时 end() 不发命令');
78
+ }
79
+
80
+ // --- 5: kill stops the run, and the next action restarts the same capsule -----------------------
81
+ {
82
+ const indicator = fakeIndicator();
83
+ const activity = new ActivityWindow({ indicator, leaseMs: 300, beatMs: 60 });
84
+ activity.claim();
85
+ await activity.end({ reason: 'kill' }); // control-page 终止
86
+ assert.equal(activity.active, false, 'end() left the window active');
87
+ assert.equal(activity.phase, 'stopped', 'the window does not report stopped after a kill');
88
+ const stopped = indicator.calls.find((c) => c.cmd === 'phase' && c.args.phase === 'stopped');
89
+ assert(stopped !== undefined, 'end() did not paint the stopped phase');
90
+ assert(indicator.calls.filter((c) => c.cmd === 'phase').length === 1, 'a stop painted more than the one phase it should');
91
+
92
+ activity.claim(); // the documented restart path
93
+ assert.equal(activity.active, true, 'the next action did not restart the capsule');
94
+ assert.equal(activity.phase, 'acting', 'the window does not report acting after the restart');
95
+ // `end()` left the window inactive, so the restart goes through `show` (which carries
96
+ // phase:'acting'), not through a second `phase` command. Either way the pill must come
97
+ // back as acting with a fresh label, never sit on the stale "stopped" wording.
98
+ const phases = indicator.calls
99
+ .filter((c) => c.cmd === 'phase')
100
+ .map((c) => c.args.phase);
101
+ assert.deepEqual(phases, ['stopped'], `the stop painted ${JSON.stringify(phases)}`);
102
+ const showsAfter = indicator.calls.slice(indicator.calls.indexOf(stopped) + 1).filter((c) => c.cmd === 'show');
103
+ assert.equal(showsAfter.length, 1, `expected one show for the restart, got ${showsAfter.length}`);
104
+ assert.equal(showsAfter[0].args.phase, 'acting', 'the restart did not come back as acting');
105
+ assert(typeof showsAfter[0].args.subtext === 'string', 'the restart did not carry the subtext, so the second line went stale');
106
+ assert(showsAfter[0].args.idleHideMs !== undefined, 'the restart did not re-arm the idle watchdog');
107
+ console.log('✅ 终止→「御屏 · 已停止」→ 下一次动作重新点亮胶囊(show + acting + 新 subtext)');
108
+ }
109
+
110
+ // --- 6: no third state exists (the paused state was removed from the product) ---------------------
111
+ {
112
+ const indicator = fakeIndicator();
113
+ const activity = new ActivityWindow({ indicator, leaseMs: 200, beatMs: 50 });
114
+ assert.equal(typeof activity.waiting, 'undefined', 'waiting() is back: a state no switch can reach is dead code');
115
+ assert.equal(typeof activity.resume, 'undefined', 'resume() is back: nothing can resume a run that cannot pause');
116
+ activity.claim();
117
+ activity.claim(); // two claims in a row must stay in acting
118
+ const phases = indicator.calls.filter((c) => c.cmd === 'phase').map((c) => c.args.phase);
119
+ assert.deepEqual(phases, [], `a claim produced a phase change: ${JSON.stringify(phases)}`);
120
+
121
+ // The one remaining `phase: 'acting'` sender: a claim on a live window that is not acting
122
+ // (defensive — nothing sets that today, but the branch must not go untested and drift).
123
+ const indicator2 = fakeIndicator();
124
+ const activity2 = new ActivityWindow({ indicator: indicator2, leaseMs: 300, beatMs: 60 });
125
+ activity2.claim();
126
+ activity2.phase = 'stopped'; // simulate a stale non-acting phase
127
+ activity2.claim();
128
+ const phases2 = indicator2.calls.filter((c) => c.cmd === 'phase').map((c) => c.args.phase);
129
+ assert.deepEqual(phases2, ['acting'], `the stale phase was not repainted: ${JSON.stringify(phases2)}`);
130
+ const flip = indicator2.calls.find((c) => c.cmd === 'phase');
131
+ assert(typeof flip.args.subtext === 'string' && typeof flip.args.mode === 'string', 'the phase flip did not carry subtext+mode');
132
+ console.log('✅ 只有 acting/stopped 两态;连点动作不产生多余相位切换;陈旧相位会被重绘');
133
+ }
134
+
135
+ // --- 7: an unclaimed claim lights the screen; an unclaimed end() does not -------------------------
136
+ {
137
+ const indicator = fakeIndicator();
138
+ const activity = new ActivityWindow({ indicator, leaseMs: 200, beatMs: 50 });
139
+ await activity.end({ reason: 'nothing was running' });
140
+ assert.equal(activity.active, false, 'end() on an inactive window activated it');
141
+ assert.equal(indicator.calls.length, 0, 'end() on an inactive window still sent a command');
142
+ activity.claim();
143
+ assert.equal(activity.active, true, 'a real claim did not start the overlay');
144
+ assert.equal(indicator.calls[0].cmd, 'show', 'a claim did not show the overlay');
145
+ console.log('✅ 未激活时 end() 静默;真 claim 才点亮(show)');
146
+ }
147
+
148
+ // --- 8: the choke point classifies commands, and internal probes stay silent ---------------------
149
+ // This is the flicker regression: the Esc watchdog polls `escape_pressed` every 40 ms. When the
150
+ // client inferred "observation = not an action", each poll renewed the lease and beat the overlay
151
+ // ~8×/s, which interleaved with the 100 ms pulse and made the ring visibly flicker.
152
+ {
153
+ const { CuaWorker } = await import('../src/worker-client.js');
154
+ const fired = { action: [], observe: [] };
155
+ const worker = new CuaWorker({
156
+ logger: () => {},
157
+ onActionStart: (cmd) => fired.action.push(cmd),
158
+ onObserve: (cmd) => fired.observe.push(cmd),
159
+ });
160
+ // Never spawn PowerShell: the classification runs before the request is written, and the
161
+ // returned promise is deliberately left pending (we only assert which hook fired).
162
+ worker.start = () => {};
163
+ worker.proc = { stdin: { write: () => {} }, exitCode: null, killed: false };
164
+
165
+ const fire = (cmd) => { worker.call(cmd, {}, { timeoutMs: 5 }).catch(() => {}); };
166
+
167
+ for (let i = 0; i < 20; i++) fire('escape_pressed'); // the 40 ms watchdog
168
+ fire('ping');
169
+ fire('set_pointer_mode');
170
+ fire('snapshot');
171
+ fire('list_windows');
172
+ fire('describe');
173
+ fire('capture');
174
+ fire('ocr');
175
+ fire('wait');
176
+ fire('prepare_batch');
177
+ fire('find_text');
178
+ fire('resolve_window');
179
+ fire('pointer_target');
180
+ fire('act');
181
+ fire('pointer_click');
182
+ await sleep(30);
183
+
184
+ assert.deepEqual(fired.observe.filter((c) => c === 'escape_pressed'), [],
185
+ 'escape_pressed renewed the lease: the Esc watchdog would beat the overlay ~8×/s and the ring would flicker');
186
+ // Only the two real input commands fired here may reach the action hook; the probes must not.
187
+ assert.deepEqual([...fired.action].sort(), ['act', 'pointer_click'],
188
+ `the action hook saw ${JSON.stringify(fired.action)}: a probe leaked into it`);
189
+ assert.deepEqual([...fired.observe].sort(), ['capture', 'describe', 'find_text', 'list_windows', 'ocr', 'pointer_target', 'prepare_batch', 'resolve_window', 'snapshot', 'wait'],
190
+ `observation whitelist drifted: ${JSON.stringify(fired.observe)}`);
191
+ console.log('✅ 咽喉点分类正确:内部探针(escape_pressed/ping/set_pointer_mode)静默,10 个观测命令续租');
192
+ }
193
+
194
+ // --- 9: the heartbeat renders, but a SILENT run still goes out (the 用完不停止 regression) -------
195
+ // The immortal-capsule bug: the heartbeat re-armed the lease every 30 s, so a run the model never
196
+ // closed with computer_done beat forever and the overlay never stopped. The lease must expire on
197
+ // real-activity silence alone — while the beat keeps the renderer fed up to that moment.
198
+ {
199
+ const indicator = fakeIndicator();
200
+ const activity = new ActivityWindow({ indicator, leaseMs: 150, beatMs: 40 });
201
+ activity.claim(); // one action starts the run…
202
+ await sleep(520); // …then total silence: >3 lease periods
203
+ assert.equal(activity.active, false, 'a silent run is still alive: the heartbeat renewed the lease again (immortal capsule)');
204
+ const stopped = indicator.calls.find((c) => c.cmd === 'phase' && c.args.phase === 'stopped');
205
+ assert(stopped !== undefined, 'the expired run did not paint 已停止 on the way out');
206
+ const beats = indicator.calls.filter((c) => c.cmd === 'beat').length;
207
+ assert(beats >= 3, `the heartbeat stopped feeding the renderer before expiry: only ${beats} beat(s)`);
208
+ const after = indicator.calls.length;
209
+ await sleep(150);
210
+ assert.equal(indicator.calls.length, after, 'a dead run is still beating');
211
+
212
+ // Expiry must defer, not fire, while one command is genuinely in flight.
213
+ const ind2 = fakeIndicator();
214
+ let busy = true;
215
+ const activity2 = new ActivityWindow({ indicator: ind2, canEnd: () => !busy, leaseMs: 100, beatMs: 40 });
216
+ activity2.claim();
217
+ await sleep(250); // two lease periods… but busy
218
+ assert.equal(activity2.active, true, 'the lease expired mid-action and dropped the capsule during real work');
219
+ busy = false;
220
+ await sleep(250); // …then silence: it must go out
221
+ assert.equal(activity2.active, false, 'after busy cleared, the deferred lease never ended the run');
222
+ console.log('✅ 心跳只喂渲染不续租:静默 run 在租约内必熄灭;动作在飞时过期推迟而非硬收');
223
+ }
224
+
225
+ // --- 10: the subtext carries batch progress (appName · last step label (N steps)) ----------------
226
+ // The pill's second line used to be just the target app name: store.step recorded every step's
227
+ // label and the stepsRun counter, but none of it reached the overlay, so the person watching the
228
+ // screen could not tell how far the batch had gotten. The composition lives in composeSubtext()
229
+ // (activity-window.js, beside the palette — index.js only wires store into it via resolveLabel)
230
+ // and the result must reach the overlay through EVERY send site: claim's show, a claim on a live
231
+ // window (beat), observe's beat, the heartbeat beat, the stale-phase repaint, and the
232
+ // withoutIndicator restore.
233
+ {
234
+ const { composeSubtext } = await import('../src/activity-window.js');
235
+ const { Store } = await import('../src/state.js');
236
+
237
+ const store = new Store();
238
+ assert.equal(composeSubtext(store), '', 'a session with no target must keep the empty subtext');
239
+ store.setTarget({ windowId: 'w1', appName: '记事本', title: 't' });
240
+ assert.equal(composeSubtext(store), '记事本', 'with no steps yet the subtext stays the bare app name');
241
+ store.step({ label: '点击 确定', status: 'passed' });
242
+ store.step({ label: '输入 御屏', status: 'passed' });
243
+ assert.equal(composeSubtext(store), '记事本 · 输入 御屏(2 步)', 'the subtext must name the last step and the step count');
244
+
245
+ // The count is the RUN counter, not steps.length: the store trims steps at 200, so a long run
246
+ // would freeze the display at exactly 200 forever if the length were read instead.
247
+ for (let i = 0; i < 201; i++) store.step({ label: `s${i}`, status: 'passed' });
248
+ assert.equal(store.steps.length, 200, 'the store should have trimmed steps to its cap');
249
+ assert.equal(composeSubtext(store), '记事本 · s200(203 步)', 'the count must come from counters.stepsRun, not the trimmed steps.length');
250
+
251
+ // Real chain end to end: real Store → real composeSubtext → ActivityWindow's subtext at all
252
+ // six send sites. Timings: lease 600 ms keeps expiry out of the way, beat 40 ms fires one
253
+ // heartbeat inside the 50 ms pause below.
254
+ const composed = composeSubtext(store);
255
+ const indicator = fakeIndicator();
256
+ const activity = new ActivityWindow({ indicator, leaseMs: 600, beatMs: 40, resolveLabel: () => composeSubtext(store) });
257
+ activity.claim(); // show
258
+ activity.claim(); // beat (claim on a live acting window)
259
+ activity.observe(); // beat (observation renew)
260
+ await sleep(50); // beat (heartbeat)
261
+ activity.phase = 'stopped';
262
+ activity.claim(); // phase acting (stale-phase repaint)
263
+ await activity.withoutIndicator(async () => {}); // phase hidden + acting (restore branch)
264
+ const sent = indicator.calls.filter((c) => c.cmd === 'show' || c.cmd === 'beat' || (c.cmd === 'phase' && c.args.phase === 'acting'));
265
+ const kinds = { show: 0, beat: 0, acting: 0 };
266
+ for (const c of sent) {
267
+ kinds[c.cmd === 'show' ? 'show' : c.cmd === 'beat' ? 'beat' : 'acting']++;
268
+ assert.equal(c.args.subtext, composed, `${c.cmd} did not carry the progress subtext`);
269
+ }
270
+ assert(kinds.show >= 1 && kinds.beat >= 3 && kinds.acting >= 2, `a send site was not exercised: ${JSON.stringify(kinds)}`);
271
+ console.log('✅ 指示层 subtext 携带批次进度「appName · 最近一步(N 步)」:show/beat×3/相位重绘/恢复分支全透传,计数用 stepsRun');
272
+ }
273
+
274
+ // --- 11: read-only observation mode refuses input at the choke point and never lights the overlay
275
+ // P-10: with readOnly, every ACTION_COMMANDS member is refused one layer ABOVE the halt latch —
276
+ // before busy()/claim() — so a read-only session (unattended evaluation/demo, DSH_NATIVE_UIA_
277
+ // READ_ONLY=1) cannot light the indicator at all, while the observation whitelist keeps working.
278
+ {
279
+ const { CuaWorker } = await import('../src/worker-client.js');
280
+ const fired = { action: [], observe: [] };
281
+ const worker = new CuaWorker({
282
+ readOnly: true,
283
+ logger: () => {},
284
+ onActionStart: (cmd) => fired.action.push(cmd),
285
+ onObserve: (cmd) => fired.observe.push(cmd),
286
+ });
287
+ worker.start = () => {};
288
+ worker.proc = { stdin: { write: () => {} }, exitCode: null, killed: false };
289
+
290
+ // Every command that can put input on the desktop must answer read_only_mode…
291
+ const inputs = ['act', 'commit_batch', 'launch', 'close_window', 'pointer_click', 'pointer_drag', 'pointer_scroll', 'type_text', 'key'];
292
+ for (const cmd of inputs) {
293
+ await assert.rejects(worker.call(cmd, {}), (error) => error.code === 'read_only_mode',
294
+ `${cmd} was not refused in read-only mode`);
295
+ }
296
+ assert.equal(worker.stats.readOnlyRefused, inputs.length, 'read-only refusals are not counted in stats');
297
+ // …and none of them may reach the claim hook: 只读会话不点亮指示层(拒绝发生在 claim 之前)。
298
+ assert.equal(fired.action.length, 0, 'a read-only refusal claimed the overlay: 只读会话点亮了指示层');
299
+ // 观察照常:懒派生 worker(此处 stub 掉)后走 observe 分支,续租通道不受只读影响。
300
+ // fire-and-forget(同第 8 节):stub 管道永不回包,await 会挂满 30 s 的 unref 超时;
301
+ // onObserve 在 call() 内同步触发,短超时让 promise 以可捕获的方式落定。
302
+ worker.call('snapshot', {}, { timeoutMs: 5 }).catch(() => {});
303
+ await sleep(20);
304
+ assert.deepEqual(fired.observe, ['snapshot'], 'an observation command did not ride the normal observe path in read-only mode');
305
+ console.log('✅ 只读观察模式:投递类动作在咽喉点拒绝(read_only_mode)且不点亮指示层,观察命令照常');
306
+ }
307
+
308
+ console.log('\n全部通过:租约/心跳/观察续租/终止与重启/探针静默/静默自熄/进度 subtext/只读咽喉点行为符合预期(两态)');
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Register or unregister this plugin in a DeepSeek Harness desktop profile.
4
+ * Only two keys of the profile package.json are touched: `dsh.profile.bundles`
5
+ * and `dependencies`. Both edits are derived from the file as it is on disk,
6
+ * never from a copied-out list, and every run leaves a timestamped backup.
7
+ */
8
+ import { readFileSync, writeFileSync, copyFileSync, existsSync, mkdirSync } from 'node:fs';
9
+ import { dirname, join, resolve, isAbsolute } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { homedir } from 'node:os';
12
+
13
+ // The plugin is registered wherever THIS COPY lives, derived from the script's own location and
14
+ // never from a fixed path. A distribution handed to another person lands in a different folder
15
+ // (different user name, different drive), and a hardcoded root made `install` write a link: to a
16
+ // directory that does not exist on their machine — the profile then failed to resolve the bundle.
17
+ const CORE_NAME = 'dsh-native-uia';
18
+ const CORE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
19
+ // Informational only (status output / docs). DSH_PLUGIN_ROOT still overrides the displayed root for
20
+ // people who keep plugins somewhere unusual.
21
+ const PLUGIN_ROOT = process.env.DSH_PLUGIN_ROOT ?? join(homedir(), '.dsh', 'plugins');
22
+ /**
23
+ * One package, multiple components — the WorkBuddy shape. The single package is
24
+ * the only bundle and the only profile dependency; the panel is its client half
25
+ * (`dsh.client` in the same manifest), so there are no component packages to
26
+ * link and no rows beyond the one bare-name row the patch inserts.
27
+ */
28
+ import { readdirSync } from 'node:fs';
29
+ const ALL = [{ name: CORE_NAME, dir: CORE_DIR }];
30
+ // DSH_PROFILE is often a bare profile NAME ("desktop"), not a path — the host exports it that way.
31
+ // Joining it directly produced "desktop\package.json" relative to the cwd and status failed with
32
+ // "profile manifest not found" even though the plugin was correctly registered. Accept both forms.
33
+ const PROFILE_HOME = join(homedir(), '.dsh', 'profiles');
34
+ function resolveProfile(value) {
35
+ if (value === undefined || value === '') return join(PROFILE_HOME, 'desktop');
36
+ return isAbsolute(value) ? value : join(PROFILE_HOME, value);
37
+ }
38
+ const PROFILE = resolveProfile(process.env.DSH_PROFILE);
39
+ const MANIFEST = join(PROFILE, 'package.json');
40
+ const mode = process.argv[2] ?? 'status';
41
+
42
+ if (!existsSync(join(CORE_DIR, 'client', 'client.js'))) {
43
+ console.error(`FAIL ${CORE_DIR}/client/client.js is missing; the manifest declares dsh.client but the panel bundle is gone`);
44
+ process.exit(1);
45
+ }
46
+ for (const pkg of ALL) {
47
+ if (!existsSync(join(pkg.dir, 'package.json'))) {
48
+ console.error(`FAIL component ${pkg.name} is not on disk at ${pkg.dir}`);
49
+ process.exit(1);
50
+ }
51
+ }
52
+
53
+ function fail(message) {
54
+ console.error(`FAIL ${message}`);
55
+ process.exit(1);
56
+ }
57
+
58
+ function readManifest() {
59
+ if (!existsSync(MANIFEST)) fail(`profile manifest not found: ${MANIFEST}`);
60
+ let json;
61
+ try {
62
+ json = JSON.parse(readFileSync(MANIFEST, 'utf8'));
63
+ } catch (error) {
64
+ fail(`profile manifest is not valid JSON (${error.message}); refusing to rewrite it`);
65
+ }
66
+ if (json.dsh?.profile?.bundles === undefined || !Array.isArray(json.dsh.profile.bundles)) {
67
+ fail('dsh.profile.bundles is missing or is not an array; refusing to invent it');
68
+ }
69
+ json.dependencies ??= {};
70
+ return json;
71
+ }
72
+
73
+ function writeManifest(json) {
74
+ const text = `${JSON.stringify(json, null, 2)}\n`;
75
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
76
+ copyFileSync(MANIFEST, `${MANIFEST}.bak-${stamp}`);
77
+ const tmp = `${MANIFEST}.tmp-${process.pid}`;
78
+ writeFileSync(tmp, text, 'utf8');
79
+ JSON.parse(readFileSync(tmp, 'utf8'));
80
+ writeFileSync(MANIFEST, text, 'utf8');
81
+ return `${MANIFEST}.bak-${stamp}`;
82
+ }
83
+
84
+ function status(json) {
85
+ const bundles = json.dsh.profile.bundles;
86
+ const asBundle = bundles.includes(CORE_NAME);
87
+ const asDep = json.dependencies?.[CORE_NAME] !== undefined;
88
+ const panel = json.dependencies?.['dsh-native-uia-ui'] !== undefined;
89
+ console.log([
90
+ `profile ${PROFILE}`,
91
+ `bundles ${bundles.length}`,
92
+ `${CORE_NAME.padEnd(22)} bundle=${asBundle ? 'yes' : 'NO '} dep=${asDep ? 'yes' : 'NO '} panel=client-half`,
93
+ ...(panel ? [`dsh-native-uia-ui${' '.repeat(5)} still a profile dependency (stale: the panel now lives inside ${CORE_NAME})`] : []),
94
+ ].join('\n'));
95
+ return asBundle && asDep && !panel;
96
+ }
97
+
98
+ if (mode === 'status') {
99
+ process.exit(status(readManifest()) ? 0 : 1);
100
+ }
101
+
102
+ if (mode === 'install') {
103
+ const json = readManifest();
104
+ const added = [];
105
+ if (!json.dsh.profile.bundles.includes(CORE_NAME)) {
106
+ json.dsh.profile.bundles.push(CORE_NAME);
107
+ added.push(`${CORE_NAME} (bundle)`);
108
+ }
109
+ for (const pkg of ALL) {
110
+ if (json.dependencies[pkg.name] !== `link:${pkg.dir}`) {
111
+ json.dependencies[pkg.name] = `link:${pkg.dir}`;
112
+ added.push(`${pkg.name} (dependency)`);
113
+ }
114
+ }
115
+ // The panel used to be its own package; its dependency (and any stray bundle
116
+ // entry) is stale now that it lives inside this one package.
117
+ const stale = 'dsh-native-uia-ui';
118
+ if (json.dependencies[stale] !== undefined) {
119
+ delete json.dependencies[stale];
120
+ added.push(`removed ${stale} (dependency; the panel now lives inside ${CORE_NAME})`);
121
+ }
122
+ if (json.dsh.profile.bundles.includes(stale)) {
123
+ json.dsh.profile.bundles = json.dsh.profile.bundles.filter((b) => b !== stale);
124
+ added.push(`removed ${stale} (bundle entry)`);
125
+ }
126
+ const backup = added.length > 0 ? writeManifest(json) : null;
127
+ const after = readManifest();
128
+ if (!after.dsh.profile.bundles.includes(CORE_NAME)) fail('re-read after write still lacks the core bundle entry');
129
+ for (const pkg of ALL) {
130
+ if (after.dependencies[pkg.name] !== `link:${pkg.dir}`) fail(`re-read after write still lacks the ${pkg.name} dependency`);
131
+ }
132
+ if (after.dependencies[stale] !== undefined) fail(`${stale} dependency survived removal`);
133
+ console.log(added.length === 0 ? 'already registered, nothing written' : `added:\n ${added.join('\n ')}\nbackup: ${backup}`);
134
+ console.log('then run: (cd "$DSH_PROFILE" && pnpm install --ignore-scripts) # link: deps must be linked, file: deps would be copied');
135
+ console.log('restart DeepSeek Harness for the profile to reload');
136
+ process.exit(0);
137
+ }
138
+
139
+ if (mode === 'remove') {
140
+ const json = readManifest();
141
+ const names = new Set([...ALL.map((pkg) => pkg.name), 'dsh-native-uia-ui']);
142
+ json.dsh.profile.bundles = json.dsh.profile.bundles.filter((b) => !names.has(b));
143
+ for (const name of names) delete json.dependencies[name];
144
+ const backup = writeManifest(json);
145
+ const after = readManifest();
146
+ for (const name of names) {
147
+ if (after.dsh.profile.bundles.includes(name)) fail(`${name} bundle entry survived removal`);
148
+ }
149
+ console.log(`removed ${names.size} entries (everything else untouched)\nbackup: ${backup}`);
150
+ process.exit(0);
151
+ }
152
+
153
+ console.error(`usage: node install.mjs [install|remove|status]`);
154
+ process.exit(2);
@@ -0,0 +1,14 @@
1
+ // ESM resolve/load hook used by scripts/load-tools.mjs. The host package
2
+ // `@deepseek-ai/dsh-tools` is provided by DSH itself and is not installed here, so the load test
3
+ // substitutes a one-line defineTool: the point is to prove the tool modules RESOLVE and every
4
+ // handler builds against its bindings, not to re-test the host SDK.
5
+ const STUB = 'data:text/javascript,' + encodeURIComponent(
6
+ 'export const defineTool = (definition) => ({ ...definition, __stub: true });\n',
7
+ );
8
+
9
+ export async function resolve(specifier, context, next) {
10
+ if (specifier === '@deepseek-ai/dsh-tools') {
11
+ return { url: STUB, shortCircuit: true };
12
+ }
13
+ return next(specifier, context);
14
+ }
@@ -0,0 +1,25 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { classify, classifyBatch, classifyClose, classifyLaunch, classifyKeys, POLICY } from '../../src/guard.js';
4
+ import { saveNote, noteHint } from '../../src/notes.js';
5
+ import { toolsSource } from './sources.mjs';
6
+
7
+ // Shared loader for the regression scripts: reads the PRODUCTION tool sources (concatenated in the
8
+ // order scripts/lib/sources.mjs declares), strips their ESM wrapper (imports / named exports) and
9
+ // evaluates the result as a plain function body with injected deps, so the scripts exercise the
10
+ // real source without a copy. `returnExpr` is the expression of the `return` statement inside the
11
+ // new Function body — each script picks the names it needs. Exported consts (PASS_THROUGH /
12
+ // OCR_COVER) are stripped to plain consts so scripts can pull the SAME set the tool uses instead
13
+ // of keeping a second copy around.
14
+ export async function loadToolsSource(returnExpr) {
15
+ const source = toolsSource();
16
+ const body = source
17
+ .replace(/^import .*;\r?\n/gm, '')
18
+ .replace(/^export async function /gm, 'async function ')
19
+ .replace(/^export function /gm, 'function ')
20
+ .replace(/^export const (\w+) =/gm, 'const $1 =')
21
+ .replace(/^export \{ [^}]+ \};?\r?\n/gm, '');
22
+ return new Function('deps', `const {writeFile,readdir,readFile,mkdir,unlink,join,defineTool,classify,classifyBatch,classifyClose,classifyLaunch,classifyKeys,saveNote,noteHint,POLICY}=deps;\n${body}\nreturn ${returnExpr};`)({
23
+ ...fs, join, defineTool: (x) => x, classify, classifyBatch, classifyClose, classifyLaunch, classifyKeys, saveNote, noteHint, POLICY,
24
+ });
25
+ }
@@ -0,0 +1,62 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const root = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
6
+
7
+ /**
8
+ * The browser half, the Host half and the gates all have to agree on ONE list order: the tool
9
+ * sources are concatenated in this order for the harness (which strips imports and evaluates the
10
+ * body), and the gates read the same concatenation so a rule can never be checked against a file
11
+ * the runtime no longer loads.
12
+ */
13
+ export const TOOLS_FILES = [
14
+ 'src/tools/runtime.js',
15
+ 'src/tools/format.js',
16
+ 'src/tools/ocr.js',
17
+ 'src/tools/recipes.js',
18
+ 'src/tools/defs/observe.js',
19
+ 'src/tools/defs/act.js',
20
+ 'src/tools/defs/pointer.js',
21
+ 'src/tools/defs/lifecycle.js',
22
+ 'src/tools/index.js',
23
+ ];
24
+
25
+ export function toolsSource() {
26
+ return TOOLS_FILES.map((rel) => `// ---- ${rel} ----\n${readFileSync(join(root, rel), 'utf8')}`).join('\n');
27
+ }
28
+
29
+ export function toolsFileList() {
30
+ return TOOLS_FILES.slice();
31
+ }
32
+
33
+ /**
34
+ * The PowerShell worker, split the same way: the entry keeps process setup and the stdio loop, the
35
+ * body lives in worker/lib in this order. The entry dot-sources the very list below at run time,
36
+ * and the gates read the concatenation, so "the file the gate parsed" and "the file the worker ran"
37
+ * are the same text.
38
+ */
39
+ export const WORKER_ENTRY = 'worker/uia-worker.ps1';
40
+
41
+ export const WORKER_FILES = [
42
+ 'worker/lib/01-core.ps1',
43
+ 'worker/lib/02-uia.ps1',
44
+ 'worker/lib/03-window.ps1',
45
+ 'worker/lib/04-match.ps1',
46
+ 'worker/lib/05-value.ps1',
47
+ 'worker/lib/06-snapshot.ps1',
48
+ 'worker/lib/07-action.ps1',
49
+ 'worker/lib/08-command.ps1',
50
+ 'worker/lib/09-pointer.ps1',
51
+ 'worker/lib/10-dispatch.ps1',
52
+ ];
53
+
54
+ export function workerSource() {
55
+ return [WORKER_ENTRY, ...WORKER_FILES]
56
+ .map((rel) => `# ---- ${rel} ----\n${readFileSync(join(root, rel), 'utf8')}`)
57
+ .join('\n');
58
+ }
59
+
60
+ export function workerFileList() {
61
+ return [WORKER_ENTRY, ...WORKER_FILES];
62
+ }
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ import { register } from 'node:module';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { dirname, join } from 'node:path';
6
+
7
+ // The module graph is the one thing a text-level gate cannot check: the split into
8
+ // src/tools/{runtime,format,ocr,recipes,defs/*} means a missing or mis-levelled import only shows
9
+ // up when the host applies the plugin — and then the whole plugin is dead (no tools, no service).
10
+ // This loads the real modules through a stub for the host SDK and asserts the full tool list
11
+ // registers, so the split stays honest without a desktop.
12
+ register(pathToFileURL(join(dirname(fileURLToPath(import.meta.url)), 'lib', 'dsh-tools-stub.mjs')));
13
+
14
+ const root = dirname(dirname(fileURLToPath(import.meta.url)));
15
+ // The package entry is imported too: it is what the host actually loads, and a tool module that
16
+ // stops re-exporting something index.js imports (idleTimeoutMs) kills the plugin the same way.
17
+ const entry = await import(pathToFileURL(join(root, 'src', 'index.js')).href);
18
+ if (typeof entry.apply !== 'function' || entry.name !== 'dsh-native-uia') {
19
+ console.error('entry module does not expose apply()/name for the host');
20
+ process.exit(1);
21
+ }
22
+ const { registerTools } = await import(pathToFileURL(join(root, 'src', 'tools', 'index.js')).href);
23
+
24
+ const EXPECTED = [
25
+ 'computer_windows', 'computer_snapshot', 'computer_find_text', 'computer_parse', 'computer_capture',
26
+ 'computer_act', 'computer_run', 'computer_wait', 'computer_resolve_window', 'computer_replay',
27
+ 'computer_click', 'computer_drag', 'computer_scroll', 'computer_type', 'computer_key', 'computer_mouse',
28
+ 'computer_launch', 'computer_close', 'computer_window', 'computer_done', 'computer_clipboard',
29
+ ];
30
+
31
+ const registered = [];
32
+ const store = {
33
+ windows: [], steps: [], counters: { refused: 0 }, running: false, busy: false, blocked: [], heldButtons: new Set(), attempts: new Map(), confirmTimeoutMs: 8000,
34
+ line() {}, block() { return { id: 1 }; }, step() {}, actionDone() {}, holdButton(b) { this.heldButtons.add(b); }, releaseButton(b) { return this.heldButtons.delete(b); },
35
+ noteAttempt(sig, ok) { const cur = this.attempts.get(sig) ?? { total: 0, misses: 0 }; cur.total += 1; cur.misses = ok ? 0 : cur.misses + 1; this.attempts.set(sig, cur); return cur; }, clearAttempts() { this.attempts.clear(); },
36
+ };
37
+ let disposed = false;
38
+ const dispose = registerTools(
39
+ { tools: { register: (d) => { registered.push(d); return () => {}; } }, systemPrompt: { add: () => () => {} } },
40
+ {
41
+ worker: { call: async () => ({}) },
42
+ store,
43
+ dataDir: join(process.env.TEMP ?? '.', 'dsh-native-uia-loadtest'),
44
+ owned: { windows: new Set() },
45
+ finishRun: async () => {},
46
+ activity: { withoutIndicator: async (f) => f(), beat() {}, show() {}, hide() {} },
47
+ },
48
+ );
49
+
50
+ const names = registered.map((d) => d.name);
51
+ const missing = EXPECTED.filter((n) => !names.includes(n));
52
+ const extra = names.filter((n) => !EXPECTED.includes(n));
53
+ if (missing.length) { console.error(`missing tools: ${missing.join(', ')}`); process.exit(1); }
54
+ if (extra.length) { console.error(`unexpected tools: ${extra.join(', ')}`); process.exit(1); }
55
+ if (typeof dispose === 'function') { dispose(); disposed = true; }
56
+
57
+ // Registration only proves the module graph links. A helper that ended up in the wrong domain
58
+ // module (classifyPoint lived in act.js while the pointer tools called it) still registers fine and
59
+ // only dies when a tool runs, so every handler is invoked once with empty args: argument guards
60
+ // answer with a string, and a missing binding throws ReferenceError, which fails this test.
61
+ const broken = [];
62
+ for (const definition of registered) {
63
+ if (typeof definition.execute !== 'function') continue;
64
+ try {
65
+ await definition.execute({}, { signal: undefined });
66
+ } catch (error) {
67
+ if (error instanceof ReferenceError) broken.push(`${definition.name}: ${error.message}`);
68
+ }
69
+ }
70
+ if (broken.length) {
71
+ console.error(`handlers reference names their module does not define:\n${broken.join('\n')}`);
72
+ process.exit(1);
73
+ }
74
+ console.log(`${names.length}/${EXPECTED.length} tools registered, module graph loads, dispose=${disposed}`);