dsh-windows-parallel-mcp 0.4.1 → 0.6.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/host-tools.js CHANGED
@@ -18,8 +18,8 @@
18
18
  // that the caller can branch on the code and read the next step.
19
19
  export const TOOL_NAME = 'wpm';
20
20
 
21
- /** The five actions, in the order the contract lists them. */
22
- export const ACTIONS = ['windows', 'click', 'type', 'focus', 'status'];
21
+ /** The eight actions, in the order the contract lists them. */
22
+ export const ACTIONS = ['windows', 'click', 'type', 'focus', 'status', 'snapshot', 'screenshot', 'preview'];
23
23
 
24
24
  /**
25
25
  * One field of the simplified parameter spec -- the shape the host's `defineTool` consumes and the
@@ -54,7 +54,10 @@ export const PARAMETERS = {
54
54
  'windows: list live windows that can be driven (hwnd, title, class, pid, rect). '
55
55
  + 'status: read the focus table (foreground window, focused control, last human input age, paused flag). '
56
56
  + 'click: click at a screen coordinate inside the target. type: write text into the target. '
57
- + 'focus: move keyboard focus to a named control inside the target.',
57
+ + 'focus: move keyboard focus to a named control inside the target. '
58
+ + 'snapshot: read the accessibility tree as a numbered element table (labels you can act on). '
59
+ + 'screenshot: capture the target rect to a PNG and return its coordinate mapping as data. '
60
+ + 'preview: draw the marker at a point and report the element under it, without clicking.',
58
61
  },
59
62
  hwnd: {
60
63
  type: 'string',
@@ -70,6 +73,21 @@ export const PARAMETERS = {
70
73
  + 'because a window message cannot address "the control called X".',
71
74
  },
72
75
  replace: { type: 'boolean', description: 'Replace the existing value instead of appending (type only).' },
76
+ // ---- 0.6.0: where the caret goes, and what the engine reads back afterwards ------------------
77
+ // The description names the syscall because the parameter is a syscall argument, and it names the
78
+ // measured exception because '-1 means the end' is a documentation sentence that WinForms EDIT does
79
+ // not honour (findings 8.2). A caller reading this should be able to predict the result exactly.
80
+ caretPosition: {
81
+ type: 'string',
82
+ enum: ['idle', 'start', 'end'],
83
+ description:
84
+ 'type only, message door: where the caret sits before the characters are sent. "idle" (default) touches nothing -- ' +
85
+ 'the caret is where the control left it, which for a never-focused field is position 0 (measured), so "idle" is not "start". ' +
86
+ '"start" is EM_SETSEL(0,0); "end" is EM_SETSEL(len,len) with len read from the control, because the documented -1 form is a no-op ' +
87
+ 'on WinForms EDIT. On a buffer containing newlines the numeric end can land inside the text, so the result reports the requested ' +
88
+ 'and the applied pair (caret=end asked=6 applied=4,4) and the readback decides. The UIA value channel replaces the whole value and ' +
89
+ 'has no caret to move -- it answers caretIgnored=value-pattern instead of pretending it honoured this.',
90
+ },
73
91
  settleMs: { type: 'number', description: 'How long to let the app commit its state before the effect is judged (0-2000, default 350).' },
74
92
  // ---- R3. Every one of these costs the owner something real, so each description says so: a caller
75
93
  // that asks for takeover has to know it moves the pointer and needs the HUD up.
@@ -96,6 +114,61 @@ export const PARAMETERS = {
96
114
  + 'call is refused with keyinject_unavailable. Never moves the mouse, never clicks. The result '
97
115
  + 'reports effect=reported-by-send, not "verified".',
98
116
  },
117
+ // ---- 0.5.0: the frame / label / image-coordinate surface -----------------------------------
118
+ // Every description below says what the field costs or what it refuses, because each one exists to
119
+ // remove a way for the caller to silently act on the wrong thing.
120
+ label: {
121
+ type: 'number',
122
+ description:
123
+ 'Element number from action=snapshot (click/type/focus). The label is resolved back to the UIA '
124
+ + 'ELEMENT by RuntimeId, so the action still takes the silent pattern path instead of degrading to '
125
+ + 'a coordinate click. For click, x/y stay required and must fall inside the labelled element, so '
126
+ + '"the point is the contract" remains true.',
127
+ },
128
+ snapId: {
129
+ type: 'string',
130
+ description:
131
+ 'The snapId the label came from. A label whose snapId has been superseded is refused with '
132
+ + 'stale_ref: element numbers only mean something in the frame that printed them.',
133
+ },
134
+ space: {
135
+ type: 'string',
136
+ enum: ['screen', 'image'],
137
+ description:
138
+ 'Coordinate space of click x/y. "screen" (default) is physical screen pixels. "image" means image '
139
+ + 'pixels from the screenshot named by shotId -- the ENGINE converts them, so the caller never '
140
+ + 'multiplies a scale factor; the point-ownership assertion still runs after conversion.',
141
+ },
142
+ shotId: {
143
+ type: 'string',
144
+ description:
145
+ 'The shotId from action=screenshot. Required when space="image" (refused before any worker call); '
146
+ + 'an id that was already cleaned up by the retention policy is refused with stale_ref.',
147
+ },
148
+ maxElements: {
149
+ type: 'number',
150
+ description: 'snapshot only: hard cap on returned elements (1-5000, default 300). The text then says "truncated at N of M" and truncated is true.',
151
+ },
152
+ interactableOnly: {
153
+ type: 'boolean',
154
+ description: 'snapshot only (default true): return only elements exposing a usable UIA pattern. false returns the whole visible tree.',
155
+ },
156
+ sinceSnapId: {
157
+ type: 'string',
158
+ description: 'snapshot only: return an added/removed/changed diff against this earlier snapId instead of the whole table. An unchanged tree yields an empty delta.',
159
+ },
160
+ intent: {
161
+ type: 'string',
162
+ description: 'snapshot only: what this frame is FOR. It travels with the frame so a deciding subagent can answer with a single label.',
163
+ },
164
+ fullScreen: {
165
+ type: 'boolean',
166
+ description: 'screenshot only (default false): capture the whole virtual screen instead of one window. Off by default so the owner\'s desktop is never captured silently.',
167
+ },
168
+ maxWidth: {
169
+ type: 'number',
170
+ description: 'screenshot only: downscale the saved image to at most this width (0 = no scaling, default). Scaling changes the coordinate system, so it must be asked for explicitly and is reported as scale.',
171
+ },
99
172
  };
100
173
 
101
174
  /**
package/lib/index.js CHANGED
@@ -7,13 +7,15 @@
7
7
  // row, no second Node process — the tool is registered here and the only child process is the
8
8
  // PowerShell worker, which the engine already needed in either form.
9
9
  //
10
- // WHY ONE TOOL AND NOT FIVE. src/schema/tools.json names five actions as the contract surface. The
10
+ // WHY ONE TOOL AND NOT FIVE. src/schema/tools.json names eight actions as the contract surface. The
11
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
12
+ // discriminator, because every registered tool is resident schema on every turn — eight entries
13
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
14
+ // preserved exactly: same eight actions, same fourteen refusal codes, same required arguments. The
15
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".
16
+ // cannot quietly become "we support seven actions". 0.5.0's three new actions went into the SAME one
17
+ // tool for the same reason the earlier five did: the token argument does not weaken when the surface
18
+ // grows.
17
19
  //
18
20
  // THE THREE THINGS THIS FILE MUST GET RIGHT, each of which would look like a working plugin while
19
21
  // being wrong:
@@ -66,6 +68,9 @@ import { evaluateProof } from './proof-window.mjs';
66
68
  * @property {boolean} keyInjectAllowed
67
69
  * @property {number} takeoverMaxMs
68
70
  * @property {number} takeoverArmMs
71
+ * @property {number} snapshotMaxElements
72
+ * @property {number} screenshotMaxWidth
73
+ * @property {number} shotsKeep
69
74
  */
70
75
 
71
76
  /**
@@ -144,6 +149,12 @@ export function apply(ctx, config = {}) {
144
149
  keyInjectAllowed: resolveSetting(config.keyInjectAllowed, false) === true,
145
150
  takeoverMaxMs: clampNumber(resolveSetting(config.takeoverMaxMs, 10000), 500, 60000, 10000),
146
151
  takeoverArmMs: clampNumber(resolveSetting(config.takeoverArmMs, 800), 0, 5000, 800),
152
+ // ---- 0.5.0 read-path settings. Forwarded, never silently clamped on the caller's behalf: the
153
+ // engine is the one that reports what it actually used (maxElements/shotsKeep ride back on the
154
+ // result), so "the setting took" is observable rather than assumed.
155
+ snapshotMaxElements: clampNumber(resolveSetting(config.snapshotMaxElements, 300), 1, 5000, 300),
156
+ screenshotMaxWidth: clampNumber(resolveSetting(config.screenshotMaxWidth, 0), 0, 7680, 0),
157
+ shotsKeep: clampNumber(resolveSetting(config.shotsKeep, 10), 1, 200, 10),
147
158
  };
148
159
 
149
160
  const logger = ctx.logger ?? console;
@@ -296,6 +307,41 @@ export function apply(ctx, config = {}) {
296
307
  return { action: 'windows' };
297
308
  case 'status':
298
309
  return { action: 'status' };
310
+ case 'snapshot':
311
+ // A READ. maxElements is the SETTING unless the caller asked for a specific cap, and
312
+ // interactableOnly defaults ON because the frame exists to be decided on, not to be dumped.
313
+ requireArg(args, 'hwnd', 'snapshot');
314
+ return {
315
+ action: 'snapshot',
316
+ hwnd: args.hwnd,
317
+ maxElements: clampNumber(args.maxElements, 1, 5000, settings.snapshotMaxElements),
318
+ interactableOnly: args.interactableOnly !== false,
319
+ sinceSnapId: typeof args.sinceSnapId === 'string' ? args.sinceSnapId : '',
320
+ intent: typeof args.intent === 'string' ? args.intent : '',
321
+ };
322
+ case 'screenshot':
323
+ // fullScreen is the ONLY way to capture without naming a window, and it must be asked for:
324
+ // silently capturing the owner's whole desktop would be exactly the overreach this product
325
+ // refuses elsewhere. A non-fullscreen capture with no hwnd is refused here, before the worker.
326
+ if (args.fullScreen !== true) requireArg(args, 'hwnd', 'screenshot');
327
+ return {
328
+ action: 'screenshot',
329
+ hwnd: args.fullScreen === true ? (args.hwnd ?? '') : args.hwnd,
330
+ fullScreen: args.fullScreen === true,
331
+ maxWidth: clampNumber(args.maxWidth, 0, 7680, settings.screenshotMaxWidth),
332
+ shotsKeep: settings.shotsKeep,
333
+ };
334
+ case 'preview':
335
+ // Silent by construction: no click, no focus, no input queue entry. The engine draws the
336
+ // marker and answers with the element UNDER the point as text.
337
+ requireArg(args, 'hwnd', 'preview');
338
+ requireArg(args, 'x', 'preview');
339
+ requireArg(args, 'y', 'preview');
340
+ return {
341
+ action: 'preview', hwnd: args.hwnd,
342
+ x: Math.round(/** @type {number} */ (args.x)),
343
+ y: Math.round(/** @type {number} */ (args.y)),
344
+ };
299
345
  case 'click':
300
346
  requireArg(args, 'hwnd', 'click');
301
347
  requireArg(args, 'x', 'click');
@@ -305,7 +351,23 @@ export function apply(ctx, config = {}) {
305
351
  // thing that narrows them. A checker cannot see through a separate function's throw, so this
306
352
  // is where the guarantee is recorded -- not a suppression, since requireArg throws for both
307
353
  // undefined and null before this line is reached.
308
- return { action: 'click', hwnd: args.hwnd, x: Math.round(/** @type {number} */ (args.x)), y: Math.round(/** @type {number} */ (args.y)), settleMs, ...takeoverFields };
354
+ //
355
+ // THE COORDINATE SPACE IS EXPLICIT. 'image' without a shotId is refused HERE, before any worker
356
+ // request: image pixels only mean something relative to a capture, and reinterpreting them as
357
+ // screen pixels would click somewhere plausibly wrong -- the exact failure mode `stale_ref`
358
+ // exists for. A label rides along with its snapId so the engine can resolve the ELEMENT.
359
+ const space = args.space === 'image' ? 'image' : 'screen';
360
+ if (space === 'image' && (typeof args.shotId !== 'string' || args.shotId === '')) {
361
+ throw refusal('stale_ref', 'space:"image" needs the shotId of the screenshot whose pixels you are pointing at; no worker request was made and no coordinate was reinterpreted');
362
+ }
363
+ return {
364
+ action: 'click', hwnd: args.hwnd, x: Math.round(/** @type {number} */ (args.x)), y: Math.round(/** @type {number} */ (args.y)), settleMs,
365
+ ...(space === 'image' ? { space: 'image', shotId: args.shotId } : {}),
366
+ ...(typeof args.label === 'number' && args.label > 0
367
+ ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
368
+ : {}),
369
+ ...takeoverFields,
370
+ };
309
371
  case 'type':
310
372
  requireArg(args, 'hwnd', 'type');
311
373
  if (typeof args.text !== 'string' || args.text.length === 0) {
@@ -315,12 +377,29 @@ export function apply(ctx, config = {}) {
315
377
  }
316
378
  return {
317
379
  action: 'type', hwnd: args.hwnd, text: args.text,
318
- elementName: args.elementName ?? '', replace: args.replace === true, settleMs, ...takeoverFields,
380
+ elementName: args.elementName ?? '', replace: args.replace === true, settleMs,
381
+ // Forwarded only when it is one of the three values the engine declares; anything else is
382
+ // dropped to the default HERE rather than passed on, because the engine's ValidateSet would
383
+ // turn a model's typo into `action_failed` -- and a schema the host already validates against
384
+ // (validateArguments, plus the registered enum) means a wrong value here did not come from a
385
+ // validated call. The drop is logged into the result by the engine's own caret= field, which
386
+ // always reports what was applied.
387
+ caretPosition: args.caretPosition === 'start' || args.caretPosition === 'end' ? args.caretPosition : 'idle',
388
+ ...(typeof args.label === 'number' && args.label > 0
389
+ ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
390
+ : {}),
391
+ ...takeoverFields,
319
392
  };
320
393
  case 'focus':
321
394
  requireArg(args, 'hwnd', 'focus');
322
- requireArg(args, 'elementName', 'focus');
323
- return { action: 'focus', hwnd: args.hwnd, elementName: args.elementName, settleMs, ...takeoverFields };
395
+ if ((typeof args.label !== 'number' || args.label <= 0)) requireArg(args, 'elementName', 'focus');
396
+ return {
397
+ action: 'focus', hwnd: args.hwnd, elementName: args.elementName ?? '', settleMs,
398
+ ...(typeof args.label === 'number' && args.label > 0
399
+ ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
400
+ : {}),
401
+ ...takeoverFields,
402
+ };
324
403
  default:
325
404
  throw refusal('no_hwnd', `unknown action '${args.action}'`);
326
405
  }
@@ -338,11 +417,18 @@ export function apply(ctx, config = {}) {
338
417
  + 'and -- with keyInput:"inject" -- type into the foreground target through synthetic keyboard input '
339
418
  + 'for windows that have no message door and no accessible pattern (terminals). Takeover is refused '
340
419
  + 'unless the owner enabled it, always shows a three-phase HUD with a stop button and a global abort '
341
- + 'key, is interruptible three ways, and never injects mouse events. Refusals carry a code (no_hwnd, '
342
- + 'paused, elevated_target, unreachable, terminal_no_door, needs_facts, action_failed, '
343
- + 'restore_failed, takeover_unavailable, keyinject_unavailable, takeover_aborted) and a reason. '
344
- + 'Start with action=windows to get an hwnd, or action=status to see what currently holds the '
345
- + 'foreground.',
420
+ + 'key, is interruptible three ways, and never injects mouse events. '
421
+ + 'THREE READ ACTIONS make the target legible without guessing: snapshot returns a NUMBERED element '
422
+ + 'table (a continuous `label`, control type, name, automation id, rect, patterns) that click/type/'
423
+ + 'focus accept as `label`+`snapId`; screenshot writes the window rect to a PNG and returns '
424
+ + 'screenRect/imageSize/scale/identity/frame as data so image coordinates can be handed straight '
425
+ + 'back to click with space:"image" (the engine converts, the caller never multiplies); preview '
426
+ + 'draws the marker at a point and reports, as TEXT, the element under it -- a reviewable click that '
427
+ + 'needs no picture. Refusals carry a code (no_hwnd, '
428
+ + 'paused, elevated_target, unreachable, uia_tree_empty, uia_probe_failed, terminal_no_door, needs_facts, action_failed, '
429
+ + 'restore_failed, takeover_unavailable, keyinject_unavailable, takeover_aborted, stale_ref) and a reason. '
430
+ + 'Start with action=windows to get an hwnd, action=snapshot to read a frame, or action=status to see '
431
+ + 'what currently holds the foreground.',
346
432
  parameters: PARAMETERS,
347
433
  output: {
348
434
  schema: {
@@ -424,7 +510,12 @@ export function apply(ctx, config = {}) {
424
510
  // letting a refusal start the overlay would mean a dead hwnd silently spawns a WPF window.
425
511
  const r = envelope.result;
426
512
  if (request.action === 'click' && r && r.ok !== false && !r.refusal) {
427
- markPoint(request.x, request.y);
513
+ // With space:'image' the request coordinates are IMAGE pixels; the engine reports the screen
514
+ // point it actually converted to, and the marker must be drawn THERE. Drawing it at the image
515
+ // pixel would put the visible cursor somewhere other than where the click landed -- a marker
516
+ // that lies is worse than no marker, because the README sells it as the point that was acted on.
517
+ const screen = request.space === 'image' ? parsePoint(r.screenPoint) : null;
518
+ markPoint(screen ? screen.x : request.x, screen ? screen.y : request.y);
428
519
  }
429
520
  return format(args.action, envelope.result);
430
521
  },
@@ -548,6 +639,11 @@ function format(action, r) {
548
639
  bits.push(`pauseHotkey=${r.hotkeyRegistered === true ? (r.hotkeyLabel || 'registered') : 'unavailable'}`);
549
640
  if (r.overlayReason) bits.push(`overlayNote=${r.overlayReason}`);
550
641
  if (r.pauseReason) bits.push(`pauseReason=${r.pauseReason}`);
642
+ // The DPI stance is a FACT the read paths depend on: rects and captured pixels are physical only
643
+ // while this process is per-monitor DPI aware. Reporting it here is what keeps a future deletion of
644
+ // the setter from turning into a silent half-scale coordinate system (the marker already proved
645
+ // that failure mode: 470,410 acted on at 303,263 on this 150% display).
646
+ bits.push(`dpiAware=${r.dpiAware === true}`);
551
647
  if (r.stance) bits.push(`stance: ${r.stance}`);
552
648
  return result(action, true, '', bits.join('\n'));
553
649
  }
@@ -572,14 +668,28 @@ function format(action, r) {
572
668
  return result(action, false, code, `${code}${reason}`);
573
669
  }
574
670
 
671
+ // ---- 0.5.0 READ RESULTS ---------------------------------------------------------------------
672
+ // These three have no channel, no tier and no proof window: there is no action to prove. Rendering
673
+ // happens HERE (not in the engine) for the same reason every other action's text does -- one place
674
+ // owns "what the model reads", and the engine stays a JSON protocol.
675
+ if (action === 'snapshot') return formatSnapshot(r);
676
+ if (action === 'screenshot') return formatScreenshot(r);
677
+ if (action === 'preview') return formatPreview(r);
678
+
575
679
  // WHO REPORTED THE SUCCESS. The engine sets `effect` when a channel call RETURNS without throwing;
576
- // this file never upgrades it, and the three values are not degrees of confidence in the app -- they
577
- // name who is speaking (README's table states the same three lines, keep them in step):
680
+ // this file never upgrades it, and the four values are not degrees of confidence in the app -- they
681
+ // name who is speaking (README's table states the same four lines, keep them in step):
578
682
  // unverified no channel reported success at all;
579
683
  // reported-by-send the window message was DELIVERED -- nothing here proves the target app
580
684
  // processed it;
581
- // reported-by-pattern the UIA pattern call RETURNED -- nothing here proves the interface changed.
582
- // Read as "who says it worked", never as "the application's state is confirmed".
685
+ // reported-by-pattern the UIA pattern call RETURNED -- nothing here proves the interface changed;
686
+ // readback-verified 0.6.0: the value was READ BACK after the settle window and equals the value
687
+ // predicted from measurements the CONTROL reported. This is the only value that
688
+ // is about the application rather than about the call, and the engine grants it
689
+ // only on an exact match -- a masked field reports readback=unavailable and an
690
+ // app that reformatted the input reports readbackMismatch=true, neither of which
691
+ // is an upgrade (findings 8.1/8.2).
692
+ // Read the first three as "who says it worked", never as "the application's state is confirmed".
583
693
  const bits = [
584
694
  `${action} ok`,
585
695
  `channel=${r.channel || '?'}`,
@@ -638,6 +748,12 @@ function format(action, r) {
638
748
  proof: proof.verdict,
639
749
  proofDimensions: proof.dimensions,
640
750
  effect: r.effect || 'unverified',
751
+ // A converted point travels back with the result so the caller can check the arithmetic it never
752
+ // performed. `screenPoint` is the fact the marker is drawn from, too: with space:'image' the
753
+ // request's own x/y are image pixels and would put the visible marker in the wrong place.
754
+ ...(r.coordSpace === 'image'
755
+ ? { coordSpace: 'image', shotId: r.shotId, imagePoint: r.imagePoint, screenPoint: r.screenPoint, scale: r.scale }
756
+ : {}),
641
757
  ...(r.takeover === 'true'
642
758
  ? { takeover: 'on', cursorRestored: r.cursorRestored === 'true', injectedChars: r.injectedChars ?? 0 }
643
759
  : {}),
@@ -649,6 +765,167 @@ function truncate(s, n) {
649
765
  return s.length <= n ? s : `${s.slice(0, n - 1)}…`;
650
766
  }
651
767
 
768
+ /**
769
+ * One element row of a snapshot frame. The format is the contract the caller reasons on, so it is
770
+ * fixed here: `label ControlType "Name" [AutomationId] rect=l,t,r,b patterns=...`. The label is
771
+ * what a deciding side answers with; the rect is in PHYSICAL screen pixels, in the same space as
772
+ * screenRect, which is what makes `space:"image"` conversion possible without a second coordinate table.
773
+ * @param {any} e @returns {string}
774
+ */
775
+ function elementLine(e) {
776
+ const rc = e?.rect ?? {};
777
+ const pats = Array.isArray(e?.patterns) ? e.patterns : [];
778
+ return `${e?.label ?? '?'} ${e?.controlType ?? '?'} "${e?.name ?? ''}" [${e?.automationId ?? ''}] `
779
+ + `rect=${rc.left ?? '?'},${rc.top ?? '?'},${rc.right ?? '?'},${rc.bottom ?? '?'} `
780
+ + `patterns=${pats.length ? pats.join('|') : 'none'}`;
781
+ }
782
+
783
+ /**
784
+ * Render a snapshot frame.
785
+ *
786
+ * WHY THE DELTA IS A FIRST-CLASS FORM. Repeating an unchanged 70-row table between two steps is the
787
+ * dominant token cost of a multi-step flow, and it is pure noise: nothing in it changed. With
788
+ * `sinceSnapId` the answer is "no changes" plus the three lists that DID move. The full table stays
789
+ * available -- this is an option, not a replacement.
790
+ * @param {any} r @returns {Record<string, any>}
791
+ */
792
+ function formatSnapshot(r) {
793
+ const rows = Array.isArray(r.elements) ? r.elements : [];
794
+ const count = Number.isFinite(r.count) ? Number(r.count) : rows.length;
795
+ const total = Number.isFinite(r.total) ? Number(r.total) : count;
796
+ const truncated = r.truncated === true || r.truncated === 'true';
797
+ const delta = r.delta && typeof r.delta === 'object' ? r.delta : null;
798
+ const added = Array.isArray(delta?.added) ? delta.added : [];
799
+ const removed = Array.isArray(delta?.removed) ? delta.removed : [];
800
+ const changed = Array.isArray(delta?.changed) ? delta.changed : [];
801
+
802
+ const head = `snapshot ok: ${count} element(s)`
803
+ + (truncated ? ` (truncated at ${count} of ${total})` : '')
804
+ + (delta ? ` (delta vs ${delta.sinceSnapId}: +${added.length} -${removed.length} ~${changed.length})` : '');
805
+ const meta = [`snapId=${r.snapId || '?'}`, `frame=${r.frame || '?'}`, `frameCheck=${r.frameCheck || '?'}`, `total=${total}`];
806
+ if (r.frameInset && typeof r.frameInset === 'object') {
807
+ meta.push(`frameInset=${r.frameInset.left ?? '?'},${r.frameInset.top ?? '?'},${r.frameInset.right ?? '?'},${r.frameInset.bottom ?? '?'}`);
808
+ }
809
+ if (Number.isFinite(r.outsideFrame) && Number(r.outsideFrame) > 0) {
810
+ meta.push(`outsideFrame=${r.outsideFrame}`);
811
+ }
812
+ if (r.intent) meta.push(`intent=${r.intent}`);
813
+ const lines = [head, meta.join(' ')];
814
+
815
+ if (delta) {
816
+ if (added.length === 0 && removed.length === 0 && changed.length === 0) {
817
+ lines.push(`no changes since ${delta.sinceSnapId}`);
818
+ } else {
819
+ for (const a of added) lines.push(` + ${elementLine(a)}`);
820
+ for (const m of removed) lines.push(` - ${elementLine(m)}`);
821
+ for (const c of changed) lines.push(` ~ ${elementLine(c)} changed=${(Array.isArray(c.changed) ? c.changed : []).join(',')}`);
822
+ }
823
+ } else if (count === 0) {
824
+ // A REAL ANSWER, said out loud. This deliberately does NOT reuse uia_tree_empty: that code means
825
+ // "UI Automation is switched off in the application" and its next step is relaunching the app.
826
+ // Zero visible elements on a window that answers fine (measured: Clash, Everything) has no such
827
+ // next step, so inventing one would be the canned message this product refuses.
828
+ lines.push('0 element(s) is a real state: this window exposes no visible element to UI Automation right now. '
829
+ + 'It is not uia_tree_empty (that code is about the application disabling accessibility) and it is not a failure.');
830
+ } else {
831
+ for (const e of rows) lines.push(elementLine(e));
832
+ }
833
+ if (r.frame === 'win32') {
834
+ lines.push('note: frame=win32 -- DWM EXTENDED_FRAME_BOUNDS was unavailable, so this frame came from GetWindowRect and includes the invisible resize shadow. '
835
+ + 'The frame check above passed (it compares the frame against the window rect the tree reports), but the capture and the labels are both 8px larger than the visible window edge.');
836
+ }
837
+ if (r.frameCheck === 'unknown') {
838
+ lines.push('note: frameCheck=unknown -- the accessibility tree would not report its root rect, so the frame could not be cross-checked. Labels are still in physical screen pixels; treat an edge-of-window label with suspicion.');
839
+ }
840
+ if (Number(r.outsideFrame) > 0) {
841
+ lines.push(`note: ${r.outsideFrame} element(s) were excluded because their rect does not overlap the captured frame; a label you cannot point at inside the capture would be a trap, so they are counted here instead of numbered.`);
842
+ }
843
+ return result('snapshot', true, '', lines.join('\n'), {
844
+ snapId: r.snapId, elements: rows, count, total, truncated, frameCheck: r.frameCheck, intent: r.intent ?? '',
845
+ // The delta travels structurally too: a caller that branches on "did anything move" must not have
846
+ // to parse the text, and the counts are the same numbers the head line prints.
847
+ ...(delta ? { delta } : {}),
848
+ ...(r.frameInset ? { frameInset: r.frameInset } : {}),
849
+ ...(Number.isFinite(r.outsideFrame) ? { outsideFrame: Number(r.outsideFrame) } : {}),
850
+ });
851
+ }
852
+
853
+ /**
854
+ * Render a screenshot: the mapping is the product, the file is the delivery.
855
+ * @param {any} r @returns {Record<string, any>}
856
+ */
857
+ function formatScreenshot(r) {
858
+ const rect = r.screenRect && typeof r.screenRect === 'object' ? r.screenRect : {};
859
+ const size = r.imageSize && typeof r.imageSize === 'object' ? r.imageSize : {};
860
+ const scale = typeof r.scale === 'number' ? r.scale : 1;
861
+ const identity = r.identity === true || r.identity === 'true';
862
+ const dpiAware = r.dpiAware === true || r.dpiAware === 'true';
863
+ const lines = [
864
+ `screenshot ok: ${size.width ?? '?'}x${size.height ?? '?'} px (scale=${scale} identity=${identity}) frame=${r.frame || '?'} captureBackend=${r.captureBackend || '?'} dpiAware=${dpiAware}`,
865
+ `file=${r.file || '?'}`,
866
+ `shotId=${r.shotId || '?'}`,
867
+ `screenRect=${rect.left ?? '?'},${rect.top ?? '?'},${rect.right ?? '?'},${rect.bottom ?? '?'} `
868
+ + `imageSize=${size.width ?? '?'}x${size.height ?? '?'} bytes=${r.bytes ?? '?'} shotsKeep=${r.shotsKeep ?? '?'} latencyMs=${r.latencyMs ?? '?'}`,
869
+ 'mapping: screenX = screenRect.left + round(imageX / scale); screenY = screenRect.top + round(imageY / scale). '
870
+ + `The ENGINE applies this when a click passes space:"image" with shotId=${r.shotId || '?'}; do not multiply it yourself.`,
871
+ ];
872
+ // 0.6.0-B. The cheap path is BitBlt and the fallback is Graphics.CopyFromScreen; they are measured
873
+ // equivalent on a still scene (identical size, identical PNG bytes, 0 per-channel difference over
874
+ // 17388 sample points) and they are NOT the same call, so which one ran is part of the result rather
875
+ // than an implementation detail. A note appears only when the fast path was refused.
876
+ if (!r.captureBackend) lines.push('note: captureBackend was not reported by the engine -- this result predates 0.6.0 or the engine is out of step with this build.');
877
+ if (r.captureNote) lines.push(`note: ${r.captureNote} -- the picture came from Graphics.CopyFromScreen this time.`);
878
+ if (identity) {
879
+ lines.push('identity=true means the image was NOT resampled: image pixels and screen pixels differ only by the rect origin.');
880
+ }
881
+ if (r.frame === 'win32') {
882
+ lines.push('note: frame=win32 -- DWM EXTENDED_FRAME_BOUNDS was unavailable, so screenRect came from GetWindowRect and includes the invisible shadow. '
883
+ + 'Coordinates stay consistent with THIS capture, but a click at the very edge can land on the shadow rather than the client area.');
884
+ }
885
+ return result('screenshot', true, '', lines.join('\n'), {
886
+ shotId: r.shotId, file: r.file, screenRect: rect, imageSize: size,
887
+ scale, identity, frame: r.frame, captureBackend: r.captureBackend, dpiAware,
888
+ });
889
+ }
890
+
891
+ /**
892
+ * Render a preview. The report is text on purpose: "what is under that point" is answered by the OS,
893
+ * so confirming a point never depends on the model's reading of a picture.
894
+ * @param {any} r @returns {Record<string, any>}
895
+ */
896
+ function formatPreview(r) {
897
+ const x = r.previewX ?? '?';
898
+ const y = r.previewY ?? '?';
899
+ const atPoint = r.previewAtPoint === true || r.previewAtPoint === 'true';
900
+ const head = atPoint && r.previewControlType
901
+ ? `preview: would click ${x},${y} -> ${r.previewControlType} "${r.previewName || ''}"`
902
+ + (r.previewAutomationId ? ` [${r.previewAutomationId}]` : '')
903
+ : `preview: would click ${x},${y} -> no element is exposed at that point`;
904
+ const rect = r.previewRect && typeof r.previewRect === 'object' ? r.previewRect : {};
905
+ const lines = [
906
+ head,
907
+ `rect=${rect.left ?? '?'},${rect.top ?? '?'},${rect.right ?? '?'},${rect.bottom ?? '?'}`,
908
+ `marker=${r.markerPlaced === true || r.markerPlaced === 'true' ? 'placed' : 'unavailable'}${r.markerReason ? ` (${r.markerReason})` : ''}`,
909
+ ];
910
+ if (r.previewReason) lines.push(`reason: ${r.previewReason}`);
911
+ lines.push('no click was sent: a preview writes no input-queue entry, takes no focus, and produces no proof window');
912
+ return result('preview', true, '', lines.join('\n'), {
913
+ preview: {
914
+ x, y,
915
+ name: r.previewName ?? '', controlType: r.previewControlType ?? '', automationId: r.previewAutomationId ?? '',
916
+ },
917
+ });
918
+ }
919
+
920
+ /** Parse an engine-emitted "x,y" point. Returns null for anything else rather than guessing 0,0. */
921
+ /** @param {any} s @returns {{x: number, y: number}|null} */
922
+ function parsePoint(s) {
923
+ if (typeof s !== 'string') return null;
924
+ const m = s.match(/^(-?\d+),(-?\d+)$/);
925
+ if (!m) return null;
926
+ return { x: Number(m[1]), y: Number(m[2]) };
927
+ }
928
+
652
929
  /** Clamp a possibly-undefined number into [min,max], falling back to `fallback` for non-numbers. */
653
930
  /** @param {any} value @param {number} min @param {number} max @param {number} fallback @returns {number} */
654
931
  function clampNumber(value, min, max, fallback) {
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "dsh-windows-parallel-mcp",
3
- "version": "0.4.1",
3
+ "version": "0.6.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest",
7
7
  "registry": "https://registry.npmjs.org/"
8
8
  },
9
- "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
+ "description": "Drive a Windows window quietly by default and visibly on request: one tool, eight actions (windows, status, click, type, focus, snapshot, screenshot, preview), a channel decision table that prefers the quiet door, a bounded self-reversing focus flash when only UI Automation can reach the control, an opt-in takeover tier (HUD mandatory, cursor always restored, keyboard injection only when asked and only for the foreground target), and a read surface that hands the model a numbered element frame plus screenshot coordinates as data so it never multiplies a scale factor. Since 0.6.0 a write is read back: effect=readback-verified is granted only when the value in the field matches a prediction built from the control's own measurements, caretPosition places the caret (start/end, with the applied selection reported), disabled and focus-moved targets are named in the result, and the screenshot says which path painted it (captureBackend=bitblt|gdiplus). Windows PowerShell 5.1 sidecar, zero install dependencies, no mouse injection.",
10
10
  "keywords": [
11
11
  "deepseek",
12
12
  "deepseek-harness",
@@ -31,7 +31,10 @@
31
31
  "main": "lib/index.js",
32
32
  "types": "types/index.d.ts",
33
33
  "exports": {
34
- ".": { "types": "./types/index.d.ts", "default": "./lib/index.js" },
34
+ ".": {
35
+ "types": "./types/index.d.ts",
36
+ "default": "./lib/index.js"
37
+ },
35
38
  "./cordis.patch.yml": "./cordis.patch.yml",
36
39
  "./dsh.plugin.json": "./dsh.plugin.json",
37
40
  "./src/engine/*": "./src/engine/*",