@aivin-labs/cli 1.0.5 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +288 -216
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +551 -5
  4. package/bin/lib/browserAutomation.mjs +384 -614
  5. package/bin/lib/browserTui.mjs +276 -251
  6. package/bin/lib/cancellation.mjs +61 -0
  7. package/bin/lib/localBrowser.mjs +345 -0
  8. package/bin/lib/mcpProxy.mjs +869 -837
  9. package/bin/lib/missionStream.mjs +696 -691
  10. package/bin/lib/releaseKeys.mjs +9 -0
  11. package/bin/lib/remote/activityLog.mjs +68 -0
  12. package/bin/lib/remote/autoStart.mjs +617 -0
  13. package/bin/lib/remote/autoUpdate.mjs +129 -0
  14. package/bin/lib/remote/brand.mjs +60 -0
  15. package/bin/lib/remote/browserTunnel.mjs +403 -0
  16. package/bin/lib/remote/callLedger.mjs +134 -0
  17. package/bin/lib/remote/cdpPolicy.mjs +79 -0
  18. package/bin/lib/remote/client.mjs +808 -0
  19. package/bin/lib/remote/clipboard.mjs +138 -0
  20. package/bin/lib/remote/codingAgents.mjs +293 -0
  21. package/bin/lib/remote/constants.mjs +234 -0
  22. package/bin/lib/remote/credentials.mjs +208 -0
  23. package/bin/lib/remote/daemonLock.mjs +86 -0
  24. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  25. package/bin/lib/remote/desktop/index.mjs +272 -0
  26. package/bin/lib/remote/desktop/linux.mjs +144 -0
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  28. package/bin/lib/remote/desktop/mac.mjs +187 -0
  29. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  30. package/bin/lib/remote/desktop/strings.mjs +74 -0
  31. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  32. package/bin/lib/remote/deviceMemory.mjs +246 -0
  33. package/bin/lib/remote/deviceProfile.mjs +142 -0
  34. package/bin/lib/remote/deviceWatches.mjs +138 -0
  35. package/bin/lib/remote/docText.mjs +117 -0
  36. package/bin/lib/remote/fileIndexer.mjs +399 -0
  37. package/bin/lib/remote/gui/index.mjs +326 -0
  38. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  39. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  40. package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
  41. package/bin/lib/remote/httpTransfer.mjs +89 -0
  42. package/bin/lib/remote/idempotency.mjs +135 -0
  43. package/bin/lib/remote/keepAwake.mjs +100 -0
  44. package/bin/lib/remote/localConfirm.mjs +268 -0
  45. package/bin/lib/remote/localPolicy.mjs +256 -0
  46. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  47. package/bin/lib/remote/mascot/ask.mjs +768 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  49. package/bin/lib/remote/mascot/assets.mjs +827 -0
  50. package/bin/lib/remote/mascot/bot.mjs +372 -0
  51. package/bin/lib/remote/mascot/hostSource.mjs +759 -0
  52. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  53. package/bin/lib/remote/mascot/index.mjs +493 -0
  54. package/bin/lib/remote/mascot/labels.mjs +82 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  56. package/bin/lib/remote/mascot/strings.mjs +375 -0
  57. package/bin/lib/remote/mascot/ui.mjs +104 -0
  58. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  59. package/bin/lib/remote/meeting/index.mjs +415 -0
  60. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  61. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  62. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  63. package/bin/lib/remote/memberFsPool.mjs +134 -0
  64. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  65. package/bin/lib/remote/mission.mjs +156 -0
  66. package/bin/lib/remote/missionQuestion.mjs +63 -0
  67. package/bin/lib/remote/multiUser.mjs +344 -0
  68. package/bin/lib/remote/netProxy.mjs +145 -0
  69. package/bin/lib/remote/notify.mjs +58 -0
  70. package/bin/lib/remote/office/index.mjs +90 -0
  71. package/bin/lib/remote/policyCommand.mjs +93 -0
  72. package/bin/lib/remote/processes.mjs +217 -0
  73. package/bin/lib/remote/sandbox.mjs +221 -0
  74. package/bin/lib/remote/schedule.mjs +213 -0
  75. package/bin/lib/remote/scheduler.mjs +124 -0
  76. package/bin/lib/remote/tabGroups.mjs +209 -0
  77. package/bin/lib/remote/textIndex.mjs +131 -0
  78. package/bin/lib/remote/tokenStore.mjs +77 -0
  79. package/bin/lib/remote/toolHandlers.mjs +741 -0
  80. package/bin/lib/remote/undoStore.mjs +242 -0
  81. package/bin/lib/remoteControl.mjs +26 -0
  82. package/bin/lib/scaffold.mjs +654 -653
  83. package/bin/lib/selfUpdate.mjs +71 -0
  84. package/bin/lib/update/binarySwap.mjs +63 -0
  85. package/bin/lib/update/constants.mjs +56 -0
  86. package/bin/lib/update/download.mjs +145 -0
  87. package/bin/lib/update/signature.mjs +42 -0
  88. package/bin/lib/update/state.mjs +205 -0
  89. package/bin/lib/update/versions.mjs +60 -0
  90. package/docs/AIVIN_MASCOT.md +116 -0
  91. package/docs/CLI.md +1484 -1299
  92. package/docs/media/aivin-mascot-states.mp4 +0 -0
  93. 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
+ }