@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,138 @@
1
+ import { spawn } from 'child_process';
2
+ import { DeviceErrorCode, ToolGroup } from './constants.mjs';
3
+ import { DeviceToolError } from './sandbox.mjs';
4
+ import { findOnPath } from '../localBrowser.mjs';
5
+
6
+ /**
7
+ * Clipboard của máy (29/10/2026): "lấy cái tôi vừa copy", "dán kết quả vào clipboard cho tôi". Windows: chữ, ảnh (PNG), danh sách tệp đã
8
+ * copy trong Explorer; macOS (pbpaste / pbcopy) và Linux (wl-paste / xclip / xsel): chữ.
9
+ *
10
+ * Không đọc nội dung app đánh dấu riêng tư — trình quản lý mật khẩu (KeePass, 1Password, Bitwarden…) đặt định dạng
11
+ * `ExcludeClipboardContentFromMonitorProcessing` / `CanIncludeInClipboardHistory = 0` khi copy mật khẩu, chính lịch sử clipboard của Windows
12
+ * cũng bỏ qua — ở đây cũng vậy (trả `private: true`, không có nội dung).
13
+ */
14
+
15
+ const MAX_TEXT = 200_000;
16
+ const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
17
+ const TIMEOUT_MS = 15_000;
18
+
19
+ const PS_READ = String.raw`
20
+ $ErrorActionPreference = 'Stop'
21
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
22
+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing
23
+ $d = [Windows.Forms.Clipboard]::GetDataObject()
24
+ $out = @{ formats = @() }
25
+ if ($d) { $out.formats = @($d.GetFormats()) }
26
+ $private = $false
27
+ if ($d -and $d.GetDataPresent('ExcludeClipboardContentFromMonitorProcessing')) { $private = $true }
28
+ if ($d -and $d.GetDataPresent('CanIncludeInClipboardHistory')) {
29
+ $s = $d.GetData('CanIncludeInClipboardHistory')
30
+ if ($s -is [IO.MemoryStream] -and $s.Length -ge 4) { $b = $s.ToArray(); if ([BitConverter]::ToInt32($b, 0) -eq 0) { $private = $true } }
31
+ }
32
+ if ($private) { $out.private = $true }
33
+ elseif ([Windows.Forms.Clipboard]::ContainsText()) { $out.text = [Windows.Forms.Clipboard]::GetText() }
34
+ elseif ([Windows.Forms.Clipboard]::ContainsFileDropList()) { $out.files = @([Windows.Forms.Clipboard]::GetFileDropList()) }
35
+ elseif ([Windows.Forms.Clipboard]::ContainsImage()) {
36
+ $img = [Windows.Forms.Clipboard]::GetImage(); $ms = New-Object IO.MemoryStream
37
+ $img.Save($ms, [Drawing.Imaging.ImageFormat]::Png)
38
+ $out.image = @{ mime = 'image/png'; base64 = [Convert]::ToBase64String($ms.ToArray()); width = $img.Width; height = $img.Height }
39
+ }
40
+ [Console]::Out.Write(($out | ConvertTo-Json -Compress -Depth 4))
41
+ `;
42
+
43
+ const PS_WRITE = String.raw`
44
+ $ErrorActionPreference = 'Stop'
45
+ [Console]::InputEncoding = [Text.Encoding]::UTF8
46
+ Add-Type -AssemblyName System.Windows.Forms
47
+ $t = [Console]::In.ReadToEnd()
48
+ if ($t.Length -eq 0) { [Windows.Forms.Clipboard]::Clear() } else { [Windows.Forms.Clipboard]::SetText($t) }
49
+ [Console]::Out.Write('{"ok":true}')
50
+ `;
51
+
52
+ function run(cmd, args, { input, signal, spawnImpl = spawn } = {}) {
53
+ return new Promise((resolve, reject) => {
54
+ const child = spawnImpl(cmd, args, { windowsHide: true });
55
+ const out = [];
56
+ let err = '';
57
+ const timer = setTimeout(() => { child.kill(); reject(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, 'Clipboard timed out')); }, TIMEOUT_MS);
58
+ const onAbort = () => { child.kill(); reject(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled')); };
59
+ signal?.addEventListener('abort', onAbort, { once: true });
60
+ child.stdout.on('data', (d) => out.push(d));
61
+ child.stderr.on('data', (d) => { err = (err + d).slice(-2000); });
62
+ child.on('error', (e) => { clearTimeout(timer); reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Cannot reach the clipboard: ${e.message}`)); });
63
+ child.on('close', (code) => {
64
+ clearTimeout(timer);
65
+ signal?.removeEventListener('abort', onAbort);
66
+ if (code === 0) resolve(Buffer.concat(out).toString('utf8'));
67
+ else reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, err.trim().split(/\r?\n/).slice(-2).join(' ') || `Clipboard command failed (${code})`));
68
+ });
69
+ if (input !== undefined) child.stdin.end(input, 'utf8');
70
+ else child.stdin.end();
71
+ });
72
+ }
73
+
74
+ const ps = (script) => ['powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-Command', script]];
75
+
76
+ /** Lệnh đọc / ghi chữ trên macOS / Linux theo công cụ có sẵn — không có → null. */
77
+ export function unixClipboardCommands({ platform = process.platform, env = process.env, onPath = (n) => findOnPath([n]) } = {}) {
78
+ if (platform === 'darwin') return { read: ['pbpaste', []], write: ['pbcopy', []] };
79
+ if (platform !== 'linux') return null;
80
+ if (env.WAYLAND_DISPLAY && onPath('wl-paste') && onPath('wl-copy')) return { read: ['wl-paste', ['--no-newline']], write: ['wl-copy', []] };
81
+ if (!env.DISPLAY) return null;
82
+ if (onPath('xclip')) return { read: ['xclip', ['-selection', 'clipboard', '-o']], write: ['xclip', ['-selection', 'clipboard']] };
83
+ if (onPath('xsel')) return { read: ['xsel', ['--clipboard', '--output']], write: ['xsel', ['--clipboard', '--input']] };
84
+ return null;
85
+ }
86
+
87
+ /** `null` khi máy không có clipboard dùng được (máy chủ không màn hình, thiếu công cụ). */
88
+ export function createClipboard({ platform = process.platform, spawnImpl = spawn, unix = unixClipboardCommands({ platform }) } = {}) {
89
+ if (platform !== 'win32' && !unix) return null;
90
+
91
+ async function read(ctx) {
92
+ if (platform === 'win32') {
93
+ const [cmd, args] = ps(PS_READ);
94
+ const res = JSON.parse((await run(cmd, args, { signal: ctx?.signal, spawnImpl })) || '{}');
95
+ if (res.private) return { private: true, note: 'The app that copied this marked it private (e.g. a password manager) — it is not read.' };
96
+ if (typeof res.text === 'string') return { kind: 'text', ...cutText(res.text) };
97
+ if (Array.isArray(res.files)) return { kind: 'files', files: res.files };
98
+ if (res.image) {
99
+ if (res.image.base64.length * 0.75 > MAX_IMAGE_BYTES) return { kind: 'image', too_large: true, width: res.image.width, height: res.image.height };
100
+ return { kind: 'image', image: res.image };
101
+ }
102
+ return { kind: 'empty' };
103
+ }
104
+ const text = await run(unix.read[0], unix.read[1], { signal: ctx?.signal, spawnImpl }).catch(() => '');
105
+ return text ? { kind: 'text', ...cutText(text) } : { kind: 'empty' };
106
+ }
107
+
108
+ async function write(args = {}, ctx) {
109
+ const text = String(args.text ?? '');
110
+ if (text.length > MAX_TEXT) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Text too long for the clipboard (max ${MAX_TEXT} characters)`);
111
+ if (platform === 'win32') {
112
+ const [cmd, a] = ps(PS_WRITE);
113
+ await run(cmd, a, { input: text, signal: ctx?.signal, spawnImpl });
114
+ } else {
115
+ await run(unix.write[0], unix.write[1], { input: text, signal: ctx?.signal, spawnImpl });
116
+ }
117
+ return { ok: true, chars: text.length };
118
+ }
119
+
120
+ return { read, write };
121
+ }
122
+
123
+ function cutText(text) {
124
+ return text.length > MAX_TEXT ? { text: text.slice(0, MAX_TEXT), truncated: true, total_chars: text.length } : { text };
125
+ }
126
+
127
+ const schema = (properties, required = []) => ({ type: 'object', properties, required });
128
+
129
+ export function buildClipboardTools(clipboard) {
130
+ return [
131
+ { name: 'clipboard.read', group: ToolGroup.SYSTEM, read_only: true, handler: (_a, c) => clipboard.read(c),
132
+ description: 'What the user has copied right now: text, an image (Windows) or the files copied in Explorer (Windows: their paths). Content a password manager marked private is never returned.',
133
+ input_schema: schema({}) },
134
+ { name: 'clipboard.write', group: ToolGroup.SYSTEM, handler: (a, c) => clipboard.write(a, c),
135
+ description: 'Put text on the clipboard (replaces what the user had copied), so they can paste it anywhere.',
136
+ input_schema: schema({ text: { type: 'string', description: 'text to copy' } }, ['text']) },
137
+ ];
138
+ }
@@ -0,0 +1,293 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { randomUUID } from 'crypto';
5
+ import { execFileSync, spawn } from 'child_process';
6
+ import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
7
+ import { DeviceToolError, resolveInRoots, scrubEnv } from './sandbox.mjs';
8
+
9
+ /**
10
+ * Giao việc cho agent lập trình trên máy (30/10/2026) — Claude Code trước, Codex / Gemini / Aider… sau — bằng chế độ không giao diện của
11
+ * chính agent (`claude -p --output-format stream-json`…) thay vì gõ vào panel trong VS Code qua GUI (webview, cây trợ năng trống, giòn).
12
+ *
13
+ * Một bộ công cụ chung `agent.run / status / stop / sessions` + một ADAPTER mỏng mỗi agent. Adapter chỉ khai cái riêng của agent đó:
14
+ * tìm binary, dựng tham số (chế độ quyền, nói tiếp phiên, model), đọc một dòng sự kiện ra chữ / công cụ / kết quả. Phần chung viết một lần:
15
+ * chạy nền, chờ, đọc tiếp theo con trỏ, dừng, nhớ phiên theo thư mục, đẩy chữ lên Aivin (`ctx.onOutput`). Thêm agent = thêm adapter đã
16
+ * kiểm cờ dòng lệnh THẬT trên máy (không đoán).
17
+ *
18
+ * An toàn: đề bài đi qua stdin (không lộ trong danh sách tiến trình, không dính trích dẫn của shell); chế độ quyền chỉ `plan` (chỉ đọc) /
19
+ * `manual` (mặc định: việc cần quyền bị từ chối — chế độ không giao diện không ai trả lời hộp hỏi) / `accept_edits` (sửa tệp trong thư
20
+ * mục) — không bao giờ chế độ bỏ qua quyền. BE xét `agent.run` như `shell.exec` (buộc hỏi người ở máy không toàn quyền): agent tự chạy lệnh.
21
+ */
22
+
23
+ const SESSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'agent-sessions.json');
24
+ const MAX_SESSIONS = 50;
25
+ const MAX_JOBS = 4;
26
+ const DEFAULT_WAIT_MS = 90_000;
27
+ const MAX_WAIT_MS = 10 * 60_000;
28
+ const MAX_PROMPT_CHARS = 20_000;
29
+ const MAX_ANSWER_CHARS = 12_000;
30
+ const MAX_TEXTS = 400;
31
+ const KEEP_DONE_MS = 30 * 60_000;
32
+ /** Đã chạy đủ MAX_JOBS việc cùng lúc. */
33
+ const AGENT_BUSY = 'AGENT_BUSY';
34
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
35
+ const MODEL_RE = /^[a-z0-9][a-z0-9.\-[\]]{0,60}$/i;
36
+
37
+ /** Chế độ quyền chung — mỗi adapter đổi sang cờ của agent mình; agent không có chế độ tương đương thì từ chối. */
38
+ export const AgentMode = Object.freeze({ PLAN: 'plan', MANUAL: 'manual', ACCEPT_EDITS: 'accept_edits' });
39
+
40
+ const str = (description) => ({ type: 'string', description });
41
+ const num = (description) => ({ type: 'number', description });
42
+ const schema = (properties, required = []) => ({ type: 'object', properties, required });
43
+
44
+ /** `<dir>/<exe>` của mọi thư mục trong PATH. */
45
+ function onPath(exe, env) {
46
+ return String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean).map((dir) => path.join(dir, exe));
47
+ }
48
+
49
+ /** Claude Code (2.1.x): `-p --output-format stream-json --verbose`, `--permission-mode`, `--resume <id>`, `--model`. Kiểm thật 30/10/2026. */
50
+ export const CLAUDE_ADAPTER = Object.freeze({
51
+ id: 'claude',
52
+ label: 'Claude Code',
53
+ candidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
54
+ const exe = platform === 'win32' ? 'claude.exe' : 'claude';
55
+ const out = [...onPath(exe, env), path.join(home, '.local', 'bin', exe), path.join(home, '.claude', 'local', exe)];
56
+ // Bản kèm extension VS Code (người dùng chỉ cài extension, không cài CLI).
57
+ const extRoot = path.join(home, '.vscode', 'extensions');
58
+ try {
59
+ for (const d of fs.readdirSync(extRoot)) if (d.startsWith('anthropic.claude-code-')) out.push(path.join(extRoot, d, 'resources', 'native-binary', exe));
60
+ } catch { /* không có VS Code */ }
61
+ return out;
62
+ },
63
+ args({ mode, resume, model }) {
64
+ const flag = { [AgentMode.PLAN]: 'plan', [AgentMode.MANUAL]: 'manual', [AgentMode.ACCEPT_EDITS]: 'acceptEdits' }[mode];
65
+ const argv = ['-p', '--output-format', 'stream-json', '--verbose', '--permission-mode', flag];
66
+ if (resume) argv.push('--resume', resume);
67
+ if (model) argv.push('--model', model);
68
+ return argv;
69
+ },
70
+ /** Một dòng `stream-json` → cập nhật việc; trả đoạn chữ đáng đẩy lên Aivin (chữ agent viết / công cụ nó dùng), hoặc ''. */
71
+ parse(job, msg) {
72
+ if (msg.session_id && !job.session_id) job.session_id = msg.session_id;
73
+ if (msg.type === 'system' && msg.subtype === 'init') { job.model = msg.model; return ''; }
74
+ if (msg.type === 'assistant') {
75
+ const parts = [];
76
+ for (const c of msg.message?.content || []) {
77
+ if (c.type === 'text' && c.text?.trim()) { job.texts.push(c.text); parts.push(c.text); }
78
+ if (c.type === 'tool_use') {
79
+ const target = c.input?.file_path || c.input?.path || c.input?.command || c.input?.pattern || c.input?.url || '';
80
+ const line = `🔧 ${c.name}${target ? ` ${String(target).slice(0, 160)}` : ''}`;
81
+ job.tools.push(line);
82
+ parts.push(line);
83
+ }
84
+ }
85
+ return parts.join('\n');
86
+ }
87
+ if (msg.type === 'result') {
88
+ job.result = {
89
+ ok: !msg.is_error && msg.subtype === 'success', answer: String(msg.result ?? '').slice(0, MAX_ANSWER_CHARS),
90
+ cost_usd: typeof msg.total_cost_usd === 'number' ? Math.round(msg.total_cost_usd * 10_000) / 10_000 : undefined,
91
+ turns: msg.num_turns, duration_ms: msg.duration_ms,
92
+ };
93
+ }
94
+ return '';
95
+ },
96
+ });
97
+
98
+ export const DEFAULT_AGENT_ADAPTERS = Object.freeze([CLAUDE_ADAPTER]);
99
+
100
+ function versionOf(bin) {
101
+ try {
102
+ const out = execFileSync(bin, ['--version'], { encoding: 'utf8', timeout: 15_000, windowsHide: true });
103
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(out);
104
+ return m ? m.slice(1).map(Number) : null;
105
+ } catch { return null; }
106
+ }
107
+ const newer = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return false; };
108
+
109
+ /** Bản mới nhất chạy được của một agent trên máy, hoặc null. */
110
+ export function findAgentBinary(adapter, opts = {}) {
111
+ let best = null;
112
+ for (const bin of [...new Set(adapter.candidates(opts))]) {
113
+ if (!fs.existsSync(bin)) continue;
114
+ const v = (opts.versionOf || versionOf)(bin);
115
+ if (v && (!best || newer(v, best.version))) best = { bin, version: v };
116
+ }
117
+ return best ? { bin: best.bin, version: best.version.join('.') } : null;
118
+ }
119
+
120
+ /** Tham số của một lần chạy — kiểm chung (chế độ, mã phiên, model) rồi adapter dựng cờ riêng. Đề bài KHÔNG ở đây. */
121
+ export function agentArgs(adapter, { mode = AgentMode.MANUAL, resume, model } = {}) {
122
+ if (!Object.values(AgentMode).includes(mode)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `mode must be one of: ${Object.values(AgentMode).join(', ')}`);
123
+ if (resume && !UUID_RE.test(resume)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'session must be "new", "continue" or a session id');
124
+ if (model && !MODEL_RE.test(model)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Bad model name');
125
+ return adapter.args({ mode, resume, model });
126
+ }
127
+
128
+ function loadSessions() {
129
+ try { const v = JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf8')); return Array.isArray(v) ? v : []; } catch { return []; }
130
+ }
131
+ function saveSessions(list) {
132
+ try { fs.mkdirSync(path.dirname(SESSIONS_FILE), { recursive: true }); fs.writeFileSync(SESSIONS_FILE, JSON.stringify(list.slice(0, MAX_SESSIONS), null, 1)); } catch { /* chỉ để tiện nói tiếp */ }
133
+ }
134
+
135
+ export function createAgentRunner({ adapters = DEFAULT_AGENT_ADAPTERS, find = findAgentBinary, spawnImpl = spawn, now = Date.now } = {}) {
136
+ const found = new Map();
137
+ const jobs = new Map();
138
+ const binaryOf = (adapter) => {
139
+ if (!found.has(adapter.id)) found.set(adapter.id, find(adapter));
140
+ return found.get(adapter.id);
141
+ };
142
+ /** Agent đã cài trên máy (theo thứ tự ưu tiên của danh sách adapter). */
143
+ const installed = () => adapters.filter((a) => binaryOf(a));
144
+ const adapterFor = (id) => {
145
+ const list = installed();
146
+ if (!list.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No coding agent is installed on this computer (looked for: ${adapters.map((a) => a.label).join(', ')})`);
147
+ if (!id) return list[0];
148
+ const a = list.find((x) => x.id === id);
149
+ if (!a) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${id} is not installed here — available: ${list.map((x) => x.id).join(', ')}`);
150
+ return a;
151
+ };
152
+
153
+ const prune = () => {
154
+ for (const [id, j] of jobs) if (j.status !== 'running' && now() - j.endedAt > KEEP_DONE_MS) jobs.delete(id);
155
+ };
156
+ const view = (j, sinceText = 0, sinceTool = 0) => ({
157
+ job: j.id, agent: j.agent, status: j.status, session_id: j.session_id, cwd: j.cwdShown, mode: j.mode, model: j.model,
158
+ new_text: j.texts.slice(sinceText).join('\n\n').slice(-MAX_ANSWER_CHARS) || undefined,
159
+ tools_used: j.tools.slice(sinceTool).slice(-40),
160
+ ...(j.result ? { result: j.result } : {}),
161
+ ...(j.error ? { error: j.error } : {}),
162
+ next_text: j.texts.length, next_tool: j.tools.length,
163
+ });
164
+
165
+ function remember(j) {
166
+ if (!j.session_id) return;
167
+ const list = loadSessions().filter((s) => !(s.agent === j.agent && s.session_id === j.session_id));
168
+ list.unshift({ agent: j.agent, session_id: j.session_id, cwd: j.cwd, prompt: j.prompt.slice(0, 200), at: new Date(now()).toISOString(), ok: j.result?.ok });
169
+ saveSessions(list);
170
+ }
171
+
172
+ function waitDone(j, ms, signal) {
173
+ if (j.status !== 'running') return Promise.resolve();
174
+ return new Promise((resolve) => {
175
+ const done = () => { clearTimeout(t); signal?.removeEventListener('abort', done); j.waiters.delete(done); resolve(); };
176
+ const t = setTimeout(done, ms);
177
+ signal?.addEventListener('abort', done, { once: true });
178
+ j.waiters.add(done);
179
+ });
180
+ }
181
+
182
+ async function run(args, ctx = {}, env = {}) {
183
+ prune();
184
+ const prompt = String(args.prompt || '').trim();
185
+ if (!prompt) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give prompt (the task for the coding agent)');
186
+ if (prompt.length > MAX_PROMPT_CHARS) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `prompt is longer than ${MAX_PROMPT_CHARS} characters`);
187
+ if ([...jobs.values()].filter((j) => j.status === 'running').length >= MAX_JOBS) throw new DeviceToolError(AGENT_BUSY, `${MAX_JOBS} agent tasks are already running — wait or agent.stop one`);
188
+ const adapter = adapterFor(args.agent ? String(args.agent) : undefined);
189
+ const cwd = resolveInRoots(env.roots || [], String(args.cwd || (env.roots || [])[0] || '.'));
190
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd}`);
191
+ const session = String(args.session || 'new');
192
+ const resume = session === 'new' ? undefined
193
+ : session === 'continue' ? loadSessions().find((s) => s.agent === adapter.id && s.cwd === cwd)?.session_id
194
+ : session;
195
+ if (session === 'continue' && !resume) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No earlier ${adapter.label} session in this folder — use session "new"`);
196
+ const mode = String(args.mode || AgentMode.MANUAL);
197
+ const argv = agentArgs(adapter, { mode, resume, model: args.model ? String(args.model) : undefined });
198
+
199
+ const j = {
200
+ id: `${adapter.id}-${randomUUID().slice(0, 8)}`, agent: adapter.id, status: 'running', prompt, cwd, cwdShown: args.cwd || cwd, mode,
201
+ session_id: resume, model: undefined, texts: [], tools: [], result: null, error: null, endedAt: 0, waiters: new Set(), child: null,
202
+ };
203
+ const child = spawnImpl(binaryOf(adapter).bin, argv, { cwd, env: scrubEnv(process.env), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
204
+ j.child = child;
205
+ jobs.set(j.id, j);
206
+ let buf = '';
207
+ let stderr = '';
208
+ child.stdout.on('data', (d) => {
209
+ buf += d.toString();
210
+ let nl;
211
+ while ((nl = buf.indexOf('\n')) >= 0) {
212
+ const line = buf.slice(0, nl).trim();
213
+ buf = buf.slice(nl + 1);
214
+ if (!line) continue;
215
+ let msg;
216
+ try { msg = JSON.parse(line); } catch { continue; }
217
+ if (!msg || typeof msg !== 'object') continue;
218
+ const shown = adapter.parse(j, msg);
219
+ if (j.texts.length > MAX_TEXTS) j.texts.splice(0, j.texts.length - MAX_TEXTS);
220
+ if (shown && typeof ctx.onOutput === 'function') { try { ctx.onOutput(`${shown}\n`); } catch { /* chỉ là tiến trình */ } }
221
+ }
222
+ });
223
+ child.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-2000); });
224
+ const finish = (code) => {
225
+ if (j.status !== 'running') return;
226
+ j.status = j.result?.ok ? 'done' : 'failed';
227
+ if (!j.result) j.error = (stderr.trim().split(/\r?\n/).slice(-3).join(' ') || `${adapter.id} exited with code ${code}`).slice(0, 500);
228
+ j.endedAt = now();
229
+ remember(j);
230
+ for (const w of [...j.waiters]) w();
231
+ };
232
+ child.on('error', (e) => { j.error = e.message; finish(-1); });
233
+ child.on('close', (code) => finish(code));
234
+ child.stdin.end(prompt);
235
+
236
+ await waitDone(j, Math.min(Number(args.wait_ms) || DEFAULT_WAIT_MS, MAX_WAIT_MS), ctx.signal);
237
+ return { ...view(j), hint: j.status === 'running' ? 'Still working — call agent.status with this job (and next_text / next_tool) to read on' : undefined };
238
+ }
239
+
240
+ async function status(args, ctx = {}) {
241
+ const j = jobs.get(String(args.job || ''));
242
+ if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job} (finished more than 30 minutes ago, or never started)`);
243
+ await waitDone(j, Math.min(Number(args.wait_ms) || 0, MAX_WAIT_MS), ctx.signal);
244
+ return view(j, Number(args.next_text) || 0, Number(args.next_tool) || 0);
245
+ }
246
+
247
+ function stop(args) {
248
+ const j = jobs.get(String(args.job || ''));
249
+ if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job}`);
250
+ if (j.status === 'running') {
251
+ try { j.child?.kill(); } catch { /* đã thoát */ }
252
+ j.status = 'stopped'; j.endedAt = now();
253
+ for (const w of [...j.waiters]) w();
254
+ }
255
+ return view(j);
256
+ }
257
+
258
+ function sessions(args, _ctx, env = {}) {
259
+ const cwd = args.cwd ? resolveInRoots(env.roots || [], String(args.cwd)) : null;
260
+ return { sessions: loadSessions().filter((s) => (!cwd || s.cwd === cwd) && (!args.agent || s.agent === args.agent)).slice(0, 20) };
261
+ }
262
+
263
+ return {
264
+ run, status, stop, sessions,
265
+ installed: () => installed().map((a) => ({ id: a.id, label: a.label, version: binaryOf(a).version })),
266
+ stopAll: () => { for (const j of jobs.values()) if (j.status === 'running') { try { j.child?.kill(); } catch { /* đã thoát */ } } },
267
+ };
268
+ }
269
+
270
+ /** Công cụ agent lập trình cho danh mục của Planner — `agent` liệt kê đúng các agent đã cài trên máy này. */
271
+ export function buildAgentTools(runner) {
272
+ const agents = runner.installed();
273
+ const list = agents.map((a) => `${a.id} (${a.label} ${a.version})`).join(', ');
274
+ return [
275
+ { name: 'agent.run', group: ToolGroup.PROC, handler: (a, c, e) => runner.run(a, c, e),
276
+ description: `Give a task to a coding agent installed on this computer, in a project folder, headless — installed: ${list}. Returns its answer, the tools it used, cost and a session id to continue later. Use this instead of typing into an agent's panel in VS Code through gui.*. session: "new" (default), "continue" (the latest session of that agent in that folder) or a session id. mode: manual (default; anything needing permission is refused), plan (read-only, it only proposes), accept_edits (may edit files in the folder). Waits up to wait_ms, then returns the job still running — read on with agent.status.`,
277
+ input_schema: schema({
278
+ prompt: str('the task, in plain words'), agent: str(`which agent (default ${agents[0]?.id}): ${agents.map((a) => a.id).join(' | ')}`),
279
+ cwd: str('project folder (default the first allowed folder)'), session: str('new | continue | <session id>'),
280
+ mode: str('manual | plan | accept_edits'), model: str('optional model alias of that agent'),
281
+ wait_ms: num(`wait for the answer up to this long (default ${DEFAULT_WAIT_MS}, max ${MAX_WAIT_MS})`),
282
+ }, ['prompt']) },
283
+ { name: 'agent.status', group: ToolGroup.PROC, read_only: true, handler: (a, c) => runner.status(a, c),
284
+ description: 'Read a running / finished coding-agent task: new text and tools since next_text / next_tool, the result when done. wait_ms waits for it to finish first.',
285
+ input_schema: schema({ job: str('job from agent.run'), next_text: num('cursor from the previous call'), next_tool: num('cursor from the previous call'), wait_ms: num('max 600000') }, ['job']) },
286
+ { name: 'agent.stop', group: ToolGroup.PROC, handler: (a) => runner.stop(a),
287
+ description: 'Stop a running coding-agent task.',
288
+ input_schema: schema({ job: str('job from agent.run') }, ['job']) },
289
+ { name: 'agent.sessions', group: ToolGroup.PROC, read_only: true, handler: (a, c, e) => runner.sessions(a, c, e),
290
+ description: 'Recent coding-agent sessions started from Aivin on this computer (agent, folder, first words of the task, when, ok) — to continue one.',
291
+ input_schema: schema({ cwd: str('only sessions of this folder'), agent: str('only this agent') }) },
292
+ ];
293
+ }