@aivin-labs/cli 1.0.13 → 1.0.21

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 (72) hide show
  1. package/README.md +325 -304
  2. package/bin/cli.mjs +97 -18
  3. package/bin/lib/localPreview.mjs +437 -0
  4. package/bin/lib/openFile.mjs +235 -0
  5. package/bin/lib/previewCache.mjs +71 -0
  6. package/bin/lib/remote/atomicFile.mjs +32 -0
  7. package/bin/lib/remote/autoStart.mjs +2 -1
  8. package/bin/lib/remote/autoUpdate.mjs +12 -0
  9. package/bin/lib/remote/callLedger.mjs +21 -0
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  11. package/bin/lib/remote/client.mjs +1024 -889
  12. package/bin/lib/remote/codingAgents.mjs +2 -2
  13. package/bin/lib/remote/constants.mjs +261 -251
  14. package/bin/lib/remote/credentials.mjs +81 -4
  15. package/bin/lib/remote/daemonLock.mjs +57 -17
  16. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +334 -198
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -514
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -95
  21. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  22. package/bin/lib/remote/desktop/index.mjs +21 -7
  23. package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
  24. package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
  25. package/bin/lib/remote/desktop/strings.mjs +28 -2
  26. package/bin/lib/remote/desktop/traySource.mjs +380 -16
  27. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  28. package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
  29. package/bin/lib/remote/fileIndexer.mjs +30 -14
  30. package/bin/lib/remote/folderRules.mjs +3 -0
  31. package/bin/lib/remote/gitSafe.mjs +31 -0
  32. package/bin/lib/remote/gui/index.mjs +66 -24
  33. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  34. package/bin/lib/remote/gui/windowsHost.mjs +3 -1
  35. package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
  36. package/bin/lib/remote/httpTransfer.mjs +64 -3
  37. package/bin/lib/remote/localPolicy.mjs +73 -7
  38. package/bin/lib/remote/mascot/ask.mjs +207 -42
  39. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  40. package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
  41. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  42. package/bin/lib/remote/mascot/bot.mjs +26 -2
  43. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  44. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  45. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  46. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  47. package/bin/lib/remote/mascot/hostSource.mjs +328 -49
  48. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  49. package/bin/lib/remote/mascot/images.mjs +111 -0
  50. package/bin/lib/remote/mascot/index.mjs +663 -493
  51. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  52. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  53. package/bin/lib/remote/mascot/mood.mjs +57 -0
  54. package/bin/lib/remote/mascot/rigSource.mjs +643 -609
  55. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  56. package/bin/lib/remote/mascot/strings.mjs +456 -375
  57. package/bin/lib/remote/mascot/ui.mjs +27 -7
  58. package/bin/lib/remote/multiUser.mjs +7 -2
  59. package/bin/lib/remote/notify.mjs +4 -1
  60. package/bin/lib/remote/office/index.mjs +12 -6
  61. package/bin/lib/remote/processes.mjs +5 -2
  62. package/bin/lib/remote/sandbox.mjs +26 -0
  63. package/bin/lib/remote/secretPaths.mjs +21 -0
  64. package/bin/lib/remote/tokenRotation.mjs +28 -0
  65. package/bin/lib/remote/toolHandlers.mjs +79 -15
  66. package/bin/lib/remote/watchBatcher.mjs +56 -0
  67. package/bin/lib/selfUpdate.mjs +12 -2
  68. package/bin/lib/update/binarySwap.mjs +15 -1
  69. package/bin/lib/update/state.mjs +10 -0
  70. package/docs/CLI.md +42 -1
  71. package/docs/media/aivin-ecosystem.jpg +0 -0
  72. package/package.json +7 -3
@@ -0,0 +1,235 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import axios from 'axios';
5
+ import { createHash } from 'crypto';
6
+ import { fetchWebUrl } from './context.mjs';
7
+ import { startPreviewServer } from './localPreview.mjs';
8
+ import { missionAuthHeaders, missionServerUrl, resolveWorkspace } from './workspace.mjs';
9
+ import { spawn } from 'child_process';
10
+ import { browserLogin, openBrowser, saveGlobalApiKey, tryFetchWhoami } from './auth.mjs';
11
+ import { LOCAL_BROWSERS, detectDefaultBrowserId, resolveBrowserInstall } from './localBrowser.mjs';
12
+ import { mascotLang } from './remote/mascot/strings.mjs';
13
+
14
+ /**
15
+ * `aivin open <tệp>` (04/11/2026) — mở tệp trên máy bằng Drive của Aivin (chưa đăng nhập: trang chỉ-xem, localPreview.mjs). Đã đăng nhập: tải lên workspace cá nhân (hoặc --workspace) rồi mở
16
+ * `<web>/drive?open_file=<id>&workspace_id=<ws>` (deep-link sẵn có của FE, FileShareHook.useOpenFileDeepLink).
17
+ *
18
+ * Drive là bản chính sau khi mở: cùng NỘI DUNG (sha256) đã tải trước đó → mở lại đúng tệp Drive cũ (giữ mọi chỉnh sửa trên Aivin);
19
+ * tệp trên máy đã đổi → tải thành tệp Drive MỚI, không ghi đè bản Drive (có thể đã sửa trên Aivin).
20
+ */
21
+
22
+ export const OPEN_INDEX_FILE = path.join(os.homedir(), '.aivin', 'opened-files.json');
23
+ const MAX_INDEX_ENTRIES = 500;
24
+ const DEFAULT_WEB_URL = 'https://brain.aivin.cloud';
25
+
26
+ export const OpenDisplay = Object.freeze({ WINDOW: 'window', TAB: 'tab', NONE: 'none' });
27
+
28
+ export const OpenFileError = Object.freeze({
29
+ NOT_FOUND: 'not_found',
30
+ NOT_A_FILE: 'not_a_file',
31
+ NOT_LOGGED_IN: 'not_logged_in',
32
+ UPLOAD_FAILED: 'upload_failed',
33
+ });
34
+
35
+ /** Chữ hiện cho người dùng (dòng lệnh + thông báo hệ điều hành), theo ngôn ngữ máy (mascotLang). */
36
+ const OPEN_TEXT = Object.freeze({
37
+ vi: {
38
+ [OpenFileError.NOT_FOUND]: 'Không tìm thấy tệp: {path}',
39
+ [OpenFileError.NOT_A_FILE]: 'Không phải tệp: {path}',
40
+ [OpenFileError.NOT_LOGGED_IN]: 'Máy này chưa đăng nhập Aivin — mở Terminal và chạy: aivin login',
41
+ [OpenFileError.UPLOAD_FAILED]: 'Tải "{name}" lên Drive không được: {reason}',
42
+ opening: 'Đang mở "{name}" trên Aivin…',
43
+ failed_title: 'Không mở được bằng AIVIN Bot',
44
+ },
45
+ en: {
46
+ [OpenFileError.NOT_FOUND]: 'File not found: {path}',
47
+ [OpenFileError.NOT_A_FILE]: 'Not a file: {path}',
48
+ [OpenFileError.NOT_LOGGED_IN]: 'This computer is not signed in to Aivin — open a terminal and run: aivin login',
49
+ [OpenFileError.UPLOAD_FAILED]: 'Could not upload "{name}" to Drive: {reason}',
50
+ opening: 'Opening "{name}" in Aivin…',
51
+ failed_title: 'Could not open with AIVIN Bot',
52
+ },
53
+ });
54
+
55
+ export function openText(key, vars = {}, lang = mascotLang()) {
56
+ const table = OPEN_TEXT[lang] || OPEN_TEXT.en;
57
+ return String(table[key] ?? OPEN_TEXT.en[key] ?? key).replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? ''));
58
+ }
59
+
60
+ export class OpenFileFailure extends Error {
61
+ constructor(code, vars = {}, cause) {
62
+ super(openText(code, vars), cause ? { cause } : undefined);
63
+ this.code = code;
64
+ }
65
+ }
66
+
67
+ export function fileSha256(buffer) {
68
+ return createHash('sha256').update(buffer).digest('hex');
69
+ }
70
+
71
+ /** Khoá chỉ mục: cùng máy chủ + workspace + nội dung (đổi tài khoản / máy chủ không dùng nhầm tệp của nơi khác). */
72
+ export function indexKey({ baseUrl, workspaceId, sha256 }) {
73
+ return `${baseUrl}|${workspaceId}|${sha256}`;
74
+ }
75
+
76
+ export function readOpenIndex(file = OPEN_INDEX_FILE) {
77
+ try {
78
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
79
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
80
+ } catch {
81
+ return {};
82
+ }
83
+ }
84
+
85
+ /** Ghi chỉ mục, giữ tối đa MAX_INDEX_ENTRIES mục mở gần nhất. */
86
+ export function writeOpenIndex(index, file = OPEN_INDEX_FILE) {
87
+ const entries = Object.entries(index)
88
+ .sort((a, b) => String(b[1]?.opened_at || '').localeCompare(String(a[1]?.opened_at || '')))
89
+ .slice(0, MAX_INDEX_ENTRIES);
90
+ fs.mkdirSync(path.dirname(file), { recursive: true });
91
+ const tmp = `${file}.tmp`;
92
+ fs.writeFileSync(tmp, JSON.stringify(Object.fromEntries(entries), null, 2));
93
+ fs.renameSync(tmp, file);
94
+ }
95
+
96
+ export function driveOpenUrl(webUrl, { fileId, workspaceId }) {
97
+ const params = new URLSearchParams({ open_file: fileId, workspace_id: workspaceId });
98
+ return `${String(webUrl).replace(/\/+$/, '')}/drive?${params.toString()}`;
99
+ }
100
+
101
+ function readLocalFile(filePath) {
102
+ const abs = path.resolve(filePath);
103
+ let stat;
104
+ try { stat = fs.statSync(abs); } catch (e) { throw new OpenFileFailure(OpenFileError.NOT_FOUND, { path: abs }, e); }
105
+ if (!stat.isFile()) throw new OpenFileFailure(OpenFileError.NOT_A_FILE, { path: abs });
106
+ return { abs, name: path.basename(abs), buffer: fs.readFileSync(abs) };
107
+ }
108
+
109
+ /** Tệp Drive đã tải trước đó còn mở được không (bị xoá / mất quyền → tải lại). */
110
+ async function driveFileExists(serverUrl, auth, { workspaceId, fileId }) {
111
+ try {
112
+ await axios.get(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/${encodeURIComponent(fileId)}`, { ...auth, timeout: 20_000 });
113
+ return true;
114
+ } catch (e) {
115
+ const status = e?.response?.status;
116
+ if (status === 404 || status === 403 || status === 400) return false;
117
+ throw e;
118
+ }
119
+ }
120
+
121
+ async function uploadToDrive(serverUrl, auth, { workspaceId, name, buffer }) {
122
+ const form = new FormData();
123
+ form.append('file', new Blob([buffer]), name);
124
+ try {
125
+ const res = await axios.post(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/upload`, form, {
126
+ ...auth, maxBodyLength: Infinity, maxContentLength: Infinity, timeout: 10 * 60_000,
127
+ });
128
+ const id = res.data?.id || res.data?._id;
129
+ if (!id) throw new Error('no file id in the upload response');
130
+ return String(id);
131
+ } catch (e) {
132
+ const reason = e?.response?.data?.message || e?.message || e?.code || 'unknown error';
133
+ throw new OpenFileFailure(OpenFileError.UPLOAD_FAILED, { name, reason }, e);
134
+ }
135
+ }
136
+
137
+ async function findReusable(serverUrl, auth, { index, key }) {
138
+ const hit = index[key];
139
+ if (!hit?.file_id) return null;
140
+ return (await driveFileExists(serverUrl, auth, { workspaceId: hit.workspace_id, fileId: hit.file_id })) ? hit.file_id : null;
141
+ }
142
+
143
+ /**
144
+ * Cửa sổ ứng dụng (`--app=`): không thanh địa chỉ / tab, biểu tượng riêng trên taskbar. Chỉ dùng trình duyệt MẶC ĐỊNH và chỉ khi nó là Chromium —
145
+ * phiên đăng nhập Aivin nằm ở đó; trình duyệt khác sẽ bắt đăng nhập lại, nên Firefox / chưa rõ thì trả null (mở tab thường).
146
+ */
147
+ export function appWindowCommand(url, { defaultId = detectDefaultBrowserId(), resolve = resolveBrowserInstall } = {}) {
148
+ const browser = LOCAL_BROWSERS.find((b) => b.id === defaultId);
149
+ const install = browser ? resolve(browser) : null;
150
+ return install ? { exe: install.exe, args: [`--app=${url}`] } : null;
151
+ }
152
+
153
+ function openInWindow(url) {
154
+ const cmd = appWindowCommand(url);
155
+ if (!cmd) return openBrowser(url);
156
+ const child = spawn(cmd.exe, cmd.args, { detached: true, stdio: 'ignore' });
157
+ child.on('error', () => openBrowser(url));
158
+ child.unref();
159
+ }
160
+
161
+ function showUrl(url, mode) {
162
+ if (mode === OpenDisplay.WINDOW) openInWindow(url);
163
+ else if (mode === OpenDisplay.TAB) openBrowser(url);
164
+ }
165
+
166
+ async function resolveWebUrl(serverUrl) {
167
+ return process.env.AIVIN_WEB_URL || (await fetchWebUrl(serverUrl)) || DEFAULT_WEB_URL;
168
+ }
169
+
170
+ /**
171
+ * Tải (hoặc dùng lại) rồi mở. Trả `{ url, fileId, workspaceId, reused }`; lỗi → OpenFileFailure.
172
+ * `display`: OpenDisplay — cửa sổ riêng (mặc định), tab thường, hoặc chỉ trả đường dẫn (--print).
173
+ */
174
+ export async function openLocalFile(filePath, { workspace, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE } = {}) {
175
+ if (!process.env.API_KEY) throw new OpenFileFailure(OpenFileError.NOT_LOGGED_IN);
176
+ const local = readLocalFile(filePath);
177
+ const serverUrl = missionServerUrl();
178
+ const auth = missionAuthHeaders();
179
+ const ws = await resolveWorkspace(serverUrl, auth, workspace);
180
+ const workspaceId = String(ws.id || ws._id);
181
+ const sha256 = fileSha256(local.buffer);
182
+ const key = indexKey({ baseUrl: serverUrl, workspaceId, sha256 });
183
+
184
+ const index = readOpenIndex(indexFile);
185
+ const reusedId = await findReusable(serverUrl, auth, { index, key });
186
+ const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, name: local.name, buffer: local.buffer });
187
+
188
+ index[key] = { file_id: fileId, workspace_id: workspaceId, name: local.name, path: local.abs, opened_at: new Date().toISOString() };
189
+ try { writeOpenIndex(index, indexFile); } catch { /* chỉ mất lần dùng lại sau */ }
190
+
191
+ const url = driveOpenUrl(await resolveWebUrl(serverUrl), { fileId, workspaceId });
192
+ showUrl(url, displayMode);
193
+ return { url, fileId, workspaceId, reused: !!reusedId, name: local.name };
194
+ }
195
+
196
+ const isAuthRejected = (error) => (error?.cause?.response?.status ?? error?.response?.status) === 401;
197
+
198
+ /** Nút đăng nhập trên trang xem: đăng nhập qua trình duyệt, lưu khoá, tải tệp lên Drive, trả link trình soạn để chính cửa sổ đó chuyển sang. */
199
+ async function loginAndUpload(filePath, workspace) {
200
+ const serverUrl = missionServerUrl();
201
+ if (!process.env.AIVIN_WEB_URL) process.env.AIVIN_WEB_URL = await resolveWebUrl(serverUrl);
202
+ const apiKey = await browserLogin();
203
+ saveGlobalApiKey(apiKey, serverUrl, await tryFetchWhoami(serverUrl, apiKey));
204
+ process.env.API_KEY = apiKey;
205
+ const { url } = await openLocalFile(filePath, { workspace, display: OpenDisplay.NONE });
206
+ return url;
207
+ }
208
+
209
+ let activePreviews = 0;
210
+
211
+ /** Chưa đăng nhập: trang chỉ-xem tại máy. Tiến trình sống tới khi mọi trang đã đóng. */
212
+ async function openViewOnly(filePath, { workspace, display: mode = OpenDisplay.WINDOW }) {
213
+ const abs = readLocalFile(filePath).abs;
214
+ activePreviews++;
215
+ const { url } = await startPreviewServer({
216
+ filePath: abs,
217
+ serverUrl: missionServerUrl(),
218
+ onLogin: () => loginAndUpload(abs, workspace),
219
+ onClosed: () => { if (--activePreviews === 0) process.exit(process.exitCode ?? 0); },
220
+ });
221
+ showUrl(url, mode);
222
+ return { url, name: path.basename(abs), viewOnly: true };
223
+ }
224
+
225
+ /** Lối vào của `aivin open`: đã đăng nhập → trình soạn trên Drive; chưa đăng nhập hoặc khoá đã bị thu hồi → trang chỉ-xem. */
226
+ export async function openFile(filePath, options = {}) {
227
+ if (!process.env.API_KEY) return openViewOnly(filePath, options);
228
+ try {
229
+ return await openLocalFile(filePath, options);
230
+ } catch (error) {
231
+ if (!isAuthRejected(error)) throw error;
232
+ delete process.env.API_KEY;
233
+ return openViewOnly(filePath, options);
234
+ }
235
+ }
@@ -0,0 +1,71 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { createHash, randomBytes } from 'crypto';
5
+
6
+ /**
7
+ * Cache PDF xem trước trên CHÍNH máy người dùng (04/11/2026): mở lại tệp Office chưa sửa → hiện ngay, không gửi lại lên máy chủ, không tốn
8
+ * lượt xem trong ngày. Máy chủ vẫn không lưu gì. Khoá = sha256 nội dung tệp (tệp sửa → khoá mới); `v1` đổi khi cách đổi PDF đổi.
9
+ * Tổng tối đa 500 MB, tệp không dùng quá 30 ngày bị xoá; đọc trúng thì cập nhật mtime → dọn tệp lâu không dùng nhất trước.
10
+ */
11
+
12
+ export const PREVIEW_CACHE_DIR = path.join(os.homedir(), '.aivin', 'preview-cache');
13
+ const CACHE_VERSION = 'v1';
14
+ const MAX_TOTAL_BYTES = 500 * 1024 * 1024;
15
+ const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
16
+ const PDF_MAGIC = '%PDF-';
17
+
18
+ export function contentKey(buffer) {
19
+ return `${CACHE_VERSION}-${createHash('sha256').update(buffer).digest('hex')}`;
20
+ }
21
+
22
+ const entryPath = (dir, key) => path.join(dir, `${key}.pdf`);
23
+
24
+ /** PDF đã cache cho nội dung này, hoặc null (thiếu / hỏng / không phải PDF). */
25
+ export function readCachedPdf(key, { dir = PREVIEW_CACHE_DIR } = {}) {
26
+ const file = entryPath(dir, key);
27
+ try {
28
+ const pdf = fs.readFileSync(file);
29
+ if (pdf.subarray(0, PDF_MAGIC.length).toString('latin1') !== PDF_MAGIC) return null;
30
+ const now = new Date();
31
+ try { fs.utimesSync(file, now, now); } catch { /* chỉ ảnh hưởng thứ tự dọn */ }
32
+ return pdf;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ /** Ghi tệp tạm rồi đổi tên: hai cửa sổ cùng ghi một khoá, hoặc tiến trình chết giữa chừng, không để lại PDF cụt. */
39
+ export function writeCachedPdf(key, pdf, { dir = PREVIEW_CACHE_DIR, maxTotalBytes = MAX_TOTAL_BYTES, maxAgeMs = MAX_AGE_MS } = {}) {
40
+ try {
41
+ fs.mkdirSync(dir, { recursive: true });
42
+ const tmp = path.join(dir, `.${key}.${randomBytes(6).toString('hex')}.tmp`);
43
+ fs.writeFileSync(tmp, pdf);
44
+ fs.renameSync(tmp, entryPath(dir, key));
45
+ prunePreviewCache({ dir, maxTotalBytes, maxAgeMs });
46
+ } catch {
47
+ // cache chỉ để nhanh hơn: ổ đầy / không ghi được thì lần sau đổi lại
48
+ }
49
+ }
50
+
51
+ /** Xoá tệp quá hạn và tệp tạm mồ côi, rồi xoá tệp lâu không dùng nhất tới khi tổng dưới trần. */
52
+ export function prunePreviewCache({ dir = PREVIEW_CACHE_DIR, maxTotalBytes = MAX_TOTAL_BYTES, maxAgeMs = MAX_AGE_MS, now = Date.now() } = {}) {
53
+ let names;
54
+ try { names = fs.readdirSync(dir); } catch { return; }
55
+ const entries = [];
56
+ for (const name of names) {
57
+ const file = path.join(dir, name);
58
+ let stat;
59
+ try { stat = fs.statSync(file); } catch { continue; }
60
+ const expired = now - stat.mtimeMs > maxAgeMs;
61
+ const staleTmp = name.endsWith('.tmp') && now - stat.mtimeMs > 60 * 60 * 1000;
62
+ if (expired || staleTmp) { fs.rmSync(file, { force: true }); continue; }
63
+ if (name.endsWith('.pdf')) entries.push({ file, size: stat.size, mtime: stat.mtimeMs });
64
+ }
65
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
66
+ for (const e of entries.sort((a, b) => a.mtime - b.mtime)) {
67
+ if (total <= maxTotalBytes) break;
68
+ fs.rmSync(e.file, { force: true });
69
+ total -= e.size;
70
+ }
71
+ }
@@ -0,0 +1,32 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ const RENAME_RETRIES = 4;
5
+ const RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
6
+
7
+ const sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
+
9
+ /**
10
+ * Ghi tệp NGUYÊN TỬ (02/11/2026): ghi tệp tạm cạnh bên rồi đổi tên đè — người đọc chỉ thấy bản cũ trọn vẹn hoặc bản mới trọn vẹn, máy tắt /
11
+ * tiến trình bị giết giữa lúc ghi không để lại tệp cụt. Windows: đổi tên đè tệp đang bị tiến trình khác mở đọc có thể lỗi EPERM / EBUSY
12
+ * thoáng qua → thử lại vài lần (chờ ngắn, đồng bộ). Hỏng hẳn → xoá tệp tạm, ném lỗi (tệp đích giữ nguyên).
13
+ */
14
+ export function writeFileAtomic(file, data, { mode = 0o600 } = {}) {
15
+ fs.mkdirSync(path.dirname(file), { recursive: true });
16
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
17
+ try {
18
+ fs.writeFileSync(tmp, data, { mode });
19
+ for (let attempt = 0; ; attempt++) {
20
+ try {
21
+ fs.renameSync(tmp, file);
22
+ return;
23
+ } catch (e) {
24
+ if (attempt >= RENAME_RETRIES || !RETRY_CODES.has(e?.code)) throw e;
25
+ sleepSync(20 * (attempt + 1));
26
+ }
27
+ }
28
+ } catch (e) {
29
+ try { fs.rmSync(tmp, { force: true }); } catch { /* bỏ */ }
30
+ throw e;
31
+ }
32
+ }
@@ -11,6 +11,7 @@ import {
11
11
  DESKTOP_DIR, RUN_KEY, STARTUP_VALUE, TrayLaunch, installDesktop, isDesktopInstalled, launcherExePath, readSavedDaemonArgs, setStartupApproved,
12
12
  startMenuShortcutPath, startupState, uninstallDesktop,
13
13
  } from './desktop/index.mjs';
14
+ import { fileAssociationsRegistered } from './desktop/fileAssociation.mjs';
14
15
  import { installMacDesktop, isMacDesktopInstalled, macAgentPath, macAppPath, macStartupState, setMacStartup, uninstallMacDesktop } from './desktop/mac.mjs';
15
16
  import {
16
17
  hasLinuxDesktopSession, installLinuxDesktop, isLinuxDesktopInstalled, linuxAppEntryPath, linuxAutostartPath, linuxStartupState, linuxTrayAvailable,
@@ -440,7 +441,7 @@ export function desktopAppStatus() {
440
441
  if (process.platform === 'win32') {
441
442
  return {
442
443
  installed: isDesktopInstalled(), app: launcherExePath(), search: fs.existsSync(startMenuShortcutPath()) ? 'Start menu' : null,
443
- startup: startupState(), tray: true,
444
+ startup: startupState(), tray: true, openWith: fileAssociationsRegistered(),
444
445
  };
445
446
  }
446
447
  const desktop = POSIX_DESKTOP[process.platform];
@@ -62,6 +62,14 @@ export function createAutoUpdater({
62
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
63
  return;
64
64
  }
65
+ // Đã có bản mới chờ khởi động lại (cài ở lần kiểm trước / cửa sổ khác) → không kiểm / cài lại (02/11/2026: sự kiện UPDATE của máy chủ
66
+ // gọi checkNow cài chồng, đè `.prev`). Ngoại lệ: máy chủ đòi bản tối thiểu cao hơn bản đang chờ.
67
+ const waiting = ready || installedNewer();
68
+ if (waiting && !(minVersion && compareVersions(waiting, minVersion) < 0)) {
69
+ ready = waiting;
70
+ nextCheckAt = now() + jitter(checkEveryMs);
71
+ return { status: UpdateStatus.INSTALLED, latest: waiting, current: tagOf(current), already: true };
72
+ }
65
73
  try {
66
74
  const res = await install({ deviceId, urgent: urgent && !!minVersion && compareVersions(current, minVersion) < 0, holdVersions });
67
75
  nextCheckAt = now() + jitter(checkEveryMs);
@@ -115,6 +123,10 @@ export function createAutoUpdater({
115
123
 
116
124
  return {
117
125
  tick,
126
+ async checkNow({ urgent: isUrgent = true } = {}) {
127
+ urgent = isUrgent;
128
+ return check();
129
+ },
118
130
  setMinVersion,
119
131
  /** Gợi ý từ ack của `device:hello` (`hello.cli`) — xem đầu tệp. */
120
132
  setServerHints(hints) {
@@ -7,6 +7,9 @@ const UNSENT_KEEP_MS = 15 * 60_000;
7
7
  /** Kết quả đã gửi vẫn nhớ thêm chừng này (BE gửi lại đúng `call_id` vì ACK / kết quả lỡ mất → trả lại kết quả cũ, không chạy lần hai). */
8
8
  const SENT_KEEP_MS = 3 * 60_000;
9
9
  const MAX_UNSENT = 200;
10
+ /** Gửi lại kết quả chưa có ack khi socket vẫn nối: lần đầu sau ~30 s (ack chờ 15 s), giãn gấp đôi, tối đa 4 phút. */
11
+ const RESEND_BASE_MS = 30_000;
12
+ const RESEND_MAX_MS = 4 * 60_000;
10
13
  /** Kết quả lớn hơn không ghi xuống đĩa (chỉ giữ trong bộ nhớ) — daemon chết thì BE nhận lỗi thay vì nội dung. */
11
14
  const PERSIST_RESULT_BYTES = 4 * 1024 * 1024;
12
15
 
@@ -180,6 +183,24 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
180
183
  if (changed) schedulePersist();
181
184
  },
182
185
  unsent: () => [...calls.values()].filter((e) => e.state === CallState.DONE && !e.sent).map((e) => e.payload),
186
+ /** Vừa gửi kết quả này (chờ ack) — `dueForResend` giãn nhịp theo số lần đã gửi. */
187
+ markAttempt(callId) {
188
+ const e = calls.get(callId);
189
+ if (!e || e.state !== CallState.DONE || e.sent) return;
190
+ e.attempts = (e.attempts || 0) + 1;
191
+ e.attemptAt = now();
192
+ },
193
+ /**
194
+ * Kết quả đã gửi mà chưa có ack quá hạn giãn nhịp (02/11/2026): máy chủ quá tải làm lỡ ack khi socket vẫn nối thì trước đây chỉ gửi lại
195
+ * lúc nối lại — BE chờ tới hết giờ rồi agent chạy lại bước. Nhịp: `baseMs` × 2^(lần−1), tối đa `maxMs`; mục chưa gửi lần nào không
196
+ * tính (đường gửi thường lo). Cùng `call_id` → BE bỏ bản trùng.
197
+ */
198
+ dueForResend({ baseMs = RESEND_BASE_MS, maxMs = RESEND_MAX_MS } = {}) {
199
+ const t = now();
200
+ return [...calls.values()]
201
+ .filter((e) => e.state === CallState.DONE && !e.sent && e.attempts > 0 && t - e.attemptAt >= Math.min(maxMs, baseMs * 2 ** (e.attempts - 1)))
202
+ .map((e) => e.payload);
203
+ },
183
204
  heldIds: () => [...calls.entries()].filter(([, e]) => e.state === CallState.RUNNING || (e.state === CallState.DONE && !e.sent)).map(([id]) => id),
184
205
  runningIds: () => [...calls.entries()].filter(([, e]) => e.state === CallState.RUNNING).map(([id]) => id),
185
206
  prune,
@@ -29,9 +29,21 @@ export function isExtensionUrl(url) {
29
29
  return /^\s*(chrome|edge)-extension:/i.test(String(url ?? ''));
30
30
  }
31
31
 
32
+ /** Chỉ các scheme này được mở từ xa; còn lại (file:, chrome:, javascript:, scheme lạ…) chặn. */
33
+ const ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'about:', 'data:', 'blob:']);
34
+
32
35
  export function isBlockedUrl(url) {
33
- const u = String(url ?? '');
34
- return BLOCKED_URL_RE.test(u) || BLOCKED_ABOUT_RE.test(u);
36
+ // Trình duyệt bỏ ký tự điều khiển / khoảng trắng đầu-cuối và tab / xuống dòng ở giữa trước khi đọc scheme ("\u0001file:", "fi\tle:" vẫn là
37
+ // file:) — chuẩn hoá y như vậy rồi mới xét, không thì regex lọt (02/11/2026).
38
+ const u = String(url ?? '').replace(/^[\u0000- ]+|[\u0000- ]+$/g, '').replace(/[\t\n\r]/g, '');
39
+ if (!u) return false;
40
+ if (BLOCKED_URL_RE.test(u) || BLOCKED_ABOUT_RE.test(u)) return true;
41
+ try {
42
+ return !ALLOWED_PROTOCOLS.has(new URL(u).protocol);
43
+ } catch {
44
+ // Không phải URL tuyệt đối (đường tương đối) → không có scheme để lách; có dáng scheme mà không parse được → chặn.
45
+ return /^[a-z][a-z0-9+.-]*:/i.test(u);
46
+ }
35
47
  }
36
48
 
37
49
  /**