@aivin-labs/cli 1.0.5 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +263 -216
  2. package/bin/cli.mjs +1780 -1366
  3. package/bin/lib/browserAutomation.mjs +655 -648
  4. package/bin/lib/browserTui.mjs +276 -251
  5. package/bin/lib/cancellation.mjs +61 -0
  6. package/bin/lib/mcpProxy.mjs +869 -837
  7. package/bin/lib/missionStream.mjs +696 -691
  8. package/bin/lib/releaseKeys.mjs +9 -0
  9. package/bin/lib/remote/activityLog.mjs +68 -0
  10. package/bin/lib/remote/autoStart.mjs +457 -0
  11. package/bin/lib/remote/autoUpdate.mjs +129 -0
  12. package/bin/lib/remote/brand.mjs +60 -0
  13. package/bin/lib/remote/browserTunnel.mjs +292 -0
  14. package/bin/lib/remote/callLedger.mjs +134 -0
  15. package/bin/lib/remote/cdpPolicy.mjs +66 -0
  16. package/bin/lib/remote/client.mjs +726 -0
  17. package/bin/lib/remote/constants.mjs +173 -0
  18. package/bin/lib/remote/credentials.mjs +208 -0
  19. package/bin/lib/remote/daemonLock.mjs +86 -0
  20. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  21. package/bin/lib/remote/deviceMemory.mjs +246 -0
  22. package/bin/lib/remote/deviceProfile.mjs +142 -0
  23. package/bin/lib/remote/deviceWatches.mjs +138 -0
  24. package/bin/lib/remote/docText.mjs +117 -0
  25. package/bin/lib/remote/fileIndexer.mjs +399 -0
  26. package/bin/lib/remote/gui/index.mjs +245 -0
  27. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  28. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  29. package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
  30. package/bin/lib/remote/httpTransfer.mjs +89 -0
  31. package/bin/lib/remote/idempotency.mjs +135 -0
  32. package/bin/lib/remote/keepAwake.mjs +100 -0
  33. package/bin/lib/remote/localConfirm.mjs +268 -0
  34. package/bin/lib/remote/localPolicy.mjs +249 -0
  35. package/bin/lib/remote/mascot/assets.mjs +218 -0
  36. package/bin/lib/remote/mascot/hostSource.mjs +362 -0
  37. package/bin/lib/remote/mascot/index.mjs +322 -0
  38. package/bin/lib/remote/mascot/labels.mjs +83 -0
  39. package/bin/lib/remote/mascot/strings.mjs +189 -0
  40. package/bin/lib/remote/memberFsPool.mjs +134 -0
  41. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  42. package/bin/lib/remote/mission.mjs +156 -0
  43. package/bin/lib/remote/missionQuestion.mjs +63 -0
  44. package/bin/lib/remote/multiUser.mjs +344 -0
  45. package/bin/lib/remote/netProxy.mjs +145 -0
  46. package/bin/lib/remote/notify.mjs +58 -0
  47. package/bin/lib/remote/office/index.mjs +90 -0
  48. package/bin/lib/remote/policyCommand.mjs +93 -0
  49. package/bin/lib/remote/processes.mjs +217 -0
  50. package/bin/lib/remote/sandbox.mjs +221 -0
  51. package/bin/lib/remote/schedule.mjs +213 -0
  52. package/bin/lib/remote/scheduler.mjs +124 -0
  53. package/bin/lib/remote/textIndex.mjs +131 -0
  54. package/bin/lib/remote/tokenStore.mjs +77 -0
  55. package/bin/lib/remote/toolHandlers.mjs +726 -0
  56. package/bin/lib/remote/undoStore.mjs +242 -0
  57. package/bin/lib/remoteControl.mjs +26 -0
  58. package/bin/lib/scaffold.mjs +654 -653
  59. package/bin/lib/selfUpdate.mjs +71 -0
  60. package/bin/lib/update/binarySwap.mjs +63 -0
  61. package/bin/lib/update/constants.mjs +56 -0
  62. package/bin/lib/update/download.mjs +145 -0
  63. package/bin/lib/update/signature.mjs +42 -0
  64. package/bin/lib/update/state.mjs +205 -0
  65. package/bin/lib/update/versions.mjs +60 -0
  66. package/docs/CLI.md +1353 -1299
  67. package/package.json +71 -62
@@ -0,0 +1,93 @@
1
+ import chalk from 'chalk';
2
+ import readline from 'readline/promises';
3
+ import { CONFIRM_RANK, ConfirmMode, DEFAULT_LOCAL_POLICY, REMOTE_POLICY_FILE, saveLocalPolicy, stricterPolicy, verifyLocalPolicy } from './localPolicy.mjs';
4
+
5
+ /**
6
+ * `aivin remote policy [hành động] [giá trị]` — chủ máy đặt sàn luật tại máy (localPolicy.mjs). Siết luật chạy ngay; NỚI luật (bớt xác
7
+ * nhận, bật lại công cụ, bỏ chặn lệnh) phải gõ trong terminal thật và trả lời "có": lệnh shell do agent chạy không có terminal, nên agent
8
+ * không tự nới được luật của máy.
9
+ */
10
+
11
+ const CONFIRM_TEXT = {
12
+ [ConfirmMode.RISKY]: 'việc rủi ro (lệnh đổi hệ thống / bảo mật, xoá hẳn, gửi thư, đặt lịch) phải bấm "Cho phép" trên máy',
13
+ [ConfirmMode.ALWAYS]: 'MỌI việc có tác dụng phải bấm "Cho phép" trên máy',
14
+ [ConfirmMode.NEVER]: 'không hỏi trên máy — chỉ theo luật phía Aivin',
15
+ };
16
+
17
+ function show(policy) {
18
+ console.log(chalk.blue('🛡️ Luật tại máy này') + chalk.gray(` (${REMOTE_POLICY_FILE})`));
19
+ console.log(` Xác nhận trên máy: ${chalk.cyan(policy.confirm)} — ${CONFIRM_TEXT[policy.confirm]} (chờ tối đa ${policy.confirm_timeout_sec} s)`);
20
+ console.log(` Công cụ tắt: ${policy.deny_tools.length ? policy.deny_tools.join(', ') : chalk.gray('không')}`);
21
+ console.log(` Lệnh chặn thêm: ${policy.blocked_commands.length ? policy.blocked_commands.map((r) => `/${r}/`).join(' ') : chalk.gray('không')}`);
22
+ console.log(chalk.gray(' Đổi: aivin remote policy confirm <never|risky|always> · deny|allow <công cụ> · block|unblock "<regex>" · timeout <giây>'));
23
+ }
24
+
25
+ /** Nới luật: chỉ người gõ trong terminal thật, và phải trả lời "có". */
26
+ async function assertHumanLoosening(what) {
27
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
28
+ throw new Error(`Nới luật tại máy (${what}) chỉ làm được khi gõ lệnh trong cửa sổ terminal — lệnh do agent chạy không được nới luật.`);
29
+ }
30
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
31
+ try {
32
+ const answer = await rl.question(chalk.yellow(`⚠️ ${what}. Gõ "co" để đồng ý: `));
33
+ if (!/^\s*(co|có|yes|y)\s*$/i.test(answer)) throw new Error('Đã huỷ — luật giữ nguyên.');
34
+ } finally {
35
+ rl.close();
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Luật làm gốc để đổi: tệp có chữ ký đúng → nguyên văn. Tệp bị sửa ngoài lệnh này (không ký / ký sai) → không lấy phần NỚI trong đó làm gốc
41
+ * (không thì lần siết kế tiếp ký luôn phần agent tự nới): lấy bản chặt hơn của mặc định và tệp.
42
+ */
43
+ function basePolicy() {
44
+ const { policy, trusted, base } = verifyLocalPolicy();
45
+ if (trusted) return policy;
46
+ console.log(chalk.yellow('⚠️ Tệp luật bị sửa ngoài lệnh `aivin remote policy` (chữ ký không khớp) — máy chỉ áp phần siết thêm. Lưu lại bằng lệnh này để ký lại.'));
47
+ return stricterPolicy(base || { ...DEFAULT_LOCAL_POLICY, deny_tools: [], blocked_commands: [] }, policy);
48
+ }
49
+
50
+ export async function runPolicyCommand(action, value) {
51
+ const policy = basePolicy();
52
+ if (!action) return show(policy);
53
+ const v = String(value ?? '').trim();
54
+ const next = { ...policy, deny_tools: [...policy.deny_tools], blocked_commands: [...policy.blocked_commands] };
55
+ switch (action) {
56
+ case 'confirm': {
57
+ if (!(v in CONFIRM_RANK)) throw new Error('Dùng: aivin remote policy confirm <never|risky|always>');
58
+ if (CONFIRM_RANK[v] < CONFIRM_RANK[policy.confirm]) await assertHumanLoosening(`Giảm xác nhận trên máy từ "${policy.confirm}" xuống "${v}"`);
59
+ next.confirm = v;
60
+ break;
61
+ }
62
+ case 'deny':
63
+ if (!v) throw new Error('Dùng: aivin remote policy deny <tên công cụ> (vd shell.exec, office.outlook.send, gui.act)');
64
+ if (!next.deny_tools.includes(v)) next.deny_tools.push(v);
65
+ break;
66
+ case 'allow':
67
+ if (!next.deny_tools.includes(v)) throw new Error(`Công cụ ${v || '?'} đang không bị tắt.`);
68
+ await assertHumanLoosening(`Bật lại công cụ ${v} cho agent trên máy này`);
69
+ next.deny_tools = next.deny_tools.filter((t) => t !== v);
70
+ break;
71
+ case 'block':
72
+ try { new RegExp(v, 'i'); } catch { throw new Error(`Regex không hợp lệ: ${v}`); }
73
+ if (!v) throw new Error('Dùng: aivin remote policy block "<regex>" (vd "\\bgit\\s+push\\b")');
74
+ if (!next.blocked_commands.includes(v)) next.blocked_commands.push(v);
75
+ break;
76
+ case 'unblock':
77
+ if (!next.blocked_commands.includes(v)) throw new Error(`Không có luật chặn /${v}/.`);
78
+ await assertHumanLoosening(`Bỏ luật chặn lệnh /${v}/`);
79
+ next.blocked_commands = next.blocked_commands.filter((r) => r !== v);
80
+ break;
81
+ case 'timeout': {
82
+ const sec = Number(v);
83
+ if (!Number.isFinite(sec) || sec < 15 || sec > 900) throw new Error('Dùng: aivin remote policy timeout <15–900 giây>');
84
+ next.confirm_timeout_sec = Math.round(sec);
85
+ break;
86
+ }
87
+ default:
88
+ throw new Error(`Không hiểu "${action}". Dùng: confirm | deny | allow | block | unblock | timeout`);
89
+ }
90
+ const saved = saveLocalPolicy(next);
91
+ console.log(chalk.green('✅ Đã lưu — có hiệu lực ngay (công cụ tắt / bật lại vào danh mục ở lần khởi động daemon kế tiếp).'));
92
+ show(saved);
93
+ }
@@ -0,0 +1,217 @@
1
+ import { spawn } from 'child_process';
2
+ import { DeviceErrorCode, ToolGroup } from './constants.mjs';
3
+ import { DeviceToolError, assertCommandAllowed, displayPath, resolveInRoots, scrubEnv } from './sandbox.mjs';
4
+ import { accountEnv, withProcessCap } from './multiUser.mjs';
5
+ import { hasPwsh } from './deviceProfile.mjs';
6
+
7
+ /**
8
+ * Tiến trình nền + đọc log thời gian thực (28/10/2026): `proc.start` chạy lệnh dài (dev server, build / test watch, `claude -p …`, tail log)
9
+ * KHÔNG giữ vòng Planner; `proc.wait_for` chờ tới khi một dòng khớp mẫu ("ready", "error", "compiled") hoặc tiến trình thoát; `proc.read`
10
+ * đọc phần log mới theo con trỏ; `proc.stop` dừng cả cây tiến trình. Lệnh đi qua cùng sàn với `shell.exec` (chặn `.aivin`, lọc bí mật
11
+ * khỏi biến môi trường, thư mục trong vùng được phép, máy tính tổ chức chạy dưới tài khoản thành viên).
12
+ */
13
+
14
+ const MAX_PROCS = 8;
15
+ const MAX_LINES = 5000;
16
+ const MAX_LINE_CHARS = 2000;
17
+ const DEFAULT_READ_LINES = 200;
18
+ const MAX_WAIT_MS = 10 * 60_000;
19
+ /** Tiến trình đã thoát giữ log bấy nhiêu lâu rồi bỏ. */
20
+ const KEEP_EXITED_MS = 30 * 60_000;
21
+
22
+ const str = (description) => ({ type: 'string', description });
23
+ const num = (description) => ({ type: 'number', description });
24
+ const schema = (properties, required = []) => ({ type: 'object', properties, required });
25
+
26
+ /**
27
+ * Chương trình + tham số chạy một dòng lệnh trong shell của máy. PowerShell 5.1 trả mã thoát 1 cho mọi lỗi của chương trình ngoài (mất mã
28
+ * thật — `node` thoát 2 thành 1): bọc để trả đúng `$LASTEXITCODE`, lệnh PowerShell lỗi (không có mã) thì 1.
29
+ */
30
+ export function shellCommand(command, platform = process.platform) {
31
+ if (platform === 'win32') {
32
+ const wrapped = `& {
33
+ ${command}
34
+ }; if ($LASTEXITCODE) { exit $LASTEXITCODE } elseif (-not $?) { exit 1 }`;
35
+ return [hasPwsh() ? 'pwsh.exe' : 'powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', wrapped]];
36
+ }
37
+ return [process.env.SHELL || '/bin/bash', ['-c', command]];
38
+ }
39
+
40
+ export function createProcessManager() {
41
+ const procs = new Map();
42
+ let seq = 0;
43
+
44
+ const prune = () => {
45
+ for (const [id, p] of procs) if (p.status !== 'running' && Date.now() - p.endedAt > KEEP_EXITED_MS) procs.delete(id);
46
+ };
47
+
48
+ function killTree(p) {
49
+ if (p.status !== 'running') return;
50
+ if (process.platform === 'win32') spawn('taskkill', ['/pid', String(p.child.pid), '/T', '/F'], { windowsHide: true });
51
+ else { try { process.kill(-p.child.pid, 'SIGTERM'); } catch { try { p.child.kill('SIGTERM'); } catch { /* đã thoát */ } } }
52
+ }
53
+
54
+ /** Ghi log theo dòng vào bộ đệm vòng (giữ MAX_LINES dòng cuối); `cursor` tăng mãi để đọc tiếp không sót / không lặp. */
55
+ function pushOutput(p, stream, chunk) {
56
+ const text = p.partial[stream] + chunk.toString();
57
+ const parts = text.split(/\r?\n/);
58
+ p.partial[stream] = parts.pop();
59
+ for (const line of parts) addLine(p, stream, line);
60
+ }
61
+
62
+ function addLine(p, stream, line) {
63
+ p.lines.push({ n: p.cursor++, s: stream === 'stderr' ? 'e' : 'o', t: line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS)}…` : line });
64
+ if (p.lines.length > MAX_LINES) p.lines.splice(0, p.lines.length - MAX_LINES);
65
+ for (const w of [...p.waiters]) w(p.lines[p.lines.length - 1]);
66
+ }
67
+
68
+ /** Máy tính tổ chức: mỗi tiến trình thuộc một thành viên (`env.runAs`) — người khác không thấy / đọc / dừng được. */
69
+ const ownerOf = (env) => env?.runAs?.name || '';
70
+
71
+ function get(id, env) {
72
+ const p = procs.get(String(id || ''));
73
+ if (!p || p.owner !== ownerOf(env)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No background process ${id} (see proc.list)`);
74
+ return p;
75
+ }
76
+
77
+ const view = (p) => ({
78
+ id: p.id, name: p.name, command: p.command.slice(0, 300), cwd: p.cwdDisplay, status: p.status, exitCode: p.exitCode,
79
+ pid: p.child.pid, started_at: new Date(p.startedAt).toISOString(), lines: p.cursor,
80
+ });
81
+
82
+ async function start(args, _ctx, env) {
83
+ prune();
84
+ if ([...procs.values()].filter((p) => p.status === 'running' && p.owner === ownerOf(env)).length >= MAX_PROCS) {
85
+ throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `At most ${MAX_PROCS} background processes — stop one first (proc.list)`);
86
+ }
87
+ const command = String(args.command || '').trim();
88
+ if (!command) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Missing argument: command');
89
+ assertCommandAllowed(command);
90
+ const cwd = resolveInRoots(env.roots, args.cwd || '');
91
+ // Cần gõ vào (trả lời câu hỏi): PowerShell không chuyển stdin sang chương trình con → Windows chạy qua cmd.exe (chương trình con dùng
92
+ // chung stdin, mã thoát giữ nguyên); nơi khác shell vốn đã chuyển.
93
+ const interactive = !!args.interactive && process.platform === 'win32';
94
+ let [cmd, argv] = interactive ? ['cmd.exe', ['/d', '/s', '/c', `"${command}"`]] : shellCommand(command);
95
+ const runAs = env.runAs;
96
+ if (runAs) [cmd, argv] = withProcessCap(cmd, argv);
97
+ const baseEnv = scrubEnv();
98
+ const child = spawn(cmd, argv, {
99
+ cwd, env: runAs ? accountEnv(runAs, baseEnv) : baseEnv, windowsHide: true, detached: process.platform !== 'win32',
100
+ stdio: ['pipe', 'pipe', 'pipe'], windowsVerbatimArguments: interactive, ...(runAs ? { uid: runAs.uid, gid: runAs.gid } : {}),
101
+ });
102
+ const id = `p${++seq}`;
103
+ const p = {
104
+ id, owner: ownerOf(env), name: String(args.name || '').slice(0, 60) || undefined, command, cwdDisplay: displayPath(env.roots, cwd), child, status: 'running', exitCode: null,
105
+ startedAt: Date.now(), endedAt: 0, lines: [], cursor: 0, partial: { stdout: '', stderr: '' }, waiters: new Set(), exitWaiters: new Set(),
106
+ };
107
+ procs.set(id, p);
108
+ child.stdout.on('data', (c) => pushOutput(p, 'stdout', c));
109
+ child.stderr.on('data', (c) => pushOutput(p, 'stderr', c));
110
+ const finish = (code) => {
111
+ if (p.status !== 'running') return;
112
+ for (const s of ['stdout', 'stderr']) if (p.partial[s]) { addLine(p, s, p.partial[s]); p.partial[s] = ''; }
113
+ p.status = 'exited';
114
+ p.exitCode = code ?? -1;
115
+ p.endedAt = Date.now();
116
+ for (const w of [...p.exitWaiters]) w();
117
+ };
118
+ child.on('error', (e) => { addLine(p, 'stderr', `Cannot start: ${e.message}`); finish(-1); });
119
+ child.on('close', (code) => finish(code));
120
+ return view(p);
121
+ }
122
+
123
+ function read(args, env) {
124
+ const p = get(args.id, env);
125
+ const since = Number.isFinite(Number(args.since)) ? Number(args.since) : null;
126
+ const max = Math.min(Number(args.lines) || DEFAULT_READ_LINES, 1000);
127
+ let lines = since === null ? p.lines.slice(-max) : p.lines.filter((l) => l.n >= since).slice(0, max);
128
+ const filter = args.filter ? new RegExp(String(args.filter), 'i') : null;
129
+ if (filter) lines = lines.filter((l) => filter.test(l.t));
130
+ const last = lines[lines.length - 1];
131
+ return {
132
+ ...view(p), output: lines.map((l) => (l.s === 'e' ? `[err] ${l.t}` : l.t)).join('\n'),
133
+ next_since: last ? last.n + 1 : (since ?? p.cursor), dropped_before: p.lines[0]?.n || 0,
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Chờ tới khi một dòng log MỚI (từ `since`, mặc định từ đầu bộ đệm) khớp `pattern` (regex, không phân biệt hoa thường), hoặc tiến trình
139
+ * thoát, hoặc hết `timeoutMs`. Trả dòng khớp + vài dòng trước nó làm ngữ cảnh.
140
+ */
141
+ function waitFor(args, ctx, env) {
142
+ const p = get(args.id, env);
143
+ const pattern = args.pattern ? new RegExp(String(args.pattern), 'i') : null;
144
+ const since = Number.isFinite(Number(args.since)) ? Number(args.since) : 0;
145
+ const timeoutMs = Math.min(Math.max(1000, Number(args.timeoutMs) || 60_000), MAX_WAIT_MS);
146
+ const contextOf = (n) => p.lines.filter((l) => l.n < n && l.n >= n - 10).map((l) => l.t).join('\n');
147
+ const already = pattern && p.lines.find((l) => l.n >= since && pattern.test(l.t));
148
+ if (already) return Promise.resolve({ ...view(p), matched: true, line: already.t, context: contextOf(already.n), next_since: already.n + 1 });
149
+ if (p.status !== 'running') return Promise.resolve({ ...view(p), matched: false, reason: 'exited', tail: p.lines.slice(-30).map((l) => l.t).join('\n'), next_since: p.cursor });
150
+ return new Promise((resolve, reject) => {
151
+ const cleanup = () => { clearTimeout(timer); p.waiters.delete(onLine); p.exitWaiters.delete(onExit); ctx?.signal?.removeEventListener('abort', onAbort); };
152
+ const onLine = (l) => { if (pattern?.test(l.t)) { cleanup(); resolve({ ...view(p), matched: true, line: l.t, context: contextOf(l.n), next_since: l.n + 1 }); } };
153
+ const onExit = () => { cleanup(); resolve({ ...view(p), matched: false, reason: 'exited', tail: p.lines.slice(-30).map((l) => l.t).join('\n'), next_since: p.cursor }); };
154
+ const onAbort = () => { cleanup(); reject(ctx.signal.reason); };
155
+ const timer = setTimeout(() => { cleanup(); resolve({ ...view(p), matched: false, reason: 'timeout', tail: p.lines.slice(-20).map((l) => l.t).join('\n'), next_since: p.cursor }); }, timeoutMs);
156
+ p.waiters.add(onLine);
157
+ p.exitWaiters.add(onExit);
158
+ ctx?.signal?.addEventListener('abort', onAbort, { once: true });
159
+ });
160
+ }
161
+
162
+ /**
163
+ * Gõ vào tiến trình đang chạy (trả lời câu hỏi "Continue? [y/N]", nhập lựa chọn của trình cài, lệnh cho REPL). Chữ gõ vào xét như một
164
+ * lệnh: chạm `.aivin` bị chặn ở đây; BE xét cùng cổng duyệt / sàn nội dung như shell.exec. `close` = đóng stdin (báo hết dữ liệu).
165
+ */
166
+ function write(args, env) {
167
+ const p = get(args.id, env);
168
+ if (p.status !== 'running') throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Process ${p.id} has exited`);
169
+ const text = String(args.text ?? '');
170
+ assertCommandAllowed(text);
171
+ if (text) p.child.stdin.write(args.newline === false ? text : `${text}
172
+ `);
173
+ if (args.close) p.child.stdin.end();
174
+ return { ...view(p), written: text.length, closed_input: !!args.close || undefined, next_since: p.cursor };
175
+ }
176
+
177
+ function stop(args, env) {
178
+ const p = get(args.id, env);
179
+ killTree(p);
180
+ return { ...view(p), stopping: p.status === 'running' };
181
+ }
182
+
183
+ return {
184
+ start, read, waitFor, write, stop,
185
+ list: (env) => { prune(); return { processes: [...procs.values()].filter((p) => p.owner === ownerOf(env)).map(view) }; },
186
+ stopAll: () => { for (const p of procs.values()) killTree(p); },
187
+ /** Còn tiến trình nền chạy (mọi người dùng) — Cloud Computer báo BE qua heartbeat để máy không bị tắt vì "rảnh" giữa lúc đang chạy. */
188
+ hasRunning: () => [...procs.values()].some((p) => p.status === 'running'),
189
+ };
190
+ }
191
+
192
+ /** Công cụ tiến trình nền cho danh mục của Planner. */
193
+ export function buildProcessTools(pm) {
194
+ return [
195
+ { name: 'proc.start', group: ToolGroup.PROC, handler: (a, c, e) => pm.start(a, c, e),
196
+ description: `Start a long-running command in the background (dev server, build/test watcher, long script, \`claude -p "…"\`, tail -f) in ${process.platform === 'win32' ? 'PowerShell' : 'the login shell'}; returns an id at once. Then use proc.wait_for / proc.read; stop it with proc.stop. Prefer shell.exec for short commands.`,
197
+ input_schema: schema({
198
+ command: str('command line'), cwd: str('working folder, default the root'), name: str('short label'),
199
+ interactive: { type: 'boolean', description: `the program will ask for input you answer with proc.write${process.platform === 'win32' ? ' (runs through cmd.exe: plain program + arguments, not PowerShell syntax)' : ''}` },
200
+ }, ['command']) },
201
+ { name: 'proc.wait_for', group: ToolGroup.PROC, read_only: true, handler: (a, c, e) => pm.waitFor(a, c, e),
202
+ description: 'Wait until a NEW output line of a background process matches pattern (case-insensitive regex, e.g. "ready|listening", "error|failed"), or it exits, or timeoutMs passes. Returns the matched line with context and next_since for the next call.',
203
+ input_schema: schema({ id: str('process id'), pattern: str('regex to wait for; omit to wait for exit'), since: num('line cursor from a previous call'), timeoutMs: num('max 600000, default 60000') }, ['id']) },
204
+ { name: 'proc.read', group: ToolGroup.PROC, read_only: true, handler: (a, _c, e) => pm.read(a, e),
205
+ description: 'Read output of a background process: the last lines, or new lines since a cursor; filter keeps matching lines only.',
206
+ input_schema: schema({ id: str('process id'), since: num('line cursor (next_since)'), lines: num('max lines, default 200'), filter: str('regex filter') }, ['id']) },
207
+ { name: 'proc.write', group: ToolGroup.PROC, handler: (a, _c, e) => pm.write(a, e),
208
+ description: 'Type into a running background process (answer a prompt like "Continue? [y/N]", an installer choice, a line for a REPL). Adds Enter unless newline is false; close ends the input. Then proc.wait_for from the returned next_since.',
209
+ input_schema: schema({ id: str('process id'), text: str('what to type'), newline: { type: 'boolean', description: 'press Enter after the text (default true)' }, close: { type: 'boolean', description: 'close the input after writing' } }, ['id']) },
210
+ { name: 'proc.stop', group: ToolGroup.PROC, handler: (a, _c, e) => pm.stop(a, e),
211
+ description: 'Stop a background process and all its children.',
212
+ input_schema: schema({ id: str('process id') }, ['id']) },
213
+ { name: 'proc.list', group: ToolGroup.PROC, read_only: true, handler: (_a, _c, e) => pm.list(e),
214
+ description: 'Background processes started by the AI on this computer: status, exit code, command.',
215
+ input_schema: schema({}) },
216
+ ];
217
+ }
@@ -0,0 +1,221 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { DeviceErrorCode, KILL_SWITCH_FILE, REMOTE_CONFIG_DIR } from './constants.mjs';
5
+
6
+ /** Lỗi có mã để BE / Planner đọc được lý do. */
7
+ export class DeviceToolError extends Error {
8
+ constructor(code, message) {
9
+ super(message);
10
+ this.code = code;
11
+ }
12
+ }
13
+
14
+ /** realpath của tổ tiên gần nhất đã tồn tại + phần còn lại — dùng được cho đường dẫn chưa tồn tại (tệp sắp ghi). */
15
+ function realpathNearest(target) {
16
+ let current = path.resolve(target);
17
+ const rest = [];
18
+ while (!fs.existsSync(current)) {
19
+ const parent = path.dirname(current);
20
+ if (parent === current) break;
21
+ rest.unshift(path.basename(current));
22
+ current = parent;
23
+ }
24
+ let real;
25
+ try { real = fs.realpathSync.native(current); } catch { real = current; }
26
+ return path.join(real, ...rest);
27
+ }
28
+
29
+ /**
30
+ * Đường dẫn mạng / thiết bị (`\\host\share`, `//host/share`, `\\?\`, `\\.\`): chạm vào (kể cả `existsSync`) là Windows tự gửi thông tin xác thực
31
+ * NTLM ra máy ngoài — chặn theo CHUỖI trước mọi lời gọi fs (rà 28/10/2026).
32
+ */
33
+ export function isNetworkPath(raw) {
34
+ return /^[\\/]{2}/.test(String(raw || '').trim());
35
+ }
36
+
37
+ function isInside(parent, child) {
38
+ const rel = path.relative(parent, child);
39
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
40
+ }
41
+
42
+ /**
43
+ * Đường dẫn → đường tuyệt đối NẰM TRONG một thư mục gốc được phép. So bằng realpath (cả gốc lẫn đích), nên symlink / junction trỏ ra
44
+ * ngoài gốc bị chặn. Đường tương đối tính từ gốc đầu tiên. Trả về CHÍNH đường realpath đã kiểm (không phải đường chưa giải): thao tác
45
+ * sau đó không đi lại qua symlink mà tiến trình khác có thể tráo giữa lúc kiểm và lúc dùng.
46
+ */
47
+ export function resolveInRoots(roots, target = '') {
48
+ if (!roots?.length) throw new DeviceToolError(DeviceErrorCode.ROOT_DENIED, 'No allowed root directory on this device');
49
+ const raw = String(target || '');
50
+ if (isNetworkPath(raw)) throw new DeviceToolError(DeviceErrorCode.ROOT_DENIED, `Network / device paths are not allowed: ${raw}`);
51
+ const candidate = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(roots[0], raw);
52
+ const real = realpathNearest(candidate);
53
+ const allowed = roots.some((root) => isInside(realpathNearest(root), real));
54
+ if (!allowed) throw new DeviceToolError(DeviceErrorCode.ROOT_DENIED, `Path is outside the allowed folders: ${raw}`);
55
+ if (isProtectedPath(real)) throw new DeviceToolError(DeviceErrorCode.PROTECTED_PATH, `Path holds Aivin credentials and is never accessible remotely: ${raw}`);
56
+ return real;
57
+ }
58
+
59
+ /**
60
+ * Như resolveInRoots nhưng KHÔNG đi theo thành phần cuối (cho xoá / chuyển): thư mục cha giải realpath + kiểm trong gốc, tên cuối giữ
61
+ * nguyên — xoá một symlink là xoá chính symlink đó, không xoá thư mục nó trỏ tới.
62
+ */
63
+ export function resolveEntryInRoots(roots, target = '') {
64
+ const real = resolveInRoots(roots, target);
65
+ const raw = String(target || '');
66
+ const candidate = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(roots[0], raw);
67
+ const parent = path.dirname(candidate);
68
+ if (parent === candidate || isRootPath(roots, real)) return real;
69
+ return path.join(resolveInRoots(roots, parent), path.basename(candidate));
70
+ }
71
+
72
+ /** Đường (đã giải) có phải chính một thư mục gốc không — so cả dạng gốc lẫn realpath của gốc. */
73
+ export function isRootPath(roots, absolute) {
74
+ return (roots || []).some((r) => path.resolve(r) === absolute || realpathNearest(r) === absolute);
75
+ }
76
+
77
+ /**
78
+ * Thư mục cấu hình Aivin (`~/.aivin` + `AIVIN_REMOTE_HOME`): token thiết bị, API key của CLI, hồ sơ trình duyệt `aivin browser` (cookie
79
+ * đăng nhập). Chặn kể cả khi người dùng cho phép cả thư mục nhà (`--dir ~`) — lộ ra là chiếm được tài khoản / phiên web của chủ máy.
80
+ * `~/.aivin-release` (29/10/2026): chỗ mặc định giữ khoá ký bản phát hành CLI (scripts/release-key.mjs) — máy của người phát hành mà ghép
81
+ * toàn quyền thì agent bị lừa đọc được khoá là ký được bản độc cho mọi máy đã cài.
82
+ */
83
+ const PROTECTED_DIRS = [...new Set([REMOTE_CONFIG_DIR, path.join(os.homedir(), '.aivin'), path.join(os.homedir(), '.aivin-release')].map((d) => path.resolve(d)))];
84
+
85
+ let protectedReal;
86
+
87
+ export function isProtectedPath(absolute) {
88
+ // realpath thư mục bảo vệ tính một lần — chỉ mục tệp gọi hàm này cho từng tệp.
89
+ protectedReal ??= PROTECTED_DIRS.map(realpathNearest);
90
+ const real = realpathNearest(absolute);
91
+ return protectedReal.some((dir) => isInside(dir, real));
92
+ }
93
+
94
+ /** Thư mục BAO TRỌN một thư mục bảo vệ — xoá / chuyển nó là xoá / chuyển luôn token. */
95
+ export function containsProtectedPath(absolute) {
96
+ protectedReal ??= PROTECTED_DIRS.map(realpathNearest);
97
+ const real = realpathNearest(absolute);
98
+ return protectedReal.some((dir) => isInside(real, dir));
99
+ }
100
+
101
+ /**
102
+ * Tên thư mục cần loại khỏi ripgrep khi tìm dưới `base`: luôn `.aivin`, cộng tên thư mục `AIVIN_REMOTE_HOME` nếu nó nằm trong `base`
103
+ * (chỉ khi đó — loại theo tên ở mọi nơi sẽ bỏ sót cả thư mục trùng tên của người dùng).
104
+ */
105
+ export function protectedDirNamesUnder(base) {
106
+ protectedReal ??= PROTECTED_DIRS.map(realpathNearest);
107
+ const real = realpathNearest(base);
108
+ const names = new Set(['.aivin', '.aivin-release']);
109
+ for (const dir of protectedReal) if (dir !== real && isInside(real, dir)) names.add(path.basename(dir));
110
+ return [...names];
111
+ }
112
+
113
+ /**
114
+ * Đường hiển thị: tương đối với gốc ĐẦU TIÊN (gọn cho Planner), ngoài nó thì tuyệt đối. Chỉ gốc đầu: đường tương đối luôn được hiểu
115
+ * theo gốc đầu (resolveInRoots) — rút gọn theo gốc khác (vd ổ D: khi toàn quyền) thì Planner dùng lại sẽ trỏ nhầm sang thư mục nhà.
116
+ */
117
+ const rootRealCache = new Map();
118
+
119
+ export function displayPath(roots, absolute) {
120
+ const first = roots?.[0];
121
+ if (!first) return absolute;
122
+ // resolveInRoots trả realpath → so với realpath của gốc trước (gốc là junction / symlink), rồi mới tới dạng gốc.
123
+ if (!rootRealCache.has(first)) rootRealCache.set(first, realpathNearest(first));
124
+ for (const base of [rootRealCache.get(first), path.resolve(first)]) {
125
+ if (isInside(base, absolute)) return path.relative(base, absolute) || '.';
126
+ }
127
+ return absolute;
128
+ }
129
+
130
+ /**
131
+ * Gốc khi chủ máy cho TOÀN QUYỀN (`--full-access`): thư mục nhà đứng đầu (đường tương đối tính từ đây), rồi mọi ổ đĩa (Windows: các
132
+ * ổ có mặt; macOS/Linux: `/`). Thư mục cấu hình Aivin vẫn bị chặn (isProtectedPath), lệnh thảm hoạ vẫn bị chặn.
133
+ */
134
+ export function fullAccessRoots() {
135
+ const home = os.homedir();
136
+ if (process.platform !== 'win32') return [home, '/'];
137
+ const drives = 'CDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map((d) => `${d}:\\`).filter((d) => { try { return fs.existsSync(d); } catch { return false; } });
138
+ return [home, ...drives];
139
+ }
140
+
141
+ const SECRET_ENV = /(^API_KEY$|^AIVIN_|TOKEN|SECRET|PASSWORD|PASSWD|PRIVATE_KEY|CREDENTIAL|COOKIE|SESSION_KEY|ACCESS_KEY|_API_KEY$|CONNECTION_?STRING|CONN_?STR|DATABASE_URL)/i;
142
+ /**
143
+ * Đoạn tên (tách theo `_`) mang bí mật: `DB_PASS`, `STRIPE_KEY`, `GH_PAT`, `X_SIGNING_KEY`, `SSH_AUTH_SOCK`, `SENTRY_DSN`… So nguyên
144
+ * đoạn, không so chuỗi con — `PATH` không dính `PAT`, `KEYBOARD_LAYOUT` không dính `KEY`.
145
+ */
146
+ const SECRET_SEGMENTS = new Set([
147
+ 'KEY', 'KEYS', 'APIKEY', 'ACCESSKEY', 'PASS', 'PASSWD', 'PASSWORD', 'PASSPHRASE', 'ASKPASS', 'PAT', 'TOKEN', 'TOKENS', 'SECRET', 'SECRETS',
148
+ 'AUTH', 'DSN', 'CREDENTIAL', 'CREDENTIALS', 'CREDS', 'COOKIE', 'COOKIES', 'SESSION', 'SIGNING', 'PRIVATE',
149
+ ]);
150
+ /** Biến vô hại có đoạn trùng danh sách trên — vẫn giữ (thư mục hiện tại, D-Bus cho thông báo, loại phiên đồ hoạ). */
151
+ const SAFE_ENV = new Set(['PWD', 'OLDPWD', 'DBUS_SESSION_BUS_ADDRESS', 'XDG_SESSION_TYPE', 'XDG_SESSION_CLASS', 'XDG_SESSION_DESKTOP']);
152
+ /** Giá trị là URL kèm mật khẩu (`postgres://u:p@host/db`) — bỏ bất kể tên biến. */
153
+ const URL_WITH_PASSWORD = /^[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/i;
154
+
155
+ export function isSecretEnv(key, value = '') {
156
+ const name = String(key).toUpperCase();
157
+ if (SAFE_ENV.has(name)) return false;
158
+ if (SECRET_ENV.test(name)) return true;
159
+ const segments = name.split('_').filter(Boolean);
160
+ // `PWD` đứng một mình là thư mục hiện tại; là một đoạn của tên dài hơn (`DB_PWD`) thì là mật khẩu.
161
+ if (segments.some((seg) => SECRET_SEGMENTS.has(seg) || (seg === 'PWD' && segments.length > 1))) return true;
162
+ return URL_WITH_PASSWORD.test(String(value ?? ''));
163
+ }
164
+
165
+ /** Biến môi trường cho lệnh chạy từ xa: bỏ mọi biến mang bí mật (API key của CLI, token, mật khẩu, chuỗi kết nối…). */
166
+ export function scrubEnv(env = process.env) {
167
+ const out = {};
168
+ for (const [key, value] of Object.entries(env)) {
169
+ if (!isSecretEnv(key, value)) out[key] = value;
170
+ }
171
+ return out;
172
+ }
173
+
174
+ /**
175
+ * 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
+ * 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.
177
+ */
178
+ const CATASTROPHIC_COMMANDS = [
179
+ /\bformat(\.com)?\s+[a-z]:/i,
180
+ /\b(del|erase)\s+(\/[a-z]\s+)*[a-z]:\\\s*(\*|$)/i,
181
+ /\brmdir\s+(\/[a-z]\s+)*[a-z]:\\\s*$/i,
182
+ /remove-item\s+.*-recurse.*\s[a-z]:\\\s*(\*\s*)?(-|$)/i,
183
+ /\brm\s+-[a-z]*r[a-z]*f?[a-z]*\s+(--no-preserve-root\s+)?(\/|\/\*|~|~\/|\$HOME)(\s|$)/i,
184
+ /\bmkfs(\.|\s)/i,
185
+ /\bdd\s+.*of=\/dev\/(sd|nvme|hd|disk)/i,
186
+ /:\(\)\s*\{\s*:\|:&\s*\};:/,
187
+ /\bdiskpart\b/i,
188
+ ];
189
+
190
+ /** 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
+ const AIVIN_DIR_SEGMENT = /(?:^|[\\/\s'"`~=:(;,|&])\.aivin(?:-release)?(?=[\\/\s'"`);,|&]|$)/i;
192
+
193
+ function mentionsProtectedDir(command) {
194
+ if (AIVIN_DIR_SEGMENT.test(command)) return true;
195
+ const lower = command.toLowerCase().replace(/\\/g, '/');
196
+ return PROTECTED_DIRS.some((dir) => lower.includes(dir.toLowerCase().replace(/\\/g, '/')));
197
+ }
198
+
199
+ /**
200
+ * Lệnh nhắc tới thư mục bảo vệ bị chặn. Khớp chuỗi nên lách được (ghép chuỗi, mã hoá) — chỉ là sàn chống lỗi Planner / prompt injection
201
+ * thông thường; cách ly thật cần sandbox của hệ điều hành (xem docs/official/device-agent/policy-approval.md ở repo be).
202
+ */
203
+ export function assertCommandAllowed(command) {
204
+ if (CATASTROPHIC_COMMANDS.some((re) => re.test(command))) {
205
+ throw new DeviceToolError(DeviceErrorCode.BLOCKED_COMMAND, 'Command blocked by the device safety floor (destroys the whole system)');
206
+ }
207
+ if (mentionsProtectedDir(command)) {
208
+ throw new DeviceToolError(DeviceErrorCode.PROTECTED_PATH, 'Command touches the Aivin credentials folder (.aivin), which is never accessible remotely');
209
+ }
210
+ }
211
+
212
+ export function isRemotePaused() {
213
+ return fs.existsSync(KILL_SWITCH_FILE);
214
+ }
215
+
216
+ /** Bật/tắt công tắc ngắt — chỉ người ngồi trước máy làm được (lệnh CLI cục bộ), BE không đổi được. */
217
+ export function setRemotePaused(paused) {
218
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
219
+ if (paused) fs.writeFileSync(KILL_SWITCH_FILE, new Date().toISOString());
220
+ else if (fs.existsSync(KILL_SWITCH_FILE)) fs.unlinkSync(KILL_SWITCH_FILE);
221
+ }