@aivin-labs/cli 1.0.51 → 1.0.60

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 (32) hide show
  1. package/bin/cli.mjs +2215 -2211
  2. package/bin/lib/auth.mjs +119 -88
  3. package/bin/lib/context.mjs +58 -5
  4. package/bin/lib/loginHandoff.mjs +87 -0
  5. package/bin/lib/openFile.mjs +29 -4
  6. package/bin/lib/remote/agentContract.mjs +370 -0
  7. package/bin/lib/remote/agentEvidence.mjs +409 -0
  8. package/bin/lib/remote/autoStart.mjs +640 -623
  9. package/bin/lib/remote/client.mjs +55 -17
  10. package/bin/lib/remote/codingAgents.mjs +594 -293
  11. package/bin/lib/remote/constants.mjs +1 -1
  12. package/bin/lib/remote/credentials.mjs +131 -125
  13. package/bin/lib/remote/desktop/castAuth.mjs +44 -19
  14. package/bin/lib/remote/desktop/castConsent.mjs +79 -14
  15. package/bin/lib/remote/desktop/castInput.mjs +3 -0
  16. package/bin/lib/remote/desktop/castTrust.mjs +221 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +324 -40
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
  21. package/bin/lib/remote/desktop/strings.mjs +26 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +1512 -1385
  23. package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
  24. package/bin/lib/remote/dpapiHelper.mjs +91 -0
  25. package/bin/lib/remote/gui/index.mjs +422 -68
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -1530
  27. package/bin/lib/remote/humanInput.mjs +7 -0
  28. package/bin/lib/remote/localConfirm.mjs +2 -2
  29. package/bin/lib/remote/tokenStore.mjs +19 -2
  30. package/bin/lib/remote/toolHandlers.mjs +861 -859
  31. package/docs/CLI.md +1606 -1602
  32. package/package.json +1 -1
@@ -1,293 +1,594 @@
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, agentEnv, resolveInRoots } 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: agentEnv(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
- }
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { randomUUID } from 'crypto';
5
+ import { execFile, execFileSync, spawn } from 'child_process';
6
+ import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
7
+ import { DeviceToolError, agentEnv, resolveInRoots } from './sandbox.mjs';
8
+ import { parseContract, parseTestCheck, reportTemplate, sha256 } from './agentContract.mjs';
9
+ import { listWorktrees, measureEvidence, resolveCommit, worktreeState } from './agentEvidence.mjs';
10
+
11
+ /**
12
+ * 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
13
+ * 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).
14
+ *
15
+ * 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 đó:
16
+ * 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:
17
+ * 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 đã
18
+ * kiểm cờ dòng lệnh THẬT trên máy (không đoán — cờ tuỳ chọn chỉ thêm khi `--help` của bản đã cài có cờ đó).
19
+ *
20
+ * 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) /
21
+ * `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ư
22
+ * 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.
23
+ *
24
+ * Job có HỢP ĐỒNG (11/11/2026, thiết kế "Hợp đồng công việc và bằng chứng nghiệm thu"): Agentic gửi `CONTRACT.md` (+ `TEST_CHECK.md`) kèm mã
25
+ * băm; daemon kiểm khuôn, dựng `~/.aivin/jobs/<job>/`, giao cho agent trong worktree riêng với ngân sách / quyền / thời hạn của hợp đồng,
26
+ * KHÔNG nạp hook, quyền, MCP của repo (thư mục của khách là thư mục lạ). Agent xong thì daemon tự đo (agentEvidence.mjs) và trả
27
+ * `evidence` + `REPORT.md` — Agentic nghiệm thu bằng số đo, không bằng lời tự khai. Mọi job có hồ sơ trên đĩa: daemon khởi động lại vẫn trả
28
+ * lời được `agent.status` (job đang chạy lúc tắt → `interrupted`, kèm mã phiên để nói tiếp).
29
+ */
30
+
31
+ const SESSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'agent-sessions.json');
32
+ export const JOBS_DIR = path.join(REMOTE_CONFIG_DIR, 'jobs');
33
+ const MAX_SESSIONS = 50;
34
+ const MAX_JOBS = 4;
35
+ const DEFAULT_WAIT_MS = 90_000;
36
+ const MAX_WAIT_MS = 10 * 60_000;
37
+ const MAX_PROMPT_CHARS = 20_000;
38
+ const MAX_ANSWER_CHARS = 12_000;
39
+ const MAX_REPORT_CHARS = 64 * 1024;
40
+ const MAX_TEXTS = 400;
41
+ const MAX_DENIALS = 20;
42
+ const KEEP_DONE_MS = 30 * 60_000;
43
+ /** Hồ sơ job (thư mục job) giữ trên đĩa bao lâu. */
44
+ const KEEP_JOB_DIR_MS = 7 * 24 * 3_600_000;
45
+ /** Đã chạy đủ MAX_JOBS việc cùng lúc. */
46
+ const AGENT_BUSY = 'AGENT_BUSY';
47
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
48
+ const MODEL_RE = /^[a-z0-9][a-z0-9.\-[\]]{0,60}$/i;
49
+ const JOB_ID_RE = /^[a-z0-9]+-[0-9a-f]{8}$/;
50
+ const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
51
+ const RUNNING = new Set(['running', 'measuring']);
52
+
53
+ /** 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. */
54
+ export const AgentMode = Object.freeze({ PLAN: 'plan', MANUAL: 'manual', ACCEPT_EDITS: 'accept_edits' });
55
+
56
+ const str = (description) => ({ type: 'string', description });
57
+ const num = (description) => ({ type: 'number', description });
58
+ const bool = (description) => ({ type: 'boolean', description });
59
+ const schema = (properties, required = []) => ({ type: 'object', properties, required });
60
+ const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
61
+
62
+ /** `<dir>/<exe>` của mọi thư mục trong PATH. */
63
+ function onPath(exe, env) {
64
+ return String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean).map((dir) => path.join(dir, exe));
65
+ }
66
+
67
+ /** Đường dẫn tuyệt đối theo cú pháp luật quyền của Claude Code (`//` = gốc hệ thống tệp; Windows `C:\a` → `//c/a`). */
68
+ export function claudeAbsPath(abs, platform = process.platform) {
69
+ if (platform === 'win32') {
70
+ const m = /^([a-z]):[\\/]?(.*)$/i.exec(abs);
71
+ if (m) return `//${m[1].toLowerCase()}/${m[2].replace(/\\/g, '/')}`;
72
+ }
73
+ return `/${abs.replace(/\\/g, '/')}`;
74
+ }
75
+
76
+ /**
77
+ * Claude Code (2.1.x): `-p --output-format stream-json --verbose`, `--permission-mode`, `--resume <id>`, `--model`. Kiểm thật 30/10/2026.
78
+ * Cờ của job có hợp đồng kiểm trên 2.1.322 (11/11/2026): `--worktree`, `--max-budget-usd`, `--effort`, `--allowedTools`, `--add-dir`,
79
+ * `--settings`, `--setting-sources`, `--strict-mcp-config`, `--permission-prompts none`.
80
+ */
81
+ export const CLAUDE_ADAPTER = Object.freeze({
82
+ id: 'claude',
83
+ label: 'Claude Code',
84
+ candidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
85
+ const exe = platform === 'win32' ? 'claude.exe' : 'claude';
86
+ const out = [...onPath(exe, env), path.join(home, '.local', 'bin', exe), path.join(home, '.claude', 'local', exe)];
87
+ // Bản kèm extension VS Code (người dùng chỉ cài extension, không cài CLI).
88
+ const extRoot = path.join(home, '.vscode', 'extensions');
89
+ try {
90
+ for (const d of fs.readdirSync(extRoot)) if (d.startsWith('anthropic.claude-code-')) out.push(path.join(extRoot, d, 'resources', 'native-binary', exe));
91
+ } catch { /* không có VS Code */ }
92
+ return out;
93
+ },
94
+ /**
95
+ * `flags`: tập cờ bản đã cài có (từ `--help`), null = không biết → chỉ dùng cờ gốc. Cờ nhận nhiều giá trị (`--allowedTools`, `--add-dir`)
96
+ * đặt TRƯỚC một cờ thường để không nuốt tham số sau.
97
+ */
98
+ args({ mode, resume, model, budgetUsd, effort, allowedTools = [], addDirs = [], worktree, projectConfig = true, settings }, flags = null) {
99
+ const flag = { [AgentMode.PLAN]: 'plan', [AgentMode.MANUAL]: 'manual', [AgentMode.ACCEPT_EDITS]: 'acceptEdits' }[mode];
100
+ const has = (f) => !!flags?.has(f);
101
+ const argv = ['-p', '--output-format', 'stream-json', '--verbose'];
102
+ if (allowedTools.length) argv.push('--allowedTools', ...allowedTools);
103
+ if (addDirs.length) argv.push('--add-dir', ...addDirs);
104
+ argv.push('--permission-mode', flag);
105
+ // Chế độ không giao diện: không ai trả lời hộp hỏi quyền — nói rõ để việc cần quyền bị từ chối ngay, không treo.
106
+ if (has('--permission-prompts')) argv.push('--permission-prompts', 'none');
107
+ if (!projectConfig) argv.push('--setting-sources', 'user', '--strict-mcp-config');
108
+ if (settings) argv.push('--settings', JSON.stringify(settings));
109
+ if (worktree) argv.push('--worktree', worktree);
110
+ if (budgetUsd) argv.push('--max-budget-usd', String(budgetUsd));
111
+ if (effort) argv.push('--effort', effort);
112
+ if (resume) argv.push('--resume', resume);
113
+ if (model) argv.push('--model', model);
114
+ return argv;
115
+ },
116
+ /** 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 ''. */
117
+ parse(job, msg) {
118
+ if (msg.session_id && !job.session_id) job.session_id = msg.session_id;
119
+ if (msg.type === 'system' && msg.subtype === 'init') {
120
+ job.model = msg.model;
121
+ if (typeof msg.cwd === 'string') job.session_cwd = msg.cwd;
122
+ return '';
123
+ }
124
+ if (msg.type === 'assistant') {
125
+ const parts = [];
126
+ for (const c of msg.message?.content || []) {
127
+ if (c.type === 'text' && c.text?.trim()) { job.texts.push(c.text); parts.push(c.text); }
128
+ if (c.type === 'tool_use') {
129
+ const target = c.input?.file_path || c.input?.path || c.input?.command || c.input?.pattern || c.input?.url || '';
130
+ const line = `🔧 ${c.name}${target ? ` ${String(target).slice(0, 160)}` : ''}`;
131
+ job.tools.push(line);
132
+ parts.push(line);
133
+ }
134
+ }
135
+ return parts.join('\n');
136
+ }
137
+ if (msg.type === 'result') {
138
+ job.result = {
139
+ ok: !msg.is_error && msg.subtype === 'success', answer: String(msg.result ?? '').slice(0, MAX_ANSWER_CHARS),
140
+ cost_usd: typeof msg.total_cost_usd === 'number' ? Math.round(msg.total_cost_usd * 10_000) / 10_000 : undefined,
141
+ turns: msg.num_turns, duration_ms: msg.duration_ms,
142
+ };
143
+ if (msg.subtype && msg.subtype !== 'success') job.result.stop_reason = msg.subtype;
144
+ // Việc agent muốn làm mà bị từ chối (thiếu luật cho phép) — Agentic cần biết để sửa hợp đồng, không phải để agent tự vượt.
145
+ const denials = Array.isArray(msg.permission_denials) ? msg.permission_denials : [];
146
+ if (denials.length) {
147
+ job.result.permission_denials = denials.slice(0, MAX_DENIALS).map((d) => {
148
+ const target = d.tool_input?.command || d.tool_input?.file_path || d.tool_input?.path || d.tool_input?.url || '';
149
+ return { tool: String(d.tool_name || ''), ...(target ? { target: String(target).slice(0, 200) } : {}) };
150
+ });
151
+ }
152
+ }
153
+ return '';
154
+ },
155
+ });
156
+
157
+ export const DEFAULT_AGENT_ADAPTERS = Object.freeze([CLAUDE_ADAPTER]);
158
+
159
+ function versionOf(bin) {
160
+ try {
161
+ const out = execFileSync(bin, ['--version'], { encoding: 'utf8', timeout: 15_000, windowsHide: true });
162
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(out);
163
+ return m ? m.slice(1).map(Number) : null;
164
+ } catch { return null; }
165
+ }
166
+ const newer = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return false; };
167
+
168
+ /** Các cờ `--xxx` mà `--help` của binary liệt kê, hoặc null khi không đọc được. Bất đồng bộ — không chặn daemon. */
169
+ export function helpFlags(bin) {
170
+ return new Promise((resolve) => {
171
+ execFile(bin, ['--help'], { encoding: 'utf8', timeout: 20_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, out) => {
172
+ resolve(err ? null : new Set(String(out).match(/--[a-z][a-z-]+/gi) || []));
173
+ });
174
+ });
175
+ }
176
+
177
+ /** Bản mới nhất chạy được của một agent trên máy, hoặc null. */
178
+ export function findAgentBinary(adapter, opts = {}) {
179
+ let best = null;
180
+ for (const bin of [...new Set(adapter.candidates(opts))]) {
181
+ if (!fs.existsSync(bin)) continue;
182
+ const v = (opts.versionOf || versionOf)(bin);
183
+ if (v && (!best || newer(v, best.version))) best = { bin, version: v };
184
+ }
185
+ return best ? { bin: best.bin, version: best.version.join('.') } : null;
186
+ }
187
+
188
+ /** Tham số của một lần chạy — kiểm chung (chế độ, mã phiên, model, ngân sách) rồi adapter dựng cờ riêng. Đề bài KHÔNG ở đây. */
189
+ export function agentArgs(adapter, { mode = AgentMode.MANUAL, resume, model, budgetUsd, effort, ...rest } = {}, flags = null) {
190
+ if (!Object.values(AgentMode).includes(mode)) throw invalid(`mode must be one of: ${Object.values(AgentMode).join(', ')}`);
191
+ if (resume && !UUID_RE.test(resume)) throw invalid('session must be "new", "continue" or a session id');
192
+ if (model && !MODEL_RE.test(model)) throw invalid('Bad model name');
193
+ if (budgetUsd !== undefined && !(Number(budgetUsd) > 0 && Number(budgetUsd) <= 200)) throw invalid('max_budget_usd must be above 0 and at most 200');
194
+ if (effort !== undefined && !EFFORTS.includes(effort)) throw invalid(`effort must be one of: ${EFFORTS.join(', ')}`);
195
+ const argv = adapter.args({ mode, resume, model, budgetUsd: budgetUsd === undefined ? undefined : Number(budgetUsd), effort, ...rest }, flags);
196
+ // Bản đã cài không có cờ cần thiết → từ chối thay vì để agent báo lỗi lạ (hoặc bỏ qua giới hạn).
197
+ const missing = flags ? argv.filter((a) => a.startsWith('--') && !flags.has(a)) : [];
198
+ if (missing.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${adapter.label} on this computer is too old for ${missing.join(', ')} — update it`);
199
+ return argv;
200
+ }
201
+
202
+ function loadSessions() {
203
+ try { const v = JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf8')); return Array.isArray(v) ? v : []; } catch { return []; }
204
+ }
205
+ function saveSessions(list) {
206
+ 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 */ }
207
+ }
208
+
209
+ /** Đề bài của job có hợp đồng: trỏ tới các file, khuôn REPORT.md, quy tắc đặt tên test. Phần "what / why" nằm trong CONTRACT.md. */
210
+ function contractPrompt({ jobId, jobDir, contract, hasTestCheck, note }) {
211
+ const report = path.join(jobDir, 'REPORT.md');
212
+ return [
213
+ `You are doing one job for Aivin. The job contract is ${path.join(jobDir, 'CONTRACT.md')} — read it first. It says what to do, why, the limits and how the work will be judged. How to do it is up to you.`,
214
+ hasTestCheck ? `The project's test checks are in ${path.join(jobDir, 'TEST_CHECK.md')}. Cover every check of the flows named in the contract (test_check.flows), following each business rule and the 8 groups of cases.` : '',
215
+ 'Rules:',
216
+ '- Do not edit CONTRACT.md or TEST_CHECK.md. If the scope must change, stop and say so in REPORT.md (needs_scope_change: true).',
217
+ '- Stay inside the current folder for code changes. Do not touch paths the contract denies or protects (you may add new files).',
218
+ '- Name every automated test you write or run for a check so its name contains the check id (for example "CK-031 order at 23:30 keeps its day"). The device re-runs the tests and matches results by that id.',
219
+ '- Do not skip, disable or delete existing tests to make things pass.',
220
+ `When you finish (or stop), write ${report} exactly in this format — frontmatter holds short values only, sentences go in the sections; delete the example check under "Ca kiểm mới" if you propose none:`,
221
+ '',
222
+ reportTemplate({ jobId, contractId: contract.contract_id }),
223
+ note ? `\nNote from Aivin: ${note}` : '',
224
+ ].filter((l) => l !== '').join('\n');
225
+ }
226
+
227
+ export function createAgentRunner({
228
+ adapters = DEFAULT_AGENT_ADAPTERS, find = findAgentBinary, spawnImpl = spawn, now = Date.now, jobsDir = JOBS_DIR, measure = measureEvidence, probeFlags = helpFlags,
229
+ } = {}) {
230
+ const found = new Map();
231
+ const flagCache = new Map();
232
+ const jobs = new Map();
233
+ const binaryOf = (adapter) => {
234
+ if (!found.has(adapter.id)) found.set(adapter.id, find(adapter));
235
+ return found.get(adapter.id);
236
+ };
237
+ const flagsOf = async (adapter) => {
238
+ const b = binaryOf(adapter);
239
+ if (b?.flags) return new Set(b.flags);
240
+ if (!flagCache.has(adapter.id)) flagCache.set(adapter.id, b ? Promise.resolve(probeFlags(b.bin)).catch(() => null) : null);
241
+ return flagCache.get(adapter.id);
242
+ };
243
+ /** Agent đã cài trên máy (theo thứ tự ưu tiên của danh sách adapter). */
244
+ const installed = () => adapters.filter((a) => binaryOf(a));
245
+ const adapterFor = (id) => {
246
+ const list = installed();
247
+ 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(', ')})`);
248
+ if (!id) return list[0];
249
+ const a = list.find((x) => x.id === id);
250
+ if (!a) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${id} is not installed here — available: ${list.map((x) => x.id).join(', ')}`);
251
+ return a;
252
+ };
253
+
254
+ // --- Hồ sơ job trên đĩa: `<jobsDir>/<job>/job.json` (+ CONTRACT.md, TEST_CHECK.md, REPORT.md, evidence.json, logs/ của job có hợp đồng).
255
+ const dirOf = (id) => path.join(jobsDir, id);
256
+ const RECORD_KEYS = ['id', 'agent', 'status', 'cwd', 'cwdShown', 'mode', 'model', 'session_id', 'worktree', 'baseCommit', 'contractId', 'contractSha', 'continuedFrom', 'startedAt', 'endedAt', 'result', 'error'];
257
+ function persist(j) {
258
+ try {
259
+ fs.mkdirSync(dirOf(j.id), { recursive: true });
260
+ fs.writeFileSync(path.join(dirOf(j.id), 'job.json'), JSON.stringify({ ...Object.fromEntries(RECORD_KEYS.map((k) => [k, j[k]])), prompt: j.prompt.slice(0, 200) }, null, 1));
261
+ } catch { /* hồ sơ chỉ để trả lời sau khi khởi động lại */ }
262
+ }
263
+ /** Lần đầu dựng runner: nạp job cũ còn hồ sơ; job đang chạy lúc daemon tắt → `interrupted`. Dọn hồ sơ quá hạn. */
264
+ function restore() {
265
+ let names;
266
+ try { names = fs.readdirSync(jobsDir); } catch { return; }
267
+ for (const name of names) {
268
+ if (!JOB_ID_RE.test(name)) continue;
269
+ let rec;
270
+ try { rec = JSON.parse(fs.readFileSync(path.join(dirOf(name), 'job.json'), 'utf8')); } catch { continue; }
271
+ if (rec.id !== name) continue;
272
+ if (now() - (rec.endedAt || rec.startedAt || 0) > KEEP_JOB_DIR_MS) {
273
+ try { fs.rmSync(dirOf(name), { recursive: true, force: true }); } catch { /* lần sau */ }
274
+ continue;
275
+ }
276
+ const j = { ...rec, prompt: rec.prompt || '', texts: [], tools: [], waiters: new Set(), child: null, restored: true };
277
+ if (RUNNING.has(j.status)) {
278
+ j.status = 'interrupted';
279
+ j.error = 'The Aivin agent on this device restarted while this job was running — continue it with session set to its session_id';
280
+ j.endedAt = now();
281
+ persist(j);
282
+ }
283
+ jobs.set(j.id, j);
284
+ }
285
+ }
286
+ restore();
287
+
288
+ const prune = () => {
289
+ for (const [id, j] of jobs) if (!RUNNING.has(j.status) && now() - j.endedAt > KEEP_DONE_MS && !j.contractId) jobs.delete(id);
290
+ };
291
+ const readJobFile = (j, name, max) => {
292
+ try { const s = fs.readFileSync(path.join(dirOf(j.id), name), 'utf8'); return s.length > max ? `${s.slice(0, max)}\n…` : s; } catch { return undefined; }
293
+ };
294
+ const view = (j, sinceText = 0, sinceTool = 0) => {
295
+ const out = {
296
+ job: j.id, agent: j.agent, status: j.status, session_id: j.session_id, cwd: j.cwdShown, mode: j.mode, model: j.model,
297
+ new_text: j.texts.slice(sinceText).join('\n\n').slice(-MAX_ANSWER_CHARS) || undefined,
298
+ tools_used: j.tools.slice(sinceTool).slice(-40),
299
+ ...(j.result ? { result: j.result } : {}),
300
+ ...(j.error ? { error: j.error } : {}),
301
+ next_text: j.texts.length, next_tool: j.tools.length,
302
+ };
303
+ if (j.contractId) {
304
+ Object.assign(out, { contract_id: j.contractId, contract_sha256: j.contractSha, job_dir: dirOf(j.id), worktree: j.worktree || undefined });
305
+ if (!RUNNING.has(j.status)) {
306
+ const evidence = readJobFile(j, 'evidence.json', 4 * 1024 * 1024);
307
+ try { if (evidence) out.evidence = JSON.parse(evidence); } catch { /* hỏng → không gửi */ }
308
+ out.report_md = readJobFile(j, 'REPORT.md', MAX_REPORT_CHARS);
309
+ }
310
+ }
311
+ return out;
312
+ };
313
+
314
+ function remember(j) {
315
+ if (!j.session_id) return;
316
+ const list = loadSessions().filter((s) => !(s.agent === j.agent && s.session_id === j.session_id));
317
+ 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 });
318
+ saveSessions(list);
319
+ }
320
+
321
+ function waitDone(j, ms, signal) {
322
+ if (!RUNNING.has(j.status)) return Promise.resolve();
323
+ return new Promise((resolve) => {
324
+ const done = () => { clearTimeout(t); signal?.removeEventListener('abort', done); j.waiters.delete(done); resolve(); };
325
+ const t = setTimeout(done, ms);
326
+ signal?.addEventListener('abort', done, { once: true });
327
+ j.waiters.add(done);
328
+ });
329
+ }
330
+ const wake = (j) => { for (const w of [...j.waiters]) w(); };
331
+
332
+ /**
333
+ * Job có hợp đồng: kiểm khuôn + mã băm, dựng thư mục job, tính cờ của agent từ hợp đồng. Trả phần riêng của job (gộp vào `j`) + tham số
334
+ * cho adapter. Mọi lỗi ở đây xảy ra TRƯỚC khi agent chạy (không có gì thay đổi).
335
+ */
336
+ async function prepareContract(args, env, jobId, prev) {
337
+ const text = String(args.contract);
338
+ if (!args.contract_sha256) throw invalid('contract_sha256 is required with contract (the sha256 of CONTRACT.md Aivin issued)');
339
+ const parsed = parseContract(text, { expectedSha: String(args.contract_sha256) });
340
+ if (!parsed.ok) throw invalid(`CONTRACT.md is not valid: ${parsed.errors.slice(0, 12).join('; ')}`);
341
+ const { contract } = parsed;
342
+ let testCheckText = null;
343
+ if (contract.test_check) {
344
+ if (typeof args.test_check !== 'string' || !args.test_check.trim()) throw invalid('the contract names test_check — send TEST_CHECK.md as test_check');
345
+ testCheckText = args.test_check;
346
+ if (contract.test_check.sha256 && sha256(testCheckText) !== contract.test_check.sha256) throw invalid('TEST_CHECK.md does not match test_check.sha256 in the contract');
347
+ const tc = parseTestCheck(testCheckText);
348
+ if (!tc.ok) throw invalid(`TEST_CHECK.md is not valid: ${tc.errors.slice(0, 12).join('; ')}`);
349
+ const missingFlows = contract.test_check.flows.filter((f) => !tc.flows.some((x) => x.id === f));
350
+ if (missingFlows.length) throw invalid(`TEST_CHECK.md has no flow ${missingFlows.join(', ')}`);
351
+ }
352
+ // Vòng sửa (`continue_job`): làm tiếp trong worktree của job trước, diff vẫn tính từ commit gốc của lần đầu.
353
+ const cwd = prev ? prev.cwd : resolveInRoots(env.roots || [], String(args.cwd || contract.workspace.cwd || (env.roots || [])[0] || '.'));
354
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd || contract.workspace.cwd}`);
355
+ if (prev?.worktree && !fs.existsSync(prev.worktree)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `The worktree of ${prev.id} is gone: ${prev.worktree}`);
356
+ const isolate = prev ? !!prev.worktree : contract.workspace.isolation === 'worktree';
357
+ const baseCommit = prev ? prev.baseCommit : await resolveCommit(cwd, contract.workspace.base_ref);
358
+ if (isolate && !baseCommit) throw invalid(`worktree isolation needs a git repository with ${contract.workspace.base_ref} in ${args.cwd || cwd}`);
359
+ if (!prev && isolate && contract.workspace.base_ref !== 'HEAD' && baseCommit !== (await resolveCommit(cwd, 'HEAD'))) {
360
+ throw invalid(`the job worktree starts from HEAD — check out ${contract.workspace.base_ref} first, or set base_ref: HEAD`);
361
+ }
362
+
363
+ const jobDir = dirOf(jobId);
364
+ fs.mkdirSync(path.join(jobDir, 'logs'), { recursive: true });
365
+ const writeLocked = (name, body) => { const f = path.join(jobDir, name); fs.writeFileSync(f, body); try { fs.chmodSync(f, 0o444); } catch { /* chỉ là lớp phụ — mã băm mới là lớp chặn */ } };
366
+ writeLocked('CONTRACT.md', text);
367
+ if (testCheckText !== null) writeLocked('TEST_CHECK.md', testCheckText);
368
+ // Agent chỉ được ghi REPORT.md trong thư mục job; hợp đồng, bộ check và bằng chứng là của Aivin / daemon.
369
+ const deny = ['CONTRACT.md', 'TEST_CHECK.md', 'evidence.json', 'job.json', 'logs/**'].flatMap((n) => ['Edit', 'Write'].map((t) => `${t}(${claudeAbsPath(path.join(jobDir, n))})`));
370
+ return {
371
+ job: {
372
+ contract, contractId: contract.contract_id, contractSha: parsed.sha256, hasTestCheck: testCheckText !== null, testCheckText,
373
+ baseCommit, mainStateBefore: isolate ? await worktreeState(cwd) : null, isolate,
374
+ ...(prev ? { worktree: prev.worktree, fixedWorktree: !!prev.worktree, continuedFrom: prev.id } : {}),
375
+ },
376
+ cwd,
377
+ spawnCwd: prev?.worktree || cwd,
378
+ agentOpts: {
379
+ mode: contract.permissions.mode, budgetUsd: contract.limits.max_budget_usd, effort: contract.limits.effort,
380
+ allowedTools: contract.permissions.allowed_tools, addDirs: [jobDir], worktree: isolate && !prev ? jobId : undefined, projectConfig: false,
381
+ settings: { permissions: { deny } },
382
+ },
383
+ wallMs: contract.limits.max_wall_ms,
384
+ };
385
+ }
386
+
387
+ /** Worktree agent đã tạo cho job: thư mục phiên (sự kiện init) nếu đúng là một worktree của kho; không thì tìm theo tên job. */
388
+ async function findJobWorktree(j) {
389
+ const trees = await listWorktrees(j.cwd);
390
+ const same = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase();
391
+ if (j.session_cwd && !same(j.session_cwd, j.cwd) && trees.some((t) => same(t, j.session_cwd))) return path.resolve(j.session_cwd);
392
+ return trees.find((t) => !same(t, j.cwd) && path.basename(t) === j.id) || null;
393
+ }
394
+
395
+ /** Agent xong → daemon đo. Lỗi đo không làm mất kết quả của agent. */
396
+ async function finishContractJob(j) {
397
+ if (j.isolate && !j.fixedWorktree) j.worktree = await findJobWorktree(j).catch(() => null);
398
+ persist(j);
399
+ try {
400
+ const evidence = await measure({
401
+ job: { id: j.id, contractSha: j.contractSha, worktree: j.worktree, cwd: j.cwd, baseCommit: j.baseCommit, mainStateBefore: j.mainStateBefore },
402
+ contract: j.contract, testCheck: j.hasTestCheck ? parseTestCheck(j.testCheckText) : null, jobDir: dirOf(j.id), signal: j.abort.signal,
403
+ });
404
+ if (j.isolate && !j.worktree) {
405
+ evidence.worktree_missing = true;
406
+ try { fs.writeFileSync(path.join(dirOf(j.id), 'evidence.json'), JSON.stringify(evidence, null, 1)); } catch { /* đã trả qua status */ }
407
+ }
408
+ if (evidence.contract_tampered) j.error = 'contract_tampered: CONTRACT.md changed during the job';
409
+ } catch (e) {
410
+ j.error = `Measuring failed: ${e.message}`;
411
+ }
412
+ }
413
+
414
+ async function run(args, ctx = {}, env = {}) {
415
+ prune();
416
+ const withContract = args.contract !== undefined && args.contract !== null && args.contract !== '';
417
+ const prompt = String(args.prompt || '').trim();
418
+ if (!prompt && !withContract) throw invalid('Give prompt (the task for the coding agent) or contract (CONTRACT.md)');
419
+ if (prompt.length > MAX_PROMPT_CHARS) throw invalid(`prompt is longer than ${MAX_PROMPT_CHARS} characters`);
420
+ if ([...jobs.values()].filter((j) => RUNNING.has(j.status)).length >= MAX_JOBS) throw new DeviceToolError(AGENT_BUSY, `${MAX_JOBS} agent tasks are already running — wait or agent.stop one`);
421
+ const adapter = adapterFor(args.agent ? String(args.agent) : undefined);
422
+ const jobId = `${adapter.id}-${randomUUID().slice(0, 8)}`;
423
+
424
+ let cwd;
425
+ let spawnCwd;
426
+ let extra = {};
427
+ let agentOpts;
428
+ let wallMs = 0;
429
+ let prev = null;
430
+ if (args.continue_job) {
431
+ prev = jobs.get(String(args.continue_job));
432
+ if (!prev?.contractId || !prev.session_id) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No contract job ${args.continue_job} with a session to continue`);
433
+ if (RUNNING.has(prev.status)) throw invalid(`${prev.id} is still running`);
434
+ if (!withContract) throw invalid('continue_job needs the contract (the same or a new version)');
435
+ }
436
+ if (withContract) {
437
+ const prep = await prepareContract(args, env, jobId, prev);
438
+ ({ cwd, spawnCwd, agentOpts, wallMs } = prep);
439
+ extra = prep.job;
440
+ } else {
441
+ cwd = resolveInRoots(env.roots || [], String(args.cwd || (env.roots || [])[0] || '.'));
442
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd}`);
443
+ agentOpts = {
444
+ mode: String(args.mode || AgentMode.MANUAL), budgetUsd: args.max_budget_usd ?? undefined, effort: args.effort ? String(args.effort) : undefined,
445
+ projectConfig: args.project_config !== false,
446
+ };
447
+ }
448
+ const session = prev ? prev.session_id : String(args.session || 'new');
449
+ const resume = session === 'new' ? undefined
450
+ : session === 'continue' ? loadSessions().find((s) => s.agent === adapter.id && s.cwd === cwd)?.session_id
451
+ : session;
452
+ if (session === 'continue' && !resume) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No earlier ${adapter.label} session in this folder — use session "new"`);
453
+ // Nói tiếp một phiên: agent đã có worktree từ lần đầu — không tạo thêm.
454
+ if (resume && agentOpts.worktree) agentOpts = { ...agentOpts, worktree: undefined };
455
+ let argv;
456
+ try {
457
+ const flags = await flagsOf(adapter);
458
+ // Job có hợp đồng mà không đọc được cờ của bản đã cài → không chắc giới hạn (ngân sách, worktree…) được áp — từ chối.
459
+ if (withContract && !flags) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Cannot read the options of ${adapter.label} on this computer — contract jobs need them`);
460
+ argv = agentArgs(adapter, { ...agentOpts, resume, model: args.model ? String(args.model) : undefined }, flags);
461
+ } catch (e) {
462
+ if (withContract) fs.rmSync(dirOf(jobId), { recursive: true, force: true });
463
+ throw e;
464
+ }
465
+ const fullPrompt = withContract
466
+ ? contractPrompt({ jobId, jobDir: dirOf(jobId), contract: extra.contract, hasTestCheck: extra.hasTestCheck, note: prompt })
467
+ : prompt;
468
+
469
+ const j = {
470
+ id: jobId, agent: adapter.id, status: 'running', prompt: prompt || `contract ${extra.contractId}`, cwd, cwdShown: args.cwd || cwd, mode: agentOpts.mode,
471
+ session_id: resume, model: undefined, texts: [], tools: [], result: null, error: null, startedAt: now(), endedAt: 0, waiters: new Set(), child: null,
472
+ abort: new AbortController(), ...extra,
473
+ };
474
+ const child = spawnImpl(binaryOf(adapter).bin, argv, { cwd: spawnCwd || cwd, env: agentEnv(process.env), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
475
+ j.child = child;
476
+ jobs.set(j.id, j);
477
+ persist(j);
478
+ const wall = wallMs ? setTimeout(() => {
479
+ if (j.status !== 'running') return;
480
+ j.error = `Stopped at the contract time limit (${Math.round(wallMs / 60_000)} min)`;
481
+ try { j.child?.kill(); } catch { /* đã thoát */ }
482
+ }, wallMs) : null;
483
+ wall?.unref?.();
484
+ let buf = '';
485
+ let stderr = '';
486
+ child.stdout.on('data', (d) => {
487
+ buf += d.toString();
488
+ let nl;
489
+ while ((nl = buf.indexOf('\n')) >= 0) {
490
+ const line = buf.slice(0, nl).trim();
491
+ buf = buf.slice(nl + 1);
492
+ if (!line) continue;
493
+ let msg;
494
+ try { msg = JSON.parse(line); } catch { continue; }
495
+ if (!msg || typeof msg !== 'object') continue;
496
+ const shown = adapter.parse(j, msg);
497
+ if (j.texts.length > MAX_TEXTS) j.texts.splice(0, j.texts.length - MAX_TEXTS);
498
+ if (shown && typeof ctx.onOutput === 'function') { try { ctx.onOutput(`${shown}\n`); } catch { /* chỉ là tiến trình */ } }
499
+ }
500
+ });
501
+ child.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-2000); });
502
+ child.stdin.on?.('error', () => undefined);
503
+ const finish = async (code) => {
504
+ if (j.status !== 'running') return;
505
+ clearTimeout(wall);
506
+ const agentOk = !!j.result?.ok;
507
+ if (!j.result && !j.error) j.error = (stderr.trim().split(/\r?\n/).slice(-3).join(' ') || `${adapter.id} exited with code ${code}`).slice(0, 500);
508
+ if (j.contractId) {
509
+ j.status = 'measuring';
510
+ persist(j);
511
+ await finishContractJob(j);
512
+ if (j.status !== 'measuring') return; // bị dừng giữa lúc đo
513
+ }
514
+ j.status = agentOk && !j.error?.startsWith('contract_tampered') ? 'done' : 'failed';
515
+ j.endedAt = now();
516
+ remember(j);
517
+ persist(j);
518
+ wake(j);
519
+ };
520
+ child.on('error', (e) => { j.error = e.message; void finish(-1); });
521
+ child.on('close', (code) => { void finish(code); });
522
+ child.stdin.end(fullPrompt);
523
+
524
+ await waitDone(j, Math.min(Number(args.wait_ms) || DEFAULT_WAIT_MS, MAX_WAIT_MS), ctx.signal);
525
+ return { ...view(j), hint: RUNNING.has(j.status) ? 'Still working — call agent.status with this job (and next_text / next_tool) to read on' : undefined };
526
+ }
527
+
528
+ async function status(args, ctx = {}) {
529
+ const j = jobs.get(String(args.job || ''));
530
+ if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job} (finished more than 30 minutes ago, or never started)`);
531
+ await waitDone(j, Math.min(Number(args.wait_ms) || 0, MAX_WAIT_MS), ctx.signal);
532
+ return view(j, Number(args.next_text) || 0, Number(args.next_tool) || 0);
533
+ }
534
+
535
+ function halt(j, reason) {
536
+ if (!RUNNING.has(j.status)) return;
537
+ try { j.child?.kill(); } catch { /* đã thoát */ }
538
+ j.abort?.abort();
539
+ j.status = 'stopped';
540
+ if (reason) j.error = reason;
541
+ j.endedAt = now();
542
+ persist(j);
543
+ wake(j);
544
+ }
545
+
546
+ function stop(args) {
547
+ const j = jobs.get(String(args.job || ''));
548
+ if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job}`);
549
+ halt(j);
550
+ return view(j);
551
+ }
552
+
553
+ function sessions(args, _ctx, env = {}) {
554
+ const cwd = args.cwd ? resolveInRoots(env.roots || [], String(args.cwd)) : null;
555
+ return { sessions: loadSessions().filter((s) => (!cwd || s.cwd === cwd) && (!args.agent || s.agent === args.agent)).slice(0, 20) };
556
+ }
557
+
558
+ return {
559
+ run, status, stop, sessions,
560
+ installed: () => installed().map((a) => ({ id: a.id, label: a.label, version: binaryOf(a).version })),
561
+ /** Còn job đang chạy / đang đo — daemon không tự khởi động lại để cập nhật lúc này. */
562
+ hasRunning: () => [...jobs.values()].some((j) => RUNNING.has(j.status)),
563
+ stopAll: (reason = 'The Aivin agent on this device stopped') => { for (const j of jobs.values()) halt(j, reason); },
564
+ };
565
+ }
566
+
567
+ /** 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. */
568
+ export function buildAgentTools(runner) {
569
+ const agents = runner.installed();
570
+ const list = agents.map((a) => `${a.id} (${a.label} ${a.version})`).join(', ');
571
+ return [
572
+ { name: 'agent.run', group: ToolGroup.PROC, handler: (a, c, e) => runner.run(a, c, e),
573
+ 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. With contract (CONTRACT.md + contract_sha256, and test_check when the contract names one) the job runs by the contract — its own worktree, budget, permissions and time limit, no project hooks or MCP — and when it ends the device measures it and returns evidence and report_md.`,
574
+ input_schema: schema({
575
+ prompt: str('the task, in plain words (with contract: an optional extra note)'), agent: str(`which agent (default ${agents[0]?.id}): ${agents.map((a) => a.id).join(' | ')}`),
576
+ cwd: str('project folder (default the first allowed folder, or workspace.cwd of the contract)'), session: str('new | continue | <session id>'),
577
+ mode: str('manual | plan | accept_edits (with contract: from permissions.mode)'), model: str('optional model alias of that agent'),
578
+ max_budget_usd: num('stop the agent once it has spent this much (without contract)'), effort: str('low | medium | high | xhigh | max (without contract)'),
579
+ project_config: bool('load the folder\'s own agent settings, hooks and MCP servers (default true; false for a folder you do not trust; always false with contract)'),
580
+ contract: str('CONTRACT.md text issued by Aivin'), contract_sha256: str('sha256 of that CONTRACT.md'), test_check: str('TEST_CHECK.md text, when the contract names test_check'),
581
+ continue_job: str('fix round: an earlier contract job — continue its session in its worktree (send the contract again)'),
582
+ wait_ms: num(`wait for the answer up to this long (default ${DEFAULT_WAIT_MS}, max ${MAX_WAIT_MS})`),
583
+ }) },
584
+ { name: 'agent.status', group: ToolGroup.PROC, read_only: true, handler: (a, c) => runner.status(a, c),
585
+ description: 'Read a running / finished coding-agent task: new text and tools since next_text / next_tool, the result when done (with a contract also evidence and report_md). wait_ms waits for it to finish first.',
586
+ 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']) },
587
+ { name: 'agent.stop', group: ToolGroup.PROC, handler: (a) => runner.stop(a),
588
+ description: 'Stop a running coding-agent task.',
589
+ input_schema: schema({ job: str('job from agent.run') }, ['job']) },
590
+ { name: 'agent.sessions', group: ToolGroup.PROC, read_only: true, handler: (a, c, e) => runner.sessions(a, c, e),
591
+ description: 'Recent coding-agent sessions started from Aivin on this computer (agent, folder, first words of the task, when, ok) — to continue one.',
592
+ input_schema: schema({ cwd: str('only sessions of this folder'), agent: str('only this agent') }) },
593
+ ];
594
+ }