@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
|
@@ -16,10 +16,16 @@ import { ensureMemoryLoaded, memoryStats, stopWatchingMemory, watchMemoryDir } f
|
|
|
16
16
|
import { buildCatalog, buildDeviceProfile } from './deviceProfile.mjs';
|
|
17
17
|
import { createFileIndex, indexRootsFor } from './fileIndexer.mjs';
|
|
18
18
|
import { createScheduler } from './scheduler.mjs';
|
|
19
|
-
import { acquireDaemonLock } from './daemonLock.mjs';
|
|
19
|
+
import { acquireDaemonLock, lockHolder } 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';
|
|
@@ -33,6 +39,8 @@ import { createScheduleManager } from './schedule.mjs';
|
|
|
33
39
|
import { remoteDebuggingPage } from './dailyBrowser.mjs';
|
|
34
40
|
import { HOME_BASE, SHARED_DIR, createMultiUserHost, isMultiUserMode } from './multiUser.mjs';
|
|
35
41
|
import { createAutoUpdater } from './autoUpdate.mjs';
|
|
42
|
+
import { createDesktopCastManager } from './desktop/desktopCast.mjs';
|
|
43
|
+
import { createDesktopWebRtc } from './desktop/desktopWebRtc.mjs';
|
|
36
44
|
import {
|
|
37
45
|
BootAction, MAX_BOOTS_BEFORE_ROLLBACK, RESTART_EXIT_CODE, UPDATE_CONFIRM_AFTER_MS, UPDATE_ROLLED_BACK, checkBootAfterUpdate, cleanupRetired, clearStaleInstalledMarker,
|
|
38
46
|
confirmUpdate, ingestSupervisorRollback, isStandaloneBinary, noteCleanExit, updateProfile,
|
|
@@ -99,7 +107,7 @@ export function isValidDeviceCall(call) {
|
|
|
99
107
|
|
|
100
108
|
function boundedResult(outcome) {
|
|
101
109
|
if (!outcome.ok) return outcome;
|
|
102
|
-
let size
|
|
110
|
+
let size;
|
|
103
111
|
try { size = Buffer.byteLength(JSON.stringify(outcome.result ?? null)); } catch { size = MAX_RESULT_BYTES + 1; }
|
|
104
112
|
if (size <= MAX_RESULT_BYTES) return outcome;
|
|
105
113
|
return { ok: false, error: `Result too large (${size} bytes) — read smaller ranges`, error_code: DeviceErrorCode.OUTPUT_TOO_LARGE, duration_ms: outcome.duration_ms };
|
|
@@ -135,6 +143,24 @@ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name,
|
|
|
135
143
|
return creds;
|
|
136
144
|
}
|
|
137
145
|
|
|
146
|
+
/**
|
|
147
|
+
* `aivin remote pair --code`: chỉ ghép máy, không nhận việc — bộ cài dùng khi đã có khay (khay thấy máy đã ghép là mở listener ngay,
|
|
148
|
+
* người dùng đóng được cửa sổ cài). Listener đang chạy bằng token cũ thì dừng nó để khay mở lại bằng token mới. Trả pid đã dừng (hoặc null).
|
|
149
|
+
*/
|
|
150
|
+
export async function pairWithCodeOnly(options) {
|
|
151
|
+
const serverUrl = resolveServerUrl(options, loadDeviceCredentials());
|
|
152
|
+
configureProxy({ explicit: options.proxy });
|
|
153
|
+
const fullAccess = !options.dir && !!options.fullAccess;
|
|
154
|
+
const roots = (fullAccess ? fullAccessRoots() : [options.dir || process.cwd()]).map((r) => path.resolve(r));
|
|
155
|
+
const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
|
|
156
|
+
const profile = { ...buildDeviceProfile(fullAccess ? [os.homedir()] : roots), roots, access };
|
|
157
|
+
const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
|
|
158
|
+
saveDeviceCredentials({ ...creds, access });
|
|
159
|
+
const stale = lockHolder();
|
|
160
|
+
if (stale) try { process.kill(stale); } catch { /* vừa tự thoát */ }
|
|
161
|
+
return { creds, stopped: stale };
|
|
162
|
+
}
|
|
163
|
+
|
|
138
164
|
/**
|
|
139
165
|
* Daemon nhận việc từ BE (`aivin remote start`): ghép máy (token thiết bị riêng), nối namespace `/device`, công bố hồ sơ + danh mục công
|
|
140
166
|
* cụ theo năng lực máy, nhận lô lời gọi, chạy song song theo nhóm, trả kết quả + luồng stdout. Thư mục gốc, công tắc ngắt, lọc biến môi
|
|
@@ -232,9 +258,14 @@ export async function startRemoteClient(options = {}) {
|
|
|
232
258
|
const fileIndex = multiUser ? null : createFileIndex(indexRootsFor(roots, fullAccess));
|
|
233
259
|
const useDailyBrowser = options.separateBrowser !== true;
|
|
234
260
|
const browserTunnels = browser ? createBrowserTunnels({ serverUrl, deviceToken: () => creds.device_token, browser, useDailyBrowser, say: (m) => say(chalk.cyan(m)) }) : null;
|
|
235
|
-
//
|
|
236
|
-
const
|
|
237
|
-
const
|
|
261
|
+
// Tiến trình host riêng cho giao diện và cho Office COM (chỉ dựng khi lời gọi đầu tiên cần) — một lệnh COM treo / bị huỷ không làm mất snapshot giao diện.
|
|
262
|
+
const guiHost = guiProfile ? createWindowsHost() : null;
|
|
263
|
+
const officeHost = officeApps.length ? createWindowsHost() : null;
|
|
264
|
+
// 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).
|
|
265
|
+
const gui = guiProfile ? createGuiController({
|
|
266
|
+
fullAccess, host: guiHost, say: (m) => say(chalk.magenta(m)),
|
|
267
|
+
defaultWindow: () => (mascot.pid() ? { avoid_pid: mascot.pid(), fallback: mascotChat?.userWindow()?.window } : null),
|
|
268
|
+
}) : null;
|
|
238
269
|
// 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
270
|
const undo = multiUser ? null : createUndoStore();
|
|
240
271
|
void undo?.cleanup().catch(() => undefined);
|
|
@@ -260,13 +291,45 @@ export async function startRemoteClient(options = {}) {
|
|
|
260
291
|
});
|
|
261
292
|
// 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
293
|
const transfer = multiUser ? null : { serverUrl, deviceToken: () => creds.device_token };
|
|
263
|
-
|
|
294
|
+
// 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.
|
|
295
|
+
const media = !multiUser && mediaSupported() && options.meetings !== false && process.env.AIVIN_REMOTE_MEETINGS !== '0' ? createMediaHost() : null;
|
|
296
|
+
const meetings = media ? createMeetingManager({
|
|
297
|
+
roots, media, lang: mascotLang(),
|
|
298
|
+
say: (m) => say(chalk.cyan(m)),
|
|
299
|
+
notify: showOSNotification,
|
|
300
|
+
isPaused: isRemotePaused,
|
|
301
|
+
keepAwake,
|
|
302
|
+
// Đ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).
|
|
303
|
+
micBusy: () => !!mascotChat?.inCall(),
|
|
304
|
+
// 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.
|
|
305
|
+
stt: async (audio, lang) => {
|
|
306
|
+
const deadline = Date.now() + 10 * 60_000;
|
|
307
|
+
while (!socket?.connected) {
|
|
308
|
+
if (Date.now() > deadline) throw new Error('offline');
|
|
309
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
310
|
+
}
|
|
311
|
+
return socket.timeout(60_000).emitWithAck(DeviceEvent.STT, { audio, lang });
|
|
312
|
+
},
|
|
313
|
+
// 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.
|
|
314
|
+
followUp: async (text) => {
|
|
315
|
+
if (!socket?.connected) return { ok: false, error: 'offline' };
|
|
316
|
+
if (mascotChat) {
|
|
317
|
+
if (mascotChat.busy()) return { ok: false, error: 'busy' };
|
|
318
|
+
void mascotChat.ask(text);
|
|
319
|
+
return { ok: true };
|
|
320
|
+
}
|
|
321
|
+
const ack = await socket.timeout(15_000).emitWithAck(DeviceEvent.CHAT, { text, request_id: `meeting-${Date.now()}` });
|
|
322
|
+
return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
|
|
323
|
+
},
|
|
324
|
+
}) : null;
|
|
325
|
+
const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: officeHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard() };
|
|
264
326
|
const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
|
|
265
327
|
host?.start();
|
|
266
328
|
const tools = buildTools(env);
|
|
267
329
|
const byName = toolMap(tools);
|
|
268
330
|
// Công cụ chủ máy tắt (`aivin remote policy deny`) không vào danh mục — Planner không lập kế hoạch với nó (gọi tới vẫn bị chặn ở sàn luật).
|
|
269
331
|
const deniedTools = new Set(policyGuard.read().deny_tools);
|
|
332
|
+
if (deniedTools.has('gui.act')) deniedTools.add('gui.do');
|
|
270
333
|
const { catalog, hash } = buildCatalog(tools.filter((t) => !deniedTools.has(t.name)));
|
|
271
334
|
const confirmer = multiUser ? null : createLocalConfirmer();
|
|
272
335
|
// Nhiều người dùng: thêm trần song song theo từng thành viên — một người không chiếm hết chỗ của cả tổ chức.
|
|
@@ -277,8 +340,31 @@ export async function startRemoteClient(options = {}) {
|
|
|
277
340
|
onPause: () => setRemotePaused(true),
|
|
278
341
|
onResume: () => setRemotePaused(false),
|
|
279
342
|
say: (m) => say(chalk.gray(` ${m}`)),
|
|
343
|
+
// Ô 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).
|
|
344
|
+
// 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 đó.
|
|
345
|
+
onAsk: (text, window) => { void mascotChat?.reply(text, window); },
|
|
346
|
+
onChoose: (id) => { void mascotChat?.choose(id); },
|
|
347
|
+
onCancel: () => { void mascotChat?.cancel(); },
|
|
348
|
+
onNewChat: () => { void mascotChat?.newChat(); },
|
|
349
|
+
// Thả tệp vào bot → đi kèm câu gõ kế tiếp.
|
|
350
|
+
onDrop: (files) => mascotChat?.attach(files),
|
|
351
|
+
// Nói chuyện trực tiếp: mic / loa ở cửa sổ, phiên thoại realtime trên BE (mascot/ask.mjs).
|
|
352
|
+
onVoice: (msg) => {
|
|
353
|
+
if (!mascotChat) return;
|
|
354
|
+
if (msg.t === MascotHostEvent.VOICE_AUDIO) return mascotChat.voiceAudio(msg.audio);
|
|
355
|
+
if (msg.t === MascotHostEvent.VOICE_START) return void mascotChat.voiceStart(msg.window);
|
|
356
|
+
if (msg.t === MascotHostEvent.VOICE_INTERRUPT) return mascotChat.voiceInterrupt();
|
|
357
|
+
if (msg.t === MascotHostEvent.VOICE_STOP) return mascotChat.voiceStop();
|
|
358
|
+
if (msg.t === MascotHostEvent.VOICE_MIC_LOST) return mascotChat.voiceMicLost();
|
|
359
|
+
},
|
|
280
360
|
});
|
|
281
361
|
if (isRemotePaused()) mascot.paused(true);
|
|
362
|
+
const desktopCast = createDesktopCastManager();
|
|
363
|
+
const desktopWebRtc = createDesktopWebRtc({
|
|
364
|
+
emitSignal: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_SIGNAL, payload); },
|
|
365
|
+
emitStatus: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, payload); },
|
|
366
|
+
});
|
|
367
|
+
let mascotChat = null;
|
|
282
368
|
|
|
283
369
|
say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
|
|
284
370
|
say(chalk.gray(` Máy: ${creds.name} (${creds.device_id})`));
|
|
@@ -294,8 +380,12 @@ export async function startRemoteClient(options = {}) {
|
|
|
294
380
|
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
381
|
: 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
382
|
: `${browser.name} (cửa sổ riêng của Aivin)`}`));
|
|
383
|
+
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
384
|
if (isRemotePaused()) say(chalk.yellow(' ⏸ Đang TẠM DỪNG (aivin remote resume để nhận việc lại)'));
|
|
385
|
+
// `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.
|
|
386
|
+
const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
|
|
298
387
|
|
|
388
|
+
void gui?.prewarm?.();
|
|
299
389
|
fileIndex?.build()
|
|
300
390
|
.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(); })
|
|
301
391
|
.catch((e) => say(chalk.yellow(` ⚠️ Lập chỉ mục tệp lỗi: ${e.message}`)));
|
|
@@ -338,7 +428,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
338
428
|
void scheduler.cancelAll('Remote control was paused on this device');
|
|
339
429
|
cancelGating([...gating.keys()]);
|
|
340
430
|
browserTunnels?.closeAll();
|
|
341
|
-
|
|
431
|
+
guiHost?.close();
|
|
432
|
+
officeHost?.close();
|
|
342
433
|
processes.stopAll();
|
|
343
434
|
}
|
|
344
435
|
if (paused !== pausedSeen) mascot.paused(paused);
|
|
@@ -378,11 +469,16 @@ export async function startRemoteClient(options = {}) {
|
|
|
378
469
|
if (selfManaged) noteCleanExit();
|
|
379
470
|
const draining = scheduler.cancelAll('The Aivin agent on this device stopped');
|
|
380
471
|
cancelGating([...gating.keys()]);
|
|
381
|
-
ledger.persist();
|
|
472
|
+
ledger.persist({ sync: true });
|
|
382
473
|
socket.disconnect();
|
|
383
474
|
browserTunnels?.closeAll();
|
|
475
|
+
// Đóng tệp ghi họp cho đúng; biên bản làm ở lần chạy sau (meetings.recover).
|
|
476
|
+
stopMeetingRequests?.();
|
|
477
|
+
void meetings?.shutdown();
|
|
384
478
|
gui?.close();
|
|
385
|
-
|
|
479
|
+
guiHost?.close();
|
|
480
|
+
officeHost?.close();
|
|
481
|
+
desktopCast.stop();
|
|
386
482
|
processes.stopAll();
|
|
387
483
|
keepAwake.close();
|
|
388
484
|
watches?.closeAll();
|
|
@@ -406,7 +502,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
406
502
|
// 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
503
|
supervised: !!supervisor && options.handleSignals !== false,
|
|
408
504
|
deviceId: creds.device_id,
|
|
409
|
-
|
|
505
|
+
// Đ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).
|
|
506
|
+
isIdle: () => activeCalls === 0 && !processes.hasRunning?.() && !(browserTunnels?.liveCount() > 0) && !meetings?.busy(),
|
|
410
507
|
lastActivityAt: () => lastActivityAt,
|
|
411
508
|
say: (m) => say(chalk.cyan(m)),
|
|
412
509
|
onRestart: async (version) => {
|
|
@@ -457,6 +554,9 @@ export async function startRemoteClient(options = {}) {
|
|
|
457
554
|
if (!multiUser) profile.update = updateProfile({ enabled: autoUpdateEnabled });
|
|
458
555
|
const hello = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.HELLO, { protocol: PROTOCOL_VERSION, profile, catalog_hash: hash, inflight: ledger.heldIds() });
|
|
459
556
|
serverResume = Array.isArray(hello?.features) && hello.features.includes(ServerFeature.RESUME);
|
|
557
|
+
mascotChat?.setServerFeatures(hello?.features);
|
|
558
|
+
// 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).
|
|
559
|
+
void mascotChat?.syncInbox();
|
|
460
560
|
// 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
561
|
const orphaned = Array.isArray(hello?.orphaned) ? hello.orphaned.filter((id) => typeof id === 'string') : [];
|
|
462
562
|
if (orphaned.length) {
|
|
@@ -625,6 +725,7 @@ export async function startRemoteClient(options = {}) {
|
|
|
625
725
|
say(chalk.yellow(`⚠️ Mất kết nối (${reason}) — tự nối lại...`));
|
|
626
726
|
logActivity({ type: 'disconnected', reason });
|
|
627
727
|
mascot.disconnected();
|
|
728
|
+
mascotChat?.voiceDisconnected();
|
|
628
729
|
// 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
730
|
if (reason === 'io server disconnect') {
|
|
630
731
|
const delay = Math.min(30_000, 1000 * 2 ** Math.min(serverKicks++, 5)) + Math.floor(Math.random() * 500);
|
|
@@ -678,6 +779,68 @@ export async function startRemoteClient(options = {}) {
|
|
|
678
779
|
scheduler.cancel(ids);
|
|
679
780
|
cancelGating(ids);
|
|
680
781
|
}));
|
|
782
|
+
if (mascot.enabled) {
|
|
783
|
+
mascotChat = createMascotChat({
|
|
784
|
+
socket: () => socket, send: (cmd) => mascot.chat(cmd), lang: mascot.lang,
|
|
785
|
+
onAlert: (alert) => mascot.alert(alert), onPending: (on) => mascot.needsYou(on),
|
|
786
|
+
micBusy: () => !!meetings?.status()?.recording,
|
|
787
|
+
});
|
|
788
|
+
socket.on(DeviceEvent.CHAT_EVENT, guarded(DeviceEvent.CHAT_EVENT, (payload) => mascotChat.onChatEvent(payload)));
|
|
789
|
+
// 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.
|
|
790
|
+
socket.on(DeviceEvent.NOTIFY, guarded(DeviceEvent.NOTIFY, (payload) => mascotChat.onNotify(payload)));
|
|
791
|
+
socket.on(DeviceEvent.VOICE_EVENT, guarded(DeviceEvent.VOICE_EVENT, (payload) => mascotChat.onVoiceEvent(payload)));
|
|
792
|
+
}
|
|
793
|
+
socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
|
|
794
|
+
const sessionId = payload?.session_id;
|
|
795
|
+
const viewerId = payload?.viewer_id;
|
|
796
|
+
const webRtcStarted = payload?.transport === 'webrtc' && sessionId && viewerId
|
|
797
|
+
? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [] }).catch(() => false)
|
|
798
|
+
: false;
|
|
799
|
+
if (!desktopCast.isActive()) desktopCast.start({
|
|
800
|
+
sessionId: payload?.session_id,
|
|
801
|
+
maxFps: payload?.max_fps || 15,
|
|
802
|
+
maxWidth: payload?.max_width || 1366,
|
|
803
|
+
quality: payload?.quality || 65,
|
|
804
|
+
monitor: payload?.monitor ?? -1,
|
|
805
|
+
onFrame: (frame) => {
|
|
806
|
+
desktopWebRtc.push(frame);
|
|
807
|
+
// Chưa nối xong WebRTC hoặc runtime native không có → JPEG fallback vẫn cho first frame ngay.
|
|
808
|
+
if (desktopWebRtc.needsFallback() && socket.connected) socket.volatile.emit(DeviceEvent.DESKTOP_CAST_FRAME, frame);
|
|
809
|
+
},
|
|
810
|
+
onReady: (meta) => {
|
|
811
|
+
say(chalk.cyan(` 🖥️ Desktop Cast đang phát trực tiếp (${meta.bounds?.width}x${meta.bounds?.height})`));
|
|
812
|
+
if (socket.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, {
|
|
813
|
+
session_id: sessionId, viewer_id: viewerId, state: 'ready', transport: webRtcStarted ? 'webrtc' : 'jpeg', bounds: meta.bounds,
|
|
814
|
+
});
|
|
815
|
+
},
|
|
816
|
+
onError: (err) => {
|
|
817
|
+
say(chalk.yellow(` ⚠️ Desktop Cast lỗi: ${err?.message || err}`));
|
|
818
|
+
},
|
|
819
|
+
onStop: () => {
|
|
820
|
+
say(chalk.gray(` ⏹ Desktop Cast đã dừng`));
|
|
821
|
+
},
|
|
822
|
+
});
|
|
823
|
+
if (!webRtcStarted && socket.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, {
|
|
824
|
+
session_id: sessionId, viewer_id: viewerId, state: 'degraded', transport: 'jpeg', reason: 'webrtc_runtime_unavailable',
|
|
825
|
+
});
|
|
826
|
+
}));
|
|
827
|
+
socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
|
|
828
|
+
if (payload?.viewer_id) desktopWebRtc.close(payload.viewer_id);
|
|
829
|
+
if (payload?.final !== false) {
|
|
830
|
+
desktopWebRtc.closeAll();
|
|
831
|
+
desktopCast.stop();
|
|
832
|
+
}
|
|
833
|
+
}));
|
|
834
|
+
socket.on(DeviceEvent.DESKTOP_CAST_INPUT, guarded(DeviceEvent.DESKTOP_CAST_INPUT, (payload) => {
|
|
835
|
+
desktopCast.sendInput(payload);
|
|
836
|
+
}));
|
|
837
|
+
socket.on(DeviceEvent.DESKTOP_CAST_CONFIG, guarded(DeviceEvent.DESKTOP_CAST_CONFIG, (payload) => {
|
|
838
|
+
desktopCast.config(payload);
|
|
839
|
+
}));
|
|
840
|
+
socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
|
|
841
|
+
void desktopWebRtc.signal(payload).catch(() => undefined);
|
|
842
|
+
}));
|
|
843
|
+
meetings?.recover();
|
|
681
844
|
|
|
682
845
|
// 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
846
|
if (!unhandledRejectionHooked) {
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
import { DeviceErrorCode, ToolGroup } from './constants.mjs';
|
|
3
|
+
import { DeviceToolError } from './sandbox.mjs';
|
|
4
|
+
import { findOnPath } from '../localBrowser.mjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Clipboard của máy (29/10/2026): "lấy cái tôi vừa copy", "dán kết quả vào clipboard cho tôi". Windows: chữ, ảnh (PNG), danh sách tệp đã
|
|
8
|
+
* copy trong Explorer; macOS (pbpaste / pbcopy) và Linux (wl-paste / xclip / xsel): chữ.
|
|
9
|
+
*
|
|
10
|
+
* Không đọc nội dung app đánh dấu riêng tư — trình quản lý mật khẩu (KeePass, 1Password, Bitwarden…) đặt định dạng
|
|
11
|
+
* `ExcludeClipboardContentFromMonitorProcessing` / `CanIncludeInClipboardHistory = 0` khi copy mật khẩu, chính lịch sử clipboard của Windows
|
|
12
|
+
* cũng bỏ qua — ở đây cũng vậy (trả `private: true`, không có nội dung).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const MAX_TEXT = 200_000;
|
|
16
|
+
const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
17
|
+
const TIMEOUT_MS = 15_000;
|
|
18
|
+
|
|
19
|
+
const PS_READ = String.raw`
|
|
20
|
+
$ErrorActionPreference = 'Stop'
|
|
21
|
+
[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
|
22
|
+
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
|
|
23
|
+
$d = [Windows.Forms.Clipboard]::GetDataObject()
|
|
24
|
+
$out = @{ formats = @() }
|
|
25
|
+
if ($d) { $out.formats = @($d.GetFormats()) }
|
|
26
|
+
$private = $false
|
|
27
|
+
if ($d -and $d.GetDataPresent('ExcludeClipboardContentFromMonitorProcessing')) { $private = $true }
|
|
28
|
+
if ($d -and $d.GetDataPresent('CanIncludeInClipboardHistory')) {
|
|
29
|
+
$s = $d.GetData('CanIncludeInClipboardHistory')
|
|
30
|
+
if ($s -is [IO.MemoryStream] -and $s.Length -ge 4) { $b = $s.ToArray(); if ([BitConverter]::ToInt32($b, 0) -eq 0) { $private = $true } }
|
|
31
|
+
}
|
|
32
|
+
if ($private) { $out.private = $true }
|
|
33
|
+
elseif ([Windows.Forms.Clipboard]::ContainsText()) { $out.text = [Windows.Forms.Clipboard]::GetText() }
|
|
34
|
+
elseif ([Windows.Forms.Clipboard]::ContainsFileDropList()) { $out.files = @([Windows.Forms.Clipboard]::GetFileDropList()) }
|
|
35
|
+
elseif ([Windows.Forms.Clipboard]::ContainsImage()) {
|
|
36
|
+
$img = [Windows.Forms.Clipboard]::GetImage(); $ms = New-Object IO.MemoryStream
|
|
37
|
+
$img.Save($ms, [Drawing.Imaging.ImageFormat]::Png)
|
|
38
|
+
$out.image = @{ mime = 'image/png'; base64 = [Convert]::ToBase64String($ms.ToArray()); width = $img.Width; height = $img.Height }
|
|
39
|
+
}
|
|
40
|
+
[Console]::Out.Write(($out | ConvertTo-Json -Compress -Depth 4))
|
|
41
|
+
`;
|
|
42
|
+
|
|
43
|
+
const PS_WRITE = String.raw`
|
|
44
|
+
$ErrorActionPreference = 'Stop'
|
|
45
|
+
[Console]::InputEncoding = [Text.Encoding]::UTF8
|
|
46
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
47
|
+
$t = [Console]::In.ReadToEnd()
|
|
48
|
+
if ($t.Length -eq 0) { [Windows.Forms.Clipboard]::Clear() } else { [Windows.Forms.Clipboard]::SetText($t) }
|
|
49
|
+
[Console]::Out.Write('{"ok":true}')
|
|
50
|
+
`;
|
|
51
|
+
|
|
52
|
+
function run(cmd, args, { input, signal, spawnImpl = spawn } = {}) {
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
const child = spawnImpl(cmd, args, { windowsHide: true });
|
|
55
|
+
const out = [];
|
|
56
|
+
let err = '';
|
|
57
|
+
const timer = setTimeout(() => { child.kill(); reject(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, 'Clipboard timed out')); }, TIMEOUT_MS);
|
|
58
|
+
const onAbort = () => { child.kill(); reject(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled')); };
|
|
59
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
60
|
+
child.stdout.on('data', (d) => out.push(d));
|
|
61
|
+
child.stderr.on('data', (d) => { err = (err + d).slice(-2000); });
|
|
62
|
+
child.on('error', (e) => { clearTimeout(timer); reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Cannot reach the clipboard: ${e.message}`)); });
|
|
63
|
+
child.on('close', (code) => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
signal?.removeEventListener('abort', onAbort);
|
|
66
|
+
if (code === 0) resolve(Buffer.concat(out).toString('utf8'));
|
|
67
|
+
else reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, err.trim().split(/\r?\n/).slice(-2).join(' ') || `Clipboard command failed (${code})`));
|
|
68
|
+
});
|
|
69
|
+
if (input !== undefined) child.stdin.end(input, 'utf8');
|
|
70
|
+
else child.stdin.end();
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const ps = (script) => ['powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-Command', script]];
|
|
75
|
+
|
|
76
|
+
/** Lệnh đọc / ghi chữ trên macOS / Linux theo công cụ có sẵn — không có → null. */
|
|
77
|
+
export function unixClipboardCommands({ platform = process.platform, env = process.env, onPath = (n) => findOnPath([n]) } = {}) {
|
|
78
|
+
if (platform === 'darwin') return { read: ['pbpaste', []], write: ['pbcopy', []] };
|
|
79
|
+
if (platform !== 'linux') return null;
|
|
80
|
+
if (env.WAYLAND_DISPLAY && onPath('wl-paste') && onPath('wl-copy')) return { read: ['wl-paste', ['--no-newline']], write: ['wl-copy', []] };
|
|
81
|
+
if (!env.DISPLAY) return null;
|
|
82
|
+
if (onPath('xclip')) return { read: ['xclip', ['-selection', 'clipboard', '-o']], write: ['xclip', ['-selection', 'clipboard']] };
|
|
83
|
+
if (onPath('xsel')) return { read: ['xsel', ['--clipboard', '--output']], write: ['xsel', ['--clipboard', '--input']] };
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `null` khi máy không có clipboard dùng được (máy chủ không màn hình, thiếu công cụ). */
|
|
88
|
+
export function createClipboard({ platform = process.platform, spawnImpl = spawn, unix = unixClipboardCommands({ platform }) } = {}) {
|
|
89
|
+
if (platform !== 'win32' && !unix) return null;
|
|
90
|
+
|
|
91
|
+
async function read(ctx) {
|
|
92
|
+
if (platform === 'win32') {
|
|
93
|
+
const [cmd, args] = ps(PS_READ);
|
|
94
|
+
const res = JSON.parse((await run(cmd, args, { signal: ctx?.signal, spawnImpl })) || '{}');
|
|
95
|
+
if (res.private) return { private: true, note: 'The app that copied this marked it private (e.g. a password manager) — it is not read.' };
|
|
96
|
+
if (typeof res.text === 'string') return { kind: 'text', ...cutText(res.text) };
|
|
97
|
+
if (Array.isArray(res.files)) return { kind: 'files', files: res.files };
|
|
98
|
+
if (res.image) {
|
|
99
|
+
if (res.image.base64.length * 0.75 > MAX_IMAGE_BYTES) return { kind: 'image', too_large: true, width: res.image.width, height: res.image.height };
|
|
100
|
+
return { kind: 'image', image: res.image };
|
|
101
|
+
}
|
|
102
|
+
return { kind: 'empty' };
|
|
103
|
+
}
|
|
104
|
+
const text = await run(unix.read[0], unix.read[1], { signal: ctx?.signal, spawnImpl }).catch(() => '');
|
|
105
|
+
return text ? { kind: 'text', ...cutText(text) } : { kind: 'empty' };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function write(args = {}, ctx) {
|
|
109
|
+
const text = String(args.text ?? '');
|
|
110
|
+
if (text.length > MAX_TEXT) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Text too long for the clipboard (max ${MAX_TEXT} characters)`);
|
|
111
|
+
if (platform === 'win32') {
|
|
112
|
+
const [cmd, a] = ps(PS_WRITE);
|
|
113
|
+
await run(cmd, a, { input: text, signal: ctx?.signal, spawnImpl });
|
|
114
|
+
} else {
|
|
115
|
+
await run(unix.write[0], unix.write[1], { input: text, signal: ctx?.signal, spawnImpl });
|
|
116
|
+
}
|
|
117
|
+
return { ok: true, chars: text.length };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return { read, write };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function cutText(text) {
|
|
124
|
+
return text.length > MAX_TEXT ? { text: text.slice(0, MAX_TEXT), truncated: true, total_chars: text.length } : { text };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
128
|
+
|
|
129
|
+
export function buildClipboardTools(clipboard) {
|
|
130
|
+
return [
|
|
131
|
+
{ name: 'clipboard.read', group: ToolGroup.SYSTEM, read_only: true, handler: (_a, c) => clipboard.read(c),
|
|
132
|
+
description: 'What the user has copied right now: text, an image (Windows) or the files copied in Explorer (Windows: their paths). Content a password manager marked private is never returned.',
|
|
133
|
+
input_schema: schema({}) },
|
|
134
|
+
{ name: 'clipboard.write', group: ToolGroup.SYSTEM, handler: (a, c) => clipboard.write(a, c),
|
|
135
|
+
description: 'Put text on the clipboard (replaces what the user had copied), so they can paste it anywhere.',
|
|
136
|
+
input_schema: schema({ text: { type: 'string', description: 'text to copy' } }, ['text']) },
|
|
137
|
+
];
|
|
138
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { execFile } from 'child_process';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Tệp "chỉ có trên mây" (OneDrive / Dropbox / Google Drive / iCloud trên Windows, Files On-Demand): mở để đọc là Windows TẢI VỀ — một lần
|
|
8
|
+
* quét lập chỉ mục có thể kéo về hàng GB. Đọc thuộc tính thì không tải: OFFLINE (0x1000) / RECALL_ON_OPEN (0x40000) /
|
|
9
|
+
* RECALL_ON_DATA_ACCESS (0x400000) → chỉ lập chỉ mục tên. macOS: tệp iCloud chưa tải là tệp ẩn `.x.icloud` (đã bị bỏ như tệp ẩn).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const CLOUD_DIR_RE = /^(OneDrive|Dropbox|Google Drive|iCloudDrive|iCloud Drive|Box)( - .*| \(.*\))?$/i;
|
|
13
|
+
const CLOUD_ONLY_MASK = 0x1000 | 0x40000 | 0x400000;
|
|
14
|
+
const CHECK_TIMEOUT_MS = 60_000;
|
|
15
|
+
|
|
16
|
+
/** Đường dẫn nằm trong thư mục đồng bộ đám mây (chỉ Windows mới có tệp giữ chỗ cần lo). */
|
|
17
|
+
export function inCloudFolder(abs, platform = process.platform) {
|
|
18
|
+
return platform === 'win32' && abs.split(path.sep).some((seg) => CLOUD_DIR_RE.test(seg));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const SCRIPT = `
|
|
22
|
+
$ErrorActionPreference = 'SilentlyContinue'
|
|
23
|
+
[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
|
24
|
+
foreach ($p in [IO.File]::ReadAllLines($env:AIVIN_CLOUD_LIST, [Text.Encoding]::UTF8)) {
|
|
25
|
+
try { if (([int][IO.File]::GetAttributes($p)) -band ${CLOUD_ONLY_MASK}) { [Console]::Out.WriteLine($p) } } catch { }
|
|
26
|
+
}
|
|
27
|
+
`;
|
|
28
|
+
|
|
29
|
+
function runPowerShell(listFile) {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', SCRIPT], {
|
|
32
|
+
env: { ...process.env, AIVIN_CLOUD_LIST: listFile }, windowsHide: true, timeout: CHECK_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024, encoding: 'utf8',
|
|
33
|
+
}, (err, stdout) => (err ? reject(err) : resolve(stdout)));
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Trong `paths`, tệp nào chỉ có trên mây — hỏi một lần cho cả lô. Không hỏi được (PowerShell bị chặn…) → coi CẢ LÔ là trên mây: thà mất
|
|
39
|
+
* đoạn chữ đầu còn hơn tải về cả thư mục.
|
|
40
|
+
*/
|
|
41
|
+
export async function cloudOnlyFiles(paths, { platform = process.platform, run = runPowerShell } = {}) {
|
|
42
|
+
if (platform !== 'win32' || !paths.length) return new Set();
|
|
43
|
+
const listFile = path.join(os.tmpdir(), `aivin-cloud-${process.pid}-${Date.now()}.txt`);
|
|
44
|
+
try {
|
|
45
|
+
fs.writeFileSync(listFile, paths.join('\n'), 'utf8');
|
|
46
|
+
const out = await run(listFile);
|
|
47
|
+
return new Set(String(out).split(/\r?\n/).filter(Boolean));
|
|
48
|
+
} catch {
|
|
49
|
+
return new Set(paths);
|
|
50
|
+
} finally {
|
|
51
|
+
fs.rmSync(listFile, { force: true });
|
|
52
|
+
}
|
|
53
|
+
}
|