@aivin-labs/cli 1.0.5 → 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 -1366
- package/bin/lib/browserAutomation.mjs +655 -648
- package/bin/lib/browserTui.mjs +276 -251
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/mcpProxy.mjs +869 -837
- package/bin/lib/missionStream.mjs +696 -691
- 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/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/docs/CLI.md +1353 -1299
- package/package.json +71 -62
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import net from 'net';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { execFile } from 'child_process';
|
|
5
|
+
import WSClient from 'ws';
|
|
6
|
+
import { LOCAL_BROWSERS, resolveBrowserInstall } from '../browserAutomation.mjs';
|
|
7
|
+
import { applyDevicePolicy, executableDownloadGuid } from './cdpPolicy.mjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Trình duyệt HẰNG NGÀY của người dùng cho AI Browser (27/10/2026) — dùng sẵn mọi đăng nhập, không phải đăng nhập lại trong cửa sổ Aivin.
|
|
11
|
+
*
|
|
12
|
+
* Chrome 136+ không cho `--remote-debugging-port` trên hồ sơ mặc định. Cách Chrome / Edge cho phép (Chrome 144+): người dùng tự bật "Allow remote
|
|
13
|
+
* debugging for this browser instance" ở `chrome://inspect/#remote-debugging` (Edge: `edge://inspect` → Remote debugging); trình duyệt ghi cổng +
|
|
14
|
+
* đường dẫn WebSocket vào `<thư mục dữ liệu>/DevToolsActivePort`, và MỖI kết nối mới hiện hộp thoại xin phép. Vì vậy CLI giữ MỘT kết nối duy nhất
|
|
15
|
+
* (người dùng bấm Cho phép một lần) và chia cho mọi đường hầm: mỗi đường hầm một phiên trình duyệt riêng (`Target.attachToBrowserTarget`, chế độ
|
|
16
|
+
* phiên phẳng) — Puppeteer phía BE thấy như một kết nối gốc của riêng nó.
|
|
17
|
+
*
|
|
18
|
+
* Lớp bảo vệ trình duyệt của người dùng (không phải cửa sổ riêng của Aivin) — DANH SÁCH CHO PHÉP (rà 28/10/2026: danh sách chặn cũ để lọt
|
|
19
|
+
* `Network.enable` trên tab người dùng → lộ header / cookie / dữ liệu gửi đi, `Target.exposeDevToolsProtocol` mở kênh CDP ngoài tầm lọc…):
|
|
20
|
+
* - phiên trình duyệt của đường hầm: chỉ các lệnh `Target.*` / `Browser.*` Puppeteer cần (`BROWSER_SESSION_ALLOWED`);
|
|
21
|
+
* - tab KHÔNG do AI mở (tab của người dùng): chỉ khởi động / gỡ phiên gắn (`USER_TAB_ALLOWED`) — không bật miền nào, không điều hướng, gõ, bấm,
|
|
22
|
+
* chạy script, đóng;
|
|
23
|
+
* - tab AI mở: điều khiển như thường, trừ lệnh đụng kho cookie / dữ liệu của cả hồ sơ (`DAILY_BLOCKED`);
|
|
24
|
+
* - cộng bộ lọc chung `cdpPolicy.mjs` (không `file://`, ép thư mục tải, không chọn tệp trên đĩa…).
|
|
25
|
+
* Tab mới mở ở nền (không giật tiêu điểm khỏi việc người dùng đang làm).
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Chờ người dùng bấm Cho phép trên hộp thoại của trình duyệt. Cộng thời gian mở cửa sổ Aivin (dự phòng) phải nằm gọn trong `open_timeout_ms` 45 s
|
|
30
|
+
* của máy chủ — trước 28/10/2026 chờ 35 s + mở cửa sổ ~10 s vượt trần, nhiệm vụ hỏng thay vì chuyển sang cửa sổ Aivin.
|
|
31
|
+
*/
|
|
32
|
+
export const CONSENT_TIMEOUT_MS = 20_000;
|
|
33
|
+
/** Không còn đường hầm nào bấy nhiêu lâu → nhả kết nối (thanh "đang bị điều khiển" biến mất; lần sau hỏi lại). */
|
|
34
|
+
export const IDLE_CLOSE_MS = 30 * 60_000;
|
|
35
|
+
|
|
36
|
+
/** Phiên trình duyệt của một đường hầm: chỉ quản lý tab / phiên — các lệnh khác ở cấp trình duyệt đụng tới cả hồ sơ của người dùng. */
|
|
37
|
+
const BROWSER_SESSION_ALLOWED = new Set([
|
|
38
|
+
'Target.setDiscoverTargets', 'Target.setAutoAttach', 'Target.getTargets', 'Target.getTargetInfo', 'Target.createTarget', 'Target.closeTarget',
|
|
39
|
+
'Target.activateTarget', 'Target.attachToTarget', 'Target.detachFromTarget', 'Target.getBrowserContexts', 'Target.createBrowserContext',
|
|
40
|
+
'Target.disposeBrowserContext', 'Browser.getVersion', 'Browser.getWindowForTarget', 'Browser.cancelDownload',
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/** Tab của người dùng (không do AI mở): Puppeteer tự gắn mọi tab để biết danh sách — chỉ cho khởi động lại tab đang chờ và gỡ phiên. */
|
|
44
|
+
const USER_TAB_ALLOWED = new Set([
|
|
45
|
+
'Runtime.runIfWaitingForDebugger', 'Target.setAutoAttach', 'Target.detachFromTarget', 'Runtime.releaseObject', 'Runtime.releaseObjectGroup',
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
/** Kể cả trên tab AI mở: kho cookie / dữ liệu / cửa sổ của cả hồ sơ người dùng (cookie httpOnly của mọi site đã đăng nhập). */
|
|
49
|
+
const DAILY_BLOCKED = new Set([
|
|
50
|
+
'Network.getAllCookies', 'Network.getCookies', 'Network.setCookie', 'Network.setCookies', 'Network.deleteCookies', 'Network.clearBrowserCookies',
|
|
51
|
+
'Network.clearBrowserCache', 'Storage.getCookies', 'Storage.setCookies', 'Storage.clearCookies', 'Storage.clearDataForOrigin',
|
|
52
|
+
'Storage.clearDataForStorageKey', 'Browser.grantPermissions', 'Browser.resetPermissions', 'Browser.setPermission', 'Browser.setWindowBounds',
|
|
53
|
+
'Browser.setDownloadBehavior', 'Tracing.start',
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
/** Trang người dùng bật "cho phép gỡ lỗi từ xa" của trình duyệt (Edge dùng tiền tố riêng). */
|
|
57
|
+
export function remoteDebuggingPage(browserId) {
|
|
58
|
+
return browserId === 'edge' ? 'edge://inspect/#remote-debugging' : 'chrome://inspect/#remote-debugging';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** `DevToolsActivePort`: dòng 1 cổng, dòng 2 đường dẫn WebSocket (`/devtools/browser/<id>`). Không có / sai → null. */
|
|
62
|
+
export function parseDevToolsActivePort(text) {
|
|
63
|
+
const [portLine, pathLine] = String(text || '').split(/\r?\n/);
|
|
64
|
+
const port = Number(portLine);
|
|
65
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535 || !/^\/devtools\/browser\/[\w-]+$/.test(String(pathLine || '').trim())) return null;
|
|
66
|
+
return { port, path: pathLine.trim() };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function portOpen(port, timeoutMs = 800) {
|
|
70
|
+
return new Promise((resolve) => {
|
|
71
|
+
const socket = net.connect({ host: '127.0.0.1', port });
|
|
72
|
+
const done = (ok) => { socket.destroy(); resolve(ok); };
|
|
73
|
+
socket.setTimeout(timeoutMs, () => done(false));
|
|
74
|
+
socket.once('connect', () => done(true));
|
|
75
|
+
socket.once('error', () => done(false));
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Đầu nối CDP của trình duyệt đang chạy trên thư mục dữ liệu `dir` (theo `DevToolsActivePort`, cổng đang nghe) — không có → null. */
|
|
80
|
+
export async function activeBrowserEndpoint(dir, { isOpen = portOpen } = {}) {
|
|
81
|
+
let active;
|
|
82
|
+
try {
|
|
83
|
+
active = parseDevToolsActivePort(await fs.promises.readFile(path.join(dir, 'DevToolsActivePort'), 'utf8'));
|
|
84
|
+
} catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
if (!active || !(await isOpen(active.port))) return null;
|
|
88
|
+
return { port: active.port, wsUrl: `ws://127.0.0.1:${active.port}${active.path}` };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Cổng gỡ lỗi trong DÒNG LỆNH của một tiến trình trình duyệt chạy đúng thư mục dữ liệu `dir` (`--user-data-dir=<dir>` +
|
|
93
|
+
* `--remote-debugging-port=<cổng>`, cổng 0 thì không tính). Sai thư mục / không có cổng → null. So đường dẫn không phân biệt hoa thường,
|
|
94
|
+
* bỏ dấu nháy và dấu `\`/`/` cuối.
|
|
95
|
+
*/
|
|
96
|
+
export function debugPortFromCommandLine(commandLine, dir) {
|
|
97
|
+
const cmd = String(commandLine || '');
|
|
98
|
+
const norm = (p) => String(p || '').replace(/^["']|["']$/g, '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
|
|
99
|
+
const dataDir = /--user-data-dir=("[^"]+"|'[^']+'|\S+)/.exec(cmd)?.[1];
|
|
100
|
+
if (!dataDir || norm(dataDir) !== norm(dir)) return null;
|
|
101
|
+
const port = Number(/--remote-debugging-port=(\d+)/.exec(cmd)?.[1]);
|
|
102
|
+
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function listProcessCommandLines() {
|
|
106
|
+
return new Promise((resolve) => {
|
|
107
|
+
const [cmd, args] = process.platform === 'win32'
|
|
108
|
+
? ['powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', "Get-CimInstance Win32_Process -Filter \"Name='msedge.exe' OR Name='chrome.exe' OR Name='brave.exe'\" | ForEach-Object { $_.CommandLine }"]]
|
|
109
|
+
: ['ps', ['-axo', 'args=']];
|
|
110
|
+
execFile(cmd, args, { windowsHide: true, timeout: 8000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout) => resolve(err ? [] : String(stdout).split(/\r?\n/)));
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Trình duyệt đang chạy trên thư mục dữ liệu `dir` mà KHÔNG có `DevToolsActivePort` (28/10/2026: Edge 156 mở với cổng cố định không ghi
|
|
116
|
+
* tệp này → CLI tưởng chưa có cửa sổ, mở thêm Edge cùng hồ sơ, tiến trình mới chỉ chuyển giao cho cửa sổ cũ rồi thoát — mọi nhiệm vụ sau lần
|
|
117
|
+
* đầu báo "debug port never came up"). Tìm theo dòng lệnh tiến trình: chỉ nhận đúng thư mục `dir`, không nhận bừa trình duyệt khác đang mở
|
|
118
|
+
* cổng gỡ lỗi. Trả cổng đang nghe, không có → null.
|
|
119
|
+
*/
|
|
120
|
+
export async function browserPortFromProcesses(dir, { list = listProcessCommandLines, isOpen = portOpen } = {}) {
|
|
121
|
+
const ports = [...new Set((await list()).map((line) => debugPortFromCommandLine(line, dir)).filter(Boolean))];
|
|
122
|
+
for (const port of ports) if (await isOpen(port)) return port;
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Chrome / Edge hằng ngày đang chạy và đã bật gỡ lỗi từ xa (có `DevToolsActivePort` trong thư mục dữ liệu mặc định, cổng đang nghe). Trình duyệt
|
|
128
|
+
* mặc định / đã chọn xét trước. Không có → null (dùng cửa sổ riêng của Aivin).
|
|
129
|
+
*/
|
|
130
|
+
export async function findDailyBrowser(preferredId, { browsers = LOCAL_BROWSERS, resolve = resolveBrowserInstall, isOpen = portOpen } = {}) {
|
|
131
|
+
const ordered = [...browsers].sort((a, b) => Number(b.id === preferredId) - Number(a.id === preferredId));
|
|
132
|
+
for (const b of ordered) {
|
|
133
|
+
const install = resolve(b);
|
|
134
|
+
if (!install?.profileDir) continue;
|
|
135
|
+
const active = await activeBrowserEndpoint(install.profileDir, { isOpen });
|
|
136
|
+
if (active) return { id: install.id, name: install.name, wsUrl: active.wsUrl };
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Một kết nối tới trình duyệt hằng ngày, chia cho nhiều đường hầm. `connect()` mở (hoặc dùng lại) kết nối — lần đầu trình duyệt hỏi người dùng;
|
|
143
|
+
* `attach(toClient, onClose)` → đường hầm mới `{ send(text), close() }`.
|
|
144
|
+
*/
|
|
145
|
+
export function createCdpMux({ wsUrl, downloadsDir, consentTimeoutMs = CONSENT_TIMEOUT_MS, idleCloseMs = IDLE_CLOSE_MS, WebSocketImpl = WSClient, onClosed = () => {}, onBlocked = () => {} }) {
|
|
146
|
+
let upstream = null;
|
|
147
|
+
let opening = null;
|
|
148
|
+
let nextId = 1;
|
|
149
|
+
let idleTimer = null;
|
|
150
|
+
const pending = new Map();
|
|
151
|
+
/**
|
|
152
|
+
* sessionId → { client, targetId?, type?, parent?, aivin } — phiên do mux mở cho đường hầm (phiên trình duyệt) hoặc trình duyệt gắn vào sau.
|
|
153
|
+
* Puppeteer ≥ 23 gắn theo hai lớp: phiên `tab` → bên trong là phiên `page`. Chuyển sang tên miền khác (Google chuyển hướng qua accounts.google.com)
|
|
154
|
+
* trình duyệt đổi sang một đích `page` MỚI trong cùng tab — nhận là của AI nhờ phiên `tab` cha (chạy thật 28/10/2026: không nhận → mọi lệnh trên
|
|
155
|
+
* trang mới bị chặn như tab của người dùng, điều hướng treo 30 s).
|
|
156
|
+
*/
|
|
157
|
+
const sessions = new Map();
|
|
158
|
+
/** Tab AI mở (và tab bật ra từ chúng) — chỉ những tab này được điều khiển / đóng. */
|
|
159
|
+
const aivinTargets = new Set();
|
|
160
|
+
const clients = new Set();
|
|
161
|
+
let downloadsTouched = false;
|
|
162
|
+
|
|
163
|
+
const rootCall = (method, params = {}) => new Promise((resolve, reject) => {
|
|
164
|
+
if (!upstream || upstream.readyState !== WebSocketImpl.OPEN) { reject(new Error('Browser connection closed')); return; }
|
|
165
|
+
const id = nextId++;
|
|
166
|
+
pending.set(id, { resolve, reject });
|
|
167
|
+
upstream.send(JSON.stringify({ id, method, params }));
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
const shutdown = () => {
|
|
171
|
+
clearTimeout(idleTimer);
|
|
172
|
+
for (const p of pending.values()) p.reject(new Error('Browser connection closed'));
|
|
173
|
+
pending.clear();
|
|
174
|
+
for (const c of [...clients]) c.close();
|
|
175
|
+
sessions.clear();
|
|
176
|
+
upstream = null;
|
|
177
|
+
opening = null;
|
|
178
|
+
onClosed();
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const armIdle = () => {
|
|
182
|
+
clearTimeout(idleTimer);
|
|
183
|
+
if (clients.size || !idleCloseMs) return;
|
|
184
|
+
idleTimer = setTimeout(() => { try { upstream?.close(); } catch { /* đã đóng */ } }, idleCloseMs);
|
|
185
|
+
idleTimer.unref?.();
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const isAivinSession = (sid) => !!sessions.get(sid)?.aivin;
|
|
189
|
+
/** Tab của AI — kể cả phiên đã gắn trước khi kết quả `createTarget` về (tự gắn chạy ngay lúc tạo tab). */
|
|
190
|
+
const markAivin = (targetId) => {
|
|
191
|
+
aivinTargets.add(targetId);
|
|
192
|
+
for (const [sid, s] of sessions) {
|
|
193
|
+
if (s.targetId !== targetId) continue;
|
|
194
|
+
s.aivin = true;
|
|
195
|
+
markTabAivin(s.type === 'tab' ? sid : s.parent);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
/** Tab chứa trang của AI thuộc AI — mọi trang con của nó (kể cả trang mới sau khi đổi tên miền) cũng vậy. */
|
|
199
|
+
const markTabAivin = (sid) => {
|
|
200
|
+
const tab = sid ? sessions.get(sid) : null;
|
|
201
|
+
if (!tab || tab.type !== 'tab') return;
|
|
202
|
+
tab.aivin = true;
|
|
203
|
+
if (tab.targetId) aivinTargets.add(tab.targetId);
|
|
204
|
+
for (const s of sessions.values()) {
|
|
205
|
+
if (s.parent !== sid || s.aivin) continue;
|
|
206
|
+
s.aivin = true;
|
|
207
|
+
if (s.targetId) aivinTargets.add(s.targetId);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const onUpstreamMessage = (data) => {
|
|
212
|
+
// Tệp chạy được AI bắt đầu tải → huỷ ngay (không để nằm lại trong thư mục tải của người dùng).
|
|
213
|
+
const execGuid = executableDownloadGuid(data);
|
|
214
|
+
if (execGuid) rootCall('Browser.cancelDownload', { guid: execGuid }).catch(() => undefined);
|
|
215
|
+
let msg;
|
|
216
|
+
try { msg = JSON.parse(String(data)); } catch { return; }
|
|
217
|
+
if (!msg.sessionId) {
|
|
218
|
+
const p = msg.id !== undefined ? pending.get(msg.id) : null;
|
|
219
|
+
if (p) {
|
|
220
|
+
pending.delete(msg.id);
|
|
221
|
+
if (msg.error) p.reject(new Error(msg.error.message || 'CDP error'));
|
|
222
|
+
else p.resolve(msg.result || {});
|
|
223
|
+
}
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const owner = sessions.get(msg.sessionId);
|
|
227
|
+
if (!owner) return;
|
|
228
|
+
const { client } = owner;
|
|
229
|
+
track(client, msg);
|
|
230
|
+
const out = msg.sessionId === client.browserSession ? (({ sessionId: _s, ...rest }) => rest)(msg) : msg;
|
|
231
|
+
client.toClient(JSON.stringify(out));
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/** Ghi sổ phiên / tab của AI theo kết quả + sự kiện trình duyệt gửi về. */
|
|
235
|
+
const track = (client, msg) => {
|
|
236
|
+
const key = `${msg.sessionId}:${msg.id}`;
|
|
237
|
+
if (msg.id !== undefined) {
|
|
238
|
+
const req = client.requests.get(key);
|
|
239
|
+
client.requests.delete(key);
|
|
240
|
+
if (req && msg.result) {
|
|
241
|
+
if (req.method === 'Target.createTarget' && msg.result.targetId) markAivin(msg.result.targetId);
|
|
242
|
+
if (req.method === 'Target.attachToTarget' && msg.result.sessionId) {
|
|
243
|
+
sessions.set(msg.result.sessionId, { client, targetId: req.targetId, aivin: aivinTargets.has(req.targetId) });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const params = msg.params || {};
|
|
249
|
+
if (msg.method === 'Target.targetCreated' && aivinTargets.has(params.targetInfo?.openerId)) markAivin(params.targetInfo.targetId);
|
|
250
|
+
if (msg.method === 'Target.attachedToTarget' && params.sessionId) {
|
|
251
|
+
const targetId = params.targetInfo?.targetId;
|
|
252
|
+
// Khung con / worker của tab AI thuộc AI; tab bật ra từ tab AI cũng vậy.
|
|
253
|
+
const parent = msg.sessionId !== client.browserSession ? msg.sessionId : undefined;
|
|
254
|
+
const aivin = aivinTargets.has(targetId) || aivinTargets.has(params.targetInfo?.openerId) || (!!parent && isAivinSession(parent));
|
|
255
|
+
if (aivin && targetId) aivinTargets.add(targetId);
|
|
256
|
+
sessions.set(params.sessionId, { client, targetId, type: params.targetInfo?.type, parent, aivin });
|
|
257
|
+
if (aivin) markTabAivin(params.targetInfo?.type === 'tab' ? params.sessionId : parent);
|
|
258
|
+
}
|
|
259
|
+
if (msg.method === 'Target.detachedFromTarget' && params.sessionId) sessions.delete(params.sessionId);
|
|
260
|
+
if (msg.method === 'Target.targetDestroyed' && params.targetId) aivinTargets.delete(params.targetId);
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/** Lý do chặn một lệnh của đường hầm (null = cho qua). */
|
|
264
|
+
const blockReason = (client, sid, method, params) => {
|
|
265
|
+
if (DAILY_BLOCKED.has(method)) return `${method} is not allowed on the user's own browser`;
|
|
266
|
+
if (method === 'Target.detachFromTarget' && params.sessionId && sessions.get(params.sessionId)?.client !== client) return 'Unknown session';
|
|
267
|
+
if (sid === client.browserSession) {
|
|
268
|
+
if (!BROWSER_SESSION_ALLOWED.has(method)) return `${method} is not allowed on the user's own browser`;
|
|
269
|
+
if (method === 'Target.closeTarget' && !aivinTargets.has(params.targetId)) return 'Only tabs opened by Aivin can be closed';
|
|
270
|
+
if (method === 'Target.activateTarget' && !aivinTargets.has(params.targetId)) return 'Only tabs opened by Aivin can be focused';
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
if (!sessions.get(sid)?.aivin && !USER_TAB_ALLOWED.has(method)) return `Tabs not opened by Aivin are read-only (${method})`;
|
|
274
|
+
return null;
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
const connect = () => {
|
|
278
|
+
if (upstream && upstream.readyState === WebSocketImpl.OPEN) return Promise.resolve();
|
|
279
|
+
if (opening) return opening;
|
|
280
|
+
opening = new Promise((resolve, reject) => {
|
|
281
|
+
const ws = new WebSocketImpl(wsUrl, { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024, handshakeTimeout: consentTimeoutMs });
|
|
282
|
+
let settled = false;
|
|
283
|
+
const fail = (e) => {
|
|
284
|
+
if (settled) return;
|
|
285
|
+
settled = true;
|
|
286
|
+
try { ws.terminate?.(); } catch { /* đã đóng */ }
|
|
287
|
+
opening = null;
|
|
288
|
+
reject(e);
|
|
289
|
+
};
|
|
290
|
+
const timer = setTimeout(() => fail(new Error('The browser did not allow the connection in time')), consentTimeoutMs);
|
|
291
|
+
ws.once('error', (e) => { clearTimeout(timer); fail(e); });
|
|
292
|
+
ws.once('unexpected-response', (_req, res) => { clearTimeout(timer); fail(new Error(`HTTP ${res?.statusCode}`)); });
|
|
293
|
+
ws.once('open', () => {
|
|
294
|
+
upstream = ws;
|
|
295
|
+
ws.on('message', onUpstreamMessage);
|
|
296
|
+
ws.on('close', () => { if (upstream === ws) shutdown(); });
|
|
297
|
+
// Hộp thoại xin phép có thể hiện SAU khi bắt tay: chờ lệnh đầu tiên được trả lời mới coi là đã cho phép.
|
|
298
|
+
rootCall('Browser.getVersion').then(() => {
|
|
299
|
+
clearTimeout(timer);
|
|
300
|
+
if (settled) return;
|
|
301
|
+
settled = true;
|
|
302
|
+
opening = null;
|
|
303
|
+
armIdle();
|
|
304
|
+
resolve();
|
|
305
|
+
}, (e) => { clearTimeout(timer); fail(e); });
|
|
306
|
+
});
|
|
307
|
+
});
|
|
308
|
+
return opening;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
/** Đường hầm mới trên kết nối chung: một phiên trình duyệt riêng. */
|
|
312
|
+
const attach = async (toClient, onClose = () => {}) => {
|
|
313
|
+
await connect();
|
|
314
|
+
const { sessionId } = await rootCall('Target.attachToBrowserTarget');
|
|
315
|
+
let closed = false;
|
|
316
|
+
const client = {
|
|
317
|
+
browserSession: sessionId,
|
|
318
|
+
requests: new Map(),
|
|
319
|
+
toClient: (text) => { if (!closed) toClient(text); },
|
|
320
|
+
send(text) {
|
|
321
|
+
if (closed) return;
|
|
322
|
+
let msg;
|
|
323
|
+
try { msg = JSON.parse(String(text)); } catch { return; }
|
|
324
|
+
const sid = msg.sessionId || client.browserSession;
|
|
325
|
+
const owned = sessions.get(sid)?.client === client;
|
|
326
|
+
const policy = applyDevicePolicy(msg, { downloadsDir });
|
|
327
|
+
if (policy.msg) msg = policy.msg;
|
|
328
|
+
const params = msg.params || {};
|
|
329
|
+
const reason = policy.error || (owned ? blockReason(client, sid, msg.method, params) : 'Unknown session');
|
|
330
|
+
if (reason) {
|
|
331
|
+
onBlocked({ method: msg.method, reason, targetId: sessions.get(sid)?.targetId });
|
|
332
|
+
if (msg.id !== undefined) toClient(JSON.stringify({ id: msg.id, ...(msg.sessionId ? { sessionId: msg.sessionId } : {}), error: { code: -32000, message: reason } }));
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (msg.id !== undefined) client.requests.set(`${sid}:${msg.id}`, { method: msg.method, targetId: params.targetId });
|
|
336
|
+
// Thư mục tải đặt qua một trang áp cho cả hồ sơ: nhớ để trả về mặc định khi đường hầm cuối cùng đóng (tệp người dùng tự tải về đúng chỗ cũ).
|
|
337
|
+
if (msg.method === 'Page.setDownloadBehavior') client.setDownloads = true;
|
|
338
|
+
// Tab mới mở ở nền: không giật tiêu điểm khỏi cửa sổ người dùng đang làm việc.
|
|
339
|
+
const outParams = msg.method === 'Target.createTarget' && params.background === undefined ? { ...params, background: true } : msg.params;
|
|
340
|
+
upstream?.send(JSON.stringify({ ...msg, ...(outParams ? { params: outParams } : {}), sessionId: sid }));
|
|
341
|
+
},
|
|
342
|
+
close() {
|
|
343
|
+
if (closed) return;
|
|
344
|
+
closed = true;
|
|
345
|
+
clients.delete(client);
|
|
346
|
+
for (const [sid, s] of [...sessions]) if (s.client === client) sessions.delete(sid);
|
|
347
|
+
client.requests.clear();
|
|
348
|
+
if (client.setDownloads) downloadsTouched = true;
|
|
349
|
+
if (downloadsTouched && !clients.size) {
|
|
350
|
+
downloadsTouched = false;
|
|
351
|
+
rootCall('Browser.setDownloadBehavior', { behavior: 'default' }).catch(() => undefined);
|
|
352
|
+
}
|
|
353
|
+
rootCall('Target.detachFromTarget', { sessionId }).catch(() => undefined);
|
|
354
|
+
armIdle();
|
|
355
|
+
onClose();
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
sessions.set(sessionId, { client, aivin: false });
|
|
359
|
+
clients.add(client);
|
|
360
|
+
clearTimeout(idleTimer);
|
|
361
|
+
return client;
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
return {
|
|
365
|
+
connect,
|
|
366
|
+
attach,
|
|
367
|
+
close: () => { try { upstream?.close(); } catch { /* đã đóng */ } },
|
|
368
|
+
isOpen: () => !!upstream && upstream.readyState === WebSocketImpl.OPEN,
|
|
369
|
+
clientCount: () => clients.size,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { createHash } from 'crypto';
|
|
4
|
+
import YAML from 'yaml';
|
|
5
|
+
import { MemoryKind, REMOTE_CONFIG_DIR } from './constants.mjs';
|
|
6
|
+
import { createTextIndex, decodeInt8, fuseRankings, int8Cosine } from './textIndex.mjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Bộ nhớ dài hạn NẰM TRÊN MÁY. Nguồn sự thật là các tệp YAML người dùng đọc / sửa tay được (`~/.aivin/memory/<loại>.yaml`), vector
|
|
10
|
+
* (do BE tính bằng bge-m3, int8 base64) để ở tệp riêng `vectors.json` khoá theo băm nội dung — sửa nội dung một mục thì vector cũ tự
|
|
11
|
+
* bỏ, mục đó vẫn tìm được bằng từ khoá. Daemon nạp hết vào RAM: tìm kết hợp BM25 + cosine, truy cập ngẫu nhiên theo id / loại+khoá /
|
|
12
|
+
* con trỏ phân trang.
|
|
13
|
+
*
|
|
14
|
+
* Ghi: một tiến trình ghi (daemon), ghi tệp tạm rồi đổi tên (mất điện giữa chừng không hỏng tệp). Người dùng sửa tay → theo dõi thư
|
|
15
|
+
* mục, nạp lại.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export const DEVICE_MEMORY_DIR = path.join(REMOTE_CONFIG_DIR, 'memory');
|
|
19
|
+
const VECTORS_FILE = path.join(DEVICE_MEMORY_DIR, 'vectors.json');
|
|
20
|
+
const KINDS = Object.values(MemoryKind);
|
|
21
|
+
const MAX_TEXT = 4000;
|
|
22
|
+
const MAX_KEY = 160;
|
|
23
|
+
const RELOAD_DEBOUNCE_MS = 300;
|
|
24
|
+
|
|
25
|
+
const state = {
|
|
26
|
+
loaded: false,
|
|
27
|
+
items: new Map(), // id → item
|
|
28
|
+
byKind: new Map(), // kind → Map<key, id>
|
|
29
|
+
vectors: {}, // contentHash → base64
|
|
30
|
+
index: createTextIndex(),
|
|
31
|
+
watcher: null,
|
|
32
|
+
ownWriteAt: 0,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function memoryItemId(kind, key) {
|
|
36
|
+
return createHash('sha1').update(`${kind}\n${key}`).digest('hex').slice(0, 12);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function contentHash(item) {
|
|
40
|
+
return createHash('sha1').update(`${item.kind}\n${item.key}\n${item.text}`).digest('hex').slice(0, 20);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function kindFile(kind) {
|
|
44
|
+
return path.join(DEVICE_MEMORY_DIR, `${kind}.yaml`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function atomicWrite(file, content) {
|
|
48
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
49
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
50
|
+
fs.writeFileSync(tmp, content, 'utf8');
|
|
51
|
+
fs.renameSync(tmp, file);
|
|
52
|
+
state.ownWriteAt = Date.now();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function normalizeItem(raw, kind) {
|
|
56
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
57
|
+
const key = String(raw.key || '').trim().slice(0, MAX_KEY);
|
|
58
|
+
const text = String(raw.text || '').trim().slice(0, MAX_TEXT);
|
|
59
|
+
if (!key || !text) return null;
|
|
60
|
+
return {
|
|
61
|
+
id: memoryItemId(kind, key),
|
|
62
|
+
kind,
|
|
63
|
+
key,
|
|
64
|
+
text,
|
|
65
|
+
...(raw.data !== undefined ? { data: raw.data } : {}),
|
|
66
|
+
created_at: raw.created_at || new Date().toISOString(),
|
|
67
|
+
updated_at: raw.updated_at || raw.created_at || new Date().toISOString(),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function indexItem(item) {
|
|
72
|
+
state.items.set(item.id, item);
|
|
73
|
+
if (!state.byKind.has(item.kind)) state.byKind.set(item.kind, new Map());
|
|
74
|
+
state.byKind.get(item.kind).set(item.key, item.id);
|
|
75
|
+
state.index.add(item.id, `${item.key} ${item.text}`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function unindexItem(id) {
|
|
79
|
+
const item = state.items.get(id);
|
|
80
|
+
if (!item) return;
|
|
81
|
+
state.items.delete(id);
|
|
82
|
+
state.byKind.get(item.kind)?.delete(item.key);
|
|
83
|
+
state.index.remove(id);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function readKindFile(kind) {
|
|
87
|
+
try {
|
|
88
|
+
const parsed = YAML.parse(fs.readFileSync(kindFile(kind), 'utf8'));
|
|
89
|
+
const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.items) ? parsed.items : [];
|
|
90
|
+
return list.map((raw) => normalizeItem(raw, kind)).filter(Boolean);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error.code !== 'ENOENT') console.warn(`[remote] Không đọc được ${kindFile(kind)}: ${error.message}`);
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function reloadAll() {
|
|
98
|
+
state.items.clear();
|
|
99
|
+
state.byKind.clear();
|
|
100
|
+
state.index.clear();
|
|
101
|
+
for (const kind of KINDS) readKindFile(kind).forEach(indexItem);
|
|
102
|
+
try { state.vectors = JSON.parse(fs.readFileSync(VECTORS_FILE, 'utf8')) || {}; } catch { state.vectors = {}; }
|
|
103
|
+
state.loaded = true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function ensureMemoryLoaded() {
|
|
107
|
+
if (!state.loaded) reloadAll();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Theo dõi người dùng sửa tay tệp YAML → nạp lại (bỏ qua sự kiện do chính mình ghi). */
|
|
111
|
+
export function watchMemoryDir() {
|
|
112
|
+
if (state.watcher) return;
|
|
113
|
+
fs.mkdirSync(DEVICE_MEMORY_DIR, { recursive: true });
|
|
114
|
+
let timer;
|
|
115
|
+
try {
|
|
116
|
+
state.watcher = fs.watch(DEVICE_MEMORY_DIR, () => {
|
|
117
|
+
if (Date.now() - state.ownWriteAt < 1000) return;
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
timer = setTimeout(reloadAll, RELOAD_DEBOUNCE_MS);
|
|
120
|
+
});
|
|
121
|
+
state.watcher.unref?.();
|
|
122
|
+
} catch { /* hệ thống tệp không hỗ trợ theo dõi — sửa tay có hiệu lực ở lần khởi động sau */ }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function stopWatchingMemory() {
|
|
126
|
+
state.watcher?.close();
|
|
127
|
+
state.watcher = null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function persistKind(kind) {
|
|
131
|
+
const ids = [...(state.byKind.get(kind)?.values() || [])];
|
|
132
|
+
const list = ids.map((id) => {
|
|
133
|
+
const { id: _id, kind: _kind, ...rest } = state.items.get(id);
|
|
134
|
+
return rest;
|
|
135
|
+
});
|
|
136
|
+
atomicWrite(kindFile(kind), list.length ? YAML.stringify(list, { lineWidth: 0 }) : '[]\n');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function persistVectors() {
|
|
140
|
+
const live = new Set([...state.items.values()].map(contentHash));
|
|
141
|
+
for (const hash of Object.keys(state.vectors)) if (!live.has(hash)) delete state.vectors[hash];
|
|
142
|
+
atomicWrite(VECTORS_FILE, JSON.stringify(state.vectors));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function publicItem(item, score) {
|
|
146
|
+
return { id: item.id, kind: item.kind, key: item.key, text: item.text, ...(item.data !== undefined ? { data: item.data } : {}), updated_at: item.updated_at, ...(score !== undefined ? { score } : {}) };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Thêm / cập nhật theo (loại, khoá). `vector`: int8 base64 BE gửi kèm. */
|
|
150
|
+
export function putMemoryItems(items = []) {
|
|
151
|
+
ensureMemoryLoaded();
|
|
152
|
+
const touched = new Set();
|
|
153
|
+
let vectorsChanged = false;
|
|
154
|
+
let saved = 0;
|
|
155
|
+
for (const raw of Array.isArray(items) ? items : []) {
|
|
156
|
+
const kind = KINDS.includes(raw?.kind) ? raw.kind : MemoryKind.FACT;
|
|
157
|
+
const existing = state.items.get(memoryItemId(kind, String(raw?.key || '').trim().slice(0, MAX_KEY)));
|
|
158
|
+
const item = normalizeItem({ ...raw, created_at: existing?.created_at, updated_at: new Date().toISOString() }, kind);
|
|
159
|
+
if (!item) continue;
|
|
160
|
+
indexItem(item);
|
|
161
|
+
if (raw.vector) { state.vectors[contentHash(item)] = String(raw.vector); vectorsChanged = true; }
|
|
162
|
+
touched.add(kind);
|
|
163
|
+
saved++;
|
|
164
|
+
}
|
|
165
|
+
touched.forEach(persistKind);
|
|
166
|
+
if (vectorsChanged || touched.size) persistVectors();
|
|
167
|
+
return { saved };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function getMemoryItem({ id, kind, key } = {}) {
|
|
171
|
+
ensureMemoryLoaded();
|
|
172
|
+
const itemId = id || (kind && key ? memoryItemId(kind, key) : null);
|
|
173
|
+
const item = itemId ? state.items.get(itemId) : null;
|
|
174
|
+
return item ? publicItem(item) : null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Phân trang theo con trỏ (vị trí), mới cập nhật trước. */
|
|
178
|
+
export function listMemoryItems({ kind, cursor = 0, limit = 50 } = {}) {
|
|
179
|
+
ensureMemoryLoaded();
|
|
180
|
+
const all = [...state.items.values()]
|
|
181
|
+
.filter((i) => !kind || i.kind === kind)
|
|
182
|
+
.sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)));
|
|
183
|
+
const start = Math.max(0, Number(cursor) || 0);
|
|
184
|
+
const size = Math.min(Math.max(1, Number(limit) || 50), 200);
|
|
185
|
+
const page = all.slice(start, start + size).map((i) => publicItem(i));
|
|
186
|
+
return { total: all.length, items: page, next_cursor: start + size < all.length ? start + size : null };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function deleteMemoryItems({ ids = [], kind, key } = {}) {
|
|
190
|
+
ensureMemoryLoaded();
|
|
191
|
+
const targets = [...ids];
|
|
192
|
+
if (kind && key) targets.push(memoryItemId(kind, key));
|
|
193
|
+
const touched = new Set();
|
|
194
|
+
let deleted = 0;
|
|
195
|
+
for (const id of new Set(targets)) {
|
|
196
|
+
const item = state.items.get(id);
|
|
197
|
+
if (!item) continue;
|
|
198
|
+
touched.add(item.kind);
|
|
199
|
+
unindexItem(id);
|
|
200
|
+
deleted++;
|
|
201
|
+
}
|
|
202
|
+
touched.forEach(persistKind);
|
|
203
|
+
if (touched.size) persistVectors();
|
|
204
|
+
return { deleted };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function clearDeviceMemory(kind) {
|
|
208
|
+
ensureMemoryLoaded();
|
|
209
|
+
const kinds = kind ? [kind] : KINDS;
|
|
210
|
+
for (const k of kinds) {
|
|
211
|
+
for (const id of [...(state.byKind.get(k)?.values() || [])]) unindexItem(id);
|
|
212
|
+
persistKind(k);
|
|
213
|
+
}
|
|
214
|
+
persistVectors();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Tìm kết hợp: BM25 (từ khoá) và cosine (vector đề bài do BE gửi) gộp bằng RRF. `score` trả về là cosine (0 khi mục chưa có vector) —
|
|
219
|
+
* BE dùng nó làm ngưỡng "đủ giống để chạy lại quy trình".
|
|
220
|
+
*/
|
|
221
|
+
export function searchMemory({ query = '', vector, kinds, limit = 8 } = {}) {
|
|
222
|
+
ensureMemoryLoaded();
|
|
223
|
+
const kindSet = Array.isArray(kinds) && kinds.length ? new Set(kinds) : null;
|
|
224
|
+
const allowed = (id) => !kindSet || kindSet.has(state.items.get(id)?.kind);
|
|
225
|
+
const wide = Math.max(limit * 3, 20);
|
|
226
|
+
const lexical = query ? state.index.search(query, { limit: wide, filter: allowed }).map((h) => h.id) : [];
|
|
227
|
+
const q = decodeInt8(vector);
|
|
228
|
+
const cosine = new Map();
|
|
229
|
+
if (q) {
|
|
230
|
+
for (const item of state.items.values()) {
|
|
231
|
+
if (!allowed(item.id)) continue;
|
|
232
|
+
const v = decodeInt8(state.vectors[contentHash(item)]);
|
|
233
|
+
if (v) cosine.set(item.id, int8Cosine(q, v));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const semantic = [...cosine.entries()].sort((a, b) => b[1] - a[1]).slice(0, wide).map(([id]) => id);
|
|
237
|
+
return fuseRankings([lexical, semantic]).slice(0, limit).map((id) => publicItem(state.items.get(id), Number((cosine.get(id) || 0).toFixed(4))));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function memoryStats() {
|
|
241
|
+
ensureMemoryLoaded();
|
|
242
|
+
const byKind = {};
|
|
243
|
+
for (const item of state.items.values()) byKind[item.kind] = (byKind[item.kind] || 0) + 1;
|
|
244
|
+
const withVector = [...state.items.values()].filter((i) => state.vectors[contentHash(i)]).length;
|
|
245
|
+
return { total: state.items.size, by_kind: byKind, with_vector: withVector, dir: DEVICE_MEMORY_DIR };
|
|
246
|
+
}
|