@aivin-labs/cli 1.0.8 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +25 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1912 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +142 -31
  9. package/bin/lib/remote/callLedger.mjs +1 -1
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +87 -5
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/codingAgents.mjs +293 -0
  14. package/bin/lib/remote/constants.mjs +61 -0
  15. package/bin/lib/remote/dailyBrowser.mjs +1 -1
  16. package/bin/lib/remote/desktop/index.mjs +272 -0
  17. package/bin/lib/remote/desktop/linux.mjs +144 -0
  18. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  19. package/bin/lib/remote/desktop/mac.mjs +187 -0
  20. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  21. package/bin/lib/remote/desktop/strings.mjs +74 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  23. package/bin/lib/remote/docText.mjs +1 -1
  24. package/bin/lib/remote/fileIndexer.mjs +1 -1
  25. package/bin/lib/remote/gui/index.mjs +93 -12
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +280 -28
  27. package/bin/lib/remote/idempotency.mjs +1 -1
  28. package/bin/lib/remote/localPolicy.mjs +9 -2
  29. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  30. package/bin/lib/remote/mascot/ask.mjs +768 -0
  31. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  32. package/bin/lib/remote/mascot/assets.mjs +825 -216
  33. package/bin/lib/remote/mascot/bot.mjs +372 -0
  34. package/bin/lib/remote/mascot/hostSource.mjs +498 -101
  35. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  36. package/bin/lib/remote/mascot/index.mjs +199 -28
  37. package/bin/lib/remote/mascot/labels.mjs +2 -3
  38. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  39. package/bin/lib/remote/mascot/strings.mjs +204 -18
  40. package/bin/lib/remote/mascot/ui.mjs +104 -0
  41. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  42. package/bin/lib/remote/meeting/index.mjs +415 -0
  43. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  44. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  45. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  46. package/bin/lib/remote/tabGroups.mjs +209 -0
  47. package/bin/lib/remote/toolHandlers.mjs +15 -0
  48. package/docs/AIVIN_MASCOT.md +116 -0
  49. package/docs/CLI.md +142 -11
  50. package/docs/media/aivin-mascot-states.mp4 +0 -0
  51. package/package.json +1 -1
@@ -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, CHROME_DEBUG_PORT, LOCAL_BROWSERS, detectDefaultBrowserId, launchLocalChromeWithDebugging, probeLocalChromeDebugger,
6
+ AIVIN_BROWSER_PROFILE_DIR, DEBUG_PORTS, LOCAL_BROWSERS, detectDefaultBrowserId, launchLocalChromeWithDebugging, probeLocalChromeDebugger,
7
7
  resolveBrowserInstall,
8
- } from '../browserAutomation.mjs';
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 DEBUG_PORTS) {
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,20 +83,32 @@ 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
- return { wsUrl: await launchLocalChromeWithDebugging(freePort, preferredId), browserId: preferredId };
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
- /** 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`. */
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
- function pipeTunnel({ relayUrl, deviceToken, chromeWsUrl, signal, downloadsDir }) {
89
- const toBackend = new WSClient(relayUrl, { headers: { Authorization: `Device ${tokenOf(deviceToken)}` }, agent: proxyAgentFor(relayUrl) });
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|"targetId"/;
99
+
100
+ /**
101
+ * 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:
102
+ * 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`).
103
+ * `onAivinTarget(targetId)` — tab AI vừa mở (`Target.createTarget` của BE, hoặc tab bật ra từ tab đó).
104
+ */
105
+ export function pipeTunnel({ relayUrl, authorization, chromeWsUrl, signal, downloadsDir, onAivinTarget = () => {} }) {
106
+ const toBackend = new WSClient(relayUrl, { headers: { Authorization: authorization }, agent: proxyAgentFor(relayUrl) });
90
107
  const toChrome = new WSClient(chromeWsUrl, { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024 });
108
+ const extensionTargets = new Set();
109
+ const extensionSessions = new Set();
110
+ const aivinTargets = new Set();
111
+ const pendingCreates = new Set(); // `${sessionId}:${id}` của lệnh Target.createTarget chưa có trả lời
91
112
  const close = () => {
92
113
  try { toBackend.close(); } catch { /* đã đóng */ }
93
114
  try { toChrome.close(); } catch { /* đã đóng */ }
@@ -97,25 +118,65 @@ function pipeTunnel({ relayUrl, deviceToken, chromeWsUrl, signal, downloadsDir }
97
118
  from.on('close', close);
98
119
  from.on('error', close);
99
120
  };
121
+ const extensionBlock = (msg) => {
122
+ if (msg.sessionId && extensionSessions.has(msg.sessionId) && !EXTENSION_SESSION_ALLOWED.has(msg.method)) return `${msg.method} is not allowed on browser extensions`;
123
+ if (msg.method === 'Target.attachToTarget' && extensionTargets.has(msg.params?.targetId)) return 'Attaching to browser extensions is not allowed';
124
+ return null;
125
+ };
100
126
  toBackend.on('message', (data) => {
101
127
  let msg;
102
128
  try { msg = JSON.parse(String(data)); } catch { return; }
103
- const { msg: out, error } = applyDevicePolicy(msg, { downloadsDir });
129
+ const { msg: out, error: policyError } = applyDevicePolicy(msg, { downloadsDir });
130
+ const error = policyError || extensionBlock(msg);
104
131
  if (error) {
105
132
  if (msg.id !== undefined && toBackend.readyState === WSClient.OPEN) {
106
133
  toBackend.send(JSON.stringify({ id: msg.id, ...(msg.sessionId ? { sessionId: msg.sessionId } : {}), error: { code: -32000, message: error } }));
107
134
  }
108
135
  return;
109
136
  }
137
+ if (msg.method === 'Target.createTarget' && msg.id !== undefined) pendingCreates.add(`${msg.sessionId || ''}:${msg.id}`);
110
138
  if (toChrome.readyState === WSClient.OPEN) toChrome.send(JSON.stringify(out));
111
139
  });
112
140
  toBackend.on('close', close);
113
141
  toBackend.on('error', close);
142
+ const noteTarget = (info) => {
143
+ if (!info?.targetId) return;
144
+ if (isExtensionUrl(info.url)) extensionTargets.add(info.targetId);
145
+ };
146
+ const markAivin = (targetId) => {
147
+ if (!targetId || aivinTargets.has(targetId)) return;
148
+ aivinTargets.add(targetId);
149
+ try { onAivinTarget(targetId); } catch { /* gom nhóm chỉ là hiển thị */ }
150
+ };
114
151
  // 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
152
  let cancelId = 2_000_000_000;
116
153
  toChrome.on('message', (data) => {
117
- const guid = executableDownloadGuid(data);
154
+ const text = String(data);
155
+ const guid = executableDownloadGuid(text);
118
156
  if (guid && toChrome.readyState === WSClient.OPEN) toChrome.send(JSON.stringify({ id: cancelId++, method: 'Browser.cancelDownload', params: { guid } }));
157
+ if (!UPSTREAM_INTEREST_RE.test(text)) return;
158
+ let msg;
159
+ try { msg = JSON.parse(text); } catch { return; }
160
+ const params = msg.params || {};
161
+ if (msg.id !== undefined) {
162
+ const key = `${msg.sessionId || ''}:${msg.id}`;
163
+ if (pendingCreates.delete(key) && msg.result?.targetId) markAivin(msg.result.targetId);
164
+ // Target.getTargets / getTargetInfo: biết đích tiện ích trước khi BE xin gắn thẳng vào nó.
165
+ for (const info of msg.result?.targetInfos || []) noteTarget(info);
166
+ noteTarget(msg.result?.targetInfo);
167
+ return;
168
+ }
169
+ if (msg.method === 'Target.attachedToTarget') {
170
+ noteTarget(params.targetInfo);
171
+ if (params.sessionId && isExtensionUrl(params.targetInfo?.url)) extensionSessions.add(params.sessionId);
172
+ } else if (msg.method === 'Target.detachedFromTarget') {
173
+ extensionSessions.delete(params.sessionId);
174
+ } else if (msg.method === 'Target.targetCreated' || msg.method === 'Target.targetInfoChanged') {
175
+ noteTarget(params.targetInfo);
176
+ // Tab bật ra từ tab AI (window.open, target=_blank) cũng là của AI.
177
+ const info = params.targetInfo;
178
+ if (msg.method === 'Target.targetCreated' && info?.type === 'page' && aivinTargets.has(info.openerId)) markAivin(info.targetId);
179
+ }
119
180
  });
120
181
  relay(toChrome, toBackend);
121
182
  const opened = (ws) => new Promise((resolve, reject) => {
@@ -132,8 +193,8 @@ function pipeTunnel({ relayUrl, deviceToken, chromeWsUrl, signal, downloadsDir }
132
193
  }
133
194
 
134
195
  /** Đườ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, deviceToken, mux, signal }) {
136
- const toBackend = new WSClient(relayUrl, { headers: { Authorization: `Device ${tokenOf(deviceToken)}` }, agent: proxyAgentFor(relayUrl) });
196
+ function pipeTunnelToMux({ relayUrl, authorization, mux, signal }) {
197
+ const toBackend = new WSClient(relayUrl, { headers: { Authorization: authorization }, agent: proxyAgentFor(relayUrl) });
137
198
  let client = null;
138
199
  let closed = false;
139
200
  const early = [];
@@ -196,14 +257,34 @@ async function findDownload(dir, name, since, signal) {
196
257
  /**
197
258
  * 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
259
  * tin ghép máy. `ensureBrowser` thay được trong test (không mở trình duyệt thật).
260
+ *
261
+ * `authorization` — header xác thực đầy đủ (chuỗi / hàm), thay cho `Device <token máy>`: `aivin browser` dùng `Bearer <API key>`.
262
+ * `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
263
+ * 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
264
  */
200
265
  export function createBrowserTunnels({
201
- serverUrl, deviceToken, browser, downloadsDir = AIVIN_DOWNLOADS_DIR, say = () => {}, ensureBrowser = ensureAivinBrowser,
266
+ serverUrl, deviceToken, authorization, browser, downloadsDir = AIVIN_DOWNLOADS_DIR, say = () => {}, ensureBrowser = ensureAivinBrowser,
202
267
  useDailyBrowser = true, findDaily = findDailyBrowser, createMux = createCdpMux, notify = showOSNotification,
268
+ groupTabs = true, createGrouper = createTabGrouper,
203
269
  }) {
204
- const live = new Set();
270
+ const live = new Map(); // tunnelId → { close, done, deliberate }
205
271
  let daily = null;
206
272
  let dailyCooldownUntil = 0;
273
+ let grouper = null; // { wsUrl, g } — một bộ gom nhóm cho cửa sổ Aivin đang dùng
274
+ const authHeader = () => (authorization ? tokenOf(authorization) : `Device ${tokenOf(deviceToken)}`);
275
+
276
+ function grouperFor(wsUrl) {
277
+ if (!groupTabs || !wsUrl) return null;
278
+ if (grouper?.wsUrl !== wsUrl) {
279
+ grouper?.g.close();
280
+ const g = createGrouper({
281
+ wsUrl,
282
+ 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) }),
283
+ });
284
+ grouper = { wsUrl, g };
285
+ }
286
+ return grouper.g;
287
+ }
207
288
 
208
289
  /** 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
290
  async function dailyBrowser() {
@@ -216,12 +297,13 @@ export function createBrowserTunnels({
216
297
  const onBlocked = ({ method, reason, targetId }) => {
217
298
  if (blockedSeen.has(method) || blockedSeen.size > 50) return;
218
299
  blockedSeen.add(method);
219
- say(`🛡️ Đã chặn ${method} trên ${found.name} của bạn — ${reason}${targetId ? ` (tab ${String(targetId).slice(0, 8)})` : ''}`);
300
+ 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
301
  };
221
- daily = { ...found, mux: createMux({ wsUrl: found.wsUrl, downloadsDir, onBlocked, onClosed: () => say(`🔌 Đã nhả ${found.name} hằng ngày của bạn`) }) };
302
+ const onClosed = () => say(`🔌 Đã nhả ${found.name} hằng ngày của bạn`, { type: 'released', browser: found.name });
303
+ daily = { ...found, mux: createMux({ wsUrl: found.wsUrl, downloadsDir, onBlocked, onClosed }) };
222
304
  }
223
305
  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}.`);
306
+ 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
307
  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
308
  }
227
309
  try {
@@ -229,7 +311,7 @@ export function createBrowserTunnels({
229
311
  return daily;
230
312
  } catch (e) {
231
313
  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.`);
314
+ 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
315
  return null;
234
316
  }
235
317
  }
@@ -244,9 +326,14 @@ export function createBrowserTunnels({
244
326
  assertNotAborted(ctx?.signal);
245
327
  await fs.promises.mkdir(downloadsDir, { recursive: true }).catch(() => undefined);
246
328
  const relayUrl = `${serverUrl.replace(/^http/i, 'ws')}/browser-tunnel/external?tunnel_id=${encodeURIComponent(tunnelId)}`;
329
+ const g = shared ? null : grouperFor(wsUrl);
330
+ const title = groupTitle(typeof args?.label === 'string' ? args.label : '');
247
331
  const tunnel = shared
248
- ? pipeTunnelToMux({ relayUrl, deviceToken, mux: shared.mux, signal: ctx?.signal })
249
- : pipeTunnel({ relayUrl, deviceToken, chromeWsUrl: wsUrl, signal: ctx?.signal, downloadsDir });
332
+ ? pipeTunnelToMux({ relayUrl, authorization: authHeader(), mux: shared.mux, signal: ctx?.signal })
333
+ : pipeTunnel({
334
+ relayUrl, authorization: authHeader(), chromeWsUrl: wsUrl, signal: ctx?.signal, downloadsDir,
335
+ onAivinTarget: (targetId) => { g?.add(targetId, { key: tunnelId, title }); },
336
+ });
250
337
  try {
251
338
  await tunnel.ready;
252
339
  } catch (e) {
@@ -257,9 +344,20 @@ export function createBrowserTunnels({
257
344
  tunnel.close();
258
345
  assertNotAborted(ctx.signal);
259
346
  }
260
- live.add(tunnel);
261
- tunnel.done.then(() => live.delete(tunnel));
262
- say(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 ${browser?.name || ''} trên máy này`.trim());
347
+ const entry = { close: tunnel.close, deliberate: false };
348
+ close(tunnelId); // BE mở lại cùng tunnel_id (thử lại phía máy chủ) → thay đường hầm cũ
349
+ live.set(tunnelId, entry);
350
+ // `ctx.onClose({ deliberate })` — đường hầm đóng: do `close(tunnelId)` / `closeAll()` (deliberate) hay tự rớt (mạng, trình duyệt bị đóng).
351
+ tunnel.done.then(() => {
352
+ if (live.get(tunnelId) === entry) live.delete(tunnelId);
353
+ g?.forget(tunnelId);
354
+ ctx?.onClose?.({ deliberate: entry.deliberate });
355
+ });
356
+ const name = shared?.name || browser?.name || '';
357
+ say(
358
+ 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`,
359
+ { type: 'using', browser: name, daily: !!shared },
360
+ );
263
361
  return { browser: shared?.name || browser?.name, downloads_dir: downloadsDir, ...(shared ? { daily: true } : {}) };
264
362
  }
265
363
 
@@ -281,12 +379,25 @@ export function createBrowserTunnels({
281
379
  }
282
380
  }
283
381
 
382
+ /** Đóng một đường hầm (chủ động — `ctx.onClose` nhận `deliberate: true`). */
383
+ function close(tunnelId) {
384
+ const entry = live.get(tunnelId);
385
+ if (!entry) return;
386
+ entry.deliberate = true;
387
+ entry.close();
388
+ }
389
+
284
390
  function closeAll() {
285
- for (const t of live) t.close();
391
+ for (const entry of live.values()) {
392
+ entry.deliberate = true;
393
+ entry.close();
394
+ }
286
395
  live.clear();
287
396
  daily?.mux.close();
288
397
  daily = null;
398
+ grouper?.g.close();
399
+ grouper = null;
289
400
  }
290
401
 
291
- return { open, readDownload, closeAll, liveCount: () => live.size };
402
+ return { open, readDownload, close, closeAll, liveCount: () => live.size };
292
403
  }
@@ -45,7 +45,7 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
45
45
  }
46
46
 
47
47
  function load() {
48
- let rows = [];
48
+ let rows;
49
49
  try { rows = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return; }
50
50
  const t = now();
51
51
  for (const r of Array.isArray(rows) ? rows : []) {
@@ -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
- if (ALWAYS_BLOCKED.has(method)) return { error: `${method} is not allowed on this computer` };
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
  }
@@ -19,7 +19,13 @@ import { createScheduler } from './scheduler.mjs';
19
19
  import { acquireDaemonLock } from './daemonLock.mjs';
20
20
  import { randomUUID } from 'crypto';
21
21
  import { DeviceToolError, fullAccessRoots, isRemotePaused, setRemotePaused } from './sandbox.mjs';
22
- import { createMascot } from './mascot/index.mjs';
22
+ import { createMascot, HostEvent as MascotHostEvent } from './mascot/index.mjs';
23
+ import { createMascotChat } from './mascot/ask.mjs';
24
+ import { mascotLang } from './mascot/strings.mjs';
25
+ import { showOSNotification } from './notify.mjs';
26
+ import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs';
27
+ import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
28
+ import { createClipboard } from './clipboard.mjs';
23
29
  import { buildTools, toolMap } from './toolHandlers.mjs';
24
30
  import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
25
31
  import { createGuiController, detectGui } from './gui/index.mjs';
@@ -99,7 +105,7 @@ export function isValidDeviceCall(call) {
99
105
 
100
106
  function boundedResult(outcome) {
101
107
  if (!outcome.ok) return outcome;
102
- let size = 0;
108
+ let size;
103
109
  try { size = Buffer.byteLength(JSON.stringify(outcome.result ?? null)); } catch { size = MAX_RESULT_BYTES + 1; }
104
110
  if (size <= MAX_RESULT_BYTES) return outcome;
105
111
  return { ok: false, error: `Result too large (${size} bytes) — read smaller ranges`, error_code: DeviceErrorCode.OUTPUT_TOO_LARGE, duration_ms: outcome.duration_ms };
@@ -234,7 +240,11 @@ export async function startRemoteClient(options = {}) {
234
240
  const browserTunnels = browser ? createBrowserTunnels({ serverUrl, deviceToken: () => creds.device_token, browser, useDailyBrowser, say: (m) => say(chalk.cyan(m)) }) : null;
235
241
  // Một tiến trình host chung cho giao diện + Office (chỉ dựng khi lời gọi đầu tiên cần).
236
242
  const winHost = guiProfile || officeApps.length ? createWindowsHost() : null;
237
- const gui = guiProfile ? createGuiController({ fullAccess, host: winHost, say: (m) => say(chalk.magenta(m)) }) : null;
243
+ // Không nói cửa sổ mà focus đang ở linh vật (chủ máy vừa gõ vào ô hỏi) → cửa sổ họ đang dùng lúc hỏi (mascot/ask.mjs).
244
+ const gui = guiProfile ? createGuiController({
245
+ fullAccess, host: winHost, say: (m) => say(chalk.magenta(m)),
246
+ defaultWindow: () => (mascot.pid() ? { avoid_pid: mascot.pid(), fallback: mascotChat?.userWindow()?.window } : null),
247
+ }) : null;
238
248
  // Kho hoàn tác (xoá → thùng rác của kho, ghi đè → giữ bản cũ). Máy tính tổ chức: công cụ tệp chạy dưới tài khoản thành viên, không có kho.
239
249
  const undo = multiUser ? null : createUndoStore();
240
250
  void undo?.cleanup().catch(() => undefined);
@@ -260,7 +270,38 @@ export async function startRemoteClient(options = {}) {
260
270
  });
261
271
  // Tệp lớn đi HTTP thẳng với vé của BE (fs.upload / fs.download) — máy tính tổ chức không có (gửi HTTP chạy bằng tài khoản của daemon).
262
272
  const transfer = multiUser ? null : { serverUrl, deviceToken: () => creds.device_token };
263
- const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: winHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer };
273
+ // Ghi chú cuộc họp + chụp màn hình (meeting/) — Windows, máy cá nhân; tắt: --no-meetings / AIVIN_REMOTE_MEETINGS=0.
274
+ const media = !multiUser && mediaSupported() && options.meetings !== false && process.env.AIVIN_REMOTE_MEETINGS !== '0' ? createMediaHost() : null;
275
+ const meetings = media ? createMeetingManager({
276
+ roots, media, lang: mascotLang(),
277
+ say: (m) => say(chalk.cyan(m)),
278
+ notify: showOSNotification,
279
+ isPaused: isRemotePaused,
280
+ keepAwake,
281
+ // Đang nói chuyện với linh vật → không ghi biên bản họp (và ngược lại, xem micBusy của mascotChat).
282
+ micBusy: () => !!mascotChat?.inCall(),
283
+ // Chuyển chữ từng đoạn qua chính `device:stt` của ô hỏi linh vật; mất mạng thì chờ nối lại (tối đa 10 phút) rồi mới báo lỗi.
284
+ stt: async (audio, lang) => {
285
+ const deadline = Date.now() + 10 * 60_000;
286
+ while (!socket?.connected) {
287
+ if (Date.now() > deadline) throw new Error('offline');
288
+ await new Promise((r) => setTimeout(r, 5000));
289
+ }
290
+ return socket.timeout(60_000).emitWithAck(DeviceEvent.STT, { audio, lang });
291
+ },
292
+ // Lượt chat sau họp: qua ô hỏi của linh vật (câu trả lời hiện ở đó); không có linh vật thì gửi thẳng.
293
+ followUp: async (text) => {
294
+ if (!socket?.connected) return { ok: false, error: 'offline' };
295
+ if (mascotChat) {
296
+ if (mascotChat.busy()) return { ok: false, error: 'busy' };
297
+ void mascotChat.ask(text);
298
+ return { ok: true };
299
+ }
300
+ const ack = await socket.timeout(15_000).emitWithAck(DeviceEvent.CHAT, { text, request_id: `meeting-${Date.now()}` });
301
+ return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
302
+ },
303
+ }) : null;
304
+ const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: winHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard() };
264
305
  const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
265
306
  host?.start();
266
307
  const tools = buildTools(env);
@@ -277,8 +318,26 @@ export async function startRemoteClient(options = {}) {
277
318
  onPause: () => setRemotePaused(true),
278
319
  onResume: () => setRemotePaused(false),
279
320
  say: (m) => say(chalk.gray(` ${m}`)),
321
+ // Ô hỏi của linh vật: gõ / nói → lượt chat trên Aivin qua socket của máy (mascot/ask.mjs, dựng sau khi có socket).
322
+ // Gõ khi Aivin đang hỏi lại → là câu trả lời; nút lựa chọn → trả lời đúng lựa chọn đó.
323
+ onAsk: (text, window) => { void mascotChat?.reply(text, window); },
324
+ onChoose: (id) => { void mascotChat?.choose(id); },
325
+ onCancel: () => { void mascotChat?.cancel(); },
326
+ onNewChat: () => { void mascotChat?.newChat(); },
327
+ // Thả tệp vào bot → đi kèm câu gõ kế tiếp.
328
+ onDrop: (files) => mascotChat?.attach(files),
329
+ // Nói chuyện trực tiếp: mic / loa ở cửa sổ, phiên thoại realtime trên BE (mascot/ask.mjs).
330
+ onVoice: (msg) => {
331
+ if (!mascotChat) return;
332
+ if (msg.t === MascotHostEvent.VOICE_AUDIO) return mascotChat.voiceAudio(msg.audio);
333
+ if (msg.t === MascotHostEvent.VOICE_START) return void mascotChat.voiceStart(msg.window);
334
+ if (msg.t === MascotHostEvent.VOICE_INTERRUPT) return mascotChat.voiceInterrupt();
335
+ if (msg.t === MascotHostEvent.VOICE_STOP) return mascotChat.voiceStop();
336
+ if (msg.t === MascotHostEvent.VOICE_MIC_LOST) return mascotChat.voiceMicLost();
337
+ },
280
338
  });
281
339
  if (isRemotePaused()) mascot.paused(true);
340
+ let mascotChat = null;
282
341
 
283
342
  say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
284
343
  say(chalk.gray(` Máy: ${creds.name} (${creds.device_id})`));
@@ -294,7 +353,10 @@ export async function startRemoteClient(options = {}) {
294
353
  say(chalk.gray(` Trình duyệt: ${!browser ? 'không có Chrome / Edge — AI dùng trình duyệt trên máy chủ'
295
354
  : useDailyBrowser ? `${browser.name} hằng ngày của bạn nếu đã bật ${remoteDebuggingPage(browser.id)}, không thì cửa sổ riêng của Aivin`
296
355
  : `${browser.name} (cửa sổ riêng của Aivin)`}`));
356
+ say(chalk.gray(` Cuộc họp: ${meetings ? 'AI ghi chú được cuộc họp (âm thanh máy + micro, bạn bấm Cho phép mỗi lần) và chụp màn hình; tắt: --no-meetings' : 'không (chỉ Windows)'}`));
297
357
  if (isRemotePaused()) say(chalk.yellow(' ⏸ Đang TẠM DỪNG (aivin remote resume để nhận việc lại)'));
358
+ // `aivin remote meeting start|stop` gõ ở máy → daemon này; buổi ghi / biên bản dở từ lần chạy trước → làm nốt.
359
+ const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
298
360
 
299
361
  fileIndex?.build()
300
362
  .then((s) => { say(chalk.gray(` Chỉ mục tệp: ${s.files} tệp (${s.updated} cập nhật, ${s.ms} ms)`)); fileIndex.watch(); })
@@ -381,6 +443,9 @@ export async function startRemoteClient(options = {}) {
381
443
  ledger.persist();
382
444
  socket.disconnect();
383
445
  browserTunnels?.closeAll();
446
+ // Đóng tệp ghi họp cho đúng; biên bản làm ở lần chạy sau (meetings.recover).
447
+ stopMeetingRequests?.();
448
+ void meetings?.shutdown();
384
449
  gui?.close();
385
450
  winHost?.close();
386
451
  processes.stopAll();
@@ -406,7 +471,8 @@ export async function startRemoteClient(options = {}) {
406
471
  // Chỉ tự thoát để chuyển bản khi chắc có trình giữ chạy mở lại (detectSupervisor) — không thì chỉ nhắc.
407
472
  supervised: !!supervisor && options.handleSignals !== false,
408
473
  deviceId: creds.device_id,
409
- isIdle: () => activeCalls === 0 && !processes.hasRunning?.() && !(browserTunnels?.liveCount() > 0),
474
+ // Đang ghi họp / làm biên bản: không tự khởi động lại để cập nhật (mất đoạn ghi).
475
+ isIdle: () => activeCalls === 0 && !processes.hasRunning?.() && !(browserTunnels?.liveCount() > 0) && !meetings?.busy(),
410
476
  lastActivityAt: () => lastActivityAt,
411
477
  say: (m) => say(chalk.cyan(m)),
412
478
  onRestart: async (version) => {
@@ -457,6 +523,9 @@ export async function startRemoteClient(options = {}) {
457
523
  if (!multiUser) profile.update = updateProfile({ enabled: autoUpdateEnabled });
458
524
  const hello = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.HELLO, { protocol: PROTOCOL_VERSION, profile, catalog_hash: hash, inflight: ledger.heldIds() });
459
525
  serverResume = Array.isArray(hello?.features) && hello.features.includes(ServerFeature.RESUME);
526
+ mascotChat?.setServerFeatures(hello?.features);
527
+ // Báo chủ động lỡ trong lúc offline + câu hỏi đang ghim đã đóng ở nơi khác (BE có hộp báo).
528
+ void mascotChat?.syncInbox();
460
529
  // Việc máy còn giữ mà BE không còn chờ (đã huỷ / hết giờ lúc máy mất mạng — lệnh huỷ không tới được máy): dừng ngay, bỏ kết quả.
461
530
  const orphaned = Array.isArray(hello?.orphaned) ? hello.orphaned.filter((id) => typeof id === 'string') : [];
462
531
  if (orphaned.length) {
@@ -625,6 +694,7 @@ export async function startRemoteClient(options = {}) {
625
694
  say(chalk.yellow(`⚠️ Mất kết nối (${reason}) — tự nối lại...`));
626
695
  logActivity({ type: 'disconnected', reason });
627
696
  mascot.disconnected();
697
+ mascotChat?.voiceDisconnected();
628
698
  // Server chủ động cắt (BE khởi động lại, socket khác của máy này vừa thay chỗ…) → socket.io-client KHÔNG tự nối lại; nối tay, giãn nhịp.
629
699
  if (reason === 'io server disconnect') {
630
700
  const delay = Math.min(30_000, 1000 * 2 ** Math.min(serverKicks++, 5)) + Math.floor(Math.random() * 500);
@@ -678,6 +748,18 @@ export async function startRemoteClient(options = {}) {
678
748
  scheduler.cancel(ids);
679
749
  cancelGating(ids);
680
750
  }));
751
+ if (mascot.enabled) {
752
+ mascotChat = createMascotChat({
753
+ socket: () => socket, send: (cmd) => mascot.chat(cmd), lang: mascot.lang,
754
+ onAlert: (alert) => mascot.alert(alert), onPending: (on) => mascot.needsYou(on),
755
+ micBusy: () => !!meetings?.status()?.recording,
756
+ });
757
+ socket.on(DeviceEvent.CHAT_EVENT, guarded(DeviceEvent.CHAT_EVENT, (payload) => mascotChat.onChatEvent(payload)));
758
+ // Báo chủ động: việc của chủ máy (web, chạy nền, automation…) xong / lỗi / cần trả lời.
759
+ socket.on(DeviceEvent.NOTIFY, guarded(DeviceEvent.NOTIFY, (payload) => mascotChat.onNotify(payload)));
760
+ socket.on(DeviceEvent.VOICE_EVENT, guarded(DeviceEvent.VOICE_EVENT, (payload) => mascotChat.onVoiceEvent(payload)));
761
+ }
762
+ meetings?.recover();
681
763
 
682
764
  // Lưới cuối: promise bị từ chối mà không ai bắt → ghi log, KHÔNG thoát (daemon phục vụ cả tổ chức, chết là mất mọi lời gọi đang chạy).
683
765
  if (!unhandledRejectionHooked) {