dsh-windows-parallel-mcp 0.5.0 → 0.7.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/index.js CHANGED
@@ -25,12 +25,29 @@
25
25
  // 3. `paused` and `enabled` are server-side gates. They are checked here, before any worker call,
26
26
  // because a prompt-level hint is not a switch (R2.5).
27
27
  import { createConfigSchema, CONFIG_DEFAULTS } from './config.js';
28
- import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
28
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
29
29
  import { tmpdir } from 'node:os';
30
30
  import { dirname, join } from 'node:path';
31
31
  import { WorkerClient, workerScript } from './engine.js';
32
32
  import { ACTIONS, PARAMETERS, TOOL_NAME, resolveDefineTool } from './host-tools.js';
33
33
  import { evaluateProof } from './proof-window.mjs';
34
+ import { actionTier, policyDecision, tierTable } from './policy.js';
35
+ import { auditLine, auditWrite } from './audit.js';
36
+
37
+ /**
38
+ * The tier each action declares it needs, read ONCE from the contract file -- not copied into a table
39
+ * here. The reason is this repo's most repeated lesson: three hand-kept copies of one vocabulary drift
40
+ * (scripts/check-refusals.mjs exists because of it), and a policy table written in two places would be
41
+ * the same bug with permission semantics attached. If the file cannot be read the table is EMPTY, and an
42
+ * empty table makes `actionTier` answer `takeover` for everything -- fail closed, never fail open.
43
+ * @type {Record<string, {requiresTier: string, requiresTierFor: Record<string,string>}>}
44
+ */
45
+ const REQUIRES_TIER = (() => {
46
+ try {
47
+ const doc = JSON.parse(readFileSync(new URL('../src/schema/tools.json', import.meta.url), 'utf8'));
48
+ return tierTable(doc.tools ?? []);
49
+ } catch { return {}; }
50
+ })();
34
51
 
35
52
  // ---- THE PUBLIC CONTRACT IS THE SOURCE OF TRUTH, AND THIS FILE IS CHECKED AGAINST IT ----------
36
53
  //
@@ -71,6 +88,11 @@ import { evaluateProof } from './proof-window.mjs';
71
88
  * @property {number} snapshotMaxElements
72
89
  * @property {number} screenshotMaxWidth
73
90
  * @property {number} shotsKeep
91
+ * @property {boolean} appLaunchAllowed
92
+ * @property {string[]} appLaunchAllow
93
+ * @property {'readonly'|'quiet'|'balanced'|'full'} policy
94
+ * @property {number} policyIdleMs
95
+ * @property {number} auditKeep
74
96
  */
75
97
 
76
98
  /**
@@ -155,6 +177,16 @@ export function apply(ctx, config = {}) {
155
177
  snapshotMaxElements: clampNumber(resolveSetting(config.snapshotMaxElements, 300), 1, 5000, 300),
156
178
  screenshotMaxWidth: clampNumber(resolveSetting(config.screenshotMaxWidth, 0), 0, 7680, 0),
157
179
  shotsKeep: clampNumber(resolveSetting(config.shotsKeep, 10), 1, 200, 10),
180
+ // ---- 0.7.0 desktop gates. Read defensively because a whitelist is a list of AUTHORIZATIONS: a
181
+ // non-array, an empty entry, or a stray space must never turn into "everything is allowed".
182
+ appLaunchAllowed: resolveSetting(config.appLaunchAllowed, false) === true,
183
+ appLaunchAllow: normalizeAllowList(resolveSetting(config.appLaunchAllow, [])),
184
+ // ---- 0.7.0 authorization model. `policy` is the ONE knob that says how far this plugin may go
185
+ // without asking again; the per-action `requiresTier` in src/schema/tools.json is the other axis, so
186
+ // adding an action never means adding a setting.
187
+ policy: normalizePolicy(resolveSetting(config.policy, 'balanced')),
188
+ policyIdleMs: clampNumber(resolveSetting(config.policyIdleMs, 3000), 0, 60000, 3000),
189
+ auditKeep: clampNumber(resolveSetting(config.auditKeep, 2000), 100, 200000, 2000),
158
190
  };
159
191
 
160
192
  const logger = ctx.logger ?? console;
@@ -281,6 +313,40 @@ export function apply(ctx, config = {}) {
281
313
 
282
314
  const { defineTool } = resolvedTools;
283
315
 
316
+ // Counted rather than logged-and-forgotten: an audit that silently fails to write would leave the
317
+ // operator with a log that LOOKS complete. The count is reported in the result text when non-zero.
318
+ let auditFailures = 0;
319
+
320
+ /**
321
+ * The audit line for one call, built once so every exit path writes the same SHAPE. A refusal path
322
+ * that forgot to record would be the hole that makes an audit log useless, so this is called from a
323
+ * single place in `execute` rather than from each return.
324
+ * @param {WpmArgs} args @param {string} decision @param {string} code
325
+ * @param {Record<string, any>} [extra]
326
+ * @returns {{ok:boolean, wrote:boolean, error?:string}}
327
+ */
328
+ const writeAudit = (args, decision, code, extra) => {
329
+ const r = auditLine({
330
+ action: String(args.action ?? ''), hwnd: String(args.hwnd ?? ''),
331
+ tier: String(extra?.tier ?? actionTier(REQUIRES_TIER, String(args.action ?? ''), args.op)),
332
+ policy: settings.policy, decision, code,
333
+ userActiveAgeMs: extra?.userActiveAgeMs, effect: String(extra?.effect ?? ''),
334
+ latencyMs: extra?.latencyMs, detail: extra?.detail,
335
+ forced: args.forceUserActive === true,
336
+ // The two content-free facts about a launch (R1: the whitelist cannot make arguments safe, so the
337
+ // record is what makes a bad one reviewable).
338
+ ...(args.action === 'launch' ? { target: String(args.target ?? ''), args: String(args.args ?? '') } : {}),
339
+ // Clipboard and type: lengths only. A log that copied the clipboard or the typed text would be a
340
+ // second place a secret lives, and the second place is the one nobody protects.
341
+ ...(args.action === 'clipboard' ? { op: String(args.op ?? ''), format: String(args.format ?? 'text') } : {}),
342
+ ...(typeof args.text === 'string' ? { chars: args.text.length } : {}),
343
+ ...(typeof extra?.chars === 'number' ? { resultChars: extra.chars } : {}),
344
+ });
345
+ const w = auditWrite(r, { keep: settings.auditKeep });
346
+ if (!w.ok) auditFailures += 1;
347
+ return w;
348
+ };
349
+
284
350
  /** Build the worker request for one action. Throws for arguments the action cannot use. */
285
351
  /** @param {WpmArgs} args @returns {any} */
286
352
  function toRequest(args) {
@@ -302,6 +368,15 @@ export function apply(ctx, config = {}) {
302
368
  ...(keyInput === 'inject' ? { keyInput } : {}),
303
369
  }
304
370
  : {};
371
+ // ---- 0.7.0 authorization fields, forwarded to the engine for the door actions. The host has ALREADY
372
+ // refused anything above the ceiling (so a refusal here costs zero worker requests); these travel so
373
+ // the engine can apply the idle check, which needs a measurement only it can take.
374
+ const authFields = {
375
+ policy: settings.policy,
376
+ requiredTier: actionTier(REQUIRES_TIER, args.action, args.op),
377
+ policyIdleMs: settings.policyIdleMs,
378
+ ...(args.forceUserActive === true ? { forceUserActive: true } : {}),
379
+ };
305
380
  switch (args.action) {
306
381
  case 'windows':
307
382
  return { action: 'windows' };
@@ -362,6 +437,7 @@ export function apply(ctx, config = {}) {
362
437
  }
363
438
  return {
364
439
  action: 'click', hwnd: args.hwnd, x: Math.round(/** @type {number} */ (args.x)), y: Math.round(/** @type {number} */ (args.y)), settleMs,
440
+ ...authFields,
365
441
  ...(space === 'image' ? { space: 'image', shotId: args.shotId } : {}),
366
442
  ...(typeof args.label === 'number' && args.label > 0
367
443
  ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
@@ -378,6 +454,14 @@ export function apply(ctx, config = {}) {
378
454
  return {
379
455
  action: 'type', hwnd: args.hwnd, text: args.text,
380
456
  elementName: args.elementName ?? '', replace: args.replace === true, settleMs,
457
+ ...authFields,
458
+ // Forwarded only when it is one of the three values the engine declares; anything else is
459
+ // dropped to the default HERE rather than passed on, because the engine's ValidateSet would
460
+ // turn a model's typo into `action_failed` -- and a schema the host already validates against
461
+ // (validateArguments, plus the registered enum) means a wrong value here did not come from a
462
+ // validated call. The drop is logged into the result by the engine's own caret= field, which
463
+ // always reports what was applied.
464
+ caretPosition: args.caretPosition === 'start' || args.caretPosition === 'end' ? args.caretPosition : 'idle',
381
465
  ...(typeof args.label === 'number' && args.label > 0
382
466
  ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
383
467
  : {}),
@@ -388,11 +472,64 @@ export function apply(ctx, config = {}) {
388
472
  if ((typeof args.label !== 'number' || args.label <= 0)) requireArg(args, 'elementName', 'focus');
389
473
  return {
390
474
  action: 'focus', hwnd: args.hwnd, elementName: args.elementName ?? '', settleMs,
475
+ ...authFields,
391
476
  ...(typeof args.label === 'number' && args.label > 0
392
477
  ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
393
478
  : {}),
394
479
  ...takeoverFields,
395
480
  };
481
+ case 'launch': {
482
+ // The gates are applied in `execute` BEFORE this line is reached, so a refusal costs no worker
483
+ // request at all; this function only shapes an authorised call. `args` is passed through as one
484
+ // command line -- the whitelist vouches for the program, not for its arguments, which is exactly
485
+ // why the audit records both.
486
+ requireArg(args, 'target', 'launch');
487
+ return {
488
+ action: 'launch', target: args.target,
489
+ ...(typeof args.args === 'string' && args.args ? { args: args.args } : {}),
490
+ waitMs: clampNumber(args.waitMs, 0, 30000, 3000),
491
+ policy: settings.policy, policyIdleMs: settings.policyIdleMs,
492
+ launchAllowed: settings.appLaunchAllowed,
493
+ allowList: settings.appLaunchAllow,
494
+ ...(args.forceUserActive === true ? { forceUserActive: true } : {}),
495
+ };
496
+ }
497
+ case 'clipboard': {
498
+ if (args.op !== 'read' && args.op !== 'write') {
499
+ throw refusal('action_failed', "clipboard needs op:'read' or op:'write'; no worker request was made");
500
+ }
501
+ const format = args.format === 'image' ? 'image' : 'text';
502
+ if (args.op === 'write' && format === 'text' && (typeof args.text !== 'string' || args.text.length === 0)) {
503
+ // Same rule as `type`: an empty write cannot be told apart from a clipboard the owner already
504
+ // cleared, and "the write worked" would then be a claim about nothing.
505
+ throw refusal('action_failed', 'clipboard write needs text; an empty write is indistinguishable from an already-empty clipboard');
506
+ }
507
+ return {
508
+ action: 'clipboard', op: args.op, format,
509
+ ...(format === 'text' && args.op === 'write' ? { text: args.text } : {}),
510
+ ...(format === 'image' && typeof args.shotId === 'string' ? { shotId: args.shotId } : {}),
511
+ };
512
+ }
513
+ case 'window': {
514
+ // An action with no target window is not a convenience, it is the ability to move something
515
+ // nobody named -- so `hwnd` stays mandatory and "the front window" is not a selector here.
516
+ requireArg(args, 'hwnd', 'window');
517
+ const op = String(args.op ?? '');
518
+ if (!['minimize', 'restore', 'move', 'resize', 'topmost'].includes(op)) {
519
+ throw refusal('action_failed', `window needs op=minimize|restore|move|resize|topmost, not '${args.op ?? ''}'; no worker request was made`);
520
+ }
521
+ if (op === 'move' && (typeof args.x !== 'number' || typeof args.y !== 'number')) {
522
+ throw refusal('action_failed', 'window move needs x and y in physical screen pixels; guessing the current position would make the move unreviewable');
523
+ }
524
+ if (op === 'resize' && (typeof args.width !== 'number' || typeof args.height !== 'number')) {
525
+ throw refusal('action_failed', 'window resize needs width and height');
526
+ }
527
+ return {
528
+ action: 'window', hwnd: args.hwnd, op,
529
+ ...(op === 'move' ? { x: Math.round(/** @type {number} */ (args.x)), y: Math.round(/** @type {number} */ (args.y)) } : {}),
530
+ ...(op === 'resize' ? { width: Math.round(/** @type {number} */ (args.width)), height: Math.round(/** @type {number} */ (args.height)) } : {}),
531
+ };
532
+ }
396
533
  default:
397
534
  throw refusal('no_hwnd', `unknown action '${args.action}'`);
398
535
  }
@@ -419,7 +556,14 @@ export function apply(ctx, config = {}) {
419
556
  + 'draws the marker at a point and reports, as TEXT, the element under it -- a reviewable click that '
420
557
  + 'needs no picture. Refusals carry a code (no_hwnd, '
421
558
  + 'paused, elevated_target, unreachable, uia_tree_empty, uia_probe_failed, terminal_no_door, needs_facts, action_failed, '
422
- + 'restore_failed, takeover_unavailable, keyinject_unavailable, takeover_aborted, stale_ref) and a reason. '
559
+ + 'restore_failed, takeover_unavailable, keyinject_unavailable, takeover_aborted, stale_ref, app_launch_denied, '
560
+ + 'policy_denied, user_active) and a reason. '
561
+ + 'THREE DESKTOP ACTIONS exist since 0.7.0 and are gated by settings rather than by the target: launch needs '
562
+ + 'appLaunchAllowed AND an exact appLaunchAllow entry (an empty whitelist means nothing, and no wildcard exists); '
563
+ + 'clipboard reads and writes the system clipboard, reporting lengths and never contents; window changes one '
564
+ + 'named window (minimize/restore/move/resize/topmost) and verifies the change by reading the window state back. '
565
+ + 'The single `policy` setting is the ceiling over all eleven actions: a call above it is refused with '
566
+ + 'policy_denied, whose next step is to raise the setting and not to retry. '
423
567
  + 'Start with action=windows to get an hwnd, action=snapshot to read a frame, or action=status to see '
424
568
  + 'what currently holds the foreground.',
425
569
  parameters: PARAMETERS,
@@ -443,24 +587,77 @@ export function apply(ctx, config = {}) {
443
587
  },
444
588
  /** @param {WpmArgs} args @param {WpmExec|undefined} exec @returns {Promise<Record<string, any>>} */
445
589
  async execute(args, exec) {
590
+ // THE GATE ORDER IS THE SAFETY DESIGN, and each gate that can be answered from settings is answered
591
+ // before the worker is touched -- asserted that way with a request counter in test/plugin-test.mjs.
592
+ // 1 paused 2 policy 3 takeover / keyInject 4 launch gate + whitelist 5 (engine) idle 6 table
593
+ // Every exit below goes through `finish`, because an audit written on one path and forgotten on the
594
+ // next is an audit log that looks complete and is not.
595
+ /** True once the audit line for this call has been written -- any second call is ignored. A
596
+ * boolean, not an object: the field's whole job is "have we recorded this yet". */
597
+ let audited = false;
598
+ /** @param {Record<string, any>} res @returns {Record<string, any>} */
599
+ const finish = (res) => {
600
+ if (!audited) {
601
+ audited = true;
602
+ writeAudit(args, res.ok === true ? 'allow' : 'deny', String(res.refusal ?? ''), {
603
+ effect: res.effect, latencyMs: res.latencyMs, chars: res.chars,
604
+ tier: res.tier, detail: res.refusal ? String(res.text ?? '').slice(0, 200) : undefined,
605
+ });
606
+ }
607
+ if (auditFailures) res.text = `${res.text} auditNote=${auditFailures} write(s) failed`;
608
+ return res;
609
+ };
446
610
  // Server-side gates first: a paused or disabled engine must refuse before it spends a worker
447
611
  // call, and the refusal must name the gate rather than describe a symptom.
448
612
  if (!settings.enabled) {
449
- return result(args.action, false, 'paused', 'windows-parallel is switched off in settings; no action was attempted');
613
+ return finish(result(args.action, false, 'paused', 'windows-parallel is switched off in settings; no action was attempted'));
614
+ }
615
+ // ---- 0.7.0 policy ceiling. ONE setting against the tier the action declares, so a new action
616
+ // never needs a new switch -- and never can slip past one that was never added.
617
+ const pd = policyDecision({
618
+ policy: settings.policy, table: REQUIRES_TIER, action: String(args.action),
619
+ takeoverRequested: args.takeover === true, keyInjectRequested: args.keyInput === 'inject',
620
+ // clipboard is the one action whose two halves live on different rungs; the table refinement is
621
+ // consulted here so `policy:'readonly'` still permits a read while a write is refused.
622
+ op: args.action === 'clipboard' ? args.op : undefined,
623
+ });
624
+ if (pd.denied) {
625
+ return finish(result(args.action, false, 'policy_denied',
626
+ `policy='${settings.policy}' allows at most the '${pd.ceiling}' rung and this call needs '${pd.required}'. Nothing was sent to the worker and no window was touched. Next step is a settings change, not a retry: raise policy in the plugin settings${args.takeover === true ? ' or drop takeover:true' : ''}${args.action === 'clipboard' && args.op === 'write' ? ' (a clipboard READ is allowed at this level)' : ''}`));
450
627
  }
451
628
  // ---- R3 gates, BEFORE the worker. A refused takeover costs zero worker requests, which is
452
629
  // asserted with a request counter in test/plugin-test.mjs: "the gate is checked" is otherwise
453
630
  // indistinguishable from "the gate is checked after the expensive part".
454
631
  if (args.takeover === true && !settings.takeoverAllowed) {
455
- return result(args.action, false, 'takeover_unavailable',
632
+ return finish(result(args.action, false, 'takeover_unavailable',
456
633
  'takeoverAllowed is off in settings; the action was refused rather than silently downgraded to the quiet tier. '
457
- + 'The quiet tier still works without takeover:true' + hwndHint(args));
634
+ + 'The quiet tier still works without takeover:true' + hwndHint(args)));
458
635
  }
459
636
  if (args.keyInput === 'inject' && (!settings.keyInjectAllowed || args.takeover !== true)) {
460
- return result(args.action, false, 'keyinject_unavailable',
637
+ return finish(result(args.action, false, 'keyinject_unavailable',
461
638
  args.takeover !== true
462
639
  ? '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'
463
- : 'keyInjectAllowed is off in settings; no keystroke was sent');
640
+ : 'keyInjectAllowed is off in settings; no keystroke was sent'));
641
+ }
642
+ // ---- 0.7.0 the launch gate, then its whitelist. TWO switches, and the reason they are two is that
643
+ // "the owner enabled the capability" and "this program is on the approved list" are different
644
+ // decisions made at different times; folding them into one would make enabling launch enable every
645
+ // program at once. An empty whitelist refuses even when the gate is on -- that is the point.
646
+ if (args.action === 'launch') {
647
+ if (!settings.appLaunchAllowed) {
648
+ return finish(result('launch', false, 'app_launch_denied',
649
+ 'appLaunchAllowed is off in settings, so no program may be started and no worker request was made. The next step is the owner\'s: turn the gate on AND list the exact program in appLaunchAllow'));
650
+ }
651
+ const name = String(args.target ?? '').trim().toLowerCase();
652
+ if (!name) {
653
+ return finish(result('launch', false, 'app_launch_denied', 'launch needs a target program name or path; nothing was started'));
654
+ }
655
+ // EXACT, case-folded membership. No wildcard, no prefix, no path normalisation: `notepad` must not
656
+ // authorise `notepad-helper.exe`, and a rule that grows by prefix is a whitelist in name only.
657
+ if (!settings.appLaunchAllow.includes(name)) {
658
+ return finish(result('launch', false, 'app_launch_denied',
659
+ `'${args.target}' is not on the appLaunchAllow whitelist (which holds ${settings.appLaunchAllow.length} exact name(s)); no process was started. Add the exact name or absolute path -- there is no wildcard and no prefix match${name.includes('\\') ? ' (a path must appear verbatim)' : ''}`));
660
+ }
464
661
  }
465
662
  // A pre-worker refusal is still a refusal, not a thrown error. The first version of this file
466
663
  // let `toRequest` throw for an empty write, and the caller saw a crashed tool call instead of
@@ -477,7 +674,7 @@ export function apply(ctx, config = {}) {
477
674
  // because the only thrower is `refusal()` above; the `??` fallbacks still keep the vocabulary
478
675
  // intact when it is not.
479
676
  const code = /** @type {WpmError} */ (err)?.refusal ?? 'action_failed';
480
- return result(args.action, false, code, /** @type {WpmError} */ (err)?.reason ?? String(/** @type {WpmError} */ (err)?.message ?? err));
677
+ return finish(result(args.action, false, code, /** @type {WpmError} */ (err)?.reason ?? String(/** @type {WpmError} */ (err)?.message ?? err)));
481
678
  }
482
679
  let envelope;
483
680
  const disarm = request.takeover ? armAbort(exec) : () => {};
@@ -490,12 +687,12 @@ export function apply(ctx, config = {}) {
490
687
  // the original read `err.message` directly, and a non-Error thrown here still renders the
491
688
  // same way it always did -- widening the expression would be a behaviour change dressed as
492
689
  // type safety, which is exactly what this file refuses to do.
493
- return result(args.action, false, 'action_failed', `engine worker unavailable: ${/** @type {Error} */ (err).message}`);
690
+ return finish(result(args.action, false, 'action_failed', `engine worker unavailable: ${/** @type {Error} */ (err).message}`));
494
691
  } finally {
495
692
  disarm();
496
693
  }
497
694
  if (!envelope.ok) {
498
- return result(args.action, false, 'action_failed', `worker error: ${envelope.error ?? 'unknown'}`);
695
+ return finish(result(args.action, false, 'action_failed', `worker error: ${envelope.error ?? 'unknown'}`));
499
696
  }
500
697
  // click coordinates are SCREEN pixels (the engine converts to client space itself), so the
501
698
  // marker can be placed straight from the request -- no second coordinate system to get wrong.
@@ -510,7 +707,7 @@ export function apply(ctx, config = {}) {
510
707
  const screen = request.space === 'image' ? parsePoint(r.screenPoint) : null;
511
708
  markPoint(screen ? screen.x : request.x, screen ? screen.y : request.y);
512
709
  }
513
- return format(args.action, envelope.result);
710
+ return finish(format(args.action, envelope.result));
514
711
  },
515
712
  });
516
713
 
@@ -539,6 +736,29 @@ function resolveSetting(value, fallback) {
539
736
  return v;
540
737
  }
541
738
 
739
+ /**
740
+ * The launch whitelist, as the gate sees it: trimmed, empties dropped, LOWER-CASED for comparison.
741
+ * Case-folding is a deliberate decision and it is stated here rather than left to the reader: Windows
742
+ * treats program names and paths case-insensitively, so a whitelist that was case-sensitive would
743
+ * refuse `notepad.exe` when the owner wrote `NOTEPAD.EXE` -- and an operator who is refused for a
744
+ * spelling difference starts adding wildcards, which is the failure this list exists to prevent.
745
+ * @param {any} value @returns {string[]}
746
+ */
747
+ function normalizeAllowList(value) {
748
+ if (!Array.isArray(value)) return [];
749
+ return value.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim().toLowerCase());
750
+ }
751
+
752
+ /**
753
+ * The policy level, defaulted rather than trusted. A typo in a bundle patch (`banlanced`) must not
754
+ * become "full" -- the safe direction for an unparseable authorization setting is the DOWNGRADE, and
755
+ * `balanced` is the documented default that the README and the settings form both describe.
756
+ * @param {any} value @returns {'readonly'|'quiet'|'balanced'|'full'}
757
+ */
758
+ function normalizePolicy(value) {
759
+ return value === 'readonly' || value === 'quiet' || value === 'full' ? value : 'balanced';
760
+ }
761
+
542
762
  /** @param {any} value @returns {number} */
543
763
  function clampSettle(value) {
544
764
  const n = Number(value);
@@ -548,7 +768,7 @@ function clampSettle(value) {
548
768
 
549
769
  /**
550
770
  * @param {Record<string, any>} args
551
- * @param {'hwnd'|'x'|'y'|'text'|'elementName'} key
771
+ * @param {'hwnd'|'x'|'y'|'text'|'elementName'|'target'} key
552
772
  * @param {string} action
553
773
  * @returns {void}
554
774
  */
@@ -668,15 +888,29 @@ function format(action, r) {
668
888
  if (action === 'snapshot') return formatSnapshot(r);
669
889
  if (action === 'screenshot') return formatScreenshot(r);
670
890
  if (action === 'preview') return formatPreview(r);
891
+ // ---- 0.7.0 DESKTOP RESULTS -----------------------------------------------------------------
892
+ // No channel, no tier, no proof window: these actions do not choose a door and there is no
893
+ // disturbance for a proof to attribute. What they DO carry is a read-back of the state they changed,
894
+ // rendered explicitly so a caller can see the difference between "the syscall answered" and "the
895
+ // window is like that now".
896
+ if (action === 'launch') return formatLaunch(r);
897
+ if (action === 'clipboard') return formatClipboard(r);
898
+ if (action === 'window') return formatWindow(r);
671
899
 
672
900
  // WHO REPORTED THE SUCCESS. The engine sets `effect` when a channel call RETURNS without throwing;
673
- // this file never upgrades it, and the three values are not degrees of confidence in the app -- they
674
- // name who is speaking (README's table states the same three lines, keep them in step):
901
+ // this file never upgrades it, and the four values are not degrees of confidence in the app -- they
902
+ // name who is speaking (README's table states the same four lines, keep them in step):
675
903
  // unverified no channel reported success at all;
676
904
  // reported-by-send the window message was DELIVERED -- nothing here proves the target app
677
905
  // processed it;
678
- // reported-by-pattern the UIA pattern call RETURNED -- nothing here proves the interface changed.
679
- // Read as "who says it worked", never as "the application's state is confirmed".
906
+ // reported-by-pattern the UIA pattern call RETURNED -- nothing here proves the interface changed;
907
+ // readback-verified 0.6.0: the value was READ BACK after the settle window and equals the value
908
+ // predicted from measurements the CONTROL reported. This is the only value that
909
+ // is about the application rather than about the call, and the engine grants it
910
+ // only on an exact match -- a masked field reports readback=unavailable and an
911
+ // app that reformatted the input reports readbackMismatch=true, neither of which
912
+ // is an upgrade (findings 8.1/8.2).
913
+ // Read the first three as "who says it worked", never as "the application's state is confirmed".
680
914
  const bits = [
681
915
  `${action} ok`,
682
916
  `channel=${r.channel || '?'}`,
@@ -848,7 +1082,7 @@ function formatScreenshot(r) {
848
1082
  const identity = r.identity === true || r.identity === 'true';
849
1083
  const dpiAware = r.dpiAware === true || r.dpiAware === 'true';
850
1084
  const lines = [
851
- `screenshot ok: ${size.width ?? '?'}x${size.height ?? '?'} px (scale=${scale} identity=${identity}) frame=${r.frame || '?'} dpiAware=${dpiAware}`,
1085
+ `screenshot ok: ${size.width ?? '?'}x${size.height ?? '?'} px (scale=${scale} identity=${identity}) frame=${r.frame || '?'} captureBackend=${r.captureBackend || '?'} dpiAware=${dpiAware}`,
852
1086
  `file=${r.file || '?'}`,
853
1087
  `shotId=${r.shotId || '?'}`,
854
1088
  `screenRect=${rect.left ?? '?'},${rect.top ?? '?'},${rect.right ?? '?'},${rect.bottom ?? '?'} `
@@ -856,6 +1090,12 @@ function formatScreenshot(r) {
856
1090
  'mapping: screenX = screenRect.left + round(imageX / scale); screenY = screenRect.top + round(imageY / scale). '
857
1091
  + `The ENGINE applies this when a click passes space:"image" with shotId=${r.shotId || '?'}; do not multiply it yourself.`,
858
1092
  ];
1093
+ // 0.6.0-B. The cheap path is BitBlt and the fallback is Graphics.CopyFromScreen; they are measured
1094
+ // equivalent on a still scene (identical size, identical PNG bytes, 0 per-channel difference over
1095
+ // 17388 sample points) and they are NOT the same call, so which one ran is part of the result rather
1096
+ // than an implementation detail. A note appears only when the fast path was refused.
1097
+ 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.');
1098
+ if (r.captureNote) lines.push(`note: ${r.captureNote} -- the picture came from Graphics.CopyFromScreen this time.`);
859
1099
  if (identity) {
860
1100
  lines.push('identity=true means the image was NOT resampled: image pixels and screen pixels differ only by the rect origin.');
861
1101
  }
@@ -865,7 +1105,7 @@ function formatScreenshot(r) {
865
1105
  }
866
1106
  return result('screenshot', true, '', lines.join('\n'), {
867
1107
  shotId: r.shotId, file: r.file, screenRect: rect, imageSize: size,
868
- scale, identity, frame: r.frame, dpiAware,
1108
+ scale, identity, frame: r.frame, captureBackend: r.captureBackend, dpiAware,
869
1109
  });
870
1110
  }
871
1111
 
@@ -898,6 +1138,81 @@ function formatPreview(r) {
898
1138
  });
899
1139
  }
900
1140
 
1141
+ /**
1142
+ * Render a launch. The two facts that matter are the pid (the process exists) and whether it has
1143
+ * published a window yet -- and the second is reported as `window-not-yet` rather than as a failure,
1144
+ * because Process.Start returning while MainWindowHandle is 0 is normal (measured 1348 ms cold).
1145
+ * An agent that is told "started, no window yet" can poll or pick a different target; an agent that is
1146
+ * told "failed" when the program is running will start it again.
1147
+ * @param {any} r @returns {Record<string, any>}
1148
+ */
1149
+ function formatLaunch(r) {
1150
+ const lines = [
1151
+ `launch ok: pid=${r.pid ?? '?'} name=${r.processName ?? '?'}`,
1152
+ `detail=${r.detail || '(none)'}`,
1153
+ ];
1154
+ if (r.hwnd) lines.push(`hwnd=${r.hwnd} -- the window is addressable now; use it with action=snapshot or click`);
1155
+ else lines.push('hwnd=(none yet) -- the process is running but has published no top-level window; this is NOT a failure, and retrying the launch would start a second copy');
1156
+ if (r.note) lines.push(`note: ${r.note}`);
1157
+ if (r.latencyMs !== undefined) lines.push(`latencyMs=${r.latencyMs} waitedMs=${r.waitedMs ?? 0}`);
1158
+ return result('launch', true, '', lines.join('\n'), {
1159
+ pid: r.pid, hwnd: r.hwnd || '', processName: r.processName, waitedMs: r.waitedMs,
1160
+ effect: r.effect || 'unverified',
1161
+ });
1162
+ }
1163
+
1164
+ /**
1165
+ * Render a clipboard result. THE VALUE IS DELIBERATELY ABSENT from a text read's summary line: it is
1166
+ * present in the structured field the caller asked for, and the text says what it is rather than
1167
+ * being it -- a log line or a screenshot of this result should not become a second copy of whatever was
1168
+ * on the clipboard.
1169
+ * @param {any} r @returns {Record<string, any>}
1170
+ */
1171
+ function formatClipboard(r) {
1172
+ const lines = [];
1173
+ if (r.clipFormat === 'image') {
1174
+ lines.push(`clipboard ${r.op ?? ''} ok: image size=${r.readbackSize || r.imageSize || '?'}`);
1175
+ if (r.file) lines.push(`file=${r.file}`);
1176
+ if (r.clipId) lines.push(`clipId=${r.clipId}`);
1177
+ if (r.shotId) lines.push(`shotId=${r.shotId}`);
1178
+ } else {
1179
+ lines.push(`clipboard ${r.op ?? ''} ok: text chars=${r.chars ?? r.readbackChars ?? '?'}`);
1180
+ if (r.truncated) lines.push(`truncated: the clipboard held ${r.chars} characters and the 64 KB cap applies -- the value was cut, not lost`);
1181
+ }
1182
+ lines.push(`effect=${r.effect || 'unverified'}`);
1183
+ if (r.latencyMs !== undefined) lines.push(`latencyMs=${r.latencyMs}`);
1184
+ if (r.detail) lines.push(`detail=${r.detail}`);
1185
+ lines.push('privacy: a clipboard READ reports its length, never its content; the audit log records op/format/length only, because the clipboard may hold a token the owner copied seconds ago');
1186
+ return result('clipboard', true, '', lines.join('\n'), {
1187
+ clipFormat: r.clipFormat, chars: r.chars, truncated: r.truncated === true,
1188
+ file: r.file, clipId: r.clipId, imageSize: r.imageSize, readbackSize: r.readbackSize,
1189
+ effect: r.effect || 'unverified',
1190
+ });
1191
+ }
1192
+
1193
+ /**
1194
+ * Render a window op. `verified` is the word the whole action is built around: the op's own read-back
1195
+ * (IsIconic, the rect, the ex-style) said yes, not `ShowWindow` returning true.
1196
+ * @param {any} r @returns {Record<string, any>}
1197
+ */
1198
+ function formatWindow(r) {
1199
+ const lines = [
1200
+ `window ok: ${r.detail || '(no detail)'}`,
1201
+ `effect=${r.effect || 'unverified'}`,
1202
+ ];
1203
+ if (r.latencyMs !== undefined) lines.push(`latencyMs=${r.latencyMs}`);
1204
+ if (r.reason) lines.push(`reason: ${r.reason}`);
1205
+ lines.push('verified means the WINDOW reports the state (IsIconic / the rect / WS_EX_TOPMOST), not that the syscall answered; move/resize/topmost never activate the window');
1206
+ return result('window', true, '', lines.join('\n'), {
1207
+ effect: r.effect || 'unverified', detail: r.detail,
1208
+ // Forwarded, not re-derived: `foregroundTaken` is the engine's measurement of GetForegroundWindow on
1209
+ // both sides of the call. Dropping it here would leave the claim in the prose and out of the object,
1210
+ // which is how a caller that reads structure ends up less informed than one that reads text.
1211
+ foregroundTaken: r.foregroundTaken === true,
1212
+ verified: /verified=true/.test(String(r.detail ?? '')),
1213
+ });
1214
+ }
1215
+
901
1216
  /** Parse an engine-emitted "x,y" point. Returns null for anything else rather than guessing 0,0. */
902
1217
  /** @param {any} s @returns {{x: number, y: number}|null} */
903
1218
  function parsePoint(s) {
package/lib/policy.js ADDED
@@ -0,0 +1,127 @@
1
+ // policy.js -- the authorization ladder, as one pure module.
2
+ //
3
+ // WHY TWO AXES AND NOT ELEVEN SWITCHES. Every action declares the LOWEST rung it can ever need
4
+ // (`requiresTier` in src/schema/tools.json); the owner sets ONE ceiling (`policy`). A caller asking for
5
+ // more than the ceiling is refused with `policy_denied` whose next step is named: raise the setting, do
6
+ // not retry. The alternative -- a boolean per action -- would need eleven settings for eleven actions and
7
+ // a twelfth the moment a capability is added, and the pair that actually drifts is the setting nobody
8
+ // reads and the action nobody thought about.
9
+ //
10
+ // THE RUNGS ARE ABOUT DISTURBANCE, NOT ABOUT RISK CATEGORY:
11
+ // readonly touches nothing: reads a window list, a tree, a screen, a clipboard VALUE;
12
+ // quiet writes into one named window through its message door -- zero foreground change, measured;
13
+ // flash the same write when only UI Automation can reach it: one bounded flash that reverses itself;
14
+ // takeover the real cursor moves and the focus is held until the action ends, HUD mandatory.
15
+ // `launch` sits at takeover because it is the one action whose consequences outlive the call; it ALSO
16
+ // needs its own gate (appLaunchAllowed) and its own whitelist, which no tier ordering can express.
17
+ //
18
+ // NO IO, NO STATE, NO CLOCK. Every function here is answerable from its arguments, which is what makes
19
+ // the table testable without a desktop and what keeps a policy decision from depending on when it was
20
+ // asked. Drift between this set and tools.json is a gate (scripts/check-policy-table.mjs), not a comment.
21
+
22
+ /** The four rungs, lowest first. Order is the semantics: `tierAtLeast` compares positions here. */
23
+ export const TIER_ORDER = ['readonly', 'quiet', 'flash', 'takeover'];
24
+
25
+ /** The four settings levels, lowest first, each naming the highest rung it permits. */
26
+ export const POLICY_LEVELS = ['readonly', 'quiet', 'balanced', 'full'];
27
+
28
+ /**
29
+ * Which rung each `policy` level allows at most. `balanced` is the default and stops at `flash`: the
30
+ * quiet door and the self-reversing UIA path are permitted, the takeover tier and `launch` are not.
31
+ * @type {Record<string, string>}
32
+ */
33
+ export const POLICY_CEILINGS = {
34
+ readonly: 'readonly',
35
+ quiet: 'quiet',
36
+ balanced: 'flash',
37
+ full: 'takeover',
38
+ };
39
+
40
+ /**
41
+ * Is `required` at or below what `policy` permits?
42
+ *
43
+ * An unknown `policy` or unknown `required` answers FALSE. That is the whole safety argument of this
44
+ * function: a typo in a bundle patch, a tier someone added to tools.json without adding it here, or a
45
+ * caller that invents a level must all fall on the refusing side, because "unparseable setting" and
46
+ * "everything allowed" reading the same way is how a permission system becomes decoration.
47
+ * @param {string} policy @param {string} required @returns {boolean}
48
+ */
49
+ export function tierAtLeast(policy, required) {
50
+ const ceiling = POLICY_CEILINGS[policy];
51
+ if (!ceiling) return false;
52
+ const need = TIER_ORDER.indexOf(required);
53
+ if (need < 0) return false;
54
+ return need <= TIER_ORDER.indexOf(ceiling);
55
+ }
56
+
57
+ /**
58
+ * The rung a (action, requestedTier) pair needs. When the caller explicitly asks for the takeover tier
59
+ * that outranks the action's declared minimum, because asking for the cursor to move IS the higher
60
+ * request; otherwise the declared rung decides.
61
+ * @param {string} required the action's declared `requiresTier`
62
+ * @param {boolean} takeoverRequested
63
+ * @param {boolean} keyInjectRequested
64
+ * @returns {string}
65
+ */
66
+ export function effectiveTier(required, takeoverRequested = false, keyInjectRequested = false) {
67
+ if (takeoverRequested || keyInjectRequested) return 'takeover';
68
+ return TIER_ORDER.includes(required) ? required : 'takeover';
69
+ }
70
+
71
+ /**
72
+ * The action's declared rung, or `takeover` for an action nobody declared -- an undeclared action is
73
+ * treated as the loudest one until a human says otherwise. Silence about a capability must not read as
74
+ * permission for it.
75
+ *
76
+ * `op` consults `requiresTierFor` for the one action whose halves live on different rungs: reading the
77
+ * clipboard touches nothing, writing it replaces something the owner put there, and a single rung for
78
+ * both would have to be either too loose or too tight. An op that the table does not refine falls back
79
+ * to the action's rung -- it never falls back to "allowed".
80
+ * @param {Record<string, any>} table action -> requiresTier (and optionally requiresTierFor)
81
+ * @param {string} action @param {string} [op] @returns {string}
82
+ */
83
+ export function actionTier(table, action, op) {
84
+ const entry = table ? table[action] : undefined;
85
+ if (entry && typeof entry === 'object') {
86
+ const perOp = op && entry.requiresTierFor ? entry.requiresTierFor[op] : undefined;
87
+ if (typeof perOp === 'string') return TIER_ORDER.includes(perOp) ? perOp : 'takeover';
88
+ return TIER_ORDER.includes(entry.requiresTier) ? entry.requiresTier : 'takeover';
89
+ }
90
+ if (typeof entry === 'string') return TIER_ORDER.includes(entry) ? entry : 'takeover';
91
+ return 'takeover';
92
+ }
93
+
94
+ /**
95
+ * The tier table as `lib/index.js` and the gate both want it: one object per action, carrying the
96
+ * declared rung and, where the action has halves, the per-op refinement. Reading it through THIS
97
+ * function is the single place the shape is understood; the contract file stays the source of truth.
98
+ * @param {Array<{action:string, requiresTier?:string, requiresTierFor?:Record<string,string>}>} tools
99
+ * @returns {Record<string, {requiresTier: string, requiresTierFor: Record<string,string>}>}
100
+ */
101
+ export function tierTable(tools) {
102
+ /** @type {Record<string, {requiresTier: string, requiresTierFor: Record<string,string>}>} */
103
+ const out = {};
104
+ for (const t of tools ?? []) {
105
+ if (!t || typeof t.action !== 'string') continue;
106
+ out[t.action] = {
107
+ requiresTier: typeof t.requiresTier === 'string' ? t.requiresTier : '',
108
+ requiresTierFor: (t.requiresTierFor && typeof t.requiresTierFor === 'object') ? t.requiresTierFor : {},
109
+ };
110
+ }
111
+ return out;
112
+ }
113
+ /**
114
+ * Should this action be refused for being above the ceiling? Returns the decision so the caller
115
+ * cannot accidentally invert the boolean: `denied` is the refusal, and the two facts a reader
116
+ * needs (what the action needed, what the policy allows) come back already formatted.
117
+ * @param {{policy: string, table: Record<string,any>, action: string, op?: string, takeoverRequested?: boolean, keyInjectRequested?: boolean}} q
118
+ * @returns {{denied: boolean, required: string, ceiling: string}}
119
+ */
120
+ export function policyDecision(q) {
121
+ const required = effectiveTier(actionTier(q.table, q.action, q.op), q.takeoverRequested, q.keyInjectRequested);
122
+ return {
123
+ denied: !tierAtLeast(q.policy, required),
124
+ required,
125
+ ceiling: POLICY_CEILINGS[q.policy] ?? '(unknown policy)',
126
+ };
127
+ }