@aivin-labs/cli 1.0.51 → 1.0.60

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 (32) hide show
  1. package/bin/cli.mjs +2215 -2211
  2. package/bin/lib/auth.mjs +119 -88
  3. package/bin/lib/context.mjs +58 -5
  4. package/bin/lib/loginHandoff.mjs +87 -0
  5. package/bin/lib/openFile.mjs +29 -4
  6. package/bin/lib/remote/agentContract.mjs +370 -0
  7. package/bin/lib/remote/agentEvidence.mjs +409 -0
  8. package/bin/lib/remote/autoStart.mjs +640 -623
  9. package/bin/lib/remote/client.mjs +55 -17
  10. package/bin/lib/remote/codingAgents.mjs +594 -293
  11. package/bin/lib/remote/constants.mjs +1 -1
  12. package/bin/lib/remote/credentials.mjs +131 -125
  13. package/bin/lib/remote/desktop/castAuth.mjs +44 -19
  14. package/bin/lib/remote/desktop/castConsent.mjs +79 -14
  15. package/bin/lib/remote/desktop/castInput.mjs +3 -0
  16. package/bin/lib/remote/desktop/castTrust.mjs +221 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +324 -40
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
  21. package/bin/lib/remote/desktop/strings.mjs +26 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +1512 -1385
  23. package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
  24. package/bin/lib/remote/dpapiHelper.mjs +91 -0
  25. package/bin/lib/remote/gui/index.mjs +422 -68
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -1530
  27. package/bin/lib/remote/humanInput.mjs +7 -0
  28. package/bin/lib/remote/localConfirm.mjs +2 -2
  29. package/bin/lib/remote/tokenStore.mjs +19 -2
  30. package/bin/lib/remote/toolHandlers.mjs +861 -859
  31. package/docs/CLI.md +1606 -1602
  32. package/package.json +1 -1
@@ -32,7 +32,7 @@ import { showOSNotification } from './notify.mjs';
32
32
  import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs';
33
33
  import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
34
34
  import { createClipboard } from './clipboard.mjs';
35
- import { buildTools, toolMap } from './toolHandlers.mjs';
35
+ import { activeAgentRunner, buildTools, toolMap } from './toolHandlers.mjs';
36
36
  import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
37
37
  import { createGuiController, detectGui } from './gui/index.mjs';
38
38
  import { createWindowsHost } from './gui/windowsHost.mjs';
@@ -45,7 +45,7 @@ import { createScheduleManager } from './schedule.mjs';
45
45
  import { remoteDebuggingPage } from './dailyBrowser.mjs';
46
46
  import { HOME_BASE, SHARED_DIR, createMultiUserHost, isMultiUserMode } from './multiUser.mjs';
47
47
  import { createAutoUpdater } from './autoUpdate.mjs';
48
- import { createDesktopCastManager } from './desktop/desktopCast.mjs';
48
+ import { castLeadInConfig, createDesktopCastManager } from './desktop/desktopCast.mjs';
49
49
  import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
50
50
  import { CastInputRejection, createCastInputGate } from './desktop/castInput.mjs';
51
51
  import { createCastFileDrop, createDropBatches, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
@@ -53,6 +53,7 @@ import {
53
53
  CAST_ACTION_FILE, askCastConsent, checkCastAction, clearCastSession, isCastLocked, lockCast, recordCastSession, unlockCast,
54
54
  } from './desktop/castAuth.mjs';
55
55
  import { CastConsentDecision, createCastConsent } from './desktop/castConsent.mjs';
56
+ import { castViewerInfo, castViewerLabel, createCastTrust, createDeviceProver } from './desktop/castTrust.mjs';
56
57
  import { createCastTouchViewers, shouldDrawCursorInFrame } from './desktop/castTouchViewers.mjs';
57
58
  import { createConfirmBarrier } from './confirmBarrier.mjs';
58
59
  import { newInputTag } from './humanInput.mjs';
@@ -497,8 +498,11 @@ export async function startRemoteClient(options = {}) {
497
498
  };
498
499
  /** 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. */
499
500
  const releaseCastInput = () => { if (castGate.takeHeldInput()) desktopCast.sendInput({ action: 'release_all' }); };
501
+ const castTrust = createCastTrust();
502
+ const castProver = createDeviceProver({ send: emitCastStatus });
500
503
  const castConsent = createCastConsent({
501
- ask: ({ viewerDevice, locked, signal }) => askCastConsent({ viewerDevice: viewerDevice || 'Thiết bị từ xa', repeatedAfterBlock: locked, signal }),
504
+ trust: castTrust,
505
+ ask: ({ viewerDevice, viewerInfo, locked, canTrust, signal }) => askCastConsent({ viewerDevice: viewerDevice || 'Thiết bị từ xa', viewerInfo, repeatedAfterBlock: locked, canTrust, signal }),
502
506
  getMode: () => policyGuard.read().cast_consent,
503
507
  isLocked: isCastLocked,
504
508
  unlock: unlockCast,
@@ -576,7 +580,10 @@ export async function startRemoteClient(options = {}) {
576
580
  if (CAST_RESUMABLE_REASONS.has(reason)) castConsent.suspend(sessionId);
577
581
  else castConsent.forget(sessionId);
578
582
  }
579
- if (CAST_SHUTDOWN_REASONS.has(reason)) castConsent.cancelAll();
583
+ if (CAST_SHUTDOWN_REASONS.has(reason)) {
584
+ castConsent.cancelAll();
585
+ castProver.cancel();
586
+ }
580
587
  clearTimeout(castDisconnectTimer);
581
588
  castDisconnectTimer = null;
582
589
  clearTimeout(castReconfirmTimer);
@@ -603,7 +610,7 @@ export async function startRemoteClient(options = {}) {
603
610
  let castInputTag = null;
604
611
  const castTrustTag = () => (castInputTag && desktopCast.isActive() ? castInputTag : null);
605
612
  /** Mở tiến trình quay cho một phiên (lần đầu, hoặc mở lại khi tiến trình sập). `false` khi máy không quay được. */
606
- function startCapture({ sessionId, viewerId, viewerDevice, castConfig }) {
613
+ function startCapture({ sessionId, viewerId, viewerDevice, viewerPlace = '', castConfig }) {
607
614
  return !!desktopCast.start({
608
615
  sessionId,
609
616
  inputTag: castInputTag,
@@ -649,7 +656,7 @@ export async function startRemoteClient(options = {}) {
649
656
  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})`));
650
657
  mascot.remoteView(true, { device: viewerDevice });
651
658
  holdCastAwake(true);
652
- recordCastSession({ active: true, sessionId, viewerId, viewerDevice });
659
+ recordCastSession({ active: true, sessionId, viewerId, viewerDevice, viewerPlace });
653
660
  emitCastStatus({ session_id: sessionId, state: CastState.READY, bounds: meta.bounds });
654
661
  },
655
662
  onError: (err) => {
@@ -674,7 +681,7 @@ export async function startRemoteClient(options = {}) {
674
681
  say(chalk.yellow(' ⚠️ Tiến trình xem màn hình dừng bất ngờ — mở lại'));
675
682
  // Tiến trình cũ chết không kịp nhả nút chuột đang giữ: nhả trên tiến trình mới.
676
683
  const hadHeld = castGate.takeHeldInput();
677
- if (startCapture({ sessionId, viewerId, viewerDevice, castConfig })) {
684
+ if (startCapture({ sessionId, viewerId, viewerDevice, viewerPlace, castConfig })) {
678
685
  desktopWebRtc.attachPipe(desktopCast.pipeName());
679
686
  if (hadHeld) for (const button of [0, 1, 2]) desktopCast.sendInput({ action: 'mouseup', button });
680
687
  return;
@@ -694,7 +701,11 @@ export async function startRemoteClient(options = {}) {
694
701
  /** Chủ máy bấm "Ngắt" ở khay / `aivin remote disconnect`: chạy ngay khi tệp lệnh xuất hiện (fs.watch), đọc định kỳ chỉ để dự phòng. */
695
702
  const checkCastActionNow = () => {
696
703
  const action = checkCastAction();
704
+ // Gỡ thiết bị tin cậy ở khay. Chỉ siết quyền lại, người đang xem (nếu có) không bị ngắt.
705
+ if (action?.action === 'untrust') return void castTrust.remove(action.key);
706
+ if (action?.action === 'untrust_all') return void castTrust.removeAll();
697
707
  if (action?.action !== 'stop_and_block') return;
708
+ castConsent.revokeSessionTrust(desktopCast.sessionId());
698
709
  lockCast({ viewerDevice: action.viewer_device });
699
710
  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.'));
700
711
  stopDesktopCast('user_revoked');
@@ -771,6 +782,7 @@ export async function startRemoteClient(options = {}) {
771
782
  guiHost?.close();
772
783
  officeHost?.close();
773
784
  processes.stopAll();
785
+ activeAgentRunner()?.stopAll('Remote control was paused on this device');
774
786
  // Công tắc ngắt chặn cả xem / điều khiển màn hình từ web, không chỉ việc của AI.
775
787
  stopDesktopCast('paused');
776
788
  }
@@ -843,6 +855,8 @@ export async function startRemoteClient(options = {}) {
843
855
  guiHost?.close();
844
856
  officeHost?.close();
845
857
  processes.stopAll();
858
+ // Job của agent lập trình: dừng + ghi hồ sơ (`stopped`) — lần chạy sau `agent.status` vẫn đọc được, nói tiếp bằng session_id.
859
+ activeAgentRunner()?.stopAll();
846
860
  keepAwake.close();
847
861
  castAwake.close();
848
862
  watches?.closeAll();
@@ -868,7 +882,8 @@ export async function startRemoteClient(options = {}) {
868
882
  deviceId: creds.device_id,
869
883
  // Đ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).
870
884
  // Đang có người xem màn hình: khởi động lại là cắt phiên (và mất đồng ý của chủ máy — nằm trong bộ nhớ).
871
- isIdle: () => activeCalls === 0 && !processes.hasRunning?.() && !(browserTunnels?.liveCount() > 0) && !meetings?.busy() && !desktopCast.isActive(),
885
+ // Job của agent lập trình chạy nền sau khi `agent.run` đã trả lời (activeCalls về 0) — vẫn là bận: khởi động lại là giết job.
886
+ isIdle: () => activeCalls === 0 && !processes.hasRunning?.() && !activeAgentRunner()?.hasRunning() && !(browserTunnels?.liveCount() > 0) && !meetings?.busy() && !desktopCast.isActive(),
872
887
  lastActivityAt: () => lastActivityAt,
873
888
  say: (m) => say(chalk.cyan(m)),
874
889
  onRestart: async (version) => {
@@ -1118,6 +1133,11 @@ export async function startRemoteClient(options = {}) {
1118
1133
  hold(0, HoldPhase.STARTED);
1119
1134
  };
1120
1135
 
1136
+ const guiActivity = (call, outcome) => {
1137
+ const { method, action, window_class: windowClass } = outcome.result || {};
1138
+ return call.tool.startsWith('gui.') && method ? { method, action, window_class: windowClass } : {};
1139
+ };
1140
+
1121
1141
  /** 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. */
1122
1142
  const handleCall = async (call) => {
1123
1143
  const streamer = createStreamer(socket, call.call_id);
@@ -1143,7 +1163,8 @@ export async function startRemoteClient(options = {}) {
1143
1163
  const payload = { call_id: call.call_id, ...sent };
1144
1164
  ledger.finish(call.call_id, payload, { persistNow: !socket.connected });
1145
1165
  sendResult(payload);
1146
- logActivity({ type: 'tool_call', tool: call.tool, id: call.call_id, success: outcome.ok, error: outcome.error, ms: outcome.duration_ms });
1166
+ // GUI: thao tác đi đường nào (chạy nền hay chuột / phím thật) và trên loại cửa sổ nào — để biết còn bao nhiêu việc phải mượn chuột.
1167
+ logActivity({ type: 'tool_call', tool: call.tool, id: call.call_id, success: outcome.ok, error: outcome.error, ms: outcome.duration_ms, ...guiActivity(call, outcome) });
1147
1168
  if (!tool?.internal) {
1148
1169
  const failed = host ? outcome.error_code : outcome.error;
1149
1170
  say(outcome.ok ? chalk.green(` ✓ ${callLabel(call)} (${outcome.duration_ms} ms)`) : chalk.red(` ✗ ${callLabel(call)}: ${failed}`));
@@ -1282,7 +1303,12 @@ export async function startRemoteClient(options = {}) {
1282
1303
  socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
1283
1304
  const sessionId = payload?.session_id;
1284
1305
  const viewerId = payload?.viewer_id;
1285
- const viewerDevice = payload?.viewer_device || payload?.viewerDevice || payload?.viewer_platform || payload?.viewerPlatform;
1306
+ const viewerType = payload?.viewer_device || payload?.viewerDevice || payload?.viewer_platform || payload?.viewerPlatform;
1307
+ const deviceKey = typeof payload?.device_key === 'string' ? payload.device_key : '';
1308
+ // `viewer_name` (loại máy + model + trình duyệt) chỉ để hiện; máy chủ đời cũ không gửi thì dùng loại máy.
1309
+ const viewerDevice = castViewerLabel(payload?.viewer_name || viewerType, deviceKey, payload?.viewer_key);
1310
+ // Tài khoản / nơi / IP do máy chủ thấy (trình duyệt không tự khai được): chủ máy nhờ đó biết ai đang xin vào, không chỉ tên máy.
1311
+ const viewerInfo = castViewerInfo(payload, mascotLang());
1286
1312
  if (!sessionId || !viewerId) return;
1287
1313
  // Chủ máy đã tạm dừng điều khiển từ xa → từ chối cả xem màn hình.
1288
1314
  if (isRemotePaused()) {
@@ -1290,9 +1316,16 @@ export async function startRemoteClient(options = {}) {
1290
1316
  return;
1291
1317
  }
1292
1318
  // 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.
1293
- const decision = await castConsent.decide({ sessionId, viewerId, viewerDevice, viewerKey: payload?.viewer_key });
1319
+ const decision = await castConsent.decide({
1320
+ sessionId, viewerId, viewerDevice, viewerKey: payload?.viewer_key, deviceKey, viewerInfo,
1321
+ prove: async () => {
1322
+ const proven = await castProver.prove({ sessionId, viewerId, deviceKey });
1323
+ if (proven === true) say(chalk.cyan(` 🔑 Thiết bị tin cậy "${viewerDevice || viewerId}" vào xem màn hình`));
1324
+ return proven;
1325
+ },
1326
+ });
1294
1327
  if (decision !== CastConsentDecision.ALLOW) {
1295
- logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, result: decision });
1328
+ logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, ...viewerInfo, result: decision });
1296
1329
  if (decision === CastConsentDecision.CANCELLED) return;
1297
1330
  say(chalk.red(` ✕ Không cho xem màn hình (${decision}): ${viewerDevice || viewerId}`));
1298
1331
  emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: decision });
@@ -1303,7 +1336,7 @@ export async function startRemoteClient(options = {}) {
1303
1336
  emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
1304
1337
  return;
1305
1338
  }
1306
- logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, result: decision });
1339
+ logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, ...viewerInfo, result: decision });
1307
1340
  const castConfig = {
1308
1341
  max_fps: payload?.max_fps || 15,
1309
1342
  max_width: payload?.max_width || 1366,
@@ -1311,7 +1344,7 @@ export async function startRemoteClient(options = {}) {
1311
1344
  monitor: payload?.monitor ?? -1,
1312
1345
  };
1313
1346
  if (desktopCast.isActive() && desktopCast.sessionId() !== sessionId) stopDesktopCast('replaced', false);
1314
- castTouchViewers.add(viewerId, viewerDevice);
1347
+ castTouchViewers.add(viewerId, viewerType);
1315
1348
  if (desktopCast.sessionId() === sessionId) {
1316
1349
  clearTimeout(castReconfirmTimer);
1317
1350
  castReconfirmTimer = null;
@@ -1319,14 +1352,17 @@ export async function startRemoteClient(options = {}) {
1319
1352
  if (!desktopCast.isActive()) {
1320
1353
  castInputTag = newInputTag();
1321
1354
  castRestarts.length = 0;
1322
- if (!startCapture({ sessionId, viewerId, viewerDevice, castConfig })) return;
1355
+ if (!startCapture({ sessionId, viewerId, viewerDevice, viewerPlace: viewerInfo.place, castConfig })) return;
1323
1356
  } else {
1324
1357
  desktopCast.config(castConfig);
1325
1358
  // Màn hình đứng yên thì ảnh thưa: người mới vào cần một ảnh ngay.
1326
1359
  desktopCast.refresh();
1327
1360
  }
1361
+ // Ảnh mở màn (BE chỉ gửi khi người xem mở lại trên mạng đã biết là tốt): một ảnh JPEG nét trong lúc video còn khởi động.
1362
+ const leadIn = castLeadInConfig(payload?.lead_in);
1363
+ if (leadIn) desktopCast.config(leadIn);
1328
1364
  const webRtcStarted = payload?.transport === 'webrtc'
1329
- ? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null, audio: payload?.audio !== false }).catch(() => false)
1365
+ ? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null, videoCodecs: Array.isArray(payload?.video_codecs) ? payload.video_codecs : null, audio: payload?.audio !== false }).catch(() => false)
1330
1366
  : false;
1331
1367
  // Phiên đã dừng / bị thay trong lúc dựng WebRTC (tới 30 s): không báo trạng thái cho phiên đã chết.
1332
1368
  if (desktopCast.sessionId() !== sessionId) return;
@@ -1336,7 +1372,8 @@ export async function startRemoteClient(options = {}) {
1336
1372
  });
1337
1373
  }));
1338
1374
  socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
1339
- if (payload?.session_id) castConsent.cancel({ sessionId: payload.session_id, viewerId: payload.viewer_id, final: payload.final !== false });
1375
+ if (payload?.session_id) castConsent.cancel({ sessionId: payload.session_id, viewerId: payload.viewer_id, final: payload.final !== false, away: payload.away === true });
1376
+ castProver.cancel(payload?.final !== false ? undefined : payload?.viewer_id);
1340
1377
  if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) {
1341
1378
  // Phiên đã dừng ở máy (gián đoạn) mà máy chủ kết thúc hẳn: quên đồng ý đang giữ.
1342
1379
  if (payload.final !== false) castConsent.forget(payload.session_id);
@@ -1364,6 +1401,7 @@ export async function startRemoteClient(options = {}) {
1364
1401
  castGate.setHumanTakeover(payload.active === true ? { idleMs: Number(payload.idle_ms), maxWaitMs: Number(payload.max_wait_ms) } : null);
1365
1402
  }));
1366
1403
  socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
1404
+ if (payload?.type === 'device_proof') return castProver.answer(payload);
1367
1405
  void desktopWebRtc.signal(payload).catch(() => undefined);
1368
1406
  }));
1369
1407
  meetings?.recover();