dsh-windows-parallel-mcp 0.1.0 → 0.1.2

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 CHANGED
@@ -1,330 +1,393 @@
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 };
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
+ import { evaluateProof } from './proof-window.mjs';
29
+
30
+ /** Stable Cordis plugin name (this is what a profile entry points at). */
31
+ export const name = 'windows-parallel';
32
+
33
+ /** Services that must exist before the tool can register. */
34
+ export const inject = ['tools'];
35
+
36
+ /**
37
+ * The settings schema is resolved once, at module load, because Cordis reads `Config` synchronously
38
+ * as a standard-schema value (it calls `Config['~standard'].validate(config)`). A factory function
39
+ * here -- the first version of this file -- fails activation with
40
+ * `Cannot read properties of undefined (reading 'validate')`, which is only visible by booting a real
41
+ * profile. See lib/config.js.
42
+ */
43
+ const resolvedConfig = await createConfigSchema();
44
+ export const Config = resolvedConfig.schema;
45
+ export const configSource = resolvedConfig.source;
46
+
47
+ /**
48
+ * Resolved at module load, not inside `apply`. Cordis treats whatever `apply` returns as a
49
+ * disposable effect, so an `async apply` returns a Promise and the plugin dies with "Invalid effect"
50
+ * -- the second activation failure found by booting a real profile. Anything asynchronous therefore
51
+ * has to finish before `apply` runs, which top-level await makes possible and keeps `apply` sync.
52
+ */
53
+ const resolvedTools = await resolveDefineTool();
54
+ export const toolHelperSource = resolvedTools.source;
55
+
56
+ /**
57
+ * Register the tool. `apply` is the whole host half; there is no client half yet, which is
58
+ * deliberate: the overlay / pill / hotkey layer is task_54 and gets its own commit. A plugin with a
59
+ * working tool and no UI is usable; a plugin with UI and no working tool is a demo.
60
+ */
61
+ export function apply(ctx, config = {}) {
62
+ const settings = {
63
+ enabled: resolveSetting(config.enabled, true),
64
+ settleMs: resolveSetting(config.settleMs, 350),
65
+ requestTimeoutMs: resolveSetting(config.requestTimeoutMs, 20000),
66
+ powershellPath: resolveSetting(config.powershellPath, ''),
67
+ overlay: resolveSetting(config.overlay, true),
68
+ logWorkerStderr: resolveSetting(config.logWorkerStderr, false),
69
+ };
70
+
71
+ const logger = ctx.logger ?? console;
72
+ // ---- the marker -----------------------------------------------------------------------------
73
+ // Deliberately fire-and-forget and deliberately AFTER the action has answered: this is a visual
74
+ // aid, not part of the result, and making it synchronous would put 19ms (plus a one-time ~875ms
75
+ // overlay start) on every click. Two rules keep it honest:
76
+ // * it is fired after the action request resolves, so a slow overlay start can never delay the
77
+ // action the user is waiting for;
78
+ // * the first failure is WARNED, not swallowed -- an overlay that never appears would otherwise
79
+ // make the README's "AI cursor is a click-through overlay" claim silently untrue.
80
+ // Cost measured over the real worker protocol (.tmp/worker-overlay.mjs): start ~875ms once,
81
+ // marker 19ms, status 15ms, stop ~660ms.
82
+ let overlayReady = null;
83
+ let overlayWarned = false;
84
+ const ensureOverlay = () => {
85
+ if (overlayReady) return overlayReady;
86
+ overlayReady = client.request({ action: 'overlay', on: true }).then((env) => {
87
+ if (!env.ok) throw new Error(env.error || 'overlay start refused');
88
+ const st = env.result?.state ?? {};
89
+ if (!st.running) throw new Error(st.reason || 'overlay reported not running');
90
+ if (st.hotkeyRegistered === false) {
91
+ logger.warn?.(`[windows-parallel] pause hotkey unavailable: ${st.reason || 'RegisterHotKey failed'}`);
92
+ } else if (st.hotkeyLabel && st.hotkeyLabel !== 'Ctrl+Alt+Q') {
93
+ logger.warn?.(`[windows-parallel] Ctrl+Alt+Q is owned by another app; the pause key is ${st.hotkeyLabel}`);
94
+ }
95
+ return st;
96
+ }).catch((err) => {
97
+ overlayReady = null; // let the next action retry rather than latch off
98
+ if (!overlayWarned) {
99
+ overlayWarned = true;
100
+ logger.warn?.(`[windows-parallel] marker overlay unavailable (${err.message}); actions still work`);
101
+ }
102
+ throw err;
103
+ });
104
+ return overlayReady;
105
+ };
106
+ /**
107
+ * Place the marker at a PHYSICAL screen point. Never awaited by the caller path.
108
+ * Placement RETRIES until the overlay reports running or a 6 s deadline passes -- not as a
109
+ * bandage but because the old single-shot silently broke the shipped promise: a cold worker's
110
+ * handshake can expire while the overlay is genuinely still starting (measured: WPF JIT past the
111
+ * budget), the marker request was then skipped, and the click had already answered so nobody ever
112
+ * retried. A promise with a race window is a promise that loses the race sometimes. The deadline
113
+ * is BOUNDED and a confirmed-dead start (a reason with starting=false) stops the loop immediately
114
+ * and warns -- endless patience would just hide a broken surface.
115
+ */
116
+ const markPoint = (x, y) => {
117
+ if (!settings.overlay || !Number.isFinite(x) || !Number.isFinite(y)) return;
118
+ const mx = Math.round(x);
119
+ const my = Math.round(y);
120
+ void (async () => {
121
+ await ensureOverlay().catch(() => {}); // kick the start; its own failures are warned there
122
+ const deadline = Date.now() + 6000;
123
+ for (;;) {
124
+ const env = await client.request({ action: 'marker', x: mx, y: my }).catch(() => null);
125
+ const res = env?.result;
126
+ if (env?.ok && res?.ok !== false) return; // placed
127
+ if (res && res.reason === 'overlay not running') {
128
+ const st = await client.request({ action: 'overlay', on: true }).catch(() => null);
129
+ const state = st?.result?.state;
130
+ if (state && state.running) continue; // up now; retry placement
131
+ if (state && !state.starting && state.reason) {
132
+ if (!overlayWarned) {
133
+ overlayWarned = true;
134
+ logger.warn?.(`[windows-parallel] marker overlay failed to start (${state.reason}); actions still work`);
135
+ }
136
+ return; // dead for a named reason: stop
137
+ }
138
+ }
139
+ if (Date.now() >= deadline) {
140
+ if (!overlayWarned) {
141
+ overlayWarned = true;
142
+ logger.warn?.('[windows-parallel] marker was not placed within 6s of the click; actions still work');
143
+ }
144
+ return;
145
+ }
146
+ await new Promise((r) => setTimeout(r, 150));
147
+ }
148
+ })().catch(() => { /* warned inside; a marker must never become an unhandled rejection */ });
149
+ };
150
+ logger.info?.(`[windows-parallel] config schema: ${configSource}`);
151
+ const client = new WorkerClient({
152
+ powershellPath: settings.powershellPath,
153
+ script: workerScript(),
154
+ requestTimeoutMs: settings.requestTimeoutMs,
155
+ onStderr: (line) => {
156
+ if (settings.logWorkerStderr) logger.warn?.(`[wpm worker] ${line}`);
157
+ },
158
+ onExit: ({ code }) => {
159
+ logger.warn?.(`[windows-parallel] engine worker exited (code=${code}); it will restart on the next call`);
160
+ },
161
+ });
162
+
163
+ const { defineTool } = resolvedTools;
164
+
165
+ /** Build the worker request for one action. Throws for arguments the action cannot use. */
166
+ function toRequest(args) {
167
+ const settleMs = clampSettle(args.settleMs ?? settings.settleMs);
168
+ switch (args.action) {
169
+ case 'windows':
170
+ return { action: 'windows' };
171
+ case 'status':
172
+ return { action: 'status' };
173
+ case 'click':
174
+ requireArg(args, 'hwnd', 'click');
175
+ requireArg(args, 'x', 'click');
176
+ requireArg(args, 'y', 'click');
177
+ return { action: 'click', hwnd: args.hwnd, x: Math.round(args.x), y: Math.round(args.y), settleMs };
178
+ case 'type':
179
+ requireArg(args, 'hwnd', 'type');
180
+ if (typeof args.text !== 'string' || args.text.length === 0) {
181
+ // Refused here rather than sent: a write of nothing succeeds silently on every channel,
182
+ // so an empty string is indistinguishable from a dead door.
183
+ throw refusal('unreachable', 'type needs a non-empty text; an empty write cannot be verified');
184
+ }
185
+ return {
186
+ action: 'type', hwnd: args.hwnd, text: args.text,
187
+ elementName: args.elementName ?? '', replace: args.replace === true, settleMs,
188
+ };
189
+ case 'focus':
190
+ requireArg(args, 'hwnd', 'focus');
191
+ requireArg(args, 'elementName', 'focus');
192
+ return { action: 'focus', hwnd: args.hwnd, elementName: args.elementName, settleMs };
193
+ default:
194
+ throw refusal('no_hwnd', `unknown action '${args.action}'`);
195
+ }
196
+ }
197
+
198
+ const tool = defineTool({
199
+ name: TOOL_NAME,
200
+ description:
201
+ 'Drive a Windows window without moving the cursor or stealing the keyboard: click at a screen '
202
+ + 'coordinate, write text, or move focus inside ONE named window, choosing the cheapest available '
203
+ + 'door. A classic child window is addressed with window messages (measured: zero foreground '
204
+ + 'changes). A window that only exposes a UI Automation pattern costs one bounded foreground flash '
205
+ + 'that is reversed once afterwards (measured net return 15-95 ms). The real cursor never moves in '
206
+ + 'either tier, no keystrokes are synthesized, and the tool never pulls focus back from a window '
207
+ + 'the user chose. Refusals carry a code (no_hwnd, paused, elevated_target, unreachable, '
208
+ + 'terminal_no_door, needs_facts, action_failed, restore_failed) and a reason. Start with '
209
+ + 'action=windows to get an hwnd, or action=status to see what currently holds the foreground.',
210
+ parameters: PARAMETERS,
211
+ output: {
212
+ schema: {
213
+ type: 'object',
214
+ additionalProperties: true,
215
+ properties: {
216
+ action: { type: 'string', required: true },
217
+ ok: { type: 'boolean', required: true },
218
+ refusal: { type: 'string' },
219
+ text: { type: 'string', required: true },
220
+ },
221
+ },
222
+ render: (_args, value) => [{ type: 'text', text: value.text }],
223
+ },
224
+ async execute(args) {
225
+ // Server-side gates first: a paused or disabled engine must refuse before it spends a worker
226
+ // call, and the refusal must name the gate rather than describe a symptom.
227
+ if (!settings.enabled) {
228
+ return result(args.action, false, 'paused', 'windows-parallel is switched off in settings; no action was attempted');
229
+ }
230
+ // A pre-worker refusal is still a refusal, not a thrown error. The first version of this file
231
+ // let `toRequest` throw for an empty write, and the caller saw a crashed tool call instead of
232
+ // `unreachable` -- the exact "refusal became an exception" defect this plugin's own comment
233
+ // above warns about. Caught by test/plugin-test.mjs, which asserts the code is returned.
234
+ let request;
235
+ try {
236
+ request = toRequest(args);
237
+ } catch (err) {
238
+ const code = err?.refusal ?? 'action_failed';
239
+ return result(args.action, false, code, err?.reason ?? String(err?.message ?? err));
240
+ }
241
+ let envelope;
242
+ try {
243
+ envelope = await client.request(request);
244
+ } catch (err) {
245
+ // The worker layer failed (crash, timeout, missing engine). This is not a refusal code: the
246
+ // engine never got to decide. Say exactly that instead of borrowing a code it does not own.
247
+ return result(args.action, false, 'action_failed', `engine worker unavailable: ${err.message}`);
248
+ }
249
+ if (!envelope.ok) {
250
+ return result(args.action, false, 'action_failed', `worker error: ${envelope.error ?? 'unknown'}`);
251
+ }
252
+ // click coordinates are SCREEN pixels (the engine converts to client space itself), so the
253
+ // marker can be placed straight from the request -- no second coordinate system to get wrong.
254
+ // Only a click that actually ran places a marker: a refused click has no impact point, and
255
+ // letting a refusal start the overlay would mean a dead hwnd silently spawns a WPF window.
256
+ const r = envelope.result;
257
+ if (request.action === 'click' && r && r.ok !== false && !r.refusal) {
258
+ markPoint(request.x, request.y);
259
+ }
260
+ return format(args.action, envelope.result);
261
+ },
262
+ });
263
+
264
+ ctx.tools.register(tool);
265
+ ctx.on?.('dispose', () => { void client.dispose(); });
266
+ // No return value. Cordis treats whatever `apply` returns as a disposable effect, so returning the
267
+ // registered tool is at best ignored and at worst an "Invalid effect" that disables the plugin --
268
+ // the same class of failure as the async apply, one step further in.
269
+ }
270
+
271
+ // ---- small helpers ---------------------------------------------------------------------------
272
+
273
+ /** A Cordis settings value may be a live ref (0.1.7+) or a plain value (older lines). */
274
+ function resolveSetting(value, fallback) {
275
+ if (value === undefined || value === null) return fallback;
276
+ const v = typeof value.get === 'function' ? value.get() : value;
277
+ if (v === undefined || v === null) return fallback;
278
+ return v;
279
+ }
280
+
281
+ function clampSettle(value) {
282
+ const n = Number(value);
283
+ if (!Number.isFinite(n)) return 350;
284
+ return Math.max(0, Math.min(2000, Math.round(n)));
285
+ }
286
+
287
+ function requireArg(args, key, action) {
288
+ if (args[key] === undefined || args[key] === null || args[key] === '') {
289
+ throw refusal('no_hwnd', `action=${action} requires '${key}'`);
290
+ }
291
+ }
292
+
293
+ /** A refusal thrown before the worker is reached; caught by the caller path that renders results. */
294
+ function refusal(code, reason) {
295
+ const err = new Error(`${code}: ${reason}`);
296
+ err.refusal = code;
297
+ err.reason = reason;
298
+ return err;
299
+ }
300
+
301
+ function result(action, ok, refusalCode, text, extra) {
302
+ return { action, ok, refusal: refusalCode, text: refusalCode ? `${refusalCode}: ${text}` : text, ...(extra || {}) };
303
+ }
304
+
305
+ /**
306
+ * Turn a worker result into the tool's output value.
307
+ *
308
+ * The text is the product. A caller that gets `ok:false` with a code and a reason can act; a caller
309
+ * that gets "the action failed" cannot. Every number reported here is measured by the engine, not
310
+ * inferred by this file.
311
+ */
312
+ function format(action, r) {
313
+ if (!r) return result(action, false, 'action_failed', 'engine returned no result');
314
+
315
+ if (action === 'windows') {
316
+ const list = Array.isArray(r.windows) ? r.windows : [];
317
+ if (list.length === 0) {
318
+ return result(action, true, '', 'no drivable windows are visible right now (minimised and untitled windows are excluded by design)');
319
+ }
320
+ const lines = list.map((w) => `${w.hwnd} ${truncate(String(w.title), 60)} [${w.cls}] pid=${w.pid} rect=${w.rect}`);
321
+ return result(action, true, '', `${list.length} drivable window(s):\n${lines.join('\n')}`);
322
+ }
323
+
324
+ if (action === 'status') {
325
+ const bits = [
326
+ `paused=${r.paused === true}`,
327
+ `foreground=${r.foreground || '(none)'}`,
328
+ `foregroundPid=${r.foregroundPid || '(none)'}`,
329
+ `focusedControl=${r.focusControl || '(none)'}`,
330
+ `lastHumanInputAgeMs=${r.lastInputAgeMs ?? 'unknown'}`,
331
+ ];
332
+ // The control surface travels with status. Without it, "the overlay is on" and "the pause key
333
+ // registered" are claims the user cannot check -- and this machine's desktop already owns
334
+ // Ctrl+Alt+Q, so the real chord is not the documented one. Silence here would be a lie.
335
+ bits.push(`overlay=${r.overlayRunning === true ? 'on' : 'off'}`);
336
+ // The overlay's hwnd, so an INDEPENDENT oracle can verify the exact window the product thinks
337
+ // it is showing. Title-matching alone cannot do this: a leaked overlay from an earlier run is
338
+ // also titled WpmOverlay, and grading that instead of ours would make the marker arms grade
339
+ // homework that is not even in this class.
340
+ if (r.overlayHwnd && r.overlayHwnd !== '0') bits.push(`overlayHwnd=${r.overlayHwnd}`);
341
+ bits.push(`pauseHotkey=${r.hotkeyRegistered === true ? (r.hotkeyLabel || 'registered') : 'unavailable'}`);
342
+ if (r.overlayReason) bits.push(`overlayNote=${r.overlayReason}`);
343
+ if (r.pauseReason) bits.push(`pauseReason=${r.pauseReason}`);
344
+ if (r.stance) bits.push(`stance: ${r.stance}`);
345
+ return result(action, true, '', bits.join('\n'));
346
+ }
347
+
348
+ // Action results. `refusal` is the engine's own code: an empty string means the action ran.
349
+ const code = r.refusal ? String(r.refusal) : '';
350
+ if (code) {
351
+ const reason = r.reason ? ` (${r.reason})` : '';
352
+ return result(action, false, code, `${code}${reason}`);
353
+ }
354
+
355
+ const bits = [
356
+ `${action} ok`,
357
+ `channel=${r.channel || '?'}`,
358
+ `tier=${r.tier || '?'}`,
359
+ `focusTaken=${r.focusTaken === 'true' || r.focusTaken === true}`,
360
+ ];
361
+ // THE PROOF. The engine sampled cursor/foreground/focus/last-input-age in TWO windows: a short
362
+ // pre-action CONTROL (captured while, by construction, nothing was done) and the settle window
363
+ // AFTER the door call. The judgment is arithmetic and lives in one pure implementation
364
+ // (proof-window.mjs), never here and never in the README. Three verdicts, and their asymmetry is
365
+ // the whole point -- see proof-window.mjs's header for the idle-baseline measurement behind it:
366
+ // pass no unexplained cursor gap, no unexplained foreground/focus switch;
367
+ // inconclusive the desktop moved or switched in a way position data cannot attribute to the
368
+ // action (the idle baseline proved our absence does not imply desktop stillness);
369
+ // fail a foreground/focus switch the control shows the desktop was NOT doing, on a tier
370
+ // that did not DECLARE a bounded flash.
371
+ // `declaredFlash` is the decision table's own needsRestore: on the bounded-flash tier the engine
372
+ // DELIBERATELY raises foreground inside the window and restores it after -- the promise of that
373
+ // tier was never "don't touch", it is "don't keep", and the restore table owns that promise
374
+ // (restore_failed surfaces separately). Sampling cannot be allowed to contradict the contract.
375
+ // A missing/short window is 'insufficient': silence is not innocence.
376
+ const proof = evaluateProof(r.proofSamples || [], {
377
+ control: r.proofControl || [],
378
+ declaredFlash: r.tier === 'bounded-flash',
379
+ });
380
+ bits.push(`proof=${proof.verdict}(${proof.reason})`);
381
+ if (r.restoreOutcome) bits.push(`restore=${r.restoreOutcome}`);
382
+ if (r.flashMs !== undefined) bits.push(`flashMs=${r.flashMs}`);
383
+ if (r.latencyMs !== undefined) bits.push(`latencyMs=${r.latencyMs}`);
384
+ if (r.detail) bits.push(`detail=${r.detail}`);
385
+ return result(action, true, '', bits.join(' '), { proof: proof.verdict, proofDimensions: proof.dimensions });
386
+ }
387
+
388
+ function truncate(s, n) {
389
+ return s.length <= n ? s : `${s.slice(0, n - 1)}…`;
390
+ }
391
+
392
+ // Exported for tests: the projection from the five contract actions to this one tool.
393
+ export const _internals = { PARAMETERS, ACTIONS, TOOL_NAME, clampSettle, CONFIG_DEFAULTS };