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,310 +1,310 @@
1
- # worker.ps1 -- the sidecar's line protocol: one JSON request in, one JSON response out.
2
- #
3
- # WHY A WORKER AND NOT A DIRECT CALL. Two constraints collide in this process model:
4
- # * UIA COM wants a single-threaded apartment (powershell.exe -STA), and
5
- # * the caller is a Node event loop that cannot block on a synchronous P/Invoke round trip
6
- # without stalling the host's own tool loop.
7
- # A long-lived STA process speaking one-line-request/one-line-response satisfies both. The same
8
- # shape was measured to work in the sibling competitor (Node registers tools, PS sidecar speaks JSON
9
- # lines) and TS-1 in findings.md chose it for that reason -- not for elegance.
10
- #
11
- # THE PROTOCOL IS THE PRODUCT'S UNDERPINNING, so it is deliberately boring and total:
12
- # request {"id":"<string>","action":"windows|click|type|focus|status", ...args}
13
- # response {"id":"<string>","ok":true,"result":{...}}
14
- # {"id":"<string>","ok":false,"error":"<message>","code":"<refusal-or-empty>"}
15
- #
16
- # THREE RULES THAT COST A RUN EACH IF BROKEN:
17
- # 1. NOTHING ELSE MAY TOUCH STDOUT. Add-Type, assembly loads and any stray Write-Output would
18
- # interleave with the protocol lines and the reader would parse rubbish. Every call whose
19
- # output is not the response is assigned to $null, and the response is written through
20
- # [Console]::Out directly so a redirected pipeline cannot swallow or pad it.
21
- # 2. A BAD REQUEST MUST STILL GET AN ANSWER. A null id is a bug on the caller's side; answering
22
- # with an error keeps the caller's request map from leaking a permanently-pending entry.
23
- # 3. STDOUT/STDIN ARE UTF-8. This host's ANSI codepage is GBK, and window titles plus typed text
24
- # are routinely non-ASCII: without this, Chinese text arrives as mojibake and every title match
25
- # silently fails -- the same class as the BOM-less .ps1 incident recorded in check-ps-bom.mjs.
26
- #
27
- # Exit is driven by stdin closing: the parent owns the lifetime, so the worker never decides to stop
28
- # on its own (an idle-exit would race the next request).
29
- $ErrorActionPreference = 'Stop'
30
- Set-StrictMode -Version 2.0
31
-
32
- try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { }
33
- try { [Console]::InputEncoding = [System.Text.Encoding]::UTF8 } catch { }
34
- $ProgressPreference = 'SilentlyContinue'
35
-
36
- $EngineRoot = $PSScriptRoot
37
- . (Join-Path $EngineRoot 'engine.ps1')
38
-
39
- function Write-Response([string]$Id, $Payload) {
40
- # Two-step because ConvertTo-Json is the only reliable serializer here, and because a response
41
- # that fails to serialize must still produce a protocol line rather than a silent stall.
42
- try {
43
- $line = $Payload | ConvertTo-Json -Depth 8 -Compress
44
- } catch {
45
- $line = '{"id":' + (ConvertTo-Json $Id -Compress) + ',"ok":false,"error":"response serialization failed: ' + ($_.Exception.Message -replace '"', "'") + '","code":""}'
46
- }
47
- [Console]::Out.WriteLine($line)
48
- [Console]::Out.Flush()
49
- }
50
-
51
- function Get-Arg($Bag, [string]$Name, $Default = $null) {
52
- if ($null -eq $Bag) { return $Default }
53
- if (-not ($Bag.PSObject.Properties.Name -contains $Name)) { return $Default }
54
- $v = $Bag.$Name
55
- if ($null -eq $v) { return $Default }
56
- return $v
57
- }
58
-
59
- # Announced once, on stderr, so the Node half can tell "the engine loaded" from "the process is up
60
- # but the engine is not". It is a diagnostic only: no protocol line is written before a request.
61
- [Console]::Error.WriteLine('wpm-worker ready engine=' + $EngineRoot)
62
-
63
- while ($true) {
64
- $line = [Console]::In.ReadLine()
65
- if ($null -eq $line) { break } # parent closed stdin: orderly shutdown
66
- if ($line.Trim() -eq '') { continue }
67
-
68
- $req = $null
69
- try { $req = $line | ConvertFrom-Json } catch {
70
- Write-Response '' @{ id = ''; ok = $false; error = 'request is not valid JSON: ' + $_.Exception.Message; code = '' }
71
- continue
72
- }
73
-
74
- $id = [string](Get-Arg $req 'id' '')
75
- $action = [string](Get-Arg $req 'action' '')
76
-
77
- try {
78
- switch ($action) {
79
- 'windows' {
80
- $list = @(Get-WpmWindowList)
81
- Write-Response $id @{ id = $id; ok = $true; result = @{ windows = $list; count = $list.Count } }
82
- }
83
- 'status' {
84
- $st = Get-WpmStatus
85
- Write-Response $id @{ id = $id; ok = $true; result = $st }
86
- }
87
- 'overlay' {
88
- # Product surface (task_54): the marker + Ctrl+Alt+Q. `on` starts/stops the overlay thread;
89
- # `x`/`y` move the marker to the point the engine just acted on (the Node half calls this
90
- # after a successful action; the marker auto-hides).
91
- . (Join-Path $EngineRoot 'overlay.ps1')
92
- $on = [bool](Get-Arg $req 'on' $true)
93
- if ($on) {
94
- $r = Start-WpmOverlay
95
- # The handshake now waits for the SAME flag the verdict reports (OverlayOn, not the hwnd)
96
- # and says 'starting' when the budget merely expired -- so it can stay short and honest.
97
- # Patience above a genuinely slow start lives in the Node half's placement retry loop,
98
- # where a stop condition exists; a worker-side sleep cannot name one.
99
- $st = Get-WpmOverlayState -WaitMs 2500
100
- } else {
101
- $r = Stop-WpmOverlay
102
- $st = $r.state
103
- }
104
- $mx = [int](Get-Arg $req 'x' -1)
105
- $my = [int](Get-Arg $req 'y' -1)
106
- if ($on -and $mx -ge 0 -and $my -ge 0) { [void](Set-WpmOverlayMarker -X $mx -Y $my) }
107
- Write-Response $id @{ id = $id; ok = $true; result = @{ start = $r; state = $st } }
108
- }
109
- 'marker' {
110
- . (Join-Path $EngineRoot 'overlay.ps1')
111
- $mx = [int](Get-Arg $req 'x' -1)
112
- $my = [int](Get-Arg $req 'y' -1)
113
- $hide = [bool](Get-Arg $req 'hide' $false)
114
- $r = Set-WpmOverlayMarker -X $mx -Y $my -Hide:$hide
115
- Write-Response $id @{ id = $id; ok = $true; result = $r }
116
- }
117
- 'pause' {
118
- # Owner control. Kept in the worker rather than in Node so the pause flag lives in exactly
119
- # one process: two copies would let a model bypass the pause by reaching whichever copy
120
- # forgot it.
121
- $on = [bool](Get-Arg $req 'on' $true)
122
- Set-WpmPaused $on 'owner'
123
- Write-Response $id @{ id = $id; ok = $true; result = @{ paused = $on } }
124
- }
125
- 'click' {
126
- # R3: takeover/keyInput travel as explicit request fields. The HOST half is what enforces the
127
- # settings gates (lib/index.js) and strips these fields when a gate is off, so a request that
128
- # arrives here with takeover=true was already authorised; the engine still re-checks the HUD.
129
- $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action click `
130
- -X ([int](Get-Arg $req 'x' -1)) -Y ([int](Get-Arg $req 'y' -1)) `
131
- -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
132
- -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
133
- -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
134
- -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
135
- -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
136
- -Space ([string](Get-Arg $req 'space' 'screen')) `
137
- -ShotId ([string](Get-Arg $req 'shotId' '')) `
138
- -Label ([int](Get-Arg $req 'label' 0)) `
139
- -SnapId ([string](Get-Arg $req 'snapId' '')) `
140
- -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
141
- -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000)) `
142
- -KeyInject:([bool](([string](Get-Arg $req 'keyInput' 'none')) -eq 'inject')) `
143
- -TakeoverArmMs ([int](Get-Arg $req 'takeoverArmMs' 800)) `
144
- -HudDoneMs ([int](Get-Arg $req 'hudDoneMs' 1500))
145
- Write-Response $id @{ id = $id; ok = $true; result = $r }
146
- }
147
- 'type' {
148
- # caretPosition is forwarded as given: the engine's ValidateSet is the single place that decides
149
- # what values exist, and coercing an unknown value to 'idle' here would launder a caller bug into
150
- # a silent behaviour change -- the write would go through at the wrong caret and look like a
151
- # successful default. A bad value must fail loudly, at the one layer that owns the vocabulary.
152
- $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action type `
153
- -Text ([string](Get-Arg $req 'text' '')) -ElementName ([string](Get-Arg $req 'elementName' '')) `
154
- -Label ([int](Get-Arg $req 'label' 0)) `
155
- -SnapId ([string](Get-Arg $req 'snapId' '')) `
156
- -CaretPosition ([string](Get-Arg $req 'caretPosition' 'idle')) `
157
- -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
158
- -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
159
- -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
160
- -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
161
- -Replace:([bool](Get-Arg $req 'replace' $false)) -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
162
- -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
163
- -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000)) `
164
- -KeyInject:([bool](([string](Get-Arg $req 'keyInput' 'none')) -eq 'inject')) `
165
- -TakeoverArmMs ([int](Get-Arg $req 'takeoverArmMs' 800)) `
166
- -HudDoneMs ([int](Get-Arg $req 'hudDoneMs' 1500))
167
- Write-Response $id @{ id = $id; ok = $true; result = $r }
168
- }
169
- 'focus' {
170
- $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action focus `
171
- -ElementName ([string](Get-Arg $req 'elementName' '')) `
172
- -Label ([int](Get-Arg $req 'label' 0)) `
173
- -SnapId ([string](Get-Arg $req 'snapId' '')) `
174
- -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
175
- -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
176
- -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
177
- -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
178
- -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
179
- -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
180
- -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000))
181
- Write-Response $id @{ id = $id; ok = $true; result = $r }
182
- }
183
- 'snapshot' {
184
- # Read path (0.5.0). The cap comes from the host settings (snapshotMaxElements), which sends it
185
- # as maxElements; interactableOnly defaults ON because the whole point of the frame is to be
186
- # small enough for a decision, not to be an exhaustive dump.
187
- $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action snapshot `
188
- -MaxElements ([int](Get-Arg $req 'maxElements' 300)) `
189
- -InteractableOnly ([bool](Get-Arg $req 'interactableOnly' $true)) `
190
- -SinceSnapId ([string](Get-Arg $req 'sinceSnapId' '')) `
191
- -Intent ([string](Get-Arg $req 'intent' ''))
192
- Write-Response $id @{ id = $id; ok = $true; result = $r }
193
- }
194
- 'screenshot' {
195
- $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action screenshot `
196
- -FullScreen ([bool](Get-Arg $req 'fullScreen' $false)) `
197
- -MaxWidth ([int](Get-Arg $req 'maxWidth' 0)) `
198
- -ShotsKeep ([int](Get-Arg $req 'shotsKeep' 10))
199
- Write-Response $id @{ id = $id; ok = $true; result = $r }
200
- }
201
- 'preview' {
202
- # Silent by construction: the marker is a click-through request and nothing is serialised into
203
- # any input queue. No proof window is produced -- there is no action to prove.
204
- $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action preview `
205
- -X ([int](Get-Arg $req 'x' -1)) -Y ([int](Get-Arg $req 'y' -1))
206
- Write-Response $id @{ id = $id; ok = $true; result = $r }
207
- }
208
- # ---- 0.7.0 desktop actions ---------------------------------------------------------------
209
- # These three are dispatched to Invoke-WpmDesktopAction rather than Invoke-WpmAction: they choose
210
- # no channel and cost no tier, so the door table has nothing to say about them. The SETTINGS gates
211
- # (appLaunchAllowed and its whitelist, the policy tier, the idle check) live in the host half and
212
- # have already been applied -- a request that reached here was authorised, exactly as with
213
- # takeover:true above, and the engine still re-checks what only it can see (a live hwnd, the real
214
- # window state after the call).
215
- 'launch' {
216
- $argv = Get-Arg $req 'args' @()
217
- if ($null -eq $argv) { $argv = @() }
218
- $allow = Get-Arg $req 'allowList' @()
219
- if ($null -eq $allow) { $allow = @() }
220
- $r = Invoke-WpmDesktopAction -Action launch `
221
- -Target ([string](Get-Arg $req 'target' '')) `
222
- -Arguments $argv `
223
- -WaitMs ([int](Get-Arg $req 'waitMs' 3000)) `
224
- -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
225
- -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
226
- -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
227
- -AppLaunchAllowed:([bool](Get-Arg $req 'launchAllowed' $false)) `
228
- -AppLaunchAllow ([string[]]@($allow))
229
- Write-Response $id @{ id = $id; ok = $true; result = $r }
230
- }
231
- 'clipboard' {
232
- $r = Invoke-WpmDesktopAction -Action clipboard `
233
- -Op ([string](Get-Arg $req 'op' 'read')) `
234
- -Format ([string](Get-Arg $req 'format' 'text')) `
235
- -Text ([string](Get-Arg $req 'text' '')) `
236
- -ShotId ([string](Get-Arg $req 'shotId' '')) `
237
- -MaxChars ([int](Get-Arg $req 'maxChars' 65536))
238
- Write-Response $id @{ id = $id; ok = $true; result = $r }
239
- }
240
- 'window' {
241
- $r = Invoke-WpmDesktopAction -Action window `
242
- -Hwnd ([string](Get-Arg $req 'hwnd' '')) `
243
- -Op ([string](Get-Arg $req 'op' '')) `
244
- -X ([int](Get-Arg $req 'x' 0)) -Y ([int](Get-Arg $req 'y' 0)) `
245
- -Width ([int](Get-Arg $req 'width' 0)) -Height ([int](Get-Arg $req 'height' 0))
246
- Write-Response $id @{ id = $id; ok = $true; result = $r }
247
- }
248
- 'hud' {
249
- # Product surface for tests and for the owner: start/stop the HUD on its own, so its window
250
- # properties can be measured without an action in flight (test/hud-test.ps1).
251
- . (Join-Path $EngineRoot 'hud.ps1')
252
- $on = [bool](Get-Arg $req 'on' $true)
253
- if ($on) {
254
- $r = Start-WpmHud -Action ([string](Get-Arg $req 'action' 'hud')) -MaxMs ([int](Get-Arg $req 'maxMs' 10000)) -ArmMs ([int](Get-Arg $req 'armMs' 0))
255
- $st = if ($r.state) { $r.state } else { Get-WpmHudState -WaitMs 100 }
256
- } else {
257
- $r = Stop-WpmHud
258
- $st = $r.state
259
- }
260
- Write-Response $id @{ id = $id; ok = $true; result = @{ hud = $st } }
261
- }
262
- 'takeover' {
263
- # Alias of 'hud' on purpose: the HUD IS the takeover precondition, so "takeover on" and "hud on"
264
- # are the same operation. Reported separately from the settings gate, which lives in the host.
265
- . (Join-Path $EngineRoot 'hud.ps1')
266
- $on = [bool](Get-Arg $req 'on' $true)
267
- if ($on) {
268
- $r = Start-WpmHud -Action 'takeover' -MaxMs ([int](Get-Arg $req 'maxMs' 10000)) -ArmMs 0
269
- $st = if ($r.state) { $r.state } else { Get-WpmHudState -WaitMs 100 }
270
- } else {
271
- $r = Stop-WpmHud
272
- $st = $r.state
273
- }
274
- Write-Response $id @{ id = $id; ok = $true; result = @{ hud = $st; stance = 'takeover requires the host setting takeoverAllowed; the HUD is the hard precondition' } }
275
- }
276
- 'abort' {
277
- # IMMEDIATE ANSWER, and it must not wait for anything. This is the host's signal -> worker path;
278
- # the FILE latch is the path the engine actually polls, so both are written here and the answer
279
- # goes out before any cleanup work could delay it.
280
- . (Join-Path $EngineRoot 'takeover.ps1')
281
- [WpmCtl]::TakeoverAbort = $true
282
- $latch = Get-WpmTakeoverLatchPath
283
- $written = $false
284
- try {
285
- $dir = Split-Path -Parent $latch
286
- if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
287
- Set-Content -LiteralPath $latch -Value 'abort' -Encoding ASCII -ErrorAction Stop
288
- $written = $true
289
- } catch { }
290
- Write-Response $id @{ id = $id; ok = $true; result = @{ aborted = $true; latch = $latch; latchWritten = $written; flagSet = [bool][WpmCtl]::TakeoverAbort } }
291
- }
292
- 'ping' {
293
- # `text` is echoed back verbatim. That is not decoration: the protocol's encoding is a real
294
- # failure surface on this host (ANSI codepage GBK), and an echo is the only way to prove a
295
- # non-ASCII string survives Node -> stdin -> PowerShell -> stdout -> Node unchanged. The tool
296
- # surface deliberately does not expose this action.
297
- $echo = [string](Get-Arg $req 'text' '')
298
- Write-Response $id @{ id = $id; ok = $true; result = @{ pong = $true; pid = $PID; text = $echo; len = $echo.Length } }
299
- }
300
- default {
301
- Write-Response $id @{ id = $id; ok = $false; error = "unknown action '$action'"; code = '' }
302
- }
303
- }
304
- } catch {
305
- # The action threw. The engine's own refusals are returned as ok=$true results carrying
306
- # `refusal`; reaching here means something outside the decision table broke, so it is reported
307
- # as an error with the exception text rather than folded into a refusal code it does not own.
308
- Write-Response $id @{ id = $id; ok = $false; error = $_.Exception.Message; code = '' }
309
- }
310
- }
1
+ # worker.ps1 -- the sidecar's line protocol: one JSON request in, one JSON response out.
2
+ #
3
+ # WHY A WORKER AND NOT A DIRECT CALL. Two constraints collide in this process model:
4
+ # * UIA COM wants a single-threaded apartment (powershell.exe -STA), and
5
+ # * the caller is a Node event loop that cannot block on a synchronous P/Invoke round trip
6
+ # without stalling the host's own tool loop.
7
+ # A long-lived STA process speaking one-line-request/one-line-response satisfies both. The same
8
+ # shape was measured to work in the sibling competitor (Node registers tools, PS sidecar speaks JSON
9
+ # lines) and TS-1 in findings.md chose it for that reason -- not for elegance.
10
+ #
11
+ # THE PROTOCOL IS THE PRODUCT'S UNDERPINNING, so it is deliberately boring and total:
12
+ # request {"id":"<string>","action":"windows|click|type|focus|status", ...args}
13
+ # response {"id":"<string>","ok":true,"result":{...}}
14
+ # {"id":"<string>","ok":false,"error":"<message>","code":"<refusal-or-empty>"}
15
+ #
16
+ # THREE RULES THAT COST A RUN EACH IF BROKEN:
17
+ # 1. NOTHING ELSE MAY TOUCH STDOUT. Add-Type, assembly loads and any stray Write-Output would
18
+ # interleave with the protocol lines and the reader would parse rubbish. Every call whose
19
+ # output is not the response is assigned to $null, and the response is written through
20
+ # [Console]::Out directly so a redirected pipeline cannot swallow or pad it.
21
+ # 2. A BAD REQUEST MUST STILL GET AN ANSWER. A null id is a bug on the caller's side; answering
22
+ # with an error keeps the caller's request map from leaking a permanently-pending entry.
23
+ # 3. STDOUT/STDIN ARE UTF-8. This host's ANSI codepage is GBK, and window titles plus typed text
24
+ # are routinely non-ASCII: without this, Chinese text arrives as mojibake and every title match
25
+ # silently fails -- the same class as the BOM-less .ps1 incident recorded in check-ps-bom.mjs.
26
+ #
27
+ # Exit is driven by stdin closing: the parent owns the lifetime, so the worker never decides to stop
28
+ # on its own (an idle-exit would race the next request).
29
+ $ErrorActionPreference = 'Stop'
30
+ Set-StrictMode -Version 2.0
31
+
32
+ try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { }
33
+ try { [Console]::InputEncoding = [System.Text.Encoding]::UTF8 } catch { }
34
+ $ProgressPreference = 'SilentlyContinue'
35
+
36
+ $EngineRoot = $PSScriptRoot
37
+ . (Join-Path $EngineRoot 'engine.ps1')
38
+
39
+ function Write-Response([string]$Id, $Payload) {
40
+ # Two-step because ConvertTo-Json is the only reliable serializer here, and because a response
41
+ # that fails to serialize must still produce a protocol line rather than a silent stall.
42
+ try {
43
+ $line = $Payload | ConvertTo-Json -Depth 8 -Compress
44
+ } catch {
45
+ $line = '{"id":' + (ConvertTo-Json $Id -Compress) + ',"ok":false,"error":"response serialization failed: ' + ($_.Exception.Message -replace '"', "'") + '","code":""}'
46
+ }
47
+ [Console]::Out.WriteLine($line)
48
+ [Console]::Out.Flush()
49
+ }
50
+
51
+ function Get-Arg($Bag, [string]$Name, $Default = $null) {
52
+ if ($null -eq $Bag) { return $Default }
53
+ if (-not ($Bag.PSObject.Properties.Name -contains $Name)) { return $Default }
54
+ $v = $Bag.$Name
55
+ if ($null -eq $v) { return $Default }
56
+ return $v
57
+ }
58
+
59
+ # Announced once, on stderr, so the Node half can tell "the engine loaded" from "the process is up
60
+ # but the engine is not". It is a diagnostic only: no protocol line is written before a request.
61
+ [Console]::Error.WriteLine('wpm-worker ready engine=' + $EngineRoot)
62
+
63
+ while ($true) {
64
+ $line = [Console]::In.ReadLine()
65
+ if ($null -eq $line) { break } # parent closed stdin: orderly shutdown
66
+ if ($line.Trim() -eq '') { continue }
67
+
68
+ $req = $null
69
+ try { $req = $line | ConvertFrom-Json } catch {
70
+ Write-Response '' @{ id = ''; ok = $false; error = 'request is not valid JSON: ' + $_.Exception.Message; code = '' }
71
+ continue
72
+ }
73
+
74
+ $id = [string](Get-Arg $req 'id' '')
75
+ $action = [string](Get-Arg $req 'action' '')
76
+
77
+ try {
78
+ switch ($action) {
79
+ 'windows' {
80
+ $list = @(Get-WpmWindowList)
81
+ Write-Response $id @{ id = $id; ok = $true; result = @{ windows = $list; count = $list.Count } }
82
+ }
83
+ 'status' {
84
+ $st = Get-WpmStatus
85
+ Write-Response $id @{ id = $id; ok = $true; result = $st }
86
+ }
87
+ 'overlay' {
88
+ # Product surface (task_54): the marker + Ctrl+Alt+Q. `on` starts/stops the overlay thread;
89
+ # `x`/`y` move the marker to the point the engine just acted on (the Node half calls this
90
+ # after a successful action; the marker auto-hides).
91
+ . (Join-Path $EngineRoot 'overlay.ps1')
92
+ $on = [bool](Get-Arg $req 'on' $true)
93
+ if ($on) {
94
+ $r = Start-WpmOverlay
95
+ # The handshake now waits for the SAME flag the verdict reports (OverlayOn, not the hwnd)
96
+ # and says 'starting' when the budget merely expired -- so it can stay short and honest.
97
+ # Patience above a genuinely slow start lives in the Node half's placement retry loop,
98
+ # where a stop condition exists; a worker-side sleep cannot name one.
99
+ $st = Get-WpmOverlayState -WaitMs 2500
100
+ } else {
101
+ $r = Stop-WpmOverlay
102
+ $st = $r.state
103
+ }
104
+ $mx = [int](Get-Arg $req 'x' -1)
105
+ $my = [int](Get-Arg $req 'y' -1)
106
+ if ($on -and $mx -ge 0 -and $my -ge 0) { [void](Set-WpmOverlayMarker -X $mx -Y $my) }
107
+ Write-Response $id @{ id = $id; ok = $true; result = @{ start = $r; state = $st } }
108
+ }
109
+ 'marker' {
110
+ . (Join-Path $EngineRoot 'overlay.ps1')
111
+ $mx = [int](Get-Arg $req 'x' -1)
112
+ $my = [int](Get-Arg $req 'y' -1)
113
+ $hide = [bool](Get-Arg $req 'hide' $false)
114
+ $r = Set-WpmOverlayMarker -X $mx -Y $my -Hide:$hide
115
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
116
+ }
117
+ 'pause' {
118
+ # Owner control. Kept in the worker rather than in Node so the pause flag lives in exactly
119
+ # one process: two copies would let a model bypass the pause by reaching whichever copy
120
+ # forgot it.
121
+ $on = [bool](Get-Arg $req 'on' $true)
122
+ Set-WpmPaused $on 'owner'
123
+ Write-Response $id @{ id = $id; ok = $true; result = @{ paused = $on } }
124
+ }
125
+ 'click' {
126
+ # R3: takeover/keyInput travel as explicit request fields. The HOST half is what enforces the
127
+ # settings gates (lib/index.js) and strips these fields when a gate is off, so a request that
128
+ # arrives here with takeover=true was already authorised; the engine still re-checks the HUD.
129
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action click `
130
+ -X ([int](Get-Arg $req 'x' -1)) -Y ([int](Get-Arg $req 'y' -1)) `
131
+ -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
132
+ -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
133
+ -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
134
+ -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
135
+ -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
136
+ -Space ([string](Get-Arg $req 'space' 'screen')) `
137
+ -ShotId ([string](Get-Arg $req 'shotId' '')) `
138
+ -Label ([int](Get-Arg $req 'label' 0)) `
139
+ -SnapId ([string](Get-Arg $req 'snapId' '')) `
140
+ -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
141
+ -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000)) `
142
+ -KeyInject:([bool](([string](Get-Arg $req 'keyInput' 'none')) -eq 'inject')) `
143
+ -TakeoverArmMs ([int](Get-Arg $req 'takeoverArmMs' 800)) `
144
+ -HudDoneMs ([int](Get-Arg $req 'hudDoneMs' 1500))
145
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
146
+ }
147
+ 'type' {
148
+ # caretPosition is forwarded as given: the engine's ValidateSet is the single place that decides
149
+ # what values exist, and coercing an unknown value to 'idle' here would launder a caller bug into
150
+ # a silent behaviour change -- the write would go through at the wrong caret and look like a
151
+ # successful default. A bad value must fail loudly, at the one layer that owns the vocabulary.
152
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action type `
153
+ -Text ([string](Get-Arg $req 'text' '')) -ElementName ([string](Get-Arg $req 'elementName' '')) `
154
+ -Label ([int](Get-Arg $req 'label' 0)) `
155
+ -SnapId ([string](Get-Arg $req 'snapId' '')) `
156
+ -CaretPosition ([string](Get-Arg $req 'caretPosition' 'idle')) `
157
+ -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
158
+ -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
159
+ -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
160
+ -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
161
+ -Replace:([bool](Get-Arg $req 'replace' $false)) -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
162
+ -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
163
+ -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000)) `
164
+ -KeyInject:([bool](([string](Get-Arg $req 'keyInput' 'none')) -eq 'inject')) `
165
+ -TakeoverArmMs ([int](Get-Arg $req 'takeoverArmMs' 800)) `
166
+ -HudDoneMs ([int](Get-Arg $req 'hudDoneMs' 1500))
167
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
168
+ }
169
+ 'focus' {
170
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action focus `
171
+ -ElementName ([string](Get-Arg $req 'elementName' '')) `
172
+ -Label ([int](Get-Arg $req 'label' 0)) `
173
+ -SnapId ([string](Get-Arg $req 'snapId' '')) `
174
+ -SettleMs ([int](Get-Arg $req 'settleMs' 350)) `
175
+ -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
176
+ -RequiredTier ([string](Get-Arg $req 'requiredTier' 'quiet')) `
177
+ -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
178
+ -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
179
+ -Takeover:([bool](Get-Arg $req 'takeover' $false)) `
180
+ -TakeoverMaxMs ([int](Get-Arg $req 'takeoverMaxMs' 10000))
181
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
182
+ }
183
+ 'snapshot' {
184
+ # Read path (0.5.0). The cap comes from the host settings (snapshotMaxElements), which sends it
185
+ # as maxElements; interactableOnly defaults ON because the whole point of the frame is to be
186
+ # small enough for a decision, not to be an exhaustive dump.
187
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action snapshot `
188
+ -MaxElements ([int](Get-Arg $req 'maxElements' 300)) `
189
+ -InteractableOnly ([bool](Get-Arg $req 'interactableOnly' $true)) `
190
+ -SinceSnapId ([string](Get-Arg $req 'sinceSnapId' '')) `
191
+ -Intent ([string](Get-Arg $req 'intent' ''))
192
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
193
+ }
194
+ 'screenshot' {
195
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action screenshot `
196
+ -FullScreen ([bool](Get-Arg $req 'fullScreen' $false)) `
197
+ -MaxWidth ([int](Get-Arg $req 'maxWidth' 0)) `
198
+ -ShotsKeep ([int](Get-Arg $req 'shotsKeep' 10))
199
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
200
+ }
201
+ 'preview' {
202
+ # Silent by construction: the marker is a click-through request and nothing is serialised into
203
+ # any input queue. No proof window is produced -- there is no action to prove.
204
+ $r = Invoke-WpmAction -Hwnd ([string](Get-Arg $req 'hwnd' '')) -Action preview `
205
+ -X ([int](Get-Arg $req 'x' -1)) -Y ([int](Get-Arg $req 'y' -1))
206
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
207
+ }
208
+ # ---- 0.7.0 desktop actions ---------------------------------------------------------------
209
+ # These three are dispatched to Invoke-WpmDesktopAction rather than Invoke-WpmAction: they choose
210
+ # no channel and cost no tier, so the door table has nothing to say about them. The SETTINGS gates
211
+ # (appLaunchAllowed and its whitelist, the policy tier, the idle check) live in the host half and
212
+ # have already been applied -- a request that reached here was authorised, exactly as with
213
+ # takeover:true above, and the engine still re-checks what only it can see (a live hwnd, the real
214
+ # window state after the call).
215
+ 'launch' {
216
+ $argv = Get-Arg $req 'args' @()
217
+ if ($null -eq $argv) { $argv = @() }
218
+ $allow = Get-Arg $req 'allowList' @()
219
+ if ($null -eq $allow) { $allow = @() }
220
+ $r = Invoke-WpmDesktopAction -Action launch `
221
+ -Target ([string](Get-Arg $req 'target' '')) `
222
+ -Arguments $argv `
223
+ -WaitMs ([int](Get-Arg $req 'waitMs' 3000)) `
224
+ -Policy ([string](Get-Arg $req 'policy' 'balanced')) `
225
+ -PolicyIdleMs ([int](Get-Arg $req 'policyIdleMs' 3000)) `
226
+ -ForceUserActive:([bool](Get-Arg $req 'forceUserActive' $false)) `
227
+ -AppLaunchAllowed:([bool](Get-Arg $req 'launchAllowed' $false)) `
228
+ -AppLaunchAllow ([string[]]@($allow))
229
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
230
+ }
231
+ 'clipboard' {
232
+ $r = Invoke-WpmDesktopAction -Action clipboard `
233
+ -Op ([string](Get-Arg $req 'op' 'read')) `
234
+ -Format ([string](Get-Arg $req 'format' 'text')) `
235
+ -Text ([string](Get-Arg $req 'text' '')) `
236
+ -ShotId ([string](Get-Arg $req 'shotId' '')) `
237
+ -MaxChars ([int](Get-Arg $req 'maxChars' 65536))
238
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
239
+ }
240
+ 'window' {
241
+ $r = Invoke-WpmDesktopAction -Action window `
242
+ -Hwnd ([string](Get-Arg $req 'hwnd' '')) `
243
+ -Op ([string](Get-Arg $req 'op' '')) `
244
+ -X ([int](Get-Arg $req 'x' 0)) -Y ([int](Get-Arg $req 'y' 0)) `
245
+ -Width ([int](Get-Arg $req 'width' 0)) -Height ([int](Get-Arg $req 'height' 0))
246
+ Write-Response $id @{ id = $id; ok = $true; result = $r }
247
+ }
248
+ 'hud' {
249
+ # Product surface for tests and for the owner: start/stop the HUD on its own, so its window
250
+ # properties can be measured without an action in flight (test/hud-test.ps1).
251
+ . (Join-Path $EngineRoot 'hud.ps1')
252
+ $on = [bool](Get-Arg $req 'on' $true)
253
+ if ($on) {
254
+ $r = Start-WpmHud -Action ([string](Get-Arg $req 'action' 'hud')) -MaxMs ([int](Get-Arg $req 'maxMs' 10000)) -ArmMs ([int](Get-Arg $req 'armMs' 0))
255
+ $st = if ($r.state) { $r.state } else { Get-WpmHudState -WaitMs 100 }
256
+ } else {
257
+ $r = Stop-WpmHud
258
+ $st = $r.state
259
+ }
260
+ Write-Response $id @{ id = $id; ok = $true; result = @{ hud = $st } }
261
+ }
262
+ 'takeover' {
263
+ # Alias of 'hud' on purpose: the HUD IS the takeover precondition, so "takeover on" and "hud on"
264
+ # are the same operation. Reported separately from the settings gate, which lives in the host.
265
+ . (Join-Path $EngineRoot 'hud.ps1')
266
+ $on = [bool](Get-Arg $req 'on' $true)
267
+ if ($on) {
268
+ $r = Start-WpmHud -Action 'takeover' -MaxMs ([int](Get-Arg $req 'maxMs' 10000)) -ArmMs 0
269
+ $st = if ($r.state) { $r.state } else { Get-WpmHudState -WaitMs 100 }
270
+ } else {
271
+ $r = Stop-WpmHud
272
+ $st = $r.state
273
+ }
274
+ Write-Response $id @{ id = $id; ok = $true; result = @{ hud = $st; stance = 'takeover requires the host setting takeoverAllowed; the HUD is the hard precondition' } }
275
+ }
276
+ 'abort' {
277
+ # IMMEDIATE ANSWER, and it must not wait for anything. This is the host's signal -> worker path;
278
+ # the FILE latch is the path the engine actually polls, so both are written here and the answer
279
+ # goes out before any cleanup work could delay it.
280
+ . (Join-Path $EngineRoot 'takeover.ps1')
281
+ [WpmCtl]::TakeoverAbort = $true
282
+ $latch = Get-WpmTakeoverLatchPath
283
+ $written = $false
284
+ try {
285
+ $dir = Split-Path -Parent $latch
286
+ if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
287
+ Set-Content -LiteralPath $latch -Value 'abort' -Encoding ASCII -ErrorAction Stop
288
+ $written = $true
289
+ } catch { }
290
+ Write-Response $id @{ id = $id; ok = $true; result = @{ aborted = $true; latch = $latch; latchWritten = $written; flagSet = [bool][WpmCtl]::TakeoverAbort } }
291
+ }
292
+ 'ping' {
293
+ # `text` is echoed back verbatim. That is not decoration: the protocol's encoding is a real
294
+ # failure surface on this host (ANSI codepage GBK), and an echo is the only way to prove a
295
+ # non-ASCII string survives Node -> stdin -> PowerShell -> stdout -> Node unchanged. The tool
296
+ # surface deliberately does not expose this action.
297
+ $echo = [string](Get-Arg $req 'text' '')
298
+ Write-Response $id @{ id = $id; ok = $true; result = @{ pong = $true; pid = $PID; text = $echo; len = $echo.Length } }
299
+ }
300
+ default {
301
+ Write-Response $id @{ id = $id; ok = $false; error = "unknown action '$action'"; code = '' }
302
+ }
303
+ }
304
+ } catch {
305
+ # The action threw. The engine's own refusals are returned as ok=$true results carrying
306
+ # `refusal`; reaching here means something outside the decision table broke, so it is reported
307
+ # as an error with the exception text rather than folded into a refusal code it does not own.
308
+ Write-Response $id @{ id = $id; ok = $false; error = $_.Exception.Message; code = '' }
309
+ }
310
+ }