@aivin-labs/cli 1.0.51 → 1.0.60

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 (32) hide show
  1. package/bin/cli.mjs +2215 -2211
  2. package/bin/lib/auth.mjs +119 -88
  3. package/bin/lib/context.mjs +58 -5
  4. package/bin/lib/loginHandoff.mjs +87 -0
  5. package/bin/lib/openFile.mjs +29 -4
  6. package/bin/lib/remote/agentContract.mjs +370 -0
  7. package/bin/lib/remote/agentEvidence.mjs +409 -0
  8. package/bin/lib/remote/autoStart.mjs +640 -623
  9. package/bin/lib/remote/client.mjs +55 -17
  10. package/bin/lib/remote/codingAgents.mjs +594 -293
  11. package/bin/lib/remote/constants.mjs +1 -1
  12. package/bin/lib/remote/credentials.mjs +131 -125
  13. package/bin/lib/remote/desktop/castAuth.mjs +44 -19
  14. package/bin/lib/remote/desktop/castConsent.mjs +79 -14
  15. package/bin/lib/remote/desktop/castInput.mjs +3 -0
  16. package/bin/lib/remote/desktop/castTrust.mjs +221 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +324 -40
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
  21. package/bin/lib/remote/desktop/strings.mjs +26 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +1512 -1385
  23. package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
  24. package/bin/lib/remote/dpapiHelper.mjs +91 -0
  25. package/bin/lib/remote/gui/index.mjs +422 -68
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -1530
  27. package/bin/lib/remote/humanInput.mjs +7 -0
  28. package/bin/lib/remote/localConfirm.mjs +2 -2
  29. package/bin/lib/remote/tokenStore.mjs +19 -2
  30. package/bin/lib/remote/toolHandlers.mjs +861 -859
  31. package/docs/CLI.md +1606 -1602
  32. package/package.json +1 -1
@@ -24,7 +24,7 @@ import { isProtectedPromptWindow } from '../humanInput.mjs';
24
24
 
25
25
  /** Tiến trình không bao giờ điều khiển: quản lý mật khẩu, hộp nâng quyền, bảo mật hệ thống, màn hình khoá. */
26
26
  const BLOCKED_PROCESSES = new Set([
27
- 'consent', 'credentialuihost', 'lockapp', 'logonui', 'securityhealthsystray', 'securityhealthhost', 'windowsdefender', 'msmpeng',
27
+ 'consent', 'credentialuihost', 'credentialuibroker', 'lockapp', 'logonui', 'securityhealthsystray', 'securityhealthhost', 'windowsdefender', 'msmpeng',
28
28
  'keepass', 'keepassxc', '1password', 'bitwarden', 'lastpass', 'dashlane', 'enpass', 'nordpass', 'roboform',
29
29
  ]);
30
30
  /**
@@ -45,12 +45,20 @@ const EXECUTABLE_EXT = /\.(exe|com|bat|cmd|ps1|psm1|vbs|vbe|js|jse|wsf|wsh|msi|m
45
45
  const OBSERVE_MAX_NODES = 300;
46
46
  const APPS_CACHE_MS = 10 * 60_000;
47
47
  const OPEN_WAIT_MS = 10_000;
48
+ /** Mở tệp: Excel / Word khởi động nguội mất 10–15 s mới ghi tên tệp lên tiêu đề. */
49
+ const OPEN_FILE_WAIT_MS = 20_000;
48
50
  const WAIT_MAX_MS = 60_000;
49
51
  const FIND_DEFAULT = 20;
50
52
  const FIND_MAX = 60;
51
53
  const SEMANTIC_CHOICES = 5;
52
54
  /** 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). */
53
55
  const NOTIFY_EVERY_MS = 5 * 60_000;
56
+ /** Không hỏi người dùng (10/11/2026, user: "xin quyền gì lắt nhắt thế"): cần chuột / phím thật thì chờ họ ngừng tay chừng này rồi mượn thật nhanh. */
57
+ export const REAL_INPUT_IDLE_MS = 2500;
58
+ /** Họ bận liên tục quá chừng này thì thôi, báo Planner để nói trong khung chat. */
59
+ export const REAL_INPUT_WAIT_MS = 30_000;
60
+ const REAL_INPUT_POLL_MS = 400;
61
+ const GUI_PERSON_PRESENT = 'GUI_PERSON_PRESENT';
54
62
 
55
63
  const str = (description) => ({ type: 'string', description });
56
64
  const num = (description) => ({ type: 'number', description });
@@ -72,8 +80,16 @@ export function detectGui({ disabled = false, multiUser = false, platform = proc
72
80
 
73
81
  const normalizeProcess = (name) => String(name || '').toLowerCase().replace(/\.exe$/, '');
74
82
 
83
+ /** PickerHost còn mở các hộp chọn tệp bình thường, nên chỉ chặn đúng hộp xác thực "Windows Security" của nó. */
84
+ function isWindowsSecurityPrompt(windowInfo) {
85
+ if (normalizeProcess(windowInfo?.process) !== 'pickerhost') return false;
86
+ const title = normalizeName(windowInfo?.title);
87
+ return title === 'windows security' || title === 'bao mat windows';
88
+ }
89
+
75
90
  /** Ứng dụng này có được điều khiển không — ném lỗi nếu bị chặn. */
76
91
  export function assertWindowAllowed(windowInfo, { fullAccess }) {
92
+ if (isWindowsSecurityPrompt(windowInfo)) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, 'This is a Windows Security prompt — only the person at this computer can answer it');
77
93
  // Hộp xác nhận / đồng ý của chính Aivin: chỉ người ở máy trả lời — AI bấm "Cho phép" là tự duyệt việc của mình (humanInput.mjs).
78
94
  if (isProtectedPromptWindow(windowInfo?.title)) {
79
95
  throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, 'This is an Aivin confirmation box — only the person at this computer can answer it');
@@ -96,39 +112,169 @@ export function assertAppAllowed(name, { fullAccess }) {
96
112
 
97
113
  const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/gi, 'd').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
98
114
 
115
+ /**
116
+ * Planner nhìn ảnh nói theo ký hiệu trên nút ("×", "7", "☰"), cây trợ năng gọi bằng chữ ("Multiply by", "Seven", "Open Navigation").
117
+ * Mỗi ký hiệu → các tên chữ hay gặp; khớp qua tên chữ bị trừ nhẹ điểm so với khớp thẳng (gui-bench 13/11/2026: "×" / "=" bị bỏ hết ký tự
118
+ * thành truy vấn rỗng, "7" không khớp "Seven").
119
+ */
120
+ const GLYPH_ALIASES = {
121
+ '×': ['multiply', 'times', 'close'], '*': ['multiply'], '✕': ['close'], '✖': ['close'], '╳': ['close'], 'x': ['close'],
122
+ '÷': ['divide'], '/': ['divide'], '+': ['plus', 'add', 'new'], '-': ['minus', 'subtract'], '−': ['minus', 'subtract'], '–': ['minus'],
123
+ '=': ['equals', 'equal'], '%': ['percent'], '±': ['positive negative', 'negate'], '+/-': ['positive negative', 'negate'], '.': ['decimal'], ',': ['decimal'],
124
+ '←': ['back'], '→': ['forward', 'next'], '↑': ['up'], '↓': ['down'], '⌫': ['backspace'],
125
+ '☰': ['navigation', 'menu'], '≡': ['navigation', 'menu'], '⋯': ['more'], '…': ['more'], '...': ['more'], '⋮': ['more'],
126
+ '🔍': ['search'], '⚙': ['settings'], '⚙️': ['settings'], '⟳': ['refresh'], '↻': ['refresh'], '✓': ['ok', 'done'], '✔': ['ok', 'done'],
127
+ menu: ['navigation'], hamburger: ['navigation', 'menu'],
128
+ };
129
+ const DIGIT_WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
130
+
131
+ /**
132
+ * Từ chỉ loại phần tử ở đầu / cuối mô tả ("nút Lưu", "Save button", "ô Họ tên", "text area") là gợi ý vai trò chứ không phải chữ trên phần
133
+ * tử. Không tách ra thì "Save button" chỉ khớp nửa câu → mơ hồ; "text area" không khớp gì dù cửa sổ chỉ có một ô soạn thảo.
134
+ */
135
+ const EDITABLE_ROLES = ['edit', 'document', 'combobox'];
136
+ const ROLE_HINTS = [
137
+ [/^(text ?box|text ?field|text ?area|text ?input|input ?box|input ?field|input|edit ?box|field|box|editor|o nhap|o)$/, EDITABLE_ROLES],
138
+ [/^(button|btn|nut|icon|bieu tuong)$/, ['button', 'splitbutton', 'menuitem', 'hyperlink']],
139
+ [/^(link|hyperlink|lien ket|duong dan)$/, ['hyperlink']],
140
+ [/^(tab)$/, ['tabitem']],
141
+ [/^(check ?box|o tich|o danh dau)$/, ['checkbox']],
142
+ [/^(drop ?down|combo ?box|combo|danh sach chon)$/, ['combobox']],
143
+ ];
144
+
145
+ function roleHintOf(phrase) {
146
+ for (const [re, roles] of ROLE_HINTS) if (re.test(phrase)) return roles;
147
+ return null;
148
+ }
149
+
150
+ /** Tách từ chỉ loại ở cuối rồi ở đầu (một hoặc hai từ). Không có → null. */
151
+ function splitRoleHint(q) {
152
+ const words = q.split(' ').filter(Boolean);
153
+ for (const n of [2, 1]) {
154
+ if (words.length >= n) {
155
+ const tail = roleHintOf(words.slice(-n).join(' '));
156
+ if (tail) return { rest: words.slice(0, -n).join(' '), roles: tail };
157
+ const head = roleHintOf(words.slice(0, n).join(' '));
158
+ if (head) return { rest: words.slice(n).join(' '), roles: head };
159
+ }
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /** Các cách hiểu một mô tả: nguyên văn, qua ký hiệu / chữ số, và bỏ từ chỉ loại (kèm vai trò gợi ý). */
165
+ function queryVariants(raw) {
166
+ const text = String(raw || '').trim();
167
+ const out = [];
168
+ const add = (q, alias, roles) => {
169
+ const n = normalizeName(q);
170
+ const words = n.split(' ').filter(Boolean);
171
+ if (!words.length && !roles) return;
172
+ if (out.some((v) => v.q === n && String(v.roles) === String(roles))) return;
173
+ out.push({ q: n, words, alias, roles });
174
+ };
175
+ add(text, false);
176
+ const lower = text.toLowerCase();
177
+ for (const a of GLYPH_ALIASES[lower] || []) add(a, true);
178
+ if (/^\d$/.test(lower)) add(DIGIT_WORDS[+lower], true);
179
+ const hint = splitRoleHint(normalizeName(text).replace(/^(the|a|an) /, ''));
180
+ if (hint) add(hint.rest, false, hint.roles);
181
+ return out;
182
+ }
183
+
184
+ /** Mô tả nói thẳng tới khung cửa sổ — chỉ khi đó mới chọn phần tử khung (nút thu nhỏ / đóng, menu hệ thống). */
185
+ const CHROME_QUERY = /\b(minimi[sz]e|maximi[sz]e|restore|close|system menu|title ?bar)\b/;
186
+ const CHROME_QUERY_VI = /(thu nhỏ|phóng to|khôi phục|đóng|thanh tiêu đề)/i;
187
+
188
+ /** Phần tử làm được thao tác này không (fill cần ô nhập, toggle cần ô tích…). undefined = không biết thao tác. */
189
+ function compatibleWith(node, action) {
190
+ const role = String(node.role || '').toLowerCase();
191
+ const p = node.patterns || [];
192
+ if (node.source === 'ocr') return true;
193
+ switch (action) {
194
+ case GuiAction.SET_VALUE: case GuiAction.TYPE: return !node.readonly && (EDITABLE_ROLES.includes(role) || p.includes('value'));
195
+ case GuiAction.TOGGLE: return p.includes('toggle') || role === 'checkbox' || role === 'radiobutton';
196
+ case GuiAction.SELECT: return p.includes('select') || p.includes('expand') || ['combobox', 'list', 'listitem', 'tabitem', 'radiobutton', 'dataitem', 'treeitem'].includes(role);
197
+ case GuiAction.CLICK: case GuiAction.DOUBLE_CLICK: return p.length > 0 || ['button', 'menuitem', 'hyperlink', 'listitem', 'tabitem', 'treeitem', 'checkbox', 'radiobutton', 'dataitem', 'splitbutton'].includes(role);
198
+ default: return undefined;
199
+ }
200
+ }
201
+
202
+ /** Từ ngắn (≤ 2 ký tự) và số chỉ khớp nguyên một từ của chữ hiện trên phần tử — không khớp đầu từ, không khớp AutomationId ("1" ≠ "Item 1"). */
203
+ const strictWord = (word) => word.length <= 2 || /^\d+$/.test(word);
204
+
99
205
  /**
100
206
  * Rank UI nodes with richer evidence while keeping the model-facing schema small. Hard exclusions happen
101
207
  * before scoring; exact accessible names and AutomationIds beat loose word matches. The margin between the
102
208
  * first two candidates is used by gui.do to refuse ambiguous actions instead of guessing.
209
+ * `complete` = mọi từ của (một cách hiểu) mô tả đều khớp. `action` (tuỳ chọn) ưu tiên phần tử làm được thao tác đó.
103
210
  */
104
- export function rankGuiNodes(nodes, query, role = '', { matchValue = true } = {}) {
105
- const q = normalizeName(query);
106
- const words = q.split(' ').filter(Boolean);
211
+ export function rankGuiNodes(nodes, query, role = '', { matchValue = true, action, includeOffscreen = false } = {}) {
212
+ const variants = queryVariants(query);
107
213
  const wantedRole = String(role || '').toLowerCase();
108
- if (!words.length) return [];
109
- return (nodes || [])
110
- .filter((n) => (!wantedRole || String(n.role || '').toLowerCase() === wantedRole || n.source === 'ocr') && !n.disabled && !n.offscreen)
214
+ if (!variants.length) return [];
215
+ const allowChrome = CHROME_QUERY.test(normalizeName(query)) || CHROME_QUERY_VI.test(String(query || ''));
216
+ // Chữ OCR nằm trên một phần tử đã tắt cũng là đã tắt: bấm vào đó không có tác dụng mà vẫn báo thành công.
217
+ const disabledRects = (nodes || []).filter((n) => n.disabled && n.rect).map((n) => n.rect);
218
+ const onDisabled = (n) => n.source === 'ocr' && n.rect && disabledRects.some((r) => {
219
+ const cx = n.rect.x + n.rect.w / 2;
220
+ const cy = n.rect.y + n.rect.h / 2;
221
+ return cx >= r.x && cx <= r.x + r.w && cy >= r.y && cy <= r.y + r.h;
222
+ });
223
+ const pool = (nodes || []).filter((n) => (!wantedRole || String(n.role || '').toLowerCase() === wantedRole || n.source === 'ocr')
224
+ && !n.disabled && (includeOffscreen || !n.offscreen) && !onDisabled(n) && (allowChrome || !n.chrome));
225
+ // Mô tả chỉ có từ chỉ loại ("text area"): ứng viên là mọi phần tử đúng loại làm được thao tác — chỉ một thì chắc, nhiều thì mơ hồ.
226
+ const roleOnly = variants.find((v) => !v.words.length && v.roles);
227
+ const roleOnlyHits = roleOnly ? pool.filter((n) => roleOnly.roles.includes(String(n.role || '').toLowerCase()) && compatibleWith(n, action) !== false) : [];
228
+ return pool
111
229
  .map((node, order) => {
112
230
  const name = normalizeName(node.name);
113
231
  const aid = normalizeName(node.automation_id);
114
232
  const value = matchValue ? normalizeName(node.value) : '';
115
233
  const help = normalizeName(node.help);
116
234
  const combined = [name, aid, value, help].filter(Boolean).join(' ');
117
- const hits = words.filter((word) => combined.includes(word)).length;
118
- if (!hits) return null;
119
- let score = Math.round((hits / words.length) * 50);
120
- const evidence = [];
121
- if (name === q) { score += 50; evidence.push('exact_name'); }
122
- else if (aid === q) { score += 45; evidence.push('exact_automation_id'); }
123
- else if (name.startsWith(q)) { score += 35; evidence.push('name_prefix'); }
124
- else if (words.every((word) => name.includes(word))) { score += 30; evidence.push('all_words_in_name'); }
125
- else if (words.every((word) => combined.includes(word))) { score += 20; evidence.push('all_words'); }
126
- if (node.source === 'ocr') { score -= 5; evidence.push('ocr'); }
127
- if (node.patterns?.length) { score += 3; evidence.push('actionable_pattern'); }
128
- return { node, score, hits, evidence, order };
235
+ const shown = [name, value, help].filter(Boolean).join(' ').split(' ');
236
+ // Khớp theo đầu từ; chỉ từ đủ dài mới được khớp giữa chuỗi (AutomationId dính liền) — "ton" (tồn) không được khớp "TogglePaneButton".
237
+ const tokens = combined.split(' ');
238
+ const nodeRole = String(node.role || '').toLowerCase();
239
+ const compat = compatibleWith(node, action);
240
+ let best = null;
241
+ for (const v of variants) {
242
+ if (!v.words.length) {
243
+ if (!roleOnlyHits.includes(node)) continue;
244
+ const entry = { score: 55, hits: 1, total: 1, complete: roleOnlyHits.length === 1, evidence: ['only_of_role'] };
245
+ if (!best || entry.score > best.score) best = entry;
246
+ continue;
247
+ }
248
+ const { q, words } = v;
249
+ const hits = words.filter((word) => (strictWord(word)
250
+ ? shown.includes(word)
251
+ : tokens.some((token) => token.startsWith(word)) || (word.length >= 4 && combined.includes(word)))).length;
252
+ if (!hits) continue;
253
+ let score = Math.round((hits / words.length) * 50);
254
+ const evidence = [];
255
+ const longQ = q.length > 2;
256
+ if (name === q) { score += 50; evidence.push('exact_name'); }
257
+ else if (longQ && aid === q) { score += 45; evidence.push('exact_automation_id'); }
258
+ else if (longQ && name.startsWith(q)) { score += 35; evidence.push('name_prefix'); }
259
+ else if (words.every((word) => (strictWord(word) ? name.split(' ').includes(word) : name.includes(word)))) { score += 30; evidence.push('all_words_in_name'); }
260
+ else if (hits === words.length) { score += 20; evidence.push('all_words'); }
261
+ if (v.alias) { score -= 5; evidence.push('alias'); }
262
+ if (v.roles) {
263
+ if (v.roles.includes(nodeRole)) { score += 8; evidence.push('role_hint'); } else if (node.source !== 'ocr') score -= 10;
264
+ }
265
+ const entry = { score, hits, total: words.length, complete: hits === words.length, evidence };
266
+ if (!best || entry.score > best.score || (entry.score === best.score && entry.complete && !best.complete)) best = entry;
267
+ }
268
+ if (!best) return null;
269
+ if (node.source === 'ocr') { best.score -= 5; best.evidence.push('ocr'); }
270
+ if (node.patterns?.length) { best.score += 3; best.evidence.push('actionable_pattern'); }
271
+ // fill vào nhãn chữ / toggle một nút thường không làm được gì mà có thể vẫn "thành công": ưu tiên phần tử làm được thao tác.
272
+ if (compat === true) { best.score += 8; best.evidence.push('fits_action'); }
273
+ else if (compat === false && action !== GuiAction.CLICK) { best.score -= 30; best.evidence.push('wrong_kind'); }
274
+ return { node, ...best, order };
129
275
  })
130
276
  .filter(Boolean)
131
- .sort((a, b) => b.score - a.score || b.hits - a.hits || a.order - b.order);
277
+ .sort((a, b) => b.score - a.score || Number(b.complete) - Number(a.complete) || b.hits - a.hits || a.order - b.order);
132
278
  }
133
279
 
134
280
  /**
@@ -153,6 +299,82 @@ export function needsServerCheck(query, node) {
153
299
  return riskyLabelWords(node?.name || node?.automation_id).some((w) => !asked.has(w));
154
300
  }
155
301
 
302
+ /**
303
+ * gui.do không chắc → trả ứng viên để BE phân giải. BE đọc `role` / `name` / `id` (DeviceGuiService: `${role} "${name}" [${id}]`), bản cũ chỉ
304
+ * có `ref` / `label` nên thông báo cho Planner thành `item "" []` — giữ cả hai kiểu.
305
+ */
306
+ function ambiguousResult(found) {
307
+ return {
308
+ ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
309
+ choices: found.nodes.map((n) => ({
310
+ ref: n.id, id: n.id, role: n.role, name: n.name || n.automation_id || undefined,
311
+ label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — '),
312
+ })),
313
+ observation: found._raw_observation,
314
+ };
315
+ }
316
+
317
+ /**
318
+ * Khung cửa sổ trong kết quả observe: bỏ thanh tiêu đề / menu hệ thống (thang phân giải ở BE cũng chọn nhầm chúng: "System" của Settings),
319
+ * giữ mỗi loại nút thu nhỏ / phóng to / đóng một cái (ứng dụng Store có hai bộ). Id của các node còn lại không đổi.
320
+ */
321
+ export function withoutChromeNoise(nodes) {
322
+ const seenCaption = new Set();
323
+ return nodes.filter((n) => {
324
+ if (!n.chrome) return true;
325
+ if (n.role !== 'button') return false;
326
+ const key = n.automation_id || n.name;
327
+ if (seenCaption.has(key)) return false;
328
+ seenCaption.add(key);
329
+ return true;
330
+ });
331
+ }
332
+
333
+ /**
334
+ * Nhiều ô nhập cùng tên: MSAA đặt tên ô theo nhãn chữ đứng trước nó, nên ô không có nhãn ngay sau cũng mang tên nhãn trên (gui-bench
335
+ * 13/11/2026: phiếu thu WinForms có hai ô "Số tiền"). Lấy ô nằm cùng hàng, bên phải nhãn chữ đúng tên đó; không phân định được → null.
336
+ */
337
+ export function pickByLabelRow(candidates, nodes, query) {
338
+ const editable = candidates.filter((n) => n.rect && compatibleWith(n, GuiAction.SET_VALUE) === true);
339
+ if (editable.length < 2) return null;
340
+ const want = normalizeName(query);
341
+ const labels = nodes.filter((n) => n.rect && n.source !== 'ocr' && String(n.role || '').toLowerCase() === 'text' && normalizeName(n.name) === want);
342
+ const sameRow = editable.filter((e) => labels.some((l) => {
343
+ const cy = e.rect.y + e.rect.h / 2;
344
+ return cy >= l.rect.y - 4 && cy <= l.rect.y + l.rect.h + 4 && e.rect.x >= l.rect.x + l.rect.w - 4;
345
+ }));
346
+ return sameRow.length === 1 ? sameRow[0] : null;
347
+ }
348
+
349
+ const CLICK_GROUND_ROLES = new Set(['button', 'splitbutton', 'menuitem', 'hyperlink', 'listitem', 'tabitem', 'treeitem', 'checkbox', 'radiobutton', 'dataitem']);
350
+
351
+ /**
352
+ * Chữ đọc trên ảnh nằm gọn trong một phần tử thật làm được thao tác (nút hiện "C" là "Clear", nút biểu tượng có chữ khác tên trợ năng) →
353
+ * thao tác trên phần tử đó: chạy bằng pattern dưới nền, có bằng chứng đọc lại, thay vì bấm toạ độ bằng chuột thật. Phần tử chứa phải ôm sát
354
+ * chữ (không lấy cả khung / vùng cuộn chứa mọi chữ). Không có → giữ node chữ.
355
+ */
356
+ export function groundOcrNode(ocrNode, nodes, action) {
357
+ if (ocrNode?.source !== 'ocr' || !ocrNode.rect) return ocrNode;
358
+ const r = ocrNode.rect;
359
+ const cx = r.x + r.w / 2;
360
+ const cy = r.y + r.h / 2;
361
+ const textArea = Math.max(1, r.w * r.h);
362
+ let best = null;
363
+ for (const n of nodes) {
364
+ if (n.source === 'ocr' || n.chrome || n.disabled || n.offscreen || !n.rect) continue;
365
+ const b = n.rect;
366
+ if (cx < b.x || cx > b.x + b.w || cy < b.y || cy > b.y + b.h) continue;
367
+ const area = b.w * b.h;
368
+ if (area > Math.max(60 * textArea, 6000) || area > 160_000) continue;
369
+ const role = String(n.role || '').toLowerCase();
370
+ const fits = action === GuiAction.CLICK || action === GuiAction.DOUBLE_CLICK || action === GuiAction.RIGHT_CLICK
371
+ ? CLICK_GROUND_ROLES.has(role) || (n.patterns || []).includes('invoke')
372
+ : compatibleWith(n, action) === true;
373
+ if (fits && (!best || area < best.rect.w * best.rect.h)) best = n;
374
+ }
375
+ return best || ocrNode;
376
+ }
377
+
156
378
  /** 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. */
157
379
  export function matchApps(apps, query) {
158
380
  const q = normalizeName(query);
@@ -167,6 +389,22 @@ export function matchApps(apps, query) {
167
389
  return scored.filter((x) => x.score === top).map((x) => x.app);
168
390
  }
169
391
 
392
+ /**
393
+ * Mở qua explorer.exe. KHÔNG `windowsHide` (13/11/2026, gui-bench): cờ đó đặt SW_HIDE trong STARTUPINFO và Explorer / ứng dụng mở tệp làm
394
+ * theo — thư mục, Notepad lần đầu mở ra cửa sổ ẨN: người dùng không thấy, gui.windows không liệt kê, open_app chờ hết 10 s rồi báo không có
395
+ * cửa sổ. explorer.exe không có cửa sổ console nên không cần giấu gì; cửa sổ mới vẫn được đưa xuống nền ở settleNewWindow.
396
+ */
397
+ /** Lệnh liên kết tệp là "Open with AIVIN Office Suite" (`"…\Aivin.exe" --open "%1"`). */
398
+ export function isAivinOpenCommand(command, executable) {
399
+ const exe = path.win32.basename(String(executable || '')).toLowerCase();
400
+ const cmd = String(command || '');
401
+ return (exe === 'aivin.exe' || /\baivin\.exe\b/i.test(cmd)) && /(^|\s)--open\b/i.test(cmd);
402
+ }
403
+
404
+ function launchShell(target) {
405
+ spawn('explorer.exe', [target], { windowsHide: false, detached: true, stdio: 'ignore' }).on('error', () => undefined).unref();
406
+ }
407
+
170
408
  function runPowerShellJson(script, signal) {
171
409
  return new Promise((resolve, reject) => {
172
410
  // Đầu ra UTF-8: tên cửa sổ / ứng dụng tiếng Việt không thành `?` (PowerShell không console ghi theo bảng mã OEM).
@@ -188,7 +426,7 @@ function runPowerShellJson(script, signal) {
188
426
  * 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ả).
189
427
  */
190
428
  export function createGuiController({
191
- fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null, fetchApps = (signal) => runPowerShellJson('Get-StartApps | Select-Object Name, AppID | ConvertTo-Json -Compress', signal),
429
+ fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null, realInputIdleMs = REAL_INPUT_IDLE_MS, realInputWaitMs = REAL_INPUT_WAIT_MS, fetchApps = (signal) => runPowerShellJson('Get-StartApps | Select-Object Name, AppID | ConvertTo-Json -Compress', signal),
192
430
  } = {}) {
193
431
  let appsCache = null;
194
432
  let appsInflight = null;
@@ -196,6 +434,24 @@ export function createGuiController({
196
434
  /** Cửa sổ của từng lần observe — để kiểm ứng dụng bị chặn ở thao tác theo node_id. */
197
435
  const snapshotWindows = new Map();
198
436
 
437
+ /**
438
+ * Thao tác chạy dưới nền thì đi thẳng. Host chỉ báo GUI_PERSON_PRESENT ngay trước lần đầu đụng chuột / phím thật, lúc chưa làm gì, nên thử lại
439
+ * là an toàn: chờ người dùng ngừng tay. Họ bận suốt → GUI_USER_ACTIVE, không có hộp hỏi nào.
440
+ */
441
+ async function whenPersonPauses(ctx, run) {
442
+ const deadline = Date.now() + Math.min(realInputWaitMs, (ctx?.timeoutMs || Infinity) / 2);
443
+ for (;;) {
444
+ try {
445
+ return await run(realInputIdleMs);
446
+ } catch (e) {
447
+ if (e?.code !== GUI_PERSON_PRESENT) throw e;
448
+ if (ctx?.signal?.aborted) throw ctx.signal.reason;
449
+ if (Date.now() + REAL_INPUT_POLL_MS >= deadline) throw new DeviceToolError(DeviceErrorCode.GUI_USER_ACTIVE, 'The person at this computer kept using it and this step needs the real mouse/keyboard — nothing was done. Tell them in the chat so they can do this step themselves or pause for a few seconds');
450
+ await new Promise((r) => setTimeout(r, REAL_INPUT_POLL_MS));
451
+ }
452
+ }
453
+ }
454
+
199
455
  const announce = (windowInfo) => {
200
456
  const now = Date.now();
201
457
  if (now - lastNotifyAt < NOTIFY_EVERY_MS) return;
@@ -206,7 +462,7 @@ export function createGuiController({
206
462
 
207
463
  async function windows(args, ctx) {
208
464
  const list = await host.call('windows', { all: !!args.include_dialogs }, ctx);
209
- return { windows: list.map((w) => ({ ...w, blocked: BLOCKED_PROCESSES.has(normalizeProcess(w.process)) || (!fullAccess && SHELL_PROCESSES.has(normalizeProcess(w.process))) || isProtectedPromptWindow(w.title) || undefined })) };
465
+ return { windows: list.map((w) => ({ ...w, blocked: BLOCKED_PROCESSES.has(normalizeProcess(w.process)) || (!fullAccess && SHELL_PROCESSES.has(normalizeProcess(w.process))) || isProtectedPromptWindow(w.title) || isWindowsSecurityPrompt(w) || undefined })) };
210
466
  }
211
467
 
212
468
  /**
@@ -233,8 +489,10 @@ export function createGuiController({
233
489
  ocr: typeof args.ocr === 'boolean' ? args.ocr : undefined,
234
490
  image_max_width: Number(args.image_max_width) || 1366,
235
491
  image_quality: Number(args.image_quality) || 70,
492
+ budget_ms: Number(args.budget_ms) || undefined,
236
493
  }, ctx);
237
494
  assertWindowAllowed(res.window, { fullAccess });
495
+ if (Array.isArray(res.nodes)) res.nodes = withoutChromeNoise(res.nodes);
238
496
  snapshotWindows.set(String(res.snapshot), res.window);
239
497
  if (snapshotWindows.size > 20) snapshotWindows.delete(snapshotWindows.keys().next().value);
240
498
  return res;
@@ -246,15 +504,26 @@ export function createGuiController({
246
504
  * hết từ thì lấy phần tử khớp nhiều từ nhất.
247
505
  */
248
506
  async function find(args, ctx) {
249
- const words = normalizeName(args.query).split(' ').filter(Boolean);
250
- if (!words.length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give query (words of the element to find)');
507
+ if (!queryVariants(args.query).length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give query (words of the element to find)');
508
+ const res = await observe({ ...args, max_nodes: 1500, budget_ms: 10_000 }, ctx);
509
+ return rankObservation(res, args);
510
+ }
511
+
512
+ /** Lọc / xếp hạng một lần observe theo mô tả (dùng chung cho gui.find và cho gui.do sau khi thêm chữ OCR vào cùng snapshot). */
513
+ function rankObservation(res, args) {
251
514
  const role = String(args.role || '').toLowerCase();
252
515
  const max = Math.max(1, Math.min(Number(args.max) || FIND_DEFAULT, FIND_MAX));
253
- const res = await observe({ ...args, max_nodes: 1500 }, ctx);
254
516
  // gui.do chọn phần tử để BẤM: không tính nội dung ô — chữ trên màn hình (thư, trang web) không được lái việc chọn nút (02/11/2026).
255
- const scored = rankGuiNodes(res.nodes, args.query, role, { matchValue: args.match_value !== false });
256
- const all = scored.filter((x) => x.hits === words.length);
257
- const pool = all.length ? all : scored.filter((x) => x.hits === scored[0]?.hits);
517
+ let scored = rankGuiNodes(res.nodes, args.query, role, { matchValue: args.match_value !== false, action: args.action });
518
+ // Không có phần tử đang hiện nào khớp đủ: xét cả phần tử khuất trong vùng cuộn (mục cuối trang Settings, danh sách dài) — host cuộn tới
519
+ // hoặc gọi pattern khi thao tác. Phần tử đang hiện luôn được ưu tiên, menu ẩn không lấn được nút đang thấy.
520
+ if (!scored.some((x) => x.complete)) {
521
+ const hidden = rankGuiNodes(res.nodes, args.query, role, { matchValue: args.match_value !== false, action: args.action, includeOffscreen: true });
522
+ if (hidden.some((x) => x.complete)) scored = hidden;
523
+ }
524
+ const all = scored.filter((x) => x.complete);
525
+ const cover = (x) => x.hits / x.total;
526
+ const pool = all.length ? all : scored.filter((x) => cover(x) === cover(scored[0]));
258
527
  const picked = pool.slice(0, max);
259
528
  const margin = picked.length > 1 ? picked[0].score - picked[1].score : picked.length ? picked[0].score : 0;
260
529
  const out = { ...res, nodes: picked.map((x) => x.node), query: String(args.query), matched: all.length || scored.length, exact: all.length > 0, confidence: !picked.length ? 'none' : margin >= 15 || picked.length === 1 ? 'high' : margin >= 5 ? 'medium' : 'low', ambiguous: picked.length > 1 && margin < 5 || undefined };
@@ -281,32 +550,30 @@ export function createGuiController({
281
550
  action, window: args.within || args.window, keys: command === 'key' ? args.value : undefined,
282
551
  direction: command === 'scroll' ? args.value : undefined,
283
552
  }, ctx);
284
- return { ok: true, action: command, effect: result.window_title_changed || result.focused_element || command };
553
+ return { ok: true, action: command, method: result.method, effect: result.window_title_changed || result.focused_element || command };
285
554
  }
286
555
 
287
556
  const query = String(args.target || '').trim();
288
557
  if (!query) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give target');
289
- let found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false }, ctx);
290
- if (!found.nodes.length && !found.ocr && found.tree_quality !== 'poor') {
291
- found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false, ocr: true }, ctx);
558
+ const findArgs = { query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false, action };
559
+ let found = await find(findArgs, ctx);
560
+ if ((!found.nodes.length || !found.exact) && !found.ocr && found.tree_quality !== 'poor') {
561
+ // Đọc chữ trên ảnh của CHÍNH lần observe vừa rồi (cùng snapshot, id nối tiếp) — không đi lại cây trợ năng lần hai.
562
+ const raw = found._raw_observation;
563
+ const extra = await host.call('ocr', { snapshot: raw.snapshot }, ctx).catch(() => null);
564
+ if (extra?.nodes?.length) {
565
+ const viaOcr = rankObservation({ ...raw, nodes: [...raw.nodes, ...extra.nodes], ocr: extra.ocr }, findArgs);
566
+ if (viaOcr.nodes.length && (viaOcr.exact || !found.nodes.length)) found = viaOcr;
567
+ }
292
568
  }
293
569
  if (!found.nodes.length) throw new DeviceToolError(DeviceErrorCode.GUI_TARGET_NOT_FOUND, `No enabled visible target matched "${query}"`);
294
- if (found.ambiguous) {
295
- return {
296
- ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
297
- choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
298
- observation: found._raw_observation,
299
- };
300
- }
570
+ let picked = found.ambiguous ? null : found.nodes[0];
571
+ if (found.ambiguous && found.exact && action === GuiAction.SET_VALUE) picked = pickByLabelRow(found.nodes, found._raw_observation?.nodes || [], query);
572
+ // Khớp một phần (không phần tử nào có đủ mọi từ) cũng là không chắc: chỉ trả ứng viên để BE phân giải, không bấm thẳng.
573
+ if (!picked || !found.exact) return ambiguousResult(found);
301
574
 
302
- const node = found.nodes[0];
303
- if (command !== 'fill' && needsServerCheck(query, node)) {
304
- return {
305
- ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
306
- choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
307
- observation: found._raw_observation,
308
- };
309
- }
575
+ const node = groundOcrNode(picked, found._raw_observation?.nodes || [], action);
576
+ if (command !== 'fill' && needsServerCheck(query, node)) return ambiguousResult(found);
310
577
  if (command === 'fill' && node.password) {
311
578
  throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'AI may not fill password or secret fields — ask the user to enter it');
312
579
  }
@@ -330,6 +597,9 @@ export function createGuiController({
330
597
  ok: true, action: command, target: node.name || node.automation_id || node.role,
331
598
  ...(verified === undefined ? {} : { verified }),
332
599
  ...(result.screen_point ? { screen_point: result.screen_point } : {}),
600
+ ...(result.app_busy ? { app_busy: true } : {}),
601
+ method: result.method,
602
+ window_class: result.window_class,
333
603
  effect: result.window_title_changed || result.target || result.focused_element || command,
334
604
  };
335
605
  }
@@ -346,8 +616,9 @@ export function createGuiController({
346
616
  }
347
617
 
348
618
  async function focus(args, ctx) {
349
- assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
350
- return host.call('focus', target(args), ctx);
619
+ const windowInfo = await windowInfoOf(args, ctx);
620
+ assertWindowAllowed(windowInfo, { fullAccess });
621
+ return whenPersonPauses(ctx, (grace) => host.call('focus', { ...target(args), check_user_input: true, user_input_grace_ms: grace }, ctx));
351
622
  }
352
623
 
353
624
  async function act(args, ctx) {
@@ -360,12 +631,23 @@ export function createGuiController({
360
631
  if (snap && !windowInfo) throw new DeviceToolError(DeviceErrorCode.GUI_STALE_NODE, `Node ${args.node_id} is from an old observation — observe again`);
361
632
  assertWindowAllowed(windowInfo, { fullAccess });
362
633
  announce(windowInfo);
363
- return host.call('act', {
634
+ return whenPersonPauses(ctx, (grace) => host.call('act', {
364
635
  action, node_id: args.node_id, ...(args.node_id ? {} : target(args)), method: args.method, text: args.text, keys: args.keys,
365
636
  option: args.option, state: args.state, direction: args.direction, amount: args.amount, point: args.point, to: args.to,
366
637
  image_scale: args.image_scale, settle_ms: args.settle_ms,
367
- check_user_input: true, user_input_grace_ms: Number(args.user_input_grace_ms) || 1500,
368
- }, ctx);
638
+ // Planner chỉ được xin chờ lâu hơn, không được rút ngắn: rút ngắn là tự cho phép lấy chuột của người đang dùng máy.
639
+ check_user_input: true, user_input_grace_ms: Math.max(grace, Number(args.user_input_grace_ms) || 0),
640
+ }, ctx));
641
+ }
642
+
643
+ /** Đọc cả bảng dưới nền: host tự cuộn, gộp các dòng rồi cuộn về chỗ cũ. */
644
+ async function readTable(args, ctx) {
645
+ const snap = args.node_id ? String(args.node_id).split('.')[0] : null;
646
+ if (!snap || String(args.node_id).includes('.t')) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give node_id of the table (from gui.observe or gui.find)');
647
+ const windowInfo = snapshotWindows.get(snap);
648
+ if (!windowInfo) throw new DeviceToolError(DeviceErrorCode.GUI_STALE_NODE, `Node ${args.node_id} is from an old observation — observe again`);
649
+ assertWindowAllowed(windowInfo, { fullAccess });
650
+ return host.call('read_table', { node_id: args.node_id, max_rows: Math.max(1, Math.min(Number(args.max_rows) || 300, 2000)) }, ctx);
369
651
  }
370
652
 
371
653
  async function listApps(signal) {
@@ -394,24 +676,93 @@ export function createGuiController({
394
676
  return null;
395
677
  }
396
678
 
397
- /** Cửa sổ AI vừa mở được Windows đưa lên trước → đẩy xuống dưới, trả focus cho cửa sổ người dùng đang dùng (chạy nền). */
398
- async function sendToBack(win, before, ctx) {
679
+ /**
680
+ * Cửa sổ đang hiện tệp vừa mở: tiêu đề chứa tên tệp, là cửa sổ mới HOẶC cửa sổ có sẵn vừa đổi tiêu đề. gui-bench 13/11/2026: Notepad / Excel /
681
+ * Explorer đang chạy thì mở tệp thành tab trong cửa sổ cũ và đóng cửa sổ tạm — trước đây trả về cửa sổ tạm (đã chết, GUI_WINDOW_GONE ở bước
682
+ * sau) hoặc chờ đủ 10 s "cửa sổ mới" không bao giờ tới. Ứng dụng không ghi tên tệp lên tiêu đề → lấy cửa sổ mới đầu tiên còn sống.
683
+ */
684
+ async function waitFileWindow(before, base, ctx) {
685
+ const want = normalizeName(base);
686
+ const titleOf = new Map(before.map((w) => [w.window, w.title]));
687
+ const started = Date.now();
688
+ const deadline = started + OPEN_FILE_WAIT_MS;
689
+ let firstFresh = null;
690
+ let freshSince = 0;
691
+ while (Date.now() < deadline) {
692
+ await new Promise((r) => setTimeout(r, 300));
693
+ if (ctx.signal?.aborted) throw ctx.signal.reason;
694
+ const now = await host.call('windows', {}, ctx);
695
+ const showing = now.filter((w) => normalizeName(w.title).includes(want));
696
+ const hit = showing.find((w) => titleOf.get(w.window) !== w.title)
697
+ // Tệp đã mở sẵn ở tab đang hiện: tiêu đề không đổi — nhận sau một nhịp (không thì vừa mở là trả ngay cửa sổ cũ trước khi tab mới kịp hiện).
698
+ || (Date.now() - started > 1500 ? showing[0] : undefined);
699
+ if (hit) return hit;
700
+ const fresh = now.find((w) => !titleOf.has(w.window));
701
+ if (fresh && !firstFresh) { firstFresh = fresh; freshSince = Date.now(); }
702
+ if (firstFresh && !now.some((w) => w.window === firstFresh.window)) firstFresh = null;
703
+ // Cửa sổ mới đã đứng yên một lúc mà tiêu đề không có tên tệp: ứng dụng đó không ghi tên tệp lên tiêu đề.
704
+ if (firstFresh && Date.now() - freshSince > 2500) return now.find((w) => w.window === firstFresh.window);
705
+ }
706
+ return firstFresh;
707
+ }
708
+
709
+ /** Cửa sổ đang ở trên cùng trước khi mở ứng dụng, kể cả loại không có trong gui.windows (hộp hệ thống, cửa sổ công cụ). */
710
+ const currentForeground = (ctx) => host.call('window_info', {}, ctx).then((w) => w?.window).catch(() => undefined);
711
+
712
+ /**
713
+ * Cửa sổ AI vừa mở được Windows đưa lên trước → đẩy xuống dưới, trả focus cho cửa sổ người dùng đang dùng (chạy nền). Ứng dụng thường tự
714
+ * kích hoạt lại ngay sau khi cửa sổ hiện ra, nên làm thêm vài lượt ngắn; host chỉ trả focus khi nó vẫn đang ở ứng dụng vừa mở.
715
+ */
716
+ async function sendToBack(win, userWindow, ctx) {
399
717
  if (!win || background === false) return;
400
- const userWindow = before.find((w) => w.focused)?.window;
401
- await host.call('to_back', { window: win.window, restore_to: userWindow }, ctx).catch(() => undefined);
718
+ for (const [i, wait] of [0, 350, 600].entries()) {
719
+ if (wait) await new Promise((r) => setTimeout(r, wait));
720
+ if (ctx.signal?.aborted) return;
721
+ await host.call('to_back', { window: win.window, restore_to: userWindow, wait_content: i === 0 }, ctx).catch(() => undefined);
722
+ }
723
+ }
724
+
725
+ /** Đưa cửa sổ mới xuống nền; cửa sổ đầu tiên đôi khi chỉ là màn hình chờ đã đóng (Sticky Notes) → trả cửa sổ thật thay vì handle đã chết. */
726
+ async function settleNewWindow(win, before, userWindow, hint, ctx) {
727
+ if (!win) return win;
728
+ await sendToBack(win, userWindow, ctx);
729
+ const alive = await host.call('window_info', { window: win.window }, ctx).then(() => true).catch(() => false);
730
+ if (alive) return win;
731
+ const next = await waitNewWindow(before, ctx, hint);
732
+ await sendToBack(next, userWindow, ctx);
733
+ return next;
734
+ }
735
+
736
+ /**
737
+ * Chặn mở tệp khi ứng dụng Windows sẽ dùng là "Open with AIVIN Office Suite" (`Aivin.exe --open`) — 13/11/2026, gui-bench: `.csv` trong HKCU
738
+ * trỏ tới ProgID không tồn tại nên Windows rơi về verb AIVIN, tệp bị đem TẢI LÊN Drive thay vì mở trong Excel. AI mở tệp trên máy không được
739
+ * kéo theo việc tải tệp lên mạng. Host không trả lời được thì cho qua (không chặn nhầm vì lỗi tra cứu).
740
+ */
741
+ async function assertNotAivinOpen(abs, ctx) {
742
+ const ext = path.extname(abs);
743
+ if (!ext) return;
744
+ const assoc = await host.call('assoc', { ext }, ctx).catch(() => null);
745
+ if (!assoc || !isAivinOpenCommand(assoc.command, assoc.executable)) return;
746
+ throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP,
747
+ `Windows opens ${ext} files on this computer with "AIVIN Office Suite", which uploads the file to Drive — not opened. Open the app by name (e.g. gui.open_app name="Excel") and open the file from there, or ask the user`);
402
748
  }
403
749
 
404
750
  /** Mở ứng dụng theo tên trong danh sách Start, hoặc mở một tệp trong vùng được phép bằng ứng dụng mặc định. Không chạy lệnh tuỳ ý. */
405
751
  async function openApp(args, ctx, env) {
406
752
  const before = await host.call('windows', {}, ctx);
753
+ const userWindow = await currentForeground(ctx);
407
754
  if (args.file) {
408
755
  const abs = resolveInRoots(env.roots, String(args.file));
409
756
  if (EXECUTABLE_EXT.test(abs)) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, 'Opening programs or scripts is not allowed — use an app name, or shell.exec');
410
757
  if (!fs.existsSync(abs)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `File not found: ${args.file}`);
411
- spawn('explorer.exe', [abs], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
412
- const win = await waitNewWindow(before, ctx, path.basename(abs, path.extname(abs)));
413
- await sendToBack(win, before, ctx);
414
- return { opened: path.basename(abs), window: win, hint: win ? undefined : 'No new window appeared yet — the file may have opened in an existing window; check gui.windows' };
758
+ await assertNotAivinOpen(abs, ctx);
759
+ launchShell(abs);
760
+ const base = path.basename(abs, path.extname(abs));
761
+ const shown = await waitFileWindow(before, base, ctx);
762
+ const win = shown && before.some((w) => w.window === shown.window)
763
+ ? (await sendToBack(shown, userWindow, ctx), shown)
764
+ : await settleNewWindow(shown, before, userWindow, base, ctx);
765
+ return { opened: path.basename(abs), window: win, hint: win ? undefined : 'No window shows this file yet — Windows may have no working default app for this file type; check gui.windows, or open the app by name' };
415
766
  }
416
767
  const name = String(args.name || '').trim();
417
768
  if (!name) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give name (an installed app) or file');
@@ -420,14 +771,13 @@ export function createGuiController({
420
771
  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' };
421
772
  const app = matches[0];
422
773
  assertAppAllowed(app.name, { fullAccess });
423
- spawn('explorer.exe', [`shell:AppsFolder\\${app.app_id}`], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
424
- const win = await waitNewWindow(before, ctx, app.name);
425
- await sendToBack(win, before, ctx);
774
+ launchShell(`shell:AppsFolder\\${app.app_id}`);
775
+ const win = await settleNewWindow(await waitNewWindow(before, ctx, app.name), before, userWindow, app.name, ctx);
426
776
  if (win) assertWindowAllowed(win, { fullAccess });
427
777
  return { opened: app.name, window: win, hint: win ? undefined : 'App started but no new window yet — call gui.windows in a moment' };
428
778
  }
429
779
 
430
- return { windows, observe, find, waitFor, focus, act, semanticDo, openApp, prewarm: () => listApps(), close: () => host.close() };
780
+ return { windows, observe, find, waitFor, focus, act, readTable, semanticDo, openApp, prewarm: () => listApps(), close: () => host.close() };
431
781
  }
432
782
 
433
783
  /** Công cụ GUI cho danh mục của Planner. */
@@ -448,7 +798,7 @@ export function buildGuiTools(gui) {
448
798
  description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
449
799
  input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
450
800
  { name: 'gui.observe', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.observe(a, c),
451
- 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. image_error = no screenshot this time (the app can only be captured from the screen and the window is behind/covered — gui.focus it first if a screenshot is needed).',
801
+ 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. truncated_by = why the list is partial: time / long_list (a very long table or list; scroll it, or use gui.find) / node_limit. In a long table scrolled far down, the rows on screen come back with role "row", source "accessible" and an id like "4.t2" that gui.act can click. content_unavailable = a Store app shows only its frame because it is still starting or suspended — gui.focus it, then observe again. image_error = no screenshot this time (the app can only be captured from the screen and the window is behind/covered — gui.focus it first if a screenshot is needed).',
452
802
  input_schema: schema({
453
803
  window: target.window, include_image: bool('attach a screenshot even when the tree is good'), max_nodes: num('default 300'),
454
804
  ocr: bool('read the text on the window even when the tree is good (default: only when poor)'),
@@ -466,17 +816,21 @@ export function buildGuiTools(gui) {
466
816
  automation_id: str('element AutomationId (exact)'), role: str('element role, e.g. button, menuitem, edit, window'),
467
817
  title_contains: str('wait on a window title instead of an element'), timeout_ms: num('default 10000, max 60000'),
468
818
  }) },
819
+ { name: 'gui.read_table', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.readTable(a, c),
820
+ description: 'Read a whole long table as data, in the background: scrolls it, joins the rows, scrolls back. Prefer this to observing and scrolling screen by screen. node_id = the table, from gui.observe or gui.find. Returns columns, rows (each one line of cells), complete, reason when incomplete, gaps = rows may be missing between pages.',
821
+ input_schema: schema({ node_id: target.node_id, max_rows: num('default 300, at most 2000') }, ['node_id']) },
469
822
  { name: 'gui.focus', group: ToolGroup.GUI, handler: (a, c) => gui.focus(a, c),
470
- description: 'Bring a window to the front (restores it if minimized).',
823
+ description: 'Bring a window to the front (restores it if minimized). This takes the screen from the person using the computer: most actions work on windows behind others, so only use it when an action really needs the window in front.',
471
824
  input_schema: schema({ window: target.window }, ['window']) },
472
825
  { name: 'gui.act', group: ToolGroup.GUI, handler: (a, c) => gui.act(a, c),
473
- 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). Without node_id give window. Stops with GUI_USER_ACTIVE if the person is using the mouse/keyboard, and with GUI_FOCUS_LOST (nothing clicked / the rest not typed) if real mouse/keyboard input could not reach the window — it could not come to the front, or another window covers the point.',
826
+ description: 'Runs behind the person\'s windows whenever the app allows it. Result method: invoke/value/select/toggle/scroll/background/posted = done without the real mouse; accessible = the control selected the item but no click event fired, so check the app reacted (observe) before relying on it. The real mouse/keyboard is only borrowed when the person pauses for a moment, then given back; GUI_USER_ACTIVE = they kept using the computer, nothing was done, so tell them in the chat. 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; app_busy = the action ran but the app is still working, so no evidence yet — gui.wait_for or observe later. OCR text nodes ("4.t2") take click / double_click / right_click, or set_value / type (clicks there, then types). Without node_id give window. Stops with GUI_USER_ACTIVE if the person is using the mouse/keyboard, and with GUI_FOCUS_LOST (nothing clicked / the rest not typed) if real mouse/keyboard input could not reach the window — it could not come to the front, or another window covers the point.',
827
+ // method trong kết quả: posted = gửi thẳng vào cửa sổ; accessible = control tự chọn mục, không phát sự kiện bấm.
474
828
  input_schema: schema({
475
829
  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'),
476
830
  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'),
477
831
  point: { type: 'object', description: '{x,y} on the last screenshot when no node_id', properties: { x: num('x'), y: num('y') } },
478
832
  to: { type: 'object', description: 'drag destination {x,y} on the last screenshot', properties: { x: num('x'), y: num('y') } },
479
- image_scale: num('scale of the screenshot the point was taken from'), method: str('auto | pattern | mouse (default auto)'),
833
+ image_scale: num('scale of the screenshot the point was taken from'), method: str('auto | pattern | mouse | background (default auto; background = never touch the real mouse/keyboard, fail with GUI_NEEDS_REAL_INPUT instead)'),
480
834
  }, ['action']) },
481
835
  { name: 'gui.open_app', group: ToolGroup.GUI, handler: (a, c, e) => gui.openApp(a, c, e),
482
836
  description: 'Open an installed app by name (from the Start menu list), or open a document file with its default app. Returns the new window. Does not run programs or scripts by path.',