@aivin-labs/cli 1.0.5 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +288 -216
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +551 -5
  4. package/bin/lib/browserAutomation.mjs +384 -614
  5. package/bin/lib/browserTui.mjs +276 -251
  6. package/bin/lib/cancellation.mjs +61 -0
  7. package/bin/lib/localBrowser.mjs +345 -0
  8. package/bin/lib/mcpProxy.mjs +869 -837
  9. package/bin/lib/missionStream.mjs +696 -691
  10. package/bin/lib/releaseKeys.mjs +9 -0
  11. package/bin/lib/remote/activityLog.mjs +68 -0
  12. package/bin/lib/remote/autoStart.mjs +617 -0
  13. package/bin/lib/remote/autoUpdate.mjs +129 -0
  14. package/bin/lib/remote/brand.mjs +60 -0
  15. package/bin/lib/remote/browserTunnel.mjs +403 -0
  16. package/bin/lib/remote/callLedger.mjs +134 -0
  17. package/bin/lib/remote/cdpPolicy.mjs +79 -0
  18. package/bin/lib/remote/client.mjs +808 -0
  19. package/bin/lib/remote/clipboard.mjs +138 -0
  20. package/bin/lib/remote/codingAgents.mjs +293 -0
  21. package/bin/lib/remote/constants.mjs +234 -0
  22. package/bin/lib/remote/credentials.mjs +208 -0
  23. package/bin/lib/remote/daemonLock.mjs +86 -0
  24. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  25. package/bin/lib/remote/desktop/index.mjs +272 -0
  26. package/bin/lib/remote/desktop/linux.mjs +144 -0
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  28. package/bin/lib/remote/desktop/mac.mjs +187 -0
  29. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  30. package/bin/lib/remote/desktop/strings.mjs +74 -0
  31. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  32. package/bin/lib/remote/deviceMemory.mjs +246 -0
  33. package/bin/lib/remote/deviceProfile.mjs +142 -0
  34. package/bin/lib/remote/deviceWatches.mjs +138 -0
  35. package/bin/lib/remote/docText.mjs +117 -0
  36. package/bin/lib/remote/fileIndexer.mjs +399 -0
  37. package/bin/lib/remote/gui/index.mjs +326 -0
  38. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  39. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  40. package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
  41. package/bin/lib/remote/httpTransfer.mjs +89 -0
  42. package/bin/lib/remote/idempotency.mjs +135 -0
  43. package/bin/lib/remote/keepAwake.mjs +100 -0
  44. package/bin/lib/remote/localConfirm.mjs +268 -0
  45. package/bin/lib/remote/localPolicy.mjs +256 -0
  46. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  47. package/bin/lib/remote/mascot/ask.mjs +768 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  49. package/bin/lib/remote/mascot/assets.mjs +827 -0
  50. package/bin/lib/remote/mascot/bot.mjs +372 -0
  51. package/bin/lib/remote/mascot/hostSource.mjs +759 -0
  52. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  53. package/bin/lib/remote/mascot/index.mjs +493 -0
  54. package/bin/lib/remote/mascot/labels.mjs +82 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  56. package/bin/lib/remote/mascot/strings.mjs +375 -0
  57. package/bin/lib/remote/mascot/ui.mjs +104 -0
  58. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  59. package/bin/lib/remote/meeting/index.mjs +415 -0
  60. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  61. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  62. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  63. package/bin/lib/remote/memberFsPool.mjs +134 -0
  64. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  65. package/bin/lib/remote/mission.mjs +156 -0
  66. package/bin/lib/remote/missionQuestion.mjs +63 -0
  67. package/bin/lib/remote/multiUser.mjs +344 -0
  68. package/bin/lib/remote/netProxy.mjs +145 -0
  69. package/bin/lib/remote/notify.mjs +58 -0
  70. package/bin/lib/remote/office/index.mjs +90 -0
  71. package/bin/lib/remote/policyCommand.mjs +93 -0
  72. package/bin/lib/remote/processes.mjs +217 -0
  73. package/bin/lib/remote/sandbox.mjs +221 -0
  74. package/bin/lib/remote/schedule.mjs +213 -0
  75. package/bin/lib/remote/scheduler.mjs +124 -0
  76. package/bin/lib/remote/tabGroups.mjs +209 -0
  77. package/bin/lib/remote/textIndex.mjs +131 -0
  78. package/bin/lib/remote/tokenStore.mjs +77 -0
  79. package/bin/lib/remote/toolHandlers.mjs +741 -0
  80. package/bin/lib/remote/undoStore.mjs +242 -0
  81. package/bin/lib/remoteControl.mjs +26 -0
  82. package/bin/lib/scaffold.mjs +654 -653
  83. package/bin/lib/selfUpdate.mjs +71 -0
  84. package/bin/lib/update/binarySwap.mjs +63 -0
  85. package/bin/lib/update/constants.mjs +56 -0
  86. package/bin/lib/update/download.mjs +145 -0
  87. package/bin/lib/update/signature.mjs +42 -0
  88. package/bin/lib/update/state.mjs +205 -0
  89. package/bin/lib/update/versions.mjs +60 -0
  90. package/docs/AIVIN_MASCOT.md +116 -0
  91. package/docs/CLI.md +1484 -1299
  92. package/docs/media/aivin-mascot-states.mp4 +0 -0
  93. package/package.json +71 -62
package/bin/cli.mjs CHANGED
@@ -17,6 +17,11 @@ import { createRequire } from 'module';
17
17
  // expands into.
18
18
  import { flattenManifestFile } from '@aivin-labs/sdk';
19
19
 
20
+ // Side-effect only import - installs the global Ctrl+C → abort-in-flight-requests wiring
21
+ // (`bin/lib/cancellation.mjs`) once, before any command runs. Must load before any lib file below
22
+ // makes its first axios call so the interceptor is already in place.
23
+ import './lib/cancellation.mjs';
24
+
20
25
  import { DEFAULT_AIVIN_BASE_URL, GLOBAL_CREDENTIALS_PATH, fetchWebUrl, loadActiveContext, clearActiveContext } from './lib/context.mjs';
21
26
  import { requireArg } from './lib/util.mjs';
22
27
  import { readStdin, createFromJSON, createInteractive, validatePluginConfig, validateMcpProxyConfig } from './lib/scaffold.mjs';
@@ -50,6 +55,17 @@ import {
50
55
  listAgentsCmd,
51
56
  } from './lib/workspace.mjs';
52
57
  import { runMission, runBrowserMission } from './lib/mission.mjs';
58
+ import { DeviceAccess } from './lib/remote/constants.mjs';
59
+ import { configureProxy } from './lib/remote/netProxy.mjs';
60
+ import { DAEMON_RUNNING } from './lib/remote/daemonLock.mjs';
61
+ import { runPolicyCommand } from './lib/remote/policyCommand.mjs';
62
+ import { loadMascotSettings, saveMascotSettings } from './lib/remote/mascot/index.mjs';
63
+ import { MascotText, mascotLang, mascotText } from './lib/remote/mascot/strings.mjs';
64
+ import { UiResult, showMascotDemo, showMascotUi } from './lib/remote/mascot/ui.mjs';
65
+ import { desktopAppStatus, installDesktopApp, uninstallDesktopApp } from './lib/remote/autoStart.mjs';
66
+ import { createMeetingManager, requestMeeting } from './lib/remote/meeting/index.mjs';
67
+ import { DEFAULT_HOTKEYS, hotkeyCandidates, parseHotkey, probeHotkey } from './lib/remote/mascot/hotkey.mjs';
68
+ import { RESTART_EXIT_CODE, UPDATE_ROLLED_BACK, UpdateStatus, cleanupRetired, downloadRoot, installUpdate, isStandaloneBinary, saveUpdateSettings } from './lib/selfUpdate.mjs';
53
69
  import {
54
70
  createAutomationJob,
55
71
  listTasks,
@@ -65,6 +81,36 @@ import {
65
81
  deleteProjectCmd,
66
82
  listProjectsCmd,
67
83
  } from './lib/tasks.mjs';
84
+ import {
85
+ startRemoteClient,
86
+ testRemoteConnection,
87
+ enableAutoStart,
88
+ disableAutoStart,
89
+ getAutoStartStatus,
90
+ buildDeviceProfile,
91
+ buildTools,
92
+ buildCatalog,
93
+ getOrCreateDeviceId,
94
+ resetDeviceId,
95
+ loadDeviceCredentials,
96
+ pairDevice,
97
+ listDevices,
98
+ unpairDevice,
99
+ isRemotePaused,
100
+ setRemotePaused,
101
+ getRecentLogs,
102
+ clearLogs,
103
+ memoryStats,
104
+ listMemoryItems,
105
+ searchMemory,
106
+ putMemoryItems,
107
+ deleteMemoryItems,
108
+ clearDeviceMemory,
109
+ createFileIndex,
110
+ indexRootsFor,
111
+ runRemoteMission,
112
+ MemoryKind,
113
+ } from './lib/remoteControl.mjs';
68
114
 
69
115
  // Load env vars: the current project's `.env` first (any deliberate per-project override), THEN
70
116
  // fill in AIVIN_BASE_URL/API_KEY/SDK_ENDPOINT from the machine's active context if the project
@@ -91,7 +137,10 @@ const __dirname = dirname(__filename);
91
137
  // This CLI's own version (`aivin --version`) - distinct from whatever @aivin-labs/sdk version a
92
138
  // given plugin project has installed. See lib/scaffold.mjs for how a fresh scaffold's `@aivin-labs/
93
139
  // sdk` dependency pin is resolved (from the actually-installed sdk, not from here).
94
- const CLI_PACKAGE_JSON = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
140
+ // Bản tệp chạy đóng gói (scripts/build-binary.mjs) không có package.json trên đĩa — phiên bản được ghi sẵn lúc build.
141
+ const CLI_PACKAGE_JSON = process.env.AIVIN_CLI_BINARY
142
+ ? { version: process.env.AIVIN_CLI_BINARY, engines: {} }
143
+ : JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
95
144
 
96
145
  const CLI_VERSION = CLI_PACKAGE_JSON.version;
97
146
 
@@ -683,6 +732,9 @@ mcpCommand
683
732
  .option('--private', 'Deploy to your org only - default')
684
733
  .option('--org', 'Alias of --private - there is no narrower per-workspace scope today')
685
734
  .option('--quiet', 'Skip live progress output while scanning (on by default otherwise)')
735
+ .option('--auth', 'Đánh dấu MCP này cần credential -> BE sinh connection_id, CLI hỏi gắn connector (OAuth HOẶC credential_form tuỳ chọn lúc đó). Dùng cho MCP cần API key/token mà scan không tự nhận ra')
736
+ .option('--oauth', 'Bí danh cũ của --auth (giữ để không phá lệnh đã dùng)')
737
+ .option('--test-token <token>', 'Access token dùng THỬ để đọc tool của remote MCP cần OAuth (Notion/Slack/Linear/Figma...). Chỉ dùng lúc quét, KHÔNG lưu lại - xem test_token trong plugin-store.proto')
686
738
  .option('-y, --yes', 'Skip the deploy confirmation prompt (required in non-TTY/CI contexts, which otherwise now refuse to deploy at all - see scanAndPublishMcp)')
687
739
  .action(async (url, options) => {
688
740
  try {
@@ -943,10 +995,11 @@ keyCommand
943
995
 
944
996
  program
945
997
  .command('browser [mission]')
946
- .description("Run an AI Browser mission - by default opens/reuses a local browser window dedicated to AI Browser (own profile, own cookies - log in once, watch missions run live from then on); --remote uses a server-side browser instead")
998
+ .description("Run an AI Browser mission - by default in your everyday Chrome/Edge if you've switched on remote debugging in it (chrome://inspect/#remote-debugging), otherwise in a local browser window dedicated to AI Browser (own profile - log in once, the AI's tabs grouped together); --remote uses a server-side browser instead")
947
999
  .option('--remote', 'Use a server-side pooled browser instead of your own local one (no local browser needed, no cookies/logins carried over)')
948
- .option('--debug-port <port>', 'Local mode only: port to look for/launch your browser\'s remote debugging on (default: 9222, auto-tries a few nearby ports if that one is taken by something else) - pass this to pin an exact port instead')
949
- .option('--browser <edge|chrome>', "Local mode only: which browser to drive - default: auto-detects your OS's actual default browser, falling back to whichever of Edge/Chrome is installed if that can't be determined")
1000
+ .option('--debug-port <port>', 'Local mode only: port to launch the AI Browser window\'s remote debugging on (default: 9222, auto-tries a few nearby ports if that one is taken by something else) - pass this to pin an exact port instead')
1001
+ .option('--browser <edge|chrome|brave|chromium>', "Local mode only: which browser to drive - default: auto-detects your OS's actual default browser, falling back to whichever of Edge/Chrome/Brave/Chromium is installed if that can't be determined")
1002
+ .option('--separate-browser', 'Local mode only: always use the dedicated AI Browser window, never your everyday browser (even if remote debugging is switched on in it)')
950
1003
  .option('--url <url>', "Local mode only: open this URL before the mission starts, instead of a blank page - skips a wasted first analysis step and avoids the AI having to search the web to find the target site itself (auto-guessed for a few well-known sites mentioned by name in the mission if omitted)")
951
1004
  .option('--workspace <id>', 'Workspace id to run in (default: your personal workspace)')
952
1005
  .option('--project <id>', 'Project id within the workspace (--remote only)')
@@ -968,6 +1021,475 @@ program
968
1021
  }
969
1022
  });
970
1023
 
1024
+ program
1025
+ .command('ui')
1026
+ .description('Show the Aivin mascot on this computer with its ask box (Windows) - starts the background listener if it is not running')
1027
+ .option('--demo', 'Preview every mascot animation state without pairing or starting the listener')
1028
+ .action(async (options) => {
1029
+ const lang = mascotLang();
1030
+ const say = (key, color = chalk.green) => console.log(color(mascotText(lang, key)));
1031
+ if (options.demo) {
1032
+ const result = showMascotDemo();
1033
+ if (result === UiResult.UNSUPPORTED) return say(MascotText.CMD_UNSUPPORTED, chalk.yellow);
1034
+ if (result === UiResult.START_FAILED) { console.error(chalk.red('Không thể mở bản demo linh vật.')); process.exitCode = 1; return; }
1035
+ console.log(chalk.green('✓ Demo linh vật đang chạy qua 8 trạng thái — đóng cửa sổ hoặc nhấn Ctrl+C để dừng.'));
1036
+ return;
1037
+ }
1038
+ const result = await showMascotUi({ onStarting: () => say(MascotText.UI_STARTING, chalk.gray) });
1039
+ if (result === UiResult.UNSUPPORTED) return say(MascotText.CMD_UNSUPPORTED, chalk.yellow);
1040
+ if (result === UiResult.SHOWN) return say(MascotText.UI_SHOWN);
1041
+ if (result === UiResult.STARTED) return say(MascotText.UI_STARTED);
1042
+ if (result === UiResult.NOT_PAIRED) return say(MascotText.UI_NOT_PAIRED, chalk.yellow);
1043
+ say(MascotText.UI_START_FAILED, chalk.red);
1044
+ process.exitCode = 1;
1045
+ });
1046
+
1047
+ program
1048
+ .command('desktop [action]')
1049
+ .description('Aivin as a desktop app: install (Windows: system tray + Start menu; macOS: menu bar + Aivin.app; Linux: app menu + tray) and start it with the computer | uninstall | status (default)')
1050
+ .option('--no-autostart', "install: don't start Aivin with the computer (turn it on later from Aivin's menu or the system's startup settings)")
1051
+ .option('--no-launch', "install: don't open Aivin now")
1052
+ .action((action = 'status', options) => {
1053
+ // Chỗ bật / tắt khởi động cùng máy của từng hệ điều hành — cùng chỗ menu Aivin và `aivin remote enable|disable` đổi.
1054
+ const startupWhere = { win32: 'Task Manager → Startup apps', darwin: 'System Settings → General → Login Items', linux: 'Startup Applications / Autostart' }[process.platform] || '';
1055
+ const where = { win32: 'khay hệ thống, tìm "Aivin" trong Start', darwin: 'thanh menu, tìm "Aivin" bằng Spotlight', linux: 'khay hệ thống, tìm "Aivin" trong menu ứng dụng' }[process.platform] || '';
1056
+ try {
1057
+ if (action === 'install') {
1058
+ const res = installDesktopApp({ autostart: options.autostart !== false, launch: options.launch !== false });
1059
+ console.log(chalk.green(`✅ Đã cài Aivin vào máy: ${where}.`));
1060
+ console.log(chalk.gray(` Ứng dụng: ${res.exe}`));
1061
+ console.log(chalk.gray(` Khởi động cùng máy: ${res.autostart ? 'bật' : 'tắt'} (đổi ở menu Aivin hoặc ${startupWhere})`));
1062
+ if (process.platform === 'linux' && !desktopAppStatus().tray) {
1063
+ console.log(chalk.yellow(' ⚠️ Máy chưa có AppIndicator cho python3 nên không có biểu tượng khay — Aivin vẫn chạy nền. Cài: sudo apt install gir1.2-ayatanaappindicator3-0.1 (Ubuntu / Debian)'));
1064
+ }
1065
+ return;
1066
+ }
1067
+ if (action === 'uninstall') {
1068
+ const res = uninstallDesktopApp();
1069
+ console.log(chalk.green('✅ Đã gỡ ứng dụng Aivin trên màn hình và mục khởi động cùng máy (lệnh `aivin` vẫn còn).'));
1070
+ if (!res.removed) console.log(chalk.yellow(' ⚠️ Ứng dụng còn đang chạy nên chưa xoá hết được tệp — chạy lại lệnh này sau ít giây.'));
1071
+ return;
1072
+ }
1073
+ if (action !== 'status') throw new Error('Dùng: aivin desktop install [--no-autostart] [--no-launch] | uninstall | status');
1074
+ const st = desktopAppStatus();
1075
+ if (st.supported === false) return console.log(chalk.gray(`Chưa có ứng dụng Aivin trên màn hình cho ${process.platform} — dùng \`aivin remote enable\`.`));
1076
+ console.log(chalk.blue('🖥️ Aivin trên máy này:'));
1077
+ console.log(chalk.gray(` Ứng dụng: ${st.installed ? st.app : 'chưa cài — aivin desktop install'}`));
1078
+ if (st.installed) console.log(chalk.gray(` Tìm bằng: ${st.search || 'không'}`));
1079
+ console.log(chalk.gray(` Khởi động cùng máy: ${st.startup.registered ? (st.startup.enabled ? 'bật' : `tắt (${startupWhere})`) : 'không'}`));
1080
+ if (process.platform === 'linux') console.log(chalk.gray(` Biểu tượng khay: ${st.tray ? 'có' : 'không (thiếu python3 + AppIndicator) — vẫn chạy nền'}`));
1081
+ } catch (error) {
1082
+ console.error(chalk.red('❌'), error.message);
1083
+ process.exit(1);
1084
+ }
1085
+ });
1086
+
1087
+ program
1088
+ .command('update')
1089
+ .description('Update aivin to the latest release (installs from get.aivin.vn; checks the release signature, the SHA256 and that the new build starts)')
1090
+ .option('--check', 'Only check whether a newer release exists')
1091
+ .option('--to <version>', 'Install this release instead of the latest, e.g. v1.0.9 (also allows going back)')
1092
+ .option('--auto <on|off>', 'Turn background updates of `aivin remote start` on or off for this computer')
1093
+ .option('--proxy <url>', 'HTTP proxy to download through (default: HTTPS_PROXY, else the system proxy setting; "none" = connect directly)')
1094
+ .action(async (options) => {
1095
+ try {
1096
+ if (options.auto !== undefined) {
1097
+ const value = String(options.auto).toLowerCase();
1098
+ if (!['on', 'off'].includes(value)) throw new Error('Dùng: aivin update --auto on|off');
1099
+ saveUpdateSettings({ auto: value === 'on' });
1100
+ console.log(chalk.green(value === 'on' ? '✅ Đã bật tự cập nhật nền.' : '✅ Đã tắt tự cập nhật nền — cập nhật bằng `aivin update` khi cần.'));
1101
+ return;
1102
+ }
1103
+ configureProxy({ explicit: options.proxy });
1104
+ if (isStandaloneBinary()) cleanupRetired();
1105
+ const root = downloadRoot();
1106
+ const res = await installUpdate({ version: options.to, root, check: !!options.check, force: !!options.to });
1107
+ if (res.status === UpdateStatus.UP_TO_DATE) return console.log(chalk.green(`✅ aivin ${res.current} là bản mới nhất.`));
1108
+ if (res.status === UpdateStatus.NOT_BINARY) {
1109
+ return console.log(chalk.yellow(`⬆ Có aivin ${res.latest} (máy này ${res.current}). Bản cài qua npm: npm i -g @aivin-labs/cli@latest`));
1110
+ }
1111
+ if (res.status === UpdateStatus.AVAILABLE) return console.log(chalk.yellow(`⬆ Có aivin ${res.latest} (máy này ${res.current}) — chạy \`aivin update\` để cài.`));
1112
+ if (res.status === UpdateStatus.SKIPPED) {
1113
+ return console.log(chalk.yellow(`⚠️ Máy này đã tự lùi khỏi aivin ${res.latest} (khởi động hỏng). Vẫn muốn cài: aivin update --to ${res.latest}`));
1114
+ }
1115
+ if (res.status === UpdateStatus.BUSY) return console.log(chalk.yellow('⏳ Đang có một lần cập nhật khác chạy trên máy này — thử lại sau ít phút.'));
1116
+ console.log(chalk.green(`✅ Đã cài aivin ${res.latest} (trước đó ${res.current}).`));
1117
+ console.log(chalk.gray(' `aivin remote start` chạy nền (tự khởi động cùng máy) tự chuyển sang bản mới khi máy rảnh; cửa sổ đang mở thì đóng và chạy lại.'));
1118
+ } catch (error) {
1119
+ console.error(chalk.red('❌'), error.message);
1120
+ process.exit(1);
1121
+ }
1122
+ });
1123
+
1124
+ const remoteCommand = program
1125
+ .command('remote')
1126
+ .description('Let your Aivin agents work on this computer (Device Agent) - pair, run the listener, manage memory and safety')
1127
+ // Proxy công ty cho mọi lệnh remote gọi máy chủ (ghép máy, remote do, test…) — `start` tự cấu hình kèm --proxy của nó.
1128
+ .hook('preAction', (_cmd, action) => { if (action.name() !== 'start') configureProxy({ explicit: action.opts().proxy }); });
1129
+
1130
+ const remoteFail = (error) => {
1131
+ console.error(chalk.red('❌'), error.message);
1132
+ process.exit(1);
1133
+ };
1134
+
1135
+ remoteCommand
1136
+ .command('start')
1137
+ .description('Pair this computer (first time) and listen for work from your agents in the foreground')
1138
+ .option('--dir <path>', 'Folder the agent may work in (default: the folder saved at pairing, else the current folder)')
1139
+ .option('--name <name>', 'Name shown for this computer (default: hostname)')
1140
+ .option('--repair', 'Pair again (new device token; the old one stops working)')
1141
+ .option('--full-access', 'Let the agent work anywhere on this computer (all drives; relative paths start at your home folder). Kept across restarts; --dir switches back to one folder')
1142
+ .option('--code <code>', 'Pair with a one-time code from Aivin (chat box → Browser ▾ → Add this computer) - no `aivin login` needed')
1143
+ .option('--server <url>', 'Aivin server the code belongs to (Aivin prints it in the command when needed)')
1144
+ .option('--no-browser', "Don't let AI Browser use a browser window on this computer (web tasks then run in Aivin's server-side browser)")
1145
+ .option('--no-gui', "Don't let the agent control app windows on this computer with the mouse/keyboard (Windows)")
1146
+ .option('--no-meetings', "Don't let the agent take notes of meetings (record the computer's sound + microphone) or take screenshots on this computer (Windows)")
1147
+ .option('--separate-browser', "Always use Aivin's own browser window, never your everyday Chrome/Edge (even if remote debugging is enabled at chrome://inspect/#remote-debugging)")
1148
+ .option('--quiet', 'No interactive logs')
1149
+ .option('--proxy <url>', 'HTTP proxy to reach Aivin through (default: HTTPS_PROXY, else the system proxy setting; "none" = connect directly)')
1150
+ .option('--no-keep-awake', "Don't keep this computer from sleeping while the agent is working on it")
1151
+ .option('--no-auto-update', "Don't download new aivin releases in the background this run (to turn it off for good: aivin update --auto off)")
1152
+ .option('--no-mascot', "Don't show the Aivin mascot on screen this run (to turn it off for good: aivin remote mascot off)")
1153
+ .option('--multi-user', "Organization cloud computer (Linux container provisioned by Aivin): token from AIVIN_DEVICE_TOKEN/AIVIN_DEVICE_ID/AIVIN_SERVER, every org member works in their own Linux account + home folder")
1154
+ .action(async (options) => {
1155
+ try {
1156
+ await startRemoteClient(options);
1157
+ } catch (error) {
1158
+ // Tự khởi động (--quiet) mà đã có cửa sổ khác nhận việc: không phải lỗi — thoát 0 để trình giữ chạy không chạy lại mãi.
1159
+ if (error?.code === DAEMON_RUNNING && options.quiet) {
1160
+ console.error(chalk.gray(error.message));
1161
+ process.exit(0);
1162
+ }
1163
+ // Vừa tự lùi bản: có trình giữ chạy → mã 75, được mở lại ngay bằng bản cũ.
1164
+ if (error?.code === UPDATE_ROLLED_BACK) {
1165
+ console.error(chalk.yellow(`↩ ${error.message}`));
1166
+ process.exit(error.restart ? RESTART_EXIT_CODE : 1);
1167
+ }
1168
+ remoteFail(error);
1169
+ }
1170
+ });
1171
+
1172
+ remoteCommand
1173
+ .command('pair')
1174
+ .description('Pair (or re-pair) this computer with your account without starting the listener')
1175
+ .option('--dir <path>', 'Folder the agent may work in (default: current folder)')
1176
+ .option('--name <name>', 'Name shown for this computer (default: hostname)')
1177
+ .action(async (options) => {
1178
+ try {
1179
+ const roots = [path.resolve(options.dir || process.cwd())];
1180
+ const creds = await pairDevice({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY, roots, name: options.name, profile: buildDeviceProfile(roots) });
1181
+ console.log(chalk.green(`✅ Đã ghép máy "${creds.name}" (${creds.device_id})`));
1182
+ console.log(chalk.gray(` Thư mục được phép: ${creds.roots.join(' | ')}`));
1183
+ console.log(chalk.gray(' Chạy `aivin remote start` để bắt đầu nhận việc.'));
1184
+ } catch (error) {
1185
+ remoteFail(error);
1186
+ }
1187
+ });
1188
+
1189
+ remoteCommand
1190
+ .command('devices')
1191
+ .description('List computers paired with your account and whether they are online')
1192
+ .action(async () => {
1193
+ try {
1194
+ const devices = await listDevices({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY });
1195
+ const mine = loadDeviceCredentials()?.device_id;
1196
+ if (!devices.length) return console.log(chalk.gray('Chưa có máy nào được ghép. Chạy `aivin remote start` trên máy cần dùng.'));
1197
+ for (const d of devices) {
1198
+ const state = d.online ? chalk.green('● online') : chalk.gray('○ offline');
1199
+ console.log(`${state} ${chalk.bold(d.name)}${d.device_id === mine ? chalk.cyan(' (máy này)') : ''} ${chalk.gray(`${d.platform || ''} · ${d.tools_count} công cụ · ${d.device_id}`)}`);
1200
+ }
1201
+ } catch (error) {
1202
+ remoteFail(error);
1203
+ }
1204
+ });
1205
+
1206
+ remoteCommand
1207
+ .command('unpair [deviceId]')
1208
+ .description('Revoke a paired computer (default: this one) - its token stops working immediately')
1209
+ .action(async (deviceId) => {
1210
+ try {
1211
+ const target = deviceId || loadDeviceCredentials()?.device_id;
1212
+ if (!target) throw new Error('Máy này chưa được ghép.');
1213
+ await unpairDevice({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY, deviceId: target });
1214
+ console.log(chalk.green(`✅ Đã thu hồi máy ${target}.`));
1215
+ } catch (error) {
1216
+ remoteFail(error);
1217
+ }
1218
+ });
1219
+
1220
+ remoteCommand
1221
+ .command('pause')
1222
+ .description('Kill switch: refuse every remote call on this computer until `aivin remote resume`')
1223
+ .action(() => {
1224
+ setRemotePaused(true);
1225
+ console.log(chalk.yellow('⏸ Đã tạm dừng — máy này từ chối mọi việc từ xa.'));
1226
+ });
1227
+
1228
+ remoteCommand
1229
+ .command('mascot [action] [combo]')
1230
+ .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 that calls the mascot (default Win+Alt+Space)')
1231
+ .action((action, combo) => {
1232
+ const lang = mascotLang();
1233
+ if (action === 'hotkey') {
1234
+ try {
1235
+ const setting = loadMascotSettings().hotkey;
1236
+ if (!combo) {
1237
+ const active = hotkeyCandidates(setting);
1238
+ if (!active.length) return console.log('Phím tắt gọi linh vật: tắt (bật lại: aivin remote mascot hotkey default)');
1239
+ return console.log(`Phím tắt gọi linh vật: ${active[0].label}${setting ? '' : ' (mặc định)'} — không đăng ký được thì thử lần lượt: ${active.slice(1).map((h) => h.label).join(', ')}`);
1240
+ }
1241
+ if (combo === 'off') { saveMascotSettings({ hotkey: 'off' }); return console.log(chalk.green('✅ Đã tắt phím tắt gọi linh vật.')); }
1242
+ if (combo === 'default') { saveMascotSettings({ hotkey: null }); return console.log(chalk.green(`✅ Dùng phím tắt mặc định ${DEFAULT_HOTKEYS[0]}.`)); }
1243
+ const hotkey = parseHotkey(combo);
1244
+ const free = probeHotkey(hotkey);
1245
+ if (free === false) {
1246
+ console.log(chalk.yellow(`⚠️ ${hotkey.label} đang bị một ứng dụng khác (hoặc chính linh vật đang chạy) giữ — nếu không phải linh vật thì chọn tổ hợp khác.`));
1247
+ }
1248
+ saveMascotSettings({ hotkey: hotkey.label });
1249
+ return console.log(chalk.green(`✅ Phím tắt gọi linh vật: ${hotkey.label} — có hiệu lực khi linh vật khởi động lại (aivin remote start).`));
1250
+ } catch (error) {
1251
+ return remoteFail(error);
1252
+ }
1253
+ }
1254
+ if (action && !['on', 'off'].includes(action)) remoteFail(new Error(mascotText(lang, MascotText.CMD_USAGE)));
1255
+ if (process.platform !== 'win32') console.log(chalk.gray(mascotText(lang, MascotText.CMD_UNSUPPORTED)));
1256
+ if (!action) return console.log(mascotText(lang, loadMascotSettings().enabled ? MascotText.CMD_STATUS_ON : MascotText.CMD_STATUS_OFF));
1257
+ saveMascotSettings({ enabled: action === 'on' });
1258
+ console.log(chalk.green(`✅ ${mascotText(lang, action === 'on' ? MascotText.CMD_ON : MascotText.CMD_OFF)}`));
1259
+ });
1260
+
1261
+ remoteCommand
1262
+ .command('meeting [action] [title...]')
1263
+ .description('Meeting notes on this computer (Windows, needs `aivin remote start` running): start [title] | stop | status | list | show [id] — records the computer\'s sound (the others) + your microphone, transcribes it when the meeting ends')
1264
+ .option('--then <instruction>', 'start: what Aivin should do with the transcript afterwards, e.g. "summarize and draft an email to my manager"')
1265
+ .option('--lang <vi|en>', 'start: language spoken in the meeting')
1266
+ .option('--no-screens', "start: don't save screenshots when the screen changes")
1267
+ .action(async (action = 'status', titleWords = [], options) => {
1268
+ try {
1269
+ const fmt = (s) => { const m = Math.floor((s || 0) / 60); return `${m} phút ${String((s || 0) % 60).padStart(2, '0')} giây`; };
1270
+ if (action === 'start') {
1271
+ const res = await requestMeeting('start', { title: titleWords.join(' '), then: options.then, lang: options.lang, screens: options.screens });
1272
+ console.log(chalk.green(`🎙️ Đang ghi "${res.title}" (id ${res.id})${res.sources && !res.sources.mic ? ' — không mở được micro' : ''}${res.sources && !res.sources.system ? ' — không mở được âm thanh máy' : ''}.`));
1273
+ console.log(chalk.yellow(' Hãy báo cho mọi người trong cuộc họp biết họ đang được ghi âm.'));
1274
+ console.log(chalk.gray(' Tự dừng khi cửa sổ họp đóng / im lặng lâu; dừng tay: aivin remote meeting stop'));
1275
+ return;
1276
+ }
1277
+ if (action === 'stop') {
1278
+ const res = await requestMeeting('stop', { id: titleWords[0] });
1279
+ console.log(chalk.green(`⏹ Đã dừng ghi "${res.title}" (${fmt(res.duration_s)}) — đang làm biên bản, xem: aivin remote meeting status`));
1280
+ return;
1281
+ }
1282
+ const meetings = createMeetingManager({ media: null });
1283
+ if (action === 'list' || action === 'status') {
1284
+ const list = meetings.list({ limit: action === 'list' ? 20 : 5 });
1285
+ if (!list.length) return console.log(chalk.gray('Chưa ghi cuộc họp nào trên máy này. Bắt đầu: aivin remote meeting start "Tên cuộc họp"'));
1286
+ for (const m of list) {
1287
+ const when = new Date(m.started_at).toLocaleString('vi-VN');
1288
+ console.log(`${m.status === 'recording' ? '🔴' : m.status === 'done' ? '✅' : m.status === 'failed' ? '❌' : '⏳'} ${m.title} ${chalk.gray(`${when} · ${fmt(m.duration_s)} · ${m.status}${m.follow_up ? ` · việc sau họp: ${m.follow_up}` : ''} · ${m.id}`)}`);
1289
+ }
1290
+ return;
1291
+ }
1292
+ if (action === 'show') {
1293
+ const t = meetings.transcript({ id: titleWords[0], max_chars: 100_000 });
1294
+ console.log(t.text || chalk.gray(t.note));
1295
+ return;
1296
+ }
1297
+ remoteFail(new Error('Usage: aivin remote meeting start [title] [--then "..."] | stop | status | list | show [id]'));
1298
+ } catch (error) {
1299
+ remoteFail(error);
1300
+ }
1301
+ });
1302
+
1303
+ remoteCommand
1304
+ .command('policy [action] [value]')
1305
+ .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')
1306
+ .action(async (action, value) => {
1307
+ try {
1308
+ await runPolicyCommand(action, value);
1309
+ } catch (error) {
1310
+ remoteFail(error);
1311
+ }
1312
+ });
1313
+
1314
+ remoteCommand
1315
+ .command('resume')
1316
+ .description('Turn the kill switch off')
1317
+ .action(() => {
1318
+ setRemotePaused(false);
1319
+ console.log(chalk.green('▶ Máy này nhận việc từ xa trở lại.'));
1320
+ });
1321
+
1322
+ remoteCommand
1323
+ .command('enable')
1324
+ .description('Start the listener automatically when this computer starts (Windows: the Aivin tray app, listed in Task Manager → Startup apps)')
1325
+ .option('--dir <path>', 'Folder the agent may work in (default: current folder)')
1326
+ .option('--proxy <url>', 'HTTP proxy the auto-started listener should use (default: detect at every start)')
1327
+ .action((options) => {
1328
+ try {
1329
+ const res = enableAutoStart(options);
1330
+ console.log(chalk.green('✅ Đã bật tự khởi động cùng máy.'));
1331
+ console.log(chalk.gray(` Thư mục: ${res.rootDir}`));
1332
+ console.log(chalk.gray(` Tệp khởi động: ${res.filePath}`));
1333
+ if (res.warning) console.log(chalk.yellow(` ⚠️ ${res.warning}`));
1334
+ } catch (error) {
1335
+ remoteFail(error);
1336
+ }
1337
+ });
1338
+
1339
+ remoteCommand
1340
+ .command('disable')
1341
+ .description('Stop starting the listener with this computer')
1342
+ .action(() => {
1343
+ try {
1344
+ disableAutoStart();
1345
+ console.log(chalk.green('✅ Đã tắt tự khởi động cùng máy.'));
1346
+ } catch (error) {
1347
+ remoteFail(error);
1348
+ }
1349
+ });
1350
+
1351
+ remoteCommand
1352
+ .command('status')
1353
+ .description('Show pairing, allowed folders, kill switch, auto-start, tools and memory of this computer')
1354
+ .action(() => {
1355
+ try {
1356
+ const creds = loadDeviceCredentials();
1357
+ const roots = creds?.roots?.length ? creds.roots : [process.cwd()];
1358
+ const profile = buildDeviceProfile(roots);
1359
+ const { catalog, hash } = buildCatalog(buildTools({ roots, binaries: profile.binaries, projects: profile.projects }));
1360
+ const stats = memoryStats();
1361
+ console.log(chalk.blue('💻 Máy này:'));
1362
+ console.log(chalk.gray(` Mã máy: ${getOrCreateDeviceId()}`));
1363
+ console.log(chalk.gray(` Đã ghép: ${creds ? chalk.green(`có — ${creds.name} @ ${creds.server_url}`) : chalk.yellow('chưa')}`));
1364
+ console.log(chalk.gray(` Thư mục: ${roots.join(' | ')}`));
1365
+ console.log(chalk.gray(` Công tắc ngắt: ${isRemotePaused() ? chalk.yellow('ĐANG TẠM DỪNG') : 'tắt'}`));
1366
+ console.log(chalk.gray(` Tự khởi động: ${getAutoStartStatus().enabled ? 'bật' : 'tắt'}`));
1367
+ console.log(chalk.gray(` Chương trình: ${profile.binaries.join(', ') || '-'}`));
1368
+ console.log(chalk.gray(` Dự án: ${profile.projects.map((p) => `${p.name} (${p.kind})`).join(', ') || '-'}`));
1369
+ console.log(chalk.gray(` Ghi nhớ: ${stats.total} mục (${stats.with_vector} có vector) — ${stats.dir}`));
1370
+ console.log(chalk.blue(`\n🛠️ ${catalog.length} công cụ (dấu vân tay ${hash.slice(0, 12)}):`));
1371
+ for (const t of catalog) console.log(` - ${chalk.cyan(t.name)}${t.read_only ? chalk.gray(' [chỉ đọc]') : t.destructive ? chalk.red(' [không hoàn tác]') : chalk.yellow(' [ghi]')}`);
1372
+ } catch (error) {
1373
+ remoteFail(error);
1374
+ }
1375
+ });
1376
+
1377
+ remoteCommand
1378
+ .command('test')
1379
+ .description('Check the server connection and whether the server sees this computer online')
1380
+ .action(async () => {
1381
+ try {
1382
+ const r = await testRemoteConnection();
1383
+ console.log(chalk.gray(` Máy chủ: ${r.serverUrl} — ${r.httpOk ? chalk.green(`thông (${r.latencyMs} ms)`) : chalk.red('không kết nối được')}`));
1384
+ console.log(chalk.gray(` Đã ghép: ${r.paired ? `có (${r.deviceId})` : chalk.yellow('chưa — chạy aivin remote start')}`));
1385
+ if (r.online !== null) console.log(chalk.gray(` Online: ${r.online ? chalk.green('có') : chalk.yellow(r.registered === false ? 'máy chủ không có máy này (đã thu hồi?)' : 'không — chạy aivin remote start')}`));
1386
+ if (r.error) console.log(chalk.yellow(` ⚠️ ${r.error}`));
1387
+ } catch (error) {
1388
+ remoteFail(error);
1389
+ }
1390
+ });
1391
+
1392
+ remoteCommand
1393
+ .command('logs')
1394
+ .description('Recent remote activity on this computer')
1395
+ .option('--limit <n>', 'Entries to show (default 30)', '30')
1396
+ .option('--clear', 'Clear the activity log')
1397
+ .action((options) => {
1398
+ if (options.clear) {
1399
+ clearLogs();
1400
+ return console.log(chalk.green('✅ Đã xoá nhật ký.'));
1401
+ }
1402
+ const logs = getRecentLogs(options.limit);
1403
+ if (!logs.length) return console.log(chalk.gray('Chưa có hoạt động nào.'));
1404
+ for (const log of logs) {
1405
+ const time = log.timestamp ? new Date(log.timestamp).toLocaleTimeString() : '';
1406
+ if (log.type === 'tool_call') console.log(` [${time}] ${log.success ? chalk.green('✓') : chalk.red('✗')} ${chalk.cyan(log.tool)}${log.ms !== undefined ? chalk.gray(` ${log.ms} ms`) : ''} ${log.error ? chalk.red(log.error) : ''}`);
1407
+ else console.log(` [${time}] ${chalk.gray(log.type)} ${chalk.gray(log.reason || log.serverUrl || '')}`);
1408
+ }
1409
+ });
1410
+
1411
+ remoteCommand
1412
+ .command('memory [action] [value...]')
1413
+ .description('On-device memory (~/.aivin/memory/*.yaml): list [kind] | search <words> | add <text> | forget <id> | clear [kind]')
1414
+ .option('--kind <kind>', `Kind: ${Object.values(MemoryKind).join(', ')}`)
1415
+ .option('--key <key>', 'Stable key for add (default: derived from the text)')
1416
+ .action((action = 'list', valueParts = [], options) => {
1417
+ try {
1418
+ const value = valueParts.join(' ').trim();
1419
+ if (action === 'search') {
1420
+ if (!value) throw new Error('Dùng: aivin remote memory search <từ khoá>');
1421
+ const hits = searchMemory({ query: value, kinds: options.kind ? [options.kind] : undefined, limit: 20 });
1422
+ if (!hits.length) return console.log(chalk.gray('Không có mục nào khớp.'));
1423
+ hits.forEach((h) => console.log(` ${chalk.gray(h.id)} [${h.kind}] ${chalk.bold(h.key)}: ${h.text}`));
1424
+ return;
1425
+ }
1426
+ if (action === 'add') {
1427
+ if (!value) throw new Error('Dùng: aivin remote memory add "<nội dung>" --kind fact --key <khoá>');
1428
+ const kind = options.kind || MemoryKind.FACT;
1429
+ const key = options.key || value.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').slice(0, 60);
1430
+ putMemoryItems([{ kind, key, text: value }]);
1431
+ return console.log(chalk.green(`✅ Đã nhớ [${kind}] ${key}`));
1432
+ }
1433
+ if (action === 'forget') {
1434
+ if (!value) throw new Error('Dùng: aivin remote memory forget <id> (xem id bằng memory list / search)');
1435
+ const res = deleteMemoryItems({ ids: value.split(/[\s,]+/) });
1436
+ return console.log(chalk.green(`✅ Đã quên ${res.deleted} mục.`));
1437
+ }
1438
+ if (action === 'clear') {
1439
+ clearDeviceMemory(value || options.kind || undefined);
1440
+ return console.log(chalk.green('✅ Đã xoá bộ nhớ.'));
1441
+ }
1442
+ const page = listMemoryItems({ kind: value || options.kind, limit: 100 });
1443
+ const stats = memoryStats();
1444
+ console.log(chalk.blue(`🧠 Bộ nhớ trên máy: ${stats.total} mục — ${stats.dir} (sửa tay các tệp .yaml được)`));
1445
+ page.items.forEach((i) => console.log(` ${chalk.gray(i.id)} [${i.kind}] ${chalk.bold(i.key)}: ${String(i.text).slice(0, 160)}`));
1446
+ if (page.next_cursor !== null) console.log(chalk.gray(` … còn ${page.total - page.items.length} mục`));
1447
+ } catch (error) {
1448
+ remoteFail(error);
1449
+ }
1450
+ });
1451
+
1452
+ remoteCommand
1453
+ .command('reindex')
1454
+ .description('Rebuild the file index of the allowed folders now')
1455
+ .action(async () => {
1456
+ try {
1457
+ const creds = loadDeviceCredentials();
1458
+ const index = createFileIndex(indexRootsFor(creds?.roots || [process.cwd()], creds?.access === DeviceAccess.FULL));
1459
+ const stats = await index.build();
1460
+ index.close();
1461
+ console.log(chalk.green(`✅ Chỉ mục: ${stats.files} tệp (${stats.updated} cập nhật, ${stats.removed} bỏ) trong ${stats.ms} ms`));
1462
+ } catch (error) {
1463
+ remoteFail(error);
1464
+ }
1465
+ });
1466
+
1467
+ remoteCommand
1468
+ .command('reset-id')
1469
+ .description('Give this computer a new device id (cloned machines) - you must pair again')
1470
+ .action(() => {
1471
+ const id = resetDeviceId();
1472
+ console.log(chalk.green(`✅ Mã máy mới: ${id} — chạy \`aivin remote start\` để ghép lại.`));
1473
+ });
1474
+
1475
+ remoteCommand
1476
+ .command('do [objective]')
1477
+ .description('Give a job to the Device Agent on your computer (the listener must be running there)')
1478
+ .option('--device <name>', 'Which paired computer (default: your online one)')
1479
+ .option('--cwd <path>', 'Folder the job is about')
1480
+ .option('--file <id...>', 'Aivin workspace file id(s) the job may save onto the computer')
1481
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1482
+ .option('--agent <id>', 'Agent to act as (default: the workspace default agent)')
1483
+ .option('--no-watch', 'Do not stream progress')
1484
+ .action(async (objective, options) => {
1485
+ try {
1486
+ objective = await requireArg(objective, { prompt: 'What should the agent do on your computer?', usage: 'Usage: aivin remote do "<job>"' });
1487
+ await runRemoteMission(objective, options);
1488
+ } catch (error) {
1489
+ remoteFail(error);
1490
+ }
1491
+ });
1492
+
971
1493
  const doCommand = program
972
1494
  .command('do [agentNickname] [mission]')
973
1495
  .description("Have <agentNickname> work toward a goal in the background - not a specific deployed plugin")
@@ -1341,7 +1863,29 @@ projectCommand
1341
1863
  }
1342
1864
  });
1343
1865
 
1344
- export { validatePluginConfig, incrementVersion, validateMcpProxyConfig, buildDeploymentPayload, buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, setFieldConnector, buildRegisterConnectorDto, buildCreateTaskPayload };
1866
+ export {
1867
+ validatePluginConfig,
1868
+ incrementVersion,
1869
+ validateMcpProxyConfig,
1870
+ buildDeploymentPayload,
1871
+ buildMcpManifest,
1872
+ parseMcpArgs,
1873
+ guessConnectorQueryFromEnvVarName,
1874
+ setFieldConnector,
1875
+ buildRegisterConnectorDto,
1876
+ buildCreateTaskPayload,
1877
+ buildDeviceProfile,
1878
+ buildTools,
1879
+ buildCatalog,
1880
+ enableAutoStart,
1881
+ disableAutoStart,
1882
+ getAutoStartStatus,
1883
+ resetDeviceId,
1884
+ getRecentLogs,
1885
+ clearLogs,
1886
+ testRemoteConnection,
1887
+ runRemoteMission,
1888
+ };
1345
1889
 
1346
1890
  // Only parse argv when run directly (`aivin ...` / `node bin/cli.mjs ...`),
1347
1891
  // not when this module is imported (e.g. by tests) - otherwise Commander
@@ -1353,6 +1897,8 @@ export { validatePluginConfig, incrementVersion, validateMcpProxyConfig, buildDe
1353
1897
  // string-equal the resolved URL and silently skip program.parse() entirely (global `aivin` would
1354
1898
  // do nothing at all). Resolve argv[1] through the same symlink before comparing.
1355
1899
  function resolveIsMain() {
1900
+ // Tệp chạy đóng gói: chính nó là chương trình, không có chuyện bị import.
1901
+ if (process.env.AIVIN_CLI_BINARY) return true;
1356
1902
  if (!process.argv[1]) return false;
1357
1903
  try {
1358
1904
  return import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href;