@aivin-labs/cli 1.0.5 → 1.0.8

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 (67) hide show
  1. package/README.md +263 -216
  2. package/bin/cli.mjs +1780 -1366
  3. package/bin/lib/browserAutomation.mjs +655 -648
  4. package/bin/lib/browserTui.mjs +276 -251
  5. package/bin/lib/cancellation.mjs +61 -0
  6. package/bin/lib/mcpProxy.mjs +869 -837
  7. package/bin/lib/missionStream.mjs +696 -691
  8. package/bin/lib/releaseKeys.mjs +9 -0
  9. package/bin/lib/remote/activityLog.mjs +68 -0
  10. package/bin/lib/remote/autoStart.mjs +457 -0
  11. package/bin/lib/remote/autoUpdate.mjs +129 -0
  12. package/bin/lib/remote/brand.mjs +60 -0
  13. package/bin/lib/remote/browserTunnel.mjs +292 -0
  14. package/bin/lib/remote/callLedger.mjs +134 -0
  15. package/bin/lib/remote/cdpPolicy.mjs +66 -0
  16. package/bin/lib/remote/client.mjs +726 -0
  17. package/bin/lib/remote/constants.mjs +173 -0
  18. package/bin/lib/remote/credentials.mjs +208 -0
  19. package/bin/lib/remote/daemonLock.mjs +86 -0
  20. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  21. package/bin/lib/remote/deviceMemory.mjs +246 -0
  22. package/bin/lib/remote/deviceProfile.mjs +142 -0
  23. package/bin/lib/remote/deviceWatches.mjs +138 -0
  24. package/bin/lib/remote/docText.mjs +117 -0
  25. package/bin/lib/remote/fileIndexer.mjs +399 -0
  26. package/bin/lib/remote/gui/index.mjs +245 -0
  27. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  28. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  29. package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
  30. package/bin/lib/remote/httpTransfer.mjs +89 -0
  31. package/bin/lib/remote/idempotency.mjs +135 -0
  32. package/bin/lib/remote/keepAwake.mjs +100 -0
  33. package/bin/lib/remote/localConfirm.mjs +268 -0
  34. package/bin/lib/remote/localPolicy.mjs +249 -0
  35. package/bin/lib/remote/mascot/assets.mjs +218 -0
  36. package/bin/lib/remote/mascot/hostSource.mjs +362 -0
  37. package/bin/lib/remote/mascot/index.mjs +322 -0
  38. package/bin/lib/remote/mascot/labels.mjs +83 -0
  39. package/bin/lib/remote/mascot/strings.mjs +189 -0
  40. package/bin/lib/remote/memberFsPool.mjs +134 -0
  41. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  42. package/bin/lib/remote/mission.mjs +156 -0
  43. package/bin/lib/remote/missionQuestion.mjs +63 -0
  44. package/bin/lib/remote/multiUser.mjs +344 -0
  45. package/bin/lib/remote/netProxy.mjs +145 -0
  46. package/bin/lib/remote/notify.mjs +58 -0
  47. package/bin/lib/remote/office/index.mjs +90 -0
  48. package/bin/lib/remote/policyCommand.mjs +93 -0
  49. package/bin/lib/remote/processes.mjs +217 -0
  50. package/bin/lib/remote/sandbox.mjs +221 -0
  51. package/bin/lib/remote/schedule.mjs +213 -0
  52. package/bin/lib/remote/scheduler.mjs +124 -0
  53. package/bin/lib/remote/textIndex.mjs +131 -0
  54. package/bin/lib/remote/tokenStore.mjs +77 -0
  55. package/bin/lib/remote/toolHandlers.mjs +726 -0
  56. package/bin/lib/remote/undoStore.mjs +242 -0
  57. package/bin/lib/remoteControl.mjs +26 -0
  58. package/bin/lib/scaffold.mjs +654 -653
  59. package/bin/lib/selfUpdate.mjs +71 -0
  60. package/bin/lib/update/binarySwap.mjs +63 -0
  61. package/bin/lib/update/constants.mjs +56 -0
  62. package/bin/lib/update/download.mjs +145 -0
  63. package/bin/lib/update/signature.mjs +42 -0
  64. package/bin/lib/update/state.mjs +205 -0
  65. package/bin/lib/update/versions.mjs +60 -0
  66. package/docs/CLI.md +1353 -1299
  67. package/package.json +71 -62
@@ -0,0 +1,904 @@
1
+ /**
2
+ * Mã C# của tiến trình điều khiển giao diện trên Windows (UI Automation + SendInput + chụp cửa sổ). Nhúng thành chuỗi vì CLI đóng gói
3
+ * thành một tệp nhị phân (bun) — lúc chạy ghi ra thư mục cấu hình rồi PowerShell 5.1 biên dịch (`Add-Type`, CodeDom → chỉ cú pháp C# 5:
4
+ * không `$"..."`, không `?.`, không thân hàm `=>`). Bản dịch được lưu thành DLL theo dấu vân tay mã, lần sau nạp thẳng.
5
+ *
6
+ * Giao thức: mỗi dòng stdin một JSON `{ id, op, args }`, mỗi dòng stdout một JSON `{ id, ok, result | error, code }`. Chạy trên luồng MTA
7
+ * riêng (UI Automation phía client nên ở MTA). Toạ độ là pixel vật lý (tiến trình bật DPI-aware theo từng màn hình).
8
+ *
9
+ * Cùng tiến trình có đầu nối Office qua COM (officeHostSource.mjs, op `office`) — ghép sau phần chính.
10
+ */
11
+ import { OFFICE_CSHARP } from './officeHostSource.mjs';
12
+
13
+ const MAIN_CSHARP = String.raw`
14
+ using System;
15
+ using System.Collections.Generic;
16
+ using System.Diagnostics;
17
+ using System.Drawing;
18
+ using System.Drawing.Drawing2D;
19
+ using System.Drawing.Imaging;
20
+ using System.IO;
21
+ using System.Reflection;
22
+ using System.Runtime.InteropServices;
23
+ using System.Text;
24
+ using System.Threading;
25
+ using System.Web.Script.Serialization;
26
+ using System.Windows.Automation;
27
+
28
+ namespace AivinGui {
29
+ public class GuiError : Exception {
30
+ public string Code;
31
+ public GuiError(string code, string message) : base(message) { Code = code; }
32
+ }
33
+
34
+ public static class Native {
35
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
36
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
37
+ [StructLayout(LayoutKind.Sequential)] public struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
38
+ [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
39
+ [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
40
+ [StructLayout(LayoutKind.Explicit)] public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
41
+ [StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public INPUTUNION u; }
42
+ public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
43
+
44
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam);
45
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
46
+ [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
47
+ [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hWnd);
48
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder sb, int max);
49
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr hWnd, StringBuilder sb, int max);
50
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
51
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT r);
52
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
53
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
54
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int cmd);
55
+ [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);
56
+ [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hWnd, uint cmd);
57
+ [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hWnd, int index);
58
+ [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdc, uint flags);
59
+ [DllImport("user32.dll")] public static extern uint SendInput(uint n, INPUT[] inputs, int size);
60
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
61
+ [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
62
+ [DllImport("user32.dll")] public static extern bool GetLastInputInfo(ref LASTINPUTINFO info);
63
+ [DllImport("user32.dll")] public static extern short VkKeyScan(char ch);
64
+ [DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
65
+ [DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
66
+ [DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr hWnd);
67
+ [DllImport("user32.dll")] public static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access);
68
+ [DllImport("user32.dll")] public static extern bool CloseDesktop(IntPtr desk);
69
+ [DllImport("kernel32.dll")] public static extern uint GetTickCount();
70
+ [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
71
+ [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int cx, int cy, uint flags);
72
+ [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
73
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, IntPtr wParam, string lParam, uint flags, uint timeout, out IntPtr result);
74
+ [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool attach);
75
+ [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hWnd, int attr, out int value, int size);
76
+ }
77
+
78
+ public class Host {
79
+ const int GWL_EXSTYLE = -20;
80
+ const int WS_EX_TOOLWINDOW = 0x80;
81
+ const uint INPUT_MOUSE = 0, INPUT_KEYBOARD = 1;
82
+ const uint MOUSEEVENTF_MOVE = 0x1, MOUSEEVENTF_LEFTDOWN = 0x2, MOUSEEVENTF_LEFTUP = 0x4, MOUSEEVENTF_RIGHTDOWN = 0x8, MOUSEEVENTF_RIGHTUP = 0x10;
83
+ const uint MOUSEEVENTF_WHEEL = 0x800, MOUSEEVENTF_ABSOLUTE = 0x8000, MOUSEEVENTF_VIRTUALDESK = 0x4000;
84
+ const uint KEYEVENTF_EXTENDEDKEY = 0x1, KEYEVENTF_KEYUP = 0x2, KEYEVENTF_UNICODE = 0x4;
85
+
86
+ static readonly JavaScriptSerializer Json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue, RecursionLimit = 200 };
87
+ /** Ảnh chụp của lần observe: node_id = "<snap>.<idx>" → phần tử. Giữ vài lần gần nhất, cũ hơn → GUI_STALE_NODE. */
88
+ static readonly Dictionary<int, Dictionary<int, AutomationElement>> Snapshots = new Dictionary<int, Dictionary<int, AutomationElement>>();
89
+ static readonly Dictionary<int, IntPtr> SnapshotWindow = new Dictionary<int, IntPtr>();
90
+ static int snapSeq = 0;
91
+ const int KEEP_SNAPSHOTS = 6;
92
+ /** Mốc lần cuối chính tiến trình này phát input (chuột / phím) — để phân biệt với input của người dùng. */
93
+ static uint lastInjectedTick = 0;
94
+ /**
95
+ * Kiểm "người dùng đang dùng chuột / phím" CHỈ khi thao tác sắp phát input thật (chuột, phím, đổi cửa sổ trên cùng). Thao tác theo
96
+ * pattern (SetValue / Invoke / Toggle / Select) không chiếm chuột, không giật focus → chạy song song với người dùng được (chạy thật
97
+ * 28/10/2026: người dùng đang gõ ở cửa sổ khác, mọi set_value bị dừng oan 12 lượt).
98
+ */
99
+ static bool pendingInputCheck = false;
100
+ static long inputGraceMs = 1500;
101
+
102
+ static void GuardInput() {
103
+ if (!pendingInputCheck) return;
104
+ pendingInputCheck = false;
105
+ long idle = UserIdleMs();
106
+ if (idle < inputGraceMs) throw new GuiError("GUI_USER_ACTIVE", "The user is using the mouse/keyboard right now (" + idle + " ms ago) — this action needs the real mouse/keyboard");
107
+ }
108
+
109
+ static void MoveCursor(int x, int y) { GuardInput(); Native.SetCursorPos(x, y); }
110
+
111
+ public static void Run() {
112
+ try { Native.SetProcessDpiAwarenessContext(new IntPtr(-4)); } catch { }
113
+ var t = new Thread(Loop);
114
+ t.SetApartmentState(ApartmentState.MTA);
115
+ t.Start();
116
+ t.Join();
117
+ }
118
+
119
+ static void Loop() {
120
+ var input = new StreamReader(Console.OpenStandardInput(), new UTF8Encoding(false));
121
+ var output = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false));
122
+ output.AutoFlush = true;
123
+ output.WriteLine(Json.Serialize(new Dictionary<string, object> { { "ready", true } }));
124
+ string line;
125
+ while ((line = input.ReadLine()) != null) {
126
+ if (line.Trim().Length == 0) continue;
127
+ object id = null;
128
+ var res = new Dictionary<string, object>();
129
+ try {
130
+ var req = (Dictionary<string, object>)Json.DeserializeObject(line);
131
+ id = Get(req, "id");
132
+ var args = Get(req, "args") as Dictionary<string, object>;
133
+ if (args == null) args = new Dictionary<string, object>();
134
+ res["result"] = Dispatch(Str(req, "op"), args);
135
+ res["ok"] = true;
136
+ } catch (GuiError e) {
137
+ res["ok"] = false; res["code"] = e.Code; res["error"] = e.Message;
138
+ } catch (ElementNotAvailableException e) {
139
+ res["ok"] = false; res["code"] = "GUI_STALE_NODE"; res["error"] = "Element is gone: " + e.Message;
140
+ } catch (Exception e) {
141
+ res["ok"] = false; res["code"] = "EXECUTION_FAILED"; res["error"] = e.GetType().Name + ": " + e.Message;
142
+ }
143
+ res["id"] = id;
144
+ output.WriteLine(Json.Serialize(res));
145
+ }
146
+ }
147
+
148
+ static object Dispatch(string op, Dictionary<string, object> a) {
149
+ switch (op) {
150
+ case "ping": return new Dictionary<string, object> { { "pong", true }, { "screens", Screens() }, { "interactive", InteractiveDesktop() } };
151
+ case "windows": return ListWindows(Bool(a, "all", false));
152
+ case "observe": return Observe(a);
153
+ case "window_info": { IntPtr h = ResolveWindow(a); if (h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused"); return WindowInfo(h, Native.GetForegroundWindow()); }
154
+ case "focus": return FocusWindowOp(a);
155
+ case "to_back": {
156
+ IntPtr h = ResolveWindow(a);
157
+ IntPtr prev = ParseWindow(Str(a, "restore_to"));
158
+ bool restored = prev != IntPtr.Zero && RestoreForeground(prev, h);
159
+ SendToBack(h);
160
+ return new Dictionary<string, object> { { "sent_to_back", true }, { "focus_returned_to_user", restored } };
161
+ }
162
+ case "act": return Act(a);
163
+ case "office": return Office.Run(a);
164
+ case "idle": return new Dictionary<string, object> { { "idle_ms", IdleMs() }, { "user_idle_ms", UserIdleMs() } };
165
+ default: throw new GuiError("INVALID_ARGS", "Unknown op: " + op);
166
+ }
167
+ }
168
+
169
+ // ── tiện ích đọc tham số ────────────────────────────────────────────────────────────────────
170
+
171
+ static object Get(Dictionary<string, object> d, string k) { object v; return d != null && d.TryGetValue(k, out v) ? v : null; }
172
+ static string Str(Dictionary<string, object> d, string k) { var v = Get(d, k); return v == null ? null : Convert.ToString(v); }
173
+ static int Int(Dictionary<string, object> d, string k, int def) { var v = Get(d, k); try { return v == null ? def : Convert.ToInt32(v); } catch { return def; } }
174
+ static double Dbl(Dictionary<string, object> d, string k, double def) { var v = Get(d, k); try { return v == null ? def : Convert.ToDouble(v); } catch { return def; } }
175
+ static bool Bool(Dictionary<string, object> d, string k, bool def) { var v = Get(d, k); try { return v == null ? def : Convert.ToBoolean(v); } catch { return def; } }
176
+
177
+ static List<object> Screens() {
178
+ var list = new List<object>();
179
+ foreach (var s in System.Windows.Forms.Screen.AllScreens) {
180
+ list.Add(new Dictionary<string, object> { { "x", s.Bounds.X }, { "y", s.Bounds.Y }, { "w", s.Bounds.Width }, { "h", s.Bounds.Height }, { "primary", s.Primary } });
181
+ }
182
+ return list;
183
+ }
184
+
185
+ /** Màn hình đang khoá / chuyển sang desktop bảo mật (UAC) → không mở được desktop nhận input. */
186
+ static bool InteractiveDesktop() {
187
+ IntPtr d = Native.OpenInputDesktop(0, false, 0x0100);
188
+ if (d == IntPtr.Zero) return false;
189
+ Native.CloseDesktop(d);
190
+ return true;
191
+ }
192
+
193
+ static uint IdleMs() {
194
+ var info = new Native.LASTINPUTINFO(); info.cbSize = (uint)Marshal.SizeOf(info);
195
+ if (!Native.GetLastInputInfo(ref info)) return 0;
196
+ return Native.GetTickCount() - info.dwTime;
197
+ }
198
+
199
+ /** Thời gian từ lần input gần nhất KHÔNG phải của AI (gần đúng: input mới hơn lần AI phát cuối + 150 ms là của người). */
200
+ static long UserIdleMs() {
201
+ var info = new Native.LASTINPUTINFO(); info.cbSize = (uint)Marshal.SizeOf(info);
202
+ if (!Native.GetLastInputInfo(ref info)) return long.MaxValue;
203
+ uint now = Native.GetTickCount();
204
+ if (lastInjectedTick != 0 && info.dwTime - lastInjectedTick < 150) return long.MaxValue;
205
+ return now - info.dwTime;
206
+ }
207
+
208
+ // ── cửa sổ ──────────────────────────────────────────────────────────────────────────────────
209
+
210
+ static string WindowText(IntPtr h) { var sb = new StringBuilder(512); Native.GetWindowText(h, sb, sb.Capacity); return sb.ToString(); }
211
+ static string ClassOf(IntPtr h) { var sb = new StringBuilder(256); Native.GetClassName(h, sb, sb.Capacity); return sb.ToString(); }
212
+
213
+ static string ProcessName(uint pid) {
214
+ try { return Process.GetProcessById((int)pid).ProcessName; } catch { return ""; }
215
+ }
216
+
217
+ static bool IsCloaked(IntPtr h) {
218
+ int cloaked = 0;
219
+ try { Native.DwmGetWindowAttribute(h, 14, out cloaked, 4); } catch { }
220
+ return cloaked != 0;
221
+ }
222
+
223
+ static Dictionary<string, object> RectDict(Native.RECT r) {
224
+ return new Dictionary<string, object> { { "x", r.Left }, { "y", r.Top }, { "w", r.Right - r.Left }, { "h", r.Bottom - r.Top } };
225
+ }
226
+
227
+ static Dictionary<string, object> WindowInfo(IntPtr h, IntPtr fg) {
228
+ uint pid; Native.GetWindowThreadProcessId(h, out pid);
229
+ Native.RECT r; Native.GetWindowRect(h, out r);
230
+ return new Dictionary<string, object> {
231
+ { "window", "0x" + h.ToInt64().ToString("x") }, { "title", WindowText(h) }, { "process", ProcessName(pid) }, { "pid", (long)pid },
232
+ { "class", ClassOf(h) }, { "rect", RectDict(r) }, { "focused", h == fg }, { "minimized", Native.IsIconic(h) },
233
+ };
234
+ }
235
+
236
+ static List<object> ListWindows(bool all) {
237
+ var list = new List<object>();
238
+ IntPtr fg = Native.GetForegroundWindow();
239
+ uint selfPid = (uint)Process.GetCurrentProcess().Id;
240
+ Native.EnumWindows(delegate (IntPtr h, IntPtr l) {
241
+ if (!Native.IsWindowVisible(h) || IsCloaked(h)) return true;
242
+ if (Native.GetWindow(h, 4) != IntPtr.Zero && !all) return true; // có cửa sổ chủ → hộp thoại con, lấy qua cửa sổ chủ
243
+ if ((Native.GetWindowLong(h, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) != 0) return true;
244
+ string title = WindowText(h);
245
+ if (title.Length == 0) return true;
246
+ uint pid; Native.GetWindowThreadProcessId(h, out pid);
247
+ if (pid == selfPid) return true;
248
+ list.Add(WindowInfo(h, fg));
249
+ return true;
250
+ }, IntPtr.Zero);
251
+ return list;
252
+ }
253
+
254
+ static IntPtr ParseWindow(string s) {
255
+ if (string.IsNullOrEmpty(s)) return IntPtr.Zero;
256
+ try {
257
+ long v = s.StartsWith("0x") ? Convert.ToInt64(s.Substring(2), 16) : Convert.ToInt64(s);
258
+ return new IntPtr(v);
259
+ } catch { return IntPtr.Zero; }
260
+ }
261
+
262
+ /** Cửa sổ theo handle, hoặc tìm theo tiêu đề / tên tiến trình (chứa, không phân biệt hoa thường); không có → cửa sổ đang focus. */
263
+ static IntPtr ResolveWindow(Dictionary<string, object> a) {
264
+ string w = Str(a, "window");
265
+ IntPtr h = ParseWindow(w);
266
+ if (h != IntPtr.Zero) {
267
+ if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "Window no longer exists: " + w);
268
+ return h;
269
+ }
270
+ if (!string.IsNullOrEmpty(w)) {
271
+ string q = w.ToLowerInvariant();
272
+ foreach (Dictionary<string, object> info in ListWindows(false)) {
273
+ if (Convert.ToString(info["title"]).ToLowerInvariant().Contains(q) || Convert.ToString(info["process"]).ToLowerInvariant() == q) {
274
+ return ParseWindow(Convert.ToString(info["window"]));
275
+ }
276
+ }
277
+ throw new GuiError("NOT_FOUND", "No window matches: " + w);
278
+ }
279
+ return Native.GetForegroundWindow();
280
+ }
281
+
282
+ /** Đẩy cửa sổ xuống đáy chồng cửa sổ, không kích hoạt — nằm dưới cửa sổ người dùng, thao tác theo pattern vẫn chạy được. */
283
+ static void SendToBack(IntPtr h) {
284
+ if (h == IntPtr.Zero || !Native.IsWindow(h)) return;
285
+ Native.SetWindowPos(h, new IntPtr(1), 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0010);
286
+ }
287
+
288
+ /** Cửa sổ trên cùng bị thao tác vừa rồi đổi đi → đưa cửa sổ cũ lên lại (gắn luồng input tạm, không phát phím giả). */
289
+ static bool RestoreForeground(IntPtr prev, IntPtr target) {
290
+ IntPtr cur = Native.GetForegroundWindow();
291
+ if (prev == IntPtr.Zero || cur == prev || prev == target || !Native.IsWindow(prev)) return false;
292
+ uint pid;
293
+ uint curThread = Native.GetWindowThreadProcessId(cur, out pid);
294
+ uint me = Native.GetCurrentThreadId();
295
+ bool attached = curThread != 0 && curThread != me && Native.AttachThreadInput(me, curThread, true);
296
+ try { Native.SetForegroundWindow(prev); } finally { if (attached) Native.AttachThreadInput(me, curThread, false); }
297
+ return Native.GetForegroundWindow() == prev;
298
+ }
299
+
300
+ static void ForceForeground(IntPtr h) {
301
+ if (Native.IsIconic(h)) Native.ShowWindow(h, 9);
302
+ if (Native.GetForegroundWindow() == h) return;
303
+ GuardInput();
304
+ // Windows chỉ cho đổi cửa sổ trước khi tiến trình vừa có input → nhấn nhả Alt (không tạo ký tự) rồi đặt.
305
+ KeyTap(0x12);
306
+ Native.SetForegroundWindow(h);
307
+ Native.BringWindowToTop(h);
308
+ Thread.Sleep(80);
309
+ }
310
+
311
+ static object FocusWindowOp(Dictionary<string, object> a) {
312
+ IntPtr h = ResolveWindow(a);
313
+ ForceForeground(h);
314
+ return new Dictionary<string, object> { { "focused", Native.GetForegroundWindow() == h }, { "window", WindowInfo(h, Native.GetForegroundWindow()) } };
315
+ }
316
+
317
+ // ── observe: cây trợ năng rút gọn + ảnh ─────────────────────────────────────────────────────
318
+
319
+ static CacheRequest BuildCache() {
320
+ var c = new CacheRequest();
321
+ c.TreeScope = TreeScope.Element | TreeScope.Children;
322
+ c.TreeFilter = Automation.ControlViewCondition;
323
+ c.AutomationElementMode = AutomationElementMode.Full;
324
+ c.Add(AutomationElement.NameProperty); c.Add(AutomationElement.ControlTypeProperty); c.Add(AutomationElement.AutomationIdProperty);
325
+ c.Add(AutomationElement.ClassNameProperty); c.Add(AutomationElement.BoundingRectangleProperty); c.Add(AutomationElement.IsEnabledProperty);
326
+ c.Add(AutomationElement.IsOffscreenProperty); c.Add(AutomationElement.IsPasswordProperty); c.Add(AutomationElement.HasKeyboardFocusProperty);
327
+ c.Add(AutomationElement.AcceleratorKeyProperty); c.Add(AutomationElement.AccessKeyProperty); c.Add(AutomationElement.HelpTextProperty);
328
+ c.Add(AutomationElement.IsInvokePatternAvailableProperty); c.Add(AutomationElement.IsValuePatternAvailableProperty);
329
+ c.Add(AutomationElement.IsTogglePatternAvailableProperty); c.Add(AutomationElement.IsSelectionItemPatternAvailableProperty);
330
+ c.Add(AutomationElement.IsExpandCollapsePatternAvailableProperty); c.Add(AutomationElement.IsScrollPatternAvailableProperty);
331
+ c.Add(AutomationElement.IsTextPatternAvailableProperty);
332
+ c.Add(ValuePattern.ValueProperty); c.Add(ValuePattern.IsReadOnlyProperty); c.Add(TogglePattern.ToggleStateProperty);
333
+ c.Add(SelectionItemPattern.IsSelectedProperty); c.Add(ExpandCollapsePattern.ExpandCollapseStateProperty);
334
+ return c;
335
+ }
336
+
337
+ static object Cached(AutomationElement e, AutomationProperty p) {
338
+ try { var v = e.GetCachedPropertyValue(p, true); return v == AutomationElement.NotSupported ? null : v; } catch { return null; }
339
+ }
340
+
341
+ static string Clip(string s, int max) { if (s == null) return null; s = s.Replace("\r", " ").Replace("\n", " ").Trim(); return s.Length > max ? s.Substring(0, max) + "…" : s; }
342
+
343
+ static Dictionary<string, object> Describe(AutomationElement e, string nodeId, int depth, System.Windows.Rect win) {
344
+ var n = new Dictionary<string, object>();
345
+ n["id"] = nodeId;
346
+ var ct = Cached(e, AutomationElement.ControlTypeProperty) as ControlType;
347
+ n["role"] = ct == null ? "unknown" : ct.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant();
348
+ string name = Clip(Cached(e, AutomationElement.NameProperty) as string, 160);
349
+ if (!string.IsNullOrEmpty(name)) n["name"] = name;
350
+ string aid = Cached(e, AutomationElement.AutomationIdProperty) as string;
351
+ if (!string.IsNullOrEmpty(aid) && aid.Length <= 80) n["automation_id"] = aid;
352
+ string cls = Cached(e, AutomationElement.ClassNameProperty) as string;
353
+ if (!string.IsNullOrEmpty(cls) && cls.Length <= 60) n["class"] = cls;
354
+ n["depth"] = depth;
355
+ var patterns = new List<string>();
356
+ if (true.Equals(Cached(e, AutomationElement.IsInvokePatternAvailableProperty))) patterns.Add("invoke");
357
+ if (true.Equals(Cached(e, AutomationElement.IsValuePatternAvailableProperty))) {
358
+ patterns.Add("value");
359
+ if (!true.Equals(Cached(e, AutomationElement.IsPasswordProperty))) {
360
+ string v = Clip(Cached(e, ValuePattern.ValueProperty) as string, 300);
361
+ if (!string.IsNullOrEmpty(v)) n["value"] = v;
362
+ }
363
+ if (true.Equals(Cached(e, ValuePattern.IsReadOnlyProperty))) n["readonly"] = true;
364
+ }
365
+ if (true.Equals(Cached(e, AutomationElement.IsTogglePatternAvailableProperty))) {
366
+ patterns.Add("toggle");
367
+ var ts = Cached(e, TogglePattern.ToggleStateProperty);
368
+ if (ts != null) n["checked"] = ts.ToString().ToLowerInvariant();
369
+ }
370
+ if (true.Equals(Cached(e, AutomationElement.IsSelectionItemPatternAvailableProperty))) {
371
+ patterns.Add("select");
372
+ if (true.Equals(Cached(e, SelectionItemPattern.IsSelectedProperty))) n["selected"] = true;
373
+ }
374
+ if (true.Equals(Cached(e, AutomationElement.IsExpandCollapsePatternAvailableProperty))) {
375
+ patterns.Add("expand");
376
+ var es = Cached(e, ExpandCollapsePattern.ExpandCollapseStateProperty);
377
+ if (es != null) n["expanded"] = es.ToString().ToLowerInvariant();
378
+ }
379
+ if (true.Equals(Cached(e, AutomationElement.IsScrollPatternAvailableProperty))) patterns.Add("scroll");
380
+ if (true.Equals(Cached(e, AutomationElement.IsTextPatternAvailableProperty))) patterns.Add("text");
381
+ if (patterns.Count > 0) n["patterns"] = patterns;
382
+ if (true.Equals(Cached(e, AutomationElement.IsPasswordProperty))) n["password"] = true;
383
+ if (false.Equals(Cached(e, AutomationElement.IsEnabledProperty))) n["disabled"] = true;
384
+ if (true.Equals(Cached(e, AutomationElement.HasKeyboardFocusProperty))) n["focused"] = true;
385
+ string acc = Cached(e, AutomationElement.AcceleratorKeyProperty) as string;
386
+ if (!string.IsNullOrEmpty(acc)) n["shortcut"] = acc;
387
+ string help = Clip(Cached(e, AutomationElement.HelpTextProperty) as string, 120);
388
+ if (!string.IsNullOrEmpty(help) && help != name) n["help"] = help;
389
+ object rectObj = Cached(e, AutomationElement.BoundingRectangleProperty);
390
+ if (rectObj is System.Windows.Rect) {
391
+ var r = (System.Windows.Rect)rectObj;
392
+ if (!r.IsEmpty && r.Width > 0 && r.Height > 0) {
393
+ n["rect"] = new Dictionary<string, object> { { "x", (int)(r.X - win.X) }, { "y", (int)(r.Y - win.Y) }, { "w", (int)r.Width }, { "h", (int)r.Height } };
394
+ }
395
+ }
396
+ if (true.Equals(Cached(e, AutomationElement.IsOffscreenProperty))) n["offscreen"] = true;
397
+ return n;
398
+ }
399
+
400
+ static bool IsInteractive(Dictionary<string, object> n) {
401
+ if (n.ContainsKey("patterns")) return true;
402
+ string role = Convert.ToString(n["role"]);
403
+ return role == "button" || role == "edit" || role == "menuitem" || role == "hyperlink" || role == "listitem" || role == "tabitem" || role == "treeitem" || role == "checkbox" || role == "radiobutton" || role == "combobox";
404
+ }
405
+
406
+ static object Observe(Dictionary<string, object> a) {
407
+ IntPtr h = ResolveWindow(a);
408
+ if (h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused");
409
+ int maxNodes = Math.Max(20, Math.Min(Int(a, "max_nodes", 300), 1500));
410
+ int maxDepth = Math.Max(2, Math.Min(Int(a, "max_depth", 25), 60));
411
+ var sw = Stopwatch.StartNew();
412
+ AutomationElement root = AutomationElement.FromHandle(h);
413
+ var cache = BuildCache();
414
+ var nodes = new List<object>();
415
+ var map = new Dictionary<int, AutomationElement>();
416
+ int snap = ++snapSeq;
417
+ Native.RECT wr; Native.GetWindowRect(h, out wr);
418
+ var winRect = new System.Windows.Rect(wr.Left, wr.Top, Math.Max(1, wr.Right - wr.Left), Math.Max(1, wr.Bottom - wr.Top));
419
+ int named = 0, interactive = 0;
420
+ bool truncated = false;
421
+ var queue = new Queue<KeyValuePair<AutomationElement, int>>();
422
+ using (cache.Activate()) {
423
+ root = root.GetUpdatedCache(cache);
424
+ }
425
+ queue.Enqueue(new KeyValuePair<AutomationElement, int>(root, 0));
426
+ while (queue.Count > 0) {
427
+ if (nodes.Count >= maxNodes) { truncated = true; break; }
428
+ var item = queue.Dequeue();
429
+ AutomationElement e = item.Key;
430
+ int idx = nodes.Count;
431
+ var n = Describe(e, snap + "." + idx, item.Value, winRect);
432
+ // Ngoài màn hình và không có chữ → bỏ (danh sách dài cuộn ẩn), vẫn đi vào con nếu là khung chứa.
433
+ bool skip = n.ContainsKey("offscreen") && !n.ContainsKey("name") && item.Value > 0;
434
+ if (!skip) {
435
+ map[idx] = e;
436
+ nodes.Add(n);
437
+ if (n.ContainsKey("name")) named++;
438
+ if (IsInteractive(n)) interactive++;
439
+ }
440
+ if (item.Value >= maxDepth) continue;
441
+ AutomationElementCollection kids;
442
+ try {
443
+ using (cache.Activate()) { kids = e.FindAll(TreeScope.Children, Condition.TrueCondition); }
444
+ } catch { continue; }
445
+ foreach (AutomationElement k in kids) queue.Enqueue(new KeyValuePair<AutomationElement, int>(k, item.Value + 1));
446
+ }
447
+ Snapshots[snap] = map;
448
+ SnapshotWindow[snap] = h;
449
+ while (Snapshots.Count > KEEP_SNAPSHOTS) {
450
+ int oldest = int.MaxValue;
451
+ foreach (var k in Snapshots.Keys) if (k < oldest) oldest = k;
452
+ Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest);
453
+ }
454
+ // Cây nghèo: ít phần tử có tên / thao tác được (ứng dụng vẽ tay, canvas, Electron tắt trợ năng) → cần ảnh để định vị.
455
+ string quality = (interactive >= 3 && named >= 5) ? "good" : "poor";
456
+ var res = new Dictionary<string, object> {
457
+ { "snapshot", snap }, { "window", WindowInfo(h, Native.GetForegroundWindow()) }, { "nodes", nodes }, { "node_count", nodes.Count },
458
+ { "interactive_count", interactive }, { "tree_quality", quality }, { "truncated", truncated }, { "tree_ms", sw.ElapsedMilliseconds },
459
+ { "dpi", (long)SafeDpi(h) },
460
+ };
461
+ bool wantImage = Bool(a, "include_image", false) || (quality == "poor" && Bool(a, "image_when_poor", true));
462
+ if (wantImage) {
463
+ var sw2 = Stopwatch.StartNew();
464
+ res["image"] = CaptureWindow(h, Int(a, "image_max_width", 1366), Int(a, "image_quality", 70));
465
+ res["image_ms"] = sw2.ElapsedMilliseconds;
466
+ }
467
+ return res;
468
+ }
469
+
470
+ static uint SafeDpi(IntPtr h) { try { return Native.GetDpiForWindow(h); } catch { return 96; } }
471
+
472
+ static Dictionary<string, object> CaptureWindow(IntPtr h, int maxWidth, int quality) {
473
+ Native.RECT r; Native.GetWindowRect(h, out r);
474
+ int w = Math.Max(1, r.Right - r.Left), ht = Math.Max(1, r.Bottom - r.Top);
475
+ using (var bmp = new Bitmap(w, ht, PixelFormat.Format32bppArgb)) {
476
+ bool ok = false;
477
+ using (var g = Graphics.FromImage(bmp)) {
478
+ IntPtr hdc = g.GetHdc();
479
+ try { ok = Native.PrintWindow(h, hdc, 2); } finally { g.ReleaseHdc(hdc); }
480
+ // PrintWindow trả ảnh đen với vài ứng dụng GPU → chụp vùng màn hình (cửa sổ phải đang hiện trên cùng).
481
+ if (!ok || IsMostlyBlack(bmp)) g.CopyFromScreen(r.Left, r.Top, 0, 0, new Size(w, ht));
482
+ }
483
+ double scale = w > maxWidth ? (double)maxWidth / w : 1.0;
484
+ int ow = Math.Max(1, (int)(w * scale)), oh = Math.Max(1, (int)(ht * scale));
485
+ using (var outBmp = new Bitmap(ow, oh, PixelFormat.Format24bppRgb)) {
486
+ using (var g2 = Graphics.FromImage(outBmp)) {
487
+ g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
488
+ g2.DrawImage(bmp, 0, 0, ow, oh);
489
+ }
490
+ var codec = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.MimeType == "image/jpeg");
491
+ var ep = new EncoderParameters(1);
492
+ ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Max(30, Math.Min(quality, 95)));
493
+ using (var ms = new MemoryStream()) {
494
+ outBmp.Save(ms, codec, ep);
495
+ return new Dictionary<string, object> { { "mime", "image/jpeg" }, { "base64", Convert.ToBase64String(ms.ToArray()) }, { "width", ow }, { "height", oh }, { "scale", scale } };
496
+ }
497
+ }
498
+ }
499
+ }
500
+
501
+ static bool IsMostlyBlack(Bitmap b) {
502
+ int dark = 0, total = 0;
503
+ for (int x = 0; x < b.Width; x += Math.Max(1, b.Width / 16)) {
504
+ for (int y = 0; y < b.Height; y += Math.Max(1, b.Height / 16)) {
505
+ var c = b.GetPixel(x, y); total++;
506
+ if (c.R < 8 && c.G < 8 && c.B < 8) dark++;
507
+ }
508
+ }
509
+ return total > 0 && dark * 10 >= total * 9;
510
+ }
511
+
512
+ // ── act ─────────────────────────────────────────────────────────────────────────────────────
513
+
514
+ static AutomationElement NodeOf(string nodeId, out IntPtr window) {
515
+ window = IntPtr.Zero;
516
+ int dot = nodeId == null ? -1 : nodeId.IndexOf('.');
517
+ if (dot <= 0) throw new GuiError("INVALID_ARGS", "Bad node id: " + nodeId);
518
+ int snap, idx;
519
+ if (!int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 1), out idx)) throw new GuiError("INVALID_ARGS", "Bad node id: " + nodeId);
520
+ Dictionary<int, AutomationElement> map;
521
+ if (!Snapshots.TryGetValue(snap, out map)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
522
+ AutomationElement e;
523
+ if (!map.TryGetValue(idx, out e)) throw new GuiError("NOT_FOUND", "No node " + nodeId);
524
+ window = SnapshotWindow[snap];
525
+ return e;
526
+ }
527
+
528
+ static object Pattern(AutomationElement e, AutomationPattern p) {
529
+ object o; return e.TryGetCurrentPattern(p, out o) ? o : null;
530
+ }
531
+
532
+ static Dictionary<string, object> Live(AutomationElement e) {
533
+ var d = new Dictionary<string, object>();
534
+ try {
535
+ d["exists"] = true;
536
+ d["name"] = Clip(e.Current.Name, 160);
537
+ d["enabled"] = e.Current.IsEnabled;
538
+ d["focused"] = e.Current.HasKeyboardFocus;
539
+ var vp = Pattern(e, ValuePattern.Pattern) as ValuePattern;
540
+ if (vp != null && !e.Current.IsPassword) d["value"] = Clip(vp.Current.Value, 300);
541
+ var tp = Pattern(e, TogglePattern.Pattern) as TogglePattern;
542
+ if (tp != null) d["checked"] = tp.Current.ToggleState.ToString().ToLowerInvariant();
543
+ var sp = Pattern(e, SelectionItemPattern.Pattern) as SelectionItemPattern;
544
+ if (sp != null) d["selected"] = sp.Current.IsSelected;
545
+ var ep = Pattern(e, ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
546
+ if (ep != null) d["expanded"] = ep.Current.ExpandCollapseState.ToString().ToLowerInvariant();
547
+ } catch (ElementNotAvailableException) {
548
+ d.Clear(); d["exists"] = false;
549
+ }
550
+ return d;
551
+ }
552
+
553
+ static System.Windows.Point CenterOf(AutomationElement e) {
554
+ System.Windows.Point p;
555
+ try { if (e.TryGetClickablePoint(out p)) return p; } catch { }
556
+ System.Windows.Rect r = e.Current.BoundingRectangle;
557
+ if (r.IsEmpty) throw new GuiError("GUI_NOT_CLICKABLE", "Element has no position on screen");
558
+ return new System.Windows.Point(r.X + r.Width / 2, r.Y + r.Height / 2);
559
+ }
560
+
561
+ static object Act(Dictionary<string, object> a) {
562
+ string action = Str(a, "action") ?? "click";
563
+ string nodeId = Str(a, "node_id");
564
+ string method = Str(a, "method") ?? "auto";
565
+ inputGraceMs = Int(a, "user_input_grace_ms", 1500);
566
+ pendingInputCheck = Bool(a, "check_user_input", true);
567
+ if (!InteractiveDesktop()) throw new GuiError("GUI_LOCKED", "The screen is locked or a secure prompt is showing");
568
+ AutomationElement el = null;
569
+ IntPtr window = IntPtr.Zero;
570
+ if (!string.IsNullOrEmpty(nodeId)) el = NodeOf(nodeId, out window);
571
+ else window = ResolveWindow(a);
572
+ string beforeTitle = window == IntPtr.Zero ? "" : WindowText(window);
573
+ if (el != null) {
574
+ bool isPassword = false;
575
+ try { isPassword = el.Current.IsPassword; } catch (ElementNotAvailableException) { throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is gone — observe again"); }
576
+ if (isPassword && (action == "type" || action == "set_value")) throw new GuiError("GUI_PASSWORD_FIELD", "Typing into a password field is not allowed — ask the user to type it");
577
+ }
578
+ IntPtr fgBefore = Native.GetForegroundWindow();
579
+ string used = DoAction(action, method, el, window, a);
580
+ // Thao tác theo pattern không cần cửa sổ đích ở trên cùng, nhưng nhiều ứng dụng (WinForms qua MSAA) tự lấy focus khi bị SetValue /
581
+ // Expand → phím người dùng đang gõ ở cửa sổ khác rơi vào ô của AI (chạy thật 28/10/2026: ô Họ tên bị chèn "ã", "x", "ch"). Trả focus
582
+ // về cửa sổ người dùng đang dùng ngay sau thao tác.
583
+ bool restored = used != "mouse" && used != "keyboard" && RestoreForeground(fgBefore, window);
584
+ // Chạy nền: người dùng đang ở cửa sổ khác → cửa sổ của AI về lại dưới đáy (không chồng lên việc của người dùng).
585
+ if (restored || (used != "mouse" && used != "keyboard" && fgBefore != window && window != IntPtr.Zero)) SendToBack(window);
586
+ Thread.Sleep(Math.Max(0, Math.Min(Int(a, "settle_ms", 250), 3000)));
587
+ var res = new Dictionary<string, object> { { "action", action }, { "method", used } };
588
+ if (restored) res["focus_returned_to_user"] = true;
589
+ if (el != null) res["target"] = Live(el);
590
+ IntPtr fg = Native.GetForegroundWindow();
591
+ res["foreground"] = WindowInfo(fg, fg);
592
+ if (window != IntPtr.Zero) {
593
+ bool alive = Native.IsWindow(window);
594
+ res["window_closed"] = !alive;
595
+ if (alive) {
596
+ string after = WindowText(window);
597
+ if (after != beforeTitle) res["window_title_changed"] = new Dictionary<string, object> { { "from", beforeTitle }, { "to", after } };
598
+ }
599
+ }
600
+ try {
601
+ var fe = AutomationElement.FocusedElement;
602
+ if (fe != null) res["focused_element"] = new Dictionary<string, object> { { "role", fe.Current.ControlType.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant() }, { "name", Clip(fe.Current.Name, 120) } };
603
+ } catch { }
604
+ return res;
605
+ }
606
+
607
+ static string DoAction(string action, string method, AutomationElement el, IntPtr window, Dictionary<string, object> a) {
608
+ bool allowPattern = method != "mouse";
609
+ switch (action) {
610
+ case "click": {
611
+ if (el != null && allowPattern) {
612
+ var ip = Pattern(el, InvokePattern.Pattern) as InvokePattern;
613
+ string role = el.Current.ControlType.ProgrammaticName;
614
+ bool invokeRole = role.EndsWith("Button") || role.EndsWith("MenuItem") || role.EndsWith("Hyperlink") || role.EndsWith("SplitButton");
615
+ if (ip != null && invokeRole) { ip.Invoke(); return "invoke"; }
616
+ if (role.EndsWith("ListItem") || role.EndsWith("TabItem") || role.EndsWith("TreeItem") || role.EndsWith("RadioButton")) {
617
+ var sp = Pattern(el, SelectionItemPattern.Pattern) as SelectionItemPattern;
618
+ if (sp != null) { sp.Select(); return "select"; }
619
+ }
620
+ if (role.EndsWith("CheckBox")) {
621
+ var tp = Pattern(el, TogglePattern.Pattern) as TogglePattern;
622
+ if (tp != null) { tp.Toggle(); return "toggle"; }
623
+ }
624
+ if (method == "pattern") {
625
+ if (ip != null) { ip.Invoke(); return "invoke"; }
626
+ throw new GuiError("GUI_NO_PATTERN", "Element has no click pattern — retry with method mouse");
627
+ }
628
+ }
629
+ MouseAt(el, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1);
630
+ return "mouse";
631
+ }
632
+ case "double_click": MouseAt(el, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 2); return "mouse";
633
+ case "right_click": MouseAt(el, window, a, MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, 1); return "mouse";
634
+ case "set_value": {
635
+ string text = Str(a, "text") ?? "";
636
+ if (el != null && allowPattern) {
637
+ var vp = Pattern(el, ValuePattern.Pattern) as ValuePattern;
638
+ if (vp != null && !vp.Current.IsReadOnly) { vp.SetValue(text); return "value"; }
639
+ if (TryBackgroundSetText(el, text)) return "background";
640
+ }
641
+ FocusTarget(el, window);
642
+ KeyCombo("ctrl+a");
643
+ TypeText(text);
644
+ return "keyboard";
645
+ }
646
+ case "type": {
647
+ string text = Str(a, "text") ?? "";
648
+ if (allowPattern && TryBackgroundType(el, text)) return "background";
649
+ FocusTarget(el, window); TypeText(text); return "keyboard";
650
+ }
651
+ case "key": FocusTarget(el, window); KeyCombo(Str(a, "keys") ?? ""); return "keyboard";
652
+ case "scroll": {
653
+ string dir = (Str(a, "direction") ?? "down").ToLowerInvariant();
654
+ int amount = Math.Max(1, Math.Min(Int(a, "amount", 3), 30));
655
+ if (el != null && allowPattern) {
656
+ var sp = Pattern(el, ScrollPattern.Pattern) as ScrollPattern;
657
+ if (sp != null) {
658
+ for (int i = 0; i < amount; i++) {
659
+ if (dir == "up") sp.ScrollVertical(ScrollAmount.SmallDecrement);
660
+ else if (dir == "left") sp.ScrollHorizontal(ScrollAmount.SmallDecrement);
661
+ else if (dir == "right") sp.ScrollHorizontal(ScrollAmount.SmallIncrement);
662
+ else sp.ScrollVertical(ScrollAmount.SmallIncrement);
663
+ }
664
+ return "scroll";
665
+ }
666
+ }
667
+ var p = PointFor(el, window, a);
668
+ ForceForeground(window);
669
+ MoveCursor((int)p.X, (int)p.Y);
670
+ int delta = (dir == "up" ? 120 : -120) * amount;
671
+ var inp = MouseInput(MOUSEEVENTF_WHEEL, 0, 0, delta);
672
+ Send(new[] { inp });
673
+ return "mouse";
674
+ }
675
+ case "select": {
676
+ if (el == null) throw new GuiError("INVALID_ARGS", "select needs node_id");
677
+ string option = Str(a, "option");
678
+ if (!string.IsNullOrEmpty(option)) {
679
+ // Mục của danh sách thường có sẵn trong cây khi đang đóng → chọn thẳng, không thả danh sách xuống (thả xuống kéo cửa sổ lên
680
+ // trên cùng, giật focus của người dùng). Chỉ mở khi mục chưa có trong cây.
681
+ var ep = Pattern(el, ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
682
+ var match = el.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, option, PropertyConditionFlags.IgnoreCase));
683
+ bool expanded = false;
684
+ if (match == null && ep != null) { try { ep.Expand(); expanded = true; Thread.Sleep(200); } catch { } }
685
+ if (match == null) match = FindByName(el, option);
686
+ if (match == null) throw new GuiError("NOT_FOUND", "No option named: " + option);
687
+ var sip = Pattern(match, SelectionItemPattern.Pattern) as SelectionItemPattern;
688
+ if (sip != null) sip.Select(); else { var ip = Pattern(match, InvokePattern.Pattern) as InvokePattern; if (ip != null) ip.Invoke(); else throw new GuiError("GUI_NO_PATTERN", "Option cannot be selected"); }
689
+ if (ep != null && expanded) { try { ep.Collapse(); } catch { } }
690
+ return "select";
691
+ }
692
+ var sp2 = Pattern(el, SelectionItemPattern.Pattern) as SelectionItemPattern;
693
+ if (sp2 == null) throw new GuiError("GUI_NO_PATTERN", "Element is not selectable");
694
+ sp2.Select();
695
+ return "select";
696
+ }
697
+ case "toggle": {
698
+ if (el == null) throw new GuiError("INVALID_ARGS", "toggle needs node_id");
699
+ var tp = Pattern(el, TogglePattern.Pattern) as TogglePattern;
700
+ if (tp == null) throw new GuiError("GUI_NO_PATTERN", "Element is not a toggle");
701
+ string want = Str(a, "state");
702
+ for (int i = 0; i < 3; i++) {
703
+ if (want != null && tp.Current.ToggleState.ToString().ToLowerInvariant() == want.ToLowerInvariant()) break;
704
+ tp.Toggle();
705
+ if (want == null) break;
706
+ }
707
+ return "toggle";
708
+ }
709
+ case "expand":
710
+ case "collapse": {
711
+ if (el == null) throw new GuiError("INVALID_ARGS", action + " needs node_id");
712
+ var ep = Pattern(el, ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
713
+ if (ep == null) throw new GuiError("GUI_NO_PATTERN", "Element cannot expand/collapse");
714
+ if (action == "expand") ep.Expand(); else ep.Collapse();
715
+ return "expand";
716
+ }
717
+ case "drag": {
718
+ var start = PointFor(el, window, a);
719
+ var toD = Get(a, "to") as Dictionary<string, object>;
720
+ if (toD == null) throw new GuiError("INVALID_ARGS", "drag needs to {x,y}");
721
+ var to = WindowPoint(window, a, toD);
722
+ ForceForeground(window);
723
+ MoveCursor((int)start.X, (int)start.Y);
724
+ Send(new[] { MouseInput(MOUSEEVENTF_LEFTDOWN, 0, 0, 0) });
725
+ for (int i = 1; i <= 10; i++) {
726
+ MoveCursor((int)(start.X + (to.X - start.X) * i / 10), (int)(start.Y + (to.Y - start.Y) * i / 10));
727
+ Thread.Sleep(15);
728
+ }
729
+ Send(new[] { MouseInput(MOUSEEVENTF_LEFTUP, 0, 0, 0) });
730
+ return "mouse";
731
+ }
732
+ default: throw new GuiError("INVALID_ARGS", "Unknown action: " + action);
733
+ }
734
+ }
735
+
736
+ static AutomationElement FindByName(AutomationElement root, string name) {
737
+ var cond = new PropertyCondition(AutomationElement.NameProperty, name, PropertyConditionFlags.IgnoreCase);
738
+ var hit = root.FindFirst(TreeScope.Descendants, cond);
739
+ if (hit != null) return hit;
740
+ // Danh sách thả xuống của ComboBox Win32 là cửa sổ riêng → tìm từ gốc màn hình trong các popup đang mở.
741
+ return AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new AndCondition(cond, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)));
742
+ }
743
+
744
+ const uint WM_SETTEXT = 0x000C, WM_CHAR = 0x0102, SMTO_ABORTIFHUNG = 0x0002;
745
+
746
+ /** Handle Win32 riêng của phần tử (ô nhập / nút Win32, WinForms có; WPF / UWP / Chromium thì không). */
747
+ static IntPtr OwnHandle(AutomationElement el) {
748
+ if (el == null) return IntPtr.Zero;
749
+ try { int h = el.Current.NativeWindowHandle; return h == 0 ? IntPtr.Zero : new IntPtr(h); } catch { return IntPtr.Zero; }
750
+ }
751
+
752
+ /**
753
+ * Chạy NỀN (28/10/2026, user: "chạy nền, không chiếm focus"): ô Win32 có handle riêng → đặt chữ bằng WM_SETTEXT / gửi ký tự bằng
754
+ * WM_CHAR thẳng vào handle — không đưa cửa sổ lên, không đụng bàn phím thật. Ô không có handle (WPF, UWP, trình duyệt) → false, nơi
755
+ * gọi mới dùng bàn phím thật.
756
+ */
757
+ static bool TryBackgroundSetText(AutomationElement el, string text) {
758
+ IntPtr h = OwnHandle(el);
759
+ if (h == IntPtr.Zero) return false;
760
+ IntPtr r;
761
+ return Native.SendMessageTimeout(h, WM_SETTEXT, IntPtr.Zero, text, SMTO_ABORTIFHUNG, 2000, out r) != IntPtr.Zero;
762
+ }
763
+
764
+ static bool TryBackgroundType(AutomationElement el, string text) {
765
+ IntPtr h = OwnHandle(el);
766
+ if (h == IntPtr.Zero) return false;
767
+ foreach (char ch in text) {
768
+ if (ch == '\r') continue;
769
+ Native.PostMessage(h, WM_CHAR, new IntPtr(ch == '\n' ? 13 : ch), IntPtr.Zero);
770
+ }
771
+ Thread.Sleep(30);
772
+ return true;
773
+ }
774
+
775
+ static void FocusTarget(AutomationElement el, IntPtr window) {
776
+ if (window != IntPtr.Zero) ForceForeground(window);
777
+ if (el != null) { try { el.SetFocus(); } catch { } Thread.Sleep(50); }
778
+ }
779
+
780
+ /** Toạ độ theo ảnh của lần observe ({x,y} trong khung ảnh đã thu nhỏ, kèm scale) → toạ độ màn hình. */
781
+ static System.Windows.Point WindowPoint(IntPtr window, Dictionary<string, object> a, Dictionary<string, object> pt) {
782
+ if (window == IntPtr.Zero) throw new GuiError("INVALID_ARGS", "A window is required for x/y targets");
783
+ Native.RECT r; Native.GetWindowRect(window, out r);
784
+ double scale = Dbl(a, "image_scale", 1.0);
785
+ if (scale <= 0) scale = 1.0;
786
+ double x = Dbl(pt, "x", -1), y = Dbl(pt, "y", -1);
787
+ if (x < 0 || y < 0) throw new GuiError("INVALID_ARGS", "x/y must be non-negative");
788
+ double sx = r.Left + x / scale, sy = r.Top + y / scale;
789
+ if (sx > r.Right || sy > r.Bottom) throw new GuiError("INVALID_ARGS", "x/y is outside the window");
790
+ return new System.Windows.Point(sx, sy);
791
+ }
792
+
793
+ static System.Windows.Point PointFor(AutomationElement el, IntPtr window, Dictionary<string, object> a) {
794
+ if (el != null) return CenterOf(el);
795
+ var pt = Get(a, "point") as Dictionary<string, object>;
796
+ if (pt == null) throw new GuiError("INVALID_ARGS", "Give node_id or point {x,y}");
797
+ return WindowPoint(window, a, pt);
798
+ }
799
+
800
+ static void MouseAt(AutomationElement el, IntPtr window, Dictionary<string, object> a, uint down, uint up, int times) {
801
+ var p = PointFor(el, window, a);
802
+ if (window != IntPtr.Zero) ForceForeground(window);
803
+ MoveCursor((int)p.X, (int)p.Y);
804
+ Thread.Sleep(30);
805
+ var list = new List<Native.INPUT>();
806
+ for (int i = 0; i < times; i++) { list.Add(MouseInput(down, 0, 0, 0)); list.Add(MouseInput(up, 0, 0, 0)); }
807
+ Send(list.ToArray());
808
+ }
809
+
810
+ static Native.INPUT MouseInput(uint flags, int dx, int dy, int data) {
811
+ var i = new Native.INPUT { type = INPUT_MOUSE };
812
+ i.u.mi = new Native.MOUSEINPUT { dx = dx, dy = dy, mouseData = data, dwFlags = flags };
813
+ return i;
814
+ }
815
+
816
+ static Native.INPUT KeyInput(ushort vk, ushort scan, uint flags) {
817
+ var i = new Native.INPUT { type = INPUT_KEYBOARD };
818
+ i.u.ki = new Native.KEYBDINPUT { wVk = vk, wScan = scan, dwFlags = flags };
819
+ return i;
820
+ }
821
+
822
+ static void Send(Native.INPUT[] inputs) {
823
+ if (inputs.Length == 0) return;
824
+ GuardInput();
825
+ uint sent = Native.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(Native.INPUT)));
826
+ lastInjectedTick = Native.GetTickCount();
827
+ if (sent != inputs.Length) throw new GuiError("GUI_INPUT_BLOCKED", "Windows blocked the input (a higher-privilege window is in front?)");
828
+ }
829
+
830
+ static void KeyTap(ushort vk) { Send(new[] { KeyInput(vk, 0, 0), KeyInput(vk, 0, KEYEVENTF_KEYUP) }); }
831
+
832
+ static void TypeText(string text) {
833
+ var list = new List<Native.INPUT>();
834
+ foreach (char ch in text) {
835
+ if (ch == '\n') { list.Add(KeyInput(0x0D, 0, 0)); list.Add(KeyInput(0x0D, 0, KEYEVENTF_KEYUP)); continue; }
836
+ if (ch == '\r') continue;
837
+ list.Add(KeyInput(0, ch, KEYEVENTF_UNICODE));
838
+ list.Add(KeyInput(0, ch, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP));
839
+ if (list.Count >= 200) { Send(list.ToArray()); list.Clear(); Thread.Sleep(5); }
840
+ }
841
+ Send(list.ToArray());
842
+ }
843
+
844
+ static readonly Dictionary<string, ushort> Keys = new Dictionary<string, ushort> {
845
+ { "ctrl", 0x11 }, { "control", 0x11 }, { "shift", 0x10 }, { "alt", 0x12 }, { "win", 0x5B }, { "meta", 0x5B },
846
+ { "enter", 0x0D }, { "return", 0x0D }, { "tab", 0x09 }, { "esc", 0x1B }, { "escape", 0x1B }, { "space", 0x20 },
847
+ { "backspace", 0x08 }, { "delete", 0x2E }, { "del", 0x2E }, { "insert", 0x2D }, { "home", 0x24 }, { "end", 0x23 },
848
+ { "pageup", 0x21 }, { "pagedown", 0x22 }, { "up", 0x26 }, { "down", 0x28 }, { "left", 0x25 }, { "right", 0x27 },
849
+ { "f1", 0x70 }, { "f2", 0x71 }, { "f3", 0x72 }, { "f4", 0x73 }, { "f5", 0x74 }, { "f6", 0x75 }, { "f7", 0x76 }, { "f8", 0x77 },
850
+ { "f9", 0x78 }, { "f10", 0x79 }, { "f11", 0x7A }, { "f12", 0x7B }, { "apps", 0x5D }, { "menu", 0x5D },
851
+ };
852
+ static readonly HashSet<ushort> Extended = new HashSet<ushort> { 0x2E, 0x2D, 0x24, 0x23, 0x21, 0x22, 0x26, 0x28, 0x25, 0x27, 0x5B, 0x5D };
853
+
854
+ /** "ctrl+s", "alt+f4", "enter", "ctrl+shift+n" — nhiều tổ hợp cách nhau bằng dấu cách: "ctrl+a delete". */
855
+ static void KeyCombo(string spec) {
856
+ foreach (string combo in spec.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) {
857
+ var vks = new List<ushort>();
858
+ foreach (string raw in combo.ToLowerInvariant().Split('+')) {
859
+ string k = raw.Trim();
860
+ if (k.Length == 0) continue;
861
+ ushort vk;
862
+ if (Keys.TryGetValue(k, out vk)) { vks.Add(vk); continue; }
863
+ if (k.Length == 1) {
864
+ short s = Native.VkKeyScan(k[0]);
865
+ if (s == -1) throw new GuiError("INVALID_ARGS", "Unknown key: " + k);
866
+ vks.Add((ushort)(s & 0xFF));
867
+ continue;
868
+ }
869
+ throw new GuiError("INVALID_ARGS", "Unknown key: " + k);
870
+ }
871
+ if (vks.Count == 0) continue;
872
+ var list = new List<Native.INPUT>();
873
+ foreach (var vk in vks) list.Add(KeyInput(vk, 0, Extended.Contains(vk) ? KEYEVENTF_EXTENDEDKEY : 0));
874
+ for (int i = vks.Count - 1; i >= 0; i--) list.Add(KeyInput(vks[i], 0, KEYEVENTF_KEYUP | (Extended.Contains(vks[i]) ? KEYEVENTF_EXTENDEDKEY : 0)));
875
+ Send(list.ToArray());
876
+ Thread.Sleep(40);
877
+ }
878
+ }
879
+ }
880
+ }
881
+ `;
882
+
883
+ export const WINDOWS_HOST_CSHARP = MAIN_CSHARP + OFFICE_CSHARP;
884
+
885
+ /** Script PowerShell: nạp DLL đã dịch (nếu có), không thì dịch từ mã C# rồi lưu DLL; sau đó chạy vòng đọc/ghi JSON. */
886
+ export const WINDOWS_HOST_PS1 = String.raw`
887
+ $ErrorActionPreference = 'Stop'
888
+ $dll = $env:AIVIN_GUI_DLL
889
+ $src = $env:AIVIN_GUI_SRC
890
+ $refs = @('UIAutomationClient', 'UIAutomationTypes', 'WindowsBase', 'System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions')
891
+ if ($dll -and (Test-Path -LiteralPath $dll)) {
892
+ Add-Type -Path $dll
893
+ } else {
894
+ foreach ($r in $refs) { Add-Type -AssemblyName $r }
895
+ if ($dll) {
896
+ Add-Type -TypeDefinition ([IO.File]::ReadAllText($src)) -ReferencedAssemblies $refs -OutputAssembly $dll -OutputType Library
897
+ Add-Type -Path $dll
898
+ } else {
899
+ Add-Type -TypeDefinition ([IO.File]::ReadAllText($src)) -ReferencedAssemblies $refs
900
+ }
901
+ }
902
+ foreach ($r in $refs) { Add-Type -AssemblyName $r }
903
+ [AivinGui.Host]::Run()
904
+ `;