@aivin-labs/cli 1.0.43 → 1.0.47

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/bin/cli.mjs CHANGED
@@ -7,7 +7,8 @@ import path from 'path';
7
7
  import inquirer from 'inquirer';
8
8
  import { spawn } from 'child_process';
9
9
  import axios from 'axios';
10
- import dotenv from 'dotenv';
10
+ import { loadProjectEnv } from './lib/projectEnv.mjs';
11
+ import { requestCastStop } from './lib/remote/desktop/castAuth.mjs';
11
12
  import { fileURLToPath, pathToFileURL } from 'url';
12
13
  import { dirname } from 'path';
13
14
  import { createRequire } from 'module';
@@ -131,9 +132,8 @@ import {
131
132
  // didn't set them. `dotenv.config()` never overrides a variable that's already set, so a project's
132
133
  // own `.env` (or a real shell env var) always wins over the global context, exactly like before -
133
134
  // but nothing requires a project to have a `.env` at all anymore for the common single-context case.
134
- // `quiet: true` - otherwise dotenv prints an "injected env" tip line to stdout on every run, which
135
- // would corrupt `--json-output` mode (meant for clean, parseable JSON on stdout).
136
- dotenv.config({ quiet: true });
135
+ // Chỉ các lệnh làm việc trên dự án plugin mới đọc `.env` (xem projectEnv.mjs).
136
+ loadProjectEnv();
137
137
 
138
138
  {
139
139
  const selectedServer = process.env.AIVIN_BASE_URL
@@ -1185,9 +1185,26 @@ program
1185
1185
  const toast = process.env.AIVIN_OPEN_UI === 'toast';
1186
1186
  for (const file of files) {
1187
1187
  try {
1188
- if (toast) showOSNotification({ title: 'AIVIN Bot', body: openText('opening', { name: path.basename(file) }) });
1188
+ const name = path.basename(file);
1189
+ if (toast) showOSNotification({ title: 'AIVIN Bot', body: openText('opening', { name }) });
1190
+ let lastReported = 0;
1191
+ const onProgress = (percent, phase) => {
1192
+ if (phase === 'processing') {
1193
+ if (toast) showOSNotification({ title: 'AIVIN Bot', body: openText('processing', { name }) });
1194
+ else process.stdout.write(`\r${chalk.cyan('⏳')} ${openText('processing', { name })}\n`);
1195
+ return;
1196
+ }
1197
+ if (percent - lastReported >= 25 || percent === 100) {
1198
+ lastReported = percent;
1199
+ if (toast && (percent === 0 || percent === 50 || percent === 100)) {
1200
+ showOSNotification({ title: 'AIVIN Bot', body: openText('uploading', { name, percent }) });
1201
+ } else if (!toast) {
1202
+ process.stdout.write(`\r${chalk.cyan('⬆')} ${openText('uploading', { name, percent })}`);
1203
+ }
1204
+ }
1205
+ };
1189
1206
  const display = options.print ? OpenDisplay.NONE : options.tab ? OpenDisplay.TAB : OpenDisplay.WINDOW;
1190
- const res = await openFile(file, { workspace: options.workspace, display });
1207
+ const res = await openFile(file, { workspace: options.workspace, display, onProgress });
1191
1208
  console.log(options.print ? res.url : chalk.green(`✅ ${res.name} → ${res.url}${res.reused ? ' (Drive copy reused)' : ''}${res.viewOnly ? ' (view only, not signed in - closes with its window)' : ''}`));
1192
1209
  } catch (error) {
1193
1210
  console.error(chalk.red('❌'), error.message);
@@ -1430,6 +1447,17 @@ remoteCommand
1430
1447
  console.log(chalk.yellow('⏸ Đã tạm dừng — máy này từ chối mọi việc từ xa.'));
1431
1448
  });
1432
1449
 
1450
+ remoteCommand
1451
+ .command('disconnect')
1452
+ .description('Cut off whoever is viewing or controlling this screen; the next session must be allowed on this computer')
1453
+ .action(() => {
1454
+ if (!requestCastStop()) {
1455
+ console.log(chalk.gray('Không có ai đang xem màn hình máy này.'));
1456
+ return;
1457
+ }
1458
+ console.log(chalk.yellow('⏹ Đã gửi lệnh ngắt. Phiên xem sau phải bấm "Cho phép" trên máy này.'));
1459
+ });
1460
+
1433
1461
  remoteCommand
1434
1462
  .command('mascot [action] [combo]')
1435
1463
  .description('The Aivin mascot floating on screen while the listener runs (Windows): on | off — no argument shows the current setting; hotkey [combo|off|default] — the key combination for voice (default Alt+Shift+Space; off turns off both keys), with --chat the one that opens the ask box to type (default Alt+Space)')
@@ -1520,7 +1548,7 @@ remoteCommand
1520
1548
 
1521
1549
  remoteCommand
1522
1550
  .command('policy [action] [value]')
1523
- .description('Rules enforced on this computer itself (Aivin cannot change them): which steps need a click on this computer, tools turned off, extra blocked commands')
1551
+ .description('Rules enforced on this computer itself (Aivin cannot change them): which steps need a click on this computer, tools turned off, extra blocked commands, whether viewing this screen needs a click here (cast ask|unattended|off)')
1524
1552
  .action(async (action, value) => {
1525
1553
  try {
1526
1554
  await runPolicyCommand(action, value);
package/bin/lib/auth.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import chalk from 'chalk';
2
- import { exec } from 'child_process';
2
+ import { execFile } from 'child_process';
3
3
  import http from 'http';
4
4
  import os from 'os';
5
5
  import { randomBytes } from 'crypto';
@@ -21,16 +21,30 @@ export function saveGlobalApiKey(apiKey, baseUrl = process.env.AIVIN_BASE_URL ||
21
21
  return saveActiveContext(baseUrl, apiKey, identity);
22
22
  }
23
23
 
24
+ /**
25
+ * Lệnh mở trình duyệt, không qua shell: URL có thể do máy chủ trả về nên không được ghép vào chuỗi lệnh. Chỉ http(s); sai thì null.
26
+ */
27
+ export function browserCommand(url, platform = process.platform, systemRoot = process.env.SystemRoot || 'C:\\Windows') {
28
+ let href;
29
+ try {
30
+ const parsed = new URL(url);
31
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
32
+ href = parsed.href;
33
+ } catch {
34
+ return null;
35
+ }
36
+ if (platform === 'win32') return { file: `${systemRoot}\\System32\\rundll32.exe`, args: ['url.dll,FileProtocolHandler', href] };
37
+ return { file: platform === 'darwin' ? 'open' : 'xdg-open', args: [href] };
38
+ }
39
+
24
40
  export function openBrowser(url) {
25
- const platform = process.platform;
26
- const command =
27
- platform === 'win32' ? `start "" "${url}"` : platform === 'darwin' ? `open "${url}"` : `xdg-open "${url}"`;
28
- exec(command, (error) => {
29
- if (error) {
30
- console.log(chalk.yellow('Could not open a browser automatically - open this URL manually:'));
31
- console.log(chalk.cyan(` ${url}`));
32
- }
33
- });
41
+ const showManually = () => {
42
+ console.log(chalk.yellow('Could not open a browser automatically - open this URL manually:'));
43
+ console.log(chalk.cyan(` ${url}`));
44
+ };
45
+ const command = browserCommand(url);
46
+ if (!command) return showManually();
47
+ execFile(command.file, command.args, (error) => { if (error) showManually(); });
34
48
  }
35
49
 
36
50
  /**
@@ -40,6 +40,8 @@ const OPEN_TEXT = Object.freeze({
40
40
  [OpenFileError.NOT_LOGGED_IN]: 'Máy này chưa đăng nhập Aivin — mở Terminal và chạy: aivin login',
41
41
  [OpenFileError.UPLOAD_FAILED]: 'Tải "{name}" lên Drive không được: {reason}',
42
42
  opening: 'Đang mở "{name}" trên Aivin…',
43
+ uploading: 'Đang tải "{name}" lên Drive… ({percent}%)',
44
+ processing: 'Đang xử lý "{name}" và mở tài liệu…',
43
45
  failed_title: 'Không mở được bằng AIVIN Bot',
44
46
  },
45
47
  en: {
@@ -48,6 +50,8 @@ const OPEN_TEXT = Object.freeze({
48
50
  [OpenFileError.NOT_LOGGED_IN]: 'This computer is not signed in to Aivin — open a terminal and run: aivin login',
49
51
  [OpenFileError.UPLOAD_FAILED]: 'Could not upload "{name}" to Drive: {reason}',
50
52
  opening: 'Opening "{name}" in Aivin…',
53
+ uploading: 'Uploading "{name}" to Drive… ({percent}%)',
54
+ processing: 'Processing "{name}" and opening document…',
51
55
  failed_title: 'Could not open with AIVIN Bot',
52
56
  },
53
57
  });
@@ -118,13 +122,20 @@ async function driveFileExists(serverUrl, auth, { workspaceId, fileId }) {
118
122
  }
119
123
  }
120
124
 
121
- async function uploadToDrive(serverUrl, auth, { workspaceId, name, buffer }) {
125
+ async function uploadToDrive(serverUrl, auth, { workspaceId, name, buffer }, onProgress) {
122
126
  const form = new FormData();
123
127
  form.append('file', new Blob([buffer]), name);
124
128
  try {
125
129
  const res = await axios.post(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/upload`, form, {
126
130
  ...auth, maxBodyLength: Infinity, maxContentLength: Infinity, timeout: 10 * 60_000,
131
+ onUploadProgress: (e) => {
132
+ if (e.total && onProgress) {
133
+ const percent = Math.min(100, Math.round((e.loaded * 100) / e.total));
134
+ onProgress(percent);
135
+ }
136
+ },
127
137
  });
138
+ if (onProgress) onProgress(100, 'processing');
128
139
  const id = res.data?.id || res.data?._id;
129
140
  if (!id) throw new Error('no file id in the upload response');
130
141
  return String(id);
@@ -147,7 +158,7 @@ async function findReusable(serverUrl, auth, { index, key }) {
147
158
  export function appWindowCommand(url, { defaultId = detectDefaultBrowserId(), resolve = resolveBrowserInstall } = {}) {
148
159
  const browser = LOCAL_BROWSERS.find((b) => b.id === defaultId);
149
160
  const install = browser ? resolve(browser) : null;
150
- return install ? { exe: install.exe, args: [`--app=${url}`] } : null;
161
+ return install ? { exe: install.exe, args: ['--start-maximized', `--app=${url}`] } : null;
151
162
  }
152
163
 
153
164
  function openInWindow(url) {
@@ -171,7 +182,7 @@ async function resolveWebUrl(serverUrl) {
171
182
  * Tải (hoặc dùng lại) rồi mở. Trả `{ url, fileId, workspaceId, reused }`; lỗi → OpenFileFailure.
172
183
  * `display`: OpenDisplay — cửa sổ riêng (mặc định), tab thường, hoặc chỉ trả đường dẫn (--print).
173
184
  */
174
- export async function openLocalFile(filePath, { workspace, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE } = {}) {
185
+ export async function openLocalFile(filePath, { workspace, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE, onProgress } = {}) {
175
186
  if (!process.env.API_KEY) throw new OpenFileFailure(OpenFileError.NOT_LOGGED_IN);
176
187
  const local = readLocalFile(filePath);
177
188
  const serverUrl = missionServerUrl();
@@ -183,7 +194,7 @@ export async function openLocalFile(filePath, { workspace, display: displayMode
183
194
 
184
195
  const index = readOpenIndex(indexFile);
185
196
  const reusedId = await findReusable(serverUrl, auth, { index, key });
186
- const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, name: local.name, buffer: local.buffer });
197
+ const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, name: local.name, buffer: local.buffer }, onProgress);
187
198
 
188
199
  index[key] = { file_id: fileId, workspace_id: workspaceId, name: local.name, path: local.abs, opened_at: new Date().toISOString() };
189
200
  try { writeOpenIndex(index, indexFile); } catch { /* chỉ mất lần dùng lại sau */ }
@@ -0,0 +1,27 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import dotenv from 'dotenv';
4
+
5
+ /** Chỉ lệnh làm việc trên một dự án plugin mới đọc `.env` của thư mục hiện tại. Tệp này có thể đến từ repo vừa tải về hay tệp zip vừa giải nén. */
6
+ const PROJECT_COMMANDS = new Set(['create', 'init', 'validate', 'start', 'deploy', 'test', 'plugin', 'connector', 'pluginstore', 'mcp']);
7
+ /** Biến đổi cách CLI tin cậy mạng, chỗ lưu khoá, nguồn cập nhật: chỉ nhận từ môi trường thật, không nhận từ tệp trong dự án. */
8
+ const NEVER_FROM_PROJECT = /^(NODE_|AIVIN_(?!BASE_URL$|CLI_SDK_VERSION$|TRIGGER_TIMEOUT_MS$)|(HTTP|HTTPS|ALL|NO)_PROXY$)/i;
9
+
10
+ export function projectEnvEntries(argv, parsed) {
11
+ const command = argv.find((arg) => !arg.startsWith('-'));
12
+ if (!PROJECT_COMMANDS.has(command)) return {};
13
+ return Object.fromEntries(Object.entries(parsed).filter(([key]) => !NEVER_FROM_PROJECT.test(key)));
14
+ }
15
+
16
+ /** Không đè biến đã có sẵn trong môi trường thật. */
17
+ export function loadProjectEnv({ argv = process.argv.slice(2), env = process.env, file = path.resolve('.env') } = {}) {
18
+ let text;
19
+ try {
20
+ text = fs.readFileSync(file, 'utf8');
21
+ } catch {
22
+ return;
23
+ }
24
+ for (const [key, value] of Object.entries(projectEnvEntries(argv, dotenv.parse(text)))) {
25
+ if (env[key] === undefined) env[key] = value;
26
+ }
27
+ }
@@ -4,7 +4,7 @@ import axios from 'axios';
4
4
  import chalk from 'chalk';
5
5
  import readline from 'readline/promises';
6
6
  import { io } from 'socket.io-client';
7
- import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
7
+ import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
8
8
  import { readActiveServer, resolveServerUrl as normalizeServerUrl, setActiveServer } from '../servers.mjs';
9
9
  import { logActivity } from './activityLog.mjs';
10
10
  import { DEFAULT_SCOPE_LIMITS, DEVICE_NAMESPACE, CastState, DeviceAccess, DeviceErrorCode, DeviceEvent, HoldPhase, MAX_RESULT_BYTES, PROTOCOL_VERSION, REMOTE_IDEM_FILE, REMOTE_OUTBOX_FILE, ServerFeature, ToolGroup } from './constants.mjs';
@@ -48,6 +48,10 @@ import { createDesktopCastManager } from './desktop/desktopCast.mjs';
48
48
  import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
49
49
  import { CastInputRejection, createCastInputGate } from './desktop/castInput.mjs';
50
50
  import { createCastFileDrop, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
51
+ import {
52
+ askCastConsent, checkCastAction, clearCastSession, isCastLocked, lockCast, recordCastSession, unlockCast,
53
+ } from './desktop/castAuth.mjs';
54
+ import { CastConsentDecision, createCastConsent } from './desktop/castConsent.mjs';
51
55
  import {
52
56
  BootAction, MAX_BOOTS_BEFORE_ROLLBACK, RESTART_EXIT_CODE, UPDATE_CONFIRM_AFTER_MS, UPDATE_ROLLED_BACK, checkBootAfterUpdate, cleanupRetired, clearStaleInstalledMarker,
53
57
  confirmUpdate, ingestSupervisorRollback, isStandaloneBinary, noteCleanExit, updateProfile,
@@ -70,7 +74,7 @@ const PAUSE_POLL_MS = 2000;
70
74
  const RESULT_ACK_TIMEOUT_MS = 15_000;
71
75
  /** Tự cập nhật: báo BE "sắp khởi động lại để chuyển bản" (chờ ack tối đa bấy nhiêu), và máy dự kiến quay lại trong bấy nhiêu. */
72
76
  const RESTARTING_ACK_TIMEOUT_MS = 2_000;
73
- const RESTART_EXPECT_BACK_MS = 30_000;
77
+ const RESTART_EXPECT_BACK_MS = 30_000;
74
78
  const CAST_DISCONNECT_GRACE_MS = 8_000;
75
79
 
76
80
  /** Gom đoạn stdout/stderr của một lời gọi, đẩy lên theo nhịp (không bắn mỗi dòng một gói). */
@@ -127,14 +131,14 @@ function boundedResult(outcome) {
127
131
  * khởi động lại trên máy đang đăng nhập CLI với máy chủ B sẽ lặng lẽ ghép lại sang B bằng API key (chạy thật 26/10/2026). Đổi máy chủ
128
132
  * thì dùng `--server` (hoặc `--repair`).
129
133
  */
130
- export function resolveServerUrl(options, saved, env = process.env) {
131
- const explicit = options.server || options.serverUrl;
132
- const url = explicit || (options.code ? DEFAULT_AIVIN_BASE_URL : null)
133
- || readActiveServer()
134
- || (options.repair ? undefined : saved?.server_url)
135
- || env.AIVIN_BASE_URL || env.AIVIN_SERVER
136
- || DEFAULT_AIVIN_BASE_URL;
137
- return normalizeServerUrl(url);
134
+ export function resolveServerUrl(options, saved, env = process.env) {
135
+ const explicit = options.server || options.serverUrl;
136
+ const url = explicit || (options.code ? DEFAULT_AIVIN_BASE_URL : null)
137
+ || readActiveServer()
138
+ || (options.repair ? undefined : saved?.server_url)
139
+ || env.AIVIN_BASE_URL || env.AIVIN_SERVER
140
+ || DEFAULT_AIVIN_BASE_URL;
141
+ return normalizeServerUrl(url);
138
142
  }
139
143
 
140
144
  /**
@@ -159,20 +163,20 @@ async function confirmServerChange(saved, serverUrl) {
159
163
  * Thông tin ghép máy: có mã kết nối thì luôn ghép bằng mã (người dùng vừa bấm "Thêm máy tính này"); có sẵn và đúng máy chủ thì dùng;
160
164
  * không thì ghép mới bằng API key đang đăng nhập.
161
165
  */
162
- async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
163
- const current = loadDeviceCredentials();
164
- await confirmServerChange(current, serverUrl);
165
- setActiveServer(serverUrl);
166
- let creds = loadDeviceCredentials(serverUrl);
167
- if (code) {
168
- creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
169
- } else if (!creds || repair) {
170
- creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
171
- } else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
172
- creds.roots = roots;
173
- saveDeviceCredentials(creds);
174
- }
175
- return creds;
166
+ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
167
+ const current = loadDeviceCredentials();
168
+ await confirmServerChange(current, serverUrl);
169
+ setActiveServer(serverUrl);
170
+ let creds = loadDeviceCredentials(serverUrl);
171
+ if (code) {
172
+ creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
173
+ } else if (!creds || repair) {
174
+ creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
175
+ } else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
176
+ creds.roots = roots;
177
+ saveDeviceCredentials(creds);
178
+ }
179
+ return creds;
176
180
  }
177
181
 
178
182
  /**
@@ -180,7 +184,7 @@ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name,
180
184
  * 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).
181
185
  */
182
186
  export async function pairWithCodeOnly(options) {
183
- const saved = loadDeviceCredentials();
187
+ const saved = loadDeviceCredentials();
184
188
  const serverUrl = resolveServerUrl(options, saved);
185
189
  await confirmServerChange(saved, serverUrl);
186
190
  configureProxy({ explicit: options.proxy });
@@ -188,7 +192,7 @@ export async function pairWithCodeOnly(options) {
188
192
  const roots = (fullAccess ? fullAccessRoots() : [options.dir || process.cwd()]).map((r) => path.resolve(r));
189
193
  const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
190
194
  const profile = { ...buildDeviceProfile(fullAccess ? [os.homedir()] : roots), roots, access };
191
- const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
195
+ const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
192
196
  setActiveServer(serverUrl);
193
197
  saveDeviceCredentials({ ...creds, access });
194
198
  const stale = lockHolder();
@@ -207,8 +211,8 @@ export async function startRemoteClient(options = {}) {
207
211
  const envCreds = multiUser ? credentialsFromEnv() : null;
208
212
  if (multiUser && !envCreds) throw new Error('--multi-user cần AIVIN_DEVICE_TOKEN, AIVIN_DEVICE_ID và AIVIN_SERVER (máy tính tổ chức do Aivin cấp).');
209
213
  if (multiUser && process.platform === 'win32') throw new Error('--multi-user chỉ chạy trên Linux (container máy tính tổ chức).');
210
- const savedHint = envCreds || loadDeviceCredentials();
211
- const serverUrl = resolveServerUrl(options, savedHint);
214
+ const savedHint = envCreds || loadDeviceCredentials();
215
+ const serverUrl = resolveServerUrl(options, savedHint);
212
216
  const saved = envCreds || loadDeviceCredentials(serverUrl);
213
217
  // Trước mọi lời gọi mạng (ghép máy cũng đi qua proxy).
214
218
  const proxy = configureProxy({ explicit: options.proxy });
@@ -445,8 +449,8 @@ export async function startRemoteClient(options = {}) {
445
449
  let castBlockedNoticeAt = 0;
446
450
  const emitCastStatus = (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, payload); };
447
451
  /** Thao tác từ xa (qua máy chủ hoặc kênh WebRTC) — qua cổng chặn rồi mới xuống tiến trình điều khiển. */
448
- const applyRemoteInput = (raw, viewerId) => {
449
- const sessionId = desktopCast.sessionId();
452
+ const applyRemoteInput = (raw, viewerId) => {
453
+ const sessionId = desktopCast.sessionId();
450
454
  if (!sessionId || (raw?.session_id && raw.session_id !== sessionId)) return;
451
455
  const res = castGate.accept(raw);
452
456
  if (res.ok) return desktopCast.sendInput(res.cmd);
@@ -456,14 +460,35 @@ export async function startRemoteClient(options = {}) {
456
460
  };
457
461
  /** AI sắp bấm / người xem rời giữa lúc đang kéo: nhả nút + phím bổ trợ trên máy, gói nhả của người xem có thể không bao giờ tới. */
458
462
  const releaseCastInput = () => { if (castGate.takeHeldInput()) desktopCast.sendInput({ action: 'release_all' }); };
463
+ const castConsent = createCastConsent({
464
+ ask: ({ viewerDevice, locked, signal }) => askCastConsent({ viewerDevice: viewerDevice || 'Thiết bị từ xa', repeatedAfterBlock: locked, signal }),
465
+ getMode: () => policyGuard.read().cast_consent,
466
+ isLocked: isCastLocked,
467
+ unlock: unlockCast,
468
+ onWaiting: ({ sessionId, viewerId, viewerDevice }) => {
469
+ say(chalk.yellow(` ⚠️ Thiết bị "${viewerDevice || viewerId}" xin xem màn hình — chờ bấm "Cho phép" trên máy này`));
470
+ emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.AWAITING_CONSENT });
471
+ },
472
+ });
459
473
  const castFileDrop = createCastFileDrop({
460
474
  reply: (viewerId, msg) => desktopWebRtc.replyFile(viewerId, msg),
461
475
  checkAllowed: () => (isRemotePaused() ? FileDropReason.PAUSED : aiGuiBusy > 0 ? FileDropReason.AI_ACTIVE : null),
462
- onSaved: ({ path: file, name, bytes, reveal }) => {
476
+ onSaved: ({ path: file, name, bytes, reveal, paste, x, y, rx, ry }) => {
463
477
  say(chalk.cyan(` 📥 Đã nhận tệp từ web: ${file}`));
464
478
  logActivity({ type: 'desktop_cast_file', id: desktopCast.sessionId(), name, bytes });
465
- // Không mở cửa sổ đè lên giữa lúc AI đang bấm.
466
- if (reveal && aiGuiBusy === 0) revealInExplorer(file);
479
+ if (paste) {
480
+ desktopCast.sendInput({
481
+ action: 'paste_file',
482
+ path: file,
483
+ x,
484
+ y,
485
+ rx,
486
+ ry,
487
+ click: Number.isFinite(x) && Number.isFinite(y),
488
+ });
489
+ } else if (reveal && aiGuiBusy === 0) {
490
+ revealInExplorer(file);
491
+ }
467
492
  },
468
493
  });
469
494
  // WebRTC chạy ở tiến trình con (thư viện native sập lúc thoát — xem webrtcWorker.mjs), daemon chỉ chuyển tín hiệu / thao tác / JPEG.
@@ -486,13 +511,15 @@ export async function startRemoteClient(options = {}) {
486
511
  const syncCastJpeg = () => {
487
512
  const jpeg = desktopWebRtc.needsJpeg() || !desktopWebRtc.videoLive();
488
513
  desktopCast.setJpeg(jpeg);
489
- desktopCast.setCursorInFrame(jpeg || !desktopWebRtc.localCursor());
514
+ desktopCast.setCursorInFrame(jpeg || !desktopWebRtc.localCursor());
490
515
  desktopCast.setAudio(desktopWebRtc.needsAudio());
491
516
  };
492
517
  /** Dừng hẳn phiên trên máy (tạm dừng / mất kết nối / tắt daemon); `notify` = báo BE kết thúc phiên. */
493
518
  const stopDesktopCast = (reason, notify = true) => {
494
- const sessionId = desktopCast.sessionId();
495
- clearTimeout(castDisconnectTimer);
519
+ clearCastSession();
520
+ const sessionId = desktopCast.sessionId();
521
+ if (sessionId) castConsent.forget(sessionId);
522
+ clearTimeout(castDisconnectTimer);
496
523
  castDisconnectTimer = null;
497
524
  desktopWebRtc.closeAll();
498
525
  void castFileDrop.closeAll();
@@ -503,8 +530,17 @@ export async function startRemoteClient(options = {}) {
503
530
  logActivity({ type: 'desktop_cast', id: sessionId, reason, inputs: castGate.takeAcceptedCount() });
504
531
  if (notify && sessionId) emitCastStatus({ session_id: sessionId, state: CastState.STOPPED, reason, final: true });
505
532
  };
506
- let mascotChat = null;
533
+ let mascotChat = null;
507
534
  let castDisconnectTimer = null;
535
+ const castActionTimer = setInterval(() => {
536
+ const action = checkCastAction();
537
+ if (action?.action === 'stop_and_block') {
538
+ lockCast({ viewerDevice: action.viewer_device });
539
+ say(chalk.yellow(' ⏹ Đã ngắt người đang xem. Phiên sau phải bấm "Cho phép" trên máy này.'));
540
+ stopDesktopCast('user_revoked');
541
+ }
542
+ }, 1000);
543
+ castActionTimer.unref?.();
508
544
 
509
545
  say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
510
546
  say(chalk.gray(` Máy: ${creds.name} (${creds.device_id})`));
@@ -525,7 +561,7 @@ export async function startRemoteClient(options = {}) {
525
561
  // `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.
526
562
  const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
527
563
 
528
- void gui?.prewarm?.();
564
+ void gui?.prewarm?.();
529
565
  void desktopCast.prewarm?.();
530
566
  fileIndex?.build()
531
567
  .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(); })
@@ -609,7 +645,7 @@ export async function startRemoteClient(options = {}) {
609
645
  stopped = true;
610
646
  clearInterval(heartbeat);
611
647
  clearInterval(pauseWatch);
612
- clearTimeout(confirmTimer);
648
+ clearTimeout(confirmTimer);
613
649
  clearTimeout(castDisconnectTimer);
614
650
  updater?.close();
615
651
  mascot.close();
@@ -834,6 +870,28 @@ export async function startRemoteClient(options = {}) {
834
870
  onDuplicate: (call) => say(chalk.gray(` ↺ ${callLabel(call)}: đã làm ở lần gửi trước — trả lại kết quả cũ`)),
835
871
  });
836
872
 
873
+ /**
874
+ * Trước khi AI bấm: chờ người thôi tay. Người đang tạm cầm lái từ web thì chờ lâu hơn hạn của lời gọi nên xin BE lùi hạn, và đăng ký vào
875
+ * `gating` để lệnh huỷ dừng được lúc đang chờ. Không thì người vừa trả quyền xong là bước đã huỷ vẫn bấm.
876
+ */
877
+ const waitForHumanToYield = async (call) => {
878
+ const holdMs = castGate.takeoverWaitMs();
879
+ if (!holdMs) return void await castGate.waitHumanIdle();
880
+ const hold = (extraMs, phase) => { if (socket.connected) socket.emit(DeviceEvent.HOLD, { call_id: call.call_id, extra_ms: extraMs, phase }); };
881
+ hold(holdMs, HoldPhase.WAITING);
882
+ const controller = new AbortController();
883
+ gating.set(call.call_id, controller);
884
+ let yielded;
885
+ try {
886
+ yielded = await castGate.waitHumanIdle({ signal: controller.signal });
887
+ } finally {
888
+ gating.delete(call.call_id);
889
+ }
890
+ if (controller.signal.aborted) throw new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled while waiting for the person controlling this computer — the step did not run');
891
+ if (!yielded) throw new DeviceToolError(DeviceErrorCode.NOT_STARTED, 'The person is still controlling this computer from the web — the step did not run, try again later');
892
+ hold(0, HoldPhase.STARTED);
893
+ };
894
+
837
895
  /** Không bao giờ ném / để lọt promise bị từ chối: lỗi bất ngờ vẫn trả kết quả lỗi cho BE. */
838
896
  const handleCall = async (call) => {
839
897
  const streamer = createStreamer(socket, call.call_id);
@@ -845,18 +903,20 @@ export async function startRemoteClient(options = {}) {
845
903
  keepAwake.hold();
846
904
  const def = byName.get(call.tool);
847
905
  const guiWrite = def?.group === ToolGroup.GUI && !def?.read_only;
906
+ let guiBusyHeld = false;
848
907
  try {
849
908
  if (guiWrite) {
850
- // Người đang điều khiển từ web → AI chờ người thôi tay (tối đa 3 s) rồi mới bấm; trong lúc AI bấm, thao tác từ web bị bỏ.
851
- await castGate.waitHumanIdle();
909
+ // Người đang điều khiển từ web → AI chờ người thôi tay rồi mới bấm; trong lúc AI bấm, thao tác từ web bị bỏ.
910
+ await waitForHumanToYield(call);
852
911
  releaseCastInput();
853
912
  aiGuiBusy++;
913
+ guiBusyHeld = true;
854
914
  }
855
915
  ({ tool, outcome } = await runOnce(call, streamer));
856
916
  } catch (e) {
857
917
  outcome = { ok: false, error: e?.message || String(e), error_code: e?.code || DeviceErrorCode.EXECUTION_FAILED, duration_ms: 0 };
858
918
  } finally {
859
- if (guiWrite) aiGuiBusy--;
919
+ if (guiBusyHeld) aiGuiBusy--;
860
920
  keepAwake.release();
861
921
  syncProcAwake();
862
922
  }
@@ -986,8 +1046,8 @@ export async function startRemoteClient(options = {}) {
986
1046
  updater.requestCheck();
987
1047
  }));
988
1048
  socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
989
- const sessionId = payload?.session_id;
990
- const viewerId = payload?.viewer_id;
1049
+ const sessionId = payload?.session_id;
1050
+ const viewerId = payload?.viewer_id;
991
1051
  const viewerDevice = payload?.viewer_device || payload?.viewerDevice || payload?.viewer_platform || payload?.viewerPlatform;
992
1052
  if (!sessionId || !viewerId) return;
993
1053
  // Chủ máy đã tạm dừng điều khiển từ xa → từ chối cả xem màn hình.
@@ -995,6 +1055,21 @@ export async function startRemoteClient(options = {}) {
995
1055
  emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
996
1056
  return;
997
1057
  }
1058
+ // Quyết định trước khi chụp bất cứ thứ gì; chỉ máy này trả lời được, máy chủ không trả lời thay.
1059
+ const decision = await castConsent.decide({ sessionId, viewerId, viewerDevice, viewerKey: payload?.viewer_key });
1060
+ if (decision !== CastConsentDecision.ALLOW) {
1061
+ logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, result: decision });
1062
+ if (decision === CastConsentDecision.CANCELLED) return;
1063
+ say(chalk.red(` ✕ Không cho xem màn hình (${decision}): ${viewerDevice || viewerId}`));
1064
+ emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: decision });
1065
+ return;
1066
+ }
1067
+ // Chủ máy có thể bấm tạm dừng trong lúc hộp đang mở.
1068
+ if (isRemotePaused()) {
1069
+ emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
1070
+ return;
1071
+ }
1072
+ logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, result: decision });
998
1073
  const castConfig = {
999
1074
  max_fps: payload?.max_fps || 15,
1000
1075
  max_width: payload?.max_width || 1366,
@@ -1012,11 +1087,19 @@ export async function startRemoteClient(options = {}) {
1012
1087
  onFrame: (frame) => {
1013
1088
  desktopWebRtc.push(frame);
1014
1089
  // Còn người xem chưa có kênh WebRTC (đang nối / runtime native không có) → JPEG qua máy chủ; BE chỉ chuyển cho những người đó.
1015
- if (desktopWebRtc.needsFallback() && socket.connected) socket.volatile.emit(DeviceEvent.DESKTOP_CAST_FRAME, frame);
1090
+ // Binary thay base64: nhẹ hơn khoảng một phần ba; JPEG đã nén nên không nén thêm.
1091
+ if (desktopWebRtc.needsFallback() && socket.connected) {
1092
+ socket.volatile.compress(false).emit(DeviceEvent.DESKTOP_CAST_FRAME, { ...frame, image: Buffer.from(frame.image, 'base64') });
1093
+ }
1016
1094
  syncCastJpeg();
1017
1095
  },
1018
1096
  // Mọi người xem đã có video → tiến trình quay thôi nén JPEG, chỉ gửi meta (toạ độ) + khung thô cho bộ mã hoá video.
1019
- onMeta: (meta) => { desktopWebRtc.push(meta); syncCastJpeg(); },
1097
+ onMeta: (meta) => {
1098
+ desktopWebRtc.push(meta);
1099
+ // Màn hình đứng yên không có ảnh: người xem qua máy chủ vẫn cần gói giữ nhịp để biết máy còn sống.
1100
+ if (desktopWebRtc.needsFallback() && socket.connected) socket.volatile.emit(DeviceEvent.DESKTOP_CAST_FRAME, meta);
1101
+ syncCastJpeg();
1102
+ },
1020
1103
  onCursor: (cursor) => desktopWebRtc.pushCursor(cursor),
1021
1104
  onCursorShape: (shape) => desktopWebRtc.pushCursorShape(shape),
1022
1105
  onInputFocus: (focus) => {
@@ -1026,16 +1109,17 @@ export async function startRemoteClient(options = {}) {
1026
1109
  socket.emit(DeviceEvent.DESKTOP_CAST_INPUT_FOCUS, { session_id: sessionId, editable: focus?.editable === true });
1027
1110
  }
1028
1111
  },
1029
- onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
1030
- onClipboard: (clip) => desktopWebRtc.pushClipboard?.(clip),
1031
- onSecureDesktop: (sec) => {
1032
- desktopWebRtc.pushSecureDesktop?.(sec);
1033
- emitCastStatus({ session_id: sessionId, state: 'secure_desktop', active: sec?.active === true });
1112
+ onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
1113
+ onClipboard: (clip) => desktopWebRtc.pushClipboard?.(clip),
1114
+ onSecureDesktop: (sec) => {
1115
+ desktopWebRtc.pushSecureDesktop?.(sec);
1116
+ emitCastStatus({ session_id: sessionId, state: 'secure_desktop', active: sec?.active === true });
1034
1117
  },
1035
1118
  rawPipe: true,
1036
1119
  onReady: (meta) => {
1037
1120
  say(chalk.cyan(` 🖥️ Đang có người xem + điều khiển màn hình máy này từ web (${meta.bounds?.width}x${meta.bounds?.height})`));
1038
1121
  mascot.remoteView(true, { device: viewerDevice });
1122
+ recordCastSession({ active: true, sessionId, viewerId, viewerDevice });
1039
1123
  emitCastStatus({ session_id: sessionId, state: CastState.READY, bounds: meta.bounds });
1040
1124
  },
1041
1125
  onError: (err) => {
@@ -1044,11 +1128,14 @@ export async function startRemoteClient(options = {}) {
1044
1128
  onStop: () => {
1045
1129
  say(chalk.gray(' ⏹ Đã ngừng xem màn hình từ web'));
1046
1130
  mascot.remoteView(false);
1131
+ clearCastSession();
1047
1132
  },
1048
1133
  });
1049
1134
  if (!started) return;
1050
1135
  } else {
1051
1136
  desktopCast.config(castConfig);
1137
+ // Màn hình đứng yên thì ảnh thưa: người mới vào cần một ảnh ngay.
1138
+ desktopCast.refresh();
1052
1139
  }
1053
1140
  const webRtcStarted = payload?.transport === 'webrtc'
1054
1141
  ? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null, audio: payload?.audio !== false }).catch(() => false)
@@ -1059,6 +1146,7 @@ export async function startRemoteClient(options = {}) {
1059
1146
  });
1060
1147
  }));
1061
1148
  socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
1149
+ if (payload?.session_id) castConsent.cancel({ sessionId: payload.session_id, viewerId: payload.viewer_id, final: payload.final !== false });
1062
1150
  if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
1063
1151
  if (payload?.viewer_id) {
1064
1152
  desktopWebRtc.close(payload.viewer_id);
@@ -1071,9 +1159,13 @@ export async function startRemoteClient(options = {}) {
1071
1159
  socket.on(DeviceEvent.DESKTOP_CAST_CONFIG, guarded(DeviceEvent.DESKTOP_CAST_CONFIG, (payload) => {
1072
1160
  if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
1073
1161
  const { max_fps, max_width, quality, monitor, audio } = payload || {};
1074
- desktopCast.config({ max_fps, max_width, quality, monitor, ...(typeof audio === 'boolean' ? { audio } : {}) });
1162
+ desktopCast.config({ max_fps, max_width, quality, monitor, ...(typeof audio === 'boolean' ? { audio } : {}) });
1075
1163
  if (typeof audio === 'boolean') desktopWebRtc.setAudio(audio);
1076
1164
  }));
1165
+ socket.on(DeviceEvent.DESKTOP_CAST_TAKEOVER, guarded(DeviceEvent.DESKTOP_CAST_TAKEOVER, (payload) => {
1166
+ if (!payload?.session_id || payload.session_id !== desktopCast.sessionId()) return;
1167
+ castGate.setHumanTakeover(payload.active === true ? { idleMs: Number(payload.idle_ms), maxWaitMs: Number(payload.max_wait_ms) } : null);
1168
+ }));
1077
1169
  socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
1078
1170
  void desktopWebRtc.signal(payload).catch(() => undefined);
1079
1171
  }));
@@ -1102,8 +1194,8 @@ export async function startRemoteClient(options = {}) {
1102
1194
  * socket, bắt tay thử sẽ đá daemon đang chạy ra.
1103
1195
  */
1104
1196
  export async function testRemoteConnection(options = {}) {
1105
- const savedHint = loadDeviceCredentials();
1106
- const serverUrl = resolveServerUrl(options, savedHint);
1197
+ const savedHint = loadDeviceCredentials();
1198
+ const serverUrl = resolveServerUrl(options, savedHint);
1107
1199
  const creds = loadDeviceCredentials(serverUrl);
1108
1200
  const apiKey = options.apiKey ?? process.env.API_KEY;
1109
1201
  const report = { serverUrl, paired: !!creds, deviceId: creds?.device_id, httpOk: false, latencyMs: null, online: null, error: null };
@@ -103,11 +103,13 @@ export const DeviceEvent = Object.freeze({
103
103
  DESKTOP_CAST_STATUS: 'device:desktop_cast_status',
104
104
  /** CLI → BE: ô có tiêu điểm sau cú nhấp có phải ô nhập chữ — cho người xem đường JPEG (WebRTC đi kênh thao tác). */
105
105
  DESKTOP_CAST_INPUT_FOCUS: 'device:desktop_cast_input_focus',
106
+ /** BE → CLI: người xem tạm cầm lái khi AI đang chạy / trả lại — `{ session_id, active, idle_ms, max_wait_ms }`. */
107
+ DESKTOP_CAST_TAKEOVER: 'device:desktop_cast_takeover',
106
108
  });
107
109
 
108
110
  /** Trạng thái phiên xem màn hình gửi BE (`device:desktop_cast_status`) — khớp BE `DesktopCastState`. */
109
111
  export const CastState = Object.freeze({
110
- READY: 'ready', CONNECTED: 'connected', DEGRADED: 'degraded', STOPPED: 'stopped', REFUSED: 'refused', INPUT_BLOCKED: 'input_blocked',
112
+ READY: 'ready', CONNECTED: 'connected', DEGRADED: 'degraded', STOPPED: 'stopped', REFUSED: 'refused', INPUT_BLOCKED: 'input_blocked', AWAITING_CONSENT: 'awaiting_consent',
111
113
  });
112
114
 
113
115
  /** Loại báo chủ động (`device:notify`). */
@@ -212,6 +214,8 @@ export const DeviceErrorCode = Object.freeze({
212
214
  CANCELLED: 'CANCELLED',
213
215
  /** Bước có tác dụng đã bắt đầu thì daemon khởi động lại — không biết đã làm tới đâu, không tự làm lại. */
214
216
  INTERRUPTED: 'INTERRUPTED',
217
+ /** Bước CHƯA chạy (vd người đang tạm cầm lái từ web tới hết hạn chờ) — gửi lại an toàn. */
218
+ NOT_STARTED: 'NOT_STARTED',
215
219
  TOOL_UNKNOWN: 'TOOL_UNKNOWN',
216
220
  INVALID_ARGS: 'INVALID_ARGS',
217
221
  NOT_FOUND: 'NOT_FOUND',