dsh-windows-parallel-mcp 0.1.6 → 0.3.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 (48) hide show
  1. package/CHANGELOG.de.md +374 -0
  2. package/CHANGELOG.es.md +374 -0
  3. package/CHANGELOG.fr.md +374 -0
  4. package/CHANGELOG.it.md +374 -0
  5. package/CHANGELOG.ja.md +374 -0
  6. package/CHANGELOG.ko.md +374 -0
  7. package/CHANGELOG.md +116 -1
  8. package/CHANGELOG.pt.md +374 -0
  9. package/CHANGELOG.ru.md +374 -0
  10. package/CHANGELOG.zh.md +374 -0
  11. package/INSTALL.de.md +126 -0
  12. package/INSTALL.es.md +126 -0
  13. package/INSTALL.fr.md +126 -0
  14. package/INSTALL.it.md +126 -0
  15. package/INSTALL.ja.md +126 -0
  16. package/INSTALL.ko.md +126 -0
  17. package/INSTALL.md +49 -11
  18. package/INSTALL.pt.md +126 -0
  19. package/INSTALL.ru.md +126 -0
  20. package/INSTALL.zh.md +126 -0
  21. package/README.de.md +275 -0
  22. package/README.es.md +275 -0
  23. package/README.fr.md +275 -0
  24. package/README.it.md +275 -0
  25. package/README.ja.md +275 -0
  26. package/README.ko.md +275 -0
  27. package/README.md +114 -24
  28. package/README.pt.md +275 -0
  29. package/README.ru.md +275 -0
  30. package/README.zh.md +275 -0
  31. package/docs/refusals.md +17 -10
  32. package/docs/takeover.md +129 -0
  33. package/dsh.plugin.json +3 -3
  34. package/lib/config.js +57 -2
  35. package/lib/host-tools.js +32 -2
  36. package/lib/index.js +149 -14
  37. package/lib/proof-window.mjs +24 -3
  38. package/package.json +38 -4
  39. package/src/engine/decide.ps1 +110 -57
  40. package/src/engine/engine.ps1 +201 -8
  41. package/src/engine/hud.ps1 +411 -0
  42. package/src/engine/input-inject.ps1 +176 -0
  43. package/src/engine/overlay.ps1 +7 -1
  44. package/src/engine/takeover.ps1 +144 -0
  45. package/src/engine/win.ps1 +18 -1
  46. package/src/engine/worker.ps1 +63 -4
  47. package/src/schema/tools.json +57 -13
  48. package/types/index.d.ts +68 -0
@@ -0,0 +1,411 @@
1
+ # hud.ps1 -- the R3 safety surface: a three-phase window that says what the engine is doing with the
2
+ # owner's mouse/keyboard/focus, offers a real stop button, and owns the global abort chord. (spec.md §2)
3
+ #
4
+ # WHY THIS IS A HARD PREREQUISITE RATHER THAN A NICETY. R3 lets the engine move the real cursor and type
5
+ # into the foreground window. Both are invisible cost the owner pays; a takeover without a surface would
6
+ # mean the pointer moves and text appears with no way to tell "an agent did that" from "the machine did
7
+ # something". So: no HUD, no takeover -- enforced twice (engine refuses before any primitive call;
8
+ # scripts/check-takeover-path.mjs G3 asserts the call order is structural).
9
+ #
10
+ # ARCHITECTURE IS BORROWED, DELIBERATELY: an STA runspace + WPF + a DispatcherTimer pump that reads and
11
+ # writes ONLY [WpmCtl] fields. overlay.ps1 measured why (overlay.ps1:163-176): a cross-thread
12
+ # Dispatcher.Invoke of a PowerShell scriptblock cost 1818ms and sometimes never returned, because the
13
+ # pump thread is already inside Dispatcher.Run(). Three volatile fields cost nothing.
14
+ #
15
+ # TWO MEASURED DETAILS THAT CHANGED THE DESIGN (findings §G6, scripts/probe-hittest-children.ps1):
16
+ # * the HwndSource hook DOES receive WM_NCHITTEST but its return value does not reach hit-testing
17
+ # (empty point still answered HTCLIENT). So click-through is done with a WNDPROC subclass instead:
18
+ # HTTRANSPARENT outside the button's rect, CallWindowProc inside it. Measured after the change:
19
+ # empty point -> -1 and WindowFromPoint no longer returns this window; button point -> 1.
20
+ # * WS_EX_NOACTIVATE + ShowActivated=false is what keeps the HUD from stealing the foreground while
21
+ # the button stays clickable (measured: GetForegroundWindow unchanged across Show()).
22
+ #
23
+ # NO WATCHDOG, NO AUTO-CLOSE LOOP. The engine owns the lifecycle: it starts the HUD for one action and
24
+ # stops it in its own finally block. A window that decided on its own to shut down mid-action would be a
25
+ # second owner of the abort decision, which is exactly the bug the pause-flag comments elsewhere warn
26
+ # about.
27
+
28
+ Set-StrictMode -Version 2.0
29
+
30
+ if (-not ('WpmCtl' -as [type])) {
31
+ . (Join-Path $PSScriptRoot 'win.ps1')
32
+ }
33
+
34
+ if (-not (Get-Variable -Name WpmHudRunspace -Scope Script -ErrorAction SilentlyContinue)) {
35
+ $script:WpmHudRunspace = $null
36
+ $script:WpmHudPowerShell = $null
37
+ $script:WpmHudHandle = $null
38
+ }
39
+ $script:WpmHudHotkeyId = 0xB002
40
+
41
+ # Ctrl+Alt+Q is the PAUSE key and is already owned on this desktop; the abort chord needs its own space.
42
+ # The candidate table exists for the same reason overlay.ps1 has one: whatever registers is reported, so
43
+ # the owner reads the key that actually works instead of the one the docs promise.
44
+ $script:WpmAbortChords = @(
45
+ @{ label = 'Ctrl+Alt+X'; mods = 0x0003; vk = 0x58 },
46
+ @{ label = 'Ctrl+Alt+Z'; mods = 0x0003; vk = 0x5A },
47
+ @{ label = 'Ctrl+Alt+C'; mods = 0x0003; vk = 0x43 },
48
+ @{ label = 'Ctrl+Alt+V'; mods = 0x0003; vk = 0x56 },
49
+ @{ label = 'Ctrl+Alt+B'; mods = 0x0003; vk = 0x42 },
50
+ @{ label = 'Ctrl+Alt+N'; mods = 0x0003; vk = 0x4E },
51
+ @{ label = 'Ctrl+Shift+X'; mods = 0x0006; vk = 0x58 },
52
+ @{ label = 'Ctrl+Alt+Shift+X'; mods = 0x0007; vk = 0x58 }
53
+ )
54
+
55
+ if (-not ('WpmHud' -as [type])) {
56
+ Add-Type -TypeDefinition @'
57
+ using System;
58
+ using System.Runtime.InteropServices;
59
+
60
+ public static class WpmHud
61
+ {
62
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
63
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
64
+ public delegate IntPtr WndProc(IntPtr h, uint m, IntPtr w, IntPtr l);
65
+
66
+ [DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
67
+ [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
68
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
69
+ [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")] public static extern IntPtr SetWindowLongPtr(IntPtr h, int idx, IntPtr proc);
70
+ [DllImport("user32.dll")] public static extern IntPtr CallWindowProc(IntPtr prev, IntPtr h, uint m, IntPtr w, IntPtr l);
71
+ [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr h, uint msg, IntPtr w, IntPtr l);
72
+
73
+ public const uint WM_NCHITTEST = 0x0084;
74
+ public const int HTTRANSPARENT = -1;
75
+ public const int SM_CXSCREEN = 0;
76
+ public const int SM_CYSCREEN = 1;
77
+
78
+ static IntPtr prev = IntPtr.Zero;
79
+ static RECT zone;
80
+ static WndProc keepAlive;
81
+ public static int HitCount = 0;
82
+
83
+ // Click-through outside the control zone, WPF's own hit-testing inside it. Installed AFTER Show()
84
+ // so the button's physical rect is already known.
85
+ public static bool InstallHitZone(IntPtr h, int left, int top, int right, int bottom) {
86
+ zone = new RECT(); zone.Left = left; zone.Top = top; zone.Right = right; zone.Bottom = bottom;
87
+ keepAlive = new WndProc(Proc);
88
+ prev = SetWindowLongPtr(h, -4, Marshal.GetFunctionPointerForDelegate(keepAlive));
89
+ return prev != IntPtr.Zero;
90
+ }
91
+ static IntPtr Proc(IntPtr h, uint m, IntPtr w, IntPtr l) {
92
+ if (m == WM_NCHITTEST) {
93
+ HitCount++;
94
+ long packed = (long)l;
95
+ int x = (short)(packed & 0xFFFF);
96
+ int y = (short)((packed >> 16) & 0xFFFF);
97
+ if (!(x >= zone.Left && x <= zone.Right && y >= zone.Top && y <= zone.Bottom)) return new IntPtr(HTTRANSPARENT);
98
+ }
99
+ return CallWindowProc(prev, h, m, w, l);
100
+ }
101
+ public static IntPtr HitTest(IntPtr h, int x, int y) {
102
+ IntPtr lp = (IntPtr)((y << 16) | (x & 0xFFFF));
103
+ return SendMessage(h, WM_NCHITTEST, IntPtr.Zero, lp);
104
+ }
105
+ public static IntPtr WindowAt(int x, int y) { POINT p; p.X = x; p.Y = y; return WindowFromPoint(p); }
106
+ }
107
+ '@
108
+ }
109
+
110
+ $script:WpmHudBody = @'
111
+ param([string]$Action, [int]$MaxMs, [int]$ArmMs, [int]$HotkeyId, [object[]]$Chords)
112
+ try {
113
+ Add-Type -AssemblyName PresentationFramework
114
+ Add-Type -AssemblyName PresentationCore
115
+ Add-Type -AssemblyName WindowsBase
116
+
117
+ $win = [System.Windows.Window]::new()
118
+ $win.Title = 'WpmHud'
119
+ $win.WindowStyle = [System.Windows.WindowStyle]::None
120
+ $win.ResizeMode = [System.Windows.ResizeMode]::NoResize
121
+ $win.ShowActivated = $false # WPF half of NOACTIVATE: Show() must not steal the foreground
122
+ $win.ShowInTaskbar = $false
123
+ $win.Topmost = $true
124
+ $win.Width = 470.0
125
+ $win.Height = 104.0
126
+ $win.Left = -3000.0
127
+ $win.Top = -3000.0
128
+ $win.WindowStartupLocation = [System.Windows.WindowStartupLocation]::Manual
129
+ # The surface colour is a PHASE SIGNAL, not decoration (see the pump). It starts on the arming tint so a
130
+ # window that somehow never gets a pump tick is still telling the truth about what it is waiting for.
131
+ $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 44, 12))
132
+ $win.Opacity = 0.94
133
+
134
+ # THREE COLUMNS: a 5px accent bar, the text, the button. The bar is the second channel for the phase
135
+ # colour, because a tinted background alone is easy to miss when the window is 470x104 at the screen edge
136
+ # and the owner is looking at the target window rather than at the HUD.
137
+ $grid = [System.Windows.Controls.Grid]::new()
138
+ $grid.Margin = [System.Windows.Thickness]::new(0.0, 0.0, 14.0, 0.0)
139
+ $colBar = [System.Windows.Controls.ColumnDefinition]::new()
140
+ $colBar.Width = [System.Windows.GridLength]::new(5.0)
141
+ $colA = [System.Windows.Controls.ColumnDefinition]::new()
142
+ $colA.Width = [System.Windows.GridLength]::new(1.0, [System.Windows.GridUnitType]::Star)
143
+ $colB = [System.Windows.Controls.ColumnDefinition]::new()
144
+ $colB.Width = [System.Windows.GridLength]::Auto
145
+ [void]$grid.ColumnDefinitions.Add($colBar)
146
+ [void]$grid.ColumnDefinitions.Add($colA)
147
+ [void]$grid.ColumnDefinitions.Add($colB)
148
+
149
+ $bar = [System.Windows.Controls.Border]::new()
150
+ $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(240, 173, 24))
151
+ [System.Windows.Controls.Grid]::SetColumn($bar, 0)
152
+ [void]$grid.Children.Add($bar)
153
+
154
+ $tb = [System.Windows.Controls.TextBlock]::new()
155
+ $tb.TextWrapping = [System.Windows.TextWrapping]::Wrap
156
+ $tb.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
157
+ $tb.Foreground = [System.Windows.Media.Brushes]::White
158
+ $tb.FontSize = 13.0
159
+ $tb.Text = 'WPM'
160
+ $tb.Margin = [System.Windows.Thickness]::new(14.0, 10.0, 10.0, 10.0)
161
+ [System.Windows.Controls.Grid]::SetColumn($tb, 1)
162
+ [void]$grid.Children.Add($tb)
163
+
164
+ $btn = [System.Windows.Controls.Button]::new()
165
+ $btn.Content = '中止'
166
+ $btn.Width = 92.0
167
+ $btn.Height = 40.0
168
+ $btn.FontSize = 13.0
169
+ $btn.Focusable = $false
170
+ $btn.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
171
+ $btn.Margin = [System.Windows.Thickness]::new(0.0, 0.0, 0.0, 0.0)
172
+ [System.Windows.Controls.Grid]::SetColumn($btn, 2)
173
+ [void]$grid.Children.Add($btn)
174
+
175
+ $win.Content = $grid
176
+ $win.Show()
177
+ $hwnd = (New-Object System.Windows.Interop.WindowInteropHelper($win)).Handle
178
+ [WpmCtl]::HudHwnd = [int64]$hwnd
179
+
180
+ # Topmost + no-activate, explicitly (the measured promise is the ex-style read-back, not the look).
181
+ $bits = [WpmWin]::WS_EX_TOPMOST -bor [WpmWin]::WS_EX_NOACTIVATE
182
+ [void][WpmWin]::AddExStyles($hwnd, $bits)
183
+
184
+ # Physical placement bottom-right. WPF's Left/Top are device independent and did not agree with this
185
+ # desktop at 150% (overlay.ps1 recorded marker at (303,263) for a target of (470,410)), so placement
186
+ # is SetWindowPos in physical pixels after reading the real rect once.
187
+ $rc0 = New-Object 'WpmWin+RECT'
188
+ [void][WpmWin]::GetWindowRect([IntPtr]$hwnd, [ref]$rc0)
189
+ $pw = [int]($rc0.Right - $rc0.Left); $ph = [int]($rc0.Bottom - $rc0.Top)
190
+ if ($pw -le 0) { $pw = 470 }
191
+ if ($ph -le 0) { $ph = 104 }
192
+ $screenW = [WpmHud]::GetSystemMetrics([WpmHud]::SM_CXSCREEN)
193
+ $screenH = [WpmHud]::GetSystemMetrics([WpmHud]::SM_CYSCREEN)
194
+ [void][WpmWin]::MoveNoActivate([IntPtr]$hwnd, ($screenW - $pw - 24), ($screenH - $ph - 64), $pw, $ph)
195
+
196
+ # Click-through outside the button. Measured in scripts/probe-hittest-children.ps1.
197
+ $bp = $btn.PointToScreen([System.Windows.Point]::new(0.0, 0.0))
198
+ $bw = [int]$btn.ActualWidth; $bh = [int]$btn.ActualHeight
199
+ if ($bw -le 0) { $bw = 92 }
200
+ if ($bh -le 0) { $bh = 40 }
201
+ $hitOk = [WpmHud]::InstallHitZone([IntPtr]$hwnd, [int]$bp.X, [int]$bp.Y, [int]($bp.X + $bw), [int]($bp.Y + $bh))
202
+
203
+ $hkOk = $false
204
+ $hkLabel = ''
205
+ foreach ($c in $Chords) {
206
+ if ([WpmWin]::RegisterHotKey($hwnd, $HotkeyId, [uint32]$c.mods, [uint32]$c.vk)) {
207
+ $hkOk = $true; $hkLabel = [string]$c.label; break
208
+ }
209
+ }
210
+ [WpmCtl]::AbortChordOk = [bool]$hkOk
211
+ [WpmCtl]::AbortChordLabel = $hkLabel
212
+
213
+ $src = [System.Windows.Interop.HwndSource]::FromHwnd($hwnd)
214
+ if ($src) {
215
+ $hkId = $HotkeyId
216
+ $hook = [System.Windows.Interop.HwndSourceHook] {
217
+ param($h, $m, $wp, $lp, [ref]$handled)
218
+ if ($m -eq [WpmWin]::WM_HOTKEY -and [int]$wp -eq $hkId) {
219
+ [WpmCtl]::TakeoverAbort = $true
220
+ $handled.Value = $true
221
+ return [IntPtr]::Zero
222
+ }
223
+ $handled.Value = $false
224
+ return [IntPtr]::Zero
225
+ }
226
+ [void]$src.AddHook($hook)
227
+ }
228
+
229
+ $btn.Add_Click({ [WpmCtl]::TakeoverAbort = $true })
230
+
231
+ # THE PUMP. 50ms, reads fields, writes pixels. Nothing is marshalled from another thread.
232
+ $lastPhase = ''
233
+ $pump = [System.Windows.Threading.DispatcherTimer]::new()
234
+ $pump.Interval = [TimeSpan]::FromMilliseconds(50)
235
+ $pump.Add_Tick({
236
+ $phase = [string][WpmCtl]::HudPhase
237
+ $act = [string][WpmCtl]::HudAction
238
+ $elapsed = [int][WpmCtl]::HudElapsedMs
239
+ $max = [int][WpmCtl]::HudMaxMs
240
+ $injected = [int][WpmCtl]::InjectedChars
241
+ $chord = [string][WpmCtl]::AbortChordLabel
242
+ $secs = [Math]::Round($elapsed / 1000.0, 1)
243
+ $maxSecs = [Math]::Round($max / 1000.0, 1)
244
+ # THE THREE PHASES MUST BE TELLABLE APART FROM ACROSS THE ROOM, not just by reading the words.
245
+ # The owner's attention is on the target window while an agent borrows their pointer, so the phase is
246
+ # encoded TWICE: the whole surface tint, and a 5px accent bar (a tint alone is easy to miss at the
247
+ # screen edge). Colours are chosen for meaning rather than prettiness -- amber = not yet, red = now,
248
+ # green = over -- and the accent stays the most saturated element so it reads at a glance.
249
+ if ($phase -eq 'arming') {
250
+ # AMBER: about to borrow. Nothing has moved yet; this is the cancellable window.
251
+ $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 44, 12))
252
+ $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(240, 173, 24))
253
+ $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(255, 216, 138))
254
+ $chordLine = if ($chord) { '中断键 ' + $chord + ' 可取消' } else { '中断键不可用,请点按钮' }
255
+ $tb.Text = '即将使用你的鼠标/键盘/焦点 · ' + $act + [char]0x000A + $chordLine
256
+ $btn.Content = '取消'
257
+ $btn.IsEnabled = $true
258
+ } elseif ($phase -eq 'active') {
259
+ # RED: the pointer/focus are actually held. The one state that costs the owner something right now.
260
+ $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(58, 18, 18))
261
+ $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(232, 64, 64))
262
+ $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(255, 190, 190))
263
+ $tb.Text = '占用中 · ' + $act + [char]0x000A + ('已用 ' + $secs.ToString() + 's / 上限 ' + $maxSecs.ToString() + 's') + [char]0x000A + ('已注入 ' + $injected.ToString() + ' 字')
264
+ $btn.Content = '停止'
265
+ $btn.IsEnabled = $true
266
+ } else {
267
+ # GREEN: returned. A completed state that says "nothing is being held" without needing to be read.
268
+ $win.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(14, 46, 30))
269
+ $bar.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(52, 199, 123))
270
+ $tb.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(178, 240, 205))
271
+ $tb.Text = '已归还:光标已复位'
272
+ $btn.Content = '完成'
273
+ $btn.IsEnabled = $false
274
+ }
275
+ $lastPhase = $phase
276
+ })
277
+ $pump.Start()
278
+
279
+ [WpmCtl]::Dispatcher = [System.Windows.Threading.Dispatcher]::CurrentDispatcher
280
+ [WpmCtl]::Window = $win
281
+ [WpmCtl]::Timer = $pump
282
+ [WpmCtl]::HudOn = $true
283
+ [WpmCtl]::Reason = if ($hitOk) { '' } else { 'WNDPROC subclass failed; the HUD is hit-testable everywhere (degraded)' }
284
+
285
+ [System.Windows.Threading.Dispatcher]::Run()
286
+ } catch {
287
+ [WpmCtl]::Reason = $_.Exception.Message
288
+ } finally {
289
+ [WpmCtl]::HudOn = $false
290
+ [WpmCtl]::HudPhase = ''
291
+ [WpmCtl]::HudHwnd = [int64]0
292
+ [WpmCtl]::AbortChordOk = $false
293
+ [WpmCtl]::AbortChordLabel = ''
294
+ [WpmCtl]::Window = $null
295
+ [WpmCtl]::Timer = $null
296
+ [WpmCtl]::Dispatcher = $null
297
+ }
298
+ '@
299
+
300
+ function Start-WpmHud {
301
+ param([string]$Action = 'action', [int]$MaxMs = 10000, [int]$ArmMs = 800, [int]$WaitMs = 3000)
302
+ if ($script:WpmHudRunspace -and $script:WpmHudRunspace.RunspaceStateInfo.State -eq 'Opened') {
303
+ return @{ started = $false; ready = [bool][WpmCtl]::HudOn; reason = 'already running' }
304
+ }
305
+ [WpmCtl]::Reason = ''
306
+ [WpmCtl]::HudPhase = 'arming'
307
+ [WpmCtl]::HudAction = $Action
308
+ [WpmCtl]::HudMaxMs = $MaxMs
309
+ [WpmCtl]::HudElapsedMs = 0
310
+ [WpmCtl]::InjectedChars = 0
311
+ $iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2()
312
+ $rs = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($iss)
313
+ $rs.ApartmentState = [System.Threading.ApartmentState]::STA
314
+ $rs.ThreadOptions = [System.Management.Automation.Runspaces.PSThreadOptions]::Default
315
+ $rs.Open()
316
+ if ($rs.RunspaceStateInfo.State -ne 'Opened') {
317
+ return @{ started = $false; ready = $false; reason = "runspace failed to open: $($rs.RunspaceStateInfo)" }
318
+ }
319
+ $ps = [PowerShell]::Create()
320
+ $ps.Runspace = $rs
321
+ [void]$ps.AddScript($script:WpmHudBody).AddArgument($Action).AddArgument($MaxMs).AddArgument($ArmMs).AddArgument($script:WpmHudHotkeyId).AddArgument($script:WpmAbortChords)
322
+ $script:WpmHudHandle = $ps.BeginInvoke()
323
+ $script:WpmHudRunspace = $rs
324
+ $script:WpmHudPowerShell = $ps
325
+ $st = Get-WpmHudState -WaitMs $WaitMs
326
+ return @{ started = [bool]$st.running; ready = [bool]$st.running; reason = [string]$st.reason; state = $st }
327
+ }
328
+
329
+ function Get-WpmHudState {
330
+ # Wait for HudOn -- the same flag the readiness verdict uses. A budget that expired mid-init is
331
+ # 'starting', not 'dead': the caller can tell a slow start from a body that threw (overlay.ps1:250-262).
332
+ param([int]$WaitMs = 2500)
333
+ $deadline = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + $WaitMs
334
+ while ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $deadline -and -not [WpmCtl]::HudOn) {
335
+ Start-Sleep -Milliseconds 50
336
+ }
337
+ $hwnd = [WpmCtl]::HudHwnd
338
+ $ex = 0
339
+ if ($hwnd -ne 0) { $ex = [WpmWin]::GetWindowLong([IntPtr]$hwnd, [WpmWin]::GWL_EXSTYLE) }
340
+ return @{
341
+ running = [bool][WpmCtl]::HudOn
342
+ starting = (-not [WpmCtl]::HudOn) -and ($script:WpmHudHandle -ne $null) -and (-not $script:WpmHudHandle.AsyncWaitHandle.WaitOne(0))
343
+ hwnd = [string]$hwnd
344
+ phase = [string][WpmCtl]::HudPhase
345
+ abortChordRegistered = [bool][WpmCtl]::AbortChordOk
346
+ abortChordLabel = [string][WpmCtl]::AbortChordLabel
347
+ injectedChars = [int][WpmCtl]::InjectedChars
348
+ abortRequested = [bool][WpmCtl]::TakeoverAbort
349
+ reason = [string][WpmCtl]::Reason
350
+ exStyle = '0x{0:X8}' -f $ex
351
+ topmost = [bool]($ex -band [WpmWin]::WS_EX_TOPMOST)
352
+ noActivate = [bool]($ex -band [WpmWin]::WS_EX_NOACTIVATE)
353
+ transparent = [bool]($ex -band [WpmWin]::WS_EX_TRANSPARENT)
354
+ foregroundNow = [WpmWin]::Fg()
355
+ }
356
+ }
357
+
358
+ function Test-WpmHudReady {
359
+ return [bool]([WpmCtl]::HudOn -and [WpmCtl]::HudHwnd -ne 0)
360
+ }
361
+
362
+ function Set-WpmHudPhase {
363
+ # A REQUEST, not an action: three field writes, applied by the HUD's own pump. Called on every phase
364
+ # change and every 50ms while active (for the elapsed clock).
365
+ param([ValidateSet('arming', 'active', 'done')][string]$Phase, [string]$Action = '', [int]$MaxMs = -1, [int]$ElapsedMs = -1)
366
+ [WpmCtl]::HudPhase = $Phase
367
+ if ($Action) { [WpmCtl]::HudAction = $Action }
368
+ if ($MaxMs -ge 0) { [WpmCtl]::HudMaxMs = $MaxMs }
369
+ if ($ElapsedMs -ge 0) { [WpmCtl]::HudElapsedMs = $ElapsedMs }
370
+ return @{ phase = $Phase; hudOn = [bool][WpmCtl]::HudOn }
371
+ }
372
+
373
+ function Stop-WpmHud {
374
+ param([int]$WaitMs = 2500)
375
+ $hwnd = [WpmCtl]::HudHwnd
376
+ $posted = $false
377
+ if ($hwnd -ne 0) {
378
+ try { $posted = [bool][WpmWin]::PostMessageW([IntPtr]$hwnd, [uint32][WpmWin]::WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero) } catch { $posted = $false }
379
+ }
380
+ $completed = $false
381
+ if ($script:WpmHudHandle) {
382
+ $spin = 0
383
+ while (-not $script:WpmHudHandle.IsCompleted -and $spin -lt 6) { Start-Sleep -Milliseconds 50; $spin++ }
384
+ $completed = [bool]$script:WpmHudHandle.IsCompleted
385
+ }
386
+ if (-not $completed) {
387
+ $d = [WpmCtl]::Dispatcher
388
+ if ($d) { try { [void]$d.InvokeShutdown() } catch { } }
389
+ $spin = 0
390
+ while ($script:WpmHudHandle -and -not $script:WpmHudHandle.IsCompleted -and $spin -lt 20) { Start-Sleep -Milliseconds 25; $spin++ }
391
+ $completed = [bool]($script:WpmHudHandle -and $script:WpmHudHandle.IsCompleted)
392
+ }
393
+ if ($script:WpmHudHandle) { try { $script:WpmHudPowerShell.EndInvoke($script:WpmHudHandle) | Out-Null } catch { } }
394
+ if ($script:WpmHudPowerShell) { try { $script:WpmHudPowerShell.Dispose() } catch { }; $script:WpmHudPowerShell = $null }
395
+ if ($script:WpmHudRunspace) { try { $script:WpmHudRunspace.Dispose() } catch { }; $script:WpmHudRunspace = $null }
396
+ $script:WpmHudHandle = $null
397
+ $st = Get-WpmHudState -WaitMs 150
398
+ if (-not $completed) {
399
+ [WpmCtl]::HudOn = $false
400
+ [WpmCtl]::HudPhase = ''
401
+ [WpmCtl]::HudHwnd = [int64]0
402
+ [WpmCtl]::AbortChordOk = $false
403
+ [WpmCtl]::AbortChordLabel = ''
404
+ [WpmCtl]::Window = $null
405
+ [WpmCtl]::Timer = $null
406
+ [WpmCtl]::Dispatcher = $null
407
+ $st = Get-WpmHudState -WaitMs 100
408
+ $st.reason = 'hud pipeline did not end within the bound; state cleared by Stop-WpmHud'
409
+ }
410
+ return @{ stopped = $true; completed = $completed; posted = $posted; state = $st }
411
+ }
@@ -0,0 +1,176 @@
1
+ # input-inject.ps1 -- the ONE file allowed to call SendInput, and it can only ever construct a
2
+ # KEYBOARD event. (R3, spec.md §1)
3
+ #
4
+ # WHY KEYBOARD IS ALLOWED WHERE MOUSE IS NOT. Measured (findings §B): a terminal's text surface has
5
+ # three child HWNDs and none of them accepts WM_CHAR/WM_SETTEXT, so no message door exists; UIA exposes
6
+ # no pattern either. Its text can only be typed. A mouse event has an alternative that already exists
7
+ # (SetCursorPos shows the point, the message/UIA tier clicks), so mouse injection buys nothing and stays
8
+ # banned -- the gate forbids MOUSEEVENTF_* repo-wide, and this file never names it.
9
+ #
10
+ # THE THREE CONSTRAINTS THAT MATTER MORE THAN THE CAPABILITY (spec.md §1):
11
+ # S1 FOREGROUND IS THE TARGET. SendInput delivers to the current foreground window, not to "the
12
+ # window you meant". Measured with this host's own probe (scripts/probe-sendinput-unicode.ps1):
13
+ # text sent while window B was foreground landed in B and NOT in A, even though A was the target
14
+ # the caller had in mind. So the assertion below is not ceremony -- it is the difference between
15
+ # typing into the terminal and typing into whatever the owner was writing.
16
+ # S2 INTERRUPTIBLE PER CHARACTER. A 500-character payload must not be an uninterruptible burst: the
17
+ # loop checks the caller's abort probe every 8 characters or 50ms and reports how many characters
18
+ # actually went out.
19
+ # S3 NO MOUSE. Only INPUT_KEYBOARD is constructed; there is no code path here that can move a pointer
20
+ # or click (the gate enforces the constants' absence, not the intent).
21
+ #
22
+ # WHY KEYEVENTF_UNICODE AND NOT SCAN CODES. Unicode mode does not consult the keyboard layout, so it
23
+ # works on a DE layout and with Chinese/emoji payloads; scan-code mapping (VkKeyScan) mis-types on
24
+ # non-US layouts and dead keys. The price is documented rather than hidden: a Unicode-injected character
25
+ # carries no hardware scancode, and the rare target that only reads scancodes (some games, remote KVM)
26
+ # will ignore it.
27
+
28
+ Set-StrictMode -Version 2.0
29
+
30
+ if (-not ('WpmCtl' -as [type])) {
31
+ . (Join-Path $PSScriptRoot 'win.ps1')
32
+ }
33
+
34
+ if (-not ('WpmInject' -as [type])) {
35
+ Add-Type -TypeDefinition @'
36
+ using System;
37
+ using System.Runtime.InteropServices;
38
+
39
+ public static class WpmInject
40
+ {
41
+ [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT
42
+ {
43
+ public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo;
44
+ }
45
+ [StructLayout(LayoutKind.Sequential)] public struct INPUT
46
+ {
47
+ public uint type; public KEYBDINPUT ki; public int pad0; public int pad1;
48
+ }
49
+
50
+ [DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint n, INPUT[] inputs, int cbSize);
51
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
52
+ [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags);
53
+
54
+ public const uint INPUT_KEYBOARD = 1;
55
+ public const uint KEYEVENTF_KEYUP = 0x0002;
56
+ public const uint KEYEVENTF_UNICODE = 0x0004;
57
+
58
+ static INPUT Make(ushort scan, uint flags) {
59
+ INPUT i = new INPUT();
60
+ i.type = INPUT_KEYBOARD;
61
+ i.ki.wVk = 0;
62
+ i.ki.wScan = scan;
63
+ i.ki.dwFlags = flags;
64
+ i.ki.time = 0;
65
+ i.ki.dwExtraInfo = IntPtr.Zero;
66
+ return i;
67
+ }
68
+
69
+ // One character = one down + one up, as a single SendInput call so the pair cannot be separated by
70
+ // another process's input. Returns the number of events the OS accepted (0..2).
71
+ public static uint SendChar(char c) {
72
+ INPUT[] pair = new INPUT[2];
73
+ pair[0] = Make((ushort)c, KEYEVENTF_UNICODE);
74
+ pair[1] = Make((ushort)c, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP);
75
+ return SendInput(2, pair, Marshal.SizeOf(typeof(INPUT)));
76
+ }
77
+
78
+ // A named key with optional modifiers -- used where a target needs RETURN/TAB rather than text.
79
+ // The modifiers are held for the duration of the press and released in reverse order.
80
+ public static uint SendCombo(ushort vk, ushort[] mods) {
81
+ int n = 2 * (mods.Length + 1);
82
+ INPUT[] seq = new INPUT[n];
83
+ int k = 0;
84
+ foreach (ushort m in mods) { INPUT i = Make(m, 0); seq[k++] = i; }
85
+ { INPUT d = Make(vk, 0); seq[k++] = d; }
86
+ { INPUT u = Make(vk, KEYEVENTF_KEYUP); seq[k++] = u; }
87
+ for (int j = mods.Length - 1; j >= 0; j--) { INPUT r = Make(mods[j], KEYEVENTF_KEYUP); seq[k++] = r; }
88
+ return SendInput((uint)n, seq, Marshal.SizeOf(typeof(INPUT)));
89
+ }
90
+
91
+ public static string ForegroundClass() {
92
+ IntPtr fg = GetForegroundWindow();
93
+ return fg.ToInt64().ToString();
94
+ }
95
+ public static string RootOf(string hwnd) {
96
+ IntPtr h = new IntPtr(long.Parse(hwnd));
97
+ IntPtr root = GetAncestor(h, 2);
98
+ return root.ToInt64().ToString();
99
+ }
100
+ }
101
+ '@
102
+ }
103
+
104
+ function Test-WpmTargetForeground {
105
+ # S1's assertion. A child of the target counts (the foreground is often the child control), which is
106
+ # why this compares ROOTS rather than exact handles.
107
+ param([string]$Hwnd)
108
+ if (-not $Hwnd) { return @{ ok = $false; foreground = ''; reason = 'no target hwnd' } }
109
+ $fg = [WpmInject]::ForegroundClass()
110
+ if (-not $fg -or $fg -eq '0') { return @{ ok = $false; foreground = ''; reason = 'no foreground window' } }
111
+ $fgRoot = [WpmInject]::RootOf($fg)
112
+ $targetRoot = [WpmInject]::RootOf($Hwnd)
113
+ $match = ($fg -eq $Hwnd) -or ($fgRoot -eq $targetRoot)
114
+ return @{ ok = [bool]$match; foreground = $fg; foregroundRoot = $fgRoot; targetRoot = $targetRoot
115
+ reason = if ($match) { '' } else { 'the foreground window is not the target; sending input would write into the wrong application' } }
116
+ }
117
+
118
+ function Send-WpmKeyText {
119
+ # PER-CHARACTER LOOP, by design (S2). The abort probe is a caller-supplied scriptblock so this file
120
+ # does not need to know where the interruption comes from (HUD button, global chord, host latch).
121
+ param(
122
+ [string]$Text = '',
123
+ [scriptblock]$ShouldAbort = $null,
124
+ [int]$CheckEveryChars = 8,
125
+ [int]$CheckEveryMs = 50
126
+ )
127
+ if (-not $Text) { return @{ ok = $false; sent = 0; chars = 0; aborted = $false; reason = 'empty payload' } }
128
+ $chars = 0
129
+ $events = 0
130
+ $lastCheck = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
131
+ for ($i = 0; $i -lt $Text.Length; $i++) {
132
+ if ($ShouldAbort) {
133
+ $dueByCount = ($CheckEveryChars -gt 0) -and (($i % $CheckEveryChars) -eq 0)
134
+ $nowMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
135
+ $dueByTime = (($nowMs - $lastCheck) -ge $CheckEveryMs)
136
+ if ($i -gt 0 -and ($dueByCount -or $dueByTime)) {
137
+ $lastCheck = $nowMs
138
+ $stop = $false
139
+ try { $stop = [bool](& $ShouldAbort) } catch { $stop = $false }
140
+ if ($stop) {
141
+ return @{ ok = $false; sent = $events; chars = $chars; aborted = $true
142
+ reason = 'interrupted after ' + $chars + ' of ' + $Text.Length + ' characters' }
143
+ }
144
+ }
145
+ }
146
+ $queued = [WpmInject]::SendChar([char]$Text[$i])
147
+ $events += [int]$queued
148
+ $chars += 1
149
+ # Progress is published per character so a caller watching [WpmCtl]::InjectedChars (the HUD does)
150
+ # sees the real count even if the call is later interrupted.
151
+ [WpmCtl]::InjectedChars = $chars
152
+ if ($queued -eq 0) {
153
+ return @{ ok = $false; sent = $events; chars = $chars; aborted = $false
154
+ reason = 'SendInput accepted no events for character ' + $i + ' (a higher-integrity foreground refuses input)' }
155
+ }
156
+ Start-Sleep -Milliseconds 2
157
+ }
158
+ return @{ ok = $true; sent = $events; chars = $chars; aborted = $false; reason = '' }
159
+ }
160
+
161
+ function Send-WpmKeyPress {
162
+ # Single key + modifiers. Kept because "type" is not the only thing an agent needs: confirming a
163
+ # dialog or submitting a form is a RETURN press, and faking it with a text write would be a lie.
164
+ param([string]$Key = 'enter')
165
+ $map = @{
166
+ 'enter' = 0x0D; 'return' = 0x0D; 'tab' = 0x09; 'escape' = 0x1B; 'esc' = 0x1B
167
+ 'space' = 0x20; 'backspace' = 0x08; 'delete' = 0x2E; 'up' = 0x26; 'down' = 0x28
168
+ 'left' = 0x25; 'right' = 0x27; 'home' = 0x24; 'end' = 0x23
169
+ }
170
+ $k = $Key.ToLowerInvariant()
171
+ if (-not $map.ContainsKey($k)) {
172
+ return @{ ok = $false; sent = 0; reason = "unknown key '" + $Key + "'; named keys: " + (($map.Keys | Sort-Object) -join ', ') }
173
+ }
174
+ $queued = [WpmInject]::SendCombo([uint16]$map[$k], [uint16[]]@())
175
+ return @{ ok = [bool]($queued -gt 0); sent = [int]$queued; reason = if ($queued -gt 0) { '' } else { 'SendInput accepted no events' } }
176
+ }
@@ -1,4 +1,4 @@
1
- # overlay.ps1 -- the product's visible surface: an AI marker that never takes the foreground,
1
+ # overlay.ps1 -- the product's visible surface: an AI marker that never takes the foreground,
2
2
  # and a global hotkey that pauses the engine server-side. (task_54)
3
3
  #
4
4
  # WHAT THIS IS FOR. Two README claims need a real surface:
@@ -84,6 +84,12 @@ try {
84
84
  $win.WindowStartupLocation = [System.Windows.WindowStartupLocation]::Manual
85
85
  $win.ShowInTaskbar = $false
86
86
  $win.Topmost = $true
87
+ # THE MARKER HAD A WHITE SQUARE BEHIND IT, and the cause was an omission, not a style: AllowsTransparency
88
+ # makes the window's pixels able to show what is underneath, but a WPF Window's DEFAULT background is
89
+ # SystemColors.WindowBrush (white), so the 22px window painted an opaque white tile and the ring sat
90
+ # inside it. Only the ellipse is drawn; the rest of the surface must be explicitly transparent or it
91
+ # keeps the default brush. (hud.ps1 always set its background, which is why the HUD never showed this.)
92
+ $win.Background = [System.Windows.Media.Brushes]::Transparent
87
93
  $win.Opacity = 0.85
88
94
 
89
95
  $ring = [System.Windows.Shapes.Ellipse]::new()