@agy-daddy/plugin-cli 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Antigravity Context Viewer Contributors
4
+ Copyright (c) 2026 Agy-Daddy Contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ Agy-Daddy CLI Launcher Plugin (@agy-daddy/plugin-cli)
2
+
3
+ This project incorporates cross-platform terminal detection, escaping, and
4
+ multiplexer host validation derived from:
5
+ - iamvicliu/antigravity-suite (baseline commit c349284: meter-cli-launcher.js,
6
+ meter-terminals.js)
7
+ Copyright (c) 2026 Antigravity Context Viewer Contributors (MIT License)
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # @agy-daddy/plugin-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Agy-Daddy Layer-1 官方插件:顶栏 CLI 启动胶囊与跨平台终端(Terminal / iTerm2 / Ghostty / Warp / Rex / WezTerm / tmux / Windows Terminal / PowerShell)启动器。
4
+
5
+ ## 特性
6
+ - 隔离世界安全注入:顶栏按钮经 Bridge 安全触发,不访问页面全局。
7
+ - 严格校验并转义 `muxHost` 与工作目录参数,防止命令注入。
8
+ - 软消费可选 `proxy.getCliEnv()` 自动继承 `127.0.0.1:18766` 代理环境并恢复交互终端真彩色。
@@ -0,0 +1,49 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "id": "agy-daddy.cli",
4
+ "publisher": "agy-daddy",
5
+ "version": "1.0.0",
6
+ "license": "MIT",
7
+ "displayName": {
8
+ "zh-CN": "CLI 终端启动器",
9
+ "en": "CLI Terminal Launcher"
10
+ },
11
+ "description": {
12
+ "zh-CN": "顶栏 CLI 胶囊与多平台/多复用器(Rex/WezTerm/tmux)终端一键启动",
13
+ "en": "Topbar CLI capsule and one-click terminal launcher across Rex, WezTerm, tmux, and system shells"
14
+ },
15
+ "engines": {
16
+ "agyDaddy": "^1.0.0",
17
+ "antigravity": ">=2.32.0"
18
+ },
19
+ "main": "./src/node.js",
20
+ "renderer": "./src/renderer.js",
21
+ "world": "isolated",
22
+ "activationEvents": ["onStartup"],
23
+ "requires": {
24
+ "anchors": ["topbar.rightCluster"]
25
+ },
26
+ "provides": {
27
+ "services": {
28
+ "cli": { "version": "1.0.0", "realm": "node" }
29
+ }
30
+ },
31
+ "consumes": {
32
+ "proxy": { "version": "^1.0.0", "optional": true }
33
+ },
34
+ "permissions": [
35
+ "dom:write",
36
+ "bridge:route",
37
+ "process:spawn",
38
+ "fs:brain-read",
39
+ "rpc:read"
40
+ ],
41
+ "contributes": {
42
+ "topbar.units": [{ "id": "cli", "order": 40 }],
43
+ "settings": { "schema": "./settings.schema.json" },
44
+ "commands": [
45
+ { "id": "cli.launch", "title": { "zh-CN": "在新终端启动 CLI", "en": "Launch CLI in terminal" } }
46
+ ],
47
+ "locales": "./locales"
48
+ }
49
+ }
package/baseline.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "source": "iamvicliu/antigravity-suite",
3
+ "absorbedSha": "c349284",
4
+ "paths": [
5
+ "meter-cli-launcher.js",
6
+ "meter-terminals.js",
7
+ "meter-cli-launcher.test.js",
8
+ "scripts/cli-window-helper.cs"
9
+ ]
10
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "unit.label": "CLI",
3
+ "unit.launched": "CLI Launched"
4
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "unit.label": "CLI",
3
+ "unit.launched": "CLI 已拉起"
4
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@agy-daddy/plugin-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Agy-Daddy multi-platform terminal and multiplexer (Rex/WezTerm/tmux) CLI launcher plugin",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/agy-daddy/agy-daddy.git",
9
+ "directory": "agy-daddy-plugin-cli"
10
+ },
11
+ "main": "./src/node.js",
12
+ "agyPlugin": "./agy-plugin.json",
13
+ "files": [
14
+ "agy-plugin.json",
15
+ "settings.schema.json",
16
+ "src/",
17
+ "locales/",
18
+ "scripts/cli-window-helper.cs",
19
+ "baseline.json",
20
+ "README.md",
21
+ "LICENSE",
22
+ "NOTICE"
23
+ ],
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "scripts": {
28
+ "test": "AGY_DADDY_TEST_MODE=1 node --test test/*.test.js"
29
+ },
30
+ "engines": {
31
+ "node": ">=22.4.0"
32
+ }
33
+ }
@@ -0,0 +1,453 @@
1
+ using System;
2
+ using System.Collections.Generic;
3
+ using System.Diagnostics;
4
+ using System.IO;
5
+ using System.Runtime.InteropServices;
6
+ using System.Text;
7
+ using System.Threading;
8
+
9
+ public class Program {
10
+ [StructLayout(LayoutKind.Sequential)]
11
+ public struct Rect {
12
+ public int Left;
13
+ public int Top;
14
+ public int Right;
15
+ public int Bottom;
16
+ }
17
+
18
+ [StructLayout(LayoutKind.Sequential)]
19
+ public struct Point {
20
+ public int X;
21
+ public int Y;
22
+ }
23
+
24
+ [StructLayout(LayoutKind.Sequential)]
25
+ public struct MonitorInfo {
26
+ public int cbSize;
27
+ public Rect rcMonitor;
28
+ public Rect rcWork;
29
+ public uint dwFlags;
30
+ }
31
+
32
+ [StructLayout(LayoutKind.Sequential)]
33
+ public struct PROCESSENTRY32 {
34
+ public uint dwSize;
35
+ public uint cntUsage;
36
+ public uint th32ProcessID;
37
+ public IntPtr th32DefaultHeapID;
38
+ public uint th32ModuleID;
39
+ public uint cntThreads;
40
+ public uint th32ParentProcessID;
41
+ public int pcPriClassBase;
42
+ public uint dwFlags;
43
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
44
+ public string szExeFile;
45
+ }
46
+
47
+ delegate bool EnumDesktopWindowsProc(IntPtr hWnd, IntPtr lParam);
48
+ [DllImport("user32.dll", SetLastError = true)] static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags, bool fInherit, uint dwDesiredAccess);
49
+ [DllImport("user32.dll", SetLastError = true)] static extern bool CloseDesktop(IntPtr hDesktop);
50
+ [DllImport("user32.dll", SetLastError = true)] static extern bool SetThreadDesktop(IntPtr hDesktop);
51
+ [DllImport("user32.dll", SetLastError = true)] static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDesktopWindowsProc lpfn, IntPtr lParam);
52
+
53
+ [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr hWnd);
54
+ [DllImport("user32.dll")] static extern bool IsIconic(IntPtr hWnd);
55
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
56
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
57
+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
58
+ [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
59
+
60
+ [DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
61
+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
62
+ [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags);
63
+ [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
64
+ [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
65
+ [DllImport("user32.dll")] static extern IntPtr MonitorFromPoint(Point pt, uint dwFlags);
66
+ [DllImport("user32.dll")] static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);
67
+ [DllImport("user32.dll")] static extern bool GetCursorPos(out Point lpPoint);
68
+ [DllImport("user32.dll")] static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfo lpmi);
69
+ [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd);
70
+ [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr hWnd);
71
+ [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
72
+ [DllImport("user32.dll")] static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
73
+ [DllImport("user32.dll")] static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
74
+ [DllImport("user32.dll")] static extern bool AllowSetForegroundWindow(int dwProcessId);
75
+ [DllImport("user32.dll")] static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
76
+
77
+ [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
78
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
79
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
80
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr hObject);
81
+
82
+ static readonly IntPtr HWND_TOPMOST = (IntPtr)(-1);
83
+ static readonly IntPtr HWND_NOTOPMOST = (IntPtr)(-2);
84
+ const uint SWP_SHOWWINDOW = 0x0040;
85
+ const int SW_RESTORE = 9;
86
+ const uint MONITOR_DEFAULTTONEAREST = 2;
87
+ const uint GENERIC_ALL = 0x10000000;
88
+ const byte VK_MENU = 0x12;
89
+ const uint KEYEVENTF_KEYUP = 0x0002;
90
+ const uint GA_ROOT = 2;
91
+
92
+ static string EscapeJson(string str) {
93
+ if (str == null) return "";
94
+ return str.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "").Replace("\n", " ");
95
+ }
96
+
97
+ static bool IsProcessTreeRelated(uint windowPid, uint launchedPid) {
98
+ if (windowPid == 0 || launchedPid == 0) return false;
99
+ if (windowPid == launchedPid) return true;
100
+
101
+ var parentMap = new Dictionary<uint, uint>();
102
+ IntPtr snap = CreateToolhelp32Snapshot(0x00000002, 0);
103
+ if (snap != IntPtr.Zero && snap.ToInt64() != -1) {
104
+ PROCESSENTRY32 pe = new PROCESSENTRY32();
105
+ pe.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));
106
+ if (Process32First(snap, ref pe)) {
107
+ do {
108
+ parentMap[pe.th32ProcessID] = pe.th32ParentProcessID;
109
+ } while (Process32Next(snap, ref pe));
110
+ }
111
+ CloseHandle(snap);
112
+ }
113
+
114
+ // 向上追溯 launchedPid 的父进程链(如 cmd.exe -> OpenConsole.exe -> WindowsTerminal.exe)
115
+ uint curr = launchedPid;
116
+ int depth = 0;
117
+ while (curr != 0 && parentMap.ContainsKey(curr) && depth < 10) {
118
+ uint parent = parentMap[curr];
119
+ if (parent == windowPid) return true;
120
+ curr = parent;
121
+ depth++;
122
+ }
123
+
124
+ // 向上追溯 windowPid(如窗口进程是 launchedPid 的子进程)
125
+ curr = windowPid;
126
+ depth = 0;
127
+ while (curr != 0 && parentMap.ContainsKey(curr) && depth < 10) {
128
+ uint parent = parentMap[curr];
129
+ if (parent == launchedPid) return true;
130
+ curr = parent;
131
+ depth++;
132
+ }
133
+
134
+ return false;
135
+ }
136
+
137
+ static void ForceForeground(IntPtr targetHwnd, uint targetPid) {
138
+ try {
139
+ AllowSetForegroundWindow((int)targetPid);
140
+ AllowSetForegroundWindow(-1);
141
+
142
+ // 模拟短 Alt 键脉冲解除 Windows 前台锁定超时
143
+ keybd_event(VK_MENU, 0, 0, UIntPtr.Zero);
144
+ keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
145
+
146
+ IntPtr curFg = GetForegroundWindow();
147
+ uint curFgPid = 0;
148
+ uint curFgThread = GetWindowThreadProcessId(curFg, out curFgPid);
149
+ uint myThread = GetCurrentThreadId();
150
+
151
+ if (curFgThread != 0 && curFgThread != myThread) {
152
+ AttachThreadInput(myThread, curFgThread, true);
153
+ }
154
+
155
+ if (IsIconic(targetHwnd)) {
156
+ ShowWindow(targetHwnd, SW_RESTORE);
157
+ }
158
+
159
+ SetForegroundWindow(targetHwnd);
160
+ BringWindowToTop(targetHwnd);
161
+ SwitchToThisWindow(targetHwnd, true);
162
+
163
+ if (curFgThread != 0 && curFgThread != myThread) {
164
+ AttachThreadInput(myThread, curFgThread, false);
165
+ }
166
+ } catch {}
167
+ }
168
+
169
+ public static int Main(string[] args) {
170
+ Console.OutputEncoding = Encoding.UTF8;
171
+ IntPtr prevDpi = SetThreadDpiAwarenessContext((IntPtr)(-4));
172
+
173
+ string runnerBat = "";
174
+ string cwd = "";
175
+ long ownerHwndVal = 0;
176
+ int customWidth = 0;
177
+ int customHeight = 0;
178
+
179
+ for (int i = 0; i < args.Length; i++) {
180
+ if (args[i] == "--cmd" && i + 1 < args.Length) runnerBat = args[++i];
181
+ else if (args[i] == "--cwd" && i + 1 < args.Length) cwd = args[++i];
182
+ else if (args[i] == "--owner" && i + 1 < args.Length) long.TryParse(args[++i], out ownerHwndVal);
183
+ else if (args[i] == "--width" && i + 1 < args.Length) int.TryParse(args[++i], out customWidth);
184
+ else if (args[i] == "--height" && i + 1 < args.Length) int.TryParse(args[++i], out customHeight);
185
+ }
186
+
187
+ if (string.IsNullOrEmpty(runnerBat) || !File.Exists(runnerBat)) {
188
+ Console.WriteLine("{\"ok\":false,\"terminalSpawned\":false,\"error\":\"runner script not found: " + EscapeJson(runnerBat) + "\"}");
189
+ return 1;
190
+ }
191
+
192
+ if (string.IsNullOrEmpty(cwd) || !Directory.Exists(cwd)) {
193
+ cwd = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
194
+ }
195
+
196
+ IntPtr hDesk = OpenDesktop("Default", 0, false, GENERIC_ALL);
197
+ if (hDesk != IntPtr.Zero) {
198
+ SetThreadDesktop(hDesk);
199
+ }
200
+
201
+ AllowSetForegroundWindow(-1);
202
+
203
+ string sessionTag = "AGCLI_" + Guid.NewGuid().ToString("N").Substring(0, 10);
204
+
205
+ // 1. 快照当前已存在的终端窗口(避免混淆)
206
+ var existingHwnds = new HashSet<IntPtr>();
207
+ EnumDesktopWindows(hDesk, (hWnd, lParam) => {
208
+ if (!IsWindowVisible(hWnd)) return true;
209
+ StringBuilder sbClass = new StringBuilder(128);
210
+ GetClassName(hWnd, sbClass, 128);
211
+ string cls = sbClass.ToString();
212
+ if (cls == "CASCADIA_HOSTING_WINDOW_CLASS" || cls == "ConsoleWindowClass") {
213
+ existingHwnds.Add(hWnd);
214
+ }
215
+ return true;
216
+ }, IntPtr.Zero);
217
+
218
+ // 2. 启动终端 cmd
219
+ string cmdArgs = string.Format("/d /k \"title Antigravity CLI [{0}] & \"{1}\"\"", sessionTag, runnerBat);
220
+ ProcessStartInfo psi = new ProcessStartInfo {
221
+ FileName = "cmd.exe",
222
+ Arguments = cmdArgs,
223
+ WorkingDirectory = cwd,
224
+ UseShellExecute = true
225
+ };
226
+
227
+ Stopwatch sw = Stopwatch.StartNew();
228
+ Process proc = null;
229
+ try {
230
+ proc = Process.Start(psi);
231
+ } catch (Exception ex) {
232
+ Console.WriteLine("{\"ok\":false,\"terminalSpawned\":false,\"error\":\"Process.Start failed: " + EscapeJson(ex.Message) + "\"}");
233
+ return 2;
234
+ }
235
+
236
+ int launchedPid = proc != null ? proc.Id : 0;
237
+ if (launchedPid == 0) {
238
+ Console.WriteLine("{\"ok\":false,\"terminalSpawned\":false,\"error\":\"Process.Start returned empty PID\"}");
239
+ return 2;
240
+ }
241
+
242
+ // 3. 轮询查找目标顶级可见窗口(最长 4.5 秒)
243
+ IntPtr targetHwnd = IntPtr.Zero;
244
+ uint targetPid = 0;
245
+ string targetClass = "";
246
+ string targetTitle = "";
247
+ string matchReason = "";
248
+
249
+ for (int i = 0; i < 90; i++) {
250
+ Thread.Sleep(50);
251
+ EnumDesktopWindows(hDesk, (hWnd, lParam) => {
252
+ if (!IsWindowVisible(hWnd)) return true;
253
+ StringBuilder sbClass = new StringBuilder(128);
254
+ GetClassName(hWnd, sbClass, 128);
255
+ string cls = sbClass.ToString();
256
+ if (cls != "CASCADIA_HOSTING_WINDOW_CLASS" && cls != "ConsoleWindowClass") return true;
257
+
258
+ StringBuilder sbTitle = new StringBuilder(256);
259
+ GetWindowText(hWnd, sbTitle, 256);
260
+ string title = sbTitle.ToString();
261
+
262
+ uint pid = 0;
263
+ GetWindowThreadProcessId(hWnd, out pid);
264
+
265
+ // 优先 1:唯一会话标识精确匹配(最强特征)
266
+ if (title.Contains(sessionTag)) {
267
+ targetHwnd = hWnd;
268
+ targetPid = pid;
269
+ targetClass = cls;
270
+ targetTitle = title;
271
+ matchReason = "session_tag_match";
272
+ return false;
273
+ }
274
+
275
+ // 优先 2:新出现且具备严谨的进程树血缘关联(绝不仅凭新窗口盲目认领)
276
+ if (!existingHwnds.Contains(hWnd) && targetHwnd == IntPtr.Zero) {
277
+ if (IsProcessTreeRelated(pid, (uint)launchedPid)) {
278
+ targetHwnd = hWnd;
279
+ targetPid = pid;
280
+ targetClass = cls;
281
+ targetTitle = title;
282
+ matchReason = "process_tree_relationship";
283
+ }
284
+ }
285
+ return true;
286
+ }, IntPtr.Zero);
287
+
288
+ if (targetHwnd != IntPtr.Zero && matchReason == "session_tag_match") {
289
+ break;
290
+ }
291
+ }
292
+
293
+ long findElapsedMs = sw.ElapsedMilliseconds;
294
+
295
+ if (targetHwnd == IntPtr.Zero) {
296
+ // 终端已创建但窗口查找超时
297
+ Console.WriteLine(string.Format("{{\"ok\":false,\"terminalSpawned\":true,\"cliAlive\":true,\"windowLocated\":false,\"error\":\"timeout waiting for terminal window\",\"elapsedMs\":{0},\"cmdPid\":{1}}}",
298
+ findElapsedMs, launchedPid));
299
+ return 3;
300
+ }
301
+
302
+ string targetProcName = "unknown";
303
+ try {
304
+ targetProcName = Process.GetProcessById((int)targetPid).ProcessName;
305
+ } catch {}
306
+
307
+ // 4. 确定当前操作所在的显示器工作区
308
+ Point pt;
309
+ IntPtr hMon = IntPtr.Zero;
310
+ if (GetCursorPos(out pt)) {
311
+ hMon = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
312
+ }
313
+ if (hMon == IntPtr.Zero && ownerHwndVal != 0) {
314
+ hMon = MonitorFromWindow((IntPtr)ownerHwndVal, MONITOR_DEFAULTTONEAREST);
315
+ }
316
+ if (hMon == IntPtr.Zero) {
317
+ hMon = MonitorFromWindow(targetHwnd, MONITOR_DEFAULTTONEAREST);
318
+ }
319
+
320
+ MonitorInfo mi = new MonitorInfo();
321
+ mi.cbSize = Marshal.SizeOf(typeof(MonitorInfo));
322
+ if (!GetMonitorInfo(hMon, ref mi)) {
323
+ mi.rcWork = new Rect { Left = 0, Top = 0, Right = 1920, Bottom = 1080 };
324
+ }
325
+
326
+ int workW = mi.rcWork.Right - mi.rcWork.Left;
327
+ int workH = mi.rcWork.Bottom - mi.rcWork.Top;
328
+
329
+ int finalW = customWidth > 0 ? customWidth : Math.Min(1100, Math.Max(700, (int)(workW * 0.65)));
330
+ int finalH = customHeight > 0 ? customHeight : Math.Min(700, Math.Max(450, (int)(workH * 0.65)));
331
+ finalW = Math.Min(finalW, (int)(workW * 0.90));
332
+ finalH = Math.Min(finalH, (int)(workH * 0.90));
333
+
334
+ int targetX = mi.rcWork.Left + (workW - finalW) / 2;
335
+ int targetY = mi.rcWork.Top + (workH - finalH) / 2;
336
+
337
+ if (IsIconic(targetHwnd)) {
338
+ ShowWindow(targetHwnd, SW_RESTORE);
339
+ }
340
+
341
+ // 5. TOPMOST 置顶并移动到精确居中位置
342
+ bool swp1 = SetWindowPos(targetHwnd, HWND_TOPMOST, targetX, targetY, finalW, finalH, SWP_SHOWWINDOW);
343
+
344
+ // 6. 撤销 TOPMOST,变为普通顶层窗口(允许后续被其他正常窗口遮挡)
345
+ bool swp2 = SetWindowPos(targetHwnd, HWND_NOTOPMOST, targetX, targetY, finalW, finalH, SWP_SHOWWINDOW);
346
+
347
+ // 7. 强力激活前台与键盘输入焦点
348
+ ForceForeground(targetHwnd, targetPid);
349
+
350
+ // 8. 测量实际位置与中心偏差
351
+ Rect actualRect;
352
+ bool rectOk = GetWindowRect(targetHwnd, out actualRect);
353
+ int actualW = actualRect.Right - actualRect.Left;
354
+ int actualH = actualRect.Bottom - actualRect.Top;
355
+ int actualCenterX = actualRect.Left + actualW / 2;
356
+ int actualCenterY = actualRect.Top + actualH / 2;
357
+ int workCenterX = mi.rcWork.Left + workW / 2;
358
+ int workCenterY = mi.rcWork.Top + workH / 2;
359
+ int deltaX = actualCenterX - workCenterX;
360
+ int deltaY = actualCenterY - workCenterY;
361
+
362
+ // 居中偏差容差为 25 像素
363
+ bool isCentered = rectOk && (Math.Abs(deltaX) <= 25) && (Math.Abs(deltaY) <= 25);
364
+
365
+ // 9. 检验前台状态(检验顶级窗口或其输入根窗口是否为目标窗口)
366
+ Thread.Sleep(80);
367
+ IntPtr fgHwnd1 = GetForegroundWindow();
368
+ Thread.Sleep(150);
369
+ IntPtr fgHwnd2 = GetForegroundWindow();
370
+
371
+ bool isFgFinal = (fgHwnd2 == targetHwnd) || (GetAncestor(fgHwnd2, GA_ROOT) == targetHwnd);
372
+ long totalElapsedMs = sw.ElapsedMilliseconds;
373
+
374
+ // 10. 检查 CLI 进程存活状态
375
+ bool cliAlive = false;
376
+ try {
377
+ Process p = Process.GetProcessById(launchedPid);
378
+ cliAlive = !p.HasExited;
379
+ } catch {}
380
+
381
+ // 综合判定成功:API 正常、居中达标、前台激活、CLI 存活
382
+ bool placementOk = rectOk && (swp1 || swp2) && isCentered;
383
+ bool allOk = placementOk && isFgFinal && cliAlive;
384
+
385
+ List<string> issues = new List<string>();
386
+ if (!rectOk) issues.Add("GetWindowRect failed");
387
+ if (!swp1 && !swp2) issues.Add("SetWindowPos failed");
388
+ if (!isCentered) issues.Add(string.Format("Window not centered (dx={0}, dy={1})", deltaX, deltaY));
389
+ if (!isFgFinal) issues.Add("Foreground activation failed");
390
+ if (!cliAlive) issues.Add("CLI process exited prematurely");
391
+
392
+ string errorMsg = issues.Count > 0 ? string.Join("; ", issues.ToArray()) : "";
393
+
394
+ // 输出结构化 JSON
395
+ string json = string.Format(
396
+ "{{" +
397
+ "\"ok\":{0}," +
398
+ "\"terminalSpawned\":true," +
399
+ "\"cliAlive\":{1}," +
400
+ "\"windowLocated\":true," +
401
+ "\"isCentered\":{2}," +
402
+ "\"isForeground\":{3}," +
403
+ "\"posSuccess\":{4}," +
404
+ "\"error\":{5}," +
405
+ "\"sessionTag\":\"{6}\"," +
406
+ "\"matchReason\":\"{7}\"," +
407
+ "\"cmdPid\":{8}," +
408
+ "\"windowHwnd\":\"0x{9:X8}\"," +
409
+ "\"windowHwndVal\":{10}," +
410
+ "\"windowPid\":{11}," +
411
+ "\"processName\":\"{12}\"," +
412
+ "\"className\":\"{13}\"," +
413
+ "\"title\":\"{14}\"," +
414
+ "\"workArea\":{{\"left\":{15},\"top\":{16},\"right\":{17},\"bottom\":{18},\"width\":{19},\"height\":{20}}}," +
415
+ "\"targetRect\":{{\"left\":{21},\"top\":{22},\"width\":{23},\"height\":{24}}}," +
416
+ "\"actualRect\":{{\"left\":{25},\"top\":{26},\"width\":{27},\"height\":{28}}}," +
417
+ "\"centerOffset\":{{\"dx\":{29},\"dy\":{30}}}," +
418
+ "\"foregroundHwnd\":\"0x{31:X8}\"," +
419
+ "\"findElapsedMs\":{32}," +
420
+ "\"totalElapsedMs\":{33}" +
421
+ "}}",
422
+ allOk ? "true" : "false",
423
+ cliAlive ? "true" : "false",
424
+ isCentered ? "true" : "false",
425
+ isFgFinal ? "true" : "false",
426
+ (swp1 || swp2) ? "true" : "false",
427
+ string.IsNullOrEmpty(errorMsg) ? "null" : "\"" + EscapeJson(errorMsg) + "\"",
428
+ sessionTag,
429
+ matchReason,
430
+ launchedPid,
431
+ targetHwnd.ToInt64(),
432
+ targetHwnd.ToInt64(),
433
+ targetPid,
434
+ EscapeJson(targetProcName),
435
+ EscapeJson(targetClass),
436
+ EscapeJson(targetTitle),
437
+ mi.rcWork.Left, mi.rcWork.Top, mi.rcWork.Right, mi.rcWork.Bottom, workW, workH,
438
+ targetX, targetY, finalW, finalH,
439
+ actualRect.Left, actualRect.Top, actualW, actualH,
440
+ deltaX, deltaY,
441
+ fgHwnd2.ToInt64(),
442
+ findElapsedMs,
443
+ totalElapsedMs
444
+ );
445
+
446
+ Console.WriteLine(json);
447
+
448
+ if (hDesk != IntPtr.Zero) CloseDesktop(hDesk);
449
+ if (prevDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(prevDpi);
450
+
451
+ return allOk ? 0 : 10;
452
+ }
453
+ }