@aivin-labs/cli 1.0.8 → 1.0.11

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 (51) hide show
  1. package/README.md +25 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1912 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +142 -31
  9. package/bin/lib/remote/callLedger.mjs +1 -1
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +87 -5
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/codingAgents.mjs +293 -0
  14. package/bin/lib/remote/constants.mjs +61 -0
  15. package/bin/lib/remote/dailyBrowser.mjs +1 -1
  16. package/bin/lib/remote/desktop/index.mjs +272 -0
  17. package/bin/lib/remote/desktop/linux.mjs +144 -0
  18. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  19. package/bin/lib/remote/desktop/mac.mjs +187 -0
  20. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  21. package/bin/lib/remote/desktop/strings.mjs +74 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  23. package/bin/lib/remote/docText.mjs +1 -1
  24. package/bin/lib/remote/fileIndexer.mjs +1 -1
  25. package/bin/lib/remote/gui/index.mjs +93 -12
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +280 -28
  27. package/bin/lib/remote/idempotency.mjs +1 -1
  28. package/bin/lib/remote/localPolicy.mjs +9 -2
  29. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  30. package/bin/lib/remote/mascot/ask.mjs +768 -0
  31. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  32. package/bin/lib/remote/mascot/assets.mjs +825 -216
  33. package/bin/lib/remote/mascot/bot.mjs +372 -0
  34. package/bin/lib/remote/mascot/hostSource.mjs +498 -101
  35. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  36. package/bin/lib/remote/mascot/index.mjs +199 -28
  37. package/bin/lib/remote/mascot/labels.mjs +2 -3
  38. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  39. package/bin/lib/remote/mascot/strings.mjs +204 -18
  40. package/bin/lib/remote/mascot/ui.mjs +104 -0
  41. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  42. package/bin/lib/remote/meeting/index.mjs +415 -0
  43. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  44. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  45. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  46. package/bin/lib/remote/tabGroups.mjs +209 -0
  47. package/bin/lib/remote/toolHandlers.mjs +15 -0
  48. package/docs/AIVIN_MASCOT.md +116 -0
  49. package/docs/CLI.md +142 -11
  50. package/docs/media/aivin-mascot-states.mp4 +0 -0
  51. package/package.json +1 -1
@@ -11,6 +11,10 @@ import { createWindowsHost } from './windowsHost.mjs';
11
11
  * nghèo; thao tác theo "pattern" (Invoke / Value / Toggle…) trước, chuột / phím giả lập sau. Mọi thao tác ghi trả bằng chứng đọc lại
12
12
  * sau khi làm (giá trị mới, tiêu đề cửa sổ, phần tử còn / mất).
13
13
  *
14
+ * Đợt 2 (30/10/2026): cây nghèo → host đọc chữ trên ảnh bằng OCR có sẵn của Windows (chạy trên máy), mỗi cụm chữ thành node `<snap>.t<k>`
15
+ * click / gõ được — BE tìm "nút Ghi sổ" theo chữ thay vì nhờ VLM đoán toạ độ; `gui.wait_for` chờ phần tử / cửa sổ hiện ra hoặc mất đi
16
+ * thay cho observe lặp.
17
+ *
14
18
  * Sàn cứng trên máy (BE không đổi được): không gõ vào ô mật khẩu (host chặn), không điều khiển ứng dụng nhạy cảm (`BLOCKED_PROCESSES`),
15
19
  * máy chỉ mở thư mục (không toàn quyền) thì không điều khiển cửa sổ dòng lệnh / registry — không lách vùng thư mục bằng cách gõ lệnh
16
20
  * vào terminal; người dùng đang dùng chuột / phím → dừng (`GUI_USER_ACTIVE`).
@@ -21,16 +25,27 @@ const BLOCKED_PROCESSES = new Set([
21
25
  'consent', 'credentialuihost', 'lockapp', 'logonui', 'securityhealthsystray', 'securityhealthhost', 'windowsdefender', 'msmpeng',
22
26
  'keepass', 'keepassxc', '1password', 'bitwarden', 'lastpass', 'dashlane', 'enpass', 'nordpass', 'roboform',
23
27
  ]);
24
- /** Chỉ cho khi máy toàn quyền — điều khiển được những thứ này là chạy lệnh tuỳ ý ngoài vùng thư mục. */
28
+ /**
29
+ * Chỉ cho khi máy toàn quyền — điều khiển được những thứ này là chạy lệnh tuỳ ý ngoài vùng thư mục: terminal / registry, và (30/10/2026)
30
+ * trình soạn code có terminal tích hợp + ứng dụng agent tự chạy lệnh (VS Code, Cursor, Claude…) — gõ vào terminal của VS Code hay nhờ panel
31
+ * Claude chạy lệnh cũng là lách vùng thư mục như gõ vào cmd.
32
+ */
25
33
  const SHELL_PROCESSES = new Set([
26
34
  'cmd', 'powershell', 'pwsh', 'windowsterminal', 'wt', 'openconsole', 'conhost', 'regedit', 'mmc', 'taskmgr', 'wsl', 'bash', 'mintty',
35
+ 'code', 'code - insiders', 'codium', 'cursor', 'windsurf', 'zed', 'devenv', 'idea64', 'pycharm64', 'webstorm64', 'rider64', 'goland64',
36
+ 'claude', 'chatgpt', 'warp', 'alacritty', 'wezterm-gui', 'hyper', 'tabby',
27
37
  ]);
38
+ /** Cùng nhóm đó theo tên trong menu Start (`gui.open_app` tìm theo tên, khác tên tiến trình) — chặn trước khi mở. */
39
+ const SHELL_APP_NAME = /\b(command prompt|powershell|terminal|registry editor|task manager|visual studio|vs ?code|cursor|windsurf|zed|intellij|pycharm|webstorm|rider|goland|claude|chatgpt|warp|alacritty|wezterm|hyper|tabby|wsl|ubuntu|git bash)\b/i;
28
40
  /** Không mở tệp có đuôi chạy được bằng `gui.open_app` (mở = chạy chương trình). */
29
41
  const EXECUTABLE_EXT = /\.(exe|com|bat|cmd|ps1|psm1|vbs|vbe|js|jse|wsf|wsh|msi|msp|lnk|scr|pif|hta|cpl|jar|reg|url|appref-ms|application)$/i;
30
42
 
31
43
  const OBSERVE_MAX_NODES = 300;
32
44
  const APPS_CACHE_MS = 10 * 60_000;
33
45
  const OPEN_WAIT_MS = 10_000;
46
+ const WAIT_MAX_MS = 60_000;
47
+ const FIND_DEFAULT = 20;
48
+ const FIND_MAX = 60;
34
49
  /** Báo người dùng "AI đang điều khiển" một lần mỗi quãng này (lần thao tác ghi đầu tiên). */
35
50
  const NOTIFY_EVERY_MS = 5 * 60_000;
36
51
 
@@ -64,6 +79,14 @@ export function assertWindowAllowed(windowInfo, { fullAccess }) {
64
79
  }
65
80
  }
66
81
 
82
+ /** Ứng dụng này (tên trong menu Start) có được mở không — ném lỗi trước khi mở. */
83
+ export function assertAppAllowed(name, { fullAccess }) {
84
+ if (BLOCKED_PROCESSES.has(normalizeProcess(String(name || '').replace(/\s+/g, '')))) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${name}" is not allowed`);
85
+ if (!fullAccess && SHELL_APP_NAME.test(String(name || ''))) {
86
+ throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${name}" needs full device access (aivin remote start --full-access)`);
87
+ }
88
+ }
89
+
67
90
  const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
68
91
 
69
92
  /** Chọn ứng dụng theo tên: trùng hẳn > bắt đầu bằng > chứa. Nhiều ứng viên ngang nhau → trả danh sách để Planner chọn lại. */
@@ -98,7 +121,9 @@ function runPowerShellJson(script, signal) {
98
121
  /**
99
122
  * Bộ điều khiển GUI của máy. `env.fullAccess` quyết định có cho điều khiển terminal không. `host` truyền vào được (test dùng host giả).
100
123
  */
101
- export function createGuiController({ fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true } = {}) {
124
+ export function createGuiController({
125
+ fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null,
126
+ } = {}) {
102
127
  let appsCache = null;
103
128
  let lastNotifyAt = 0;
104
129
  /** Cửa sổ của từng lần observe — để kiểm ứng dụng bị chặn ở thao tác theo node_id. */
@@ -117,14 +142,20 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
117
142
  return { windows: list.map((w) => ({ ...w, blocked: BLOCKED_PROCESSES.has(normalizeProcess(w.process)) || (!fullAccess && SHELL_PROCESSES.has(normalizeProcess(w.process))) || undefined })) };
118
143
  }
119
144
 
120
- const windowInfoOf = (args, ctx) => host.call('window_info', { window: args.window }, ctx);
145
+ /**
146
+ * Không nói cửa sổ = cửa sổ đang focus; nhưng chủ máy vừa gõ vào ô hỏi của linh vật thì focus là chính linh vật → host đổi sang cửa sổ họ
147
+ * đang dùng ngay trước đó (`defaultWindow()` = `{ avoid_pid, fallback }`).
148
+ */
149
+ const target = (args) => (args.window ? { window: args.window } : { ...defaultWindow() });
150
+ const windowInfoOf = (args, ctx) => host.call('window_info', target(args), ctx);
121
151
 
122
152
  async function observe(args, ctx) {
123
153
  const res = await host.call('observe', {
124
- window: args.window,
154
+ ...target(args),
125
155
  max_nodes: Math.min(Number(args.max_nodes) || OBSERVE_MAX_NODES, 1500),
126
156
  include_image: !!args.include_image,
127
157
  image_when_poor: args.image_when_poor !== false,
158
+ ocr: typeof args.ocr === 'boolean' ? args.ocr : undefined,
128
159
  image_max_width: Number(args.image_max_width) || 1366,
129
160
  image_quality: Number(args.image_quality) || 70,
130
161
  }, ctx);
@@ -134,9 +165,43 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
134
165
  return res;
135
166
  }
136
167
 
168
+ /**
169
+ * Chỉ những phần tử khớp chữ cần tìm (cửa sổ lớn: Excel, ERP có hàng trăm phần tử) — đi cả cây (tới 1500) rồi lọc ở đây; id vẫn của lần
170
+ * observe đó nên `gui.act` dùng được ngay. Mọi từ đều có trong tên / AutomationId / giá trị / chú thích (bỏ dấu); không phần tử nào đủ
171
+ * hết từ thì lấy phần tử khớp nhiều từ nhất.
172
+ */
173
+ async function find(args, ctx) {
174
+ const words = normalizeName(args.query).split(' ').filter(Boolean);
175
+ if (!words.length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give query (words of the element to find)');
176
+ const role = String(args.role || '').toLowerCase();
177
+ const max = Math.max(1, Math.min(Number(args.max) || FIND_DEFAULT, FIND_MAX));
178
+ const res = await observe({ ...args, max_nodes: 1500 }, ctx);
179
+ const scored = (res.nodes || [])
180
+ .filter((n) => !role || n.role === role)
181
+ .map((n) => {
182
+ const text = normalizeName([n.name, n.automation_id, n.value, n.help].filter(Boolean).join(' '));
183
+ return { n, hits: words.filter((w) => text.includes(w)).length };
184
+ })
185
+ .filter((x) => x.hits > 0);
186
+ const all = scored.filter((x) => x.hits === words.length);
187
+ const picked = (all.length ? all : scored.sort((a, b) => b.hits - a.hits)).slice(0, max).map((x) => x.n);
188
+ return { ...res, nodes: picked, query: String(args.query), matched: all.length ? all.length : scored.length, exact: all.length > 0 };
189
+ }
190
+
191
+ /** Chờ phần tử / cửa sổ hiện ra hoặc mất đi — chỉ đọc. Chờ trong một cửa sổ thì cửa sổ đó phải được phép điều khiển. */
192
+ async function waitFor(args, ctx) {
193
+ const elementWait = !!(args.name || args.automation_id);
194
+ if (elementWait || args.window) assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
195
+ return host.call('wait_for', {
196
+ ...(elementWait || args.window ? target(args) : {}),
197
+ until: args.until, name: args.name, automation_id: args.automation_id, role: args.role, title_contains: args.title_contains,
198
+ timeout_ms: Math.min(Number(args.timeout_ms) || 10_000, WAIT_MAX_MS),
199
+ }, ctx);
200
+ }
201
+
137
202
  async function focus(args, ctx) {
138
203
  assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
139
- return host.call('focus', { window: args.window }, ctx);
204
+ return host.call('focus', target(args), ctx);
140
205
  }
141
206
 
142
207
  async function act(args, ctx) {
@@ -148,7 +213,7 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
148
213
  assertWindowAllowed(windowInfo, { fullAccess });
149
214
  announce(windowInfo);
150
215
  return host.call('act', {
151
- action, node_id: args.node_id, window: args.node_id ? undefined : args.window, method: args.method, text: args.text, keys: args.keys,
216
+ action, node_id: args.node_id, ...(args.node_id ? {} : target(args)), method: args.method, text: args.text, keys: args.keys,
152
217
  option: args.option, state: args.state, direction: args.direction, amount: args.amount, point: args.point, to: args.to,
153
218
  image_scale: args.image_scale, settle_ms: args.settle_ms,
154
219
  check_user_input: true, user_input_grace_ms: Number(args.user_input_grace_ms) || 1500,
@@ -202,7 +267,7 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
202
267
  if (!matches.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No installed app named "${name}"`);
203
268
  if (matches.length > 1 && !args.first) return { ambiguous: true, candidates: matches.slice(0, 10).map((m) => m.name), hint: 'Call again with the exact name' };
204
269
  const app = matches[0];
205
- if (BLOCKED_PROCESSES.has(normalizeProcess(app.name.replace(/\s+/g, '')))) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${app.name}" is not allowed`);
270
+ assertAppAllowed(app.name, { fullAccess });
206
271
  spawn('explorer.exe', [`shell:AppsFolder\\${app.app_id}`], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
207
272
  const win = await waitNewWindow(before, ctx, app.name);
208
273
  await sendToBack(win, before, ctx);
@@ -210,27 +275,43 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
210
275
  return { opened: app.name, window: win, hint: win ? undefined : 'App started but no new window yet — call gui.windows in a moment' };
211
276
  }
212
277
 
213
- return { windows, observe, focus, act, openApp, close: () => host.close() };
278
+ return { windows, observe, find, waitFor, focus, act, openApp, close: () => host.close() };
214
279
  }
215
280
 
216
281
  /** Công cụ GUI cho danh mục của Planner. */
217
282
  export function buildGuiTools(gui) {
218
283
  const target = {
219
284
  node_id: str('target element id from the latest gui.observe (preferred)'),
220
- window: str('window handle (0x…) or a title/process to match; default the focused window'),
285
+ window: str('window handle (0x…) or a title/process to match; default the focused window (asked from the mascot: the window the person was using)'),
221
286
  };
222
287
  return [
223
288
  { name: 'gui.windows', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.windows(a, c),
224
289
  description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
225
290
  input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
226
291
  { name: 'gui.observe', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.observe(a, c),
227
- description: 'Read a window as an accessibility tree: each element has an id (node_id), role, name, value, state and supported actions. tree_quality "poor" = the app draws its own UI; a screenshot is then attached automatically (or set include_image). Ids are only valid until the next observe of that window.',
228
- input_schema: schema({ window: target.window, include_image: bool('attach a screenshot even when the tree is good'), max_nodes: num('default 300') }) },
292
+ description: 'Read a window as an accessibility tree: each element has an id (node_id), role, name, value, state and supported actions. tree_quality "poor" = the app draws its own UI; a screenshot is then attached and the text on it is read on the device (OCR): each text run becomes a node with role "text", source "ocr" and an id like "4.t2" that gui.act can click / type at. Ids are only valid until the next observe of that window.',
293
+ input_schema: schema({
294
+ window: target.window, include_image: bool('attach a screenshot even when the tree is good'), max_nodes: num('default 300'),
295
+ ocr: bool('read the text on the window even when the tree is good (default: only when poor)'),
296
+ }) },
297
+ { name: 'gui.find', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.find(a, c),
298
+ description: 'Like gui.observe but returns only the elements whose name / AutomationId / value contains the query words (accents ignored), optionally of one role — for big windows (spreadsheets, ERP forms) where the full tree is too long. Ids work with gui.act right away. exact=false means no element had every word; the closest ones are returned.',
299
+ input_schema: schema({
300
+ query: str('words of the element, e.g. "Save", "Số tiền", "Customer name"'), window: target.window,
301
+ role: str('only this role, e.g. button, edit, menuitem, dataitem'), max: num('default 20, max 60'),
302
+ }, ['query']) },
303
+ { name: 'gui.wait_for', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.waitFor(a, c),
304
+ description: 'Wait until the UI reaches a state instead of observing again and again: an element (name contains / automation_id, optional role) appears or is gone in a window, or a window whose title contains some text appears or is gone (no window = any window). Returns met + waited_ms + the match; GUI_WAIT_TIMEOUT if it did not happen in time.',
305
+ input_schema: schema({
306
+ until: str('appears (default) | gone'), window: target.window, name: str('element name contains this text (case-insensitive)'),
307
+ automation_id: str('element AutomationId (exact)'), role: str('element role, e.g. button, menuitem, edit, window'),
308
+ title_contains: str('wait on a window title instead of an element'), timeout_ms: num('default 10000, max 60000'),
309
+ }) },
229
310
  { name: 'gui.focus', group: ToolGroup.GUI, handler: (a, c) => gui.focus(a, c),
230
311
  description: 'Bring a window to the front (restores it if minimized).',
231
312
  input_schema: schema({ window: target.window }, ['window']) },
232
313
  { name: 'gui.act', group: ToolGroup.GUI, handler: (a, c) => gui.act(a, c),
233
- description: 'Do one action on an element (node_id) or at a point of the last screenshot: click, double_click, right_click, set_value (replace a field\'s text), type (keystrokes into the focused element), key (shortcut like "ctrl+s", "alt+f4", "enter"), scroll, select (option of a list/combo), toggle, expand, collapse, drag. Uses accessibility actions first (works even when the window is behind), real mouse/keyboard otherwise. Returns evidence: the element\'s new value/state, window title change, focused element. Stops with GUI_USER_ACTIVE if the person is using the mouse/keyboard.',
314
+ description: 'Do one action on an element (node_id) or at a point of the last screenshot: click, double_click, right_click, set_value (replace a field\'s text), type (keystrokes into the focused element), key (shortcut like "ctrl+s", "alt+f4", "enter"), scroll, select (option of a list/combo), toggle, expand, collapse, drag. Uses accessibility actions first (works even when the window is behind), real mouse/keyboard otherwise. Returns evidence: the element\'s new value/state, window title change, focused element. OCR text nodes ("4.t2") take click / double_click / right_click, or set_value / type (clicks there, then types). Stops with GUI_USER_ACTIVE if the person is using the mouse/keyboard.',
234
315
  input_schema: schema({
235
316
  action: str(Object.values(GuiAction).join(' | ')), ...target, text: str('text for set_value / type'), keys: str('for key: e.g. "ctrl+s", several separated by spaces'),
236
317
  option: str('for select: the option name'), state: str('for toggle: on | off'), direction: str('for scroll: up | down | left | right'), amount: num('scroll steps, default 3'),
@@ -87,6 +87,8 @@ namespace AivinGui {
87
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
88
  static readonly Dictionary<int, Dictionary<int, AutomationElement>> Snapshots = new Dictionary<int, Dictionary<int, AutomationElement>>();
89
89
  static readonly Dictionary<int, IntPtr> SnapshotWindow = new Dictionary<int, IntPtr>();
90
+ /** Chữ OCR của lần observe: node_id = "<snap>.t<k>" → khung chữ (pixel, so với góc trái trên cửa sổ). */
91
+ static readonly Dictionary<int, List<System.Windows.Rect>> OcrSnapshots = new Dictionary<int, List<System.Windows.Rect>>();
90
92
  static int snapSeq = 0;
91
93
  const int KEEP_SNAPSHOTS = 6;
92
94
  /** 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. */
@@ -160,6 +162,7 @@ namespace AivinGui {
160
162
  return new Dictionary<string, object> { { "sent_to_back", true }, { "focus_returned_to_user", restored } };
161
163
  }
162
164
  case "act": return Act(a);
165
+ case "wait_for": return WaitFor(a);
163
166
  case "office": return Office.Run(a);
164
167
  case "idle": return new Dictionary<string, object> { { "idle_ms", IdleMs() }, { "user_idle_ms", UserIdleMs() } };
165
168
  default: throw new GuiError("INVALID_ARGS", "Unknown op: " + op);
@@ -170,6 +173,7 @@ namespace AivinGui {
170
173
 
171
174
  static object Get(Dictionary<string, object> d, string k) { object v; return d != null && d.TryGetValue(k, out v) ? v : null; }
172
175
  static string Str(Dictionary<string, object> d, string k) { var v = Get(d, k); return v == null ? null : Convert.ToString(v); }
176
+ static long Long(Dictionary<string, object> d, string k) { var v = Get(d, k); try { return v == null ? 0 : Convert.ToInt64(v); } catch { return 0; } }
173
177
  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
178
  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
179
  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; } }
@@ -276,7 +280,17 @@ namespace AivinGui {
276
280
  }
277
281
  throw new GuiError("NOT_FOUND", "No window matches: " + w);
278
282
  }
279
- return Native.GetForegroundWindow();
283
+ // Đang focus là chính linh vật (chủ máy vừa bấm vào ô hỏi) → cửa sổ họ đang dùng ngay trước đó ("fallback"), không thì không có.
284
+ IntPtr fg = Native.GetForegroundWindow();
285
+ long avoid = Long(a, "avoid_pid");
286
+ if (avoid > 0 && fg != IntPtr.Zero) {
287
+ uint fgPid; Native.GetWindowThreadProcessId(fg, out fgPid);
288
+ if (fgPid == avoid) {
289
+ IntPtr back = ParseWindow(Str(a, "fallback"));
290
+ return back != IntPtr.Zero && Native.IsWindow(back) ? back : IntPtr.Zero;
291
+ }
292
+ }
293
+ return fg;
280
294
  }
281
295
 
282
296
  /** Đẩ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. */
@@ -449,7 +463,7 @@ namespace AivinGui {
449
463
  while (Snapshots.Count > KEEP_SNAPSHOTS) {
450
464
  int oldest = int.MaxValue;
451
465
  foreach (var k in Snapshots.Keys) if (k < oldest) oldest = k;
452
- Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest);
466
+ Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest); OcrSnapshots.Remove(oldest);
453
467
  }
454
468
  // 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
469
  string quality = (interactive >= 3 && named >= 5) ? "good" : "poor";
@@ -459,42 +473,79 @@ namespace AivinGui {
459
473
  { "dpi", (long)SafeDpi(h) },
460
474
  };
461
475
  bool wantImage = Bool(a, "include_image", false) || (quality == "poor" && Bool(a, "image_when_poor", true));
462
- if (wantImage) {
476
+ // Cây nghèo → đọc chữ trên ảnh (OCR của Windows, chạy trên máy): mỗi cụm chữ thành một node "text" có toạ độ, thang quyết định đích
477
+ // ở BE tìm được "nút Lưu" theo chữ như với phần tử thật thay vì đoán toạ độ trên ảnh.
478
+ bool wantOcr = Bool(a, "ocr", quality == "poor");
479
+ if (wantImage || wantOcr) {
463
480
  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;
481
+ using (var bmp = GrabWindow(h)) {
482
+ if (wantImage) {
483
+ res["image"] = EncodeImage(bmp, Int(a, "image_max_width", 1366), Int(a, "image_quality", 70));
484
+ res["image_ms"] = sw2.ElapsedMilliseconds;
485
+ }
486
+ if (wantOcr) AddOcrNodes(res, nodes, snap, bmp, Str(a, "ocr_lang"), Int(a, "ocr_max_nodes", 200));
487
+ }
466
488
  }
467
489
  return res;
468
490
  }
469
491
 
470
492
  static uint SafeDpi(IntPtr h) { try { return Native.GetDpiForWindow(h); } catch { return 96; } }
471
493
 
472
- static Dictionary<string, object> CaptureWindow(IntPtr h, int maxWidth, int quality) {
494
+ static Bitmap GrabWindow(IntPtr h) {
473
495
  Native.RECT r; Native.GetWindowRect(h, out r);
474
496
  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));
497
+ var bmp = new Bitmap(w, ht, PixelFormat.Format32bppArgb);
498
+ bool ok = false;
499
+ using (var g = Graphics.FromImage(bmp)) {
500
+ IntPtr hdc = g.GetHdc();
501
+ try { ok = Native.PrintWindow(h, hdc, 2); } finally { g.ReleaseHdc(hdc); }
502
+ // 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).
503
+ if (!ok || IsMostlyBlack(bmp)) g.CopyFromScreen(r.Left, r.Top, 0, 0, new Size(w, ht));
504
+ }
505
+ return bmp;
506
+ }
507
+
508
+ static Dictionary<string, object> EncodeImage(Bitmap bmp, int maxWidth, int quality) {
509
+ int w = bmp.Width, ht = bmp.Height;
510
+ double scale = w > maxWidth ? (double)maxWidth / w : 1.0;
511
+ int ow = Math.Max(1, (int)(w * scale)), oh = Math.Max(1, (int)(ht * scale));
512
+ using (var outBmp = new Bitmap(ow, oh, PixelFormat.Format24bppRgb)) {
513
+ using (var g2 = Graphics.FromImage(outBmp)) {
514
+ g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
515
+ g2.DrawImage(bmp, 0, 0, ow, oh);
482
516
  }
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
- }
517
+ var codec = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.MimeType == "image/jpeg");
518
+ var ep = new EncoderParameters(1);
519
+ ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Max(30, Math.Min(quality, 95)));
520
+ using (var ms = new MemoryStream()) {
521
+ outBmp.Save(ms, codec, ep);
522
+ return new Dictionary<string, object> { { "mime", "image/jpeg" }, { "base64", Convert.ToBase64String(ms.ToArray()) }, { "width", ow }, { "height", oh }, { "scale", scale } };
523
+ }
524
+ }
525
+ }
526
+
527
+ static void AddOcrNodes(Dictionary<string, object> res, List<object> nodes, int snap, Bitmap bmp, string lang, int max) {
528
+ var sw = Stopwatch.StartNew();
529
+ try {
530
+ string used;
531
+ var segments = Ocr.Read(bmp, lang, out used);
532
+ var rects = new List<System.Windows.Rect>();
533
+ foreach (var s in segments) {
534
+ if (rects.Count >= Math.Max(0, max)) break;
535
+ var r = s.Rect;
536
+ nodes.Add(new Dictionary<string, object> {
537
+ { "id", snap + ".t" + rects.Count }, { "role", "text" }, { "name", s.Text }, { "source", "ocr" },
538
+ { "rect", new Dictionary<string, object> { { "x", (int)r.X }, { "y", (int)r.Y }, { "w", (int)r.Width }, { "h", (int)r.Height } } },
539
+ });
540
+ rects.Add(r);
497
541
  }
542
+ OcrSnapshots[snap] = rects;
543
+ var info = new Dictionary<string, object> { { "lang", used }, { "count", rects.Count }, { "ms", sw.ElapsedMilliseconds } };
544
+ if (!used.StartsWith("vi", StringComparison.OrdinalIgnoreCase)) info["hint"] = "No Vietnamese OCR on this PC — Vietnamese text loses its accents. Settings → Time & language → Language → add Vietnamese (Optical character recognition)";
545
+ res["ocr"] = info;
546
+ res["node_count"] = nodes.Count;
547
+ } catch (Exception e) {
548
+ res["ocr"] = new Dictionary<string, object> { { "error", (e is GuiError ? e.Message : e.GetType().Name + ": " + e.Message) } };
498
549
  }
499
550
  }
500
551
 
@@ -567,7 +618,16 @@ namespace AivinGui {
567
618
  if (!InteractiveDesktop()) throw new GuiError("GUI_LOCKED", "The screen is locked or a secure prompt is showing");
568
619
  AutomationElement el = null;
569
620
  IntPtr window = IntPtr.Zero;
570
- if (!string.IsNullOrEmpty(nodeId)) el = NodeOf(nodeId, out window);
621
+ ocrPoint = null;
622
+ if (!string.IsNullOrEmpty(nodeId) && nodeId.Contains(".t")) {
623
+ ocrPoint = OcrPointOf(nodeId, out window);
624
+ if (action != "click" && action != "double_click" && action != "right_click" && action != "set_value" && action != "type") {
625
+ throw new GuiError("INVALID_ARGS", "Text read from the screenshot (OCR) supports click / double_click / right_click / set_value / type only");
626
+ }
627
+ // Chữ OCR không phải ô nhập: gõ vào nó = click vào chỗ đó trước rồi gõ bằng bàn phím.
628
+ if (action == "set_value" || action == "type") { MouseAt(null, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1); method = "mouse"; }
629
+ }
630
+ else if (!string.IsNullOrEmpty(nodeId)) el = NodeOf(nodeId, out window);
571
631
  else window = ResolveWindow(a);
572
632
  string beforeTitle = window == IntPtr.Zero ? "" : WindowText(window);
573
633
  if (el != null) {
@@ -790,8 +850,96 @@ namespace AivinGui {
790
850
  return new System.Windows.Point(sx, sy);
791
851
  }
792
852
 
853
+ /**
854
+ * Chờ giao diện tới trạng thái mong đợi thay vì Planner observe lặp: phần tử (tên chứa chữ / AutomationId, lọc vai trò) hiện ra hoặc mất
855
+ * đi trong cửa sổ, hoặc cửa sổ có tiêu đề chứa chữ hiện ra / đóng (không nói cửa sổ = tìm trong mọi cửa sổ). Hỏi lại mỗi ~250 ms.
856
+ */
857
+ static object WaitFor(Dictionary<string, object> a) {
858
+ string until = (Str(a, "until") ?? "appears").ToLowerInvariant();
859
+ bool gone = until == "gone" || until == "disappears";
860
+ string name = Str(a, "name"), aid = Str(a, "automation_id"), role = Str(a, "role"), title = Str(a, "title_contains");
861
+ bool windowLevel = string.IsNullOrEmpty(name) && string.IsNullOrEmpty(aid);
862
+ if (windowLevel && string.IsNullOrEmpty(title)) throw new GuiError("INVALID_ARGS", "Give name / automation_id (an element) or title_contains (a window)");
863
+ int timeout = Math.Max(200, Math.Min(Int(a, "timeout_ms", 10000), 60000));
864
+ IntPtr h = (!windowLevel || !string.IsNullOrEmpty(Str(a, "window"))) ? ResolveWindow(a) : IntPtr.Zero;
865
+ if (!windowLevel && h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused");
866
+ var sw = Stopwatch.StartNew();
867
+ while (true) {
868
+ bool alive = h == IntPtr.Zero || Native.IsWindow(h);
869
+ Dictionary<string, object> match = null;
870
+ if (windowLevel) {
871
+ if (h != IntPtr.Zero) {
872
+ if (alive && WindowText(h).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) match = WindowInfo(h, Native.GetForegroundWindow());
873
+ } else {
874
+ foreach (Dictionary<string, object> info in ListWindows(false)) {
875
+ if (Convert.ToString(info["title"]).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) { match = info; break; }
876
+ }
877
+ }
878
+ } else if (alive) {
879
+ match = FindElement(h, name, aid, role);
880
+ }
881
+ if (gone ? match == null : match != null) {
882
+ var res = new Dictionary<string, object> { { "met", true }, { "until", gone ? "gone" : "appears" }, { "waited_ms", sw.ElapsedMilliseconds } };
883
+ if (match != null) res["match"] = match;
884
+ if (!alive) res["window_closed"] = true;
885
+ return res;
886
+ }
887
+ if (!alive) throw new GuiError("GUI_WINDOW_GONE", "The window closed while waiting for the element to appear");
888
+ if (sw.ElapsedMilliseconds >= timeout) {
889
+ throw new GuiError("GUI_WAIT_TIMEOUT", "Still " + (gone ? "present" : "not there") + " after " + sw.ElapsedMilliseconds + " ms — observe to see what the window shows instead");
890
+ }
891
+ Thread.Sleep(250);
892
+ }
893
+ }
894
+
895
+ /** Phần tử đầu tiên khớp (AutomationId trùng hẳn, hoặc tên chứa chữ — không phân biệt hoa thường), có lọc vai trò. */
896
+ static Dictionary<string, object> FindElement(IntPtr h, string name, string aid, string role) {
897
+ AutomationElement root;
898
+ try { root = AutomationElement.FromHandle(h); } catch { return null; }
899
+ var cache = new CacheRequest();
900
+ cache.Add(AutomationElement.NameProperty); cache.Add(AutomationElement.ControlTypeProperty); cache.Add(AutomationElement.AutomationIdProperty);
901
+ cache.Add(AutomationElement.IsOffscreenProperty);
902
+ cache.AutomationElementMode = AutomationElementMode.None;
903
+ Condition cond = string.IsNullOrEmpty(aid) ? Condition.TrueCondition : new PropertyCondition(AutomationElement.AutomationIdProperty, aid);
904
+ AutomationElementCollection all;
905
+ try { using (cache.Activate()) { all = root.FindAll(TreeScope.Descendants, cond); } } catch (ElementNotAvailableException) { return null; }
906
+ foreach (AutomationElement e in all) {
907
+ string n = Cached(e, AutomationElement.NameProperty) as string ?? "";
908
+ var ct = Cached(e, AutomationElement.ControlTypeProperty) as ControlType;
909
+ string r = ct == null ? "" : ct.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant();
910
+ if (!string.IsNullOrEmpty(name) && n.IndexOf(name, StringComparison.OrdinalIgnoreCase) < 0) continue;
911
+ if (!string.IsNullOrEmpty(role) && !string.Equals(r, role, StringComparison.OrdinalIgnoreCase)) continue;
912
+ if (true.Equals(Cached(e, AutomationElement.IsOffscreenProperty)) && string.IsNullOrEmpty(aid)) continue;
913
+ var m = new Dictionary<string, object> { { "role", r }, { "name", Clip(n, 120) } };
914
+ string id = Cached(e, AutomationElement.AutomationIdProperty) as string;
915
+ if (!string.IsNullOrEmpty(id)) m["automation_id"] = id;
916
+ return m;
917
+ }
918
+ return null;
919
+ }
920
+
921
+ /** Điểm màn hình của node chữ OCR của thao tác đang chạy (null = không phải node OCR). */
922
+ static System.Windows.Point? ocrPoint = null;
923
+
924
+ static System.Windows.Point OcrPointOf(string nodeId, out IntPtr window) {
925
+ window = IntPtr.Zero;
926
+ int dot = nodeId.IndexOf(".t");
927
+ int snap, idx;
928
+ if (!int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 2), out idx)) throw new GuiError("INVALID_ARGS", "Bad node id: " + nodeId);
929
+ List<System.Windows.Rect> rects;
930
+ if (!OcrSnapshots.TryGetValue(snap, out rects)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
931
+ if (idx < 0 || idx >= rects.Count) throw new GuiError("NOT_FOUND", "No node " + nodeId);
932
+ window = SnapshotWindow[snap];
933
+ if (!Native.IsWindow(window)) throw new GuiError("GUI_STALE_NODE", "The window of " + nodeId + " is closed — observe again");
934
+ // Khung chữ tính theo góc cửa sổ lúc observe → cộng vị trí cửa sổ HIỆN TẠI (người dùng có thể đã kéo cửa sổ đi).
935
+ Native.RECT wr; Native.GetWindowRect(window, out wr);
936
+ var r = rects[idx];
937
+ return new System.Windows.Point(wr.Left + r.X + r.Width / 2, wr.Top + r.Y + r.Height / 2);
938
+ }
939
+
793
940
  static System.Windows.Point PointFor(AutomationElement el, IntPtr window, Dictionary<string, object> a) {
794
941
  if (el != null) return CenterOf(el);
942
+ if (ocrPoint.HasValue) return ocrPoint.Value;
795
943
  var pt = Get(a, "point") as Dictionary<string, object>;
796
944
  if (pt == null) throw new GuiError("INVALID_ARGS", "Give node_id or point {x,y}");
797
945
  return WindowPoint(window, a, pt);
@@ -877,6 +1025,110 @@ namespace AivinGui {
877
1025
  }
878
1026
  }
879
1027
  }
1028
+
1029
+ /** Một cụm chữ OCR liền nhau trên cùng dòng (một nút / nhãn), khung theo pixel của ảnh. */
1030
+ public class OcrSegment {
1031
+ public string Text;
1032
+ public System.Windows.Rect Rect;
1033
+ }
1034
+
1035
+ /**
1036
+ * OCR có sẵn của Windows 10+ (Windows.Media.Ocr, chạy trên máy, không gửi ảnh đi đâu). Gọi WinRT qua reflection — Add-Type (CodeDom,
1037
+ * C# 5) không tham chiếu được .winmd. Lần đầu ~0,1 s, các lần sau ~15 ms. Ưu tiên tiếng Việt nếu máy có gói OCR tiếng Việt, rồi ngôn
1038
+ * ngữ hồ sơ người dùng.
1039
+ */
1040
+ public static class Ocr {
1041
+ const string WRT = "System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
1042
+ static readonly Dictionary<string, object> Engines = new Dictionary<string, object>();
1043
+ static MethodInfo asTask;
1044
+
1045
+ static Type WinRT(string name, string asm) { return Type.GetType(name + ", " + asm + ", ContentType=WindowsRuntime", true); }
1046
+
1047
+ /** Chờ một IAsyncOperation<T> của WinRT: kiểu T lấy từ kiểu trả về KHAI BÁO (đối tượng COM lúc chạy không lộ interface). */
1048
+ static object Call(MethodInfo mi, object target, params object[] args) {
1049
+ object op = mi.Invoke(target, args);
1050
+ if (asTask == null) {
1051
+ foreach (var m in Type.GetType("System.WindowsRuntimeSystemExtensions, " + WRT, true).GetMethods()) {
1052
+ var ps = m.GetParameters();
1053
+ if (m.Name == "AsTask" && m.IsGenericMethod && ps.Length == 1 && ps[0].ParameterType.GetGenericTypeDefinition().FullName == "Windows.Foundation.IAsyncOperation" + (char)96 + "1") { asTask = m; break; }
1054
+ }
1055
+ if (asTask == null) throw new GuiError("GUI_OCR_UNAVAILABLE", "WinRT async bridge not found");
1056
+ }
1057
+ var task = (System.Threading.Tasks.Task)asTask.MakeGenericMethod(mi.ReturnType.GetGenericArguments()[0]).Invoke(null, new[] { op });
1058
+ if (!task.Wait(15000)) throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR timed out");
1059
+ return task.GetType().GetProperty("Result").GetValue(task, null);
1060
+ }
1061
+
1062
+ static object Engine(string lang, out string used) {
1063
+ var engineT = WinRT("Windows.Media.Ocr.OcrEngine", "Windows.Media");
1064
+ var tries = new List<string>();
1065
+ if (!string.IsNullOrEmpty(lang)) tries.Add(lang);
1066
+ tries.Add("vi");
1067
+ tries.Add("");
1068
+ foreach (var t in tries) {
1069
+ object e;
1070
+ if (Engines.TryGetValue(t, out e) && e != null) { used = Tag(e); return e; }
1071
+ if (t.Length == 0) {
1072
+ e = engineT.GetMethod("TryCreateFromUserProfileLanguages").Invoke(null, null);
1073
+ } else {
1074
+ var langT = WinRT("Windows.Globalization.Language", "Windows.Globalization");
1075
+ object l;
1076
+ try { l = Activator.CreateInstance(langT, t); } catch { continue; }
1077
+ e = engineT.GetMethod("TryCreateFromLanguage").Invoke(null, new[] { l });
1078
+ }
1079
+ Engines[t] = e;
1080
+ if (e != null) { used = Tag(e); return e; }
1081
+ }
1082
+ throw new GuiError("GUI_OCR_UNAVAILABLE", "No OCR language is installed on this PC");
1083
+ }
1084
+
1085
+ static string Tag(object engine) {
1086
+ var l = engine.GetType().GetProperty("RecognizerLanguage").GetValue(engine, null);
1087
+ return Convert.ToString(l.GetType().GetProperty("LanguageTag").GetValue(l, null));
1088
+ }
1089
+
1090
+ static double D(object o, string p) { return Convert.ToDouble(o.GetType().GetProperty(p).GetValue(o, null)); }
1091
+
1092
+ public static List<OcrSegment> Read(Bitmap bmp, string lang, out string used) {
1093
+ try {
1094
+ return ReadInner(bmp, lang, out used);
1095
+ } catch (TargetInvocationException e) {
1096
+ throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR failed: " + (e.InnerException != null ? e.InnerException.Message : e.Message));
1097
+ } catch (AggregateException e) {
1098
+ throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR failed: " + e.InnerException.Message);
1099
+ }
1100
+ }
1101
+
1102
+ static List<OcrSegment> ReadInner(Bitmap bmp, string lang, out string used) {
1103
+ object engine = Engine(lang, out used);
1104
+ var engineT = engine.GetType();
1105
+ byte[] png;
1106
+ using (var ms = new MemoryStream()) { bmp.Save(ms, ImageFormat.Png); png = ms.ToArray(); }
1107
+ var ras = Type.GetType("System.IO.WindowsRuntimeStreamExtensions, " + WRT, true)
1108
+ .GetMethod("AsRandomAccessStream", new[] { typeof(Stream) }).Invoke(null, new object[] { new MemoryStream(png) });
1109
+ var decT = WinRT("Windows.Graphics.Imaging.BitmapDecoder", "Windows.Graphics");
1110
+ var decoder = Call(decT.GetMethod("CreateAsync", new[] { WinRT("Windows.Storage.Streams.IRandomAccessStream", "Windows.Storage") }), null, ras);
1111
+ var soft = Call(decT.GetMethod("GetSoftwareBitmapAsync", Type.EmptyTypes), decoder);
1112
+ var result = Call(WinRT("Windows.Media.Ocr.OcrEngine", "Windows.Media").GetMethod("RecognizeAsync"), engine, soft);
1113
+ var segments = new List<OcrSegment>();
1114
+ foreach (var line in (System.Collections.IEnumerable)result.GetType().GetProperty("Lines").GetValue(result, null)) {
1115
+ // Một dòng OCR hay gộp nhiều nút cạnh nhau ("Save As Cancel") → tách thành cụm khi khoảng trống giữa hai từ lớn hơn ~1 chiều cao chữ.
1116
+ OcrSegment cur = null;
1117
+ double lastRight = 0;
1118
+ foreach (var w in (System.Collections.IEnumerable)line.GetType().GetProperty("Words").GetValue(line, null)) {
1119
+ var r = w.GetType().GetProperty("BoundingRect").GetValue(w, null);
1120
+ var rect = new System.Windows.Rect(D(r, "X"), D(r, "Y"), D(r, "Width"), D(r, "Height"));
1121
+ string text = Convert.ToString(w.GetType().GetProperty("Text").GetValue(w, null));
1122
+ if (cur != null && rect.X - lastRight > Math.Max(8, Math.Max(rect.Height, cur.Rect.Height))) { segments.Add(cur); cur = null; }
1123
+ if (cur == null) cur = new OcrSegment { Text = text, Rect = rect };
1124
+ else { cur.Text += " " + text; cur.Rect = System.Windows.Rect.Union(cur.Rect, rect); }
1125
+ lastRight = rect.Right;
1126
+ }
1127
+ if (cur != null) segments.Add(cur);
1128
+ }
1129
+ return segments;
1130
+ }
1131
+ }
880
1132
  }
881
1133
  `;
882
1134
 
@@ -61,7 +61,7 @@ export function createIdemLog(file, { now = () => Date.now() } = {}) {
61
61
 
62
62
  /** Đọc sổ cũ: trả các khoá còn hạn (đã xong / bị ngắt), viết gọn tệp. */
63
63
  function load() {
64
- let raw = '';
64
+ let raw;
65
65
  try { raw = fs.readFileSync(file, 'utf8'); } catch { return entries; }
66
66
  const t = now();
67
67
  for (const line of raw.split('\n')) {
@@ -42,7 +42,13 @@ const POLICY_KEY_ACCOUNT = 'remote-policy-key';
42
42
  const COMMAND_ARG = Object.freeze({ 'shell.exec': 'command', 'proc.start': 'command', 'proc.write': 'text', 'sys.schedule': 'command', 'gui.act': 'text' });
43
43
 
44
44
  /** Công cụ luôn xét là rủi ro: gửi ra ngoài thay người dùng, cài việc chạy định kỳ (cách bám trụ kinh điển của mã độc). */
45
- const ALWAYS_RISKY_TOOLS = new Set(['office.outlook.send', 'sys.schedule']);
45
+ // meeting.start: ghi âm micro + âm thanh máy — AI không tự bật ghi âm khi không ai ngồi trước máy biết (29/10/2026).
46
+ const ALWAYS_RISKY_TOOLS = new Set(['office.outlook.send', 'sys.schedule', 'meeting.start']);
47
+ const ALWAYS_RISKY_REASON = {
48
+ 'office.outlook.send': 'Gửi thư thay bạn',
49
+ 'sys.schedule': 'Đặt việc chạy định kỳ trên máy',
50
+ 'meeting.start': 'Ghi âm cuộc họp (micro + âm thanh máy) và chụp màn hình',
51
+ };
46
52
 
47
53
  /**
48
54
  * Lệnh có hậu quả khó lấy lại / chạm bảo mật — khớp chuỗi nên lách được (ghép chuỗi, mã hoá), nhưng chính các cách lách thông dụng
@@ -212,7 +218,7 @@ const commandOf = (toolName, args) => (COMMAND_ARG[toolName] ? String(args?.[COM
212
218
 
213
219
  /** Vì sao một lời gọi rủi ro (chuỗi ngắn để hiện cho người dùng) — `null` = không rủi ro. */
214
220
  export function riskReason(tool, args = {}) {
215
- if (ALWAYS_RISKY_TOOLS.has(tool.name)) return tool.name === 'office.outlook.send' ? 'Gửi thư thay bạn' : 'Đặt việc chạy định kỳ trên máy';
221
+ if (ALWAYS_RISKY_TOOLS.has(tool.name)) return ALWAYS_RISKY_REASON[tool.name];
216
222
  if (tool.destructive && args.permanent === true) return 'Xoá hẳn, không lấy lại được';
217
223
  const command = commandOf(tool.name, args);
218
224
  if (command && RISKY_COMMAND_PATTERNS.some((re) => re.test(command))) return 'Lệnh có thể thay đổi hệ thống hoặc cài đặt bảo mật';
@@ -243,6 +249,7 @@ export function describeCall(tool, args = {}) {
243
249
  const command = commandOf(tool.name, args);
244
250
  if (command) return cut(command);
245
251
  if (tool.name === 'office.outlook.send') return cut(`Tới: ${args.to || '?'} — ${args.subject || ''}`, 300);
252
+ if (tool.name === 'meeting.start') return cut(`${args.title || 'Cuộc họp'}${args.then ? ` — sau đó: ${args.then}` : ''}`, 300);
246
253
  if (args.path) return cut(args.path, 300);
247
254
  if (Array.isArray(args.paths)) return cut(args.paths.join(', '), 300);
248
255
  return tool.name;