@aivin-labs/cli 1.0.11 → 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.
- package/README.md +16 -0
- package/bin/cli.mjs +67 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +73 -14
- package/bin/lib/remote/client.mjs +89 -8
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/constants.mjs +17 -0
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
- package/bin/lib/remote/desktop/index.mjs +44 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +295 -292
- package/bin/lib/remote/desktop/traySource.mjs +541 -527
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +757 -399
- package/bin/lib/remote/folderRules.mjs +140 -0
- package/bin/lib/remote/gui/index.mjs +126 -17
- package/bin/lib/remote/gui/windowsHost.mjs +9 -2
- package/bin/lib/remote/gui/windowsHostSource.mjs +194 -51
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +8 -2
- package/bin/lib/remote/mascot/askHostSource.mjs +18 -0
- package/bin/lib/remote/mascot/bot.mjs +29 -4
- package/bin/lib/remote/mascot/hostSource.mjs +4 -4
- package/bin/lib/remote/mascot/rigSource.mjs +12 -7
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/toolHandlers.mjs +788 -741
- package/bin/lib/remoteControl.mjs +26 -26
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1504 -1484
- 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 +71 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -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
|
+
}
|
|
@@ -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
|
|
|
@@ -89,6 +90,41 @@ export function assertAppAllowed(name, { fullAccess }) {
|
|
|
89
90
|
|
|
90
91
|
const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
91
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
|
+
|
|
92
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. */
|
|
93
129
|
export function matchApps(apps, query) {
|
|
94
130
|
const q = normalizeName(query);
|
|
@@ -122,9 +158,10 @@ function runPowerShellJson(script, signal) {
|
|
|
122
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ả).
|
|
123
159
|
*/
|
|
124
160
|
export function createGuiController({
|
|
125
|
-
fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null,
|
|
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),
|
|
126
162
|
} = {}) {
|
|
127
|
-
let appsCache = null;
|
|
163
|
+
let appsCache = null;
|
|
164
|
+
let appsInflight = null;
|
|
128
165
|
let lastNotifyAt = 0;
|
|
129
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. */
|
|
130
167
|
const snapshotWindows = new Map();
|
|
@@ -176,16 +213,77 @@ export function createGuiController({
|
|
|
176
213
|
const role = String(args.role || '').toLowerCase();
|
|
177
214
|
const max = Math.max(1, Math.min(Number(args.max) || FIND_DEFAULT, FIND_MAX));
|
|
178
215
|
const res = await observe({ ...args, max_nodes: 1500 }, ctx);
|
|
179
|
-
const scored = (res.nodes
|
|
180
|
-
.filter((n) => !role || n.role === role)
|
|
181
|
-
.map((n) => {
|
|
182
|
-
const text = normalizeName([n.name, n.automation_id, n.value, n.help].filter(Boolean).join(' '));
|
|
183
|
-
return { n, hits: words.filter((w) => text.includes(w)).length };
|
|
184
|
-
})
|
|
185
|
-
.filter((x) => x.hits > 0);
|
|
216
|
+
const scored = rankGuiNodes(res.nodes, args.query, role);
|
|
186
217
|
const all = scored.filter((x) => x.hits === words.length);
|
|
187
|
-
const
|
|
188
|
-
|
|
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
|
+
};
|
|
189
287
|
}
|
|
190
288
|
|
|
191
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. */
|
|
@@ -221,11 +319,15 @@ export function createGuiController({
|
|
|
221
319
|
}
|
|
222
320
|
|
|
223
321
|
async function listApps(signal) {
|
|
224
|
-
if (appsCache && Date.now() - appsCache.at < APPS_CACHE_MS) return appsCache.apps;
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
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;
|
|
229
331
|
}
|
|
230
332
|
|
|
231
333
|
async function waitNewWindow(before, ctx, hint) {
|
|
@@ -275,7 +377,7 @@ export function createGuiController({
|
|
|
275
377
|
return { opened: app.name, window: win, hint: win ? undefined : 'App started but no new window yet — call gui.windows in a moment' };
|
|
276
378
|
}
|
|
277
379
|
|
|
278
|
-
return { windows, observe, find, waitFor, focus, act, openApp, close: () => host.close() };
|
|
380
|
+
return { windows, observe, find, waitFor, focus, act, semanticDo, openApp, prewarm: () => listApps(), close: () => host.close() };
|
|
279
381
|
}
|
|
280
382
|
|
|
281
383
|
/** Công cụ GUI cho danh mục của Planner. */
|
|
@@ -285,6 +387,13 @@ export function buildGuiTools(gui) {
|
|
|
285
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)'),
|
|
286
388
|
};
|
|
287
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']) },
|
|
288
397
|
{ name: 'gui.windows', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.windows(a, c),
|
|
289
398
|
description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
|
|
290
399
|
input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
|
|
@@ -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
|
|
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 = () => {
|
|
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); },
|