@aivin-labs/cli 1.0.4 → 1.0.8
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 +263 -216
- package/bin/cli.mjs +1780 -1361
- package/bin/lib/browserAutomation.mjs +655 -648
- package/bin/lib/browserTui.mjs +276 -245
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/codegen.mjs +61 -5
- package/bin/lib/connectors.mjs +55 -21
- package/bin/lib/deploy.mjs +25 -2
- package/bin/lib/mcpProxy.mjs +869 -773
- package/bin/lib/mission.mjs +13 -1
- package/bin/lib/missionStream.mjs +696 -660
- package/bin/lib/pluginAuthResolve.mjs +127 -0
- package/bin/lib/pluginTrigger.mjs +207 -90
- package/bin/lib/releaseKeys.mjs +9 -0
- package/bin/lib/remote/activityLog.mjs +68 -0
- package/bin/lib/remote/autoStart.mjs +457 -0
- package/bin/lib/remote/autoUpdate.mjs +129 -0
- package/bin/lib/remote/brand.mjs +60 -0
- package/bin/lib/remote/browserTunnel.mjs +292 -0
- package/bin/lib/remote/callLedger.mjs +134 -0
- package/bin/lib/remote/cdpPolicy.mjs +66 -0
- package/bin/lib/remote/client.mjs +726 -0
- package/bin/lib/remote/constants.mjs +173 -0
- package/bin/lib/remote/credentials.mjs +208 -0
- package/bin/lib/remote/daemonLock.mjs +86 -0
- package/bin/lib/remote/dailyBrowser.mjs +371 -0
- package/bin/lib/remote/deviceMemory.mjs +246 -0
- package/bin/lib/remote/deviceProfile.mjs +142 -0
- package/bin/lib/remote/deviceWatches.mjs +138 -0
- package/bin/lib/remote/docText.mjs +117 -0
- package/bin/lib/remote/fileIndexer.mjs +399 -0
- package/bin/lib/remote/gui/index.mjs +245 -0
- package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
- package/bin/lib/remote/gui/windowsHost.mjs +109 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
- package/bin/lib/remote/httpTransfer.mjs +89 -0
- package/bin/lib/remote/idempotency.mjs +135 -0
- package/bin/lib/remote/keepAwake.mjs +100 -0
- package/bin/lib/remote/localConfirm.mjs +268 -0
- package/bin/lib/remote/localPolicy.mjs +249 -0
- package/bin/lib/remote/mascot/assets.mjs +218 -0
- package/bin/lib/remote/mascot/hostSource.mjs +362 -0
- package/bin/lib/remote/mascot/index.mjs +322 -0
- package/bin/lib/remote/mascot/labels.mjs +83 -0
- package/bin/lib/remote/mascot/strings.mjs +189 -0
- package/bin/lib/remote/memberFsPool.mjs +134 -0
- package/bin/lib/remote/memberFsWorker.mjs +60 -0
- package/bin/lib/remote/mission.mjs +156 -0
- package/bin/lib/remote/missionQuestion.mjs +63 -0
- package/bin/lib/remote/multiUser.mjs +344 -0
- package/bin/lib/remote/netProxy.mjs +145 -0
- package/bin/lib/remote/notify.mjs +58 -0
- package/bin/lib/remote/office/index.mjs +90 -0
- package/bin/lib/remote/policyCommand.mjs +93 -0
- package/bin/lib/remote/processes.mjs +217 -0
- package/bin/lib/remote/sandbox.mjs +221 -0
- package/bin/lib/remote/schedule.mjs +213 -0
- package/bin/lib/remote/scheduler.mjs +124 -0
- package/bin/lib/remote/textIndex.mjs +131 -0
- package/bin/lib/remote/tokenStore.mjs +77 -0
- package/bin/lib/remote/toolHandlers.mjs +726 -0
- package/bin/lib/remote/undoStore.mjs +242 -0
- package/bin/lib/remoteControl.mjs +26 -0
- package/bin/lib/scaffold.mjs +654 -653
- package/bin/lib/selfUpdate.mjs +71 -0
- package/bin/lib/store.mjs +16 -2
- package/bin/lib/tasks.mjs +52 -8
- package/bin/lib/update/binarySwap.mjs +63 -0
- package/bin/lib/update/constants.mjs +56 -0
- package/bin/lib/update/download.mjs +145 -0
- package/bin/lib/update/signature.mjs +42 -0
- package/bin/lib/update/state.mjs +205 -0
- package/bin/lib/update/versions.mjs +60 -0
- package/bin/lib/util.mjs +8 -0
- package/docs/CLI.md +1353 -1274
- package/package.json +71 -62
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import zlib from 'zlib';
|
|
5
|
+
import { IGNORED_DIRS, REMOTE_CONFIG_DIR } from './constants.mjs';
|
|
6
|
+
import { extractDocText, isDocFile, wellFormed } from './docText.mjs';
|
|
7
|
+
import { isProtectedPath } from './sandbox.mjs';
|
|
8
|
+
import { createTextIndex, decodeInt8, int8Cosine } from './textIndex.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Chỉ mục tệp trong RAM cho các thư mục được phép: tên/đường dẫn + định danh đầu tệp (hàm, lớp, khoá…) → tìm tức thì theo tên lẫn nội
|
|
12
|
+
* dung chính mà không quét đĩa mỗi lần. Khởi động: nạp bản chụp gzip, quét lại TĂNG DẦN (chỉ đọc tệp có mtime/size đổi). Chạy: theo
|
|
13
|
+
* dõi thư mục (`fs.watch` đệ quy), cập nhật đúng tệp đổi.
|
|
14
|
+
*
|
|
15
|
+
* Tệp dạng tài liệu (docx/xlsx/pptx/pdf/txt…) có thêm đoạn chữ đầu (`preview`, đọc cả trong gói Office) và vector bge-m3 do BE tính
|
|
16
|
+
* (`vectorize`, chạy nền): tìm kết hợp từ khoá BM25 + ngữ nghĩa (cosine) gộp bằng RRF — "hợp đồng thuê văn phòng" ra
|
|
17
|
+
* `HD_thue_VP_2026.pdf`. Thư mục người dùng (Desktop, Documents, Downloads, OneDrive…) quét trước để trần số tệp không cắt mất chúng.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const SNAPSHOT_FILE = path.join(REMOTE_CONFIG_DIR, 'file-index.json.gz');
|
|
21
|
+
const VECTORS_FILE = path.join(REMOTE_CONFIG_DIR, 'file-vectors.json.gz');
|
|
22
|
+
const SNAPSHOT_VERSION = 3;
|
|
23
|
+
const MAX_FILES = 200_000;
|
|
24
|
+
const HEAD_BYTES = 16 * 1024;
|
|
25
|
+
const MAX_HEAD_FILE_BYTES = 2 * 1024 * 1024;
|
|
26
|
+
const MAX_IDENTIFIERS = 200;
|
|
27
|
+
const STAT_CONCURRENCY = 64;
|
|
28
|
+
const WATCH_DEBOUNCE_MS = 800;
|
|
29
|
+
const SNAPSHOT_DEBOUNCE_MS = 10_000;
|
|
30
|
+
/** Số tệp tài liệu tối đa có vector (mỗi vector ~1,4 KB). */
|
|
31
|
+
const MAX_VECTOR_FILES = Number(process.env.AIVIN_REMOTE_MAX_VECTOR_FILES) || 20_000;
|
|
32
|
+
const EMBED_BATCH = 32;
|
|
33
|
+
const BACKOFF_BASE_MS = 30_000;
|
|
34
|
+
const BACKOFF_MAX_MS = 30 * 60_000;
|
|
35
|
+
const RANK_DEPTH = 50;
|
|
36
|
+
/** Hằng số k của Reciprocal Rank Fusion. */
|
|
37
|
+
const RRF_K = 60;
|
|
38
|
+
const TEXT_EXTENSIONS = new Set([
|
|
39
|
+
'.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', '.md', '.txt', '.yaml', '.yml', '.toml', '.ini', '.env', '.py', '.go', '.rs',
|
|
40
|
+
'.java', '.kt', '.cs', '.cpp', '.cc', '.c', '.h', '.hpp', '.php', '.rb', '.swift', '.scala', '.sql', '.sh', '.ps1', '.bat', '.cmd',
|
|
41
|
+
'.html', '.css', '.scss', '.vue', '.svelte', '.xml', '.gradle', '.proto', '.graphql', '.dart', '.lua', '.r', '.csv',
|
|
42
|
+
]);
|
|
43
|
+
/** Chỉ bỏ khi LẬP CHỈ MỤC (fs.list / fs.grep vẫn vào được): dữ liệu ứng dụng, hệ điều hành, thùng rác, kho gói — hàng trăm nghìn tệp vô ích. */
|
|
44
|
+
const INDEX_SKIP_DIRS = new Set([
|
|
45
|
+
'AppData', 'Application Data', 'Local Settings', '$Recycle.Bin', 'System Volume Information', 'Windows', 'Program Files',
|
|
46
|
+
'Program Files (x86)', 'ProgramData', 'Library', '.Trash', '.npm', '.yarn', '.pnpm-store', '.nuget', '.m2', '.cargo', '.rustup',
|
|
47
|
+
'.vscode', '.cursor', '.docker', 'miniconda3', 'anaconda3', 'snap',
|
|
48
|
+
]);
|
|
49
|
+
/** Thư mục người dùng quét trước (ngay dưới gốc) — tài liệu thật thường nằm ở đây. */
|
|
50
|
+
const PRIORITY_DIRS = ['Desktop', 'Documents', 'Downloads', 'OneDrive', 'Pictures', 'Dropbox', 'Google Drive'];
|
|
51
|
+
/** Bộ theo dõi thư mục hỏng (gốc bị xoá, rút ổ ngoài, Linux hết inotify) → quét lại tăng dần theo nhịp này thay vì để chỉ mục cũ mãi. */
|
|
52
|
+
const RESCAN_MS = 10 * 60_000;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Tệp nhìn như chứa bí mật (tên hoặc đoạn đầu): không giữ đoạn chữ / định danh trong chỉ mục, không gửi đi tính vector, không đưa vào gợi
|
|
56
|
+
* ý của Planner — "mat-khau.txt" tên bình thường mà nội dung là mật khẩu (rà 28/10/2026). Vẫn tìm được theo TÊN tệp.
|
|
57
|
+
*/
|
|
58
|
+
const SECRET_NAME_RE = /(passw|mat[-_ ]?khau|mật[-_ ]?khẩu|secret|credential|(^|[^a-z])tokens?([^a-z]|$)|private[-_ ]?key|recovery[-_ ]?code|seed[-_ ]?phrase|(^|[^a-z0-9])(2fa|otp)([^a-z]|$)|\.env$|id_(rsa|ed25519|ecdsa|dsa)|\.(pem|key|p12|pfx|kdbx|ovpn)$)/i;
|
|
59
|
+
const SECRET_TEXT_RE = /(-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(password|passwd|pwd|mật khẩu|mat khau|api[_-]?key|secret|token)\s*[:=]\s*\S{4,}|\bAKIA[0-9A-Z]{16}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bsk-[A-Za-z0-9_-]{20,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,})/i;
|
|
60
|
+
|
|
61
|
+
export function looksSecret(abs, text = '') {
|
|
62
|
+
return SECRET_NAME_RE.test(path.basename(abs)) || (!!text && SECRET_TEXT_RE.test(text));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const skipDir = (name) => IGNORED_DIRS.has(name) || INDEX_SKIP_DIRS.has(name);
|
|
66
|
+
|
|
67
|
+
function identifiersOf(text) {
|
|
68
|
+
const seen = new Set();
|
|
69
|
+
for (const m of text.matchAll(/[\p{L}_][\p{L}\p{N}_]{2,}/gu)) {
|
|
70
|
+
seen.add(m[0]);
|
|
71
|
+
if (seen.size >= MAX_IDENTIFIERS) break;
|
|
72
|
+
}
|
|
73
|
+
return [...seen].join(' ');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function headTokens(abs, size) {
|
|
77
|
+
if (!TEXT_EXTENSIONS.has(path.extname(abs).toLowerCase()) || size > MAX_HEAD_FILE_BYTES) return '';
|
|
78
|
+
let handle;
|
|
79
|
+
try {
|
|
80
|
+
handle = await fs.promises.open(abs, 'r');
|
|
81
|
+
const buf = Buffer.alloc(Math.min(HEAD_BYTES, size));
|
|
82
|
+
const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
|
|
83
|
+
return identifiersOf(buf.subarray(0, bytesRead).toString('utf8'));
|
|
84
|
+
} catch {
|
|
85
|
+
return '';
|
|
86
|
+
} finally {
|
|
87
|
+
await handle?.close().catch(() => undefined);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function mapLimit(items, limit, fn) {
|
|
92
|
+
let cursor = 0;
|
|
93
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
94
|
+
while (cursor < items.length) {
|
|
95
|
+
const i = cursor++;
|
|
96
|
+
await fn(items[i], i);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
await Promise.all(workers);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Duyệt cây (bỏ thư mục rác / hệ thống, không theo symlink ra ngoài) → danh sách đường tuyệt đối của tệp. */
|
|
103
|
+
async function walk(root, limit, skip = new Set()) {
|
|
104
|
+
const files = [];
|
|
105
|
+
const queue = [root];
|
|
106
|
+
while (queue.length && files.length < limit) {
|
|
107
|
+
const batch = queue.splice(0, STAT_CONCURRENCY);
|
|
108
|
+
await mapLimit(batch, STAT_CONCURRENCY, async (dir) => {
|
|
109
|
+
let entries;
|
|
110
|
+
try { entries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { return; }
|
|
111
|
+
for (const entry of entries) {
|
|
112
|
+
if (entry.isSymbolicLink()) continue;
|
|
113
|
+
const full = path.join(dir, entry.name);
|
|
114
|
+
if (isProtectedPath(full) || skip.has(full)) continue;
|
|
115
|
+
if (entry.isDirectory()) { if (!skipDir(entry.name)) queue.push(full); } else if (entry.isFile()) files.push(full);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return files.slice(0, limit);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Thư mục ưu tiên có thật ngay dưới các gốc (kể cả `OneDrive - Công ty`). */
|
|
123
|
+
function priorityDirsOf(roots) {
|
|
124
|
+
const out = [];
|
|
125
|
+
for (const root of roots) {
|
|
126
|
+
let names = [];
|
|
127
|
+
try { names = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name); } catch { continue; }
|
|
128
|
+
for (const want of PRIORITY_DIRS) {
|
|
129
|
+
for (const name of names) if (name === want || name.startsWith(`${want} -`)) out.push(path.join(root, name));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const vectorKey = (entry) => `${entry.mtime}:${entry.size}`;
|
|
136
|
+
|
|
137
|
+
export function createFileIndex(roots) {
|
|
138
|
+
const resolvedRoots = roots.map((r) => path.resolve(r));
|
|
139
|
+
const entries = new Map(); // abs → { mtime, size, tokens, preview? }
|
|
140
|
+
const vectors = new Map(); // abs → { key, b64, vec: Int8Array }
|
|
141
|
+
const index = createTextIndex();
|
|
142
|
+
const watchers = [];
|
|
143
|
+
let rescanTimer = null;
|
|
144
|
+
let snapshotTimer;
|
|
145
|
+
let vectorTimer;
|
|
146
|
+
let lastBuild = null;
|
|
147
|
+
let priorityDirs = [];
|
|
148
|
+
let embedder = null;
|
|
149
|
+
let vectorizing = false;
|
|
150
|
+
let failures = 0;
|
|
151
|
+
let pausedUntil = 0;
|
|
152
|
+
|
|
153
|
+
const docText = (abs, entry) => `${abs.split(path.sep).slice(-6).join(' ')} ${entry.tokens || ''} ${entry.preview || ''}`;
|
|
154
|
+
const isPriority = (abs) => priorityDirs.some((d) => abs.startsWith(d + path.sep));
|
|
155
|
+
|
|
156
|
+
function setEntry(abs, entry) {
|
|
157
|
+
entries.set(abs, entry);
|
|
158
|
+
index.add(abs, docText(abs, entry));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function dropEntry(abs) {
|
|
162
|
+
entries.delete(abs);
|
|
163
|
+
vectors.delete(abs);
|
|
164
|
+
index.remove(abs);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function loadSnapshot() {
|
|
168
|
+
try {
|
|
169
|
+
const data = JSON.parse(zlib.gunzipSync(fs.readFileSync(SNAPSHOT_FILE)).toString('utf8'));
|
|
170
|
+
if (data?.version !== SNAPSHOT_VERSION || JSON.stringify(data.roots) !== JSON.stringify(resolvedRoots)) return 0;
|
|
171
|
+
for (const [abs, mtime, size, tokens, preview] of data.entries || []) setEntry(abs, { mtime, size, tokens, ...(preview ? { preview } : {}) });
|
|
172
|
+
loadVectors();
|
|
173
|
+
return entries.size;
|
|
174
|
+
} catch {
|
|
175
|
+
return 0;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function loadVectors() {
|
|
180
|
+
try {
|
|
181
|
+
const data = JSON.parse(zlib.gunzipSync(fs.readFileSync(VECTORS_FILE)).toString('utf8'));
|
|
182
|
+
for (const [abs, key, b64] of data.vectors || []) {
|
|
183
|
+
const entry = entries.get(abs);
|
|
184
|
+
if (entry && vectorKey(entry) === key) vectors.set(abs, { key, b64, vec: decodeInt8(b64) });
|
|
185
|
+
}
|
|
186
|
+
} catch { /* chưa có vector — tính dần */ }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function atomicGzip(file, payload) {
|
|
190
|
+
fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
|
|
191
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
192
|
+
fs.writeFileSync(tmp, zlib.gzipSync(JSON.stringify(payload)));
|
|
193
|
+
fs.renameSync(tmp, file);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function saveSnapshot() {
|
|
197
|
+
try {
|
|
198
|
+
atomicGzip(SNAPSHOT_FILE, {
|
|
199
|
+
version: SNAPSHOT_VERSION, roots: resolvedRoots,
|
|
200
|
+
entries: [...entries.entries()].map(([abs, e]) => (e.preview ? [abs, e.mtime, e.size, e.tokens, e.preview] : [abs, e.mtime, e.size, e.tokens])),
|
|
201
|
+
});
|
|
202
|
+
atomicGzip(VECTORS_FILE, { vectors: [...vectors.entries()].map(([abs, v]) => [abs, v.key, v.b64]) });
|
|
203
|
+
} catch { /* bản chụp chỉ để khởi động nhanh — hỏng thì lần sau quét lại */ }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function scheduleSnapshot() {
|
|
207
|
+
clearTimeout(snapshotTimer);
|
|
208
|
+
snapshotTimer = setTimeout(saveSnapshot, SNAPSHOT_DEBOUNCE_MS);
|
|
209
|
+
snapshotTimer.unref?.();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function refreshFile(abs) {
|
|
213
|
+
let stat;
|
|
214
|
+
try { stat = await fs.promises.stat(abs); } catch { if (entries.has(abs)) dropEntry(abs); return 'removed'; }
|
|
215
|
+
if (!stat.isFile()) return 'skipped';
|
|
216
|
+
const mtime = Math.floor(stat.mtimeMs);
|
|
217
|
+
const prev = entries.get(abs);
|
|
218
|
+
if (prev && prev.mtime === mtime && prev.size === stat.size) return 'same';
|
|
219
|
+
const preview = isDocFile(abs) ? await extractDocText(abs, stat.size) : '';
|
|
220
|
+
const tokens = await headTokens(abs, stat.size);
|
|
221
|
+
// Tệp như chứa bí mật: chỉ giữ tên (tìm theo tên vẫn được), bỏ đoạn chữ + định danh.
|
|
222
|
+
if (looksSecret(abs, `${preview}\n${tokens}`)) setEntry(abs, { mtime, size: stat.size, tokens: '', secret: true });
|
|
223
|
+
else setEntry(abs, { mtime, size: stat.size, tokens, ...(preview ? { preview } : {}) });
|
|
224
|
+
vectors.delete(abs);
|
|
225
|
+
return 'updated';
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Quét tăng dần: thư mục người dùng trước, rồi phần còn lại của các gốc. Tệp mới / đổi được đọc lại, tệp mất bị bỏ. */
|
|
229
|
+
async function build() {
|
|
230
|
+
const startedAt = Date.now();
|
|
231
|
+
const fromSnapshot = entries.size ? 0 : loadSnapshot();
|
|
232
|
+
priorityDirs = priorityDirsOf(resolvedRoots);
|
|
233
|
+
const found = new Set();
|
|
234
|
+
let updated = 0;
|
|
235
|
+
for (const dir of [...priorityDirs, ...resolvedRoots]) {
|
|
236
|
+
if (found.size >= MAX_FILES) break;
|
|
237
|
+
const skip = resolvedRoots.includes(dir) ? new Set(priorityDirs) : new Set();
|
|
238
|
+
const files = (await walk(dir, MAX_FILES - found.size, skip)).filter((f) => !found.has(f));
|
|
239
|
+
files.forEach((f) => found.add(f));
|
|
240
|
+
await mapLimit(files, STAT_CONCURRENCY, async (abs) => { if ((await refreshFile(abs)) === 'updated') updated++; });
|
|
241
|
+
}
|
|
242
|
+
let removed = 0;
|
|
243
|
+
for (const abs of [...entries.keys()]) if (!found.has(abs)) { dropEntry(abs); removed++; }
|
|
244
|
+
saveSnapshot();
|
|
245
|
+
lastBuild = { files: entries.size, updated, removed, from_snapshot: fromSnapshot, capped: found.size >= MAX_FILES, ms: Date.now() - startedAt, at: new Date().toISOString() };
|
|
246
|
+
scheduleVectorize(0);
|
|
247
|
+
return lastBuild;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function watch() {
|
|
251
|
+
const pending = new Set();
|
|
252
|
+
let timer;
|
|
253
|
+
const flush = async () => {
|
|
254
|
+
const batch = [...pending];
|
|
255
|
+
pending.clear();
|
|
256
|
+
await mapLimit(batch, STAT_CONCURRENCY, refreshFile);
|
|
257
|
+
scheduleSnapshot();
|
|
258
|
+
scheduleVectorize(5_000);
|
|
259
|
+
};
|
|
260
|
+
const fallBackToRescan = () => {
|
|
261
|
+
// Bộ theo dõi hỏng: đóng, chuyển sang quét lại định kỳ (tăng dần — chỉ đọc tệp có mtime / size đổi).
|
|
262
|
+
if (rescanTimer) return;
|
|
263
|
+
rescanTimer = setInterval(() => void build().catch(() => undefined), RESCAN_MS);
|
|
264
|
+
rescanTimer.unref?.();
|
|
265
|
+
};
|
|
266
|
+
for (const root of resolvedRoots) {
|
|
267
|
+
try {
|
|
268
|
+
const w = fs.watch(root, { recursive: true }, (_event, name) => {
|
|
269
|
+
if (!name) return;
|
|
270
|
+
const rel = String(name);
|
|
271
|
+
if (rel.split(/[\\/]/).some((seg) => skipDir(seg))) return;
|
|
272
|
+
if (isProtectedPath(path.join(root, rel))) return;
|
|
273
|
+
pending.add(path.join(root, rel));
|
|
274
|
+
clearTimeout(timer);
|
|
275
|
+
timer = setTimeout(() => void flush(), WATCH_DEBOUNCE_MS);
|
|
276
|
+
});
|
|
277
|
+
// Không có listener 'error' thì lỗi của bộ theo dõi (gốc bị xoá, rút ổ ngoài, hết inotify) ném ra ngoài và làm sập daemon.
|
|
278
|
+
w.on('error', () => {
|
|
279
|
+
try { w.close(); } catch { /* đã đóng */ }
|
|
280
|
+
fallBackToRescan();
|
|
281
|
+
});
|
|
282
|
+
w.unref?.();
|
|
283
|
+
watchers.push(w);
|
|
284
|
+
} catch { fallBackToRescan(); /* không theo dõi được (hệ thống tệp mạng…) */ }
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Đoạn mô tả đưa đi tính vector: tên + thư mục gần nhất + chữ đầu tệp. */
|
|
289
|
+
const embedText = (abs, entry) => `${path.basename(abs)} | ${path.dirname(abs).split(path.sep).slice(-3).join(' / ')}${entry.preview ? ` | ${entry.preview}` : ''}`;
|
|
290
|
+
|
|
291
|
+
/** Tệp tài liệu cần (tính lại) vector: thư mục người dùng trước, mới sửa trước; giữ trong trần MAX_VECTOR_FILES. */
|
|
292
|
+
function vectorQueue() {
|
|
293
|
+
const docs = [...entries.entries()].filter(([abs, e]) => isDocFile(abs) && !e.secret)
|
|
294
|
+
.sort(([a, ea], [b, eb]) => (Number(isPriority(b)) - Number(isPriority(a))) || (eb.mtime - ea.mtime))
|
|
295
|
+
.slice(0, MAX_VECTOR_FILES);
|
|
296
|
+
const keep = new Set(docs.map(([abs]) => abs));
|
|
297
|
+
for (const abs of [...vectors.keys()]) if (!keep.has(abs)) vectors.delete(abs);
|
|
298
|
+
return docs.filter(([abs, e]) => vectors.get(abs)?.key !== vectorKey(e));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Tính vector nền theo lô (`embed(texts) → base64[]`, BE tính bằng bge-m3). BE cũ / lỗi → dừng, lần sau thử lại; tìm theo từ khoá vẫn
|
|
303
|
+
* chạy bình thường.
|
|
304
|
+
*/
|
|
305
|
+
async function vectorize() {
|
|
306
|
+
if (!embedder || vectorizing || Date.now() < pausedUntil) return { embedded: 0, total: vectors.size };
|
|
307
|
+
vectorizing = true;
|
|
308
|
+
let embedded = 0;
|
|
309
|
+
let failed = false;
|
|
310
|
+
try {
|
|
311
|
+
const queue = vectorQueue();
|
|
312
|
+
for (let i = 0; i < queue.length; i += EMBED_BATCH) {
|
|
313
|
+
const batch = queue.slice(i, i + EMBED_BATCH);
|
|
314
|
+
const out = await embedder(batch.map(([abs, e]) => wellFormed(embedText(abs, e))));
|
|
315
|
+
if (!Array.isArray(out) || out.length !== batch.length) { failed = true; break; }
|
|
316
|
+
batch.forEach(([abs, e], j) => { if (out[j]) vectors.set(abs, { key: vectorKey(e), b64: out[j], vec: decodeInt8(out[j]) }); });
|
|
317
|
+
embedded += batch.length;
|
|
318
|
+
failures = 0;
|
|
319
|
+
if (embedded % 512 === 0) scheduleSnapshot();
|
|
320
|
+
}
|
|
321
|
+
} catch { failed = true; } finally {
|
|
322
|
+
vectorizing = false;
|
|
323
|
+
}
|
|
324
|
+
if (embedded) scheduleSnapshot();
|
|
325
|
+
// BE bận / lỗi → nghỉ giãn dần (30 s → tối đa 30 phút) thay vì thử lại mỗi lần tệp đổi — không dồn tải lên dịch vụ vector dùng chung.
|
|
326
|
+
if (failed) {
|
|
327
|
+
failures++;
|
|
328
|
+
const pauseMs = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (failures - 1));
|
|
329
|
+
pausedUntil = Date.now() + pauseMs;
|
|
330
|
+
scheduleVectorize(pauseMs + 1_000);
|
|
331
|
+
}
|
|
332
|
+
return { embedded, total: vectors.size, failed: failed || undefined };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function scheduleVectorize(delayMs) {
|
|
336
|
+
if (!embedder) return;
|
|
337
|
+
clearTimeout(vectorTimer);
|
|
338
|
+
vectorTimer = setTimeout(() => void vectorize(), delayMs);
|
|
339
|
+
vectorTimer.unref?.();
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function setEmbedder(fn) {
|
|
343
|
+
embedder = fn;
|
|
344
|
+
if (lastBuild) scheduleVectorize(2_000);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function close() {
|
|
348
|
+
if (rescanTimer) { clearInterval(rescanTimer); rescanTimer = null; }
|
|
349
|
+
watchers.splice(0).forEach((w) => w.close());
|
|
350
|
+
clearTimeout(snapshotTimer);
|
|
351
|
+
clearTimeout(vectorTimer);
|
|
352
|
+
saveSnapshot();
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Tìm theo tên / đường dẫn / định danh / chữ đầu tài liệu; có `vector` (bge-m3 int8 base64 của câu hỏi) thì gộp thêm xếp hạng ngữ
|
|
357
|
+
* nghĩa. Trả đường hiển thị tương đối với gốc + dung lượng, ngày sửa, đoạn xem trước.
|
|
358
|
+
*/
|
|
359
|
+
function search(query, limit = 10, vector) {
|
|
360
|
+
const lexical = index.search(query, { limit: Math.max(limit, RANK_DEPTH) }).map((r) => r.id);
|
|
361
|
+
const q = vector ? decodeInt8(vector) : null;
|
|
362
|
+
const semantic = q && vectors.size
|
|
363
|
+
? [...vectors.entries()].map(([abs, v]) => [abs, int8Cosine(q, v.vec)]).sort((a, b) => b[1] - a[1]).slice(0, RANK_DEPTH)
|
|
364
|
+
: [];
|
|
365
|
+
const similarity = new Map(semantic);
|
|
366
|
+
const ranked = semantic.length ? fuse(lexical, semantic.map(([abs]) => abs), similarity) : lexical;
|
|
367
|
+
return ranked.slice(0, limit).map((id) => {
|
|
368
|
+
const root = resolvedRoots.find((r) => id.startsWith(r)) || resolvedRoots[0];
|
|
369
|
+
const e = entries.get(id);
|
|
370
|
+
return {
|
|
371
|
+
path: path.relative(root, id) || id,
|
|
372
|
+
size: e?.size,
|
|
373
|
+
modified: e?.mtime ? new Date(e.mtime).toISOString().slice(0, 10) : undefined,
|
|
374
|
+
...(e?.preview ? { preview: e.preview.slice(0, 200) } : {}),
|
|
375
|
+
...(similarity.has(id) ? { similarity: Number(similarity.get(id).toFixed(3)) } : {}),
|
|
376
|
+
};
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
return {
|
|
381
|
+
build, watch, close, search, refreshFile, vectorize, setEmbedder,
|
|
382
|
+
stats: () => ({ files: entries.size, vectors: vectors.size, last_build: lastBuild }),
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Gộp hai bảng xếp hạng (RRF). Hoà điểm — tệp đầu bảng từ khoá vs tệp đầu bảng ngữ nghĩa — thì tệp gần nghĩa hơn đứng trước: từ khoá
|
|
388
|
+
* chỉ trùng một chữ chung ("thuê") hay gặp hơn là trùng nghĩa.
|
|
389
|
+
*/
|
|
390
|
+
function fuse(lexical, semantic, similarity) {
|
|
391
|
+
const score = new Map();
|
|
392
|
+
for (const list of [lexical, semantic]) list.forEach((id, rank) => score.set(id, (score.get(id) || 0) + 1 / (RRF_K + rank + 1)));
|
|
393
|
+
return [...score.keys()].sort((a, b) => (score.get(b) - score.get(a)) || ((similarity.get(b) ?? -1) - (similarity.get(a) ?? -1)));
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Gốc lập chỉ mục: máy toàn quyền chỉ quét thư mục nhà (cả ổ là hàng trăm nghìn tệp hệ thống). */
|
|
397
|
+
export function indexRootsFor(roots, fullAccess) {
|
|
398
|
+
return fullAccess ? [os.homedir()] : roots;
|
|
399
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { spawn } from 'child_process';
|
|
4
|
+
import { DeviceErrorCode, ToolGroup } from '../constants.mjs';
|
|
5
|
+
import { DeviceToolError, resolveInRoots } from '../sandbox.mjs';
|
|
6
|
+
import { showOSNotification } from '../notify.mjs';
|
|
7
|
+
import { createWindowsHost } from './windowsHost.mjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Tầng điều khiển giao diện (28/10/2026, đợt 1: Windows). Nhìn cửa sổ bằng cây trợ năng của hệ điều hành (UI Automation) + ảnh khi cây
|
|
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
|
+
* sau khi làm (giá trị mới, tiêu đề cửa sổ, phần tử còn / mất).
|
|
13
|
+
*
|
|
14
|
+
* 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
|
+
* 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
|
+
* vào terminal; người dùng đang dùng chuột / phím → dừng (`GUI_USER_ACTIVE`).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Tiến trình không bao giờ điều khiển: quản lý mật khẩu, hộp nâng quyền, bảo mật hệ thống, màn hình khoá. */
|
|
20
|
+
const BLOCKED_PROCESSES = new Set([
|
|
21
|
+
'consent', 'credentialuihost', 'lockapp', 'logonui', 'securityhealthsystray', 'securityhealthhost', 'windowsdefender', 'msmpeng',
|
|
22
|
+
'keepass', 'keepassxc', '1password', 'bitwarden', 'lastpass', 'dashlane', 'enpass', 'nordpass', 'roboform',
|
|
23
|
+
]);
|
|
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. */
|
|
25
|
+
const SHELL_PROCESSES = new Set([
|
|
26
|
+
'cmd', 'powershell', 'pwsh', 'windowsterminal', 'wt', 'openconsole', 'conhost', 'regedit', 'mmc', 'taskmgr', 'wsl', 'bash', 'mintty',
|
|
27
|
+
]);
|
|
28
|
+
/** Không mở tệp có đuôi chạy được bằng `gui.open_app` (mở = chạy chương trình). */
|
|
29
|
+
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
|
+
|
|
31
|
+
const OBSERVE_MAX_NODES = 300;
|
|
32
|
+
const APPS_CACHE_MS = 10 * 60_000;
|
|
33
|
+
const OPEN_WAIT_MS = 10_000;
|
|
34
|
+
/** 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
|
+
const NOTIFY_EVERY_MS = 5 * 60_000;
|
|
36
|
+
|
|
37
|
+
const str = (description) => ({ type: 'string', description });
|
|
38
|
+
const num = (description) => ({ type: 'number', description });
|
|
39
|
+
const bool = (description) => ({ type: 'boolean', description });
|
|
40
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
41
|
+
|
|
42
|
+
export const GuiAction = Object.freeze({
|
|
43
|
+
CLICK: 'click', DOUBLE_CLICK: 'double_click', RIGHT_CLICK: 'right_click', SET_VALUE: 'set_value', TYPE: 'type', KEY: 'key',
|
|
44
|
+
SCROLL: 'scroll', SELECT: 'select', TOGGLE: 'toggle', EXPAND: 'expand', COLLAPSE: 'collapse', DRAG: 'drag',
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/** Năng lực GUI khai trong hồ sơ máy. Chỉ Windows ở đợt này; máy tính tổ chức (nhiều người chung) không có màn hình. */
|
|
48
|
+
export function detectGui({ disabled = false, multiUser = false, platform = process.platform } = {}) {
|
|
49
|
+
if (disabled || multiUser || platform !== 'win32') return null;
|
|
50
|
+
// Phiên 0 (dịch vụ) không có màn hình tương tác.
|
|
51
|
+
if (process.env.SESSIONNAME === 'Services') return null;
|
|
52
|
+
return { backend: 'uia', actions: Object.values(GuiAction) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const normalizeProcess = (name) => String(name || '').toLowerCase().replace(/\.exe$/, '');
|
|
56
|
+
|
|
57
|
+
/** Ứng dụng này có được điều khiển không — ném lỗi nếu bị chặn. */
|
|
58
|
+
export function assertWindowAllowed(windowInfo, { fullAccess }) {
|
|
59
|
+
const proc = normalizeProcess(windowInfo?.process);
|
|
60
|
+
if (!proc) return;
|
|
61
|
+
if (BLOCKED_PROCESSES.has(proc)) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Controlling "${windowInfo.process}" is not allowed on this device`);
|
|
62
|
+
if (!fullAccess && SHELL_PROCESSES.has(proc)) {
|
|
63
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Controlling "${windowInfo.process}" needs full device access (aivin remote start --full-access)`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
68
|
+
|
|
69
|
+
/** 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
|
+
export function matchApps(apps, query) {
|
|
71
|
+
const q = normalizeName(query);
|
|
72
|
+
if (!q) return [];
|
|
73
|
+
const scored = apps.map((app) => {
|
|
74
|
+
const n = normalizeName(app.name);
|
|
75
|
+
const score = n === q ? 3 : n.startsWith(q) ? 2 : n.includes(q) ? 1 : 0;
|
|
76
|
+
return { app, score };
|
|
77
|
+
}).filter((x) => x.score > 0).sort((a, b) => b.score - a.score || a.app.name.length - b.app.name.length);
|
|
78
|
+
if (!scored.length) return [];
|
|
79
|
+
const top = scored[0].score;
|
|
80
|
+
return scored.filter((x) => x.score === top).map((x) => x.app);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function runPowerShellJson(script, signal) {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
const c = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true });
|
|
86
|
+
let out = '';
|
|
87
|
+
c.stdout.on('data', (d) => { out += d.toString(); });
|
|
88
|
+
const onAbort = () => { try { c.kill(); } catch { /* đã thoát */ } };
|
|
89
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
90
|
+
c.on('error', (e) => reject(e));
|
|
91
|
+
c.on('close', () => {
|
|
92
|
+
signal?.removeEventListener('abort', onAbort);
|
|
93
|
+
try { const v = JSON.parse(out || 'null'); resolve(Array.isArray(v) ? v : v ? [v] : []); } catch (e) { reject(e); }
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 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
|
+
*/
|
|
101
|
+
export function createGuiController({ fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true } = {}) {
|
|
102
|
+
let appsCache = null;
|
|
103
|
+
let lastNotifyAt = 0;
|
|
104
|
+
/** 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
|
+
const snapshotWindows = new Map();
|
|
106
|
+
|
|
107
|
+
const announce = (windowInfo) => {
|
|
108
|
+
const now = Date.now();
|
|
109
|
+
if (now - lastNotifyAt < NOTIFY_EVERY_MS) return;
|
|
110
|
+
lastNotifyAt = now;
|
|
111
|
+
say(`🖱 AI đang điều khiển ${windowInfo?.process || 'màn hình'} — di chuột hoặc gõ phím để AI dừng lại.`);
|
|
112
|
+
notify({ title: 'Aivin đang điều khiển máy này', body: `AI đang thao tác trên ${windowInfo?.title || windowInfo?.process || 'màn hình'}. Di chuột hoặc gõ phím để AI dừng và hỏi bạn.` });
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
async function windows(args, ctx) {
|
|
116
|
+
const list = await host.call('windows', { all: !!args.include_dialogs }, ctx);
|
|
117
|
+
return { windows: list.map((w) => ({ ...w, blocked: BLOCKED_PROCESSES.has(normalizeProcess(w.process)) || (!fullAccess && SHELL_PROCESSES.has(normalizeProcess(w.process))) || undefined })) };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const windowInfoOf = (args, ctx) => host.call('window_info', { window: args.window }, ctx);
|
|
121
|
+
|
|
122
|
+
async function observe(args, ctx) {
|
|
123
|
+
const res = await host.call('observe', {
|
|
124
|
+
window: args.window,
|
|
125
|
+
max_nodes: Math.min(Number(args.max_nodes) || OBSERVE_MAX_NODES, 1500),
|
|
126
|
+
include_image: !!args.include_image,
|
|
127
|
+
image_when_poor: args.image_when_poor !== false,
|
|
128
|
+
image_max_width: Number(args.image_max_width) || 1366,
|
|
129
|
+
image_quality: Number(args.image_quality) || 70,
|
|
130
|
+
}, ctx);
|
|
131
|
+
assertWindowAllowed(res.window, { fullAccess });
|
|
132
|
+
snapshotWindows.set(String(res.snapshot), res.window);
|
|
133
|
+
if (snapshotWindows.size > 20) snapshotWindows.delete(snapshotWindows.keys().next().value);
|
|
134
|
+
return res;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function focus(args, ctx) {
|
|
138
|
+
assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
|
|
139
|
+
return host.call('focus', { window: args.window }, ctx);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function act(args, ctx) {
|
|
143
|
+
const action = String(args.action || GuiAction.CLICK);
|
|
144
|
+
if (!Object.values(GuiAction).includes(action)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown action: ${action}`);
|
|
145
|
+
const snap = args.node_id ? String(args.node_id).split('.')[0] : null;
|
|
146
|
+
const windowInfo = snap ? snapshotWindows.get(snap) : await windowInfoOf(args, ctx);
|
|
147
|
+
if (snap && !windowInfo) throw new DeviceToolError(DeviceErrorCode.GUI_STALE_NODE, `Node ${args.node_id} is from an old observation — observe again`);
|
|
148
|
+
assertWindowAllowed(windowInfo, { fullAccess });
|
|
149
|
+
announce(windowInfo);
|
|
150
|
+
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,
|
|
152
|
+
option: args.option, state: args.state, direction: args.direction, amount: args.amount, point: args.point, to: args.to,
|
|
153
|
+
image_scale: args.image_scale, settle_ms: args.settle_ms,
|
|
154
|
+
check_user_input: true, user_input_grace_ms: Number(args.user_input_grace_ms) || 1500,
|
|
155
|
+
}, ctx);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
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;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function waitNewWindow(before, ctx, hint) {
|
|
167
|
+
const known = new Set(before.map((w) => w.window));
|
|
168
|
+
const deadline = Date.now() + OPEN_WAIT_MS;
|
|
169
|
+
while (Date.now() < deadline) {
|
|
170
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
171
|
+
if (ctx.signal?.aborted) throw ctx.signal.reason;
|
|
172
|
+
const now = await host.call('windows', {}, ctx);
|
|
173
|
+
const fresh = now.filter((w) => !known.has(w.window));
|
|
174
|
+
const pick = fresh.find((w) => hint && normalizeName(`${w.title} ${w.process}`).includes(normalizeName(hint).split(' ')[0])) || fresh[0];
|
|
175
|
+
if (pick) return pick;
|
|
176
|
+
}
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Cửa sổ AI vừa mở được Windows đưa lên trước → đẩy xuống dưới, trả focus cho cửa sổ người dùng đang dùng (chạy nền). */
|
|
181
|
+
async function sendToBack(win, before, ctx) {
|
|
182
|
+
if (!win || background === false) return;
|
|
183
|
+
const userWindow = before.find((w) => w.focused)?.window;
|
|
184
|
+
await host.call('to_back', { window: win.window, restore_to: userWindow }, ctx).catch(() => undefined);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Mở ứng dụng theo tên trong danh sách Start, hoặc mở một tệp trong vùng được phép bằng ứng dụng mặc định. Không chạy lệnh tuỳ ý. */
|
|
188
|
+
async function openApp(args, ctx, env) {
|
|
189
|
+
const before = await host.call('windows', {}, ctx);
|
|
190
|
+
if (args.file) {
|
|
191
|
+
const abs = resolveInRoots(env.roots, String(args.file));
|
|
192
|
+
if (EXECUTABLE_EXT.test(abs)) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, 'Opening programs or scripts is not allowed — use an app name, or shell.exec');
|
|
193
|
+
if (!fs.existsSync(abs)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `File not found: ${args.file}`);
|
|
194
|
+
spawn('explorer.exe', [abs], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
|
|
195
|
+
const win = await waitNewWindow(before, ctx, path.basename(abs, path.extname(abs)));
|
|
196
|
+
await sendToBack(win, before, ctx);
|
|
197
|
+
return { opened: path.basename(abs), window: win, hint: win ? undefined : 'No new window appeared yet — the file may have opened in an existing window; check gui.windows' };
|
|
198
|
+
}
|
|
199
|
+
const name = String(args.name || '').trim();
|
|
200
|
+
if (!name) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give name (an installed app) or file');
|
|
201
|
+
const matches = matchApps(await listApps(ctx.signal), name);
|
|
202
|
+
if (!matches.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No installed app named "${name}"`);
|
|
203
|
+
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
|
+
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`);
|
|
206
|
+
spawn('explorer.exe', [`shell:AppsFolder\\${app.app_id}`], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
|
|
207
|
+
const win = await waitNewWindow(before, ctx, app.name);
|
|
208
|
+
await sendToBack(win, before, ctx);
|
|
209
|
+
if (win) assertWindowAllowed(win, { fullAccess });
|
|
210
|
+
return { opened: app.name, window: win, hint: win ? undefined : 'App started but no new window yet — call gui.windows in a moment' };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return { windows, observe, focus, act, openApp, close: () => host.close() };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Công cụ GUI cho danh mục của Planner. */
|
|
217
|
+
export function buildGuiTools(gui) {
|
|
218
|
+
const target = {
|
|
219
|
+
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'),
|
|
221
|
+
};
|
|
222
|
+
return [
|
|
223
|
+
{ name: 'gui.windows', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.windows(a, c),
|
|
224
|
+
description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
|
|
225
|
+
input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
|
|
226
|
+
{ 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') }) },
|
|
229
|
+
{ name: 'gui.focus', group: ToolGroup.GUI, handler: (a, c) => gui.focus(a, c),
|
|
230
|
+
description: 'Bring a window to the front (restores it if minimized).',
|
|
231
|
+
input_schema: schema({ window: target.window }, ['window']) },
|
|
232
|
+
{ 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.',
|
|
234
|
+
input_schema: schema({
|
|
235
|
+
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
|
+
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'),
|
|
237
|
+
point: { type: 'object', description: '{x,y} on the last screenshot when no node_id', properties: { x: num('x'), y: num('y') } },
|
|
238
|
+
to: { type: 'object', description: 'drag destination {x,y} on the last screenshot', properties: { x: num('x'), y: num('y') } },
|
|
239
|
+
image_scale: num('scale of the screenshot the point was taken from'), method: str('auto | pattern | mouse (default auto)'),
|
|
240
|
+
}, ['action']) },
|
|
241
|
+
{ name: 'gui.open_app', group: ToolGroup.GUI, handler: (a, c, e) => gui.openApp(a, c, e),
|
|
242
|
+
description: 'Open an installed app by name (from the Start menu list), or open a document file with its default app. Returns the new window. Does not run programs or scripts by path.',
|
|
243
|
+
input_schema: schema({ name: str('app name, e.g. "Excel", "Calculator"'), file: str('a document path inside the allowed folders'), first: bool('take the first match when several apps share the name') }) },
|
|
244
|
+
];
|
|
245
|
+
}
|