@aivin-labs/cli 1.0.5 → 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 (67) hide show
  1. package/README.md +263 -216
  2. package/bin/cli.mjs +1780 -1366
  3. package/bin/lib/browserAutomation.mjs +655 -648
  4. package/bin/lib/browserTui.mjs +276 -251
  5. package/bin/lib/cancellation.mjs +61 -0
  6. package/bin/lib/mcpProxy.mjs +869 -837
  7. package/bin/lib/missionStream.mjs +696 -691
  8. package/bin/lib/releaseKeys.mjs +9 -0
  9. package/bin/lib/remote/activityLog.mjs +68 -0
  10. package/bin/lib/remote/autoStart.mjs +457 -0
  11. package/bin/lib/remote/autoUpdate.mjs +129 -0
  12. package/bin/lib/remote/brand.mjs +60 -0
  13. package/bin/lib/remote/browserTunnel.mjs +292 -0
  14. package/bin/lib/remote/callLedger.mjs +134 -0
  15. package/bin/lib/remote/cdpPolicy.mjs +66 -0
  16. package/bin/lib/remote/client.mjs +726 -0
  17. package/bin/lib/remote/constants.mjs +173 -0
  18. package/bin/lib/remote/credentials.mjs +208 -0
  19. package/bin/lib/remote/daemonLock.mjs +86 -0
  20. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  21. package/bin/lib/remote/deviceMemory.mjs +246 -0
  22. package/bin/lib/remote/deviceProfile.mjs +142 -0
  23. package/bin/lib/remote/deviceWatches.mjs +138 -0
  24. package/bin/lib/remote/docText.mjs +117 -0
  25. package/bin/lib/remote/fileIndexer.mjs +399 -0
  26. package/bin/lib/remote/gui/index.mjs +245 -0
  27. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  28. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  29. package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
  30. package/bin/lib/remote/httpTransfer.mjs +89 -0
  31. package/bin/lib/remote/idempotency.mjs +135 -0
  32. package/bin/lib/remote/keepAwake.mjs +100 -0
  33. package/bin/lib/remote/localConfirm.mjs +268 -0
  34. package/bin/lib/remote/localPolicy.mjs +249 -0
  35. package/bin/lib/remote/mascot/assets.mjs +218 -0
  36. package/bin/lib/remote/mascot/hostSource.mjs +362 -0
  37. package/bin/lib/remote/mascot/index.mjs +322 -0
  38. package/bin/lib/remote/mascot/labels.mjs +83 -0
  39. package/bin/lib/remote/mascot/strings.mjs +189 -0
  40. package/bin/lib/remote/memberFsPool.mjs +134 -0
  41. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  42. package/bin/lib/remote/mission.mjs +156 -0
  43. package/bin/lib/remote/missionQuestion.mjs +63 -0
  44. package/bin/lib/remote/multiUser.mjs +344 -0
  45. package/bin/lib/remote/netProxy.mjs +145 -0
  46. package/bin/lib/remote/notify.mjs +58 -0
  47. package/bin/lib/remote/office/index.mjs +90 -0
  48. package/bin/lib/remote/policyCommand.mjs +93 -0
  49. package/bin/lib/remote/processes.mjs +217 -0
  50. package/bin/lib/remote/sandbox.mjs +221 -0
  51. package/bin/lib/remote/schedule.mjs +213 -0
  52. package/bin/lib/remote/scheduler.mjs +124 -0
  53. package/bin/lib/remote/textIndex.mjs +131 -0
  54. package/bin/lib/remote/tokenStore.mjs +77 -0
  55. package/bin/lib/remote/toolHandlers.mjs +726 -0
  56. package/bin/lib/remote/undoStore.mjs +242 -0
  57. package/bin/lib/remoteControl.mjs +26 -0
  58. package/bin/lib/scaffold.mjs +654 -653
  59. package/bin/lib/selfUpdate.mjs +71 -0
  60. package/bin/lib/update/binarySwap.mjs +63 -0
  61. package/bin/lib/update/constants.mjs +56 -0
  62. package/bin/lib/update/download.mjs +145 -0
  63. package/bin/lib/update/signature.mjs +42 -0
  64. package/bin/lib/update/state.mjs +205 -0
  65. package/bin/lib/update/versions.mjs +60 -0
  66. package/docs/CLI.md +1353 -1299
  67. package/package.json +71 -62
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Khoá công khai ký bản phát hành CLI (Ed25519, 29/10/2026). Tự cập nhật chỉ cài bản có `SHA256SUMS.sig` ký bằng một khoá trong danh sách
3
+ * này — chiếm được trang tải (get.aivin.vn) cũng không đẩy được tệp chạy lạ xuống máy đã cài. Khoá bí mật KHÔNG nằm trên trang tải / CI
4
+ * (scripts/release-key.mjs tạo, scripts/sign-release.mjs ký). Đổi khoá: thêm khoá mới ở đây, phát hành một bản ký bằng khoá cũ, rồi mới ký
5
+ * bằng khoá mới; gỡ khoá cũ ở bản sau đó.
6
+ */
7
+ export const RELEASE_PUBLIC_KEYS = Object.freeze([
8
+ { id: '05b62965e1847716', key: 'QlThaBcc4Yl+ctV2MD+VuOOa0lu3yBxhiexprDarWHM=' },
9
+ ]);
@@ -0,0 +1,68 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { REMOTE_CONFIG_DIR } from './deviceProfile.mjs';
4
+
5
+ export const REMOTE_ACTIVITY_LOG_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-activity.log');
6
+ const MAX_LOG_LINES = 500;
7
+
8
+ /**
9
+ * Ghi lại một hoạt động điều khiển từ xa vào nhật ký máy tính.
10
+ */
11
+ export function logActivity(entry) {
12
+ try {
13
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
14
+ const line = JSON.stringify({
15
+ timestamp: new Date().toISOString(),
16
+ ...entry,
17
+ }) + '\n';
18
+
19
+ fs.appendFileSync(REMOTE_ACTIVITY_LOG_FILE, line, 'utf8');
20
+
21
+ // Cắt tỉa nếu tập tin nhật ký vượt quá giới hạn
22
+ const content = fs.readFileSync(REMOTE_ACTIVITY_LOG_FILE, 'utf8');
23
+ const lines = content.trim().split('\n').filter(Boolean);
24
+ if (lines.length > MAX_LOG_LINES) {
25
+ const trimmed = lines.slice(-MAX_LOG_LINES).join('\n') + '\n';
26
+ fs.writeFileSync(REMOTE_ACTIVITY_LOG_FILE, trimmed, 'utf8');
27
+ }
28
+ } catch {
29
+ // Tránh để lỗi ghi nhật ký làm gián đoạn luồng chính
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Lấy danh sách các hoạt động gần đây nhất.
35
+ */
36
+ export function getRecentLogs(limit = 50) {
37
+ try {
38
+ if (!fs.existsSync(REMOTE_ACTIVITY_LOG_FILE)) return [];
39
+ const content = fs.readFileSync(REMOTE_ACTIVITY_LOG_FILE, 'utf8');
40
+ const lines = content.trim().split('\n').filter(Boolean);
41
+ return lines
42
+ .slice(-Number(limit))
43
+ .map((line) => {
44
+ try {
45
+ return JSON.parse(line);
46
+ } catch {
47
+ return { message: line };
48
+ }
49
+ })
50
+ .reverse();
51
+ } catch {
52
+ return [];
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Xóa toàn bộ lịch sử hoạt động.
58
+ */
59
+ export function clearLogs() {
60
+ try {
61
+ if (fs.existsSync(REMOTE_ACTIVITY_LOG_FILE)) {
62
+ fs.unlinkSync(REMOTE_ACTIVITY_LOG_FILE);
63
+ }
64
+ return { success: true };
65
+ } catch (err) {
66
+ throw new Error(`Không thể xóa nhật ký hoạt động: ${err.message}`);
67
+ }
68
+ }
@@ -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
+ }