@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
|
@@ -1,399 +1,773 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import os from 'os';
|
|
3
|
-
import path from 'path';
|
|
4
|
-
import zlib from 'zlib';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
const
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
const
|
|
51
|
-
/**
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
*/
|
|
58
|
-
const
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import zlib from 'zlib';
|
|
5
|
+
import { REMOTE_CONFIG_DIR } from './constants.mjs';
|
|
6
|
+
import { cloudOnlyFiles, inCloudFolder } from './cloudFiles.mjs';
|
|
7
|
+
import { extractDocText, isDocFile, wellFormed } from './docText.mjs';
|
|
8
|
+
import { FolderKind, classifyDir, folderSummary, skipDir, skipFile } from './folderRules.mjs';
|
|
9
|
+
import { isProtectedPath } from './sandbox.mjs';
|
|
10
|
+
import { createWatchBatcher } from './watchBatcher.mjs';
|
|
11
|
+
import { openSqlite } from './sqliteDb.mjs';
|
|
12
|
+
import { decodeInt8, int8Cosine, tokenize } from './textIndex.mjs';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Chỉ mục tệp (SQLite trên đĩa) 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
|
|
16
|
+
* nội dung chính mà không quét đĩa mỗi lần. Khởi động: mở chỉ mục đã có, quét lại TĂNG DẦN (chỉ đọc tệp có mtime/size đổi). Chạy: theo
|
|
17
|
+
* dõi thư mục (`fs.watch` đệ quy), cập nhật đúng tệp đổi.
|
|
18
|
+
*
|
|
19
|
+
* 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
|
|
20
|
+
* (`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
|
|
21
|
+
* `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.
|
|
22
|
+
*
|
|
23
|
+
* Bỏ / gộp theo folderRules.mjs (thư mục ẩn, tệp tạm, thư mục ứng dụng, thư mục hàng loạt ảnh / log, kho git → một mục đại diện). Tệp chỉ có
|
|
24
|
+
* trên mây: chỉ lập chỉ mục tên (cloudFiles.mjs). Thư mục làm việc người dùng chỉ định (`addFolder`, `index-folders.json`) lập chỉ mục đầy
|
|
25
|
+
* đủ, kể cả code trong kho git.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const DB_FILE = path.join(REMOTE_CONFIG_DIR, 'file-index.db');
|
|
29
|
+
/** Thư mục làm việc người dùng chỉ định (qua chat — công cụ fs.index_folder — hoặc `aivin remote index add`). */
|
|
30
|
+
const INDEX_FOLDERS_FILE = path.join(REMOTE_CONFIG_DIR, 'index-folders.json');
|
|
31
|
+
/** Mẫu loại trừ người dùng chỉ định (`aivin remote index-exclude add`). */
|
|
32
|
+
const INDEX_EXCLUDES_FILE = path.join(REMOTE_CONFIG_DIR, 'index-excludes.json');
|
|
33
|
+
/** Bản chụp gzip của bản giữ chỉ mục trong RAM (≤ 1.0.11) — chép sang SQLite lần đầu rồi xoá. */
|
|
34
|
+
const LEGACY_SNAPSHOT_FILE = path.join(REMOTE_CONFIG_DIR, 'file-index.json.gz');
|
|
35
|
+
const LEGACY_VECTORS_FILE = path.join(REMOTE_CONFIG_DIR, 'file-vectors.json.gz');
|
|
36
|
+
const LEGACY_SNAPSHOT_VERSION = 3;
|
|
37
|
+
const MAX_FILES = 200_000;
|
|
38
|
+
const HEAD_BYTES = 16 * 1024;
|
|
39
|
+
const MAX_HEAD_FILE_BYTES = 2 * 1024 * 1024;
|
|
40
|
+
const MAX_IDENTIFIERS = 200;
|
|
41
|
+
const STAT_CONCURRENCY = 64;
|
|
42
|
+
const WATCH_DEBOUNCE_MS = 800;
|
|
43
|
+
/** Lô theo dõi chạy chậm nhất sau chừng này kể từ sự kiện đầu (tệp bị ghi liên tục không giữ lô mãi) — 02/11/2026. */
|
|
44
|
+
const WATCH_MAX_WAIT_MS = 5_000;
|
|
45
|
+
/** Quá chừng này đường dẫn chờ → bỏ danh sách, quét lại tăng dần cả cây. */
|
|
46
|
+
const WATCH_MAX_PENDING = 5_000;
|
|
47
|
+
/** Từ trong câu hỏi dài từ chừng này trở lên thì khớp cả tiền tố ("auth" ↔ "authentication"). */
|
|
48
|
+
const PREFIX_MIN = 4;
|
|
49
|
+
/** Số vector đọc mỗi lần khi tìm theo nghĩa. */
|
|
50
|
+
const VECTOR_SCAN_CHUNK = 2000;
|
|
51
|
+
/** Số tệp tài liệu tối đa có vector (mỗi vector ~1,4 KB). */
|
|
52
|
+
const MAX_VECTOR_FILES = Number(process.env.AIVIN_REMOTE_MAX_VECTOR_FILES) || 20_000;
|
|
53
|
+
const EMBED_BATCH = 32;
|
|
54
|
+
const BACKOFF_BASE_MS = 30_000;
|
|
55
|
+
const BACKOFF_MAX_MS = 30 * 60_000;
|
|
56
|
+
const RANK_DEPTH = 50;
|
|
57
|
+
/** Hằng số k của Reciprocal Rank Fusion. */
|
|
58
|
+
const RRF_K = 60;
|
|
59
|
+
const TEXT_EXTENSIONS = new Set([
|
|
60
|
+
'.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', '.md', '.txt', '.yaml', '.yml', '.toml', '.py', '.go', '.rs',
|
|
61
|
+
'.java', '.kt', '.cs', '.cpp', '.cc', '.c', '.h', '.hpp', '.php', '.rb', '.swift', '.scala', '.sql', '.sh', '.ps1', '.bat', '.cmd',
|
|
62
|
+
'.html', '.css', '.scss', '.vue', '.svelte', '.xml', '.gradle', '.proto', '.graphql', '.dart', '.lua', '.r', '.csv',
|
|
63
|
+
]);
|
|
64
|
+
/** 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. */
|
|
65
|
+
const PRIORITY_DIRS = ['Desktop', 'Documents', 'Downloads', 'OneDrive', 'Pictures', 'Dropbox', 'Google Drive'];
|
|
66
|
+
/** 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. */
|
|
67
|
+
const RESCAN_MS = 10 * 60_000;
|
|
68
|
+
/** CLI (`aivin remote index add`) sửa danh sách thư mục làm việc khi listener đang chạy → listener thấy sau chừng này. */
|
|
69
|
+
const INDEX_FOLDERS_POLL_MS = 5_000;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 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
|
|
73
|
+
* ý 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.
|
|
74
|
+
*/
|
|
75
|
+
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;
|
|
76
|
+
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;
|
|
77
|
+
|
|
78
|
+
export function looksSecret(abs, text = '') {
|
|
79
|
+
return SECRET_NAME_RE.test(path.basename(abs)) || (!!text && SECRET_TEXT_RE.test(text));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function identifiersOf(text) {
|
|
83
|
+
const seen = new Set();
|
|
84
|
+
for (const m of text.matchAll(/[\p{L}_][\p{L}\p{N}_]{2,}/gu)) {
|
|
85
|
+
seen.add(m[0]);
|
|
86
|
+
if (seen.size >= MAX_IDENTIFIERS) break;
|
|
87
|
+
}
|
|
88
|
+
return [...seen].join(' ');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const readsContent = (abs) => isDocFile(abs) || TEXT_EXTENSIONS.has(path.extname(abs).toLowerCase());
|
|
92
|
+
|
|
93
|
+
async function headTokens(abs, size) {
|
|
94
|
+
if (!TEXT_EXTENSIONS.has(path.extname(abs).toLowerCase()) || size > MAX_HEAD_FILE_BYTES) return '';
|
|
95
|
+
let handle;
|
|
96
|
+
try {
|
|
97
|
+
handle = await fs.promises.open(abs, 'r');
|
|
98
|
+
const buf = Buffer.alloc(Math.min(HEAD_BYTES, size));
|
|
99
|
+
const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
|
|
100
|
+
return identifiersOf(buf.subarray(0, bytesRead).toString('utf8'));
|
|
101
|
+
} catch {
|
|
102
|
+
return '';
|
|
103
|
+
} finally {
|
|
104
|
+
await handle?.close().catch(() => undefined);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function mapLimit(items, limit, fn) {
|
|
109
|
+
let cursor = 0;
|
|
110
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
111
|
+
while (cursor < items.length) {
|
|
112
|
+
const i = cursor++;
|
|
113
|
+
await fn(items[i], i);
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
await Promise.all(workers);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Duyệt cây theo folderRules (không theo symlink ra ngoài): bỏ thư mục ẩn / rác, gộp thư mục ứng dụng / hàng loạt / kho git thành một mục.
|
|
121
|
+
* `full` (thư mục làm việc người dùng chỉ định): kho git bên trong cũng lập chỉ mục đầy đủ. Gốc của lần duyệt không bị gộp.
|
|
122
|
+
* → `{ files: [{ abs, repo }], folders: [{ abs, kind, mtime, count, note, words }] }` (`repo` = nằm trong kho git → chỉ giữ tài liệu).
|
|
123
|
+
*/
|
|
124
|
+
async function walk(root, limit, { skip = new Set(), full = false, excludes = null } = {}) {
|
|
125
|
+
const files = [];
|
|
126
|
+
const folders = [];
|
|
127
|
+
const queue = [{ dir: root, repo: false }];
|
|
128
|
+
const collapse = async (dir, kind, entries) => {
|
|
129
|
+
const stat = await fs.promises.stat(dir).catch(() => null);
|
|
130
|
+
folders.push({ abs: dir, kind, mtime: stat ? Math.floor(stat.mtimeMs) : 0, ...folderSummary(kind, dir, entries) });
|
|
131
|
+
};
|
|
132
|
+
while (queue.length && files.length < limit) {
|
|
133
|
+
const batch = queue.splice(0, STAT_CONCURRENCY);
|
|
134
|
+
await mapLimit(batch, STAT_CONCURRENCY, async ({ dir, repo }) => {
|
|
135
|
+
let entries;
|
|
136
|
+
try { entries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { return; }
|
|
137
|
+
const kind = dir === root ? null : classifyDir(path.basename(dir), entries);
|
|
138
|
+
if (kind === FolderKind.APP) return collapse(dir, kind, entries);
|
|
139
|
+
let inRepo = repo;
|
|
140
|
+
if (kind === FolderKind.REPO && !full) {
|
|
141
|
+
if (!repo) await collapse(dir, kind, entries);
|
|
142
|
+
inRepo = true;
|
|
143
|
+
}
|
|
144
|
+
const bulk = kind === FolderKind.BULK;
|
|
145
|
+
if (bulk) await collapse(dir, kind, entries);
|
|
146
|
+
for (const entry of entries) {
|
|
147
|
+
if (entry.isSymbolicLink()) continue;
|
|
148
|
+
const abs = path.join(dir, entry.name);
|
|
149
|
+
if (isProtectedPath(abs) || skip.has(abs)) continue;
|
|
150
|
+
if (entry.isDirectory()) {
|
|
151
|
+
if (!skipDir(entry.name, excludes)) queue.push({ dir: abs, repo: inRepo });
|
|
152
|
+
} else if (entry.isFile() && !skipFile(entry.name, excludes) && (!(bulk || inRepo) || isDocFile(entry.name))) {
|
|
153
|
+
files.push({ abs, repo: inRepo });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
return { files: files.slice(0, limit), folders };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Thư mục ưu tiên có thật ngay dưới các gốc (kể cả `OneDrive - Công ty`). */
|
|
162
|
+
function priorityDirsOf(roots) {
|
|
163
|
+
const out = [];
|
|
164
|
+
for (const root of roots) {
|
|
165
|
+
let names;
|
|
166
|
+
try { names = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name); } catch { continue; }
|
|
167
|
+
for (const want of PRIORITY_DIRS) {
|
|
168
|
+
for (const name of names) if (name === want || name.startsWith(`${want} -`)) out.push(path.join(root, name));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Thư mục làm việc người dùng chỉ định (đường tuyệt đối). */
|
|
175
|
+
export function loadIndexFolders() {
|
|
176
|
+
try {
|
|
177
|
+
const data = JSON.parse(fs.readFileSync(INDEX_FOLDERS_FILE, 'utf8'));
|
|
178
|
+
return Array.isArray(data?.folders) ? data.folders.filter((f) => typeof f === 'string' && path.isAbsolute(f)) : [];
|
|
179
|
+
} catch {
|
|
180
|
+
return [];
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function saveIndexFolders(folders) {
|
|
185
|
+
fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
|
|
186
|
+
const list = [...new Set(folders.map((f) => path.resolve(f)))];
|
|
187
|
+
fs.writeFileSync(INDEX_FOLDERS_FILE, JSON.stringify({ folders: list }, null, 2));
|
|
188
|
+
return list;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Mẫu loại trừ người dùng chỉ định (`index-excludes.json`). */
|
|
192
|
+
export function loadIndexExcludes() {
|
|
193
|
+
try {
|
|
194
|
+
const data = JSON.parse(fs.readFileSync(INDEX_EXCLUDES_FILE, 'utf8'));
|
|
195
|
+
return Array.isArray(data?.excludes) ? data.excludes.filter((e) => typeof e === 'string' && e.trim().length > 0) : [];
|
|
196
|
+
} catch {
|
|
197
|
+
return [];
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function saveIndexExcludes(excludes) {
|
|
202
|
+
fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
|
|
203
|
+
const list = [...new Set(excludes.map((e) => String(e).trim()).filter(Boolean))];
|
|
204
|
+
fs.writeFileSync(INDEX_EXCLUDES_FILE, JSON.stringify({ excludes: list }, null, 2));
|
|
205
|
+
return list;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Đọc các mẫu loại trừ từ tệp `.aivinignore` trong thư mục (nếu có). */
|
|
209
|
+
export function loadIgnoreFile(dir) {
|
|
210
|
+
const ignorePath = path.join(dir, '.aivinignore');
|
|
211
|
+
try {
|
|
212
|
+
return fs.readFileSync(ignorePath, 'utf8')
|
|
213
|
+
.split(/\r?\n/)
|
|
214
|
+
.map((line) => line.trim())
|
|
215
|
+
.filter((line) => line.length > 0 && !line.startsWith('#'));
|
|
216
|
+
} catch {
|
|
217
|
+
return [];
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const within = (dir, abs) => abs === dir || abs.startsWith(dir.endsWith(path.sep) ? dir : dir + path.sep);
|
|
222
|
+
const vectorKey = (entry) => `${entry.mtime}:${entry.size}`;
|
|
223
|
+
|
|
224
|
+
/** Đổi bảng → tăng số này: chỉ mục cũ bị bỏ, quét lại từ đầu. */
|
|
225
|
+
const SCHEMA_VERSION = '2';
|
|
226
|
+
const PRAGMAS = `
|
|
227
|
+
PRAGMA journal_mode = WAL;
|
|
228
|
+
PRAGMA synchronous = NORMAL;
|
|
229
|
+
PRAGMA busy_timeout = 5000;
|
|
230
|
+
PRAGMA cache_size = -8000;
|
|
231
|
+
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
|
|
232
|
+
`;
|
|
233
|
+
// FTS5 không giữ bản chữ (contentless) — chữ tách sẵn chỉ cần để lập chỉ mục; xem / xếp hạng dùng bảng files. `kind` ≠ NULL: mục đại diện
|
|
234
|
+
// cho một thư mục gộp (FolderKind), `size` = số mục bên trong, `preview` = ghi chú cho agent.
|
|
235
|
+
const SCHEMA = `
|
|
236
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
237
|
+
id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE, mtime INTEGER, size INTEGER, preview TEXT, kind TEXT,
|
|
238
|
+
secret INTEGER NOT NULL DEFAULT 0, doc INTEGER NOT NULL DEFAULT 0, prio INTEGER NOT NULL DEFAULT 0
|
|
239
|
+
);
|
|
240
|
+
CREATE INDEX IF NOT EXISTS files_vector_order ON files (doc, secret, prio DESC, mtime DESC);
|
|
241
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5 (
|
|
242
|
+
body, content = '', contentless_delete = 1, tokenize = 'unicode61 remove_diacritics 0', prefix = '${PREFIX_MIN}'
|
|
243
|
+
);
|
|
244
|
+
CREATE TABLE IF NOT EXISTS vectors (id INTEGER PRIMARY KEY, key TEXT NOT NULL, vec BLOB NOT NULL);
|
|
245
|
+
`;
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Chỉ mục nằm trên đĩa (SQLite, `file-index.db`), không nạp vào RAM: bảng `files` (đường dẫn, mtime/size, chữ đầu tài liệu, mục thư mục
|
|
249
|
+
* gộp), FTS5 cho từ khoá (BM25 + khớp tiền tố, chữ đã tách sẵn bằng `tokenize` — bỏ dấu, camelCase, chữ Hán thành cặp), `vectors` (int8
|
|
250
|
+
* BLOB). Tìm chỉ đọc vài trang B-tree; vector quét theo khúc. ~100k tệp từng ngốn ~1 GB RAM khi mọi thứ là Map / Set trong bộ nhớ.
|
|
251
|
+
*/
|
|
252
|
+
export function createFileIndex(roots) {
|
|
253
|
+
const resolvedRoots = roots.map((r) => path.resolve(r));
|
|
254
|
+
const watchers = new Map(); // thư mục được theo dõi → fs.FSWatcher
|
|
255
|
+
let db = null;
|
|
256
|
+
let opening = null;
|
|
257
|
+
let st = null;
|
|
258
|
+
let migrated = 0;
|
|
259
|
+
let rescanTimer = null;
|
|
260
|
+
let vectorTimer;
|
|
261
|
+
let lastBuild = null;
|
|
262
|
+
let priorityDirs = [];
|
|
263
|
+
let indexFolders = loadIndexFolders();
|
|
264
|
+
let indexExcludes = loadIndexExcludes();
|
|
265
|
+
const rootIgnores = resolvedRoots.flatMap(loadIgnoreFile);
|
|
266
|
+
let activeExcludes = new Set([...indexExcludes, ...rootIgnores].map((s) => s.toLowerCase()));
|
|
267
|
+
|
|
268
|
+
const reloadExcludes = () => {
|
|
269
|
+
indexExcludes = loadIndexExcludes();
|
|
270
|
+
const updatedRoots = resolvedRoots.flatMap(loadIgnoreFile);
|
|
271
|
+
activeExcludes = new Set([...indexExcludes, ...updatedRoots].map((s) => s.toLowerCase()));
|
|
272
|
+
};
|
|
273
|
+
/** Thư mục gộp đã biết (từ chỉ mục) — để bộ theo dõi không lập chỉ mục lẻ từng ảnh chụp màn hình mới. */
|
|
274
|
+
let collapsed = [];
|
|
275
|
+
let watching = false;
|
|
276
|
+
let embedder = null;
|
|
277
|
+
let vectorizing = false;
|
|
278
|
+
let failures = 0;
|
|
279
|
+
let pausedUntil = 0;
|
|
280
|
+
|
|
281
|
+
const docText = (abs, entry) => `${abs.split(path.sep).slice(-6).join(' ')} ${entry.tokens || ''} ${entry.preview || ''}`;
|
|
282
|
+
const isPriority = (abs) => priorityDirs.some((d) => within(d, abs)) || indexFolders.some((d) => within(d, abs));
|
|
283
|
+
/** Nằm trong thư mục / là tệp không lập chỉ mục (tính từ gốc) — bản chụp cũ còn giữ những tệp này. */
|
|
284
|
+
const skippedPath = (abs) => {
|
|
285
|
+
const root = resolvedRoots.find((r) => within(r, abs));
|
|
286
|
+
if (!root) return true;
|
|
287
|
+
const segs = path.relative(root, abs).split(path.sep);
|
|
288
|
+
return segs.slice(0, -1).some((d) => skipDir(d, activeExcludes)) || skipFile(segs[segs.length - 1], activeExcludes);
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
function ensureOpen() {
|
|
292
|
+
if (!opening) {
|
|
293
|
+
opening = (async () => {
|
|
294
|
+
fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
|
|
295
|
+
db = await openSqlite(DB_FILE);
|
|
296
|
+
db.exec(PRAGMAS);
|
|
297
|
+
const meta = (key) => db.prepare('SELECT value FROM meta WHERE key = ?').get(key)?.value;
|
|
298
|
+
const setMeta = db.prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value');
|
|
299
|
+
if (meta('schema') !== SCHEMA_VERSION) {
|
|
300
|
+
db.exec('DROP TABLE IF EXISTS files; DROP TABLE IF EXISTS fts; DROP TABLE IF EXISTS vectors; DELETE FROM meta;');
|
|
301
|
+
setMeta.run('schema', SCHEMA_VERSION);
|
|
302
|
+
}
|
|
303
|
+
db.exec(SCHEMA);
|
|
304
|
+
// Đổi gốc (ghép lại với thư mục khác / bật toàn quyền) → chỉ mục cũ vô dụng.
|
|
305
|
+
if (meta('roots') !== JSON.stringify(resolvedRoots)) {
|
|
306
|
+
db.exec('DELETE FROM files; DELETE FROM fts; DELETE FROM vectors;');
|
|
307
|
+
setMeta.run('roots', JSON.stringify(resolvedRoots));
|
|
308
|
+
}
|
|
309
|
+
st = {
|
|
310
|
+
find: db.prepare('SELECT id, mtime, size, kind, doc FROM files WHERE path = ?'),
|
|
311
|
+
upsert: db.prepare(`INSERT INTO files (path, mtime, size, preview, kind, secret, doc, prio) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
312
|
+
ON CONFLICT(path) DO UPDATE SET mtime = excluded.mtime, size = excluded.size, preview = excluded.preview, kind = excluded.kind,
|
|
313
|
+
secret = excluded.secret, doc = excluded.doc, prio = excluded.prio RETURNING id`),
|
|
314
|
+
flags: db.prepare('UPDATE files SET doc = ?, prio = ? WHERE id = ?'),
|
|
315
|
+
ftsDelete: db.prepare('DELETE FROM fts WHERE rowid = ?'),
|
|
316
|
+
ftsInsert: db.prepare('INSERT INTO fts (rowid, body) VALUES (?, ?)'),
|
|
317
|
+
fileDelete: db.prepare('DELETE FROM files WHERE id = ?'),
|
|
318
|
+
vectorDelete: db.prepare('DELETE FROM vectors WHERE id = ?'),
|
|
319
|
+
vectorPut: db.prepare('INSERT INTO vectors (id, key, vec) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET key = excluded.key, vec = excluded.vec'),
|
|
320
|
+
vectorChunk: db.prepare('SELECT id, vec FROM vectors WHERE id > ? ORDER BY id LIMIT ?'),
|
|
321
|
+
lexical: db.prepare('SELECT rowid AS id FROM fts WHERE fts MATCH ? ORDER BY rank LIMIT ?'),
|
|
322
|
+
row: db.prepare('SELECT path, size, mtime, preview, kind FROM files WHERE id = ?'),
|
|
323
|
+
paths: db.prepare('SELECT id, path FROM files'),
|
|
324
|
+
collapsed: db.prepare('SELECT path, kind FROM files WHERE kind IS NOT NULL'),
|
|
325
|
+
fileCount: db.prepare('SELECT count(*) AS n FROM files WHERE kind IS NULL'),
|
|
326
|
+
folderCount: db.prepare('SELECT count(*) AS n FROM files WHERE kind IS NOT NULL'),
|
|
327
|
+
vectorCount: db.prepare('SELECT count(*) AS n FROM vectors'),
|
|
328
|
+
};
|
|
329
|
+
priorityDirs = priorityDirsOf(resolvedRoots);
|
|
330
|
+
migrated = migrateLegacySnapshot();
|
|
331
|
+
collapsed = st.collapsed.all().map((r) => ({ abs: r.path, kind: r.kind }));
|
|
332
|
+
})();
|
|
333
|
+
}
|
|
334
|
+
return opening;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function setEntry(abs, entry) {
|
|
338
|
+
const { id } = st.upsert.get(abs, entry.mtime, entry.size, entry.preview || null, entry.kind || null, entry.secret ? 1 : 0,
|
|
339
|
+
entry.doc ? 1 : 0, isPriority(abs) ? 1 : 0);
|
|
340
|
+
st.ftsDelete.run(id);
|
|
341
|
+
st.ftsInsert.run(id, tokenize(docText(abs, entry)).join(' '));
|
|
342
|
+
return id;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function dropId(id) {
|
|
346
|
+
st.ftsDelete.run(id);
|
|
347
|
+
st.vectorDelete.run(id);
|
|
348
|
+
st.fileDelete.run(id);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Bản chụp gzip của bản cũ (giữ mọi thứ trong RAM) → chép sang SQLite một lần, kể cả vector (khỏi bắt BE tính lại), rồi xoá. */
|
|
352
|
+
function migrateLegacySnapshot() {
|
|
353
|
+
if (!fs.existsSync(LEGACY_SNAPSHOT_FILE)) return 0;
|
|
354
|
+
let count = 0;
|
|
355
|
+
try {
|
|
356
|
+
const data = JSON.parse(zlib.gunzipSync(fs.readFileSync(LEGACY_SNAPSHOT_FILE)).toString('utf8'));
|
|
357
|
+
if (data?.version === LEGACY_SNAPSHOT_VERSION && JSON.stringify(data.roots) === JSON.stringify(resolvedRoots) && !st.fileCount.get().n) {
|
|
358
|
+
let vectors = [];
|
|
359
|
+
try { vectors = JSON.parse(zlib.gunzipSync(fs.readFileSync(LEGACY_VECTORS_FILE)).toString('utf8')).vectors || []; } catch { /* chưa có */ }
|
|
360
|
+
db.transaction(() => {
|
|
361
|
+
const keys = new Map();
|
|
362
|
+
for (const [abs, mtime, size, tokens, preview] of data.entries || []) {
|
|
363
|
+
if (skippedPath(abs)) continue;
|
|
364
|
+
const entry = { mtime, size, tokens, preview, secret: looksSecret(abs), doc: isDocFile(abs) };
|
|
365
|
+
keys.set(abs, { id: setEntry(abs, entry), key: vectorKey(entry) });
|
|
366
|
+
count++;
|
|
367
|
+
}
|
|
368
|
+
for (const [abs, key, b64] of vectors) {
|
|
369
|
+
const file = keys.get(abs);
|
|
370
|
+
if (file && file.key === key && b64) st.vectorPut.run(file.id, key, Buffer.from(b64, 'base64'));
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
} catch { count = 0; /* hỏng → quét lại từ đầu */ }
|
|
375
|
+
for (const f of [LEGACY_SNAPSHOT_FILE, LEGACY_VECTORS_FILE]) fs.rmSync(f, { force: true });
|
|
376
|
+
return count;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Mục đại diện cho thư mục gộp — chỉ ghi khi đổi (mtime thư mục / số mục / loại). */
|
|
380
|
+
function setFolder(f) {
|
|
381
|
+
const prev = st.find.get(f.abs);
|
|
382
|
+
if (prev && prev.kind === f.kind && prev.mtime === f.mtime && prev.size === f.count) return false;
|
|
383
|
+
setEntry(f.abs, { mtime: f.mtime, size: f.count, preview: f.note, tokens: f.words, kind: f.kind });
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Đọc lại một tệp nếu mtime / size đổi. `repo`: nằm trong kho git (tài liệu ở đây không tính vector). `contentOk`: undefined = tệp trong
|
|
389
|
+
* thư mục đám mây thì trả 'cloud' để người gọi hỏi thuộc tính cả lô; false = chỉ lập chỉ mục tên (tệp chỉ có trên mây).
|
|
390
|
+
*/
|
|
391
|
+
async function refreshFile(abs, { repo = false, contentOk } = {}) {
|
|
392
|
+
await ensureOpen();
|
|
393
|
+
const prev = st.find.get(abs);
|
|
394
|
+
let stat;
|
|
395
|
+
try { stat = await fs.promises.stat(abs); } catch {
|
|
396
|
+
if (prev) dropId(prev.id);
|
|
397
|
+
return 'removed';
|
|
398
|
+
}
|
|
399
|
+
if (!stat.isFile()) return 'skipped';
|
|
400
|
+
const mtime = Math.floor(stat.mtimeMs);
|
|
401
|
+
const doc = isDocFile(abs) && !repo;
|
|
402
|
+
if (prev && prev.mtime === mtime && prev.size === stat.size) {
|
|
403
|
+
// Cùng tệp nhưng nay thuộc / không còn thuộc thư mục làm việc người dùng chỉ định → chỉ sửa cờ.
|
|
404
|
+
if (Boolean(prev.doc) !== doc) st.flags.run(doc ? 1 : 0, isPriority(abs) ? 1 : 0, prev.id);
|
|
405
|
+
return 'same';
|
|
406
|
+
}
|
|
407
|
+
if (contentOk === undefined && readsContent(abs) && inCloudFolder(abs)) return 'cloud';
|
|
408
|
+
const read = contentOk !== false;
|
|
409
|
+
const preview = read && isDocFile(abs) ? await extractDocText(abs, stat.size) : '';
|
|
410
|
+
const tokens = read ? await headTokens(abs, stat.size) : '';
|
|
411
|
+
// 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.
|
|
412
|
+
const id = looksSecret(abs, `${preview}\n${tokens}`)
|
|
413
|
+
? setEntry(abs, { mtime, size: stat.size, tokens: '', secret: true, doc })
|
|
414
|
+
: setEntry(abs, { mtime, size: stat.size, tokens, preview, doc });
|
|
415
|
+
st.vectorDelete.run(id);
|
|
416
|
+
return 'updated';
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Lô tệp ở thư mục đám mây: hỏi thuộc tính một lần, tệp chỉ có trên mây chỉ lập chỉ mục tên. */
|
|
420
|
+
async function refreshCloud(list) {
|
|
421
|
+
if (!list.length) return 0;
|
|
422
|
+
const offline = await cloudOnlyFiles(list.map((f) => f.abs));
|
|
423
|
+
let updated = 0;
|
|
424
|
+
await mapLimit(list, STAT_CONCURRENCY, async (f) => {
|
|
425
|
+
if ((await refreshFile(f.abs, { repo: f.repo, contentOk: !offline.has(f.abs) })) === 'updated') updated++;
|
|
426
|
+
});
|
|
427
|
+
return updated;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Lập chỉ mục một cây (gốc / thư mục ưu tiên / thư mục làm việc) → số tệp cập nhật; ghi nhận mọi đường đã thấy vào `found`. */
|
|
431
|
+
async function indexTree(dir, { found, limit, skip, full }) {
|
|
432
|
+
const { files, folders } = await walk(dir, limit, { skip, full, excludes: activeExcludes });
|
|
433
|
+
let updated = 0;
|
|
434
|
+
for (const f of folders) {
|
|
435
|
+
if (found.has(f.abs)) continue;
|
|
436
|
+
found.add(f.abs);
|
|
437
|
+
if (setFolder(f)) updated++;
|
|
438
|
+
}
|
|
439
|
+
const fresh = files.filter((f) => !found.has(f.abs));
|
|
440
|
+
fresh.forEach((f) => found.add(f.abs));
|
|
441
|
+
const cloud = [];
|
|
442
|
+
await mapLimit(fresh, STAT_CONCURRENCY, async (f) => {
|
|
443
|
+
const r = await refreshFile(f.abs, { repo: f.repo });
|
|
444
|
+
if (r === 'updated') updated++;
|
|
445
|
+
else if (r === 'cloud') cloud.push(f);
|
|
446
|
+
});
|
|
447
|
+
return updated + await refreshCloud(cloud);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Quét tăng dần: thư mục làm việc người dùng chỉ định trước, rồi thư mục người dùng, rồi phần còn lại của các gốc. Tệp mới / đổi được đọc
|
|
452
|
+
* lại, tệp không còn thấy bị bỏ.
|
|
453
|
+
*/
|
|
454
|
+
async function build() {
|
|
455
|
+
const startedAt = Date.now();
|
|
456
|
+
const first = !lastBuild;
|
|
457
|
+
await ensureOpen();
|
|
458
|
+
reloadExcludes();
|
|
459
|
+
priorityDirs = priorityDirsOf(resolvedRoots);
|
|
460
|
+
indexFolders = loadIndexFolders();
|
|
461
|
+
const found = new Set();
|
|
462
|
+
let updated = 0;
|
|
463
|
+
const plan = [
|
|
464
|
+
...indexFolders.map((dir) => ({ dir, full: true })),
|
|
465
|
+
...priorityDirs.map((dir) => ({ dir })),
|
|
466
|
+
...resolvedRoots.map((dir) => ({ dir, root: true })),
|
|
467
|
+
];
|
|
468
|
+
for (const { dir, full, root } of plan) {
|
|
469
|
+
if (found.size >= MAX_FILES) break;
|
|
470
|
+
const skip = new Set([...indexFolders.filter((d) => d !== dir), ...(root ? priorityDirs : [])]);
|
|
471
|
+
updated += await indexTree(dir, { found, limit: MAX_FILES - found.size, skip, full });
|
|
472
|
+
}
|
|
473
|
+
// Có trong chỉ mục mà lần quét này không thấy (đã xoá / đổi tên / nay bị bỏ qua) — một lần đọc, không ghi gì cho tệp không đổi.
|
|
474
|
+
const gone = st.paths.all().filter((r) => !found.has(r.path));
|
|
475
|
+
db.transaction(() => { for (const { id } of gone) dropId(id); });
|
|
476
|
+
collapsed = st.collapsed.all().map((r) => ({ abs: r.path, kind: r.kind }));
|
|
477
|
+
lastBuild = {
|
|
478
|
+
files: st.fileCount.get().n, folders: st.folderCount.get().n, updated, removed: gone.length, from_snapshot: first ? migrated : 0,
|
|
479
|
+
capped: found.size >= MAX_FILES, ms: Date.now() - startedAt, at: new Date().toISOString(),
|
|
480
|
+
};
|
|
481
|
+
scheduleVectorize(0);
|
|
482
|
+
return lastBuild;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Tệp bộ theo dõi báo đổi: có lập chỉ mục không, và có nằm trong kho git không. null = bỏ (thư mục ẩn / rác, tệp tạm, trong thư mục ứng
|
|
487
|
+
* dụng, tệp không phải tài liệu trong thư mục hàng loạt hay kho git).
|
|
488
|
+
*/
|
|
489
|
+
/** Phần rẻ của `ruleFor` (không duyệt danh sách thư mục gộp): thư mục / tệp gốc của đường dẫn, null = bỏ ngay. */
|
|
490
|
+
function watchBase(abs) {
|
|
491
|
+
const folder = indexFolders.filter((d) => within(d, abs)).sort((a, b) => b.length - a.length)[0];
|
|
492
|
+
const base = folder || resolvedRoots.find((r) => within(r, abs));
|
|
493
|
+
if (!base || isProtectedPath(abs)) return null;
|
|
494
|
+
const segs = path.relative(base, abs).split(path.sep);
|
|
495
|
+
if (segs.slice(0, -1).some((d) => skipDir(d, activeExcludes)) || skipFile(segs[segs.length - 1], activeExcludes)) return null;
|
|
496
|
+
return { base, folder };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function ruleFor(abs) {
|
|
500
|
+
const hit = watchBase(abs);
|
|
501
|
+
if (!hit) return null;
|
|
502
|
+
const { base, folder } = hit;
|
|
503
|
+
let repo = false;
|
|
504
|
+
for (const c of collapsed) {
|
|
505
|
+
// Chỉ thư mục gộp nằm GIỮA gốc và tệp; gộp bao trùm cả gốc (thư mục làm việc nằm trong một kho git…) không tính.
|
|
506
|
+
if (c.abs === abs || !within(c.abs, abs) || within(c.abs, base)) continue;
|
|
507
|
+
if (c.kind === FolderKind.APP) return null;
|
|
508
|
+
if (c.kind === FolderKind.BULK && path.dirname(abs) === c.abs && !isDocFile(abs)) return null;
|
|
509
|
+
if (c.kind === FolderKind.REPO && !folder) repo = true;
|
|
510
|
+
}
|
|
511
|
+
if (repo && !isDocFile(abs)) return null;
|
|
512
|
+
return { repo };
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function watchDir(dir, fallBackToRescan) {
|
|
516
|
+
if (watchers.has(dir)) return;
|
|
517
|
+
try {
|
|
518
|
+
const w = fs.watch(dir, { recursive: true }, (_event, name) => {
|
|
519
|
+
if (!name) return;
|
|
520
|
+
const abs = path.join(dir, String(name));
|
|
521
|
+
// Lọc ngay (thư mục ẩn / rác / node_modules…, 02/11/2026): sự kiện của đường bị bỏ không giữ lô chờ, không vào tập chờ.
|
|
522
|
+
if (!watchBase(abs)) return;
|
|
523
|
+
batcher?.add(abs);
|
|
524
|
+
});
|
|
525
|
+
// 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.
|
|
526
|
+
w.on('error', () => {
|
|
527
|
+
try { w.close(); } catch { /* đã đóng */ }
|
|
528
|
+
watchers.delete(dir);
|
|
529
|
+
fallBackToRescan();
|
|
530
|
+
});
|
|
531
|
+
w.unref?.();
|
|
532
|
+
watchers.set(dir, w);
|
|
533
|
+
} catch { fallBackToRescan(); /* không theo dõi được (hệ thống tệp mạng…) */ }
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
let rewatch = () => {};
|
|
537
|
+
let batcher = null;
|
|
538
|
+
|
|
539
|
+
function watch() {
|
|
540
|
+
watching = true;
|
|
541
|
+
const run = async (batch) => {
|
|
542
|
+
const cloud = [];
|
|
543
|
+
await mapLimit(batch, STAT_CONCURRENCY, async (abs) => {
|
|
544
|
+
const rule = ruleFor(abs);
|
|
545
|
+
if (!rule) return;
|
|
546
|
+
if ((await refreshFile(abs, { repo: rule.repo })) === 'cloud') cloud.push({ abs, repo: rule.repo });
|
|
547
|
+
});
|
|
548
|
+
await refreshCloud(cloud);
|
|
549
|
+
scheduleVectorize(5_000);
|
|
550
|
+
};
|
|
551
|
+
// Có trần chờ (maxWait) + trần cỡ tập chờ: quá → quét lại tăng dần cả cây thay vì giữ hàng chục nghìn đường dẫn (watchBatcher.mjs).
|
|
552
|
+
batcher?.close();
|
|
553
|
+
batcher = createWatchBatcher({
|
|
554
|
+
debounceMs: WATCH_DEBOUNCE_MS, maxWaitMs: WATCH_MAX_WAIT_MS, maxPending: WATCH_MAX_PENDING,
|
|
555
|
+
onBatch: run, onOverflow: () => build().catch(() => undefined),
|
|
556
|
+
});
|
|
557
|
+
const fallBackToRescan = () => {
|
|
558
|
+
// Bộ theo dõi hỏng: chuyển sang quét lại định kỳ (tăng dần — chỉ đọc tệp có mtime / size đổi).
|
|
559
|
+
if (rescanTimer) return;
|
|
560
|
+
rescanTimer = setInterval(() => void build().catch(() => undefined), RESCAN_MS);
|
|
561
|
+
rescanTimer.unref?.();
|
|
562
|
+
};
|
|
563
|
+
rewatch = () => {
|
|
564
|
+
const want = [...resolvedRoots, ...indexFolders.filter((d) => !resolvedRoots.some((r) => within(r, d)))];
|
|
565
|
+
for (const [dir, w] of watchers) if (!want.includes(dir)) { try { w.close(); } catch { /* đã đóng */ } watchers.delete(dir); }
|
|
566
|
+
for (const dir of want) watchDir(dir, fallBackToRescan);
|
|
567
|
+
};
|
|
568
|
+
rewatch();
|
|
569
|
+
// `aivin remote index add|remove` (tiến trình khác) sửa danh sách → quét lại tăng dần.
|
|
570
|
+
fs.watchFile(INDEX_FOLDERS_FILE, { interval: INDEX_FOLDERS_POLL_MS, persistent: false }, () => {
|
|
571
|
+
if (JSON.stringify(loadIndexFolders()) === JSON.stringify(indexFolders)) return;
|
|
572
|
+
void build().then(() => rewatch()).catch(() => undefined);
|
|
573
|
+
});
|
|
574
|
+
// `aivin remote index-exclude` sửa danh sách mẫu loại trừ → quét lại tăng dần.
|
|
575
|
+
fs.watchFile(INDEX_EXCLUDES_FILE, { interval: INDEX_FOLDERS_POLL_MS, persistent: false }, () => {
|
|
576
|
+
if (JSON.stringify(loadIndexExcludes()) === JSON.stringify(indexExcludes)) return;
|
|
577
|
+
void build().then(() => rewatch()).catch(() => undefined);
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Thư mục làm việc người dùng chỉ định (qua chat → fs.index_folder): lập chỉ mục đầy đủ ngay (kể cả code trong kho git), ưu tiên tính
|
|
583
|
+
* vector, theo dõi thay đổi. Chờ tối đa `waitMs` — quá thì vẫn chạy tiếp ở nền (`done: false`).
|
|
584
|
+
*/
|
|
585
|
+
async function addFolder(dir, { waitMs = 15_000 } = {}) {
|
|
586
|
+
const abs = path.resolve(dir);
|
|
587
|
+
indexFolders = saveIndexFolders([...loadIndexFolders(), abs]);
|
|
588
|
+
await ensureOpen();
|
|
589
|
+
const found = new Set();
|
|
590
|
+
const job = indexTree(abs, { found, limit: MAX_FILES, skip: new Set(indexFolders.filter((d) => d !== abs)), full: true })
|
|
591
|
+
.then((updated) => {
|
|
592
|
+
collapsed = st.collapsed.all().map((r) => ({ abs: r.path, kind: r.kind }));
|
|
593
|
+
if (watching) rewatch();
|
|
594
|
+
scheduleVectorize(1_000);
|
|
595
|
+
return updated;
|
|
596
|
+
});
|
|
597
|
+
let timer;
|
|
598
|
+
const result = await Promise.race([job.then((updated) => ({ done: true, updated })), new Promise((r) => { timer = setTimeout(() => r({ done: false }), waitMs); })]);
|
|
599
|
+
clearTimeout(timer);
|
|
600
|
+
return { folder: abs, folders: indexFolders, indexed: [...found].length, ...result };
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** Bỏ thư mục làm việc: quét lại tăng dần để bỏ những gì chỉ có vì thư mục này (code trong kho git, thư mục ngoài gốc). */
|
|
604
|
+
async function removeFolder(dir) {
|
|
605
|
+
const abs = path.resolve(dir);
|
|
606
|
+
indexFolders = saveIndexFolders(loadIndexFolders().filter((d) => d !== abs));
|
|
607
|
+
const stats = await build();
|
|
608
|
+
if (watching) rewatch();
|
|
609
|
+
return { folder: abs, folders: indexFolders, removed: stats.removed };
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** Đoạn mô tả đưa đi tính vector: tên + thư mục gần nhất + chữ đầu tệp. */
|
|
613
|
+
const embedText = (abs, entry) => `${path.basename(abs)} | ${path.dirname(abs).split(path.sep).slice(-3).join(' / ')}${entry.preview ? ` | ${entry.preview}` : ''}`;
|
|
614
|
+
|
|
615
|
+
/** Tệp tài liệu cần (tính lại) vector: thư mục ưu tiên trước, mới sửa trước; giữ trong trần MAX_VECTOR_FILES. */
|
|
616
|
+
function vectorQueue() {
|
|
617
|
+
const order = 'FROM files WHERE doc = 1 AND secret = 0 ORDER BY prio DESC, mtime DESC LIMIT ?';
|
|
618
|
+
db.prepare(`DELETE FROM vectors WHERE id NOT IN (SELECT id ${order})`).run(MAX_VECTOR_FILES);
|
|
619
|
+
return db.prepare(`SELECT f.id, f.path, f.mtime, f.size, f.preview, v.key AS vkey FROM (SELECT * ${order}) f LEFT JOIN vectors v ON v.id = f.id`)
|
|
620
|
+
.all(MAX_VECTOR_FILES).filter((r) => r.vkey !== vectorKey(r));
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* 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
|
|
625
|
+
* chạy bình thường.
|
|
626
|
+
*/
|
|
627
|
+
async function vectorize() {
|
|
628
|
+
if (!db || !embedder || vectorizing || Date.now() < pausedUntil) return { embedded: 0, total: db ? st.vectorCount.get().n : 0 };
|
|
629
|
+
vectorizing = true;
|
|
630
|
+
let embedded = 0;
|
|
631
|
+
let failed = false;
|
|
632
|
+
try {
|
|
633
|
+
const queue = vectorQueue();
|
|
634
|
+
for (let i = 0; i < queue.length; i += EMBED_BATCH) {
|
|
635
|
+
const batch = queue.slice(i, i + EMBED_BATCH);
|
|
636
|
+
const out = await embedder(batch.map((r) => wellFormed(embedText(r.path, r))));
|
|
637
|
+
if (!Array.isArray(out) || out.length !== batch.length) { failed = true; break; }
|
|
638
|
+
if (!db) break;
|
|
639
|
+
db.transaction(() => batch.forEach((r, j) => { if (out[j]) st.vectorPut.run(r.id, vectorKey(r), Buffer.from(out[j], 'base64')); }));
|
|
640
|
+
embedded += batch.length;
|
|
641
|
+
failures = 0;
|
|
642
|
+
}
|
|
643
|
+
} catch { failed = true; } finally {
|
|
644
|
+
vectorizing = false;
|
|
645
|
+
}
|
|
646
|
+
// 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.
|
|
647
|
+
if (failed) {
|
|
648
|
+
failures++;
|
|
649
|
+
const pauseMs = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (failures - 1));
|
|
650
|
+
pausedUntil = Date.now() + pauseMs;
|
|
651
|
+
scheduleVectorize(pauseMs + 1_000);
|
|
652
|
+
}
|
|
653
|
+
return { embedded, total: db ? st.vectorCount.get().n : 0, failed: failed || undefined };
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
function scheduleVectorize(delayMs) {
|
|
657
|
+
if (!embedder) return;
|
|
658
|
+
clearTimeout(vectorTimer);
|
|
659
|
+
vectorTimer = setTimeout(() => void vectorize(), delayMs);
|
|
660
|
+
vectorTimer.unref?.();
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function setEmbedder(fn) {
|
|
664
|
+
embedder = fn;
|
|
665
|
+
if (lastBuild) scheduleVectorize(2_000);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function close() {
|
|
669
|
+
if (rescanTimer) { clearInterval(rescanTimer); rescanTimer = null; }
|
|
670
|
+
for (const w of watchers.values()) { try { w.close(); } catch { /* đã đóng */ } }
|
|
671
|
+
watchers.clear();
|
|
672
|
+
batcher?.close();
|
|
673
|
+
batcher = null;
|
|
674
|
+
if (watching) {
|
|
675
|
+
fs.unwatchFile(INDEX_FOLDERS_FILE);
|
|
676
|
+
fs.unwatchFile(INDEX_EXCLUDES_FILE);
|
|
677
|
+
}
|
|
678
|
+
watching = false;
|
|
679
|
+
clearTimeout(vectorTimer);
|
|
680
|
+
try { db?.close(); } catch { /* đã đóng */ }
|
|
681
|
+
db = null;
|
|
682
|
+
opening = null;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** Từ khoá → FTS5: mỗi từ một vế OR; từ ≥ PREFIX_MIN ký tự khớp cả tiền tố ("auth" ↔ "authentication"). Từ chỉ có chữ / số — không cần thoát. */
|
|
686
|
+
const matchExpr = (query) => [...new Set(tokenize(query))].map((t) => `"${t}"${t.length >= PREFIX_MIN ? '*' : ''}`).join(' OR ');
|
|
687
|
+
|
|
688
|
+
/** Vector gần câu hỏi nhất: quét bảng theo khúc (không giữ cả bảng trong RAM). */
|
|
689
|
+
function nearest(q, depth) {
|
|
690
|
+
let top = [];
|
|
691
|
+
for (let after = 0; ;) {
|
|
692
|
+
const rows = st.vectorChunk.all(after, VECTOR_SCAN_CHUNK);
|
|
693
|
+
for (const r of rows) top.push([r.id, int8Cosine(q, new Int8Array(r.vec.buffer, r.vec.byteOffset, r.vec.byteLength))]);
|
|
694
|
+
top = top.sort((a, b) => b[1] - a[1]).slice(0, depth);
|
|
695
|
+
if (rows.length < VECTOR_SCAN_CHUNK) return top;
|
|
696
|
+
after = rows[rows.length - 1].id;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* 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ữ
|
|
702
|
+
* nghĩa. Trả đường hiển thị (tương đối với gốc; thư mục làm việc ngoài gốc thì tuyệt đối) + dung lượng, ngày sửa, đoạn xem trước; thư mục
|
|
703
|
+
* gộp có `type: 'folder'` + `note`. `abs` = đường tuyệt đối (để gộp với kết quả của bộ tìm hệ điều hành).
|
|
704
|
+
*/
|
|
705
|
+
function search(query, limit = 10, vector) {
|
|
706
|
+
if (!db) return [];
|
|
707
|
+
const depth = Math.max(limit, RANK_DEPTH);
|
|
708
|
+
const words = [...new Set(tokenize(query))];
|
|
709
|
+
let lexical = [];
|
|
710
|
+
if (words.length > 1) {
|
|
711
|
+
const andExpr = words.map((t) => `"${t}"${t.length >= PREFIX_MIN ? '*' : ''}`).join(' AND ');
|
|
712
|
+
const orExpr = words.map((t) => `"${t}"${t.length >= PREFIX_MIN ? '*' : ''}`).join(' OR ');
|
|
713
|
+
const andHits = st.lexical.all(andExpr, depth).map((r) => r.id);
|
|
714
|
+
const orHits = st.lexical.all(orExpr, depth).map((r) => r.id);
|
|
715
|
+
lexical = [...new Set([...andHits, ...orHits])].slice(0, depth);
|
|
716
|
+
} else if (words.length === 1) {
|
|
717
|
+
const expr = matchExpr(query);
|
|
718
|
+
lexical = expr ? st.lexical.all(expr, depth).map((r) => r.id) : [];
|
|
719
|
+
}
|
|
720
|
+
const q = vector ? decodeInt8(vector) : null;
|
|
721
|
+
const semantic = q ? nearest(q, RANK_DEPTH) : [];
|
|
722
|
+
const similarity = new Map(semantic);
|
|
723
|
+
const ranked = semantic.length ? fuse(lexical, semantic.map(([id]) => id), similarity) : lexical;
|
|
724
|
+
return ranked.slice(0, limit).flatMap((id) => {
|
|
725
|
+
const e = st.row.get(id);
|
|
726
|
+
if (!e) return [];
|
|
727
|
+
const root = resolvedRoots.find((r) => within(r, e.path));
|
|
728
|
+
const modified = e.mtime ? new Date(e.mtime).toISOString().slice(0, 10) : undefined;
|
|
729
|
+
const shown = root ? path.relative(root, e.path) || e.path : e.path;
|
|
730
|
+
if (e.kind) return [{ path: shown, abs: e.path, type: 'folder', kind: e.kind, items: e.size, modified, note: e.preview }];
|
|
731
|
+
return [{
|
|
732
|
+
path: shown, abs: e.path, size: e.size, modified,
|
|
733
|
+
...(e.preview ? { preview: e.preview.slice(0, 200) } : {}),
|
|
734
|
+
...(similarity.has(id) ? { similarity: Number(similarity.get(id).toFixed(3)) } : {}),
|
|
735
|
+
}];
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
return {
|
|
740
|
+
build, watch, close, search, refreshFile, vectorize, setEmbedder, addFolder, removeFolder,
|
|
741
|
+
folders: () => [...indexFolders],
|
|
742
|
+
excludes: () => [...activeExcludes],
|
|
743
|
+
addExclude: async (pattern) => {
|
|
744
|
+
saveIndexExcludes([...loadIndexExcludes(), pattern]);
|
|
745
|
+
reloadExcludes();
|
|
746
|
+
return build();
|
|
747
|
+
},
|
|
748
|
+
removeExclude: async (pattern) => {
|
|
749
|
+
saveIndexExcludes(loadIndexExcludes().filter((e) => e.toLowerCase() !== pattern.toLowerCase()));
|
|
750
|
+
reloadExcludes();
|
|
751
|
+
return build();
|
|
752
|
+
},
|
|
753
|
+
stats: () => ({
|
|
754
|
+
files: db ? st.fileCount.get().n : 0, folders: db ? st.folderCount.get().n : 0, vectors: db ? st.vectorCount.get().n : 0,
|
|
755
|
+
index_folders: [...indexFolders], index_excludes: [...activeExcludes], last_build: lastBuild,
|
|
756
|
+
}),
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* 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á
|
|
762
|
+
* chỉ trùng một chữ chung ("thuê") hay gặp hơn là trùng nghĩa.
|
|
763
|
+
*/
|
|
764
|
+
function fuse(lexical, semantic, similarity) {
|
|
765
|
+
const score = new Map();
|
|
766
|
+
for (const list of [lexical, semantic]) list.forEach((id, rank) => score.set(id, (score.get(id) || 0) + 1 / (RRF_K + rank + 1)));
|
|
767
|
+
return [...score.keys()].sort((a, b) => (score.get(b) - score.get(a)) || ((similarity.get(b) ?? -1) - (similarity.get(a) ?? -1)));
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** 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). */
|
|
771
|
+
export function indexRootsFor(roots, fullAccess) {
|
|
772
|
+
return fullAccess ? [os.homedir()] : roots;
|
|
773
|
+
}
|