@aivin-labs/cli 1.0.11 → 1.0.21
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.
- package/README.md +325 -288
- package/bin/cli.mjs +163 -17
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +331 -52
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { IGNORED_DIRS } from './constants.mjs';
|
|
4
|
+
import { isDocFile } from './docText.mjs';
|
|
5
|
+
import { isSecretPath } from './secretPaths.mjs';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 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
|
|
9
|
+
* 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
|
|
10
|
+
* bộ tìm tệp của hệ điều hành (osSearch.mjs).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** 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). */
|
|
14
|
+
export const FolderKind = Object.freeze({
|
|
15
|
+
/** 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). */
|
|
16
|
+
APP: 'app',
|
|
17
|
+
/** 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. */
|
|
18
|
+
BULK: 'bulk',
|
|
19
|
+
/** 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). */
|
|
20
|
+
REPO: 'repo',
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** 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. */
|
|
24
|
+
const INDEX_SKIP_DIRS = new Set([
|
|
25
|
+
'appdata', 'application data', 'local settings', '$recycle.bin', 'system volume information', 'windows', 'program files',
|
|
26
|
+
'program files (x86)', 'programdata', 'library', 'miniconda3', 'anaconda3', 'snap', 'site-packages', 'pods', 'deriveddata',
|
|
27
|
+
'__pycache__', '.turbo', '.pnpm-store', '.cargo', '.rustup', '.gradle', '.dart_tool', '.nuget',
|
|
28
|
+
'system32', 'syswow64', 'recovery', '$windows.~bt', '$windows.~ws', 'steamapps', 'package-cache', 'caches', 'cacheddata',
|
|
29
|
+
'.vs', '.bundle', 'vendor',
|
|
30
|
+
]);
|
|
31
|
+
|
|
32
|
+
const NORMALIZED_SKIP_DIRS = new Set([
|
|
33
|
+
...INDEX_SKIP_DIRS,
|
|
34
|
+
...[...IGNORED_DIRS].map((d) => d.toLowerCase()),
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
/** Tệp tạm / sao lưu / sinh ra khi biên dịch / tải dở — không ai tìm. */
|
|
38
|
+
const SKIP_FILE_EXT = new Set([
|
|
39
|
+
'.tmp', '.temp', '.old', '.bak', '.swp', '.swo', '.crdownload', '.part', '.partial', '.download', '.lock', '.pyc', '.pyo', '.class',
|
|
40
|
+
'.o', '.obj', '.pdb', '.dll', '.sys', '.cache', '.dmp', '.etl', '.blf', '.regtrans-ms', '.iso', '.vmdk', '.qcow2',
|
|
41
|
+
'.map', '.tsbuildinfo', '.suo', '.user', '.ilk', '.exp', '.lib', '.apk', '.aab', '.dylib', '.so',
|
|
42
|
+
]);
|
|
43
|
+
const SKIP_FILE_NAMES = new Set([
|
|
44
|
+
'thumbs.db', 'desktop.ini', 'ntuser.dat', 'ntuser.ini',
|
|
45
|
+
'npm-debug.log', 'yarn-error.log', 'pnpm-debug.log',
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
/** 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). */
|
|
49
|
+
export function skipDir(name, extraExcludes) {
|
|
50
|
+
if (!name || name.startsWith('.')) return true;
|
|
51
|
+
const lower = name.toLowerCase();
|
|
52
|
+
if (NORMALIZED_SKIP_DIRS.has(lower)) return true;
|
|
53
|
+
if (extraExcludes && (extraExcludes.has(name) || extraExcludes.has(lower))) return true;
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function skipFile(name, extraExcludes) {
|
|
58
|
+
if (!name) return true;
|
|
59
|
+
const lower = name.toLowerCase();
|
|
60
|
+
if (lower.startsWith('.') || lower.startsWith('~$') || lower.endsWith('~')) return true;
|
|
61
|
+
if (SKIP_FILE_NAMES.has(lower) || lower.startsWith('ntuser.dat')) return true;
|
|
62
|
+
if (SKIP_FILE_EXT.has(path.extname(lower))) return true;
|
|
63
|
+
if (lower.endsWith('.min.js') || lower.endsWith('.min.css') || lower.endsWith('.d.ts.map')) return true;
|
|
64
|
+
// Khoá riêng, kho mật khẩu…: chỉ mục giữ đoạn xem trước nội dung tệp.
|
|
65
|
+
if (isSecretPath(lower)) return true;
|
|
66
|
+
if (extraExcludes && (extraExcludes.has(name) || extraExcludes.has(lower))) return true;
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const BULK_MIN_FILES = 300;
|
|
71
|
+
/** 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). */
|
|
72
|
+
const BULK_DOC_SHARE = 0.2;
|
|
73
|
+
const APP_MIN_DLLS = 3;
|
|
74
|
+
|
|
75
|
+
/** 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. */
|
|
76
|
+
export function classifyDir(name, entries) {
|
|
77
|
+
if (/\.app$/i.test(name)) return FolderKind.APP;
|
|
78
|
+
const names = new Set(entries.map((e) => e.name.toLowerCase()));
|
|
79
|
+
if (names.has('.git')) return FolderKind.REPO;
|
|
80
|
+
if (names.has('pyvenv.cfg') || names.has('conda-meta') || names.has('local state') || (names.has('preferences') && names.has('local storage'))) {
|
|
81
|
+
return FolderKind.APP;
|
|
82
|
+
}
|
|
83
|
+
const files = entries.filter((e) => e.isFile());
|
|
84
|
+
const exe = files.some((f) => /\.exe$/i.test(f.name));
|
|
85
|
+
if (exe && files.filter((f) => /\.dll$/i.test(f.name)).length >= APP_MIN_DLLS) return FolderKind.APP;
|
|
86
|
+
if (files.length >= BULK_MIN_FILES && files.filter((f) => isDocFile(f.name)).length < files.length * BULK_DOC_SHARE) return FolderKind.BULK;
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const CATEGORIES = [
|
|
91
|
+
{ 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'] },
|
|
92
|
+
{ words: 'videos video clips recordings', ext: ['.mp4', '.mov', '.mkv', '.avi', '.webm', '.m4v', '.wmv'] },
|
|
93
|
+
{ words: 'audio music sound recordings am thanh nhac', ext: ['.mp3', '.wav', '.m4a', '.flac', '.aac', '.ogg'] },
|
|
94
|
+
{ words: 'logs log nhat ky', ext: ['.log'] },
|
|
95
|
+
{ words: 'data export du lieu', ext: ['.json', '.csv', '.xml', '.ndjson', '.parquet'] },
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
const README_RE = /^readme(\.(md|txt|rst))?$/i;
|
|
99
|
+
const README_CHARS = 300;
|
|
100
|
+
|
|
101
|
+
function readmeOf(dir, entries) {
|
|
102
|
+
const file = entries.find((e) => e.isFile() && README_RE.test(e.name));
|
|
103
|
+
if (!file) return '';
|
|
104
|
+
try {
|
|
105
|
+
const fd = fs.openSync(path.join(dir, file.name), 'r');
|
|
106
|
+
try {
|
|
107
|
+
const buf = Buffer.alloc(2048);
|
|
108
|
+
const n = fs.readSync(fd, buf, 0, buf.length, 0);
|
|
109
|
+
return buf.subarray(0, n).toString('utf8').replace(/\s+/g, ' ').trim().slice(0, README_CHARS);
|
|
110
|
+
} finally { fs.closeSync(fd); }
|
|
111
|
+
} catch {
|
|
112
|
+
return '';
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 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
|
|
118
|
+
* hình" tìm ra Pictures\Screenshots), `count` = số mục ngay bên trong.
|
|
119
|
+
*/
|
|
120
|
+
export function folderSummary(kind, dir, entries) {
|
|
121
|
+
const files = entries.filter((e) => e.isFile());
|
|
122
|
+
if (kind === FolderKind.APP) {
|
|
123
|
+
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.' };
|
|
124
|
+
}
|
|
125
|
+
if (kind === FolderKind.REPO) {
|
|
126
|
+
const readme = readmeOf(dir, entries);
|
|
127
|
+
return {
|
|
128
|
+
count: entries.length, words: `project code repository source git du an ma nguon ${readme}`,
|
|
129
|
+
note: `Code project (git) — code is not indexed (use fs.grep inside it; fs.index_folder indexes it fully).${readme ? ` README: ${readme}` : ''}`,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
const byExt = new Map();
|
|
133
|
+
for (const f of files) {
|
|
134
|
+
const ext = path.extname(f.name).toLowerCase() || '(none)';
|
|
135
|
+
byExt.set(ext, (byExt.get(ext) || 0) + 1);
|
|
136
|
+
}
|
|
137
|
+
const top = [...byExt].sort((a, b) => b[1] - a[1]);
|
|
138
|
+
const words = CATEGORIES.filter((c) => c.ext.some((e) => byExt.has(e))).map((c) => c.words).join(' ');
|
|
139
|
+
return {
|
|
140
|
+
count: files.length, words: `${words} ${top.map(([e]) => e.slice(1)).join(' ')}`,
|
|
141
|
+
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.`,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `git.*` CHỈ ĐỌC chạy an toàn trên kho lạ (02/11/2026). Cấu hình của kho (`.git/config` — agent ghi được bằng fs.write / shell, hoặc kho tải
|
|
3
|
+
* về) chạy được chương trình tuỳ ý ngay trong `git status` / `git diff` / `git log`: `core.fsmonitor`, `diff.external`, `diff.<x>.textconv`,
|
|
4
|
+
* hook `post-index-change` khi git làm mới chỉ mục… Công cụ chỉ đọc không được hỏi xác nhận nên đây là đường chạy mã lách sàn luật.
|
|
5
|
+
* - `--no-optional-locks`: status không ghi lại chỉ mục (không có hook ghi chỉ mục);
|
|
6
|
+
* - `-c core.fsmonitor=false`, `-c core.hooksPath=<thiết bị rỗng>`: không chạy fsmonitor, không tìm thấy hook nào (áp cả cho kho con);
|
|
7
|
+
* - diff / show / log thêm `--no-ext-diff --no-textconv`;
|
|
8
|
+
* - bỏ mọi biến môi trường `GIT_*` của tiến trình (GIT_EXTERNAL_DIFF, GIT_SSH_COMMAND, GIT_CONFIG_*, GIT_DIR…), tắt hỏi mật khẩu.
|
|
9
|
+
* Còn hở: `filter.<x>.clean` (kho tự khai bộ lọc qua `.gitattributes` + cấu hình) có thể chạy khi so tệp đang sửa — xem file-operations.md.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
|
|
13
|
+
const DIFF_LIKE = new Set(['diff', 'show', 'log']);
|
|
14
|
+
|
|
15
|
+
/** argv cho `git` (đã gồm `-C <cwd>`), `sub` = lệnh con và tham số của nó. */
|
|
16
|
+
export function safeGitArgv(cwd, sub, { nullDevice = NULL_DEVICE } = {}) {
|
|
17
|
+
const [cmd, ...rest] = sub;
|
|
18
|
+
const hardened = DIFF_LIKE.has(cmd) ? [cmd, '--no-ext-diff', '--no-textconv', ...rest] : [cmd, ...rest];
|
|
19
|
+
// `log.showSignature` + `gpg.program` trong `.git/config`: `git log` chạy chương trình của kho để kiểm chữ ký commit (rà 02/11/2026).
|
|
20
|
+
return ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', `core.hooksPath=${nullDevice}`, '-c', 'log.showSignature=false', '-c', `gpg.program=${nullDevice}`, '-C', cwd, ...hardened];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Môi trường cho git: bỏ mọi `GIT_*` (Windows: tên biến không phân biệt hoa thường), thêm cờ không hỏi mật khẩu / không đọc pager. */
|
|
24
|
+
export function safeGitEnv(base = process.env) {
|
|
25
|
+
const out = {};
|
|
26
|
+
for (const [key, value] of Object.entries(base || {})) {
|
|
27
|
+
if (/^git_/i.test(key)) continue;
|
|
28
|
+
out[key] = value;
|
|
29
|
+
}
|
|
30
|
+
return { ...out, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' };
|
|
31
|
+
}
|
|
@@ -46,6 +46,7 @@ const OPEN_WAIT_MS = 10_000;
|
|
|
46
46
|
const WAIT_MAX_MS = 60_000;
|
|
47
47
|
const FIND_DEFAULT = 20;
|
|
48
48
|
const FIND_MAX = 60;
|
|
49
|
+
const SEMANTIC_CHOICES = 5;
|
|
49
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). */
|
|
50
51
|
const NOTIFY_EVERY_MS = 5 * 60_000;
|
|
51
52
|
|
|
@@ -87,7 +88,64 @@ export function assertAppAllowed(name, { fullAccess }) {
|
|
|
87
88
|
}
|
|
88
89
|
}
|
|
89
90
|
|
|
90
|
-
const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
91
|
+
const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/gi, 'd').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
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 = '', { matchValue = true } = {}) {
|
|
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 = matchValue ? 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
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Nhãn nút chốt / phá huỷ (đã bỏ dấu, viết thường). Cổng duyệt trên BE xét câu mô tả, nên khi máy tự chọn phần tử có nhãn kiểu này mà câu
|
|
130
|
+
* mô tả không nói tới (vd "Lưu" khớp tiền tố "Lưu và gửi") thì không bấm thẳng — trả mơ hồ để BE phân giải + xét sàn an toàn trên đúng nút.
|
|
131
|
+
*/
|
|
132
|
+
const RISKY_LABEL_WORDS = new Set([
|
|
133
|
+
'send', 'submit', 'post', 'publish', 'delete', 'remove', 'erase', 'pay', 'purchase', 'buy', 'order', 'confirm', 'approve', 'transfer', 'logout', 'signout',
|
|
134
|
+
'gui', 'dang', 'xoa', 'go', 'huy', 'mua', 'chuyen', 'duyet',
|
|
135
|
+
]);
|
|
136
|
+
const RISKY_LABEL_PHRASES = ['sign out', 'log out', 'thanh toan', 'xac nhan', 'dang xuat', 'dat hang', 'chuyen tien', 'go bo'];
|
|
137
|
+
|
|
138
|
+
export function riskyLabelWords(label) {
|
|
139
|
+
const n = normalizeName(label);
|
|
140
|
+
const words = n.split(' ').filter((w) => RISKY_LABEL_WORDS.has(w));
|
|
141
|
+
return [...words, ...RISKY_LABEL_PHRASES.filter((p) => ` ${n} `.includes(` ${p} `))];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Phần tử đã chọn mang nhãn chốt / phá huỷ mà câu mô tả không có → không bấm thẳng. */
|
|
145
|
+
export function needsServerCheck(query, node) {
|
|
146
|
+
const asked = new Set(riskyLabelWords(query));
|
|
147
|
+
return riskyLabelWords(node?.name || node?.automation_id).some((w) => !asked.has(w));
|
|
148
|
+
}
|
|
91
149
|
|
|
92
150
|
/** 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. */
|
|
93
151
|
export function matchApps(apps, query) {
|
|
@@ -122,9 +180,10 @@ function runPowerShellJson(script, signal) {
|
|
|
122
180
|
* 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ả).
|
|
123
181
|
*/
|
|
124
182
|
export function createGuiController({
|
|
125
|
-
fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null,
|
|
183
|
+
fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null, fetchApps = (signal) => runPowerShellJson('Get-StartApps | Select-Object Name, AppID | ConvertTo-Json -Compress', signal),
|
|
126
184
|
} = {}) {
|
|
127
185
|
let appsCache = null;
|
|
186
|
+
let appsInflight = null;
|
|
128
187
|
let lastNotifyAt = 0;
|
|
129
188
|
/** Cửa sổ của từng lần observe — để kiểm ứng dụng bị chặn ở thao tác theo node_id. */
|
|
130
189
|
const snapshotWindows = new Map();
|
|
@@ -148,6 +207,14 @@ export function createGuiController({
|
|
|
148
207
|
*/
|
|
149
208
|
const target = (args) => (args.window ? { window: args.window } : { ...defaultWindow() });
|
|
150
209
|
const windowInfoOf = (args, ctx) => host.call('window_info', target(args), ctx);
|
|
210
|
+
/**
|
|
211
|
+
* Thao tác có thay đổi mà không nêu cửa sổ (02/11/2026): không lấy cửa sổ đang focus — người dùng có thể vừa chuyển sang cửa sổ khác. Chỉ
|
|
212
|
+
* cho khi hỏi từ linh vật (có cửa sổ chủ máy dùng ngay trước đó); host kiểm lại đúng lúc thao tác (linh vật có đang được focus không).
|
|
213
|
+
*/
|
|
214
|
+
const assertWindowNamed = (windowArg) => {
|
|
215
|
+
if (windowArg || defaultWindow()?.fallback) return;
|
|
216
|
+
throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Name the window for this action (window / within: a handle 0x… or a title/process from gui.windows) — input is never sent to whatever window happens to be focused');
|
|
217
|
+
};
|
|
151
218
|
|
|
152
219
|
async function observe(args, ctx) {
|
|
153
220
|
const res = await host.call('observe', {
|
|
@@ -176,16 +243,87 @@ export function createGuiController({
|
|
|
176
243
|
const role = String(args.role || '').toLowerCase();
|
|
177
244
|
const max = Math.max(1, Math.min(Number(args.max) || FIND_DEFAULT, FIND_MAX));
|
|
178
245
|
const res = await observe({ ...args, max_nodes: 1500 }, ctx);
|
|
179
|
-
|
|
180
|
-
|
|
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);
|
|
246
|
+
// 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).
|
|
247
|
+
const scored = rankGuiNodes(res.nodes, args.query, role, { matchValue: args.match_value !== false });
|
|
186
248
|
const all = scored.filter((x) => x.hits === words.length);
|
|
187
|
-
const
|
|
188
|
-
|
|
249
|
+
const pool = all.length ? all : scored.filter((x) => x.hits === scored[0]?.hits);
|
|
250
|
+
const picked = pool.slice(0, max);
|
|
251
|
+
const margin = picked.length > 1 ? picked[0].score - picked[1].score : picked.length ? picked[0].score : 0;
|
|
252
|
+
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 };
|
|
253
|
+
Object.defineProperty(out, '_raw_observation', { value: res, enumerable: false });
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Compact semantic fast path. The caller states intent; candidate evidence, exclusions, ambiguity handling,
|
|
259
|
+
* execution and cheap post-action verification stay inside the device runtime.
|
|
260
|
+
*/
|
|
261
|
+
async function semanticDo(args, ctx, env) {
|
|
262
|
+
const command = String(args.do || '').toLowerCase();
|
|
263
|
+
if (command === 'open') return openApp({ name: args.target, file: args.file }, ctx, env);
|
|
264
|
+
const action = {
|
|
265
|
+
click: GuiAction.CLICK, fill: GuiAction.SET_VALUE, select: GuiAction.SELECT, toggle: GuiAction.TOGGLE,
|
|
266
|
+
key: GuiAction.KEY, scroll: GuiAction.SCROLL,
|
|
267
|
+
}[command];
|
|
268
|
+
if (!action) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown semantic action: ${args.do || ''}`);
|
|
269
|
+
assertWindowNamed(args.within || args.window);
|
|
270
|
+
|
|
271
|
+
if ((command === 'key' || command === 'scroll') && !args.target) {
|
|
272
|
+
const result = await act({
|
|
273
|
+
action, window: args.within || args.window, keys: command === 'key' ? args.value : undefined,
|
|
274
|
+
direction: command === 'scroll' ? args.value : undefined,
|
|
275
|
+
}, ctx);
|
|
276
|
+
return { ok: true, action: command, effect: result.window_title_changed || result.focused_element || command };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const query = String(args.target || '').trim();
|
|
280
|
+
if (!query) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give target');
|
|
281
|
+
let found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false }, ctx);
|
|
282
|
+
if (!found.nodes.length && !found.ocr && found.tree_quality !== 'poor') {
|
|
283
|
+
found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false, ocr: true }, ctx);
|
|
284
|
+
}
|
|
285
|
+
if (!found.nodes.length) throw new DeviceToolError(DeviceErrorCode.GUI_TARGET_NOT_FOUND, `No enabled visible target matched "${query}"`);
|
|
286
|
+
if (found.ambiguous) {
|
|
287
|
+
return {
|
|
288
|
+
ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
|
|
289
|
+
choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
|
|
290
|
+
observation: found._raw_observation,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const node = found.nodes[0];
|
|
295
|
+
if (command !== 'fill' && needsServerCheck(query, node)) {
|
|
296
|
+
return {
|
|
297
|
+
ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
|
|
298
|
+
choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
|
|
299
|
+
observation: found._raw_observation,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
if (command === 'fill' && node.password) {
|
|
303
|
+
throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'AI may not fill password or secret fields — ask the user to enter it');
|
|
304
|
+
}
|
|
305
|
+
const result = await act({
|
|
306
|
+
action, node_id: node.id,
|
|
307
|
+
text: command === 'fill' ? args.value : undefined,
|
|
308
|
+
option: command === 'select' ? args.value : undefined,
|
|
309
|
+
state: command === 'toggle' ? args.value : undefined,
|
|
310
|
+
}, ctx);
|
|
311
|
+
let verified;
|
|
312
|
+
if (command === 'fill' && Object.hasOwn(result.target || {}, 'value')) verified = String(result.target.value) === String(args.value ?? '');
|
|
313
|
+
if (command === 'select' && Object.hasOwn(result.target || {}, 'selected')) verified = result.target.selected === true;
|
|
314
|
+
if (command === 'toggle' && Object.hasOwn(result.target || {}, 'checked')) {
|
|
315
|
+
const expected = String(args.value || '').toLowerCase();
|
|
316
|
+
verified = expected === 'on' ? result.target.checked === 'on' : expected === 'off' ? result.target.checked === 'off' : undefined;
|
|
317
|
+
}
|
|
318
|
+
if (verified === false) {
|
|
319
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_NO_EFFECT, `${command} ran but the target did not reach the requested state`);
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
ok: true, action: command, target: node.name || node.automation_id || node.role,
|
|
323
|
+
...(verified === undefined ? {} : { verified }),
|
|
324
|
+
...(result.screen_point ? { screen_point: result.screen_point } : {}),
|
|
325
|
+
effect: result.window_title_changed || result.target || result.focused_element || command,
|
|
326
|
+
};
|
|
189
327
|
}
|
|
190
328
|
|
|
191
329
|
/** 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. */
|
|
@@ -208,6 +346,8 @@ export function createGuiController({
|
|
|
208
346
|
const action = String(args.action || GuiAction.CLICK);
|
|
209
347
|
if (!Object.values(GuiAction).includes(action)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown action: ${action}`);
|
|
210
348
|
const snap = args.node_id ? String(args.node_id).split('.')[0] : null;
|
|
349
|
+
// node_id đã chỉ đúng phần tử của một lần observe (kèm cửa sổ của nó) — chỉ thao tác không node_id mới phải nêu cửa sổ.
|
|
350
|
+
if (!snap) assertWindowNamed(args.window);
|
|
211
351
|
const windowInfo = snap ? snapshotWindows.get(snap) : await windowInfoOf(args, ctx);
|
|
212
352
|
if (snap && !windowInfo) throw new DeviceToolError(DeviceErrorCode.GUI_STALE_NODE, `Node ${args.node_id} is from an old observation — observe again`);
|
|
213
353
|
assertWindowAllowed(windowInfo, { fullAccess });
|
|
@@ -222,10 +362,14 @@ export function createGuiController({
|
|
|
222
362
|
|
|
223
363
|
async function listApps(signal) {
|
|
224
364
|
if (appsCache && Date.now() - appsCache.at < APPS_CACHE_MS) return appsCache.apps;
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
365
|
+
if (appsInflight && !signal) return appsInflight;
|
|
366
|
+
const task = Promise.resolve().then(() => fetchApps(signal)).catch(() => []).then((rows) => {
|
|
367
|
+
const apps = (rows || []).filter((r) => r?.Name && r?.AppID).map((r) => ({ name: String(r.Name), app_id: String(r.AppID) }));
|
|
368
|
+
if (apps.length) appsCache = { at: Date.now(), apps };
|
|
369
|
+
return apps.length ? apps : (appsCache?.apps || []);
|
|
370
|
+
}).finally(() => { if (appsInflight === task) appsInflight = null; });
|
|
371
|
+
if (!signal) appsInflight = task;
|
|
372
|
+
return task;
|
|
229
373
|
}
|
|
230
374
|
|
|
231
375
|
async function waitNewWindow(before, ctx, hint) {
|
|
@@ -275,21 +419,28 @@ export function createGuiController({
|
|
|
275
419
|
return { opened: app.name, window: win, hint: win ? undefined : 'App started but no new window yet — call gui.windows in a moment' };
|
|
276
420
|
}
|
|
277
421
|
|
|
278
|
-
return { windows, observe, find, waitFor, focus, act, openApp, close: () => host.close() };
|
|
422
|
+
return { windows, observe, find, waitFor, focus, act, semanticDo, openApp, prewarm: () => listApps(), close: () => host.close() };
|
|
279
423
|
}
|
|
280
424
|
|
|
281
425
|
/** Công cụ GUI cho danh mục của Planner. */
|
|
282
426
|
export function buildGuiTools(gui) {
|
|
283
427
|
const target = {
|
|
284
428
|
node_id: str('target element id from the latest gui.observe (preferred)'),
|
|
285
|
-
window: str('window handle (0x…) or a title/process to match;
|
|
429
|
+
window: str('window handle (0x…) or a title/process to match; reading defaults to the focused window, but an action without node_id must name it (asked from the mascot: the window the person was using)'),
|
|
286
430
|
};
|
|
287
431
|
return [
|
|
432
|
+
{ name: 'gui.do', group: ToolGroup.GUI, handler: (a, c, e) => gui.semanticDo(a, c, e),
|
|
433
|
+
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.',
|
|
434
|
+
input_schema: schema({
|
|
435
|
+
do: str('click | fill | select | toggle | key | scroll | open'), target: str('short visible label or app name'),
|
|
436
|
+
value: str('text, option, on/off, key chord, or scroll direction'), within: str('window title/process to act in (required, except when asked from the mascot)'),
|
|
437
|
+
role: str('optional role such as button or edit'), file: str('document path for open'),
|
|
438
|
+
}, ['do']) },
|
|
288
439
|
{ name: 'gui.windows', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.windows(a, c),
|
|
289
440
|
description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
|
|
290
441
|
input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
|
|
291
442
|
{ name: 'gui.observe', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.observe(a, c),
|
|
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.',
|
|
443
|
+
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).',
|
|
293
444
|
input_schema: schema({
|
|
294
445
|
window: target.window, include_image: bool('attach a screenshot even when the tree is good'), max_nodes: num('default 300'),
|
|
295
446
|
ocr: bool('read the text on the window even when the tree is good (default: only when poor)'),
|
|
@@ -311,7 +462,7 @@ export function buildGuiTools(gui) {
|
|
|
311
462
|
description: 'Bring a window to the front (restores it if minimized).',
|
|
312
463
|
input_schema: schema({ window: target.window }, ['window']) },
|
|
313
464
|
{ name: 'gui.act', group: ToolGroup.GUI, handler: (a, c) => gui.act(a, c),
|
|
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.',
|
|
465
|
+
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.',
|
|
315
466
|
input_schema: schema({
|
|
316
467
|
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'),
|
|
317
468
|
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'),
|