@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.
- package/README.md +325 -304
- package/bin/cli.mjs +97 -18
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/callLedger.mjs +21 -0
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -889
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -251
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -198
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -514
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -95
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +21 -7
- package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
- package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +380 -16
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/fileIndexer.mjs +30 -14
- package/bin/lib/remote/folderRules.mjs +3 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +66 -24
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +3 -1
- package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/localPolicy.mjs +73 -7
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +26 -2
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +328 -49
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +643 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +79 -15
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/CLI.md +42 -1
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/package.json +7 -3
|
@@ -6,6 +6,7 @@ import { isDesktopInstalled, launchTray } from '../desktop/index.mjs';
|
|
|
6
6
|
import { loadDeviceCredentials } from '../credentials.mjs';
|
|
7
7
|
import { lockHolder } from '../daemonLock.mjs';
|
|
8
8
|
import { HostCommand, HostEvent, MASCOT_DIR, MascotState, loadMascotSettings, requestMascotShow, saveMascotSettings, writeHostFiles } from './index.mjs';
|
|
9
|
+
import { Mood, MOOD_GESTURE, moodOf, SUBDUED_MOODS } from './mood.mjs';
|
|
9
10
|
import { mascotLang } from './strings.mjs';
|
|
10
11
|
|
|
11
12
|
/**
|
|
@@ -22,6 +23,24 @@ export const MASCOT_DEMO_STATES = Object.freeze([
|
|
|
22
23
|
MascotState.IDLE, MascotState.WORKING, MascotState.THINKING, MascotState.WAITING,
|
|
23
24
|
MascotState.DONE, MascotState.ERROR, MascotState.PAUSED, MascotState.OFFLINE,
|
|
24
25
|
]);
|
|
26
|
+
/** Nét mặt theo emoji (mood.mjs) trong demo: mỗi mood một câu mẫu chỉ có emoji, đi qua `moodOf` như câu trả lời thật. */
|
|
27
|
+
export const MASCOT_DEMO_MOODS = Object.freeze([
|
|
28
|
+
{ mood: Mood.SAD, text: '😔' }, { mood: Mood.CRY, text: '😭' }, { mood: Mood.SHEEPISH, text: '😅' }, { mood: Mood.HAPPY, text: '😊' },
|
|
29
|
+
{ mood: Mood.CELEBRATE, text: '🎉' }, { mood: Mood.SURPRISED, text: '😮' }, { mood: Mood.CURIOUS, text: '🤔' },
|
|
30
|
+
]);
|
|
31
|
+
/** `aivin ui --demo [--moods]`: cả trạng thái lẫn nét mặt, hoặc chỉ nét mặt. */
|
|
32
|
+
export const DemoScope = Object.freeze({ ALL: 'all', MOODS: 'moods' });
|
|
33
|
+
|
|
34
|
+
/** Một bước demo → lệnh cho cửa sổ. Nét mặt: như `alert` của daemon — buồn / ngượng về chờ việc, còn lại "xong" rồi cử chỉ. */
|
|
35
|
+
function demoCommands(step) {
|
|
36
|
+
if (typeof step === 'string') return [{ t: HostCommand.STATE, state: step }, { t: HostCommand.MAIN, text: `Demo: ${step}` }];
|
|
37
|
+
const mood = moodOf(step.text);
|
|
38
|
+
return [
|
|
39
|
+
{ t: HostCommand.STATE, state: SUBDUED_MOODS.has(mood) ? MascotState.IDLE : MascotState.DONE },
|
|
40
|
+
{ t: HostCommand.MAIN, text: `Demo: ${step.mood} ${step.text}` },
|
|
41
|
+
{ t: HostCommand.GESTURE, ...MOOD_GESTURE[mood] },
|
|
42
|
+
];
|
|
43
|
+
}
|
|
25
44
|
|
|
26
45
|
const START_WAIT_MS = 20_000;
|
|
27
46
|
const POLL_MS = 500;
|
|
@@ -70,7 +89,11 @@ export async function showMascotUi({ platform = process.platform, onStarting = (
|
|
|
70
89
|
}
|
|
71
90
|
|
|
72
91
|
/** Preview all visual states without pairing or starting the remote listener. The child + interval keep Node alive until the window closes or Ctrl+C. */
|
|
73
|
-
|
|
92
|
+
/**
|
|
93
|
+
* `onEarlyExit()`: cửa sổ thoát trước khi `ready` — thường vì linh vật thật của daemon đang giữ mutex (mỗi lúc một linh vật), lệnh demo
|
|
94
|
+
* báo thay vì im lặng như đang chạy.
|
|
95
|
+
*/
|
|
96
|
+
export function showMascotDemo({ platform = process.platform, env = process.env, stateMs = 3800, scope = DemoScope.ALL, onEarlyExit = () => {}, deps = {} } = {}) {
|
|
74
97
|
if (platform !== 'win32') return UiResult.UNSUPPORTED;
|
|
75
98
|
const d = { spawn, writeHostFiles, loadMascotSettings, setInterval, clearInterval, ...deps };
|
|
76
99
|
let home;
|
|
@@ -81,21 +104,18 @@ export function showMascotDemo({ platform = process.platform, env = process.env,
|
|
|
81
104
|
});
|
|
82
105
|
let timer = null;
|
|
83
106
|
let index = 0;
|
|
107
|
+
const steps = scope === DemoScope.MOODS ? MASCOT_DEMO_MOODS : [...MASCOT_DEMO_STATES, ...MASCOT_DEMO_MOODS];
|
|
84
108
|
const send = (message) => {
|
|
85
109
|
try { child.stdin.write(`${JSON.stringify(message)}\n`); } catch { /* preview window closed */ }
|
|
86
110
|
};
|
|
87
|
-
const showState = () =>
|
|
88
|
-
const state = MASCOT_DEMO_STATES[index++ % MASCOT_DEMO_STATES.length];
|
|
89
|
-
send({ t: HostCommand.STATE, state });
|
|
90
|
-
send({ t: HostCommand.MAIN, text: `Demo: ${state}`, quiet: false });
|
|
91
|
-
};
|
|
111
|
+
const showState = () => demoCommands(steps[index++ % steps.length]).forEach(send);
|
|
92
112
|
readline.createInterface({ input: child.stdout }).on('line', (line) => {
|
|
93
113
|
let event;
|
|
94
114
|
try { event = JSON.parse(line); } catch { return; }
|
|
95
115
|
if (event.t === HostEvent.READY && !timer) { showState(); timer = d.setInterval(showState, stateMs); }
|
|
96
116
|
if (event.t === HostEvent.OFF) { send({ t: HostCommand.QUIT }); child.stdin.end(); }
|
|
97
117
|
});
|
|
98
|
-
child.on('close', () => { if (timer) d.clearInterval(timer); });
|
|
118
|
+
child.on('close', () => { if (timer) d.clearInterval(timer); else onEarlyExit(); });
|
|
99
119
|
child.on('error', () => { if (timer) d.clearInterval(timer); });
|
|
100
120
|
return UiResult.DEMO;
|
|
101
121
|
} catch {
|
|
@@ -231,8 +231,13 @@ export function withProcessCap(cmd, argv, { platform = process.platform, exists
|
|
|
231
231
|
return [PRLIMIT, [`--nproc=${n}:${n}`, '--', cmd, ...argv]];
|
|
232
232
|
}
|
|
233
233
|
|
|
234
|
-
/**
|
|
235
|
-
|
|
234
|
+
/**
|
|
235
|
+
* Công cụ bị chặn khi hết dung lượng — đọc, liệt kê, xoá vẫn chạy để người dùng tự dọn chỗ. 02/11/2026 thêm `fs.copy` (chép cả thư mục),
|
|
236
|
+
* `fs.download` (tệp lớn qua HTTP), `proc.write` (gõ tiếp vào tiến trình nền — lệnh mới có thể ghi đĩa).
|
|
237
|
+
*/
|
|
238
|
+
export const QUOTA_GUARDED_TOOLS = new Set([
|
|
239
|
+
'fs.write', 'fs.edit', 'fs.copy', 'fs.move', 'fs.move_many', 'fs.undo', 'fs.download', 'shell.exec', 'proc.start', 'proc.write',
|
|
240
|
+
]);
|
|
236
241
|
const DISK_MEASURE_MS = 60_000;
|
|
237
242
|
const DISK_RESERVE_MB = 64;
|
|
238
243
|
const DISK_WARN_RATIO = 0.9;
|
|
@@ -49,7 +49,10 @@ export function showOSNotification({ title, body, url } = {}) {
|
|
|
49
49
|
stdio: 'ignore', detached: true,
|
|
50
50
|
}).unref();
|
|
51
51
|
} else {
|
|
52
|
-
spawn(
|
|
52
|
+
// Lỗi spawn (máy không cài libnotify) là sự kiện bất đồng bộ, `try` không bắt được — không có listener là sập cả daemon.
|
|
53
|
+
const child = spawn('notify-send', ['--urgency=critical', t, m], { stdio: 'ignore', detached: true });
|
|
54
|
+
child.on('error', () => undefined);
|
|
55
|
+
child.unref();
|
|
53
56
|
}
|
|
54
57
|
} catch {
|
|
55
58
|
// best-effort
|
|
@@ -42,6 +42,12 @@ function attachments(env, list) {
|
|
|
42
42
|
return files.map((f) => resolveInRoots(env.roots, String(f)));
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
/**
|
|
46
|
+
* `save` chỉ chuyển khi nêu rõ (true / false); không nêu → host quyết theo ai mở tệp (02/11/2026): tệp AI tự mở thì lưu, tệp người dùng đang
|
|
47
|
+
* mở thì KHÔNG lưu (lưu = lưu luôn thay đổi dở của người dùng).
|
|
48
|
+
*/
|
|
49
|
+
const saveArg = (v) => (typeof v === 'boolean' ? v : undefined);
|
|
50
|
+
|
|
45
51
|
/** Công cụ Office cho danh mục của Planner — chỉ các ứng dụng máy có. */
|
|
46
52
|
export function buildOfficeTools(host, apps) {
|
|
47
53
|
const call = (op, args, ctx) => host.call('office', { ...args, op }, ctx);
|
|
@@ -53,9 +59,9 @@ export function buildOfficeTools(host, apps) {
|
|
|
53
59
|
description: 'Read cells of an Excel workbook through Excel itself (exact values, every sheet name; works on a workbook the user has open). Default: the used range of the active sheet.',
|
|
54
60
|
input_schema: schema({ path: str('workbook path'), sheet: str('sheet name, default the active sheet'), range: str('e.g. "A1:D20", default the used range'), formulas: bool('also return formulas') }, ['path']) },
|
|
55
61
|
{ name: 'office.excel.write', group: ToolGroup.OFFICE,
|
|
56
|
-
handler: async (a, c, e) => call('excel.write', { path: officePath(e, a.path, EXCEL_EXT, 'Excel'), sheet: a.sheet, cells: a.cells, range: a.range, values: a.values, create: !!a.create, save: a.save
|
|
57
|
-
description: 'Write cells through Excel: cells {"B2": value
|
|
58
|
-
input_schema: schema({ path: str('workbook path'), sheet: str('sheet name'), cells: { type: 'object', description: '{"A1": value, "C3": "=SUM(A1:A2)"}' }, range: str('top-left cell for values, e.g. "A2"'), values: { type: 'array', description: 'rows of values', items: { type: 'array' } }, create: bool('create the workbook if missing'), save: bool('save after writing
|
|
62
|
+
handler: async (a, c, e) => call('excel.write', { path: officePath(e, a.path, EXCEL_EXT, 'Excel'), sheet: a.sheet, cells: a.cells, range: a.range, values: a.values, create: !!a.create, save: saveArg(a.save), force_save: a.force_save === true, formula: a.formula === true }, c),
|
|
63
|
+
description: 'Write cells through Excel: cells {"B2": value} and/or range (top-left cell) + values (rows). Keeps formatting. Text starting with = + - @ is written as plain text unless formula is true (then "=..." becomes a formula). A workbook the AI opened is saved by default; a workbook the user already has open is edited in place and NOT saved unless save is true (result unsaved=true: tell the user to review and save). Returns the displayed text of written cells.',
|
|
64
|
+
input_schema: schema({ path: str('workbook path'), sheet: str('sheet name'), cells: { type: 'object', description: '{"A1": value, "C3": "=SUM(A1:A2)" with formula true}' }, range: str('top-left cell for values, e.g. "A2"'), values: { type: 'array', description: 'rows of values', items: { type: 'array' } }, create: bool('create the workbook if missing'), formula: bool('write "=..." text as formulas (only when the user wants formulas)'), force_save: bool('save even though the open file already had unsaved changes - only after the user confirms'), save: bool('save after writing: default true for a file the AI opens, false for a workbook the user has open (true also saves the user\'s own unsaved edits)') }, ['path']) },
|
|
59
65
|
);
|
|
60
66
|
}
|
|
61
67
|
if (apps.includes('word')) {
|
|
@@ -65,9 +71,9 @@ export function buildOfficeTools(host, apps) {
|
|
|
65
71
|
description: 'Read the full text of a Word document through Word (also .doc/.rtf; works on a document the user has open).',
|
|
66
72
|
input_schema: schema({ path: str('document path'), max_chars: num('default 20000') }, ['path']) },
|
|
67
73
|
{ name: 'office.word.edit', group: ToolGroup.OFFICE,
|
|
68
|
-
handler: async (a, c, e) => call('word.edit', { path: officePath(e, a.path, WORD_EXT, 'Word'), find: a.find, replace: a.replace, append: a.append, create: !!a.create, save: a.save
|
|
69
|
-
description: 'Edit a Word document through Word, keeping its formatting: replace every occurrence of find with replace, and/or append a paragraph at the end.
|
|
70
|
-
input_schema: schema({ path: str('document path'), find: str('exact text to replace'), replace: str('replacement text'), append: str('paragraph to add at the end'), create: bool('create the document if missing'), save: bool('default true') }, ['path']) },
|
|
74
|
+
handler: async (a, c, e) => call('word.edit', { path: officePath(e, a.path, WORD_EXT, 'Word'), find: a.find, replace: a.replace, append: a.append, create: !!a.create, save: saveArg(a.save), force_save: a.force_save === true }, c),
|
|
75
|
+
description: 'Edit a Word document through Word, keeping its formatting: replace every occurrence of find with replace, and/or append a paragraph at the end. A document the AI opened is saved by default; a document the user already has open is edited in place and NOT saved unless save is true (result unsaved=true). Returns how many were replaced.',
|
|
76
|
+
input_schema: schema({ path: str('document path'), find: str('exact text to replace'), replace: str('replacement text'), append: str('paragraph to add at the end'), create: bool('create the document if missing'), force_save: bool('save even though the open file already had unsaved changes - only after the user confirms'), save: bool('default true for a file the AI opens, false for a document the user has open') }, ['path']) },
|
|
71
77
|
);
|
|
72
78
|
}
|
|
73
79
|
if (apps.includes('outlook')) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from 'child_process';
|
|
2
2
|
import { DeviceErrorCode, ToolGroup } from './constants.mjs';
|
|
3
|
-
import { DeviceToolError, assertCommandAllowed, displayPath, resolveInRoots
|
|
3
|
+
import { DeviceToolError, agentEnv, assertCommandAllowed, displayPath, resolveInRoots } from './sandbox.mjs';
|
|
4
4
|
import { accountEnv, withProcessCap } from './multiUser.mjs';
|
|
5
5
|
import { hasPwsh } from './deviceProfile.mjs';
|
|
6
6
|
|
|
@@ -94,7 +94,7 @@ export function createProcessManager() {
|
|
|
94
94
|
let [cmd, argv] = interactive ? ['cmd.exe', ['/d', '/s', '/c', `"${command}"`]] : shellCommand(command);
|
|
95
95
|
const runAs = env.runAs;
|
|
96
96
|
if (runAs) [cmd, argv] = withProcessCap(cmd, argv);
|
|
97
|
-
const baseEnv =
|
|
97
|
+
const baseEnv = agentEnv();
|
|
98
98
|
const child = spawn(cmd, argv, {
|
|
99
99
|
cwd, env: runAs ? accountEnv(runAs, baseEnv) : baseEnv, windowsHide: true, detached: process.platform !== 'win32',
|
|
100
100
|
stdio: ['pipe', 'pipe', 'pipe'], windowsVerbatimArguments: interactive, ...(runAs ? { uid: runAs.uid, gid: runAs.gid } : {}),
|
|
@@ -107,6 +107,8 @@ export function createProcessManager() {
|
|
|
107
107
|
procs.set(id, p);
|
|
108
108
|
child.stdout.on('data', (c) => pushOutput(p, 'stdout', c));
|
|
109
109
|
child.stderr.on('data', (c) => pushOutput(p, 'stderr', c));
|
|
110
|
+
// Ghi vào stdin đã đóng (EPIPE, sau `close`): không có listener là sập cả daemon.
|
|
111
|
+
child.stdin.on('error', (e) => addLine(p, 'stderr', `Cannot write to input: ${e.message}`));
|
|
110
112
|
const finish = (code) => {
|
|
111
113
|
if (p.status !== 'running') return;
|
|
112
114
|
for (const s of ['stdout', 'stderr']) if (p.partial[s]) { addLine(p, s, p.partial[s]); p.partial[s] = ''; }
|
|
@@ -168,6 +170,7 @@ export function createProcessManager() {
|
|
|
168
170
|
if (p.status !== 'running') throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Process ${p.id} has exited`);
|
|
169
171
|
const text = String(args.text ?? '');
|
|
170
172
|
assertCommandAllowed(text);
|
|
173
|
+
if (p.child.stdin.destroyed || p.child.stdin.writableEnded) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Input of process ${p.id} is already closed`);
|
|
171
174
|
if (text) p.child.stdin.write(args.newline === false ? text : `${text}
|
|
172
175
|
`);
|
|
173
176
|
if (args.close) p.child.stdin.end();
|
|
@@ -171,6 +171,26 @@ export function scrubEnv(env = process.env) {
|
|
|
171
171
|
return out;
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
+
/**
|
|
175
|
+
* Đánh dấu tiến trình do agent chạy (`shell.exec`, `proc.start`, `agent.run`…): CLI Aivin chạy trong đó không đổi việc ghép máy / luật tại máy /
|
|
176
|
+
* công tắc ngắt (`assertHumanCommand`). Rà 02/11/2026: lệnh `aivin remote pair --code X --server URL` của agent chuyển máy sang tài khoản khác.
|
|
177
|
+
*/
|
|
178
|
+
export const AGENT_CALL_ENV = 'AIVIN_AGENT_CALL';
|
|
179
|
+
|
|
180
|
+
export function agentEnv(env = process.env) {
|
|
181
|
+
return { ...scrubEnv(env), [AGENT_CALL_ENV]: '1' };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const HUMAN_ONLY_REMOTE_COMMANDS = new Set(['start', 'pair', 'unpair', 'pause', 'resume', 'enable', 'disable', 'reset-id', 'do']);
|
|
185
|
+
const HUMAN_ONLY_COMMANDS = new Set(['do', 'login', 'logout']);
|
|
186
|
+
|
|
187
|
+
/** Lệnh chỉ người ngồi trước máy được chạy. `parent` / `name`: lệnh cha + lệnh con của CLI. */
|
|
188
|
+
export function assertHumanCommand(parent, name, env = process.env) {
|
|
189
|
+
if (env[AGENT_CALL_ENV] !== '1') return;
|
|
190
|
+
const blocked = parent === 'remote' ? HUMAN_ONLY_REMOTE_COMMANDS.has(name) : HUMAN_ONLY_COMMANDS.has(name) || HUMAN_ONLY_COMMANDS.has(parent);
|
|
191
|
+
if (blocked) throw new Error(`\`aivin ${parent === 'remote' ? 'remote ' : ''}${name}\` chỉ người ngồi trước máy mới chạy được — agent không được đổi việc ghép máy, luật tại máy hay giao việc mới.`);
|
|
192
|
+
}
|
|
193
|
+
|
|
174
194
|
/**
|
|
175
195
|
* Lưới an toàn CUỐI cho lệnh shell: chỉ chặn các lệnh phá huỷ cả hệ thống (format ổ, xoá gốc, ghi đè thiết bị, fork bomb). Đây KHÔNG
|
|
176
196
|
* phải cơ chế phân quyền — quyền nằm ở luật của agent phía BE; lưới này chỉ để một lệnh thảm hoạ không bao giờ chạy.
|
|
@@ -190,6 +210,9 @@ const CATASTROPHIC_COMMANDS = [
|
|
|
190
210
|
/** Lệnh nhắc tới thư mục cấu hình Aivin / khoá ký (`.aivin`, `.aivin-release` như một đoạn đường dẫn, hoặc đường tuyệt đối của `AIVIN_REMOTE_HOME`). */
|
|
191
211
|
const AIVIN_DIR_SEGMENT = /(?:^|[\\/\s'"`~=:(;,|&])\.aivin(?:-release)?(?=[\\/\s'"`);,|&]|$)/i;
|
|
192
212
|
|
|
213
|
+
/** Agent gọi chính CLI Aivin để đổi việc ghép máy / luật / giao việc mới. Khớp chuỗi — `assertHumanCommand` là chốt thứ hai trong tiến trình CLI. */
|
|
214
|
+
const AIVIN_SELF_COMMAND = /\baivin(\.exe)?["']?\s+(remote\s+(pair|start|unpair|pause|resume|enable|disable|reset-id|do)\b|do\b|login\b|logout\b)/i;
|
|
215
|
+
|
|
193
216
|
function mentionsProtectedDir(command) {
|
|
194
217
|
if (AIVIN_DIR_SEGMENT.test(command)) return true;
|
|
195
218
|
const lower = command.toLowerCase().replace(/\\/g, '/');
|
|
@@ -204,6 +227,9 @@ export function assertCommandAllowed(command) {
|
|
|
204
227
|
if (CATASTROPHIC_COMMANDS.some((re) => re.test(command))) {
|
|
205
228
|
throw new DeviceToolError(DeviceErrorCode.BLOCKED_COMMAND, 'Command blocked by the device safety floor (destroys the whole system)');
|
|
206
229
|
}
|
|
230
|
+
if (AIVIN_SELF_COMMAND.test(command)) {
|
|
231
|
+
throw new DeviceToolError(DeviceErrorCode.BLOCKED_COMMAND, 'Command changes this computer\'s Aivin pairing or starts new Aivin work — only the person at the computer can do that');
|
|
232
|
+
}
|
|
207
233
|
if (mentionsProtectedDir(command)) {
|
|
208
234
|
throw new DeviceToolError(DeviceErrorCode.PROTECTED_PATH, 'Command touches the Aivin credentials folder (.aivin), which is never accessible remotely');
|
|
209
235
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tệp / thư mục mang bí mật trên máy (khoá SSH, thông tin đăng nhập đám mây, `.env`, kho mật khẩu trình duyệt…). Công cụ quét cả cây thư mục
|
|
3
|
+
* (`fs.grep`, chỉ mục tệp) tự bỏ qua: đường dẫn người gọi đưa chỉ là thư mục cha nên cổng duyệt phía BE không thấy gì để hỏi (rà 02/11/2026).
|
|
4
|
+
* Đọc đúng tệp đó theo tên vẫn đi qua cổng duyệt như thường.
|
|
5
|
+
*/
|
|
6
|
+
const SECRET_PATH_PATTERNS = [
|
|
7
|
+
/(^|[\\/])\.(ssh|gnupg|aws|azure|kube|password-store)([\\/]|$)/i,
|
|
8
|
+
/(^|[\\/])\.config[\\/]gcloud([\\/]|$)/i,
|
|
9
|
+
/(^|[\\/])\.docker[\\/]config\.json$/i,
|
|
10
|
+
/(^|[\\/])\.(npmrc|pypirc|netrc|git-credentials)$/i,
|
|
11
|
+
/(^|[\\/])\.env(\.[^\\/]*)?$/i,
|
|
12
|
+
/(^|[\\/])id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
|
|
13
|
+
/\.(pem|key|p12|pfx|kdbx|keychain-db|ovpn)$/i,
|
|
14
|
+
/(^|[\\/])(login data|cookies|web data|key4\.db|logins\.json|wallet\.dat)$/i,
|
|
15
|
+
/[\\/]appdata[\\/]roaming[\\/]microsoft[\\/](credentials|protect)([\\/]|$)/i,
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
export function isSecretPath(p) {
|
|
19
|
+
const text = String(p || '');
|
|
20
|
+
return SECRET_PATH_PATTERNS.some((re) => re.test(text));
|
|
21
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { confirmTokenRotation, revertTokenRotation } from './credentials.mjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Xoay vòng token phía daemon (02/11/2026) — phần chốt / lùi tách khỏi client.mjs:
|
|
5
|
+
* - token mới lưu kèm token cũ (`previous_sealed`, credentials.mjs) tới khi máy chủ xác nhận;
|
|
6
|
+
* - máy chủ xác nhận = ack ROTATED `ok`, hoặc chào (HELLO) thành công bằng chính token mới → bỏ token cũ;
|
|
7
|
+
* - máy chủ từ chối token mới (`DEVICE_UNAUTHORIZED`) mà còn token cũ → nối lại bằng token cũ TRƯỚC khi xoá ghép máy.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Chào thành công bằng `token` → token cũ (nếu còn giữ) hết cần. Không ném. */
|
|
11
|
+
export function settleRotation(token) {
|
|
12
|
+
try { return confirmTokenRotation(token); } catch { return false; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Máy chủ từ chối token hiện hành: còn token cũ chưa bỏ → đổi `creds` + `socket.auth` sang token cũ, hẹn nối lại, trả true (người gọi KHÔNG
|
|
17
|
+
* xoá ghép máy). Không còn → false.
|
|
18
|
+
*/
|
|
19
|
+
export function fallBackToPreviousToken({ creds, socket, isStopped = () => false, delayMs = 1000, revert = revertTokenRotation }) {
|
|
20
|
+
let previous;
|
|
21
|
+
try { previous = revert(creds.device_token); } catch { previous = null; }
|
|
22
|
+
if (!previous) return false;
|
|
23
|
+
creds.device_token = previous;
|
|
24
|
+
socket.auth = { ...socket.auth, device_token: previous };
|
|
25
|
+
// Lỗi từ middleware của máy chủ: socket.io-client không tự nối lại (socket.active = false) → nối tay.
|
|
26
|
+
setTimeout(() => { if (!isStopped() && !socket.active) socket.connect(); }, delayMs);
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import os from 'os';
|
|
3
3
|
import path from 'path';
|
|
4
|
-
import readline from 'readline';
|
|
5
4
|
import { spawn } from 'child_process';
|
|
6
5
|
import { DeviceErrorCode, IGNORED_DIRS, MemoryKind, ToolGroup } from './constants.mjs';
|
|
6
|
+
import { isSecretPath } from './secretPaths.mjs';
|
|
7
7
|
import {
|
|
8
|
-
DeviceToolError, assertCommandAllowed, containsProtectedPath, displayPath, isProtectedPath, isRootPath, protectedDirNamesUnder,
|
|
8
|
+
DeviceToolError, agentEnv, assertCommandAllowed, containsProtectedPath, displayPath, isProtectedPath, isRootPath, protectedDirNamesUnder,
|
|
9
9
|
resolveEntryInRoots, resolveInRoots, scrubEnv,
|
|
10
10
|
} from './sandbox.mjs';
|
|
11
11
|
import { deleteMemoryItems, getMemoryItem, listMemoryItems, putMemoryItems, searchMemory } from './deviceMemory.mjs';
|
|
@@ -25,6 +25,7 @@ let sharedAgents = null;
|
|
|
25
25
|
import { buildScheduleTools } from './schedule.mjs';
|
|
26
26
|
import { buildWatchTools } from './deviceWatches.mjs';
|
|
27
27
|
import { buildTransferTools } from './httpTransfer.mjs';
|
|
28
|
+
import { safeGitArgv, safeGitEnv } from './gitSafe.mjs';
|
|
28
29
|
import { buildMeetingTools } from './meeting/index.mjs';
|
|
29
30
|
import { buildClipboardTools } from './clipboard.mjs';
|
|
30
31
|
|
|
@@ -51,6 +52,10 @@ const MAX_LIST_ENTRIES = 2000;
|
|
|
51
52
|
const MAX_BATCH_ITEMS = 1000;
|
|
52
53
|
const BATCH_CONCURRENCY = 8;
|
|
53
54
|
const GREP_CONCURRENCY = 16;
|
|
55
|
+
/** Lệnh thoát rồi mà ống ra còn mở (tiến trình nền giữ): chờ nốt đầu ra bấy nhiêu ms. */
|
|
56
|
+
const EXIT_DRAIN_MS = 2000;
|
|
57
|
+
/** Đã huỷ mà tiến trình chưa đóng hẳn: trả chỗ chạy lệnh sau bấy nhiêu ms. */
|
|
58
|
+
const ABORT_SETTLE_MS = 3000;
|
|
54
59
|
|
|
55
60
|
const str = (description) => ({ type: 'string', description });
|
|
56
61
|
const num = (description) => ({ type: 'number', description });
|
|
@@ -79,16 +84,39 @@ async function looksBinary(abs) {
|
|
|
79
84
|
}
|
|
80
85
|
}
|
|
81
86
|
|
|
87
|
+
/**
|
|
88
|
+
* Từng dòng của luồng, dòng dài quá `maxChars` bị cắt. Không dùng `readline`: dòng rất dài (log / JSON một dòng > 512 MB) ném `RangeError` ở
|
|
89
|
+
* nơi không bắt được, sập cả daemon (rà 02/11/2026).
|
|
90
|
+
*/
|
|
91
|
+
async function* boundedLines(stream, maxChars) {
|
|
92
|
+
let pending = '';
|
|
93
|
+
let overflowed = false;
|
|
94
|
+
for await (const chunk of stream) {
|
|
95
|
+
const parts = chunk.split('\n');
|
|
96
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
97
|
+
if (!overflowed) yield `${pending}${parts[i]}`.replace(/\r$/, '').slice(0, maxChars);
|
|
98
|
+
pending = '';
|
|
99
|
+
overflowed = false;
|
|
100
|
+
}
|
|
101
|
+
if (!overflowed) pending += parts[parts.length - 1];
|
|
102
|
+
if (pending.length > maxChars) {
|
|
103
|
+
if (!overflowed) yield pending.slice(0, maxChars);
|
|
104
|
+
pending = '';
|
|
105
|
+
overflowed = true;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (pending && !overflowed) yield pending.replace(/\r$/, '');
|
|
109
|
+
}
|
|
110
|
+
|
|
82
111
|
/** Đọc theo khoảng dòng bằng luồng — tệp lớn không phải nạp cả vào RAM. */
|
|
83
112
|
async function readLines(abs, startLine, endLine, signal) {
|
|
84
113
|
const stream = fs.createReadStream(abs, { encoding: 'utf8' });
|
|
85
|
-
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
86
114
|
const lines = [];
|
|
87
115
|
let n = 0;
|
|
88
116
|
let bytes = 0;
|
|
89
117
|
let truncatedByBytes = false;
|
|
90
118
|
try {
|
|
91
|
-
for await (const line of
|
|
119
|
+
for await (const line of boundedLines(stream, MAX_READ_BYTES + 1)) {
|
|
92
120
|
n++;
|
|
93
121
|
if (n < startLine) continue;
|
|
94
122
|
if (n > endLine) break;
|
|
@@ -98,7 +126,6 @@ async function readLines(abs, startLine, endLine, signal) {
|
|
|
98
126
|
if (signal?.aborted) break;
|
|
99
127
|
}
|
|
100
128
|
} finally {
|
|
101
|
-
rl.close();
|
|
102
129
|
stream.destroy();
|
|
103
130
|
}
|
|
104
131
|
throwIfAborted(signal);
|
|
@@ -302,7 +329,7 @@ async function fsPreview(args, ctx, env) {
|
|
|
302
329
|
function runProcess(cmd, argv, { cwd, signal, onOutput, env, maxOutput = MAX_EXEC_OUTPUT, shell = false, runAs }) {
|
|
303
330
|
return new Promise((resolve, reject) => {
|
|
304
331
|
const startedAt = Date.now();
|
|
305
|
-
const baseEnv = env ||
|
|
332
|
+
const baseEnv = env || agentEnv();
|
|
306
333
|
const account = runAs ? { uid: runAs.uid, gid: runAs.gid } : {};
|
|
307
334
|
// Thành viên máy tính tổ chức: trần số tiến trình theo uid (prlimit) — một người không fork bomb được cả container.
|
|
308
335
|
if (runAs) [cmd, argv] = withProcessCap(cmd, argv);
|
|
@@ -310,22 +337,43 @@ function runProcess(cmd, argv, { cwd, signal, onOutput, env, maxOutput = MAX_EXE
|
|
|
310
337
|
let stdout = '';
|
|
311
338
|
let stderr = '';
|
|
312
339
|
let killed = false;
|
|
340
|
+
let settled = false;
|
|
341
|
+
const timers = [];
|
|
342
|
+
// Vào `run…` một lần duy nhất: `close` bình thường, hoặc hết giờ chờ khi tiến trình cháu còn giữ ống ra (`nohup server &`, `Start-Process`).
|
|
343
|
+
const settle = (code, extra = {}) => {
|
|
344
|
+
if (settled) return;
|
|
345
|
+
settled = true;
|
|
346
|
+
timers.forEach(clearTimeout);
|
|
347
|
+
signal?.removeEventListener('abort', onAbort);
|
|
348
|
+
child.stdout.destroy();
|
|
349
|
+
child.stderr.destroy();
|
|
350
|
+
if (signal?.aborted) return reject(signal.reason || new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled'));
|
|
351
|
+
resolve({ exitCode: code ?? -1, stdout, stderr, durationMs: Date.now() - startedAt, ...extra, ...(stdout.length >= maxOutput || stderr.length >= maxOutput ? { outputTruncated: true } : {}) });
|
|
352
|
+
};
|
|
313
353
|
const killTree = () => {
|
|
314
|
-
if (killed
|
|
354
|
+
if (killed) return;
|
|
315
355
|
killed = true;
|
|
316
|
-
|
|
317
|
-
|
|
356
|
+
// Shell đã thoát mà cháu còn chạy: trên Linux / macOS vẫn giết được cả nhóm tiến trình; Windows mất dấu cây, taskkill báo lỗi vô hại.
|
|
357
|
+
if (process.platform === 'win32') { if (child.exitCode === null) spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true }).on('error', () => undefined); }
|
|
358
|
+
else { try { process.kill(-child.pid, 'SIGKILL'); } catch { try { child.kill('SIGKILL'); } catch { /* đã thoát */ } } }
|
|
359
|
+
};
|
|
360
|
+
const onAbort = () => {
|
|
361
|
+
killTree();
|
|
362
|
+
// Huỷ phải trả chỗ chạy lệnh dù cháu không chết được (trước đây giữ chỗ EXEC tới khi cháu tự thoát — 3 lệnh như vậy là kẹt mọi lệnh sau).
|
|
363
|
+
timers.push(setTimeout(() => settle(-1), ABORT_SETTLE_MS));
|
|
318
364
|
};
|
|
319
|
-
const onAbort = () => killTree();
|
|
320
365
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
321
366
|
child.stdout.on('data', (chunk) => { const t = chunk.toString(); if (stdout.length < maxOutput) stdout += t; onOutput?.('stdout', t); });
|
|
322
367
|
child.stderr.on('data', (chunk) => { const t = chunk.toString(); if (stderr.length < maxOutput) stderr += t; onOutput?.('stderr', t); });
|
|
323
|
-
child.on('error', (e) => {
|
|
324
|
-
|
|
368
|
+
child.on('error', (e) => {
|
|
369
|
+
settled = true;
|
|
370
|
+
timers.forEach(clearTimeout);
|
|
325
371
|
signal?.removeEventListener('abort', onAbort);
|
|
326
|
-
|
|
327
|
-
resolve({ exitCode: code ?? -1, stdout, stderr, durationMs: Date.now() - startedAt, ...(stdout.length >= maxOutput || stderr.length >= maxOutput ? { outputTruncated: true } : {}) });
|
|
372
|
+
reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Cannot start process: ${e.message}`));
|
|
328
373
|
});
|
|
374
|
+
// Lệnh đã xong mà tiến trình nền nó để lại còn giữ ống ra: trả kết quả, tiến trình nền chạy tiếp (đúng ý `nohup … &`).
|
|
375
|
+
child.on('exit', (code) => { timers.push(setTimeout(() => settle(code, { backgroundKept: true }), EXIT_DRAIN_MS)); });
|
|
376
|
+
child.on('close', (code) => settle(code));
|
|
329
377
|
});
|
|
330
378
|
}
|
|
331
379
|
|
|
@@ -333,6 +381,8 @@ async function fsGrep(args, ctx, env) {
|
|
|
333
381
|
const query = String(requireArg(args.query, 'query'));
|
|
334
382
|
const abs = resolveInRoots(env.roots, args.path || '');
|
|
335
383
|
const maxResults = Math.min(Number(args.maxResults) || 50, 500);
|
|
384
|
+
// Tìm từ thư mục cha không quét tệp bí mật (cổng duyệt phía BE chỉ thấy thư mục cha). Người gọi nêu đúng chỗ bí mật thì đã qua cổng duyệt.
|
|
385
|
+
const secretsAllowed = isSecretPath(abs);
|
|
336
386
|
if (env.binaries?.includes('rg')) {
|
|
337
387
|
// Loại thư mục cấu hình Aivin kể cả khi bật tìm tệp ẩn; lọc lại kết quả phía dưới phòng khi glob của người gọi lách được.
|
|
338
388
|
const exclude = protectedDirNamesUnder(abs).flatMap((name) => ['-g', `!${name}`]);
|
|
@@ -343,6 +393,7 @@ async function fsGrep(args, ctx, env) {
|
|
|
343
393
|
const matches = res.stdout.split(/\r?\n/).filter(Boolean).map((line) => {
|
|
344
394
|
const m = line.match(/^(.*?):(\d+):(.*)$/);
|
|
345
395
|
if (m && isProtectedPath(path.resolve(abs, m[1]))) return null;
|
|
396
|
+
if (m && !secretsAllowed && isSecretPath(path.resolve(abs, m[1]))) return null;
|
|
346
397
|
return m ? { path: displayPath(env.roots, m[1]), line: Number(m[2]), text: m[3].slice(0, 300) } : { text: line.slice(0, 300) };
|
|
347
398
|
}).filter(Boolean).slice(0, maxResults);
|
|
348
399
|
return { engine: 'ripgrep', total: matches.length, matches };
|
|
@@ -372,6 +423,8 @@ async function fsGrep(args, ctx, env) {
|
|
|
372
423
|
for (const e of entries) {
|
|
373
424
|
const full = path.join(dir, e.name);
|
|
374
425
|
if (isProtectedPath(full)) continue;
|
|
426
|
+
// Như ripgrep: bỏ tệp / thư mục ẩn (`.ssh`, `.aws`, `.env`…) — máy không có rg từng quét cả chúng.
|
|
427
|
+
if (!secretsAllowed && (e.name.startsWith('.') || isSecretPath(full))) continue;
|
|
375
428
|
if (e.isDirectory()) { if (!IGNORED_DIRS.has(e.name) && !e.isSymbolicLink()) queue.push(full); continue; }
|
|
376
429
|
if (e.isFile() && (!glob || glob.test(e.name))) files.push(full);
|
|
377
430
|
}
|
|
@@ -493,8 +546,18 @@ async function fsCopy(args, _ctx, env) {
|
|
|
493
546
|
const stat = await fs.promises.stat(src).catch(() => null);
|
|
494
547
|
if (!stat) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Not found: ${args.sourcePath}`);
|
|
495
548
|
if (path.resolve(src) === path.resolve(dest)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Source and destination are the same');
|
|
549
|
+
// Chép một thư mục BAO TRỌN `.aivin` (vd cả thư mục nhà) là đưa token / khoá ký / cookie ra chỗ đọc được — như fs.move / fs.delete.
|
|
550
|
+
if (containsProtectedPath(src)) throw new DeviceToolError(DeviceErrorCode.PROTECTED_PATH, 'Folder holds Aivin credentials and cannot be copied remotely');
|
|
551
|
+
// Đích bị XOÁ trước khi chép khi `overwrite`: đích là gốc được phép / thư mục chứa `.aivin` / thư mục chứa nguồn thì mất cả cây (rà 02/11/2026:
|
|
552
|
+
// chép `a.txt` vào `.` xoá sạch thư mục được phép).
|
|
553
|
+
if (isRootPath(env.roots, dest)) throw new DeviceToolError(DeviceErrorCode.ROOT_DENIED, 'Refusing to replace an allowed root folder');
|
|
554
|
+
if (containsProtectedPath(dest)) throw new DeviceToolError(DeviceErrorCode.PROTECTED_PATH, 'Folder holds Aivin credentials and cannot be replaced remotely');
|
|
555
|
+
const relToDest = path.relative(dest, src);
|
|
556
|
+
if (relToDest && !relToDest.startsWith('..') && !path.isAbsolute(relToDest)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Destination contains the source — copy into a new path inside it instead');
|
|
496
557
|
const exists = fs.existsSync(dest);
|
|
497
558
|
if (exists && args.overwrite !== true) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Destination exists (set overwrite to replace it): ${args.destinationPath}`);
|
|
559
|
+
// Không hiểu kiểu `cp`: chép TỆP vào thư mục có sẵn không được thay cả thư mục đó.
|
|
560
|
+
if (exists && !stat.isDirectory() && fs.statSync(dest).isDirectory()) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Destination is a folder — give the full file path inside it: ${args.destinationPath}`);
|
|
498
561
|
const undo = undoOf(args, env, 'copy');
|
|
499
562
|
try {
|
|
500
563
|
if (undo) await undo.ensureDir(path.dirname(dest));
|
|
@@ -624,9 +687,10 @@ async function systemInfo(_args, _ctx, env) {
|
|
|
624
687
|
};
|
|
625
688
|
}
|
|
626
689
|
|
|
690
|
+
/** git chỉ đọc — không để cấu hình / hook / biến môi trường của kho chạy chương trình (gitSafe.mjs, 02/11/2026). */
|
|
627
691
|
async function git(argv, args, ctx, env) {
|
|
628
692
|
const cwd = resolveInRoots(env.roots, args.path || '');
|
|
629
|
-
const res = await runProcess('git',
|
|
693
|
+
const res = await runProcess('git', safeGitArgv(cwd, argv), { cwd, signal: ctx.signal, maxOutput: 512 * 1024, runAs: env.runAs, env: safeGitEnv(scrubEnv()) });
|
|
630
694
|
return { cwd: displayPath(env.roots, cwd), ...res };
|
|
631
695
|
}
|
|
632
696
|
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gom sự kiện của bộ theo dõi tệp thành lô (02/11/2026). Trước đây chỉ debounce: tệp bị ghi liên tục (log, bản build, đồng bộ đám mây) đẩy
|
|
3
|
+
* hẹn giờ lùi mãi → lô không bao giờ chạy, còn tập `pending` phình không giới hạn trong RAM.
|
|
4
|
+
* - `debounceMs`: chờ yên chừng này rồi chạy;
|
|
5
|
+
* - `maxWaitMs`: kể từ sự kiện đầu của lô, chạy chậm nhất sau chừng này dù sự kiện còn dồn tới;
|
|
6
|
+
* - `maxPending`: quá chừng này đường dẫn khác nhau → bỏ danh sách, chạy `onOverflow` (quét lại tăng dần cả cây) thay vì `onBatch`.
|
|
7
|
+
* `onBatch(paths)` / `onOverflow()` có thể async; lô chạy tuần tự (lô sau chờ lô trước xong).
|
|
8
|
+
*/
|
|
9
|
+
export function createWatchBatcher({ debounceMs = 800, maxWaitMs = 5_000, maxPending = 5_000, onBatch, onOverflow, now = Date.now } = {}) {
|
|
10
|
+
const pending = new Set();
|
|
11
|
+
let overflow = false;
|
|
12
|
+
let firstAt = 0;
|
|
13
|
+
let timer = null;
|
|
14
|
+
let chain = Promise.resolve();
|
|
15
|
+
|
|
16
|
+
const run = () => {
|
|
17
|
+
timer = null;
|
|
18
|
+
firstAt = 0;
|
|
19
|
+
const batch = [...pending];
|
|
20
|
+
const full = overflow;
|
|
21
|
+
pending.clear();
|
|
22
|
+
overflow = false;
|
|
23
|
+
chain = chain.then(() => (full ? onOverflow?.() : batch.length ? onBatch?.(batch) : undefined)).catch(() => undefined);
|
|
24
|
+
return chain;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
add(abs) {
|
|
29
|
+
if (!overflow) {
|
|
30
|
+
pending.add(abs);
|
|
31
|
+
if (pending.size > maxPending) {
|
|
32
|
+
pending.clear();
|
|
33
|
+
overflow = true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const t = now();
|
|
37
|
+
if (!firstAt) firstAt = t;
|
|
38
|
+
if (timer) clearTimeout(timer);
|
|
39
|
+
const wait = Math.max(0, Math.min(debounceMs, firstAt + maxWaitMs - t));
|
|
40
|
+
timer = setTimeout(run, wait);
|
|
41
|
+
timer.unref?.();
|
|
42
|
+
},
|
|
43
|
+
/** Chạy ngay lô đang chờ (test / đóng). */
|
|
44
|
+
flushNow() {
|
|
45
|
+
if (timer) clearTimeout(timer);
|
|
46
|
+
return run();
|
|
47
|
+
},
|
|
48
|
+
size: () => pending.size,
|
|
49
|
+
overflowed: () => overflow,
|
|
50
|
+
close() {
|
|
51
|
+
if (timer) clearTimeout(timer);
|
|
52
|
+
timer = null;
|
|
53
|
+
pending.clear();
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
package/bin/lib/selfUpdate.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
} from './update/constants.mjs';
|
|
8
8
|
import { replaceBinary } from './update/binarySwap.mjs';
|
|
9
9
|
import { downloadRelease, downloadRoot, fetchLatestVersion, fetchRollout, verifyStarts } from './update/download.mjs';
|
|
10
|
-
import { loadUpdateSettings, recordInstalled, withUpdateLock } from './update/state.mjs';
|
|
10
|
+
import { diskAheadOfRunning, loadUpdateSettings, recordInstalled, withUpdateLock } from './update/state.mjs';
|
|
11
11
|
import { compareVersions, currentCliVersion, isStandaloneBinary, parseVersion, releaseAsset, rolloutBucket, tagOf, versionList } from './update/versions.mjs';
|
|
12
12
|
|
|
13
13
|
/**
|
|
@@ -44,6 +44,12 @@ export async function installUpdate({
|
|
|
44
44
|
const result = { current: tagOf(current), latest };
|
|
45
45
|
if (!force && compareVersions(latest, current) <= 0) return { ...result, status: UpdateStatus.UP_TO_DATE };
|
|
46
46
|
if (!binary) return { ...result, status: UpdateStatus.NOT_BINARY };
|
|
47
|
+
// Đĩa đã có đúng bản này (hoặc mới hơn) chờ khởi động lại → không tải / cài lại (02/11/2026: cài lại từng đè `.prev` bằng bản chưa chạy).
|
|
48
|
+
const alreadyOnDisk = () => {
|
|
49
|
+
const onDisk = diskAheadOfRunning({ target, current, file: markerFile });
|
|
50
|
+
return !force && onDisk && compareVersions(onDisk, latest) >= 0 ? { ...result, status: UpdateStatus.INSTALLED, already: true } : null;
|
|
51
|
+
};
|
|
52
|
+
if (alreadyOnDisk()) return alreadyOnDisk();
|
|
47
53
|
if (!version && loadUpdateSettings(settingsFile).skip.includes(latest)) return { ...result, status: UpdateStatus.SKIPPED };
|
|
48
54
|
if (!version && versionList(holdVersions).includes(latest)) return { ...result, status: UpdateStatus.HELD };
|
|
49
55
|
if (check) return { ...result, status: UpdateStatus.AVAILABLE };
|
|
@@ -52,13 +58,17 @@ export async function installUpdate({
|
|
|
52
58
|
if (rollout && rollout.version === latest && rolloutBucket(deviceId, latest) >= rollout.percent) return { ...result, status: UpdateStatus.DEFERRED };
|
|
53
59
|
}
|
|
54
60
|
return withUpdateLock(async () => {
|
|
61
|
+
// Cửa sổ khác vừa cài xong trong lúc chờ khoá.
|
|
62
|
+
const done = alreadyOnDisk();
|
|
63
|
+
if (done) return done;
|
|
55
64
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'aivin-update-'));
|
|
56
65
|
try {
|
|
57
66
|
const file = await downloadRelease({ root, version: latest, asset: releaseAsset(), destDir: tmp, signal, keys });
|
|
58
67
|
await verify(file, latest);
|
|
59
68
|
let backup;
|
|
60
69
|
try {
|
|
61
|
-
|
|
70
|
+
// Tệp trên đĩa là bản chưa từng chạy → `.prev` (bản đang chạy) giữ nguyên làm chỗ tự lùi.
|
|
71
|
+
backup = replaceBinary({ newFile: file, target, keepBackup: !!diskAheadOfRunning({ target, current, file: markerFile }) });
|
|
62
72
|
} catch (e) {
|
|
63
73
|
throw new Error(`Không thay được ${target} (${e?.code || e?.message}) — cài lại bằng bộ cài: https://get.aivin.vn`, { cause: e });
|
|
64
74
|
}
|
|
@@ -16,8 +16,22 @@ export function retire(file) {
|
|
|
16
16
|
* Thay tệp chạy, giữ bản cũ ở `<tệp>.prev`. Windows: đổi tên bản đang chạy thành `.prev` rồi chép bản mới (chép hỏng thì trả tên cũ lại).
|
|
17
17
|
* macOS / Linux: chép bản cũ ra `.prev`, chép bản mới cạnh bên rồi đổi tên nguyên khối. Trả đường dẫn bản cũ (null nếu chưa có).
|
|
18
18
|
*/
|
|
19
|
-
export function replaceBinary({ newFile, target, platform = process.platform }) {
|
|
19
|
+
export function replaceBinary({ newFile, target, platform = process.platform, keepBackup = false }) {
|
|
20
20
|
const backup = `${target}.prev`;
|
|
21
|
+
// Tệp trên đĩa là bản mới CHƯA từng chạy (đã cài, chờ khởi động lại) → `.prev` đang là bản đang chạy / đã chạy ổn: giữ nguyên, chỉ thay
|
|
22
|
+
// tệp chạy (02/11/2026 — trước đây cài lần hai đè `.prev` bằng bản chưa kiểm, Windows còn dời chính tệp đang chạy vào `.trash`).
|
|
23
|
+
if (keepBackup && fs.existsSync(backup)) {
|
|
24
|
+
const staged = `${target}.new`;
|
|
25
|
+
fs.copyFileSync(newFile, staged);
|
|
26
|
+
if (platform !== 'win32') fs.chmodSync(staged, 0o755);
|
|
27
|
+
try {
|
|
28
|
+
fs.renameSync(staged, target);
|
|
29
|
+
} catch (e) {
|
|
30
|
+
fs.rmSync(staged, { force: true });
|
|
31
|
+
throw e;
|
|
32
|
+
}
|
|
33
|
+
return backup;
|
|
34
|
+
}
|
|
21
35
|
if (fs.existsSync(backup)) retire(backup);
|
|
22
36
|
const had = fs.existsSync(target);
|
|
23
37
|
if (platform === 'win32') {
|
package/bin/lib/update/state.mjs
CHANGED
|
@@ -81,6 +81,16 @@ export function installedNewerThanRunning({ target = process.execPath, current =
|
|
|
81
81
|
return loadUpdateSettings(settingsFile).skip.includes(tagOf(marker.version)) ? null : tagOf(marker.version);
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
/**
|
|
85
|
+
* Đĩa đang giữ một bản ĐÃ CÀI mà chưa chạy (mới hơn bản đang chạy, đúng tệp chạy này) — kể cả bản nằm trong danh sách bỏ qua. Trả phiên
|
|
86
|
+
* bản hoặc null. Dùng để không cài chồng / không đè `.prev` (02/11/2026).
|
|
87
|
+
*/
|
|
88
|
+
export function diskAheadOfRunning({ target = process.execPath, current = currentCliVersion(), file = UPDATE_INSTALLED_FILE } = {}) {
|
|
89
|
+
const marker = readInstalledMarker(file);
|
|
90
|
+
if (!marker || !samePath(marker.path, target) || compareVersions(marker.version, current) <= 0) return null;
|
|
91
|
+
return tagOf(marker.version);
|
|
92
|
+
}
|
|
93
|
+
|
|
84
94
|
/** 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
95
|
export function clearStaleInstalledMarker({ target = process.execPath, file = UPDATE_INSTALLED_FILE } = {}) {
|
|
86
96
|
const marker = readInstalledMarker(file);
|