@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,205 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import {
4
+ BootAction, LOCK_STALE_MS, MAX_BOOTS_BEFORE_ROLLBACK, RollbackBy, UPDATE_INSTALLED_FILE, UPDATE_LOCK_FILE, UPDATE_PENDING_FILE, UPDATE_ROLLBACK_FILE,
5
+ UPDATE_SETTINGS_FILE, UPDATE_STATE_FILE, UPDATE_STATUS_FILE, UpdateStatus,
6
+ } from './constants.mjs';
7
+ import { restoreBackup, retire } from './binarySwap.mjs';
8
+ import { compareVersions, currentCliVersion, parseVersion, tagOf, versionList } from './versions.mjs';
9
+
10
+ /** Trạng thái tự cập nhật trên đĩa (`~/.aivin`): cài đặt, khoá, dấu đã cài, bản chờ xác nhận, tự lùi bản, kết quả kiểm gửi máy chủ. */
11
+
12
+ const MAX_ROLLBACK_HISTORY = 5;
13
+ const MAX_ERROR_CHARS = 200;
14
+
15
+ function readJson(file) {
16
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
17
+ }
18
+
19
+ export function writeJson(file, data) {
20
+ fs.mkdirSync(path.dirname(file), { recursive: true });
21
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
22
+ }
23
+
24
+ const samePath = (a, b) => (process.platform === 'win32' ? String(a).toLowerCase() === String(b).toLowerCase() : a === b);
25
+
26
+ export function loadUpdateSettings(file = UPDATE_SETTINGS_FILE) {
27
+ const data = readJson(file) || {};
28
+ return { auto: data.auto !== false, skip: versionList(data.skip) };
29
+ }
30
+
31
+ export function saveUpdateSettings(patch, file = UPDATE_SETTINGS_FILE) {
32
+ const next = { ...loadUpdateSettings(file), ...patch };
33
+ writeJson(file, next);
34
+ return next;
35
+ }
36
+
37
+ const addSkip = (version, file) => saveUpdateSettings({ skip: [...new Set([...loadUpdateSettings(file).skip, tagOf(version)])] }, file);
38
+
39
+ function isAlive(pid) {
40
+ if (!Number.isInteger(pid) || pid <= 0) return false;
41
+ try { process.kill(pid, 0); return true; } catch (e) { return e?.code === 'EPERM'; }
42
+ }
43
+
44
+ /** Một lần cập nhật mỗi lúc (daemon tự cập nhật + `aivin update` ở cửa sổ khác cùng thay một tệp). */
45
+ export async function withUpdateLock(fn, file = UPDATE_LOCK_FILE) {
46
+ fs.mkdirSync(path.dirname(file), { recursive: true });
47
+ const body = JSON.stringify({ pid: process.pid, at: Date.now() });
48
+ try {
49
+ fs.writeFileSync(file, body, { flag: 'wx' });
50
+ } catch (e) {
51
+ if (e?.code !== 'EEXIST') throw e;
52
+ const held = readJson(file);
53
+ if (held && isAlive(Number(held.pid)) && Date.now() - Number(held.at) < LOCK_STALE_MS) return { status: UpdateStatus.BUSY };
54
+ fs.writeFileSync(file, body);
55
+ }
56
+ try {
57
+ return await fn();
58
+ } finally {
59
+ try { if (Number(readJson(file)?.pid) === process.pid) fs.rmSync(file, { force: true }); } catch { /* đã bị lấy lại */ }
60
+ }
61
+ }
62
+
63
+ /** Sau khi thay tệp: bản chờ xác nhận (JSON cho tệp chạy + dòng chữ cho trình giữ chạy) và dấu "đĩa đã có bản mới". */
64
+ export function recordInstalled({ version, current, target, backup, stateFile = UPDATE_STATE_FILE, markerFile = UPDATE_INSTALLED_FILE, pendingFile = UPDATE_PENDING_FILE }) {
65
+ const at = new Date().toISOString();
66
+ writeJson(stateFile, { version: tagOf(version), previous: tagOf(current), target, backup, boots: 0, installed_at: at });
67
+ writeJson(markerFile, { version: tagOf(version), path: target, installed_at: at });
68
+ if (backup) fs.writeFileSync(pendingFile, `${tagOf(version)}\n`);
69
+ else fs.rmSync(pendingFile, { force: true });
70
+ }
71
+
72
+ export function readInstalledMarker(file = UPDATE_INSTALLED_FILE) {
73
+ const data = readJson(file);
74
+ return data && parseVersion(data.version) && typeof data.path === 'string' ? data : null;
75
+ }
76
+
77
+ /** Đĩa đã có bản mới hơn bản đang chạy cho đúng tệp chạy này (cài ở cửa sổ khác / bởi daemon). Bản đã tự lùi khỏi không tính. */
78
+ export function installedNewerThanRunning({ target = process.execPath, current = currentCliVersion(), file = UPDATE_INSTALLED_FILE, settingsFile = UPDATE_SETTINGS_FILE } = {}) {
79
+ const marker = readInstalledMarker(file);
80
+ if (!marker || !samePath(marker.path, target) || compareVersions(marker.version, current) <= 0) return null;
81
+ return loadUpdateSettings(settingsFile).skip.includes(tagOf(marker.version)) ? null : tagOf(marker.version);
82
+ }
83
+
84
+ /** Tiến trình vừa khởi động chính là tệp đang nằm trên đĩa → dấu "đã cài bản mới" cho tệp này đã cũ (cài lại bằng bộ cài, đã lùi bản…). */
85
+ export function clearStaleInstalledMarker({ target = process.execPath, file = UPDATE_INSTALLED_FILE } = {}) {
86
+ const marker = readInstalledMarker(file);
87
+ if (marker && samePath(marker.path, target)) fs.rmSync(file, { force: true });
88
+ }
89
+
90
+ export function readUpdateStatus(file = UPDATE_STATUS_FILE) {
91
+ const data = readJson(file) || {};
92
+ return {
93
+ last_check_at: typeof data.last_check_at === 'string' ? data.last_check_at : null,
94
+ last_error: typeof data.last_error === 'string' ? data.last_error : null,
95
+ site_latest: parseVersion(data.site_latest) ? tagOf(data.site_latest) : null,
96
+ site_behind: data.site_behind === true,
97
+ rolled_back: Array.isArray(data.rolled_back) ? data.rolled_back.filter((r) => parseVersion(r?.version)).slice(-MAX_ROLLBACK_HISTORY) : [],
98
+ };
99
+ }
100
+
101
+ /** Ghi kết quả một lần kiểm (thành công: xoá lỗi cũ). Không ghi được thì thôi — chỉ để báo máy chủ. */
102
+ export function recordCheck({ siteLatest, error, siteBehind, file = UPDATE_STATUS_FILE } = {}) {
103
+ try {
104
+ const prev = readUpdateStatus(file);
105
+ writeJson(file, {
106
+ ...prev,
107
+ last_check_at: new Date().toISOString(),
108
+ last_error: error ? String(error).slice(0, MAX_ERROR_CHARS) : null,
109
+ ...(siteLatest ? { site_latest: tagOf(siteLatest) } : {}),
110
+ ...(siteBehind !== undefined ? { site_behind: !!siteBehind } : {}),
111
+ });
112
+ } catch { /* chỉ để báo */ }
113
+ }
114
+
115
+ function recordRollback({ version, by, file = UPDATE_STATUS_FILE }) {
116
+ try {
117
+ const prev = readUpdateStatus(file);
118
+ writeJson(file, { ...prev, rolled_back: [...prev.rolled_back, { version: tagOf(version), by, at: new Date().toISOString() }].slice(-MAX_ROLLBACK_HISTORY) });
119
+ } catch { /* chỉ để báo */ }
120
+ }
121
+
122
+ /**
123
+ * Trình giữ chạy đã tự lùi bản (bản mới sập trước khi tệp chạy kịp kiểm): đưa bản đó vào danh sách bỏ qua, ghi lịch sử, dọn trạng thái chờ.
124
+ * Gọi khi khởi động, trước checkBootAfterUpdate. Trả phiên bản đã bị lùi (null nếu không có).
125
+ */
126
+ export function ingestSupervisorRollback({
127
+ rollbackFile = UPDATE_ROLLBACK_FILE, settingsFile = UPDATE_SETTINGS_FILE, statusFile = UPDATE_STATUS_FILE, stateFile = UPDATE_STATE_FILE,
128
+ markerFile = UPDATE_INSTALLED_FILE, pendingFile = UPDATE_PENDING_FILE,
129
+ } = {}) {
130
+ let line;
131
+ try { line = fs.readFileSync(rollbackFile, 'utf8').trim().split(/\r?\n/)[0]; } catch { return null; }
132
+ fs.rmSync(rollbackFile, { force: true });
133
+ if (!parseVersion(line)) return null;
134
+ addSkip(line, settingsFile);
135
+ recordRollback({ version: line, by: RollbackBy.SUPERVISOR, file: statusFile });
136
+ for (const f of [stateFile, markerFile, pendingFile]) fs.rmSync(f, { force: true });
137
+ return tagOf(line);
138
+ }
139
+
140
+ /**
141
+ * Gọi ĐẦU TIÊN khi `aivin remote start` khởi động. Đang chạy đúng bản vừa cài mà chưa được xác nhận: đếm lần khởi động; quá
142
+ * MAX_BOOTS_BEFORE_ROLLBACK lần (mỗi lần sập trình giữ chạy mở lại) → trả bản cũ, ghi bản này vào danh sách bỏ qua.
143
+ */
144
+ export function checkBootAfterUpdate({
145
+ current = currentCliVersion(), target = process.execPath, maxBoots = MAX_BOOTS_BEFORE_ROLLBACK, platform = process.platform,
146
+ stateFile = UPDATE_STATE_FILE, settingsFile = UPDATE_SETTINGS_FILE, markerFile = UPDATE_INSTALLED_FILE, pendingFile = UPDATE_PENDING_FILE,
147
+ statusFile = UPDATE_STATUS_FILE,
148
+ } = {}) {
149
+ const state = readJson(stateFile);
150
+ if (!state || !parseVersion(state.version) || !samePath(state.target, target)) return { action: BootAction.NONE };
151
+ if (compareVersions(state.version, current) !== 0) {
152
+ // Đang chạy bản khác bản vừa cài (người dùng đã lùi / cài đè) — trạng thái chờ hết nghĩa.
153
+ for (const f of [stateFile, pendingFile]) fs.rmSync(f, { force: true });
154
+ return { action: BootAction.NONE };
155
+ }
156
+ // Lần trước dừng gọn (Ctrl+C, chuyển bản, thu hồi…) → không phải sập, không tính.
157
+ const boots = (Number(state.boots) || 0) + (state.clean_exit ? 0 : 1);
158
+ if (boots <= maxBoots || !state.backup || !fs.existsSync(state.backup)) {
159
+ writeJson(stateFile, { ...state, boots, clean_exit: false });
160
+ return { action: BootAction.PENDING, boots };
161
+ }
162
+ restoreBackup({ target, backup: state.backup, platform });
163
+ addSkip(state.version, settingsFile);
164
+ recordRollback({ version: state.version, by: RollbackBy.BINARY, file: statusFile });
165
+ for (const f of [stateFile, markerFile, pendingFile]) fs.rmSync(f, { force: true });
166
+ return { action: BootAction.ROLLED_BACK, version: tagOf(state.version), previous: state.previous ? tagOf(state.previous) : null };
167
+ }
168
+
169
+ /** Daemon dừng gọn khi bản mới còn chờ xác nhận → lần khởi động sau không bị tính là sập. */
170
+ export function noteCleanExit({ current = currentCliVersion(), target = process.execPath, stateFile = UPDATE_STATE_FILE } = {}) {
171
+ const state = readJson(stateFile);
172
+ if (!state || !samePath(state.target, target) || compareVersions(state.version, current) !== 0) return;
173
+ try { writeJson(stateFile, { ...state, clean_exit: true }); } catch { /* không ghi được → lần sau tính là sập, chậm lắm là lùi oan một bản */ }
174
+ }
175
+
176
+ /** Bản đang chạy ổn (chạy đủ lâu không sập) → bỏ bản cũ, hết theo dõi khởi động (cả ở trình giữ chạy). */
177
+ export function confirmUpdate({ current = currentCliVersion(), target = process.execPath, stateFile = UPDATE_STATE_FILE, pendingFile = UPDATE_PENDING_FILE } = {}) {
178
+ const state = readJson(stateFile);
179
+ if (!state || !samePath(state.target, target) || compareVersions(state.version, current) !== 0) return false;
180
+ if (state.backup && fs.existsSync(state.backup)) {
181
+ try { retire(state.backup); } catch { /* lần sau */ }
182
+ }
183
+ for (const f of [stateFile, pendingFile]) fs.rmSync(f, { force: true });
184
+ return true;
185
+ }
186
+
187
+ /** Tình trạng tự cập nhật gửi máy chủ trong hồ sơ máy (`profile.update`) — máy chủ gom lại để thấy cả đội máy, tự hoãn bản lỗi. */
188
+ export function updateProfile({
189
+ enabled = true, current = currentCliVersion(), target = process.execPath, settingsFile = UPDATE_SETTINGS_FILE, statusFile = UPDATE_STATUS_FILE,
190
+ stateFile = UPDATE_STATE_FILE,
191
+ } = {}) {
192
+ const settings = loadUpdateSettings(settingsFile);
193
+ const status = readUpdateStatus(statusFile);
194
+ const state = readJson(stateFile);
195
+ const pending = state && samePath(state.target, target) && compareVersions(state.version, current) === 0 ? tagOf(state.version) : null;
196
+ return {
197
+ auto: enabled && settings.auto,
198
+ pending,
199
+ last_check_at: status.last_check_at,
200
+ last_error: status.last_error,
201
+ site_latest: status.site_latest,
202
+ site_behind: status.site_behind,
203
+ rolled_back: status.rolled_back.map((r) => r.version),
204
+ };
205
+ }
@@ -0,0 +1,60 @@
1
+ import fs from 'fs';
2
+ import { createHash } from 'crypto';
3
+ import { execFileSync } from 'child_process';
4
+ import { createRequire } from 'module';
5
+
6
+ const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
7
+ const require = createRequire(import.meta.url);
8
+
9
+ /** Phiên bản đang chạy: tệp chạy đóng gói ghi sẵn lúc build, bản npm đọc package.json. */
10
+ export function currentCliVersion() {
11
+ if (process.env.AIVIN_CLI_BINARY) return process.env.AIVIN_CLI_BINARY;
12
+ try { return require('../../../package.json').version; } catch { return '0.0.0'; }
13
+ }
14
+
15
+ export const isStandaloneBinary = () => !!process.env.AIVIN_CLI_BINARY;
16
+
17
+ export function parseVersion(v) {
18
+ const m = VERSION_RE.exec(String(v || '').trim());
19
+ return m ? { parts: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] || '' } : null;
20
+ }
21
+
22
+ /** So sánh phiên bản (`v` đầu tuỳ ý): âm / 0 / dương. Bản thử nghiệm (`-beta`) nhỏ hơn bản chính cùng số. Không đọc được → nhỏ nhất. */
23
+ export function compareVersions(a, b) {
24
+ const pa = parseVersion(a);
25
+ const pb = parseVersion(b);
26
+ if (!pa || !pb) return (pa ? 1 : 0) - (pb ? 1 : 0);
27
+ for (let i = 0; i < 3; i++) if (pa.parts[i] !== pb.parts[i]) return pa.parts[i] - pb.parts[i];
28
+ if (pa.pre === pb.pre) return 0;
29
+ if (!pa.pre) return 1;
30
+ if (!pb.pre) return -1;
31
+ return pa.pre < pb.pre ? -1 : 1;
32
+ }
33
+
34
+ export const tagOf = (v) => `v${String(v).replace(/^v/, '')}`;
35
+
36
+ /** Danh sách phiên bản lấy từ ngoài (máy chủ, tệp cài đặt): bỏ mục hỏng, chuẩn hoá `vX.Y.Z`, có trần. */
37
+ export const versionList = (list, max = 50) => (Array.isArray(list) ? list.filter((v) => parseVersion(v)).slice(0, max).map(tagOf) : []);
38
+
39
+ function isMusl() {
40
+ try { return fs.readdirSync('/lib').some((f) => f.startsWith('ld-musl-')); } catch { return false; }
41
+ }
42
+
43
+ /** Tệp x64 chạy dưới Rosetta trên Apple Silicon → lên bản arm64 gốc (như install.sh). */
44
+ function underRosetta() {
45
+ try { return execFileSync('sysctl', ['-n', 'sysctl.proc_translated'], { encoding: 'utf8', timeout: 5000 }).trim() === '1'; } catch { return false; }
46
+ }
47
+
48
+ /** Tên bản build cho máy này — khớp TARGETS của scripts/build-binary.mjs. */
49
+ export function releaseAsset({ platform = process.platform, arch = process.arch, musl, rosetta } = {}) {
50
+ const cpu = arch === 'arm64' ? 'arm64' : 'x64';
51
+ if (platform === 'win32') return `aivin-windows-${cpu}.exe`;
52
+ if (platform === 'darwin') return `aivin-darwin-${cpu === 'x64' && (rosetta ?? underRosetta()) ? 'arm64' : cpu}`;
53
+ if (platform === 'linux') return `aivin-linux-${cpu}${(musl ?? isMusl()) ? '-musl' : ''}`;
54
+ throw new Error(`Nền tảng ${platform} chưa có bản tự cập nhật`);
55
+ }
56
+
57
+ /** Máy nào thuộc đợt nào cố định theo (mã máy, phiên bản): tăng % chỉ thêm máy, không đổi máy đã lên. */
58
+ export function rolloutBucket(deviceId, version) {
59
+ return parseInt(createHash('sha256').update(`${deviceId}:${tagOf(version)}`).digest('hex').slice(0, 8), 16) % 100;
60
+ }
package/bin/lib/util.mjs CHANGED
@@ -2,6 +2,14 @@ import chalk from 'chalk';
2
2
  import readline from 'readline';
3
3
  import inquirer from 'inquirer';
4
4
 
5
+ // ✅ FIX: several axios calls across the CLI (store.mjs, connectors.mjs, deploy.mjs's main deploy
6
+ // POST) had no `timeout` at all - a network glitch/overloaded backend left the spinner spinning
7
+ // forever with no way out short of Ctrl+C, which is especially costly for a call like `connector
8
+ // register` where the whole interactive form (including a typed-in OAuth client_secret) would have
9
+ // to be re-entered from scratch afterwards. A generous but finite default so a genuinely slow-but-
10
+ // alive backend still succeeds, while a truly hung connection eventually surfaces as a normal error.
11
+ export const DEFAULT_API_TIMEOUT_MS = 30000;
12
+
5
13
  // Same spinner deployPlugin has always had, factored out so other long-running network calls
6
14
  // (AI codegen, connector register) get the same "still working, not hung" feedback instead of a
7
15
  // static line that just sits there for however many seconds the request takes.