@aivin-labs/cli 1.0.8 → 1.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -0
- package/bin/assets/aivin-mascot.png +0 -0
- package/bin/cli.mjs +1979 -1780
- package/bin/lib/browserAutomation.mjs +232 -469
- package/bin/lib/localBrowser.mjs +345 -0
- package/bin/lib/remote/activityLog.mjs +1 -1
- package/bin/lib/remote/autoStart.mjs +174 -14
- package/bin/lib/remote/browserTunnel.mjs +187 -37
- package/bin/lib/remote/callLedger.mjs +74 -15
- package/bin/lib/remote/cdpPolicy.mjs +14 -1
- package/bin/lib/remote/client.mjs +174 -11
- package/bin/lib/remote/clipboard.mjs +138 -0
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +293 -0
- package/bin/lib/remote/constants.mjs +78 -0
- package/bin/lib/remote/dailyBrowser.mjs +9 -3
- package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
- package/bin/lib/remote/desktop/index.mjs +309 -0
- package/bin/lib/remote/desktop/linux.mjs +144 -0
- package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
- package/bin/lib/remote/desktop/mac.mjs +187 -0
- package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
- package/bin/lib/remote/desktop/strings.mjs +74 -0
- package/bin/lib/remote/desktop/traySource.mjs +541 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +86 -1
- package/bin/lib/remote/fileIndexer.mjs +757 -399
- package/bin/lib/remote/folderRules.mjs +140 -0
- package/bin/lib/remote/gui/index.mjs +208 -18
- package/bin/lib/remote/gui/windowsHost.mjs +9 -2
- package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
- package/bin/lib/remote/idempotency.mjs +50 -21
- package/bin/lib/remote/localPolicy.mjs +17 -4
- package/bin/lib/remote/mascot/adpcm.mjs +70 -0
- package/bin/lib/remote/mascot/ask.mjs +768 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
- package/bin/lib/remote/mascot/assets.mjs +825 -216
- package/bin/lib/remote/mascot/bot.mjs +397 -0
- package/bin/lib/remote/mascot/hostSource.mjs +500 -103
- package/bin/lib/remote/mascot/hotkey.mjs +66 -0
- package/bin/lib/remote/mascot/index.mjs +199 -28
- package/bin/lib/remote/mascot/labels.mjs +2 -3
- package/bin/lib/remote/mascot/rigSource.mjs +614 -0
- package/bin/lib/remote/mascot/strings.mjs +204 -18
- package/bin/lib/remote/mascot/ui.mjs +104 -0
- package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
- package/bin/lib/remote/meeting/index.mjs +415 -0
- package/bin/lib/remote/meeting/recorder.mjs +109 -0
- package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
- package/bin/lib/remote/meeting/transcribe.mjs +259 -0
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tabGroups.mjs +209 -0
- package/bin/lib/remote/toolHandlers.mjs +788 -726
- package/bin/lib/remoteControl.mjs +26 -26
- package/docs/AIVIN_MASCOT.md +130 -0
- package/docs/CLI.md +1504 -1353
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +71 -71
|
@@ -3,15 +3,16 @@ import os from 'os';
|
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import WSClient from 'ws';
|
|
5
5
|
import {
|
|
6
|
-
AIVIN_BROWSER_PROFILE_DIR,
|
|
6
|
+
AIVIN_BROWSER_PROFILE_DIR, DEBUG_PORTS, LOCAL_BROWSERS, detectDefaultBrowserId, launchLocalChromeWithDebugging, probeLocalChromeDebugger,
|
|
7
7
|
resolveBrowserInstall,
|
|
8
|
-
} from '../
|
|
8
|
+
} from '../localBrowser.mjs';
|
|
9
9
|
import { DeviceErrorCode } from './constants.mjs';
|
|
10
|
-
import { applyDevicePolicy, executableDownloadGuid } from './cdpPolicy.mjs';
|
|
10
|
+
import { EXTENSION_SESSION_ALLOWED, applyDevicePolicy, executableDownloadGuid, isExtensionUrl } from './cdpPolicy.mjs';
|
|
11
11
|
import { activeBrowserEndpoint, browserPortFromProcesses, createCdpMux, findDailyBrowser } from './dailyBrowser.mjs';
|
|
12
12
|
import { proxyAgentFor } from './netProxy.mjs';
|
|
13
13
|
import { showOSNotification } from './notify.mjs';
|
|
14
14
|
import { DeviceToolError } from './sandbox.mjs';
|
|
15
|
+
import { createTabGrouper, groupTitle } from './tabGroups.mjs';
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
18
|
* Trình duyệt của máy cho AI Browser (CLI ≥ 1.0.8, 27/10/2026). BE gọi `browser.open_tunnel` khi một nhiệm vụ web chạy trên máy này: mở (hoặc dùng
|
|
@@ -24,9 +25,12 @@ import { DeviceToolError } from './sandbox.mjs';
|
|
|
24
25
|
* Ưu tiên trình duyệt HẰNG NGÀY của người dùng nếu họ đã bật gỡ lỗi từ xa ở `chrome://inspect/#remote-debugging` (dailyBrowser.mjs, 27/10/2026):
|
|
25
26
|
* dùng sẵn mọi đăng nhập; một kết nối chung (bấm Cho phép một lần), mỗi đường hầm một phiên riêng, tab của người dùng chỉ đọc. Người dùng không bật,
|
|
26
27
|
* từ chối, hoặc chạy `--separate-browser` → cửa sổ riêng của Aivin như trên.
|
|
28
|
+
*
|
|
29
|
+
* Từ 29/10/2026 `aivin browser` (chế độ local) cũng đi qua bộ đường hầm này (xác thực bằng API key thay vì token máy) — trước đó nó có đường ống
|
|
30
|
+
* riêng không qua `cdpPolicy.mjs` và nhận bừa Chrome / Edge nào đang nghe ở 9222–9225. Tab AI mở trong cửa sổ Aivin được gom vào một nhóm tab mỗi
|
|
31
|
+
* đường hầm (tabGroups.mjs).
|
|
27
32
|
*/
|
|
28
33
|
|
|
29
|
-
const DEBUG_PORTS = [CHROME_DEBUG_PORT, 9223, 9224, 9225];
|
|
30
34
|
const TUNNEL_ID_RE = /^[a-z0-9-]{8,64}$/i;
|
|
31
35
|
const MAX_READ_BYTES = 1024 * 1024;
|
|
32
36
|
const DOWNLOAD_WAIT_MS = 8000;
|
|
@@ -54,19 +58,24 @@ export function detectLocalBrowser() {
|
|
|
54
58
|
* CDP của cửa sổ Aivin đang chạy, không có thì mở. Chỉ nhận trình duyệt chạy ĐÚNG hồ sơ Aivin (`DevToolsActivePort` trong
|
|
55
59
|
* `~/.aivin/browser-profile`) — trước 28/10/2026 nhận bừa Chrome / Edge nào đang nghe ở 9222–9225, kể cả trình duyệt thật của người dùng mở cổng
|
|
56
60
|
* gỡ lỗi (AI có toàn quyền CDP mà không qua lớp bảo vệ, không hỏi). Cổng bị dịch vụ / trình duyệt khác chiếm thì thử cổng kế bên.
|
|
61
|
+
*
|
|
62
|
+
* `ports` — cổng được thử khi phải mở mới (`aivin browser --debug-port` ghim một cổng); `launch: false` — chỉ dùng lại, không mở (nối lại sau khi rớt
|
|
63
|
+
* mạng: người dùng đã đóng cửa sổ thì không tự mở lại giữa chừng). `browserId` trả về là trình duyệt THẬT đang chạy (`edge` / `chrome`, Brave và
|
|
64
|
+
* Chromium báo là `chrome`).
|
|
57
65
|
*/
|
|
58
|
-
async function ensureAivinBrowser(preferredId) {
|
|
66
|
+
export async function ensureAivinBrowser(preferredId, { ports = DEBUG_PORTS, launch = true, log } = {}) {
|
|
59
67
|
const running = await activeBrowserEndpoint(AIVIN_BROWSER_PROFILE_DIR);
|
|
60
|
-
if (running) return { wsUrl: running.wsUrl, browserId: preferredId };
|
|
68
|
+
if (running) return { wsUrl: running.wsUrl, browserId: (await probeLocalChromeDebugger(running.port)).browserId || preferredId, port: running.port };
|
|
61
69
|
// Cửa sổ Aivin đang mở mà không ghi DevToolsActivePort (Edge với cổng cố định) → dùng lại theo dòng lệnh tiến trình, không mở thêm.
|
|
62
70
|
const processPort = await browserPortFromProcesses(AIVIN_BROWSER_PROFILE_DIR);
|
|
63
71
|
if (processPort) {
|
|
64
|
-
const { wsUrl } = await probeLocalChromeDebugger(processPort);
|
|
65
|
-
if (wsUrl) return { wsUrl, browserId: preferredId };
|
|
72
|
+
const { wsUrl, browserId } = await probeLocalChromeDebugger(processPort);
|
|
73
|
+
if (wsUrl) return { wsUrl, browserId: browserId || preferredId, port: processPort };
|
|
66
74
|
}
|
|
75
|
+
if (!launch) throw new DeviceToolError(DeviceErrorCode.BROWSER_NOT_FOUND, 'The Aivin browser window is no longer running');
|
|
67
76
|
const conflicts = [];
|
|
68
77
|
let freePort;
|
|
69
|
-
for (const port of
|
|
78
|
+
for (const port of ports) {
|
|
70
79
|
const probed = await probeLocalChromeDebugger(port);
|
|
71
80
|
if (probed.wsUrl) { conflicts.push(`${port} (another browser profile)`); continue; }
|
|
72
81
|
if (probed.conflict) { conflicts.push(`${port} (${probed.conflict})`); continue; }
|
|
@@ -74,21 +83,51 @@ async function ensureAivinBrowser(preferredId) {
|
|
|
74
83
|
}
|
|
75
84
|
if (freePort === undefined) throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Browser debug ports are all taken by other services: ${conflicts.join(', ')}`);
|
|
76
85
|
try {
|
|
77
|
-
|
|
86
|
+
const wsUrl = await launchLocalChromeWithDebugging(freePort, preferredId, log ? { log } : undefined);
|
|
87
|
+
return { wsUrl, browserId: (await probeLocalChromeDebugger(freePort)).browserId || preferredId, port: freePort, launched: true };
|
|
78
88
|
} catch (e) {
|
|
79
89
|
const notFound = /could not find/i.test(e?.message || '');
|
|
80
90
|
throw new DeviceToolError(notFound ? DeviceErrorCode.BROWSER_NOT_FOUND : DeviceErrorCode.EXECUTION_FAILED, e?.message || String(e));
|
|
81
91
|
}
|
|
82
92
|
}
|
|
83
93
|
|
|
84
|
-
/**
|
|
85
|
-
/** Token máy: chuỗi, hoặc hàm trả token hiện hành (daemon xoay vòng token khi đang chạy). */
|
|
94
|
+
/** Token máy / header xác thực: chuỗi, hoặc hàm trả giá trị hiện hành (daemon xoay vòng token khi đang chạy). */
|
|
86
95
|
const tokenOf = (t) => (typeof t === 'function' ? t() : t);
|
|
87
96
|
|
|
88
|
-
|
|
89
|
-
|
|
97
|
+
/** Khung trình duyệt gửi lên có thể đáng xem (gắn / gỡ phiên, tab mới, trả lời có targetId) — so chuỗi trước, chỉ parse khi cần. */
|
|
98
|
+
const UPSTREAM_INTEREST_RE = /attachedToTarget|detachedFromTarget|targetCreated|targetInfoChanged|targetDestroyed|"targetId"/;
|
|
99
|
+
const KEEPALIVE_MS = 30_000;
|
|
100
|
+
const MAX_EARLY_QUEUE_BYTES = 4 * 1024 * 1024;
|
|
101
|
+
|
|
102
|
+
function watchSocketAlive(ws, onDead, intervalMs = KEEPALIVE_MS) {
|
|
103
|
+
if (!intervalMs || typeof ws.ping !== 'function') return () => {};
|
|
104
|
+
let awaitingPong = false;
|
|
105
|
+
ws.on('pong', () => { awaitingPong = false; });
|
|
106
|
+
const timer = setInterval(() => {
|
|
107
|
+
if (ws.readyState !== WSClient.OPEN) return;
|
|
108
|
+
if (awaitingPong) { try { ws.terminate?.(); } catch { /* đã đóng */ } onDead(); return; }
|
|
109
|
+
awaitingPong = true;
|
|
110
|
+
try { ws.ping(); } catch { /* đang đóng */ }
|
|
111
|
+
}, intervalMs);
|
|
112
|
+
timer.unref?.();
|
|
113
|
+
return () => clearInterval(timer);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Hai WebSocket nối nhau (BE ↔ trình duyệt), chờ cả hai mở. Một đầu đóng → đóng đầu kia. Lệnh BE gửi xuống đi qua bộ lọc `cdpPolicy.mjs`, cộng:
|
|
118
|
+
* không lệnh nào vào phiên / đích `chrome-extension://` ngoài `EXTENSION_SESSION_ALLOWED` (tiện ích gom nhóm tab có quyền `debugger`).
|
|
119
|
+
* `onAivinTarget(targetId)` — tab AI vừa mở (`Target.createTarget` của BE, hoặc tab bật ra từ tab đó).
|
|
120
|
+
*/
|
|
121
|
+
export function pipeTunnel({ relayUrl, authorization, chromeWsUrl, signal, downloadsDir, onAivinTarget = () => {} }) {
|
|
122
|
+
const toBackend = new WSClient(relayUrl, { headers: { Authorization: authorization }, agent: proxyAgentFor(relayUrl) });
|
|
90
123
|
const toChrome = new WSClient(chromeWsUrl, { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024 });
|
|
91
|
-
const
|
|
124
|
+
const extensionTargets = new Set();
|
|
125
|
+
const extensionSessions = new Set();
|
|
126
|
+
const aivinTargets = new Set();
|
|
127
|
+
const pendingCreates = new Set(); // `${sessionId}:${id}` của lệnh Target.createTarget chưa có trả lời
|
|
128
|
+
let stopKeepalive = () => {};
|
|
129
|
+
const close = () => {
|
|
130
|
+
stopKeepalive();
|
|
92
131
|
try { toBackend.close(); } catch { /* đã đóng */ }
|
|
93
132
|
try { toChrome.close(); } catch { /* đã đóng */ }
|
|
94
133
|
};
|
|
@@ -97,27 +136,71 @@ function pipeTunnel({ relayUrl, deviceToken, chromeWsUrl, signal, downloadsDir }
|
|
|
97
136
|
from.on('close', close);
|
|
98
137
|
from.on('error', close);
|
|
99
138
|
};
|
|
139
|
+
const extensionBlock = (msg) => {
|
|
140
|
+
if (msg.sessionId && extensionSessions.has(msg.sessionId) && !EXTENSION_SESSION_ALLOWED.has(msg.method)) return `${msg.method} is not allowed on browser extensions`;
|
|
141
|
+
if (msg.method === 'Target.attachToTarget' && extensionTargets.has(msg.params?.targetId)) return 'Attaching to browser extensions is not allowed';
|
|
142
|
+
return null;
|
|
143
|
+
};
|
|
100
144
|
toBackend.on('message', (data) => {
|
|
101
145
|
let msg;
|
|
102
146
|
try { msg = JSON.parse(String(data)); } catch { return; }
|
|
103
|
-
const { msg: out, error } = applyDevicePolicy(msg, { downloadsDir });
|
|
147
|
+
const { msg: out, error: policyError } = applyDevicePolicy(msg, { downloadsDir });
|
|
148
|
+
const error = policyError || extensionBlock(msg);
|
|
104
149
|
if (error) {
|
|
105
150
|
if (msg.id !== undefined && toBackend.readyState === WSClient.OPEN) {
|
|
106
151
|
toBackend.send(JSON.stringify({ id: msg.id, ...(msg.sessionId ? { sessionId: msg.sessionId } : {}), error: { code: -32000, message: error } }));
|
|
107
152
|
}
|
|
108
153
|
return;
|
|
109
154
|
}
|
|
155
|
+
if (msg.method === 'Target.createTarget' && msg.id !== undefined) pendingCreates.add(`${msg.sessionId || ''}:${msg.id}`);
|
|
110
156
|
if (toChrome.readyState === WSClient.OPEN) toChrome.send(JSON.stringify(out));
|
|
111
157
|
});
|
|
112
158
|
toBackend.on('close', close);
|
|
113
159
|
toBackend.on('error', close);
|
|
160
|
+
const noteTarget = (info) => {
|
|
161
|
+
if (!info?.targetId) return;
|
|
162
|
+
if (isExtensionUrl(info.url)) extensionTargets.add(info.targetId);
|
|
163
|
+
};
|
|
164
|
+
const markAivin = (targetId) => {
|
|
165
|
+
if (!targetId || aivinTargets.has(targetId)) return;
|
|
166
|
+
aivinTargets.add(targetId);
|
|
167
|
+
try { onAivinTarget(targetId); } catch { /* gom nhóm chỉ là hiển thị */ }
|
|
168
|
+
};
|
|
114
169
|
// Tệp chạy được AI bắt đầu tải → huỷ ngay ở trình duyệt (không để nằm lại trong thư mục tải của máy).
|
|
115
170
|
let cancelId = 2_000_000_000;
|
|
116
171
|
toChrome.on('message', (data) => {
|
|
117
|
-
const
|
|
172
|
+
const text = String(data);
|
|
173
|
+
const guid = executableDownloadGuid(text);
|
|
118
174
|
if (guid && toChrome.readyState === WSClient.OPEN) toChrome.send(JSON.stringify({ id: cancelId++, method: 'Browser.cancelDownload', params: { guid } }));
|
|
175
|
+
if (!UPSTREAM_INTEREST_RE.test(text)) return;
|
|
176
|
+
let msg;
|
|
177
|
+
try { msg = JSON.parse(text); } catch { return; }
|
|
178
|
+
const params = msg.params || {};
|
|
179
|
+
if (msg.id !== undefined) {
|
|
180
|
+
const key = `${msg.sessionId || ''}:${msg.id}`;
|
|
181
|
+
if (pendingCreates.delete(key) && msg.result?.targetId) markAivin(msg.result.targetId);
|
|
182
|
+
// Target.getTargets / getTargetInfo: biết đích tiện ích trước khi BE xin gắn thẳng vào nó.
|
|
183
|
+
for (const info of msg.result?.targetInfos || []) noteTarget(info);
|
|
184
|
+
noteTarget(msg.result?.targetInfo);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (msg.method === 'Target.attachedToTarget') {
|
|
188
|
+
noteTarget(params.targetInfo);
|
|
189
|
+
if (params.sessionId && isExtensionUrl(params.targetInfo?.url)) extensionSessions.add(params.sessionId);
|
|
190
|
+
} else if (msg.method === 'Target.detachedFromTarget') {
|
|
191
|
+
extensionSessions.delete(params.sessionId);
|
|
192
|
+
} else if (msg.method === 'Target.targetCreated' || msg.method === 'Target.targetInfoChanged') {
|
|
193
|
+
noteTarget(params.targetInfo);
|
|
194
|
+
// Tab bật ra từ tab AI (window.open, target=_blank) cũng là của AI.
|
|
195
|
+
const info = params.targetInfo;
|
|
196
|
+
if (msg.method === 'Target.targetCreated' && info?.type === 'page' && aivinTargets.has(info.openerId)) markAivin(info.targetId);
|
|
197
|
+
} else if (msg.method === 'Target.targetDestroyed' && params.targetId) {
|
|
198
|
+
extensionTargets.delete(params.targetId);
|
|
199
|
+
aivinTargets.delete(params.targetId);
|
|
200
|
+
}
|
|
119
201
|
});
|
|
120
|
-
relay(toChrome, toBackend);
|
|
202
|
+
relay(toChrome, toBackend);
|
|
203
|
+
stopKeepalive = watchSocketAlive(toBackend, close);
|
|
121
204
|
const opened = (ws) => new Promise((resolve, reject) => {
|
|
122
205
|
ws.once('open', resolve);
|
|
123
206
|
ws.once('error', reject);
|
|
@@ -132,18 +215,28 @@ function pipeTunnel({ relayUrl, deviceToken, chromeWsUrl, signal, downloadsDir }
|
|
|
132
215
|
}
|
|
133
216
|
|
|
134
217
|
/** Đường hầm trên kết nối chung tới trình duyệt hằng ngày: BE ↔ một phiên riêng của bộ chia. Khung BE gửi trước khi phiên sẵn sàng được giữ lại. */
|
|
135
|
-
function pipeTunnelToMux({ relayUrl,
|
|
136
|
-
const toBackend = new WSClient(relayUrl, { headers: { Authorization:
|
|
218
|
+
function pipeTunnelToMux({ relayUrl, authorization, mux, signal }) {
|
|
219
|
+
const toBackend = new WSClient(relayUrl, { headers: { Authorization: authorization }, agent: proxyAgentFor(relayUrl) });
|
|
137
220
|
let client = null;
|
|
138
221
|
let closed = false;
|
|
139
|
-
const early = [];
|
|
140
|
-
|
|
222
|
+
const early = [];
|
|
223
|
+
let earlyBytes = 0;
|
|
224
|
+
let stopKeepalive = () => {};
|
|
225
|
+
const close = () => {
|
|
226
|
+
stopKeepalive();
|
|
141
227
|
if (closed) return;
|
|
142
228
|
closed = true;
|
|
143
229
|
try { toBackend.close(); } catch { /* đã đóng */ }
|
|
144
230
|
client?.close();
|
|
145
231
|
};
|
|
146
|
-
toBackend.on('message', (data) => {
|
|
232
|
+
toBackend.on('message', (data) => {
|
|
233
|
+
const str = String(data);
|
|
234
|
+
if (client) { client.send(str); return; }
|
|
235
|
+
earlyBytes += Buffer.byteLength(str);
|
|
236
|
+
if (earlyBytes > MAX_EARLY_QUEUE_BYTES) { try { toBackend.close(1009, 'too much data before pairing'); } catch { /* đã đóng */ } close(); return; }
|
|
237
|
+
early.push(str);
|
|
238
|
+
});
|
|
239
|
+
stopKeepalive = watchSocketAlive(toBackend, close);
|
|
147
240
|
toBackend.on('close', close);
|
|
148
241
|
toBackend.on('error', close);
|
|
149
242
|
const onAbort = () => close();
|
|
@@ -196,14 +289,34 @@ async function findDownload(dir, name, since, signal) {
|
|
|
196
289
|
/**
|
|
197
290
|
* Bộ đường hầm của daemon: `open` / `readDownload` cho hai công cụ nội bộ, `closeAll` khi dừng. `env.serverUrl` + `env.deviceToken` lấy từ thông
|
|
198
291
|
* tin ghép máy. `ensureBrowser` thay được trong test (không mở trình duyệt thật).
|
|
292
|
+
*
|
|
293
|
+
* `authorization` — header xác thực đầy đủ (chuỗi / hàm), thay cho `Device <token máy>`: `aivin browser` dùng `Bearer <API key>`.
|
|
294
|
+
* `say(text, event)` — `event` là dạng có cấu trúc của cùng thông báo (`{ type, browser, … }`) cho nơi gọi muốn tự viết câu (`aivin browser` nói
|
|
295
|
+
* tiếng Anh). `groupTabs` — gom tab AI mở trong cửa sổ Aivin thành một nhóm tab mỗi đường hầm (tabGroups.mjs).
|
|
199
296
|
*/
|
|
200
297
|
export function createBrowserTunnels({
|
|
201
|
-
serverUrl, deviceToken, browser, downloadsDir = AIVIN_DOWNLOADS_DIR, say = () => {}, ensureBrowser = ensureAivinBrowser,
|
|
298
|
+
serverUrl, deviceToken, authorization, browser, downloadsDir = AIVIN_DOWNLOADS_DIR, say = () => {}, ensureBrowser = ensureAivinBrowser,
|
|
202
299
|
useDailyBrowser = true, findDaily = findDailyBrowser, createMux = createCdpMux, notify = showOSNotification,
|
|
300
|
+
groupTabs = true, createGrouper = createTabGrouper,
|
|
203
301
|
}) {
|
|
204
|
-
const live = new
|
|
302
|
+
const live = new Map(); // tunnelId → { close, done, deliberate }
|
|
205
303
|
let daily = null;
|
|
206
304
|
let dailyCooldownUntil = 0;
|
|
305
|
+
let grouper = null; // { wsUrl, g } — một bộ gom nhóm cho cửa sổ Aivin đang dùng
|
|
306
|
+
const authHeader = () => (authorization ? tokenOf(authorization) : `Device ${tokenOf(deviceToken)}`);
|
|
307
|
+
|
|
308
|
+
function grouperFor(wsUrl) {
|
|
309
|
+
if (!groupTabs || !wsUrl) return null;
|
|
310
|
+
if (grouper?.wsUrl !== wsUrl) {
|
|
311
|
+
grouper?.g.close();
|
|
312
|
+
const g = createGrouper({
|
|
313
|
+
wsUrl,
|
|
314
|
+
onUnavailable: (e) => say(`🗂️ Không gom nhóm tab được (${e?.message || e}) — đóng rồi mở lại cửa sổ Aivin để bật.`, { type: 'groups-unavailable', reason: e?.message || String(e) }),
|
|
315
|
+
});
|
|
316
|
+
grouper = { wsUrl, g };
|
|
317
|
+
}
|
|
318
|
+
return grouper.g;
|
|
319
|
+
}
|
|
207
320
|
|
|
208
321
|
/** Kết nối chung tới trình duyệt hằng ngày (lần đầu trình duyệt hỏi người dùng). Không bật / bị từ chối → null (dùng cửa sổ Aivin). */
|
|
209
322
|
async function dailyBrowser() {
|
|
@@ -216,12 +329,13 @@ export function createBrowserTunnels({
|
|
|
216
329
|
const onBlocked = ({ method, reason, targetId }) => {
|
|
217
330
|
if (blockedSeen.has(method) || blockedSeen.size > 50) return;
|
|
218
331
|
blockedSeen.add(method);
|
|
219
|
-
say(`🛡️ Đã chặn ${method} trên ${found.name} của bạn — ${reason}${targetId ? ` (tab ${String(targetId).slice(0, 8)})` : ''}
|
|
332
|
+
say(`🛡️ Đã chặn ${method} trên ${found.name} của bạn — ${reason}${targetId ? ` (tab ${String(targetId).slice(0, 8)})` : ''}`, { type: 'blocked', browser: found.name, method, reason });
|
|
220
333
|
};
|
|
221
|
-
|
|
334
|
+
const onClosed = () => say(`🔌 Đã nhả ${found.name} hằng ngày của bạn`, { type: 'released', browser: found.name });
|
|
335
|
+
daily = { ...found, mux: createMux({ wsUrl: found.wsUrl, downloadsDir, onBlocked, onClosed }) };
|
|
222
336
|
}
|
|
223
337
|
if (!daily.mux.isOpen()) {
|
|
224
|
-
say(`🔐 ${found.name} đang hỏi: cho phép Aivin dùng trình duyệt này? Bấm "Allow" / "Cho phép" trên cửa sổ ${found.name}
|
|
338
|
+
say(`🔐 ${found.name} đang hỏi: cho phép Aivin dùng trình duyệt này? Bấm "Allow" / "Cho phép" trên cửa sổ ${found.name}.`, { type: 'consent', browser: found.name });
|
|
225
339
|
notify({ title: `Aivin muốn dùng ${found.name} của bạn`, body: `Bấm "Allow" trên hộp thoại của ${found.name} để AI làm việc bằng các tài khoản bạn đã đăng nhập.` });
|
|
226
340
|
}
|
|
227
341
|
try {
|
|
@@ -229,7 +343,7 @@ export function createBrowserTunnels({
|
|
|
229
343
|
return daily;
|
|
230
344
|
} catch (e) {
|
|
231
345
|
dailyCooldownUntil = Date.now() + DAILY_RETRY_COOLDOWN_MS;
|
|
232
|
-
say(`↩️ ${found.name} chưa cho phép (${e?.message || e}) — dùng cửa sổ riêng của Aivin
|
|
346
|
+
say(`↩️ ${found.name} chưa cho phép (${e?.message || e}) — dùng cửa sổ riêng của Aivin.`, { type: 'daily-declined', browser: found.name, reason: e?.message || String(e) });
|
|
233
347
|
return null;
|
|
234
348
|
}
|
|
235
349
|
}
|
|
@@ -244,9 +358,14 @@ export function createBrowserTunnels({
|
|
|
244
358
|
assertNotAborted(ctx?.signal);
|
|
245
359
|
await fs.promises.mkdir(downloadsDir, { recursive: true }).catch(() => undefined);
|
|
246
360
|
const relayUrl = `${serverUrl.replace(/^http/i, 'ws')}/browser-tunnel/external?tunnel_id=${encodeURIComponent(tunnelId)}`;
|
|
361
|
+
const g = shared ? null : grouperFor(wsUrl);
|
|
362
|
+
const title = groupTitle(typeof args?.label === 'string' ? args.label : '');
|
|
247
363
|
const tunnel = shared
|
|
248
|
-
? pipeTunnelToMux({ relayUrl,
|
|
249
|
-
: pipeTunnel({
|
|
364
|
+
? pipeTunnelToMux({ relayUrl, authorization: authHeader(), mux: shared.mux, signal: ctx?.signal })
|
|
365
|
+
: pipeTunnel({
|
|
366
|
+
relayUrl, authorization: authHeader(), chromeWsUrl: wsUrl, signal: ctx?.signal, downloadsDir,
|
|
367
|
+
onAivinTarget: (targetId) => { g?.add(targetId, { key: tunnelId, title }); },
|
|
368
|
+
});
|
|
250
369
|
try {
|
|
251
370
|
await tunnel.ready;
|
|
252
371
|
} catch (e) {
|
|
@@ -257,16 +376,34 @@ export function createBrowserTunnels({
|
|
|
257
376
|
tunnel.close();
|
|
258
377
|
assertNotAborted(ctx.signal);
|
|
259
378
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
379
|
+
const entry = { close: tunnel.close, deliberate: false };
|
|
380
|
+
close(tunnelId); // BE mở lại cùng tunnel_id (thử lại phía máy chủ) → thay đường hầm cũ
|
|
381
|
+
live.set(tunnelId, entry);
|
|
382
|
+
// `ctx.onClose({ deliberate })` — đường hầm đóng: do `close(tunnelId)` / `closeAll()` (deliberate) hay tự rớt (mạng, trình duyệt bị đóng).
|
|
383
|
+
tunnel.done.then(() => {
|
|
384
|
+
if (live.get(tunnelId) === entry) live.delete(tunnelId);
|
|
385
|
+
g?.forget(tunnelId);
|
|
386
|
+
ctx?.onClose?.({ deliberate: entry.deliberate });
|
|
387
|
+
});
|
|
388
|
+
const name = shared?.name || browser?.name || '';
|
|
389
|
+
say(
|
|
390
|
+
shared ? `🌐 AI đang dùng ${shared.name} hằng ngày của bạn (tab mới, mở ở nền)` : `🌐 AI đang dùng trình duyệt ${name ? `${name} ` : ''}trên máy này`,
|
|
391
|
+
{ type: 'using', browser: name, daily: !!shared },
|
|
392
|
+
);
|
|
263
393
|
return { browser: shared?.name || browser?.name, downloads_dir: downloadsDir, ...(shared ? { daily: true } : {}) };
|
|
264
394
|
}
|
|
265
395
|
|
|
266
396
|
async function readDownload(args, ctx) {
|
|
267
397
|
const name = String(args?.name || '');
|
|
268
398
|
if (!name || name !== path.basename(name) || name.includes('..')) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Invalid file name');
|
|
269
|
-
const
|
|
399
|
+
const reqOffset = Math.max(0, Number(args?.offset) || 0);
|
|
400
|
+
const since = Number(args?.since) || 0;
|
|
401
|
+
let hit = null;
|
|
402
|
+
if (reqOffset > 0 && !name.endsWith(PARTIAL_SUFFIX)) {
|
|
403
|
+
const st = await fs.promises.stat(path.join(downloadsDir, name)).catch(() => null);
|
|
404
|
+
if (st?.isFile() && st.mtimeMs >= since - 2000) hit = { name, size: st.size };
|
|
405
|
+
}
|
|
406
|
+
if (!hit) hit = await findDownload(downloadsDir, name, since, ctx?.signal);
|
|
270
407
|
if (!hit) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Downloaded file not found: ${name}`);
|
|
271
408
|
const offset = Math.max(0, Number(args?.offset) || 0);
|
|
272
409
|
const length = Math.min(Math.max(0, Number(args?.length) || MAX_READ_BYTES), MAX_READ_BYTES, Math.max(0, hit.size - offset));
|
|
@@ -281,12 +418,25 @@ export function createBrowserTunnels({
|
|
|
281
418
|
}
|
|
282
419
|
}
|
|
283
420
|
|
|
421
|
+
/** Đóng một đường hầm (chủ động — `ctx.onClose` nhận `deliberate: true`). */
|
|
422
|
+
function close(tunnelId) {
|
|
423
|
+
const entry = live.get(tunnelId);
|
|
424
|
+
if (!entry) return;
|
|
425
|
+
entry.deliberate = true;
|
|
426
|
+
entry.close();
|
|
427
|
+
}
|
|
428
|
+
|
|
284
429
|
function closeAll() {
|
|
285
|
-
for (const
|
|
430
|
+
for (const entry of live.values()) {
|
|
431
|
+
entry.deliberate = true;
|
|
432
|
+
entry.close();
|
|
433
|
+
}
|
|
286
434
|
live.clear();
|
|
287
435
|
daily?.mux.close();
|
|
288
436
|
daily = null;
|
|
437
|
+
grouper?.g.close();
|
|
438
|
+
grouper = null;
|
|
289
439
|
}
|
|
290
440
|
|
|
291
|
-
return { open, readDownload, closeAll, liveCount: () => live.size };
|
|
441
|
+
return { open, readDownload, close, closeAll, liveCount: () => live.size };
|
|
292
442
|
}
|
|
@@ -22,21 +22,34 @@ function payloadBytes(payload) {
|
|
|
22
22
|
* - Kết quả chưa gửi được (mất mạng, chưa có ack) ghi xuống `REMOTE_OUTBOX_FILE` — daemon khởi động lại vẫn gửi.
|
|
23
23
|
* - `heldIds()`: lời gọi máy đang giữ, gửi lên khi chào để BE đối chiếu (huỷ việc không còn ai chờ, khỏi gửi lại việc máy đang làm).
|
|
24
24
|
*/
|
|
25
|
-
export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.now() } = {}) {
|
|
25
|
+
export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.now(), debounceMs = 40 } = {}) {
|
|
26
26
|
const calls = new Map();
|
|
27
|
+
let persistTimer = null;
|
|
28
|
+
let writeChain = Promise.resolve();
|
|
27
29
|
|
|
28
|
-
function
|
|
30
|
+
function buildUnsentRows() {
|
|
29
31
|
const unsent = [...calls.entries()].filter(([, e]) => e.state === CallState.DONE && !e.sent);
|
|
32
|
+
return unsent.map(([id, e]) => {
|
|
33
|
+
const payload = payloadBytes(e.payload) <= PERSIST_RESULT_BYTES ? e.payload
|
|
34
|
+
: { call_id: id, ok: false, error: 'Result was too large to keep while offline — run the step again', error_code: 'OUTPUT_TOO_LARGE', duration_ms: e.payload.duration_ms };
|
|
35
|
+
return { id, at: e.at, payload };
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function clearPersistTimer() {
|
|
40
|
+
if (!persistTimer) return;
|
|
41
|
+
clearTimeout(persistTimer);
|
|
42
|
+
persistTimer = null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function persistSync() {
|
|
46
|
+
clearPersistTimer();
|
|
47
|
+
const rows = buildUnsentRows();
|
|
30
48
|
try {
|
|
31
|
-
if (!
|
|
49
|
+
if (!rows.length) {
|
|
32
50
|
fs.rmSync(file, { force: true });
|
|
33
51
|
return;
|
|
34
52
|
}
|
|
35
|
-
const rows = unsent.map(([id, e]) => {
|
|
36
|
-
const payload = payloadBytes(e.payload) <= PERSIST_RESULT_BYTES ? e.payload
|
|
37
|
-
: { call_id: id, ok: false, error: 'Result was too large to keep while offline — run the step again', error_code: 'OUTPUT_TOO_LARGE', duration_ms: e.payload.duration_ms };
|
|
38
|
-
return { id, at: e.at, payload };
|
|
39
|
-
});
|
|
40
53
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
41
54
|
const tmp = `${file}.tmp`;
|
|
42
55
|
fs.writeFileSync(tmp, JSON.stringify(rows), { mode: 0o600 });
|
|
@@ -44,8 +57,46 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
|
|
|
44
57
|
} catch { /* không ghi được: vẫn giữ trong bộ nhớ */ }
|
|
45
58
|
}
|
|
46
59
|
|
|
60
|
+
function enqueueAsyncPersist() {
|
|
61
|
+
clearPersistTimer();
|
|
62
|
+
const rows = buildUnsentRows();
|
|
63
|
+
if (!rows.length) {
|
|
64
|
+
try { fs.rmSync(file, { force: true }); } catch { /* bỏ qua */ }
|
|
65
|
+
return writeChain;
|
|
66
|
+
}
|
|
67
|
+
const serialized = JSON.stringify(rows);
|
|
68
|
+
writeChain = writeChain.then(async () => {
|
|
69
|
+
try {
|
|
70
|
+
await fs.promises.mkdir(path.dirname(file), { recursive: true });
|
|
71
|
+
const tmp = `${file}.tmp`;
|
|
72
|
+
await fs.promises.writeFile(tmp, serialized, { mode: 0o600 });
|
|
73
|
+
await fs.promises.rename(tmp, file);
|
|
74
|
+
} catch { /* không ghi được: vẫn giữ trong bộ nhớ */ }
|
|
75
|
+
});
|
|
76
|
+
return writeChain;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function schedulePersist() {
|
|
80
|
+
const hasUnsent = [...calls.values()].some((e) => e.state === CallState.DONE && !e.sent);
|
|
81
|
+
if (!hasUnsent) {
|
|
82
|
+
clearPersistTimer();
|
|
83
|
+
try { fs.rmSync(file, { force: true }); } catch { /* bỏ qua */ }
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (debounceMs <= 0) {
|
|
87
|
+
persistSync();
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (persistTimer) return;
|
|
91
|
+
persistTimer = setTimeout(() => {
|
|
92
|
+
persistTimer = null;
|
|
93
|
+
void enqueueAsyncPersist();
|
|
94
|
+
}, debounceMs);
|
|
95
|
+
persistTimer.unref?.();
|
|
96
|
+
}
|
|
97
|
+
|
|
47
98
|
function load() {
|
|
48
|
-
let rows
|
|
99
|
+
let rows;
|
|
49
100
|
try { rows = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return; }
|
|
50
101
|
const t = now();
|
|
51
102
|
for (const r of Array.isArray(rows) ? rows : []) {
|
|
@@ -70,7 +121,7 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
|
|
|
70
121
|
calls.delete(id);
|
|
71
122
|
changed = true;
|
|
72
123
|
}
|
|
73
|
-
if (changed)
|
|
124
|
+
if (changed) schedulePersist();
|
|
74
125
|
}
|
|
75
126
|
|
|
76
127
|
load();
|
|
@@ -86,7 +137,10 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
|
|
|
86
137
|
/** Lời gọi xong — kết quả chờ gửi. `persistNow`: ghi xuống đĩa ngay (đang mất kết nối). */
|
|
87
138
|
finish(callId, payload, { persistNow = false } = {}) {
|
|
88
139
|
calls.set(callId, { state: CallState.DONE, at: now(), payload, sent: false });
|
|
89
|
-
if (persistNow)
|
|
140
|
+
if (persistNow) {
|
|
141
|
+
for (const e of calls.values()) if (e.state === CallState.DONE && !e.sent) e.onDisk = true;
|
|
142
|
+
persistSync();
|
|
143
|
+
}
|
|
90
144
|
},
|
|
91
145
|
markSent(callId) {
|
|
92
146
|
const e = calls.get(callId);
|
|
@@ -94,7 +148,7 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
|
|
|
94
148
|
const wasOnDisk = e.onDisk;
|
|
95
149
|
e.sent = true;
|
|
96
150
|
e.payload = { call_id: callId, ...pick(e.payload) };
|
|
97
|
-
if (wasOnDisk)
|
|
151
|
+
if (wasOnDisk) schedulePersist();
|
|
98
152
|
},
|
|
99
153
|
/** Lời gọi đã xong bị BE gửi lại: đánh dấu chưa gửi, trả kết quả để gửi lần nữa. */
|
|
100
154
|
reopen(callId) {
|
|
@@ -104,9 +158,14 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
|
|
|
104
158
|
return e.payload;
|
|
105
159
|
},
|
|
106
160
|
/** Ghi các kết quả chưa gửi xuống đĩa (gửi chưa được xác nhận / daemon sắp dừng). */
|
|
107
|
-
persist() {
|
|
161
|
+
persist({ sync = false } = {}) {
|
|
108
162
|
for (const e of calls.values()) if (e.state === CallState.DONE && !e.sent) e.onDisk = true;
|
|
109
|
-
|
|
163
|
+
if (sync) persistSync();
|
|
164
|
+
else schedulePersist();
|
|
165
|
+
},
|
|
166
|
+
/** Đẩy ngay các thay đổi đang chờ ghi bất đồng bộ xuống đĩa. */
|
|
167
|
+
flush() {
|
|
168
|
+
return persistTimer ? enqueueAsyncPersist() : writeChain;
|
|
110
169
|
},
|
|
111
170
|
/** BE báo không còn ai chờ → bỏ kết quả chưa gửi của các lời gọi này. */
|
|
112
171
|
drop(callIds) {
|
|
@@ -118,7 +177,7 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
|
|
|
118
177
|
changed = true;
|
|
119
178
|
}
|
|
120
179
|
}
|
|
121
|
-
if (changed)
|
|
180
|
+
if (changed) schedulePersist();
|
|
122
181
|
},
|
|
123
182
|
unsent: () => [...calls.values()].filter((e) => e.state === CallState.DONE && !e.sent).map((e) => e.payload),
|
|
124
183
|
heldIds: () => [...calls.entries()].filter(([, e]) => e.state === CallState.RUNNING || (e.state === CallState.DONE && !e.sent)).map(([id]) => id),
|
|
@@ -17,6 +17,18 @@ const ALWAYS_BLOCKED = new Set([
|
|
|
17
17
|
'DOM.setFileInputFiles', 'Page.setInterceptFileChooserDialog', 'Browser.close', 'Browser.crash', 'Browser.crashGpuProcess',
|
|
18
18
|
]);
|
|
19
19
|
|
|
20
|
+
/**
|
|
21
|
+
* Phiên gắn vào đích của tiện ích (`chrome-extension://…` — service worker / trang nền, gồm tiện ích gom nhóm tab của Aivin có quyền `debugger`):
|
|
22
|
+
* Puppeteer tự gắn mọi đích nên chỉ cho khởi động lại đích đang chờ và gỡ phiên — không chạy script trong tiện ích (29/10/2026).
|
|
23
|
+
*/
|
|
24
|
+
export const EXTENSION_SESSION_ALLOWED = new Set([
|
|
25
|
+
'Runtime.runIfWaitingForDebugger', 'Target.setAutoAttach', 'Target.detachFromTarget', 'Runtime.releaseObject', 'Runtime.releaseObjectGroup',
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
export function isExtensionUrl(url) {
|
|
29
|
+
return /^\s*(chrome|edge)-extension:/i.test(String(url ?? ''));
|
|
30
|
+
}
|
|
31
|
+
|
|
20
32
|
export function isBlockedUrl(url) {
|
|
21
33
|
const u = String(url ?? '');
|
|
22
34
|
return BLOCKED_URL_RE.test(u) || BLOCKED_ABOUT_RE.test(u);
|
|
@@ -29,7 +41,8 @@ export function isBlockedUrl(url) {
|
|
|
29
41
|
export function applyDevicePolicy(msg, { downloadsDir }) {
|
|
30
42
|
const method = String(msg?.method || '');
|
|
31
43
|
const params = msg?.params || {};
|
|
32
|
-
|
|
44
|
+
// `Extensions.*`: nạp / gỡ tiện ích, đọc kho của tiện ích — cửa sổ Aivin mở với `--enable-unsafe-extension-debugging` (để CLI nạp tiện ích gom nhóm tab).
|
|
45
|
+
if (ALWAYS_BLOCKED.has(method) || method.startsWith('Extensions.')) return { error: `${method} is not allowed on this computer` };
|
|
33
46
|
if ((method === 'Target.setAutoAttach' || method === 'Target.attachToTarget') && params.flatten === false) {
|
|
34
47
|
return { error: 'Only flattened sessions are allowed' };
|
|
35
48
|
}
|