dsh-windows-parallel-mcp 0.8.2 → 0.9.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.de.md +444 -419
  2. package/CHANGELOG.es.md +444 -419
  3. package/CHANGELOG.fr.md +444 -419
  4. package/CHANGELOG.it.md +444 -419
  5. package/CHANGELOG.ja.md +444 -419
  6. package/CHANGELOG.ko.md +444 -419
  7. package/CHANGELOG.md +965 -940
  8. package/CHANGELOG.pt.md +444 -419
  9. package/CHANGELOG.ru.md +444 -419
  10. package/CHANGELOG.zh.md +444 -419
  11. package/INSTALL.de.md +126 -126
  12. package/INSTALL.es.md +126 -126
  13. package/INSTALL.fr.md +126 -126
  14. package/INSTALL.it.md +126 -126
  15. package/INSTALL.ja.md +126 -126
  16. package/INSTALL.ko.md +126 -126
  17. package/INSTALL.md +122 -122
  18. package/INSTALL.pt.md +126 -126
  19. package/INSTALL.ru.md +126 -126
  20. package/INSTALL.zh.md +126 -126
  21. package/README.de.md +684 -684
  22. package/README.es.md +684 -684
  23. package/README.fr.md +684 -684
  24. package/README.it.md +684 -684
  25. package/README.ja.md +684 -684
  26. package/README.ko.md +684 -684
  27. package/README.md +680 -680
  28. package/README.pt.md +684 -684
  29. package/README.ru.md +684 -684
  30. package/README.zh.md +684 -684
  31. package/cordis.patch.yml +15 -15
  32. package/docs/refusals.md +90 -90
  33. package/docs/takeover.md +128 -128
  34. package/dsh.plugin.json +18 -18
  35. package/lib/config.js +275 -275
  36. package/lib/engine.js +252 -252
  37. package/lib/host-tools.js +365 -338
  38. package/lib/index.js +1275 -1249
  39. package/lib/peers-schemastery.js +23 -23
  40. package/lib/peers-tools.js +15 -15
  41. package/lib/proof-window.mjs +427 -427
  42. package/package.json +122 -122
  43. package/server.json +110 -110
  44. package/src/engine/decide.ps1 +356 -356
  45. package/src/engine/engine.ps1 +1208 -1208
  46. package/src/engine/hud.ps1 +411 -411
  47. package/src/engine/input-inject.ps1 +176 -176
  48. package/src/engine/overlay.ps1 +389 -389
  49. package/src/engine/takeover.ps1 +144 -144
  50. package/src/engine/win.ps1 +1881 -1881
  51. package/src/engine/worker.ps1 +310 -310
  52. package/src/schema/tools.json +533 -533
  53. package/types/index.d.ts +190 -187
package/lib/index.js CHANGED
@@ -1,1249 +1,1275 @@
1
- // index.js — the host half: one tool, one worker, and the refusal vocabulary kept intact.
2
- //
3
- // THE SHAPE OF THIS FILE IS THE FORM DECISION. R3.1' in spec.md recorded the fork as
4
- // A. DSH native plugin: the host registers the tool directly; PowerShell is a sidecar.
5
- // B. MCP server: the host talks to a separate MCP process over stdio.
6
- // The owner chose A on 2026-11-19. Concretely that means: no `@modelcontextprotocol/sdk`, no bridge
7
- // row, no second Node process — the tool is registered here and the only child process is the
8
- // PowerShell worker, which the engine already needed in either form.
9
- //
10
- // WHY ONE TOOL AND NOT FIVE. src/schema/tools.json names eight actions as the contract surface. The
11
- // host convention (shell / terminal / read / write in this same build) is one tool with an action
12
- // discriminator, because every registered tool is resident schema on every turn — eight entries
13
- // describing one engine is a standing token cost for no gain in capability. The contract is
14
- // preserved exactly: same eight actions, same fourteen refusal codes, same required arguments. The
15
- // mapping is asserted in test/plugin-test.mjs against the contract file, so "we project to one tool"
16
- // cannot quietly become "we support 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.
19
- //
20
- // THE THREE THINGS THIS FILE MUST GET RIGHT, each of which would look like a working plugin while
21
- // being wrong:
22
- // 1. A disappeared worker must not become a dead tool. The client restarts once and reports.
23
- // 2. A refusal must survive as a refusal. It is returned in the result text with its code, never
24
- // swallowed and never turned into a generic failure — R3.2 forbids canned messages.
25
- // 3. `paused` and `enabled` are server-side gates. They are checked here, before any worker call,
26
- // because a prompt-level hint is not a switch (R2.5).
27
- import { createConfigSchema, CONFIG_DEFAULTS } from './config.js';
28
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
29
- import { tmpdir } from 'node:os';
30
- import { dirname, join } from 'node:path';
31
- import { WorkerClient, workerScript } from './engine.js';
32
- import { ACTIONS, PARAMETERS, TOOL_NAME, resolveDefineTool } from './host-tools.js';
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
- })();
51
-
52
- // ---- THE PUBLIC CONTRACT IS THE SOURCE OF TRUTH, AND THIS FILE IS CHECKED AGAINST IT ----------
53
- //
54
- // types/index.d.ts is what a consumer imports and what `scripts/check-types.mjs` proves a strict
55
- // client accepts. The typedef block below IMPORTS that same file, so the annotations in this
56
- // implementation are checked against the shipped promise rather than against a private copy of it:
57
- // rename a field in types/index.d.ts and `scripts/check-jsdoc.mjs` turns this file red. That
58
- // direction is the whole point -- a generated .d.ts (what a TypeScript rewrite would emit here) has
59
- // no `WpmAction`/`RefusalCode`/`WpmArgs` at all, so it could not do this.
60
- //
61
- // (The first version of this block used `// @typedef` lines. Those are comments, not JSDoc: nothing
62
- // was declared, and the checker answered "Cannot find name 'WpmArgs'". A JSDoc block is required.)
63
- /**
64
- * @typedef {import('../types/index.d.ts').WpmAction} WpmAction
65
- * @typedef {import('../types/index.d.ts').WpmArgs} WpmArgs
66
- * @typedef {import('../types/index.d.ts').RefusalCode} RefusalCode
67
- * @typedef {import('../types/index.d.ts').WpmResult} WpmResult
68
- * @typedef {import('../types/index.d.ts').WpmExec} WpmExec
69
- */
70
-
71
- /**
72
- * The settings object `apply` derives from the Cordis config. Spelled out because the config VALUE is
73
- * `{}` at the type level -- config.js validates it at runtime, and a validator's output is not a
74
- * static fact -- so without this every one of the ten reads under `apply` reports "does not exist on
75
- * type '{}'". The property list here must match `FIELDS` in config.js; both are checked by
76
- * test/plugin-test.mjs.
77
- * @typedef {object} WpmSettings
78
- * @property {boolean} enabled
79
- * @property {number} settleMs
80
- * @property {number} requestTimeoutMs
81
- * @property {string} powershellPath
82
- * @property {boolean} overlay
83
- * @property {boolean} logWorkerStderr
84
- * @property {boolean} takeoverAllowed
85
- * @property {boolean} keyInjectAllowed
86
- * @property {number} takeoverMaxMs
87
- * @property {number} takeoverArmMs
88
- * @property {number} snapshotMaxElements
89
- * @property {number} screenshotMaxWidth
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
96
- */
97
-
98
- /**
99
- * A refusal thrown before the worker is reached. The two extra fields are the whole point: the caller
100
- * path reads `err.refusal` for the code and `err.reason` for the sentence, so typing this as a plain
101
- * `Error` would lose the vocabulary that makes a refusal actionable.
102
- * @typedef {Error & {refusal?: RefusalCode, reason?: string}} WpmError
103
- */
104
-
105
- /**
106
- * One worker envelope, as engine.js documents it. `result` is deliberately `any`: its shape is the
107
- * PowerShell engine's JSON-lines protocol, and pretending to type it from this side would be the
108
- * "type safety over half the system" mistake in miniature.
109
- * @typedef {object} Envelope
110
- * @property {boolean} [ok]
111
- * @property {string} [error]
112
- * @property {any} [result]
113
- */
114
-
115
- /**
116
- * The Cordis context surface this plugin touches, and nothing more. `logger` is optional everywhere it
117
- * is used (`logger.warn?.(...)`) because a host that supplies no logger must still work.
118
- * @typedef {object} CordisContext
119
- * @property {{register: (tool: any) => void}} tools
120
- * @property {{info?: (m: string) => void, warn?: (m: string) => void}} [logger]
121
- * @property {(event: string, fn: () => void) => void} [on]
122
- */
123
-
124
- /** Stable Cordis plugin name (this is what a profile entry points at). */
125
- export const name = 'windows-parallel';
126
-
127
- /** Services that must exist before the tool can register. */
128
- export const inject = ['tools'];
129
-
130
- /**
131
- * The settings schema is resolved once, at module load, because Cordis reads `Config` synchronously
132
- * as a standard-schema value (it calls `Config['~standard'].validate(config)`). A factory function
133
- * here -- the first version of this file -- fails activation with
134
- * `Cannot read properties of undefined (reading 'validate')`, which is only visible by booting a real
135
- * profile. See lib/config.js.
136
- */
137
- const resolvedConfig = await createConfigSchema();
138
- export const Config = resolvedConfig.schema;
139
- export const configSource = resolvedConfig.source;
140
-
141
- /**
142
- * Resolved at module load, not inside `apply`. Cordis treats whatever `apply` returns as a
143
- * disposable effect, so an `async apply` returns a Promise and the plugin dies with "Invalid effect"
144
- * -- the second activation failure found by booting a real profile. Anything asynchronous therefore
145
- * has to finish before `apply` runs, which top-level await makes possible and keeps `apply` sync.
146
- */
147
- const resolvedTools = await resolveDefineTool();
148
- export const toolHelperSource = resolvedTools.source;
149
-
150
- /**
151
- * Register the tool. `apply` is the whole host half; there is no client half yet, which is
152
- * deliberate: the overlay / pill / hotkey layer is task_54 and gets its own commit. A plugin with a
153
- * working tool and no UI is usable; a plugin with UI and no working tool is a demo.
154
- * @param {CordisContext} ctx
155
- * @param {Record<string, any>} [config]
156
- * @returns {void}
157
- */
158
- export function apply(ctx, config = {}) {
159
- /** @type {WpmSettings} */
160
- const settings = {
161
- enabled: resolveSetting(config.enabled, true),
162
- settleMs: resolveSetting(config.settleMs, 350),
163
- requestTimeoutMs: resolveSetting(config.requestTimeoutMs, 20000),
164
- powershellPath: resolveSetting(config.powershellPath, ''),
165
- overlay: resolveSetting(config.overlay, true),
166
- logWorkerStderr: resolveSetting(config.logWorkerStderr, false),
167
- // ---- R3 gates. Both default false: with them off this build behaves exactly like 0.1.6, so an
168
- // upgrade cannot silently start moving the owner's cursor. The gates live HERE, before the worker,
169
- // because a prompt-level hint is not a switch (same reasoning as `enabled`/`paused`).
170
- takeoverAllowed: resolveSetting(config.takeoverAllowed, false) === true,
171
- keyInjectAllowed: resolveSetting(config.keyInjectAllowed, false) === true,
172
- takeoverMaxMs: clampNumber(resolveSetting(config.takeoverMaxMs, 10000), 500, 60000, 10000),
173
- takeoverArmMs: clampNumber(resolveSetting(config.takeoverArmMs, 800), 0, 5000, 800),
174
- // ---- 0.5.0 read-path settings. Forwarded, never silently clamped on the caller's behalf: the
175
- // engine is the one that reports what it actually used (maxElements/shotsKeep ride back on the
176
- // result), so "the setting took" is observable rather than assumed.
177
- snapshotMaxElements: clampNumber(resolveSetting(config.snapshotMaxElements, 300), 1, 5000, 300),
178
- screenshotMaxWidth: clampNumber(resolveSetting(config.screenshotMaxWidth, 0), 0, 7680, 0),
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),
190
- };
191
-
192
- const logger = ctx.logger ?? console;
193
- // ---- the marker -----------------------------------------------------------------------------
194
- // Deliberately fire-and-forget and deliberately AFTER the action has answered: this is a visual
195
- // aid, not part of the result, and making it synchronous would put 19ms (plus a one-time ~875ms
196
- // overlay start) on every click. Two rules keep it honest:
197
- // * it is fired after the action request resolves, so a slow overlay start can never delay the
198
- // action the user is waiting for;
199
- // * the first failure is WARNED, not swallowed -- an overlay that never appears would otherwise
200
- // make the README's "AI cursor is a click-through overlay" claim silently untrue.
201
- // Cost measured over the real worker protocol (.tmp/worker-overlay.mjs): start ~875ms once,
202
- // marker 19ms, status 15ms, stop ~660ms.
203
- /** @type {Promise<any>|null} */
204
- let overlayReady = null;
205
- let overlayWarned = false;
206
- const ensureOverlay = () => {
207
- if (overlayReady) return overlayReady;
208
- overlayReady = client.request({ action: 'overlay', on: true }).then((env) => {
209
- if (!env.ok) throw new Error(env.error || 'overlay start refused');
210
- const st = env.result?.state ?? {};
211
- if (!st.running) throw new Error(st.reason || 'overlay reported not running');
212
- if (st.hotkeyRegistered === false) {
213
- logger.warn?.(`[windows-parallel] pause hotkey unavailable: ${st.reason || 'RegisterHotKey failed'}`);
214
- } else if (st.hotkeyLabel && st.hotkeyLabel !== 'Ctrl+Alt+Q') {
215
- logger.warn?.(`[windows-parallel] Ctrl+Alt+Q is owned by another app; the pause key is ${st.hotkeyLabel}`);
216
- }
217
- return st;
218
- }).catch((err) => {
219
- overlayReady = null; // let the next action retry rather than latch off
220
- if (!overlayWarned) {
221
- overlayWarned = true;
222
- logger.warn?.(`[windows-parallel] marker overlay unavailable (${err.message}); actions still work`);
223
- }
224
- throw err;
225
- });
226
- return overlayReady;
227
- };
228
- /**
229
- * Place the marker at a PHYSICAL screen point. Never awaited by the caller path.
230
- * Placement RETRIES until the overlay reports running or a 6 s deadline passes -- not as a
231
- * bandage but because the old single-shot silently broke the shipped promise: a cold worker's
232
- * handshake can expire while the overlay is genuinely still starting (measured: WPF JIT past the
233
- * budget), the marker request was then skipped, and the click had already answered so nobody ever
234
- * retried. A promise with a race window is a promise that loses the race sometimes. The deadline
235
- * is BOUNDED and a confirmed-dead start (a reason with starting=false) stops the loop immediately
236
- * and warns -- endless patience would just hide a broken surface.
237
- * @param {number} x @param {number} y @returns {void}
238
- */
239
- const markPoint = (x, y) => {
240
- if (!settings.overlay || !Number.isFinite(x) || !Number.isFinite(y)) return;
241
- const mx = Math.round(x);
242
- const my = Math.round(y);
243
- void (async () => {
244
- await ensureOverlay().catch(() => {}); // kick the start; its own failures are warned there
245
- const deadline = Date.now() + 6000;
246
- for (;;) {
247
- const env = await client.request({ action: 'marker', x: mx, y: my }).catch(() => null);
248
- const res = env?.result;
249
- if (env?.ok && res?.ok !== false) return; // placed
250
- if (res && res.reason === 'overlay not running') {
251
- const st = await client.request({ action: 'overlay', on: true }).catch(() => null);
252
- const state = st?.result?.state;
253
- if (state && state.running) continue; // up now; retry placement
254
- if (state && !state.starting && state.reason) {
255
- if (!overlayWarned) {
256
- overlayWarned = true;
257
- logger.warn?.(`[windows-parallel] marker overlay failed to start (${state.reason}); actions still work`);
258
- }
259
- return; // dead for a named reason: stop
260
- }
261
- }
262
- if (Date.now() >= deadline) {
263
- if (!overlayWarned) {
264
- overlayWarned = true;
265
- logger.warn?.('[windows-parallel] marker was not placed within 6s of the click; actions still work');
266
- }
267
- return;
268
- }
269
- await new Promise((r) => setTimeout(r, 150));
270
- }
271
- })().catch(() => { /* warned inside; a marker must never become an unhandled rejection */ });
272
- };
273
- logger.info?.(`[windows-parallel] config schema: ${configSource}`);
274
- const client = new WorkerClient({
275
- powershellPath: settings.powershellPath,
276
- script: workerScript(),
277
- requestTimeoutMs: settings.requestTimeoutMs,
278
- onStderr: (line) => {
279
- if (settings.logWorkerStderr) logger.warn?.(`[wpm worker] ${line}`);
280
- },
281
- onExit: ({ code }) => {
282
- logger.warn?.(`[windows-parallel] engine worker exited (code=${code}); it will restart on the next call`);
283
- },
284
- });
285
-
286
- /**
287
- * Wire the host's cancellation into the worker. THE WORKER IS SINGLE-THREADED: while it is inside an
288
- * action it cannot read a new request, so an 'abort' request alone would be answered only after the
289
- * action it was meant to stop. The engine therefore polls a latch FILE at the path this writes, and
290
- * the worker request is sent as well (fire-and-forget) so an idle worker clears its flag too.
291
- * Two channels because one of them is a local file write that cannot be lost to a wedged loop.
292
- */
293
- const activeLatches = new Set();
294
- /** @param {WpmExec|undefined} exec @returns {() => void} */
295
- const armAbort = (exec) => {
296
- const signal = exec?.signal;
297
- if (!signal || typeof signal.addEventListener !== 'function') return () => {};
298
- const onAbort = () => {
299
- const pid = client.child?.pid;
300
- if (!pid) return;
301
- const latch = abortLatchPath(pid);
302
- try {
303
- mkdirSync(dirname(latch), { recursive: true });
304
- writeFileSync(latch, 'abort', 'utf8');
305
- activeLatches.add(latch);
306
- } catch { /* the HUD button and the abort chord remain available */ }
307
- void client.request({ action: 'abort' }).catch(() => {});
308
- };
309
- if (signal.aborted) { onAbort(); return () => {}; }
310
- signal.addEventListener('abort', onAbort, { once: true });
311
- return () => signal.removeEventListener('abort', onAbort);
312
- };
313
-
314
- const { defineTool } = resolvedTools;
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
-
350
- /** Build the worker request for one action. Throws for arguments the action cannot use. */
351
- /** @param {WpmArgs} args @returns {any} */
352
- function toRequest(args) {
353
- const settleMs = clampSettle(args.settleMs ?? settings.settleMs);
354
- // The takeover fields are attached ONLY when the caller asked for them AND the gate is open. When a
355
- // gate is closed the field is STRIPPED, not forwarded: a worker that received takeover:true would be
356
- // free to act on it, and the safe answer to "the gate is off" is the silent-tier request, which the
357
- // engine then refuses or serves by its own table (task_26).
358
- const takeover = args.takeover === true && settings.takeoverAllowed;
359
- const keyInput = takeover && args.keyInput === 'inject' && settings.keyInjectAllowed ? 'inject' : 'none';
360
- // takeoverArmMs is the OWNER's patience, not the caller's: it comes from settings and is forwarded so
361
- // the settings surface actually controls the pre-move cancellation window (a setting that never
362
- // reaches the engine is a form, not a switch).
363
- const takeoverFields = takeover
364
- ? {
365
- takeover: true,
366
- takeoverMaxMs: clampNumber(args.takeoverMaxMs, 500, 60000, settings.takeoverMaxMs),
367
- takeoverArmMs: settings.takeoverArmMs,
368
- ...(keyInput === 'inject' ? { keyInput } : {}),
369
- }
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
- };
380
- switch (args.action) {
381
- case 'windows':
382
- return { action: 'windows' };
383
- case 'status':
384
- return { action: 'status' };
385
- case 'snapshot':
386
- // A READ. maxElements is the SETTING unless the caller asked for a specific cap, and
387
- // interactableOnly defaults ON because the frame exists to be decided on, not to be dumped.
388
- requireArg(args, 'hwnd', 'snapshot');
389
- return {
390
- action: 'snapshot',
391
- hwnd: args.hwnd,
392
- maxElements: clampNumber(args.maxElements, 1, 5000, settings.snapshotMaxElements),
393
- interactableOnly: args.interactableOnly !== false,
394
- sinceSnapId: typeof args.sinceSnapId === 'string' ? args.sinceSnapId : '',
395
- intent: typeof args.intent === 'string' ? args.intent : '',
396
- };
397
- case 'screenshot':
398
- // fullScreen is the ONLY way to capture without naming a window, and it must be asked for:
399
- // silently capturing the owner's whole desktop would be exactly the overreach this product
400
- // refuses elsewhere. A non-fullscreen capture with no hwnd is refused here, before the worker.
401
- if (args.fullScreen !== true) requireArg(args, 'hwnd', 'screenshot');
402
- return {
403
- action: 'screenshot',
404
- hwnd: args.fullScreen === true ? (args.hwnd ?? '') : args.hwnd,
405
- fullScreen: args.fullScreen === true,
406
- maxWidth: clampNumber(args.maxWidth, 0, 7680, settings.screenshotMaxWidth),
407
- shotsKeep: settings.shotsKeep,
408
- };
409
- case 'preview':
410
- // Silent by construction: no click, no focus, no input queue entry. The engine draws the
411
- // marker and answers with the element UNDER the point as text.
412
- requireArg(args, 'hwnd', 'preview');
413
- requireArg(args, 'x', 'preview');
414
- requireArg(args, 'y', 'preview');
415
- return {
416
- action: 'preview', hwnd: args.hwnd,
417
- x: Math.round(/** @type {number} */ (args.x)),
418
- y: Math.round(/** @type {number} */ (args.y)),
419
- };
420
- case 'click':
421
- requireArg(args, 'hwnd', 'click');
422
- requireArg(args, 'x', 'click');
423
- requireArg(args, 'y', 'click');
424
- // The two casts state what `requireArg` just enforced: `WpmArgs.x/y` are optional in the
425
- // public contract (click requires them, windows does not), and the guard above is the only
426
- // thing that narrows them. A checker cannot see through a separate function's throw, so this
427
- // is where the guarantee is recorded -- not a suppression, since requireArg throws for both
428
- // undefined and null before this line is reached.
429
- //
430
- // THE COORDINATE SPACE IS EXPLICIT. 'image' without a shotId is refused HERE, before any worker
431
- // request: image pixels only mean something relative to a capture, and reinterpreting them as
432
- // screen pixels would click somewhere plausibly wrong -- the exact failure mode `stale_ref`
433
- // exists for. A label rides along with its snapId so the engine can resolve the ELEMENT.
434
- const space = args.space === 'image' ? 'image' : 'screen';
435
- if (space === 'image' && (typeof args.shotId !== 'string' || args.shotId === '')) {
436
- 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');
437
- }
438
- return {
439
- action: 'click', hwnd: args.hwnd, x: Math.round(/** @type {number} */ (args.x)), y: Math.round(/** @type {number} */ (args.y)), settleMs,
440
- ...authFields,
441
- ...(space === 'image' ? { space: 'image', shotId: args.shotId } : {}),
442
- ...(typeof args.label === 'number' && args.label > 0
443
- ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
444
- : {}),
445
- ...takeoverFields,
446
- };
447
- case 'type':
448
- requireArg(args, 'hwnd', 'type');
449
- if (typeof args.text !== 'string' || args.text.length === 0) {
450
- // Refused here rather than sent: a write of nothing succeeds silently on every channel,
451
- // so an empty string is indistinguishable from a dead door.
452
- throw refusal('unreachable', 'type needs a non-empty text; an empty write cannot be verified');
453
- }
454
- return {
455
- action: 'type', hwnd: args.hwnd, text: args.text,
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',
465
- ...(typeof args.label === 'number' && args.label > 0
466
- ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
467
- : {}),
468
- ...takeoverFields,
469
- };
470
- case 'focus':
471
- requireArg(args, 'hwnd', 'focus');
472
- if ((typeof args.label !== 'number' || args.label <= 0)) requireArg(args, 'elementName', 'focus');
473
- return {
474
- action: 'focus', hwnd: args.hwnd, elementName: args.elementName ?? '', settleMs,
475
- ...authFields,
476
- ...(typeof args.label === 'number' && args.label > 0
477
- ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
478
- : {}),
479
- ...takeoverFields,
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
- }
533
- default:
534
- throw refusal('no_hwnd', `unknown action '${args.action}'`);
535
- }
536
- }
537
-
538
- const tool = defineTool({
539
- name: TOOL_NAME,
540
- description:
541
- 'Drive a Windows window: click at a screen coordinate, write text, or move focus inside ONE named '
542
- + 'window, choosing the cheapest available door. Two tiers are silent: a classic child window is '
543
- + 'addressed with window messages (measured: zero foreground changes), and a window that only '
544
- + 'exposes a UI Automation pattern costs one bounded foreground flash that is reversed once '
545
- + 'afterwards (measured net return 15-95 ms). A THIRD tier exists and is opt-in: takeover:true may '
546
- + 'move the real cursor to the action point (always restored), hold the focus until the action ends, '
547
- + 'and -- with keyInput:"inject" -- type into the foreground target through synthetic keyboard input '
548
- + 'for windows that have no message door and no accessible pattern (terminals). Takeover is refused '
549
- + 'unless the owner enabled it, always shows a three-phase HUD with a stop button and a global abort '
550
- + 'key, is interruptible three ways, and never injects mouse events. '
551
- + 'THREE READ ACTIONS make the target legible without guessing: snapshot returns a NUMBERED element '
552
- + 'table (a continuous `label`, control type, name, automation id, rect, patterns) that click/type/'
553
- + 'focus accept as `label`+`snapId`; screenshot writes the window rect to a PNG and returns '
554
- + 'screenRect/imageSize/scale/identity/frame as data so image coordinates can be handed straight '
555
- + 'back to click with space:"image" (the engine converts, the caller never multiplies); preview '
556
- + 'draws the marker at a point and reports, as TEXT, the element under it -- a reviewable click that '
557
- + 'needs no picture. Refusals carry a code (no_hwnd, '
558
- + 'paused, elevated_target, unreachable, uia_tree_empty, uia_probe_failed, terminal_no_door, needs_facts, action_failed, '
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. '
567
- + 'Start with action=windows to get an hwnd, action=snapshot to read a frame, or action=status to see '
568
- + 'what currently holds the foreground.',
569
- parameters: PARAMETERS,
570
- output: {
571
- schema: {
572
- type: 'object',
573
- additionalProperties: true,
574
- properties: {
575
- action: { type: 'string', required: true },
576
- ok: { type: 'boolean', required: true },
577
- refusal: { type: 'string' },
578
- text: { type: 'string', required: true },
579
- },
580
- },
581
- // `WpmResult.text` is optional in the public contract (a consumer may hold a partial object),
582
- // but every value that reaches this render is built by `result()` below, which always sets it.
583
- // The cast records that invariant instead of substituting '' -- an empty string would be a
584
- // rendered blank, and the text IS the product here.
585
- /** @param {WpmArgs} _args @param {WpmResult} value @returns {Array<{type: string, text: string}>} */
586
- render: (_args, value) => [{ type: 'text', text: /** @type {string} */ (value.text) }],
587
- },
588
- /** @param {WpmArgs} args @param {WpmExec|undefined} exec @returns {Promise<Record<string, any>>} */
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
- };
610
- // Server-side gates first: a paused or disabled engine must refuse before it spends a worker
611
- // call, and the refusal must name the gate rather than describe a symptom.
612
- if (!settings.enabled) {
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)' : ''}`));
627
- }
628
- // ---- R3 gates, BEFORE the worker. A refused takeover costs zero worker requests, which is
629
- // asserted with a request counter in test/plugin-test.mjs: "the gate is checked" is otherwise
630
- // indistinguishable from "the gate is checked after the expensive part".
631
- if (args.takeover === true && !settings.takeoverAllowed) {
632
- return finish(result(args.action, false, 'takeover_unavailable',
633
- 'takeoverAllowed is off in settings; the action was refused rather than silently downgraded to the quiet tier. '
634
- + 'The quiet tier still works without takeover:true' + hwndHint(args)));
635
- }
636
- if (args.keyInput === 'inject' && (!settings.keyInjectAllowed || args.takeover !== true)) {
637
- return finish(result(args.action, false, 'keyinject_unavailable',
638
- args.takeover !== true
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'
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
- }
661
- }
662
- // A pre-worker refusal is still a refusal, not a thrown error. The first version of this file
663
- // let `toRequest` throw for an empty write, and the caller saw a crashed tool call instead of
664
- // `unreachable` -- the exact "refusal became an exception" defect this plugin's own comment
665
- // above warns about. Caught by test/plugin-test.mjs, which asserts the code is returned.
666
- let request;
667
- try {
668
- request = toRequest(args);
669
- } catch (err) {
670
- // `catch` binds `unknown` under strict, which is correct: anything can be thrown. The casts
671
- // are the narrowing step, kept INLINE so the statements and local names below are exactly what
672
- // they were -- `scripts`-level AST comparison against the previous revision is a gate here, and
673
- // a rename would make a comment-only change look like a behaviour change. Safe on this path
674
- // because the only thrower is `refusal()` above; the `??` fallbacks still keep the vocabulary
675
- // intact when it is not.
676
- const code = /** @type {WpmError} */ (err)?.refusal ?? 'action_failed';
677
- return finish(result(args.action, false, code, /** @type {WpmError} */ (err)?.reason ?? String(/** @type {WpmError} */ (err)?.message ?? err)));
678
- }
679
- let envelope;
680
- const disarm = request.takeover ? armAbort(exec) : () => {};
681
- try {
682
- envelope = await client.request(request);
683
- } catch (err) {
684
- // The worker layer failed (crash, timeout, missing engine). This is not a refusal code: the
685
- // engine never got to decide. Say exactly that instead of borrowing a code it does not own.
686
- // Cast inline for the same reason as above. No `String(...)` wrapper and no `?.` are added:
687
- // the original read `err.message` directly, and a non-Error thrown here still renders the
688
- // same way it always did -- widening the expression would be a behaviour change dressed as
689
- // type safety, which is exactly what this file refuses to do.
690
- return finish(result(args.action, false, 'action_failed', `engine worker unavailable: ${/** @type {Error} */ (err).message}`));
691
- } finally {
692
- disarm();
693
- }
694
- if (!envelope.ok) {
695
- return finish(result(args.action, false, 'action_failed', `worker error: ${envelope.error ?? 'unknown'}`));
696
- }
697
- // click coordinates are SCREEN pixels (the engine converts to client space itself), so the
698
- // marker can be placed straight from the request -- no second coordinate system to get wrong.
699
- // Only a click that actually ran places a marker: a refused click has no impact point, and
700
- // letting a refusal start the overlay would mean a dead hwnd silently spawns a WPF window.
701
- const r = envelope.result;
702
- if (request.action === 'click' && r && r.ok !== false && !r.refusal) {
703
- // With space:'image' the request coordinates are IMAGE pixels; the engine reports the screen
704
- // point it actually converted to, and the marker must be drawn THERE. Drawing it at the image
705
- // pixel would put the visible cursor somewhere other than where the click landed -- a marker
706
- // that lies is worse than no marker, because the README sells it as the point that was acted on.
707
- const screen = request.space === 'image' ? parsePoint(r.screenPoint) : null;
708
- markPoint(screen ? screen.x : request.x, screen ? screen.y : request.y);
709
- }
710
- return finish(format(args.action, envelope.result));
711
- },
712
- });
713
-
714
- ctx.tools.register(tool);
715
- ctx.on?.('dispose', () => {
716
- // A latch that outlives the worker would abort the NEXT worker's first takeover (the path is keyed
717
- // by pid, so a new process gets a new path -- this is belt and braces, and it keeps %LOCALAPPDATA%
718
- // tidy for an operator reading it).
719
- for (const latch of activeLatches) { try { rmSync(latch, { force: true }); } catch { } }
720
- activeLatches.clear();
721
- void client.dispose();
722
- });
723
- // No return value. Cordis treats whatever `apply` returns as a disposable effect, so returning the
724
- // registered tool is at best ignored and at worst an "Invalid effect" that disables the plugin --
725
- // the same class of failure as the async apply, one step further in.
726
- }
727
-
728
- // ---- small helpers ---------------------------------------------------------------------------
729
-
730
- /** A Cordis settings value may be a live ref (0.1.7+) or a plain value (older lines). */
731
- /** @param {any} value @param {any} fallback @returns {any} */
732
- function resolveSetting(value, fallback) {
733
- if (value === undefined || value === null) return fallback;
734
- const v = typeof value.get === 'function' ? value.get() : value;
735
- if (v === undefined || v === null) return fallback;
736
- return v;
737
- }
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
-
762
- /** @param {any} value @returns {number} */
763
- function clampSettle(value) {
764
- const n = Number(value);
765
- if (!Number.isFinite(n)) return 350;
766
- return Math.max(0, Math.min(2000, Math.round(n)));
767
- }
768
-
769
- /**
770
- * @param {Record<string, any>} args
771
- * @param {'hwnd'|'x'|'y'|'text'|'elementName'|'target'} key
772
- * @param {string} action
773
- * @returns {void}
774
- */
775
- function requireArg(args, key, action) {
776
- if (args[key] === undefined || args[key] === null || args[key] === '') {
777
- throw refusal('no_hwnd', `action=${action} requires '${key}'`);
778
- }
779
- }
780
-
781
- /**
782
- * A refusal thrown before the worker is reached; caught by the caller path that renders results.
783
- * @param {RefusalCode} code
784
- * @param {string} reason
785
- * @returns {WpmError}
786
- */
787
- function refusal(code, reason) {
788
- // The cast is the definition of this function's payload: a plain Error plus the two fields the
789
- // caller path reads. Writing it after construction (rather than using a subclass) keeps `instanceof
790
- // Error` true for the host, which is what the catch sites rely on.
791
- const err = /** @type {WpmError} */ (new Error(`${code}: ${reason}`));
792
- err.refusal = code;
793
- err.reason = reason;
794
- return err;
795
- }
796
-
797
- /**
798
- * @param {string} action
799
- * @param {boolean} ok
800
- * @param {RefusalCode|''} refusalCode
801
- * @param {string} text
802
- * @param {Record<string, any>} [extra]
803
- * @returns {Record<string, any>}
804
- */
805
- function result(action, ok, refusalCode, text, extra) {
806
- return { action, ok, refusal: refusalCode, text: refusalCode ? `${refusalCode}: ${text}` : text, ...(extra || {}) };
807
- }
808
-
809
- /**
810
- * Turn a worker result into the tool's output value.
811
- *
812
- * The text is the product. A caller that gets `ok:false` with a code and a reason can act; a caller
813
- * that gets "the action failed" cannot. Every number reported here is measured by the engine, not
814
- * inferred by this file.
815
- * @param {string} action
816
- * @param {any} r
817
- * @returns {Record<string, any>}
818
- */
819
- function format(action, r) {
820
- if (!r) return result(action, false, 'action_failed', 'engine returned no result');
821
-
822
- if (action === 'windows') {
823
- const list = Array.isArray(r.windows) ? r.windows : [];
824
- if (list.length === 0) {
825
- return result(action, true, '', 'no drivable windows are visible right now (minimised and untitled windows are excluded by design)');
826
- }
827
- const lines = list.map(/** @param {any} w @returns {string} */ (w) => `${w.hwnd} ${truncate(String(w.title), 60)} [${w.cls}] pid=${w.pid} rect=${w.rect}`);
828
- return result(action, true, '', `${list.length} drivable window(s):\n${lines.join('\n')}`);
829
- }
830
-
831
- if (action === 'status') {
832
- const bits = [
833
- `paused=${r.paused === true}`,
834
- `foreground=${r.foreground || '(none)'}`,
835
- `foregroundPid=${r.foregroundPid || '(none)'}`,
836
- `focusedControl=${r.focusControl || '(none)'}`,
837
- `lastHumanInputAgeMs=${r.lastInputAgeMs ?? 'unknown'}`,
838
- ];
839
- // The control surface travels with status. Without it, "the overlay is on" and "the pause key
840
- // registered" are claims the user cannot check -- and this machine's desktop already owns
841
- // Ctrl+Alt+Q, so the real chord is not the documented one. Silence here would be a lie.
842
- bits.push(`overlay=${r.overlayRunning === true ? 'on' : 'off'}`);
843
- // The takeover surface, on the same principle: the owner must be able to check "is the HUD up and
844
- // which abort key is real" without inferring it from a successful call.
845
- bits.push(`hud=${r.hudOn === true ? 'on' : 'off'}`);
846
- if (r.abortChord) bits.push(`abortChord=${r.abortChord}`);
847
- // The overlay's hwnd, so an INDEPENDENT oracle can verify the exact window the product thinks
848
- // it is showing. Title-matching alone cannot do this: a leaked overlay from an earlier run is
849
- // also titled WpmOverlay, and grading that instead of ours would make the marker arms grade
850
- // homework that is not even in this class.
851
- if (r.overlayHwnd && r.overlayHwnd !== '0') bits.push(`overlayHwnd=${r.overlayHwnd}`);
852
- bits.push(`pauseHotkey=${r.hotkeyRegistered === true ? (r.hotkeyLabel || 'registered') : 'unavailable'}`);
853
- if (r.overlayReason) bits.push(`overlayNote=${r.overlayReason}`);
854
- if (r.pauseReason) bits.push(`pauseReason=${r.pauseReason}`);
855
- // The DPI stance is a FACT the read paths depend on: rects and captured pixels are physical only
856
- // while this process is per-monitor DPI aware. Reporting it here is what keeps a future deletion of
857
- // the setter from turning into a silent half-scale coordinate system (the marker already proved
858
- // that failure mode: 470,410 acted on at 303,263 on this 150% display).
859
- bits.push(`dpiAware=${r.dpiAware === true}`);
860
- if (r.stance) bits.push(`stance: ${r.stance}`);
861
- return result(action, true, '', bits.join('\n'));
862
- }
863
-
864
- // Action results. `refusal` is the engine's own code: an empty string means the action ran.
865
- // The cast leans on `scripts/check-refusals.mjs`, which pins the engine's emitted codes to the
866
- // closed set in src/schema/tools.json: the wire format is a string, but the vocabulary is a
867
- // contract that another gate already enforces. Typing this as plain `string` would push the check
868
- // to every call site; typing it as `RefusalCode` names where the guarantee actually comes from.
869
- const code = r.refusal ? /** @type {RefusalCode} */ (String(r.refusal)) : '';
870
- if (code) {
871
- const reason = r.reason ? ` (${r.reason})` : '';
872
- // A takeover refusal still carries the takeover accounting: "aborted after 12 characters, cursor
873
- // restored" is the information that makes an interruption harmless instead of alarming.
874
- if (r.takeover === 'true') {
875
- const extra = ` [takeover=on cursorRestored=${r.cursorRestored === 'true'} injectedChars=${r.injectedChars ?? 0}`
876
- + `${r.abortChord ? ` abortChord=${r.abortChord}` : ''}]`;
877
- return result(action, false, code, `${code}${reason}${extra}`, {
878
- takeover: 'on', cursorRestored: r.cursorRestored === 'true', injectedChars: r.injectedChars ?? 0,
879
- });
880
- }
881
- return result(action, false, code, `${code}${reason}`);
882
- }
883
-
884
- // ---- 0.5.0 READ RESULTS ---------------------------------------------------------------------
885
- // These three have no channel, no tier and no proof window: there is no action to prove. Rendering
886
- // happens HERE (not in the engine) for the same reason every other action's text does -- one place
887
- // owns "what the model reads", and the engine stays a JSON protocol.
888
- if (action === 'snapshot') return formatSnapshot(r);
889
- if (action === 'screenshot') return formatScreenshot(r);
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);
899
-
900
- // WHO REPORTED THE SUCCESS. The engine sets `effect` when a channel call RETURNS without throwing;
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):
903
- // unverified no channel reported success at all;
904
- // reported-by-send the window message was DELIVERED -- nothing here proves the target app
905
- // processed it;
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".
914
- const bits = [
915
- `${action} ok`,
916
- `channel=${r.channel || '?'}`,
917
- `tier=${r.tier || '?'}`,
918
- `effect=${r.effect || 'unverified'}`,
919
- `focusTaken=${r.focusTaken === 'true' || r.focusTaken === true}`,
920
- ];
921
- // The takeover accounting. Every number here was measured by the engine (cursor read-backs, the
922
- // injected-character counter, the chord that actually registered) -- nothing in this file infers it.
923
- if (r.takeover === 'true') {
924
- bits.push('takeover=on');
925
- bits.push(`cursorMoved=${r.cursorMoved === 'true'}`);
926
- bits.push(`cursorRestored=${r.cursorRestored === 'true'}`);
927
- if (r.takeoverMs !== undefined) bits.push(`takeoverMs=${r.takeoverMs}`);
928
- if (r.abortChord) bits.push(`abortChord=${r.abortChord}`);
929
- if (r.keysInjected !== undefined) bits.push(`keysInjected=${r.keysInjected}`);
930
- bits.push(`injectedChars=${r.injectedChars ?? 0}`);
931
- if (r.cursorRestoreReason) bits.push(`cursorRestoreReason=${r.cursorRestoreReason}`);
932
- if (r.takeoverNote) bits.push(`takeoverNote=${r.takeoverNote}`);
933
- }
934
- // THE PROOF. The engine sampled cursor/foreground/focus/last-input-age in TWO windows: a short
935
- // pre-action CONTROL (captured while, by construction, nothing was done) and the settle window
936
- // AFTER the door call. The judgment is arithmetic and lives in one pure implementation
937
- // (proof-window.mjs), never here and never in the README. Three verdicts, and their asymmetry is
938
- // the whole point -- see proof-window.mjs's header for the idle-baseline measurement behind it:
939
- // pass no unexplained cursor gap, no unexplained foreground/focus switch;
940
- // inconclusive the desktop moved or switched in a way position data cannot attribute to the
941
- // action (the idle baseline proved our absence does not imply desktop stillness);
942
- // fail a foreground/focus switch the control shows the desktop was NOT doing, on a tier
943
- // that did not DECLARE a bounded flash.
944
- // `declaredFlash` is the decision table's own needsRestore: on the bounded-flash tier the engine
945
- // DELIBERATELY raises foreground inside the window and restores it after -- the promise of that
946
- // tier was never "don't touch", it is "don't keep", and the restore table owns that promise
947
- // (restore_failed surfaces separately). Sampling cannot be allowed to contradict the contract.
948
- // A missing/short window is 'insufficient': silence is not innocence.
949
- const proof = evaluateProof(r.proofSamples || [], {
950
- control: r.proofControl || [],
951
- declaredFlash: r.tier === 'bounded-flash',
952
- // The takeover tier DELIBERATELY moves the cursor and may hold the foreground; the promise it makes
953
- // is "nothing was kept", not "nothing was touched". A cursor that was not restored still fails, and
954
- // does so through the same evaluator instead of a special case here.
955
- declaredTakeover: r.tier === 'takeover',
956
- cursorRestored: r.cursorRestored === 'false' ? false : undefined,
957
- // The effect travels into the judgment, not just into the text. Without this, "nothing worked"
958
- // still reads as proof=pass whenever the desktop happened to stay still (R2 in the plan). One call
959
- // is one action, so `actions` is left to batch callers; a channel that reported NOTHING here caps
960
- // the verdict at inconclusive rather than inventing a red on a single quiet call.
961
- effect: r.effect || 'unverified',
962
- });
963
- bits.push(`proof=${proof.verdict}(${proof.reason})`);
964
- if (r.restoreOutcome) bits.push(`restore=${r.restoreOutcome}`);
965
- if (r.flashMs !== undefined) bits.push(`flashMs=${r.flashMs}`);
966
- if (r.latencyMs !== undefined) bits.push(`latencyMs=${r.latencyMs}`);
967
- if (r.detail) bits.push(`detail=${r.detail}`);
968
- return result(action, true, '', bits.join(' '), {
969
- proof: proof.verdict,
970
- proofDimensions: proof.dimensions,
971
- effect: r.effect || 'unverified',
972
- // A converted point travels back with the result so the caller can check the arithmetic it never
973
- // performed. `screenPoint` is the fact the marker is drawn from, too: with space:'image' the
974
- // request's own x/y are image pixels and would put the visible marker in the wrong place.
975
- ...(r.coordSpace === 'image'
976
- ? { coordSpace: 'image', shotId: r.shotId, imagePoint: r.imagePoint, screenPoint: r.screenPoint, scale: r.scale }
977
- : {}),
978
- ...(r.takeover === 'true'
979
- ? { takeover: 'on', cursorRestored: r.cursorRestored === 'true', injectedChars: r.injectedChars ?? 0 }
980
- : {}),
981
- });
982
- }
983
-
984
- /** @param {string} s @param {number} n @returns {string} */
985
- function truncate(s, n) {
986
- return s.length <= n ? s : `${s.slice(0, n - 1)}…`;
987
- }
988
-
989
- /**
990
- * One element row of a snapshot frame. The format is the contract the caller reasons on, so it is
991
- * fixed here: `label ControlType "Name" [AutomationId] rect=l,t,r,b patterns=...`. The label is
992
- * what a deciding side answers with; the rect is in PHYSICAL screen pixels, in the same space as
993
- * screenRect, which is what makes `space:"image"` conversion possible without a second coordinate table.
994
- * @param {any} e @returns {string}
995
- */
996
- function elementLine(e) {
997
- const rc = e?.rect ?? {};
998
- const pats = Array.isArray(e?.patterns) ? e.patterns : [];
999
- return `${e?.label ?? '?'} ${e?.controlType ?? '?'} "${e?.name ?? ''}" [${e?.automationId ?? ''}] `
1000
- + `rect=${rc.left ?? '?'},${rc.top ?? '?'},${rc.right ?? '?'},${rc.bottom ?? '?'} `
1001
- + `patterns=${pats.length ? pats.join('|') : 'none'}`;
1002
- }
1003
-
1004
- /**
1005
- * Render a snapshot frame.
1006
- *
1007
- * WHY THE DELTA IS A FIRST-CLASS FORM. Repeating an unchanged 70-row table between two steps is the
1008
- * dominant token cost of a multi-step flow, and it is pure noise: nothing in it changed. With
1009
- * `sinceSnapId` the answer is "no changes" plus the three lists that DID move. The full table stays
1010
- * available -- this is an option, not a replacement.
1011
- * @param {any} r @returns {Record<string, any>}
1012
- */
1013
- function formatSnapshot(r) {
1014
- const rows = Array.isArray(r.elements) ? r.elements : [];
1015
- const count = Number.isFinite(r.count) ? Number(r.count) : rows.length;
1016
- const total = Number.isFinite(r.total) ? Number(r.total) : count;
1017
- const truncated = r.truncated === true || r.truncated === 'true';
1018
- const delta = r.delta && typeof r.delta === 'object' ? r.delta : null;
1019
- const added = Array.isArray(delta?.added) ? delta.added : [];
1020
- const removed = Array.isArray(delta?.removed) ? delta.removed : [];
1021
- const changed = Array.isArray(delta?.changed) ? delta.changed : [];
1022
-
1023
- const head = `snapshot ok: ${count} element(s)`
1024
- + (truncated ? ` (truncated at ${count} of ${total})` : '')
1025
- + (delta ? ` (delta vs ${delta.sinceSnapId}: +${added.length} -${removed.length} ~${changed.length})` : '');
1026
- const meta = [`snapId=${r.snapId || '?'}`, `frame=${r.frame || '?'}`, `frameCheck=${r.frameCheck || '?'}`, `total=${total}`];
1027
- if (r.frameInset && typeof r.frameInset === 'object') {
1028
- meta.push(`frameInset=${r.frameInset.left ?? '?'},${r.frameInset.top ?? '?'},${r.frameInset.right ?? '?'},${r.frameInset.bottom ?? '?'}`);
1029
- }
1030
- if (Number.isFinite(r.outsideFrame) && Number(r.outsideFrame) > 0) {
1031
- meta.push(`outsideFrame=${r.outsideFrame}`);
1032
- }
1033
- if (r.intent) meta.push(`intent=${r.intent}`);
1034
- const lines = [head, meta.join(' ')];
1035
-
1036
- if (delta) {
1037
- if (added.length === 0 && removed.length === 0 && changed.length === 0) {
1038
- lines.push(`no changes since ${delta.sinceSnapId}`);
1039
- } else {
1040
- for (const a of added) lines.push(` + ${elementLine(a)}`);
1041
- for (const m of removed) lines.push(` - ${elementLine(m)}`);
1042
- for (const c of changed) lines.push(` ~ ${elementLine(c)} changed=${(Array.isArray(c.changed) ? c.changed : []).join(',')}`);
1043
- }
1044
- } else if (count === 0) {
1045
- // A REAL ANSWER, said out loud. This deliberately does NOT reuse uia_tree_empty: that code means
1046
- // "UI Automation is switched off in the application" and its next step is relaunching the app.
1047
- // Zero visible elements on a window that answers fine (measured: Clash, Everything) has no such
1048
- // next step, so inventing one would be the canned message this product refuses.
1049
- lines.push('0 element(s) is a real state: this window exposes no visible element to UI Automation right now. '
1050
- + 'It is not uia_tree_empty (that code is about the application disabling accessibility) and it is not a failure.');
1051
- } else {
1052
- for (const e of rows) lines.push(elementLine(e));
1053
- }
1054
- if (r.frame === 'win32') {
1055
- lines.push('note: frame=win32 -- DWM EXTENDED_FRAME_BOUNDS was unavailable, so this frame came from GetWindowRect and includes the invisible resize shadow. '
1056
- + '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.');
1057
- }
1058
- if (r.frameCheck === 'unknown') {
1059
- 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.');
1060
- }
1061
- if (Number(r.outsideFrame) > 0) {
1062
- 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.`);
1063
- }
1064
- return result('snapshot', true, '', lines.join('\n'), {
1065
- snapId: r.snapId, elements: rows, count, total, truncated, frameCheck: r.frameCheck, intent: r.intent ?? '',
1066
- // The delta travels structurally too: a caller that branches on "did anything move" must not have
1067
- // to parse the text, and the counts are the same numbers the head line prints.
1068
- ...(delta ? { delta } : {}),
1069
- ...(r.frameInset ? { frameInset: r.frameInset } : {}),
1070
- ...(Number.isFinite(r.outsideFrame) ? { outsideFrame: Number(r.outsideFrame) } : {}),
1071
- });
1072
- }
1073
-
1074
- /**
1075
- * Render a screenshot: the mapping is the product, the file is the delivery.
1076
- * @param {any} r @returns {Record<string, any>}
1077
- */
1078
- function formatScreenshot(r) {
1079
- const rect = r.screenRect && typeof r.screenRect === 'object' ? r.screenRect : {};
1080
- const size = r.imageSize && typeof r.imageSize === 'object' ? r.imageSize : {};
1081
- const scale = typeof r.scale === 'number' ? r.scale : 1;
1082
- const identity = r.identity === true || r.identity === 'true';
1083
- const dpiAware = r.dpiAware === true || r.dpiAware === 'true';
1084
- const lines = [
1085
- `screenshot ok: ${size.width ?? '?'}x${size.height ?? '?'} px (scale=${scale} identity=${identity}) frame=${r.frame || '?'} captureBackend=${r.captureBackend || '?'} dpiAware=${dpiAware}`,
1086
- `file=${r.file || '?'}`,
1087
- `shotId=${r.shotId || '?'}`,
1088
- `screenRect=${rect.left ?? '?'},${rect.top ?? '?'},${rect.right ?? '?'},${rect.bottom ?? '?'} `
1089
- + `imageSize=${size.width ?? '?'}x${size.height ?? '?'} bytes=${r.bytes ?? '?'} shotsKeep=${r.shotsKeep ?? '?'} latencyMs=${r.latencyMs ?? '?'}`,
1090
- 'mapping: screenX = screenRect.left + round(imageX / scale); screenY = screenRect.top + round(imageY / scale). '
1091
- + `The ENGINE applies this when a click passes space:"image" with shotId=${r.shotId || '?'}; do not multiply it yourself.`,
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.`);
1099
- if (identity) {
1100
- lines.push('identity=true means the image was NOT resampled: image pixels and screen pixels differ only by the rect origin.');
1101
- }
1102
- if (r.frame === 'win32') {
1103
- lines.push('note: frame=win32 -- DWM EXTENDED_FRAME_BOUNDS was unavailable, so screenRect came from GetWindowRect and includes the invisible shadow. '
1104
- + 'Coordinates stay consistent with THIS capture, but a click at the very edge can land on the shadow rather than the client area.');
1105
- }
1106
- return result('screenshot', true, '', lines.join('\n'), {
1107
- shotId: r.shotId, file: r.file, screenRect: rect, imageSize: size,
1108
- scale, identity, frame: r.frame, captureBackend: r.captureBackend, dpiAware,
1109
- });
1110
- }
1111
-
1112
- /**
1113
- * Render a preview. The report is text on purpose: "what is under that point" is answered by the OS,
1114
- * so confirming a point never depends on the model's reading of a picture.
1115
- * @param {any} r @returns {Record<string, any>}
1116
- */
1117
- function formatPreview(r) {
1118
- const x = r.previewX ?? '?';
1119
- const y = r.previewY ?? '?';
1120
- const atPoint = r.previewAtPoint === true || r.previewAtPoint === 'true';
1121
- const head = atPoint && r.previewControlType
1122
- ? `preview: would click ${x},${y} -> ${r.previewControlType} "${r.previewName || ''}"`
1123
- + (r.previewAutomationId ? ` [${r.previewAutomationId}]` : '')
1124
- : `preview: would click ${x},${y} -> no element is exposed at that point`;
1125
- const rect = r.previewRect && typeof r.previewRect === 'object' ? r.previewRect : {};
1126
- const lines = [
1127
- head,
1128
- `rect=${rect.left ?? '?'},${rect.top ?? '?'},${rect.right ?? '?'},${rect.bottom ?? '?'}`,
1129
- `marker=${r.markerPlaced === true || r.markerPlaced === 'true' ? 'placed' : 'unavailable'}${r.markerReason ? ` (${r.markerReason})` : ''}`,
1130
- ];
1131
- if (r.previewReason) lines.push(`reason: ${r.previewReason}`);
1132
- lines.push('no click was sent: a preview writes no input-queue entry, takes no focus, and produces no proof window');
1133
- return result('preview', true, '', lines.join('\n'), {
1134
- preview: {
1135
- x, y,
1136
- name: r.previewName ?? '', controlType: r.previewControlType ?? '', automationId: r.previewAutomationId ?? '',
1137
- },
1138
- });
1139
- }
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
-
1216
- /** Parse an engine-emitted "x,y" point. Returns null for anything else rather than guessing 0,0. */
1217
- /** @param {any} s @returns {{x: number, y: number}|null} */
1218
- function parsePoint(s) {
1219
- if (typeof s !== 'string') return null;
1220
- const m = s.match(/^(-?\d+),(-?\d+)$/);
1221
- if (!m) return null;
1222
- return { x: Number(m[1]), y: Number(m[2]) };
1223
- }
1224
-
1225
- /** Clamp a possibly-undefined number into [min,max], falling back to `fallback` for non-numbers. */
1226
- /** @param {any} value @param {number} min @param {number} max @param {number} fallback @returns {number} */
1227
- function clampNumber(value, min, max, fallback) {
1228
- const n = Number(value);
1229
- if (!Number.isFinite(n)) return fallback;
1230
- return Math.max(min, Math.min(max, Math.round(n)));
1231
- }
1232
-
1233
- /** The same latch path the engine computes: %LOCALAPPDATA%\wpm\takeover-abort.<worker pid>. */
1234
- /** @param {number|string} pid @returns {string} */
1235
- function abortLatchPath(pid) {
1236
- const base = process.env.LOCALAPPDATA || tmpdir();
1237
- return join(base, 'wpm', `takeover-abort.${pid}`);
1238
- }
1239
-
1240
- /** A one-line target hint for a pre-worker refusal: the caller can retry without the field. */
1241
- /** @param {WpmArgs} args @returns {string} */
1242
- function hwndHint(args) {
1243
- return args.hwnd ? ` (target hwnd=${args.hwnd})` : '';
1244
- }
1245
-
1246
- // Exported for tests: the projection from the five contract actions to this one tool.
1247
- // `formatResult` is here so the effect dimension can be asserted on the SHIPPED projection, with
1248
- // hand-authored engine results, without a desktop that has to cooperate.
1249
- export const _internals = { PARAMETERS, ACTIONS, TOOL_NAME, clampSettle, CONFIG_DEFAULTS, formatResult: format };
1
+ // index.js — the host half: one tool, one worker, and the refusal vocabulary kept intact.
2
+ //
3
+ // THE SHAPE OF THIS FILE IS THE FORM DECISION. R3.1' in spec.md recorded the fork as
4
+ // A. DSH native plugin: the host registers the tool directly; PowerShell is a sidecar.
5
+ // B. MCP server: the host talks to a separate MCP process over stdio.
6
+ // The owner chose A on 2026-11-19. Concretely that means: no `@modelcontextprotocol/sdk`, no bridge
7
+ // row, no second Node process — the tool is registered here and the only child process is the
8
+ // PowerShell worker, which the engine already needed in either form.
9
+ //
10
+ // WHY ONE TOOL AND NOT FIVE. src/schema/tools.json names eight actions as the contract surface. The
11
+ // host convention (shell / terminal / read / write in this same build) is one tool with an action
12
+ // discriminator, because every registered tool is resident schema on every turn — eight entries
13
+ // describing one engine is a standing token cost for no gain in capability. The contract is
14
+ // preserved exactly: same eight actions, same fourteen refusal codes, same required arguments. The
15
+ // mapping is asserted in test/plugin-test.mjs against the contract file, so "we project to one tool"
16
+ // cannot quietly become "we support 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.
19
+ //
20
+ // THE THREE THINGS THIS FILE MUST GET RIGHT, each of which would look like a working plugin while
21
+ // being wrong:
22
+ // 1. A disappeared worker must not become a dead tool. The client restarts once and reports.
23
+ // 2. A refusal must survive as a refusal. It is returned in the result text with its code, never
24
+ // swallowed and never turned into a generic failure — R3.2 forbids canned messages.
25
+ // 3. `paused` and `enabled` are server-side gates. They are checked here, before any worker call,
26
+ // because a prompt-level hint is not a switch (R2.5).
27
+ import { createConfigSchema, CONFIG_DEFAULTS } from './config.js';
28
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
29
+ import { tmpdir } from 'node:os';
30
+ import { dirname, join } from 'node:path';
31
+ import { WorkerClient, workerScript } from './engine.js';
32
+ import { ACTIONS, PARAMETERS, TOOL_NAME, resolveDefineTool } from './host-tools.js';
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
+ })();
51
+
52
+ // ---- THE PUBLIC CONTRACT IS THE SOURCE OF TRUTH, AND THIS FILE IS CHECKED AGAINST IT ----------
53
+ //
54
+ // types/index.d.ts is what a consumer imports and what `scripts/check-types.mjs` proves a strict
55
+ // client accepts. The typedef block below IMPORTS that same file, so the annotations in this
56
+ // implementation are checked against the shipped promise rather than against a private copy of it:
57
+ // rename a field in types/index.d.ts and `scripts/check-jsdoc.mjs` turns this file red. That
58
+ // direction is the whole point -- a generated .d.ts (what a TypeScript rewrite would emit here) has
59
+ // no `WpmAction`/`RefusalCode`/`WpmArgs` at all, so it could not do this.
60
+ //
61
+ // (The first version of this block used `// @typedef` lines. Those are comments, not JSDoc: nothing
62
+ // was declared, and the checker answered "Cannot find name 'WpmArgs'". A JSDoc block is required.)
63
+ /**
64
+ * @typedef {import('../types/index.d.ts').WpmAction} WpmAction
65
+ * @typedef {import('../types/index.d.ts').WpmArgs} WpmArgs
66
+ * @typedef {import('../types/index.d.ts').RefusalCode} RefusalCode
67
+ * @typedef {import('../types/index.d.ts').WpmResult} WpmResult
68
+ * @typedef {import('../types/index.d.ts').WpmExec} WpmExec
69
+ */
70
+
71
+ /**
72
+ * The settings object `apply` derives from the Cordis config. Spelled out because the config VALUE is
73
+ * `{}` at the type level -- config.js validates it at runtime, and a validator's output is not a
74
+ * static fact -- so without this every one of the ten reads under `apply` reports "does not exist on
75
+ * type '{}'". The property list here must match `FIELDS` in config.js; both are checked by
76
+ * test/plugin-test.mjs.
77
+ * @typedef {object} WpmSettings
78
+ * @property {boolean} enabled
79
+ * @property {number} settleMs
80
+ * @property {number} requestTimeoutMs
81
+ * @property {string} powershellPath
82
+ * @property {boolean} overlay
83
+ * @property {boolean} logWorkerStderr
84
+ * @property {boolean} takeoverAllowed
85
+ * @property {boolean} keyInjectAllowed
86
+ * @property {number} takeoverMaxMs
87
+ * @property {number} takeoverArmMs
88
+ * @property {number} snapshotMaxElements
89
+ * @property {number} screenshotMaxWidth
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
96
+ */
97
+
98
+ /**
99
+ * A refusal thrown before the worker is reached. The two extra fields are the whole point: the caller
100
+ * path reads `err.refusal` for the code and `err.reason` for the sentence, so typing this as a plain
101
+ * `Error` would lose the vocabulary that makes a refusal actionable.
102
+ * @typedef {Error & {refusal?: RefusalCode, reason?: string}} WpmError
103
+ */
104
+
105
+ /**
106
+ * One worker envelope, as engine.js documents it. `result` is deliberately `any`: its shape is the
107
+ * PowerShell engine's JSON-lines protocol, and pretending to type it from this side would be the
108
+ * "type safety over half the system" mistake in miniature.
109
+ * @typedef {object} Envelope
110
+ * @property {boolean} [ok]
111
+ * @property {string} [error]
112
+ * @property {any} [result]
113
+ */
114
+
115
+ /**
116
+ * The Cordis context surface this plugin touches, and nothing more. `logger` is optional everywhere it
117
+ * is used (`logger.warn?.(...)`) because a host that supplies no logger must still work.
118
+ * @typedef {object} CordisContext
119
+ * @property {{register: (tool: any) => void}} tools
120
+ * @property {{info?: (m: string) => void, warn?: (m: string) => void}} [logger]
121
+ * @property {(event: string, fn: () => void) => void} [on]
122
+ */
123
+
124
+ /** Stable Cordis plugin name (this is what a profile entry points at). */
125
+ export const name = 'windows-parallel';
126
+
127
+ /** Services that must exist before the tool can register. */
128
+ export const inject = ['tools'];
129
+
130
+ /**
131
+ * The settings schema is resolved once, at module load, because Cordis reads `Config` synchronously
132
+ * as a standard-schema value (it calls `Config['~standard'].validate(config)`). A factory function
133
+ * here -- the first version of this file -- fails activation with
134
+ * `Cannot read properties of undefined (reading 'validate')`, which is only visible by booting a real
135
+ * profile. See lib/config.js.
136
+ */
137
+ const resolvedConfig = await createConfigSchema();
138
+ export const Config = resolvedConfig.schema;
139
+ export const configSource = resolvedConfig.source;
140
+
141
+ /**
142
+ * Resolved at module load, not inside `apply`. Cordis treats whatever `apply` returns as a
143
+ * disposable effect, so an `async apply` returns a Promise and the plugin dies with "Invalid effect"
144
+ * -- the second activation failure found by booting a real profile. Anything asynchronous therefore
145
+ * has to finish before `apply` runs, which top-level await makes possible and keeps `apply` sync.
146
+ */
147
+ const resolvedTools = await resolveDefineTool();
148
+ export const toolHelperSource = resolvedTools.source;
149
+
150
+ /**
151
+ * Register the tool. `apply` is the whole host half; there is no client half yet, which is
152
+ * deliberate: the overlay / pill / hotkey layer is task_54 and gets its own commit. A plugin with a
153
+ * working tool and no UI is usable; a plugin with UI and no working tool is a demo.
154
+ * @param {CordisContext} ctx
155
+ * @param {Record<string, any>} [config]
156
+ * @returns {void}
157
+ */
158
+ export function apply(ctx, config = {}) {
159
+ /** @type {WpmSettings} */
160
+ const settings = {
161
+ enabled: resolveSetting(config.enabled, true),
162
+ settleMs: resolveSetting(config.settleMs, 350),
163
+ requestTimeoutMs: resolveSetting(config.requestTimeoutMs, 20000),
164
+ powershellPath: resolveSetting(config.powershellPath, ''),
165
+ overlay: resolveSetting(config.overlay, true),
166
+ logWorkerStderr: resolveSetting(config.logWorkerStderr, false),
167
+ // ---- R3 gates. Both default false: with them off this build behaves exactly like 0.1.6, so an
168
+ // upgrade cannot silently start moving the owner's cursor. The gates live HERE, before the worker,
169
+ // because a prompt-level hint is not a switch (same reasoning as `enabled`/`paused`).
170
+ takeoverAllowed: resolveSetting(config.takeoverAllowed, false) === true,
171
+ keyInjectAllowed: resolveSetting(config.keyInjectAllowed, false) === true,
172
+ takeoverMaxMs: clampSetting(resolveSetting(config.takeoverMaxMs, 10000), 500, 60000, 10000),
173
+ takeoverArmMs: clampSetting(resolveSetting(config.takeoverArmMs, 800), 0, 5000, 800),
174
+ // ---- 0.5.0 read-path settings. Forwarded, never silently clamped on the caller's behalf: the
175
+ // engine is the one that reports what it actually used (maxElements/shotsKeep ride back on the
176
+ // result), so "the setting took" is observable rather than assumed.
177
+ snapshotMaxElements: clampSetting(resolveSetting(config.snapshotMaxElements, 300), 1, 5000, 300),
178
+ screenshotMaxWidth: clampSetting(resolveSetting(config.screenshotMaxWidth, 0), 0, 7680, 0),
179
+ shotsKeep: clampSetting(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: clampSetting(resolveSetting(config.policyIdleMs, 3000), 0, 60000, 3000),
189
+ auditKeep: clampSetting(resolveSetting(config.auditKeep, 2000), 100, 200000, 2000),
190
+ };
191
+
192
+ const logger = ctx.logger ?? console;
193
+ // ---- the marker -----------------------------------------------------------------------------
194
+ // Deliberately fire-and-forget and deliberately AFTER the action has answered: this is a visual
195
+ // aid, not part of the result, and making it synchronous would put 19ms (plus a one-time ~875ms
196
+ // overlay start) on every click. Two rules keep it honest:
197
+ // * it is fired after the action request resolves, so a slow overlay start can never delay the
198
+ // action the user is waiting for;
199
+ // * the first failure is WARNED, not swallowed -- an overlay that never appears would otherwise
200
+ // make the README's "AI cursor is a click-through overlay" claim silently untrue.
201
+ // Cost measured over the real worker protocol (.tmp/worker-overlay.mjs): start ~875ms once,
202
+ // marker 19ms, status 15ms, stop ~660ms.
203
+ /** @type {Promise<any>|null} */
204
+ let overlayReady = null;
205
+ let overlayWarned = false;
206
+ const ensureOverlay = () => {
207
+ if (overlayReady) return overlayReady;
208
+ overlayReady = client.request({ action: 'overlay', on: true }).then((env) => {
209
+ if (!env.ok) throw new Error(env.error || 'overlay start refused');
210
+ const st = env.result?.state ?? {};
211
+ if (!st.running) throw new Error(st.reason || 'overlay reported not running');
212
+ if (st.hotkeyRegistered === false) {
213
+ logger.warn?.(`[windows-parallel] pause hotkey unavailable: ${st.reason || 'RegisterHotKey failed'}`);
214
+ } else if (st.hotkeyLabel && st.hotkeyLabel !== 'Ctrl+Alt+Q') {
215
+ logger.warn?.(`[windows-parallel] Ctrl+Alt+Q is owned by another app; the pause key is ${st.hotkeyLabel}`);
216
+ }
217
+ return st;
218
+ }).catch((err) => {
219
+ overlayReady = null; // let the next action retry rather than latch off
220
+ if (!overlayWarned) {
221
+ overlayWarned = true;
222
+ logger.warn?.(`[windows-parallel] marker overlay unavailable (${err.message}); actions still work`);
223
+ }
224
+ throw err;
225
+ });
226
+ return overlayReady;
227
+ };
228
+ /**
229
+ * Place the marker at a PHYSICAL screen point. Never awaited by the caller path.
230
+ * Placement RETRIES until the overlay reports running or a 6 s deadline passes -- not as a
231
+ * bandage but because the old single-shot silently broke the shipped promise: a cold worker's
232
+ * handshake can expire while the overlay is genuinely still starting (measured: WPF JIT past the
233
+ * budget), the marker request was then skipped, and the click had already answered so nobody ever
234
+ * retried. A promise with a race window is a promise that loses the race sometimes. The deadline
235
+ * is BOUNDED and a confirmed-dead start (a reason with starting=false) stops the loop immediately
236
+ * and warns -- endless patience would just hide a broken surface.
237
+ * @param {number} x @param {number} y @returns {void}
238
+ */
239
+ const markPoint = (x, y) => {
240
+ if (!settings.overlay || !Number.isFinite(x) || !Number.isFinite(y)) return;
241
+ const mx = Math.round(x);
242
+ const my = Math.round(y);
243
+ void (async () => {
244
+ await ensureOverlay().catch(() => {}); // kick the start; its own failures are warned there
245
+ const deadline = Date.now() + 6000;
246
+ for (;;) {
247
+ const env = await client.request({ action: 'marker', x: mx, y: my }).catch(() => null);
248
+ const res = env?.result;
249
+ if (env?.ok && res?.ok !== false) return; // placed
250
+ if (res && res.reason === 'overlay not running') {
251
+ const st = await client.request({ action: 'overlay', on: true }).catch(() => null);
252
+ const state = st?.result?.state;
253
+ if (state && state.running) continue; // up now; retry placement
254
+ if (state && !state.starting && state.reason) {
255
+ if (!overlayWarned) {
256
+ overlayWarned = true;
257
+ logger.warn?.(`[windows-parallel] marker overlay failed to start (${state.reason}); actions still work`);
258
+ }
259
+ return; // dead for a named reason: stop
260
+ }
261
+ }
262
+ if (Date.now() >= deadline) {
263
+ if (!overlayWarned) {
264
+ overlayWarned = true;
265
+ logger.warn?.('[windows-parallel] marker was not placed within 6s of the click; actions still work');
266
+ }
267
+ return;
268
+ }
269
+ await new Promise((r) => setTimeout(r, 150));
270
+ }
271
+ })().catch(() => { /* warned inside; a marker must never become an unhandled rejection */ });
272
+ };
273
+ logger.info?.(`[windows-parallel] config schema: ${configSource}`);
274
+ const client = new WorkerClient({
275
+ powershellPath: settings.powershellPath,
276
+ script: workerScript(),
277
+ requestTimeoutMs: settings.requestTimeoutMs,
278
+ onStderr: (line) => {
279
+ if (settings.logWorkerStderr) logger.warn?.(`[wpm worker] ${line}`);
280
+ },
281
+ onExit: ({ code }) => {
282
+ logger.warn?.(`[windows-parallel] engine worker exited (code=${code}); it will restart on the next call`);
283
+ },
284
+ });
285
+
286
+ /**
287
+ * Wire the host's cancellation into the worker. THE WORKER IS SINGLE-THREADED: while it is inside an
288
+ * action it cannot read a new request, so an 'abort' request alone would be answered only after the
289
+ * action it was meant to stop. The engine therefore polls a latch FILE at the path this writes, and
290
+ * the worker request is sent as well (fire-and-forget) so an idle worker clears its flag too.
291
+ * Two channels because one of them is a local file write that cannot be lost to a wedged loop.
292
+ */
293
+ const activeLatches = new Set();
294
+ /** @param {WpmExec|undefined} exec @returns {() => void} */
295
+ const armAbort = (exec) => {
296
+ const signal = exec?.signal;
297
+ if (!signal || typeof signal.addEventListener !== 'function') return () => {};
298
+ const onAbort = () => {
299
+ const pid = client.child?.pid;
300
+ if (!pid) return;
301
+ const latch = abortLatchPath(pid);
302
+ try {
303
+ mkdirSync(dirname(latch), { recursive: true });
304
+ writeFileSync(latch, 'abort', 'utf8');
305
+ activeLatches.add(latch);
306
+ } catch { /* the HUD button and the abort chord remain available */ }
307
+ void client.request({ action: 'abort' }).catch(() => {});
308
+ };
309
+ if (signal.aborted) { onAbort(); return () => {}; }
310
+ signal.addEventListener('abort', onAbort, { once: true });
311
+ return () => signal.removeEventListener('abort', onAbort);
312
+ };
313
+
314
+ const { defineTool } = resolvedTools;
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
+
350
+ /** Build the worker request for one action. Throws for arguments the action cannot use. */
351
+ /** @param {WpmArgs} args @returns {any} */
352
+ function toRequest(args) {
353
+ const settleMs = clampSettle(args.settleMs ?? settings.settleMs);
354
+ // The takeover fields are attached ONLY when the caller asked for them AND the gate is open. When a
355
+ // gate is closed the field is STRIPPED, not forwarded: a worker that received takeover:true would be
356
+ // free to act on it, and the safe answer to "the gate is off" is the silent-tier request, which the
357
+ // engine then refuses or serves by its own table (task_26).
358
+ const takeover = args.takeover === true && settings.takeoverAllowed;
359
+ const keyInput = takeover && args.keyInput === 'inject' && settings.keyInjectAllowed ? 'inject' : 'none';
360
+ // takeoverArmMs is the OWNER's patience, not the caller's: it comes from settings and is forwarded so
361
+ // the settings surface actually controls the pre-move cancellation window (a setting that never
362
+ // reaches the engine is a form, not a switch).
363
+ const takeoverFields = takeover
364
+ ? {
365
+ takeover: true,
366
+ takeoverMaxMs: refuseOutOfRange(args.takeoverMaxMs, 500, 60000, settings.takeoverMaxMs, 'takeoverMaxMs'),
367
+ takeoverArmMs: settings.takeoverArmMs,
368
+ ...(keyInput === 'inject' ? { keyInput } : {}),
369
+ }
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
+ };
380
+ switch (args.action) {
381
+ case 'windows':
382
+ return { action: 'windows' };
383
+ case 'status':
384
+ return { action: 'status' };
385
+ case 'snapshot':
386
+ // A READ. maxElements is the SETTING unless the caller asked for a specific cap, and
387
+ // interactableOnly defaults ON because the frame exists to be decided on, not to be dumped.
388
+ requireArg(args, 'hwnd', 'snapshot');
389
+ return {
390
+ action: 'snapshot',
391
+ hwnd: args.hwnd,
392
+ maxElements: refuseOutOfRange(args.maxElements, 1, 5000, settings.snapshotMaxElements, 'maxElements'),
393
+ interactableOnly: args.interactableOnly !== false,
394
+ sinceSnapId: typeof args.sinceSnapId === 'string' ? args.sinceSnapId : '',
395
+ intent: typeof args.intent === 'string' ? args.intent : '',
396
+ };
397
+ case 'screenshot':
398
+ // fullScreen is the ONLY way to capture without naming a window, and it must be asked for:
399
+ // silently capturing the owner's whole desktop would be exactly the overreach this product
400
+ // refuses elsewhere. A non-fullscreen capture with no hwnd is refused here, before the worker.
401
+ if (args.fullScreen !== true) requireArg(args, 'hwnd', 'screenshot');
402
+ return {
403
+ action: 'screenshot',
404
+ hwnd: args.fullScreen === true ? (args.hwnd ?? '') : args.hwnd,
405
+ fullScreen: args.fullScreen === true,
406
+ maxWidth: refuseOutOfRange(args.maxWidth, 0, 7680, settings.screenshotMaxWidth, 'maxWidth'),
407
+ shotsKeep: settings.shotsKeep,
408
+ };
409
+ case 'preview':
410
+ // Silent by construction: no click, no focus, no input queue entry. The engine draws the
411
+ // marker and answers with the element UNDER the point as text.
412
+ requireArg(args, 'hwnd', 'preview');
413
+ requireArg(args, 'x', 'preview');
414
+ requireArg(args, 'y', 'preview');
415
+ return {
416
+ action: 'preview', hwnd: args.hwnd,
417
+ x: Math.round(/** @type {number} */ (args.x)),
418
+ y: Math.round(/** @type {number} */ (args.y)),
419
+ };
420
+ case 'click':
421
+ requireArg(args, 'hwnd', 'click');
422
+ requireArg(args, 'x', 'click');
423
+ requireArg(args, 'y', 'click');
424
+ // The two casts state what `requireArg` just enforced: `WpmArgs.x/y` are optional in the
425
+ // public contract (click requires them, windows does not), and the guard above is the only
426
+ // thing that narrows them. A checker cannot see through a separate function's throw, so this
427
+ // is where the guarantee is recorded -- not a suppression, since requireArg throws for both
428
+ // undefined and null before this line is reached.
429
+ //
430
+ // THE COORDINATE SPACE IS EXPLICIT. 'image' without a shotId is refused HERE, before any worker
431
+ // request: image pixels only mean something relative to a capture, and reinterpreting them as
432
+ // screen pixels would click somewhere plausibly wrong -- the exact failure mode `stale_ref`
433
+ // exists for. A label rides along with its snapId so the engine can resolve the ELEMENT.
434
+ const space = args.space === 'image' ? 'image' : 'screen';
435
+ if (space === 'image' && (typeof args.shotId !== 'string' || args.shotId === '')) {
436
+ 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');
437
+ }
438
+ return {
439
+ action: 'click', hwnd: args.hwnd, x: Math.round(/** @type {number} */ (args.x)), y: Math.round(/** @type {number} */ (args.y)), settleMs,
440
+ ...authFields,
441
+ ...(space === 'image' ? { space: 'image', shotId: args.shotId } : {}),
442
+ ...(typeof args.label === 'number' && args.label > 0
443
+ ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
444
+ : {}),
445
+ ...takeoverFields,
446
+ };
447
+ case 'type':
448
+ requireArg(args, 'hwnd', 'type');
449
+ if (typeof args.text !== 'string' || args.text.length === 0) {
450
+ // Refused here rather than sent: a write of nothing succeeds silently on every channel,
451
+ // so an empty string is indistinguishable from a dead door.
452
+ throw refusal('unreachable', 'type needs a non-empty text; an empty write cannot be verified');
453
+ }
454
+ return {
455
+ action: 'type', hwnd: args.hwnd, text: args.text,
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',
465
+ ...(typeof args.label === 'number' && args.label > 0
466
+ ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
467
+ : {}),
468
+ ...takeoverFields,
469
+ };
470
+ case 'focus':
471
+ requireArg(args, 'hwnd', 'focus');
472
+ if ((typeof args.label !== 'number' || args.label <= 0)) requireArg(args, 'elementName', 'focus');
473
+ return {
474
+ action: 'focus', hwnd: args.hwnd, elementName: args.elementName ?? '', settleMs,
475
+ ...authFields,
476
+ ...(typeof args.label === 'number' && args.label > 0
477
+ ? { label: Math.round(args.label), snapId: typeof args.snapId === 'string' ? args.snapId : '' }
478
+ : {}),
479
+ ...takeoverFields,
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: refuseOutOfRange(args.waitMs, 0, 30000, 3000, 'waitMs'),
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
+ }
533
+ default:
534
+ throw refusal('no_hwnd', `unknown action '${args.action}'`);
535
+ }
536
+ }
537
+
538
+ const tool = defineTool({
539
+ name: TOOL_NAME,
540
+ description:
541
+ 'Drive a Windows window: click at a screen coordinate, write text, or move focus inside ONE named '
542
+ + 'window, choosing the cheapest available door. Two tiers are silent: a classic child window is '
543
+ + 'addressed with window messages (measured: zero foreground changes), and a window that only '
544
+ + 'exposes a UI Automation pattern costs one bounded foreground flash that is reversed once '
545
+ + 'afterwards (measured net return 15-95 ms). A THIRD tier exists and is opt-in: takeover:true may '
546
+ + 'move the real cursor to the action point (always restored), hold the focus until the action ends, '
547
+ + 'and -- with keyInput:"inject" -- type into the foreground target through synthetic keyboard input '
548
+ + 'for windows that have no message door and no accessible pattern (terminals). Takeover is refused '
549
+ + 'unless the owner enabled it, always shows a three-phase HUD with a stop button and a global abort '
550
+ + 'key, is interruptible three ways, and never injects mouse events. '
551
+ + 'THREE READ ACTIONS make the target legible without guessing: snapshot returns a NUMBERED element '
552
+ + 'table (a continuous `label`, control type, name, automation id, rect, patterns) that click/type/'
553
+ + 'focus accept as `label`+`snapId`; screenshot writes the window rect to a PNG and returns '
554
+ + 'screenRect/imageSize/scale/identity/frame as data so image coordinates can be handed straight '
555
+ + 'back to click with space:"image" (the engine converts, the caller never multiplies); preview '
556
+ + 'draws the marker at a point and reports, as TEXT, the element under it -- a reviewable click that '
557
+ + 'needs no picture. Refusals carry a code (no_hwnd, '
558
+ + 'paused, elevated_target, unreachable, uia_tree_empty, uia_probe_failed, terminal_no_door, needs_facts, action_failed, '
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. '
567
+ + 'Start with action=windows to get an hwnd, action=snapshot to read a frame, or action=status to see '
568
+ + 'what currently holds the foreground.',
569
+ parameters: PARAMETERS,
570
+ output: {
571
+ schema: {
572
+ type: 'object',
573
+ additionalProperties: true,
574
+ properties: {
575
+ action: { type: 'string', required: true },
576
+ ok: { type: 'boolean', required: true },
577
+ refusal: { type: 'string' },
578
+ text: { type: 'string', required: true },
579
+ },
580
+ },
581
+ // `WpmResult.text` is optional in the public contract (a consumer may hold a partial object),
582
+ // but every value that reaches this render is built by `result()` below, which always sets it.
583
+ // The cast records that invariant instead of substituting '' -- an empty string would be a
584
+ // rendered blank, and the text IS the product here.
585
+ /** @param {WpmArgs} _args @param {WpmResult} value @returns {Array<{type: string, text: string}>} */
586
+ render: (_args, value) => [{ type: 'text', text: /** @type {string} */ (value.text) }],
587
+ },
588
+ /** @param {WpmArgs} args @param {WpmExec|undefined} exec @returns {Promise<Record<string, any>>} */
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
+ };
610
+ // Server-side gates first: a paused or disabled engine must refuse before it spends a worker
611
+ // call, and the refusal must name the gate rather than describe a symptom.
612
+ if (!settings.enabled) {
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)' : ''}`));
627
+ }
628
+ // ---- R3 gates, BEFORE the worker. A refused takeover costs zero worker requests, which is
629
+ // asserted with a request counter in test/plugin-test.mjs: "the gate is checked" is otherwise
630
+ // indistinguishable from "the gate is checked after the expensive part".
631
+ if (args.takeover === true && !settings.takeoverAllowed) {
632
+ return finish(result(args.action, false, 'takeover_unavailable',
633
+ 'takeoverAllowed is off in settings; the action was refused rather than silently downgraded to the quiet tier. '
634
+ + 'The quiet tier still works without takeover:true' + hwndHint(args)));
635
+ }
636
+ if (args.keyInput === 'inject' && (!settings.keyInjectAllowed || args.takeover !== true)) {
637
+ return finish(result(args.action, false, 'keyinject_unavailable',
638
+ args.takeover !== true
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'
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
+ }
661
+ }
662
+ // A pre-worker refusal is still a refusal, not a thrown error. The first version of this file
663
+ // let `toRequest` throw for an empty write, and the caller saw a crashed tool call instead of
664
+ // `unreachable` -- the exact "refusal became an exception" defect this plugin's own comment
665
+ // above warns about. Caught by test/plugin-test.mjs, which asserts the code is returned.
666
+ let request;
667
+ try {
668
+ request = toRequest(args);
669
+ } catch (err) {
670
+ // `catch` binds `unknown` under strict, which is correct: anything can be thrown. The casts
671
+ // are the narrowing step, kept INLINE so the statements and local names below are exactly what
672
+ // they were -- `scripts`-level AST comparison against the previous revision is a gate here, and
673
+ // a rename would make a comment-only change look like a behaviour change. Safe on this path
674
+ // because the only thrower is `refusal()` above; the `??` fallbacks still keep the vocabulary
675
+ // intact when it is not.
676
+ const code = /** @type {WpmError} */ (err)?.refusal ?? 'action_failed';
677
+ return finish(result(args.action, false, code, /** @type {WpmError} */ (err)?.reason ?? String(/** @type {WpmError} */ (err)?.message ?? err)));
678
+ }
679
+ let envelope;
680
+ const disarm = request.takeover ? armAbort(exec) : () => {};
681
+ try {
682
+ envelope = await client.request(request);
683
+ } catch (err) {
684
+ // The worker layer failed (crash, timeout, missing engine). This is not a refusal code: the
685
+ // engine never got to decide. Say exactly that instead of borrowing a code it does not own.
686
+ // Cast inline for the same reason as above. No `String(...)` wrapper and no `?.` are added:
687
+ // the original read `err.message` directly, and a non-Error thrown here still renders the
688
+ // same way it always did -- widening the expression would be a behaviour change dressed as
689
+ // type safety, which is exactly what this file refuses to do.
690
+ return finish(result(args.action, false, 'action_failed', `engine worker unavailable: ${/** @type {Error} */ (err).message}`));
691
+ } finally {
692
+ disarm();
693
+ }
694
+ if (!envelope.ok) {
695
+ return finish(result(args.action, false, 'action_failed', `worker error: ${envelope.error ?? 'unknown'}`));
696
+ }
697
+ // click coordinates are SCREEN pixels (the engine converts to client space itself), so the
698
+ // marker can be placed straight from the request -- no second coordinate system to get wrong.
699
+ // Only a click that actually ran places a marker: a refused click has no impact point, and
700
+ // letting a refusal start the overlay would mean a dead hwnd silently spawns a WPF window.
701
+ const r = envelope.result;
702
+ if (request.action === 'click' && r && r.ok !== false && !r.refusal) {
703
+ // With space:'image' the request coordinates are IMAGE pixels; the engine reports the screen
704
+ // point it actually converted to, and the marker must be drawn THERE. Drawing it at the image
705
+ // pixel would put the visible cursor somewhere other than where the click landed -- a marker
706
+ // that lies is worse than no marker, because the README sells it as the point that was acted on.
707
+ const screen = request.space === 'image' ? parsePoint(r.screenPoint) : null;
708
+ markPoint(screen ? screen.x : request.x, screen ? screen.y : request.y);
709
+ }
710
+ return finish(format(args.action, envelope.result));
711
+ },
712
+ });
713
+
714
+ ctx.tools.register(tool);
715
+ ctx.on?.('dispose', () => {
716
+ // A latch that outlives the worker would abort the NEXT worker's first takeover (the path is keyed
717
+ // by pid, so a new process gets a new path -- this is belt and braces, and it keeps %LOCALAPPDATA%
718
+ // tidy for an operator reading it).
719
+ for (const latch of activeLatches) { try { rmSync(latch, { force: true }); } catch { } }
720
+ activeLatches.clear();
721
+ void client.dispose();
722
+ });
723
+ // No return value. Cordis treats whatever `apply` returns as a disposable effect, so returning the
724
+ // registered tool is at best ignored and at worst an "Invalid effect" that disables the plugin --
725
+ // the same class of failure as the async apply, one step further in.
726
+ }
727
+
728
+ // ---- small helpers ---------------------------------------------------------------------------
729
+
730
+ /** A Cordis settings value may be a live ref (0.1.7+) or a plain value (older lines). */
731
+ /** @param {any} value @param {any} fallback @returns {any} */
732
+ function resolveSetting(value, fallback) {
733
+ if (value === undefined || value === null) return fallback;
734
+ const v = typeof value.get === 'function' ? value.get() : value;
735
+ if (v === undefined || v === null) return fallback;
736
+ return v;
737
+ }
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
+
762
+ /** @param {any} value @returns {number} */
763
+ function clampSettle(value) {
764
+ const n = Number(value);
765
+ if (!Number.isFinite(n)) return 350;
766
+ return Math.max(0, Math.min(2000, Math.round(n)));
767
+ }
768
+
769
+ /**
770
+ * @param {Record<string, any>} args
771
+ * @param {'hwnd'|'x'|'y'|'text'|'elementName'|'target'} key
772
+ * @param {string} action
773
+ * @returns {void}
774
+ */
775
+ function requireArg(args, key, action) {
776
+ if (args[key] === undefined || args[key] === null || args[key] === '') {
777
+ throw refusal('no_hwnd', `action=${action} requires '${key}'`);
778
+ }
779
+ }
780
+
781
+ /**
782
+ * A refusal thrown before the worker is reached; caught by the caller path that renders results.
783
+ * @param {RefusalCode} code
784
+ * @param {string} reason
785
+ * @returns {WpmError}
786
+ */
787
+ function refusal(code, reason) {
788
+ // The cast is the definition of this function's payload: a plain Error plus the two fields the
789
+ // caller path reads. Writing it after construction (rather than using a subclass) keeps `instanceof
790
+ // Error` true for the host, which is what the catch sites rely on.
791
+ const err = /** @type {WpmError} */ (new Error(`${code}: ${reason}`));
792
+ err.refusal = code;
793
+ err.reason = reason;
794
+ return err;
795
+ }
796
+
797
+ /**
798
+ * @param {string} action
799
+ * @param {boolean} ok
800
+ * @param {RefusalCode|''} refusalCode
801
+ * @param {string} text
802
+ * @param {Record<string, any>} [extra]
803
+ * @returns {Record<string, any>}
804
+ */
805
+ function result(action, ok, refusalCode, text, extra) {
806
+ return { action, ok, refusal: refusalCode, text: refusalCode ? `${refusalCode}: ${text}` : text, ...(extra || {}) };
807
+ }
808
+
809
+ /**
810
+ * Turn a worker result into the tool's output value.
811
+ *
812
+ * The text is the product. A caller that gets `ok:false` with a code and a reason can act; a caller
813
+ * that gets "the action failed" cannot. Every number reported here is measured by the engine, not
814
+ * inferred by this file.
815
+ * @param {string} action
816
+ * @param {any} r
817
+ * @returns {Record<string, any>}
818
+ */
819
+ function format(action, r) {
820
+ if (!r) return result(action, false, 'action_failed', 'engine returned no result');
821
+
822
+ if (action === 'windows') {
823
+ const list = Array.isArray(r.windows) ? r.windows : [];
824
+ if (list.length === 0) {
825
+ return result(action, true, '', 'no drivable windows are visible right now (minimised and untitled windows are excluded by design)');
826
+ }
827
+ const lines = list.map(/** @param {any} w @returns {string} */ (w) => `${w.hwnd} ${truncate(String(w.title), 60)} [${w.cls}] pid=${w.pid} rect=${w.rect}`);
828
+ return result(action, true, '', `${list.length} drivable window(s):\n${lines.join('\n')}`);
829
+ }
830
+
831
+ if (action === 'status') {
832
+ const bits = [
833
+ `paused=${r.paused === true}`,
834
+ `foreground=${r.foreground || '(none)'}`,
835
+ `foregroundPid=${r.foregroundPid || '(none)'}`,
836
+ `focusedControl=${r.focusControl || '(none)'}`,
837
+ `lastHumanInputAgeMs=${r.lastInputAgeMs ?? 'unknown'}`,
838
+ ];
839
+ // The control surface travels with status. Without it, "the overlay is on" and "the pause key
840
+ // registered" are claims the user cannot check -- and this machine's desktop already owns
841
+ // Ctrl+Alt+Q, so the real chord is not the documented one. Silence here would be a lie.
842
+ bits.push(`overlay=${r.overlayRunning === true ? 'on' : 'off'}`);
843
+ // The takeover surface, on the same principle: the owner must be able to check "is the HUD up and
844
+ // which abort key is real" without inferring it from a successful call.
845
+ bits.push(`hud=${r.hudOn === true ? 'on' : 'off'}`);
846
+ if (r.abortChord) bits.push(`abortChord=${r.abortChord}`);
847
+ // The overlay's hwnd, so an INDEPENDENT oracle can verify the exact window the product thinks
848
+ // it is showing. Title-matching alone cannot do this: a leaked overlay from an earlier run is
849
+ // also titled WpmOverlay, and grading that instead of ours would make the marker arms grade
850
+ // homework that is not even in this class.
851
+ if (r.overlayHwnd && r.overlayHwnd !== '0') bits.push(`overlayHwnd=${r.overlayHwnd}`);
852
+ bits.push(`pauseHotkey=${r.hotkeyRegistered === true ? (r.hotkeyLabel || 'registered') : 'unavailable'}`);
853
+ if (r.overlayReason) bits.push(`overlayNote=${r.overlayReason}`);
854
+ if (r.pauseReason) bits.push(`pauseReason=${r.pauseReason}`);
855
+ // The DPI stance is a FACT the read paths depend on: rects and captured pixels are physical only
856
+ // while this process is per-monitor DPI aware. Reporting it here is what keeps a future deletion of
857
+ // the setter from turning into a silent half-scale coordinate system (the marker already proved
858
+ // that failure mode: 470,410 acted on at 303,263 on this 150% display).
859
+ bits.push(`dpiAware=${r.dpiAware === true}`);
860
+ if (r.stance) bits.push(`stance: ${r.stance}`);
861
+ return result(action, true, '', bits.join('\n'));
862
+ }
863
+
864
+ // Action results. `refusal` is the engine's own code: an empty string means the action ran.
865
+ // The cast leans on `scripts/check-refusals.mjs`, which pins the engine's emitted codes to the
866
+ // closed set in src/schema/tools.json: the wire format is a string, but the vocabulary is a
867
+ // contract that another gate already enforces. Typing this as plain `string` would push the check
868
+ // to every call site; typing it as `RefusalCode` names where the guarantee actually comes from.
869
+ const code = r.refusal ? /** @type {RefusalCode} */ (String(r.refusal)) : '';
870
+ if (code) {
871
+ const reason = r.reason ? ` (${r.reason})` : '';
872
+ // A takeover refusal still carries the takeover accounting: "aborted after 12 characters, cursor
873
+ // restored" is the information that makes an interruption harmless instead of alarming.
874
+ if (r.takeover === 'true') {
875
+ const extra = ` [takeover=on cursorRestored=${r.cursorRestored === 'true'} injectedChars=${r.injectedChars ?? 0}`
876
+ + `${r.abortChord ? ` abortChord=${r.abortChord}` : ''}]`;
877
+ return result(action, false, code, `${code}${reason}${extra}`, {
878
+ takeover: 'on', cursorRestored: r.cursorRestored === 'true', injectedChars: r.injectedChars ?? 0,
879
+ });
880
+ }
881
+ return result(action, false, code, `${code}${reason}`);
882
+ }
883
+
884
+ // ---- 0.5.0 READ RESULTS ---------------------------------------------------------------------
885
+ // These three have no channel, no tier and no proof window: there is no action to prove. Rendering
886
+ // happens HERE (not in the engine) for the same reason every other action's text does -- one place
887
+ // owns "what the model reads", and the engine stays a JSON protocol.
888
+ if (action === 'snapshot') return formatSnapshot(r);
889
+ if (action === 'screenshot') return formatScreenshot(r);
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);
899
+
900
+ // WHO REPORTED THE SUCCESS. The engine sets `effect` when a channel call RETURNS without throwing;
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):
903
+ // unverified no channel reported success at all;
904
+ // reported-by-send the window message was DELIVERED -- nothing here proves the target app
905
+ // processed it;
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".
914
+ const bits = [
915
+ `${action} ok`,
916
+ `channel=${r.channel || '?'}`,
917
+ `tier=${r.tier || '?'}`,
918
+ `effect=${r.effect || 'unverified'}`,
919
+ `focusTaken=${r.focusTaken === 'true' || r.focusTaken === true}`,
920
+ ];
921
+ // The takeover accounting. Every number here was measured by the engine (cursor read-backs, the
922
+ // injected-character counter, the chord that actually registered) -- nothing in this file infers it.
923
+ if (r.takeover === 'true') {
924
+ bits.push('takeover=on');
925
+ bits.push(`cursorMoved=${r.cursorMoved === 'true'}`);
926
+ bits.push(`cursorRestored=${r.cursorRestored === 'true'}`);
927
+ if (r.takeoverMs !== undefined) bits.push(`takeoverMs=${r.takeoverMs}`);
928
+ if (r.abortChord) bits.push(`abortChord=${r.abortChord}`);
929
+ if (r.keysInjected !== undefined) bits.push(`keysInjected=${r.keysInjected}`);
930
+ bits.push(`injectedChars=${r.injectedChars ?? 0}`);
931
+ if (r.cursorRestoreReason) bits.push(`cursorRestoreReason=${r.cursorRestoreReason}`);
932
+ if (r.takeoverNote) bits.push(`takeoverNote=${r.takeoverNote}`);
933
+ }
934
+ // THE PROOF. The engine sampled cursor/foreground/focus/last-input-age in TWO windows: a short
935
+ // pre-action CONTROL (captured while, by construction, nothing was done) and the settle window
936
+ // AFTER the door call. The judgment is arithmetic and lives in one pure implementation
937
+ // (proof-window.mjs), never here and never in the README. Three verdicts, and their asymmetry is
938
+ // the whole point -- see proof-window.mjs's header for the idle-baseline measurement behind it:
939
+ // pass no unexplained cursor gap, no unexplained foreground/focus switch;
940
+ // inconclusive the desktop moved or switched in a way position data cannot attribute to the
941
+ // action (the idle baseline proved our absence does not imply desktop stillness);
942
+ // fail a foreground/focus switch the control shows the desktop was NOT doing, on a tier
943
+ // that did not DECLARE a bounded flash.
944
+ // `declaredFlash` is the decision table's own needsRestore: on the bounded-flash tier the engine
945
+ // DELIBERATELY raises foreground inside the window and restores it after -- the promise of that
946
+ // tier was never "don't touch", it is "don't keep", and the restore table owns that promise
947
+ // (restore_failed surfaces separately). Sampling cannot be allowed to contradict the contract.
948
+ // A missing/short window is 'insufficient': silence is not innocence.
949
+ const proof = evaluateProof(r.proofSamples || [], {
950
+ control: r.proofControl || [],
951
+ declaredFlash: r.tier === 'bounded-flash',
952
+ // The takeover tier DELIBERATELY moves the cursor and may hold the foreground; the promise it makes
953
+ // is "nothing was kept", not "nothing was touched". A cursor that was not restored still fails, and
954
+ // does so through the same evaluator instead of a special case here.
955
+ declaredTakeover: r.tier === 'takeover',
956
+ cursorRestored: r.cursorRestored === 'false' ? false : undefined,
957
+ // The effect travels into the judgment, not just into the text. Without this, "nothing worked"
958
+ // still reads as proof=pass whenever the desktop happened to stay still (R2 in the plan). One call
959
+ // is one action, so `actions` is left to batch callers; a channel that reported NOTHING here caps
960
+ // the verdict at inconclusive rather than inventing a red on a single quiet call.
961
+ effect: r.effect || 'unverified',
962
+ });
963
+ bits.push(`proof=${proof.verdict}(${proof.reason})`);
964
+ if (r.restoreOutcome) bits.push(`restore=${r.restoreOutcome}`);
965
+ if (r.flashMs !== undefined) bits.push(`flashMs=${r.flashMs}`);
966
+ if (r.latencyMs !== undefined) bits.push(`latencyMs=${r.latencyMs}`);
967
+ if (r.detail) bits.push(`detail=${r.detail}`);
968
+ return result(action, true, '', bits.join(' '), {
969
+ proof: proof.verdict,
970
+ proofDimensions: proof.dimensions,
971
+ effect: r.effect || 'unverified',
972
+ // A converted point travels back with the result so the caller can check the arithmetic it never
973
+ // performed. `screenPoint` is the fact the marker is drawn from, too: with space:'image' the
974
+ // request's own x/y are image pixels and would put the visible marker in the wrong place.
975
+ ...(r.coordSpace === 'image'
976
+ ? { coordSpace: 'image', shotId: r.shotId, imagePoint: r.imagePoint, screenPoint: r.screenPoint, scale: r.scale }
977
+ : {}),
978
+ ...(r.takeover === 'true'
979
+ ? { takeover: 'on', cursorRestored: r.cursorRestored === 'true', injectedChars: r.injectedChars ?? 0 }
980
+ : {}),
981
+ });
982
+ }
983
+
984
+ /** @param {string} s @param {number} n @returns {string} */
985
+ function truncate(s, n) {
986
+ return s.length <= n ? s : `${s.slice(0, n - 1)}…`;
987
+ }
988
+
989
+ /**
990
+ * One element row of a snapshot frame. The format is the contract the caller reasons on, so it is
991
+ * fixed here: `label ControlType "Name" [AutomationId] rect=l,t,r,b patterns=...`. The label is
992
+ * what a deciding side answers with; the rect is in PHYSICAL screen pixels, in the same space as
993
+ * screenRect, which is what makes `space:"image"` conversion possible without a second coordinate table.
994
+ * @param {any} e @returns {string}
995
+ */
996
+ function elementLine(e) {
997
+ const rc = e?.rect ?? {};
998
+ const pats = Array.isArray(e?.patterns) ? e.patterns : [];
999
+ return `${e?.label ?? '?'} ${e?.controlType ?? '?'} "${e?.name ?? ''}" [${e?.automationId ?? ''}] `
1000
+ + `rect=${rc.left ?? '?'},${rc.top ?? '?'},${rc.right ?? '?'},${rc.bottom ?? '?'} `
1001
+ + `patterns=${pats.length ? pats.join('|') : 'none'}`;
1002
+ }
1003
+
1004
+ /**
1005
+ * Render a snapshot frame.
1006
+ *
1007
+ * WHY THE DELTA IS A FIRST-CLASS FORM. Repeating an unchanged 70-row table between two steps is the
1008
+ * dominant token cost of a multi-step flow, and it is pure noise: nothing in it changed. With
1009
+ * `sinceSnapId` the answer is "no changes" plus the three lists that DID move. The full table stays
1010
+ * available -- this is an option, not a replacement.
1011
+ * @param {any} r @returns {Record<string, any>}
1012
+ */
1013
+ function formatSnapshot(r) {
1014
+ const rows = Array.isArray(r.elements) ? r.elements : [];
1015
+ const count = Number.isFinite(r.count) ? Number(r.count) : rows.length;
1016
+ const total = Number.isFinite(r.total) ? Number(r.total) : count;
1017
+ const truncated = r.truncated === true || r.truncated === 'true';
1018
+ const delta = r.delta && typeof r.delta === 'object' ? r.delta : null;
1019
+ const added = Array.isArray(delta?.added) ? delta.added : [];
1020
+ const removed = Array.isArray(delta?.removed) ? delta.removed : [];
1021
+ const changed = Array.isArray(delta?.changed) ? delta.changed : [];
1022
+
1023
+ const head = `snapshot ok: ${count} element(s)`
1024
+ + (truncated ? ` (truncated at ${count} of ${total})` : '')
1025
+ + (delta ? ` (delta vs ${delta.sinceSnapId}: +${added.length} -${removed.length} ~${changed.length})` : '');
1026
+ const meta = [`snapId=${r.snapId || '?'}`, `frame=${r.frame || '?'}`, `frameCheck=${r.frameCheck || '?'}`, `total=${total}`];
1027
+ if (r.frameInset && typeof r.frameInset === 'object') {
1028
+ meta.push(`frameInset=${r.frameInset.left ?? '?'},${r.frameInset.top ?? '?'},${r.frameInset.right ?? '?'},${r.frameInset.bottom ?? '?'}`);
1029
+ }
1030
+ if (Number.isFinite(r.outsideFrame) && Number(r.outsideFrame) > 0) {
1031
+ meta.push(`outsideFrame=${r.outsideFrame}`);
1032
+ }
1033
+ if (r.intent) meta.push(`intent=${r.intent}`);
1034
+ const lines = [head, meta.join(' ')];
1035
+
1036
+ if (delta) {
1037
+ if (added.length === 0 && removed.length === 0 && changed.length === 0) {
1038
+ lines.push(`no changes since ${delta.sinceSnapId}`);
1039
+ } else {
1040
+ for (const a of added) lines.push(` + ${elementLine(a)}`);
1041
+ for (const m of removed) lines.push(` - ${elementLine(m)}`);
1042
+ for (const c of changed) lines.push(` ~ ${elementLine(c)} changed=${(Array.isArray(c.changed) ? c.changed : []).join(',')}`);
1043
+ }
1044
+ } else if (count === 0) {
1045
+ // A REAL ANSWER, said out loud. This deliberately does NOT reuse uia_tree_empty: that code means
1046
+ // "UI Automation is switched off in the application" and its next step is relaunching the app.
1047
+ // Zero visible elements on a window that answers fine (measured: Clash, Everything) has no such
1048
+ // next step, so inventing one would be the canned message this product refuses.
1049
+ lines.push('0 element(s) is a real state: this window exposes no visible element to UI Automation right now. '
1050
+ + 'It is not uia_tree_empty (that code is about the application disabling accessibility) and it is not a failure.');
1051
+ } else {
1052
+ for (const e of rows) lines.push(elementLine(e));
1053
+ }
1054
+ if (r.frame === 'win32') {
1055
+ lines.push('note: frame=win32 -- DWM EXTENDED_FRAME_BOUNDS was unavailable, so this frame came from GetWindowRect and includes the invisible resize shadow. '
1056
+ + '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.');
1057
+ }
1058
+ if (r.frameCheck === 'unknown') {
1059
+ 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.');
1060
+ }
1061
+ if (Number(r.outsideFrame) > 0) {
1062
+ 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.`);
1063
+ }
1064
+ return result('snapshot', true, '', lines.join('\n'), {
1065
+ snapId: r.snapId, elements: rows, count, total, truncated, frameCheck: r.frameCheck, intent: r.intent ?? '',
1066
+ // The delta travels structurally too: a caller that branches on "did anything move" must not have
1067
+ // to parse the text, and the counts are the same numbers the head line prints.
1068
+ ...(delta ? { delta } : {}),
1069
+ ...(r.frameInset ? { frameInset: r.frameInset } : {}),
1070
+ ...(Number.isFinite(r.outsideFrame) ? { outsideFrame: Number(r.outsideFrame) } : {}),
1071
+ });
1072
+ }
1073
+
1074
+ /**
1075
+ * Render a screenshot: the mapping is the product, the file is the delivery.
1076
+ * @param {any} r @returns {Record<string, any>}
1077
+ */
1078
+ function formatScreenshot(r) {
1079
+ const rect = r.screenRect && typeof r.screenRect === 'object' ? r.screenRect : {};
1080
+ const size = r.imageSize && typeof r.imageSize === 'object' ? r.imageSize : {};
1081
+ const scale = typeof r.scale === 'number' ? r.scale : 1;
1082
+ const identity = r.identity === true || r.identity === 'true';
1083
+ const dpiAware = r.dpiAware === true || r.dpiAware === 'true';
1084
+ const lines = [
1085
+ `screenshot ok: ${size.width ?? '?'}x${size.height ?? '?'} px (scale=${scale} identity=${identity}) frame=${r.frame || '?'} captureBackend=${r.captureBackend || '?'} dpiAware=${dpiAware}`,
1086
+ `file=${r.file || '?'}`,
1087
+ `shotId=${r.shotId || '?'}`,
1088
+ `screenRect=${rect.left ?? '?'},${rect.top ?? '?'},${rect.right ?? '?'},${rect.bottom ?? '?'} `
1089
+ + `imageSize=${size.width ?? '?'}x${size.height ?? '?'} bytes=${r.bytes ?? '?'} shotsKeep=${r.shotsKeep ?? '?'} latencyMs=${r.latencyMs ?? '?'}`,
1090
+ 'mapping: screenX = screenRect.left + round(imageX / scale); screenY = screenRect.top + round(imageY / scale). '
1091
+ + `The ENGINE applies this when a click passes space:"image" with shotId=${r.shotId || '?'}; do not multiply it yourself.`,
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.`);
1099
+ if (identity) {
1100
+ lines.push('identity=true means the image was NOT resampled: image pixels and screen pixels differ only by the rect origin.');
1101
+ }
1102
+ if (r.frame === 'win32') {
1103
+ lines.push('note: frame=win32 -- DWM EXTENDED_FRAME_BOUNDS was unavailable, so screenRect came from GetWindowRect and includes the invisible shadow. '
1104
+ + 'Coordinates stay consistent with THIS capture, but a click at the very edge can land on the shadow rather than the client area.');
1105
+ }
1106
+ return result('screenshot', true, '', lines.join('\n'), {
1107
+ shotId: r.shotId, file: r.file, screenRect: rect, imageSize: size,
1108
+ scale, identity, frame: r.frame, captureBackend: r.captureBackend, dpiAware,
1109
+ });
1110
+ }
1111
+
1112
+ /**
1113
+ * Render a preview. The report is text on purpose: "what is under that point" is answered by the OS,
1114
+ * so confirming a point never depends on the model's reading of a picture.
1115
+ * @param {any} r @returns {Record<string, any>}
1116
+ */
1117
+ function formatPreview(r) {
1118
+ const x = r.previewX ?? '?';
1119
+ const y = r.previewY ?? '?';
1120
+ const atPoint = r.previewAtPoint === true || r.previewAtPoint === 'true';
1121
+ const head = atPoint && r.previewControlType
1122
+ ? `preview: would click ${x},${y} -> ${r.previewControlType} "${r.previewName || ''}"`
1123
+ + (r.previewAutomationId ? ` [${r.previewAutomationId}]` : '')
1124
+ : `preview: would click ${x},${y} -> no element is exposed at that point`;
1125
+ const rect = r.previewRect && typeof r.previewRect === 'object' ? r.previewRect : {};
1126
+ const lines = [
1127
+ head,
1128
+ `rect=${rect.left ?? '?'},${rect.top ?? '?'},${rect.right ?? '?'},${rect.bottom ?? '?'}`,
1129
+ `marker=${r.markerPlaced === true || r.markerPlaced === 'true' ? 'placed' : 'unavailable'}${r.markerReason ? ` (${r.markerReason})` : ''}`,
1130
+ ];
1131
+ if (r.previewReason) lines.push(`reason: ${r.previewReason}`);
1132
+ lines.push('no click was sent: a preview writes no input-queue entry, takes no focus, and produces no proof window');
1133
+ return result('preview', true, '', lines.join('\n'), {
1134
+ preview: {
1135
+ x, y,
1136
+ name: r.previewName ?? '', controlType: r.previewControlType ?? '', automationId: r.previewAutomationId ?? '',
1137
+ },
1138
+ });
1139
+ }
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
+
1216
+ /** Parse an engine-emitted "x,y" point. Returns null for anything else rather than guessing 0,0. */
1217
+ /** @param {any} s @returns {{x: number, y: number}|null} */
1218
+ function parsePoint(s) {
1219
+ if (typeof s !== 'string') return null;
1220
+ const m = s.match(/^(-?\d+),(-?\d+)$/);
1221
+ if (!m) return null;
1222
+ return { x: Number(m[1]), y: Number(m[2]) };
1223
+ }
1224
+
1225
+ /** Clamp a possibly-undefined number into [min,max], falling back to `fallback` for non-numbers.
1226
+ * SETTINGS only (0.9.0 split): a bad value on the configuration surface is a typo behind a form that
1227
+ * schemastery already validated, so the tolerant clamp stays -- refusing there would let one stale
1228
+ * setting brick every tool call. Call ARGUMENTS must not ride this function: silently rewriting what
1229
+ * the caller sent is the silent-fake-success shape G1 names. Use refuseOutOfRange there. */
1230
+ /** @param {any} value @param {number} min @param {number} max @param {number} fallback @returns {number} */
1231
+ function clampSetting(value, min, max, fallback) {
1232
+ const n = Number(value);
1233
+ if (!Number.isFinite(n)) return fallback;
1234
+ return Math.max(min, Math.min(max, Math.round(n)));
1235
+ }
1236
+
1237
+ /**
1238
+ * The argument-side twin: an out-of-range (or non-integer where `integer` is declared, or otherwise
1239
+ * non-numeric) CALL argument is a refusal naming the value the caller actually sent, never a silent
1240
+ * rewrite. `undefined` still means "not asked for" and takes the fallback. This layer is belt-and-braces
1241
+ * behind validateArguments -- the host's own defineTool may skip the shim's validator, so the sites
1242
+ * that forward numbers to the worker re-check the same bounds here.
1243
+ * @param {any} value @param {number} min @param {number} max @param {number|string} fallback
1244
+ * @param {string} name @param {boolean} [integer]
1245
+ * @returns {number|string}
1246
+ */
1247
+ function refuseOutOfRange(value, min, max, fallback, name, integer = true) {
1248
+ if (value === undefined || value === null) return fallback;
1249
+ const n = Number(value);
1250
+ if (!Number.isFinite(n) || (integer && !Number.isInteger(n))) {
1251
+ throw refusal('invalid_argument', `'${name}' must be ${integer ? 'a whole number' : 'a number'} in [${min}, ${max}] (got ${JSON.stringify(value)}); no worker request was made and the value was not rewritten`);
1252
+ }
1253
+ if (n < min || n > max) {
1254
+ throw refusal('invalid_argument', `'${name}' must be in [${min}, ${max}] (got ${n}); no worker request was made and the value was not clamped`);
1255
+ }
1256
+ return n;
1257
+ }
1258
+
1259
+ /** The same latch path the engine computes: %LOCALAPPDATA%\wpm\takeover-abort.<worker pid>. */
1260
+ /** @param {number|string} pid @returns {string} */
1261
+ function abortLatchPath(pid) {
1262
+ const base = process.env.LOCALAPPDATA || tmpdir();
1263
+ return join(base, 'wpm', `takeover-abort.${pid}`);
1264
+ }
1265
+
1266
+ /** A one-line target hint for a pre-worker refusal: the caller can retry without the field. */
1267
+ /** @param {WpmArgs} args @returns {string} */
1268
+ function hwndHint(args) {
1269
+ return args.hwnd ? ` (target hwnd=${args.hwnd})` : '';
1270
+ }
1271
+
1272
+ // Exported for tests: the projection from the five contract actions to this one tool.
1273
+ // `formatResult` is here so the effect dimension can be asserted on the SHIPPED projection, with
1274
+ // hand-authored engine results, without a desktop that has to cooperate.
1275
+ export const _internals = { PARAMETERS, ACTIONS, TOOL_NAME, clampSettle, clampSetting, refuseOutOfRange, CONFIG_DEFAULTS, formatResult: format };