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
@@ -1,1208 +1,1208 @@
1
- # engine.ps1 -- the only place where a decision becomes a syscall.
2
- #
3
- # One entry point, Invoke-WpmAction, and it always returns a result object rather than throwing on
4
- # a refusal: 'refused' is a normal outcome of this product, not an error path, and R3.2 requires
5
- # the reason to survive to the caller. Every result carries which channel ran, which tier it cost,
6
- # whether the owner's focus was taken and given back, and how long the whole thing took.
7
- #
8
- # ORDER OF OPERATIONS IS THE SAFETY DESIGN:
9
- # 1. measure the target's doors (facts; a target with no facts is refused)
10
- # 2. decide (pure table; pause/elevation/integrity first)
11
- # 3. if the tier costs a flash: capture the focus table BEFORE touching anything
12
- # 4. act through the cheapest available door
13
- # 5. if a flash was taken: restore, once, through the restore table
14
- # Nothing in step 4 can run for a target whose step 2 said refuse, and nothing in step 5 can pull
15
- # the focus from a window the owner chose.
16
-
17
- Set-StrictMode -Version 2.0
18
- $script:WpmEngineRoot = $PSScriptRoot
19
- . (Join-Path $PSScriptRoot 'decide.ps1')
20
- . (Join-Path $PSScriptRoot 'win.ps1')
21
-
22
- # THE PAUSE FLAG LIVES IN [WpmCtl], a static holder -- not in a script variable. The global hotkey
23
- # (Ctrl+Alt+Q, overlay.ps1) flips it from the overlay thread while actions read it on the main
24
- # thread; two copies across threads is the bug pattern this repo keeps meeting, and a script-scope
25
- # variable is exactly that second copy. $script:WpmPauseReason stays here because it is only ever
26
- # set through Set-WpmPaused, which runs on the main thread.
27
- $script:WpmPauseReason = ''
28
-
29
- function Set-WpmPaused([bool]$On, [string]$Reason = 'owner') {
30
- [WpmCtl]::Paused = $On
31
- $script:WpmPauseReason = if ($On) { $Reason } else { '' }
32
- }
33
-
34
- function Get-WpmStatus {
35
- $entry = Get-WpmFocusEntry
36
- return @{
37
- paused = [bool][WpmCtl]::Paused
38
- pauseReason = $script:WpmPauseReason
39
- foreground = $entry.fgHwnd
40
- foregroundPid = $entry.fgPid
41
- focusControl = $entry.focusHwnd
42
- lastInputAgeMs = $entry.lastInputAgeMs
43
- # The control board travels with status: whether the owner's overlay/hotkey surface is up, and
44
- # whether the hotkey actually registered. A silent 'overlay off' would make the README's
45
- # Ctrl+Alt+Q promise untrue with no way to notice.
46
- overlayRunning = [bool][WpmCtl]::OverlayOn
47
- overlayHwnd = [string][WpmCtl]::OverlayHwnd
48
- # The HUD travels with status for the same reason the overlay does: "the takeover surface exists"
49
- # must be checkable by the owner and by an independent oracle, not inferred from a successful call.
50
- hudOn = [bool][WpmCtl]::HudOn
51
- hudHwnd = [string][WpmCtl]::HudHwnd
52
- hudPhase = [string][WpmCtl]::HudPhase
53
- abortChord = [string][WpmCtl]::AbortChordLabel
54
- abortRequested = [bool][WpmCtl]::TakeoverAbort
55
- hotkeyRegistered = [bool][WpmCtl]::HotkeyOk
56
- hotkeyLabel = [string][WpmCtl]::HotkeyLabel
57
- overlayReason = [string][WpmCtl]::Reason
58
- dpiAware = [bool]$script:WpmDpiAware
59
- stance = 'quiet tier: no physical input at all; takeover tier (opt-in, HUD mandatory): cursor moves and is always restored, keyboard typed only when asked, three interrupt paths, no mouse injection'
60
- }
61
- }
62
-
63
- function Get-WpmWindowList {
64
- # Read-only enumeration for the model to choose a target by hwnd. Only visible, titled, non-cloaked
65
- # windows are listed: a list padded with invisible helper windows makes target selection guesswork.
66
- $acc = @()
67
- $cb = [WpmWin+EnumProc] {
68
- param([IntPtr]$h, [IntPtr]$l)
69
- if (-not [WpmWin]::IsWindowVisible($h)) { return $true }
70
- $t = [WpmWin]::Txt($h)
71
- if (-not $t) { return $true }
72
- if ([WpmWin]::IsIconic($h)) { return $true }
73
- $r = New-Object 'WpmWin+RECT'
74
- [void][WpmWin]::GetWindowRect($h, [ref]$r)
75
- $script:WpmEnumAcc += [pscustomobject]@{
76
- hwnd = $h.ToInt64().ToString()
77
- title = $t
78
- cls = [WpmWin]::Cls($h)
79
- pid = [WpmWin]::PidOf($h)
80
- rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)"
81
- }
82
- return $true
83
- }
84
- $script:WpmEnumAcc = @()
85
- [void][WpmWin]::EnumWindows($cb, [IntPtr]::Zero)
86
- $out = $script:WpmEnumAcc
87
- $script:WpmEnumAcc = $null
88
- return $out
89
- }
90
-
91
- function Resolve-WpmChildAtPoint([IntPtr]$Hwnd, [int]$X, [int]$Y) {
92
- # Which child HWND sits under a screen point, or Zero with the REASON recorded.
93
- #
94
- # The hit test refuses two different worlds with the same word, and the refusal text has to keep
95
- # them apart because their next steps do not overlap: a point outside every child of the named
96
- # window is a wrong coordinate; a point that IS inside one of our children but has a foreign window
97
- # on top is COVERAGE.
98
- #
99
- # WHY COVERAGE STILL REFUSES, when SendMessageW needs no visibility. Measured 2026-11-24: with the
100
- # owner's browser covering the target (target visible=true, rect 120,120,540,420; WindowFromPoint
101
- # over its own button returned Chrome_WidgetWin_1), delivering WM_LBUTTONDOWN/UP to the button
102
- # returned ok and the application NEVER RAN THE HANDLER -- focusTaken=false, button caption
103
- # unchanged. A click the app silently ignores is worse than a refusal that says why: the first
104
- # reports success for something that did not happen. So this refuses, names the blocker class, and
105
- # points at the only next step that works (bring the target forward).
106
- #
107
- # Index order is still not a contract (the original note): when the point is ours, the child is
108
- # chosen by which RECT holds it, never by its position in the enumeration.
109
- $p = New-Object 'WpmWin+POINT'
110
- $p.X = $X; $p.Y = $Y
111
- $hit = [WpmWin]::WindowFromPoint($p)
112
- $script:WpmPointCovered = $false
113
- $script:WpmPointBlocker = ''
114
- if ($hit -ne [IntPtr]::Zero -and [WpmWin]::Root($hit) -eq $Hwnd) { return $hit }
115
- foreach ($c in @([WpmWin]::Children($Hwnd))) {
116
- $child = [IntPtr]$c
117
- $r = New-Object 'WpmWin+RECT'
118
- if (-not [WpmWin]::GetWindowRect($child, [ref]$r)) { continue }
119
- if ($X -ge $r.Left -and $X -lt $r.Right -and $Y -ge $r.Top -and $Y -lt $r.Bottom) {
120
- $script:WpmPointCovered = $true
121
- if ($hit -ne [IntPtr]::Zero) { $script:WpmPointBlocker = [WpmWin]::Cls([WpmWin]::Root($hit)) }
122
- return [IntPtr]::Zero
123
- }
124
- }
125
- return [IntPtr]::Zero
126
- }
127
-
128
- function Get-WpmProofWindow {
129
- <#
130
- Sample cursor / foreground / focused-control / last-PHYSICAL-input-age for a fixed window.
131
- Four read-only syscalls per sample, no process, so it costs nothing the engine would not already
132
- pay while parked in a wait. Attribution is arithmetic and lives in lib/proof-window.mjs; this
133
- only produces the raw samples. If a read throws (secure desktop, transient) we stop early and
134
- return what we have -- the caller then reports 'insufficient' rather than inventing a verdict.
135
- Returns an array; the leading comma keeps it an array even when there is exactly one element.
136
- #>
137
- param([int]$Ms, [int]$EveryMs = 15)
138
- $samples = @()
139
- $base = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
140
- $deadline = $base + $Ms
141
- $next = $base
142
- while ($true) {
143
- $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
144
- if ($now -ge $deadline) { break }
145
- if ($now -lt $next) { Start-Sleep -Milliseconds ([Math]::Max(1, [int]($next - $now))); continue }
146
- try {
147
- $s = [WpmWin]::Sample()
148
- $samples += (@{ ts = $now; cx = [int]$s[0]; cy = [int]$s[1]; fg = [string]$s[2]; focus = [string]$s[3]; inputAgeMs = [long]$s[4] })
149
- } catch { break }
150
- $next = $now + $EveryMs
151
- }
152
- try {
153
- $tEnd = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
154
- $s2 = [WpmWin]::Sample()
155
- $samples += (@{ ts = $tEnd; cx = [int]$s2[0]; cy = [int]$s2[1]; fg = [string]$s2[2]; focus = [string]$s2[3]; inputAgeMs = [long]$s2[4] })
156
- } catch { }
157
- return ,$samples
158
- }
159
-
160
- function Invoke-WpmAction {
161
- param(
162
- # NOT Mandatory any more: a full-screen screenshot (screenshot + fullScreen:true) legitimately has
163
- # no target window, and PowerShell REFUSES to bind an empty string to a Mandatory [string]
164
- # parameter -- which surfaced as "cannot bind argument to parameter 'Hwnd' because it is an empty
165
- # string" instead of the capture the caller asked for. Every windowed action still checks liveness
166
- # itself and returns no_hwnd, so nothing was made lenient except the binding.
167
- [string]$Hwnd = '',
168
- [Parameter(Mandatory)][ValidateSet('click', 'type', 'focus', 'status', 'snapshot', 'screenshot', 'preview')][string]$Action,
169
- [int]$X = -1,
170
- [int]$Y = -1,
171
- [string]$Text = '',
172
- [string]$ElementName = '',
173
- [switch]$Replace,
174
- [int]$SettleMs = 350,
175
- # ---- R3 ------------------------------------------------------------------------------------
176
- # Takeover is a REQUEST with preconditions, never a flag that silently upgrades an action
177
- # (spec.md §4). TakeoverArmMs is the cancellation window; HudDoneMs is how long the "returned"
178
- # phase stays on screen before the HUD is torn down.
179
- [switch]$Takeover,
180
- [int]$TakeoverMaxMs = 10000,
181
- [switch]$KeyInject,
182
- [int]$TakeoverArmMs = 800,
183
- [int]$HudDoneMs = 1500,
184
- # ---- 0.5.0 read paths and element addressing ------------------------------------------------
185
- # `Space` is the coordinate space of X/Y for click. 'image' means the numbers came from a
186
- # screenshot and the ENGINE converts them: the caller never multiplies a scale factor, which is
187
- # the failure the upstream library documents against itself ("Click lands in the wrong place").
188
- [ValidateSet('screen', 'image')][string]$Space = 'screen',
189
- [string]$ShotId = '',
190
- # A label is a reference into the LAST frame this worker printed. It is resolved back to the UIA
191
- # element by RuntimeId, so a labelled action still takes the silent pattern path.
192
- [int]$Label = 0,
193
- [string]$SnapId = '',
194
- [int]$MaxElements = 300,
195
- [bool]$InteractableOnly = $true,
196
- [string]$SinceSnapId = '',
197
- [string]$Intent = '',
198
- [bool]$FullScreen = $false,
199
- [int]$MaxWidth = 0,
200
- [int]$ShotsKeep = 10,
201
- # ---- 0.6.0: where the caret should be when the message door types (type only) ----------------
202
- # `idle` is the existing behaviour and stays the default: nothing is touched, so an upgrade cannot
203
- # start moving carets on its own. `end` is implemented as EM_SETSEL(len,len) with len read from the
204
- # control, NOT as the documented -1 -- measured on WinForms EDIT, EM_SETSEL(-1,-1) leaves the
205
- # selection at 0,0 and the character lands at the FRONT (findings 8.2). The UIA `value` channel
206
- # replaces the whole value and has no caret to place, so it reports caretIgnored rather than
207
- # pretending the request was honoured.
208
- [ValidateSet('idle', 'start', 'end')][string]$CaretPosition = 'idle',
209
- # ---- 0.7.0 authorization, measured here because only this process can see the desktop -------
210
- # `Policy` and `RequiredTier` come from the host (settings + tools.json). The IDLE CHECK cannot come
211
- # from the host: last-input age is a GetLastInputInfo reading, and a host that wanted it before the
212
- # worker call would have to make a worker call. So the ceiling is enforced twice (host pre-worker,
213
- # engine here) and idle is enforced once, at the only place the number exists.
214
- [string]$Policy = 'balanced',
215
- [string]$RequiredTier = 'quiet',
216
- [int]$PolicyIdleMs = 3000,
217
- [switch]$ForceUserActive
218
- )
219
- $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
220
- $h = [IntPtr][int64]$Hwnd
221
- $result = @{
222
- ok = $false; action = $Action; hwnd = $Hwnd; channel = ''; tier = ''
223
- refusal = ''; reason = ''; detail = ''; latencyMs = 0
224
- focusTaken = 'false'; restoreOutcome = ''; restoreSetFg = ''; restoreJoined = ''
225
- effect = 'unverified'; proofSamples = @()
226
- # R3 fields. Empty strings rather than $null so the host half can test truthiness without
227
- # distinguishing "not a takeover" from "a takeover that said nothing".
228
- takeover = 'false'; cursorMoved = ''; cursorRestored = ''; takeoverMs = 0
229
- abortChord = ''; keysInjected = 0; injectedChars = 0
230
- }
231
-
232
- # A QUERY IS NOT AN ACTION, and this branch is early on purpose. It used to sit inside the action
233
- # chain, where 'status' fell through to the UIA branch and INVOKED the pattern it found -- a call
234
- # whose entire purpose is to report state would click a control. It is also placed before the
235
- # target check because a query has no target: 'what holds the focus' is answerable whatever the
236
- # caller passed, and refusing it for an unreachable window would be a query lying about why it
237
- # is empty. (Found by reading the branch order while writing the refusal cases, not by a failing
238
- # run -- the assertion in test/refusals-test.ps1 pins the fixed behaviour, it did not catch it.)
239
- if ($Action -eq 'status') {
240
- $st = Get-WpmStatus
241
- $result.ok = $true
242
- $result.channel = 'none'; $result.tier = 'none'
243
- $result.detail = 'status: query only, no action taken'
244
- $result.foreground = $st.foreground
245
- $result.foregroundPid = $st.foregroundPid
246
- $result.focusControl = $st.focusControl
247
- $result.lastInputAgeMs = $st.lastInputAgeMs
248
- $result.paused = $st.paused
249
- $result.stance = $st.stance
250
- # The DPI stance travels with status because the read paths (snapshot rects, screenshot pixels)
251
- # are only in PHYSICAL pixels while this process is per-monitor DPI aware. A future deletion of the
252
- # setter would otherwise turn the whole coordinate story half-scale with nothing to notice.
253
- $result.dpiAware = [bool]$st.dpiAware
254
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
255
- return $result
256
- }
257
-
258
- # ---- 0.5.0 READ PATHS: snapshot / screenshot / preview --------------------------------------
259
- # A READ IS NOT AN ACTION. None of these three writes an input-queue entry, takes the focus, or
260
- # produces a proof window -- there is no action to prove. They sit before the hwnd check because a
261
- # full-screen capture has no target window at all; each branch performs its own liveness check, so a
262
- # dead handle is still `no_hwnd` and a paused engine still says `paused` rather than serving reads.
263
- if ($Action -eq 'snapshot' -or $Action -eq 'screenshot' -or $Action -eq 'preview') {
264
- if ([WpmCtl]::Paused) {
265
- $result.refusal = 'paused'; $result.reason = $script:WpmRefusals.paused
266
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
267
- return $result
268
- }
269
- $needsWindow = -not ($Action -eq 'screenshot' -and $FullScreen)
270
- if ($needsWindow -and (-not $h -or -not [WpmWin]::IsWindow($h))) {
271
- $result.refusal = 'no_hwnd'; $result.reason = 'the hwnd does not identify a live window'
272
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
273
- return $result
274
- }
275
- $result.channel = 'none'; $result.tier = 'none'
276
- if ($Action -eq 'snapshot') {
277
- try {
278
- $snap = Get-WpmSnapshotTree -Hwnd $h -MaxElements $MaxElements -InteractableOnly $InteractableOnly `
279
- -Intent $Intent -SinceSnapId $SinceSnapId
280
- } catch {
281
- $result.refusal = 'uia_probe_failed'
282
- $result.reason = 'the accessibility probe threw while walking the tree: ' + $_.Exception.Message
283
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
284
- return $result
285
- }
286
- $snapFrame = if ($snap.ContainsKey('frame')) { [string]$snap.frame } else { '' }
287
- $snapCheck = if ($snap.ContainsKey('frameCheck')) { [string]$snap.frameCheck } else { '' }
288
- if (-not $snap.ok) {
289
- # THREE FAILURE WORLDS, three codes: a superseded id is stale_ref (re-read the frame); a frame
290
- # self-check failure is a refusal to point at all (unreachable -- the coordinates cannot be
291
- # trusted); anything else means the walk itself failed to measure (uia_probe_failed).
292
- if ($snap.stale) { $result.refusal = 'stale_ref' }
293
- elseif ($snapCheck -eq 'fail') { $result.refusal = 'unreachable' }
294
- else { $result.refusal = 'uia_probe_failed' }
295
- $result.reason = [string]$snap.reason
296
- $result.frame = $snapFrame
297
- $result.frameCheck = $snapCheck
298
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
299
- return $result
300
- }
301
- $result.ok = $true
302
- $result.detail = 'snapshot: read only, no action taken'
303
- $result.snapId = [string]$snap.snapId
304
- $result.frame = $snapFrame
305
- $result.frameCheck = $snapCheck
306
- $result.frameInset = $snap.frameInset
307
- $result.outsideFrame = [int]$snap.outsideFrame
308
- $result.intent = [string]$snap.intent
309
- $result.total = [int]$snap.total
310
- $result.count = [int]$snap.count
311
- $result.truncated = [bool]$snap.truncated
312
- $result.elements = @($snap.elements)
313
- $result.delta = $snap.delta
314
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
315
- return $result
316
- }
317
- if ($Action -eq 'screenshot') {
318
- try {
319
- $shot = Get-WpmScreenshot -Hwnd $h -FullScreen $FullScreen -MaxWidth $MaxWidth -Keep $ShotsKeep
320
- } catch {
321
- $result.refusal = 'action_failed'
322
- $result.reason = 'the capture threw: ' + $_.Exception.Message
323
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
324
- return $result
325
- }
326
- if (-not $shot.ok) {
327
- $result.refusal = 'action_failed'; $result.reason = [string]$shot.reason
328
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
329
- return $result
330
- }
331
- $result.ok = $true
332
- $result.detail = 'screenshot: read only, no action taken'
333
- $result.shotId = [string]$shot.shotId
334
- $result.file = [string]$shot.file
335
- $result.screenRect = $shot.screenRect
336
- $result.imageSize = $shot.imageSize
337
- $result.scale = [double]$shot.scale
338
- $result.identity = [bool]$shot.identity
339
- $result.frame = [string]$shot.frame
340
- # WHICH CAPTURE PATH PRODUCED THE PICTURE. Reported on every screenshot, not only when the cheap
341
- # path failed: a field that appears only in the exceptional case is how a silent substitution looks.
342
- $result.captureBackend = [string]$shot.captureBackend
343
- if ($shot.captureNote) { $result.captureNote = [string]$shot.captureNote }
344
- $result.dpiAware = [bool]$shot.dpiAware
345
- $result.bytes = [long]$shot.bytes
346
- $result.shotsKeep = [int]$shot.shotsKeep
347
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
348
- return $result
349
- }
350
- # ---- preview: draw the point, report the element under it as TEXT -------------------------
351
- $pv = Get-WpmPreviewAt -Hwnd $h -X $X -Y $Y
352
- if (-not $pv.ok) {
353
- if ($pv.outside) {
354
- $result.refusal = 'unreachable'
355
- $result.reason = 'the preview point does not belong to the target window: ' + [string]$pv.reason
356
- } else {
357
- # NOT `unreachable`: the point may be fine. The probe itself failed, so no conclusion about
358
- # what is under it is licensed -- the same distinction uia_probe_failed already draws.
359
- $result.refusal = 'uia_probe_failed'
360
- $result.reason = [string]$pv.reason
361
- }
362
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
363
- return $result
364
- }
365
- # THE MARKER IS A REQUEST, NOT AN ACTION (overlay.ps1 Set-WpmOverlayMarker writes three fields and
366
- # returns). A missing overlay downgrades to text only -- it must never fail the preview, because
367
- # "what is under this point" is answerable without a picture.
368
- $marker = @{ ok = $false; reason = 'overlay not loaded' }
369
- try {
370
- . (Join-Path $PSScriptRoot 'overlay.ps1')
371
- $marker = Set-WpmOverlayMarker -X $X -Y $Y
372
- } catch {
373
- $marker = @{ ok = $false; reason = 'overlay unavailable: ' + $_.Exception.Message }
374
- }
375
- $result.ok = $true
376
- $result.detail = 'preview: would click ' + $X + ',' + $Y
377
- $result.previewX = [int]$X
378
- $result.previewY = [int]$Y
379
- $result.previewAtPoint = [bool]$pv.atPoint
380
- $result.previewName = [string]$pv.name
381
- $result.previewControlType = [string]$pv.controlType
382
- $result.previewAutomationId = [string]$pv.automationId
383
- $result.previewRect = $pv.rect
384
- $result.previewReason = [string]$pv.reason
385
- $result.markerPlaced = [bool]$marker.ok
386
- $result.markerReason = if ($marker.ContainsKey('reason')) { [string]$marker.reason } else { '' }
387
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
388
- return $result
389
- }
390
-
391
- if (-not [WpmWin]::IsWindow($h)) {
392
- $result.refusal = 'no_hwnd'; $result.reason = 'the hwnd does not identify a live window'
393
- return $result
394
- }
395
-
396
- # ---- 0.6.0: a DISABLED target is a fact about the target, and Windows discards input to it -----
397
- # Measured (findings 8.1): with EnableWindow(false) every message this engine sends still RETURNS --
398
- # WM_SETTEXT and WM_CHAR both answer as if they worked, and the control simply does not take the click.
399
- # This is deliberately not a new refusal code: 'disabled' is a state of the target, not an error in the
400
- # call, and the caller may well want to know that the window is there but greyed out. What it does cost
401
- # is the right to claim an effect: `effect` is pinned to 'unverified' for a disabled target, so a
402
- # green-looking result cannot be produced by a window that was throwing our input away.
403
- $targetDisabled = -not [WpmWin]::IsWindowEnabled($h)
404
-
405
- # ---- 0.5.0: image coordinates are converted by the ENGINE, before anything is probed ---------
406
- # Why here: a bogus shotId must cost zero target probing, and the converted point then flows through
407
- # the EXISTING click path unchanged -- including the point-ownership assertion and the proof window.
408
- # Nothing about the safety contract is relaxed by accepting image coordinates.
409
- if ($Action -eq 'click' -and $Space -eq 'image') {
410
- $conv = Convert-WpmImagePoint -ShotId $ShotId -X $X -Y $Y
411
- if (-not $conv.ok) {
412
- $result.refusal = if ($conv.stale) { 'stale_ref' } else { 'unreachable' }
413
- $result.reason = [string]$conv.reason
414
- $result.coordSpace = 'image'
415
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
416
- return $result
417
- }
418
- $result.coordSpace = 'image'
419
- $result.shotId = [string]$ShotId
420
- $result.scale = [double]$conv.scale
421
- $result.imagePoint = "$X,$Y"
422
- $result.screenPoint = "$($conv.x),$($conv.y)"
423
- $X = [int]$conv.x
424
- $Y = [int]$conv.y
425
- }
426
-
427
- # Coordinates travel into the probe: the UIA tier resolves the element AT THE POINT. Without them
428
- # an unnamed click had no way to be anything other than "first control in tree order".
429
- $probe = Get-WpmFacts -Hwnd $h -Action $Action -ElementName $ElementName -X $X -Y $Y
430
- $facts = $probe.facts
431
- $facts.paused = [bool][WpmCtl]::Paused
432
- # ---- 0.5.0: a LABEL addresses the element itself -------------------------------------------
433
- # The label is resolved back to the UIA element by RuntimeId (measured stable across queries, 71/71),
434
- # so the action keeps the silent pattern path and never degrades into a coordinate click. Two things
435
- # are then enforced, and they are deliberately redundant:
436
- # * the label must still resolve, otherwise this is a reference to a frame that is gone (stale_ref);
437
- # * for a click, the caller's point must fall inside the labelled element -- "the point is the
438
- # contract" is not weakened by adding a second way to name the target.
439
- if ($Label -gt 0) {
440
- $res = Resolve-WpmSnapshotLabel -Hwnd $h -Label $Label -SnapId $SnapId
441
- if (-not $res.ok) {
442
- $result.refusal = 'stale_ref'; $result.reason = [string]$res.reason
443
- $result.label = $Label
444
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
445
- return $result
446
- }
447
- if ($Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
448
- $lr = $res.row.rect
449
- $eps = 2
450
- if ($X -lt ([int]$lr.left - $eps) -or $X -gt ([int]$lr.right + $eps) -or
451
- $Y -lt ([int]$lr.top - $eps) -or $Y -gt ([int]$lr.bottom + $eps)) {
452
- $result.refusal = 'unreachable'
453
- $result.reason = "label $Label is at rect=$($lr.left),$($lr.top),$($lr.right),$($lr.bottom) but the click point is $X,$Y -- the label and the point must agree before either is used"
454
- $result.label = $Label
455
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
456
- return $result
457
- }
458
- }
459
- $probe.uiaElement = $res.element
460
- $probe.uiaReason = ''
461
- $facts.hasPattern = $true
462
- $facts.patternKind = [string]$res.patternKind
463
- $facts.uiaTreeEmpty = $false
464
- $facts.uiaProbeFailed = $false
465
- $facts.messageDoor = $false # a window message cannot address "label 3"
466
- $result.label = $Label
467
- $result.snapId = [string]$res.snapId
468
- }
469
- if ($ElementName) {
470
- # A named control cannot be addressed through a window message: the message tiers take
471
- # coordinates or a child HWND, and "the Save button" is neither. Suppressing the door here is
472
- # what makes 'click the named button' honest -- claiming the quiet tier while actually having
473
- # to raise the window would report the cheap tier for the expensive action.
474
- $facts.messageDoor = $false
475
- }
476
- # ---- R3: the takeover request, and the HUD that must exist BEFORE the table can approve it ----
477
- # Order is the safety design: cheap disqualifiers first (a paused or elevated refusal must never spawn
478
- # a window), then the HUD, then the full decision. $Facts.hudReady is therefore a MEASUREMENT of the
479
- # HUD that was actually started, not an assumption that "we are about to start one".
480
- $facts.takeoverRequested = [bool]$Takeover
481
- $facts.keyInjectRequested = [bool]$KeyInject
482
- $facts.keyInjectAllowed = [bool]$KeyInject # the host gate already stripped the field when off
483
- $facts.hudReady = $false
484
- $facts.foregroundIsTarget = $false
485
- # 0.7.0: the rung this call actually needs. An explicit takeover request outranks the action's declared
486
- # minimum because moving the real cursor IS the higher permission; that escalation has to be visible to
487
- # the policy and idle checks or `policy:'quiet'` would be bypassed by a single flag.
488
- $facts.policy = $Policy
489
- $facts.requiredTier = $(if ($Takeover -or $KeyInject) { 'takeover' } else { $RequiredTier })
490
- $facts.forceUserActive = [bool]$ForceUserActive
491
- $facts.policyIdleMs = $PolicyIdleMs
492
- # Measured NOW, not carried from the earlier probe: an age read before the HUD came up would describe a
493
- # desktop that no longer exists, and the whole point of this fact is "was the owner busy a moment ago".
494
- $facts.lastInputAgeMs = [WpmWin]::LastInputAgeMs()
495
- $preFacts = $facts.Clone()
496
- $preFacts.takeoverRequested = $false
497
- $preFacts.keyInjectRequested = $false
498
- # THE ESCALATION GOES BACK OUT TOO. `requiredTier` was raised to 'takeover' a few lines above because
499
- # this call asks for the takeover tier; the pre-pass exists precisely to ask "what does the ACTION
500
- # itself need", so leaving the escalated rung in place made a `keyInput:'inject'`-only call answer
501
- # `user_active` (an idle refusal) instead of the `keyinject_unavailable` the arm asserts. A clone that
502
- # clears the request flags must clear what those flags implied, or the pre-pass measures a different
503
- # call than the one it claims to be checking.
504
- $preFacts.requiredTier = $RequiredTier
505
- $pre = Get-WpmChannelDecision $preFacts
506
- # THE CHEAP DISQUALIFIERS RUN BEFORE ANY WINDOW IS CREATED. 0.7.0 adds policy_denied and user_active to
507
- # this list rather than letting them be discovered later: a takeover request that the owner's settings
508
- # exclude must not flash a HUD at them on its way to saying no -- the HUD is itself the disturbance the
509
- # refusal exists to prevent.
510
- if ($pre.channel -eq 'refuse' -and (@('paused', 'no_hwnd', 'elevated_target', 'policy_denied', 'user_active') -contains $pre.refusal)) {
511
- $result.refusal = $pre.refusal; $result.reason = $pre.reason
512
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
513
- return $result
514
- }
515
- # BEFORE ANY RAISE. If the injection path has to bring the target forward, the focus table must be
516
- # captured first, or the raise looks like a third party's and would never be reversed.
517
- $entry = Get-WpmFocusEntry
518
- $hudStarted = $false
519
- $raisedByUs = $false
520
- if ($facts.takeoverRequested) {
521
- # G2: the two primitive modules are dot-sourced INSIDE this branch and nowhere else. The quiet and
522
- # bounded-flash tiers never even load SetCursorPos/SendInput into the session.
523
- . (Join-Path $PSScriptRoot 'takeover.ps1')
524
- . (Join-Path $PSScriptRoot 'input-inject.ps1')
525
- . (Join-Path $PSScriptRoot 'hud.ps1')
526
- # A CANCELLATION THAT ARRIVES DURING SETUP MUST NOT BE THROWN AWAY. The host writes the latch as soon as
527
- # the signal fires, and setup (module load + HUD start) can take longer than that. Clearing the latch
528
- # unconditionally at this point would delete a cancellation that was meant for THIS call -- measured
529
- # with test/signal-test.mjs: the abort landed, the latch was written, and the action ran to completion.
530
- # So: snapshot, then clear (a stale latch from a crashed action must not poison every later call), then
531
- # honour what was found.
532
- $preAborted = Test-WpmTakeoverAbort
533
- Reset-WpmTakeoverAbort | Out-Null
534
- $armClamped = [Math]::Max(0, [Math]::Min(5000, $TakeoverArmMs))
535
- $maxClamped = [Math]::Max(500, [Math]::Min(60000, $TakeoverMaxMs))
536
- $hud = Start-WpmHud -Action $Action -MaxMs $maxClamped -ArmMs $armClamped
537
- $hudStarted = [bool]$hud.ready
538
- $facts.hudReady = $hudStarted
539
- if ($facts.keyInjectRequested -and $hudStarted -and -not $facts.elevatedTarget) {
540
- # S1: SendInput writes to the FOREGROUND window. One raise attempt through the same input-queue
541
- # unlock the focus restore uses, then re-measure -- a decision made now is evidence; a decision
542
- # made 800ms ago is not.
543
- $fg0 = Test-WpmTargetForeground -Hwnd $Hwnd
544
- if (-not $fg0.ok) {
545
- $raised = [WpmWin]::RestoreForeground([IntPtr]$h)
546
- if ($raised -like 'true*') { $raisedByUs = $true }
547
- Start-Sleep -Milliseconds 60
548
- }
549
- $fg1 = Test-WpmTargetForeground -Hwnd $Hwnd
550
- $facts.foregroundIsTarget = [bool]$fg1.ok
551
- }
552
- }
553
- $decision = Get-WpmChannelDecision $facts
554
- # G3, and not ceremony: the HUD runs on its own thread and can fail between Start-WpmHud and here. The
555
- # decision approved takeover on a fact measured a moment ago; re-measure before a primitive exists in
556
- # the call path. scripts/check-takeover-path.mjs asserts this check sits between the branch entry and
557
- # every call to Set-WpmCursorTakeover / Send-WpmKeyText.
558
- if ($facts.takeoverRequested -and $decision.tier -eq 'takeover' -and -not (Test-WpmHudReady)) {
559
- if ($hudStarted) { [void](Stop-WpmHud) }
560
- $result.refusal = 'takeover_unavailable'
561
- $result.reason = $script:WpmRefusals.takeover_unavailable + ' [the HUD stopped between start and arming]'
562
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
563
- return $result
564
- }
565
- if ($raisedByUs -and -not $decision.needsRestore) {
566
- # We moved the owner's foreground for the injection; the same table that reverses a UIA flash has to
567
- # reverse this too, or "we only borrow what we give back" would have a hole exactly where the
568
- # loudest primitive is.
569
- $decision.needsRestore = $true
570
- }
571
-
572
- $result.channel = $decision.channel; $result.tier = $decision.tier
573
- $result.family = $probe.family; $result.cls = $probe.cls
574
- if ($decision.channel -eq 'refuse') {
575
- if ($hudStarted) { [void](Stop-WpmHud) }
576
- $result.refusal = $decision.refusal; $result.reason = $decision.reason
577
- # A refusal that says only 'unreachable' makes the reader guess which of two very different
578
- # things happened. When the point probe ran, it knows: the point is outside the target, or the
579
- # element there has no pattern, or the tree could not be walked at all. Carry that out -- a
580
- # refusal is a normal product outcome and its reason is the product (R3.2). The split codes
581
- # (uia_probe_failed / uia_tree_empty, decide.ps1) need the same context, so the point reason
582
- # rides on all of them; the probe's exception text always follows when it exists, because a
583
- # uia_probe_failed refusal whose reason hides the exception is a diagnosis with the evidence
584
- # redacted.
585
- if ($decision.refusal -in @('unreachable', 'uia_probe_failed', 'uia_tree_empty') -and $probe.uiaReason) {
586
- $result.reason = "$($decision.reason) -- at that point: $($probe.uiaReason)"
587
- }
588
- if ($probe.uiaErr) { $result.reason = "$($result.reason) [uia: $($probe.uiaErr)]" }
589
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
590
- return $result
591
- }
592
-
593
- # The focus table was captured above (before any raise). For the quiet tier it is still needed,
594
- # because 'the quiet channel did not take focus' is a claim that needs a before-value to be
595
- # falsifiable.
596
- $raisedHwnd = ''
597
- # THE PRE-ACTION CONTROL WINDOW. Sampled here, immediately BEFORE the door call, so that during it,
598
- # by construction, WE have done nothing. WHY A CONTROL IS REQUIRED AND NOT JUST A THRESHOLD:
599
- # "unexplained motion" from GetLastInputInfo proves no PHYSICAL input happened in the gap -- it
600
- # cannot tell our action apart from some background app nudging the cursor or stealing focus. A
601
- # hardcoded threshold is the vacuous-control trap this repo wrote down once (P0 task_5(f): "the
602
- # reset control passed vacuously"), and three real clicks proved it: a clean click measured isolated
603
- # 3.16px and 7.07px cursor jumps. So the judgment is STRUCTURAL, decided in lib/proof-window.mjs
604
- # using BOTH windows: sustained multi-gap cursor motion fails (no ambient correction drags across
605
- # gaps), an isolated single jump is inconclusive (a position delta cannot name its cause), and a
606
- # foreground/focus switch is blamed on us (fail) only when the control window shows the desktop was
607
- # NOT already doing it. Kept short (80ms): a few samples, no perceptible slowdown.
608
- $controlSamples = Get-WpmProofWindow -Ms 80
609
- $tAct = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
610
- # 0.6.0 locals. Declared here rather than inside the dispatch branches so that a channel which never
611
- # armed a readback (invoke/toggle/select, a refusal, an exception) is the ABSENCE of a plan and not a
612
- # leftover value from the previous call -- this worker is long-lived, and a stale plan would grade
613
- # today's action against yesterday's field.
614
- $focusBeforeDoor = $null
615
- $focusAfterDoor = $null
616
- $readbackPlan = $null
617
-
618
- # ---- the takeover choreography (spec.md §3) -------------------------------------------------
619
- # Everything from here to the finally exists because R3 promises three things the quiet tier never
620
- # did: the pointer move is VISIBLE (so the owner is warned before it costs them anything), the
621
- # pointer is ALWAYS returned, and the whole thing can be interrupted from three different places.
622
- $takeover = ($decision.tier -eq 'takeover')
623
- $cursorEntry = $null
624
- $abortedBeforeAct = $false
625
- $abortedByPause = $false
626
- $abortedDuringSetup = $false
627
- # $preAborted is NOT re-initialised here: it was snapshotted before Reset-WpmTakeoverAbort cleared the
628
- # flag, and re-zeroing it at this point silently discarded a cancellation that arrived during setup.
629
- # (Measured by test/signal-test.mjs -- the abort landed, the latch existed, and the action still ran.)
630
- $takeoverStartMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
631
- if ($takeover) {
632
- $result.takeover = 'true'
633
- if ($preAborted) { $abortedBeforeAct = $true; $abortedDuringSetup = $true }
634
- $result.hudHwnd = [string][WpmCtl]::HudHwnd
635
- # ARMING is a real cancellation window, not a sleep: all three interruption paths are read every
636
- # 50ms, and the HUD clock is updated so a long arming still shows progress.
637
- $armMs = [Math]::Max(0, [Math]::Min(5000, $TakeoverArmMs))
638
- $armDeadline = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + $armMs
639
- Set-WpmHudPhase -Phase 'arming' -Action $Action -MaxMs $TakeoverMaxMs -ElapsedMs 0 | Out-Null
640
- while ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $armDeadline) {
641
- # C12: the PAUSE switch is an interruption too, not a flag only read at decision time. The owner can
642
- # press it while the HUD is counting, and the promise is "stops now", not "stops next time".
643
- if (Test-WpmTakeoverAbort) { $abortedBeforeAct = $true; break }
644
- if ([WpmCtl]::Paused) { $abortedBeforeAct = $true; $abortedByPause = $true; break }
645
- Set-WpmHudPhase -Phase 'arming' -ElapsedMs ([int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $takeoverStartMs)) | Out-Null
646
- Start-Sleep -Milliseconds 50
647
- }
648
- if (-not $abortedBeforeAct) { Set-WpmHudPhase -Phase 'active' | Out-Null }
649
- }
650
-
651
- try {
652
- # THE CURSOR MOVE LIVES INSIDE THE SAME try THAT OWNS THE RESTORE (spec.md §6 G4): an exception in
653
- # the door call below still reaches the finally that puts the pointer back.
654
- #
655
- # 0.6.0: the focus table is re-read HERE, at the moment of sending, not reused from the one captured
656
- # before the probe. See the focusMoved block after the settle window for why this is a warning and
657
- # never a refusal.
658
- $focusBeforeDoor = Get-WpmFocusEntry
659
- if ($takeover -and -not $abortedBeforeAct -and $Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
660
- $cursorEntry = Set-WpmCursorTakeover -X $X -Y $Y
661
- $result.cursorMoved = if ($cursorEntry.applied) { 'true' } else { 'false' }
662
- $result.cursorX = [int]$cursorEntry.x
663
- $result.cursorY = [int]$cursorEntry.y
664
- $result.cursorBeforeX = [int]$cursorEntry.beforeX
665
- $result.cursorBeforeY = [int]$cursorEntry.beforeY
666
- }
667
- if ($abortedBeforeAct) {
668
- $result.refusal = 'takeover_aborted'
669
- $result.reason = if ($abortedByPause) { 'the owner paused the engine during the arming window; nothing was clicked or typed' } elseif ($abortedDuringSetup) { 'cancelled by the host before the arming window opened; nothing was clicked or typed' } else { 'interrupted during the arming window; nothing was clicked or typed' }
670
- } elseif ($decision.channel -eq 'message') {
671
- if ($Action -eq 'type') {
672
- # The door kind is decided ONCE, in the probe (win.ps1), and consumed here by kind.
673
- # This path used to re-match class names with its own copy of the pattern -- and that copy
674
- # carried the same 'Edit' vs 'WindowsForms10.EDIT.*' bug, so a fix in one place would have
675
- # silently left the other broken. One matcher, one truth.
676
- $target = $null
677
- foreach ($d in $probe.doorHandles) {
678
- if ($d.kind -eq 'text') { $target = [IntPtr]$d.hwnd; break }
679
- }
680
- if (-not $target) {
681
- $result.refusal = 'unreachable'; $result.reason = 'no editable child window for the message tier'
682
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
683
- return $result
684
- }
685
- if ([WpmWin]::IsWindowEnabled($target) -eq $false) { $targetDisabled = $true }
686
- # THE PRE-READ. Taken BEFORE the write, because the expected post-write value is only computable
687
- # from the value the control held plus the insertion point the CONTROL reports (its own EM_GETSEL
688
- # answer) -- not from an assumption that a write appends. Measured: an unfocused WinForms TextBox
689
- # inserts at 0, so 'abc' + 'XYZ' is 'XYZabc'; the model has to know both numbers or the
690
- # comparison grades its own guess.
691
- $preRead = Read-WpmControlText -Hwnd $target
692
- $w = [WpmWin]::MessageTextAt($target, $Text, [bool]$Replace, $CaretPosition)
693
- $mode = [string]$w[0]
694
- $sentChars = [int]$w[1]
695
- $selStart = [int]$w[2]; $selEnd = [int]$w[3]
696
- $caretAskedAt = if ($w.Count -gt 4) { [int]$w[4] } else { -1 }
697
- # Readback runs AFTER the settle window (the proof sampling is the settle), so an app that commits
698
- # its value asynchronously is not judged against a half-written buffer (plan R2).
699
- $readbackPlan = @{
700
- kind = 'message'; hwnd = $target; mode = $mode
701
- pre = $preRead; selStart = $selStart; selEnd = $selEnd; text = $Text; replace = [bool]$Replace
702
- }
703
- $caretNote = "caret=$CaretPosition asked=$(if ($caretAskedAt -ge 0) { $caretAskedAt } else { '(untouched)' }) applied=$selStart,$selEnd"
704
- $result.detail = "msg=$mode|$sentChars child=$($target.ToInt64()) $caretNote" + $(if (-not $preRead.exposesText) { ' readbackPre=unavailable' } else { '' })
705
- $result.effect = 'reported-by-send'
706
- } elseif ($Action -eq 'click') {
707
- if ($X -lt 0 -or $Y -lt 0) {
708
- $result.refusal = 'unreachable'; $result.reason = 'click needs screen coordinates'
709
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
710
- return $result
711
- }
712
- $child = Resolve-WpmChildAtPoint $h $X $Y
713
- if ($child -eq [IntPtr]::Zero) {
714
- $result.refusal = 'unreachable'
715
- $result.reason = $(if ($script:WpmPointCovered) {
716
- "the point is inside a child of the target but another window is on top (blocker class=$($script:WpmPointBlocker)); a message press there is accepted and ignored -- the application never runs the handler. Next step: bring the target to the front, or choose a point that is visible"
717
- } else { 'no child window of the target sits under that point' })
718
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
719
- return $result
720
- }
721
- $r = [WpmWin]::MessageClick($child, $X, $Y)
722
- $result.detail = "msg=$r child=$($child.ToInt64())"
723
- $result.effect = 'reported-by-send'
724
- }
725
- } elseif ($decision.channel -eq 'input') {
726
- # THE MEASURED DOORLESS CASE (a terminal, findings §B): typing into the FOREGROUND window. The
727
- # foreground assertion is repeated here, at the moment of sending, because the desktop can change
728
- # during the arming window -- the decision's fact is evidence about then, not about now.
729
- $fgNow = Test-WpmTargetForeground -Hwnd $Hwnd
730
- if (-not $fgNow.ok) {
731
- $result.refusal = 'keyinject_unavailable'
732
- $result.reason = $script:WpmRefusals.keyinject_unavailable + ' [foreground at send time: ' + $fgNow.foreground + ']'
733
- } else {
734
- # The pause switch rides the same abort probe: a long injection must stop when the owner says so.
735
- $inj = Send-WpmKeyText -Text $Text -ShouldAbort { (Test-WpmTakeoverAbort) -or [WpmCtl]::Paused }
736
- $result.detail = 'inject=unicode chars=' + $inj.chars + ' events=' + $inj.sent
737
- $result.keysInjected = [int]$inj.sent
738
- $result.injectedChars = [int]$inj.chars
739
- $result.effect = if ($inj.chars -gt 0) { 'reported-by-send' } else { 'unverified' }
740
- if ($inj.aborted) {
741
- $result.refusal = 'takeover_aborted'
742
- $result.reason = $inj.reason
743
- } elseif (-not $inj.ok) {
744
- $result.refusal = 'keyinject_unavailable'
745
- $result.reason = $inj.reason
746
- }
747
- }
748
- } elseif ($Action -eq 'focus') {
749
- # Focusing a control is a real operation an agent needs (type into a field, then read it).
750
- # It is also the one action that MUST change keyboard focus, so it is the honest way to
751
- # exercise the bounded-flash path: an Invoke can complete without activating anything, but
752
- # SetFocus cannot -- it transfers focus by definition.
753
- if ($decision.channel -ne 'uia') {
754
- $result.refusal = 'unreachable'; $result.reason = 'focus requires a UIA element; the message tier cannot set keyboard focus'
755
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
756
- return $result
757
- }
758
- $el = $probe.uiaElement
759
- if (-not $el) {
760
- $result.refusal = 'unreachable'; $result.reason = 'no element to focus'
761
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
762
- return $result
763
- }
764
- $el.SetFocus()
765
- $result.detail = 'uia=SetFocus'
766
- $result.effect = 'reported-by-pattern'
767
- } elseif ($decision.channel -eq 'uia') {
768
- $el = $probe.uiaElement
769
- if (-not $el) {
770
- $result.refusal = 'unreachable'; $result.reason = 'pattern was reported but no element could be re-obtained'
771
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
772
- return $result
773
- }
774
- $pats = Get-WpmUiaCached
775
- $kind = $facts.patternKind
776
- if ($kind -eq 'invoke') {
777
- $pat = $el.GetCurrentPattern($pats.invoke)
778
- $pat.Invoke()
779
- } elseif ($kind -eq 'value') {
780
- $pat = $el.GetCurrentPattern($pats.value)
781
- # THE PRE-READ THROUGH THE SAME PATTERN that writes. The UIA `value` channel is a whole-value
782
- # replace, so the expected after-value is computable exactly -- and the current value is read
783
- # from the pattern, not from a window message, because this is the channel the write went through.
784
- $preVal = ''
785
- $preOk = $false
786
- try { $preVal = [string]$pat.Current.Value; $preOk = $true } catch { $preOk = $false }
787
- $pat.SetValue($(if ($Replace) { $Text } else { [string]$pat.Current.Value + $Text }))
788
- $readbackPlan = @{
789
- kind = 'uia-value'; pat = $pat; mode = 'value'
790
- expected = $(if ($Replace) { $Text } else { $preVal + $Text })
791
- preOk = $preOk; pre = $preVal; text = $Text; replace = [bool]$Replace
792
- }
793
- } elseif ($kind -eq 'toggle') {
794
- $pat = $el.GetCurrentPattern($pats.toggle); $pat.Toggle()
795
- } elseif ($kind -eq 'select') {
796
- $pat = $el.GetCurrentPattern($pats.select); $pat.Select()
797
- } elseif ($kind -eq 'legacy') {
798
- $pat = $el.GetCurrentPattern($pats.legacy)
799
- $preVal = ''; $preOk = $false
800
- try { $preVal = [string]$pat.Current.Value; $preOk = $true } catch { $preOk = $false }
801
- $pat.SetValue($Text)
802
- $readbackPlan = @{
803
- kind = 'uia-legacy'; pat = $pat; mode = 'legacy'
804
- expected = $Text; preOk = $preOk; pre = $preVal; text = $Text; replace = $true
805
- }
806
- }
807
- $result.detail = "uia=$kind"
808
- # A caret request on this channel has no meaning -- `value` replaces the whole string, there is no
809
- # insertion point to move. Saying so is the difference between honouring a parameter and quietly
810
- # dropping it (the same discipline as `frame` and, in 0.6.0-B, `captureBackend`: a path that did
811
- # not do what you asked says so in the result).
812
- if ($CaretPosition -ne 'idle' -and $readbackPlan) {
813
- $result.detail += " caretIgnored=$kind-pattern"
814
- }
815
- $result.effect = 'reported-by-pattern'
816
- }
817
- $focusAfterDoor = Get-WpmFocusEntry
818
- } catch {
819
- $result.refusal = 'action_failed'
820
- $result.reason = 'the channel call threw: ' + $_.Exception.Message
821
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
822
- } finally {
823
- # THE BORROWED POINTER IS RETURNED HERE, UNCONDITIONALLY. Success, exception, refusal and
824
- # interruption all arrive at this block, which is the whole reason the move was placed inside the
825
- # try above. 'restored' is the READ-BACK, not the intent: a restore the OS refused reports
826
- # cursorRestored=false and becomes a hard proof failure downstream (spec.md §6, C5).
827
- if ($takeover) {
828
- if ($cursorEntry) {
829
- $cur = Restore-WpmCursorTakeover -Entry $cursorEntry
830
- $result.cursorRestored = if ($cur.restored) { 'true' } else { 'false' }
831
- $result.cursorAfterX = [int]$cur.x
832
- $result.cursorAfterY = [int]$cur.y
833
- if (-not $cur.restored) { $result.cursorRestoreReason = $cur.reason }
834
- } else {
835
- # No click point, so nothing was borrowed: the honest report is restored=true with moved=false.
836
- $result.cursorRestored = 'true'
837
- }
838
- $result.injectedChars = [int][WpmCtl]::InjectedChars
839
- $result.abortChord = [string][WpmCtl]::AbortChordLabel
840
- $result.takeoverMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $takeoverStartMs
841
- if ($TakeoverMaxMs -gt 0 -and $result.takeoverMs -gt $TakeoverMaxMs) {
842
- $result.takeoverNote = 'the action exceeded takeoverMaxMs=' + $TakeoverMaxMs + '; it was still restored'
843
- }
844
- # A LATCH LEFT BEHIND WOULD ABORT THE NEXT CALL. The host clears its own copy on dispose, but the
845
- # worker pid outlives a single action, so the engine clears it here as well -- after the restore, so
846
- # an interruption that arrives during cleanup is still visible to this action's own accounting.
847
- Reset-WpmTakeoverAbort | Out-Null
848
- Set-WpmHudPhase -Phase 'done' -ElapsedMs ([int]$result.takeoverMs) | Out-Null
849
- $dwell = if ($result.refusal) { 120 } else { [Math]::Max(0, [Math]::Min(5000, $HudDoneMs)) }
850
- if ($dwell -gt 0) { Start-Sleep -Milliseconds $dwell }
851
- [void](Stop-WpmHud)
852
- }
853
- }
854
-
855
- # THE ACTION WINDOW. Sampled DURING the settle sleep the engine already performed, so collecting
856
- # proof costs no extra delay. This is the window the claim is made about; it is judged against the
857
- # pre-action control captured above (proof-window decides how, from both). Attribution is arithmetic
858
- # and lives in lib/proof-window.mjs -- the engine only produces samples.
859
- $result.proofControl = $controlSamples
860
- $result.proofSamples = Get-WpmProofWindow -Ms $SettleMs
861
-
862
- # ---- 0.6.0 READBACK: the fourth `effect`, earned by reading the value back -------------------
863
- # This runs AFTER the settle window on purpose (plan R2): an application that commits its text
864
- # asynchronously must not be judged against a half-written buffer. The rule is narrow and it is the
865
- # whole feature -- `readback-verified` is used ONLY when the value read back equals the value the
866
- # model predicted from measurements the CONTROL reported. Anything else keeps the effect the write
867
- # itself earned, and the reason travels in `detail`.
868
- #
869
- # A mismatch is NOT a failure. The app may legitimately reformat what it was given (case folding,
870
- # trimming, a mask, a numeric parse), and `unreachable`/`action_failed` must not be repurposed to
871
- # mean "the value is not what I expected" -- so the refusal set is unchanged by this block, by design.
872
- if ($readbackPlan) {
873
- $expected = $null
874
- $expectedHow = ''
875
- if ($readbackPlan.kind -eq 'message') {
876
- $post = Read-WpmControlText -Hwnd $readbackPlan.hwnd
877
- $pre = $readbackPlan.pre
878
- if ($readbackPlan.mode -eq 'settext') {
879
- $expected = [string]$readbackPlan.text; $expectedHow = 'settext-equals-text'
880
- } elseif (-not $pre.exposesText -or $pre.truncated) {
881
- $expected = $null; $expectedHow = $(if (-not $pre.exposesText) { 'pre-read-unavailable' } else { 'pre-read-truncated' })
882
- } else {
883
- $b = [string]$pre.text
884
- $s = [int]$readbackPlan.selStart; $e = [int]$readbackPlan.selEnd
885
- if ($s -lt 0) { $s = 0 }
886
- if ($e -lt $s) { $e = $s }
887
- if ($s -gt $b.Length) { $s = $b.Length }
888
- if ($e -gt $b.Length) { $e = $b.Length }
889
- $expected = $b.Substring(0, $s) + [string]$readbackPlan.text + $b.Substring($e)
890
- $expectedHow = "insert-at-$s-$e"
891
- }
892
- $postRef = $post
893
- } else {
894
- $postVal = ''; $postOk = $false
895
- try { $postVal = [string]$readbackPlan.pat.Current.Value; $postOk = $true } catch { $postOk = $false }
896
- $expected = [string]$readbackPlan.expected; $expectedHow = 'pattern-current-value'
897
- $postRef = @{ ok = $postOk; exposesText = $postOk; truncated = $false; text = $postVal; chars = $postVal.Length }
898
- }
899
-
900
- if (-not $postRef.exposesText) {
901
- # Not "empty": the read produced nothing usable. Reporting readback=unavailable keeps the two
902
- # apart, which is the difference between "this field hides its text" and "this field is empty".
903
- $result.detail += ' readback=unavailable'
904
- } elseif ($null -eq $expected) {
905
- $result.detail += " readback=unmodelled($expectedHow)"
906
- } else {
907
- $shown = [string]$postRef.text
908
- if ($shown.Length -gt 120) { $shown = $shown.Substring(0, 119) + [char]0x2026 }
909
- $result.detail += " readback=$shown readbackLen=$([string]$postRef.text.Length)"
910
- if ($postRef.text -eq $expected) {
911
- $result.effect = 'readback-verified'
912
- } else {
913
- # The mismatch is carried as data because a caller that only reads `effect` must still be able
914
- # to tell "nothing reported success" from "it reported success and the value says otherwise".
915
- $result.detail += ' readbackMismatch=true'
916
- }
917
- }
918
- }
919
-
920
- # ---- 0.6.0 focus re-check at the moment of sending ------------------------------------------
921
- # A WARNING, never a refusal. The desktop can move between the probe and the send, and on the
922
- # bounded-flash tier the move is the channel working as documented. Refusing on a mismatch would
923
- # kill correct writes to be safe about a fact the readback already judges better -- so the field
924
- # says what was measured and lets the caller weigh it.
925
- if ($focusBeforeDoor -and $focusAfterDoor) {
926
- $moved = ($focusBeforeDoor.fgHwnd -ne $focusAfterDoor.fgHwnd) -or
927
- ($focusBeforeDoor.focusHwnd -ne $focusAfterDoor.focusHwnd)
928
- $result.detail += " focusMoved=$($moved.ToString().ToLower())"
929
- }
930
-
931
- # ---- 0.6.0 the disabled target, recorded last so it cannot be overridden ---------------------
932
- # `effect` is pinned to 'unverified' here even if a readback matched: a write into a greyed-out
933
- # window is not an effect the owner can rely on, and the one claim this field makes is that the
934
- # channel's own report is not being dressed up as a verified state change.
935
- if ($targetDisabled) {
936
- $result.detail += ' disabled=true'
937
- $result.effect = 'unverified'
938
- }
939
-
940
- # Did the action actually take the owner's focus? Measured, not assumed -- the quiet tier is
941
- # expected to say no and the flash tier yes, and a run where both say the same thing is a broken
942
- # instrument rather than a good result.
943
- #
944
- # WHICH window now holds the foreground matters, and the first version got it wrong: it recorded
945
- # whatever held the foreground as "the window we raised". When an action causes the TARGET APP to
946
- # open a dialog, that dialog is what comes forward -- so it looked like our own raised window and
947
- # was promptly restored away, shutting the dialog's focus the agent had just asked for. Only the
948
- # target itself counts as ours; anything else is the app's own window or a third party's, and it
949
- # is classified, never reversed.
950
- $nowFg = [WpmWin]::Fg()
951
- $targetStr = $h.ToInt64().ToString()
952
- $raisedHwnd = ''
953
- $raisedElsewhere = ''
954
- if ($nowFg -ne $entry.fgHwnd) {
955
- $result.focusTaken = 'true'
956
- if ($nowFg -eq $targetStr) { $raisedHwnd = $nowFg } else { $raisedElsewhere = $nowFg }
957
- }
958
- $result.raisedOurs = ($raisedHwnd -ne '').ToString().ToLower()
959
- if ($raisedElsewhere) { $result.raisedElsewhere = $raisedElsewhere }
960
-
961
- if ($decision.needsRestore) {
962
- $res = Restore-WpmFocus -Entry $entry -RaisedHwnd $raisedHwnd -RaisedElsewhere $raisedElsewhere `
963
- -TargetPid ($probe.pid.ToString())
964
- $result.restoreOutcome = $res.outcome
965
- $result.restoreReason = $res.reason
966
- $result.restoreSetFg = $res.setFg
967
- $result.restoreJoined = $res.joined
968
- $result.fgAfterRestore = $res.fgAfter
969
- # A restore the table authorised but the OS refused is a named failure, not a success with a
970
- # caveat: the owner is left in a window they did not choose, so the caller must surface it.
971
- # The span the owner actually pays: from the moment the action was issued to the moment the
972
- # focus was back. Reported separately from end-to-end latency because latency includes the
973
- # door probe and the settle wait, and a 'budget' quoted from latency would overstate the
974
- # disturbance by an order of magnitude.
975
- # Only meaningful when focus was actually taken: reporting a 'flash span' for an action that
976
- # never disturbed the owner would put a scary number next to a non-event.
977
- if ($result.focusTaken -eq 'true') {
978
- $result.flashMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $tAct
979
- }
980
- if ($res.outcome -eq 'restore' -and $res.setFg -ne 'true') {
981
- $result.refusal = 'restore_failed'
982
- $result.reason = 'the OS refused to return the foreground; the owner is still in the wrong window'
983
- }
984
- }
985
-
986
- $result.ok = ($result.refusal -eq '')
987
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
988
- $result.fgBefore = $entry.fgHwnd
989
- $result.fgNow = [WpmWin]::Fg()
990
- return $result
991
- }
992
-
993
- # ==================================================================================================
994
- # 0.7.0: the three desktop actions that are NOT door actions.
995
- # ==================================================================================================
996
-
997
- function Invoke-WpmDesktopAction {
998
- <#
999
- launch / clipboard / window live beside Invoke-WpmAction, not inside it, and that separation is the
1000
- point: a door action chooses a channel, costs a tier, takes and returns a focus, and is judged by a
1001
- proof window. A window move or a clipboard write does none of those things, and routing them through
1002
- the door table would either force them into a refusal code they do not deserve or make the table
1003
- answer for capabilities it never measured.
1004
-
1005
- WHAT THEY STILL DO: every one of them is verified by reading the STATE back -- `IsIconic`, the rect,
1006
- the ex-style, the clipboard's own content -- because the rule this product has been bitten by is that
1007
- a syscall's return value describes the CALL. So `effect` uses the same four values and the same rule:
1008
- `readback-verified` only when the read agrees, `unverified` otherwise, and the disagreement or the
1009
- reason travels in `detail`. No refusal code was added for this batch either: `launch` with the gate
1010
- off, a window with no hwnd, and a clipboard holding an unexpected format are all answered by the host
1011
- gate or by the existing `no_hwnd` / `action_failed` vocabulary.
1012
- #>
1013
- param(
1014
- [Parameter(Mandatory)][ValidateSet('launch', 'clipboard', 'window')][string]$Action,
1015
- [string]$Hwnd = '',
1016
- [string]$Target = '',
1017
- [object]$Arguments = $null,
1018
- [int]$WaitMs = 3000,
1019
- [string]$Op = '',
1020
- [string]$Format = 'text',
1021
- [string]$Text = '',
1022
- [string]$ShotId = '',
1023
- [int]$X = 0,
1024
- [int]$Y = 0,
1025
- [int]$Width = 0,
1026
- [int]$Height = 0,
1027
- [int]$MaxChars = 65536,
1028
- # ---- 0.7.0 authorization. The host gate runs first and costs zero worker requests; these are the
1029
- # engine's own second line, checked against the same table in decide.ps1 so the two processes cannot
1030
- # disagree about what the owner permitted.
1031
- [string]$Policy = 'balanced',
1032
- [int]$PolicyIdleMs = 3000,
1033
- [switch]$ForceUserActive,
1034
- [bool]$AppLaunchAllowed = $false,
1035
- [string[]]$AppLaunchAllow = @()
1036
- )
1037
- $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1038
- $result = @{ ok = $false; action = $Action; hwnd = $Hwnd; refusal = ''; reason = ''; detail = ''
1039
- effect = 'unverified'; latencyMs = 0 }
1040
-
1041
- if ($Action -eq 'launch') {
1042
- # The engine re-runs the gate and the whitelist through the SAME table the host used. A permission
1043
- # that lives in only one of the two processes is a permission that can be reached around by calling
1044
- # the other, and `launch` is the one action where that distinction has consequences.
1045
- $launchFacts = New-WpmFacts -Hwnd '' -Action launch -FactsMeasured $true `
1046
- -Policy $Policy -RequiredTier 'takeover' -PolicyIdleMs $PolicyIdleMs `
1047
- -ForceUserActive:([bool]$ForceUserActive) -LastInputAgeMs ([WpmWin]::LastInputAgeMs()) `
1048
- -AppLaunchAllowed:$AppLaunchAllowed -AppLaunchAllow $AppLaunchAllow -LaunchTarget $Target
1049
- $ld = Get-WpmChannelDecision $launchFacts
1050
- if ($ld.channel -eq 'refuse') {
1051
- $result.refusal = [string]$ld.refusal; $result.reason = [string]$ld.reason
1052
- $result.detail = "launch gate: allowed=$AppLaunchAllowed whitelist=$(@($AppLaunchAllow).Count) name(s)"
1053
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1054
- return $result
1055
- }
1056
- $argv = @()
1057
- if ($Arguments -is [array]) { $argv = @($Arguments | ForEach-Object { [string]$_ }) }
1058
- elseif ($Arguments -is [string] -and $Arguments) { $argv = @($Arguments) }
1059
- $s = Start-WpmApp -Target $Target -Arguments $argv
1060
- if (-not $s.ok) {
1061
- $result.refusal = 'action_failed'; $result.reason = [string]$s.reason
1062
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1063
- return $result
1064
- }
1065
- $result.pid = [int]$s.pid
1066
- $result.processName = [string]$s.name
1067
- $result.target = [string]$s.target
1068
- # The window is waited for only when the caller asked to address one. hwnd=0 after a successful
1069
- # launch is a REPORTED state ('window-not-yet'), never a failure -- see Wait-WpmAppWindow.
1070
- if ($WaitMs -gt 0) {
1071
- $w = Wait-WpmAppWindow -ProcessId ([int]$s.pid) -WaitMs $WaitMs
1072
- $result.hwnd = [string]$w.hwnd
1073
- $result.waitedMs = [int]$w.waitedMs
1074
- if ($w.hwnd) {
1075
- $result.ok = $true
1076
- $result.effect = 'readback-verified'
1077
- $result.detail = "launched pid=$($s.pid) hwnd=$($w.hwnd) title=$($w.title)"
1078
- } elseif ($w.ContainsKey('detail')) {
1079
- # ContainsKey on purpose: Wait-WpmAppWindow answers THREE different shapes -- window found, no
1080
- # window yet (carries detail=window-not-yet and a note), and the process is gone (carries a
1081
- # reason and no detail at all). Reading a key that a branch never set is a StrictMode throw, and a
1082
- # throw inside the handler for a started-but-windowless process would report `action_failed` on
1083
- # a program that is running fine -- the exact overstatement this engine exists to avoid.
1084
- $result.ok = $true
1085
- $result.detail = "launched pid=$($s.pid) " + [string]$w.detail + " waitedMs=$($w.waitedMs)"
1086
- if ($w.ContainsKey('note')) { $result.note = [string]$w.note }
1087
- } else {
1088
- $result.refusal = 'action_failed'
1089
- $result.reason = [string]$w.reason
1090
- $result.detail = "launched pid=$($s.pid) but no window could be observed"
1091
- }
1092
- } else {
1093
- $result.ok = $true
1094
- $result.detail = "launched pid=$($s.pid) window=not-asked (waitMs=0)"
1095
- }
1096
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1097
- return $result
1098
- }
1099
-
1100
- if ($Action -eq 'clipboard') {
1101
- if ($Op -eq 'read') {
1102
- $c = Get-WpmClipboard -Format $Format -MaxChars $MaxChars
1103
- if (-not $c.ok) {
1104
- $result.refusal = 'action_failed'; $result.reason = [string]$c.reason
1105
- # ContainsKey before reading: these failure paths return DIFFERENT key sets by design (a format
1106
- # miss carries the names it found, an exception does not), and under Set-StrictMode 2.0 reading a
1107
- # key that is simply absent throws -- turning a documented refusal into a crash inside the
1108
- # refusal handler, which is the failure mode the first run of this branch produced.
1109
- if ($c.ContainsKey('formats') -and $c.formats) { $result.detail = 'formats=' + ($c.formats -join ',') }
1110
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1111
- return $result
1112
- }
1113
- $result.ok = $true
1114
- $result.clipFormat = [string]$c.format
1115
- if ($c.format -eq 'text') {
1116
- # The CONTENT is deliberately not put into `detail`: the result text is written into a model's
1117
- # context and an audit line, and the clipboard is exactly the place where that can carry a token
1118
- # (R8). Length and the truncation flag are enough to decide what to do next.
1119
- $result.chars = [int]$c.chars
1120
- $result.truncated = [bool]$c.truncated
1121
- $result.effect = 'readback-verified'
1122
- $result.detail = "clipboard=read format=text chars=$($c.chars)" + $(if ($c.truncated) { " truncated=$($MaxChars)" } else { '' })
1123
- } else {
1124
- $result.file = [string]$c.file
1125
- $result.clipId = [string]$c.clipId
1126
- $result.imageSize = "$($c.width)x$($c.height)"
1127
- $result.effect = 'readback-verified'
1128
- $result.detail = "clipboard=read format=image file=$($c.file) size=$($c.width)x$($c.height)"
1129
- }
1130
- } elseif ($Op -eq 'write') {
1131
- $c = Set-WpmClipboard -Format $Format -Text $Text -ShotId $ShotId
1132
- if (-not $c.ok) {
1133
- $result.refusal = $(if ($c.ContainsKey('stale') -and $c.stale) { 'stale_ref' } else { 'action_failed' })
1134
- $result.reason = [string]$c.reason
1135
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1136
- return $result
1137
- }
1138
- $result.ok = $true
1139
- $result.clipFormat = [string]$c.format
1140
- if ($c.format -eq 'text') {
1141
- $result.chars = [int]$c.chars
1142
- # The read-back is a LENGTH comparison, and the value itself is not echoed: same reason as above.
1143
- $result.readbackChars = [int]$c.readbackChars
1144
- $result.effect = $(if ($c.readbackMatches) { 'readback-verified' } else { 'unverified' })
1145
- $result.detail = "clipboard=write format=text chars=$($c.chars) readbackChars=$($c.readbackChars)" +
1146
- $(if ($c.readbackMatches) { '' } else { ' readbackMismatch=true' })
1147
- } else {
1148
- $result.readbackSize = "$($c.readbackWidth)x$($c.readbackHeight)"
1149
- # The image read-back is a SIZE comparison against the shot that was pushed in: the pixels
1150
- # themselves cannot be hashed (two reads of a live screen differ, findings 5.1) and the shot's own
1151
- # dimensions are the fact the caller can act on.
1152
- $dimsMatch = ($c.readbackWidth -eq $c.width) -and ($c.readbackHeight -eq $c.height)
1153
- $result.effect = $(if ($dimsMatch) { 'readback-verified' } else { 'unverified' })
1154
- $result.detail = "clipboard=write format=image shotId=$($c.shotId) asked=$($c.width)x$($c.height) readback=$($c.readbackWidth)x$($c.readbackHeight)" +
1155
- $(if ($dimsMatch) { '' } else { ' readbackMismatch=true' })
1156
- }
1157
- } else {
1158
- $result.refusal = 'action_failed'; $result.reason = "clipboard needs op='read' or op='write'"
1159
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1160
- return $result
1161
- }
1162
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1163
- return $result
1164
- }
1165
-
1166
- # ---- window ------------------------------------------------------------------
1167
- if (-not $Hwnd) {
1168
- $result.refusal = 'no_hwnd'; $result.reason = 'window acts on one named window; there is no "all windows" op'
1169
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1170
- return $result
1171
- }
1172
- $fgBeforeOp = [WpmWin]::Fg()
1173
- $w = Invoke-WpmWindowOp -Hwnd ([IntPtr][int64]$Hwnd) -Op $Op -X $X -Y $Y -Width $Width -Height $Height
1174
- $fgAfterOp = [WpmWin]::Fg()
1175
- # Only the 'hwnd is not a live window' branch carries a refusal code; the others answer ok/false with a
1176
- # reason. Under StrictMode an unguarded read of a key that branch never sets would throw inside the
1177
- # handler, so presence is tested rather than assumed.
1178
- if ($w.ContainsKey('refusal') -and $w.refusal) { $result.refusal = [string]$w.refusal }
1179
- $result.ok = [bool]$w.ok
1180
- $result.reason = [string]$w.reason
1181
- $bits = @("window=$Op")
1182
- foreach ($k in @('iconic', 'called', 'asked', 'size', 'rect', 'before', 'topmost', 'exStyle', 'activated')) {
1183
- if ($w.ContainsKey($k)) {
1184
- # Lower-cased deliberately: every other boolean this engine puts into `detail` reads
1185
- # disabled=true / focusMoved=false / verified=true, and a PowerShell `True` in the same sentence is
1186
- # how a field ends up being parsed two ways by two consumers.
1187
- $val = $w[$k]
1188
- if ($val -is [bool]) { $val = $val.ToString().ToLower() }
1189
- $bits += "$k=$val"
1190
- }
1191
- }
1192
- $bits += $(if ($w.ok) { 'verified=true' } else { 'verified=false' })
1193
- # DID THE OWNER LOSE THE FOREGROUND TO THIS CALL -- measured on both sides of it, because
1194
- # `restore` activates by definition and a window op that quietly took the focus while reporting only a
1195
- # size change is the failure shape this product keeps meeting. Saying it is not the same as refusing
1196
- # it: the caller asked for the window to come back, and coming back is what restoring means.
1197
- $fgTaken = ($fgBeforeOp -ne $fgAfterOp) -and ($fgAfterOp -eq $Hwnd)
1198
- $bits += "foregroundTaken=$($fgTaken.ToString().ToLower())"
1199
- if ($fgTaken) {
1200
- $bits += "foregroundBefore=$fgBeforeOp foregroundAfter=$fgAfterOp"
1201
- }
1202
- $result.detail = ($bits -join ' ')
1203
- $result.foregroundTaken = $fgTaken
1204
- # The window's own answer is the read-back, so the effect follows it directly.
1205
- $result.effect = $(if ($w.ok) { 'readback-verified' } else { 'unverified' })
1206
- $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1207
- return $result
1208
- }
1
+ # engine.ps1 -- the only place where a decision becomes a syscall.
2
+ #
3
+ # One entry point, Invoke-WpmAction, and it always returns a result object rather than throwing on
4
+ # a refusal: 'refused' is a normal outcome of this product, not an error path, and R3.2 requires
5
+ # the reason to survive to the caller. Every result carries which channel ran, which tier it cost,
6
+ # whether the owner's focus was taken and given back, and how long the whole thing took.
7
+ #
8
+ # ORDER OF OPERATIONS IS THE SAFETY DESIGN:
9
+ # 1. measure the target's doors (facts; a target with no facts is refused)
10
+ # 2. decide (pure table; pause/elevation/integrity first)
11
+ # 3. if the tier costs a flash: capture the focus table BEFORE touching anything
12
+ # 4. act through the cheapest available door
13
+ # 5. if a flash was taken: restore, once, through the restore table
14
+ # Nothing in step 4 can run for a target whose step 2 said refuse, and nothing in step 5 can pull
15
+ # the focus from a window the owner chose.
16
+
17
+ Set-StrictMode -Version 2.0
18
+ $script:WpmEngineRoot = $PSScriptRoot
19
+ . (Join-Path $PSScriptRoot 'decide.ps1')
20
+ . (Join-Path $PSScriptRoot 'win.ps1')
21
+
22
+ # THE PAUSE FLAG LIVES IN [WpmCtl], a static holder -- not in a script variable. The global hotkey
23
+ # (Ctrl+Alt+Q, overlay.ps1) flips it from the overlay thread while actions read it on the main
24
+ # thread; two copies across threads is the bug pattern this repo keeps meeting, and a script-scope
25
+ # variable is exactly that second copy. $script:WpmPauseReason stays here because it is only ever
26
+ # set through Set-WpmPaused, which runs on the main thread.
27
+ $script:WpmPauseReason = ''
28
+
29
+ function Set-WpmPaused([bool]$On, [string]$Reason = 'owner') {
30
+ [WpmCtl]::Paused = $On
31
+ $script:WpmPauseReason = if ($On) { $Reason } else { '' }
32
+ }
33
+
34
+ function Get-WpmStatus {
35
+ $entry = Get-WpmFocusEntry
36
+ return @{
37
+ paused = [bool][WpmCtl]::Paused
38
+ pauseReason = $script:WpmPauseReason
39
+ foreground = $entry.fgHwnd
40
+ foregroundPid = $entry.fgPid
41
+ focusControl = $entry.focusHwnd
42
+ lastInputAgeMs = $entry.lastInputAgeMs
43
+ # The control board travels with status: whether the owner's overlay/hotkey surface is up, and
44
+ # whether the hotkey actually registered. A silent 'overlay off' would make the README's
45
+ # Ctrl+Alt+Q promise untrue with no way to notice.
46
+ overlayRunning = [bool][WpmCtl]::OverlayOn
47
+ overlayHwnd = [string][WpmCtl]::OverlayHwnd
48
+ # The HUD travels with status for the same reason the overlay does: "the takeover surface exists"
49
+ # must be checkable by the owner and by an independent oracle, not inferred from a successful call.
50
+ hudOn = [bool][WpmCtl]::HudOn
51
+ hudHwnd = [string][WpmCtl]::HudHwnd
52
+ hudPhase = [string][WpmCtl]::HudPhase
53
+ abortChord = [string][WpmCtl]::AbortChordLabel
54
+ abortRequested = [bool][WpmCtl]::TakeoverAbort
55
+ hotkeyRegistered = [bool][WpmCtl]::HotkeyOk
56
+ hotkeyLabel = [string][WpmCtl]::HotkeyLabel
57
+ overlayReason = [string][WpmCtl]::Reason
58
+ dpiAware = [bool]$script:WpmDpiAware
59
+ stance = 'quiet tier: no physical input at all; takeover tier (opt-in, HUD mandatory): cursor moves and is always restored, keyboard typed only when asked, three interrupt paths, no mouse injection'
60
+ }
61
+ }
62
+
63
+ function Get-WpmWindowList {
64
+ # Read-only enumeration for the model to choose a target by hwnd. Only visible, titled, non-cloaked
65
+ # windows are listed: a list padded with invisible helper windows makes target selection guesswork.
66
+ $acc = @()
67
+ $cb = [WpmWin+EnumProc] {
68
+ param([IntPtr]$h, [IntPtr]$l)
69
+ if (-not [WpmWin]::IsWindowVisible($h)) { return $true }
70
+ $t = [WpmWin]::Txt($h)
71
+ if (-not $t) { return $true }
72
+ if ([WpmWin]::IsIconic($h)) { return $true }
73
+ $r = New-Object 'WpmWin+RECT'
74
+ [void][WpmWin]::GetWindowRect($h, [ref]$r)
75
+ $script:WpmEnumAcc += [pscustomobject]@{
76
+ hwnd = $h.ToInt64().ToString()
77
+ title = $t
78
+ cls = [WpmWin]::Cls($h)
79
+ pid = [WpmWin]::PidOf($h)
80
+ rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)"
81
+ }
82
+ return $true
83
+ }
84
+ $script:WpmEnumAcc = @()
85
+ [void][WpmWin]::EnumWindows($cb, [IntPtr]::Zero)
86
+ $out = $script:WpmEnumAcc
87
+ $script:WpmEnumAcc = $null
88
+ return $out
89
+ }
90
+
91
+ function Resolve-WpmChildAtPoint([IntPtr]$Hwnd, [int]$X, [int]$Y) {
92
+ # Which child HWND sits under a screen point, or Zero with the REASON recorded.
93
+ #
94
+ # The hit test refuses two different worlds with the same word, and the refusal text has to keep
95
+ # them apart because their next steps do not overlap: a point outside every child of the named
96
+ # window is a wrong coordinate; a point that IS inside one of our children but has a foreign window
97
+ # on top is COVERAGE.
98
+ #
99
+ # WHY COVERAGE STILL REFUSES, when SendMessageW needs no visibility. Measured 2026-11-24: with the
100
+ # owner's browser covering the target (target visible=true, rect 120,120,540,420; WindowFromPoint
101
+ # over its own button returned Chrome_WidgetWin_1), delivering WM_LBUTTONDOWN/UP to the button
102
+ # returned ok and the application NEVER RAN THE HANDLER -- focusTaken=false, button caption
103
+ # unchanged. A click the app silently ignores is worse than a refusal that says why: the first
104
+ # reports success for something that did not happen. So this refuses, names the blocker class, and
105
+ # points at the only next step that works (bring the target forward).
106
+ #
107
+ # Index order is still not a contract (the original note): when the point is ours, the child is
108
+ # chosen by which RECT holds it, never by its position in the enumeration.
109
+ $p = New-Object 'WpmWin+POINT'
110
+ $p.X = $X; $p.Y = $Y
111
+ $hit = [WpmWin]::WindowFromPoint($p)
112
+ $script:WpmPointCovered = $false
113
+ $script:WpmPointBlocker = ''
114
+ if ($hit -ne [IntPtr]::Zero -and [WpmWin]::Root($hit) -eq $Hwnd) { return $hit }
115
+ foreach ($c in @([WpmWin]::Children($Hwnd))) {
116
+ $child = [IntPtr]$c
117
+ $r = New-Object 'WpmWin+RECT'
118
+ if (-not [WpmWin]::GetWindowRect($child, [ref]$r)) { continue }
119
+ if ($X -ge $r.Left -and $X -lt $r.Right -and $Y -ge $r.Top -and $Y -lt $r.Bottom) {
120
+ $script:WpmPointCovered = $true
121
+ if ($hit -ne [IntPtr]::Zero) { $script:WpmPointBlocker = [WpmWin]::Cls([WpmWin]::Root($hit)) }
122
+ return [IntPtr]::Zero
123
+ }
124
+ }
125
+ return [IntPtr]::Zero
126
+ }
127
+
128
+ function Get-WpmProofWindow {
129
+ <#
130
+ Sample cursor / foreground / focused-control / last-PHYSICAL-input-age for a fixed window.
131
+ Four read-only syscalls per sample, no process, so it costs nothing the engine would not already
132
+ pay while parked in a wait. Attribution is arithmetic and lives in lib/proof-window.mjs; this
133
+ only produces the raw samples. If a read throws (secure desktop, transient) we stop early and
134
+ return what we have -- the caller then reports 'insufficient' rather than inventing a verdict.
135
+ Returns an array; the leading comma keeps it an array even when there is exactly one element.
136
+ #>
137
+ param([int]$Ms, [int]$EveryMs = 15)
138
+ $samples = @()
139
+ $base = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
140
+ $deadline = $base + $Ms
141
+ $next = $base
142
+ while ($true) {
143
+ $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
144
+ if ($now -ge $deadline) { break }
145
+ if ($now -lt $next) { Start-Sleep -Milliseconds ([Math]::Max(1, [int]($next - $now))); continue }
146
+ try {
147
+ $s = [WpmWin]::Sample()
148
+ $samples += (@{ ts = $now; cx = [int]$s[0]; cy = [int]$s[1]; fg = [string]$s[2]; focus = [string]$s[3]; inputAgeMs = [long]$s[4] })
149
+ } catch { break }
150
+ $next = $now + $EveryMs
151
+ }
152
+ try {
153
+ $tEnd = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
154
+ $s2 = [WpmWin]::Sample()
155
+ $samples += (@{ ts = $tEnd; cx = [int]$s2[0]; cy = [int]$s2[1]; fg = [string]$s2[2]; focus = [string]$s2[3]; inputAgeMs = [long]$s2[4] })
156
+ } catch { }
157
+ return ,$samples
158
+ }
159
+
160
+ function Invoke-WpmAction {
161
+ param(
162
+ # NOT Mandatory any more: a full-screen screenshot (screenshot + fullScreen:true) legitimately has
163
+ # no target window, and PowerShell REFUSES to bind an empty string to a Mandatory [string]
164
+ # parameter -- which surfaced as "cannot bind argument to parameter 'Hwnd' because it is an empty
165
+ # string" instead of the capture the caller asked for. Every windowed action still checks liveness
166
+ # itself and returns no_hwnd, so nothing was made lenient except the binding.
167
+ [string]$Hwnd = '',
168
+ [Parameter(Mandatory)][ValidateSet('click', 'type', 'focus', 'status', 'snapshot', 'screenshot', 'preview')][string]$Action,
169
+ [int]$X = -1,
170
+ [int]$Y = -1,
171
+ [string]$Text = '',
172
+ [string]$ElementName = '',
173
+ [switch]$Replace,
174
+ [int]$SettleMs = 350,
175
+ # ---- R3 ------------------------------------------------------------------------------------
176
+ # Takeover is a REQUEST with preconditions, never a flag that silently upgrades an action
177
+ # (spec.md §4). TakeoverArmMs is the cancellation window; HudDoneMs is how long the "returned"
178
+ # phase stays on screen before the HUD is torn down.
179
+ [switch]$Takeover,
180
+ [int]$TakeoverMaxMs = 10000,
181
+ [switch]$KeyInject,
182
+ [int]$TakeoverArmMs = 800,
183
+ [int]$HudDoneMs = 1500,
184
+ # ---- 0.5.0 read paths and element addressing ------------------------------------------------
185
+ # `Space` is the coordinate space of X/Y for click. 'image' means the numbers came from a
186
+ # screenshot and the ENGINE converts them: the caller never multiplies a scale factor, which is
187
+ # the failure the upstream library documents against itself ("Click lands in the wrong place").
188
+ [ValidateSet('screen', 'image')][string]$Space = 'screen',
189
+ [string]$ShotId = '',
190
+ # A label is a reference into the LAST frame this worker printed. It is resolved back to the UIA
191
+ # element by RuntimeId, so a labelled action still takes the silent pattern path.
192
+ [int]$Label = 0,
193
+ [string]$SnapId = '',
194
+ [int]$MaxElements = 300,
195
+ [bool]$InteractableOnly = $true,
196
+ [string]$SinceSnapId = '',
197
+ [string]$Intent = '',
198
+ [bool]$FullScreen = $false,
199
+ [int]$MaxWidth = 0,
200
+ [int]$ShotsKeep = 10,
201
+ # ---- 0.6.0: where the caret should be when the message door types (type only) ----------------
202
+ # `idle` is the existing behaviour and stays the default: nothing is touched, so an upgrade cannot
203
+ # start moving carets on its own. `end` is implemented as EM_SETSEL(len,len) with len read from the
204
+ # control, NOT as the documented -1 -- measured on WinForms EDIT, EM_SETSEL(-1,-1) leaves the
205
+ # selection at 0,0 and the character lands at the FRONT (findings 8.2). The UIA `value` channel
206
+ # replaces the whole value and has no caret to place, so it reports caretIgnored rather than
207
+ # pretending the request was honoured.
208
+ [ValidateSet('idle', 'start', 'end')][string]$CaretPosition = 'idle',
209
+ # ---- 0.7.0 authorization, measured here because only this process can see the desktop -------
210
+ # `Policy` and `RequiredTier` come from the host (settings + tools.json). The IDLE CHECK cannot come
211
+ # from the host: last-input age is a GetLastInputInfo reading, and a host that wanted it before the
212
+ # worker call would have to make a worker call. So the ceiling is enforced twice (host pre-worker,
213
+ # engine here) and idle is enforced once, at the only place the number exists.
214
+ [string]$Policy = 'balanced',
215
+ [string]$RequiredTier = 'quiet',
216
+ [int]$PolicyIdleMs = 3000,
217
+ [switch]$ForceUserActive
218
+ )
219
+ $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
220
+ $h = [IntPtr][int64]$Hwnd
221
+ $result = @{
222
+ ok = $false; action = $Action; hwnd = $Hwnd; channel = ''; tier = ''
223
+ refusal = ''; reason = ''; detail = ''; latencyMs = 0
224
+ focusTaken = 'false'; restoreOutcome = ''; restoreSetFg = ''; restoreJoined = ''
225
+ effect = 'unverified'; proofSamples = @()
226
+ # R3 fields. Empty strings rather than $null so the host half can test truthiness without
227
+ # distinguishing "not a takeover" from "a takeover that said nothing".
228
+ takeover = 'false'; cursorMoved = ''; cursorRestored = ''; takeoverMs = 0
229
+ abortChord = ''; keysInjected = 0; injectedChars = 0
230
+ }
231
+
232
+ # A QUERY IS NOT AN ACTION, and this branch is early on purpose. It used to sit inside the action
233
+ # chain, where 'status' fell through to the UIA branch and INVOKED the pattern it found -- a call
234
+ # whose entire purpose is to report state would click a control. It is also placed before the
235
+ # target check because a query has no target: 'what holds the focus' is answerable whatever the
236
+ # caller passed, and refusing it for an unreachable window would be a query lying about why it
237
+ # is empty. (Found by reading the branch order while writing the refusal cases, not by a failing
238
+ # run -- the assertion in test/refusals-test.ps1 pins the fixed behaviour, it did not catch it.)
239
+ if ($Action -eq 'status') {
240
+ $st = Get-WpmStatus
241
+ $result.ok = $true
242
+ $result.channel = 'none'; $result.tier = 'none'
243
+ $result.detail = 'status: query only, no action taken'
244
+ $result.foreground = $st.foreground
245
+ $result.foregroundPid = $st.foregroundPid
246
+ $result.focusControl = $st.focusControl
247
+ $result.lastInputAgeMs = $st.lastInputAgeMs
248
+ $result.paused = $st.paused
249
+ $result.stance = $st.stance
250
+ # The DPI stance travels with status because the read paths (snapshot rects, screenshot pixels)
251
+ # are only in PHYSICAL pixels while this process is per-monitor DPI aware. A future deletion of the
252
+ # setter would otherwise turn the whole coordinate story half-scale with nothing to notice.
253
+ $result.dpiAware = [bool]$st.dpiAware
254
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
255
+ return $result
256
+ }
257
+
258
+ # ---- 0.5.0 READ PATHS: snapshot / screenshot / preview --------------------------------------
259
+ # A READ IS NOT AN ACTION. None of these three writes an input-queue entry, takes the focus, or
260
+ # produces a proof window -- there is no action to prove. They sit before the hwnd check because a
261
+ # full-screen capture has no target window at all; each branch performs its own liveness check, so a
262
+ # dead handle is still `no_hwnd` and a paused engine still says `paused` rather than serving reads.
263
+ if ($Action -eq 'snapshot' -or $Action -eq 'screenshot' -or $Action -eq 'preview') {
264
+ if ([WpmCtl]::Paused) {
265
+ $result.refusal = 'paused'; $result.reason = $script:WpmRefusals.paused
266
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
267
+ return $result
268
+ }
269
+ $needsWindow = -not ($Action -eq 'screenshot' -and $FullScreen)
270
+ if ($needsWindow -and (-not $h -or -not [WpmWin]::IsWindow($h))) {
271
+ $result.refusal = 'no_hwnd'; $result.reason = 'the hwnd does not identify a live window'
272
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
273
+ return $result
274
+ }
275
+ $result.channel = 'none'; $result.tier = 'none'
276
+ if ($Action -eq 'snapshot') {
277
+ try {
278
+ $snap = Get-WpmSnapshotTree -Hwnd $h -MaxElements $MaxElements -InteractableOnly $InteractableOnly `
279
+ -Intent $Intent -SinceSnapId $SinceSnapId
280
+ } catch {
281
+ $result.refusal = 'uia_probe_failed'
282
+ $result.reason = 'the accessibility probe threw while walking the tree: ' + $_.Exception.Message
283
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
284
+ return $result
285
+ }
286
+ $snapFrame = if ($snap.ContainsKey('frame')) { [string]$snap.frame } else { '' }
287
+ $snapCheck = if ($snap.ContainsKey('frameCheck')) { [string]$snap.frameCheck } else { '' }
288
+ if (-not $snap.ok) {
289
+ # THREE FAILURE WORLDS, three codes: a superseded id is stale_ref (re-read the frame); a frame
290
+ # self-check failure is a refusal to point at all (unreachable -- the coordinates cannot be
291
+ # trusted); anything else means the walk itself failed to measure (uia_probe_failed).
292
+ if ($snap.stale) { $result.refusal = 'stale_ref' }
293
+ elseif ($snapCheck -eq 'fail') { $result.refusal = 'unreachable' }
294
+ else { $result.refusal = 'uia_probe_failed' }
295
+ $result.reason = [string]$snap.reason
296
+ $result.frame = $snapFrame
297
+ $result.frameCheck = $snapCheck
298
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
299
+ return $result
300
+ }
301
+ $result.ok = $true
302
+ $result.detail = 'snapshot: read only, no action taken'
303
+ $result.snapId = [string]$snap.snapId
304
+ $result.frame = $snapFrame
305
+ $result.frameCheck = $snapCheck
306
+ $result.frameInset = $snap.frameInset
307
+ $result.outsideFrame = [int]$snap.outsideFrame
308
+ $result.intent = [string]$snap.intent
309
+ $result.total = [int]$snap.total
310
+ $result.count = [int]$snap.count
311
+ $result.truncated = [bool]$snap.truncated
312
+ $result.elements = @($snap.elements)
313
+ $result.delta = $snap.delta
314
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
315
+ return $result
316
+ }
317
+ if ($Action -eq 'screenshot') {
318
+ try {
319
+ $shot = Get-WpmScreenshot -Hwnd $h -FullScreen $FullScreen -MaxWidth $MaxWidth -Keep $ShotsKeep
320
+ } catch {
321
+ $result.refusal = 'action_failed'
322
+ $result.reason = 'the capture threw: ' + $_.Exception.Message
323
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
324
+ return $result
325
+ }
326
+ if (-not $shot.ok) {
327
+ $result.refusal = 'action_failed'; $result.reason = [string]$shot.reason
328
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
329
+ return $result
330
+ }
331
+ $result.ok = $true
332
+ $result.detail = 'screenshot: read only, no action taken'
333
+ $result.shotId = [string]$shot.shotId
334
+ $result.file = [string]$shot.file
335
+ $result.screenRect = $shot.screenRect
336
+ $result.imageSize = $shot.imageSize
337
+ $result.scale = [double]$shot.scale
338
+ $result.identity = [bool]$shot.identity
339
+ $result.frame = [string]$shot.frame
340
+ # WHICH CAPTURE PATH PRODUCED THE PICTURE. Reported on every screenshot, not only when the cheap
341
+ # path failed: a field that appears only in the exceptional case is how a silent substitution looks.
342
+ $result.captureBackend = [string]$shot.captureBackend
343
+ if ($shot.captureNote) { $result.captureNote = [string]$shot.captureNote }
344
+ $result.dpiAware = [bool]$shot.dpiAware
345
+ $result.bytes = [long]$shot.bytes
346
+ $result.shotsKeep = [int]$shot.shotsKeep
347
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
348
+ return $result
349
+ }
350
+ # ---- preview: draw the point, report the element under it as TEXT -------------------------
351
+ $pv = Get-WpmPreviewAt -Hwnd $h -X $X -Y $Y
352
+ if (-not $pv.ok) {
353
+ if ($pv.outside) {
354
+ $result.refusal = 'unreachable'
355
+ $result.reason = 'the preview point does not belong to the target window: ' + [string]$pv.reason
356
+ } else {
357
+ # NOT `unreachable`: the point may be fine. The probe itself failed, so no conclusion about
358
+ # what is under it is licensed -- the same distinction uia_probe_failed already draws.
359
+ $result.refusal = 'uia_probe_failed'
360
+ $result.reason = [string]$pv.reason
361
+ }
362
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
363
+ return $result
364
+ }
365
+ # THE MARKER IS A REQUEST, NOT AN ACTION (overlay.ps1 Set-WpmOverlayMarker writes three fields and
366
+ # returns). A missing overlay downgrades to text only -- it must never fail the preview, because
367
+ # "what is under this point" is answerable without a picture.
368
+ $marker = @{ ok = $false; reason = 'overlay not loaded' }
369
+ try {
370
+ . (Join-Path $PSScriptRoot 'overlay.ps1')
371
+ $marker = Set-WpmOverlayMarker -X $X -Y $Y
372
+ } catch {
373
+ $marker = @{ ok = $false; reason = 'overlay unavailable: ' + $_.Exception.Message }
374
+ }
375
+ $result.ok = $true
376
+ $result.detail = 'preview: would click ' + $X + ',' + $Y
377
+ $result.previewX = [int]$X
378
+ $result.previewY = [int]$Y
379
+ $result.previewAtPoint = [bool]$pv.atPoint
380
+ $result.previewName = [string]$pv.name
381
+ $result.previewControlType = [string]$pv.controlType
382
+ $result.previewAutomationId = [string]$pv.automationId
383
+ $result.previewRect = $pv.rect
384
+ $result.previewReason = [string]$pv.reason
385
+ $result.markerPlaced = [bool]$marker.ok
386
+ $result.markerReason = if ($marker.ContainsKey('reason')) { [string]$marker.reason } else { '' }
387
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
388
+ return $result
389
+ }
390
+
391
+ if (-not [WpmWin]::IsWindow($h)) {
392
+ $result.refusal = 'no_hwnd'; $result.reason = 'the hwnd does not identify a live window'
393
+ return $result
394
+ }
395
+
396
+ # ---- 0.6.0: a DISABLED target is a fact about the target, and Windows discards input to it -----
397
+ # Measured (findings 8.1): with EnableWindow(false) every message this engine sends still RETURNS --
398
+ # WM_SETTEXT and WM_CHAR both answer as if they worked, and the control simply does not take the click.
399
+ # This is deliberately not a new refusal code: 'disabled' is a state of the target, not an error in the
400
+ # call, and the caller may well want to know that the window is there but greyed out. What it does cost
401
+ # is the right to claim an effect: `effect` is pinned to 'unverified' for a disabled target, so a
402
+ # green-looking result cannot be produced by a window that was throwing our input away.
403
+ $targetDisabled = -not [WpmWin]::IsWindowEnabled($h)
404
+
405
+ # ---- 0.5.0: image coordinates are converted by the ENGINE, before anything is probed ---------
406
+ # Why here: a bogus shotId must cost zero target probing, and the converted point then flows through
407
+ # the EXISTING click path unchanged -- including the point-ownership assertion and the proof window.
408
+ # Nothing about the safety contract is relaxed by accepting image coordinates.
409
+ if ($Action -eq 'click' -and $Space -eq 'image') {
410
+ $conv = Convert-WpmImagePoint -ShotId $ShotId -X $X -Y $Y
411
+ if (-not $conv.ok) {
412
+ $result.refusal = if ($conv.stale) { 'stale_ref' } else { 'unreachable' }
413
+ $result.reason = [string]$conv.reason
414
+ $result.coordSpace = 'image'
415
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
416
+ return $result
417
+ }
418
+ $result.coordSpace = 'image'
419
+ $result.shotId = [string]$ShotId
420
+ $result.scale = [double]$conv.scale
421
+ $result.imagePoint = "$X,$Y"
422
+ $result.screenPoint = "$($conv.x),$($conv.y)"
423
+ $X = [int]$conv.x
424
+ $Y = [int]$conv.y
425
+ }
426
+
427
+ # Coordinates travel into the probe: the UIA tier resolves the element AT THE POINT. Without them
428
+ # an unnamed click had no way to be anything other than "first control in tree order".
429
+ $probe = Get-WpmFacts -Hwnd $h -Action $Action -ElementName $ElementName -X $X -Y $Y
430
+ $facts = $probe.facts
431
+ $facts.paused = [bool][WpmCtl]::Paused
432
+ # ---- 0.5.0: a LABEL addresses the element itself -------------------------------------------
433
+ # The label is resolved back to the UIA element by RuntimeId (measured stable across queries, 71/71),
434
+ # so the action keeps the silent pattern path and never degrades into a coordinate click. Two things
435
+ # are then enforced, and they are deliberately redundant:
436
+ # * the label must still resolve, otherwise this is a reference to a frame that is gone (stale_ref);
437
+ # * for a click, the caller's point must fall inside the labelled element -- "the point is the
438
+ # contract" is not weakened by adding a second way to name the target.
439
+ if ($Label -gt 0) {
440
+ $res = Resolve-WpmSnapshotLabel -Hwnd $h -Label $Label -SnapId $SnapId
441
+ if (-not $res.ok) {
442
+ $result.refusal = 'stale_ref'; $result.reason = [string]$res.reason
443
+ $result.label = $Label
444
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
445
+ return $result
446
+ }
447
+ if ($Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
448
+ $lr = $res.row.rect
449
+ $eps = 2
450
+ if ($X -lt ([int]$lr.left - $eps) -or $X -gt ([int]$lr.right + $eps) -or
451
+ $Y -lt ([int]$lr.top - $eps) -or $Y -gt ([int]$lr.bottom + $eps)) {
452
+ $result.refusal = 'unreachable'
453
+ $result.reason = "label $Label is at rect=$($lr.left),$($lr.top),$($lr.right),$($lr.bottom) but the click point is $X,$Y -- the label and the point must agree before either is used"
454
+ $result.label = $Label
455
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
456
+ return $result
457
+ }
458
+ }
459
+ $probe.uiaElement = $res.element
460
+ $probe.uiaReason = ''
461
+ $facts.hasPattern = $true
462
+ $facts.patternKind = [string]$res.patternKind
463
+ $facts.uiaTreeEmpty = $false
464
+ $facts.uiaProbeFailed = $false
465
+ $facts.messageDoor = $false # a window message cannot address "label 3"
466
+ $result.label = $Label
467
+ $result.snapId = [string]$res.snapId
468
+ }
469
+ if ($ElementName) {
470
+ # A named control cannot be addressed through a window message: the message tiers take
471
+ # coordinates or a child HWND, and "the Save button" is neither. Suppressing the door here is
472
+ # what makes 'click the named button' honest -- claiming the quiet tier while actually having
473
+ # to raise the window would report the cheap tier for the expensive action.
474
+ $facts.messageDoor = $false
475
+ }
476
+ # ---- R3: the takeover request, and the HUD that must exist BEFORE the table can approve it ----
477
+ # Order is the safety design: cheap disqualifiers first (a paused or elevated refusal must never spawn
478
+ # a window), then the HUD, then the full decision. $Facts.hudReady is therefore a MEASUREMENT of the
479
+ # HUD that was actually started, not an assumption that "we are about to start one".
480
+ $facts.takeoverRequested = [bool]$Takeover
481
+ $facts.keyInjectRequested = [bool]$KeyInject
482
+ $facts.keyInjectAllowed = [bool]$KeyInject # the host gate already stripped the field when off
483
+ $facts.hudReady = $false
484
+ $facts.foregroundIsTarget = $false
485
+ # 0.7.0: the rung this call actually needs. An explicit takeover request outranks the action's declared
486
+ # minimum because moving the real cursor IS the higher permission; that escalation has to be visible to
487
+ # the policy and idle checks or `policy:'quiet'` would be bypassed by a single flag.
488
+ $facts.policy = $Policy
489
+ $facts.requiredTier = $(if ($Takeover -or $KeyInject) { 'takeover' } else { $RequiredTier })
490
+ $facts.forceUserActive = [bool]$ForceUserActive
491
+ $facts.policyIdleMs = $PolicyIdleMs
492
+ # Measured NOW, not carried from the earlier probe: an age read before the HUD came up would describe a
493
+ # desktop that no longer exists, and the whole point of this fact is "was the owner busy a moment ago".
494
+ $facts.lastInputAgeMs = [WpmWin]::LastInputAgeMs()
495
+ $preFacts = $facts.Clone()
496
+ $preFacts.takeoverRequested = $false
497
+ $preFacts.keyInjectRequested = $false
498
+ # THE ESCALATION GOES BACK OUT TOO. `requiredTier` was raised to 'takeover' a few lines above because
499
+ # this call asks for the takeover tier; the pre-pass exists precisely to ask "what does the ACTION
500
+ # itself need", so leaving the escalated rung in place made a `keyInput:'inject'`-only call answer
501
+ # `user_active` (an idle refusal) instead of the `keyinject_unavailable` the arm asserts. A clone that
502
+ # clears the request flags must clear what those flags implied, or the pre-pass measures a different
503
+ # call than the one it claims to be checking.
504
+ $preFacts.requiredTier = $RequiredTier
505
+ $pre = Get-WpmChannelDecision $preFacts
506
+ # THE CHEAP DISQUALIFIERS RUN BEFORE ANY WINDOW IS CREATED. 0.7.0 adds policy_denied and user_active to
507
+ # this list rather than letting them be discovered later: a takeover request that the owner's settings
508
+ # exclude must not flash a HUD at them on its way to saying no -- the HUD is itself the disturbance the
509
+ # refusal exists to prevent.
510
+ if ($pre.channel -eq 'refuse' -and (@('paused', 'no_hwnd', 'elevated_target', 'policy_denied', 'user_active') -contains $pre.refusal)) {
511
+ $result.refusal = $pre.refusal; $result.reason = $pre.reason
512
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
513
+ return $result
514
+ }
515
+ # BEFORE ANY RAISE. If the injection path has to bring the target forward, the focus table must be
516
+ # captured first, or the raise looks like a third party's and would never be reversed.
517
+ $entry = Get-WpmFocusEntry
518
+ $hudStarted = $false
519
+ $raisedByUs = $false
520
+ if ($facts.takeoverRequested) {
521
+ # G2: the two primitive modules are dot-sourced INSIDE this branch and nowhere else. The quiet and
522
+ # bounded-flash tiers never even load SetCursorPos/SendInput into the session.
523
+ . (Join-Path $PSScriptRoot 'takeover.ps1')
524
+ . (Join-Path $PSScriptRoot 'input-inject.ps1')
525
+ . (Join-Path $PSScriptRoot 'hud.ps1')
526
+ # A CANCELLATION THAT ARRIVES DURING SETUP MUST NOT BE THROWN AWAY. The host writes the latch as soon as
527
+ # the signal fires, and setup (module load + HUD start) can take longer than that. Clearing the latch
528
+ # unconditionally at this point would delete a cancellation that was meant for THIS call -- measured
529
+ # with test/signal-test.mjs: the abort landed, the latch was written, and the action ran to completion.
530
+ # So: snapshot, then clear (a stale latch from a crashed action must not poison every later call), then
531
+ # honour what was found.
532
+ $preAborted = Test-WpmTakeoverAbort
533
+ Reset-WpmTakeoverAbort | Out-Null
534
+ $armClamped = [Math]::Max(0, [Math]::Min(5000, $TakeoverArmMs))
535
+ $maxClamped = [Math]::Max(500, [Math]::Min(60000, $TakeoverMaxMs))
536
+ $hud = Start-WpmHud -Action $Action -MaxMs $maxClamped -ArmMs $armClamped
537
+ $hudStarted = [bool]$hud.ready
538
+ $facts.hudReady = $hudStarted
539
+ if ($facts.keyInjectRequested -and $hudStarted -and -not $facts.elevatedTarget) {
540
+ # S1: SendInput writes to the FOREGROUND window. One raise attempt through the same input-queue
541
+ # unlock the focus restore uses, then re-measure -- a decision made now is evidence; a decision
542
+ # made 800ms ago is not.
543
+ $fg0 = Test-WpmTargetForeground -Hwnd $Hwnd
544
+ if (-not $fg0.ok) {
545
+ $raised = [WpmWin]::RestoreForeground([IntPtr]$h)
546
+ if ($raised -like 'true*') { $raisedByUs = $true }
547
+ Start-Sleep -Milliseconds 60
548
+ }
549
+ $fg1 = Test-WpmTargetForeground -Hwnd $Hwnd
550
+ $facts.foregroundIsTarget = [bool]$fg1.ok
551
+ }
552
+ }
553
+ $decision = Get-WpmChannelDecision $facts
554
+ # G3, and not ceremony: the HUD runs on its own thread and can fail between Start-WpmHud and here. The
555
+ # decision approved takeover on a fact measured a moment ago; re-measure before a primitive exists in
556
+ # the call path. scripts/check-takeover-path.mjs asserts this check sits between the branch entry and
557
+ # every call to Set-WpmCursorTakeover / Send-WpmKeyText.
558
+ if ($facts.takeoverRequested -and $decision.tier -eq 'takeover' -and -not (Test-WpmHudReady)) {
559
+ if ($hudStarted) { [void](Stop-WpmHud) }
560
+ $result.refusal = 'takeover_unavailable'
561
+ $result.reason = $script:WpmRefusals.takeover_unavailable + ' [the HUD stopped between start and arming]'
562
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
563
+ return $result
564
+ }
565
+ if ($raisedByUs -and -not $decision.needsRestore) {
566
+ # We moved the owner's foreground for the injection; the same table that reverses a UIA flash has to
567
+ # reverse this too, or "we only borrow what we give back" would have a hole exactly where the
568
+ # loudest primitive is.
569
+ $decision.needsRestore = $true
570
+ }
571
+
572
+ $result.channel = $decision.channel; $result.tier = $decision.tier
573
+ $result.family = $probe.family; $result.cls = $probe.cls
574
+ if ($decision.channel -eq 'refuse') {
575
+ if ($hudStarted) { [void](Stop-WpmHud) }
576
+ $result.refusal = $decision.refusal; $result.reason = $decision.reason
577
+ # A refusal that says only 'unreachable' makes the reader guess which of two very different
578
+ # things happened. When the point probe ran, it knows: the point is outside the target, or the
579
+ # element there has no pattern, or the tree could not be walked at all. Carry that out -- a
580
+ # refusal is a normal product outcome and its reason is the product (R3.2). The split codes
581
+ # (uia_probe_failed / uia_tree_empty, decide.ps1) need the same context, so the point reason
582
+ # rides on all of them; the probe's exception text always follows when it exists, because a
583
+ # uia_probe_failed refusal whose reason hides the exception is a diagnosis with the evidence
584
+ # redacted.
585
+ if ($decision.refusal -in @('unreachable', 'uia_probe_failed', 'uia_tree_empty') -and $probe.uiaReason) {
586
+ $result.reason = "$($decision.reason) -- at that point: $($probe.uiaReason)"
587
+ }
588
+ if ($probe.uiaErr) { $result.reason = "$($result.reason) [uia: $($probe.uiaErr)]" }
589
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
590
+ return $result
591
+ }
592
+
593
+ # The focus table was captured above (before any raise). For the quiet tier it is still needed,
594
+ # because 'the quiet channel did not take focus' is a claim that needs a before-value to be
595
+ # falsifiable.
596
+ $raisedHwnd = ''
597
+ # THE PRE-ACTION CONTROL WINDOW. Sampled here, immediately BEFORE the door call, so that during it,
598
+ # by construction, WE have done nothing. WHY A CONTROL IS REQUIRED AND NOT JUST A THRESHOLD:
599
+ # "unexplained motion" from GetLastInputInfo proves no PHYSICAL input happened in the gap -- it
600
+ # cannot tell our action apart from some background app nudging the cursor or stealing focus. A
601
+ # hardcoded threshold is the vacuous-control trap this repo wrote down once (P0 task_5(f): "the
602
+ # reset control passed vacuously"), and three real clicks proved it: a clean click measured isolated
603
+ # 3.16px and 7.07px cursor jumps. So the judgment is STRUCTURAL, decided in lib/proof-window.mjs
604
+ # using BOTH windows: sustained multi-gap cursor motion fails (no ambient correction drags across
605
+ # gaps), an isolated single jump is inconclusive (a position delta cannot name its cause), and a
606
+ # foreground/focus switch is blamed on us (fail) only when the control window shows the desktop was
607
+ # NOT already doing it. Kept short (80ms): a few samples, no perceptible slowdown.
608
+ $controlSamples = Get-WpmProofWindow -Ms 80
609
+ $tAct = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
610
+ # 0.6.0 locals. Declared here rather than inside the dispatch branches so that a channel which never
611
+ # armed a readback (invoke/toggle/select, a refusal, an exception) is the ABSENCE of a plan and not a
612
+ # leftover value from the previous call -- this worker is long-lived, and a stale plan would grade
613
+ # today's action against yesterday's field.
614
+ $focusBeforeDoor = $null
615
+ $focusAfterDoor = $null
616
+ $readbackPlan = $null
617
+
618
+ # ---- the takeover choreography (spec.md §3) -------------------------------------------------
619
+ # Everything from here to the finally exists because R3 promises three things the quiet tier never
620
+ # did: the pointer move is VISIBLE (so the owner is warned before it costs them anything), the
621
+ # pointer is ALWAYS returned, and the whole thing can be interrupted from three different places.
622
+ $takeover = ($decision.tier -eq 'takeover')
623
+ $cursorEntry = $null
624
+ $abortedBeforeAct = $false
625
+ $abortedByPause = $false
626
+ $abortedDuringSetup = $false
627
+ # $preAborted is NOT re-initialised here: it was snapshotted before Reset-WpmTakeoverAbort cleared the
628
+ # flag, and re-zeroing it at this point silently discarded a cancellation that arrived during setup.
629
+ # (Measured by test/signal-test.mjs -- the abort landed, the latch existed, and the action still ran.)
630
+ $takeoverStartMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
631
+ if ($takeover) {
632
+ $result.takeover = 'true'
633
+ if ($preAborted) { $abortedBeforeAct = $true; $abortedDuringSetup = $true }
634
+ $result.hudHwnd = [string][WpmCtl]::HudHwnd
635
+ # ARMING is a real cancellation window, not a sleep: all three interruption paths are read every
636
+ # 50ms, and the HUD clock is updated so a long arming still shows progress.
637
+ $armMs = [Math]::Max(0, [Math]::Min(5000, $TakeoverArmMs))
638
+ $armDeadline = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + $armMs
639
+ Set-WpmHudPhase -Phase 'arming' -Action $Action -MaxMs $TakeoverMaxMs -ElapsedMs 0 | Out-Null
640
+ while ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $armDeadline) {
641
+ # C12: the PAUSE switch is an interruption too, not a flag only read at decision time. The owner can
642
+ # press it while the HUD is counting, and the promise is "stops now", not "stops next time".
643
+ if (Test-WpmTakeoverAbort) { $abortedBeforeAct = $true; break }
644
+ if ([WpmCtl]::Paused) { $abortedBeforeAct = $true; $abortedByPause = $true; break }
645
+ Set-WpmHudPhase -Phase 'arming' -ElapsedMs ([int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $takeoverStartMs)) | Out-Null
646
+ Start-Sleep -Milliseconds 50
647
+ }
648
+ if (-not $abortedBeforeAct) { Set-WpmHudPhase -Phase 'active' | Out-Null }
649
+ }
650
+
651
+ try {
652
+ # THE CURSOR MOVE LIVES INSIDE THE SAME try THAT OWNS THE RESTORE (spec.md §6 G4): an exception in
653
+ # the door call below still reaches the finally that puts the pointer back.
654
+ #
655
+ # 0.6.0: the focus table is re-read HERE, at the moment of sending, not reused from the one captured
656
+ # before the probe. See the focusMoved block after the settle window for why this is a warning and
657
+ # never a refusal.
658
+ $focusBeforeDoor = Get-WpmFocusEntry
659
+ if ($takeover -and -not $abortedBeforeAct -and $Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
660
+ $cursorEntry = Set-WpmCursorTakeover -X $X -Y $Y
661
+ $result.cursorMoved = if ($cursorEntry.applied) { 'true' } else { 'false' }
662
+ $result.cursorX = [int]$cursorEntry.x
663
+ $result.cursorY = [int]$cursorEntry.y
664
+ $result.cursorBeforeX = [int]$cursorEntry.beforeX
665
+ $result.cursorBeforeY = [int]$cursorEntry.beforeY
666
+ }
667
+ if ($abortedBeforeAct) {
668
+ $result.refusal = 'takeover_aborted'
669
+ $result.reason = if ($abortedByPause) { 'the owner paused the engine during the arming window; nothing was clicked or typed' } elseif ($abortedDuringSetup) { 'cancelled by the host before the arming window opened; nothing was clicked or typed' } else { 'interrupted during the arming window; nothing was clicked or typed' }
670
+ } elseif ($decision.channel -eq 'message') {
671
+ if ($Action -eq 'type') {
672
+ # The door kind is decided ONCE, in the probe (win.ps1), and consumed here by kind.
673
+ # This path used to re-match class names with its own copy of the pattern -- and that copy
674
+ # carried the same 'Edit' vs 'WindowsForms10.EDIT.*' bug, so a fix in one place would have
675
+ # silently left the other broken. One matcher, one truth.
676
+ $target = $null
677
+ foreach ($d in $probe.doorHandles) {
678
+ if ($d.kind -eq 'text') { $target = [IntPtr]$d.hwnd; break }
679
+ }
680
+ if (-not $target) {
681
+ $result.refusal = 'unreachable'; $result.reason = 'no editable child window for the message tier'
682
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
683
+ return $result
684
+ }
685
+ if ([WpmWin]::IsWindowEnabled($target) -eq $false) { $targetDisabled = $true }
686
+ # THE PRE-READ. Taken BEFORE the write, because the expected post-write value is only computable
687
+ # from the value the control held plus the insertion point the CONTROL reports (its own EM_GETSEL
688
+ # answer) -- not from an assumption that a write appends. Measured: an unfocused WinForms TextBox
689
+ # inserts at 0, so 'abc' + 'XYZ' is 'XYZabc'; the model has to know both numbers or the
690
+ # comparison grades its own guess.
691
+ $preRead = Read-WpmControlText -Hwnd $target
692
+ $w = [WpmWin]::MessageTextAt($target, $Text, [bool]$Replace, $CaretPosition)
693
+ $mode = [string]$w[0]
694
+ $sentChars = [int]$w[1]
695
+ $selStart = [int]$w[2]; $selEnd = [int]$w[3]
696
+ $caretAskedAt = if ($w.Count -gt 4) { [int]$w[4] } else { -1 }
697
+ # Readback runs AFTER the settle window (the proof sampling is the settle), so an app that commits
698
+ # its value asynchronously is not judged against a half-written buffer (plan R2).
699
+ $readbackPlan = @{
700
+ kind = 'message'; hwnd = $target; mode = $mode
701
+ pre = $preRead; selStart = $selStart; selEnd = $selEnd; text = $Text; replace = [bool]$Replace
702
+ }
703
+ $caretNote = "caret=$CaretPosition asked=$(if ($caretAskedAt -ge 0) { $caretAskedAt } else { '(untouched)' }) applied=$selStart,$selEnd"
704
+ $result.detail = "msg=$mode|$sentChars child=$($target.ToInt64()) $caretNote" + $(if (-not $preRead.exposesText) { ' readbackPre=unavailable' } else { '' })
705
+ $result.effect = 'reported-by-send'
706
+ } elseif ($Action -eq 'click') {
707
+ if ($X -lt 0 -or $Y -lt 0) {
708
+ $result.refusal = 'unreachable'; $result.reason = 'click needs screen coordinates'
709
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
710
+ return $result
711
+ }
712
+ $child = Resolve-WpmChildAtPoint $h $X $Y
713
+ if ($child -eq [IntPtr]::Zero) {
714
+ $result.refusal = 'unreachable'
715
+ $result.reason = $(if ($script:WpmPointCovered) {
716
+ "the point is inside a child of the target but another window is on top (blocker class=$($script:WpmPointBlocker)); a message press there is accepted and ignored -- the application never runs the handler. Next step: bring the target to the front, or choose a point that is visible"
717
+ } else { 'no child window of the target sits under that point' })
718
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
719
+ return $result
720
+ }
721
+ $r = [WpmWin]::MessageClick($child, $X, $Y)
722
+ $result.detail = "msg=$r child=$($child.ToInt64())"
723
+ $result.effect = 'reported-by-send'
724
+ }
725
+ } elseif ($decision.channel -eq 'input') {
726
+ # THE MEASURED DOORLESS CASE (a terminal, findings §B): typing into the FOREGROUND window. The
727
+ # foreground assertion is repeated here, at the moment of sending, because the desktop can change
728
+ # during the arming window -- the decision's fact is evidence about then, not about now.
729
+ $fgNow = Test-WpmTargetForeground -Hwnd $Hwnd
730
+ if (-not $fgNow.ok) {
731
+ $result.refusal = 'keyinject_unavailable'
732
+ $result.reason = $script:WpmRefusals.keyinject_unavailable + ' [foreground at send time: ' + $fgNow.foreground + ']'
733
+ } else {
734
+ # The pause switch rides the same abort probe: a long injection must stop when the owner says so.
735
+ $inj = Send-WpmKeyText -Text $Text -ShouldAbort { (Test-WpmTakeoverAbort) -or [WpmCtl]::Paused }
736
+ $result.detail = 'inject=unicode chars=' + $inj.chars + ' events=' + $inj.sent
737
+ $result.keysInjected = [int]$inj.sent
738
+ $result.injectedChars = [int]$inj.chars
739
+ $result.effect = if ($inj.chars -gt 0) { 'reported-by-send' } else { 'unverified' }
740
+ if ($inj.aborted) {
741
+ $result.refusal = 'takeover_aborted'
742
+ $result.reason = $inj.reason
743
+ } elseif (-not $inj.ok) {
744
+ $result.refusal = 'keyinject_unavailable'
745
+ $result.reason = $inj.reason
746
+ }
747
+ }
748
+ } elseif ($Action -eq 'focus') {
749
+ # Focusing a control is a real operation an agent needs (type into a field, then read it).
750
+ # It is also the one action that MUST change keyboard focus, so it is the honest way to
751
+ # exercise the bounded-flash path: an Invoke can complete without activating anything, but
752
+ # SetFocus cannot -- it transfers focus by definition.
753
+ if ($decision.channel -ne 'uia') {
754
+ $result.refusal = 'unreachable'; $result.reason = 'focus requires a UIA element; the message tier cannot set keyboard focus'
755
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
756
+ return $result
757
+ }
758
+ $el = $probe.uiaElement
759
+ if (-not $el) {
760
+ $result.refusal = 'unreachable'; $result.reason = 'no element to focus'
761
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
762
+ return $result
763
+ }
764
+ $el.SetFocus()
765
+ $result.detail = 'uia=SetFocus'
766
+ $result.effect = 'reported-by-pattern'
767
+ } elseif ($decision.channel -eq 'uia') {
768
+ $el = $probe.uiaElement
769
+ if (-not $el) {
770
+ $result.refusal = 'unreachable'; $result.reason = 'pattern was reported but no element could be re-obtained'
771
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
772
+ return $result
773
+ }
774
+ $pats = Get-WpmUiaCached
775
+ $kind = $facts.patternKind
776
+ if ($kind -eq 'invoke') {
777
+ $pat = $el.GetCurrentPattern($pats.invoke)
778
+ $pat.Invoke()
779
+ } elseif ($kind -eq 'value') {
780
+ $pat = $el.GetCurrentPattern($pats.value)
781
+ # THE PRE-READ THROUGH THE SAME PATTERN that writes. The UIA `value` channel is a whole-value
782
+ # replace, so the expected after-value is computable exactly -- and the current value is read
783
+ # from the pattern, not from a window message, because this is the channel the write went through.
784
+ $preVal = ''
785
+ $preOk = $false
786
+ try { $preVal = [string]$pat.Current.Value; $preOk = $true } catch { $preOk = $false }
787
+ $pat.SetValue($(if ($Replace) { $Text } else { [string]$pat.Current.Value + $Text }))
788
+ $readbackPlan = @{
789
+ kind = 'uia-value'; pat = $pat; mode = 'value'
790
+ expected = $(if ($Replace) { $Text } else { $preVal + $Text })
791
+ preOk = $preOk; pre = $preVal; text = $Text; replace = [bool]$Replace
792
+ }
793
+ } elseif ($kind -eq 'toggle') {
794
+ $pat = $el.GetCurrentPattern($pats.toggle); $pat.Toggle()
795
+ } elseif ($kind -eq 'select') {
796
+ $pat = $el.GetCurrentPattern($pats.select); $pat.Select()
797
+ } elseif ($kind -eq 'legacy') {
798
+ $pat = $el.GetCurrentPattern($pats.legacy)
799
+ $preVal = ''; $preOk = $false
800
+ try { $preVal = [string]$pat.Current.Value; $preOk = $true } catch { $preOk = $false }
801
+ $pat.SetValue($Text)
802
+ $readbackPlan = @{
803
+ kind = 'uia-legacy'; pat = $pat; mode = 'legacy'
804
+ expected = $Text; preOk = $preOk; pre = $preVal; text = $Text; replace = $true
805
+ }
806
+ }
807
+ $result.detail = "uia=$kind"
808
+ # A caret request on this channel has no meaning -- `value` replaces the whole string, there is no
809
+ # insertion point to move. Saying so is the difference between honouring a parameter and quietly
810
+ # dropping it (the same discipline as `frame` and, in 0.6.0-B, `captureBackend`: a path that did
811
+ # not do what you asked says so in the result).
812
+ if ($CaretPosition -ne 'idle' -and $readbackPlan) {
813
+ $result.detail += " caretIgnored=$kind-pattern"
814
+ }
815
+ $result.effect = 'reported-by-pattern'
816
+ }
817
+ $focusAfterDoor = Get-WpmFocusEntry
818
+ } catch {
819
+ $result.refusal = 'action_failed'
820
+ $result.reason = 'the channel call threw: ' + $_.Exception.Message
821
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
822
+ } finally {
823
+ # THE BORROWED POINTER IS RETURNED HERE, UNCONDITIONALLY. Success, exception, refusal and
824
+ # interruption all arrive at this block, which is the whole reason the move was placed inside the
825
+ # try above. 'restored' is the READ-BACK, not the intent: a restore the OS refused reports
826
+ # cursorRestored=false and becomes a hard proof failure downstream (spec.md §6, C5).
827
+ if ($takeover) {
828
+ if ($cursorEntry) {
829
+ $cur = Restore-WpmCursorTakeover -Entry $cursorEntry
830
+ $result.cursorRestored = if ($cur.restored) { 'true' } else { 'false' }
831
+ $result.cursorAfterX = [int]$cur.x
832
+ $result.cursorAfterY = [int]$cur.y
833
+ if (-not $cur.restored) { $result.cursorRestoreReason = $cur.reason }
834
+ } else {
835
+ # No click point, so nothing was borrowed: the honest report is restored=true with moved=false.
836
+ $result.cursorRestored = 'true'
837
+ }
838
+ $result.injectedChars = [int][WpmCtl]::InjectedChars
839
+ $result.abortChord = [string][WpmCtl]::AbortChordLabel
840
+ $result.takeoverMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $takeoverStartMs
841
+ if ($TakeoverMaxMs -gt 0 -and $result.takeoverMs -gt $TakeoverMaxMs) {
842
+ $result.takeoverNote = 'the action exceeded takeoverMaxMs=' + $TakeoverMaxMs + '; it was still restored'
843
+ }
844
+ # A LATCH LEFT BEHIND WOULD ABORT THE NEXT CALL. The host clears its own copy on dispose, but the
845
+ # worker pid outlives a single action, so the engine clears it here as well -- after the restore, so
846
+ # an interruption that arrives during cleanup is still visible to this action's own accounting.
847
+ Reset-WpmTakeoverAbort | Out-Null
848
+ Set-WpmHudPhase -Phase 'done' -ElapsedMs ([int]$result.takeoverMs) | Out-Null
849
+ $dwell = if ($result.refusal) { 120 } else { [Math]::Max(0, [Math]::Min(5000, $HudDoneMs)) }
850
+ if ($dwell -gt 0) { Start-Sleep -Milliseconds $dwell }
851
+ [void](Stop-WpmHud)
852
+ }
853
+ }
854
+
855
+ # THE ACTION WINDOW. Sampled DURING the settle sleep the engine already performed, so collecting
856
+ # proof costs no extra delay. This is the window the claim is made about; it is judged against the
857
+ # pre-action control captured above (proof-window decides how, from both). Attribution is arithmetic
858
+ # and lives in lib/proof-window.mjs -- the engine only produces samples.
859
+ $result.proofControl = $controlSamples
860
+ $result.proofSamples = Get-WpmProofWindow -Ms $SettleMs
861
+
862
+ # ---- 0.6.0 READBACK: the fourth `effect`, earned by reading the value back -------------------
863
+ # This runs AFTER the settle window on purpose (plan R2): an application that commits its text
864
+ # asynchronously must not be judged against a half-written buffer. The rule is narrow and it is the
865
+ # whole feature -- `readback-verified` is used ONLY when the value read back equals the value the
866
+ # model predicted from measurements the CONTROL reported. Anything else keeps the effect the write
867
+ # itself earned, and the reason travels in `detail`.
868
+ #
869
+ # A mismatch is NOT a failure. The app may legitimately reformat what it was given (case folding,
870
+ # trimming, a mask, a numeric parse), and `unreachable`/`action_failed` must not be repurposed to
871
+ # mean "the value is not what I expected" -- so the refusal set is unchanged by this block, by design.
872
+ if ($readbackPlan) {
873
+ $expected = $null
874
+ $expectedHow = ''
875
+ if ($readbackPlan.kind -eq 'message') {
876
+ $post = Read-WpmControlText -Hwnd $readbackPlan.hwnd
877
+ $pre = $readbackPlan.pre
878
+ if ($readbackPlan.mode -eq 'settext') {
879
+ $expected = [string]$readbackPlan.text; $expectedHow = 'settext-equals-text'
880
+ } elseif (-not $pre.exposesText -or $pre.truncated) {
881
+ $expected = $null; $expectedHow = $(if (-not $pre.exposesText) { 'pre-read-unavailable' } else { 'pre-read-truncated' })
882
+ } else {
883
+ $b = [string]$pre.text
884
+ $s = [int]$readbackPlan.selStart; $e = [int]$readbackPlan.selEnd
885
+ if ($s -lt 0) { $s = 0 }
886
+ if ($e -lt $s) { $e = $s }
887
+ if ($s -gt $b.Length) { $s = $b.Length }
888
+ if ($e -gt $b.Length) { $e = $b.Length }
889
+ $expected = $b.Substring(0, $s) + [string]$readbackPlan.text + $b.Substring($e)
890
+ $expectedHow = "insert-at-$s-$e"
891
+ }
892
+ $postRef = $post
893
+ } else {
894
+ $postVal = ''; $postOk = $false
895
+ try { $postVal = [string]$readbackPlan.pat.Current.Value; $postOk = $true } catch { $postOk = $false }
896
+ $expected = [string]$readbackPlan.expected; $expectedHow = 'pattern-current-value'
897
+ $postRef = @{ ok = $postOk; exposesText = $postOk; truncated = $false; text = $postVal; chars = $postVal.Length }
898
+ }
899
+
900
+ if (-not $postRef.exposesText) {
901
+ # Not "empty": the read produced nothing usable. Reporting readback=unavailable keeps the two
902
+ # apart, which is the difference between "this field hides its text" and "this field is empty".
903
+ $result.detail += ' readback=unavailable'
904
+ } elseif ($null -eq $expected) {
905
+ $result.detail += " readback=unmodelled($expectedHow)"
906
+ } else {
907
+ $shown = [string]$postRef.text
908
+ if ($shown.Length -gt 120) { $shown = $shown.Substring(0, 119) + [char]0x2026 }
909
+ $result.detail += " readback=$shown readbackLen=$([string]$postRef.text.Length)"
910
+ if ($postRef.text -eq $expected) {
911
+ $result.effect = 'readback-verified'
912
+ } else {
913
+ # The mismatch is carried as data because a caller that only reads `effect` must still be able
914
+ # to tell "nothing reported success" from "it reported success and the value says otherwise".
915
+ $result.detail += ' readbackMismatch=true'
916
+ }
917
+ }
918
+ }
919
+
920
+ # ---- 0.6.0 focus re-check at the moment of sending ------------------------------------------
921
+ # A WARNING, never a refusal. The desktop can move between the probe and the send, and on the
922
+ # bounded-flash tier the move is the channel working as documented. Refusing on a mismatch would
923
+ # kill correct writes to be safe about a fact the readback already judges better -- so the field
924
+ # says what was measured and lets the caller weigh it.
925
+ if ($focusBeforeDoor -and $focusAfterDoor) {
926
+ $moved = ($focusBeforeDoor.fgHwnd -ne $focusAfterDoor.fgHwnd) -or
927
+ ($focusBeforeDoor.focusHwnd -ne $focusAfterDoor.focusHwnd)
928
+ $result.detail += " focusMoved=$($moved.ToString().ToLower())"
929
+ }
930
+
931
+ # ---- 0.6.0 the disabled target, recorded last so it cannot be overridden ---------------------
932
+ # `effect` is pinned to 'unverified' here even if a readback matched: a write into a greyed-out
933
+ # window is not an effect the owner can rely on, and the one claim this field makes is that the
934
+ # channel's own report is not being dressed up as a verified state change.
935
+ if ($targetDisabled) {
936
+ $result.detail += ' disabled=true'
937
+ $result.effect = 'unverified'
938
+ }
939
+
940
+ # Did the action actually take the owner's focus? Measured, not assumed -- the quiet tier is
941
+ # expected to say no and the flash tier yes, and a run where both say the same thing is a broken
942
+ # instrument rather than a good result.
943
+ #
944
+ # WHICH window now holds the foreground matters, and the first version got it wrong: it recorded
945
+ # whatever held the foreground as "the window we raised". When an action causes the TARGET APP to
946
+ # open a dialog, that dialog is what comes forward -- so it looked like our own raised window and
947
+ # was promptly restored away, shutting the dialog's focus the agent had just asked for. Only the
948
+ # target itself counts as ours; anything else is the app's own window or a third party's, and it
949
+ # is classified, never reversed.
950
+ $nowFg = [WpmWin]::Fg()
951
+ $targetStr = $h.ToInt64().ToString()
952
+ $raisedHwnd = ''
953
+ $raisedElsewhere = ''
954
+ if ($nowFg -ne $entry.fgHwnd) {
955
+ $result.focusTaken = 'true'
956
+ if ($nowFg -eq $targetStr) { $raisedHwnd = $nowFg } else { $raisedElsewhere = $nowFg }
957
+ }
958
+ $result.raisedOurs = ($raisedHwnd -ne '').ToString().ToLower()
959
+ if ($raisedElsewhere) { $result.raisedElsewhere = $raisedElsewhere }
960
+
961
+ if ($decision.needsRestore) {
962
+ $res = Restore-WpmFocus -Entry $entry -RaisedHwnd $raisedHwnd -RaisedElsewhere $raisedElsewhere `
963
+ -TargetPid ($probe.pid.ToString())
964
+ $result.restoreOutcome = $res.outcome
965
+ $result.restoreReason = $res.reason
966
+ $result.restoreSetFg = $res.setFg
967
+ $result.restoreJoined = $res.joined
968
+ $result.fgAfterRestore = $res.fgAfter
969
+ # A restore the table authorised but the OS refused is a named failure, not a success with a
970
+ # caveat: the owner is left in a window they did not choose, so the caller must surface it.
971
+ # The span the owner actually pays: from the moment the action was issued to the moment the
972
+ # focus was back. Reported separately from end-to-end latency because latency includes the
973
+ # door probe and the settle wait, and a 'budget' quoted from latency would overstate the
974
+ # disturbance by an order of magnitude.
975
+ # Only meaningful when focus was actually taken: reporting a 'flash span' for an action that
976
+ # never disturbed the owner would put a scary number next to a non-event.
977
+ if ($result.focusTaken -eq 'true') {
978
+ $result.flashMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $tAct
979
+ }
980
+ if ($res.outcome -eq 'restore' -and $res.setFg -ne 'true') {
981
+ $result.refusal = 'restore_failed'
982
+ $result.reason = 'the OS refused to return the foreground; the owner is still in the wrong window'
983
+ }
984
+ }
985
+
986
+ $result.ok = ($result.refusal -eq '')
987
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
988
+ $result.fgBefore = $entry.fgHwnd
989
+ $result.fgNow = [WpmWin]::Fg()
990
+ return $result
991
+ }
992
+
993
+ # ==================================================================================================
994
+ # 0.7.0: the three desktop actions that are NOT door actions.
995
+ # ==================================================================================================
996
+
997
+ function Invoke-WpmDesktopAction {
998
+ <#
999
+ launch / clipboard / window live beside Invoke-WpmAction, not inside it, and that separation is the
1000
+ point: a door action chooses a channel, costs a tier, takes and returns a focus, and is judged by a
1001
+ proof window. A window move or a clipboard write does none of those things, and routing them through
1002
+ the door table would either force them into a refusal code they do not deserve or make the table
1003
+ answer for capabilities it never measured.
1004
+
1005
+ WHAT THEY STILL DO: every one of them is verified by reading the STATE back -- `IsIconic`, the rect,
1006
+ the ex-style, the clipboard's own content -- because the rule this product has been bitten by is that
1007
+ a syscall's return value describes the CALL. So `effect` uses the same four values and the same rule:
1008
+ `readback-verified` only when the read agrees, `unverified` otherwise, and the disagreement or the
1009
+ reason travels in `detail`. No refusal code was added for this batch either: `launch` with the gate
1010
+ off, a window with no hwnd, and a clipboard holding an unexpected format are all answered by the host
1011
+ gate or by the existing `no_hwnd` / `action_failed` vocabulary.
1012
+ #>
1013
+ param(
1014
+ [Parameter(Mandatory)][ValidateSet('launch', 'clipboard', 'window')][string]$Action,
1015
+ [string]$Hwnd = '',
1016
+ [string]$Target = '',
1017
+ [object]$Arguments = $null,
1018
+ [int]$WaitMs = 3000,
1019
+ [string]$Op = '',
1020
+ [string]$Format = 'text',
1021
+ [string]$Text = '',
1022
+ [string]$ShotId = '',
1023
+ [int]$X = 0,
1024
+ [int]$Y = 0,
1025
+ [int]$Width = 0,
1026
+ [int]$Height = 0,
1027
+ [int]$MaxChars = 65536,
1028
+ # ---- 0.7.0 authorization. The host gate runs first and costs zero worker requests; these are the
1029
+ # engine's own second line, checked against the same table in decide.ps1 so the two processes cannot
1030
+ # disagree about what the owner permitted.
1031
+ [string]$Policy = 'balanced',
1032
+ [int]$PolicyIdleMs = 3000,
1033
+ [switch]$ForceUserActive,
1034
+ [bool]$AppLaunchAllowed = $false,
1035
+ [string[]]$AppLaunchAllow = @()
1036
+ )
1037
+ $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1038
+ $result = @{ ok = $false; action = $Action; hwnd = $Hwnd; refusal = ''; reason = ''; detail = ''
1039
+ effect = 'unverified'; latencyMs = 0 }
1040
+
1041
+ if ($Action -eq 'launch') {
1042
+ # The engine re-runs the gate and the whitelist through the SAME table the host used. A permission
1043
+ # that lives in only one of the two processes is a permission that can be reached around by calling
1044
+ # the other, and `launch` is the one action where that distinction has consequences.
1045
+ $launchFacts = New-WpmFacts -Hwnd '' -Action launch -FactsMeasured $true `
1046
+ -Policy $Policy -RequiredTier 'takeover' -PolicyIdleMs $PolicyIdleMs `
1047
+ -ForceUserActive:([bool]$ForceUserActive) -LastInputAgeMs ([WpmWin]::LastInputAgeMs()) `
1048
+ -AppLaunchAllowed:$AppLaunchAllowed -AppLaunchAllow $AppLaunchAllow -LaunchTarget $Target
1049
+ $ld = Get-WpmChannelDecision $launchFacts
1050
+ if ($ld.channel -eq 'refuse') {
1051
+ $result.refusal = [string]$ld.refusal; $result.reason = [string]$ld.reason
1052
+ $result.detail = "launch gate: allowed=$AppLaunchAllowed whitelist=$(@($AppLaunchAllow).Count) name(s)"
1053
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1054
+ return $result
1055
+ }
1056
+ $argv = @()
1057
+ if ($Arguments -is [array]) { $argv = @($Arguments | ForEach-Object { [string]$_ }) }
1058
+ elseif ($Arguments -is [string] -and $Arguments) { $argv = @($Arguments) }
1059
+ $s = Start-WpmApp -Target $Target -Arguments $argv
1060
+ if (-not $s.ok) {
1061
+ $result.refusal = 'action_failed'; $result.reason = [string]$s.reason
1062
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1063
+ return $result
1064
+ }
1065
+ $result.pid = [int]$s.pid
1066
+ $result.processName = [string]$s.name
1067
+ $result.target = [string]$s.target
1068
+ # The window is waited for only when the caller asked to address one. hwnd=0 after a successful
1069
+ # launch is a REPORTED state ('window-not-yet'), never a failure -- see Wait-WpmAppWindow.
1070
+ if ($WaitMs -gt 0) {
1071
+ $w = Wait-WpmAppWindow -ProcessId ([int]$s.pid) -WaitMs $WaitMs
1072
+ $result.hwnd = [string]$w.hwnd
1073
+ $result.waitedMs = [int]$w.waitedMs
1074
+ if ($w.hwnd) {
1075
+ $result.ok = $true
1076
+ $result.effect = 'readback-verified'
1077
+ $result.detail = "launched pid=$($s.pid) hwnd=$($w.hwnd) title=$($w.title)"
1078
+ } elseif ($w.ContainsKey('detail')) {
1079
+ # ContainsKey on purpose: Wait-WpmAppWindow answers THREE different shapes -- window found, no
1080
+ # window yet (carries detail=window-not-yet and a note), and the process is gone (carries a
1081
+ # reason and no detail at all). Reading a key that a branch never set is a StrictMode throw, and a
1082
+ # throw inside the handler for a started-but-windowless process would report `action_failed` on
1083
+ # a program that is running fine -- the exact overstatement this engine exists to avoid.
1084
+ $result.ok = $true
1085
+ $result.detail = "launched pid=$($s.pid) " + [string]$w.detail + " waitedMs=$($w.waitedMs)"
1086
+ if ($w.ContainsKey('note')) { $result.note = [string]$w.note }
1087
+ } else {
1088
+ $result.refusal = 'action_failed'
1089
+ $result.reason = [string]$w.reason
1090
+ $result.detail = "launched pid=$($s.pid) but no window could be observed"
1091
+ }
1092
+ } else {
1093
+ $result.ok = $true
1094
+ $result.detail = "launched pid=$($s.pid) window=not-asked (waitMs=0)"
1095
+ }
1096
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1097
+ return $result
1098
+ }
1099
+
1100
+ if ($Action -eq 'clipboard') {
1101
+ if ($Op -eq 'read') {
1102
+ $c = Get-WpmClipboard -Format $Format -MaxChars $MaxChars
1103
+ if (-not $c.ok) {
1104
+ $result.refusal = 'action_failed'; $result.reason = [string]$c.reason
1105
+ # ContainsKey before reading: these failure paths return DIFFERENT key sets by design (a format
1106
+ # miss carries the names it found, an exception does not), and under Set-StrictMode 2.0 reading a
1107
+ # key that is simply absent throws -- turning a documented refusal into a crash inside the
1108
+ # refusal handler, which is the failure mode the first run of this branch produced.
1109
+ if ($c.ContainsKey('formats') -and $c.formats) { $result.detail = 'formats=' + ($c.formats -join ',') }
1110
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1111
+ return $result
1112
+ }
1113
+ $result.ok = $true
1114
+ $result.clipFormat = [string]$c.format
1115
+ if ($c.format -eq 'text') {
1116
+ # The CONTENT is deliberately not put into `detail`: the result text is written into a model's
1117
+ # context and an audit line, and the clipboard is exactly the place where that can carry a token
1118
+ # (R8). Length and the truncation flag are enough to decide what to do next.
1119
+ $result.chars = [int]$c.chars
1120
+ $result.truncated = [bool]$c.truncated
1121
+ $result.effect = 'readback-verified'
1122
+ $result.detail = "clipboard=read format=text chars=$($c.chars)" + $(if ($c.truncated) { " truncated=$($MaxChars)" } else { '' })
1123
+ } else {
1124
+ $result.file = [string]$c.file
1125
+ $result.clipId = [string]$c.clipId
1126
+ $result.imageSize = "$($c.width)x$($c.height)"
1127
+ $result.effect = 'readback-verified'
1128
+ $result.detail = "clipboard=read format=image file=$($c.file) size=$($c.width)x$($c.height)"
1129
+ }
1130
+ } elseif ($Op -eq 'write') {
1131
+ $c = Set-WpmClipboard -Format $Format -Text $Text -ShotId $ShotId
1132
+ if (-not $c.ok) {
1133
+ $result.refusal = $(if ($c.ContainsKey('stale') -and $c.stale) { 'stale_ref' } else { 'action_failed' })
1134
+ $result.reason = [string]$c.reason
1135
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1136
+ return $result
1137
+ }
1138
+ $result.ok = $true
1139
+ $result.clipFormat = [string]$c.format
1140
+ if ($c.format -eq 'text') {
1141
+ $result.chars = [int]$c.chars
1142
+ # The read-back is a LENGTH comparison, and the value itself is not echoed: same reason as above.
1143
+ $result.readbackChars = [int]$c.readbackChars
1144
+ $result.effect = $(if ($c.readbackMatches) { 'readback-verified' } else { 'unverified' })
1145
+ $result.detail = "clipboard=write format=text chars=$($c.chars) readbackChars=$($c.readbackChars)" +
1146
+ $(if ($c.readbackMatches) { '' } else { ' readbackMismatch=true' })
1147
+ } else {
1148
+ $result.readbackSize = "$($c.readbackWidth)x$($c.readbackHeight)"
1149
+ # The image read-back is a SIZE comparison against the shot that was pushed in: the pixels
1150
+ # themselves cannot be hashed (two reads of a live screen differ, findings 5.1) and the shot's own
1151
+ # dimensions are the fact the caller can act on.
1152
+ $dimsMatch = ($c.readbackWidth -eq $c.width) -and ($c.readbackHeight -eq $c.height)
1153
+ $result.effect = $(if ($dimsMatch) { 'readback-verified' } else { 'unverified' })
1154
+ $result.detail = "clipboard=write format=image shotId=$($c.shotId) asked=$($c.width)x$($c.height) readback=$($c.readbackWidth)x$($c.readbackHeight)" +
1155
+ $(if ($dimsMatch) { '' } else { ' readbackMismatch=true' })
1156
+ }
1157
+ } else {
1158
+ $result.refusal = 'action_failed'; $result.reason = "clipboard needs op='read' or op='write'"
1159
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1160
+ return $result
1161
+ }
1162
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1163
+ return $result
1164
+ }
1165
+
1166
+ # ---- window ------------------------------------------------------------------
1167
+ if (-not $Hwnd) {
1168
+ $result.refusal = 'no_hwnd'; $result.reason = 'window acts on one named window; there is no "all windows" op'
1169
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1170
+ return $result
1171
+ }
1172
+ $fgBeforeOp = [WpmWin]::Fg()
1173
+ $w = Invoke-WpmWindowOp -Hwnd ([IntPtr][int64]$Hwnd) -Op $Op -X $X -Y $Y -Width $Width -Height $Height
1174
+ $fgAfterOp = [WpmWin]::Fg()
1175
+ # Only the 'hwnd is not a live window' branch carries a refusal code; the others answer ok/false with a
1176
+ # reason. Under StrictMode an unguarded read of a key that branch never sets would throw inside the
1177
+ # handler, so presence is tested rather than assumed.
1178
+ if ($w.ContainsKey('refusal') -and $w.refusal) { $result.refusal = [string]$w.refusal }
1179
+ $result.ok = [bool]$w.ok
1180
+ $result.reason = [string]$w.reason
1181
+ $bits = @("window=$Op")
1182
+ foreach ($k in @('iconic', 'called', 'asked', 'size', 'rect', 'before', 'topmost', 'exStyle', 'activated')) {
1183
+ if ($w.ContainsKey($k)) {
1184
+ # Lower-cased deliberately: every other boolean this engine puts into `detail` reads
1185
+ # disabled=true / focusMoved=false / verified=true, and a PowerShell `True` in the same sentence is
1186
+ # how a field ends up being parsed two ways by two consumers.
1187
+ $val = $w[$k]
1188
+ if ($val -is [bool]) { $val = $val.ToString().ToLower() }
1189
+ $bits += "$k=$val"
1190
+ }
1191
+ }
1192
+ $bits += $(if ($w.ok) { 'verified=true' } else { 'verified=false' })
1193
+ # DID THE OWNER LOSE THE FOREGROUND TO THIS CALL -- measured on both sides of it, because
1194
+ # `restore` activates by definition and a window op that quietly took the focus while reporting only a
1195
+ # size change is the failure shape this product keeps meeting. Saying it is not the same as refusing
1196
+ # it: the caller asked for the window to come back, and coming back is what restoring means.
1197
+ $fgTaken = ($fgBeforeOp -ne $fgAfterOp) -and ($fgAfterOp -eq $Hwnd)
1198
+ $bits += "foregroundTaken=$($fgTaken.ToString().ToLower())"
1199
+ if ($fgTaken) {
1200
+ $bits += "foregroundBefore=$fgBeforeOp foregroundAfter=$fgAfterOp"
1201
+ }
1202
+ $result.detail = ($bits -join ' ')
1203
+ $result.foregroundTaken = $fgTaken
1204
+ # The window's own answer is the read-back, so the effect follows it directly.
1205
+ $result.effect = $(if ($w.ok) { 'readback-verified' } else { 'unverified' })
1206
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1207
+ return $result
1208
+ }