dsh-windows-parallel-mcp 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -48,6 +48,32 @@ $script:WpmRefusals = @{
48
48
  needs_facts = 'the caller supplied no measured facts for this target; refusing instead of assuming quiet'
49
49
  takeover_unavailable = 'takeover was requested but cannot run safely right now: the HUD is not up, or the takeover gate is off. Next step: enable takeoverAllowed in settings (the HUD is a hard precondition, not a decoration) or call without takeover:true'
50
50
  keyinject_unavailable= 'keyboard injection was requested but cannot run: this target is not the foreground window and could not be raised (or it is elevated). Next step: bring the target to the front yourself, or call without keyInput:''inject'''
51
+ # ---- 0.7.0 authorization model. Three codes, each naming the NEXT STEP rather than describing the
52
+ # symptom, because all three are settings decisions and a caller that cannot tell which setting to
53
+ # raise will retry the same call forever.
54
+ policy_denied = 'the action''s declared tier is above what the policy setting allows. Next step: raise policy in settings (readonly < quiet < balanced < full) -- NOT retrying this call'
55
+ user_active = 'the owner was at the keyboard when this was asked for (last physical input younger than policyIdleMs) and the action needs the takeover tier. This product does not open a dialog at someone who is typing -- a popup is a second disturbance dressed as consent. Next step: wait for idle, or pass forceUserActive:true explicitly (it is recorded in the audit log as forced)'
56
+ app_launch_denied = 'launch is not authorised: appLaunchAllowed is off, or the program is not on the appLaunchAllow whitelist (an empty whitelist means nothing may launch). Next step: the OWNER adds the exact name to the whitelist; a wildcard does not exist and this refusal is not a transient failure to retry through'
57
+ }
58
+
59
+ # THE LADDER, mirrored from lib/policy.js. Two copies of an ordering is normally the bug pattern this
60
+ # repo refuses, and it is allowed here for exactly one reason: the engine and the host each need the
61
+ # comparison in their own process, and scripts/check-policy-table.mjs asserts the two copies agree
62
+ # (rung set, order, and every action's declared tier in tools.json). A drift between them is red at build
63
+ # time instead of being a permission the owner believes they revoked.
64
+ $script:WpmTierOrder = @('readonly', 'quiet', 'flash', 'takeover')
65
+ $script:WpmPolicyCeiling = @{
66
+ readonly = 'readonly'; quiet = 'quiet'; balanced = 'flash'; full = 'takeover'
67
+ }
68
+
69
+ function Test-WpmTierAllowed {
70
+ # Pure, and it fails CLOSED in both directions: an unknown policy or an unknown rung answers false.
71
+ # "Unparseable setting" and "everything allowed" must never read the same way.
72
+ param([string]$Policy, [string]$Required)
73
+ if (-not $script:WpmPolicyCeiling.ContainsKey($Policy)) { return $false }
74
+ $need = [Array]::IndexOf($script:WpmTierOrder, $Required)
75
+ if ($need -lt 0) { return $false }
76
+ return $need -le [Array]::IndexOf($script:WpmTierOrder, $script:WpmPolicyCeiling[$Policy])
51
77
  }
52
78
 
53
79
  function New-WpmFacts {
@@ -69,7 +95,17 @@ function New-WpmFacts {
69
95
  [bool]$KeyInjectRequested = $false, # caller asked for keyboard injection (keyInput:'inject')
70
96
  [bool]$KeyInjectAllowed = $false, # the host gate (keyInjectAllowed) let the request through
71
97
  [bool]$HudReady = $false, # hud.ps1 says a HUD window is up RIGHT NOW
72
- [bool]$ForegroundIsTarget = $false # GetForegroundWindow() (or its root) IS this target
98
+ [bool]$ForegroundIsTarget = $false, # GetForegroundWindow() (or its root) IS this target
99
+ # ---- 0.7.0 authorization facts, supplied by the caller because decide.ps1 does no IO: it cannot
100
+ # read settings, and a table that read its own permissions could not be unit-tested.
101
+ [string]$Policy = 'balanced', # the ceiling the owner set (readonly|quiet|balanced|full)
102
+ [string]$RequiredTier = 'quiet', # what THIS action needs at minimum (tools.json#requiresTier)
103
+ [long]$LastInputAgeMs = -1, # -1 = UNKNOWN; unknown refuses, it does not mean "idle"
104
+ [int]$PolicyIdleMs = 3000,
105
+ [bool]$ForceUserActive = $false, # the caller's explicit override, recorded in the audit
106
+ [bool]$AppLaunchAllowed = $false,
107
+ [string[]]$AppLaunchAllow = @(),
108
+ [string]$LaunchTarget = ''
73
109
  )
74
110
  return @{
75
111
  hwnd = $Hwnd; paused = $Paused; elevatedTarget = $ElevatedTarget; family = $Family
@@ -78,6 +114,9 @@ function New-WpmFacts {
78
114
  uiaTreeEmpty = $UiaTreeEmpty; uiaProbeFailed = $UiaProbeFailed
79
115
  takeoverRequested = $TakeoverRequested; keyInjectRequested = $KeyInjectRequested
80
116
  keyInjectAllowed = $KeyInjectAllowed; hudReady = $HudReady; foregroundIsTarget = $ForegroundIsTarget
117
+ policy = $Policy; requiredTier = $RequiredTier
118
+ lastInputAgeMs = $LastInputAgeMs; policyIdleMs = $PolicyIdleMs; forceUserActive = $ForceUserActive
119
+ appLaunchAllowed = $AppLaunchAllowed; appLaunchAllow = $AppLaunchAllow; launchTarget = $LaunchTarget
81
120
  }
82
121
  }
83
122
 
@@ -102,15 +141,33 @@ function Get-WpmChannelDecision {
102
141
  return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
103
142
  refusal = 'paused'; reason = $script:WpmRefusals.paused }
104
143
  }
105
- if (-not $Facts.hwnd) {
144
+ # ---- 0.7.0 launch is not a windowed action, so the target checks do not apply to it ----------
145
+ # `no_hwnd` and `elevated_target` are statements ABOUT A TARGET WINDOW. `launch` has no target window at
146
+ # the moment it is decided -- that is precisely the point of the action -- and letting a hwnd check run
147
+ # first would turn every launch refusal into a wrong one (`no_hwnd` tells the caller to go find a
148
+ # handle, which is not what an unauthorised program name means). Guarded by the action rather than by
149
+ # handing the table a fake hwnd, because a fabricated fact in a decision table is how tables lie.
150
+ $isWindowedAction = $Facts.action -ne 'launch'
151
+ if ($isWindowedAction -and (-not $Facts.hwnd)) {
106
152
  return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
107
153
  refusal = 'no_hwnd'; reason = $script:WpmRefusals.no_hwnd }
108
154
  }
109
- if ($Facts.elevatedTarget) {
155
+ if ($isWindowedAction -and $Facts.elevatedTarget) {
110
156
  return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
111
157
  refusal = 'elevated_target'; reason = $script:WpmRefusals.elevated_target }
112
158
  }
113
159
 
160
+ # ---- 0.7.0-A the policy ceiling, BEFORE any capability is consulted --------------------------
161
+ # Why here and not at the takeover branch: `policy` answers "may this rung be used at all", and a
162
+ # capability check that runs first can produce a working channel for an action the owner excluded --
163
+ # the same ordering mistake the pause check documents above. The refusal names the setting to raise,
164
+ # because the correct response to this code is a settings change, never a retry.
165
+ if (-not (Test-WpmTierAllowed $Facts.policy $Facts.requiredTier)) {
166
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
167
+ refusal = 'policy_denied'
168
+ reason = $script:WpmRefusals.policy_denied + " [action needs $($Facts.requiredTier); policy '$($Facts.policy)' allows at most $($script:WpmPolicyCeiling[$Facts.policy])]" }
169
+ }
170
+
114
171
  # ---- R3 preconditions. These are refusals about the REQUEST, not about the target, and they come
115
172
  # before the door table because a takeover that cannot show its HUD must not reach any primitive.
116
173
  if ($Facts.takeoverRequested -and -not $Facts.hudReady) {
@@ -128,6 +185,66 @@ function Get-WpmChannelDecision {
128
185
  refusal = 'keyinject_unavailable'; reason = $script:WpmRefusals.keyinject_unavailable }
129
186
  }
130
187
 
188
+ # ---- 0.7.0 the launch gate and its whitelist, double-checked here -----------------------------
189
+ # The host applies this BEFORE any worker request; this is the second line, because a permission that
190
+ # exists only in one process is a permission that can be reached around by calling the other one (the
191
+ # same argument that puts the HUD re-check in engine.ps1 rather than trusting the gate). ORDER MATTERS:
192
+ # this runs after the per-tier preconditions and BEFORE the idle check, which is the sequence the plan
193
+ # specifies -- an unauthorised program must be reported as unauthorised, not as "the owner is busy",
194
+ # because the two refusals tell the caller to change two different things.
195
+ if ($Facts.action -eq 'launch') {
196
+ if (-not $Facts.appLaunchAllowed) {
197
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
198
+ refusal = 'app_launch_denied'; reason = $script:WpmRefusals.app_launch_denied + ' [appLaunchAllowed is off]' }
199
+ }
200
+ $t = if ($Facts.launchTarget) { $Facts.launchTarget.ToLower() } else { '' }
201
+ $hit = $false
202
+ foreach ($w in @($Facts.appLaunchAllow)) {
203
+ # EXACT match, case-folded. No wildcard, no prefix, no substring: `notepad` must not authorise
204
+ # `notepad-helper.exe`, and a prefix rule is the shape of a whitelist that expands by accident.
205
+ if ($w -and ([string]$w).Trim().ToLower() -ceq $t) { $hit = $true; break }
206
+ }
207
+ if (-not $hit) {
208
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
209
+ refusal = 'app_launch_denied'
210
+ reason = $script:WpmRefusals.app_launch_denied + " [no exact entry for '$t'; whitelist holds $(@($Facts.appLaunchAllow).Count) name(s)]" }
211
+ }
212
+ # Fall through to the idle check below: an authorised name is still not permission to start a program
213
+ # while someone is typing at this keyboard.
214
+ }
215
+
216
+ # ---- 0.7.0-B idle sensing: the owner is at the keyboard, so do not interrupt them -------------
217
+ # Only a takeover-tier action is refused here. The quiet and flash tiers do not touch the owner's
218
+ # cursor or hold their focus, so "you are busy" does not apply to them -- refusing those would refuse
219
+ # the reason this product exists. `launch` reaches here with requiredTier 'takeover', so starting a
220
+ # program while the owner is typing is refused too: that is the plan's order, and it is the correct
221
+ # one, because a program started at the wrong moment is the least interruptible action in this product.
222
+ #
223
+ # AN UNKNOWN AGE ALLOWS, and that is a decision rather than an oversight. `LastInputAgeMs` answers -1
224
+ # when GetLastInputInfo fails; refusing on -1 would block every takeover on a machine where that one
225
+ # API does not answer, and the owner who opted into takeoverAllowed has already accepted the tier. This
226
+ # is the OPPOSITE of how the proof path treats -1 (there, unknown must never be read as "the desktop
227
+ # was still", because that would launder a disturbance into innocence) -- the two directions differ
228
+ # because the costs differ: here unknown costs an agent a convenience, there it costs the owner the
229
+ # truth. Both choices are stated where the comparison is made rather than inherited from a convention.
230
+ #
231
+ # Written as one-line conditions: a multi-line `if (A -and -not B` newline `-and C)` expression reads
232
+ # fine to a human and fails the PowerShell parser at the `-and` that opens the continuation line -- a
233
+ # runtime-only parse failure in a dot-sourced file, which surfaces as `action_failed` from the worker.
234
+ $needsTakeover = ($Facts.requiredTier -eq 'takeover')
235
+ $ageKnown = ([long]$Facts.lastInputAgeMs -ge 0)
236
+ $ownerPresent = ($ageKnown -and ([long]$Facts.lastInputAgeMs -lt [int]$Facts.policyIdleMs))
237
+ if ($needsTakeover -and $ownerPresent -and (-not $Facts.forceUserActive)) {
238
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
239
+ refusal = 'user_active'
240
+ reason = $script:WpmRefusals.user_active + " [last physical input $($Facts.lastInputAgeMs)ms ago; policyIdleMs=$($Facts.policyIdleMs)]" }
241
+ }
242
+
243
+ if ($Facts.action -eq 'launch') {
244
+ return @{ channel = 'launch'; tier = 'takeover'; needsRestore = $false; refusal = ''
245
+ reason = 'launch is authorised by both switches and the owner is not at the keyboard' }
246
+ }
247
+
131
248
  $tier = if ($Facts.takeoverRequested) { 'takeover' } else { 'quiet' }
132
249
 
133
250
  # TIER 1: message door. Measured free -- 0/6 raises, effect verified app-side in 6/6, cursor 0 px.
@@ -186,7 +186,16 @@ function Invoke-WpmAction {
186
186
  # selection at 0,0 and the character lands at the FRONT (findings 8.2). The UIA `value` channel
187
187
  # replaces the whole value and has no caret to place, so it reports caretIgnored rather than
188
188
  # pretending the request was honoured.
189
- [ValidateSet('idle', 'start', 'end')][string]$CaretPosition = 'idle'
189
+ [ValidateSet('idle', 'start', 'end')][string]$CaretPosition = 'idle',
190
+ # ---- 0.7.0 authorization, measured here because only this process can see the desktop -------
191
+ # `Policy` and `RequiredTier` come from the host (settings + tools.json). The IDLE CHECK cannot come
192
+ # from the host: last-input age is a GetLastInputInfo reading, and a host that wanted it before the
193
+ # worker call would have to make a worker call. So the ceiling is enforced twice (host pre-worker,
194
+ # engine here) and idle is enforced once, at the only place the number exists.
195
+ [string]$Policy = 'balanced',
196
+ [string]$RequiredTier = 'quiet',
197
+ [int]$PolicyIdleMs = 3000,
198
+ [switch]$ForceUserActive
190
199
  )
191
200
  $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
192
201
  $h = [IntPtr][int64]$Hwnd
@@ -454,11 +463,32 @@ function Invoke-WpmAction {
454
463
  $facts.keyInjectAllowed = [bool]$KeyInject # the host gate already stripped the field when off
455
464
  $facts.hudReady = $false
456
465
  $facts.foregroundIsTarget = $false
466
+ # 0.7.0: the rung this call actually needs. An explicit takeover request outranks the action's declared
467
+ # minimum because moving the real cursor IS the higher permission; that escalation has to be visible to
468
+ # the policy and idle checks or `policy:'quiet'` would be bypassed by a single flag.
469
+ $facts.policy = $Policy
470
+ $facts.requiredTier = $(if ($Takeover -or $KeyInject) { 'takeover' } else { $RequiredTier })
471
+ $facts.forceUserActive = [bool]$ForceUserActive
472
+ $facts.policyIdleMs = $PolicyIdleMs
473
+ # Measured NOW, not carried from the earlier probe: an age read before the HUD came up would describe a
474
+ # desktop that no longer exists, and the whole point of this fact is "was the owner busy a moment ago".
475
+ $facts.lastInputAgeMs = [WpmWin]::LastInputAgeMs()
457
476
  $preFacts = $facts.Clone()
458
477
  $preFacts.takeoverRequested = $false
459
478
  $preFacts.keyInjectRequested = $false
479
+ # THE ESCALATION GOES BACK OUT TOO. `requiredTier` was raised to 'takeover' a few lines above because
480
+ # this call asks for the takeover tier; the pre-pass exists precisely to ask "what does the ACTION
481
+ # itself need", so leaving the escalated rung in place made a `keyInput:'inject'`-only call answer
482
+ # `user_active` (an idle refusal) instead of the `keyinject_unavailable` the arm asserts. A clone that
483
+ # clears the request flags must clear what those flags implied, or the pre-pass measures a different
484
+ # call than the one it claims to be checking.
485
+ $preFacts.requiredTier = $RequiredTier
460
486
  $pre = Get-WpmChannelDecision $preFacts
461
- if ($pre.channel -eq 'refuse' -and (@('paused', 'no_hwnd', 'elevated_target') -contains $pre.refusal)) {
487
+ # THE CHEAP DISQUALIFIERS RUN BEFORE ANY WINDOW IS CREATED. 0.7.0 adds policy_denied and user_active to
488
+ # this list rather than letting them be discovered later: a takeover request that the owner's settings
489
+ # exclude must not flash a HUD at them on its way to saying no -- the HUD is itself the disturbance the
490
+ # refusal exists to prevent.
491
+ if ($pre.channel -eq 'refuse' -and (@('paused', 'no_hwnd', 'elevated_target', 'policy_denied', 'user_active') -contains $pre.refusal)) {
462
492
  $result.refusal = $pre.refusal; $result.reason = $pre.reason
463
493
  $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
464
494
  return $result
@@ -937,3 +967,220 @@ function Invoke-WpmAction {
937
967
  $result.fgNow = [WpmWin]::Fg()
938
968
  return $result
939
969
  }
970
+
971
+ # ==================================================================================================
972
+ # 0.7.0: the three desktop actions that are NOT door actions.
973
+ # ==================================================================================================
974
+
975
+ function Invoke-WpmDesktopAction {
976
+ <#
977
+ launch / clipboard / window live beside Invoke-WpmAction, not inside it, and that separation is the
978
+ point: a door action chooses a channel, costs a tier, takes and returns a focus, and is judged by a
979
+ proof window. A window move or a clipboard write does none of those things, and routing them through
980
+ the door table would either force them into a refusal code they do not deserve or make the table
981
+ answer for capabilities it never measured.
982
+
983
+ WHAT THEY STILL DO: every one of them is verified by reading the STATE back -- `IsIconic`, the rect,
984
+ the ex-style, the clipboard's own content -- because the rule this product has been bitten by is that
985
+ a syscall's return value describes the CALL. So `effect` uses the same four values and the same rule:
986
+ `readback-verified` only when the read agrees, `unverified` otherwise, and the disagreement or the
987
+ reason travels in `detail`. No refusal code was added for this batch either: `launch` with the gate
988
+ off, a window with no hwnd, and a clipboard holding an unexpected format are all answered by the host
989
+ gate or by the existing `no_hwnd` / `action_failed` vocabulary.
990
+ #>
991
+ param(
992
+ [Parameter(Mandatory)][ValidateSet('launch', 'clipboard', 'window')][string]$Action,
993
+ [string]$Hwnd = '',
994
+ [string]$Target = '',
995
+ [object]$Arguments = $null,
996
+ [int]$WaitMs = 3000,
997
+ [string]$Op = '',
998
+ [string]$Format = 'text',
999
+ [string]$Text = '',
1000
+ [string]$ShotId = '',
1001
+ [int]$X = 0,
1002
+ [int]$Y = 0,
1003
+ [int]$Width = 0,
1004
+ [int]$Height = 0,
1005
+ [int]$MaxChars = 65536,
1006
+ # ---- 0.7.0 authorization. The host gate runs first and costs zero worker requests; these are the
1007
+ # engine's own second line, checked against the same table in decide.ps1 so the two processes cannot
1008
+ # disagree about what the owner permitted.
1009
+ [string]$Policy = 'balanced',
1010
+ [int]$PolicyIdleMs = 3000,
1011
+ [switch]$ForceUserActive,
1012
+ [bool]$AppLaunchAllowed = $false,
1013
+ [string[]]$AppLaunchAllow = @()
1014
+ )
1015
+ $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1016
+ $result = @{ ok = $false; action = $Action; hwnd = $Hwnd; refusal = ''; reason = ''; detail = ''
1017
+ effect = 'unverified'; latencyMs = 0 }
1018
+
1019
+ if ($Action -eq 'launch') {
1020
+ # The engine re-runs the gate and the whitelist through the SAME table the host used. A permission
1021
+ # that lives in only one of the two processes is a permission that can be reached around by calling
1022
+ # the other, and `launch` is the one action where that distinction has consequences.
1023
+ $launchFacts = New-WpmFacts -Hwnd '' -Action launch -FactsMeasured $true `
1024
+ -Policy $Policy -RequiredTier 'takeover' -PolicyIdleMs $PolicyIdleMs `
1025
+ -ForceUserActive:([bool]$ForceUserActive) -LastInputAgeMs ([WpmWin]::LastInputAgeMs()) `
1026
+ -AppLaunchAllowed:$AppLaunchAllowed -AppLaunchAllow $AppLaunchAllow -LaunchTarget $Target
1027
+ $ld = Get-WpmChannelDecision $launchFacts
1028
+ if ($ld.channel -eq 'refuse') {
1029
+ $result.refusal = [string]$ld.refusal; $result.reason = [string]$ld.reason
1030
+ $result.detail = "launch gate: allowed=$AppLaunchAllowed whitelist=$(@($AppLaunchAllow).Count) name(s)"
1031
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1032
+ return $result
1033
+ }
1034
+ $argv = @()
1035
+ if ($Arguments -is [array]) { $argv = @($Arguments | ForEach-Object { [string]$_ }) }
1036
+ elseif ($Arguments -is [string] -and $Arguments) { $argv = @($Arguments) }
1037
+ $s = Start-WpmApp -Target $Target -Arguments $argv
1038
+ if (-not $s.ok) {
1039
+ $result.refusal = 'action_failed'; $result.reason = [string]$s.reason
1040
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1041
+ return $result
1042
+ }
1043
+ $result.pid = [int]$s.pid
1044
+ $result.processName = [string]$s.name
1045
+ $result.target = [string]$s.target
1046
+ # The window is waited for only when the caller asked to address one. hwnd=0 after a successful
1047
+ # launch is a REPORTED state ('window-not-yet'), never a failure -- see Wait-WpmAppWindow.
1048
+ if ($WaitMs -gt 0) {
1049
+ $w = Wait-WpmAppWindow -ProcessId ([int]$s.pid) -WaitMs $WaitMs
1050
+ $result.hwnd = [string]$w.hwnd
1051
+ $result.waitedMs = [int]$w.waitedMs
1052
+ if ($w.hwnd) {
1053
+ $result.ok = $true
1054
+ $result.effect = 'readback-verified'
1055
+ $result.detail = "launched pid=$($s.pid) hwnd=$($w.hwnd) title=$($w.title)"
1056
+ } elseif ($w.ContainsKey('detail')) {
1057
+ # ContainsKey on purpose: Wait-WpmAppWindow answers THREE different shapes -- window found, no
1058
+ # window yet (carries detail=window-not-yet and a note), and the process is gone (carries a
1059
+ # reason and no detail at all). Reading a key that a branch never set is a StrictMode throw, and a
1060
+ # throw inside the handler for a started-but-windowless process would report `action_failed` on
1061
+ # a program that is running fine -- the exact overstatement this engine exists to avoid.
1062
+ $result.ok = $true
1063
+ $result.detail = "launched pid=$($s.pid) " + [string]$w.detail + " waitedMs=$($w.waitedMs)"
1064
+ if ($w.ContainsKey('note')) { $result.note = [string]$w.note }
1065
+ } else {
1066
+ $result.refusal = 'action_failed'
1067
+ $result.reason = [string]$w.reason
1068
+ $result.detail = "launched pid=$($s.pid) but no window could be observed"
1069
+ }
1070
+ } else {
1071
+ $result.ok = $true
1072
+ $result.detail = "launched pid=$($s.pid) window=not-asked (waitMs=0)"
1073
+ }
1074
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1075
+ return $result
1076
+ }
1077
+
1078
+ if ($Action -eq 'clipboard') {
1079
+ if ($Op -eq 'read') {
1080
+ $c = Get-WpmClipboard -Format $Format -MaxChars $MaxChars
1081
+ if (-not $c.ok) {
1082
+ $result.refusal = 'action_failed'; $result.reason = [string]$c.reason
1083
+ # ContainsKey before reading: these failure paths return DIFFERENT key sets by design (a format
1084
+ # miss carries the names it found, an exception does not), and under Set-StrictMode 2.0 reading a
1085
+ # key that is simply absent throws -- turning a documented refusal into a crash inside the
1086
+ # refusal handler, which is the failure mode the first run of this branch produced.
1087
+ if ($c.ContainsKey('formats') -and $c.formats) { $result.detail = 'formats=' + ($c.formats -join ',') }
1088
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1089
+ return $result
1090
+ }
1091
+ $result.ok = $true
1092
+ $result.clipFormat = [string]$c.format
1093
+ if ($c.format -eq 'text') {
1094
+ # The CONTENT is deliberately not put into `detail`: the result text is written into a model's
1095
+ # context and an audit line, and the clipboard is exactly the place where that can carry a token
1096
+ # (R8). Length and the truncation flag are enough to decide what to do next.
1097
+ $result.chars = [int]$c.chars
1098
+ $result.truncated = [bool]$c.truncated
1099
+ $result.effect = 'readback-verified'
1100
+ $result.detail = "clipboard=read format=text chars=$($c.chars)" + $(if ($c.truncated) { " truncated=$($MaxChars)" } else { '' })
1101
+ } else {
1102
+ $result.file = [string]$c.file
1103
+ $result.clipId = [string]$c.clipId
1104
+ $result.imageSize = "$($c.width)x$($c.height)"
1105
+ $result.effect = 'readback-verified'
1106
+ $result.detail = "clipboard=read format=image file=$($c.file) size=$($c.width)x$($c.height)"
1107
+ }
1108
+ } elseif ($Op -eq 'write') {
1109
+ $c = Set-WpmClipboard -Format $Format -Text $Text -ShotId $ShotId
1110
+ if (-not $c.ok) {
1111
+ $result.refusal = $(if ($c.ContainsKey('stale') -and $c.stale) { 'stale_ref' } else { 'action_failed' })
1112
+ $result.reason = [string]$c.reason
1113
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1114
+ return $result
1115
+ }
1116
+ $result.ok = $true
1117
+ $result.clipFormat = [string]$c.format
1118
+ if ($c.format -eq 'text') {
1119
+ $result.chars = [int]$c.chars
1120
+ # The read-back is a LENGTH comparison, and the value itself is not echoed: same reason as above.
1121
+ $result.readbackChars = [int]$c.readbackChars
1122
+ $result.effect = $(if ($c.readbackMatches) { 'readback-verified' } else { 'unverified' })
1123
+ $result.detail = "clipboard=write format=text chars=$($c.chars) readbackChars=$($c.readbackChars)" +
1124
+ $(if ($c.readbackMatches) { '' } else { ' readbackMismatch=true' })
1125
+ } else {
1126
+ $result.readbackSize = "$($c.readbackWidth)x$($c.readbackHeight)"
1127
+ # The image read-back is a SIZE comparison against the shot that was pushed in: the pixels
1128
+ # themselves cannot be hashed (two reads of a live screen differ, findings 5.1) and the shot's own
1129
+ # dimensions are the fact the caller can act on.
1130
+ $dimsMatch = ($c.readbackWidth -eq $c.width) -and ($c.readbackHeight -eq $c.height)
1131
+ $result.effect = $(if ($dimsMatch) { 'readback-verified' } else { 'unverified' })
1132
+ $result.detail = "clipboard=write format=image shotId=$($c.shotId) asked=$($c.width)x$($c.height) readback=$($c.readbackWidth)x$($c.readbackHeight)" +
1133
+ $(if ($dimsMatch) { '' } else { ' readbackMismatch=true' })
1134
+ }
1135
+ } else {
1136
+ $result.refusal = 'action_failed'; $result.reason = "clipboard needs op='read' or op='write'"
1137
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1138
+ return $result
1139
+ }
1140
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1141
+ return $result
1142
+ }
1143
+
1144
+ # ---- window ------------------------------------------------------------------
1145
+ if (-not $Hwnd) {
1146
+ $result.refusal = 'no_hwnd'; $result.reason = 'window acts on one named window; there is no "all windows" op'
1147
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1148
+ return $result
1149
+ }
1150
+ $fgBeforeOp = [WpmWin]::Fg()
1151
+ $w = Invoke-WpmWindowOp -Hwnd ([IntPtr][int64]$Hwnd) -Op $Op -X $X -Y $Y -Width $Width -Height $Height
1152
+ $fgAfterOp = [WpmWin]::Fg()
1153
+ # Only the 'hwnd is not a live window' branch carries a refusal code; the others answer ok/false with a
1154
+ # reason. Under StrictMode an unguarded read of a key that branch never sets would throw inside the
1155
+ # handler, so presence is tested rather than assumed.
1156
+ if ($w.ContainsKey('refusal') -and $w.refusal) { $result.refusal = [string]$w.refusal }
1157
+ $result.ok = [bool]$w.ok
1158
+ $result.reason = [string]$w.reason
1159
+ $bits = @("window=$Op")
1160
+ foreach ($k in @('iconic', 'called', 'asked', 'size', 'rect', 'before', 'topmost', 'exStyle', 'activated')) {
1161
+ if ($w.ContainsKey($k)) {
1162
+ # Lower-cased deliberately: every other boolean this engine puts into `detail` reads
1163
+ # disabled=true / focusMoved=false / verified=true, and a PowerShell `True` in the same sentence is
1164
+ # how a field ends up being parsed two ways by two consumers.
1165
+ $val = $w[$k]
1166
+ if ($val -is [bool]) { $val = $val.ToString().ToLower() }
1167
+ $bits += "$k=$val"
1168
+ }
1169
+ }
1170
+ $bits += $(if ($w.ok) { 'verified=true' } else { 'verified=false' })
1171
+ # DID THE OWNER LOSE THE FOREGROUND TO THIS CALL -- measured on both sides of it, because
1172
+ # `restore` activates by definition and a window op that quietly took the focus while reporting only a
1173
+ # size change is the failure shape this product keeps meeting. Saying it is not the same as refusing
1174
+ # it: the caller asked for the window to come back, and coming back is what restoring means.
1175
+ $fgTaken = ($fgBeforeOp -ne $fgAfterOp) -and ($fgAfterOp -eq $Hwnd)
1176
+ $bits += "foregroundTaken=$($fgTaken.ToString().ToLower())"
1177
+ if ($fgTaken) {
1178
+ $bits += "foregroundBefore=$fgBeforeOp foregroundAfter=$fgAfterOp"
1179
+ }
1180
+ $result.detail = ($bits -join ' ')
1181
+ $result.foregroundTaken = $fgTaken
1182
+ # The window's own answer is the read-back, so the effect follows it directly.
1183
+ $result.effect = $(if ($w.ok) { 'readback-verified' } else { 'unverified' })
1184
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
1185
+ return $result
1186
+ }