@aivin-labs/cli 1.0.4 → 1.0.8

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 (76) hide show
  1. package/README.md +263 -216
  2. package/bin/cli.mjs +1780 -1361
  3. package/bin/lib/browserAutomation.mjs +655 -648
  4. package/bin/lib/browserTui.mjs +276 -245
  5. package/bin/lib/cancellation.mjs +61 -0
  6. package/bin/lib/codegen.mjs +61 -5
  7. package/bin/lib/connectors.mjs +55 -21
  8. package/bin/lib/deploy.mjs +25 -2
  9. package/bin/lib/mcpProxy.mjs +869 -773
  10. package/bin/lib/mission.mjs +13 -1
  11. package/bin/lib/missionStream.mjs +696 -660
  12. package/bin/lib/pluginAuthResolve.mjs +127 -0
  13. package/bin/lib/pluginTrigger.mjs +207 -90
  14. package/bin/lib/releaseKeys.mjs +9 -0
  15. package/bin/lib/remote/activityLog.mjs +68 -0
  16. package/bin/lib/remote/autoStart.mjs +457 -0
  17. package/bin/lib/remote/autoUpdate.mjs +129 -0
  18. package/bin/lib/remote/brand.mjs +60 -0
  19. package/bin/lib/remote/browserTunnel.mjs +292 -0
  20. package/bin/lib/remote/callLedger.mjs +134 -0
  21. package/bin/lib/remote/cdpPolicy.mjs +66 -0
  22. package/bin/lib/remote/client.mjs +726 -0
  23. package/bin/lib/remote/constants.mjs +173 -0
  24. package/bin/lib/remote/credentials.mjs +208 -0
  25. package/bin/lib/remote/daemonLock.mjs +86 -0
  26. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  27. package/bin/lib/remote/deviceMemory.mjs +246 -0
  28. package/bin/lib/remote/deviceProfile.mjs +142 -0
  29. package/bin/lib/remote/deviceWatches.mjs +138 -0
  30. package/bin/lib/remote/docText.mjs +117 -0
  31. package/bin/lib/remote/fileIndexer.mjs +399 -0
  32. package/bin/lib/remote/gui/index.mjs +245 -0
  33. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  34. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  35. package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
  36. package/bin/lib/remote/httpTransfer.mjs +89 -0
  37. package/bin/lib/remote/idempotency.mjs +135 -0
  38. package/bin/lib/remote/keepAwake.mjs +100 -0
  39. package/bin/lib/remote/localConfirm.mjs +268 -0
  40. package/bin/lib/remote/localPolicy.mjs +249 -0
  41. package/bin/lib/remote/mascot/assets.mjs +218 -0
  42. package/bin/lib/remote/mascot/hostSource.mjs +362 -0
  43. package/bin/lib/remote/mascot/index.mjs +322 -0
  44. package/bin/lib/remote/mascot/labels.mjs +83 -0
  45. package/bin/lib/remote/mascot/strings.mjs +189 -0
  46. package/bin/lib/remote/memberFsPool.mjs +134 -0
  47. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  48. package/bin/lib/remote/mission.mjs +156 -0
  49. package/bin/lib/remote/missionQuestion.mjs +63 -0
  50. package/bin/lib/remote/multiUser.mjs +344 -0
  51. package/bin/lib/remote/netProxy.mjs +145 -0
  52. package/bin/lib/remote/notify.mjs +58 -0
  53. package/bin/lib/remote/office/index.mjs +90 -0
  54. package/bin/lib/remote/policyCommand.mjs +93 -0
  55. package/bin/lib/remote/processes.mjs +217 -0
  56. package/bin/lib/remote/sandbox.mjs +221 -0
  57. package/bin/lib/remote/schedule.mjs +213 -0
  58. package/bin/lib/remote/scheduler.mjs +124 -0
  59. package/bin/lib/remote/textIndex.mjs +131 -0
  60. package/bin/lib/remote/tokenStore.mjs +77 -0
  61. package/bin/lib/remote/toolHandlers.mjs +726 -0
  62. package/bin/lib/remote/undoStore.mjs +242 -0
  63. package/bin/lib/remoteControl.mjs +26 -0
  64. package/bin/lib/scaffold.mjs +654 -653
  65. package/bin/lib/selfUpdate.mjs +71 -0
  66. package/bin/lib/store.mjs +16 -2
  67. package/bin/lib/tasks.mjs +52 -8
  68. package/bin/lib/update/binarySwap.mjs +63 -0
  69. package/bin/lib/update/constants.mjs +56 -0
  70. package/bin/lib/update/download.mjs +145 -0
  71. package/bin/lib/update/signature.mjs +42 -0
  72. package/bin/lib/update/state.mjs +205 -0
  73. package/bin/lib/update/versions.mjs +60 -0
  74. package/bin/lib/util.mjs +8 -0
  75. package/docs/CLI.md +1353 -1274
  76. package/package.json +71 -62
@@ -0,0 +1,457 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { execFileSync } from 'child_process';
5
+ import { fileURLToPath } from 'url';
6
+ import { REMOTE_CONFIG_DIR } from './deviceProfile.mjs';
7
+ import { DeviceAccess } from './constants.mjs';
8
+ import { loadDeviceCredentials } from './credentials.mjs';
9
+ import { RESTART_EXIT_CODE, UPDATE_PENDING_FILE, UPDATE_ROLLBACK_FILE } from '../selfUpdate.mjs';
10
+
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = path.dirname(__filename);
13
+ const CLI_PATH = path.resolve(__dirname, '..', '..', 'cli.mjs');
14
+
15
+ /**
16
+ * Quy ước mã thoát của `aivin remote start` (29/10/2026) cho trình giữ chạy (Task Scheduler + VBS trên Windows, launchd, systemd):
17
+ * 0 = dừng có chủ đích (thu hồi, bị cửa sổ khác thay, đã có tiến trình khác nhận việc, Ctrl+C) → KHÔNG chạy lại; khác 0 = sập / lỗi
18
+ * (mất mạng lúc ghép máy…) → chạy lại sau ít giây, giãn dần tới 5 phút.
19
+ */
20
+ export const WINDOWS_TASK_NAME = 'Aivin Remote';
21
+ export const WINDOWS_WATCHDOG_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote.vbs');
22
+ const WINDOWS_TASK_XML_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote-task.xml');
23
+ /** macOS / Linux: launchd / systemd chạy kịch bản này (một lần mỗi lần khởi động) thay vì chạy thẳng tệp chạy — để tự lùi bản ngoài tệp chạy. */
24
+ export const POSIX_RUN_SCRIPT_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote-run.sh');
25
+ const FAST_FAIL_FILE = path.join(REMOTE_CONFIG_DIR, 'update-fastfail.txt');
26
+ /** Tự lùi bản ở trình giữ chạy: bản chờ xác nhận thoát lỗi trong chừng này giây, liên tiếp chừng này lần → trả `.prev` về. */
27
+ export const SUPERVISOR_ROLLBACK = Object.freeze({ fastExitSec: 30, failures: 3 });
28
+
29
+ /**
30
+ * Thông tin để trình giữ chạy tự lùi bản — chỉ cho tệp chạy đóng gói (bản npm không có `.prev`). Tự lùi ở NGOÀI tệp chạy bắt được cả bản mới
31
+ * sập ngay lúc nạp mã (trước khi checkBootAfterUpdate trong tệp chạy kịp chạy).
32
+ */
33
+ function supervisorRollbackPaths(launch) {
34
+ return process.env.AIVIN_CLI_BINARY ? { exe: launch[0], pendingFile: UPDATE_PENDING_FILE, rollbackFile: UPDATE_ROLLBACK_FILE, fastFailFile: FAST_FAIL_FILE } : null;
35
+ }
36
+
37
+ /** Lệnh chạy CLI: tệp chạy đóng gói (bộ cài install.ps1 / install.sh) là chính nó; bản npm là `node cli.mjs`. */
38
+ export function cliLaunchCommand() {
39
+ return process.env.AIVIN_CLI_BINARY ? [process.execPath] : [process.execPath, CLI_PATH];
40
+ }
41
+
42
+ export const REMOTE_DAEMON_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-daemon.json');
43
+
44
+ /** Tệp tự khởi động chính: Windows = thư mục Startup (dự phòng khi không tạo được tác vụ), macOS = LaunchAgent, Linux = systemd user. */
45
+ export function getAutoStartFilePath() {
46
+ if (process.platform === 'win32') {
47
+ const startupDir = path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
48
+ return path.join(startupDir, 'aivin-remote.vbs');
49
+ }
50
+ if (process.platform === 'darwin') {
51
+ return path.join(os.homedir(), 'Library', 'LaunchAgents', 'com.aivin.remote.plist');
52
+ }
53
+ return path.join(os.homedir(), '.config', 'systemd', 'user', 'aivin-remote.service');
54
+ }
55
+
56
+ /** Mọi tệp tự khởi động cần dọn khi tắt. */
57
+ export function getAllAutoStartFilePaths() {
58
+ const paths = [getAutoStartFilePath()];
59
+ if (process.platform === 'win32') paths.push(WINDOWS_WATCHDOG_FILE, WINDOWS_TASK_XML_FILE);
60
+ else paths.push(POSIX_RUN_SCRIPT_FILE);
61
+ if (process.platform === 'linux') {
62
+ paths.push(path.join(os.homedir(), '.config', 'autostart', 'aivin-remote.desktop'));
63
+ }
64
+ return paths;
65
+ }
66
+
67
+ const xmlEscape = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
68
+
69
+ /**
70
+ * Kịch bản VBS giữ daemon chạy nền (cửa sổ ẩn): chạy, chờ thoát; mã 0 → thôi; khác 0 → chờ 10 s (giãn gấp đôi tới 5 phút, chạy ổn > 5 phút
71
+ * thì về lại 10 s) rồi chạy lại. Trước 29/10/2026 tệp Startup chỉ chạy một lần lúc đăng nhập — daemon sập là máy offline tới lần đăng nhập sau.
72
+ * Mã 75 (đã cài bản mới / đã tự lùi bản) → chạy lại sau 1 s, không giãn nhịp. Đặt AIVIN_SUPERVISOR cho tiến trình con: daemon biết có
73
+ * trình giữ chạy, tự thoát để chuyển bản được (xem detectSupervisor).
74
+ * `rollback` (tệp chạy đóng gói): bản còn chờ xác nhận (có update-pending.txt) thoát lỗi trong < 30 s, 3 lần liền, mà còn `.prev` → đổi bản
75
+ * hỏng sang `.trash`, trả `.prev` về, ghi phiên bản vào update-rollback.txt (bản cũ đọc ở lần chạy sau, đưa vào danh sách bỏ qua).
76
+ */
77
+ export function windowsWatchdogScript(argv, { rollback = null } = {}) {
78
+ const cmd = argv.map((part) => `""${part}""`).join(' ');
79
+ const vbsStr = (s) => `"${String(s).replace(/"/g, '""')}"`;
80
+ const { fastExitSec, failures } = SUPERVISOR_ROLLBACK;
81
+ return [
82
+ "' Aivin Device Agent - keeps `aivin remote start` running in the background.",
83
+ "' Exit code 0 = stopped on purpose (revoked, replaced, already running) -> stop; 75 = switch to the newly installed release -> restart now;",
84
+ "' anything else -> restart with backoff. A new release that keeps crashing right away is replaced by the previous one.",
85
+ 'Set sh = CreateObject("WScript.Shell")',
86
+ `sh.Environment("Process").Item("${SUPERVISOR_ENV}") = "${Supervisor.WSCRIPT}"`,
87
+ ...(rollback ? [
88
+ 'Set fso = CreateObject("Scripting.FileSystemObject")',
89
+ `exe = ${vbsStr(rollback.exe)}`,
90
+ `pending = ${vbsStr(rollback.pendingFile)}`,
91
+ `rollback = ${vbsStr(rollback.rollbackFile)}`,
92
+ 'fast = 0',
93
+ ] : []),
94
+ 'delay = 10',
95
+ 'Do',
96
+ ' started = Now',
97
+ ` rc = sh.Run("${cmd}", 0, True)`,
98
+ ' If rc = 0 Then Exit Do',
99
+ ...(rollback ? [
100
+ ` If rc <> ${RESTART_EXIT_CODE} And DateDiff("s", started, Now) < ${fastExitSec} And fso.FileExists(pending) And fso.FileExists(exe & ".prev") Then`,
101
+ ' fast = fast + 1',
102
+ ' Else',
103
+ ' fast = 0',
104
+ ' End If',
105
+ ` If fast >= ${failures} Then`,
106
+ ' fast = 0',
107
+ ' On Error Resume Next',
108
+ ' Set t = fso.OpenTextFile(pending, 1)',
109
+ ' ver = t.ReadLine',
110
+ ' t.Close',
111
+ ' fso.MoveFile exe, exe & "-" & CLng(Timer * 100) & ".trash"',
112
+ ' If Err.Number = 0 Then fso.MoveFile exe & ".prev", exe',
113
+ ' If Err.Number = 0 Then',
114
+ ' Set t = fso.CreateTextFile(rollback, True)',
115
+ ' t.WriteLine ver',
116
+ ' t.Close',
117
+ ' fso.DeleteFile pending, True',
118
+ ' End If',
119
+ ' Err.Clear',
120
+ ' On Error GoTo 0',
121
+ ` rc = ${RESTART_EXIT_CODE}`,
122
+ ' End If',
123
+ ] : []),
124
+ ` If rc = ${RESTART_EXIT_CODE} Then`,
125
+ ' WScript.Sleep 1000',
126
+ ' Else',
127
+ ' If DateDiff("s", started, Now) > 300 Then delay = 10',
128
+ ' WScript.Sleep delay * 1000',
129
+ ' delay = delay * 2',
130
+ ' If delay > 300 Then delay = 300',
131
+ ' End If',
132
+ 'Loop',
133
+ ].join('\r\n') + '\r\n';
134
+ }
135
+
136
+ /**
137
+ * macOS / Linux: kịch bản sh launchd / systemd chạy mỗi lần khởi động (chúng tự chạy lại khi mã thoát khác 0). Đặt AIVIN_SUPERVISOR, chạy
138
+ * daemon một lần, rồi — với tệp chạy đóng gói — tự lùi bản như VBS (đếm lần sập nhanh liên tiếp trong tệp, vì mỗi lần là một tiến trình mới).
139
+ */
140
+ export function posixRunScript(argv, { supervisor, rollback = null }) {
141
+ const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
142
+ const { fastExitSec, failures } = SUPERVISOR_ROLLBACK;
143
+ return [
144
+ '#!/bin/sh',
145
+ '# Aivin Device Agent - runs `aivin remote start` once; launchd / systemd restart it on a non-zero exit (75 = switch release).',
146
+ '# A new release that crashes right away, several times in a row, while still unconfirmed is replaced by the previous one.',
147
+ `${SUPERVISOR_ENV}=${q(supervisor)}`,
148
+ `export ${SUPERVISOR_ENV}`,
149
+ ...(rollback ? [
150
+ `BIN=${q(rollback.exe)}`,
151
+ `PENDING=${q(rollback.pendingFile)}`,
152
+ `ROLLBACK=${q(rollback.rollbackFile)}`,
153
+ `FAST=${q(rollback.fastFailFile)}`,
154
+ 'started=$(date +%s)',
155
+ ] : []),
156
+ argv.map(q).join(' '),
157
+ 'rc=$?',
158
+ ...(rollback ? [
159
+ 'elapsed=$(( $(date +%s) - started ))',
160
+ `if [ "$rc" -ne 0 ] && [ "$rc" -ne ${RESTART_EXIT_CODE} ] && [ "$elapsed" -lt ${fastExitSec} ] && [ -f "$PENDING" ] && [ -f "$BIN.prev" ]; then`,
161
+ ' n=$(( $(cat "$FAST" 2>/dev/null || echo 0) + 1 ))',
162
+ ` if [ "$n" -ge ${failures} ]; then`,
163
+ ' if mv -f "$BIN.prev" "$BIN"; then head -n 1 "$PENDING" > "$ROLLBACK"; rm -f "$PENDING"; fi',
164
+ ' rm -f "$FAST"',
165
+ ` exit ${RESTART_EXIT_CODE}`,
166
+ ' fi',
167
+ ' echo "$n" > "$FAST"',
168
+ 'else',
169
+ ' rm -f "$FAST"',
170
+ 'fi',
171
+ ] : []),
172
+ 'exit "$rc"',
173
+ ].join('\n') + '\n';
174
+ }
175
+
176
+ function writePosixRunScript(argv, supervisor, launch) {
177
+ fs.mkdirSync(path.dirname(POSIX_RUN_SCRIPT_FILE), { recursive: true });
178
+ fs.writeFileSync(POSIX_RUN_SCRIPT_FILE, posixRunScript(argv, { supervisor, rollback: supervisorRollbackPaths(launch) }), { mode: 0o755 });
179
+ fs.chmodSync(POSIX_RUN_SCRIPT_FILE, 0o755);
180
+ return ['/bin/sh', POSIX_RUN_SCRIPT_FILE];
181
+ }
182
+
183
+ /** Biến môi trường trình giữ chạy của Aivin đặt cho daemon. */
184
+ export const SUPERVISOR_ENV = 'AIVIN_SUPERVISOR';
185
+ export const Supervisor = Object.freeze({ WSCRIPT: 'wscript', LAUNCHD: 'launchd', SYSTEMD: 'systemd' });
186
+
187
+ function parentCommandLine() {
188
+ try {
189
+ return execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(process.ppid)}").CommandLine`], {
190
+ encoding: 'utf8', timeout: 8000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'],
191
+ }).trim();
192
+ } catch {
193
+ return '';
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Daemon có đang chạy dưới trình giữ chạy của Aivin không (thoát mã 75 thì được mở lại). Dấu AIVIN_SUPERVISOR (tệp tự khởi động từ bản có
199
+ * tự cập nhật); tệp tự khởi động cũ không có dấu → launchd: nhãn `com.aivin.remote`; Windows: tiến trình cha là wscript chạy đúng
200
+ * aivin-remote.vbs. systemd cũ không nhận ra được → coi như không có (chỉ nhắc, không tự thoát) — an toàn hơn đoán sai rồi mất máy.
201
+ * Trước đây `--quiet` bị coi là có trình giữ chạy: ai tự chạy `--quiet` trong terminal / script riêng thì daemon tự thoát rồi máy offline.
202
+ */
203
+ export function detectSupervisor({ env = process.env, platform = process.platform, quiet = false, readParent = parentCommandLine } = {}) {
204
+ const marked = String(env[SUPERVISOR_ENV] || '');
205
+ if (Object.values(Supervisor).includes(marked)) return marked;
206
+ if (!quiet) return null;
207
+ if (platform === 'darwin' && env.XPC_SERVICE_NAME === 'com.aivin.remote') return Supervisor.LAUNCHD;
208
+ if (platform === 'win32' && /\bwscript(\.exe)?\b.*aivin-remote\.vbs/i.test(readParent())) return Supervisor.WSCRIPT;
209
+ return null;
210
+ }
211
+
212
+ /**
213
+ * Tác vụ Task Scheduler của người dùng hiện tại (không cần quyền quản trị): chạy lúc đăng nhập, phiên tương tác (điều khiển giao diện /
214
+ * Office cần màn hình của người dùng), không dừng khi chạy pin, không giới hạn thời gian, không chạy chồng.
215
+ */
216
+ export function windowsTaskXml({ userId, watchdogFile }) {
217
+ return `<?xml version="1.0" encoding="UTF-16"?>
218
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
219
+ <RegistrationInfo>
220
+ <Description>Aivin Device Agent - lets your Aivin agents work on this computer (aivin remote start)</Description>
221
+ </RegistrationInfo>
222
+ <Triggers>
223
+ <LogonTrigger>
224
+ <Enabled>true</Enabled>
225
+ <UserId>${xmlEscape(userId)}</UserId>
226
+ </LogonTrigger>
227
+ </Triggers>
228
+ <Principals>
229
+ <Principal id="Author">
230
+ <UserId>${xmlEscape(userId)}</UserId>
231
+ <LogonType>InteractiveToken</LogonType>
232
+ <RunLevel>LeastPrivilege</RunLevel>
233
+ </Principal>
234
+ </Principals>
235
+ <Settings>
236
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
237
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
238
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
239
+ <AllowHardTerminate>true</AllowHardTerminate>
240
+ <StartWhenAvailable>true</StartWhenAvailable>
241
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
242
+ <IdleSettings>
243
+ <StopOnIdleEnd>false</StopOnIdleEnd>
244
+ <RestartOnIdle>false</RestartOnIdle>
245
+ </IdleSettings>
246
+ <AllowStartOnDemand>true</AllowStartOnDemand>
247
+ <Enabled>true</Enabled>
248
+ <Hidden>false</Hidden>
249
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
250
+ <Priority>7</Priority>
251
+ <RestartOnFailure>
252
+ <Interval>PT1M</Interval>
253
+ <Count>999</Count>
254
+ </RestartOnFailure>
255
+ </Settings>
256
+ <Actions Context="Author">
257
+ <Exec>
258
+ <Command>wscript.exe</Command>
259
+ <Arguments>//B //Nologo "${xmlEscape(watchdogFile)}"</Arguments>
260
+ </Exec>
261
+ </Actions>
262
+ </Task>
263
+ `;
264
+ }
265
+
266
+ /** UTF-16 LE có BOM: wscript đọc đúng đường dẫn có dấu (tên người dùng tiếng Việt…), schtasks /XML nhận đúng khai báo encoding. */
267
+ function writeUtf16(file, text) {
268
+ fs.mkdirSync(path.dirname(file), { recursive: true });
269
+ fs.writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, 'utf16le')]));
270
+ }
271
+
272
+ function windowsUserId() {
273
+ const user = process.env.USERNAME || os.userInfo().username;
274
+ return process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${user}` : user;
275
+ }
276
+
277
+ function schtasks(args) {
278
+ return execFileSync('schtasks', args, { encoding: 'utf8', timeout: 15_000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
279
+ }
280
+
281
+ function windowsTaskExists() {
282
+ try {
283
+ schtasks(['/Query', '/TN', WINDOWS_TASK_NAME]);
284
+ return true;
285
+ } catch {
286
+ return false;
287
+ }
288
+ }
289
+
290
+ /** Windows: tác vụ Task Scheduler chạy kịch bản giữ chạy; máy chặn tạo tác vụ (chính sách công ty) → chép kịch bản vào thư mục Startup. */
291
+ function enableWindows(argv, launch) {
292
+ const script = windowsWatchdogScript(argv, { rollback: supervisorRollbackPaths(launch) });
293
+ writeUtf16(WINDOWS_WATCHDOG_FILE, script);
294
+ const startupFile = getAutoStartFilePath();
295
+ try {
296
+ writeUtf16(WINDOWS_TASK_XML_FILE, windowsTaskXml({ userId: windowsUserId(), watchdogFile: WINDOWS_WATCHDOG_FILE }));
297
+ schtasks(['/Create', '/TN', WINDOWS_TASK_NAME, '/XML', WINDOWS_TASK_XML_FILE, '/F']);
298
+ fs.rmSync(startupFile, { force: true });
299
+ return { filePath: `Task Scheduler: ${WINDOWS_TASK_NAME}`, method: 'task' };
300
+ } catch (e) {
301
+ writeUtf16(startupFile, script);
302
+ return { filePath: startupFile, method: 'startup', warning: `Không tạo được tác vụ Task Scheduler (${String(e?.stderr || e?.message || e).trim()}) — dùng thư mục Startup` };
303
+ } finally {
304
+ fs.rmSync(WINDOWS_TASK_XML_FILE, { force: true });
305
+ }
306
+ }
307
+
308
+ /** Kích hoạt tự khởi động cùng máy tính trên mọi hệ điều hành (Windows, macOS, Linux). */
309
+ export function enableAutoStart(options = {}) {
310
+ const rootDir = path.resolve(options.dir || process.cwd());
311
+ // Máy đang TOÀN QUYỀN và không nêu --dir: khởi động không kèm --dir để giữ chế độ đã lưu (kèm --dir là về chế độ một thư mục).
312
+ const keepFullAccess = !options.dir && loadDeviceCredentials()?.access === DeviceAccess.FULL;
313
+ const scopeArgs = [...(keepFullAccess ? [] : ['--dir', rootDir]), ...(options.proxy ? ['--proxy', String(options.proxy)] : [])];
314
+ const launch = cliLaunchCommand();
315
+ const argv = [...launch, 'remote', 'start', '--quiet', ...scopeArgs];
316
+ const nodeExec = launch[0];
317
+ const logOut = path.join(REMOTE_CONFIG_DIR, 'remote-service.log');
318
+ let filePath = getAutoStartFilePath();
319
+ let extra = {};
320
+
321
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
322
+
323
+ if (process.platform === 'win32') {
324
+ extra = enableWindows(argv, launch);
325
+ filePath = extra.filePath;
326
+ } else if (process.platform === 'darwin') {
327
+ // macOS: LaunchAgent chạy kịch bản sh (tự lùi bản ngoài tệp chạy), chỉ chạy lại khi thoát bất thường (mã khác 0).
328
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
329
+ const runArgv = writePosixRunScript(argv, Supervisor.LAUNCHD, launch);
330
+ const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
331
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
332
+ <plist version="1.0">
333
+ <dict>
334
+ <key>Label</key>
335
+ <string>com.aivin.remote</string>
336
+ <key>ProgramArguments</key>
337
+ <array>
338
+ ${runArgv.map((part) => ` <string>${xmlEscape(part)}</string>`).join('\n')}
339
+ </array>
340
+ <key>RunAtLoad</key>
341
+ <true/>
342
+ <key>KeepAlive</key>
343
+ <dict>
344
+ <key>SuccessfulExit</key>
345
+ <false/>
346
+ </dict>
347
+ <key>ThrottleInterval</key>
348
+ <integer>10</integer>
349
+ <key>EnvironmentVariables</key>
350
+ <dict>
351
+ <key>${SUPERVISOR_ENV}</key>
352
+ <string>${Supervisor.LAUNCHD}</string>
353
+ </dict>
354
+ <key>StandardOutPath</key>
355
+ <string>${xmlEscape(logOut)}</string>
356
+ <key>StandardErrorPath</key>
357
+ <string>${xmlEscape(logOut)}</string>
358
+ </dict>
359
+ </plist>
360
+ `;
361
+ fs.writeFileSync(filePath, plistContent, 'utf8');
362
+ } else {
363
+ // Linux: dịch vụ người dùng systemd chạy kịch bản sh (chạy lại khi thoát bất thường, tự lùi bản) + tệp XDG autostart cho máy không bật
364
+ // systemd user session (chạy thẳng, không có trình giữ chạy → không tự chuyển bản).
365
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
366
+ const execLine = argv.map((part) => `"${part}"`).join(' ');
367
+ const runLine = writePosixRunScript(argv, Supervisor.SYSTEMD, launch).map((part) => `"${part}"`).join(' ');
368
+ const serviceContent = `[Unit]
369
+ Description=AIVIN Remote Control Daemon
370
+ After=network.target
371
+
372
+ [Service]
373
+ Type=simple
374
+ ExecStart=${runLine}
375
+ Restart=on-failure
376
+ RestartSec=10
377
+ Environment=${SUPERVISOR_ENV}=${Supervisor.SYSTEMD}
378
+ WorkingDirectory=${rootDir}
379
+ StandardOutput=append:${logOut}
380
+ StandardError=append:${logOut}
381
+
382
+ [Install]
383
+ WantedBy=default.target
384
+ `;
385
+ fs.writeFileSync(filePath, serviceContent, 'utf8');
386
+
387
+ const desktopPath = path.join(os.homedir(), '.config', 'autostart', 'aivin-remote.desktop');
388
+ fs.mkdirSync(path.dirname(desktopPath), { recursive: true });
389
+ const desktopContent = `[Desktop Entry]
390
+ Type=Application
391
+ Name=AIVIN Remote Control
392
+ Exec=${execLine}
393
+ Hidden=false
394
+ NoDisplay=false
395
+ X-GNOME-Autostart-enabled=true
396
+ `;
397
+ fs.writeFileSync(desktopPath, desktopContent, 'utf8');
398
+ }
399
+
400
+ const daemonConfig = {
401
+ enabled: true,
402
+ platform: process.platform,
403
+ rootDir,
404
+ autoStartFile: filePath,
405
+ ...(extra.method ? { method: extra.method } : {}),
406
+ nodeExec,
407
+ updatedAt: new Date().toISOString(),
408
+ };
409
+ fs.writeFileSync(REMOTE_DAEMON_FILE, JSON.stringify(daemonConfig, null, 2) + '\n', 'utf8');
410
+
411
+ return { success: true, filePath, rootDir, platform: process.platform, ...(extra.warning ? { warning: extra.warning } : {}) };
412
+ }
413
+
414
+ /** Huỷ tự khởi động (tiến trình đang chạy vẫn chạy tới khi tắt). */
415
+ export function disableAutoStart() {
416
+ if (process.platform === 'win32') {
417
+ try { schtasks(['/Delete', '/TN', WINDOWS_TASK_NAME, '/F']); } catch { /* chưa có tác vụ */ }
418
+ }
419
+ for (const filePath of getAllAutoStartFilePaths()) {
420
+ try { fs.rmSync(filePath, { force: true }); } catch { /* tệp đang bị khoá */ }
421
+ }
422
+
423
+ if (fs.existsSync(REMOTE_DAEMON_FILE)) {
424
+ try {
425
+ const current = JSON.parse(fs.readFileSync(REMOTE_DAEMON_FILE, 'utf8'));
426
+ current.enabled = false;
427
+ current.updatedAt = new Date().toISOString();
428
+ fs.writeFileSync(REMOTE_DAEMON_FILE, JSON.stringify(current, null, 2) + '\n', 'utf8');
429
+ } catch {
430
+ // Bỏ qua lỗi đọc ghi cấu hình
431
+ }
432
+ }
433
+
434
+ return { success: true };
435
+ }
436
+
437
+ /** Trạng thái tự khởi động của máy. */
438
+ export function getAutoStartStatus() {
439
+ const startupFile = getAutoStartFilePath();
440
+ let daemonConfig = null;
441
+ if (fs.existsSync(REMOTE_DAEMON_FILE)) {
442
+ try {
443
+ daemonConfig = JSON.parse(fs.readFileSync(REMOTE_DAEMON_FILE, 'utf8'));
444
+ } catch {
445
+ daemonConfig = null;
446
+ }
447
+ }
448
+ const task = process.platform === 'win32' && daemonConfig?.method === 'task' && windowsTaskExists();
449
+ const installed = task || fs.existsSync(startupFile);
450
+
451
+ return {
452
+ enabled: Boolean(installed && daemonConfig?.enabled !== false),
453
+ filePath: task ? `Task Scheduler: ${WINDOWS_TASK_NAME}` : startupFile,
454
+ rootDir: daemonConfig?.rootDir || process.cwd(),
455
+ updatedAt: daemonConfig?.updatedAt || null,
456
+ };
457
+ }
@@ -0,0 +1,129 @@
1
+ import {
2
+ UpdateStatus, compareVersions, currentCliVersion, installUpdate, installedNewerThanRunning, loadUpdateSettings, parseVersion, recordCheck, tagOf,
3
+ versionList,
4
+ } from '../selfUpdate.mjs';
5
+
6
+ const HOUR = 3_600_000;
7
+ const MINUTE = 60_000;
8
+
9
+ /**
10
+ * Tự cập nhật trong `aivin remote start` (29/10/2026). Mỗi ~6 giờ (lần đầu sau 2–5 phút, rải ngẫu nhiên để các máy không cùng dội trang tải
11
+ * sau một lần phát hành) kiểm bản mới; có (và máy thuộc đợt phát hành, xem rollout.json) thì tải + kiểm chữ ký + thay tệp chạy ngay (tiến
12
+ * trình đang chạy không bị ảnh hưởng). Rồi:
13
+ * - chạy dưới trình giữ chạy thật (`supervised`, xem detectSupervisor ở autoStart.mjs): chờ máy yên `idleGraceMs` tính từ lần hoạt động cuối
14
+ * (`lastActivityAt` — lời gọi bắt đầu / kết thúc — hoặc lần cuối thấy còn tiến trình nền / đường hầm trình duyệt) → `onRestart` dừng gọn +
15
+ * thoát mã 75, trình giữ chạy mở lại bằng bản mới. 10 phút: khoảng nghỉ giữa các bước của một nhiệm vụ (lượt Planner, chờ người duyệt trên
16
+ * web) không bị coi là rảnh;
17
+ * - không có trình giữ chạy (cửa sổ chạy tay, script riêng): báo một lần "đóng, chạy lại" — không tự thoát.
18
+ * `setServerHints` (BE báo trong ack của HELLO — chỉ là gợi ý, không chọn được nguồn / tệp):
19
+ * - `min_version`: bản đang chạy cũ hơn → kiểm trong vài phút (rải ngẫu nhiên: BE khởi động lại thì mọi máy cùng nối lại), bỏ qua đợt;
20
+ * - `latest_version`: bản mới nhất BE biết (đặt lúc phát hành) — trang tải báo thấp hơn = trang tải bị chặn / tráo / cache cũ ("đóng băng"
21
+ * máy ở bản có lỗ hổng) → cảnh báo một lần + báo lại trong hồ sơ máy;
22
+ * - `hold_versions`: bản đang bị hoãn (nhiều máy tự lùi khỏi) → không cài, đã tải rồi thì không chuyển sang.
23
+ * Tắt: `aivin update --auto off`, `--no-auto-update`, hoặc AIVIN_AUTO_UPDATE=0 — khi tắt chỉ nhắc, không tải gì.
24
+ */
25
+ export function createAutoUpdater({
26
+ enabled = true, supervised = false, isIdle = () => true, lastActivityAt = () => 0, onRestart = () => {}, say = () => {}, deviceId,
27
+ checkEveryMs = 6 * HOUR, firstCheckMs = 2 * MINUTE + Math.floor(Math.random() * 3 * MINUTE), tickMs = 30_000, idleGraceMs = 10 * MINUTE,
28
+ retryMs = HOUR, urgentGapMs = 10 * MINUTE, urgentJitterMs = 5 * MINUTE,
29
+ install = installUpdate, settings = loadUpdateSettings, installedNewer = installedNewerThanRunning, record = recordCheck, current = currentCliVersion(),
30
+ now = Date.now, random = Math.random,
31
+ } = {}) {
32
+ let nextCheckAt = now() + firstCheckMs;
33
+ let checking = null;
34
+ let ready = null;
35
+ let lastBusyAt = now();
36
+ let restarting = false;
37
+ let minVersion = null;
38
+ let serverLatest = null;
39
+ let holdVersions = [];
40
+ let urgent = false;
41
+ let lastUrgentAt = -Infinity;
42
+ const notices = new Set();
43
+ const noticeOnce = (key, text) => {
44
+ if (notices.has(key)) return;
45
+ notices.add(key);
46
+ say(text);
47
+ };
48
+ const jitter = (ms) => Math.round(ms * (0.8 + random() * 0.4));
49
+ const restartHint = 'đóng cửa sổ này và chạy lại `aivin remote start` để dùng bản mới';
50
+
51
+ const noteSiteBehind = (siteLatest) => {
52
+ const behind = !!serverLatest && compareVersions(siteLatest, serverLatest) < 0;
53
+ if (behind) {
54
+ noticeOnce(`behind:${siteLatest}:${serverLatest}`, `⚠️ Trang tải báo bản mới nhất là ${siteLatest} nhưng máy chủ Aivin biết đã có ${serverLatest} — trang tải có thể đang bị chặn hoặc lỗi; máy này có thể đang kẹt ở bản cũ.`);
55
+ }
56
+ return behind;
57
+ };
58
+
59
+ const check = async () => {
60
+ if (!settings().auto) {
61
+ nextCheckAt = now() + checkEveryMs;
62
+ if (minVersion) noticeOnce(`min-off:${minVersion}`, `⚠️ Máy chủ cần aivin ${tagOf(minVersion)} trở lên (máy này ${tagOf(current)}), tự cập nhật đang tắt — chạy \`aivin update\`.`);
63
+ return;
64
+ }
65
+ try {
66
+ const res = await install({ deviceId, urgent: urgent && !!minVersion && compareVersions(current, minVersion) < 0, holdVersions });
67
+ nextCheckAt = now() + jitter(checkEveryMs);
68
+ record({ siteLatest: res.latest, siteBehind: noteSiteBehind(res.latest) });
69
+ if (res.status === UpdateStatus.INSTALLED) {
70
+ ready = res.latest;
71
+ notices.add(`ready:${ready}`);
72
+ say(`⬆ Đã tải aivin ${res.latest} (đang chạy ${res.current}) — ${supervised ? 'chuyển sang bản mới khi máy rảnh' : restartHint}.`);
73
+ } else if (res.status === UpdateStatus.NOT_BINARY) {
74
+ noticeOnce(`npm:${res.latest}`, `⬆ Có aivin ${res.latest} (máy này ${res.current}) — cập nhật: npm i -g @aivin-labs/cli@latest`);
75
+ } else if (res.status === UpdateStatus.SKIPPED) {
76
+ noticeOnce(`skip:${res.latest}`, ` (bỏ qua aivin ${res.latest}: máy này đã tự lùi khỏi bản đó vì khởi động hỏng — cài lại: aivin update --to ${res.latest})`);
77
+ } else if (res.status === UpdateStatus.HELD) {
78
+ noticeOnce(`held:${res.latest}`, ` (aivin ${res.latest} đang được máy chủ tạm hoãn — giữ bản ${res.current})`);
79
+ }
80
+ } catch (e) {
81
+ nextCheckAt = now() + retryMs;
82
+ record({ error: e?.message || String(e) });
83
+ noticeOnce(`err:${e?.message}`, ` (chưa cập nhật được: ${e?.message || e} — thử lại sau)`);
84
+ }
85
+ };
86
+
87
+ const tick = async () => {
88
+ if (!enabled || restarting) return;
89
+ if (!isIdle()) lastBusyAt = now();
90
+ ready = ready || installedNewer();
91
+ if (ready) {
92
+ if (holdVersions.includes(tagOf(ready))) return;
93
+ if (!supervised) return noticeOnce(`ready:${ready}`, `⬆ Đã cài aivin ${ready} — ${restartHint}.`);
94
+ if (!isIdle() || now() - Math.max(lastBusyAt, Number(lastActivityAt()) || 0) < idleGraceMs) return;
95
+ restarting = true;
96
+ return onRestart(ready);
97
+ }
98
+ if (checking || now() < nextCheckAt) return;
99
+ checking = check().finally(() => { checking = null; });
100
+ await checking;
101
+ };
102
+
103
+ const timer = enabled ? setInterval(() => { void tick(); }, tickMs) : null;
104
+ timer?.unref?.();
105
+
106
+ /** BE yêu cầu bản tối thiểu: máy cũ hơn → kiểm trong `urgentJitterMs` (tối đa một lần / `urgentGapMs`), bỏ qua đợt phát hành. */
107
+ const setMinVersion = (version) => {
108
+ if (!enabled || !parseVersion(version) || compareVersions(current, version) >= 0) return;
109
+ minVersion = version;
110
+ urgent = true;
111
+ if (now() - lastUrgentAt < urgentGapMs) return;
112
+ lastUrgentAt = now();
113
+ nextCheckAt = Math.min(nextCheckAt, now() + Math.floor(random() * urgentJitterMs));
114
+ };
115
+
116
+ return {
117
+ tick,
118
+ setMinVersion,
119
+ /** Gợi ý từ ack của `device:hello` (`hello.cli`) — xem đầu tệp. */
120
+ setServerHints(hints) {
121
+ if (!hints || typeof hints !== 'object') return;
122
+ holdVersions = versionList(hints.hold_versions);
123
+ serverLatest = parseVersion(hints.latest_version) ? tagOf(hints.latest_version) : null;
124
+ if (typeof hints.min_version === 'string') setMinVersion(hints.min_version);
125
+ },
126
+ close() { if (timer) clearInterval(timer); },
127
+ state: () => ({ ready, nextCheckAt, minVersion, serverLatest, holdVersions, checking: !!checking }),
128
+ };
129
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Nhận diện Aivin cho giao diện hiện trên máy người dùng (hộp xác nhận tại máy). Biểu tượng 64×64 lấy từ FE `public/images/favicon.png` —
3
+ * nhúng sẵn để tệp chạy đóng gói (bun) không phải mang tệp ảnh rời.
4
+ */
5
+ export const AIVIN_LOGO_PNG_BASE64 = [
6
+ 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAGYktHRAD/AP8A/6C9p5MAAAAHdElNRQfq',
7
+ 'BgQFHRcBXduDAAATqklEQVR42u2ae5RlVX3nP7+9z7n31n1UVVe/aegGaaCBbmx5NQIGUDSDUSHjyDKJMYhLCbIiyax5rOWwxIlvM5OYiRONZCSoicNDTCSzEIIKEUgjL3k0DU3T76ar',
8
+ 'q+tddZ9n7/2bP845dW83rTSP2M6a/q2169x7zql7zvf7e+zf77c3HJEjckSOyBH5/1fkcL/Ae+7czMXtIt/p7yBBiJIO6nx6USFEMW1ToNQcRm2ZB95z2v+7BFx898OMDZ3JUGuEHYUq',
9
+ 's0DbWBohohVsivl24e7j/1hGKXBie4SzzvvvyjQUWkpRW5RVKWrgmMYORkqLWbntp9z58Xf+6hJw3gO7eLq4iKPdDKO2xIwUaFQiTp2uVyeFoxJjV6iX5W1kiXrmi2cwJB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fK0BsPY/e8/3Dh/rrzinaLL/+3tFHHsSBYzr1QfnO1U',
54
+ 'z00SdyaEheJ0NELX99nO/S1XrPsQsaCwhR13fvhw43z9CAA47j23sbVyPAuSYepugGZSgoklUNhJX2GGPutwxFTcC+z5p48eboyvPwFzRLzzr7HSShc0bYLKLGBo+6PYdecVhxvbETki',
55
+ 'R+SIvKz8X/r/s8+w+AmkAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDI2LTA2LTA0VDA1OjI5OjE1KzAwOjAwEER1xwAAACV0RVh0ZGF0ZTptb2RpZnkAMjAyNi0wNi0wNFQwNToyOToxNSsw',
56
+ 'MDowMGEZzXsAAAAodEVYdGRhdGU6dGltZXN0YW1wADIwMjYtMDYtMDRUMDU6Mjk6MjMrMDA6MDDbU959AAAAAElFTkSuQmCC',
57
+ ].join('');
58
+
59
+ /** Màu lấy mẫu từ biểu tượng: `brand` (xanh chủ đạo, dùng cho nút chính — màu phẳng, không gradient), dải xanh đậm → xanh lơ của logo. */
60
+ export const AIVIN_BRAND = Object.freeze({ brand: '#0060E0', deep: '#0057E6', light: '#00B4F0', ink: '#1D2129', muted: '#86909C', body: '#4E5969', warn: '#D25F00', warnBg: '#FFF3E8' });