@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,393 @@
1
+ /**
2
+ * Đầu nối Office qua COM (28/10/2026) — cùng tiến trình host với tầng giao diện (windowsHostSource.mjs), op `office`. Người dùng không cấu
3
+ * hình gì: máy có Excel / Word / Outlook (ProgID trong registry) thì CLI tự bật công cụ `office.*`.
4
+ *
5
+ * Tệp người dùng ĐANG MỞ trong Excel / Word → thao tác thẳng trên bản đó (người dùng thấy ngay, chỉ lưu khi được yêu cầu). Tệp chưa mở →
6
+ * mở bằng một bản Excel / Word ẨN riêng (chạy nền, không hiện cửa sổ), lưu rồi đóng. Gọi COM bằng reflection (C# 5, không cần interop).
7
+ * Không có `using` — ghép sau phần chính, dùng chung các `using` ở đầu tệp.
8
+ */
9
+ export const OFFICE_CSHARP = String.raw`
10
+ namespace AivinGui {
11
+ public static class Office {
12
+ const int MAX_CELLS = 5000;
13
+ const int MAX_TEXT = 200000;
14
+
15
+ class Opened { public object App; public object Doc; public bool Own; }
16
+
17
+ static string S(Dictionary<string, object> d, string k) { object v; return d != null && d.TryGetValue(k, out v) && v != null ? Convert.ToString(v) : null; }
18
+ static bool B(Dictionary<string, object> d, string k, bool def) { object v; try { return d != null && d.TryGetValue(k, out v) && v != null ? Convert.ToBoolean(v) : def; } catch { return def; } }
19
+ static int I(Dictionary<string, object> d, string k, int def) { object v; try { return d != null && d.TryGetValue(k, out v) && v != null ? Convert.ToInt32(v) : def; } catch { return def; } }
20
+
21
+ // Ứng dụng bận (đang sửa ô, hộp thoại, đang khởi động): COM từ luồng MTA không tự thử lại → thử lại tới BUSY_RETRY_MS (29/10/2026).
22
+ const uint RPC_E_CALL_REJECTED = 0x80010001;
23
+ const uint RPC_E_SERVERCALL_RETRYLATER = 0x8001010A;
24
+ const int BUSY_RETRY_MS = 2000;
25
+ const int BUSY_RETRY_STEP_MS = 200;
26
+
27
+ static bool IsBusy(Exception e) {
28
+ var com = (e is TargetInvocationException && e.InnerException != null ? e.InnerException : e) as COMException;
29
+ return com != null && ((uint)com.ErrorCode == RPC_E_CALL_REJECTED || (uint)com.ErrorCode == RPC_E_SERVERCALL_RETRYLATER);
30
+ }
31
+
32
+ static object Inv(object o, string n, BindingFlags f, object[] a) {
33
+ for (int waited = 0; ; waited += BUSY_RETRY_STEP_MS) {
34
+ try { return o.GetType().InvokeMember(n, f, null, o, a); }
35
+ catch (Exception e) {
36
+ if (IsBusy(e) && waited < BUSY_RETRY_MS) { Thread.Sleep(BUSY_RETRY_STEP_MS); continue; }
37
+ if (IsBusy(e)) throw new GuiError("OFFICE_BUSY", n + ": the app is busy (a cell is being edited or a dialog is open)");
38
+ if (e is TargetInvocationException) throw new GuiError("OFFICE_FAILED", n + ": " + (e.InnerException != null ? e.InnerException.Message : e.Message));
39
+ if (e is COMException) throw new GuiError("OFFICE_FAILED", n + ": " + e.Message);
40
+ throw;
41
+ }
42
+ }
43
+ }
44
+
45
+ /** Tệp đang mở ở bản Excel / Word khác (bận) nên bản ẩn chỉ mở được dạng chỉ đọc → báo rõ thay vì để bước lưu hỏng khó hiểu. */
46
+ static void RequireWritable(object doc, bool readOnly, string path, bool word) {
47
+ if (readOnly) return;
48
+ bool ro = false;
49
+ try { ro = Convert.ToBoolean(Get(doc, "ReadOnly")); } catch (GuiError) { }
50
+ if (!ro) return;
51
+ try { if (word) Call(doc, "Close", 0); else Call(doc, "Close", false); } catch (GuiError) { }
52
+ throw new GuiError("OFFICE_BUSY", "File is open in another Excel / Word window that is busy or locked: " + path + " - ask the user to finish editing there (press Enter or Esc, close dialogs) or close the file, then try again");
53
+ }
54
+ static object Get(object o, string n, params object[] a) { return Inv(o, n, BindingFlags.GetProperty | BindingFlags.InvokeMethod, a); }
55
+ static void Set(object o, string n, object v) { Inv(o, n, BindingFlags.SetProperty, new object[] { v }); }
56
+ static object Call(object o, string n, params object[] a) { return Inv(o, n, BindingFlags.InvokeMethod, a); }
57
+ static void Release(object o) { try { if (o != null && Marshal.IsComObject(o)) Marshal.ReleaseComObject(o); } catch { } }
58
+ static object Running(string progId) { try { return Marshal.GetActiveObject(progId); } catch { return null; } }
59
+
60
+ static object Create(string progId) {
61
+ Type t = Type.GetTypeFromProgID(progId);
62
+ if (t == null) throw new GuiError("OFFICE_NOT_INSTALLED", progId + " is not installed on this computer");
63
+ try { return Activator.CreateInstance(t); }
64
+ catch (COMException e) {
65
+ // 0x80080005: ứng dụng đang chạy ở mức quyền khác (mở bằng "Run as administrator") hoặc bản mới không còn COM (Outlook mới) — chạy
66
+ // thật 28/10/2026 trên máy có cả Outlook cổ điển đang mở lẫn Outlook mới.
67
+ if ((uint)e.ErrorCode == 0x80080005) throw new GuiError("OFFICE_UNAVAILABLE", progId + " is running with different permissions (e.g. opened as administrator) or is the new app without automation - ask the user to reopen it normally, or use the GUI");
68
+ throw new GuiError("OFFICE_UNAVAILABLE", progId + " could not start: " + e.Message);
69
+ }
70
+ }
71
+
72
+ public static object Run(Dictionary<string, object> a) {
73
+ string op = S(a, "op") ?? "";
74
+ switch (op) {
75
+ case "excel.read": return ExcelRead(a);
76
+ case "excel.write": return ExcelWrite(a);
77
+ case "word.read": return WordRead(a);
78
+ case "word.edit": return WordEdit(a);
79
+ case "outlook.list": return OutlookList(a);
80
+ case "outlook.compose": return OutlookCompose(a);
81
+ default: throw new GuiError("INVALID_ARGS", "Unknown office op: " + op);
82
+ }
83
+ }
84
+
85
+ // ── Excel ──────────────────────────────────────────────────────────────────────────────────
86
+
87
+ /** Sổ đang mở trong Excel của người dùng (so FullName) → dùng luôn; không thì mở bằng Excel ẩn riêng. */
88
+ static Opened OpenWorkbook(string path, bool create, bool readOnly) {
89
+ object app = Running("Excel.Application");
90
+ if (app != null) {
91
+ // Bản đang chạy không trả lời (treo / bận, RPC_E_SERVERCALL_RETRYLATER) → bỏ qua, mở bản ẩn riêng (29/10/2026: một Excel treo
92
+ // trên máy làm mọi lời gọi office.excel.* hỏng, Planner thử lại 12 lượt).
93
+ try {
94
+ object books = Get(app, "Workbooks");
95
+ int n = Convert.ToInt32(Get(books, "Count"));
96
+ for (int i = 1; i <= n; i++) {
97
+ object b = Get(books, "Item", i);
98
+ if (string.Equals(Convert.ToString(Get(b, "FullName")), path, StringComparison.OrdinalIgnoreCase)) { Release(books); return new Opened { App = app, Doc = b, Own = false }; }
99
+ Release(b);
100
+ }
101
+ Release(books);
102
+ } catch (GuiError) { }
103
+ Release(app);
104
+ }
105
+ object own = Create("Excel.Application");
106
+ try {
107
+ Set(own, "Visible", false);
108
+ Set(own, "DisplayAlerts", false);
109
+ object wbs = Get(own, "Workbooks");
110
+ object book;
111
+ if (File.Exists(path)) book = Call(wbs, "Open", path, 0, readOnly);
112
+ else if (create) { book = Call(wbs, "Add"); Call(book, "SaveAs", path); }
113
+ else throw new GuiError("NOT_FOUND", "File not found: " + path);
114
+ Release(wbs);
115
+ RequireWritable(book, readOnly, path, false);
116
+ return new Opened { App = own, Doc = book, Own = true };
117
+ } catch { try { Call(own, "Quit"); } catch { } Release(own); throw; }
118
+ }
119
+
120
+ static void CloseWorkbook(Opened o, bool save) {
121
+ try {
122
+ if (save) Call(o.Doc, "Save");
123
+ if (o.Own) Call(o.Doc, "Close", false);
124
+ } finally {
125
+ Release(o.Doc);
126
+ if (o.Own) { try { Call(o.App, "Quit"); } catch { } }
127
+ Release(o.App);
128
+ }
129
+ }
130
+
131
+ static object SheetOf(object book, string name) {
132
+ if (!string.IsNullOrEmpty(name)) {
133
+ object sheets = Get(book, "Worksheets");
134
+ try { return Get(sheets, "Item", name); } catch (GuiError) { throw new GuiError("NOT_FOUND", "No sheet named: " + name); } finally { Release(sheets); }
135
+ }
136
+ return Get(book, "ActiveSheet");
137
+ }
138
+
139
+ static List<object> SheetNames(object book) {
140
+ var names = new List<object>();
141
+ object sheets = Get(book, "Worksheets");
142
+ int n = Convert.ToInt32(Get(sheets, "Count"));
143
+ for (int i = 1; i <= n; i++) { object s = Get(sheets, "Item", i); names.Add(Convert.ToString(Get(s, "Name"))); Release(s); }
144
+ Release(sheets);
145
+ return names;
146
+ }
147
+
148
+ static object Cell(object v) {
149
+ if (v == null) return null;
150
+ if (v is double || v is string || v is bool) return v;
151
+ return Convert.ToString(v);
152
+ }
153
+
154
+ /** Value2 của vùng → mảng hàng (cắt ở MAX_CELLS ô). */
155
+ static List<object> Rows(object value, out bool truncated) {
156
+ truncated = false;
157
+ var rows = new List<object>();
158
+ var arr = value as object[,];
159
+ if (arr == null) { rows.Add(new List<object> { Cell(value) }); return rows; }
160
+ int cells = 0;
161
+ for (int r = arr.GetLowerBound(0); r <= arr.GetUpperBound(0); r++) {
162
+ var row = new List<object>();
163
+ for (int c = arr.GetLowerBound(1); c <= arr.GetUpperBound(1); c++) {
164
+ if (++cells > MAX_CELLS) { truncated = true; break; }
165
+ row.Add(Cell(arr[r, c]));
166
+ }
167
+ rows.Add(row);
168
+ if (truncated) break;
169
+ }
170
+ return rows;
171
+ }
172
+
173
+ static object ExcelRead(Dictionary<string, object> a) {
174
+ Opened o = OpenWorkbook(S(a, "path"), false, true);
175
+ try {
176
+ object ws = SheetOf(o.Doc, S(a, "sheet"));
177
+ string range = S(a, "range");
178
+ object rng = string.IsNullOrEmpty(range) ? Get(ws, "UsedRange") : Get(ws, "Range", range);
179
+ bool truncated;
180
+ var res = new Dictionary<string, object> {
181
+ { "path", S(a, "path") }, { "sheet", Convert.ToString(Get(ws, "Name")) }, { "sheets", SheetNames(o.Doc) },
182
+ { "range", Convert.ToString(Get(rng, "Address", false, false)) }, { "rows", Rows(Get(rng, "Value2"), out truncated) },
183
+ { "open_in_user_excel", !o.Own },
184
+ };
185
+ if (B(a, "formulas", false)) { bool t2; res["formulas"] = Rows(Get(rng, "Formula"), out t2); }
186
+ if (truncated) res["truncated"] = true;
187
+ Release(rng); Release(ws);
188
+ return res;
189
+ } finally { CloseWorkbook(o, false); }
190
+ }
191
+
192
+ static object JsonValue(object v) {
193
+ if (v is decimal) return Convert.ToDouble(v);
194
+ if (v is int || v is long) return Convert.ToDouble(v);
195
+ return v;
196
+ }
197
+
198
+ static void WriteCell(object ws, string addr, object v) {
199
+ object r = Get(ws, "Range", addr);
200
+ string s = v as string;
201
+ if (s != null && s.StartsWith("=")) Set(r, "Formula", s); else Set(r, "Value2", JsonValue(v));
202
+ Release(r);
203
+ }
204
+
205
+ /** cells {"B2": giá trị | "=công thức"} và / hoặc range + values (mảng hàng). Đọc lại ô vừa ghi làm bằng chứng. */
206
+ static object ExcelWrite(Dictionary<string, object> a) {
207
+ string path = S(a, "path");
208
+ Opened o = OpenWorkbook(path, B(a, "create", false), false);
209
+ bool save = B(a, "save", true);
210
+ try {
211
+ object ws = SheetOf(o.Doc, S(a, "sheet"));
212
+ var written = new Dictionary<string, object>();
213
+ var cells = a.ContainsKey("cells") ? a["cells"] as Dictionary<string, object> : null;
214
+ if (cells != null) {
215
+ foreach (var kv in cells) {
216
+ WriteCell(ws, kv.Key, kv.Value);
217
+ object r = Get(ws, "Range", kv.Key);
218
+ written[kv.Key] = Cell(Get(r, "Text"));
219
+ Release(r);
220
+ }
221
+ }
222
+ var values = a.ContainsKey("values") ? a["values"] as object[] : null;
223
+ string range = S(a, "range");
224
+ if (values != null && !string.IsNullOrEmpty(range)) {
225
+ int rowsN = values.Length, colsN = 0;
226
+ foreach (var row in values) { var arr = row as object[]; if (arr != null && arr.Length > colsN) colsN = arr.Length; }
227
+ if (rowsN * colsN > MAX_CELLS) throw new GuiError("INVALID_ARGS", "Too many cells in one write (max " + MAX_CELLS + ")");
228
+ object start = Get(ws, "Range", range);
229
+ object target = Get(start, "Resize", rowsN, Math.Max(1, colsN));
230
+ var data = new object[rowsN, Math.Max(1, colsN)];
231
+ for (int r = 0; r < rowsN; r++) {
232
+ var arr = values[r] as object[];
233
+ for (int c = 0; arr != null && c < arr.Length; c++) data[r, c] = JsonValue(arr[c]);
234
+ }
235
+ Set(target, "Value2", data);
236
+ written[Convert.ToString(Get(target, "Address", false, false))] = rowsN + "x" + colsN;
237
+ Release(target); Release(start);
238
+ }
239
+ if (written.Count == 0) throw new GuiError("INVALID_ARGS", "Give cells {\"B2\": value} or range + values");
240
+ Release(ws);
241
+ return new Dictionary<string, object> { { "path", path }, { "written", written }, { "saved", save }, { "open_in_user_excel", !o.Own } };
242
+ } finally { CloseWorkbook(o, save); }
243
+ }
244
+
245
+ // ── Word ───────────────────────────────────────────────────────────────────────────────────
246
+
247
+ static Opened OpenDocument(string path, bool create, bool readOnly) {
248
+ object app = Running("Word.Application");
249
+ if (app != null) {
250
+ // Bản đang chạy không trả lời → bỏ qua, mở bản ẩn riêng (như OpenWorkbook).
251
+ try {
252
+ object docs = Get(app, "Documents");
253
+ int n = Convert.ToInt32(Get(docs, "Count"));
254
+ for (int i = 1; i <= n; i++) {
255
+ object d = Get(docs, "Item", i);
256
+ if (string.Equals(Convert.ToString(Get(d, "FullName")), path, StringComparison.OrdinalIgnoreCase)) { Release(docs); return new Opened { App = app, Doc = d, Own = false }; }
257
+ Release(d);
258
+ }
259
+ Release(docs);
260
+ } catch (GuiError) { }
261
+ Release(app);
262
+ }
263
+ object own = Create("Word.Application");
264
+ try {
265
+ Set(own, "Visible", false);
266
+ Set(own, "DisplayAlerts", 0);
267
+ object docs = Get(own, "Documents");
268
+ object doc;
269
+ if (File.Exists(path)) doc = Call(docs, "Open", path, false, readOnly, false);
270
+ else if (create) { doc = Call(docs, "Add"); Call(doc, "SaveAs2", path); }
271
+ else throw new GuiError("NOT_FOUND", "File not found: " + path);
272
+ Release(docs);
273
+ RequireWritable(doc, readOnly, path, true);
274
+ return new Opened { App = own, Doc = doc, Own = true };
275
+ } catch { try { Call(own, "Quit", 0); } catch { } Release(own); throw; }
276
+ }
277
+
278
+ static void CloseDocument(Opened o, bool save) {
279
+ try {
280
+ if (save) Call(o.Doc, "Save");
281
+ if (o.Own) Call(o.Doc, "Close", 0);
282
+ } finally {
283
+ Release(o.Doc);
284
+ if (o.Own) { try { Call(o.App, "Quit", 0); } catch { } }
285
+ Release(o.App);
286
+ }
287
+ }
288
+
289
+ static object WordRead(Dictionary<string, object> a) {
290
+ Opened o = OpenDocument(S(a, "path"), false, true);
291
+ try {
292
+ object content = Get(o.Doc, "Content");
293
+ string text = Convert.ToString(Get(content, "Text")).Replace("\r", "\n");
294
+ int max = Math.Max(500, Math.Min(I(a, "max_chars", 20000), MAX_TEXT));
295
+ Release(content);
296
+ var res = new Dictionary<string, object> { { "path", S(a, "path") }, { "chars", text.Length }, { "text", text.Length > max ? text.Substring(0, max) : text }, { "open_in_user_word", !o.Own } };
297
+ if (text.Length > max) res["truncated"] = true;
298
+ return res;
299
+ } finally { CloseDocument(o, false); }
300
+ }
301
+
302
+ static int CountOf(string text, string find) {
303
+ if (string.IsNullOrEmpty(find)) return 0;
304
+ int n = 0, i = 0;
305
+ while ((i = text.IndexOf(find, i, StringComparison.Ordinal)) >= 0) { n++; i += find.Length; }
306
+ return n;
307
+ }
308
+
309
+ /** Thay chữ (mọi chỗ, giữ định dạng của Word) và / hoặc thêm đoạn cuối tài liệu. */
310
+ static object WordEdit(Dictionary<string, object> a) {
311
+ string path = S(a, "path");
312
+ Opened o = OpenDocument(path, B(a, "create", false), false);
313
+ bool save = B(a, "save", true);
314
+ try {
315
+ var res = new Dictionary<string, object> { { "path", path }, { "saved", save }, { "open_in_user_word", !o.Own } };
316
+ string find = S(a, "find"), replace = S(a, "replace"), append = S(a, "append");
317
+ if (!string.IsNullOrEmpty(find)) {
318
+ object content = Get(o.Doc, "Content");
319
+ int before = CountOf(Convert.ToString(Get(content, "Text")), find);
320
+ object finder = Get(content, "Find");
321
+ Call(finder, "Execute", find, true, false, false, false, false, true, 1, false, replace ?? "", 2);
322
+ Release(finder); Release(content);
323
+ object after = Get(o.Doc, "Content");
324
+ res["replaced"] = before - CountOf(Convert.ToString(Get(after, "Text")), find);
325
+ Release(after);
326
+ }
327
+ if (!string.IsNullOrEmpty(append)) {
328
+ object content = Get(o.Doc, "Content");
329
+ Call(content, "InsertParagraphAfter");
330
+ Call(content, "InsertAfter", append);
331
+ Release(content);
332
+ res["appended_chars"] = append.Length;
333
+ }
334
+ if (!res.ContainsKey("replaced") && !res.ContainsKey("appended_chars")) throw new GuiError("INVALID_ARGS", "Give find + replace and / or append");
335
+ return res;
336
+ } finally { CloseDocument(o, save); }
337
+ }
338
+
339
+ // ── Outlook ────────────────────────────────────────────────────────────────────────────────
340
+
341
+ static object OutlookApp() { return Running("Outlook.Application") ?? Create("Outlook.Application"); }
342
+
343
+ static object OutlookList(Dictionary<string, object> a) {
344
+ object app = OutlookApp();
345
+ object ns = Call(app, "GetNamespace", "MAPI");
346
+ object folder = Call(ns, "GetDefaultFolder", S(a, "folder") == "sent" ? 5 : 6);
347
+ object items = Get(folder, "Items");
348
+ Call(items, "Sort", "[ReceivedTime]", true);
349
+ int limit = Math.Max(1, Math.Min(I(a, "limit", 20), 100));
350
+ bool unreadOnly = B(a, "unread_only", false);
351
+ int previewChars = Math.Max(0, Math.Min(I(a, "preview_chars", 300), 3000));
352
+ var list = new List<object>();
353
+ int n = Convert.ToInt32(Get(items, "Count"));
354
+ for (int i = 1; i <= n && list.Count < limit; i++) {
355
+ object it = null;
356
+ try {
357
+ it = Call(items, "Item", i);
358
+ if (unreadOnly && !true.Equals(Get(it, "UnRead"))) continue;
359
+ string body = Convert.ToString(Get(it, "Body") ?? "");
360
+ list.Add(new Dictionary<string, object> {
361
+ { "subject", Convert.ToString(Get(it, "Subject")) }, { "from", Convert.ToString(Get(it, "SenderName")) },
362
+ { "from_email", Convert.ToString(Get(it, "SenderEmailAddress")) }, { "received", Convert.ToDateTime(Get(it, "ReceivedTime")).ToString("s") },
363
+ { "unread", true.Equals(Get(it, "UnRead")) }, { "preview", body.Length > previewChars ? body.Substring(0, previewChars) : body },
364
+ });
365
+ } catch (GuiError) { /* mục không phải thư (lịch họp…) */ } finally { Release(it); }
366
+ }
367
+ Release(items); Release(folder); Release(ns); Release(app);
368
+ return new Dictionary<string, object> { { "folder", S(a, "folder") == "sent" ? "sent" : "inbox" }, { "messages", list } };
369
+ }
370
+
371
+ /** Soạn thư: lưu vào Bản nháp (mặc định) hoặc gửi luôn (send). */
372
+ static object OutlookCompose(Dictionary<string, object> a) {
373
+ object app = OutlookApp();
374
+ object mail = Call(app, "CreateItem", 0);
375
+ try {
376
+ Set(mail, "To", S(a, "to") ?? "");
377
+ if (!string.IsNullOrEmpty(S(a, "cc"))) Set(mail, "CC", S(a, "cc"));
378
+ Set(mail, "Subject", S(a, "subject") ?? "");
379
+ Set(mail, "Body", S(a, "body") ?? "");
380
+ var files = a.ContainsKey("attachments") ? a["attachments"] as object[] : null;
381
+ if (files != null) {
382
+ object att = Get(mail, "Attachments");
383
+ foreach (var f in files) Call(att, "Add", Convert.ToString(f));
384
+ Release(att);
385
+ }
386
+ bool send = B(a, "send", false);
387
+ if (send) Call(mail, "Send"); else Call(mail, "Save");
388
+ return new Dictionary<string, object> { { "sent", send }, { "saved_to_drafts", !send }, { "to", S(a, "to") }, { "subject", S(a, "subject") }, { "attachments", files == null ? 0 : files.Length } };
389
+ } finally { Release(mail); Release(app); }
390
+ }
391
+ }
392
+ }
393
+ `;
@@ -0,0 +1,109 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import readline from 'readline';
4
+ import { createHash } from 'crypto';
5
+ import { spawn } from 'child_process';
6
+ import { DeviceErrorCode, REMOTE_CONFIG_DIR } from '../constants.mjs';
7
+ import { DeviceToolError } from '../sandbox.mjs';
8
+ import { WINDOWS_HOST_CSHARP, WINDOWS_HOST_PS1 } from './windowsHostSource.mjs';
9
+
10
+ /**
11
+ * Một tiến trình PowerShell sống suốt phiên làm cầu UI Automation (xem windowsHostSource.mjs). Lần đầu dịch mã C# (~vài giây) rồi lưu DLL
12
+ * theo dấu vân tay mã vào `~/.aivin/gui/`, các lần sau nạp DLL (~0,6 s). Lời gọi tuần tự theo `id`; một lời gọi treo (ứng dụng đích treo
13
+ * thì UI Automation chờ mãi) → huỷ = giết tiến trình, lời gọi sau tự dựng lại.
14
+ */
15
+
16
+ const GUI_DIR = path.join(REMOTE_CONFIG_DIR, 'gui');
17
+ const READY_TIMEOUT_MS = 60_000;
18
+
19
+ function hostFiles() {
20
+ const hash = createHash('sha256').update(WINDOWS_HOST_CSHARP).update(WINDOWS_HOST_PS1).digest('hex').slice(0, 16);
21
+ fs.mkdirSync(GUI_DIR, { recursive: true });
22
+ const src = path.join(GUI_DIR, `host-${hash}.cs`);
23
+ const ps1 = path.join(GUI_DIR, `host-${hash}.ps1`);
24
+ if (!fs.existsSync(src)) fs.writeFileSync(src, WINDOWS_HOST_CSHARP);
25
+ if (!fs.existsSync(ps1)) fs.writeFileSync(ps1, WINDOWS_HOST_PS1);
26
+ // Bản cũ của các phiên bản CLI trước — dọn để thư mục không phình.
27
+ for (const name of fs.readdirSync(GUI_DIR)) {
28
+ if (name.startsWith('host-') && !name.startsWith(`host-${hash}`)) fs.rmSync(path.join(GUI_DIR, name), { force: true });
29
+ }
30
+ return { src, ps1, dll: path.join(GUI_DIR, `host-${hash}.dll`) };
31
+ }
32
+
33
+ export function createWindowsHost({ spawnImpl = spawn } = {}) {
34
+ let child = null;
35
+ let starting = null;
36
+ let seq = 0;
37
+ const waiters = new Map();
38
+
39
+ const failAll = (error) => {
40
+ for (const w of waiters.values()) w.reject(error);
41
+ waiters.clear();
42
+ };
43
+
44
+ const kill = () => {
45
+ const c = child;
46
+ child = null;
47
+ starting = null;
48
+ if (!c) return;
49
+ try { spawnImpl('taskkill', ['/pid', String(c.pid), '/T', '/F'], { windowsHide: true }); } catch { /* đã chết */ }
50
+ };
51
+
52
+ function start() {
53
+ if (starting) return starting;
54
+ starting = new Promise((resolve, reject) => {
55
+ const files = hostFiles();
56
+ const c = spawnImpl('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', files.ps1], {
57
+ env: { ...process.env, AIVIN_GUI_SRC: files.src, AIVIN_GUI_DLL: files.dll },
58
+ windowsHide: true,
59
+ });
60
+ child = c;
61
+ let stderr = '';
62
+ let ready = false;
63
+ const timer = setTimeout(() => { if (!ready) { kill(); reject(new DeviceToolError(DeviceErrorCode.GUI_UNAVAILABLE, 'GUI helper did not start in time')); } }, READY_TIMEOUT_MS);
64
+ c.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-4000); });
65
+ readline.createInterface({ input: c.stdout }).on('line', (line) => {
66
+ let msg;
67
+ try { msg = JSON.parse(line); } catch { return; }
68
+ if (msg.ready) { ready = true; clearTimeout(timer); resolve(); return; }
69
+ const w = waiters.get(msg.id);
70
+ if (!w) return;
71
+ waiters.delete(msg.id);
72
+ if (msg.ok) w.resolve(msg.result);
73
+ else w.reject(new DeviceToolError(msg.code || DeviceErrorCode.EXECUTION_FAILED, msg.error || 'GUI call failed'));
74
+ });
75
+ c.on('error', (e) => { clearTimeout(timer); if (child === c) kill(); reject(new DeviceToolError(DeviceErrorCode.GUI_UNAVAILABLE, `Cannot start GUI helper: ${e.message}`)); });
76
+ c.on('close', () => {
77
+ clearTimeout(timer);
78
+ if (child === c) { child = null; starting = null; }
79
+ const reason = new DeviceToolError(DeviceErrorCode.GUI_UNAVAILABLE, `GUI helper exited${stderr ? `: ${stderr.trim().split(/\r?\n/).slice(-3).join(' ')}` : ''}`);
80
+ if (!ready) reject(reason);
81
+ failAll(reason);
82
+ });
83
+ });
84
+ return starting;
85
+ }
86
+
87
+ /** Một lời gọi tới host. Huỷ (`signal`) giữa chừng → giết host (không có cách ngắt một lời gọi UI Automation đang chờ). */
88
+ async function call(op, args = {}, { signal } = {}) {
89
+ if (signal?.aborted) throw signal.reason;
90
+ await start();
91
+ if (signal?.aborted) throw signal.reason;
92
+ const id = ++seq;
93
+ return new Promise((resolve, reject) => {
94
+ const onAbort = () => { waiters.delete(id); reject(signal.reason); kill(); };
95
+ signal?.addEventListener('abort', onAbort, { once: true });
96
+ waiters.set(id, {
97
+ resolve: (v) => { signal?.removeEventListener('abort', onAbort); resolve(v); },
98
+ reject: (e) => { signal?.removeEventListener('abort', onAbort); reject(e); },
99
+ });
100
+ child.stdin.write(`${JSON.stringify({ id, op, args })}\n`);
101
+ });
102
+ }
103
+
104
+ return {
105
+ call,
106
+ close: () => { failAll(new DeviceToolError(DeviceErrorCode.CANCELLED, 'GUI helper closed')); try { child?.stdin.end(); } catch { /* đã đóng */ } kill(); },
107
+ running: () => !!child,
108
+ };
109
+ }