@aivin-labs/cli 1.0.11 → 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 -288
- package/bin/cli.mjs +163 -17
- 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/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- 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 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- 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 +331 -52
- 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 +648 -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/osSearch.mjs +107 -0
- 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/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- 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/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -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')) {
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { execFile } from 'child_process';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { isProtectedPath } from './sandbox.mjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Tìm tệp qua bộ tìm của hệ điều hành — cho những gì chỉ mục của Aivin cố ý bỏ (thư mục gộp, kho code, ổ khác ngoài thư mục nhà…): Windows
|
|
8
|
+
* Search (SystemIndex), macOS Spotlight (`mdfind`), Linux `plocate` / `locate`. Không dựng gì thêm trên máy; hệ điều hành không có / tắt bộ
|
|
9
|
+
* tìm → trả rỗng. Kết quả luôn lọc lại theo gốc được phép + vùng cấm (bộ tìm của hệ điều hành không biết sàn của Aivin).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const MAX_WORDS = 6;
|
|
13
|
+
const DEFAULT_TIMEOUT_MS = 4000;
|
|
14
|
+
|
|
15
|
+
const wordsOf = (query) => [...new Set(String(query || '').split(/[^\p{L}\p{N}]+/u).filter((w) => w.length >= 2))].slice(0, MAX_WORDS);
|
|
16
|
+
|
|
17
|
+
function run(cmd, args, { env, timeoutMs }) {
|
|
18
|
+
return new Promise((resolve) => {
|
|
19
|
+
execFile(cmd, args, { env: { ...process.env, ...env }, windowsHide: true, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024, encoding: 'utf8' },
|
|
20
|
+
(_err, stdout) => resolve(String(stdout || '')));
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Câu SQL cho Windows Search: mọi từ đều phải khớp tên tệp hoặc nội dung đã được Windows lập chỉ mục; chỉ trong các gốc. */
|
|
25
|
+
export function windowsSearchSql(words, roots, limit) {
|
|
26
|
+
const scope = roots.map((r) => `SCOPE='file:${r.replace(/\\/g, '/').replace(/'/g, "''")}'`).join(' OR ');
|
|
27
|
+
const cond = words.map((w) => `(System.FileName LIKE '%${w}%' OR CONTAINS(*, '"${w}*"'))`).join(' AND ');
|
|
28
|
+
return `SELECT TOP ${limit} System.ItemPathDisplay, System.Size, System.DateModified FROM SystemIndex WHERE (${scope}) AND ${cond} ORDER BY System.Search.Rank DESC`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const WINDOWS_SCRIPT = `
|
|
32
|
+
$ErrorActionPreference = 'Stop'
|
|
33
|
+
[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
|
34
|
+
$c = New-Object -ComObject ADODB.Connection
|
|
35
|
+
$c.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")
|
|
36
|
+
$rs = New-Object -ComObject ADODB.Recordset
|
|
37
|
+
$rs.Open($env:AIVIN_OS_SQL, $c)
|
|
38
|
+
while (-not $rs.EOF) {
|
|
39
|
+
$m = $rs.Fields.Item('System.DateModified').Value
|
|
40
|
+
$d = if ($m -is [datetime]) { $m.ToString('yyyy-MM-dd') } else { '' }
|
|
41
|
+
[Console]::Out.WriteLine([string]$rs.Fields.Item('System.ItemPathDisplay').Value + [char]9 + [string]$rs.Fields.Item('System.Size').Value + [char]9 + $d)
|
|
42
|
+
$rs.MoveNext()
|
|
43
|
+
}
|
|
44
|
+
`;
|
|
45
|
+
|
|
46
|
+
async function searchWindows(words, roots, limit, timeoutMs, exec) {
|
|
47
|
+
const out = await exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_SCRIPT], {
|
|
48
|
+
env: { AIVIN_OS_SQL: windowsSearchSql(words, roots, limit) }, timeoutMs,
|
|
49
|
+
});
|
|
50
|
+
return out.split(/\r?\n/).filter(Boolean).map((line) => {
|
|
51
|
+
const [abs, size, modified] = line.split('\t');
|
|
52
|
+
return { abs, size: size ? Number(size) : undefined, modified: modified || undefined };
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function searchMac(words, roots, limit, timeoutMs, exec) {
|
|
57
|
+
const lists = await Promise.all(roots.map((r) => exec('mdfind', ['-onlyin', r, words.join(' ')], { timeoutMs })));
|
|
58
|
+
return lists.flatMap((o) => o.split('\n')).filter(Boolean).slice(0, limit * 3).map((abs) => ({ abs }));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function searchLinux(words, limit, timeoutMs, exec) {
|
|
62
|
+
for (const cmd of ['plocate', 'locate']) {
|
|
63
|
+
const out = await exec(cmd, ['-i', '-l', String(limit * 20), words[0]], { timeoutMs });
|
|
64
|
+
if (out) return out.split('\n').filter(Boolean).map((abs) => ({ abs }));
|
|
65
|
+
}
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const inRoots = (abs, roots) => roots.some((r) => {
|
|
70
|
+
const rel = path.relative(r, abs);
|
|
71
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Tìm `query` qua bộ tìm của hệ điều hành trong `roots` → `[{ abs, size?, modified? }]` (tối đa `limit`). Lỗi / hết giờ / không có bộ tìm →
|
|
76
|
+
* mảng rỗng (không bao giờ ném lỗi).
|
|
77
|
+
*/
|
|
78
|
+
export async function osFileSearch(query, { roots, limit = 10, timeoutMs = DEFAULT_TIMEOUT_MS, platform = process.platform, exec = run } = {}) {
|
|
79
|
+
const words = wordsOf(query);
|
|
80
|
+
if (!words.length || !roots?.length) return [];
|
|
81
|
+
const resolved = roots.map((r) => path.resolve(r));
|
|
82
|
+
let found;
|
|
83
|
+
try {
|
|
84
|
+
if (platform === 'win32') found = await searchWindows(words, resolved, limit * 2, timeoutMs, exec);
|
|
85
|
+
else if (platform === 'darwin') found = await searchMac(words, resolved, limit, timeoutMs, exec);
|
|
86
|
+
else found = await searchLinux(words, limit, timeoutMs, exec);
|
|
87
|
+
} catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
const lower = words.map((w) => w.toLowerCase());
|
|
91
|
+
const out = [];
|
|
92
|
+
for (const hit of found) {
|
|
93
|
+
if (out.length >= limit) break;
|
|
94
|
+
if (!hit.abs || !path.isAbsolute(hit.abs) || !inRoots(hit.abs, resolved) || isProtectedPath(hit.abs)) continue;
|
|
95
|
+
// locate chỉ lọc được theo một từ — các từ còn lại khớp trên đường dẫn.
|
|
96
|
+
if (platform === 'linux' && !lower.every((w) => hit.abs.toLowerCase().includes(w))) continue;
|
|
97
|
+
if (hit.size === undefined) {
|
|
98
|
+
try {
|
|
99
|
+
const st = fs.statSync(hit.abs);
|
|
100
|
+
hit.size = st.isFile() ? st.size : undefined;
|
|
101
|
+
hit.modified = new Date(st.mtimeMs).toISOString().slice(0, 10);
|
|
102
|
+
} catch { continue; }
|
|
103
|
+
}
|
|
104
|
+
out.push(hit);
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
@@ -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,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQLite có sẵn trong runtime, không thêm gói: `bun:sqlite` (bản aivin.exe đóng gói bằng Bun) hoặc `node:sqlite` (chạy từ npm / mã nguồn,
|
|
3
|
+
* Node ≥ 22.13). Nạp lúc cần (import động) — Node cũ hơn vẫn chạy được phần còn lại của CLI. Trả một lớp mỏng chung: `exec`, `prepare`
|
|
4
|
+
* (`run` / `get` / `all`, tham số theo vị trí), `transaction`, `close`.
|
|
5
|
+
*/
|
|
6
|
+
export async function openSqlite(file) {
|
|
7
|
+
if (globalThis.Bun) {
|
|
8
|
+
const { Database } = await import('bun:sqlite');
|
|
9
|
+
return wrap(new Database(file, { create: true }));
|
|
10
|
+
}
|
|
11
|
+
// node:sqlite còn gắn nhãn thử nghiệm: bỏ đúng cảnh báo đó, không để nó lẫn vào đầu ra của CLI.
|
|
12
|
+
const emit = process.emitWarning;
|
|
13
|
+
process.emitWarning = (warning, ...rest) => {
|
|
14
|
+
if (/SQLite/i.test(String(warning?.message ?? warning))) return;
|
|
15
|
+
emit.call(process, warning, ...rest);
|
|
16
|
+
};
|
|
17
|
+
try {
|
|
18
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
19
|
+
return wrap(new DatabaseSync(file));
|
|
20
|
+
} finally {
|
|
21
|
+
process.emitWarning = emit;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function wrap(db) {
|
|
26
|
+
const prepare = (sql) => {
|
|
27
|
+
const st = db.prepare(sql);
|
|
28
|
+
return {
|
|
29
|
+
run: (...args) => st.run(...args),
|
|
30
|
+
get: (...args) => st.get(...args) ?? undefined,
|
|
31
|
+
all: (...args) => st.all(...args),
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
exec: (sql) => db.exec(sql),
|
|
36
|
+
prepare,
|
|
37
|
+
/** Chạy `fn` trong một giao dịch (lỗi → huỷ cả khối). */
|
|
38
|
+
transaction(fn) {
|
|
39
|
+
db.exec('BEGIN');
|
|
40
|
+
try {
|
|
41
|
+
const out = fn();
|
|
42
|
+
db.exec('COMMIT');
|
|
43
|
+
return out;
|
|
44
|
+
} catch (e) {
|
|
45
|
+
db.exec('ROLLBACK');
|
|
46
|
+
throw e;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
close: () => db.close(),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -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
|
+
}
|