dsh-windows-parallel-mcp 0.1.5 → 0.2.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.
package/lib/config.js CHANGED
@@ -35,6 +35,24 @@ const FIELDS = [
35
35
  + 'gate the action result.' },
36
36
  { key: 'logWorkerStderr', type: 'boolean', default: false, volatile: true,
37
37
  description: 'Forward the sidecar’s stderr diagnostics to the host log.' },
38
+ // ---- R3 gates. BOTH DEFAULT OFF, and that is a product decision, not timidity: with them off the
39
+ // tool behaves exactly like 0.1.6 (zero physical input), so an upgrade cannot silently start moving
40
+ // the owner's cursor. Turning takeover on is the owner's explicit act.
41
+ { key: 'takeoverAllowed', type: 'boolean', default: false, volatile: true,
42
+ description: 'Allow actions to request the takeover tier (takeover:true): the real cursor is moved '
43
+ + 'to the action point and always restored, the focus is held for the duration, and a three-phase '
44
+ + 'HUD is mandatory. Off by default; when off, a takeover request is refused with '
45
+ + 'takeover_unavailable and the action is NOT silently downgraded.' },
46
+ { key: 'keyInjectAllowed', type: 'boolean', default: false, volatile: true,
47
+ description: 'Allow keyboard injection (keyInput:"inject") inside the takeover tier, for targets '
48
+ + 'with no message door and no UIA pattern (terminals). Text is typed into the FOREGROUND window '
49
+ + 'after asserting it is the target; never mouse injection. Off by default.' },
50
+ { key: 'takeoverMaxMs', type: 'number', default: 10000, min: 500, max: 60000, volatile: true,
51
+ description: 'How long a takeover action may hold the owner’s cursor/focus before it must end. '
52
+ + 'Hard ceiling 60s; the HUD shows the elapsed/limit clock so a long action is visible.' },
53
+ { key: 'takeoverArmMs', type: 'number', default: 800, min: 0, max: 5000, volatile: true,
54
+ description: 'Length of the HUD’s arming phase: the window in which the owner can cancel before '
55
+ + 'the cursor moves or a key is typed. 0 disables the wait (the HUD still shows).' },
38
56
  ];
39
57
 
40
58
  /** Defaults, for documentation and for tests that must not depend on a resolver. */
@@ -115,8 +133,45 @@ export async function createConfigSchema() {
115
133
  if (field.volatile && typeof s.volatile === 'function') s = s.volatile();
116
134
  shape[field.key] = s;
117
135
  }
118
- const schema = z.object(shape);
119
- return { schema: typeof schema.prefault === 'function' ? schema.prefault({}) : schema, source: '@deepseek-ai/schemastery' };
136
+ const schema = typeof z.object(shape).prefault === 'function' ? z.object(shape).prefault({}) : z.object(shape);
137
+ // TWO PROPERTIES THE SHIM ALREADY HAD, restored on the Schemastery path so both paths behave the
138
+ // same way for the caller:
139
+ // * UNKNOWN KEYS ARE REJECTED, not silently carried through. Schemastery keeps them in the
140
+ // validated value, which means a typo'd setting reads as accepted while doing nothing -- the
141
+ // exact failure test/plugin-test.mjs pins, and the reason the shim has this rule;
142
+ // * '~standard' stays the single validation entry point Cordis calls.
143
+ // The Schemastery INSTANCE itself is kept: it is a callable object and it is what the host uses to
144
+ // render the settings form. Wrapping it in a plain object would trade the form for the check.
145
+ // Schemastery owns '~standard' as a non-writable accessor, so it cannot be replaced in place. The
146
+ // wrapper below is a PROXY over the instance: still callable, still carrying the instance's own
147
+ // fields and methods (which is what the settings form reads), but with one property -- the
148
+ // validation entry point Cordis calls -- replaced by the strict one.
149
+ const std = schema['~standard'];
150
+ let configValue = schema;
151
+ if (std && typeof std.validate === 'function') {
152
+ const known = new Set(FIELDS.map((f) => f.key));
153
+ const wrapped = Object.assign(Object.create(null), std, {
154
+ validate(raw) {
155
+ const input = raw && typeof raw === 'object' ? raw : {};
156
+ const unknown = Object.keys(input).filter((k) => !known.has(k));
157
+ if (unknown.length) {
158
+ return { issues: unknown.map((k) => ({ message: 'unknown setting', path: [k] })) };
159
+ }
160
+ return std.validate(raw);
161
+ },
162
+ });
163
+ try {
164
+ configValue = new Proxy(schema, {
165
+ get(target, prop, receiver) {
166
+ if (prop === '~standard') return wrapped;
167
+ const v = Reflect.get(target, prop, receiver);
168
+ return typeof v === 'function' ? v.bind(target) : v;
169
+ },
170
+ apply(target, thisArg, args) { return Reflect.apply(target, thisArg, args); },
171
+ });
172
+ } catch { configValue = schema; }
173
+ }
174
+ return { schema: configValue, source: '@deepseek-ai/schemastery' };
120
175
  }
121
176
  } catch {
122
177
  // Documented fallback, reported through `source`.
package/lib/host-tools.js CHANGED
@@ -48,6 +48,31 @@ export const PARAMETERS = {
48
48
  },
49
49
  replace: { type: 'boolean', description: 'Replace the existing value instead of appending (type only).' },
50
50
  settleMs: { type: 'number', description: 'How long to let the app commit its state before the effect is judged (0-2000, default 350).' },
51
+ // ---- R3. Every one of these costs the owner something real, so each description says so: a caller
52
+ // that asks for takeover has to know it moves the pointer and needs the HUD up.
53
+ takeover: {
54
+ type: 'boolean',
55
+ description:
56
+ 'Take the takeover tier: the REAL cursor moves to the action point (so the owner can see where the '
57
+ + 'agent is pointing) and is always restored afterwards, the focus is held until the action ends, '
58
+ + 'and a three-phase HUD is shown with a stop button and a global abort key. Requires the '
59
+ + 'takeoverAllowed setting, otherwise it is refused with takeover_unavailable (it never degrades '
60
+ + 'silently into the quiet tier). Interruptible three ways: HUD button, abort key, host cancellation.',
61
+ },
62
+ takeoverMaxMs: {
63
+ type: 'number',
64
+ description: 'Takeover only: how long the action may hold the cursor/focus (500-60000, default 10000). The HUD counts up to it.',
65
+ },
66
+ keyInput: {
67
+ type: 'string',
68
+ enum: ['none', 'inject'],
69
+ description:
70
+ 'Takeover only: "inject" types the text with synthetic KEYBOARD input (SendInput, Unicode) into the '
71
+ + 'foreground window, for targets with no message door and no UIA pattern (terminals). Requires '
72
+ + 'takeover:true and the keyInjectAllowed setting; the target must be the foreground window or the '
73
+ + 'call is refused with keyinject_unavailable. Never moves the mouse, never clicks. The result '
74
+ + 'reports effect=reported-by-send, not "verified".',
75
+ },
51
76
  };
52
77
 
53
78
  /**
@@ -104,14 +129,19 @@ export function localDefineTool(options) {
104
129
  schema: options.output.schema,
105
130
  render: options.output.render,
106
131
  },
107
- async execute(args) {
132
+ // THE SECOND ARGUMENT IS THE CALL CONTEXT, and dropping it silently disables cancellation: the plugin
133
+ // asks the host for `exec.signal` to abort a takeover in flight, and a wrapper that forwards only
134
+ // `args` makes that code path unreachable -- the abort arrives, nothing is listening, and the call
135
+ // runs to completion. Measured: the first version of this shim did exactly that, and test/signal-test.mjs
136
+ // caught it as "the cancellation was not reported" while everything else looked green.
137
+ async execute(args, exec) {
108
138
  const problems = validateArguments(parameters, args);
109
139
  if (problems.length) {
110
140
  const err = new Error(`${options.name}: ${problems.join('; ')}`);
111
141
  err.name = 'ToolArgsError';
112
142
  throw err;
113
143
  }
114
- return userExecute(args);
144
+ return userExecute(args, exec);
115
145
  },
116
146
  };
117
147
  }
package/lib/index.js CHANGED
@@ -23,6 +23,9 @@
23
23
  // 3. `paused` and `enabled` are server-side gates. They are checked here, before any worker call,
24
24
  // because a prompt-level hint is not a switch (R2.5).
25
25
  import { createConfigSchema, CONFIG_DEFAULTS } from './config.js';
26
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
27
+ import { tmpdir } from 'node:os';
28
+ import { dirname, join } from 'node:path';
26
29
  import { WorkerClient, workerScript } from './engine.js';
27
30
  import { ACTIONS, PARAMETERS, TOOL_NAME, resolveDefineTool } from './host-tools.js';
28
31
  import { evaluateProof } from './proof-window.mjs';
@@ -66,6 +69,13 @@ export function apply(ctx, config = {}) {
66
69
  powershellPath: resolveSetting(config.powershellPath, ''),
67
70
  overlay: resolveSetting(config.overlay, true),
68
71
  logWorkerStderr: resolveSetting(config.logWorkerStderr, false),
72
+ // ---- R3 gates. Both default false: with them off this build behaves exactly like 0.1.6, so an
73
+ // upgrade cannot silently start moving the owner's cursor. The gates live HERE, before the worker,
74
+ // because a prompt-level hint is not a switch (same reasoning as `enabled`/`paused`).
75
+ takeoverAllowed: resolveSetting(config.takeoverAllowed, false) === true,
76
+ keyInjectAllowed: resolveSetting(config.keyInjectAllowed, false) === true,
77
+ takeoverMaxMs: clampNumber(resolveSetting(config.takeoverMaxMs, 10000), 500, 60000, 10000),
78
+ takeoverArmMs: clampNumber(resolveSetting(config.takeoverArmMs, 800), 0, 5000, 800),
69
79
  };
70
80
 
71
81
  const logger = ctx.logger ?? console;
@@ -160,11 +170,55 @@ export function apply(ctx, config = {}) {
160
170
  },
161
171
  });
162
172
 
173
+ /**
174
+ * Wire the host's cancellation into the worker. THE WORKER IS SINGLE-THREADED: while it is inside an
175
+ * action it cannot read a new request, so an 'abort' request alone would be answered only after the
176
+ * action it was meant to stop. The engine therefore polls a latch FILE at the path this writes, and
177
+ * the worker request is sent as well (fire-and-forget) so an idle worker clears its flag too.
178
+ * Two channels because one of them is a local file write that cannot be lost to a wedged loop.
179
+ */
180
+ const activeLatches = new Set();
181
+ const armAbort = (exec) => {
182
+ const signal = exec?.signal;
183
+ if (!signal || typeof signal.addEventListener !== 'function') return () => {};
184
+ const onAbort = () => {
185
+ const pid = client.child?.pid;
186
+ if (!pid) return;
187
+ const latch = abortLatchPath(pid);
188
+ try {
189
+ mkdirSync(dirname(latch), { recursive: true });
190
+ writeFileSync(latch, 'abort', 'utf8');
191
+ activeLatches.add(latch);
192
+ } catch { /* the HUD button and the abort chord remain available */ }
193
+ void client.request({ action: 'abort' }).catch(() => {});
194
+ };
195
+ if (signal.aborted) { onAbort(); return () => {}; }
196
+ signal.addEventListener('abort', onAbort, { once: true });
197
+ return () => signal.removeEventListener('abort', onAbort);
198
+ };
199
+
163
200
  const { defineTool } = resolvedTools;
164
201
 
165
202
  /** Build the worker request for one action. Throws for arguments the action cannot use. */
166
203
  function toRequest(args) {
167
204
  const settleMs = clampSettle(args.settleMs ?? settings.settleMs);
205
+ // The takeover fields are attached ONLY when the caller asked for them AND the gate is open. When a
206
+ // gate is closed the field is STRIPPED, not forwarded: a worker that received takeover:true would be
207
+ // free to act on it, and the safe answer to "the gate is off" is the silent-tier request, which the
208
+ // engine then refuses or serves by its own table (task_26).
209
+ const takeover = args.takeover === true && settings.takeoverAllowed;
210
+ const keyInput = takeover && args.keyInput === 'inject' && settings.keyInjectAllowed ? 'inject' : 'none';
211
+ // takeoverArmMs is the OWNER's patience, not the caller's: it comes from settings and is forwarded so
212
+ // the settings surface actually controls the pre-move cancellation window (a setting that never
213
+ // reaches the engine is a form, not a switch).
214
+ const takeoverFields = takeover
215
+ ? {
216
+ takeover: true,
217
+ takeoverMaxMs: clampNumber(args.takeoverMaxMs, 500, 60000, settings.takeoverMaxMs),
218
+ takeoverArmMs: settings.takeoverArmMs,
219
+ ...(keyInput === 'inject' ? { keyInput } : {}),
220
+ }
221
+ : {};
168
222
  switch (args.action) {
169
223
  case 'windows':
170
224
  return { action: 'windows' };
@@ -174,7 +228,7 @@ export function apply(ctx, config = {}) {
174
228
  requireArg(args, 'hwnd', 'click');
175
229
  requireArg(args, 'x', 'click');
176
230
  requireArg(args, 'y', 'click');
177
- return { action: 'click', hwnd: args.hwnd, x: Math.round(args.x), y: Math.round(args.y), settleMs };
231
+ return { action: 'click', hwnd: args.hwnd, x: Math.round(args.x), y: Math.round(args.y), settleMs, ...takeoverFields };
178
232
  case 'type':
179
233
  requireArg(args, 'hwnd', 'type');
180
234
  if (typeof args.text !== 'string' || args.text.length === 0) {
@@ -184,12 +238,12 @@ export function apply(ctx, config = {}) {
184
238
  }
185
239
  return {
186
240
  action: 'type', hwnd: args.hwnd, text: args.text,
187
- elementName: args.elementName ?? '', replace: args.replace === true, settleMs,
241
+ elementName: args.elementName ?? '', replace: args.replace === true, settleMs, ...takeoverFields,
188
242
  };
189
243
  case 'focus':
190
244
  requireArg(args, 'hwnd', 'focus');
191
245
  requireArg(args, 'elementName', 'focus');
192
- return { action: 'focus', hwnd: args.hwnd, elementName: args.elementName, settleMs };
246
+ return { action: 'focus', hwnd: args.hwnd, elementName: args.elementName, settleMs, ...takeoverFields };
193
247
  default:
194
248
  throw refusal('no_hwnd', `unknown action '${args.action}'`);
195
249
  }
@@ -198,15 +252,20 @@ export function apply(ctx, config = {}) {
198
252
  const tool = defineTool({
199
253
  name: TOOL_NAME,
200
254
  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.',
255
+ 'Drive a Windows window: click at a screen coordinate, write text, or move focus inside ONE named '
256
+ + 'window, choosing the cheapest available door. Two tiers are silent: a classic child window is '
257
+ + 'addressed with window messages (measured: zero foreground changes), and a window that only '
258
+ + 'exposes a UI Automation pattern costs one bounded foreground flash that is reversed once '
259
+ + 'afterwards (measured net return 15-95 ms). A THIRD tier exists and is opt-in: takeover:true may '
260
+ + 'move the real cursor to the action point (always restored), hold the focus until the action ends, '
261
+ + 'and -- with keyInput:"inject" -- type into the foreground target through synthetic keyboard input '
262
+ + 'for windows that have no message door and no accessible pattern (terminals). Takeover is refused '
263
+ + 'unless the owner enabled it, always shows a three-phase HUD with a stop button and a global abort '
264
+ + 'key, is interruptible three ways, and never injects mouse events. Refusals carry a code (no_hwnd, '
265
+ + 'paused, elevated_target, unreachable, terminal_no_door, needs_facts, action_failed, '
266
+ + 'restore_failed, takeover_unavailable, keyinject_unavailable, takeover_aborted) and a reason. '
267
+ + 'Start with action=windows to get an hwnd, or action=status to see what currently holds the '
268
+ + 'foreground.',
210
269
  parameters: PARAMETERS,
211
270
  output: {
212
271
  schema: {
@@ -221,12 +280,26 @@ export function apply(ctx, config = {}) {
221
280
  },
222
281
  render: (_args, value) => [{ type: 'text', text: value.text }],
223
282
  },
224
- async execute(args) {
283
+ async execute(args, exec) {
225
284
  // Server-side gates first: a paused or disabled engine must refuse before it spends a worker
226
285
  // call, and the refusal must name the gate rather than describe a symptom.
227
286
  if (!settings.enabled) {
228
287
  return result(args.action, false, 'paused', 'windows-parallel is switched off in settings; no action was attempted');
229
288
  }
289
+ // ---- R3 gates, BEFORE the worker. A refused takeover costs zero worker requests, which is
290
+ // asserted with a request counter in test/plugin-test.mjs: "the gate is checked" is otherwise
291
+ // indistinguishable from "the gate is checked after the expensive part".
292
+ if (args.takeover === true && !settings.takeoverAllowed) {
293
+ return result(args.action, false, 'takeover_unavailable',
294
+ 'takeoverAllowed is off in settings; the action was refused rather than silently downgraded to the quiet tier. '
295
+ + 'The quiet tier still works without takeover:true' + hwndHint(args));
296
+ }
297
+ if (args.keyInput === 'inject' && (!settings.keyInjectAllowed || args.takeover !== true)) {
298
+ return result(args.action, false, 'keyinject_unavailable',
299
+ args.takeover !== true
300
+ ? 'keyInput:"inject" is only available inside the takeover tier (takeover:true): synthetic keys go to the FOREGROUND window, so without the HUD and the cursor contract it would be typing into whatever is in front'
301
+ : 'keyInjectAllowed is off in settings; no keystroke was sent');
302
+ }
230
303
  // A pre-worker refusal is still a refusal, not a thrown error. The first version of this file
231
304
  // let `toRequest` throw for an empty write, and the caller saw a crashed tool call instead of
232
305
  // `unreachable` -- the exact "refusal became an exception" defect this plugin's own comment
@@ -239,12 +312,15 @@ export function apply(ctx, config = {}) {
239
312
  return result(args.action, false, code, err?.reason ?? String(err?.message ?? err));
240
313
  }
241
314
  let envelope;
315
+ const disarm = request.takeover ? armAbort(exec) : () => {};
242
316
  try {
243
317
  envelope = await client.request(request);
244
318
  } catch (err) {
245
319
  // The worker layer failed (crash, timeout, missing engine). This is not a refusal code: the
246
320
  // engine never got to decide. Say exactly that instead of borrowing a code it does not own.
247
321
  return result(args.action, false, 'action_failed', `engine worker unavailable: ${err.message}`);
322
+ } finally {
323
+ disarm();
248
324
  }
249
325
  if (!envelope.ok) {
250
326
  return result(args.action, false, 'action_failed', `worker error: ${envelope.error ?? 'unknown'}`);
@@ -262,7 +338,14 @@ export function apply(ctx, config = {}) {
262
338
  });
263
339
 
264
340
  ctx.tools.register(tool);
265
- ctx.on?.('dispose', () => { void client.dispose(); });
341
+ ctx.on?.('dispose', () => {
342
+ // A latch that outlives the worker would abort the NEXT worker's first takeover (the path is keyed
343
+ // by pid, so a new process gets a new path -- this is belt and braces, and it keeps %LOCALAPPDATA%
344
+ // tidy for an operator reading it).
345
+ for (const latch of activeLatches) { try { rmSync(latch, { force: true }); } catch { } }
346
+ activeLatches.clear();
347
+ void client.dispose();
348
+ });
266
349
  // No return value. Cordis treats whatever `apply` returns as a disposable effect, so returning the
267
350
  // registered tool is at best ignored and at worst an "Invalid effect" that disables the plugin --
268
351
  // the same class of failure as the async apply, one step further in.
@@ -333,6 +416,10 @@ function format(action, r) {
333
416
  // registered" are claims the user cannot check -- and this machine's desktop already owns
334
417
  // Ctrl+Alt+Q, so the real chord is not the documented one. Silence here would be a lie.
335
418
  bits.push(`overlay=${r.overlayRunning === true ? 'on' : 'off'}`);
419
+ // The takeover surface, on the same principle: the owner must be able to check "is the HUD up and
420
+ // which abort key is real" without inferring it from a successful call.
421
+ bits.push(`hud=${r.hudOn === true ? 'on' : 'off'}`);
422
+ if (r.abortChord) bits.push(`abortChord=${r.abortChord}`);
336
423
  // The overlay's hwnd, so an INDEPENDENT oracle can verify the exact window the product thinks
337
424
  // it is showing. Title-matching alone cannot do this: a leaked overlay from an earlier run is
338
425
  // also titled WpmOverlay, and grading that instead of ours would make the marker arms grade
@@ -349,6 +436,15 @@ function format(action, r) {
349
436
  const code = r.refusal ? String(r.refusal) : '';
350
437
  if (code) {
351
438
  const reason = r.reason ? ` (${r.reason})` : '';
439
+ // A takeover refusal still carries the takeover accounting: "aborted after 12 characters, cursor
440
+ // restored" is the information that makes an interruption harmless instead of alarming.
441
+ if (r.takeover === 'true') {
442
+ const extra = ` [takeover=on cursorRestored=${r.cursorRestored === 'true'} injectedChars=${r.injectedChars ?? 0}`
443
+ + `${r.abortChord ? ` abortChord=${r.abortChord}` : ''}]`;
444
+ return result(action, false, code, `${code}${reason}${extra}`, {
445
+ takeover: 'on', cursorRestored: r.cursorRestored === 'true', injectedChars: r.injectedChars ?? 0,
446
+ });
447
+ }
352
448
  return result(action, false, code, `${code}${reason}`);
353
449
  }
354
450
 
@@ -367,6 +463,19 @@ function format(action, r) {
367
463
  `effect=${r.effect || 'unverified'}`,
368
464
  `focusTaken=${r.focusTaken === 'true' || r.focusTaken === true}`,
369
465
  ];
466
+ // The takeover accounting. Every number here was measured by the engine (cursor read-backs, the
467
+ // injected-character counter, the chord that actually registered) -- nothing in this file infers it.
468
+ if (r.takeover === 'true') {
469
+ bits.push('takeover=on');
470
+ bits.push(`cursorMoved=${r.cursorMoved === 'true'}`);
471
+ bits.push(`cursorRestored=${r.cursorRestored === 'true'}`);
472
+ if (r.takeoverMs !== undefined) bits.push(`takeoverMs=${r.takeoverMs}`);
473
+ if (r.abortChord) bits.push(`abortChord=${r.abortChord}`);
474
+ if (r.keysInjected !== undefined) bits.push(`keysInjected=${r.keysInjected}`);
475
+ bits.push(`injectedChars=${r.injectedChars ?? 0}`);
476
+ if (r.cursorRestoreReason) bits.push(`cursorRestoreReason=${r.cursorRestoreReason}`);
477
+ if (r.takeoverNote) bits.push(`takeoverNote=${r.takeoverNote}`);
478
+ }
370
479
  // THE PROOF. The engine sampled cursor/foreground/focus/last-input-age in TWO windows: a short
371
480
  // pre-action CONTROL (captured while, by construction, nothing was done) and the settle window
372
481
  // AFTER the door call. The judgment is arithmetic and lives in one pure implementation
@@ -385,6 +494,11 @@ function format(action, r) {
385
494
  const proof = evaluateProof(r.proofSamples || [], {
386
495
  control: r.proofControl || [],
387
496
  declaredFlash: r.tier === 'bounded-flash',
497
+ // The takeover tier DELIBERATELY moves the cursor and may hold the foreground; the promise it makes
498
+ // is "nothing was kept", not "nothing was touched". A cursor that was not restored still fails, and
499
+ // does so through the same evaluator instead of a special case here.
500
+ declaredTakeover: r.tier === 'takeover',
501
+ cursorRestored: r.cursorRestored === 'false' ? false : undefined,
388
502
  // The effect travels into the judgment, not just into the text. Without this, "nothing worked"
389
503
  // still reads as proof=pass whenever the desktop happened to stay still (R2 in the plan). One call
390
504
  // is one action, so `actions` is left to batch callers; a channel that reported NOTHING here caps
@@ -400,6 +514,9 @@ function format(action, r) {
400
514
  proof: proof.verdict,
401
515
  proofDimensions: proof.dimensions,
402
516
  effect: r.effect || 'unverified',
517
+ ...(r.takeover === 'true'
518
+ ? { takeover: 'on', cursorRestored: r.cursorRestored === 'true', injectedChars: r.injectedChars ?? 0 }
519
+ : {}),
403
520
  });
404
521
  }
405
522
 
@@ -407,6 +524,24 @@ function truncate(s, n) {
407
524
  return s.length <= n ? s : `${s.slice(0, n - 1)}…`;
408
525
  }
409
526
 
527
+ /** Clamp a possibly-undefined number into [min,max], falling back to `fallback` for non-numbers. */
528
+ function clampNumber(value, min, max, fallback) {
529
+ const n = Number(value);
530
+ if (!Number.isFinite(n)) return fallback;
531
+ return Math.max(min, Math.min(max, Math.round(n)));
532
+ }
533
+
534
+ /** The same latch path the engine computes: %LOCALAPPDATA%\wpm\takeover-abort.<worker pid>. */
535
+ function abortLatchPath(pid) {
536
+ const base = process.env.LOCALAPPDATA || tmpdir();
537
+ return join(base, 'wpm', `takeover-abort.${pid}`);
538
+ }
539
+
540
+ /** A one-line target hint for a pre-worker refusal: the caller can retry without the field. */
541
+ function hwndHint(args) {
542
+ return args.hwnd ? ` (target hwnd=${args.hwnd})` : '';
543
+ }
544
+
410
545
  // Exported for tests: the projection from the five contract actions to this one tool.
411
546
  // `formatResult` is here so the effect dimension can be asserted on the SHIPPED projection, with
412
547
  // hand-authored engine results, without a desktop that has to cooperate.
@@ -64,7 +64,7 @@ export function isHumanGap(b, a, humanGapFactor = 0.6) {
64
64
  * Evaluate one proof window. Pure.
65
65
  * @param {Array} samples the ACTION window
66
66
  * @param {{minSamples?:number, humanGapFactor?:number, control?:Array, declaredFlash?:boolean,
67
- * effect?:string, actions?:Array}} [opts]
67
+ * effect?:string, actions?:Array, declaredTakeover?:boolean, cursorRestored?:boolean}} [opts]
68
68
  * control = the pre-action window (sampled while nothing was done). It cannot excuse motion in the
69
69
  * action window -- the structural rule already handles that -- but it decides whether the
70
70
  * foreground/focus dimensions are evaluable at all.
@@ -145,6 +145,11 @@ export function evaluateProof(samples, opts = {}) {
145
145
 
146
146
  const v = verdictFor(attribution, control, r.length, {
147
147
  declaredFlash: opts.declaredFlash === true,
148
+ // R3 options travel through the same door as declaredFlash: a tier that DECLARES its disturbance is
149
+ // judged by the promise it made, and 'cursorRestored === false' is the one case where a declared
150
+ // move is still a failure (borrowed and not returned).
151
+ declaredTakeover: opts.declaredTakeover === true,
152
+ cursorRestored: opts.cursorRestored === false ? false : undefined,
148
153
  effect: opts.effect,
149
154
  actions: opts.actions,
150
155
  });
@@ -243,20 +248,25 @@ export function verdictFor(attribution, control, sampleCount, opts = {}) {
243
248
  const ux = a.unexplainedCursorMaxDeltaPx ?? 0;
244
249
  // No 'fail' on the cursor dimension: see the header. The idle baseline proved the desktop itself
245
250
  // produces multi-gap unexplained motion, so blaming it on the action is a false red by construction.
246
- dims.cursor = gaps === 0 ? 'pass' : 'inconclusive';
251
+ // The takeover tier is the ONE case where the engine itself moves the pointer, so motion there is
252
+ // DECLARED (informational) rather than unattributable -- and the promise it must keep is the restore,
253
+ // which is checked separately below by cursorRestored.
254
+ dims.cursor = gaps === 0 ? 'pass' : (opts.declaredTakeover ? 'declared' : 'inconclusive');
247
255
 
248
256
  const cFg = control ? (control.unexplainedForegroundSwitches ?? 0) : 0;
249
257
  const cFc = control ? (control.unexplainedFocusChanges ?? 0) : 0;
250
258
  const aFg = a.unexplainedForegroundSwitches ?? 0;
251
259
  const aFc = a.unexplainedFocusChanges ?? 0;
252
260
  if (aFg === 0) dims.foreground = 'pass';
253
- else if (opts.declaredFlash) dims.foreground = 'declared';
261
+ else if (opts.declaredFlash || opts.declaredTakeover) dims.foreground = 'declared';
254
262
  else dims.foreground = control && cFg > 0 ? 'inconclusive' : 'fail';
255
263
  if (aFc === 0) dims.focus = 'pass';
264
+ else if (opts.declaredTakeover) dims.focus = 'declared';
256
265
  else dims.focus = control && cFc > 0 ? 'inconclusive' : 'fail';
257
266
 
258
267
  const parts = [];
259
268
  if (dims.cursor === 'inconclusive') parts.push(`cursor moved ${ux}px in ${gaps} gap(s) with no physical input -- not attributable to the action (the desktop itself does this: idle baseline measured up to 3 gaps/11px with nothing running); the cursor promise is enforced at build time by check-no-cursor-control`);
269
+ if (dims.cursor === 'declared') parts.push(`cursor moved ${ux}px in ${gaps} gap(s), DECLARED by the takeover tier (the pointer was placed on the action point on request) -- the promise that applies is the restore, reported as cursorRestored`);
260
270
  if (dims.foreground === 'declared') parts.push(`foreground switched, but this tier DECLARED a bounded flash (raise then restore) -- the promise is never to KEEP the foreground, owned by the restore table`);
261
271
  if (dims.foreground === 'fail') parts.push(`${aFg} unexplained foreground switch(es) while the control showed the desktop was not switching and this tier did not declare a flash -- ours to explain`);
262
272
  if (dims.foreground === 'inconclusive') parts.push(`${aFg} foreground switch(es), but the desktop was switching on its own during the control too -- unattributable`);
@@ -275,6 +285,17 @@ export function verdictFor(attribution, control, sampleCount, opts = {}) {
275
285
  const reason = parts.length
276
286
  ? parts.join('; ')
277
287
  : `no unexplained cursor motion in ${sampleCount - 1} gaps, no unexplained foreground/focus switches`;
288
+
289
+ // THE ONE HARD RED LINE OF THE TAKEOVER TIER: borrowed and not returned. It outranks every dimension
290
+ // because "the desktop was still" is irrelevant when the pointer is demonstrably somewhere else than
291
+ // where it was handed over. A killswitch that only *usually* puts the pointer back is not a promise.
292
+ if (opts.cursorRestored === false) {
293
+ return {
294
+ verdict: 'fail',
295
+ reason: `光标借了未还 (the takeover moved the cursor and the read-back shows it did not return) -- ${reason}`,
296
+ dimensions: { ...dims, cursor: 'fail' },
297
+ };
298
+ }
278
299
  return { verdict, reason, dimensions: dims };
279
300
  }
280
301
 
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "dsh-windows-parallel-mcp",
3
- "version": "0.1.5",
3
+ "version": "0.2.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest"
7
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.",
8
+ "description": "Drive a Windows window quietly by default and visibly on request: one tool, five actions, a channel decision table that prefers the quiet door, a bounded self-reversing focus flash when only UI Automation can reach the control, and an opt-in takeover tier (HUD mandatory, cursor always restored, keyboard injection only when asked and only for the foreground target). Windows PowerShell 5.1 sidecar, zero install dependencies, no mouse injection.",
9
9
  "keywords": [
10
10
  "deepseek",
11
11
  "deepseek-harness",
@@ -40,6 +40,7 @@
40
40
  "src/engine/",
41
41
  "src/schema/",
42
42
  "docs/refusals.md",
43
+ "docs/takeover.md",
43
44
  "CHANGELOG.md",
44
45
  "cordis.patch.yml",
45
46
  "dsh.plugin.json",
@@ -68,6 +69,10 @@
68
69
  "test": "node scripts/check.mjs && node test/plugin-test.mjs && node test/worker-smoke.mjs",
69
70
  "test:decide": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File test/decide-test.ps1",
70
71
  "test:refusals": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File test/refusals-test.ps1",
72
+ "test:hud": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -STA -File test/hud-test.ps1",
73
+ "test:takeover": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -STA -File test/takeover-test.ps1",
74
+ "test:keyinject": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -STA -File test/keyinject-test.ps1",
75
+ "smoke:installed": "node test/smoke-installed.mjs",
71
76
  "prepack": "node scripts/check-pack.mjs",
72
77
  "verify:install": "node scripts/verify-install.mjs"
73
78
  }