@capyclaw/wall-suite 0.0.0-stage → 0.1.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 (148) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/composition.lock.json +48 -0
  4. package/contract/wall-contract.json +8 -0
  5. package/cordis.patch.yml +6 -0
  6. package/dsh-suite.json +118 -0
  7. package/lib/index.mjs +6 -0
  8. package/node_modules/@capyclaw/asset-service/README.md +48 -0
  9. package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
  10. package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
  11. package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
  12. package/node_modules/@capyclaw/asset-service/package.json +59 -0
  13. package/node_modules/@capyclaw/asset-service/src/index.mjs +223 -0
  14. package/node_modules/@capyclaw/foundation/README.md +51 -0
  15. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  16. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  17. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  18. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  19. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  20. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  21. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  22. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  23. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  24. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  25. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  34. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  35. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  36. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  37. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  38. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  39. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  40. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  41. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  42. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  43. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  44. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
  45. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  46. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  47. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  48. package/node_modules/@capyclaw/foundation/package.json +53 -0
  49. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  50. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  51. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  52. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  53. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +143 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +41 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  79. package/node_modules/@capyclaw/portal/README.md +70 -0
  80. package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
  81. package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
  82. package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
  83. package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
  84. package/node_modules/@capyclaw/portal/package.json +40 -0
  85. package/node_modules/@capyclaw/service-broker/README.md +104 -0
  86. package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
  87. package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
  88. package/node_modules/@capyclaw/service-broker/lib/control.mjs +193 -0
  89. package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
  90. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1236 -0
  91. package/node_modules/@capyclaw/service-broker/lib/host.mjs +182 -0
  92. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +249 -0
  93. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +325 -0
  94. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +28 -0
  95. package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
  96. package/node_modules/@capyclaw/service-broker/package.json +65 -0
  97. package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
  98. package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
  99. package/node_modules/@capyclaw/service-broker/services.json +3 -0
  100. package/node_modules/@capyclaw/service-host/README.md +86 -0
  101. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  102. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  103. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  104. package/node_modules/@capyclaw/service-host/package.json +60 -0
  105. package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
  106. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  107. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  108. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  109. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  110. package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
  111. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  112. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +142 -0
  113. package/node_modules/@capyclaw/tool-host/src/index.mjs +390 -0
  114. package/node_modules/@capyclaw/wall-workbench/README.md +58 -0
  115. package/node_modules/@capyclaw/wall-workbench/contract/wall-contract.json +8 -0
  116. package/node_modules/@capyclaw/wall-workbench/lib/host.mjs +1 -0
  117. package/node_modules/@capyclaw/wall-workbench/package.json +63 -0
  118. package/node_modules/@capyclaw/wall-workbench/plugin.mjs +1 -0
  119. package/node_modules/@capyclaw/wall-workbench/server/constants.mjs +12 -0
  120. package/node_modules/@capyclaw/wall-workbench/server/contract.mjs +12 -0
  121. package/node_modules/@capyclaw/wall-workbench/server/embedded-host.mjs +160 -0
  122. package/node_modules/@capyclaw/wall-workbench/server/infra/http.mjs +2 -0
  123. package/node_modules/@capyclaw/wall-workbench/server/infra/tuning.mjs +2 -0
  124. package/node_modules/@capyclaw/wall-workbench/server/relay.mjs +68 -0
  125. package/node_modules/@capyclaw/wall-workbench/server/routes/claim.mjs +46 -0
  126. package/node_modules/@capyclaw/wall-workbench/server/routes/workbench.mjs +29 -0
  127. package/node_modules/@capyclaw/wall-workbench/server/shared/SHARED_MANIFEST.json +70 -0
  128. package/node_modules/@capyclaw/wall-workbench/server/shared/asset-service.mjs +2 -0
  129. package/node_modules/@capyclaw/wall-workbench/server/shared/editor-host.mjs +2 -0
  130. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/editor/lease.mjs +2 -0
  131. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/api.mjs +2 -0
  132. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/http.mjs +2 -0
  133. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/mcp-http.mjs +2 -0
  134. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tools/validate.mjs +2 -0
  135. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tuning.mjs +2 -0
  136. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/util/fs-lock.mjs +2 -0
  137. package/node_modules/@capyclaw/wall-workbench/server/shared/service-host.mjs +2 -0
  138. package/node_modules/@capyclaw/wall-workbench/server/shared/tool-host.mjs +2 -0
  139. package/node_modules/@capyclaw/wall-workbench/server/shared/tuning.mjs +2 -0
  140. package/node_modules/@capyclaw/wall-workbench/server/tools/capabilities/index.mjs +2 -0
  141. package/node_modules/@capyclaw/wall-workbench/server/tools/index.mjs +12 -0
  142. package/node_modules/@capyclaw/wall-workbench/server/tools.mjs +2 -0
  143. package/node_modules/@capyclaw/wall-workbench/server/workbench-framework.mjs +305 -0
  144. package/node_modules/@capyclaw/wall-workbench/ui/app.js +142 -0
  145. package/node_modules/@capyclaw/wall-workbench/ui/index.html +20 -0
  146. package/node_modules/@capyclaw/wall-workbench/ui/style.css +74 -0
  147. package/package.json +72 -4
  148. package/services.json +3 -0
@@ -0,0 +1,811 @@
1
+ #requires -Version 5.1
2
+ <#
3
+ portal-agent.ps1 - Win32 side of the desktop popup (spawned by server/portal.mjs).
4
+
5
+ NOTE: this file is deliberately ASCII-only. Windows PowerShell 5.1 reads .ps1 files
6
+ with the system ANSI code page unless they carry a UTF-8 BOM, and the build pipeline
7
+ copies sources as plain UTF-8 (BOM stripped). Non-ASCII bytes here would corrupt the
8
+ parser, so keep comments and strings in English.
9
+
10
+ Responsibilities (windows only, no business logic):
11
+ open launch a Chromium app window (Edge/Chrome --app=URL), strip the frame,
12
+ keep it on top, place it by anchor
13
+ focus restore + raise an existing window
14
+ drag hand the window to the system move loop (WM_NCLBUTTONDOWN/HTCAPTION)
15
+ move set geometry (physical pixels)
16
+ topmost toggle always-on-top
17
+ close WM_CLOSE, then force-kill the browser process if it lingers
18
+ state dump the key -> window table
19
+ shutdown exit the agent
20
+
21
+ Protocol: one JSON object per line on stdin/stdout, UTF-8, ASCII fields only.
22
+ request {"id":"1","op":"open","key":"ppt","url":"http://...","w":780,"h":920}
23
+ response {"id":"1","ok":true,"key":"ppt","hwnd":123456,"pid":789,"rect":[x,y,w,h]}
24
+
25
+ Geometry note: Edge interprets --window-size/--window-position as DIPs, while
26
+ SetWindowPos works in physical pixels. Mixing both is what makes popups land in odd
27
+ places on scaled displays, so here we convert DIP -> physical once and set the final
28
+ geometry ourselves (twice, ~320ms apart, because the window is still initialising).
29
+ #>
30
+ $ErrorActionPreference = 'Stop'
31
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
32
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding $false
33
+
34
+ Add-Type -TypeDefinition @"
35
+ using System;
36
+ using System.Text;
37
+ using System.Runtime.InteropServices;
38
+
39
+ public static class PortalNative {
40
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
41
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
42
+
43
+ // SetWindowPlacement is the only reliable way to undo a Chromium app window that came up
44
+ // minimised: it carries both the show command and the size to restore to, whereas
45
+ // ShowWindow(SW_RESTORE) lets Chromium pick its own remembered bounds.
46
+ [StructLayout(LayoutKind.Sequential)] public struct WINDOWPLACEMENT {
47
+ public int length;
48
+ public int flags;
49
+ public int showCmd;
50
+ public POINT ptMinPosition;
51
+ public POINT ptMaxPosition;
52
+ public RECT rcNormalPosition;
53
+ }
54
+ [DllImport("user32.dll")] public static extern bool SetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT placement);
55
+ [DllImport("user32.dll")] public static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT placement);
56
+
57
+ [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint flags);
58
+ [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
59
+ [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
60
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
61
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
62
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
63
+ [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, IntPtr dwExtraInfo);
64
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
65
+ [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hWnd);
66
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
67
+ [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
68
+ [DllImport("user32.dll")] public static extern bool ReleaseCapture();
69
+ [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
70
+ [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
71
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
72
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr hWnd, StringBuilder sb, int max);
73
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder sb, int max);
74
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern bool SetWindowText(IntPtr hWnd, string text);
75
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc callback, IntPtr lParam);
76
+ [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
77
+ [DllImport("user32.dll")] public static extern uint GetDpiForSystem();
78
+ [DllImport("user32.dll")] public static extern bool SystemParametersInfo(uint action, uint param, out RECT rect, uint winIni);
79
+ [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute(IntPtr hWnd, int attr, ref int value, int size);
80
+
81
+ public delegate bool EnumProc(IntPtr hWnd, IntPtr lParam);
82
+ }
83
+ "@
84
+
85
+ [void][PortalNative]::SetProcessDPIAware()
86
+
87
+ $script:GWL_STYLE = -16
88
+ $script:WS_CAPTION = 0x00C00000
89
+ $script:WS_THICKFRAME = 0x00040000
90
+ $script:WS_SYSMENU = 0x00080000
91
+ $script:WS_MINIMIZEBOX = 0x00020000
92
+ $script:WS_MAXIMIZEBOX = 0x00010000
93
+ $script:WS_POPUP = 0x80000000
94
+ $script:SWP_FRAMECHANGED = 0x0020
95
+ $script:SWP_SHOWWINDOW = 0x0040
96
+ $script:SWP_NOSIZE = 0x0001
97
+ $script:SWP_NOMOVE = 0x0002
98
+ $script:SWP_NOACTIVATE = 0x0010
99
+ $script:SPI_GETWORKAREA = 0x0030
100
+ $script:HWND_TOPMOST = [IntPtr](-1)
101
+ $script:HWND_NOTOPMOST = [IntPtr](-2)
102
+ $script:WM_CLOSE = 0x0010
103
+ $script:WM_NCLBUTTONDOWN = 0x00A1
104
+ $script:HTCAPTION = 2
105
+ $script:SW_RESTORE = 9
106
+ $script:SW_SHOWNORMAL = 1
107
+ $script:GWL_EXSTYLE = -20
108
+ $script:WS_EX_TOPMOST = 0x00000008
109
+
110
+ $script:Windows = @{}
111
+ $script:Scale = [double]([PortalNative]::GetDpiForSystem()) / 96.0
112
+ if ($script:Scale -lt 1) { $script:Scale = 1.0 }
113
+
114
+ function Get-WorkArea {
115
+ $rect = New-Object PortalNative+RECT
116
+ if ([PortalNative]::SystemParametersInfo($script:SPI_GETWORKAREA, 0, [ref]$rect, 0)) { return $rect }
117
+ return New-Object PortalNative+RECT -Property @{ Left = 0; Top = 0; Right = 1920; Bottom = 1080 }
118
+ }
119
+
120
+ function Test-Alive($entry) {
121
+ if (-not $entry) { return $false }
122
+ return [PortalNative]::IsWindow([IntPtr]$entry.hwnd)
123
+ }
124
+
125
+ # Find a visible top-level window of class Chrome_WidgetWin_1 that either belongs to
126
+ # $targetPid or whose title equals $marker (adoption across process restarts).
127
+ function Find-Window($targetPid, $marker) {
128
+ $script:found = [IntPtr]::Zero
129
+ $script:wantPid = $targetPid
130
+ $script:wantMarker = $marker
131
+ $callback = [PortalNative+EnumProc]{
132
+ param($hWnd, $lParam)
133
+ if (-not [PortalNative]::IsWindowVisible($hWnd)) { return $true }
134
+ $sb = New-Object System.Text.StringBuilder 256
135
+ [void][PortalNative]::GetClassName($hWnd, $sb, 256)
136
+ if ($sb.ToString() -ne 'Chrome_WidgetWin_1') { return $true }
137
+ $owner = 0
138
+ [void][PortalNative]::GetWindowThreadProcessId($hWnd, [ref]$owner)
139
+ $matched = $false
140
+ if ($script:wantPid -gt 0 -and $owner -eq $script:wantPid) { $matched = $true }
141
+ if (-not $matched -and $script:wantMarker) {
142
+ $title = New-Object System.Text.StringBuilder 512
143
+ [void][PortalNative]::GetWindowText($hWnd, $title, 512)
144
+ if ($title.ToString() -eq $script:wantMarker) { $matched = $true }
145
+ }
146
+ if ($matched) { $script:found = $hWnd; return $false }
147
+ return $true
148
+ }
149
+ [void][PortalNative]::EnumWindows($callback, [IntPtr]::Zero)
150
+ return $script:found
151
+ }
152
+
153
+ function Get-Entry($key) {
154
+ if (-not $script:Windows.ContainsKey($key)) { return $null }
155
+ $entry = $script:Windows[$key]
156
+ if (-not (Test-Alive $entry)) { $script:Windows.Remove($key); return $null }
157
+ return $entry
158
+ }
159
+
160
+ # Where the user last left this window. A portal window is an ordinary window: once the
161
+ # user drags or resizes it, that is where it must come back. Chromium's own restored
162
+ # bounds are not usable here (we pass --window-position/--window-size at launch), so we
163
+ # remember the rect ourselves, keyed by URL (one window per address).
164
+ function Get-LayoutPath($profile) { return (Join-Path $profile 'portal-layout.json') }
165
+
166
+ function Read-Layouts($profile) {
167
+ $path = Get-LayoutPath $profile
168
+ if (-not (Test-Path $path)) { return @() }
169
+ try {
170
+ $doc = [System.IO.File]::ReadAllText($path) | ConvertFrom-Json
171
+ if ($doc -and $doc.layouts) { return @($doc.layouts) }
172
+ } catch { }
173
+ return @()
174
+ }
175
+
176
+ function Get-SavedLayout($profile, $url) {
177
+ if (-not $profile -or -not $url) { return $null }
178
+ foreach ($item in @(Read-Layouts $profile)) {
179
+ if ([string]$item.url -eq [string]$url) { return $item }
180
+ }
181
+ return $null
182
+ }
183
+
184
+ function Save-Layout($profile, $url, $hwnd) {
185
+ if (-not $profile -or -not $url) { return }
186
+ if (-not (Test-Alive @{ hwnd = $hwnd })) { return }
187
+ if ([PortalNative]::IsIconic([IntPtr]$hwnd)) { return }
188
+ $rect = New-Object PortalNative+RECT
189
+ [void][PortalNative]::GetWindowRect([IntPtr]$hwnd, [ref]$rect)
190
+ $w = $rect.Right - $rect.Left
191
+ $h = $rect.Bottom - $rect.Top
192
+ if ($w -lt 240 -or $h -lt 160) { return }
193
+ $list = @()
194
+ foreach ($item in @(Read-Layouts $profile)) {
195
+ if ([string]$item.url -ne [string]$url) { $list += $item }
196
+ }
197
+ $list += [pscustomobject]@{
198
+ url = [string]$url; x = [int]$rect.Left; y = [int]$rect.Top
199
+ w = [int]$w; h = [int]$h; at = [DateTime]::UtcNow.ToString('o')
200
+ }
201
+ if ($list.Count -gt 16) { $list = $list[($list.Count - 16)..($list.Count - 1)] }
202
+ try {
203
+ $json = @{ layouts = @($list) } | ConvertTo-Json -Depth 4 -Compress
204
+ [System.IO.File]::WriteAllText((Get-LayoutPath $profile), $json, (New-Object System.Text.UTF8Encoding $false))
205
+ } catch { }
206
+ }
207
+
208
+ function Resolve-Geometry($width, $height, $anchor, $margin) {
209
+ $work = Get-WorkArea
210
+ $scale = $script:Scale
211
+ $pw = [int][Math]::Round($width * $scale)
212
+ $ph = [int][Math]::Round($height * $scale)
213
+ $m = [int][Math]::Round($margin * $scale)
214
+ $maxW = [Math]::Max(320, ($work.Right - $work.Left) - 2 * $m)
215
+ $maxH = [Math]::Max(320, ($work.Bottom - $work.Top) - 2 * $m)
216
+ if ($pw -gt $maxW) { $pw = $maxW }
217
+ if ($ph -gt $maxH) { $ph = $maxH }
218
+ $x = $work.Right - $pw - $m
219
+ $y = $work.Top + [int][Math]::Round((($work.Bottom - $work.Top) - $ph) / 2)
220
+ switch ($anchor) {
221
+ 'center' { $x = $work.Left + [int][Math]::Round((($work.Right - $work.Left) - $pw) / 2) }
222
+ 'left' { $x = $work.Left + $m }
223
+ 'topright' { $y = $work.Top + $m }
224
+ }
225
+ if ($y -lt ($work.Top + $m)) { $y = $work.Top + $m }
226
+ return @{ x = $x; y = $y; w = $pw; h = $ph }
227
+ }
228
+
229
+ function Set-Geometry($entry) {
230
+ $after = if ($entry.topmost) { $script:HWND_TOPMOST } else { $script:HWND_NOTOPMOST }
231
+ [void][PortalNative]::SetWindowPos([IntPtr]$entry.hwnd, $after, $entry.x, $entry.y, $entry.w, $entry.h, $script:SWP_SHOWWINDOW)
232
+ }
233
+
234
+ # Settle a freshly opened window: Chromium re-applies its own z-order (and, on a slow
235
+ # first paint, its own bounds) for a few seconds after the page starts loading, so the
236
+ # declaration's geometry has to be held briefly. Two rules keep this from fighting the
237
+ # user, which is what made windows jump back to their start position:
238
+ #
239
+ # * the moment the window is foreground AND its rect differs from what we asked for,
240
+ # the user is dragging/resizing it: adopt their rect, remember it, stop correcting;
241
+ # * once the user has actually used the window (it was foreground) a minimise is their
242
+ # choice: never restore it again.
243
+ #
244
+ # The inherited "hidden" startup show state is a different beast: that collapse happens
245
+ # while the window has never been foreground, so it is still safe to undo.
246
+ # "On top" for these Chromium app windows is not reliable: Windows keeps an owned window in
247
+ # its owner's band, so a later WS_EX_TOPMOST request is silently ignored even though
248
+ # SetWindowPos reports success. What a user actually wants when they click a port is
249
+ # "bring that window to me", so on an explicit summon we also raise it to the foreground.
250
+ # A foreground lock can refuse SetForegroundWindow when the caller is not the active
251
+ # process; tapping ALT is the classic way to become eligible.
252
+ function Activate-Window($hwnd) {
253
+ $h = [IntPtr]$hwnd
254
+ if ([PortalNative]::IsIconic($h)) { [void][PortalNative]::ShowWindow($h, $script:SW_RESTORE) }
255
+ [void][PortalNative]::SetForegroundWindow($h)
256
+ Start-Sleep -Milliseconds 120
257
+ if ([PortalNative]::GetForegroundWindow() -eq $h) { return $true }
258
+ [PortalNative]::keybd_event(0x12, 0, 0, [IntPtr]::Zero)
259
+ [PortalNative]::keybd_event(0x12, 0, 0x2, [IntPtr]::Zero)
260
+ Start-Sleep -Milliseconds 40
261
+ [void][PortalNative]::SetForegroundWindow($h)
262
+ Start-Sleep -Milliseconds 120
263
+ return ([PortalNative]::GetForegroundWindow() -eq $h)
264
+ }
265
+
266
+ # A Chromium app window started from a windowless parent can stay minimised no matter how
267
+ # often ShowWindow(SW_RESTORE) is called: the browser keeps re-applying the show state it
268
+ # inherited. SetWindowPlacement is authoritative - it both commands SW_SHOWNORMAL and tells
269
+ # Windows which rect to restore to - so the window comes back at our geometry instead of
270
+ # Chromium's remembered bounds. Retry a few times because the first call can land while the
271
+ # first paint is still installing the window.
272
+ function Force-Show($entry, $tries) {
273
+ $hwnd = [IntPtr]$entry.hwnd
274
+ $size = [System.Runtime.InteropServices.Marshal]::SizeOf([type][PortalNative+WINDOWPLACEMENT])
275
+ for ($i = 0; $i -lt $tries; $i++) {
276
+ if (-not [PortalNative]::IsWindow($hwnd)) { return $false }
277
+ $placement = New-Object PortalNative+WINDOWPLACEMENT
278
+ $placement.length = $size
279
+ $placement.showCmd = $script:SW_SHOWNORMAL
280
+ $rect = New-Object PortalNative+RECT
281
+ $rect.Left = [int]$entry.x
282
+ $rect.Top = [int]$entry.y
283
+ $rect.Right = [int]$entry.x + [int]$entry.w
284
+ $rect.Bottom = [int]$entry.y + [int]$entry.h
285
+ $placement.rcNormalPosition = $rect
286
+ [void][PortalNative]::SetWindowPlacement($hwnd, [ref]$placement)
287
+ $after = $script:HWND_NOTOPMOST
288
+ if ($entry.topmost) { $after = $script:HWND_TOPMOST }
289
+ [void][PortalNative]::SetWindowPos($hwnd, $after, [int]$entry.x, [int]$entry.y, [int]$entry.w, [int]$entry.h, $script:SWP_SHOWWINDOW)
290
+ Start-Sleep -Milliseconds 140
291
+ if (-not [PortalNative]::IsIconic($hwnd)) { return $true }
292
+ }
293
+ return (-not [PortalNative]::IsIconic($hwnd))
294
+ }
295
+
296
+ function Keep-Topmost($entry, $rounds) {
297
+ # Chromium clears the topmost bit at unpredictable moments during the first seconds
298
+ # (first paint, favicon, network idle). This runs after the geometry has settled and
299
+ # only ever repairs that single bit: no move, no resize, no focus, no restore.
300
+ if (-not $entry.topmost) { return }
301
+ $hwnd = [IntPtr]$entry.hwnd
302
+ for ($i = 0; $i -lt $rounds; $i++) {
303
+ if (-not [PortalNative]::IsWindow($hwnd)) { return }
304
+ if ([PortalNative]::IsIconic($hwnd)) { return }
305
+ $ex = [PortalNative]::GetWindowLong($hwnd, $script:GWL_EXSTYLE)
306
+ if (($ex -band $script:WS_EX_TOPMOST) -eq 0) {
307
+ $flags = $script:SWP_NOMOVE -bor $script:SWP_NOSIZE -bor $script:SWP_NOACTIVATE
308
+ [void][PortalNative]::SetWindowPos($hwnd, $script:HWND_TOPMOST, 0, 0, 0, 0, $flags)
309
+ }
310
+ Start-Sleep -Milliseconds 400
311
+ }
312
+ }
313
+
314
+ function Settle-Window($entry, $maxMs) {
315
+ $hwnd = [IntPtr]$entry.hwnd
316
+ $started = [DateTime]::UtcNow
317
+ $stable = 0
318
+ $everFg = $false
319
+ $prevRect = ''
320
+ while ((([DateTime]::UtcNow) - $started).TotalMilliseconds -lt $maxMs) {
321
+ if (-not [PortalNative]::IsWindow($hwnd)) { return }
322
+ if ([PortalNative]::GetForegroundWindow() -eq $hwnd) { $everFg = $true }
323
+ if ([PortalNative]::IsIconic($hwnd)) {
324
+ if ($everFg) { Save-Layout $entry.profile $entry.url $hwnd; return }
325
+ [void](Force-Show $entry 2)
326
+ Start-Sleep -Milliseconds 160
327
+ continue
328
+ }
329
+ if ($entry.title) { [void][PortalNative]::SetWindowText($hwnd, [string]$entry.title) }
330
+ $rect = New-Object PortalNative+RECT
331
+ [void][PortalNative]::GetWindowRect($hwnd, [ref]$rect)
332
+ $moved = -not (($rect.Left -eq $entry.x) -and ($rect.Top -eq $entry.y) -and
333
+ (($rect.Right - $rect.Left) -eq $entry.w) -and (($rect.Bottom - $rect.Top) -eq $entry.h))
334
+ $rectKey = "$($rect.Left),$($rect.Top),$($rect.Right),$($rect.Bottom)"
335
+ # Only a *settled* difference while foreground means the user placed the window there.
336
+ # A single differing sample is just Chromium replaying its own bounds right after open,
337
+ # and the window is normally foreground at that moment, so requiring two identical
338
+ # samples keeps us from mistaking it for a drag and giving up on the geometry.
339
+ if ($moved -and ([PortalNative]::GetForegroundWindow() -eq $hwnd) -and ($rectKey -eq $prevRect)) {
340
+ $entry.x = $rect.Left
341
+ $entry.y = $rect.Top
342
+ $entry.w = $rect.Right - $rect.Left
343
+ $entry.h = $rect.Bottom - $rect.Top
344
+ Save-Layout $entry.profile $entry.url $hwnd
345
+ Keep-Topmost $entry 12
346
+ return
347
+ }
348
+ $prevRect = $rectKey
349
+ if ($moved) {
350
+ $stable = 0
351
+ Set-Geometry $entry
352
+ } else {
353
+ $ex = [PortalNative]::GetWindowLong($hwnd, $script:GWL_EXSTYLE)
354
+ $topOk = ((($ex -band $script:WS_EX_TOPMOST) -ne 0) -eq [bool]$entry.topmost)
355
+ if (-not $topOk) {
356
+ $after = $script:HWND_NOTOPMOST
357
+ if ($entry.topmost) { $after = $script:HWND_TOPMOST }
358
+ $flags = $script:SWP_NOMOVE -bor $script:SWP_NOSIZE -bor $script:SWP_NOACTIVATE
359
+ [void][PortalNative]::SetWindowPos($hwnd, $after, 0, 0, 0, 0, $flags)
360
+ } else {
361
+ $stable++
362
+ if ($stable -ge 6) {
363
+ Save-Layout $entry.profile $entry.url $hwnd
364
+ Keep-Topmost $entry 12
365
+ return
366
+ }
367
+ }
368
+ }
369
+ Start-Sleep -Milliseconds 300
370
+ }
371
+ Save-Layout $entry.profile $entry.url $hwnd
372
+ Keep-Topmost $entry 12
373
+ }
374
+
375
+ function Apply-Chrome($entry) { $hwnd = [IntPtr]$entry.hwnd
376
+ if ($entry.frameless) {
377
+ $style = [PortalNative]::GetWindowLong($hwnd, $script:GWL_STYLE)
378
+ $maskOut = $script:WS_CAPTION -bor $script:WS_THICKFRAME -bor $script:WS_SYSMENU -bor $script:WS_MINIMIZEBOX -bor $script:WS_MAXIMIZEBOX
379
+ $stripped = $style -band (-bnot $maskOut)
380
+ $newStyle = $stripped -bor $script:WS_POPUP
381
+ if ($newStyle -ne $style) { [void][PortalNative]::SetWindowLong($hwnd, $script:GWL_STYLE, $newStyle) }
382
+ }
383
+ $after = if ($entry.topmost) { $script:HWND_TOPMOST } else { $script:HWND_NOTOPMOST }
384
+ [void][PortalNative]::SetWindowPos($hwnd, $after, $entry.x, $entry.y, $entry.w, $entry.h, $script:SWP_FRAMECHANGED -bor $script:SWP_SHOWWINDOW)
385
+ # Win11 rounded corners; harmless no-op on older systems.
386
+ try {
387
+ $pref = 2
388
+ [void][PortalNative]::DwmSetWindowAttribute($hwnd, 33, [ref]$pref, 4)
389
+ } catch { }
390
+ }
391
+
392
+ function Open-Window($req) {
393
+ $key = [string]$req.key
394
+ $marker = [string]$req.marker
395
+ $existing = Get-Entry $key
396
+ if ($existing) {
397
+ # Repeated "open" calls must be invisible: this runs on every tool call, so it may
398
+ # not steal focus, move, or resize. Only bring it back if it was minimized and make
399
+ # sure it is still on top.
400
+ if ([PortalNative]::IsIconic([IntPtr]$existing.hwnd)) {
401
+ [void](Force-Show $existing 3)
402
+ }
403
+ if ($existing.title) { [void][PortalNative]::SetWindowText([IntPtr]$existing.hwnd, [string]$existing.title) }
404
+ $ex = [PortalNative]::GetWindowLong([IntPtr]$existing.hwnd, $script:GWL_EXSTYLE)
405
+ if ((($ex -band $script:WS_EX_TOPMOST) -ne 0) -ne [bool]$existing.topmost) {
406
+ $after = if ($existing.topmost) { $script:HWND_TOPMOST } else { $script:HWND_NOTOPMOST }
407
+ $flags = $script:SWP_NOMOVE -bor $script:SWP_NOSIZE -bor $script:SWP_NOACTIVATE
408
+ [void][PortalNative]::SetWindowPos([IntPtr]$existing.hwnd, $after, 0, 0, 0, 0, $flags)
409
+ }
410
+ Save-Layout $existing.profile $existing.url ([IntPtr]$existing.hwnd)
411
+ $raised = $false
412
+ if ($req.activate -ne $false) { $raised = Activate-Window $existing.hwnd }
413
+ return @{ ok = $true; key = $key; hwnd = [int64]$existing.hwnd; pid = $existing.pid; rect = @($existing.x, $existing.y, $existing.w, $existing.h); reused = $true; matched = 'key'; activated = $raised }
414
+ }
415
+
416
+ $width = [double]$req.w
417
+ $height = [double]$req.h
418
+ $anchor = if ($req.anchor) { [string]$req.anchor } else { 'right' }
419
+ $margin = if ($null -ne $req.margin) { [double]$req.margin } else { 24 }
420
+ $geo = Resolve-Geometry $width $height $anchor $margin
421
+
422
+ $hwnd = [IntPtr]::Zero
423
+ $proc = $null
424
+ $profile = [string]$req.profile
425
+ if (-not $profile) { throw 'missing profile dir' }
426
+ $url = [string]$req.url
427
+ $statePath = Join-Path $profile 'portal-window.json'
428
+
429
+ # A window the user has already dragged/resized comes back exactly where they left it;
430
+ # the anchor is only the first-ever placement.
431
+ $saved = Get-SavedLayout $profile $url
432
+ if ($saved) {
433
+ $work = Get-WorkArea
434
+ $savedW = [int]$saved.w
435
+ $savedH = [int]$saved.h
436
+ $fits = ($savedW -ge 240) -and ($savedH -ge 160) -and
437
+ ($savedW -le (($work.Right - $work.Left))) -and ($savedH -le (($work.Bottom - $work.Top)))
438
+ if ($fits) { $geo = @{ x = [int]$saved.x; y = [int]$saved.y; w = $savedW; h = $savedH } }
439
+ }
440
+
441
+ # One window per address, always: if any tracked entry already shows this URL, adopt it
442
+ # instead of opening a second one (a service that restarts on the same port must not
443
+ # stack windows, and two keys pointing at one port share the same window).
444
+ foreach ($otherKey in @($script:Windows.Keys)) {
445
+ $other = $script:Windows[$otherKey]
446
+ if (-not $other) { continue }
447
+ if ([string]$other.url -ne $url) { continue }
448
+ if (-not [PortalNative]::IsWindow([IntPtr]$other.hwnd)) { $script:Windows.Remove($otherKey); continue }
449
+ if ($otherKey -ne $key) {
450
+ $script:Windows.Remove($otherKey)
451
+ $other.key = $key
452
+ $script:Windows[$key] = $other
453
+ }
454
+ if ([PortalNative]::IsIconic([IntPtr]$other.hwnd)) {
455
+ [void](Force-Show $other 3)
456
+ }
457
+ if ($other.title) { [void][PortalNative]::SetWindowText([IntPtr]$other.hwnd, [string]$other.title) }
458
+ # Keep the user's own placement: only re-assert the topmost bit.
459
+ $ex = [PortalNative]::GetWindowLong([IntPtr]$other.hwnd, $script:GWL_EXSTYLE)
460
+ if ((($ex -band $script:WS_EX_TOPMOST) -ne 0) -ne [bool]$other.topmost) {
461
+ $after = if ($other.topmost) { $script:HWND_TOPMOST } else { $script:HWND_NOTOPMOST }
462
+ $flags = $script:SWP_NOMOVE -bor $script:SWP_NOSIZE -bor $script:SWP_NOACTIVATE
463
+ [void][PortalNative]::SetWindowPos([IntPtr]$other.hwnd, $after, 0, 0, 0, 0, $flags)
464
+ }
465
+ Save-Layout $other.profile $other.url ([IntPtr]$other.hwnd)
466
+ $raised = $false
467
+ if ($req.activate -ne $false) { $raised = Activate-Window $other.hwnd }
468
+ return @{ ok = $true; key = $key; hwnd = [int64]$other.hwnd; pid = $other.pid; rect = @($other.x, $other.y, $other.w, $other.h); reused = $true; matched = 'url'; activated = $raised }
469
+ }
470
+
471
+ # The window outlives the relay process that opened it (users keep it open), so we
472
+ # record which window belongs to this workbench and which URL it was opened with:
473
+ # - same URL (restart on the same port) -> adopt the old window, no flicker;
474
+ # - URL changed (auto port restart) -> close the old one and open a fresh one,
475
+ # otherwise it would sit on a dead port showing "not connected" forever.
476
+ $previous = $null
477
+ if (Test-Path $statePath) {
478
+ try { $previous = [System.IO.File]::ReadAllText($statePath) | ConvertFrom-Json } catch { $previous = $null }
479
+ }
480
+ if ($previous -and $previous.hwnd) {
481
+ $old = [IntPtr][int64]$previous.hwnd
482
+ if ([PortalNative]::IsWindow($old)) {
483
+ if ([string]$previous.url -eq $url) {
484
+ $ownerPid = 0
485
+ [void][PortalNative]::GetWindowThreadProcessId($old, [ref]$ownerPid)
486
+ $hwnd = $old
487
+ $proc = [pscustomobject]@{ Id = [int]$ownerPid }
488
+ } else {
489
+ [void][PortalNative]::PostMessage($old, $script:WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero)
490
+ for ($i = 0; $i -lt 20; $i++) {
491
+ Start-Sleep -Milliseconds 100
492
+ if (-not [PortalNative]::IsWindow($old)) { break }
493
+ }
494
+ if ([PortalNative]::IsWindow($old)) {
495
+ try { Stop-Process -Id ([int]$previous.pid) -Force -ErrorAction SilentlyContinue } catch { }
496
+ }
497
+ }
498
+ }
499
+ Remove-Item $statePath -Force -ErrorAction SilentlyContinue
500
+ }
501
+
502
+ if ($hwnd -eq [IntPtr]::Zero) {
503
+ $browser = [string]$req.browser
504
+ if (-not $browser -or -not (Test-Path $browser)) { throw "browser not found: $browser" }
505
+ # Chromium reads --window-size/--window-position in DIP, everything Win32-side is
506
+ # physical pixels: divide by the DPI scale so the browser's own initial placement
507
+ # already lands on our geometry instead of fighting it later.
508
+ $dipW = [int][Math]::Round($geo.w / $script:Scale)
509
+ $dipH = [int][Math]::Round($geo.h / $script:Scale)
510
+ $dipX = [int][Math]::Round($geo.x / $script:Scale)
511
+ $dipY = [int][Math]::Round($geo.y / $script:Scale)
512
+ $edgeArgs = @(
513
+ "--app=$url",
514
+ "--user-data-dir=$profile",
515
+ "--window-size=$dipW,$dipH",
516
+ "--window-position=$dipX,$dipY",
517
+ '--no-first-run',
518
+ '--no-default-browser-check',
519
+ '--disable-sync',
520
+ '--disable-features=msEdgeSidebarV2,msHubApps'
521
+ )
522
+ # Launch outside our process tree (WMI spawns under Wmiprvse): the MCP bridge and this
523
+ # agent are killed when the session ends, and a plain child would die with that job
524
+ # object. The window must outlive the session, so WMI is the default path and
525
+ # Start-Process is only the fallback.
526
+ $procId = 0
527
+ $quoted = @($browser) + ($edgeArgs | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } })
528
+ $cmdline = ($quoted | ForEach-Object { if ($_ -match '\s' -and $_ -notmatch '^"') { '"' + $_ + '"' } else { $_ } }) -join ' '
529
+ try {
530
+ # WMI children inherit a "hidden" startup show state, which Chromium then applies to
531
+ # its first window; after a window has been closed once that state sticks and every
532
+ # later launch comes back minimised. Ask for SW_SHOWNORMAL explicitly.
533
+ $startup = ([wmiclass]'Win32_ProcessStartup').CreateInstance()
534
+ $startup.ShowWindow = $script:SW_SHOWNORMAL
535
+ $created = ([wmiclass]'Win32_Process').Create($cmdline, $profile, $startup)
536
+ if ($created.ReturnValue -eq 0) { $procId = [int]$created.ProcessId }
537
+ } catch { }
538
+ if ($procId -le 0) {
539
+ $proc = Start-Process -FilePath $browser -ArgumentList $edgeArgs -PassThru -WindowStyle Normal
540
+ $procId = $proc.Id
541
+ }
542
+ for ($i = 0; $i -lt 120; $i++) {
543
+ Start-Sleep -Milliseconds 150
544
+ $hwnd = Find-Window $procId $marker
545
+ if ($hwnd -ne [IntPtr]::Zero) { break }
546
+ }
547
+ if ($hwnd -eq [IntPtr]::Zero) {
548
+ try { Stop-Process -Id $procId -Force -ErrorAction SilentlyContinue } catch { }
549
+ throw 'timed out waiting for the browser window (15s)'
550
+ }
551
+ }
552
+
553
+ $ownerPid = 0
554
+ [void][PortalNative]::GetWindowThreadProcessId($hwnd, [ref]$ownerPid)
555
+ if ($ownerPid -le 0) { $ownerPid = $procId }
556
+ $entry = [pscustomobject]@{
557
+ key = $key; pid = [int]$ownerPid; hwnd = [int64]$hwnd
558
+ x = $geo.x; y = $geo.y; w = $geo.w; h = $geo.h
559
+ title = [string]$req.title
560
+ topmost = ($req.topmost -ne $false)
561
+ frameless = ($req.frameless -eq $true)
562
+ profile = $profile; url = $url
563
+ }
564
+ try {
565
+ # UTF-8 without BOM: the title is Chinese, and ConvertFrom-Json in PS 5.1 chokes on a BOM.
566
+ $json = @{ hwnd = [int64]$hwnd; pid = [int]$ownerPid; url = $url; key = $key; title = $entry.title } | ConvertTo-Json -Compress
567
+ [System.IO.File]::WriteAllText($statePath, $json, (New-Object System.Text.UTF8Encoding $false))
568
+ } catch { }
569
+ $script:Windows[$key] = $entry
570
+ # A browser started from a windowless parent (node -> hidden PowerShell) can come up
571
+ # SW_HIDE/SW_MINIMIZE, and a minimized window reports rect -32000 so every geometry
572
+ # fix below silently fails. Force a normal show first, with the target geometry.
573
+ [void](Force-Show $entry 4)
574
+ Apply-Chrome $entry
575
+ Start-Sleep -Milliseconds 320
576
+ Set-Geometry $entry
577
+ Settle-Window $entry 14000
578
+ # Chromium can still collapse the window during the first seconds; make sure we hand back
579
+ # a window the user can actually see, at the geometry we promised.
580
+ [void](Force-Show $entry 4)
581
+ Set-Geometry $entry
582
+ # A summon from the HUD should land in front of the user; a repeated tool call (activate
583
+ # left implicit) must not steal focus while they are typing.
584
+ $raised = $false
585
+ if ($req.activate -ne $false) { $raised = Activate-Window $entry.hwnd }
586
+ return @{ ok = $true; key = $key; hwnd = $entry.hwnd; pid = $entry.pid; rect = @($entry.x, $entry.y, $entry.w, $entry.h); reused = $false; activated = $raised }
587
+ }
588
+
589
+ function Close-Window($req) {
590
+ $key = [string]$req.key
591
+ $entry = Get-Entry $key
592
+ if (-not $entry) { return @{ ok = $true; key = $key; closed = $false; note = 'not-open' } }
593
+ $hwnd = [IntPtr]$entry.hwnd
594
+ # Closing a window the user just dragged: remember where it was so reopening from the
595
+ # HUD lands there instead of back at the anchor.
596
+ Save-Layout $entry.profile $entry.url $hwnd
597
+ [void][PortalNative]::PostMessage($hwnd, $script:WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero)
598
+ for ($i = 0; $i -lt 20; $i++) {
599
+ Start-Sleep -Milliseconds 100
600
+ if (-not [PortalNative]::IsWindow($hwnd)) { break }
601
+ }
602
+ if ([PortalNative]::IsWindow($hwnd)) {
603
+ try { Stop-Process -Id $entry.pid -Force -ErrorAction SilentlyContinue } catch { }
604
+ }
605
+ if ($entry.profile) {
606
+ try { Remove-Item (Join-Path $entry.profile 'portal-window.json') -Force -ErrorAction SilentlyContinue } catch { }
607
+ }
608
+ $script:Windows.Remove($key)
609
+ return @{ ok = $true; key = $key; closed = $true }
610
+ }
611
+
612
+ function Invoke-Op($req) {
613
+ $op = [string]$req.op
614
+ switch ($op) {
615
+ 'open' { return Open-Window $req }
616
+ 'close' { return Close-Window $req }
617
+ 'focus' {
618
+ $entry = Get-Entry ([string]$req.key)
619
+ if (-not $entry) { return @{ ok = $false; error = 'not-open' } }
620
+ if ([PortalNative]::IsIconic([IntPtr]$entry.hwnd)) {
621
+ $saved = Get-SavedLayout $entry.profile $entry.url
622
+ if ($saved) {
623
+ $entry.x = [int]$saved.x; $entry.y = [int]$saved.y
624
+ $entry.w = [int]$saved.w; $entry.h = [int]$saved.h
625
+ }
626
+ [void](Force-Show $entry 3)
627
+ }
628
+ [void][PortalNative]::SetForegroundWindow([IntPtr]$entry.hwnd)
629
+ return @{ ok = $true; key = $entry.key; hwnd = $entry.hwnd }
630
+ }
631
+ # Bring a minimized window back without stealing foreground and without touching its
632
+ # geometry: the user may have moved or resized it since it was opened.
633
+ 'restore' {
634
+ $entry = Get-Entry ([string]$req.key)
635
+ if (-not $entry) { return @{ ok = $false; error = 'not-open' } }
636
+ $saved = Get-SavedLayout $entry.profile $entry.url
637
+ if ($saved) {
638
+ $entry.x = [int]$saved.x; $entry.y = [int]$saved.y
639
+ $entry.w = [int]$saved.w; $entry.h = [int]$saved.h
640
+ }
641
+ if ([PortalNative]::IsIconic([IntPtr]$entry.hwnd)) {
642
+ [void](Force-Show $entry 3)
643
+ }
644
+ $after = $script:HWND_NOTOPMOST
645
+ if ($entry.topmost) { $after = $script:HWND_TOPMOST }
646
+ $flags = $script:SWP_NOMOVE -bor $script:SWP_NOSIZE -bor $script:SWP_NOACTIVATE
647
+ [void][PortalNative]::SetWindowPos([IntPtr]$entry.hwnd, $after, 0, 0, 0, 0, $flags)
648
+ $rect = New-Object PortalNative+RECT
649
+ [void][PortalNative]::GetWindowRect([IntPtr]$entry.hwnd, [ref]$rect)
650
+ Save-Layout $entry.profile $entry.url ([IntPtr]$entry.hwnd)
651
+ return @{ ok = $true; key = $entry.key; hwnd = $entry.hwnd; rect = @($rect.Left, $rect.Top, ($rect.Right - $rect.Left), ($rect.Bottom - $rect.Top)) }
652
+ }
653
+ # Cheap "is the window still there / still on top" nudge. Used by every edit-time
654
+ # check, so it must stay silent: never move, never resize, never take focus -- the
655
+ # user may have dragged the window somewhere on purpose.
656
+ 'ping' {
657
+ $entry = Get-Entry ([string]$req.key)
658
+ if (-not $entry) { return @{ ok = $true; key = [string]$req.key; alive = $false } }
659
+ $hwnd = [IntPtr]$entry.hwnd
660
+ $ex = [PortalNative]::GetWindowLong($hwnd, $script:GWL_EXSTYLE)
661
+ $isTop = (($ex -band $script:WS_EX_TOPMOST) -ne 0)
662
+ if ($isTop -ne [bool]$entry.topmost) {
663
+ $after = if ($entry.topmost) { $script:HWND_TOPMOST } else { $script:HWND_NOTOPMOST }
664
+ $flags = $script:SWP_NOMOVE -bor $script:SWP_NOSIZE -bor $script:SWP_NOACTIVATE
665
+ [void][PortalNative]::SetWindowPos($hwnd, $after, 0, 0, 0, 0, $flags)
666
+ }
667
+ return @{ ok = $true; key = $entry.key; hwnd = $entry.hwnd; alive = $true; iconic = [PortalNative]::IsIconic($hwnd) }
668
+ }
669
+ 'drag' {
670
+ $entry = Get-Entry ([string]$req.key)
671
+ if (-not $entry) { return @{ ok = $false; error = 'not-open' } }
672
+ [void][PortalNative]::ReleaseCapture()
673
+ [void][PortalNative]::SendMessage([IntPtr]$entry.hwnd, $script:WM_NCLBUTTONDOWN, [IntPtr]$script:HTCAPTION, [IntPtr]::Zero)
674
+ $rect = New-Object PortalNative+RECT
675
+ [void][PortalNative]::GetWindowRect([IntPtr]$entry.hwnd, [ref]$rect)
676
+ $entry.x = $rect.Left; $entry.y = $rect.Top
677
+ return @{ ok = $true; key = $entry.key; rect = @($rect.Left, $rect.Top, ($rect.Right - $rect.Left), ($rect.Bottom - $rect.Top)) }
678
+ }
679
+ 'move' {
680
+ $entry = Get-Entry ([string]$req.key)
681
+ if (-not $entry) { return @{ ok = $false; error = 'not-open' } }
682
+ if ($null -ne $req.x) { $entry.x = [int]$req.x }
683
+ if ($null -ne $req.y) { $entry.y = [int]$req.y }
684
+ if ($null -ne $req.w) { $entry.w = [int]$req.w }
685
+ if ($null -ne $req.h) { $entry.h = [int]$req.h }
686
+ # A browser started from a hidden parent can come up minimized a moment after the
687
+ # open call; a minimized window reports rect -32000 and would swallow the placement.
688
+ # (Only the open path does this - a late 'move' must never resurrect a window the
689
+ # user docked on purpose; that is what the explicit 'restore' op is for.)
690
+ if ([PortalNative]::IsIconic([IntPtr]$entry.hwnd)) {
691
+ # allowRestore is only sent for the first corrections right after opening: the
692
+ # browser restores its own persisted (possibly minimized) window state while the
693
+ # page loads, so we need to undo that once. Later moves must not.
694
+ if ($req.allowRestore -eq $true) {
695
+ [void][PortalNative]::ShowWindow([IntPtr]$entry.hwnd, $script:SW_RESTORE)
696
+ [void][PortalNative]::ShowWindow([IntPtr]$entry.hwnd, $script:SW_SHOWNORMAL)
697
+ Start-Sleep -Milliseconds 200
698
+ } else {
699
+ return @{ ok = $true; key = $entry.key; skipped = 'iconic' }
700
+ }
701
+ }
702
+ # stale = only "last word" correction: if the user is already working in the
703
+ # window (it is foreground) and it already sits where the declaration wants it,
704
+ # leave it exactly alone. If it is foreground but misplaced, still fix the geometry.
705
+ if ($req.stale -eq $true -and [PortalNative]::GetForegroundWindow() -eq [IntPtr]$entry.hwnd) {
706
+ $now = New-Object PortalNative+RECT
707
+ [void][PortalNative]::GetWindowRect([IntPtr]$entry.hwnd, [ref]$now)
708
+ $already = ($now.Left -eq $entry.x) -and ($now.Top -eq $entry.y) -and
709
+ (($now.Right - $now.Left) -eq $entry.w) -and (($now.Bottom - $now.Top) -eq $entry.h)
710
+ if ($already) { return @{ ok = $true; key = $entry.key; skipped = 'foreground' } }
711
+ }
712
+ $after = if ($entry.topmost) { $script:HWND_TOPMOST } else { $script:HWND_NOTOPMOST }
713
+ [void][PortalNative]::SetWindowPos([IntPtr]$entry.hwnd, $after, $entry.x, $entry.y, $entry.w, $entry.h, $script:SWP_SHOWWINDOW)
714
+ return @{ ok = $true; key = $entry.key; rect = @($entry.x, $entry.y, $entry.w, $entry.h) }
715
+ }
716
+ 'topmost' {
717
+ $entry = Get-Entry ([string]$req.key)
718
+ if (-not $entry) { return @{ ok = $false; error = 'not-open' } }
719
+ $entry.topmost = ($req.on -ne $false)
720
+ $after = if ($entry.topmost) { $script:HWND_TOPMOST } else { $script:HWND_NOTOPMOST }
721
+ [void][PortalNative]::SetWindowPos([IntPtr]$entry.hwnd, $after, $entry.x, $entry.y, $entry.w, $entry.h, $script:SWP_SHOWWINDOW)
722
+ return @{ ok = $true; key = $entry.key; topmost = $entry.topmost }
723
+ }
724
+ 'state' {
725
+ $list = @()
726
+ foreach ($k in @($script:Windows.Keys)) {
727
+ $entry = Get-Entry $k
728
+ if (-not $entry) { continue }
729
+ # The user closing the window (X / Alt+F4) is not routed through us, so prune
730
+ # dead handles here: that is what lets "ensure" reopen a dismissed preview.
731
+ if (-not [PortalNative]::IsWindow([IntPtr]$entry.hwnd)) {
732
+ if ($entry.profile) {
733
+ try { Remove-Item (Join-Path $entry.profile 'portal-window.json') -Force -ErrorAction SilentlyContinue } catch { }
734
+ }
735
+ $script:Windows.Remove($k)
736
+ continue
737
+ }
738
+ $rect = New-Object PortalNative+RECT
739
+ [void][PortalNative]::GetWindowRect([IntPtr]$entry.hwnd, [ref]$rect)
740
+ # Remember where the user keeps this window so the next open comes back there.
741
+ Save-Layout $entry.profile $entry.url ([IntPtr]$entry.hwnd)
742
+ $list += @{ key = $entry.key; hwnd = $entry.hwnd; pid = $entry.pid; rect = @($rect.Left, $rect.Top, ($rect.Right - $rect.Left), ($rect.Bottom - $rect.Top)); topmost = $entry.topmost; iconic = [PortalNative]::IsIconic([IntPtr]$entry.hwnd) }
743
+ }
744
+ return @{ ok = $true; windows = $list; scale = $script:Scale; pid = $PID }
745
+ }
746
+ 'shutdown' { return @{ ok = $true; shutdown = $true } }
747
+ default { return @{ ok = $false; error = "unknown op: $op" } }
748
+ }
749
+ }
750
+
751
+ # When the parent (the MCP bridge) dies, stdin hits EOF. The window outlives us (WMI
752
+ # spawns it outside the job object), so for a short grace period keep the label and the
753
+ # topmost bit in place -- but never touch geometry and never restore a minimised window:
754
+ # by the time the parent goes away the user may already be arranging their desktop.
755
+ function Drain-Placement {
756
+ $deadline = [DateTime]::UtcNow.AddSeconds(8)
757
+ while ([DateTime]::UtcNow -lt $deadline) {
758
+ $alive = $false
759
+ foreach ($entry in @($script:Windows.Values)) {
760
+ $hwnd = [IntPtr]$entry.hwnd
761
+ if (-not [PortalNative]::IsWindow($hwnd)) { continue }
762
+ $alive = $true
763
+ if ([PortalNative]::IsIconic($hwnd)) { continue }
764
+ if ($entry.title) { [void][PortalNative]::SetWindowText($hwnd, [string]$entry.title) }
765
+ $ex = [PortalNative]::GetWindowLong($hwnd, $script:GWL_EXSTYLE)
766
+ $isTop = (($ex -band $script:WS_EX_TOPMOST) -ne 0)
767
+ if ($isTop -ne [bool]$entry.topmost) {
768
+ $after = $script:HWND_NOTOPMOST
769
+ if ($entry.topmost) { $after = $script:HWND_TOPMOST }
770
+ $flags = $script:SWP_NOMOVE -bor $script:SWP_NOSIZE -bor $script:SWP_NOACTIVATE
771
+ [void][PortalNative]::SetWindowPos($hwnd, $after, 0, 0, 0, 0, $flags)
772
+ }
773
+ Save-Layout $entry.profile $entry.url $hwnd
774
+ }
775
+ if (-not $alive) { break }
776
+ Start-Sleep -Milliseconds 700
777
+ }
778
+ }
779
+
780
+ while ($true) {
781
+ $line = $null
782
+ # A closed pipe can throw instead of returning $null; either way it means the parent
783
+ # (the MCP bridge) is gone and we must fall through to the drain below, not die here.
784
+ try { $line = [Console]::In.ReadLine() } catch { $line = $null }
785
+ if ($null -eq $line) { Drain-Placement; break }
786
+ if (-not $line.Trim()) { continue }
787
+ $req = $null
788
+ $response = $null
789
+ try {
790
+ $req = $line | ConvertFrom-Json
791
+ $response = Invoke-Op $req
792
+ } catch {
793
+ # If the request itself is unparsable we still need to answer on the same id,
794
+ # otherwise the node side sits in its pending map until the timeout fires.
795
+ $echoId = $null
796
+ if (-not $req) {
797
+ $match = [regex]::Match($line, '"id"\s*:\s*"([^"]*)"')
798
+ if ($match.Success) { $echoId = $match.Groups[1].Value }
799
+ }
800
+ $response = @{ ok = $false; error = [string]$_.Exception.Message }
801
+ if ($req) { $response.id = [string]$req.id; $response.op = [string]$req.op }
802
+ elseif ($echoId) { $response.id = $echoId }
803
+ }
804
+ if ($req) {
805
+ if (-not $response.ContainsKey('id')) { $response.id = [string]$req.id }
806
+ if (-not $response.ContainsKey('op')) { $response.op = [string]$req.op }
807
+ }
808
+ [Console]::Out.WriteLine(($response | ConvertTo-Json -Compress -Depth 6))
809
+ [Console]::Out.Flush()
810
+ if ($response.ContainsKey('shutdown') -and $response.shutdown) { break }
811
+ }