dsh-windows-parallel-mcp 0.0.1 → 0.1.1

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/lib/index.js ADDED
@@ -0,0 +1,330 @@
1
+ // index.js — the host half: one tool, one worker, and the refusal vocabulary kept intact.
2
+ //
3
+ // THE SHAPE OF THIS FILE IS THE FORM DECISION. R3.1' in spec.md recorded the fork as
4
+ // A. DSH native plugin: the host registers the tool directly; PowerShell is a sidecar.
5
+ // B. MCP server: the host talks to a separate MCP process over stdio.
6
+ // The owner chose A on 2026-11-19. Concretely that means: no `@modelcontextprotocol/sdk`, no bridge
7
+ // row, no second Node process — the tool is registered here and the only child process is the
8
+ // PowerShell worker, which the engine already needed in either form.
9
+ //
10
+ // WHY ONE TOOL AND NOT FIVE. src/schema/tools.json names five actions as the contract surface. The
11
+ // host convention (shell / terminal / read / write in this same build) is one tool with an action
12
+ // discriminator, because every registered tool is resident schema on every turn — five entries
13
+ // describing one engine is a standing token cost for no gain in capability. The contract is
14
+ // preserved exactly: same five actions, same eight refusal codes, same required arguments. The
15
+ // mapping is asserted in test/plugin-test.mjs against the contract file, so "we project to one tool"
16
+ // cannot quietly become "we support four actions".
17
+ //
18
+ // THE THREE THINGS THIS FILE MUST GET RIGHT, each of which would look like a working plugin while
19
+ // being wrong:
20
+ // 1. A disappeared worker must not become a dead tool. The client restarts once and reports.
21
+ // 2. A refusal must survive as a refusal. It is returned in the result text with its code, never
22
+ // swallowed and never turned into a generic failure — R3.2 forbids canned messages.
23
+ // 3. `paused` and `enabled` are server-side gates. They are checked here, before any worker call,
24
+ // because a prompt-level hint is not a switch (R2.5).
25
+ import { createConfigSchema, CONFIG_DEFAULTS } from './config.js';
26
+ import { WorkerClient, workerScript } from './engine.js';
27
+ import { ACTIONS, PARAMETERS, TOOL_NAME, resolveDefineTool } from './host-tools.js';
28
+
29
+ /** Stable Cordis plugin name (this is what a profile entry points at). */
30
+ export const name = 'windows-parallel';
31
+
32
+ /** Services that must exist before the tool can register. */
33
+ export const inject = ['tools'];
34
+
35
+ /**
36
+ * The settings schema is resolved once, at module load, because Cordis reads `Config` synchronously
37
+ * as a standard-schema value (it calls `Config['~standard'].validate(config)`). A factory function
38
+ * here -- the first version of this file -- fails activation with
39
+ * `Cannot read properties of undefined (reading 'validate')`, which is only visible by booting a real
40
+ * profile. See lib/config.js.
41
+ */
42
+ const resolvedConfig = await createConfigSchema();
43
+ export const Config = resolvedConfig.schema;
44
+ export const configSource = resolvedConfig.source;
45
+
46
+ /**
47
+ * Resolved at module load, not inside `apply`. Cordis treats whatever `apply` returns as a
48
+ * disposable effect, so an `async apply` returns a Promise and the plugin dies with "Invalid effect"
49
+ * -- the second activation failure found by booting a real profile. Anything asynchronous therefore
50
+ * has to finish before `apply` runs, which top-level await makes possible and keeps `apply` sync.
51
+ */
52
+ const resolvedTools = await resolveDefineTool();
53
+ export const toolHelperSource = resolvedTools.source;
54
+
55
+ /**
56
+ * Register the tool. `apply` is the whole host half; there is no client half yet, which is
57
+ * deliberate: the overlay / pill / hotkey layer is task_54 and gets its own commit. A plugin with a
58
+ * working tool and no UI is usable; a plugin with UI and no working tool is a demo.
59
+ */
60
+ export function apply(ctx, config = {}) {
61
+ const settings = {
62
+ enabled: resolveSetting(config.enabled, true),
63
+ settleMs: resolveSetting(config.settleMs, 350),
64
+ requestTimeoutMs: resolveSetting(config.requestTimeoutMs, 20000),
65
+ powershellPath: resolveSetting(config.powershellPath, ''),
66
+ overlay: resolveSetting(config.overlay, true),
67
+ logWorkerStderr: resolveSetting(config.logWorkerStderr, false),
68
+ };
69
+
70
+ const logger = ctx.logger ?? console;
71
+ // ---- the marker -----------------------------------------------------------------------------
72
+ // Deliberately fire-and-forget and deliberately AFTER the action has answered: this is a visual
73
+ // aid, not part of the result, and making it synchronous would put 19ms (plus a one-time ~875ms
74
+ // overlay start) on every click. Two rules keep it honest:
75
+ // * it is fired after the action request resolves, so a slow overlay start can never delay the
76
+ // action the user is waiting for;
77
+ // * the first failure is WARNED, not swallowed -- an overlay that never appears would otherwise
78
+ // make the README's "AI cursor is a click-through overlay" claim silently untrue.
79
+ // Cost measured over the real worker protocol (.tmp/worker-overlay.mjs): start ~875ms once,
80
+ // marker 19ms, status 15ms, stop ~660ms.
81
+ let overlayReady = null;
82
+ let overlayWarned = false;
83
+ const ensureOverlay = () => {
84
+ if (overlayReady) return overlayReady;
85
+ overlayReady = client.request({ action: 'overlay', on: true }).then((env) => {
86
+ if (!env.ok) throw new Error(env.error || 'overlay start refused');
87
+ const st = env.result?.state ?? {};
88
+ if (!st.running) throw new Error(st.reason || 'overlay reported not running');
89
+ if (st.hotkeyRegistered === false) {
90
+ logger.warn?.(`[windows-parallel] pause hotkey unavailable: ${st.reason || 'RegisterHotKey failed'}`);
91
+ } else if (st.hotkeyLabel && st.hotkeyLabel !== 'Ctrl+Alt+Q') {
92
+ logger.warn?.(`[windows-parallel] Ctrl+Alt+Q is owned by another app; the pause key is ${st.hotkeyLabel}`);
93
+ }
94
+ return st;
95
+ }).catch((err) => {
96
+ overlayReady = null; // let the next action retry rather than latch off
97
+ if (!overlayWarned) {
98
+ overlayWarned = true;
99
+ logger.warn?.(`[windows-parallel] marker overlay unavailable (${err.message}); actions still work`);
100
+ }
101
+ throw err;
102
+ });
103
+ return overlayReady;
104
+ };
105
+ /** Place the marker at a PHYSICAL screen point. Never awaited by the caller path. */
106
+ const markPoint = (x, y) => {
107
+ if (!settings.overlay || !Number.isFinite(x) || !Number.isFinite(y)) return;
108
+ ensureOverlay()
109
+ .then(() => client.request({ action: 'marker', x: Math.round(x), y: Math.round(y) }))
110
+ .catch(() => { /* already warned by ensureOverlay, or the marker request itself failed */ });
111
+ };
112
+ logger.info?.(`[windows-parallel] config schema: ${configSource}`);
113
+ const client = new WorkerClient({
114
+ powershellPath: settings.powershellPath,
115
+ script: workerScript(),
116
+ requestTimeoutMs: settings.requestTimeoutMs,
117
+ onStderr: (line) => {
118
+ if (settings.logWorkerStderr) logger.warn?.(`[wpm worker] ${line}`);
119
+ },
120
+ onExit: ({ code }) => {
121
+ logger.warn?.(`[windows-parallel] engine worker exited (code=${code}); it will restart on the next call`);
122
+ },
123
+ });
124
+
125
+ const { defineTool } = resolvedTools;
126
+
127
+ /** Build the worker request for one action. Throws for arguments the action cannot use. */
128
+ function toRequest(args) {
129
+ const settleMs = clampSettle(args.settleMs ?? settings.settleMs);
130
+ switch (args.action) {
131
+ case 'windows':
132
+ return { action: 'windows' };
133
+ case 'status':
134
+ return { action: 'status' };
135
+ case 'click':
136
+ requireArg(args, 'hwnd', 'click');
137
+ requireArg(args, 'x', 'click');
138
+ requireArg(args, 'y', 'click');
139
+ return { action: 'click', hwnd: args.hwnd, x: Math.round(args.x), y: Math.round(args.y), settleMs };
140
+ case 'type':
141
+ requireArg(args, 'hwnd', 'type');
142
+ if (typeof args.text !== 'string' || args.text.length === 0) {
143
+ // Refused here rather than sent: a write of nothing succeeds silently on every channel,
144
+ // so an empty string is indistinguishable from a dead door.
145
+ throw refusal('unreachable', 'type needs a non-empty text; an empty write cannot be verified');
146
+ }
147
+ return {
148
+ action: 'type', hwnd: args.hwnd, text: args.text,
149
+ elementName: args.elementName ?? '', replace: args.replace === true, settleMs,
150
+ };
151
+ case 'focus':
152
+ requireArg(args, 'hwnd', 'focus');
153
+ requireArg(args, 'elementName', 'focus');
154
+ return { action: 'focus', hwnd: args.hwnd, elementName: args.elementName, settleMs };
155
+ default:
156
+ throw refusal('no_hwnd', `unknown action '${args.action}'`);
157
+ }
158
+ }
159
+
160
+ const tool = defineTool({
161
+ name: TOOL_NAME,
162
+ description:
163
+ 'Drive a Windows window without moving the cursor or stealing the keyboard: click at a screen '
164
+ + 'coordinate, write text, or move focus inside ONE named window, choosing the cheapest available '
165
+ + 'door. A classic child window is addressed with window messages (measured: zero foreground '
166
+ + 'changes). A window that only exposes a UI Automation pattern costs one bounded foreground flash '
167
+ + 'that is reversed once afterwards (measured net return 15-95 ms). The real cursor never moves in '
168
+ + 'either tier, no keystrokes are synthesized, and the tool never pulls focus back from a window '
169
+ + 'the user chose. Refusals carry a code (no_hwnd, paused, elevated_target, unreachable, '
170
+ + 'terminal_no_door, needs_facts, action_failed, restore_failed) and a reason. Start with '
171
+ + 'action=windows to get an hwnd, or action=status to see what currently holds the foreground.',
172
+ parameters: PARAMETERS,
173
+ output: {
174
+ schema: {
175
+ type: 'object',
176
+ additionalProperties: true,
177
+ properties: {
178
+ action: { type: 'string', required: true },
179
+ ok: { type: 'boolean', required: true },
180
+ refusal: { type: 'string' },
181
+ text: { type: 'string', required: true },
182
+ },
183
+ },
184
+ render: (_args, value) => [{ type: 'text', text: value.text }],
185
+ },
186
+ async execute(args) {
187
+ // Server-side gates first: a paused or disabled engine must refuse before it spends a worker
188
+ // call, and the refusal must name the gate rather than describe a symptom.
189
+ if (!settings.enabled) {
190
+ return result(args.action, false, 'paused', 'windows-parallel is switched off in settings; no action was attempted');
191
+ }
192
+ // A pre-worker refusal is still a refusal, not a thrown error. The first version of this file
193
+ // let `toRequest` throw for an empty write, and the caller saw a crashed tool call instead of
194
+ // `unreachable` -- the exact "refusal became an exception" defect this plugin's own comment
195
+ // above warns about. Caught by test/plugin-test.mjs, which asserts the code is returned.
196
+ let request;
197
+ try {
198
+ request = toRequest(args);
199
+ } catch (err) {
200
+ const code = err?.refusal ?? 'action_failed';
201
+ return result(args.action, false, code, err?.reason ?? String(err?.message ?? err));
202
+ }
203
+ let envelope;
204
+ try {
205
+ envelope = await client.request(request);
206
+ } catch (err) {
207
+ // The worker layer failed (crash, timeout, missing engine). This is not a refusal code: the
208
+ // engine never got to decide. Say exactly that instead of borrowing a code it does not own.
209
+ return result(args.action, false, 'action_failed', `engine worker unavailable: ${err.message}`);
210
+ }
211
+ if (!envelope.ok) {
212
+ return result(args.action, false, 'action_failed', `worker error: ${envelope.error ?? 'unknown'}`);
213
+ }
214
+ // click coordinates are SCREEN pixels (the engine converts to client space itself), so the
215
+ // marker can be placed straight from the request -- no second coordinate system to get wrong.
216
+ // Only a click that actually ran places a marker: a refused click has no impact point, and
217
+ // letting a refusal start the overlay would mean a dead hwnd silently spawns a WPF window.
218
+ const r = envelope.result;
219
+ if (request.action === 'click' && r && r.ok !== false && !r.refusal) {
220
+ markPoint(request.x, request.y);
221
+ }
222
+ return format(args.action, envelope.result);
223
+ },
224
+ });
225
+
226
+ ctx.tools.register(tool);
227
+ ctx.on?.('dispose', () => { void client.dispose(); });
228
+ // No return value. Cordis treats whatever `apply` returns as a disposable effect, so returning the
229
+ // registered tool is at best ignored and at worst an "Invalid effect" that disables the plugin --
230
+ // the same class of failure as the async apply, one step further in.
231
+ }
232
+
233
+ // ---- small helpers ---------------------------------------------------------------------------
234
+
235
+ /** A Cordis settings value may be a live ref (0.1.7+) or a plain value (older lines). */
236
+ function resolveSetting(value, fallback) {
237
+ if (value === undefined || value === null) return fallback;
238
+ const v = typeof value.get === 'function' ? value.get() : value;
239
+ if (v === undefined || v === null) return fallback;
240
+ return v;
241
+ }
242
+
243
+ function clampSettle(value) {
244
+ const n = Number(value);
245
+ if (!Number.isFinite(n)) return 350;
246
+ return Math.max(0, Math.min(2000, Math.round(n)));
247
+ }
248
+
249
+ function requireArg(args, key, action) {
250
+ if (args[key] === undefined || args[key] === null || args[key] === '') {
251
+ throw refusal('no_hwnd', `action=${action} requires '${key}'`);
252
+ }
253
+ }
254
+
255
+ /** A refusal thrown before the worker is reached; caught by the caller path that renders results. */
256
+ function refusal(code, reason) {
257
+ const err = new Error(`${code}: ${reason}`);
258
+ err.refusal = code;
259
+ err.reason = reason;
260
+ return err;
261
+ }
262
+
263
+ function result(action, ok, refusalCode, text) {
264
+ return { action, ok, refusal: refusalCode, text: refusalCode ? `${refusalCode}: ${text}` : text };
265
+ }
266
+
267
+ /**
268
+ * Turn a worker result into the tool's output value.
269
+ *
270
+ * The text is the product. A caller that gets `ok:false` with a code and a reason can act; a caller
271
+ * that gets "the action failed" cannot. Every number reported here is measured by the engine, not
272
+ * inferred by this file.
273
+ */
274
+ function format(action, r) {
275
+ if (!r) return result(action, false, 'action_failed', 'engine returned no result');
276
+
277
+ if (action === 'windows') {
278
+ const list = Array.isArray(r.windows) ? r.windows : [];
279
+ if (list.length === 0) {
280
+ return result(action, true, '', 'no drivable windows are visible right now (minimised and untitled windows are excluded by design)');
281
+ }
282
+ const lines = list.map((w) => `${w.hwnd} ${truncate(String(w.title), 60)} [${w.cls}] pid=${w.pid} rect=${w.rect}`);
283
+ return result(action, true, '', `${list.length} drivable window(s):\n${lines.join('\n')}`);
284
+ }
285
+
286
+ if (action === 'status') {
287
+ const bits = [
288
+ `paused=${r.paused === true}`,
289
+ `foreground=${r.foreground || '(none)'}`,
290
+ `foregroundPid=${r.foregroundPid || '(none)'}`,
291
+ `focusedControl=${r.focusControl || '(none)'}`,
292
+ `lastHumanInputAgeMs=${r.lastInputAgeMs ?? 'unknown'}`,
293
+ ];
294
+ // The control surface travels with status. Without it, "the overlay is on" and "the pause key
295
+ // registered" are claims the user cannot check -- and this machine's desktop already owns
296
+ // Ctrl+Alt+Q, so the real chord is not the documented one. Silence here would be a lie.
297
+ bits.push(`overlay=${r.overlayRunning === true ? 'on' : 'off'}`);
298
+ bits.push(`pauseHotkey=${r.hotkeyRegistered === true ? (r.hotkeyLabel || 'registered') : 'unavailable'}`);
299
+ if (r.overlayReason) bits.push(`overlayNote=${r.overlayReason}`);
300
+ if (r.pauseReason) bits.push(`pauseReason=${r.pauseReason}`);
301
+ if (r.stance) bits.push(`stance: ${r.stance}`);
302
+ return result(action, true, '', bits.join('\n'));
303
+ }
304
+
305
+ // Action results. `refusal` is the engine's own code: an empty string means the action ran.
306
+ const code = r.refusal ? String(r.refusal) : '';
307
+ if (code) {
308
+ const reason = r.reason ? ` (${r.reason})` : '';
309
+ return result(action, false, code, `${code}${reason}`);
310
+ }
311
+
312
+ const bits = [
313
+ `${action} ok`,
314
+ `channel=${r.channel || '?'}`,
315
+ `tier=${r.tier || '?'}`,
316
+ `focusTaken=${r.focusTaken === 'true' || r.focusTaken === true}`,
317
+ ];
318
+ if (r.restoreOutcome) bits.push(`restore=${r.restoreOutcome}`);
319
+ if (r.flashMs !== undefined) bits.push(`flashMs=${r.flashMs}`);
320
+ if (r.latencyMs !== undefined) bits.push(`latencyMs=${r.latencyMs}`);
321
+ if (r.detail) bits.push(`detail=${r.detail}`);
322
+ return result(action, true, '', bits.join(' '));
323
+ }
324
+
325
+ function truncate(s, n) {
326
+ return s.length <= n ? s : `${s.slice(0, n - 1)}…`;
327
+ }
328
+
329
+ // Exported for tests: the projection from the five contract actions to this one tool.
330
+ export const _internals = { PARAMETERS, ACTIONS, TOOL_NAME, clampSettle, CONFIG_DEFAULTS };
@@ -0,0 +1,17 @@
1
+ // peers-schemastery.js -- the host's schema library, reached through a STATIC import.
2
+ //
3
+ // WHY THIS FILE EXISTS (and why it is separate from peers-tools.js). The desktop profile showed
4
+ // `config schema: local-standard-schema-shim` -- no settings form -- because a DYNAMIC
5
+ // import('@deepseek-ai/schemastery') from a `link:`-installed package resolves upward from the
6
+ // link TARGET (E:\test\...), never through the profile's node_modules. The proven pattern in the
7
+ // same profile is dsh-bash-terminal-ts: STATIC bare imports, which the host's loader resolves in
8
+ // the host realm.
9
+ //
10
+ // WHY THE SPLIT MATTERS. schemastery is a cordis dependency: present wherever the host runs.
11
+ // dsh-tools is NOT installed in this profile at all (verified: absent from node_modules). One
12
+ // combined bridge module would mean the missing dsh-tools throws during evaluation and takes
13
+ // schemastery down with it -- the plugin would fail to LOAD, which is worse than the shim path it
14
+ // was meant to fix. Two files, two independent failure domains.
15
+ import schemasteryNs from '@deepseek-ai/schemastery';
16
+
17
+ export const z = schemasteryNs?.default ?? schemasteryNs;
@@ -0,0 +1,6 @@
1
+ // peers-tools.js -- the host's defineTool, reached through a STATIC import. See peers-schemastery.js
2
+ // for why the bridge is split in two and why a dynamic bare specifier does not resolve for a
3
+ // `link:`-installed package.
4
+ import * as toolsNs from '@deepseek-ai/dsh-tools';
5
+
6
+ export const defineTool = toolsNs.defineTool;
package/package.json CHANGED
@@ -1,26 +1,66 @@
1
1
  {
2
2
  "name": "dsh-windows-parallel-mcp",
3
- "version": "0.0.1",
4
- "description": "Name reserved. Windows parallel input engine (hwnd-targeted: never moves the real cursor, never steals keyboard focus) for DeepSeek Harness. First release in development.",
5
- "license": "MIT",
6
- "author": "drscrewdriver",
3
+ "version": "0.1.1",
4
+ "publishConfig": {
5
+ "access": "public",
6
+ "tag": "latest"
7
+ },
8
+ "description": "Drive a Windows window without moving the cursor or stealing the keyboard: one tool, five actions, a channel decision table that prefers the quiet door, and a bounded self-reversing focus flash when only UI Automation can reach the control. Windows PowerShell 5.1 sidecar, zero install dependencies, no synthetic input.",
7
9
  "keywords": [
8
- "reserved",
9
- "name-reserved",
10
+ "deepseek",
11
+ "deepseek-harness",
10
12
  "dsh",
11
13
  "dsh-plugin",
12
- "deepseek-harness",
13
14
  "windows",
14
15
  "parallel",
15
16
  "hwnd",
17
+ "ui-automation",
16
18
  "computer-use"
17
19
  ],
20
+ "license": "MIT",
21
+ "type": "module",
22
+ "main": "lib/index.js",
23
+ "exports": {
24
+ ".": "./lib/index.js",
25
+ "./cordis.patch.yml": "./cordis.patch.yml",
26
+ "./dsh.plugin.json": "./dsh.plugin.json",
27
+ "./src/engine/*": "./src/engine/*",
28
+ "./package.json": "./package.json"
29
+ },
18
30
  "files": [
31
+ "lib/",
32
+ "src/engine/",
33
+ "src/schema/",
34
+ "docs/refusals.md",
35
+ "CHANGELOG.md",
36
+ "cordis.patch.yml",
37
+ "dsh.plugin.json",
38
+ "INSTALL.md",
19
39
  "README.md"
20
40
  ],
21
- "readmeFilename": "README.md",
22
- "repository": {
23
- "type": "git",
24
- "url": "git+https://github.com/drscrewdriver/dsh-windows-parallel-mcp.git"
41
+ "dsh": {
42
+ "bundle": {
43
+ "patch": "./cordis.patch.yml"
44
+ }
45
+ },
46
+ "engines": {
47
+ "node": ">=20",
48
+ "dsh": ">=0.1.7-0 <0.3.0-0"
49
+ },
50
+ "peerDependencies": {
51
+ "@deepseek-ai/dsh-tools": ">=0.1.7-0 <0.3.0-0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "@deepseek-ai/dsh-tools": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "scripts": {
59
+ "check": "node scripts/check.mjs",
60
+ "test": "node scripts/check.mjs && node test/plugin-test.mjs && node test/worker-smoke.mjs",
61
+ "test:decide": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File test/decide-test.ps1",
62
+ "test:refusals": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File test/refusals-test.ps1",
63
+ "prepack": "node scripts/check-pack.mjs",
64
+ "verify:install": "node scripts/verify-install.mjs"
25
65
  }
26
66
  }
@@ -0,0 +1,155 @@
1
+ # decide.ps1 -- the R2' channel decision, as a PURE function.
2
+ #
3
+ # WHY PURE AND FIRST. R2' turns on one table: which door a target has, and therefore whether an
4
+ # action costs the user nothing or costs them a bounded flash. Everything that can go wrong in
5
+ # that table goes wrong identically whether it is buried in a P/Invoke loop or written as a
6
+ # 30-line function, but only the function can be tested in milliseconds against every branch.
7
+ # The measured instruments in scripts/ proved the facts; this file is the part that consumes
8
+ # them, and it is kept free of IO so a wrong verdict cannot hide behind a passing desktop.
9
+ #
10
+ # THE FACTS IT CONSUMES, and where each came from:
11
+ # messageDoor -- 17/57 live windows expose a classic child door (neutral-coverage-census)
12
+ # hasPattern -- WPF/UWP/Chromium expose UIA patterns; WinForms exposes none (probe-winform)
13
+ # cursor cost -- zero in every channel (channel-raise-matrix, 0 px across 24 rounds)
14
+ # focus cost -- message door 0/6 raise; UIA pattern 6/6 and 12/12 raise
15
+ # Each fact is a measurement, not a guess. A fact that was never measured is NOT allowed to
16
+ # default to the flattering branch: missing facts refuse, they do not assume quiet.
17
+
18
+ Set-StrictMode -Version 2.0
19
+
20
+ # Refusal codes are a closed set on purpose. A generic 'failed' would make the product unable to
21
+ # tell the model why, which is the one thing R3.2 forbids: 'bottoms out to a canned message'.
22
+ $script:WpmRefusals = @{
23
+ no_hwnd = 'no target hwnd supplied; refuse rather than guess from screen coordinates'
24
+ paused = 'owner paused input; server-side refusal, not a prompt-level hint'
25
+ elevated_target = 'target runs at a higher integrity level; a non-elevated process cannot write to it'
26
+ unreachable = 'no message door and no usable UIA pattern; this target cannot be driven without physical input'
27
+ terminal_no_door = 'terminal text surface exposes no child HWND and no Document element'
28
+ needs_facts = 'the caller supplied no measured facts for this target; refusing instead of assuming quiet'
29
+ }
30
+
31
+ function New-WpmFacts {
32
+ # Explicit constructor so a missing field is a compile-time-shaped mistake in review rather
33
+ # than a silent $null that compares false and lands in the quiet branch.
34
+ param(
35
+ [string]$Hwnd = '',
36
+ [bool]$Paused = $false,
37
+ [bool]$ElevatedTarget = $false,
38
+ [string]$Family = 'unknown', # win32-classic | winforms | wpf | uwp | chromium | terminal | unknown
39
+ [bool]$MessageDoor = $false,
40
+ [bool]$HasPattern = $false,
41
+ [string]$PatternKind = 'none', # invoke | value | toggle | selectionitem | legacy | none
42
+ [string]$Action = 'click', # click | type | key | scroll
43
+ [bool]$FactsMeasured = $false
44
+ )
45
+ return @{
46
+ hwnd = $Hwnd; paused = $Paused; elevatedTarget = $ElevatedTarget; family = $Family
47
+ messageDoor = $MessageDoor; hasPattern = $HasPattern; patternKind = $PatternKind
48
+ action = $Action; factsMeasured = $FactsMeasured
49
+ }
50
+ }
51
+
52
+ function Get-WpmChannelDecision {
53
+ <#
54
+ Returns @{ channel; tier; needsRestore; refusal; reason }
55
+ channel 'message' | 'uia' | 'refuse'
56
+ tier 'quiet' | 'bounded-flash' | 'none'
57
+ needsRestore true only for the bounded-flash tier
58
+ ORDER OF CHECKS IS THE DESIGN. Pause and elevation are checked before any capability, because a
59
+ capability check that runs first can return a working channel for an action that must be
60
+ refused outright -- and the caller would then act while paused. The cheapest disqualifiers
61
+ come first; the capability table only decides between tiers that are both permitted.
62
+ #>
63
+ param([hashtable]$Facts)
64
+
65
+ if (-not $Facts) {
66
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
67
+ refusal = 'needs_facts'; reason = $script:WpmRefusals.needs_facts }
68
+ }
69
+ if ($Facts.paused) {
70
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
71
+ refusal = 'paused'; reason = $script:WpmRefusals.paused }
72
+ }
73
+ if (-not $Facts.hwnd) {
74
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
75
+ refusal = 'no_hwnd'; reason = $script:WpmRefusals.no_hwnd }
76
+ }
77
+ if ($Facts.elevatedTarget) {
78
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
79
+ refusal = 'elevated_target'; reason = $script:WpmRefusals.elevated_target }
80
+ }
81
+ # Terminal is its own code, not folded into 'unreachable': the two have different fixes (one is
82
+ # "pick another target", the other is "this class will never work"), and a product that reports
83
+ # one generic failure cannot be diagnosed by the person reading the output.
84
+ if ($Facts.family -eq 'terminal' -and -not $Facts.messageDoor -and -not $Facts.hasPattern) {
85
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
86
+ refusal = 'terminal_no_door'; reason = $script:WpmRefusals.terminal_no_door }
87
+ }
88
+
89
+ # TIER 1: message door. Measured free -- 0/6 raises, effect verified app-side in 6/6, cursor 0 px.
90
+ # Preferred whenever it exists, which INVERTS the original R2.2 priority (UIA first). The
91
+ # original order preferred the channel that steals focus; this one prefers the channel that
92
+ # does not. That inversion is the whole point of R2'.
93
+ if ($Facts.messageDoor) {
94
+ return @{ channel = 'message'; tier = 'quiet'; needsRestore = $false; refusal = ''; reason = 'classic child window accepts target-window messages' }
95
+ }
96
+
97
+ # TIER 2: UIA pattern. Measured to raise 6/6 and 12/12, therefore it always needs restoration.
98
+ # A pattern with no path to restoration would be a permanent focus theft, so the caller is told
99
+ # needsRestore=true and must honour it; the decision itself does not attempt the restore because
100
+ # a pure function cannot.
101
+ if ($Facts.hasPattern -and $Facts.patternKind -ne 'none') {
102
+ return @{ channel = 'uia'; tier = 'bounded-flash'; needsRestore = $true; refusal = ''; reason = "UIA $($Facts.patternKind) pattern available; costs one bounded foreground flash" }
103
+ }
104
+
105
+ # Neither door. Refuse, and say which one was missing -- an unmeasured target must not be
106
+ # guessed into the quiet branch, which is the failure this whole plan exists to avoid.
107
+ if (-not $Facts.factsMeasured) {
108
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
109
+ refusal = 'needs_facts'; reason = $script:WpmRefusals.needs_facts }
110
+ }
111
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
112
+ refusal = 'unreachable'; reason = $script:WpmRefusals.unreachable }
113
+ }
114
+
115
+ function Get-WpmRestoreDecision {
116
+ <#
117
+ Whether to put the focus back after a bounded-flash action, and why.
118
+ This is the safety property of R2'.4-R2'.7 expressed as a table, because these are the
119
+ branches that, if wrong, act on a window the product does not own.
120
+
121
+ currentFg == raisedHwnd -> restore (we caused it, we undo it)
122
+ currentFg pid == target pid -> skip: dialog (the app deliberately focused its own dialog)
123
+ currentFg is a third window -> skip: taken (the user or another app chose it; never fight)
124
+ nothing was raised -> skip: nothing (restoring here would fight the user)
125
+ restore already attempted once -> skip: done (one-shot; a watchdog would fight the owner)
126
+
127
+ The dialog branch is not a nicety: without it, restoring after an action that opened a Save
128
+ dialog pulls the focus out of the dialog the action just created, so the box is visible and
129
+ unresponsive. Same-pid is the discriminator because the dialog belongs to the target process.
130
+ #>
131
+ param(
132
+ [string]$CurrentFg = '',
133
+ [string]$RaisedHwnd = '',
134
+ [string]$TargetPid = '',
135
+ [string]$CurrentFgPid = '',
136
+ [bool]$RaisedHappened = $false,
137
+ [bool]$AlreadyRestored = $false
138
+ )
139
+ if ($AlreadyRestored) {
140
+ return @{ restore = $false; outcome = 'skip'; reason = 'one-shot: a restore was already attempted for this action' }
141
+ }
142
+ if (-not $RaisedHappened) {
143
+ return @{ restore = $false; outcome = 'skip'; reason = 'no raise occurred; restoring would fight the owner' }
144
+ }
145
+ if (-not $CurrentFg -or -not $RaisedHwnd) {
146
+ return @{ restore = $false; outcome = 'skip'; reason = 'foreground or raised hwnd unknown' }
147
+ }
148
+ if ($CurrentFg -eq $RaisedHwnd) {
149
+ return @{ restore = $true; outcome = 'restore'; reason = 'our own raised window owns the foreground; safe to reverse' }
150
+ }
151
+ if ($TargetPid -and $CurrentFgPid -and ($CurrentFgPid -eq $TargetPid)) {
152
+ return @{ restore = $false; outcome = 'skip-dialog'; reason = 'same pid as the target: this is the app''s own dialog, not our theft' }
153
+ }
154
+ return @{ restore = $false; outcome = 'skip-taken'; reason = 'a third window holds the foreground; never pull it from the user' }
155
+ }