dsh-native-uia 0.2.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +81 -398
  2. package/client/client.js +236 -48
  3. package/cordis.patch.yml +7 -8
  4. package/locale/en.json +2 -2
  5. package/locale/zh.json +2 -2
  6. package/package.json +8 -17
  7. package/scripts/check-lease.mjs +1 -1
  8. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  9. package/scripts/lib/load-tools-source.mjs +17 -16
  10. package/scripts/lib/sources.mjs +62 -0
  11. package/scripts/load-tools.mjs +74 -0
  12. package/scripts/measure-parse.mjs +2 -2
  13. package/scripts/regression-tools.mjs +155 -6
  14. package/scripts/regression-worker.ps1 +29 -0
  15. package/scripts/verify-live-style.mjs +46 -0
  16. package/scripts/verify-live.mjs +12 -18
  17. package/scripts/verify.mjs +953 -192
  18. package/src/activity-window.js +71 -7
  19. package/src/dashboard.js +27 -69
  20. package/src/guard.js +39 -10
  21. package/src/index.js +187 -77
  22. package/src/notes.js +83 -0
  23. package/src/state.js +97 -10
  24. package/src/themes.js +66 -0
  25. package/src/tools/defs/act.js +671 -0
  26. package/src/tools/defs/lifecycle.js +205 -0
  27. package/src/tools/defs/observe.js +325 -0
  28. package/src/tools/defs/pointer.js +328 -0
  29. package/src/tools/format.js +338 -0
  30. package/src/tools/index.js +125 -0
  31. package/src/tools/ocr.js +91 -0
  32. package/src/tools/recipes.js +49 -0
  33. package/src/tools/runtime.js +42 -0
  34. package/src/worker-client.js +32 -10
  35. package/worker/assets/dsh-whale.path +1 -0
  36. package/worker/indicator-server.ps1 +1107 -72
  37. package/worker/lib/01-core.ps1 +64 -0
  38. package/worker/lib/02-uia.ps1 +224 -0
  39. package/worker/lib/03-window.ps1 +194 -0
  40. package/worker/lib/04-match.ps1 +435 -0
  41. package/worker/lib/05-value.ps1 +254 -0
  42. package/worker/lib/06-snapshot.ps1 +412 -0
  43. package/worker/lib/07-action.ps1 +329 -0
  44. package/worker/lib/08-command.ps1 +1495 -0
  45. package/worker/lib/09-pointer.ps1 +840 -0
  46. package/worker/lib/10-dispatch.ps1 +132 -0
  47. package/worker/ps-stdio.ps1 +7 -2
  48. package/worker/uia-worker.ps1 +599 -4220
  49. package/locale/desktop/en.json +0 -6
  50. package/locale/desktop/zh.json +0 -6
  51. package/scripts/regression-halt-latch.mjs +0 -100
  52. package/src/native-uia-remote.js +0 -80
  53. package/src/panel-face.js +0 -14
  54. package/src/tools.js +0 -1482
  55. package/web/control.html +0 -1413
@@ -0,0 +1,840 @@
1
+ # 09-pointer.ps1 -- physical pointer channel and window actions
2
+ #
3
+ # Part of worker/uia-worker.ps1, dot-sourced by it in the order scripts/lib/sources.mjs declares.
4
+ # It lives in its own file only so a section can be read without scrolling the whole RPC server.
5
+ # Dot-sourcing shares the entry's script scope, so a helper here may use $script:W and may call
6
+ # any function from any other part: neighbour order is not a dependency.
7
+ function Cmd-Shutdown($A) {
8
+ return [ordered]@{
9
+ closed = $true
10
+ totalRefs = $script:W.totalRefs
11
+ windows = $script:W.windows.Count
12
+ workerPid = [int]$PID
13
+ }
14
+ }
15
+
16
+ # ---------------------------------------------------------------- physical pointer channel
17
+ # This is the only place in the worker that puts motion on the desktop. It is deliberately
18
+ # separate from the UIA action channel: `act`/`commit_batch` deliver in the background and must
19
+ # keep the cursor still, while pointer_* moves the real OS cursor so a human (and the cursor
20
+ # halo) can see the agent working.
21
+ #
22
+ # Mechanics:
23
+ # * every event is SendInput(INPUT_MOUSE) with MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE |
24
+ # MOUSEEVENTF_VIRTUALDESK, dx/dy normalised to 0..65535 across the VIRTUAL screen
25
+ # * SetCursorPos is not used and not even declared: placing the cursor would produce a single
26
+ # observable position, and the acceptance test measures a trajectory
27
+ # * coordinates are screen pixels in the same space UIA BoundingRectangle reports (physical,
28
+ # because the worker made itself per-monitor-v2 aware at startup)
29
+ # * the default glide is clamp(90 + distance * 0.35, 90, 600) ms, sampled every 8 ms along an
30
+ # ease-in-out cubic straight line, so the middle steps are the longest and nothing teleports
31
+ # * a click or a drag re-reads the window under the point (WindowFromPoint) immediately before
32
+ # it presses and refuses unless the caller's `expect` matches; the overlay windows this plugin
33
+ # draws are WS_EX_TRANSPARENT, so hit-testing here is already overlay-free
34
+ $script:ptrVirt = $null
35
+ $script:ptrPrecision = $false
36
+
37
+ function Ensure-Pointer {
38
+ if (-not $script:nativeLoaded) { Err 'native_unavailable' 'the SendInput helper did not compile (Add-Type failed), the pointer channel is off' }
39
+ }
40
+
41
+ function Get-VirtScreen {
42
+ if ($null -eq $script:ptrVirt) {
43
+ $x = 0; $y = 0; $w = 0; $h = 0
44
+ try {
45
+ # SM_XVIRTUALSCREEN=76 SM_YVIRTUALSCREEN=77 SM_CXVIRTUALSCREEN=78 SM_CYVIRTUALSCREEN=79
46
+ $x = [int][Native]::GetSystemMetrics(76); $y = [int][Native]::GetSystemMetrics(77)
47
+ $w = [int][Native]::GetSystemMetrics(78); $h = [int][Native]::GetSystemMetrics(79)
48
+ } catch { }
49
+ if ($w -le 0 -or $h -le 0) {
50
+ # Fall back to the primary monitor's metrics, never to a guessed resolution: a hardcoded
51
+ # 1920x1080 makes every coordinate normalisation wrong on any other display, and the error
52
+ # is silent — SendInput just lands somewhere else.
53
+ try { $w = [int][Native]::GetSystemMetrics(0); $h = [int][Native]::GetSystemMetrics(1) } catch { }
54
+ $x = 0; $y = 0
55
+ }
56
+ if ($w -le 0 -or $h -le 0) {
57
+ # Last resort: ask the display stack directly (System.Windows.Forms knows the desktop even
58
+ # when the user32 metrics call failed). Still measured, never assumed.
59
+ try {
60
+ $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
61
+ $x = [int]$b.X; $y = [int]$b.Y; $w = [int]$b.Width; $h = [int]$b.Height
62
+ } catch { }
63
+ }
64
+ if ($w -le 0 -or $h -le 0) {
65
+ Err 'screen_unknown' 'cannot measure the virtual screen: GetSystemMetrics and Screen.Bounds both reported no area'
66
+ }
67
+ $script:ptrVirt = @{ x = $x; y = $y; w = $w; h = $h }
68
+ Log ('pointer virtual screen ' + $x + ',' + $y + ' ' + $w + 'x' + $h + ' inputByteSize=' + [Native]::InputByteSize)
69
+ }
70
+ return $script:ptrVirt
71
+ }
72
+
73
+ # winmm timer resolution: without it Thread.Sleep(1) can overshoot to ~15 ms and an 8 ms cadence
74
+ # quietly becomes a 16 ms one. Raised once for the life of the worker (it is cheap, and the cost
75
+ # of raising/releasing around every glide is a first sample that lands late).
76
+ function Begin-Precision {
77
+ if ($script:ptrPrecision) { return }
78
+ try { [void][Native]::timeBeginPeriod(1) } catch { }
79
+ $script:ptrPrecision = $true
80
+ }
81
+
82
+ # Pixel -> 0..65535. The +0.5 puts the event on the pixel centre, which is what makes the last
83
+ # sample of a glide land on the requested pixel instead of one pixel short of it.
84
+ function To-Norm($px, $py, $v) {
85
+ $nx = [int][Math]::Round((([double]$px - [double]$v.x) + 0.5) / [double]$v.w * 65535.0)
86
+ $ny = [int][Math]::Round((([double]$py - [double]$v.y) + 0.5) / [double]$v.h * 65535.0)
87
+ if ($nx -lt 0) { $nx = 0 } elseif ($nx -gt 65535) { $nx = 65535 }
88
+ if ($ny -lt 0) { $ny = 0 } elseif ($ny -gt 65535) { $ny = 65535 }
89
+ return @{ x = $nx; y = $ny }
90
+ }
91
+
92
+ function Pointer-Pos {
93
+ $v = Get-VirtScreen
94
+ try {
95
+ $a = [Native]::CursorXY()
96
+ $x = [int]$a[0]; $y = [int]$a[1]
97
+ if ($x -eq -1 -and $y -eq -1) { return Cursor-Pos }
98
+ if ($x -lt $v.x -or $x -ge ($v.x + $v.w) -or $y -lt $v.y -or $y -ge ($v.y + $v.h)) {
99
+ Log ('pointer: cursor (' + $x + ',' + $y + ') is outside the reported virtual screen')
100
+ }
101
+ return @{ x = $x; y = $y }
102
+ } catch { return Cursor-Pos }
103
+ }
104
+
105
+ function Apply-Ease($t, $kind) {
106
+ if ($t -le 0) { return 0.0 }
107
+ if ($t -ge 1) { return 1.0 }
108
+ switch ($kind) {
109
+ 'linear' { return [double]$t }
110
+ 'ease-in' { return $t * $t * $t }
111
+ 'ease-out' { $u = 1.0 - $t; return 1.0 - ($u * $u * $u) }
112
+ default {
113
+ if ($t -lt 0.5) { return 4.0 * $t * $t * $t }
114
+ $u = -2.0 * $t + 2.0
115
+ return 1.0 - ($u * $u * $u) / 2.0
116
+ }
117
+ }
118
+ }
119
+
120
+ function Wait-Tick($deadlineTick) {
121
+ while ((TickNow) -lt $deadlineTick) {
122
+ $rem = ([double]$deadlineTick - [double](TickNow)) / 10000.0
123
+ if ($rem -gt 2.5) {
124
+ try { [Threading.Thread]::Sleep(1) } catch { break }
125
+ } else {
126
+ try { [Threading.Thread]::SpinWait(8) } catch { break }
127
+ }
128
+ }
129
+ }
130
+
131
+ function Glide-Duration($distancePx, $requestedMs) {
132
+ $auto = 90.0 + $distancePx * 0.35
133
+ if ($auto -lt 90.0) { $auto = 90.0 }
134
+ if ($auto -gt 600.0) { $auto = 600.0 }
135
+ if ($requestedMs -gt 0) {
136
+ $d = [double]$requestedMs
137
+ if ($d -lt 8.0) { $d = 8.0 }
138
+ if ($d -gt 4000.0) { $d = 4000.0 }
139
+ return @{ durationMs = [int][Math]::Round($d); source = 'caller' }
140
+ }
141
+ return @{ durationMs = [int][Math]::Round($auto); source = 'formula' }
142
+ }
143
+
144
+ # The path itself. Emits exactly floor(durationMs/8) absolute moves (or 2 when teleporting, which
145
+ # only the acceptance test does), sleeping until each 8 ms slot rather than sleeping 8 ms, so the
146
+ # cadence does not drift with timer resolution.
147
+ function Send-Pointer-Path($fromX, $fromY, $toX, $toY, $durationMs, $ease, $teleport) {
148
+ $v = Get-VirtScreen
149
+ $st = TickNow
150
+ $expected = [int][Math]::Floor([double]$durationMs / 8.0)
151
+ if ($expected -lt 1) { $expected = 1 }
152
+ $points = New-Object System.Collections.Generic.List[object]
153
+ $sent = 0
154
+ $t0 = TickNow
155
+ Begin-Precision
156
+ if ($teleport) {
157
+ $a = To-Norm $fromX $fromY $v
158
+ if ([Native]::AbsMove($a.x, $a.y) -ne 1) { Err 'input_blocked' 'SendInput refused the move event (UIPI or a blocked input desktop)' }
159
+ $sent++
160
+ [void]$points.Add([ordered]@{ x = [int]$fromX; y = [int]$fromY; t = (MsFrom $t0) })
161
+ $b = To-Norm $toX $toY $v
162
+ if ([Native]::AbsMove($b.x, $b.y) -ne 1) { Err 'input_blocked' 'SendInput refused the move event (UIPI or a blocked input desktop)' }
163
+ $sent++
164
+ [void]$points.Add([ordered]@{ x = [int]$toX; y = [int]$toY; t = (MsFrom $t0) })
165
+ } else {
166
+ for ($i = 1; $i -le $expected; $i++) {
167
+ if (Test-Escape) { Err 'cancelled' 'ESC pressed during pointer motion; glide aborted' }
168
+ $f = Apply-Ease ([double]$i / [double]$expected) $ease
169
+ $px = [int][Math]::Round([double]$fromX + ([double]$toX - [double]$fromX) * $f)
170
+ $py = [int][Math]::Round([double]$fromY + ([double]$toY - [double]$fromY) * $f)
171
+ if ($i -eq $expected) { $px = [int]$toX; $py = [int]$toY } # never leave a rounding stub
172
+ $n = To-Norm $px $py $v
173
+ if ([Native]::AbsMove($n.x, $n.y) -ne 1) { Err 'input_blocked' ('SendInput dropped the move event at step ' + $i + ' of ' + $expected) }
174
+ $sent++
175
+ [void]$points.Add([ordered]@{ x = $px; y = $py; t = (MsFrom $t0) })
176
+ Wait-Tick ($t0 + ([Int64]$i * 8 * 10000))
177
+ }
178
+ }
179
+ return @{
180
+ sent = $sent
181
+ expected = $expected
182
+ points = $points
183
+ ms = (MsFrom $st)
184
+ teleport = [bool]$teleport
185
+ durationMs = [int]$durationMs
186
+ ease = [string]$ease
187
+ }
188
+ }
189
+
190
+ function Req-Coord($A, $name, $label) {
191
+ $v = ArgOf $A $name
192
+ if ($null -eq $v) { Err 'missing_arg' ("pointer needs a '" + $name + "' coordinate" + $(if ($label) { ' of ' + $label } else { '' })) }
193
+ $d = $null
194
+ try { $d = [double]$v } catch { Err 'bad_arg' ("'" + $name + "' is not a number: " + (OneLine ([string]$v))) }
195
+ if ([double]::IsNaN($d) -or [double]::IsInfinity($d)) { Err 'bad_arg' ("'" + $name + "' is not finite") }
196
+ return [int][Math]::Round($d)
197
+ }
198
+
199
+ function Assert-In-Station($x, $y) {
200
+ $v = Get-VirtScreen
201
+ if ($x -lt $v.x -or $x -gt ($v.x + $v.w - 1) -or $y -lt $v.y -or $y -gt ($v.y + $v.h - 1)) {
202
+ Err 'out_of_bounds' ("point " + $x + "," + $y + " is outside the virtual screen " + $v.x + "," + $v.y + " " + $v.w + "x" + $v.h)
203
+ }
204
+ }
205
+
206
+ function Window-Under-Info($x, $y) {
207
+ $h = [Native]::HitTest([int]$x, [int]$y)
208
+ $app = ''
209
+ if ($h.pid -gt 0) { $app = ProcNameOf ([int]$h.pid) }
210
+ return [ordered]@{
211
+ hwnd = [int64]$h.root
212
+ hitHwnd = [int64]$h.hit
213
+ class = (TruncStr ([string]$h.rootClass) 80)
214
+ hitClass = (TruncStr ([string]$h.hitClass) 80)
215
+ title = (TruncStr ([string]$h.title) 140)
216
+ pid = [int64]$h.pid
217
+ app = $app
218
+ }
219
+ }
220
+
221
+ function Expect-Of($A) {
222
+ $e = Dict (ArgOf $A 'expect')
223
+ if ($null -eq $e -or -not ($e -is [System.Collections.IDictionary])) { $e = @{} }
224
+ $hwnd = $e.Item('hwnd')
225
+ if ($null -eq $hwnd) { $hwnd = ArgOf $A 'expectHwnd' }
226
+ $title = $e.Item('titleContains')
227
+ if ($null -eq $title -or [string]$title -eq '') { $title = StrArg $A 'expectTitleContains' '' }
228
+ $wid = [string]$e.Item('windowId')
229
+ $allow = BoolArg $A 'allowAnyTarget' $false
230
+ if ($null -ne $e.Item('allowAnyTarget')) { $allow = BoolArg $e 'allowAnyTarget' $allow }
231
+ $hwndI = 0
232
+ if ($null -ne $hwnd -and [string]$hwnd -ne '') {
233
+ try { $hwndI = [int64][double]$hwnd } catch { Err 'bad_arg' ("expect.hwnd is not a number: " + (OneLine ([string]$hwnd))) }
234
+ }
235
+ if ($hwndI -eq 0 -and $wid -ne '') {
236
+ $entry = $script:W.windows.Item($wid)
237
+ if ($null -eq $entry) { Err 'unknown_window' ("expect.windowId '" + $wid + "' is not a window this worker knows") }
238
+ try { $hwndI = [int64]$entry.hwnd } catch { $hwndI = 0 }
239
+ }
240
+ $titleS = [string]$title
241
+ return @{ hwnd = $hwndI; title = $titleS; allowAny = [bool]$allow; named = (($hwndI -ne 0) -or ($titleS -ne '')) }
242
+ }
243
+
244
+ # The safety gate. Returns the hit-test plus a verdict; it never throws, because the caller has
245
+ # to put the cursor back before reporting the refusal.
246
+ function Test-Pointer-Target($exp, $x, $y) {
247
+ $under = Window-Under-Info $x $y
248
+ if (-not $exp.named) {
249
+ if ($exp.allowAny) { return @{ under = $under; pass = $true; reason = ''; expectation = 'none (allowAnyTarget)' } }
250
+ return @{ under = $under; pass = $false; expectation = 'none'
251
+ reason = ("refusing to click at " + $x + "," + $y + " because nothing was declared as the expected target; " +
252
+ "pass expect:{hwnd|windowId|titleContains} or say allowAnyTarget:true") }
253
+ }
254
+ $ok = $true; $why = ''
255
+ if ($exp.hwnd -ne 0) {
256
+ $isUnder = [Native]::IsSelfOrDescendant([IntPtr][int64]$under.hitHwnd, [IntPtr][int64]$exp.hwnd)
257
+ $isRoot = ([int64]$under.hwnd -eq [int64]$exp.hwnd)
258
+ if (-not ($isUnder -or $isRoot)) {
259
+ $ok = $false
260
+ $why = ("the window under " + $x + "," + $y + " is hwnd " + $under.hwnd + " '" + $under.title + "' (hit hwnd " + $under.hitHwnd + "), not the expected hwnd " + $exp.hwnd)
261
+ }
262
+ }
263
+ if ($ok -and $exp.title -ne '') {
264
+ if (([string]$under.title).ToLowerInvariant().IndexOf($exp.title.ToLowerInvariant()) -lt 0) {
265
+ $ok = $false
266
+ $why = ("the window under " + $x + "," + $y + " is titled '" + $under.title + "', which does not contain '" + $exp.title + "'")
267
+ }
268
+ }
269
+ return @{ under = $under; pass = $ok; reason = $why; expectation = ('hwnd=' + $exp.hwnd + ' titleContains=' + $exp.title) }
270
+ }
271
+
272
+ function Cmd-PointerTarget($A) {
273
+ Ensure-Pointer
274
+ $x = Req-Coord $A 'x' ''; $y = Req-Coord $A 'y' ''
275
+ Assert-In-Station $x $y
276
+ $v = Get-VirtScreen
277
+ $n = To-Norm $x $y $v
278
+ $e = Expect-Of $A
279
+ $check = $null
280
+ if ($e.named) { $check = Test-Pointer-Target $e $x $y }
281
+ $r = [ordered]@{
282
+ x = [int]$x; y = [int]$y
283
+ via = 'physical'
284
+ norm = [ordered]@{ x = [int]$n.x; y = [int]$n.y }
285
+ under = (Window-Under-Info $x $y)
286
+ }
287
+ if ($null -ne $check) { $r['pass'] = [bool]$check.pass; $r['reason'] = [string]$check.reason }
288
+ return $r
289
+ }
290
+
291
+ function Resolve-Mods($A, $name) {
292
+ # Modifiers travel either as an array ("mods":["ctrl","shift"]) or as a "+"-joined string; both
293
+ # shapes exist because the Node tools and the worker's own key parser speak different dialects.
294
+ # Only the four modifier families are allowed: a full key here would silently become a chord.
295
+ $raw = ArgOf $A $name
296
+ if ($null -eq $raw) { return @() }
297
+ $items = @()
298
+ if ($raw -is [System.Collections.IEnumerable] -and -not ($raw -is [string])) {
299
+ foreach ($x in $raw) { $items += [string]$x }
300
+ } else {
301
+ $items = @(([string]$raw).ToLowerInvariant() -split '\+' | Where-Object { $_ -ne '' })
302
+ }
303
+ $vks = New-Object System.Collections.Generic.List[int]
304
+ $names = New-Object System.Collections.Generic.List[string]
305
+ foreach ($m in $items) {
306
+ $t = ([string]$m).Trim().ToLowerInvariant()
307
+ if ($t -eq '') { continue }
308
+ if (@('ctrl', 'control', 'shift', 'alt', 'option', 'win', 'meta', 'super', 'cmd') -notcontains $t) {
309
+ Err 'bad_arg' ("modifier '" + (OneLine $t) + "' is not ctrl|shift|alt|win")
310
+ }
311
+ $vks.Add([int](Resolve-KeyVk $t)) | Out-Null
312
+ # Report the caller's own modifier names back, not VK numbers: "17" in a reply is unreadable and
313
+ # made the Node side print 按住 17.
314
+ $names.Add($t) | Out-Null
315
+ }
316
+ return [ordered]@{ vks = @($vks); names = @($names) }
317
+ }
318
+
319
+ function Cmd-PointerClick($A) {
320
+ Ensure-Pointer
321
+ $x = Req-Coord $A 'x' ''; $y = Req-Coord $A 'y' ''
322
+ Assert-In-Station $x $y
323
+ $button = (StrArg $A 'button' 'left').ToLowerInvariant()
324
+ if ($button -eq '') { $button = 'left' }
325
+ if (@('left', 'right', 'middle') -notcontains $button) { Err 'bad_arg' ("button '" + $button + "' is not left|right|middle") }
326
+ $double = BoolArg $A 'double' $false
327
+ # triple = three presses (text selection in an edit, paragraph select). Anthropic's computer tool
328
+ # exposes triple_click; without it a text-only model has no way to select a line.
329
+ $triple = BoolArg $A 'triple' $false
330
+ $mres = Resolve-Mods $A 'mods'
331
+ $mods = @($mres.vks); $modNames = @($mres.names)
332
+ $moveFirst = BoolArg $A 'moveFirst' $true
333
+ $ease = (StrArg $A 'ease' 'ease-in-out').ToLowerInvariant()
334
+ if (@('ease-in-out', 'linear', 'ease-in', 'ease-out') -notcontains $ease) { $ease = 'ease-in-out' }
335
+ $pressMs = IntArg $A 'pressMs' 40
336
+ if ($pressMs -lt 8) { $pressMs = 8 }
337
+ if ($pressMs -gt 600) { $pressMs = 600 }
338
+ $exp = Expect-Of $A
339
+ $st = TickNow
340
+ $start = Pointer-Pos
341
+
342
+ # gate #1, before the cursor moves at all
343
+ $g1 = Test-Pointer-Target $exp $x $y
344
+ if (-not $g1.pass) {
345
+ $script:W.stats.refused += 1
346
+ Err 'target_mismatch' ("pointer_click refused without moving: " + $g1.reason)
347
+ }
348
+
349
+ $glide = $null
350
+ if ($moveFirst) {
351
+ $dx = [double]($x - [int]$start.x); $dy = [double]($y - [int]$start.y)
352
+ $dist = [Math]::Sqrt($dx * $dx + $dy * $dy)
353
+ $g = Glide-Duration $dist (IntArg $A 'durationMs' 0)
354
+ if ($g.durationMs + 260 -gt (BudgetLeftMs)) {
355
+ Err 'deadline_exceeded' ("the approach glide (" + $g.durationMs + " ms) plus the press does not fit the " + (BudgetLeftMs) + " ms left in this request")
356
+ }
357
+ $glide = Send-Pointer-Path ([int]$start.x) ([int]$start.y) $x $y $g.durationMs $ease $false
358
+ }
359
+
360
+ # gate #2, after the glide: the window under the point is re-read, not remembered
361
+ $g2 = Test-Pointer-Target $exp $x $y
362
+ if (-not $g2.pass) {
363
+ $script:W.stats.refused += 1
364
+ if ($null -ne $glide) {
365
+ $cur = Pointer-Pos
366
+ [void](Send-Pointer-Path ([int]$cur.x) ([int]$cur.y) ([int]$start.x) ([int]$start.y) 140 $ease $false)
367
+ }
368
+ Err 'target_mismatch' ("pointer_click refused after gliding and put the cursor back: " + $g2.reason)
369
+ }
370
+
371
+ $v = Get-VirtScreen
372
+ $n = To-Norm $x $y $v
373
+ $presses = 0
374
+ $pressesWanted = if ($triple) { 3 } elseif ($double) { 2 } else { 1 }
375
+ Begin-Precision
376
+ # Modifiers are held for the WHOLE press sequence and released in finally: an Err thrown mid-press
377
+ # (input_blocked) must never leave ctrl latched down system-wide.
378
+ foreach ($m in $mods) { if ([Native]::KeyDownVk([int]$m) -ne 1) { Err 'input_blocked' 'SendInput dropped a modifier key-down' } }
379
+ try {
380
+ for ($p = 0; $p -lt $pressesWanted; $p++) {
381
+ if ($p -gt 0) { [Threading.Thread]::Sleep(50) }
382
+ if ([Native]::AbsButtonDown($n.x, $n.y, $button) -ne 1) { Err 'input_blocked' ('SendInput dropped the button-down event at press ' + ($p + 1)) }
383
+ [Threading.Thread]::Sleep($pressMs)
384
+ if ([Native]::AbsButtonUp($n.x, $n.y, $button) -ne 1) { Err 'input_blocked' ('SendInput dropped the button-up event at press ' + ($p + 1)) }
385
+ $presses++
386
+ }
387
+ } finally {
388
+ for ($j = $mods.Count - 1; $j -ge 0; $j--) { [void][Native]::KeyUpVk([int]$mods[$j]) }
389
+ }
390
+ $at = Pointer-Pos
391
+ $script:W.stats.actionsPerformed += 1
392
+ $r = [ordered]@{
393
+ atCursor = [ordered]@{ x = [int]$at.x; y = [int]$at.y }
394
+ via = 'physical'
395
+ button = $button
396
+ down = $true
397
+ up = $true
398
+ ms = [Math]::Round((MsFrom $st), 1)
399
+ presses = [int]$presses
400
+ double = [bool]$double
401
+ triple = [bool]$triple
402
+ mods = [string]($modNames -join '+')
403
+ pressMs = [int]$pressMs
404
+ moved = [bool]($null -ne $glide)
405
+ under = $g2.under
406
+ gate = [ordered]@{ before = [bool]$g1.pass; after = [bool]$g2.pass; expectation = [string]$g2.expectation }
407
+ }
408
+ if ($null -ne $glide) {
409
+ $r['distance'] = [Math]::Round([Math]::Sqrt([Math]::Pow([double]($x - [int]$start.x), 2) + [Math]::Pow([double]($y - [int]$start.y), 2)), 1)
410
+ $r['samples'] = [int]$glide.sent
411
+ $r['expectedSamples'] = [int]$glide.expected
412
+ }
413
+ return $r
414
+ }
415
+
416
+ function Cmd-PointerDrag($A) {
417
+ Ensure-Pointer
418
+ $fd = Dict (ArgOf $A 'from')
419
+ $td = Dict (ArgOf $A 'to')
420
+ if ($null -eq $fd -or -not ($fd -is [System.Collections.IDictionary])) { Err 'missing_arg' 'pointer_drag needs from:{x,y}' }
421
+ if ($null -eq $td -or -not ($td -is [System.Collections.IDictionary])) { Err 'missing_arg' 'pointer_drag needs to:{x,y}' }
422
+ $fx = Req-Coord $fd 'x' 'from'; $fy = Req-Coord $fd 'y' 'from'
423
+ $tx = Req-Coord $td 'x' 'to'; $ty = Req-Coord $td 'y' 'to'
424
+ Assert-In-Station $fx $fy; Assert-In-Station $tx $ty
425
+ $button = (StrArg $A 'button' 'left').ToLowerInvariant()
426
+ if (@('left', 'right', 'middle') -notcontains $button) { Err 'bad_arg' ("button '" + $button + "' is not left|right|middle") }
427
+ $ease = (StrArg $A 'ease' 'ease-in-out').ToLowerInvariant()
428
+ if (@('ease-in-out', 'linear', 'ease-in', 'ease-out') -notcontains $ease) { $ease = 'ease-in-out' }
429
+ $holdMs = IntArg $A 'holdMs' 60
430
+ if ($holdMs -lt 8) { $holdMs = 8 }
431
+ if ($holdMs -gt 1000) { $holdMs = 1000 }
432
+ $exp = Expect-Of $A
433
+ $st = TickNow
434
+ $start = Pointer-Pos
435
+
436
+ # a drag is the most destructive gesture this channel can express, so the declared window has
437
+ # to hold for the endpoints AND for points in between
438
+ if ($exp.named) {
439
+ foreach ($tf in @(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)) {
440
+ $px = [int][Math]::Round([double]$fx + ([double]$tx - [double]$fx) * $tf)
441
+ $py = [int][Math]::Round([double]$fy + ([double]$ty - [double]$fy) * $tf)
442
+ $c = Test-Pointer-Target $exp $px $py
443
+ if (-not $c.pass) {
444
+ $script:W.stats.refused += 1
445
+ Err 'target_mismatch' ("pointer_drag refused before moving (probe at " + [Math]::Round($tf * 100) + "% of the path): " + $c.reason)
446
+ }
447
+ }
448
+ }
449
+
450
+ $d0x = [double]($fx - [int]$start.x); $d0y = [double]($fy - [int]$start.y)
451
+ $dist0 = [Math]::Sqrt($d0x * $d0x + $d0y * $d0y)
452
+ $dx = [double]($tx - $fx); $dy = [double]($ty - $fy)
453
+ $dist = [Math]::Sqrt($dx * $dx + $dy * $dy)
454
+ $g0 = Glide-Duration $dist0 (IntArg $A 'durationMs' 0)
455
+ $g1 = Glide-Duration $dist (IntArg $A 'durationMs2' $g0.durationMs)
456
+ $need = $g0.durationMs + $g1.durationMs + 2 * $holdMs + 300
457
+ if ($need -gt (BudgetLeftMs)) {
458
+ Err 'deadline_exceeded' ("this drag needs ~" + $need + " ms but only " + (BudgetLeftMs) + " ms are left in the request")
459
+ }
460
+
461
+ $approach = Send-Pointer-Path ([int]$start.x) ([int]$start.y) $fx $fy $g0.durationMs $ease $false
462
+ $v = Get-VirtScreen
463
+ $n = To-Norm $fx $fy $v
464
+ Begin-Precision
465
+ if ([Native]::AbsButtonDown($n.x, $n.y, $button) -ne 1) { Err 'input_blocked' 'SendInput dropped the drag button-down event' }
466
+ [Threading.Thread]::Sleep($holdMs)
467
+ # the button stays logically down; the travel events are plain absolute moves, which is what a
468
+ # real drag looks like on the wire
469
+ $travel = Send-Pointer-Path $fx $fy $tx $ty $g1.durationMs $ease $false
470
+ [Threading.Thread]::Sleep($holdMs)
471
+ $n2 = To-Norm $tx $ty $v
472
+ $upOk = $false
473
+ try { $upOk = ([Native]::AbsButtonUp($n2.x, $n2.y, $button) -eq 1) } catch { }
474
+ if (-not $upOk) {
475
+ # never leave the desktop with a button held down: retry once, then say so loudly
476
+ try { [void][Native]::AbsButtonUp($n2.x, $n2.y, $button) } catch { }
477
+ Log 'pointer_drag: the button-up event was dropped twice; the desktop may still think the button is held'
478
+ }
479
+ $at = Pointer-Pos
480
+ $under = Window-Under-Info $tx $ty
481
+ $script:W.stats.actionsPerformed += 1
482
+ return [ordered]@{
483
+ from = [ordered]@{ x = [int]$fx; y = [int]$fy }
484
+ to = [ordered]@{ x = [int]$tx; y = [int]$ty }
485
+ via = 'physical'
486
+ button = $button
487
+ down = $true
488
+ up = [bool]$upOk
489
+ distance = [Math]::Round($dist, 1)
490
+ durationMs = [int]$g1.durationMs
491
+ samples = [int]$travel.sent
492
+ expectedSamples = [int]$travel.expected
493
+ approachSamples = [int]$approach.sent
494
+ holdMs = [int]$holdMs
495
+ atCursor = [ordered]@{ x = [int]$at.x; y = [int]$at.y }
496
+ under = $under
497
+ ms = [Math]::Round((MsFrom $st), 1)
498
+ }
499
+ }
500
+
501
+ # Read-only: where is the caret / the keyboard focus right now, for an element the caller already
502
+ # has a ref for. This is the instrument that turns "an event was queued" into "the click landed".
503
+ # Named-key -> virtual-key-code table for the physical keyboard channel (Cmd-Key). Letters and digits
504
+ # are resolved by ASCII in Resolve-KeyVk; this table covers the rest.
505
+ $script:VK = @{
506
+ 'ctrl' = 0x11; 'control' = 0x11; 'alt' = 0x12; 'option' = 0x12; 'shift' = 0x10;
507
+ 'win' = 0x5B; 'meta' = 0x5B; 'super' = 0x5B; 'cmd' = 0x5B; 'winright' = 0x5C;
508
+ 'enter' = 0x0D; 'return' = 0x0D; 'tab' = 0x09; 'esc' = 0x1B; 'escape' = 0x1B;
509
+ 'backspace' = 0x08; 'delete' = 0x2E; 'del' = 0x2E; 'insert' = 0x2D; 'space' = 0x20; 'spacebar' = 0x20;
510
+ 'up' = 0x26; 'down' = 0x28; 'left' = 0x25; 'right' = 0x27; 'home' = 0x24; 'end' = 0x23;
511
+ 'pageup' = 0x21; 'pgup' = 0x21; 'pagedown' = 0x22; 'pgdn' = 0x22;
512
+ 'printscreen' = 0x2C; 'capslock' = 0x14;
513
+ 'f1' = 0x70; 'f2' = 0x71; 'f3' = 0x72; 'f4' = 0x73; 'f5' = 0x74; 'f6' = 0x75;
514
+ 'f7' = 0x76; 'f8' = 0x77; 'f9' = 0x78; 'f10' = 0x79; 'f11' = 0x7A; 'f12' = 0x7B;
515
+ }
516
+ function Resolve-KeyVk($tok) {
517
+ if ($script:VK.ContainsKey($tok)) { return [int]$script:VK[$tok] }
518
+ if ($tok.Length -eq 1) {
519
+ $code = [int][char]$tok[0]
520
+ if ($code -ge 97 -and $code -le 122) { return $code - 32 } # a-z -> VK_A..VK_Z (ASCII uppercase)
521
+ if ($code -ge 48 -and $code -le 57) { return $code } # 0-9 -> VK_0..VK_9 (ASCII digit)
522
+ }
523
+ Err 'unknown_key' ("unrecognized key '" + (OneLine $tok) + "' (use a name like enter/tab/f5/up or a single letter/digit)")
524
+ }
525
+
526
+ function Cmd-TypeText($A) {
527
+ Ensure-Pointer
528
+ $text = ArgOf $A 'text'
529
+ if ($null -eq $text) { Err 'missing_arg' 'type_text needs text' }
530
+ $text = [string]$text
531
+ if ($text.Length -gt 4000) { Err 'too_long' 'type_text accepts at most 4000 characters' }
532
+ if ($text -eq '') { return [ordered]@{ sent = 0; chars = 0; ms = 0 } }
533
+ # via = keyboard (default, per-character SendInput, semantics unchanged) | clipboard (write the
534
+ # whole text with Set-Clipboard — built into Windows PowerShell 5.1, zero dependencies — and
535
+ # deliver ONE ctrl+v through the same event pipeline Cmd-Key uses). The clipboard path is for
536
+ # long text / text with newlines: 4000 characters as keyboard events is 8000 SendInput events,
537
+ # one paste is 4. It deliberately does NOT save or restore the clipboard — documented loudly.
538
+ $via = (StrArg $A 'via' 'keyboard').ToLowerInvariant()
539
+ if (@('keyboard', 'clipboard') -notcontains $via) { Err 'bad_arg' ("via '" + (OneLine $via) + "' is not keyboard|clipboard") }
540
+ $wid = StrArg $A 'windowId' ''
541
+ if ($wid -ne '') {
542
+ $entry = Window-Entry $wid
543
+ try { [void][Native]::SetForegroundWindow([IntPtr]$entry.hwnd) } catch { }
544
+ [Threading.Thread]::Sleep(30)
545
+ }
546
+ $st = TickNow
547
+ if ($via -eq 'clipboard') {
548
+ # Set-Clipboard can lose a race against a clipboard manager inspecting the same buffer —
549
+ # retry once, then refuse honestly instead of pasting garbage.
550
+ $clipOk = $false
551
+ $clipErr = ''
552
+ for ($attempt = 0; $attempt -lt 2 -and -not $clipOk; $attempt++) {
553
+ try { Set-Clipboard -Value $text; $clipOk = $true } catch { $clipErr = $_.Exception.Message; Start-Sleep -Milliseconds 60 }
554
+ }
555
+ if (-not $clipOk) { Err 'clipboard_failed' ('Set-Clipboard threw twice (clipboard manager contention?): ' + (OneLine $clipErr)) }
556
+ [Threading.Thread]::Sleep(30) # let the write settle before the paste
557
+ # ctrl+v through the exact pipeline Cmd-Key uses (KeyDownVk/KeyUpVk + Sleep(15)). VK_CONTROL
558
+ # = 0x11, VK_V = 0x56; 'v' resolves to the same code in Resolve-KeyVk.
559
+ Begin-Precision
560
+ if ([Native]::KeyDownVk(0x11) -ne 1) { Err 'input_blocked' 'SendInput dropped the ctrl key-down' }
561
+ if ([Native]::KeyDownVk(0x56) -ne 1) { Err 'input_blocked' 'SendInput dropped the v key-down' }
562
+ [Threading.Thread]::Sleep(15)
563
+ if ([Native]::KeyUpVk(0x56) -ne 1) { Err 'input_blocked' 'SendInput dropped the v key-up' }
564
+ [void][Native]::KeyUpVk(0x11)
565
+ $script:W.stats.actionsPerformed += 1
566
+ return [ordered]@{ sent = 4; chars = [int]$text.Length; via = 'clipboard'; ms = [Math]::Round((MsFrom $st), 1) }
567
+ }
568
+ $sent = [Native]::SendUnicode($text)
569
+ if ($sent -lt 1) { Err 'input_blocked' 'SendInput accepted none of the key events (blocked input desktop?)' }
570
+ $script:W.stats.actionsPerformed += 1
571
+ return [ordered]@{ sent = [int]$sent; chars = [int]$text.Length; via = 'physical'; ms = [Math]::Round((MsFrom $st), 1) }
572
+ }
573
+
574
+ function Cmd-Key($A) {
575
+ Ensure-Pointer
576
+ $combo = StrArg $A 'keys' ''
577
+ if ($combo -eq '') { $combo = StrArg $A 'key' '' }
578
+ if ($combo -eq '') { Err 'missing_arg' 'key needs keys, e.g. "enter" or "ctrl+c" or "alt+tab"' }
579
+ $tokens = @(($combo.ToLowerInvariant() -split '\+') | Where-Object { $_ -ne '' })
580
+ if ($tokens.Count -eq 0) { Err 'bad_arg' ('could not parse keys: ' + (OneLine $combo)) }
581
+ $mods = New-Object System.Collections.Generic.List[int]
582
+ $main = 0
583
+ for ($i = 0; $i -lt $tokens.Count; $i++) {
584
+ $vk = Resolve-KeyVk ([string]$tokens[$i])
585
+ if ($i -lt $tokens.Count - 1) { $mods.Add([int]$vk) | Out-Null } else { $main = [int]$vk }
586
+ }
587
+ $st = TickNow
588
+ # repeat: tab/tab/tab/tab is one call instead of four round trips (Anthropic's key tool has the
589
+ # same knob). holdMs: a held key (space to pan, shift to range-select) — capped so a held modifier
590
+ # cannot outlive the request budget.
591
+ $repeat = IntArg $A 'repeat' 1
592
+ if ($repeat -lt 1) { $repeat = 1 }; if ($repeat -gt 100) { $repeat = 100 }
593
+ $holdMs = IntArg $A 'holdMs' 15
594
+ if ($holdMs -lt 1) { $holdMs = 1 }; if ($holdMs -gt 30000) { $holdMs = 30000 }
595
+ Begin-Precision
596
+ foreach ($m in $mods) { if ([Native]::KeyDownVk([int]$m) -ne 1) { Err 'input_blocked' 'SendInput dropped a modifier key-down' } }
597
+ try {
598
+ for ($n = 0; $n -lt $repeat; $n++) {
599
+ if ([Native]::KeyDownVk($main) -ne 1) { Err 'input_blocked' 'SendInput dropped the key-down' }
600
+ [Threading.Thread]::Sleep($holdMs)
601
+ if ([Native]::KeyUpVk($main) -ne 1) { Err 'input_blocked' 'SendInput dropped the key-up' }
602
+ if ($n -lt $repeat - 1) { [Threading.Thread]::Sleep(20) }
603
+ }
604
+ } finally {
605
+ for ($j = $mods.Count - 1; $j -ge 0; $j--) { [void][Native]::KeyUpVk([int]$mods[$j]) }
606
+ }
607
+ $script:W.stats.actionsPerformed += 1
608
+ # Field name is `combo`, not `keys`: a dictionary field literally named "keys" is shadowed by
609
+ # PowerShell member lookup ($dict.Keys) and used to serialize as {}. JsonOf now uses an enumerator,
610
+ # and the name stays clear of the collision anyway.
611
+ return [ordered]@{ combo = $combo; via = 'physical'; repeat = [int]$repeat; holdMs = [int]$holdMs; ms = [Math]::Round((MsFrom $st), 1) }
612
+ }
613
+
614
+ function Cmd-PointerScroll($A) {
615
+ Ensure-Pointer
616
+ $x = Req-Coord $A 'x' ''; $y = Req-Coord $A 'y' ''
617
+ Assert-In-Station $x $y
618
+ $dir = (StrArg $A 'direction' 'down').ToLowerInvariant()
619
+ if (@('up', 'down', 'left', 'right') -notcontains $dir) { Err 'bad_arg' ("direction '" + $dir + "' is not up|down|left|right") }
620
+ $clicks = IntArg $A 'clicks' 3
621
+ if ($clicks -lt 1) { $clicks = 1 }; if ($clicks -gt 50) { $clicks = 50 }
622
+ $horiz = ($dir -eq 'left' -or $dir -eq 'right')
623
+ $sign = if ($dir -eq 'down' -or $dir -eq 'left') { -1 } else { 1 }
624
+ $exp = Expect-Of $A
625
+ $g = Test-Pointer-Target $exp $x $y
626
+ if (-not $g.pass) { $script:W.stats.refused += 1; Err 'target_mismatch' ('pointer_scroll refused: ' + $g.reason) }
627
+ $v = Get-VirtScreen; $n = To-Norm $x $y $v
628
+ $mres = Resolve-Mods $A 'mods'
629
+ $mods = @($mres.vks); $modNames = @($mres.names)
630
+ Begin-Precision
631
+ $st = TickNow
632
+ if ([Native]::AbsMove($n.x, $n.y) -ne 1) { Err 'input_blocked' 'scroll move refused by SendInput' }
633
+ $sent = 0
634
+ # ctrl+wheel = zoom, shift+wheel = horizontal in most apps; held for the whole notch sequence and
635
+ # released in finally so a mid-sequence Err cannot latch a modifier down.
636
+ foreach ($m in $mods) { if ([Native]::KeyDownVk([int]$m) -ne 1) { Err 'input_blocked' 'SendInput dropped a modifier key-down' } }
637
+ try {
638
+ for ($i = 0; $i -lt $clicks; $i++) {
639
+ if (Test-Escape) { break }
640
+ $d = $sign * 120
641
+ $r = if ($horiz) { [Native]::AbsHWheel($n.x, $n.y, $d) } else { [Native]::AbsWheel($n.x, $n.y, $d) }
642
+ if ($r -ne 1) { Err 'input_blocked' ('SendInput dropped the wheel event at ' + ($i + 1) + ' of ' + $clicks) }
643
+ $sent++
644
+ [Threading.Thread]::Sleep(12)
645
+ }
646
+ } finally {
647
+ for ($j = $mods.Count - 1; $j -ge 0; $j--) { [void][Native]::KeyUpVk([int]$mods[$j]) }
648
+ }
649
+ $script:W.stats.actionsPerformed += 1
650
+ return [ordered]@{ at = [ordered]@{ x = [int]$x; y = [int]$y }; direction = $dir; clicks = [int]$sent; horizontal = [bool]$horiz; mods = [string]($modNames -join '+'); via = 'physical'; under = $g.under; ms = [Math]::Round((MsFrom $st), 1) }
651
+ }
652
+
653
+ function Cmd-PointerMouse($A) {
654
+ # The pieces a single click cannot express: hover (move only), press-and-hold across calls
655
+ # (down/up), marquee/table selections, and reading where the cursor is. Anthropic's computer tool
656
+ # splits mouse_move / left_mouse_down / left_mouse_up / cursor_position for exactly these cases.
657
+ Ensure-Pointer
658
+ $action = (StrArg $A 'action' 'position').ToLowerInvariant()
659
+ if (@('move', 'down', 'up', 'position') -notcontains $action) {
660
+ Err 'bad_arg' ("action '" + (OneLine $action) + "' is not move|down|up|position")
661
+ }
662
+ $button = (StrArg $A 'button' 'left').ToLowerInvariant()
663
+ if (@('left', 'right', 'middle') -notcontains $button) { Err 'bad_arg' ("button '" + $button + "' is not left|right|middle") }
664
+ $exp = Expect-Of $A
665
+ $st = TickNow
666
+
667
+ if ($action -eq 'position') {
668
+ $p = Pointer-Pos
669
+ $v = Get-VirtScreen
670
+ $n = To-Norm $p.x $p.y $v
671
+ return [ordered]@{
672
+ action = 'position'
673
+ x = [int]$p.x; y = [int]$p.y
674
+ norm = [ordered]@{ x = [int]$n.x; y = [int]$n.y }
675
+ under = (Window-Under-Info $p.x $p.y)
676
+ screen = [ordered]@{ x = [int]$v.x; y = [int]$v.y; w = [int]$v.w; h = [int]$v.h }
677
+ ms = [Math]::Round((MsFrom $st), 1)
678
+ }
679
+ }
680
+
681
+ if ($action -eq 'move') {
682
+ $x = Req-Coord $A 'x' ''; $y = Req-Coord $A 'y' ''
683
+ Assert-In-Station $x $y
684
+ $g1 = Test-Pointer-Target $exp $x $y
685
+ if (-not $g1.pass) {
686
+ $script:W.stats.refused += 1
687
+ Err 'target_mismatch' ('pointer_mouse move refused without moving: ' + $g1.reason)
688
+ }
689
+ $start = Pointer-Pos
690
+ $dist = [Math]::Sqrt([Math]::Pow([double]($x - [int]$start.x), 2) + [Math]::Pow([double]($y - [int]$start.y), 2))
691
+ $g = Glide-Duration $dist (IntArg $A 'durationMs' 0)
692
+ if ($g.durationMs + 200 -gt (BudgetLeftMs)) {
693
+ Err 'deadline_exceeded' ('the glide (' + $g.durationMs + ' ms) does not fit the ' + (BudgetLeftMs) + ' ms left in this request')
694
+ }
695
+ Begin-Precision
696
+ [void](Send-Pointer-Path ([int]$start.x) ([int]$start.y) $x $y $g.durationMs 'ease-in-out' $false)
697
+ $at = Pointer-Pos
698
+ $g2 = Test-Pointer-Target $exp $x $y
699
+ $script:W.stats.actionsPerformed += 1
700
+ return [ordered]@{
701
+ action = 'move'
702
+ atCursor = [ordered]@{ x = [int]$at.x; y = [int]$at.y }
703
+ hover = (Window-Under-Info $at.x $at.y)
704
+ distance = [Math]::Round($dist, 1)
705
+ ms = [Math]::Round((MsFrom $st), 1)
706
+ gate = [ordered]@{ before = [bool]$g1.pass; after = [bool]$g2.pass }
707
+ }
708
+ }
709
+
710
+ # down / up act at the CURRENT cursor: the caller may have moved it in an earlier call, and the
711
+ # pair has to bracket whatever gesture happens in between. The declared window is still checked.
712
+ $p = Pointer-Pos
713
+ Assert-In-Station $p.x $p.y
714
+ $check = Test-Pointer-Target $exp $p.x $p.y
715
+ if (-not $check.pass) {
716
+ $script:W.stats.refused += 1
717
+ Err 'target_mismatch' ('pointer_mouse ' + $action + ' refused: ' + $check.reason)
718
+ }
719
+ $v = Get-VirtScreen
720
+ $n = To-Norm $p.x $p.y $v
721
+ Begin-Precision
722
+ $ok = if ($action -eq 'down') { [Native]::AbsButtonDown($n.x, $n.y, $button) } else { [Native]::AbsButtonUp($n.x, $n.y, $button) }
723
+ if ($ok -ne 1) { Err 'input_blocked' ('SendInput dropped the button-' + $action + ' event') }
724
+ $script:W.stats.actionsPerformed += 1
725
+ return [ordered]@{
726
+ action = $action
727
+ atCursor = [ordered]@{ x = [int]$p.x; y = [int]$p.y }
728
+ button = $button
729
+ under = $check.under
730
+ ms = [Math]::Round((MsFrom $st), 1)
731
+ }
732
+ }
733
+
734
+ function Cmd-WindowAction($A) {
735
+ # Window state is part of operating a desktop: a minimized window has no usable rect, and a model
736
+ # that cannot restore it is stuck with "坐标指向虚空". Only acts on windows already resolved by
737
+ # the worker (windowId), never on an hwnd the caller supplies.
738
+ $entry = Window-Entry (StrArg $A 'windowId' '')
739
+ $action = (StrArg $A 'action' 'activate').ToLowerInvariant()
740
+ if (@('activate', 'restore', 'minimize', 'maximize', 'move', 'resize') -notcontains $action) {
741
+ Err 'bad_arg' ("action '" + (OneLine $action) + "' is not activate|restore|minimize|maximize|move|resize")
742
+ }
743
+ $h = [IntPtr]$entry.hwnd
744
+ $st = TickNow
745
+ $before = $null
746
+ try { $before = [ordered]@{ iconic = [bool][Native]::IsIconic($h); rect = (RectOf ([System.Windows.Automation.AutomationElement]::FromHandle($h)).Current) } } catch { }
747
+ Begin-Precision
748
+ $applied = $false
749
+ switch ($action) {
750
+ 'activate' {
751
+ if ([Native]::IsIconic($h)) { [void][Native]::ShowWindow($h, 9); Start-Sleep -Milliseconds 90 }
752
+ $applied = [bool][Native]::SetForegroundWindow($h)
753
+ if (-not $applied) { Err 'activation_refused' 'the foreground window did not switch (another process holds the foreground lock); retry after a user input event' }
754
+ }
755
+ 'restore' { $applied = [bool][Native]::ShowWindow($h, 9) }
756
+ 'minimize' { $applied = [bool][Native]::ShowWindow($h, 6) }
757
+ 'maximize' { $applied = [bool][Native]::ShowWindow($h, 3) }
758
+ 'move' {
759
+ $r = Get-WindowRectOf $h
760
+ $x = IntArg $A 'x' ([int]$r.x); $y = IntArg $A 'y' ([int]$r.y)
761
+ Assert-In-Station $x $y
762
+ $applied = [bool][Native]::MoveWindow($h, [int]$x, [int]$y, [int]$r.w, [int]$r.h, $true)
763
+ }
764
+ 'resize' {
765
+ $r = Get-WindowRectOf $h
766
+ $w = IntArg $A 'w' ([int]$r.w); $hh = IntArg $A 'h' ([int]$r.h)
767
+ if ($w -lt 80 -or $hh -lt 60) { Err 'bad_arg' 'w/h must be at least 80x60' }
768
+ $applied = [bool][Native]::MoveWindow($h, [int]$r.x, [int]$r.y, [int]$w, [int]$hh, $true)
769
+ }
770
+ }
771
+ Start-Sleep -Milliseconds 90
772
+ $after = $null
773
+ try { $after = [ordered]@{ iconic = [bool][Native]::IsIconic($h); rect = (RectOf ([System.Windows.Automation.AutomationElement]::FromHandle($h)).Current); foreground = ([Native]::GetForegroundWindow() -eq $h) } } catch { }
774
+ if ($applied) { $script:W.stats.actionsPerformed += 1 }
775
+ return [ordered]@{
776
+ windowId = [string]$entry.id
777
+ action = $action
778
+ applied = [bool]$applied
779
+ before = $before
780
+ after = $after
781
+ ms = [Math]::Round((MsFrom $st), 1)
782
+ }
783
+ }
784
+
785
+ function Cmd-ClipboardRead($A) {
786
+ # Text only. Reading a bitmap or a file list would be a different promise (and a different
787
+ # privacy surface), so an unsupported shape reports empty instead of guessing.
788
+ $text = ''
789
+ $err = ''
790
+ for ($attempt = 0; $attempt -lt 3; $attempt++) {
791
+ try { $text = [string](Get-Clipboard -Raw -ErrorAction Stop); $err = ''; break } catch { $err = $_.Exception.Message; Start-Sleep -Milliseconds 60 }
792
+ }
793
+ if ($err -ne '') { Err 'clipboard_unavailable' ('Get-Clipboard failed three times (another app holds the clipboard): ' + (OneLine $err)) }
794
+ return [ordered]@{
795
+ text = (TruncStr $text 20000)
796
+ length = $text.Length
797
+ empty = [bool]($text -eq '')
798
+ truncated = [bool]($text.Length -gt 20000)
799
+ }
800
+ }
801
+
802
+ function Cmd-ClipboardWrite($A) {
803
+ $text = StrArg $A 'text' ''
804
+ if ($text.Length -gt 20000) { Err 'too_long' 'clipboard write accepts at most 20000 characters' }
805
+ $ok = $false
806
+ $err = ''
807
+ $value = if ($text -eq '') { [string[]]@() } else { [string[]]@($text) }
808
+ for ($attempt = 0; $attempt -lt 2 -and -not $ok; $attempt++) {
809
+ try { Set-Clipboard -Value $value; $ok = $true } catch { $err = $_.Exception.Message; Start-Sleep -Milliseconds 60 }
810
+ }
811
+ if (-not $ok) { Err 'clipboard_failed' ('Set-Clipboard threw twice (clipboard manager contention?): ' + (OneLine $err)) }
812
+ $script:W.stats.actionsPerformed += 1
813
+ return [ordered]@{ length = $text.Length; cleared = $false }
814
+ }
815
+
816
+ function Cmd-ClipboardClear($A) {
817
+ # Windows PowerShell 5.1's Set-Clipboard rejects an empty string ("Value cannot be null.
818
+ # Parameter name: text") but clears fine when handed an empty string array; an empty
819
+ # `write` takes the same path so "" means cleared rather than an error.
820
+ $ok = $false
821
+ $err = ''
822
+ for ($attempt = 0; $attempt -lt 2 -and -not $ok; $attempt++) {
823
+ try { Set-Clipboard -Value ([string[]]@()); $ok = $true } catch { $err = $_.Exception.Message; Start-Sleep -Milliseconds 60 }
824
+ }
825
+ if (-not $ok) { Err 'clipboard_failed' ('Set-Clipboard threw twice: ' + (OneLine $err)) }
826
+ $script:W.stats.actionsPerformed += 1
827
+ return [ordered]@{ cleared = $true; length = 0 }
828
+ }
829
+
830
+ function Get-WindowRectOf($h) {
831
+ # RECT is nested in the Native class, so its PowerShell type name is 'Native+RECT'; a bare
832
+ # `New-Object RECT` throws "找不到类型 [RECT]" (a plain, non-terminating-by-default cmdlet error
833
+ # that still aborted every move/resize).
834
+ $rect = New-Object 'Native+RECT'
835
+ $ok = [Native]::GetWindowRect($h, [ref]$rect)
836
+ if (-not $ok) { Err 'window_unreadable' 'GetWindowRect failed for this hwnd' }
837
+ return [ordered]@{ x = [int]$rect.Left; y = [int]$rect.Top; w = [int]($rect.Right - $rect.Left); h = [int]($rect.Bottom - $rect.Top) }
838
+ }
839
+
840
+