@aivin-labs/cli 1.0.5 → 1.0.11

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 (93) hide show
  1. package/README.md +288 -216
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +551 -5
  4. package/bin/lib/browserAutomation.mjs +384 -614
  5. package/bin/lib/browserTui.mjs +276 -251
  6. package/bin/lib/cancellation.mjs +61 -0
  7. package/bin/lib/localBrowser.mjs +345 -0
  8. package/bin/lib/mcpProxy.mjs +869 -837
  9. package/bin/lib/missionStream.mjs +696 -691
  10. package/bin/lib/releaseKeys.mjs +9 -0
  11. package/bin/lib/remote/activityLog.mjs +68 -0
  12. package/bin/lib/remote/autoStart.mjs +617 -0
  13. package/bin/lib/remote/autoUpdate.mjs +129 -0
  14. package/bin/lib/remote/brand.mjs +60 -0
  15. package/bin/lib/remote/browserTunnel.mjs +403 -0
  16. package/bin/lib/remote/callLedger.mjs +134 -0
  17. package/bin/lib/remote/cdpPolicy.mjs +79 -0
  18. package/bin/lib/remote/client.mjs +808 -0
  19. package/bin/lib/remote/clipboard.mjs +138 -0
  20. package/bin/lib/remote/codingAgents.mjs +293 -0
  21. package/bin/lib/remote/constants.mjs +234 -0
  22. package/bin/lib/remote/credentials.mjs +208 -0
  23. package/bin/lib/remote/daemonLock.mjs +86 -0
  24. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  25. package/bin/lib/remote/desktop/index.mjs +272 -0
  26. package/bin/lib/remote/desktop/linux.mjs +144 -0
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  28. package/bin/lib/remote/desktop/mac.mjs +187 -0
  29. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  30. package/bin/lib/remote/desktop/strings.mjs +74 -0
  31. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  32. package/bin/lib/remote/deviceMemory.mjs +246 -0
  33. package/bin/lib/remote/deviceProfile.mjs +142 -0
  34. package/bin/lib/remote/deviceWatches.mjs +138 -0
  35. package/bin/lib/remote/docText.mjs +117 -0
  36. package/bin/lib/remote/fileIndexer.mjs +399 -0
  37. package/bin/lib/remote/gui/index.mjs +326 -0
  38. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  39. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  40. package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
  41. package/bin/lib/remote/httpTransfer.mjs +89 -0
  42. package/bin/lib/remote/idempotency.mjs +135 -0
  43. package/bin/lib/remote/keepAwake.mjs +100 -0
  44. package/bin/lib/remote/localConfirm.mjs +268 -0
  45. package/bin/lib/remote/localPolicy.mjs +256 -0
  46. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  47. package/bin/lib/remote/mascot/ask.mjs +768 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  49. package/bin/lib/remote/mascot/assets.mjs +827 -0
  50. package/bin/lib/remote/mascot/bot.mjs +372 -0
  51. package/bin/lib/remote/mascot/hostSource.mjs +759 -0
  52. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  53. package/bin/lib/remote/mascot/index.mjs +493 -0
  54. package/bin/lib/remote/mascot/labels.mjs +82 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  56. package/bin/lib/remote/mascot/strings.mjs +375 -0
  57. package/bin/lib/remote/mascot/ui.mjs +104 -0
  58. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  59. package/bin/lib/remote/meeting/index.mjs +415 -0
  60. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  61. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  62. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  63. package/bin/lib/remote/memberFsPool.mjs +134 -0
  64. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  65. package/bin/lib/remote/mission.mjs +156 -0
  66. package/bin/lib/remote/missionQuestion.mjs +63 -0
  67. package/bin/lib/remote/multiUser.mjs +344 -0
  68. package/bin/lib/remote/netProxy.mjs +145 -0
  69. package/bin/lib/remote/notify.mjs +58 -0
  70. package/bin/lib/remote/office/index.mjs +90 -0
  71. package/bin/lib/remote/policyCommand.mjs +93 -0
  72. package/bin/lib/remote/processes.mjs +217 -0
  73. package/bin/lib/remote/sandbox.mjs +221 -0
  74. package/bin/lib/remote/schedule.mjs +213 -0
  75. package/bin/lib/remote/scheduler.mjs +124 -0
  76. package/bin/lib/remote/tabGroups.mjs +209 -0
  77. package/bin/lib/remote/textIndex.mjs +131 -0
  78. package/bin/lib/remote/tokenStore.mjs +77 -0
  79. package/bin/lib/remote/toolHandlers.mjs +741 -0
  80. package/bin/lib/remote/undoStore.mjs +242 -0
  81. package/bin/lib/remoteControl.mjs +26 -0
  82. package/bin/lib/scaffold.mjs +654 -653
  83. package/bin/lib/selfUpdate.mjs +71 -0
  84. package/bin/lib/update/binarySwap.mjs +63 -0
  85. package/bin/lib/update/constants.mjs +56 -0
  86. package/bin/lib/update/download.mjs +145 -0
  87. package/bin/lib/update/signature.mjs +42 -0
  88. package/bin/lib/update/state.mjs +205 -0
  89. package/bin/lib/update/versions.mjs +60 -0
  90. package/docs/AIVIN_MASCOT.md +116 -0
  91. package/docs/CLI.md +1484 -1299
  92. package/docs/media/aivin-mascot-states.mp4 +0 -0
  93. package/package.json +71 -62
@@ -0,0 +1,134 @@
1
+ import { fork } from 'child_process';
2
+ import { fileURLToPath } from 'url';
3
+ import { DeviceErrorCode } from './constants.mjs';
4
+ import { DeviceToolError } from './sandbox.mjs';
5
+
6
+ /**
7
+ * Công cụ tệp của máy tính tổ chức chạy trong tiến trình con DƯỚI TÀI KHOẢN THÀNH VIÊN (mỗi vùng một tiến trình, dùng lại giữa các lời
8
+ * gọi). Daemon chạy root: nếu root tự đọc / ghi thì thành viên tráo một thư mục thành symlink giữa lúc kiểm đường và lúc dùng là root đọc
9
+ * / ghi được mọi nơi (nhà người khác, thư mục token, /etc). Chạy bằng uid của thành viên thì nhân Linux tự chặn phần họ không có quyền.
10
+ *
11
+ * Giao thức IPC: `{ id, tool, args, timeoutMs }` → `{ id, ok, result | error, error_code }`; huỷ: `{ cancel: id }`. Rảnh quá `idleMs` thì
12
+ * tắt, chết giữa chừng thì lời gọi đang chờ báo lỗi và lần sau dựng lại.
13
+ */
14
+
15
+ export const MEMBER_FS_WORKER_PATH = fileURLToPath(new URL('./memberFsWorker.mjs', import.meta.url));
16
+ export const MEMBER_FS_IDLE_MS = 10 * 60_000;
17
+ /** Biến môi trường mang cấu hình cho tiến trình con (gốc, chương trình có trên máy, uid mong đợi). */
18
+ export const MEMBER_FS_CONFIG_ENV = 'AIVIN_FS_WORKER_CONFIG';
19
+
20
+ /** Công cụ nào chạy trong tiến trình của thành viên: mọi `fs.*` — công cụ tệp thêm sau này mặc định cũng không chạy bằng root. */
21
+ export function runsInMemberWorker(toolName) {
22
+ return typeof toolName === 'string' && toolName.startsWith('fs.');
23
+ }
24
+
25
+ /**
26
+ * `envOf(account)` → biến môi trường cho tiến trình con (đã lọc bí mật, HOME / USER của thành viên). `rootsOf(account)` → gốc được phép.
27
+ * `account` = { name, home, uid?, gid? } — không có uid (Windows / test) thì chạy cùng tài khoản hiện tại.
28
+ */
29
+ export function createMemberFsPool({ envOf, rootsOf, binaries = [], idleMs = MEMBER_FS_IDLE_MS, workerPath = MEMBER_FS_WORKER_PATH } = {}) {
30
+ const workers = new Map();
31
+ let seq = 0;
32
+
33
+ function stopWorker(state) {
34
+ clearTimeout(state.idleTimer);
35
+ state.idleTimer = null;
36
+ try { state.child.disconnect(); } catch { /* đã ngắt */ }
37
+ // Tiến trình con thoát khi mất kênh IPC; không thoát kịp thì giết.
38
+ const killer = setTimeout(() => { if (state.child.exitCode === null && state.child.signalCode === null) state.child.kill('SIGKILL'); }, 2000);
39
+ killer.unref?.();
40
+ }
41
+
42
+ function touch(state) {
43
+ if (state.pending.size || state.idleTimer) return;
44
+ state.idleTimer = setTimeout(() => {
45
+ state.idleTimer = null;
46
+ if (!state.pending.size) {
47
+ if (workers.get(state.name) === state) workers.delete(state.name);
48
+ stopWorker(state);
49
+ }
50
+ }, idleMs);
51
+ state.idleTimer.unref?.();
52
+ }
53
+
54
+ function failAll(state, error) {
55
+ for (const p of state.pending.values()) p.fail(error);
56
+ state.pending.clear();
57
+ }
58
+
59
+ function spawnWorker(account) {
60
+ const hasIds = typeof account.uid === 'number' && typeof process.getuid === 'function';
61
+ const config = { roots: rootsOf(account), binaries, ...(hasIds ? { expectUid: account.uid } : {}) };
62
+ const child = fork(workerPath, [], {
63
+ cwd: account.home,
64
+ env: { ...envOf(account), [MEMBER_FS_CONFIG_ENV]: JSON.stringify(config) },
65
+ serialization: 'advanced',
66
+ stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
67
+ ...(hasIds ? { uid: account.uid, gid: account.gid } : {}),
68
+ });
69
+ const state = { name: account.name, child, pending: new Map(), idleTimer: null };
70
+ const onGone = (reason) => {
71
+ if (workers.get(account.name) === state) workers.delete(account.name);
72
+ clearTimeout(state.idleTimer);
73
+ failAll(state, new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `File worker stopped (${reason}) — retry the call`));
74
+ };
75
+ child.on('message', (msg) => {
76
+ const p = msg && state.pending.get(msg.id);
77
+ if (!p) return;
78
+ state.pending.delete(msg.id);
79
+ p.settle(msg);
80
+ touch(state);
81
+ });
82
+ child.on('exit', (code, signal) => onGone(signal || `exit ${code}`));
83
+ child.on('error', (e) => onGone(e.message));
84
+ workers.set(account.name, state);
85
+ return state;
86
+ }
87
+
88
+ function workerFor(account) {
89
+ const current = workers.get(account.name);
90
+ if (current && current.child.connected && current.child.exitCode === null) return current;
91
+ return spawnWorker(account);
92
+ }
93
+
94
+ /** Chạy một công cụ tệp trong tiến trình của thành viên. `ctx.signal` huỷ → báo tiến trình con dừng, trả lỗi ngay. */
95
+ function call(account, tool, args, { signal, timeoutMs } = {}) {
96
+ return new Promise((resolve, reject) => {
97
+ if (signal?.aborted) return reject(signal.reason || new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled'));
98
+ const state = workerFor(account);
99
+ clearTimeout(state.idleTimer);
100
+ state.idleTimer = null;
101
+ const id = ++seq;
102
+ const onAbort = () => {
103
+ if (!state.pending.delete(id)) return;
104
+ try { state.child.send({ cancel: id }); } catch { /* đã chết */ }
105
+ reject(signal.reason || new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled'));
106
+ touch(state);
107
+ };
108
+ const done = () => signal?.removeEventListener('abort', onAbort);
109
+ state.pending.set(id, {
110
+ settle: (msg) => {
111
+ done();
112
+ if (msg.ok) resolve(msg.result);
113
+ else reject(new DeviceToolError(msg.error_code || DeviceErrorCode.EXECUTION_FAILED, msg.error || 'File worker failed'));
114
+ },
115
+ fail: (e) => { done(); reject(e); },
116
+ });
117
+ signal?.addEventListener('abort', onAbort, { once: true });
118
+ try {
119
+ state.child.send({ id, tool, args: args || {}, timeoutMs }, (err) => {
120
+ if (err && state.pending.delete(id)) { done(); reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `File worker unavailable: ${err.message}`)); }
121
+ });
122
+ } catch (e) {
123
+ if (state.pending.delete(id)) { done(); reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `File worker unavailable: ${e.message}`)); }
124
+ }
125
+ });
126
+ }
127
+
128
+ function closeAll() {
129
+ for (const state of workers.values()) stopWorker(state);
130
+ workers.clear();
131
+ }
132
+
133
+ return { call, closeAll, size: () => workers.size, pidOf: (name) => workers.get(name)?.child.pid };
134
+ }
@@ -0,0 +1,60 @@
1
+ import { DeviceErrorCode } from './constants.mjs';
2
+ import { DeviceToolError } from './sandbox.mjs';
3
+ import { buildTools, toolMap } from './toolHandlers.mjs';
4
+ import { MEMBER_FS_CONFIG_ENV, runsInMemberWorker } from './memberFsPool.mjs';
5
+
6
+ /**
7
+ * Tiến trình con chạy công cụ tệp dưới tài khoản một thành viên máy tính tổ chức (xem memberFsPool.mjs). Dùng đúng các handler `fs.*`
8
+ * của toolHandlers.mjs với gốc = thư mục nhà của thành viên + thư mục chung; không giữ bí mật nào của daemon.
9
+ */
10
+
11
+ function readConfig() {
12
+ try { return JSON.parse(process.env[MEMBER_FS_CONFIG_ENV] || '{}') || {}; } catch { return {}; }
13
+ }
14
+ const config = readConfig();
15
+ delete process.env[MEMBER_FS_CONFIG_ENV];
16
+
17
+ // Lưới cuối: đổi tài khoản không thành (vẫn là root / sai uid) thì không chạy gì cả.
18
+ if (typeof config.expectUid === 'number' && process.getuid?.() !== config.expectUid) {
19
+ console.error(`[aivin fs worker] wrong uid ${process.getuid?.()} (expected ${config.expectUid}) — exiting`);
20
+ process.exit(70);
21
+ }
22
+
23
+ const env = { roots: Array.isArray(config.roots) ? config.roots : [], binaries: Array.isArray(config.binaries) ? config.binaries : [], projects: [], fileIndex: null };
24
+ const tools = toolMap(buildTools(env).filter((t) => runsInMemberWorker(t.name)));
25
+ const inflight = new Map();
26
+
27
+ function reply(payload) {
28
+ try { process.send?.(payload); } catch { /* daemon đã ngắt */ }
29
+ }
30
+
31
+ async function runCall({ id, tool, args, timeoutMs }) {
32
+ const spec = tools.get(tool);
33
+ if (!spec) return reply({ id, ok: false, error: `Unknown tool: ${tool}`, error_code: DeviceErrorCode.TOOL_UNKNOWN });
34
+ const controller = new AbortController();
35
+ inflight.set(id, controller);
36
+ const ms = Math.max(1000, Number(timeoutMs) || 60_000);
37
+ const timer = setTimeout(() => controller.abort(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, `Timed out after ${ms} ms`)), ms);
38
+ try {
39
+ const result = await spec.handler(args && typeof args === 'object' ? args : {}, { signal: controller.signal, timeoutMs: ms }, env);
40
+ reply({ id, ok: true, result });
41
+ } catch (error) {
42
+ const reason = controller.signal.aborted ? controller.signal.reason : error;
43
+ reply({ id, ok: false, error: reason?.message || String(reason), error_code: reason?.code || DeviceErrorCode.EXECUTION_FAILED });
44
+ } finally {
45
+ clearTimeout(timer);
46
+ inflight.delete(id);
47
+ }
48
+ }
49
+
50
+ process.on('message', (msg) => {
51
+ if (!msg || typeof msg !== 'object') return;
52
+ if (msg.cancel !== undefined) {
53
+ inflight.get(msg.cancel)?.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled by server'));
54
+ return;
55
+ }
56
+ void runCall(msg).catch((e) => reply({ id: msg.id, ok: false, error: e?.message || String(e), error_code: DeviceErrorCode.EXECUTION_FAILED }));
57
+ });
58
+ // Daemon thoát / tắt vì rảnh → kênh IPC đóng → tiến trình con thoát theo.
59
+ process.on('disconnect', () => process.exit(0));
60
+ process.on('unhandledRejection', (e) => console.error('[aivin fs worker] unhandled rejection:', e?.message || e));
@@ -0,0 +1,156 @@
1
+ import axios from 'axios';
2
+ import chalk from 'chalk';
3
+ import { randomUUID } from 'crypto';
4
+ import { io } from 'socket.io-client';
5
+ import { MISSION_LOG_EVENTS } from '../missionStream.mjs';
6
+ import { missionAuthHeaders, missionServerUrl, resolveAgentId, resolveWorkspace } from '../workspace.mjs';
7
+ import { DEVICE_API_PREFIX } from './constants.mjs';
8
+ import { deviceTokenClient, loadDeviceCredentials } from './credentials.mjs';
9
+ import { ANSWER_STATUS, askDirectQuestion } from './missionQuestion.mjs';
10
+
11
+ /** event_key kết thúc nhiệm vụ của Device Agent (BE `clientLog`). */
12
+ const DONE_KEYS = new Set(['device_agent.done', 'device_agent.failed', 'device_agent.cancelled']);
13
+
14
+ /** Dòng báo nhiệm vụ đang chờ người trả lời (BE `DEVICE_AWAITING_USER_EVENT`) — meta mang câu hỏi đã đọc cấu trúc. */
15
+ const AWAITING_USER_KEY = 'device_agent.awaiting_user';
16
+
17
+ /** Câu hỏi đang chờ: lấy trong meta của dòng tiến trình, thiếu thì hỏi BE. */
18
+ async function loadQuestion(api, sessionId, payload) {
19
+ if (payload?.meta?.direct_question) return payload.meta.direct_question;
20
+ const res = await axios.get(`${api.serverUrl}${DEVICE_API_PREFIX}/missions/${encodeURIComponent(sessionId)}/question`, api.authHeaders).catch(() => null);
21
+ return res?.data?.question || null;
22
+ }
23
+
24
+ /**
25
+ * Hỏi trong terminal rồi gửi câu trả lời; BE báo không khớp thì hỏi lại. Dòng tiến trình mới tới (đã trả lời trên web, việc chạy tiếp)
26
+ * → `signal` huỷ câu hỏi đang gõ dở.
27
+ */
28
+ async function answerInTerminal(api, sessionId, question, { signal, onInterrupt }) {
29
+ for (;;) {
30
+ const answer = await askDirectQuestion(question, { signal, onInterrupt });
31
+ if (!answer) return;
32
+ const res = await axios.post(`${api.serverUrl}${DEVICE_API_PREFIX}/missions/answer`, { session_id: sessionId, ...answer }, api.authHeaders)
33
+ .then((r) => r.data)
34
+ .catch((e) => ({ status: ANSWER_STATUS.REJECTED, error: e.response?.data?.message || e.message }));
35
+ if (res?.status === ANSWER_STATUS.ANSWERED) return console.log(chalk.gray(' Đã gửi câu trả lời — làm tiếp trên máy...'));
36
+ if (res?.status === ANSWER_STATUS.NO_QUESTION) return console.log(chalk.gray(' Câu hỏi này không còn chờ (đã trả lời ở nơi khác hoặc đã hết hạn).'));
37
+ if (res?.status === ANSWER_STATUS.INVALID_ANSWER) {
38
+ console.log(chalk.red(' Câu trả lời không khớp câu hỏi — trả lời lại.'));
39
+ continue;
40
+ }
41
+ return console.log(chalk.red(` Không gửi được câu trả lời (${res?.error || 'lỗi'}) — trả lời trên web Aivin để làm tiếp.`));
42
+ }
43
+ }
44
+
45
+ /** Theo dõi dòng tiến trình của phiên (thread = session của lượt chạy thẳng), hỏi câu đang chờ ngay trong terminal. Không bao giờ ném lỗi. */
46
+ function watchDeviceMission(api, sessionId, { idleTimeoutMs = 300_000 } = {}) {
47
+ return new Promise((resolve) => {
48
+ const socket = io(api.serverUrl, { auth: { token: api.apiKey }, transports: ['websocket'], reconnection: true });
49
+ let idle;
50
+ let settled = false;
51
+ /** Câu hỏi đang hiện trong terminal — dòng tiến trình mới tới thì huỷ (đã trả lời trên web). */
52
+ let asking = null;
53
+ const stop = (reason) => {
54
+ if (settled) return;
55
+ settled = true;
56
+ clearTimeout(idle);
57
+ asking?.abort();
58
+ socket.disconnect();
59
+ process.off('SIGINT', onSigint);
60
+ resolve(reason);
61
+ };
62
+ const onSigint = () => stop('interrupted');
63
+ const bump = () => {
64
+ clearTimeout(idle);
65
+ // Đang chờ người trả lời thì không tính "không có hoạt động" — người dùng có thể nghĩ lâu.
66
+ if (asking) return;
67
+ idle = setTimeout(() => { console.log(chalk.gray('\n(không có hoạt động — ngừng theo dõi; việc có thể vẫn đang chạy)')); stop('idle'); }, idleTimeoutMs);
68
+ };
69
+ const ask = async (payload) => {
70
+ asking?.abort();
71
+ const controller = new AbortController();
72
+ asking = controller;
73
+ clearTimeout(idle);
74
+ try {
75
+ const question = await loadQuestion(api, sessionId, payload);
76
+ if (!question || controller.signal.aborted) return;
77
+ await answerInTerminal(api, sessionId, question, { signal: controller.signal, onInterrupt: onSigint });
78
+ } catch (e) {
79
+ console.log(chalk.yellow(`⚠️ Không hỏi được trong terminal (${e.message}) — trả lời trên web Aivin để làm tiếp.`));
80
+ } finally {
81
+ if (asking === controller) asking = null;
82
+ if (!settled) bump();
83
+ }
84
+ };
85
+ process.on('SIGINT', onSigint);
86
+ socket.on('connect_error', (e) => { console.log(chalk.yellow(`⚠️ Không theo dõi được tiến trình (${e.message})`)); stop('connect_error'); });
87
+ socket.on('error', () => stop('error'));
88
+ for (const event of MISSION_LOG_EVENTS) {
89
+ socket.on(event, (payload) => {
90
+ if (!payload || (payload.thread_id !== sessionId && payload.session_id !== sessionId)) return;
91
+ const icon = payload.status === 'error' ? chalk.red('✗') : payload.status === 'success' ? chalk.green('✓') : payload.status === 'warning' ? chalk.yellow('!') : chalk.gray('·');
92
+ if (payload.event_key !== AWAITING_USER_KEY) asking?.abort();
93
+ console.log(`${chalk.gray(`[${new Date(payload.timestamp || Date.now()).toLocaleTimeString()}]`)} ${icon} ${payload.message || payload.event_key || ''}`);
94
+ if (DONE_KEYS.has(payload.event_key)) {
95
+ // Kết quả của việc (BE gắn `meta.answer` vào dòng xong) — in ra để người dùng không phải mở web xem.
96
+ if (payload.meta?.answer) console.log(`\n${chalk.green('Kết quả:')}\n${payload.meta.answer}\n`);
97
+ return stop(payload.event_key);
98
+ }
99
+ if (payload.event_key === AWAITING_USER_KEY) return void ask(payload);
100
+ bump();
101
+ });
102
+ }
103
+ bump();
104
+ });
105
+ }
106
+
107
+ /** Cùng máy chủ (bỏ dấu / cuối, không phân biệt hoa thường). */
108
+ function sameServer(a, b) {
109
+ const norm = (u) => String(u || '').trim().replace(/\/+$/, '').toLowerCase();
110
+ return !!a && norm(a) === norm(b);
111
+ }
112
+
113
+ /**
114
+ * `aivin remote do "<việc>"` — giao thẳng cho Device Agent (không qua bước chọn công cụ), chạy nền phía BE, CLI in tiến trình.
115
+ */
116
+ export async function runRemoteMission(objective, options = {}) {
117
+ const serverUrl = missionServerUrl();
118
+ const apiKey = process.env.API_KEY;
119
+ const authHeaders = missionAuthHeaders();
120
+ // Đăng nhập bằng JWT (không phải API key `<client>-ak-…`) thì không suy ra được tenant → lấy từ token thiết bị đã ghép.
121
+ const creds = loadDeviceCredentials();
122
+ const client = deviceTokenClient(creds?.device_token);
123
+ if (client && !authHeaders.headers['x-client-slug']) authHeaders.headers['x-client-slug'] = client;
124
+ // Không nêu --device mà máy này đã ghép với đúng máy chủ → làm trên chính máy này (29/10/2026: người dùng có nhiều máy online, việc gõ
125
+ // ở máy này từng chạy sang máy khác báo hiệu gần hơn). Máy này đang tắt daemon → BE tự chọn lại như khi không nêu máy.
126
+ const device = options.device || (creds?.device_id && sameServer(creds.server_url, serverUrl) ? creds.device_id : undefined);
127
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
128
+ const agentId = resolveAgentId(workspace, options.agent);
129
+ const sessionId = `device-cli-${randomUUID()}`;
130
+ console.log(chalk.blue('💻 Device Agent:'), objective);
131
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}${options.device ? ` · máy: ${options.device}` : device ? ` · máy: ${creds.name || device} (máy này)` : ''}`));
132
+ const watching = options.watch !== false ? watchDeviceMission({ serverUrl, apiKey, authHeaders }, sessionId) : Promise.resolve(undefined);
133
+ try {
134
+ await axios.post(`${serverUrl}${DEVICE_API_PREFIX}/missions/start`, {
135
+ objective,
136
+ workspace_id: workspace.id || workspace._id,
137
+ agent_id: agentId,
138
+ session_id: sessionId,
139
+ ...(device ? { device } : {}),
140
+ ...(options.cwd ? { working_dir: options.cwd } : {}),
141
+ ...(options.file?.length ? { file_ids: options.file } : {}),
142
+ }, authHeaders);
143
+ } catch (error) {
144
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
145
+ throw new Error(`Không giao được việc cho máy: ${message}`, { cause: error });
146
+ }
147
+ const reason = await watching;
148
+ if (reason === 'interrupted') {
149
+ // Ctrl+C = huỷ thật: BE dừng vòng nhiệm vụ ở nhịp kế tiếp và gửi lệnh huỷ xuống máy (kill cả cây tiến trình đang chạy).
150
+ console.log(chalk.yellow('\n⏹ Đang huỷ việc trên máy...'));
151
+ await axios.post(`${serverUrl}${DEVICE_API_PREFIX}/missions/cancel`, { session_id: sessionId }, authHeaders)
152
+ .then(() => console.log(chalk.gray(' Đã gửi lệnh huỷ.')))
153
+ .catch((e) => console.log(chalk.red(` Không gửi được lệnh huỷ (${e.response?.data?.message || e.message}) — việc có thể vẫn chạy.`)));
154
+ }
155
+ return { sessionId, reason };
156
+ }
@@ -0,0 +1,63 @@
1
+ import chalk from 'chalk';
2
+ import readline from 'readline/promises';
3
+
4
+ /** Dạng câu hỏi BE gửi (be `DeviceDirectQuestionKind`). */
5
+ export const QUESTION_KIND = { CHOICE: 'choice', FORM: 'form', TEXT: 'text' };
6
+
7
+ /** Kết quả `missions/answer` (be `DeviceMissionAnswerStatus`). */
8
+ export const ANSWER_STATUS = { ANSWERED: 'answered', NO_QUESTION: 'no_question', INVALID_ANSWER: 'invalid_answer', REJECTED: 'rejected' };
9
+
10
+ /** Dòng gõ "1,3" / "2" → id lựa chọn theo số thứ tự. Số lạ / rỗng → `undefined` (hỏi lại). */
11
+ export function parseChoiceInput(input, options, multiple) {
12
+ const picks = String(input || '').split(/[\s,;]+/).filter(Boolean).map(Number);
13
+ if (!picks.length || picks.some((n) => !Number.isInteger(n) || n < 1 || n > options.length)) return undefined;
14
+ const ids = [...new Set(picks.map((n) => options[n - 1].id))];
15
+ if (!multiple && ids.length > 1) return undefined;
16
+ return ids;
17
+ }
18
+
19
+ /**
20
+ * Hỏi câu hỏi đang chờ của nhiệm vụ ngay trong terminal. Trả thân trả lời (`option_ids` / `fields` / `text`) hoặc `undefined` khi bị huỷ
21
+ * (`signal` — câu hỏi đã được trả lời trên web, người dùng bấm Ctrl+C → `onInterrupt`). Gõ sai số thì hỏi lại, không gửi.
22
+ */
23
+ export async function askDirectQuestion(question, { signal, onInterrupt } = {}) {
24
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
25
+ // Đang hỏi thì Ctrl+C tới readline chứ không tới `process` → chuyển cho nơi gọi (huỷ nhiệm vụ như lúc không hỏi).
26
+ rl.on('SIGINT', () => onInterrupt?.());
27
+ const ask = (q) => rl.question(q, { signal });
28
+ try {
29
+ console.log(`\n${chalk.yellow('❓')} ${question.question || 'Cần bạn trả lời để làm tiếp:'}`);
30
+ if (question.kind === QUESTION_KIND.CHOICE && question.options?.length) {
31
+ question.options.forEach((o, i) => console.log(` ${chalk.cyan(`${i + 1})`)} ${o.text}`));
32
+ const hint = question.multiple ? 'Chọn số (nhiều số cách nhau dấu phẩy): ' : 'Chọn số: ';
33
+ for (;;) {
34
+ const ids = parseChoiceInput(await ask(chalk.gray(` ${hint}`)), question.options, question.multiple);
35
+ if (ids) return { option_ids: ids };
36
+ console.log(chalk.red(` Chọn một số từ 1 tới ${question.options.length}.`));
37
+ }
38
+ }
39
+ if (question.kind === QUESTION_KIND.FORM && question.fields?.length) {
40
+ const fields = {};
41
+ for (const f of question.fields) {
42
+ const choices = f.options?.length ? ` (${f.options.map((o) => o.text).join(' / ')})` : '';
43
+ for (;;) {
44
+ const value = (await ask(chalk.gray(` ${f.label}${choices}${f.required ? '' : ' (bỏ trống được)'}: `))).trim();
45
+ if (value || !f.required) {
46
+ if (value) fields[f.name] = value;
47
+ break;
48
+ }
49
+ }
50
+ }
51
+ return { fields };
52
+ }
53
+ for (;;) {
54
+ const text = (await ask(chalk.gray(' Trả lời: '))).trim();
55
+ if (text) return { text };
56
+ }
57
+ } catch (e) {
58
+ if (e?.name === 'AbortError' || e?.code === 'ABORT_ERR') return undefined;
59
+ throw e;
60
+ } finally {
61
+ rl.close();
62
+ }
63
+ }