@aivin-labs/cli 1.0.4 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +263 -216
  2. package/bin/cli.mjs +1780 -1361
  3. package/bin/lib/browserAutomation.mjs +655 -648
  4. package/bin/lib/browserTui.mjs +276 -245
  5. package/bin/lib/cancellation.mjs +61 -0
  6. package/bin/lib/codegen.mjs +61 -5
  7. package/bin/lib/connectors.mjs +55 -21
  8. package/bin/lib/deploy.mjs +25 -2
  9. package/bin/lib/mcpProxy.mjs +869 -773
  10. package/bin/lib/mission.mjs +13 -1
  11. package/bin/lib/missionStream.mjs +696 -660
  12. package/bin/lib/pluginAuthResolve.mjs +127 -0
  13. package/bin/lib/pluginTrigger.mjs +207 -90
  14. package/bin/lib/releaseKeys.mjs +9 -0
  15. package/bin/lib/remote/activityLog.mjs +68 -0
  16. package/bin/lib/remote/autoStart.mjs +457 -0
  17. package/bin/lib/remote/autoUpdate.mjs +129 -0
  18. package/bin/lib/remote/brand.mjs +60 -0
  19. package/bin/lib/remote/browserTunnel.mjs +292 -0
  20. package/bin/lib/remote/callLedger.mjs +134 -0
  21. package/bin/lib/remote/cdpPolicy.mjs +66 -0
  22. package/bin/lib/remote/client.mjs +726 -0
  23. package/bin/lib/remote/constants.mjs +173 -0
  24. package/bin/lib/remote/credentials.mjs +208 -0
  25. package/bin/lib/remote/daemonLock.mjs +86 -0
  26. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  27. package/bin/lib/remote/deviceMemory.mjs +246 -0
  28. package/bin/lib/remote/deviceProfile.mjs +142 -0
  29. package/bin/lib/remote/deviceWatches.mjs +138 -0
  30. package/bin/lib/remote/docText.mjs +117 -0
  31. package/bin/lib/remote/fileIndexer.mjs +399 -0
  32. package/bin/lib/remote/gui/index.mjs +245 -0
  33. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  34. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  35. package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
  36. package/bin/lib/remote/httpTransfer.mjs +89 -0
  37. package/bin/lib/remote/idempotency.mjs +135 -0
  38. package/bin/lib/remote/keepAwake.mjs +100 -0
  39. package/bin/lib/remote/localConfirm.mjs +268 -0
  40. package/bin/lib/remote/localPolicy.mjs +249 -0
  41. package/bin/lib/remote/mascot/assets.mjs +218 -0
  42. package/bin/lib/remote/mascot/hostSource.mjs +362 -0
  43. package/bin/lib/remote/mascot/index.mjs +322 -0
  44. package/bin/lib/remote/mascot/labels.mjs +83 -0
  45. package/bin/lib/remote/mascot/strings.mjs +189 -0
  46. package/bin/lib/remote/memberFsPool.mjs +134 -0
  47. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  48. package/bin/lib/remote/mission.mjs +156 -0
  49. package/bin/lib/remote/missionQuestion.mjs +63 -0
  50. package/bin/lib/remote/multiUser.mjs +344 -0
  51. package/bin/lib/remote/netProxy.mjs +145 -0
  52. package/bin/lib/remote/notify.mjs +58 -0
  53. package/bin/lib/remote/office/index.mjs +90 -0
  54. package/bin/lib/remote/policyCommand.mjs +93 -0
  55. package/bin/lib/remote/processes.mjs +217 -0
  56. package/bin/lib/remote/sandbox.mjs +221 -0
  57. package/bin/lib/remote/schedule.mjs +213 -0
  58. package/bin/lib/remote/scheduler.mjs +124 -0
  59. package/bin/lib/remote/textIndex.mjs +131 -0
  60. package/bin/lib/remote/tokenStore.mjs +77 -0
  61. package/bin/lib/remote/toolHandlers.mjs +726 -0
  62. package/bin/lib/remote/undoStore.mjs +242 -0
  63. package/bin/lib/remoteControl.mjs +26 -0
  64. package/bin/lib/scaffold.mjs +654 -653
  65. package/bin/lib/selfUpdate.mjs +71 -0
  66. package/bin/lib/store.mjs +16 -2
  67. package/bin/lib/tasks.mjs +52 -8
  68. package/bin/lib/update/binarySwap.mjs +63 -0
  69. package/bin/lib/update/constants.mjs +56 -0
  70. package/bin/lib/update/download.mjs +145 -0
  71. package/bin/lib/update/signature.mjs +42 -0
  72. package/bin/lib/update/state.mjs +205 -0
  73. package/bin/lib/update/versions.mjs +60 -0
  74. package/bin/lib/util.mjs +8 -0
  75. package/docs/CLI.md +1353 -1274
  76. package/package.json +71 -62
@@ -0,0 +1,89 @@
1
+ import axios from 'axios';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { pipeline } from 'stream/promises';
5
+ import { DEVICE_API_PREFIX, DeviceErrorCode, ToolGroup } from './constants.mjs';
6
+ import { DeviceToolError, displayPath, resolveInRoots } from './sandbox.mjs';
7
+
8
+ /** Header token thiết bị BE đòi ở đường chuyển tệp (be `DEVICE_TOKEN_HEADER`). */
9
+ const DEVICE_TOKEN_HEADER = 'x-aivin-device-token';
10
+ const TICKET_RE = /^[A-Za-z0-9_-]{43}$/;
11
+ const PART_RETRIES = 2;
12
+
13
+ /**
14
+ * Tệp lớn hơn trần socket đi HTTP thẳng giữa máy và kho Aivin (be DeviceDirectTransferService). Chỉ BE gọi (internal, Planner không thấy):
15
+ * BE cấp VÉ dùng một lần; CLI tự ghép địa chỉ từ máy chủ đang nối + vé — không bao giờ nhận URL từ BE, nên lời gọi không thể đẩy tệp ra
16
+ * nơi khác. Đường dẫn trên máy vẫn kiểm theo thư mục được phép (resolveInRoots, chặn ~/.aivin).
17
+ */
18
+ export function buildTransferTools({ serverUrl, deviceToken }) {
19
+ const urlOf = (ticket, part) => {
20
+ if (!TICKET_RE.test(String(ticket || ''))) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Invalid transfer ticket');
21
+ return `${String(serverUrl).replace(/\/+$/, '')}${DEVICE_API_PREFIX}/transfers/${ticket}${part === undefined ? '' : `?part=${part}`}`;
22
+ };
23
+ // `deviceToken` là hàm khi daemon có thể xoay vòng token lúc đang chạy — mỗi yêu cầu lấy token hiện hành.
24
+ const headers = (extra = {}) => ({ [DEVICE_TOKEN_HEADER]: typeof deviceToken === 'function' ? deviceToken() : deviceToken, ...extra });
25
+
26
+ async function upload(args, ctx, env) {
27
+ if (env.runAs) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Direct transfer is not available on a shared computer');
28
+ const abs = resolveInRoots(env.roots, args.path || '');
29
+ const size = (await fs.promises.stat(abs)).size;
30
+ const partBytes = Number(args.part_bytes);
31
+ const parts = Number(args.parts);
32
+ if (size !== Number(args.size)) throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `File changed before copying (${size} bytes, expected ${args.size}) — try again`);
33
+ if (!Number.isInteger(parts) || parts < 1 || !(partBytes > 0)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Invalid parts');
34
+ for (let i = 0; i < parts; i++) {
35
+ const start = i * partBytes;
36
+ const length = i < parts - 1 ? partBytes : size - start;
37
+ await withRetries(() => putPart({ url: urlOf(args.ticket, i), abs, start, length, signal: ctx.signal, headers }), ctx.signal);
38
+ ctx.onOutput?.(`uploaded ${Math.min(size, start + length)} / ${size} bytes\n`);
39
+ }
40
+ return { path: displayPath(env.roots, abs), bytes: size, parts };
41
+ }
42
+
43
+ async function download(args, ctx, env) {
44
+ if (env.runAs) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Direct transfer is not available on a shared computer');
45
+ const abs = resolveInRoots(env.roots, args.path || '');
46
+ await fs.promises.mkdir(path.dirname(abs), { recursive: true });
47
+ const res = await axios.get(urlOf(args.ticket), { headers: headers(), signal: ctx.signal, responseType: 'stream', validateStatus: () => true });
48
+ if (res.status !== 200) {
49
+ res.data?.destroy?.();
50
+ throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Download failed (HTTP ${res.status})`);
51
+ }
52
+ await pipeline(res.data, fs.createWriteStream(abs), { signal: ctx.signal });
53
+ const bytes = (await fs.promises.stat(abs)).size;
54
+ return { path: displayPath(env.roots, abs), bytes };
55
+ }
56
+
57
+ return [
58
+ { name: 'fs.upload', group: ToolGroup.FS_READ, read_only: true, internal: true, handler: upload,
59
+ description: 'BE-only: send a large file to Aivin in parts over HTTP with a one-time ticket.', input_schema: { type: 'object', properties: {} } },
60
+ { name: 'fs.download', group: ToolGroup.FS_WRITE, internal: true, handler: download,
61
+ description: 'BE-only: download a large Aivin file over HTTP with a one-time ticket into a temporary file.', input_schema: { type: 'object', properties: {} } },
62
+ ];
63
+ }
64
+
65
+ /** Một khúc = một PUT có Content-Length cố định (BE đối chiếu cỡ khúc theo vé; stream từ đĩa, không nạp cả khúc vào RAM). */
66
+ async function putPart({ url, abs, start, length, signal, headers }) {
67
+ const body = length ? fs.createReadStream(abs, { start, end: start + length - 1 }) : Buffer.alloc(0);
68
+ const res = await axios.put(url, body, {
69
+ signal, maxBodyLength: Infinity, maxContentLength: Infinity, validateStatus: () => true,
70
+ headers: headers({ 'content-type': 'application/octet-stream', 'content-length': String(length) }),
71
+ });
72
+ if (res.status < 200 || res.status >= 300) {
73
+ const err = new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Upload failed (HTTP ${res.status})`);
74
+ // Vé hết hạn / sai máy / sai khúc: thử lại cũng vô ích.
75
+ err.retryable = res.status >= 500 || res.status === 429;
76
+ throw err;
77
+ }
78
+ }
79
+
80
+ async function withRetries(fn, signal) {
81
+ for (let attempt = 0; ; attempt++) {
82
+ try {
83
+ return await fn();
84
+ } catch (e) {
85
+ if (signal?.aborted || e?.retryable === false || attempt >= PART_RETRIES) throw e;
86
+ await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
87
+ }
88
+ }
89
+ }
@@ -0,0 +1,135 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { DeviceErrorCode } from './constants.mjs';
4
+
5
+ /**
6
+ * Chống làm trùng (28/10/2026): BE gắn `idem_key` cho mỗi bước có tác dụng (theo nhiệm vụ + lượt + bước + tham số). BE khởi động lại giữa
7
+ * chừng → agentic chạy tiếp → lô bước dở được gửi lại: bước đã làm (hoặc đang làm) trả lại đúng kết quả cũ thay vì ghi / gửi / chạy lần hai.
8
+ * Bước hỏng thì quên khoá — lần sau được chạy lại.
9
+ *
10
+ * Sổ trên đĩa (29/10/2026, `file`): daemon khởi động lại (sập, máy khởi động lại, tự cập nhật) vẫn nhớ. Bước xong → trả kết quả cũ; bước
11
+ * ĐANG chạy lúc daemon chết → `INTERRUPTED` (không biết đã làm tới đâu — không tự làm lần hai, Planner kiểm lại rồi mới làm).
12
+ */
13
+
14
+ const IDEM_TTL_MS = 24 * 3600_000;
15
+ const IDEM_MAX = 3000;
16
+ /** Số khoá giữ trên đĩa (mới nhất) và trần kết quả lưu kèm — kết quả lớn hơn chỉ lưu "đã làm", không lưu nội dung. */
17
+ const PERSIST_MAX = 500;
18
+ const KEEP_RESULT_BYTES = 16 * 1024;
19
+ /** Tệp sổ dài quá bấy nhiêu dòng thì viết gọn lại (mỗi bước ghi 2 dòng). */
20
+ const COMPACT_LINES = 2000;
21
+
22
+ const IdemState = Object.freeze({ START: 'start', DONE: 'done', FAIL: 'fail', INTERRUPTED: 'interrupted' });
23
+
24
+ function keptOutcome(outcome) {
25
+ let size = Infinity;
26
+ try { size = Buffer.byteLength(JSON.stringify(outcome)); } catch { /* không tuần tự hoá được */ }
27
+ if (size <= KEEP_RESULT_BYTES) return outcome;
28
+ return { ok: true, result: { note: 'Done before the Aivin agent on this device restarted — the full result was not kept' }, duration_ms: outcome.duration_ms };
29
+ }
30
+
31
+ const interruptedOutcome = () => ({
32
+ ok: false,
33
+ error: 'This step had already started on this device when the Aivin agent restarted — it may have partly run. Check its effect before doing it again.',
34
+ error_code: DeviceErrorCode.INTERRUPTED,
35
+ duration_ms: 0,
36
+ });
37
+
38
+ /** Sổ khoá trên đĩa, mỗi dòng một sự kiện `{ k, s, at, o? }`. Đọc: dòng sau đè dòng trước; `start` không có `done` / `fail` → bị ngắt. */
39
+ export function createIdemLog(file, { now = () => Date.now() } = {}) {
40
+ const entries = new Map();
41
+ let lines = 0;
42
+
43
+ const write = (record) => {
44
+ try {
45
+ fs.mkdirSync(path.dirname(file), { recursive: true });
46
+ fs.appendFileSync(file, JSON.stringify(record) + '\n');
47
+ lines++;
48
+ if (lines > COMPACT_LINES) compact();
49
+ } catch { /* ổ đầy / không ghi được: chống trùng vẫn chạy trong bộ nhớ */ }
50
+ };
51
+
52
+ function compact() {
53
+ const keep = [...entries.entries()].slice(-PERSIST_MAX);
54
+ entries.clear();
55
+ keep.forEach(([k, v]) => entries.set(k, v));
56
+ const tmp = `${file}.tmp`;
57
+ fs.writeFileSync(tmp, keep.map(([k, v]) => JSON.stringify({ k, s: v.state, at: v.at, ...(v.outcome ? { o: v.outcome } : {}) }) + '\n').join(''));
58
+ fs.renameSync(tmp, file);
59
+ lines = keep.length;
60
+ }
61
+
62
+ /** Đọc sổ cũ: trả các khoá còn hạn (đã xong / bị ngắt), viết gọn tệp. */
63
+ function load() {
64
+ let raw = '';
65
+ try { raw = fs.readFileSync(file, 'utf8'); } catch { return entries; }
66
+ const t = now();
67
+ for (const line of raw.split('\n')) {
68
+ if (!line.trim()) continue;
69
+ let r;
70
+ try { r = JSON.parse(line); } catch { continue; }
71
+ if (typeof r?.k !== 'string' || t - Number(r.at) > IDEM_TTL_MS) continue;
72
+ entries.delete(r.k);
73
+ if (r.s === IdemState.FAIL) continue;
74
+ entries.set(r.k, { state: r.s === IdemState.START ? IdemState.INTERRUPTED : r.s, at: Number(r.at), ...(r.o ? { outcome: r.o } : {}) });
75
+ }
76
+ try { compact(); } catch { /* giữ tệp cũ */ }
77
+ return entries;
78
+ }
79
+
80
+ return {
81
+ load,
82
+ started: (k) => { entries.set(k, { state: IdemState.START, at: now() }); write({ k, s: IdemState.START, at: now() }); },
83
+ done: (k, outcome) => {
84
+ const o = keptOutcome(outcome);
85
+ entries.set(k, { state: IdemState.DONE, at: now(), outcome: o });
86
+ write({ k, s: IdemState.DONE, at: now(), o });
87
+ },
88
+ failed: (k) => { entries.delete(k); write({ k, s: IdemState.FAIL, at: now() }); },
89
+ };
90
+ }
91
+
92
+ const markDeduplicated = (r) => ({
93
+ ...r,
94
+ outcome: r.outcome.ok && r.outcome.result && typeof r.outcome.result === 'object' ? { ...r.outcome, result: { ...r.outcome.result, deduplicated: true } } : r.outcome,
95
+ });
96
+
97
+ /**
98
+ * `run(call)` → Promise<{ tool, outcome }>; `isReadOnly(toolName)`. Trả hàm chạy có chống lặp + cờ báo lần trùng (`onDuplicate`). `file`: sổ
99
+ * trên đĩa (bỏ trống = chỉ trong bộ nhớ).
100
+ *
101
+ * `deferStart`: chỉ ghi "đã bắt đầu" ra đĩa khi `run` gọi `hooks.started()` (tham số cuối) — lời gọi còn chờ người bấm xác nhận trên máy
102
+ * thì chưa chạy gì; daemon khởi động lại lúc đó không được báo `INTERRUPTED` ("có thể đã chạy một phần") cho bước chưa hề chạy.
103
+ */
104
+ export function createIdempotentRunner(run, isReadOnly, { onDuplicate, now = () => Date.now(), file, deferStart = false } = {}) {
105
+ const seen = new Map();
106
+ const log = file ? createIdemLog(file, { now }) : null;
107
+ for (const [k, v] of log?.load() || []) {
108
+ const outcome = v.state === IdemState.DONE && v.outcome ? v.outcome : interruptedOutcome();
109
+ seen.set(k, { promise: Promise.resolve({ tool: undefined, outcome }), at: v.at });
110
+ }
111
+ return (call, ...rest) => {
112
+ if (!call.idem_key || isReadOnly(call.tool)) return run(call, ...rest);
113
+ const t = now();
114
+ for (const [k, v] of seen) {
115
+ if (t - v.at > IDEM_TTL_MS || seen.size > IDEM_MAX) seen.delete(k);
116
+ else break;
117
+ }
118
+ const key = call.idem_key;
119
+ const hit = seen.get(key);
120
+ if (hit) {
121
+ onDuplicate?.(call);
122
+ return hit.promise.then(markDeduplicated);
123
+ }
124
+ let marked = false;
125
+ const started = () => { if (!marked) { marked = true; log?.started(key); } };
126
+ if (!deferStart) started();
127
+ const promise = run(call, ...rest, ...(deferStart ? [{ started }] : []));
128
+ seen.set(key, { promise, at: t });
129
+ promise.then((r) => {
130
+ if (r.outcome.ok) log?.done(key, r.outcome);
131
+ else { seen.delete(key); log?.failed(key); }
132
+ }, () => { seen.delete(key); log?.failed(key); });
133
+ return promise;
134
+ };
135
+ }
@@ -0,0 +1,100 @@
1
+ import { spawn } from 'child_process';
2
+ import fs from 'fs';
3
+
4
+ /**
5
+ * Giữ máy không ngủ khi agent đang làm việc trên máy (29/10/2026). Trước đây máy tự ngủ giữa lúc chạy lệnh dài / tiến trình nền → mất
6
+ * kết nối, việc dở. Chỉ chặn ngủ do RẢNH (idle sleep): gập máy / bấm Sleep / pin cạn vẫn ngủ như thường.
7
+ *
8
+ * Một tiến trình phụ giữ cờ chặn ngủ của hệ điều hành, chỉ chạy khi bận: Windows `SetThreadExecutionState` (PowerShell), macOS
9
+ * `caffeinate -i`, Linux `systemd-inhibit`. Tiến trình phụ thoát khi stdin đóng / daemon chết → cờ tự gỡ, không kẹt máy thức mãi.
10
+ */
11
+
12
+ /** Bận ngắn hơn bấy nhiêu thì không bật (đọc tệp 50 ms không đáng mở tiến trình phụ). */
13
+ const START_DELAY_MS = 5_000;
14
+ /** Rảnh bấy nhiêu lâu rồi mới thả cờ (lô bước kế thường tới ngay sau). */
15
+ const IDLE_RELEASE_MS = 60_000;
16
+
17
+ const WINDOWS_SCRIPT = [
18
+ "$sig = '[DllImport(\"kernel32.dll\")] public static extern uint SetThreadExecutionState(uint esFlags);'",
19
+ "$k = Add-Type -MemberDefinition $sig -Name AivinAwake -Namespace Aivin -PassThru",
20
+ // ES_CONTINUOUS | ES_SYSTEM_REQUIRED: chặn ngủ do rảnh, KHÔNG giữ màn hình sáng.
21
+ '[void]$k::SetThreadExecutionState([uint32]2147483649)',
22
+ '[void][Console]::In.ReadToEnd()',
23
+ ].join('; ');
24
+
25
+ function hasLinuxInhibit() {
26
+ return ['/usr/bin/systemd-inhibit', '/bin/systemd-inhibit'].some((p) => fs.existsSync(p));
27
+ }
28
+
29
+ /** Lệnh giữ máy thức theo hệ điều hành — `null` khi không có cách nào. */
30
+ export function keepAwakeCommand(platform = process.platform, { pid = process.pid, linuxInhibit = hasLinuxInhibit } = {}) {
31
+ if (platform === 'win32') return { cmd: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_SCRIPT] };
32
+ if (platform === 'darwin') return { cmd: 'caffeinate', args: ['-i', '-w', String(pid)] };
33
+ if (platform === 'linux' && linuxInhibit()) {
34
+ return { cmd: 'systemd-inhibit', args: ['--what=idle:sleep', '--who=Aivin', '--why=Aivin agent is working on this computer', '--mode=block', 'cat'] };
35
+ }
36
+ return null;
37
+ }
38
+
39
+ /**
40
+ * `hold(reason)` / `release(reason)` đếm theo lý do (mỗi lời gọi đang chạy một lần, tiến trình nền một lần). Bận liên tục quá
41
+ * `startDelayMs` → bật; hết bận `idleMs` → tắt.
42
+ */
43
+ export function createKeepAwake({ enabled = true, platform = process.platform, spawnImpl = spawn, startDelayMs = START_DELAY_MS, idleMs = IDLE_RELEASE_MS, say } = {}) {
44
+ const command = enabled ? keepAwakeCommand(platform) : null;
45
+ let holds = 0;
46
+ let child = null;
47
+ let startTimer = null;
48
+ let stopTimer = null;
49
+
50
+ const startChild = () => {
51
+ startTimer = null;
52
+ if (child || holds <= 0 || !command) return;
53
+ try {
54
+ child = spawnImpl(command.cmd, command.args, { stdio: ['pipe', 'ignore', 'ignore'], windowsHide: true });
55
+ child.on('error', () => { child = null; });
56
+ child.on('exit', () => { child = null; });
57
+ say?.('☕ Đang có việc — giữ máy không tự ngủ');
58
+ } catch {
59
+ child = null;
60
+ }
61
+ };
62
+
63
+ const stopChild = () => {
64
+ stopTimer = null;
65
+ if (!child) return;
66
+ const c = child;
67
+ child = null;
68
+ try { c.stdin?.end(); } catch { /* đã đóng */ }
69
+ try { c.kill(); } catch { /* đã thoát */ }
70
+ };
71
+
72
+ return {
73
+ hold() {
74
+ holds++;
75
+ if (stopTimer) { clearTimeout(stopTimer); stopTimer = null; }
76
+ if (!child && !startTimer && command) {
77
+ startTimer = setTimeout(startChild, startDelayMs);
78
+ startTimer.unref?.();
79
+ }
80
+ },
81
+ release() {
82
+ holds = Math.max(0, holds - 1);
83
+ if (holds > 0) return;
84
+ if (startTimer) { clearTimeout(startTimer); startTimer = null; }
85
+ if (child && !stopTimer) {
86
+ stopTimer = setTimeout(stopChild, idleMs);
87
+ stopTimer.unref?.();
88
+ }
89
+ },
90
+ close() {
91
+ holds = 0;
92
+ if (startTimer) clearTimeout(startTimer);
93
+ if (stopTimer) clearTimeout(stopTimer);
94
+ startTimer = null;
95
+ stopChild();
96
+ },
97
+ active: () => !!child,
98
+ holds: () => holds,
99
+ };
100
+ }
@@ -0,0 +1,268 @@
1
+ import { spawn } from 'child_process';
2
+ import fs from 'fs';
3
+ import readline from 'readline';
4
+ import { AIVIN_BRAND, AIVIN_LOGO_PNG_BASE64 } from './brand.mjs';
5
+
6
+ /**
7
+ * Hộp "Cho phép / Từ chối" NGAY TRÊN MÁY cho việc sàn luật tại máy đòi xác nhận (localPolicy.mjs). BE không trả lời thay được: chỉ người
8
+ * ngồi trước máy bấm được. Windows: hộp riêng (WinForms qua PowerShell — tiêu đề, mục đích, lệnh trong khung chữ đơn cách, đếm ngược, hai
9
+ * nút tiếng Việt; trước đây là MessageBox Yes/No thô), macOS: `osascript display dialog`, Linux: zenity / kdialog khi có màn hình; không có
10
+ * màn hình mà daemon chạy trong terminal → hỏi trong terminal; không có cả hai → không hỏi được (việc bị từ chối).
11
+ * Mặc định là "Từ chối" (Enter / Esc / đóng hộp / hết giờ đều là từ chối).
12
+ */
13
+
14
+ /** `CANCELLED`: lời gọi bị huỷ (BE huỷ / hết giờ, tạm dừng, daemon dừng) trong lúc hộp đang chờ hoặc còn xếp hàng — hộp đóng, việc không chạy. */
15
+ export const ConfirmResult = Object.freeze({ ALLOW: 'allow', REJECT: 'reject', TIMEOUT: 'timeout', UNAVAILABLE: 'unavailable', CANCELLED: 'cancelled' });
16
+
17
+ const TITLE = 'Aivin — xác nhận trên máy này';
18
+ const HEADING = 'Agent Aivin xin chạy một việc trên máy này';
19
+ const ALLOW_LABEL = 'Cho phép';
20
+ const REJECT_LABEL = 'Từ chối';
21
+ const PURPOSE_PREFIX = 'Agent ghi: ';
22
+
23
+ const b64 = (s) => Buffer.from(String(s ?? ''), 'utf8').toString('base64');
24
+
25
+ const B = AIVIN_BRAND;
26
+
27
+ const fade = (target, to, ms) => `<DoubleAnimation Storyboard.TargetName="${target}" Storyboard.TargetProperty="Opacity" To="${to}" Duration="0:0:0.${String(ms).padStart(3, '0')}"/>`;
28
+ const press = (to) => ['ScaleX', 'ScaleY'].map((axis) =>
29
+ `<DoubleAnimation Storyboard.TargetName="root" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.${axis})" To="${to}" Duration="0:0:0.090"/>`).join('');
30
+
31
+ /**
32
+ * Nút bo góc (WPF không có sẵn): lớp phủ màu `Tag` (Binding, không TemplateBinding — TemplateBinding không đổi chuỗi màu sang Brush, lớp phủ
33
+ * không bao giờ hiện) hiện dần khi rê chuột (150 ms), nhấn thì thu nhỏ nhẹ, không viền chấm của WPF; phím tắt
34
+ * Alt + chữ gạch dưới. `radius`: bo góc của nút.
35
+ */
36
+ const buttonStyle = (key, radius) => `<Style x:Key="${key}" TargetType="Button">
37
+ <Setter Property="FontSize" Value="14"/><Setter Property="FontWeight" Value="SemiBold"/><Setter Property="Cursor" Value="Hand"/>
38
+ <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
39
+ <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button">
40
+ <Grid x:Name="root" RenderTransformOrigin="0.5,0.5" Background="Transparent">
41
+ <Grid.RenderTransform><ScaleTransform ScaleX="1" ScaleY="1"/></Grid.RenderTransform>
42
+ <Border x:Name="b" CornerRadius="${radius}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
43
+ BorderThickness="{TemplateBinding BorderThickness}"/>
44
+ <Border x:Name="h" CornerRadius="${radius}" Background="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}}" Opacity="0"/>
45
+ <ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
46
+ </Grid>
47
+ <ControlTemplate.Triggers>
48
+ <Trigger Property="IsMouseOver" Value="True">
49
+ <Trigger.EnterActions><BeginStoryboard><Storyboard>${fade('h', 1, 150)}</Storyboard></BeginStoryboard></Trigger.EnterActions>
50
+ <Trigger.ExitActions><BeginStoryboard><Storyboard>${fade('h', 0, 200)}</Storyboard></BeginStoryboard></Trigger.ExitActions>
51
+ </Trigger>
52
+ <Trigger Property="IsPressed" Value="True">
53
+ <Trigger.EnterActions><BeginStoryboard><Storyboard>${press(0.97)}</Storyboard></BeginStoryboard></Trigger.EnterActions>
54
+ <Trigger.ExitActions><BeginStoryboard><Storyboard>${press(1)}</Storyboard></BeginStoryboard></Trigger.ExitActions>
55
+ </Trigger>
56
+ </ControlTemplate.Triggers>
57
+ </ControlTemplate></Setter.Value></Setter>
58
+ </Style>`;
59
+
60
+ /** Thẻ hiện ra: mờ → rõ + phóng nhẹ 0,96 → 1 (180 ms, chậm dần); đóng: ngược lại 120 ms rồi mới đóng cửa sổ. */
61
+ const cardMotion = (key, opacity, scale, ms, ease) => `<Storyboard x:Key="${key}">
62
+ <DoubleAnimation Storyboard.TargetProperty="Opacity" To="${opacity}" Duration="0:0:0.${ms}"/>
63
+ ${['ScaleX', 'ScaleY'].map((axis) => `<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.${axis})" To="${scale}" Duration="0:0:0.${ms}"><DoubleAnimation.EasingFunction><CubicEase EasingMode="${ease}"/></DoubleAnimation.EasingFunction></DoubleAnimation>`).join('\n ')}
64
+ </Storyboard>`;
65
+
66
+ /**
67
+ * Thẻ xác nhận theo nhận diện Aivin (logo + dải màu của logo, bo góc như hộp xác nhận trên web): không viền hệ thống, kéo được ở phần đầu,
68
+ * chip cảnh báo, khối lệnh chữ đơn cách, đếm ngược, "Từ chối" là nút mặc định (Enter / Esc / nút ×).
69
+ */
70
+ const WINDOWS_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
71
+ Width="520" SizeToContent="Height" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="NoResize"
72
+ Topmost="True" ShowInTaskbar="True" WindowStartupLocation="CenterScreen" FontFamily="Segoe UI" UseLayoutRounding="True">
73
+ <Window.Resources>
74
+ ${buttonStyle('Btn', 10)}
75
+ ${buttonStyle('IconBtn', 8)}
76
+ ${cardMotion('In', 1, 1, 180, 'EaseOut')}
77
+ ${cardMotion('Out', 0, 0.97, 120, 'EaseIn')}
78
+ </Window.Resources>
79
+ <Border x:Name="Card" Margin="20" CornerRadius="18" Background="White" BorderBrush="#E5E6EB" BorderThickness="1" Opacity="0" RenderTransformOrigin="0.5,0.5">
80
+ <Border.RenderTransform><ScaleTransform ScaleX="0.96" ScaleY="0.96"/></Border.RenderTransform>
81
+ <Border.Effect><DropShadowEffect BlurRadius="30" ShadowDepth="8" Direction="270" Opacity="0.18" Color="#0B1B3F"/></Border.Effect>
82
+ <StackPanel Margin="26,20,22,24">
83
+ <DockPanel x:Name="Head" Background="Transparent" LastChildFill="False">
84
+ <Image x:Name="Logo" Width="26" Height="26" RenderOptions.BitmapScalingMode="HighQuality" VerticalAlignment="Center"/>
85
+ <TextBlock Text="Aivin" FontSize="15" FontWeight="SemiBold" Foreground="${B.ink}" Margin="9,0,0,0" VerticalAlignment="Center"/>
86
+ <TextBlock x:Name="Sub" FontSize="13" Foreground="${B.muted}" Margin="8,1,0,0" VerticalAlignment="Center"/>
87
+ <Button x:Name="Close" DockPanel.Dock="Right" Style="{StaticResource IconBtn}" Content="✕" Width="32" Height="32" FontSize="12" FontWeight="Normal"
88
+ Background="Transparent" BorderThickness="0" Tag="#F2F3F5" Foreground="${B.muted}" ToolTip="Từ chối" IsTabStop="False"/>
89
+ </DockPanel>
90
+ <TextBlock x:Name="Heading" Margin="0,20,0,0" FontSize="20" FontWeight="SemiBold" Foreground="${B.ink}" TextWrapping="Wrap"/>
91
+ <Border Margin="0,12,0,0" HorizontalAlignment="Left" CornerRadius="12" Background="${B.warnBg}" Padding="11,5">
92
+ <TextBlock x:Name="Reason" Foreground="${B.warn}" FontSize="13" FontWeight="SemiBold" TextWrapping="Wrap"/>
93
+ </Border>
94
+ <TextBlock x:Name="Purpose" Margin="0,14,0,0" FontSize="14" Foreground="${B.body}" TextWrapping="Wrap" LineHeight="20"/>
95
+ <TextBlock x:Name="DetailLabel" Margin="0,16,0,6" FontSize="12" Foreground="${B.muted}"/>
96
+ <Border CornerRadius="10" Background="#F4F6FA" BorderBrush="#E8ECF3" BorderThickness="1" Padding="14,11">
97
+ <ScrollViewer MaxHeight="150" VerticalScrollBarVisibility="Auto">
98
+ <TextBlock x:Name="Detail" FontFamily="Cascadia Mono, Consolas" FontSize="13" Foreground="${B.ink}" TextWrapping="Wrap"/>
99
+ </ScrollViewer>
100
+ </Border>
101
+ <DockPanel Margin="0,24,0,0" LastChildFill="False">
102
+ <TextBlock x:Name="Countdown" VerticalAlignment="Center" FontSize="12" Foreground="${B.muted}"/>
103
+ <Button x:Name="Allow" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0" Margin="10,0,0,0"
104
+ Background="${B.brand}" Foreground="White" BorderThickness="0" Tag="#26000000"/>
105
+ <Button x:Name="Reject" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0"
106
+ Background="White" Foreground="${B.ink}" BorderBrush="#C9CDD4" BorderThickness="1" Tag="#0F000000" IsCancel="True" IsDefault="True"/>
107
+ </DockPanel>
108
+ </StackPanel>
109
+ </Border>
110
+ </Window>`;
111
+
112
+ /** Dựng thẻ WPF từ biến môi trường base64 (không phải thoát dấu nháy), in Yes / No / Timeout ra stdout. */
113
+ const WINDOWS_SCRIPT = [
114
+ 'Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase',
115
+ 'function D($n) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Environment]::GetEnvironmentVariable($n))) }',
116
+ "$w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml](D 'AIVIN_C_XAML'))))",
117
+ "$w.Title = D 'AIVIN_C_TITLE'",
118
+ "foreach ($n in 'Sub', 'Heading', 'Reason', 'Purpose', 'DetailLabel', 'Detail') { $w.FindName($n).Text = D ('AIVIN_C_' + $n.ToUpper()) }",
119
+ "if (-not $w.FindName('Purpose').Text) { $w.FindName('Purpose').Visibility = 'Collapsed' }",
120
+ "$w.FindName('Allow').Content = D 'AIVIN_C_ALLOW'; $w.FindName('Reject').Content = D 'AIVIN_C_REJECT'",
121
+ "$ms = New-Object IO.MemoryStream(, [Convert]::FromBase64String($env:AIVIN_C_LOGO)); $img = New-Object Windows.Media.Imaging.BitmapImage",
122
+ "$img.BeginInit(); $img.StreamSource = $ms; $img.CacheOption = 'OnLoad'; $img.EndInit(); $w.FindName('Logo').Source = $img",
123
+ "$script:result = 'No'; $script:closing = $false; $card = $w.FindName('Card')",
124
+ '$tm = New-Object Windows.Threading.DispatcherTimer; $tm.Interval = [TimeSpan]::FromSeconds(1)',
125
+ // Đóng có hiệu ứng: chạy storyboard "Out" rồi mới đóng cửa sổ; bấm liên tiếp chỉ tính lần đầu.
126
+ "function Finish($r) { if ($script:closing) { return }; $script:closing = $true; $script:result = $r; $tm.Stop(); $sb = $w.FindResource('Out').Clone(); $sb.Add_Completed({ $w.Close() }); $sb.Begin($card) }",
127
+ "$w.FindName('Allow').Add_Click({ Finish 'Yes' })",
128
+ "$w.FindName('Reject').Add_Click({ Finish 'No' }); $w.FindName('Close').Add_Click({ Finish 'No' })",
129
+ "$w.FindName('Head').Add_MouseLeftButtonDown({ $w.DragMove() })",
130
+ "$script:left = [int]$env:AIVIN_C_SECONDS; $fmt = D 'AIVIN_C_COUNTDOWN'; $cd = $w.FindName('Countdown'); $cd.Text = $fmt -f $script:left",
131
+ "$tm.Add_Tick({ $script:left--; $cd.Text = $fmt -f $script:left; if ($script:left -le 0) { Finish 'Timeout' } })",
132
+ "$w.Add_ContentRendered({ $w.FindResource('In').Begin($card); $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
133
+ '[void]$w.ShowDialog(); $tm.Stop(); $script:result',
134
+ ].join('\n');
135
+
136
+ /** Nội dung chữ thường (macOS / Linux / terminal): lý do, mục đích agent ghi, lệnh. */
137
+ function plainText({ reason, purpose, detail }) {
138
+ return [HEADING, '', `⚠ ${reason}`, ...(purpose ? [`${PURPOSE_PREFIX}${purpose}`] : []), '', detail].join('\n');
139
+ }
140
+
141
+ const hasExe = (candidates) => candidates.some((p) => fs.existsSync(p));
142
+
143
+ /** Lệnh hiện hộp xác nhận theo hệ điều hành + cách đọc kết quả — `null` khi máy không hiện được hộp. */
144
+ export function confirmCommand({ request, timeoutSec, platform = process.platform, env = process.env, exists = hasExe }) {
145
+ if (platform === 'win32') {
146
+ return {
147
+ cmd: 'powershell.exe',
148
+ args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_SCRIPT],
149
+ env: {
150
+ AIVIN_C_XAML: b64(WINDOWS_XAML), AIVIN_C_LOGO: AIVIN_LOGO_PNG_BASE64, AIVIN_C_TITLE: b64(TITLE),
151
+ AIVIN_C_SUB: b64('Xác nhận trên máy này'), AIVIN_C_HEADING: b64('Cho phép agent làm việc này trên máy?'),
152
+ AIVIN_C_REASON: b64(`⚠ ${request.reason}`), AIVIN_C_PURPOSE: b64(request.purpose ? `${PURPOSE_PREFIX}${request.purpose}` : ''),
153
+ AIVIN_C_DETAILLABEL: b64('SẼ THỰC HIỆN'), AIVIN_C_DETAIL: b64(request.detail),
154
+ AIVIN_C_ALLOW: b64(`_${ALLOW_LABEL}`), AIVIN_C_REJECT: b64(`_${REJECT_LABEL}`),
155
+ AIVIN_C_COUNTDOWN: b64('Tự từ chối sau {0} giây'), AIVIN_C_SECONDS: String(timeoutSec),
156
+ },
157
+ parse: (out, code) => (code !== 0 ? ConfirmResult.UNAVAILABLE : /\bYes\b/.test(out) ? ConfirmResult.ALLOW
158
+ : /\bTimeout\b/.test(out) ? ConfirmResult.TIMEOUT : ConfirmResult.REJECT),
159
+ };
160
+ }
161
+ const text = plainText(request);
162
+ if (platform === 'darwin') {
163
+ return {
164
+ cmd: 'osascript',
165
+ args: ['-e', 'on run argv',
166
+ '-e', `display dialog (item 1 of argv) with title (item 2 of argv) buttons {"${REJECT_LABEL}", "${ALLOW_LABEL}"} default button "${REJECT_LABEL}" cancel button "${REJECT_LABEL}" with icon caution giving up after ((item 3 of argv) as integer)`,
167
+ '-e', 'end run', text, TITLE, String(timeoutSec)],
168
+ parse: (out, code) => (/gave up:true/.test(out) ? ConfirmResult.TIMEOUT : code === 0 && out.includes(ALLOW_LABEL) ? ConfirmResult.ALLOW : ConfirmResult.REJECT),
169
+ };
170
+ }
171
+ if (platform === 'linux' && (env.DISPLAY || env.WAYLAND_DISPLAY)) {
172
+ if (exists(['/usr/bin/zenity', '/bin/zenity'])) {
173
+ return {
174
+ cmd: 'zenity',
175
+ args: ['--question', '--title', TITLE, '--text', text, '--no-markup', '--ok-label', ALLOW_LABEL, '--cancel-label', REJECT_LABEL, '--default-cancel', '--timeout', String(timeoutSec)],
176
+ parse: (_out, code) => (code === 0 ? ConfirmResult.ALLOW : code === 5 ? ConfirmResult.TIMEOUT : ConfirmResult.REJECT),
177
+ };
178
+ }
179
+ if (exists(['/usr/bin/kdialog', '/bin/kdialog'])) {
180
+ return {
181
+ cmd: 'kdialog',
182
+ args: ['--title', TITLE, '--yesno', text, '--yes-label', ALLOW_LABEL, '--no-label', REJECT_LABEL],
183
+ parse: (_out, code) => (code === 0 ? ConfirmResult.ALLOW : ConfirmResult.REJECT),
184
+ };
185
+ }
186
+ }
187
+ return null;
188
+ }
189
+
190
+ function runDialog(command, timeoutSec, spawnImpl, signal) {
191
+ return new Promise((resolve) => {
192
+ let out = '';
193
+ let settled = false;
194
+ let child;
195
+ let timer;
196
+ const kill = () => { try { child?.kill(); } catch { /* đã thoát */ } };
197
+ const onAbort = () => { kill(); done(ConfirmResult.CANCELLED); };
198
+ const done = (r) => {
199
+ if (settled) return;
200
+ settled = true;
201
+ clearTimeout(timer);
202
+ signal?.removeEventListener('abort', onAbort);
203
+ resolve(r);
204
+ };
205
+ try {
206
+ child = spawnImpl(command.cmd, command.args, { env: { ...process.env, ...(command.env || {}) }, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: false });
207
+ } catch {
208
+ return done(ConfirmResult.UNAVAILABLE);
209
+ }
210
+ // Cộng 10 s cho hộp tự hết giờ (đếm ngược / macOS / zenity; PowerShell nạp WinForms mất vài giây) trước khi tự giết.
211
+ timer = setTimeout(() => { kill(); done(ConfirmResult.TIMEOUT); }, (timeoutSec + 10) * 1000);
212
+ signal?.addEventListener('abort', onAbort, { once: true });
213
+ child.stdout?.on('data', (d) => { out += d; });
214
+ child.on('error', () => done(ConfirmResult.UNAVAILABLE));
215
+ child.on('close', (code) => done(command.parse(out, code)));
216
+ });
217
+ }
218
+
219
+ function askInTerminal(request, timeoutSec, signal) {
220
+ return new Promise((resolve) => {
221
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
222
+ let settled = false;
223
+ const done = (r) => {
224
+ if (settled) return;
225
+ settled = true;
226
+ clearTimeout(timer);
227
+ signal?.removeEventListener('abort', onAbort);
228
+ rl.close();
229
+ resolve(r);
230
+ };
231
+ const onAbort = () => done(ConfirmResult.CANCELLED);
232
+ const timer = setTimeout(() => done(ConfirmResult.TIMEOUT), timeoutSec * 1000);
233
+ signal?.addEventListener('abort', onAbort, { once: true });
234
+ rl.question(`\n${plainText(request)}\n Gõ "c" rồi Enter để ${ALLOW_LABEL.toLowerCase()} (Enter = ${REJECT_LABEL.toLowerCase()}, tự từ chối sau ${timeoutSec} s): `, (answer) => {
235
+ done(/^\s*(c|co|có|y|yes)\s*$/i.test(answer) ? ConfirmResult.ALLOW : ConfirmResult.REJECT);
236
+ });
237
+ });
238
+ }
239
+
240
+ /**
241
+ * Bộ hỏi xác nhận: mỗi lúc một hộp (lời gọi song song xếp hàng). `ask({ reason, purpose?, detail, timeoutSec, signal?, onStart? })` →
242
+ * `ConfirmResult`. `reason`: vì sao cần hỏi (do máy tự xét), `purpose`: mục đích agent ghi (từ BE — chỉ để tham khảo), `detail`: lệnh /
243
+ * đối tượng thật. `signal` huỷ → hộp đang mở đóng lại / hộp còn xếp hàng không hiện, trả `CANCELLED`. `onStart(queuedMs)`: gọi đúng lúc
244
+ * hộp này tới lượt hiện (đã xếp hàng bấy nhiêu ms) — để xin BE lùi hạn thêm phần đã chờ. `tty`: daemon đang chạy trong terminal tương tác
245
+ * (dự phòng khi không hiện được hộp).
246
+ */
247
+ export function createLocalConfirmer({ platform = process.platform, spawnImpl = spawn, tty = !!(process.stdin.isTTY && process.stdout.isTTY), env = process.env } = {}) {
248
+ let queue = Promise.resolve();
249
+ const askOnce = async ({ timeoutSec, signal, onStart, queuedAt, ...request }) => {
250
+ if (signal?.aborted) return ConfirmResult.CANCELLED;
251
+ onStart?.(Date.now() - queuedAt);
252
+ const command = confirmCommand({ request, timeoutSec, platform, env });
253
+ if (command) {
254
+ const result = await runDialog(command, timeoutSec, spawnImpl, signal);
255
+ if (result !== ConfirmResult.UNAVAILABLE) return result;
256
+ }
257
+ if (signal?.aborted) return ConfirmResult.CANCELLED;
258
+ return tty ? askInTerminal(request, timeoutSec, signal) : ConfirmResult.UNAVAILABLE;
259
+ };
260
+ return {
261
+ ask(req) {
262
+ const queuedAt = Date.now();
263
+ const p = queue.then(() => askOnce({ ...req, queuedAt }));
264
+ queue = p.catch(() => undefined);
265
+ return p;
266
+ },
267
+ };
268
+ }