@aivin-labs/cli 1.0.75 → 1.0.78

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.
@@ -1,953 +1,1065 @@
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 { accountEnv, withProcessCap } from './multiUser.mjs';
9
- import { parseContract, parseReport, parseTestCheck, reportTemplate, sha256 } from './agentContract.mjs';
10
-
11
- /** Thời gian tối đa cho lượt nhắc agent ghi lại REPORT.md sai khuôn (cùng phiên). */
12
- const REPORT_REPAIR_MS = 5 * 60_000;
13
- import { commitJobWork, gitRead, gitWrite, globToRegExp, listWorktrees, measureEvidence, resolveCommit, runVerifyCommand, worktreeState } from './agentEvidence.mjs';
14
- import { PREVIEW_MAX_SHOTS, capturePreview } from './agentPreview.mjs';
15
-
16
- const MAX_SCOPE_RULES = 400;
17
- /** Mẫu kiểu gitignore → mẫu luật quyền của Claude Code, neo ở mọi tầng (`package.json` → `**\/package.json`). */
18
- const anyDepth = (p) => {
19
- const q = String(p).replace(/\\/g, '/').replace(/^\.?\/+/, '');
20
- return q.startsWith('**/') ? q : `**/${q}`;
21
- };
22
-
23
- /**
24
- * Phạm vi của hợp đồng thành luật CẤM của agent (11/11 → 16/11/2026: trước đây chỉ phát hiện sau khi đo). `deny_paths`: cấm sửa / ghi theo
25
- * đúng mẫu. `protected_paths`: không được sửa / xoá tệp ĐANG CÓ, thêm tệp mới thì được — mẫu có ký tự đại diện ở tên tệp (`**\/*.test.*`)
26
- * nên chỉ cấm từng tệp đang có khớp mẫu; mẫu chỉ đích danh (`package.json`, `.github/**`) cấm thẳng. Bước đo vẫn kiểm lại.
27
- */
28
- export async function scopeDenyRules(contract, cwd, { gitOpts } = {}) {
29
- const rules = [];
30
- const add = (pattern) => { for (const t of ['Edit', 'Write']) rules.push(`${t}(${pattern})`); };
31
- for (const p of contract.scope?.deny_paths || []) add(anyDepth(p));
32
- // Ký tự đại diện ở TÊN TỆP (`*.test.*`) → chỉ tệp đang có; cả thư mục (`.github/**`) → cấm luôn tệp mới (CI chạy mọi tệp trong đó).
33
- const wildcardName = (p) => { const last = String(p).replace(/\\/g, '/').split('/').filter(Boolean).pop() || ''; return last !== '**' && /[*?[]/.test(last); };
34
- const direct = (contract.scope?.protected_paths || []).filter((p) => !wildcardName(p));
35
- const globbed = (contract.scope?.protected_paths || []).filter(wildcardName);
36
- for (const p of direct) add(anyDepth(p));
37
- if (globbed.length) {
38
- let tracked = [];
39
- try { tracked = (await gitRead(cwd, ['ls-files', '-z'], gitOpts)).toString('utf8').split('\0').filter(Boolean); } catch { /* không phải kho */ }
40
- const res = globbed.map((g) => globToRegExp(g));
41
- for (const f of tracked) if (res.some((re) => re.test(f))) add(anyDepth(f));
42
- }
43
- return [...new Set(rules)].slice(0, MAX_SCOPE_RULES);
44
- }
45
-
46
- /** Tệp của thư mục job mà BE được đọc (agent.job_file) — để đưa bằng chứng, diff, log lên kho file của Aivin. */
47
- const JOB_FILE_RE = /^(CONTRACT\.md|TEST_CHECK\.md|REPORT\.md|evidence\.json|diff\.patch|logs\/[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\.log)$/;
48
- const MAX_JOB_FILE_CHUNK = 1024 * 1024;
49
- const MAX_LINK_SCAN = 200_000;
50
-
51
- /** Thư mục có liên kết (symlink / junction) bên trong không — xoá cưỡng bức đi theo liên kết là xoá cả dữ liệu thật ở nơi khác. */
52
- function hasLinks(dir) {
53
- const stack = [dir];
54
- let seen = 0;
55
- while (stack.length) {
56
- const d = stack.pop();
57
- let entries;
58
- try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
59
- for (const e of entries) {
60
- if (++seen > MAX_LINK_SCAN) return true;
61
- if (e.isSymbolicLink()) return true;
62
- if (e.isDirectory()) stack.push(path.join(d, e.name));
63
- }
64
- }
65
- return false;
66
- }
67
-
68
- /** Cắt `buf` ở biên ký tự UTF-8 (không tách đôi một ký tự nhiều byte); trả số byte giữ lại. */
69
- function utf8Boundary(buf, eof) {
70
- if (eof) return buf.length;
71
- let end = buf.length;
72
- for (let back = 0; back < 4 && end > 0 && (buf[end - 1] & 0xc0) === 0x80; back++) end--;
73
- if (end > 0 && buf[end - 1] >= 0xc0) end--;
74
- return end;
75
- }
76
-
77
- /**
78
- * 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
79
- * 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).
80
- *
81
- * 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 đó:
82
- * 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:
83
- * 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 đã
84
- * 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ờ đó).
85
- *
86
- * 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) /
87
- * `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ư
88
- * 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.
89
- *
90
- * 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ã
91
- * 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,
92
- * 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ả
93
- * `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ả
94
- * lời được `agent.status` (job đang chạy lúc tắt → `interrupted`, kèm mã phiên để nói tiếp).
95
- */
96
-
97
- const SESSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'agent-sessions.json');
98
- export const JOBS_DIR = path.join(REMOTE_CONFIG_DIR, 'jobs');
99
- const MAX_SESSIONS = 50;
100
- const MAX_JOBS = 4;
101
- const DEFAULT_WAIT_MS = 90_000;
102
- const MAX_WAIT_MS = 10 * 60_000;
103
- const MAX_PROMPT_CHARS = 20_000;
104
- const MAX_ANSWER_CHARS = 12_000;
105
- const MAX_REPORT_CHARS = 64 * 1024;
106
- const MAX_TEXTS = 400;
107
- const MAX_DENIALS = 20;
108
- const KEEP_DONE_MS = 30 * 60_000;
109
- /** Hồ sơ job (thư mục job) giữ trên đĩa bao lâu. */
110
- const KEEP_JOB_DIR_MS = 7 * 24 * 3_600_000;
111
- /** Đã chạy đủ MAX_JOBS việc cùng lúc. */
112
- const AGENT_BUSY = 'AGENT_BUSY';
113
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
114
- const MODEL_RE = /^[a-z0-9][a-z0-9.\-[\]]{0,60}$/i;
115
- const JOB_ID_RE = /^[a-z0-9]+-[0-9a-f]{8}$/;
116
- const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
117
- const RUNNING = new Set(['running', 'measuring']);
118
-
119
- /** 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. */
120
- export const AgentMode = Object.freeze({ PLAN: 'plan', MANUAL: 'manual', ACCEPT_EDITS: 'accept_edits' });
121
-
122
- const str = (description) => ({ type: 'string', description });
123
- const num = (description) => ({ type: 'number', description });
124
- const bool = (description) => ({ type: 'boolean', description });
125
- const schema = (properties, required = []) => ({ type: 'object', properties, required });
126
- const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
127
-
128
- /** `<dir>/<exe>` của mọi thư mục trong PATH. */
129
- function onPath(exe, env) {
130
- return String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean).map((dir) => path.join(dir, exe));
131
- }
132
-
133
- /** Đườ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`). */
134
- export function claudeAbsPath(abs, platform = process.platform) {
135
- if (platform === 'win32') {
136
- const m = /^([a-z]):[\\/]?(.*)$/i.exec(abs);
137
- if (m) return `//${m[1].toLowerCase()}/${m[2].replace(/\\/g, '/')}`;
138
- }
139
- return `/${abs.replace(/\\/g, '/')}`;
140
- }
141
-
142
- /**
143
- * Claude Code (2.1.x): `-p --output-format stream-json --verbose`, `--permission-mode`, `--resume <id>`, `--model`. Kiểm thật 30/10/2026.
144
- * 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`,
145
- * `--settings`, `--setting-sources`, `--strict-mcp-config`, `--permission-prompts none`.
146
- */
147
- /**
148
- * Hồ sơ tài khoản của agent lập trình (14/11/2026) — mỗi tài khoản một thư mục cấu hình riêng, truyền qua biến môi trường CHÍNH THỨC của agent
149
- * (`profileEnv` của adapter: Claude Code `CLAUDE_CONFIG_DIR`; adapter Codex sau này `CODEX_HOME`). Chuyển tài khoản = chọn hồ sơ, không sao chép
150
- * token, không đụng giao diện. Người dùng đăng nhập vào mỗi hồ sơ MỘT lần (máy không đăng nhập hộ). Thư mục: ~/.aivin/agent-profiles/<agent>/<tên>.
151
- */
152
- export const AGENT_PROFILES_DIR = path.join(REMOTE_CONFIG_DIR, 'agent-profiles');
153
- const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/i;
154
-
155
- /** Thư mục hồ sơ `name` của adapter — tên sai / adapter không hỗ trợ / chưa tạo → lỗi kèm cách tạo. */
156
- export function agentProfileDir(adapter, name, { root = AGENT_PROFILES_DIR } = {}) {
157
- const n = String(name || '').trim();
158
- if (!adapter.profileEnv) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `${adapter.label} has no account profiles on this device`);
159
- if (!PROFILE_NAME_RE.test(n)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'account: letters, digits, - or _ (max 40)');
160
- const dir = path.join(root, adapter.id, n);
161
- if (!fs.existsSync(dir)) {
162
- throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No ${adapter.label} account profile "${n}" — the person creates it once: set ${adapter.profileEnv}=${dir}, run ${adapter.id} and sign in`);
163
- }
164
- return dir;
165
- }
166
-
167
- /** Biến chỉ tiến trình root được mang — không lọt sang tài khoản thành viên (agent đọc đăng nhập trong HOME của chính họ). */
168
- const ROOT_ONLY_AGENT_ENV = ['CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN', 'OPENAI_API_KEY'];
169
-
170
- /**
171
- * Máy tính tổ chức (17/11/2026): tiến trình con của job lập trình chạy dưới tài khoản Linux của thành viên — agent, mọi lệnh git (worktree,
172
- * commit, đo diff) và lệnh kiểm chứng; HOME / USER của họ, có trần số tiến trình theo uid. Root không ghi gì vào kho của thành viên.
173
- */
174
- export function memberSpawner(account, spawnImpl = spawn) {
175
- return (cmd, argv, opts = {}) => {
176
- const [c, a] = withProcessCap(cmd, argv);
177
- const env = { ...accountEnv(account, agentEnv(opts.env || process.env)), DISABLE_AUTOUPDATER: '1', BROWSER: '/bin/true', NO_COLOR: '1' };
178
- for (const k of ROOT_ONLY_AGENT_ENV) delete env[k];
179
- return spawnImpl(c, a, { ...opts, env, uid: account.uid, gid: account.gid });
180
- };
181
- }
182
-
183
- /** Đổi chủ cả cây thư mục (thư mục job cho thành viên). Lỗi từng mục bỏ qua — chỉ chạy được khi daemon là root. */
184
- function chownTree(dir, uid, gid) {
185
- try { fs.chownSync(dir, uid, gid); } catch { return; }
186
- for (const d of fs.readdirSync(dir, { withFileTypes: true })) {
187
- const p = path.join(dir, d.name);
188
- if (d.isDirectory()) chownTree(p, uid, gid);
189
- else { try { fs.chownSync(p, uid, gid); } catch { /* bỏ qua */ } }
190
- }
191
- }
192
-
193
- /** Thêm một mẫu vào `info/exclude` của kho (không đụng .gitignore của dự án) — thư mục worktree của job không làm bẩn `git status`. */
194
- async function excludeFromRepo(cwd, pattern, gitOpts, owner = null) {
195
- try {
196
- const file = path.resolve(cwd, (await gitRead(cwd, ['rev-parse', '--git-path', 'info/exclude'], gitOpts)).toString().trim());
197
- const existed = fs.existsSync(file);
198
- const text = existed ? fs.readFileSync(file, 'utf8') : '';
199
- if (!text.split(/\r?\n/).includes(pattern)) {
200
- fs.mkdirSync(path.dirname(file), { recursive: true });
201
- fs.appendFileSync(file, `${text && !text.endsWith('\n') ? '\n' : ''}${pattern}\n`);
202
- // Máy tổ chức: tệp mới trong .git của thành viên phải thuộc về họ (daemon là root).
203
- if (!existed && owner) { try { fs.chownSync(file, owner.uid, owner.gid); } catch { /* bỏ qua */ } }
204
- }
205
- } catch { /* không ghi được — worktree vẫn chạy, chỉ hiện trong git status */ }
206
- }
207
-
208
- /** Hồ sơ đã có của từng adapter (tên thư mục). */
209
- export function listAgentProfiles(adapters, { root = AGENT_PROFILES_DIR } = {}) {
210
- const out = {};
211
- for (const a of adapters) {
212
- if (!a.profileEnv) continue;
213
- const dir = path.join(root, a.id);
214
- out[a.id] = fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && PROFILE_NAME_RE.test(d.name)).map((d) => d.name) : [];
215
- }
216
- return out;
217
- }
218
-
219
- export const CLAUDE_ADAPTER = Object.freeze({
220
- id: 'claude',
221
- label: 'Claude Code',
222
- profileEnv: 'CLAUDE_CONFIG_DIR',
223
- candidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
224
- const exe = platform === 'win32' ? 'claude.exe' : 'claude';
225
- const out = [...onPath(exe, env), path.join(home, '.local', 'bin', exe), path.join(home, '.claude', 'local', exe)];
226
- // Bản kèm extension VS Code (người dùng chỉ cài extension, không cài CLI).
227
- const extRoot = path.join(home, '.vscode', 'extensions');
228
- try {
229
- for (const d of fs.readdirSync(extRoot)) if (d.startsWith('anthropic.claude-code-')) out.push(path.join(extRoot, d, 'resources', 'native-binary', exe));
230
- } catch { /* không có VS Code */ }
231
- return out;
232
- },
233
- /**
234
- * `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`)
235
- * đặt TRƯỚC một cờ thường để không nuốt tham số sau.
236
- */
237
- args({ mode, resume, model, budgetUsd, effort, allowedTools = [], addDirs = [], worktree, projectConfig = true, settings }, flags = null) {
238
- const flag = { [AgentMode.PLAN]: 'plan', [AgentMode.MANUAL]: 'manual', [AgentMode.ACCEPT_EDITS]: 'acceptEdits' }[mode];
239
- const has = (f) => !!flags?.has(f);
240
- const argv = ['-p', '--output-format', 'stream-json', '--verbose'];
241
- if (allowedTools.length) argv.push('--allowedTools', ...allowedTools);
242
- if (addDirs.length) argv.push('--add-dir', ...addDirs);
243
- argv.push('--permission-mode', flag);
244
- // 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.
245
- if (has('--permission-prompts')) argv.push('--permission-prompts', 'none');
246
- if (!projectConfig) argv.push('--setting-sources', 'user', '--strict-mcp-config');
247
- if (settings) argv.push('--settings', JSON.stringify(settings));
248
- if (worktree) argv.push('--worktree', worktree);
249
- if (budgetUsd) argv.push('--max-budget-usd', String(budgetUsd));
250
- if (effort) argv.push('--effort', effort);
251
- if (resume) argv.push('--resume', resume);
252
- if (model) argv.push('--model', model);
253
- return argv;
254
- },
255
- /** 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 ''. */
256
- parse(job, msg) {
257
- if (msg.session_id && !job.session_id) job.session_id = msg.session_id;
258
- if (msg.type === 'system' && msg.subtype === 'init') {
259
- job.model = msg.model;
260
- if (typeof msg.cwd === 'string') job.session_cwd = msg.cwd;
261
- return '';
262
- }
263
- if (msg.type === 'assistant') {
264
- const parts = [];
265
- for (const c of msg.message?.content || []) {
266
- if (c.type === 'text' && c.text?.trim()) { job.texts.push(c.text); parts.push(c.text); }
267
- if (c.type === 'tool_use') {
268
- const target = c.input?.file_path || c.input?.path || c.input?.command || c.input?.pattern || c.input?.url || '';
269
- const line = `🔧 ${c.name}${target ? ` ${String(target).slice(0, 160)}` : ''}`;
270
- job.tools.push(line);
271
- parts.push(line);
272
- }
273
- }
274
- return parts.join('\n');
275
- }
276
- if (msg.type === 'result') {
277
- job.result = {
278
- ok: !msg.is_error && msg.subtype === 'success', answer: String(msg.result ?? '').slice(0, MAX_ANSWER_CHARS),
279
- cost_usd: typeof msg.total_cost_usd === 'number' ? Math.round(msg.total_cost_usd * 10_000) / 10_000 : undefined,
280
- turns: msg.num_turns, duration_ms: msg.duration_ms,
281
- };
282
- if (msg.subtype && msg.subtype !== 'success') job.result.stop_reason = msg.subtype;
283
- // 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.
284
- const denials = Array.isArray(msg.permission_denials) ? msg.permission_denials : [];
285
- if (denials.length) {
286
- job.result.permission_denials = denials.slice(0, MAX_DENIALS).map((d) => {
287
- const target = d.tool_input?.command || d.tool_input?.file_path || d.tool_input?.path || d.tool_input?.url || '';
288
- return { tool: String(d.tool_name || ''), ...(target ? { target: String(target).slice(0, 200) } : {}) };
289
- });
290
- }
291
- }
292
- return '';
293
- },
294
- });
295
-
296
- /** Thư mục cài Codex đi kèm extension VS Code (openai.chatgpt-*), theo nền tảng. */
297
- function codexExtensionBins(home, exe) {
298
- const sub = process.platform === 'win32' ? 'windows-x86_64' : `${process.platform}-${os.arch()}`;
299
- const root = path.join(home, '.vscode', 'extensions');
300
- try {
301
- return fs.readdirSync(root).filter((d) => d.startsWith('openai.chatgpt-')).sort().reverse().map((d) => path.join(root, d, 'bin', sub, exe));
302
- } catch { return []; }
303
- }
304
-
305
- /**
306
- * Codex CLI (17/11/2026) — `codex exec --json`, đề bài qua stdin. Đã đo trên bản 0.169 (Windows): `-s workspace-write` một mình bị chặn mọi
307
- * lệnh ("blocked by policy"), `--approve-for-me` (sandbox workspace-write + duyệt tự động) chạy được; chỉ đọc = `-s read-only`. Không có cờ
308
- * ngân sách (thời hạn hợp đồng vẫn do daemon cắt), không quản worktree theo tên → daemon tự dựng worktree (`selfWorktree: false`).
309
- * `exec resume` không nhận cờ sandbox / duyệt → vòng sửa mở phiên MỚI trong worktree cũ (`resumable: false`; hợp đồng + lời nhắc đủ ngữ cảnh).
310
- */
311
- export const CODEX_ADAPTER = Object.freeze({
312
- id: 'codex',
313
- label: 'Codex',
314
- profileEnv: 'CODEX_HOME',
315
- selfWorktree: false,
316
- resumable: false,
317
- helpArgs: ['exec', '--help'],
318
- candidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
319
- const exe = platform === 'win32' ? 'codex.exe' : 'codex';
320
- return [...onPath(exe, env), path.join(home, '.local', 'bin', exe), ...codexExtensionBins(home, exe)];
321
- },
322
- args({ mode, model, effort, addDirs = [] }) {
323
- const argv = ['exec', '--json', '--ignore-user-config', '--ignore-rules'];
324
- // Chế độ quyền chung → sandbox của Codex. "manual" (việc cần quyền bị từ chối) không có tương đương an toàn → chỉ đọc.
325
- if (mode === AgentMode.ACCEPT_EDITS) argv.push('--approve-for-me');
326
- else argv.push('-s', 'read-only');
327
- for (const d of addDirs) argv.push('--add-dir', d);
328
- if (model) argv.push('-m', model);
329
- if (effort) argv.push('-c', `model_reasoning_effort="${effort === 'xhigh' || effort === 'max' ? 'high' : effort}"`);
330
- argv.push('-');
331
- return argv;
332
- },
333
- /** Một dòng JSONL của `codex exec --json` → cập nhật việc; trả đoạn chữ đáng đẩy lên Aivin. */
334
- parse(job, msg) {
335
- if (msg.type === 'thread.started' && typeof msg.thread_id === 'string' && !job.session_id) { job.session_id = msg.thread_id; return ''; }
336
- const item = msg.item;
337
- if (msg.type === 'item.completed' && item?.type === 'agent_message' && typeof item.text === 'string' && item.text.trim()) {
338
- job.texts.push(item.text);
339
- return item.text;
340
- }
341
- if (msg.type === 'item.started' && item && item.type !== 'agent_message' && item.type !== 'reasoning') {
342
- const target = item.command || (Array.isArray(item.changes) ? item.changes.map((c) => c.path).join(', ') : '') || '';
343
- const line = `🔧 ${item.type}${target ? ` ${String(target).slice(0, 160)}` : ''}`;
344
- job.tools.push(line);
345
- return line;
346
- }
347
- if (msg.type === 'turn.completed') {
348
- job.result = {
349
- ok: true, answer: String(job.texts[job.texts.length - 1] || '').slice(0, MAX_ANSWER_CHARS),
350
- usage: { input_tokens: msg.usage?.input_tokens, output_tokens: msg.usage?.output_tokens },
351
- };
352
- }
353
- if (msg.type === 'turn.failed' || msg.type === 'error') {
354
- job.result = { ok: false, answer: String(msg.error?.message || msg.message || 'Codex error').slice(0, MAX_ANSWER_CHARS), stop_reason: 'error' };
355
- }
356
- return '';
357
- },
358
- });
359
-
360
- export const DEFAULT_AGENT_ADAPTERS = Object.freeze([CLAUDE_ADAPTER, CODEX_ADAPTER]);
361
-
362
- function versionOf(bin) {
363
- try {
364
- const out = execFileSync(bin, ['--version'], { encoding: 'utf8', timeout: 15_000, windowsHide: true });
365
- const m = /(\d+)\.(\d+)\.(\d+)/.exec(out);
366
- return m ? m.slice(1).map(Number) : null;
367
- } catch { return null; }
368
- }
369
- const newer = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return false; };
370
-
371
- /** 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. */
372
- export function helpFlags(bin, helpArgs = ['--help']) {
373
- return new Promise((resolve) => {
374
- execFile(bin, helpArgs, { encoding: 'utf8', timeout: 20_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, out) => {
375
- resolve(err ? null : new Set(String(out).match(/--[a-z][a-z-]+/gi) || []));
376
- });
377
- });
378
- }
379
-
380
- /** Bản mới nhất chạy được của một agent trên máy, hoặc null. */
381
- export function findAgentBinary(adapter, opts = {}) {
382
- let best = null;
383
- for (const bin of [...new Set(adapter.candidates(opts))]) {
384
- if (!fs.existsSync(bin)) continue;
385
- const v = (opts.versionOf || versionOf)(bin);
386
- if (v && (!best || newer(v, best.version))) best = { bin, version: v };
387
- }
388
- return best ? { bin: best.bin, version: best.version.join('.') } : null;
389
- }
390
-
391
- /** 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. */
392
- export function agentArgs(adapter, { mode = AgentMode.MANUAL, resume, model, budgetUsd, effort, ...rest } = {}, flags = null) {
393
- if (!Object.values(AgentMode).includes(mode)) throw invalid(`mode must be one of: ${Object.values(AgentMode).join(', ')}`);
394
- if (resume && !UUID_RE.test(resume)) throw invalid('session must be "new", "continue" or a session id');
395
- if (model && !MODEL_RE.test(model)) throw invalid('Bad model name');
396
- if (budgetUsd !== undefined && !(Number(budgetUsd) > 0 && Number(budgetUsd) <= 200)) throw invalid('max_budget_usd must be above 0 and at most 200');
397
- if (effort !== undefined && !EFFORTS.includes(effort)) throw invalid(`effort must be one of: ${EFFORTS.join(', ')}`);
398
- const argv = adapter.args({ mode, resume, model, budgetUsd: budgetUsd === undefined ? undefined : Number(budgetUsd), effort, ...rest }, flags);
399
- // 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).
400
- const missing = flags ? argv.filter((a) => a.startsWith('--') && !flags.has(a)) : [];
401
- if (missing.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${adapter.label} on this computer is too old for ${missing.join(', ')} — update it`);
402
- return argv;
403
- }
404
-
405
- function loadSessions() {
406
- try { const v = JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf8')); return Array.isArray(v) ? v : []; } catch { return []; }
407
- }
408
- function saveSessions(list) {
409
- 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 */ }
410
- }
411
-
412
- /** Đề 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. */
413
- function contractPrompt({ jobId, jobDir, contract, hasTestCheck, note }) {
414
- const report = path.join(jobDir, 'REPORT.md');
415
- return [
416
- `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.`,
417
- 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.` : '',
418
- 'Rules:',
419
- '- 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).',
420
- '- Stay inside the current folder for code changes. Do not touch paths the contract denies or protects (you may add new files).',
421
- '- 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.',
422
- '- Do not skip, disable or delete existing tests to make things pass.',
423
- '- If you propose a new check under "Ca kiểm mới" with id NEW-n and method auto, write its test too and put NEW-n in the test name — the device measures it like the others.',
424
- contract.setup?.length ? `- Before running tests, run the setup commands of the contract (setup) in the current folder: ${contract.setup.map((s) => s.argv.join(' ')).join(' ; ')}.` : '',
425
- `When you finish (or stop), write ${report} exactly in this format — frontmatter holds short values only, sentences go in the sections; keep EVERY section heading even when it has nothing (an empty "# Phần chưa làm" or "# Ca kiểm mới" is fine), and delete only the example check under "Ca kiểm mới" if you propose none:`,
426
- '',
427
- reportTemplate({ jobId, contractId: contract.contract_id }),
428
- note ? `\nNote from Aivin: ${note}` : '',
429
- ].filter((l) => l !== '').join('\n');
430
- }
431
-
432
- export function createAgentRunner({
433
- adapters = DEFAULT_AGENT_ADAPTERS, find = findAgentBinary, spawnImpl = spawn, now = Date.now, jobsDir = JOBS_DIR, measure = measureEvidence, probeFlags = helpFlags,
434
- profilesRoot = AGENT_PROFILES_DIR,
435
- /** Máy tính tổ chức: tài khoản Linux của thành viên ({ name, uid, gid, home }) — mọi tiến trình con chạy dưới tài khoản này. */
436
- runAs = null,
437
- } = {}) {
438
- const childSpawn = runAs ? memberSpawner(runAs, spawnImpl) : spawnImpl;
439
- /** Lệnh git của job: dưới tài khoản thành viên khi có (tệp trong .git của họ không thuộc root). */
440
- const gitOpts = runAs ? { spawnImpl: childSpawn } : undefined;
441
- const found = new Map();
442
- const flagCache = new Map();
443
- const jobs = new Map();
444
- const binaryOf = (adapter) => {
445
- if (!found.has(adapter.id)) found.set(adapter.id, find(adapter));
446
- return found.get(adapter.id);
447
- };
448
- const flagsOf = async (adapter) => {
449
- const b = binaryOf(adapter);
450
- if (b?.flags) return new Set(b.flags);
451
- if (!flagCache.has(adapter.id)) flagCache.set(adapter.id, b ? Promise.resolve(probeFlags(b.bin, adapter.helpArgs)).catch(() => null) : null);
452
- return flagCache.get(adapter.id);
453
- };
454
- /** Agent đã cài trên máy (theo thứ tự ưu tiên của danh sách adapter). */
455
- const installed = () => adapters.filter((a) => binaryOf(a));
456
- const adapterFor = (id) => {
457
- const list = installed();
458
- 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(', ')})`);
459
- if (!id) return list[0];
460
- const a = list.find((x) => x.id === id);
461
- if (!a) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${id} is not installed here — available: ${list.map((x) => x.id).join(', ')}`);
462
- return a;
463
- };
464
-
465
- // --- 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).
466
- const dirOf = (id) => path.join(jobsDir, id);
467
- const RECORD_KEYS = ['id', 'agent', 'status', 'cwd', 'cwdShown', 'mode', 'model', 'session_id', 'worktree', 'baseCommit', 'contractId', 'contractSha', 'continuedFrom', 'delivery', 'worktreeRemoved', 'reportRepaired', 'startedAt', 'endedAt', 'result', 'error'];
468
- function persist(j) {
469
- try {
470
- fs.mkdirSync(dirOf(j.id), { recursive: true });
471
- 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));
472
- } catch { /* hồ sơ chỉ để trả lời sau khi khởi động lại */ }
473
- }
474
- /** 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. */
475
- function restore() {
476
- let names;
477
- try { names = fs.readdirSync(jobsDir); } catch { return; }
478
- for (const name of names) {
479
- if (!JOB_ID_RE.test(name)) continue;
480
- let rec;
481
- try { rec = JSON.parse(fs.readFileSync(path.join(dirOf(name), 'job.json'), 'utf8')); } catch { continue; }
482
- if (rec.id !== name) continue;
483
- if (now() - (rec.endedAt || rec.startedAt || 0) > KEEP_JOB_DIR_MS) {
484
- try { fs.rmSync(dirOf(name), { recursive: true, force: true }); } catch { /* lần sau */ }
485
- continue;
486
- }
487
- const j = { ...rec, prompt: rec.prompt || '', texts: [], tools: [], waiters: new Set(), child: null, restored: true };
488
- if (RUNNING.has(j.status)) {
489
- j.status = 'interrupted';
490
- j.error = 'The Aivin agent on this device restarted while this job was running — continue it with session set to its session_id';
491
- j.endedAt = now();
492
- persist(j);
493
- }
494
- jobs.set(j.id, j);
495
- }
496
- }
497
- restore();
498
-
499
- const prune = () => {
500
- for (const [id, j] of jobs) if (!RUNNING.has(j.status) && now() - j.endedAt > KEEP_DONE_MS && !j.contractId) jobs.delete(id);
501
- };
502
- const readJobFile = (j, name, max) => {
503
- 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; }
504
- };
505
- const view = (j, sinceText = 0, sinceTool = 0) => {
506
- const out = {
507
- job: j.id, agent: j.agent, status: j.status, session_id: j.session_id, cwd: j.cwdShown, mode: j.mode, model: j.model,
508
- new_text: j.texts.slice(sinceText).join('\n\n').slice(-MAX_ANSWER_CHARS) || undefined,
509
- tools_used: j.tools.slice(sinceTool).slice(-40),
510
- ...(j.result ? { result: j.result } : {}),
511
- ...(j.error ? { error: j.error } : {}),
512
- next_text: j.texts.length, next_tool: j.tools.length,
513
- };
514
- if (j.contractId) {
515
- Object.assign(out, {
516
- contract_id: j.contractId, contract_sha256: j.contractSha, job_dir: dirOf(j.id), worktree: j.worktree || undefined,
517
- ...(j.delivery ? { delivery: j.delivery } : {}), ...(j.worktreeRemoved ? { worktree_removed: true } : {}), ...(j.reportRepaired ? { report_repaired: true } : {}),
518
- });
519
- if (!RUNNING.has(j.status)) {
520
- const evidence = readJobFile(j, 'evidence.json', 4 * 1024 * 1024);
521
- try { if (evidence) out.evidence = JSON.parse(evidence); } catch { /* hỏng → không gửi */ }
522
- out.report_md = readJobFile(j, 'REPORT.md', MAX_REPORT_CHARS);
523
- }
524
- }
525
- return out;
526
- };
527
-
528
- function remember(j) {
529
- if (!j.session_id) return;
530
- const list = loadSessions().filter((s) => !(s.agent === j.agent && s.session_id === j.session_id));
531
- 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, ...(j.account ? { account: j.account } : {}) });
532
- saveSessions(list);
533
- }
534
-
535
- function waitDone(j, ms, signal) {
536
- if (!RUNNING.has(j.status)) return Promise.resolve();
537
- return new Promise((resolve) => {
538
- const done = () => { clearTimeout(t); signal?.removeEventListener('abort', done); j.waiters.delete(done); resolve(); };
539
- const t = setTimeout(done, ms);
540
- signal?.addEventListener('abort', done, { once: true });
541
- j.waiters.add(done);
542
- });
543
- }
544
- const wake = (j) => { for (const w of [...j.waiters]) w(); };
545
-
546
- /**
547
- * 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ố
548
- * cho adapter. Mọi lỗi ở đây xảy ra TRƯỚC khi agent chạy (không có gì thay đổi).
549
- */
550
- async function prepareContract(args, env, jobId, prev, adapter) {
551
- const text = String(args.contract);
552
- if (!args.contract_sha256) throw invalid('contract_sha256 is required with contract (the sha256 of CONTRACT.md Aivin issued)');
553
- const parsed = parseContract(text, { expectedSha: String(args.contract_sha256) });
554
- if (!parsed.ok) throw invalid(`CONTRACT.md is not valid: ${parsed.errors.slice(0, 12).join('; ')}`);
555
- const { contract } = parsed;
556
- let testCheckText = null;
557
- if (contract.test_check) {
558
- if (typeof args.test_check !== 'string' || !args.test_check.trim()) throw invalid('the contract names test_check — send TEST_CHECK.md as test_check');
559
- testCheckText = args.test_check;
560
- 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');
561
- const tc = parseTestCheck(testCheckText);
562
- if (!tc.ok) throw invalid(`TEST_CHECK.md is not valid: ${tc.errors.slice(0, 12).join('; ')}`);
563
- const missingFlows = contract.test_check.flows.filter((f) => !tc.flows.some((x) => x.id === f));
564
- if (missingFlows.length) throw invalid(`TEST_CHECK.md has no flow ${missingFlows.join(', ')}`);
565
- }
566
- // 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.
567
- const cwd = prev ? prev.cwd : resolveInRoots(env.roots || [], String(args.cwd || contract.workspace.cwd || (env.roots || [])[0] || '.'));
568
- if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd || contract.workspace.cwd}`);
569
- if (prev?.worktree && !fs.existsSync(prev.worktree)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `The worktree of ${prev.id} is gone: ${prev.worktree}`);
570
- const isolate = prev ? !!prev.worktree : contract.workspace.isolation === 'worktree';
571
- const baseCommit = prev ? prev.baseCommit : await resolveCommit(cwd, contract.workspace.base_ref, gitOpts);
572
- if (isolate && !baseCommit) throw invalid(`worktree isolation needs a git repository with ${contract.workspace.base_ref} in ${args.cwd || cwd}`);
573
- // Daemon tự dựng worktree (17/11/2026) khi agent không tự quản worktree theo tên (Codex) hoặc hợp đồng đi từ commit khác HEAD (việc nối
574
- // tiếp việc trước) — agent tự dựng thì luôn từ HEAD. Nhánh `aivin/<job>`, thư mục `<repo>/.aivin-worktrees/<job>` (loại khỏi git status).
575
- let ownWorktree = null;
576
- // Máy tổ chức: daemon luôn tự dựng worktree (dưới tài khoản thành viên) — không để agent dựng bằng đường dẫn root không biết trước.
577
- if (!prev && isolate && (runAs || adapter.selfWorktree === false || (baseCommit !== (await resolveCommit(cwd, 'HEAD', gitOpts))))) {
578
- ownWorktree = path.join(cwd, '.aivin-worktrees', jobId);
579
- await excludeFromRepo(cwd, '/.aivin-worktrees/', gitOpts, runAs);
580
- await gitWrite(cwd, ['worktree', 'add', '-q', '-b', `aivin/${jobId}`, ownWorktree, baseCommit], gitOpts);
581
- }
582
-
583
- const jobDir = dirOf(jobId);
584
- fs.mkdirSync(path.join(jobDir, 'logs'), { recursive: true });
585
- 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 */ } };
586
- writeLocked('CONTRACT.md', text);
587
- if (testCheckText !== null) writeLocked('TEST_CHECK.md', testCheckText);
588
- // Thư mục job thuộc về thành viên: agent của họ đọc hợp đồng + ghi REPORT.md (sửa CONTRACT.md thì mã băm bắt).
589
- if (runAs) chownTree(jobDir, runAs.uid, runAs.gid);
590
- // 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.
591
- const deny = [
592
- ...['CONTRACT.md', 'TEST_CHECK.md', 'evidence.json', 'job.json', 'logs/**'].flatMap((n) => ['Edit', 'Write'].map((t) => `${t}(${claudeAbsPath(path.join(jobDir, n))})`)),
593
- // Phạm vi chặn TRƯỚC (không chỉ phát hiện sau): `npm test` được phép + sửa được package.json = chạy được mọi lệnh.
594
- ...(await scopeDenyRules(contract, cwd, { gitOpts })),
595
- ];
596
- return {
597
- job: {
598
- contract, contractId: contract.contract_id, contractSha: parsed.sha256, hasTestCheck: testCheckText !== null, testCheckText,
599
- baseCommit, mainStateBefore: isolate ? await worktreeState(cwd, gitOpts) : null, isolate,
600
- ...(prev ? { worktree: prev.worktree, fixedWorktree: !!prev.worktree, continuedFrom: prev.id } : {}),
601
- ...(ownWorktree ? { worktree: ownWorktree, fixedWorktree: true } : {}),
602
- },
603
- cwd,
604
- spawnCwd: prev?.worktree || ownWorktree || cwd,
605
- agentOpts: {
606
- mode: contract.permissions.mode, budgetUsd: contract.limits.max_budget_usd, effort: contract.limits.effort,
607
- allowedTools: contract.permissions.allowed_tools, addDirs: [jobDir], worktree: isolate && !prev && !ownWorktree ? jobId : undefined, projectConfig: false,
608
- settings: { permissions: { deny } },
609
- },
610
- wallMs: contract.limits.max_wall_ms,
611
- };
612
- }
613
-
614
- /** 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. */
615
- async function findJobWorktree(j) {
616
- const trees = await listWorktrees(j.cwd, gitOpts);
617
- const same = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase();
618
- if (j.session_cwd && !same(j.session_cwd, j.cwd) && trees.some((t) => same(t, j.session_cwd))) return path.resolve(j.session_cwd);
619
- return trees.find((t) => !same(t, j.cwd) && path.basename(t) === j.id) || null;
620
- }
621
-
622
- /** Agent xong → daemon đo. Lỗi đo không làm mất kết quả của agent. */
623
- /**
624
- * REPORT.md sai khuôn (hoặc chưa ghi) → nhắc agent ghi lại MỘT lần trong cùng phiên, trước khi đo (thiết kế: "sai thì yêu cầu ghi lại trong
625
- * cùng phiên, vẫn sai thì coi là chưa giao đủ"). Rẻ hơn cả một vòng sửa (đo lại + agent đọc lại hợp đồng) chỉ vì thiếu một tiêu đề mục.
626
- */
627
- async function repairReport(j) {
628
- if (!j.respawn || j.abort.signal.aborted) return;
629
- const fresh = j.respawn.adapter.resumable === false;
630
- if (!fresh && !j.session_id) return;
631
- const file = path.join(dirOf(j.id), 'REPORT.md');
632
- let text = null;
633
- try { text = fs.readFileSync(file, 'utf8'); } catch { /* chưa ghi */ }
634
- const parsed = text === null ? { ok: false, errors: ['REPORT.md was not written'] } : parseReport(text, { contractId: j.contractId });
635
- if (parsed.ok) return;
636
- const { adapter, opts, flags, env, bin } = j.respawn;
637
- let argv;
638
- try { argv = agentArgs(adapter, { ...opts, worktree: undefined, resume: fresh ? undefined : j.session_id }, flags); } catch { return; }
639
- // Agent không nói tiếp phiên được (Codex): phiên mới không thấy khuôn lúc đầu → gửi kèm khuôn mẫu.
640
- const format = fresh ? `\n\nThe agreed format:\n${reportTemplate({ jobId: j.id, contractId: j.contractId })}` : '';
641
- const prompt = `${file} is not in the agreed format: ${parsed.errors.slice(0, 8).join('; ')}. Rewrite only REPORT.md, exactly in the ${fresh ? 'format below' : 'format given at the start'} (keep every section heading, even when empty). Do not change any other file.${format}`;
642
- await new Promise((resolve) => {
643
- let child;
644
- try { child = childSpawn(bin, argv, { cwd: j.worktree || j.respawn.cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }); } catch { resolve(); return; }
645
- const timer = setTimeout(() => { try { child.kill(); } catch { /* đã thoát */ } }, REPORT_REPAIR_MS);
646
- const done = () => { clearTimeout(timer); resolve(); };
647
- child.stdout?.on?.('data', () => undefined);
648
- child.stderr?.on?.('data', () => undefined);
649
- child.stdin?.on?.('error', () => undefined);
650
- child.on('close', done);
651
- child.on('error', done);
652
- child.stdin.end(prompt);
653
- });
654
- j.reportRepaired = true;
655
- }
656
-
657
- async function finishContractJob(j) {
658
- if (j.isolate && !j.fixedWorktree) j.worktree = await findJobWorktree(j).catch(() => null);
659
- // Sau khi biết worktree: phiên của agent nằm ở đó, nói tiếp phải đúng thư mục ấy.
660
- await repairReport(j).catch(() => undefined);
661
- // Đầu ra `git_branch`: commit thay đổi của worktree lên nhánh của job TRƯỚC khi đo — bằng chứng gắn đúng một commit.
662
- if (j.worktree && j.contract?.outputs?.some((o) => o.kind === 'git_branch')) {
663
- try {
664
- j.delivery = await commitJobWork(j.worktree, `aivin: ${j.contractId} v${j.contract.version} (job ${j.id})`, { jobId: j.id, ...(gitOpts || {}) });
665
- } catch (e) { j.delivery = { error: e.message.slice(0, 300) }; }
666
- }
667
- persist(j);
668
- try {
669
- const evidence = await measure({
670
- job: { id: j.id, contractSha: j.contractSha, worktree: j.worktree, cwd: j.cwd, baseCommit: j.baseCommit, mainStateBefore: j.mainStateBefore, delivery: j.delivery },
671
- contract: j.contract, testCheck: j.hasTestCheck ? parseTestCheck(j.testCheckText) : null, jobDir: dirOf(j.id), signal: j.abort.signal,
672
- ...(runAs ? { gitOpts, runCommand: (cmd, o) => runVerifyCommand(cmd, { ...o, spawnImpl: childSpawn }) } : {}),
673
- });
674
- if (j.isolate && !j.worktree) {
675
- evidence.worktree_missing = true;
676
- try { fs.writeFileSync(path.join(dirOf(j.id), 'evidence.json'), JSON.stringify(evidence, null, 1)); } catch { /* đã trả qua status */ }
677
- }
678
- if (evidence.contract_tampered) j.error = 'contract_tampered: CONTRACT.md changed during the job';
679
- } catch (e) {
680
- j.error = `Measuring failed: ${e.message}`;
681
- }
682
- }
683
-
684
- async function run(args, ctx = {}, env = {}) {
685
- prune();
686
- const withContract = args.contract !== undefined && args.contract !== null && args.contract !== '';
687
- const prompt = String(args.prompt || '').trim();
688
- if (!prompt && !withContract) throw invalid('Give prompt (the task for the coding agent) or contract (CONTRACT.md)');
689
- if (prompt.length > MAX_PROMPT_CHARS) throw invalid(`prompt is longer than ${MAX_PROMPT_CHARS} characters`);
690
- 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`);
691
- const adapter = adapterFor(args.agent ? String(args.agent) : undefined);
692
- const account = args.account ? String(args.account).trim() : '';
693
- if (runAs && account) throw invalid('account profiles are not used on an organisation computer — each member signs in to the agent with their own account');
694
- const accountDir = account ? agentProfileDir(adapter, account, { root: profilesRoot }) : null;
695
- const jobId = `${adapter.id}-${randomUUID().slice(0, 8)}`;
696
-
697
- let cwd;
698
- let spawnCwd;
699
- let extra = {};
700
- let agentOpts;
701
- let wallMs = 0;
702
- let prev = null;
703
- if (args.continue_job) {
704
- prev = jobs.get(String(args.continue_job));
705
- if (!prev?.contractId || !prev.session_id) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No contract job ${args.continue_job} with a session to continue`);
706
- if (RUNNING.has(prev.status)) throw invalid(`${prev.id} is still running`);
707
- if (!withContract) throw invalid('continue_job needs the contract (the same or a new version)');
708
- }
709
- if (withContract) {
710
- const prep = await prepareContract(args, env, jobId, prev, adapter);
711
- ({ cwd, spawnCwd, agentOpts, wallMs } = prep);
712
- extra = prep.job;
713
- } else {
714
- cwd = resolveInRoots(env.roots || [], String(args.cwd || (env.roots || [])[0] || '.'));
715
- if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd}`);
716
- agentOpts = {
717
- mode: String(args.mode || AgentMode.MANUAL), budgetUsd: args.max_budget_usd ?? undefined, effort: args.effort ? String(args.effort) : undefined,
718
- projectConfig: args.project_config !== false,
719
- };
720
- }
721
- const session = prev ? (adapter.resumable === false ? 'new' : prev.session_id) : String(args.session || 'new');
722
- const resume = session === 'new' ? undefined
723
- : session === 'continue' ? loadSessions().find((s) => s.agent === adapter.id && s.cwd === cwd && (s.account || '') === account)?.session_id
724
- : session;
725
- if (session === 'continue' && !resume) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No earlier ${adapter.label} session in this folder — use session "new"`);
726
- // Nói tiếp một phiên: agent đã có worktree từ lần đầu — không tạo thêm.
727
- if (resume && agentOpts.worktree) agentOpts = { ...agentOpts, worktree: undefined };
728
- let argv;
729
- try {
730
- const flags = await flagsOf(adapter);
731
- // 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.
732
- if (withContract && !flags) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Cannot read the options of ${adapter.label} on this computer — contract jobs need them`);
733
- argv = agentArgs(adapter, { ...agentOpts, resume, model: args.model ? String(args.model) : undefined }, flags);
734
- } catch (e) {
735
- if (withContract) fs.rmSync(dirOf(jobId), { recursive: true, force: true });
736
- // Worktree daemon vừa dựng cho job này (chưa giao agent) → gỡ luôn worktree + nhánh, không để rác trong repo của người dùng.
737
- if (withContract && !prev && extra.worktree && extra.fixedWorktree) {
738
- await gitWrite(cwd, ['worktree', 'remove', '--force', extra.worktree], gitOpts).catch(() => undefined);
739
- await gitWrite(cwd, ['branch', '-D', `aivin/${jobId}`], gitOpts).catch(() => undefined);
740
- }
741
- throw e;
742
- }
743
- const fullPrompt = withContract
744
- ? contractPrompt({ jobId, jobDir: dirOf(jobId), contract: extra.contract, hasTestCheck: extra.hasTestCheck, note: prompt })
745
- : prompt;
746
-
747
- const j = {
748
- id: jobId, agent: adapter.id, status: 'running', prompt: prompt || `contract ${extra.contractId}`, cwd, cwdShown: args.cwd || cwd, mode: agentOpts.mode,
749
- session_id: resume, model: undefined, texts: [], tools: [], result: null, error: null, startedAt: now(), endedAt: 0, waiters: new Set(), child: null,
750
- abort: new AbortController(), ...extra, ...(account ? { account } : {}),
751
- };
752
- // Hồ sơ tài khoản: thư mục cấu hình riêng qua biến môi trường chính thức của agent — phiên / đăng nhập / hạn mức của tài khoản đó.
753
- const childEnv = accountDir ? { ...agentEnv(process.env), [adapter.profileEnv]: accountDir } : agentEnv(process.env);
754
- const child = childSpawn(binaryOf(adapter).bin, argv, { cwd: spawnCwd || cwd, env: childEnv, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
755
- j.child = child;
756
- // Gọi lại cùng phiên (nhắc ghi lại REPORT.md) cần đúng tệp chạy, cờ, môi trường của lần này.
757
- if (withContract) j.respawn = { adapter, bin: binaryOf(adapter).bin, opts: { ...agentOpts, model: args.model ? String(args.model) : undefined }, flags: await flagsOf(adapter), env: childEnv, cwd: spawnCwd || cwd };
758
- jobs.set(j.id, j);
759
- persist(j);
760
- const wall = wallMs ? setTimeout(() => {
761
- if (j.status !== 'running') return;
762
- j.error = `Stopped at the contract time limit (${Math.round(wallMs / 60_000)} min)`;
763
- try { j.child?.kill(); } catch { /* đã thoát */ }
764
- }, wallMs) : null;
765
- wall?.unref?.();
766
- let buf = '';
767
- let stderr = '';
768
- child.stdout.on('data', (d) => {
769
- buf += d.toString();
770
- let nl;
771
- while ((nl = buf.indexOf('\n')) >= 0) {
772
- const line = buf.slice(0, nl).trim();
773
- buf = buf.slice(nl + 1);
774
- if (!line) continue;
775
- let msg;
776
- try { msg = JSON.parse(line); } catch { continue; }
777
- if (!msg || typeof msg !== 'object') continue;
778
- const shown = adapter.parse(j, msg);
779
- if (j.texts.length > MAX_TEXTS) j.texts.splice(0, j.texts.length - MAX_TEXTS);
780
- if (shown && typeof ctx.onOutput === 'function') { try { ctx.onOutput(`${shown}\n`); } catch { /* chỉ là tiến trình */ } }
781
- }
782
- });
783
- child.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-2000); });
784
- child.stdin.on?.('error', () => undefined);
785
- const finish = async (code) => {
786
- if (j.status !== 'running') return;
787
- clearTimeout(wall);
788
- const agentOk = !!j.result?.ok;
789
- if (!j.result && !j.error) j.error = (stderr.trim().split(/\r?\n/).slice(-3).join(' ') || `${adapter.id} exited with code ${code}`).slice(0, 500);
790
- if (j.contractId) {
791
- j.status = 'measuring';
792
- persist(j);
793
- await finishContractJob(j);
794
- if (j.status !== 'measuring') return; // bị dừng giữa lúc đo
795
- }
796
- j.status = agentOk && !j.error?.startsWith('contract_tampered') ? 'done' : 'failed';
797
- j.endedAt = now();
798
- remember(j);
799
- persist(j);
800
- wake(j);
801
- };
802
- child.on('error', (e) => { j.error = e.message; void finish(-1); });
803
- child.on('close', (code) => { void finish(code); });
804
- child.stdin.end(fullPrompt);
805
-
806
- await waitDone(j, Math.min(Number(args.wait_ms) || DEFAULT_WAIT_MS, MAX_WAIT_MS), ctx.signal);
807
- 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 };
808
- }
809
-
810
- async function status(args, ctx = {}) {
811
- const j = jobs.get(String(args.job || ''));
812
- if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job} (finished more than 30 minutes ago, or never started)`);
813
- await waitDone(j, Math.min(Number(args.wait_ms) || 0, MAX_WAIT_MS), ctx.signal);
814
- return view(j, Number(args.next_text) || 0, Number(args.next_tool) || 0);
815
- }
816
-
817
- function halt(j, reason) {
818
- if (!RUNNING.has(j.status)) return;
819
- try { j.child?.kill(); } catch { /* đã thoát */ }
820
- j.abort?.abort();
821
- j.status = 'stopped';
822
- if (reason) j.error = reason;
823
- j.endedAt = now();
824
- persist(j);
825
- wake(j);
826
- }
827
-
828
- function stop(args) {
829
- const j = jobs.get(String(args.job || ''));
830
- if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job}`);
831
- halt(j);
832
- return view(j);
833
- }
834
-
835
- const contractJob = (args) => {
836
- const j = jobs.get(String(args.job || ''));
837
- if (!j?.contractId) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No contract job ${args.job}`);
838
- return j;
839
- };
840
-
841
- /** Đọc một tệp của thư mục job theo khúc (BE đưa lên kho file). */
842
- function jobFile(args) {
843
- const j = contractJob(args);
844
- const name = String(args.name || '').replace(/\\/g, '/');
845
- if (!JOB_FILE_RE.test(name)) throw invalid('name must be CONTRACT.md, TEST_CHECK.md, REPORT.md, evidence.json, diff.patch or logs/<command>.log');
846
- const file = path.join(dirOf(j.id), name);
847
- let fd;
848
- try { fd = fs.openSync(file, 'r'); } catch { throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${name} is not in job ${j.id}`); }
849
- try {
850
- const size = fs.fstatSync(fd).size;
851
- const offset = Math.max(0, Math.min(size, Math.trunc(Number(args.offset) || 0)));
852
- const want = Math.max(1, Math.min(MAX_JOB_FILE_CHUNK, Math.trunc(Number(args.max_bytes) || 256 * 1024)));
853
- const buf = Buffer.alloc(Math.min(want, size - offset));
854
- const read = buf.length ? fs.readSync(fd, buf, 0, buf.length, offset) : 0;
855
- const keep = utf8Boundary(buf.subarray(0, read), offset + read >= size);
856
- return { job: j.id, name, size, offset, bytes: keep, next_offset: offset + keep, eof: offset + keep >= size, text: buf.subarray(0, keep).toString('utf8') };
857
- } finally { fs.closeSync(fd); }
858
- }
859
-
860
- /**
861
- * Gỡ worktree của job sau khi Aivin đã nhận kết quả (nhánh giao kết quả vẫn giữ). Worktree có liên kết bên trong → từ chối, để người dọn
862
- * tay (xoá cưỡng bức đi theo junction là xoá dữ liệu thật ở nơi khác).
863
- */
864
- async function cleanup(args) {
865
- const j = contractJob(args);
866
- if (RUNNING.has(j.status)) throw invalid(`${j.id} is still running`);
867
- if (!j.worktree || j.worktreeRemoved) return { job: j.id, removed: false, reason: 'no worktree to remove' };
868
- const wt = j.worktree;
869
- const known = (await listWorktrees(j.cwd, gitOpts)).some((t) => path.resolve(t).toLowerCase() === path.resolve(wt).toLowerCase());
870
- if (!known) throw invalid(`${wt} is not a worktree of ${j.cwdShown}`);
871
- if (hasLinks(wt)) throw invalid(`${wt} contains links (symlink / junction) — remove it by hand so nothing outside it is deleted`);
872
- await gitWrite(j.cwd, ['worktree', 'unlock', wt], gitOpts).catch(() => undefined);
873
- await gitWrite(j.cwd, ['worktree', 'remove', '--force', wt], gitOpts);
874
- j.worktreeRemoved = true;
875
- persist(j);
876
- return { job: j.id, removed: true, worktree: wt, ...(j.delivery?.branch ? { branch_kept: j.delivery.branch } : {}) };
877
- }
878
-
879
- /**
880
- * Cổng khớp wireframe (18/11/2026): chạy app của job trong worktree của nó, chụp các đường dẫn BE nêu, tắt app (agentPreview.mjs). Chỉ khi job
881
- * đã đo xong và worktree còn. Máy tổ chức: lệnh mở app chạy dưới tài khoản thành viên như lệnh verify.
882
- */
883
- async function preview(args, ctx) {
884
- const j = contractJob(args);
885
- if (RUNNING.has(j.status)) throw invalid(`${j.id} is still running`);
886
- if (!j.worktree || j.worktreeRemoved) throw invalid(`${j.id} has no worktree any more — preview runs before cleanup`);
887
- try {
888
- return { job: j.id, ...(await capturePreview(args, { cwd: j.worktree, spawnApp: childSpawn, signal: ctx?.signal })) };
889
- } catch (e) {
890
- throw invalid(e.message);
891
- }
892
- }
893
-
894
- function sessions(args, _ctx, env = {}) {
895
- const cwd = args.cwd ? resolveInRoots(env.roots || [], String(args.cwd)) : null;
896
- return { sessions: loadSessions().filter((s) => (!cwd || s.cwd === cwd) && (!args.agent || s.agent === args.agent)).slice(0, 20) };
897
- }
898
-
899
- return {
900
- run, status, stop, sessions, jobFile, cleanup, preview,
901
- profiles: () => ({ profiles: listAgentProfiles(installed(), { root: profilesRoot }) }),
902
- installed: () => installed().map((a) => ({ id: a.id, label: a.label, version: binaryOf(a).version })),
903
- /** 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. */
904
- hasRunning: () => [...jobs.values()].some((j) => RUNNING.has(j.status)),
905
- stopAll: (reason = 'The Aivin agent on this device stopped') => { for (const j of jobs.values()) halt(j, reason); },
906
- };
907
- }
908
-
909
- /** 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. */
910
- export function buildAgentTools(runner) {
911
- const agents = runner.installed();
912
- const list = agents.map((a) => `${a.id} (${a.label} ${a.version})`).join(', ');
913
- return [
914
- { name: 'agent.run', group: ToolGroup.PROC, handler: (a, c, e) => runner.run(a, c, e),
915
- 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.`,
916
- input_schema: schema({
917
- 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(' | ')}`),
918
- cwd: str('project folder (default the first allowed folder, or workspace.cwd of the contract)'), session: str('new | continue | <session id>'),
919
- mode: str('manual | plan | accept_edits (with contract: from permissions.mode)'), model: str('optional model alias of that agent'),
920
- max_budget_usd: num('stop the agent once it has spent this much (without contract)'), effort: str('low | medium | high | xhigh | max (without contract)'),
921
- 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)'),
922
- 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'),
923
- continue_job: str('fix round: an earlier contract job — continue its session in its worktree (send the contract again)'),
924
- account: str('run as this account profile of the agent (from agent.profiles) — its own sign-in, sessions and usage limits; default: the usual account of the agent'),
925
- wait_ms: num(`wait for the answer up to this long (default ${DEFAULT_WAIT_MS}, max ${MAX_WAIT_MS})`),
926
- }) },
927
- { name: 'agent.status', group: ToolGroup.PROC, read_only: true, handler: (a, c) => runner.status(a, c),
928
- 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.',
929
- 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']) },
930
- { name: 'agent.stop', group: ToolGroup.PROC, handler: (a) => runner.stop(a),
931
- description: 'Stop a running coding-agent task.',
932
- input_schema: schema({ job: str('job from agent.run') }, ['job']) },
933
- { name: 'agent.job_file', group: ToolGroup.PROC, read_only: true, internal: true, handler: (a) => runner.jobFile(a),
934
- description: 'BE-only: read a file of a contract job (REPORT.md, evidence.json, diff.patch, logs/<command>.log…) in chunks from offset.',
935
- input_schema: schema({ job: str('contract job'), name: str('file name'), offset: num('byte offset'), max_bytes: num('chunk size, max 1048576') }, ['job', 'name']) },
936
- { name: 'agent.cleanup', group: ToolGroup.PROC, internal: true, handler: (a) => runner.cleanup(a),
937
- description: "BE-only: remove a finished contract job's worktree (the delivery branch is kept).",
938
- input_schema: schema({ job: str('contract job') }, ['job']) },
939
- { name: 'agent.preview', group: ToolGroup.PROC, internal: true, handler: (a, c) => runner.preview(a, c),
940
- description: "BE-only: start the app of a finished contract job inside its worktree (argv), wait for url to answer, screenshot each shot path headless, stop the app. Returns PNGs (base64) to compare with the wireframe.",
941
- input_schema: schema({
942
- job: str('contract job'), argv: { type: 'array', items: { type: 'string' }, description: 'command that starts the app, as words' },
943
- url: str('base address on this computer, e.g. http://localhost:5173'), ready_timeout_ms: num('wait this long for the app to answer (max 600000)'),
944
- shots: { type: 'array', items: { type: 'object', properties: { id: str('screen id'), path: str('path starting with /'), device: str('desktop | tablet | mobile') } }, description: `at most ${PREVIEW_MAX_SHOTS} screens` },
945
- }, ['job', 'argv', 'url', 'shots']) },
946
- { name: 'agent.profiles', group: ToolGroup.PROC, read_only: true, handler: () => runner.profiles(),
947
- description: 'Account profiles of each installed coding agent on this computer (each has its own sign-in and usage limits). Pass one as account to agent.run to switch account without any UI. The person creates a profile once by signing in to it.',
948
- input_schema: schema({}) },
949
- { name: 'agent.sessions', group: ToolGroup.PROC, read_only: true, handler: (a, c, e) => runner.sessions(a, c, e),
950
- description: 'Recent coding-agent sessions started from Aivin on this computer (agent, folder, first words of the task, when, ok) — to continue one.',
951
- input_schema: schema({ cwd: str('only sessions of this folder'), agent: str('only this agent') }) },
952
- ];
953
- }
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 { accountEnv, withProcessCap } from './multiUser.mjs';
9
+ import { contractBrief, parseContract, parseReport, parseTestCheck, reportTemplate, sha256 } from './agentContract.mjs';
10
+
11
+ /** Thời gian tối đa cho lượt nhắc agent ghi lại REPORT.md sai khuôn (cùng phiên). */
12
+ const REPORT_REPAIR_MS = 5 * 60_000;
13
+ import { commitJobWork, gitRead, gitWrite, globToRegExp, listWorktrees, measureEvidence, resolveCommit, runVerifyCommand, worktreeState } from './agentEvidence.mjs';
14
+ import { PREVIEW_MAX_SHOTS, capturePreview } from './agentPreview.mjs';
15
+ import { LIGHTCODE_ADAPTER } from './lightcodeAgent.mjs';
16
+ import { buildCommandAuthEnv, redactAuthText } from './ephemeralAuth.mjs';
17
+
18
+ const MAX_SCOPE_RULES = 400;
19
+ /** Mẫu kiểu gitignore → mẫu luật quyền của Claude Code, neo ở mọi tầng (`package.json` → `**\/package.json`). */
20
+ const anyDepth = (p) => {
21
+ const q = String(p).replace(/\\/g, '/').replace(/^\.?\/+/, '');
22
+ return q.startsWith('**/') ? q : `**/${q}`;
23
+ };
24
+
25
+ /**
26
+ * Phạm vi của hợp đồng thành luật CẤM của agent (11/11 → 16/11/2026: trước đây chỉ phát hiện sau khi đo). `deny_paths`: cấm sửa / ghi theo
27
+ * đúng mẫu. `protected_paths`: không được sửa / xoá tệp ĐANG CÓ, thêm tệp mới thì được — mẫu có ký tự đại diện ở tên tệp (`**\/*.test.*`)
28
+ * nên chỉ cấm từng tệp đang có khớp mẫu; mẫu chỉ đích danh (`package.json`, `.github/**`) cấm thẳng. Bước đo vẫn kiểm lại.
29
+ */
30
+ export async function scopeDenyRules(contract, cwd, { gitOpts } = {}) {
31
+ const rules = [];
32
+ const add = (pattern) => { for (const t of ['Edit', 'Write']) rules.push(`${t}(${pattern})`); };
33
+ for (const p of contract.scope?.deny_paths || []) add(anyDepth(p));
34
+ // Ký tự đại diện ở TÊN TỆP (`*.test.*`) → chỉ tệp đang có; cả thư mục (`.github/**`) → cấm luôn tệp mới (CI chạy mọi tệp trong đó).
35
+ const wildcardName = (p) => { const last = String(p).replace(/\\/g, '/').split('/').filter(Boolean).pop() || ''; return last !== '**' && /[*?[]/.test(last); };
36
+ const direct = (contract.scope?.protected_paths || []).filter((p) => !wildcardName(p));
37
+ const globbed = (contract.scope?.protected_paths || []).filter(wildcardName);
38
+ for (const p of direct) add(anyDepth(p));
39
+ if (globbed.length) {
40
+ let tracked = [];
41
+ try { tracked = (await gitRead(cwd, ['ls-files', '-z'], gitOpts)).toString('utf8').split('\0').filter(Boolean); } catch { /* không phải kho */ }
42
+ const res = globbed.map((g) => globToRegExp(g));
43
+ for (const f of tracked) if (res.some((re) => re.test(f))) add(anyDepth(f));
44
+ }
45
+ return [...new Set(rules)].slice(0, MAX_SCOPE_RULES);
46
+ }
47
+
48
+ /** Tệp của thư mục job mà BE được đọc (agent.job_file) — để đưa bằng chứng, diff, log lên kho file của Aivin. */
49
+ const JOB_FILE_RE = /^(CONTRACT\.md|TEST_CHECK\.md|REPORT\.md|evidence\.json|diff\.patch|logs\/[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\.log)$/;
50
+ const MAX_JOB_FILE_CHUNK = 1024 * 1024;
51
+ const MAX_LINK_SCAN = 200_000;
52
+
53
+ /** Thư mục có liên kết (symlink / junction) bên trong không — xoá cưỡng bức đi theo liên kết là xoá cả dữ liệu thật ở nơi khác. */
54
+ function hasLinks(dir) {
55
+ const stack = [dir];
56
+ let seen = 0;
57
+ while (stack.length) {
58
+ const d = stack.pop();
59
+ let entries;
60
+ try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
61
+ for (const e of entries) {
62
+ if (++seen > MAX_LINK_SCAN) return true;
63
+ if (e.isSymbolicLink()) return true;
64
+ if (e.isDirectory()) stack.push(path.join(d, e.name));
65
+ }
66
+ }
67
+ return false;
68
+ }
69
+
70
+ /** Cắt `buf` ở biên ký tự UTF-8 (không tách đôi một ký tự nhiều byte); trả số byte giữ lại. */
71
+ function utf8Boundary(buf, eof) {
72
+ if (eof) return buf.length;
73
+ let end = buf.length;
74
+ for (let back = 0; back < 4 && end > 0 && (buf[end - 1] & 0xc0) === 0x80; back++) end--;
75
+ if (end > 0 && buf[end - 1] >= 0xc0) end--;
76
+ return end;
77
+ }
78
+
79
+ /**
80
+ * 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
81
+ * 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).
82
+ *
83
+ * 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 đó:
84
+ * 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:
85
+ * 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 đã
86
+ * 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ờ đó).
87
+ *
88
+ * 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) /
89
+ * `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ư
90
+ * 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.
91
+ *
92
+ * 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ã
93
+ * 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,
94
+ * 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ả
95
+ * `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ả
96
+ * lời được `agent.status` (job đang chạy lúc tắt → `interrupted`, kèm mã phiên để nói tiếp).
97
+ */
98
+
99
+ const SESSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'agent-sessions.json');
100
+ export const JOBS_DIR = path.join(REMOTE_CONFIG_DIR, 'jobs');
101
+ const MAX_SESSIONS = 50;
102
+ const MAX_JOBS = 4;
103
+ const DEFAULT_WAIT_MS = 90_000;
104
+ const MAX_WAIT_MS = 10 * 60_000;
105
+ const MAX_PROMPT_CHARS = 20_000;
106
+ const MAX_ANSWER_CHARS = 12_000;
107
+ const MAX_REPORT_CHARS = 64 * 1024;
108
+ const MAX_TEXTS = 400;
109
+ const MAX_DENIALS = 20;
110
+ const KEEP_DONE_MS = 30 * 60_000;
111
+ /** Hồ sơ job (thư mục job) giữ trên đĩa bao lâu. */
112
+ const KEEP_JOB_DIR_MS = 7 * 24 * 3_600_000;
113
+ /** Đã chạy đủ MAX_JOBS việc cùng lúc. */
114
+ const AGENT_BUSY = 'AGENT_BUSY';
115
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
116
+ const MODEL_RE = /^[a-z0-9][a-z0-9.\-[\]]{0,60}$/i;
117
+ const JOB_ID_RE = /^[a-z0-9]+-[0-9a-f]{8}$/;
118
+ const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
119
+ const RUNNING = new Set(['running', 'measuring']);
120
+
121
+ /** 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. */
122
+ export const AgentMode = Object.freeze({ PLAN: 'plan', MANUAL: 'manual', ACCEPT_EDITS: 'accept_edits' });
123
+
124
+ const str = (description) => ({ type: 'string', description });
125
+ const num = (description) => ({ type: 'number', description });
126
+ const bool = (description) => ({ type: 'boolean', description });
127
+ const schema = (properties, required = []) => ({ type: 'object', properties, required });
128
+ const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
129
+
130
+ /**
131
+ * Cổng AI tạm BE cấp (quota mặc định AIVIN) — `ai_gateway` (patch của BE) hoặc `aiGateway` (bước kế hoạch). CHỈ agent LightCode nhận; claude / codex bỏ qua.
132
+ * Nằm trong bộ nhớ của job (không argv, không env, không job.json); sai dạng / hết hạn do adapter xử lý.
133
+ */
134
+ export function gatewayOpt(args, adapter) {
135
+ const gw = args?.aiGateway ?? args?.ai_gateway;
136
+ return adapter?.id === 'lightcode' && gw ? { aiGateway: gw } : {};
137
+ }
138
+
139
+ /** `<dir>/<exe>` của mọi thư mục trong PATH. */
140
+ function onPath(exe, env) {
141
+ return String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean).map((dir) => path.join(dir, exe));
142
+ }
143
+
144
+ /** Đườ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`). */
145
+ export function claudeAbsPath(abs, platform = process.platform) {
146
+ if (platform === 'win32') {
147
+ const m = /^([a-z]):[\\/]?(.*)$/i.exec(abs);
148
+ if (m) return `//${m[1].toLowerCase()}/${m[2].replace(/\\/g, '/')}`;
149
+ }
150
+ return `/${abs.replace(/\\/g, '/')}`;
151
+ }
152
+
153
+ /**
154
+ * Claude Code (2.1.x): `-p --output-format stream-json --verbose`, `--permission-mode`, `--resume <id>`, `--model`. Kiểm thật 30/10/2026.
155
+ * 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`,
156
+ * `--settings`, `--setting-sources`, `--strict-mcp-config`, `--permission-prompts none`.
157
+ */
158
+ /**
159
+ * Hồ sơ tài khoản của agent lập trình (14/11/2026) — mỗi tài khoản một thư mục cấu hình riêng, truyền qua biến môi trường CHÍNH THỨC của agent
160
+ * (`profileEnv` của adapter: Claude Code `CLAUDE_CONFIG_DIR`; adapter Codex sau này `CODEX_HOME`). Chuyển tài khoản = chọn hồ sơ, không sao chép
161
+ * token, không đụng giao diện. Người dùng đăng nhập vào mỗi hồ sơ MỘT lần (máy không đăng nhập hộ). Thư mục: ~/.aivin/agent-profiles/<agent>/<tên>.
162
+ */
163
+ export const AGENT_PROFILES_DIR = path.join(REMOTE_CONFIG_DIR, 'agent-profiles');
164
+ const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/i;
165
+
166
+ /** Thư mục hồ sơ `name` của adapter — tên sai / adapter không hỗ trợ / chưa tạo → lỗi kèm cách tạo. */
167
+ export function agentProfileDir(adapter, name, { root = AGENT_PROFILES_DIR } = {}) {
168
+ const n = String(name || '').trim();
169
+ if (!adapter.profileEnv) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `${adapter.label} has no account profiles on this device`);
170
+ if (!PROFILE_NAME_RE.test(n)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'account: letters, digits, - or _ (max 40)');
171
+ const dir = path.join(root, adapter.id, n);
172
+ if (!fs.existsSync(dir)) {
173
+ throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No ${adapter.label} account profile "${n}" — the person creates it once: set ${adapter.profileEnv}=${dir}, run ${adapter.id} and sign in`);
174
+ }
175
+ return dir;
176
+ }
177
+
178
+ /** Biến chỉ tiến trình root được mang — không lọt sang tài khoản thành viên (agent đọc đăng nhập trong HOME của chính họ). */
179
+ const ROOT_ONLY_AGENT_ENV = ['CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN', 'OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'LCAGENT_LICENSE_FILE', 'AIVIN_LIGHTCODE_LICENSE_KEY', 'AIVIN_LIGHTCODE_MACHINE_ID'];
180
+
181
+ /**
182
+ * Máy tính tổ chức (17/11/2026): tiến trình con của job lập trình chạy dưới tài khoản Linux của thành viên — agent, mọi lệnh git (worktree,
183
+ * commit, đo diff) và lệnh kiểm chứng; HOME / USER của họ, có trần số tiến trình theo uid. Root không ghi gì vào kho của thành viên.
184
+ */
185
+ export function memberSpawner(account, spawnImpl = spawn) {
186
+ return (cmd, argv, opts = {}) => {
187
+ const [c, a] = withProcessCap(cmd, argv);
188
+ const { authExtra, ...spawnOpts } = opts;
189
+ const env = { ...accountEnv(account, agentEnv(spawnOpts.env || process.env)), DISABLE_AUTOUPDATER: '1', BROWSER: '/bin/true', NO_COLOR: '1' };
190
+ for (const k of ROOT_ONLY_AGENT_ENV) delete env[k];
191
+ // Token ngắn hạn từ AIVIN CredentialBroker (đã lọc allowlist) được gắn sau agentEnv để không bị gọt sạch, chỉ sống trong tiến trình con này.
192
+ if (authExtra && typeof authExtra === 'object') Object.assign(env, authExtra);
193
+ return spawnImpl(c, a, { ...spawnOpts, env, uid: account.uid, gid: account.gid });
194
+ };
195
+ }
196
+
197
+ /** Đổi chủ cả cây thư mục (thư mục job cho thành viên). Lỗi từng mục bỏ qua — chỉ chạy được khi daemon là root. */
198
+ function chownTree(dir, uid, gid) {
199
+ try { fs.chownSync(dir, uid, gid); } catch { return; }
200
+ for (const d of fs.readdirSync(dir, { withFileTypes: true })) {
201
+ const p = path.join(dir, d.name);
202
+ if (d.isDirectory()) chownTree(p, uid, gid);
203
+ else { try { fs.chownSync(p, uid, gid); } catch { /* bỏ qua */ } }
204
+ }
205
+ }
206
+
207
+ /** Thêm một mẫu vào `info/exclude` của kho (không đụng .gitignore của dự án) — thư mục worktree của job không làm bẩn `git status`. */
208
+ async function excludeFromRepo(cwd, pattern, gitOpts, owner = null) {
209
+ try {
210
+ const file = path.resolve(cwd, (await gitRead(cwd, ['rev-parse', '--git-path', 'info/exclude'], gitOpts)).toString().trim());
211
+ const existed = fs.existsSync(file);
212
+ const text = existed ? fs.readFileSync(file, 'utf8') : '';
213
+ if (!text.split(/\r?\n/).includes(pattern)) {
214
+ fs.mkdirSync(path.dirname(file), { recursive: true });
215
+ fs.appendFileSync(file, `${text && !text.endsWith('\n') ? '\n' : ''}${pattern}\n`);
216
+ // Máy tổ chức: tệp mới trong .git của thành viên phải thuộc về họ (daemon là root).
217
+ if (!existed && owner) { try { fs.chownSync(file, owner.uid, owner.gid); } catch { /* bỏ qua */ } }
218
+ }
219
+ } catch { /* không ghi được — worktree vẫn chạy, chỉ hiện trong git status */ }
220
+ }
221
+
222
+ /** Hồ sơ đã có của từng adapter (tên thư mục). */
223
+ export function listAgentProfiles(adapters, { root = AGENT_PROFILES_DIR } = {}) {
224
+ const out = {};
225
+ for (const a of adapters) {
226
+ if (!a.profileEnv) continue;
227
+ const dir = path.join(root, a.id);
228
+ out[a.id] = fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && PROFILE_NAME_RE.test(d.name)).map((d) => d.name) : [];
229
+ }
230
+ return out;
231
+ }
232
+
233
+ export const CLAUDE_ADAPTER = Object.freeze({
234
+ id: 'claude',
235
+ label: 'Claude Code',
236
+ profileEnv: 'CLAUDE_CONFIG_DIR',
237
+ candidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
238
+ const exe = platform === 'win32' ? 'claude.exe' : 'claude';
239
+ const out = [...onPath(exe, env), path.join(home, '.local', 'bin', exe), path.join(home, '.claude', 'local', exe)];
240
+ // Bản kèm extension VS Code (người dùng chỉ cài extension, không cài CLI).
241
+ const extRoot = path.join(home, '.vscode', 'extensions');
242
+ try {
243
+ for (const d of fs.readdirSync(extRoot)) if (d.startsWith('anthropic.claude-code-')) out.push(path.join(extRoot, d, 'resources', 'native-binary', exe));
244
+ } catch { /* không có VS Code */ }
245
+ return out;
246
+ },
247
+ /**
248
+ * `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`)
249
+ * đặt TRƯỚC một cờ thường để không nuốt tham số sau.
250
+ */
251
+ args({ mode, resume, model, budgetUsd, effort, allowedTools = [], addDirs = [], worktree, projectConfig = true, settings }, flags = null) {
252
+ const flag = { [AgentMode.PLAN]: 'plan', [AgentMode.MANUAL]: 'manual', [AgentMode.ACCEPT_EDITS]: 'acceptEdits' }[mode];
253
+ const has = (f) => !!flags?.has(f);
254
+ const argv = ['-p', '--output-format', 'stream-json', '--verbose'];
255
+ if (allowedTools.length) argv.push('--allowedTools', ...allowedTools);
256
+ if (addDirs.length) argv.push('--add-dir', ...addDirs);
257
+ argv.push('--permission-mode', flag);
258
+ // 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.
259
+ if (has('--permission-prompts')) argv.push('--permission-prompts', 'none');
260
+ if (!projectConfig) argv.push('--setting-sources', 'user', '--strict-mcp-config');
261
+ if (settings) argv.push('--settings', JSON.stringify(settings));
262
+ if (worktree) argv.push('--worktree', worktree);
263
+ if (budgetUsd) argv.push('--max-budget-usd', String(budgetUsd));
264
+ if (effort) argv.push('--effort', effort);
265
+ if (resume) argv.push('--resume', resume);
266
+ if (model) argv.push('--model', model);
267
+ return argv;
268
+ },
269
+ /** 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 ''. */
270
+ parse(job, msg) {
271
+ if (msg.session_id && !job.session_id) job.session_id = msg.session_id;
272
+ if (msg.type === 'system' && msg.subtype === 'init') {
273
+ job.model = msg.model;
274
+ if (typeof msg.cwd === 'string') job.session_cwd = msg.cwd;
275
+ return '';
276
+ }
277
+ if (msg.type === 'assistant') {
278
+ const parts = [];
279
+ for (const c of msg.message?.content || []) {
280
+ if (c.type === 'text' && c.text?.trim()) { job.texts.push(c.text); parts.push(c.text); }
281
+ if (c.type === 'tool_use') {
282
+ const target = c.input?.file_path || c.input?.path || c.input?.command || c.input?.pattern || c.input?.url || '';
283
+ const line = `🔧 ${c.name}${target ? ` ${String(target).slice(0, 160)}` : ''}`;
284
+ job.tools.push(line);
285
+ parts.push(line);
286
+ }
287
+ }
288
+ return parts.join('\n');
289
+ }
290
+ if (msg.type === 'result') {
291
+ job.result = {
292
+ ok: !msg.is_error && msg.subtype === 'success', answer: String(msg.result ?? '').slice(0, MAX_ANSWER_CHARS),
293
+ cost_usd: typeof msg.total_cost_usd === 'number' ? Math.round(msg.total_cost_usd * 10_000) / 10_000 : undefined,
294
+ turns: msg.num_turns, duration_ms: msg.duration_ms,
295
+ };
296
+ if (msg.subtype && msg.subtype !== 'success') job.result.stop_reason = msg.subtype;
297
+ // 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.
298
+ const denials = Array.isArray(msg.permission_denials) ? msg.permission_denials : [];
299
+ if (denials.length) {
300
+ job.result.permission_denials = denials.slice(0, MAX_DENIALS).map((d) => {
301
+ const target = d.tool_input?.command || d.tool_input?.file_path || d.tool_input?.path || d.tool_input?.url || '';
302
+ return { tool: String(d.tool_name || ''), ...(target ? { target: String(target).slice(0, 200) } : {}) };
303
+ });
304
+ }
305
+ }
306
+ return '';
307
+ },
308
+ });
309
+
310
+ /** Thư mục cài Codex đi kèm extension VS Code (openai.chatgpt-*), theo nền tảng. */
311
+ function codexExtensionBins(home, exe) {
312
+ const sub = process.platform === 'win32' ? 'windows-x86_64' : `${process.platform}-${os.arch()}`;
313
+ const root = path.join(home, '.vscode', 'extensions');
314
+ try {
315
+ return fs.readdirSync(root).filter((d) => d.startsWith('openai.chatgpt-')).sort().reverse().map((d) => path.join(root, d, 'bin', sub, exe));
316
+ } catch { return []; }
317
+ }
318
+
319
+ /**
320
+ * Codex CLI (17/11/2026) — `codex exec --json`, đề bài qua stdin. Đã đo trên bản 0.169 (Windows): `-s workspace-write` một mình bị chặn mọi
321
+ * lệnh ("blocked by policy"), `--approve-for-me` (sandbox workspace-write + duyệt tự động) chạy được; chỉ đọc = `-s read-only`. Không có cờ
322
+ * ngân sách (thời hạn hợp đồng vẫn do daemon cắt), không quản worktree theo tên → daemon tự dựng worktree (`selfWorktree: false`).
323
+ * `exec resume` không nhận cờ sandbox / duyệt → vòng sửa mở phiên MỚI trong worktree cũ (`resumable: false`; hợp đồng + lời nhắc đủ ngữ cảnh).
324
+ */
325
+ export const CODEX_ADAPTER = Object.freeze({
326
+ id: 'codex',
327
+ label: 'Codex',
328
+ profileEnv: 'CODEX_HOME',
329
+ selfWorktree: false,
330
+ resumable: false,
331
+ helpArgs: ['exec', '--help'],
332
+ candidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
333
+ const exe = platform === 'win32' ? 'codex.exe' : 'codex';
334
+ return [...onPath(exe, env), path.join(home, '.local', 'bin', exe), ...codexExtensionBins(home, exe)];
335
+ },
336
+ args({ mode, model, effort, addDirs = [] }) {
337
+ const argv = ['exec', '--json', '--ignore-user-config', '--ignore-rules'];
338
+ // Chế độ quyền chung → sandbox của Codex. "manual" (việc cần quyền bị từ chối) không có tương đương an toàn → chỉ đọc.
339
+ if (mode === AgentMode.ACCEPT_EDITS) argv.push('--approve-for-me');
340
+ else argv.push('-s', 'read-only');
341
+ for (const d of addDirs) argv.push('--add-dir', d);
342
+ if (model) argv.push('-m', model);
343
+ if (effort) argv.push('-c', `model_reasoning_effort="${effort === 'xhigh' || effort === 'max' ? 'high' : effort}"`);
344
+ argv.push('-');
345
+ return argv;
346
+ },
347
+ /** Một dòng JSONL của `codex exec --json` → cập nhật việc; trả đoạn chữ đáng đẩy lên Aivin. */
348
+ parse(job, msg) {
349
+ if (msg.type === 'thread.started' && typeof msg.thread_id === 'string' && !job.session_id) { job.session_id = msg.thread_id; return ''; }
350
+ const item = msg.item;
351
+ if (msg.type === 'item.completed' && item?.type === 'agent_message' && typeof item.text === 'string' && item.text.trim()) {
352
+ job.texts.push(item.text);
353
+ return item.text;
354
+ }
355
+ if (msg.type === 'item.started' && item && item.type !== 'agent_message' && item.type !== 'reasoning') {
356
+ const target = item.command || (Array.isArray(item.changes) ? item.changes.map((c) => c.path).join(', ') : '') || '';
357
+ const line = `🔧 ${item.type}${target ? ` ${String(target).slice(0, 160)}` : ''}`;
358
+ job.tools.push(line);
359
+ return line;
360
+ }
361
+ if (msg.type === 'turn.completed') {
362
+ job.result = {
363
+ ok: true, answer: String(job.texts[job.texts.length - 1] || '').slice(0, MAX_ANSWER_CHARS),
364
+ usage: { input_tokens: msg.usage?.input_tokens, output_tokens: msg.usage?.output_tokens },
365
+ };
366
+ }
367
+ if (msg.type === 'turn.failed' || msg.type === 'error') {
368
+ job.result = { ok: false, answer: String(msg.error?.message || msg.message || 'Codex error').slice(0, MAX_ANSWER_CHARS), stop_reason: 'error' };
369
+ }
370
+ return '';
371
+ },
372
+ });
373
+
374
+ /** LightCode (20/11/2026, lightcodeAgent.mjs): bên thực thi nhiều agent + tài khoản dự phòng — đứng cuối, BE chọn theo hồ sơ năng lực. */
375
+ export const DEFAULT_AGENT_ADAPTERS = Object.freeze([CLAUDE_ADAPTER, CODEX_ADAPTER, LIGHTCODE_ADAPTER]);
376
+
377
+ function versionOf(bin) {
378
+ try {
379
+ const out = execFileSync(bin, ['--version'], { encoding: 'utf8', timeout: 15_000, windowsHide: true });
380
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(out);
381
+ return m ? m.slice(1).map(Number) : null;
382
+ } catch { return null; }
383
+ }
384
+ const newer = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return false; };
385
+
386
+ /** 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. */
387
+ export function helpFlags(bin, helpArgs = ['--help']) {
388
+ return new Promise((resolve) => {
389
+ execFile(bin, helpArgs, { encoding: 'utf8', timeout: 20_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, out) => {
390
+ resolve(err ? null : new Set(String(out).match(/--[a-z][a-z-]+/gi) || []));
391
+ });
392
+ });
393
+ }
394
+
395
+ /** Bản mới nhất chạy được của một agent trên máy, hoặc null. */
396
+ export function findAgentBinary(adapter, opts = {}) {
397
+ // Agent không phải tệp chạy trên PATH (LightCode: ứng dụng desktop + cửa cục bộ) tự định vị.
398
+ if (typeof adapter.locate === 'function') return adapter.locate(opts);
399
+ let best = null;
400
+ for (const bin of [...new Set(adapter.candidates(opts))]) {
401
+ if (!fs.existsSync(bin)) continue;
402
+ const v = (opts.versionOf || versionOf)(bin);
403
+ if (v && (!best || newer(v, best.version))) best = { bin, version: v };
404
+ }
405
+ return best ? { bin: best.bin, version: best.version.join('.') } : null;
406
+ }
407
+
408
+ /** 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. */
409
+ export function agentArgs(adapter, { mode = AgentMode.MANUAL, resume, model, budgetUsd, effort, ...rest } = {}, flags = null) {
410
+ if (!Object.values(AgentMode).includes(mode)) throw invalid(`mode must be one of: ${Object.values(AgentMode).join(', ')}`);
411
+ if (resume && !UUID_RE.test(resume)) throw invalid('session must be "new", "continue" or a session id');
412
+ if (model && !MODEL_RE.test(model)) throw invalid('Bad model name');
413
+ if (budgetUsd !== undefined && !(Number(budgetUsd) > 0 && Number(budgetUsd) <= 200)) throw invalid('max_budget_usd must be above 0 and at most 200');
414
+ if (effort !== undefined && !EFFORTS.includes(effort)) throw invalid(`effort must be one of: ${EFFORTS.join(', ')}`);
415
+ const argv = adapter.args({ mode, resume, model, budgetUsd: budgetUsd === undefined ? undefined : Number(budgetUsd), effort, ...rest }, flags);
416
+ // 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).
417
+ const missing = flags ? argv.filter((a) => a.startsWith('--') && !flags.has(a)) : [];
418
+ if (missing.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${adapter.label} on this computer is too old for ${missing.join(', ')} — update it`);
419
+ return argv;
420
+ }
421
+
422
+ function loadSessions() {
423
+ try { const v = JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf8')); return Array.isArray(v) ? v : []; } catch { return []; }
424
+ }
425
+ function saveSessions(list) {
426
+ 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 */ }
427
+ }
428
+
429
+ /** Đề 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. */
430
+ function contractPrompt({ jobId, jobDir, contract, hasTestCheck, note }) {
431
+ const report = path.join(jobDir, 'REPORT.md');
432
+ return [
433
+ `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.`,
434
+ 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.` : '',
435
+ 'Rules:',
436
+ '- 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).',
437
+ '- Stay inside the current folder for code changes. Do not touch paths the contract denies or protects (you may add new files).',
438
+ '- 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.',
439
+ '- Do not skip, disable or delete existing tests to make things pass.',
440
+ '- If you propose a new check under "Ca kiểm mới" with id NEW-n and method auto, write its test too and put NEW-n in the test name — the device measures it like the others.',
441
+ contract.setup?.length ? `- Before running tests, run the setup commands of the contract (setup) in the current folder: ${contract.setup.map((s) => s.argv.join(' ')).join(' ; ')}.` : '',
442
+ `When you finish (or stop), write ${report} exactly in this format — frontmatter holds short values only, sentences go in the sections; keep EVERY section heading even when it has nothing (an empty "# Phần chưa làm" or "# Ca kiểm mới" is fine), and delete only the example check under "Ca kiểm mới" if you propose none:`,
443
+ '',
444
+ reportTemplate({ jobId, contractId: contract.contract_id }),
445
+ note ? `\nNote from Aivin: ${note}` : '',
446
+ ].filter((l) => l !== '').join('\n');
447
+ }
448
+
449
+ export function createAgentRunner({
450
+ adapters = DEFAULT_AGENT_ADAPTERS, find = findAgentBinary, spawnImpl = spawn, now = Date.now, jobsDir = JOBS_DIR, measure = measureEvidence, probeFlags = helpFlags,
451
+ profilesRoot = AGENT_PROFILES_DIR,
452
+ /** Máy tính tổ chức: tài khoản Linux của thành viên ({ name, uid, gid, home }) — mọi tiến trình con chạy dưới tài khoản này. */
453
+ runAs = null,
454
+ } = {}) {
455
+ const childSpawn = runAs ? memberSpawner(runAs, spawnImpl) : spawnImpl;
456
+ /** Lệnh git của job: dưới tài khoản thành viên khi có (tệp trong .git của họ không thuộc root). */
457
+ const gitOpts = runAs ? { spawnImpl: childSpawn } : undefined;
458
+ const found = new Map();
459
+ const flagCache = new Map();
460
+ const jobs = new Map();
461
+ const binaryOf = (adapter) => {
462
+ // Agent tự định vị (LightCode) có thể được cài / bật khi daemon đang chạy → chưa thấy thì lần sau tìm lại.
463
+ if (!found.has(adapter.id) || (adapter.locate && !found.get(adapter.id))) found.set(adapter.id, find(adapter));
464
+ return found.get(adapter.id);
465
+ };
466
+ /** Adapter tự dựng "tiến trình" (LightCode nối qua cửa cục bộ) dùng spawn riêng; còn lại qua childSpawn (máy tổ chức: dưới tài khoản thành viên). */
467
+ const spawnOf = (adapter) => (adapter?.spawn && (!runAs || adapter.memberAware) ? adapter.spawn : childSpawn);
468
+ /** Adapter tự chạy CLI dưới tài khoản thành viên (LightCode `run_as`) → chuyển tài khoản của runner này cho nó; adapter khác đã bọc bằng memberSpawner. */
469
+ const memberOpt = (adapter) => (runAs && adapter?.memberAware ? { runAs: { uid: runAs.uid, gid: runAs.gid, home: runAs.home } } : {});
470
+ const flagsOf = async (adapter) => {
471
+ const b = binaryOf(adapter);
472
+ if (b?.flags) return new Set(b.flags);
473
+ if (!flagCache.has(adapter.id)) flagCache.set(adapter.id, b ? Promise.resolve(probeFlags(b.bin, adapter.helpArgs)).catch(() => null) : null);
474
+ return flagCache.get(adapter.id);
475
+ };
476
+ /** Agent đã cài trên máy (theo thứ tự ưu tiên của danh sách adapter). */
477
+ const installed = () => adapters.filter((a) => !(runAs && a.multiUser === false) && binaryOf(a));
478
+ const adapterFor = (id) => {
479
+ const list = installed();
480
+ 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(', ')})`);
481
+ if (!id) return list[0];
482
+ const a = list.find((x) => x.id === id);
483
+ if (!a) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${id} is not installed here — available: ${list.map((x) => x.id).join(', ')}`);
484
+ return a;
485
+ };
486
+
487
+ // --- 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).
488
+ const dirOf = (id) => path.join(jobsDir, id);
489
+ const RECORD_KEYS = ['id', 'agent', 'status', 'cwd', 'cwdShown', 'mode', 'model', 'session_id', 'last_seq', 'worktree', 'baseCommit', 'isolate', 'fixedWorktree', 'mainStateBefore', 'wallMs', 'contractId', 'contractSha', 'continuedFrom', 'delivery', 'worktreeRemoved', 'reportRepaired', 'progress', 'startedAt', 'endedAt', 'result', 'error'];
490
+ function persist(j) {
491
+ try {
492
+ fs.mkdirSync(dirOf(j.id), { recursive: true });
493
+ 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));
494
+ } catch { /* hồ sơ chỉ để trả lời sau khi khởi động lại */ }
495
+ }
496
+
497
+ const prune = () => {
498
+ for (const [id, j] of jobs) if (!RUNNING.has(j.status) && now() - j.endedAt > KEEP_DONE_MS && !j.contractId) jobs.delete(id);
499
+ };
500
+ const readJobFile = (j, name, max) => {
501
+ 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; }
502
+ };
503
+ const view = (j, sinceText = 0, sinceTool = 0) => {
504
+ const redact = (v) => (j._authSecrets?.length && typeof v === 'string' ? redactAuthText(v, j._authSecrets) : v);
505
+ const rawText = j.texts.slice(sinceText).join('\n\n').slice(-MAX_ANSWER_CHARS) || undefined;
506
+ const redactedResult = j.result && typeof j.result === 'object' && j._authSecrets?.length
507
+ ? { ...j.result, ...(typeof j.result.answer === 'string' ? { answer: redact(j.result.answer) } : {}) }
508
+ : j.result;
509
+ const out = {
510
+ job: j.id, agent: j.agent, status: j.status, session_id: j.session_id, cwd: j.cwdShown, mode: j.mode, model: j.model,
511
+ new_text: redact(rawText),
512
+ tools_used: j.tools.slice(sinceTool).slice(-40),
513
+ ...(redactedResult ? { result: redactedResult } : {}),
514
+ ...(j.progress ? { progress: j.progress } : {}),
515
+ ...(j.questions?.length ? { questions: j.questions } : {}),
516
+ ...(j.error ? { error: redact(j.error) } : {}),
517
+ next_text: j.texts.length, next_tool: j.tools.length,
518
+ };
519
+ if (j.contractId) {
520
+ Object.assign(out, {
521
+ contract_id: j.contractId, contract_sha256: j.contractSha, job_dir: dirOf(j.id), worktree: j.worktree || undefined,
522
+ ...(j.delivery ? { delivery: j.delivery } : {}), ...(j.worktreeRemoved ? { worktree_removed: true } : {}), ...(j.reportRepaired ? { report_repaired: true } : {}),
523
+ });
524
+ if (!RUNNING.has(j.status)) {
525
+ const evidence = readJobFile(j, 'evidence.json', 4 * 1024 * 1024);
526
+ try { if (evidence) out.evidence = JSON.parse(evidence); } catch { /* hỏng → không gửi */ }
527
+ out.report_md = readJobFile(j, 'REPORT.md', MAX_REPORT_CHARS);
528
+ }
529
+ }
530
+ return out;
531
+ };
532
+
533
+ function remember(j) {
534
+ if (!j.session_id) return;
535
+ const list = loadSessions().filter((s) => !(s.agent === j.agent && s.session_id === j.session_id));
536
+ 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, ...(j.account ? { account: j.account } : {}) });
537
+ saveSessions(list);
538
+ }
539
+
540
+ function waitDone(j, ms, signal) {
541
+ if (!RUNNING.has(j.status)) return Promise.resolve();
542
+ return new Promise((resolve) => {
543
+ const done = () => { clearTimeout(t); signal?.removeEventListener('abort', done); j.waiters.delete(done); resolve(); };
544
+ const t = setTimeout(done, ms);
545
+ signal?.addEventListener('abort', done, { once: true });
546
+ j.waiters.add(done);
547
+ });
548
+ }
549
+ const wake = (j) => { for (const w of [...j.waiters]) w(); };
550
+
551
+ /**
552
+ * 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ố
553
+ * cho adapter. Mọi lỗi ở đây xảy ra TRƯỚC khi agent chạy (không có gì thay đổi).
554
+ */
555
+ async function prepareContract(args, env, jobId, prev, adapter) {
556
+ const text = String(args.contract);
557
+ if (!args.contract_sha256) throw invalid('contract_sha256 is required with contract (the sha256 of CONTRACT.md Aivin issued)');
558
+ const parsed = parseContract(text, { expectedSha: String(args.contract_sha256) });
559
+ if (!parsed.ok) throw invalid(`CONTRACT.md is not valid: ${parsed.errors.slice(0, 12).join('; ')}`);
560
+ const { contract } = parsed;
561
+ let testCheckText = null;
562
+ if (contract.test_check) {
563
+ if (typeof args.test_check !== 'string' || !args.test_check.trim()) throw invalid('the contract names test_check — send TEST_CHECK.md as test_check');
564
+ testCheckText = args.test_check;
565
+ 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');
566
+ const tc = parseTestCheck(testCheckText);
567
+ if (!tc.ok) throw invalid(`TEST_CHECK.md is not valid: ${tc.errors.slice(0, 12).join('; ')}`);
568
+ const missingFlows = contract.test_check.flows.filter((f) => !tc.flows.some((x) => x.id === f));
569
+ if (missingFlows.length) throw invalid(`TEST_CHECK.md has no flow ${missingFlows.join(', ')}`);
570
+ }
571
+ // 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.
572
+ const cwd = prev ? prev.cwd : resolveInRoots(env.roots || [], String(args.cwd || contract.workspace.cwd || (env.roots || [])[0] || '.'));
573
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd || contract.workspace.cwd}`);
574
+ if (prev?.worktree && !fs.existsSync(prev.worktree)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `The worktree of ${prev.id} is gone: ${prev.worktree}`);
575
+ const isolate = prev ? !!prev.worktree : contract.workspace.isolation === 'worktree';
576
+ const baseCommit = prev ? prev.baseCommit : await resolveCommit(cwd, contract.workspace.base_ref, gitOpts);
577
+ if (isolate && !baseCommit) throw invalid(`worktree isolation needs a git repository with ${contract.workspace.base_ref} in ${args.cwd || cwd}`);
578
+ // Daemon tự dựng worktree (17/11/2026) khi agent không tự quản worktree theo tên (Codex) hoặc hợp đồng đi từ commit khác HEAD (việc nối
579
+ // tiếp việc trước) — agent tự dựng thì luôn từ HEAD. Nhánh `aivin/<job>`, thư mục `<repo>/.aivin-worktrees/<job>` (loại khỏi git status).
580
+ let ownWorktree = null;
581
+ // Máy tổ chức: daemon luôn tự dựng worktree (dưới tài khoản thành viên) — không để agent dựng bằng đường dẫn root không biết trước.
582
+ if (!prev && isolate && (runAs || adapter.selfWorktree === false || (baseCommit !== (await resolveCommit(cwd, 'HEAD', gitOpts))))) {
583
+ ownWorktree = path.join(cwd, '.aivin-worktrees', jobId);
584
+ await excludeFromRepo(cwd, '/.aivin-worktrees/', gitOpts, runAs);
585
+ await gitWrite(cwd, ['worktree', 'add', '-q', '-b', `aivin/${jobId}`, ownWorktree, baseCommit], gitOpts);
586
+ }
587
+
588
+ const jobDir = dirOf(jobId);
589
+ fs.mkdirSync(path.join(jobDir, 'logs'), { recursive: true });
590
+ 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 */ } };
591
+ writeLocked('CONTRACT.md', text);
592
+ if (testCheckText !== null) writeLocked('TEST_CHECK.md', testCheckText);
593
+ // Thư mục job thuộc về thành viên: agent của họ đọc hợp đồng + ghi REPORT.md (sửa CONTRACT.md thì mã băm bắt).
594
+ if (runAs) chownTree(jobDir, runAs.uid, runAs.gid);
595
+ // 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.
596
+ const deny = [
597
+ ...['CONTRACT.md', 'TEST_CHECK.md', 'evidence.json', 'job.json', 'logs/**'].flatMap((n) => ['Edit', 'Write'].map((t) => `${t}(${claudeAbsPath(path.join(jobDir, n))})`)),
598
+ // Phạm vi chặn TRƯỚC (không chỉ phát hiện sau): `npm test` được phép + sửa được package.json = chạy được mọi lệnh.
599
+ ...(await scopeDenyRules(contract, cwd, { gitOpts })),
600
+ ];
601
+ return {
602
+ job: {
603
+ contract, contractId: contract.contract_id, contractSha: parsed.sha256, hasTestCheck: testCheckText !== null, testCheckText,
604
+ baseCommit, mainStateBefore: isolate ? await worktreeState(cwd, gitOpts) : null, isolate,
605
+ ...(prev ? { worktree: prev.worktree, fixedWorktree: !!prev.worktree, continuedFrom: prev.id } : {}),
606
+ ...(ownWorktree ? { worktree: ownWorktree, fixedWorktree: true } : {}),
607
+ },
608
+ cwd,
609
+ spawnCwd: prev?.worktree || ownWorktree || cwd,
610
+ agentOpts: {
611
+ mode: contract.permissions.mode, budgetUsd: contract.limits.max_budget_usd, effort: contract.limits.effort,
612
+ allowedTools: contract.permissions.allowed_tools, addDirs: [jobDir], worktree: isolate && !prev && !ownWorktree ? jobId : undefined, projectConfig: false,
613
+ settings: { permissions: { deny } },
614
+ // LightCode (20/11/2026): agent hỏi lại giữa chừng → dừng + chuyển câu hỏi cho Aivin (mặc định bật cho hợp đồng); `inner_agent` = agent trong LightCode.
615
+ clarify: args.clarify !== false, provider: args.inner_agent ? String(args.inner_agent) : undefined,
616
+ clientJobId: jobId,
617
+ ...(args.goal_id ? { goalId: String(args.goal_id) } : {}),
618
+ ...(Array.isArray(args.depends_on) && args.depends_on.length ? { dependsOn: args.depends_on } : {}),
619
+ ...(Number.isInteger(Number(args.max_fix_rounds)) && Number(args.max_fix_rounds) > 0 ? { maxFixRounds: Number(args.max_fix_rounds) } : {}),
620
+ ...(Array.isArray(args.deliverables) && args.deliverables.length ? { deliverables: args.deliverables } : {}),
621
+ ...gatewayOpt(args, adapter),
622
+ // Khoán việc: tiêu chí nghiệm thu (khóa) đi theo để LightCode tự đối chiếu và báo `verdict`.
623
+ ...contractBrief(parsed.body, contract),
624
+ },
625
+ wallMs: contract.limits.max_wall_ms,
626
+ };
627
+ }
628
+
629
+ /** 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. */
630
+ async function findJobWorktree(j) {
631
+ const trees = await listWorktrees(j.cwd, gitOpts);
632
+ const same = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase();
633
+ if (j.session_cwd && !same(j.session_cwd, j.cwd) && trees.some((t) => same(t, j.session_cwd))) return path.resolve(j.session_cwd);
634
+ return trees.find((t) => !same(t, j.cwd) && path.basename(t) === j.id) || null;
635
+ }
636
+
637
+ /** Agent xong → daemon đo. Lỗi đo không làm mất kết quả của agent. */
638
+ /**
639
+ * REPORT.md sai khuôn (hoặc chưa ghi) → nhắc agent ghi lại MỘT lần trong cùng phiên, trước khi đo (thiết kế: "sai thì yêu cầu ghi lại trong
640
+ * cùng phiên, vẫn sai thì coi là chưa giao đủ"). Rẻ hơn cả một vòng sửa (đo lại + agent đọc lại hợp đồng) chỉ vì thiếu một tiêu đề mục.
641
+ */
642
+ async function repairReport(j) {
643
+ if (!j.respawn || j.abort.signal.aborted) return;
644
+ // LightCode (20/11/2026): lượt dừng vì câu hỏi / vượt phạm vi / hết ngân sách… — không còn báo cáo để sửa, Aivin quyết bước kế.
645
+ if (['needs_clarification', 'scope_violation', 'budget_exceeded', 'orphaned', 'stopped'].includes(j.result?.stop_reason)) return;
646
+ const fresh = j.respawn.adapter.resumable === false;
647
+ if (!fresh && !j.session_id) return;
648
+ const file = path.join(dirOf(j.id), 'REPORT.md');
649
+ let text = null;
650
+ try { text = fs.readFileSync(file, 'utf8'); } catch { /* chưa ghi */ }
651
+ const parsed = text === null ? { ok: false, errors: ['REPORT.md was not written'] } : parseReport(text, { contractId: j.contractId });
652
+ if (parsed.ok) return;
653
+ const { adapter, opts, flags, env, bin } = j.respawn;
654
+ let argv;
655
+ // Nhắc viết lại REPORT.md chỉ sửa tệp báo cáo: không kèm lại acceptance/constraints hay bật clarify thừa cho LightCode.
656
+ try { argv = agentArgs(adapter, { ...opts, worktree: undefined, resume: fresh ? undefined : j.session_id, acceptance: undefined, constraints: undefined, clarify: false }, flags); } catch { return; }
657
+ // Agent không nói tiếp phiên được (Codex): phiên mới không thấy khuôn lúc đầu → gửi kèm khuôn mẫu.
658
+ const format = fresh ? `\n\nThe agreed format:\n${reportTemplate({ jobId: j.id, contractId: j.contractId })}` : '';
659
+ const prompt = `${file} is not in the agreed format: ${parsed.errors.slice(0, 8).join('; ')}. Rewrite only REPORT.md, exactly in the ${fresh ? 'format below' : 'format given at the start'} (keep every section heading, even when empty). Do not change any other file.${format}`;
660
+ await new Promise((resolve) => {
661
+ let child;
662
+ try { child = spawnOf(adapter)(bin, argv, { cwd: j.worktree || j.respawn.cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }); } catch { resolve(); return; }
663
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* đã thoát */ } }, REPORT_REPAIR_MS);
664
+ const done = () => { clearTimeout(timer); resolve(); };
665
+ child.stdout?.on?.('data', () => undefined);
666
+ child.stderr?.on?.('data', () => undefined);
667
+ child.stdin?.on?.('error', () => undefined);
668
+ child.on('close', done);
669
+ child.on('error', done);
670
+ child.stdin.end(prompt);
671
+ });
672
+ j.reportRepaired = true;
673
+ }
674
+
675
+ async function finishContractJob(j) {
676
+ if (j.isolate && !j.fixedWorktree) j.worktree = await findJobWorktree(j).catch(() => null);
677
+ // Agent dừng để hỏi người dùng (LightCode v2): giữ nguyên worktree + session để nói tiếp sau khi có câu trả lời — không sửa báo cáo, không commit dở, không chạy verify vô ích.
678
+ if (j.result?.stop_reason === 'needs_clarification') {
679
+ persist(j);
680
+ return;
681
+ }
682
+ // Sau khi biết worktree: phiên của agent nằm ở đó, nói tiếp phải đúng thư mục ấy.
683
+ await repairReport(j).catch(() => undefined);
684
+ // Đầu ra `git_branch`: commit thay đổi của worktree lên nhánh của job TRƯỚC khi đo — bằng chứng gắn đúng một commit.
685
+ if (j.worktree && j.contract?.outputs?.some((o) => o.kind === 'git_branch')) {
686
+ try {
687
+ j.delivery = await commitJobWork(j.worktree, `aivin: ${j.contractId} v${j.contract.version} (job ${j.id})`, { jobId: j.id, ...(gitOpts || {}) });
688
+ } catch (e) { j.delivery = { error: e.message.slice(0, 300) }; }
689
+ }
690
+ persist(j);
691
+ try {
692
+ const evidence = await measure({
693
+ job: { id: j.id, contractSha: j.contractSha, worktree: j.worktree, cwd: j.cwd, baseCommit: j.baseCommit, mainStateBefore: j.mainStateBefore, delivery: j.delivery },
694
+ contract: j.contract, testCheck: j.hasTestCheck ? parseTestCheck(j.testCheckText) : null, jobDir: dirOf(j.id), signal: j.abort.signal,
695
+ ...(runAs ? { gitOpts, runCommand: (cmd, o) => runVerifyCommand(cmd, { ...o, spawnImpl: childSpawn }) } : {}),
696
+ });
697
+ if (j.isolate && !j.worktree) {
698
+ evidence.worktree_missing = true;
699
+ try { fs.writeFileSync(path.join(dirOf(j.id), 'evidence.json'), JSON.stringify(evidence, null, 1)); } catch { /* đã trả qua status */ }
700
+ }
701
+ if (evidence.contract_tampered) j.error = 'contract_tampered: CONTRACT.md changed during the job';
702
+ } catch (e) {
703
+ j.error = `Measuring failed: ${e.message}`;
704
+ }
705
+ }
706
+
707
+ /** Gắn luồng sự kiện + giới hạn thời gian + kết thúc đo hợp đồng cho tiến trình của một job (mới chạy hoặc vừa nối lại sau restart). */
708
+ function attachChild(j, adapter, child, { wallMs = 0, onOutput } = {}) {
709
+ j.child = child;
710
+ const wall = wallMs ? setTimeout(() => {
711
+ if (j.status !== 'running') return;
712
+ j.error = `Stopped at the contract time limit (${Math.round(wallMs / 60_000)} min)`;
713
+ try { j.child?.kill(); } catch { /* đã thoát */ }
714
+ }, wallMs) : null;
715
+ wall?.unref?.();
716
+ let buf = '';
717
+ let stderr = '';
718
+ let lastPersistedAt = now();
719
+ child.stdout.on('data', (d) => {
720
+ buf += d.toString();
721
+ let nl;
722
+ while ((nl = buf.indexOf('\n')) >= 0) {
723
+ const line = buf.slice(0, nl).trim();
724
+ buf = buf.slice(nl + 1);
725
+ if (!line) continue;
726
+ let msg;
727
+ try { msg = JSON.parse(line); } catch { continue; }
728
+ if (!msg || typeof msg !== 'object') continue;
729
+ const hadSession = !!j.session_id;
730
+ const prevSeq = j.last_seq;
731
+ const shown = adapter.parse(j, msg);
732
+ if ((!hadSession && j.session_id) || (j.last_seq !== prevSeq && now() - lastPersistedAt >= 2000)) {
733
+ lastPersistedAt = now();
734
+ persist(j);
735
+ }
736
+ if (j.texts.length > MAX_TEXTS) j.texts.splice(0, j.texts.length - MAX_TEXTS);
737
+ const safeShown = shown && j._authSecrets?.length ? redactAuthText(shown, j._authSecrets) : shown;
738
+ if (safeShown && typeof onOutput === 'function') { try { onOutput(`${safeShown}\n`); } catch { /* chỉ là tiến trình */ } }
739
+ }
740
+ });
741
+ child.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-2000); });
742
+ child.stdin?.on?.('error', () => undefined);
743
+ const finish = async (code) => {
744
+ if (j.status !== 'running') return;
745
+ clearTimeout(wall);
746
+ const agentOk = !!j.result?.ok;
747
+ if (!j.result && !j.error) {
748
+ const rawErr = (stderr.trim().split(/\r?\n/).slice(-3).join(' ') || `${adapter.id} exited with code ${code}`).slice(0, 500);
749
+ j.error = j._authSecrets?.length ? redactAuthText(rawErr, j._authSecrets) : rawErr;
750
+ }
751
+ if (j.result && typeof j.result.answer === 'string' && j._authSecrets?.length) {
752
+ j.result = { ...j.result, answer: redactAuthText(j.result.answer, j._authSecrets) };
753
+ }
754
+ if (j.contractId) {
755
+ j.status = 'measuring';
756
+ persist(j);
757
+ await finishContractJob(j);
758
+ if (j.status !== 'measuring') return; // bị dừng giữa lúc đo
759
+ }
760
+ j.status = agentOk && !j.error?.startsWith('contract_tampered') ? 'done' : 'failed';
761
+ j.endedAt = now();
762
+ remember(j);
763
+ persist(j);
764
+ wake(j);
765
+ };
766
+ child.on('error', (e) => { j.error = e.message; void finish(-1); });
767
+ child.on('close', (code) => { void finish(code); });
768
+ }
769
+
770
+ /** Lần đầu dựng runner: nạp job cũ còn hồ sơ; job tách khỏi kết nối (LightCode v2) tự nối lại, còn lại → `interrupted`. Dọn hồ sơ quá hạn. */
771
+ function restore() {
772
+ let names;
773
+ try { names = fs.readdirSync(jobsDir); } catch { return; }
774
+ for (const name of names) {
775
+ if (!JOB_ID_RE.test(name)) continue;
776
+ let rec;
777
+ try { rec = JSON.parse(fs.readFileSync(path.join(dirOf(name), 'job.json'), 'utf8')); } catch { continue; }
778
+ if (rec.id !== name) continue;
779
+ if (now() - (rec.endedAt || rec.startedAt || 0) > KEEP_JOB_DIR_MS) {
780
+ try { fs.rmSync(dirOf(name), { recursive: true, force: true }); } catch { /* lần sau */ }
781
+ continue;
782
+ }
783
+ const j = { ...rec, prompt: rec.prompt || '', texts: [], tools: [], waiters: new Set(), child: null, restored: true };
784
+ if (RUNNING.has(j.status)) {
785
+ const adapter = adapters.find((a) => a.id === j.agent);
786
+ const reattached = j.status === 'running' && !runAs && adapter && typeof adapter.reattach === 'function' && j.session_id
787
+ ? adapter.reattach(j) : null;
788
+ if (reattached) {
789
+ j.abort = new AbortController();
790
+ if (j.contractId) {
791
+ try {
792
+ const cParsed = parseContract(fs.readFileSync(path.join(dirOf(j.id), 'CONTRACT.md'), 'utf8'));
793
+ if (cParsed.ok) j.contract = cParsed.contract;
794
+ } catch { /* thiếu CONTRACT.md */ }
795
+ try {
796
+ const tc = fs.readFileSync(path.join(dirOf(j.id), 'TEST_CHECK.md'), 'utf8');
797
+ if (tc) { j.hasTestCheck = true; j.testCheckText = tc; }
798
+ } catch { /* không có TEST_CHECK.md */ }
799
+ }
800
+ const remWall = j.wallMs ? Math.max(5_000, j.wallMs - Math.max(0, now() - (j.startedAt || now()))) : 0;
801
+ attachChild(j, adapter, reattached, { wallMs: remWall });
802
+ } else {
803
+ j.status = 'interrupted';
804
+ j.error = 'The Aivin agent on this device restarted while this job was running — continue it with session set to its session_id';
805
+ j.endedAt = now();
806
+ persist(j);
807
+ }
808
+ }
809
+ jobs.set(j.id, j);
810
+ }
811
+ }
812
+
813
+ async function run(args, ctx = {}, env = {}) {
814
+ prune();
815
+ const withContract = args.contract !== undefined && args.contract !== null && args.contract !== '';
816
+ const prompt = String(args.prompt || '').trim();
817
+ if (!prompt && !withContract) throw invalid('Give prompt (the task for the coding agent) or contract (CONTRACT.md)');
818
+ if (prompt.length > MAX_PROMPT_CHARS) throw invalid(`prompt is longer than ${MAX_PROMPT_CHARS} characters`);
819
+ 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`);
820
+ const adapter = adapterFor(args.agent ? String(args.agent) : undefined);
821
+ const account = args.account ? String(args.account).trim() : '';
822
+ if (runAs && account) throw invalid('account profiles are not used on an organisation computer — each member signs in to the agent with their own account');
823
+ const accountDir = account ? agentProfileDir(adapter, account, { root: profilesRoot }) : null;
824
+ const jobId = `${adapter.id}-${randomUUID().slice(0, 8)}`;
825
+
826
+ let cwd;
827
+ let spawnCwd;
828
+ let extra = {};
829
+ let agentOpts;
830
+ let wallMs = 0;
831
+ let prev = null;
832
+ if (args.continue_job) {
833
+ prev = jobs.get(String(args.continue_job));
834
+ if (!prev?.contractId || !prev.session_id) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No contract job ${args.continue_job} with a session to continue`);
835
+ if (RUNNING.has(prev.status)) throw invalid(`${prev.id} is still running`);
836
+ if (!withContract) throw invalid('continue_job needs the contract (the same or a new version)');
837
+ }
838
+ if (withContract) {
839
+ const prep = await prepareContract(args, env, jobId, prev, adapter);
840
+ ({ cwd, spawnCwd, agentOpts, wallMs } = prep);
841
+ extra = prep.job;
842
+ } else {
843
+ cwd = resolveInRoots(env.roots || [], String(args.cwd || (env.roots || [])[0] || '.'));
844
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd}`);
845
+ agentOpts = {
846
+ mode: String(args.mode || AgentMode.MANUAL), budgetUsd: args.max_budget_usd ?? undefined, effort: args.effort ? String(args.effort) : undefined,
847
+ projectConfig: args.project_config !== false,
848
+ clarify: args.clarify === true, provider: args.inner_agent ? String(args.inner_agent) : undefined,
849
+ clientJobId: jobId,
850
+ ...(args.goal_id ? { goalId: String(args.goal_id) } : {}),
851
+ ...(Array.isArray(args.depends_on) && args.depends_on.length ? { dependsOn: args.depends_on } : {}),
852
+ ...(Number.isInteger(Number(args.max_fix_rounds)) && Number(args.max_fix_rounds) > 0 ? { maxFixRounds: Number(args.max_fix_rounds) } : {}),
853
+ ...(Array.isArray(args.deliverables) && args.deliverables.length ? { deliverables: args.deliverables } : {}),
854
+ ...gatewayOpt(args, adapter),
855
+ };
856
+ }
857
+ const session = prev ? (adapter.resumable === false ? 'new' : prev.session_id) : String(args.session || 'new');
858
+ const resume = session === 'new' ? undefined
859
+ : session === 'continue' ? loadSessions().find((s) => s.agent === adapter.id && s.cwd === cwd && (s.account || '') === account)?.session_id
860
+ : session;
861
+ if (session === 'continue' && !resume) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No earlier ${adapter.label} session in this folder — use session "new"`);
862
+ // Nói tiếp một phiên: agent đã có worktree từ lần đầu — không tạo thêm.
863
+ if (resume && agentOpts.worktree) agentOpts = { ...agentOpts, worktree: undefined };
864
+ let argv;
865
+ try {
866
+ const flags = await flagsOf(adapter);
867
+ // 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.
868
+ if (withContract && !flags) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Cannot read the options of ${adapter.label} on this computer — contract jobs need them`);
869
+ argv = agentArgs(adapter, { ...agentOpts, ...memberOpt(adapter), resume, model: args.model ? String(args.model) : undefined }, flags);
870
+ } catch (e) {
871
+ if (withContract) fs.rmSync(dirOf(jobId), { recursive: true, force: true });
872
+ // Worktree daemon vừa dựng cho job này (chưa giao agent) → gỡ luôn worktree + nhánh, không để rác trong repo của người dùng.
873
+ if (withContract && !prev && extra.worktree && extra.fixedWorktree) {
874
+ await gitWrite(cwd, ['worktree', 'remove', '--force', extra.worktree], gitOpts).catch(() => undefined);
875
+ await gitWrite(cwd, ['branch', '-D', `aivin/${jobId}`], gitOpts).catch(() => undefined);
876
+ }
877
+ throw e;
878
+ }
879
+ const fullPrompt = withContract
880
+ ? contractPrompt({ jobId, jobDir: dirOf(jobId), contract: extra.contract, hasTestCheck: extra.hasTestCheck, note: prompt })
881
+ : prompt;
882
+
883
+ const j = {
884
+ id: jobId, agent: adapter.id, status: 'running', prompt: prompt || `contract ${extra.contractId}`, cwd, cwdShown: args.cwd || cwd, mode: agentOpts.mode,
885
+ session_id: resume, model: undefined, texts: [], tools: [], result: null, error: null, startedAt: now(), endedAt: 0, waiters: new Set(), child: null,
886
+ abort: new AbortController(), ...(wallMs ? { wallMs } : {}), ...extra, ...(account ? { account } : {}),
887
+ };
888
+ // Hồ sơ tài khoản: thư mục cấu hình riêng qua biến môi trường chính thức của agent — phiên / đăng nhập / hạn mức của tài khoản đó.
889
+ const { env: authExtra, secrets: authSecrets } = buildCommandAuthEnv(env.authEnv, 'git');
890
+ // Khoá cổng AI tạm cũng bị che nếu agent lỡ nhắc lại trong câu trả lời / lỗi.
891
+ const gatewayKey = typeof agentOpts.aiGateway?.apiKey === 'string' ? agentOpts.aiGateway.apiKey : '';
892
+ if (authSecrets.length || gatewayKey) j._authSecrets = [...authSecrets, ...(gatewayKey ? [gatewayKey] : [])];
893
+ const baseChildEnv = accountDir ? { ...agentEnv(process.env), [adapter.profileEnv]: accountDir } : agentEnv(process.env);
894
+ const childEnv = !runAs && Object.keys(authExtra).length ? { ...baseChildEnv, ...authExtra } : baseChildEnv;
895
+ const child = spawnOf(adapter)(binaryOf(adapter).bin, argv, {
896
+ cwd: spawnCwd || cwd,
897
+ env: childEnv,
898
+ ...(runAs && Object.keys(authExtra).length ? { authExtra } : {}),
899
+ windowsHide: true,
900
+ stdio: ['pipe', 'pipe', 'pipe'],
901
+ });
902
+ // Gọi lại cùng phiên (nhắc ghi lại REPORT.md) cần đúng tệp chạy, cờ, môi trường của lần này.
903
+ if (withContract) j.respawn = { adapter, bin: binaryOf(adapter).bin, opts: { ...agentOpts, ...memberOpt(adapter), model: args.model ? String(args.model) : undefined }, flags: await flagsOf(adapter), env: childEnv, cwd: spawnCwd || cwd };
904
+ jobs.set(j.id, j);
905
+ persist(j);
906
+ attachChild(j, adapter, child, { wallMs, onOutput: ctx.onOutput });
907
+ child.stdin.end(fullPrompt);
908
+
909
+ await waitDone(j, Math.min(Number(args.wait_ms) || DEFAULT_WAIT_MS, MAX_WAIT_MS), ctx.signal);
910
+ 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 };
911
+ }
912
+
913
+ async function status(args, ctx = {}) {
914
+ const j = jobs.get(String(args.job || ''));
915
+ if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job} (finished more than 30 minutes ago, or never started)`);
916
+ await waitDone(j, Math.min(Number(args.wait_ms) || 0, MAX_WAIT_MS), ctx.signal);
917
+ return view(j, Number(args.next_text) || 0, Number(args.next_tool) || 0);
918
+ }
919
+
920
+ function halt(j, reason) {
921
+ if (!RUNNING.has(j.status)) return;
922
+ try { j.child?.kill(); } catch { /* đã thoát */ }
923
+ j.abort?.abort();
924
+ j.status = 'stopped';
925
+ if (reason) j.error = reason;
926
+ j.endedAt = now();
927
+ persist(j);
928
+ wake(j);
929
+ }
930
+
931
+ function stop(args) {
932
+ const j = jobs.get(String(args.job || ''));
933
+ if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job}`);
934
+ halt(j);
935
+ return view(j);
936
+ }
937
+
938
+ const contractJob = (args) => {
939
+ const j = jobs.get(String(args.job || ''));
940
+ if (!j?.contractId) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No contract job ${args.job}`);
941
+ return j;
942
+ };
943
+
944
+ /** Đọc một tệp của thư mục job theo khúc (BE đưa lên kho file). */
945
+ function jobFile(args) {
946
+ const j = contractJob(args);
947
+ const name = String(args.name || '').replace(/\\/g, '/');
948
+ if (!JOB_FILE_RE.test(name)) throw invalid('name must be CONTRACT.md, TEST_CHECK.md, REPORT.md, evidence.json, diff.patch or logs/<command>.log');
949
+ const file = path.join(dirOf(j.id), name);
950
+ let fd;
951
+ try { fd = fs.openSync(file, 'r'); } catch { throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${name} is not in job ${j.id}`); }
952
+ try {
953
+ const size = fs.fstatSync(fd).size;
954
+ const offset = Math.max(0, Math.min(size, Math.trunc(Number(args.offset) || 0)));
955
+ const want = Math.max(1, Math.min(MAX_JOB_FILE_CHUNK, Math.trunc(Number(args.max_bytes) || 256 * 1024)));
956
+ const buf = Buffer.alloc(Math.min(want, size - offset));
957
+ const read = buf.length ? fs.readSync(fd, buf, 0, buf.length, offset) : 0;
958
+ const keep = utf8Boundary(buf.subarray(0, read), offset + read >= size);
959
+ return { job: j.id, name, size, offset, bytes: keep, next_offset: offset + keep, eof: offset + keep >= size, text: buf.subarray(0, keep).toString('utf8') };
960
+ } finally { fs.closeSync(fd); }
961
+ }
962
+
963
+ /**
964
+ * Gỡ worktree của job sau khi Aivin đã nhận kết quả (nhánh giao kết quả vẫn giữ). Worktree có liên kết bên trong → từ chối, để người dọn
965
+ * tay (xoá cưỡng bức đi theo junction là xoá dữ liệu thật ở nơi khác).
966
+ */
967
+ async function cleanup(args) {
968
+ const j = contractJob(args);
969
+ if (RUNNING.has(j.status)) throw invalid(`${j.id} is still running`);
970
+ if (!j.worktree || j.worktreeRemoved) return { job: j.id, removed: false, reason: 'no worktree to remove' };
971
+ const wt = j.worktree;
972
+ const known = (await listWorktrees(j.cwd, gitOpts)).some((t) => path.resolve(t).toLowerCase() === path.resolve(wt).toLowerCase());
973
+ if (!known) throw invalid(`${wt} is not a worktree of ${j.cwdShown}`);
974
+ if (hasLinks(wt)) throw invalid(`${wt} contains links (symlink / junction) — remove it by hand so nothing outside it is deleted`);
975
+ await gitWrite(j.cwd, ['worktree', 'unlock', wt], gitOpts).catch(() => undefined);
976
+ await gitWrite(j.cwd, ['worktree', 'remove', '--force', wt], gitOpts);
977
+ j.worktreeRemoved = true;
978
+ persist(j);
979
+ return { job: j.id, removed: true, worktree: wt, ...(j.delivery?.branch ? { branch_kept: j.delivery.branch } : {}) };
980
+ }
981
+
982
+ /**
983
+ * Cổng khớp wireframe (18/11/2026): chạy app của job trong worktree của nó, chụp các đường dẫn BE nêu, tắt app (agentPreview.mjs). Chỉ khi job
984
+ * đã đo xong và worktree còn. Máy tổ chức: lệnh mở app chạy dưới tài khoản thành viên như lệnh verify.
985
+ */
986
+ async function preview(args, ctx) {
987
+ const j = contractJob(args);
988
+ if (RUNNING.has(j.status)) throw invalid(`${j.id} is still running`);
989
+ if (!j.worktree || j.worktreeRemoved) throw invalid(`${j.id} has no worktree any more — preview runs before cleanup`);
990
+ try {
991
+ return { job: j.id, ...(await capturePreview(args, { cwd: j.worktree, spawnApp: childSpawn, signal: ctx?.signal })) };
992
+ } catch (e) {
993
+ throw invalid(e.message);
994
+ }
995
+ }
996
+
997
+ function sessions(args, _ctx, env = {}) {
998
+ const cwd = args.cwd ? resolveInRoots(env.roots || [], String(args.cwd)) : null;
999
+ return { sessions: loadSessions().filter((s) => (!cwd || s.cwd === cwd) && (!args.agent || s.agent === args.agent)).slice(0, 20) };
1000
+ }
1001
+
1002
+ restore();
1003
+
1004
+ return {
1005
+ run, status, stop, sessions, jobFile, cleanup, preview,
1006
+ profiles: () => ({ profiles: listAgentProfiles(installed(), { root: profilesRoot }) }),
1007
+ installed: () => installed().map((a) => ({ id: a.id, label: a.label, version: binaryOf(a).version })),
1008
+ /** 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. */
1009
+ hasRunning: () => [...jobs.values()].some((j) => RUNNING.has(j.status)),
1010
+ stopAll: (reason = 'The Aivin agent on this device stopped') => { for (const j of jobs.values()) halt(j, reason); },
1011
+ };
1012
+ }
1013
+
1014
+ /** 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. */
1015
+ export function buildAgentTools(runner) {
1016
+ const agents = runner.installed();
1017
+ const list = agents.map((a) => `${a.id} (${a.label} ${a.version})`).join(', ');
1018
+ return [
1019
+ { name: 'agent.run', group: ToolGroup.PROC, handler: (a, c, e) => runner.run(a, c, e),
1020
+ 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.`,
1021
+ input_schema: schema({
1022
+ 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(' | ')}`),
1023
+ cwd: str('project folder (default the first allowed folder, or workspace.cwd of the contract)'), session: str('new | continue | <session id>'),
1024
+ mode: str('manual | plan | accept_edits (with contract: from permissions.mode)'), model: str('optional model alias of that agent'),
1025
+ max_budget_usd: num('stop the agent once it has spent this much (without contract)'), effort: str('low | medium | high | xhigh | max (without contract)'),
1026
+ 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)'),
1027
+ 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'),
1028
+ continue_job: str('fix round: an earlier contract job — continue its session in its worktree (send the contract again)'),
1029
+ account: str('run as this account profile of the agent (from agent.profiles) — its own sign-in, sessions and usage limits; default: the usual account of the agent'),
1030
+ inner_agent: str('agent "lightcode" only: which agent inside LightCode does the work (claude | codex | gemini | opencode | antigravity; default: LightCode picks)'),
1031
+ clarify: bool('agent "lightcode" only: when the agent has a question, stop and hand it back instead of guessing (default true with contract)'),
1032
+ goal_id: str('agent "lightcode" only: strategy goal id from .lcagent/strategy.json (tracks budget and refuses closed/over-budget goals)'),
1033
+ depends_on: { type: 'array', items: { type: 'string' }, description: 'agent "lightcode" only: session ids or client_job_ids that must finish well first' },
1034
+ max_fix_rounds: num('agent "lightcode" only: internal quality-check fix rounds inside LightCode (0-3)'),
1035
+ deliverables: { type: 'array', description: 'agent "lightcode" only: files the job must leave behind (path string or { path, min_bytes }), checked for existence and valid file format' },
1036
+ ai_gateway: { type: 'object', description: 'BE-only, agent "lightcode" only: temporary AI gateway { baseUrl, apiKey, model, expiresAt } for this job (default AIVIN quota); never logged, never passed to other agents' },
1037
+ wait_ms: num(`wait for the answer up to this long (default ${DEFAULT_WAIT_MS}, max ${MAX_WAIT_MS})`),
1038
+ }) },
1039
+ { name: 'agent.status', group: ToolGroup.PROC, read_only: true, handler: (a, c) => runner.status(a, c),
1040
+ 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.',
1041
+ 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']) },
1042
+ { name: 'agent.stop', group: ToolGroup.PROC, handler: (a) => runner.stop(a),
1043
+ description: 'Stop a running coding-agent task.',
1044
+ input_schema: schema({ job: str('job from agent.run') }, ['job']) },
1045
+ { name: 'agent.job_file', group: ToolGroup.PROC, read_only: true, internal: true, handler: (a) => runner.jobFile(a),
1046
+ description: 'BE-only: read a file of a contract job (REPORT.md, evidence.json, diff.patch, logs/<command>.log…) in chunks from offset.',
1047
+ input_schema: schema({ job: str('contract job'), name: str('file name'), offset: num('byte offset'), max_bytes: num('chunk size, max 1048576') }, ['job', 'name']) },
1048
+ { name: 'agent.cleanup', group: ToolGroup.PROC, internal: true, handler: (a) => runner.cleanup(a),
1049
+ description: "BE-only: remove a finished contract job's worktree (the delivery branch is kept).",
1050
+ input_schema: schema({ job: str('contract job') }, ['job']) },
1051
+ { name: 'agent.preview', group: ToolGroup.PROC, internal: true, handler: (a, c) => runner.preview(a, c),
1052
+ description: "BE-only: start the app of a finished contract job inside its worktree (argv), wait for url to answer, screenshot each shot path headless, stop the app. Returns PNGs (base64) to compare with the wireframe.",
1053
+ input_schema: schema({
1054
+ job: str('contract job'), argv: { type: 'array', items: { type: 'string' }, description: 'command that starts the app, as words' },
1055
+ url: str('base address on this computer, e.g. http://localhost:5173'), ready_timeout_ms: num('wait this long for the app to answer (max 600000)'),
1056
+ shots: { type: 'array', items: { type: 'object', properties: { id: str('screen id'), path: str('path starting with /'), device: str('desktop | tablet | mobile') } }, description: `at most ${PREVIEW_MAX_SHOTS} screens` },
1057
+ }, ['job', 'argv', 'url', 'shots']) },
1058
+ { name: 'agent.profiles', group: ToolGroup.PROC, read_only: true, handler: () => runner.profiles(),
1059
+ description: 'Account profiles of each installed coding agent on this computer (each has its own sign-in and usage limits). Pass one as account to agent.run to switch account without any UI. The person creates a profile once by signing in to it.',
1060
+ input_schema: schema({}) },
1061
+ { name: 'agent.sessions', group: ToolGroup.PROC, read_only: true, handler: (a, c, e) => runner.sessions(a, c, e),
1062
+ description: 'Recent coding-agent sessions started from Aivin on this computer (agent, folder, first words of the task, when, ok) — to continue one.',
1063
+ input_schema: schema({ cwd: str('only sessions of this folder'), agent: str('only this agent') }) },
1064
+ ];
1065
+ }