@aivin-labs/cli 1.0.8 → 1.0.13

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 (63) hide show
  1. package/README.md +41 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1979 -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 +187 -37
  9. package/bin/lib/remote/callLedger.mjs +74 -15
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +174 -11
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +293 -0
  15. package/bin/lib/remote/constants.mjs +78 -0
  16. package/bin/lib/remote/dailyBrowser.mjs +9 -3
  17. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  18. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  19. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  20. package/bin/lib/remote/desktop/index.mjs +309 -0
  21. package/bin/lib/remote/desktop/linux.mjs +144 -0
  22. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
  23. package/bin/lib/remote/desktop/mac.mjs +187 -0
  24. package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
  25. package/bin/lib/remote/desktop/strings.mjs +74 -0
  26. package/bin/lib/remote/desktop/traySource.mjs +541 -0
  27. package/bin/lib/remote/deviceProfile.mjs +1 -0
  28. package/bin/lib/remote/docText.mjs +86 -1
  29. package/bin/lib/remote/fileIndexer.mjs +757 -399
  30. package/bin/lib/remote/folderRules.mjs +140 -0
  31. package/bin/lib/remote/gui/index.mjs +208 -18
  32. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  33. package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
  34. package/bin/lib/remote/idempotency.mjs +50 -21
  35. package/bin/lib/remote/localPolicy.mjs +17 -4
  36. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  37. package/bin/lib/remote/mascot/ask.mjs +768 -0
  38. package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
  39. package/bin/lib/remote/mascot/assets.mjs +825 -216
  40. package/bin/lib/remote/mascot/bot.mjs +397 -0
  41. package/bin/lib/remote/mascot/hostSource.mjs +500 -103
  42. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  43. package/bin/lib/remote/mascot/index.mjs +199 -28
  44. package/bin/lib/remote/mascot/labels.mjs +2 -3
  45. package/bin/lib/remote/mascot/rigSource.mjs +614 -0
  46. package/bin/lib/remote/mascot/strings.mjs +204 -18
  47. package/bin/lib/remote/mascot/ui.mjs +104 -0
  48. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  49. package/bin/lib/remote/meeting/index.mjs +415 -0
  50. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  51. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  52. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  53. package/bin/lib/remote/osSearch.mjs +107 -0
  54. package/bin/lib/remote/sqliteDb.mjs +51 -0
  55. package/bin/lib/remote/tabGroups.mjs +209 -0
  56. package/bin/lib/remote/toolHandlers.mjs +788 -726
  57. package/bin/lib/remoteControl.mjs +26 -26
  58. package/docs/AIVIN_MASCOT.md +130 -0
  59. package/docs/CLI.md +1504 -1353
  60. package/docs/media/aivin-mascot-live.gif +0 -0
  61. package/docs/media/aivin-mascot-live.png +0 -0
  62. package/docs/media/aivin-remote-architecture.svg +102 -0
  63. package/package.json +71 -71
@@ -0,0 +1,140 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { IGNORED_DIRS } from './constants.mjs';
4
+ import { isDocFile } from './docText.mjs';
5
+
6
+ /**
7
+ * Quy tắc lập chỉ mục: bỏ gì, gộp gì (31/10/2026). Đo trên máy thật: 88% tệp trong thư mục ẩn, rồi 87% phần còn lại là ảnh chụp màn hình
8
+ * tự sinh — lập chỉ mục từng tệp chỉ làm chậm và kết quả nhiễu. Những thứ bị bỏ / gộp vẫn mở được bằng fs.list / fs.grep, và tìm được qua
9
+ * bộ tìm tệp của hệ điều hành (osSearch.mjs).
10
+ */
11
+
12
+ /** Gộp thư mục thành MỘT mục (không lập chỉ mục từng tệp bên trong). */
13
+ export const FolderKind = Object.freeze({
14
+ /** Thư mục cài ứng dụng / dữ liệu ứng dụng (hồ sơ Chromium/Electron, môi trường Python, gói .app). */
15
+ APP: 'app',
16
+ /** Hàng trăm tệp không phải tài liệu (ảnh chụp màn hình, ảnh máy ảnh, log, xuất dữ liệu) — tài liệu bên trong vẫn lập chỉ mục. */
17
+ BULK: 'bulk',
18
+ /** Kho git: code tìm bằng fs.grep; chỉ lập chỉ mục README + tài liệu bên trong (trừ thư mục làm việc người dùng chỉ định). */
19
+ REPO: 'repo',
20
+ });
21
+
22
+ /** Dữ liệu ứng dụng, hệ điều hành, thùng rác, kho gói — không bao giờ lập chỉ mục. */
23
+ const INDEX_SKIP_DIRS = new Set([
24
+ 'appdata', 'application data', 'local settings', '$recycle.bin', 'system volume information', 'windows', 'program files',
25
+ 'program files (x86)', 'programdata', 'library', 'miniconda3', 'anaconda3', 'snap', 'site-packages', 'pods', 'deriveddata',
26
+ '__pycache__', '.turbo', '.pnpm-store', '.cargo', '.rustup', '.gradle', '.dart_tool', '.nuget',
27
+ 'system32', 'syswow64', 'recovery', '$windows.~bt', '$windows.~ws', 'steamapps', 'package-cache', 'caches', 'cacheddata',
28
+ '.vs', '.bundle', 'vendor',
29
+ ]);
30
+
31
+ const NORMALIZED_SKIP_DIRS = new Set([
32
+ ...INDEX_SKIP_DIRS,
33
+ ...[...IGNORED_DIRS].map((d) => d.toLowerCase()),
34
+ ]);
35
+
36
+ /** Tệp tạm / sao lưu / sinh ra khi biên dịch / tải dở — không ai tìm. */
37
+ const SKIP_FILE_EXT = new Set([
38
+ '.tmp', '.temp', '.old', '.bak', '.swp', '.swo', '.crdownload', '.part', '.partial', '.download', '.lock', '.pyc', '.pyo', '.class',
39
+ '.o', '.obj', '.pdb', '.dll', '.sys', '.cache', '.dmp', '.etl', '.blf', '.regtrans-ms', '.iso', '.vmdk', '.qcow2',
40
+ '.map', '.tsbuildinfo', '.suo', '.user', '.ilk', '.exp', '.lib', '.apk', '.aab', '.dylib', '.so',
41
+ ]);
42
+ const SKIP_FILE_NAMES = new Set([
43
+ 'thumbs.db', 'desktop.ini', 'ntuser.dat', 'ntuser.ini',
44
+ 'npm-debug.log', 'yarn-error.log', 'pnpm-debug.log',
45
+ ]);
46
+
47
+ /** Thư mục ẩn (`.claude`, `.gemini`, `.git`…) + rác build + dữ liệu hệ thống (không phân biệt hoa thường). */
48
+ export function skipDir(name, extraExcludes) {
49
+ if (!name || name.startsWith('.')) return true;
50
+ const lower = name.toLowerCase();
51
+ if (NORMALIZED_SKIP_DIRS.has(lower)) return true;
52
+ if (extraExcludes && (extraExcludes.has(name) || extraExcludes.has(lower))) return true;
53
+ return false;
54
+ }
55
+
56
+ export function skipFile(name, extraExcludes) {
57
+ if (!name) return true;
58
+ const lower = name.toLowerCase();
59
+ if (lower.startsWith('.') || lower.startsWith('~$') || lower.endsWith('~')) return true;
60
+ if (SKIP_FILE_NAMES.has(lower) || lower.startsWith('ntuser.dat')) return true;
61
+ if (SKIP_FILE_EXT.has(path.extname(lower))) return true;
62
+ if (lower.endsWith('.min.js') || lower.endsWith('.min.css') || lower.endsWith('.d.ts.map')) return true;
63
+ if (extraExcludes && (extraExcludes.has(name) || extraExcludes.has(lower))) return true;
64
+ return false;
65
+ }
66
+
67
+ export const BULK_MIN_FILES = 300;
68
+ /** Tài liệu chiếm từ chừng này trở lên → không coi là thư mục hàng loạt (thư mục 500 hoá đơn PDF vẫn lập chỉ mục từng tệp). */
69
+ const BULK_DOC_SHARE = 0.2;
70
+ const APP_MIN_DLLS = 3;
71
+
72
+ /** Phân loại thư mục theo những gì ngay bên trong (một lần readdir, không đọc tệp). null = thư mục thường. */
73
+ export function classifyDir(name, entries) {
74
+ if (/\.app$/i.test(name)) return FolderKind.APP;
75
+ const names = new Set(entries.map((e) => e.name.toLowerCase()));
76
+ if (names.has('.git')) return FolderKind.REPO;
77
+ if (names.has('pyvenv.cfg') || names.has('conda-meta') || names.has('local state') || (names.has('preferences') && names.has('local storage'))) {
78
+ return FolderKind.APP;
79
+ }
80
+ const files = entries.filter((e) => e.isFile());
81
+ const exe = files.some((f) => /\.exe$/i.test(f.name));
82
+ if (exe && files.filter((f) => /\.dll$/i.test(f.name)).length >= APP_MIN_DLLS) return FolderKind.APP;
83
+ if (files.length >= BULK_MIN_FILES && files.filter((f) => isDocFile(f.name)).length < files.length * BULK_DOC_SHARE) return FolderKind.BULK;
84
+ return null;
85
+ }
86
+
87
+ const CATEGORIES = [
88
+ { words: 'images photos pictures screenshots anh hinh chup man hinh', ext: ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.heic', '.bmp', '.tif', '.tiff', '.raw', '.cr2', '.nef', '.arw', '.dng'] },
89
+ { words: 'videos video clips recordings', ext: ['.mp4', '.mov', '.mkv', '.avi', '.webm', '.m4v', '.wmv'] },
90
+ { words: 'audio music sound recordings am thanh nhac', ext: ['.mp3', '.wav', '.m4a', '.flac', '.aac', '.ogg'] },
91
+ { words: 'logs log nhat ky', ext: ['.log'] },
92
+ { words: 'data export du lieu', ext: ['.json', '.csv', '.xml', '.ndjson', '.parquet'] },
93
+ ];
94
+
95
+ const README_RE = /^readme(\.(md|txt|rst))?$/i;
96
+ const README_CHARS = 300;
97
+
98
+ function readmeOf(dir, entries) {
99
+ const file = entries.find((e) => e.isFile() && README_RE.test(e.name));
100
+ if (!file) return '';
101
+ try {
102
+ const fd = fs.openSync(path.join(dir, file.name), 'r');
103
+ try {
104
+ const buf = Buffer.alloc(2048);
105
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
106
+ return buf.subarray(0, n).toString('utf8').replace(/\s+/g, ' ').trim().slice(0, README_CHARS);
107
+ } finally { fs.closeSync(fd); }
108
+ } catch {
109
+ return '';
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Mục đại diện cho thư mục gộp: `note` hiện trong kết quả tìm (agent biết mở bằng fs.list), `words` đưa vào chỉ mục từ khoá ("ảnh chụp màn
115
+ * hình" tìm ra Pictures\Screenshots), `count` = số mục ngay bên trong.
116
+ */
117
+ export function folderSummary(kind, dir, entries) {
118
+ const files = entries.filter((e) => e.isFile());
119
+ if (kind === FolderKind.APP) {
120
+ return { count: entries.length, words: 'application app program software data ung dung phan mem', note: 'Application / app data folder — not indexed file by file; open it with fs.list.' };
121
+ }
122
+ if (kind === FolderKind.REPO) {
123
+ const readme = readmeOf(dir, entries);
124
+ return {
125
+ count: entries.length, words: `project code repository source git du an ma nguon ${readme}`,
126
+ note: `Code project (git) — code is not indexed (use fs.grep inside it; fs.index_folder indexes it fully).${readme ? ` README: ${readme}` : ''}`,
127
+ };
128
+ }
129
+ const byExt = new Map();
130
+ for (const f of files) {
131
+ const ext = path.extname(f.name).toLowerCase() || '(none)';
132
+ byExt.set(ext, (byExt.get(ext) || 0) + 1);
133
+ }
134
+ const top = [...byExt].sort((a, b) => b[1] - a[1]);
135
+ const words = CATEGORIES.filter((c) => c.ext.some((e) => byExt.has(e))).map((c) => c.words).join(' ');
136
+ return {
137
+ count: files.length, words: `${words} ${top.map(([e]) => e.slice(1)).join(' ')}`,
138
+ note: `Folder with ${files.length} files (${top.slice(0, 3).map(([e, n]) => `${e} ${n}`).join(', ')}) — not indexed one by one (documents in it are); list it with fs.list sorted by modified.`,
139
+ };
140
+ }
@@ -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,28 @@ 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;
49
+ const SEMANTIC_CHOICES = 5;
34
50
  /** 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
51
  const NOTIFY_EVERY_MS = 5 * 60_000;
36
52
 
@@ -64,8 +80,51 @@ export function assertWindowAllowed(windowInfo, { fullAccess }) {
64
80
  }
65
81
  }
66
82
 
83
+ /** Ứng dụng này (tên trong menu Start) có được mở không — ném lỗi trước khi mở. */
84
+ export function assertAppAllowed(name, { fullAccess }) {
85
+ if (BLOCKED_PROCESSES.has(normalizeProcess(String(name || '').replace(/\s+/g, '')))) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${name}" is not allowed`);
86
+ if (!fullAccess && SHELL_APP_NAME.test(String(name || ''))) {
87
+ throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${name}" needs full device access (aivin remote start --full-access)`);
88
+ }
89
+ }
90
+
67
91
  const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
68
92
 
93
+ /**
94
+ * Rank UI nodes with richer evidence while keeping the model-facing schema small. Hard exclusions happen
95
+ * before scoring; exact accessible names and AutomationIds beat loose word matches. The margin between the
96
+ * first two candidates is used by gui.do to refuse ambiguous actions instead of guessing.
97
+ */
98
+ export function rankGuiNodes(nodes, query, role = '') {
99
+ const q = normalizeName(query);
100
+ const words = q.split(' ').filter(Boolean);
101
+ const wantedRole = String(role || '').toLowerCase();
102
+ if (!words.length) return [];
103
+ return (nodes || [])
104
+ .filter((n) => (!wantedRole || String(n.role || '').toLowerCase() === wantedRole || n.source === 'ocr') && !n.disabled && !n.offscreen)
105
+ .map((node, order) => {
106
+ const name = normalizeName(node.name);
107
+ const aid = normalizeName(node.automation_id);
108
+ const value = normalizeName(node.value);
109
+ const help = normalizeName(node.help);
110
+ const combined = [name, aid, value, help].filter(Boolean).join(' ');
111
+ const hits = words.filter((word) => combined.includes(word)).length;
112
+ if (!hits) return null;
113
+ let score = Math.round((hits / words.length) * 50);
114
+ const evidence = [];
115
+ if (name === q) { score += 50; evidence.push('exact_name'); }
116
+ else if (aid === q) { score += 45; evidence.push('exact_automation_id'); }
117
+ else if (name.startsWith(q)) { score += 35; evidence.push('name_prefix'); }
118
+ else if (words.every((word) => name.includes(word))) { score += 30; evidence.push('all_words_in_name'); }
119
+ else if (words.every((word) => combined.includes(word))) { score += 20; evidence.push('all_words'); }
120
+ if (node.source === 'ocr') { score -= 5; evidence.push('ocr'); }
121
+ if (node.patterns?.length) { score += 3; evidence.push('actionable_pattern'); }
122
+ return { node, score, hits, evidence, order };
123
+ })
124
+ .filter(Boolean)
125
+ .sort((a, b) => b.score - a.score || b.hits - a.hits || a.order - b.order);
126
+ }
127
+
69
128
  /** 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. */
70
129
  export function matchApps(apps, query) {
71
130
  const q = normalizeName(query);
@@ -98,8 +157,11 @@ function runPowerShellJson(script, signal) {
98
157
  /**
99
158
  * 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
159
  */
101
- export function createGuiController({ fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true } = {}) {
102
- let appsCache = null;
160
+ export function createGuiController({
161
+ fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null, fetchApps = (signal) => runPowerShellJson('Get-StartApps | Select-Object Name, AppID | ConvertTo-Json -Compress', signal),
162
+ } = {}) {
163
+ let appsCache = null;
164
+ let appsInflight = null;
103
165
  let lastNotifyAt = 0;
104
166
  /** Cửa sổ của từng lần observe — để kiểm ứng dụng bị chặn ở thao tác theo node_id. */
105
167
  const snapshotWindows = new Map();
@@ -117,14 +179,20 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
117
179
  return { windows: list.map((w) => ({ ...w, blocked: BLOCKED_PROCESSES.has(normalizeProcess(w.process)) || (!fullAccess && SHELL_PROCESSES.has(normalizeProcess(w.process))) || undefined })) };
118
180
  }
119
181
 
120
- const windowInfoOf = (args, ctx) => host.call('window_info', { window: args.window }, ctx);
182
+ /**
183
+ * 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ọ
184
+ * đang dùng ngay trước đó (`defaultWindow()` = `{ avoid_pid, fallback }`).
185
+ */
186
+ const target = (args) => (args.window ? { window: args.window } : { ...defaultWindow() });
187
+ const windowInfoOf = (args, ctx) => host.call('window_info', target(args), ctx);
121
188
 
122
189
  async function observe(args, ctx) {
123
190
  const res = await host.call('observe', {
124
- window: args.window,
191
+ ...target(args),
125
192
  max_nodes: Math.min(Number(args.max_nodes) || OBSERVE_MAX_NODES, 1500),
126
193
  include_image: !!args.include_image,
127
194
  image_when_poor: args.image_when_poor !== false,
195
+ ocr: typeof args.ocr === 'boolean' ? args.ocr : undefined,
128
196
  image_max_width: Number(args.image_max_width) || 1366,
129
197
  image_quality: Number(args.image_quality) || 70,
130
198
  }, ctx);
@@ -134,9 +202,104 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
134
202
  return res;
135
203
  }
136
204
 
205
+ /**
206
+ * 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
207
+ * 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 đủ
208
+ * hết từ thì lấy phần tử khớp nhiều từ nhất.
209
+ */
210
+ async function find(args, ctx) {
211
+ const words = normalizeName(args.query).split(' ').filter(Boolean);
212
+ if (!words.length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give query (words of the element to find)');
213
+ const role = String(args.role || '').toLowerCase();
214
+ const max = Math.max(1, Math.min(Number(args.max) || FIND_DEFAULT, FIND_MAX));
215
+ const res = await observe({ ...args, max_nodes: 1500 }, ctx);
216
+ const scored = rankGuiNodes(res.nodes, args.query, role);
217
+ const all = scored.filter((x) => x.hits === words.length);
218
+ const pool = all.length ? all : scored.filter((x) => x.hits === scored[0]?.hits);
219
+ const picked = pool.slice(0, max);
220
+ const margin = picked.length > 1 ? picked[0].score - picked[1].score : picked.length ? picked[0].score : 0;
221
+ 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 };
222
+ Object.defineProperty(out, '_raw_observation', { value: res, enumerable: false });
223
+ return out;
224
+ }
225
+
226
+ /**
227
+ * Compact semantic fast path. The caller states intent; candidate evidence, exclusions, ambiguity handling,
228
+ * execution and cheap post-action verification stay inside the device runtime.
229
+ */
230
+ async function semanticDo(args, ctx, env) {
231
+ const command = String(args.do || '').toLowerCase();
232
+ if (command === 'open') return openApp({ name: args.target, file: args.file }, ctx, env);
233
+ const action = {
234
+ click: GuiAction.CLICK, fill: GuiAction.SET_VALUE, select: GuiAction.SELECT, toggle: GuiAction.TOGGLE,
235
+ key: GuiAction.KEY, scroll: GuiAction.SCROLL,
236
+ }[command];
237
+ if (!action) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown semantic action: ${args.do || ''}`);
238
+
239
+ if ((command === 'key' || command === 'scroll') && !args.target) {
240
+ const result = await act({
241
+ action, window: args.within || args.window, keys: command === 'key' ? args.value : undefined,
242
+ direction: command === 'scroll' ? args.value : undefined,
243
+ }, ctx);
244
+ return { ok: true, action: command, effect: result.window_title_changed || result.focused_element || command };
245
+ }
246
+
247
+ const query = String(args.target || '').trim();
248
+ if (!query) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give target');
249
+ let found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES }, ctx);
250
+ if (!found.nodes.length && !found.ocr && found.tree_quality !== 'poor') {
251
+ found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, ocr: true }, ctx);
252
+ }
253
+ if (!found.nodes.length) throw new DeviceToolError(DeviceErrorCode.GUI_TARGET_NOT_FOUND, `No enabled visible target matched "${query}"`);
254
+ if (found.ambiguous) {
255
+ return {
256
+ ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
257
+ choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
258
+ observation: found._raw_observation,
259
+ };
260
+ }
261
+
262
+ const node = found.nodes[0];
263
+ if (command === 'fill' && node.password) {
264
+ throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'AI may not fill password or secret fields — ask the user to enter it');
265
+ }
266
+ const result = await act({
267
+ action, node_id: node.id,
268
+ text: command === 'fill' ? args.value : undefined,
269
+ option: command === 'select' ? args.value : undefined,
270
+ state: command === 'toggle' ? args.value : undefined,
271
+ }, ctx);
272
+ let verified;
273
+ if (command === 'fill' && Object.hasOwn(result.target || {}, 'value')) verified = String(result.target.value) === String(args.value ?? '');
274
+ if (command === 'select' && Object.hasOwn(result.target || {}, 'selected')) verified = result.target.selected === true;
275
+ if (command === 'toggle' && Object.hasOwn(result.target || {}, 'checked')) {
276
+ const expected = String(args.value || '').toLowerCase();
277
+ verified = expected === 'on' ? result.target.checked === 'on' : expected === 'off' ? result.target.checked === 'off' : undefined;
278
+ }
279
+ if (verified === false) {
280
+ throw new DeviceToolError(DeviceErrorCode.GUI_NO_EFFECT, `${command} ran but the target did not reach the requested state`);
281
+ }
282
+ return {
283
+ ok: true, action: command, target: node.name || node.automation_id || node.role,
284
+ ...(verified === undefined ? {} : { verified }),
285
+ effect: result.window_title_changed || result.target || result.focused_element || command,
286
+ };
287
+ }
288
+
289
+ /** 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. */
290
+ async function waitFor(args, ctx) {
291
+ const elementWait = !!(args.name || args.automation_id);
292
+ if (elementWait || args.window) assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
293
+ return host.call('wait_for', {
294
+ ...(elementWait || args.window ? target(args) : {}),
295
+ until: args.until, name: args.name, automation_id: args.automation_id, role: args.role, title_contains: args.title_contains,
296
+ timeout_ms: Math.min(Number(args.timeout_ms) || 10_000, WAIT_MAX_MS),
297
+ }, ctx);
298
+ }
299
+
137
300
  async function focus(args, ctx) {
138
301
  assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
139
- return host.call('focus', { window: args.window }, ctx);
302
+ return host.call('focus', target(args), ctx);
140
303
  }
141
304
 
142
305
  async function act(args, ctx) {
@@ -148,7 +311,7 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
148
311
  assertWindowAllowed(windowInfo, { fullAccess });
149
312
  announce(windowInfo);
150
313
  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,
314
+ action, node_id: args.node_id, ...(args.node_id ? {} : target(args)), method: args.method, text: args.text, keys: args.keys,
152
315
  option: args.option, state: args.state, direction: args.direction, amount: args.amount, point: args.point, to: args.to,
153
316
  image_scale: args.image_scale, settle_ms: args.settle_ms,
154
317
  check_user_input: true, user_input_grace_ms: Number(args.user_input_grace_ms) || 1500,
@@ -156,11 +319,15 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
156
319
  }
157
320
 
158
321
  async function listApps(signal) {
159
- if (appsCache && Date.now() - appsCache.at < APPS_CACHE_MS) return appsCache.apps;
160
- const rows = await runPowerShellJson('Get-StartApps | Select-Object Name, AppID | ConvertTo-Json -Compress', signal).catch(() => []);
161
- const apps = rows.filter((r) => r?.Name && r?.AppID).map((r) => ({ name: String(r.Name), app_id: String(r.AppID) }));
162
- appsCache = { at: Date.now(), apps };
163
- return apps;
322
+ if (appsCache && Date.now() - appsCache.at < APPS_CACHE_MS) return appsCache.apps;
323
+ if (appsInflight && !signal) return appsInflight;
324
+ const task = Promise.resolve().then(() => fetchApps(signal)).catch(() => []).then((rows) => {
325
+ const apps = (rows || []).filter((r) => r?.Name && r?.AppID).map((r) => ({ name: String(r.Name), app_id: String(r.AppID) }));
326
+ if (apps.length) appsCache = { at: Date.now(), apps };
327
+ return apps.length ? apps : (appsCache?.apps || []);
328
+ }).finally(() => { if (appsInflight === task) appsInflight = null; });
329
+ if (!signal) appsInflight = task;
330
+ return task;
164
331
  }
165
332
 
166
333
  async function waitNewWindow(before, ctx, hint) {
@@ -202,7 +369,7 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
202
369
  if (!matches.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No installed app named "${name}"`);
203
370
  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
371
  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`);
372
+ assertAppAllowed(app.name, { fullAccess });
206
373
  spawn('explorer.exe', [`shell:AppsFolder\\${app.app_id}`], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
207
374
  const win = await waitNewWindow(before, ctx, app.name);
208
375
  await sendToBack(win, before, ctx);
@@ -210,27 +377,50 @@ export function createGuiController({ fullAccess = false, host = createWindowsHo
210
377
  return { opened: app.name, window: win, hint: win ? undefined : 'App started but no new window yet — call gui.windows in a moment' };
211
378
  }
212
379
 
213
- return { windows, observe, focus, act, openApp, close: () => host.close() };
380
+ return { windows, observe, find, waitFor, focus, act, semanticDo, openApp, prewarm: () => listApps(), close: () => host.close() };
214
381
  }
215
382
 
216
383
  /** Công cụ GUI cho danh mục của Planner. */
217
384
  export function buildGuiTools(gui) {
218
385
  const target = {
219
386
  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'),
387
+ 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
388
  };
222
389
  return [
390
+ { name: 'gui.do', group: ToolGroup.GUI, handler: (a, c, e) => gui.semanticDo(a, c, e),
391
+ description: 'Fast semantic desktop action. State the intent briefly; the device finds one enabled visible target, refuses ambiguity, acts, and verifies simple value/state changes. Use precise gui.find/gui.act only after an ambiguous result.',
392
+ input_schema: schema({
393
+ do: str('click | fill | select | toggle | key | scroll | open'), target: str('short visible label or app name'),
394
+ value: str('text, option, on/off, key chord, or scroll direction'), within: str('optional window title/process'),
395
+ role: str('optional role such as button or edit'), file: str('document path for open'),
396
+ }, ['do']) },
223
397
  { name: 'gui.windows', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.windows(a, c),
224
398
  description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
225
399
  input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
226
400
  { 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') }) },
401
+ 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.',
402
+ input_schema: schema({
403
+ window: target.window, include_image: bool('attach a screenshot even when the tree is good'), max_nodes: num('default 300'),
404
+ ocr: bool('read the text on the window even when the tree is good (default: only when poor)'),
405
+ }) },
406
+ { name: 'gui.find', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.find(a, c),
407
+ 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.',
408
+ input_schema: schema({
409
+ query: str('words of the element, e.g. "Save", "Số tiền", "Customer name"'), window: target.window,
410
+ role: str('only this role, e.g. button, edit, menuitem, dataitem'), max: num('default 20, max 60'),
411
+ }, ['query']) },
412
+ { name: 'gui.wait_for', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.waitFor(a, c),
413
+ 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.',
414
+ input_schema: schema({
415
+ until: str('appears (default) | gone'), window: target.window, name: str('element name contains this text (case-insensitive)'),
416
+ automation_id: str('element AutomationId (exact)'), role: str('element role, e.g. button, menuitem, edit, window'),
417
+ title_contains: str('wait on a window title instead of an element'), timeout_ms: num('default 10000, max 60000'),
418
+ }) },
229
419
  { name: 'gui.focus', group: ToolGroup.GUI, handler: (a, c) => gui.focus(a, c),
230
420
  description: 'Bring a window to the front (restores it if minimized).',
231
421
  input_schema: schema({ window: target.window }, ['window']) },
232
422
  { 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.',
423
+ 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
424
  input_schema: schema({
235
425
  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
426
  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'),
@@ -84,14 +84,21 @@ export function createWindowsHost({ spawnImpl = spawn } = {}) {
84
84
  return starting;
85
85
  }
86
86
 
87
- /** Một lời gọi tới host. Huỷ (`signal`) giữa chừng → giết host (không có cách ngắt một lời gọi UI Automation đang chờ). */
87
+ /** Một lời gọi tới host. Huỷ (`signal`) giữa chừng: `wait_for` gửi `{ cancel: id }` để thoát vòng chờ mà không giết tiến trình host (giữ nguyên snapshot); lệnh khác treo thì giết host. */
88
88
  async function call(op, args = {}, { signal } = {}) {
89
89
  if (signal?.aborted) throw signal.reason;
90
90
  await start();
91
91
  if (signal?.aborted) throw signal.reason;
92
92
  const id = ++seq;
93
93
  return new Promise((resolve, reject) => {
94
- const onAbort = () => { waiters.delete(id); reject(signal.reason); kill(); };
94
+ const onAbort = () => {
95
+ waiters.delete(id);
96
+ reject(signal.reason);
97
+ if (op === 'wait_for' && child?.stdin?.writable) {
98
+ try { child.stdin.write(`${JSON.stringify({ cancel: String(id) })}\n`); return; } catch { /* rơi xuống kill */ }
99
+ }
100
+ kill();
101
+ };
95
102
  signal?.addEventListener('abort', onAbort, { once: true });
96
103
  waiters.set(id, {
97
104
  resolve: (v) => { signal?.removeEventListener('abort', onAbort); resolve(v); },