@aivin-labs/cli 1.0.68 → 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.
@@ -5,11 +5,15 @@ import { randomUUID } from 'crypto';
5
5
  import { execFile, execFileSync, spawn } from 'child_process';
6
6
  import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
7
7
  import { DeviceToolError, agentEnv, resolveInRoots } from './sandbox.mjs';
8
- import { parseContract, parseReport, parseTestCheck, reportTemplate, sha256 } from './agentContract.mjs';
8
+ import { accountEnv, withProcessCap } from './multiUser.mjs';
9
+ import { contractBrief, parseContract, parseReport, parseTestCheck, reportTemplate, sha256 } from './agentContract.mjs';
9
10
 
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). */
11
12
  const REPORT_REPAIR_MS = 5 * 60_000;
12
- import { commitJobWork, gitRead, gitWrite, globToRegExp, listWorktrees, measureEvidence, resolveCommit, worktreeState } from './agentEvidence.mjs';
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';
13
17
 
14
18
  const MAX_SCOPE_RULES = 400;
15
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`). */
@@ -123,6 +127,15 @@ const bool = (description) => ({ type: 'boolean', description });
123
127
  const schema = (properties, required = []) => ({ type: 'object', properties, required });
124
128
  const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
125
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
+
126
139
  /** `<dir>/<exe>` của mọi thư mục trong PATH. */
127
140
  function onPath(exe, env) {
128
141
  return String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean).map((dir) => path.join(dir, exe));
@@ -162,6 +175,50 @@ export function agentProfileDir(adapter, name, { root = AGENT_PROFILES_DIR } = {
162
175
  return dir;
163
176
  }
164
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
+
165
222
  /** Hồ sơ đã có của từng adapter (tên thư mục). */
166
223
  export function listAgentProfiles(adapters, { root = AGENT_PROFILES_DIR } = {}) {
167
224
  const out = {};
@@ -250,7 +307,72 @@ export const CLAUDE_ADAPTER = Object.freeze({
250
307
  },
251
308
  });
252
309
 
253
- export const DEFAULT_AGENT_ADAPTERS = Object.freeze([CLAUDE_ADAPTER]);
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]);
254
376
 
255
377
  function versionOf(bin) {
256
378
  try {
@@ -262,9 +384,9 @@ function versionOf(bin) {
262
384
  const newer = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return false; };
263
385
 
264
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. */
265
- export function helpFlags(bin) {
387
+ export function helpFlags(bin, helpArgs = ['--help']) {
266
388
  return new Promise((resolve) => {
267
- execFile(bin, ['--help'], { encoding: 'utf8', timeout: 20_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, out) => {
389
+ execFile(bin, helpArgs, { encoding: 'utf8', timeout: 20_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, out) => {
268
390
  resolve(err ? null : new Set(String(out).match(/--[a-z][a-z-]+/gi) || []));
269
391
  });
270
392
  });
@@ -272,6 +394,8 @@ export function helpFlags(bin) {
272
394
 
273
395
  /** Bản mới nhất chạy được của một agent trên máy, hoặc null. */
274
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);
275
399
  let best = null;
276
400
  for (const bin of [...new Set(adapter.candidates(opts))]) {
277
401
  if (!fs.existsSync(bin)) continue;
@@ -325,22 +449,32 @@ function contractPrompt({ jobId, jobDir, contract, hasTestCheck, note }) {
325
449
  export function createAgentRunner({
326
450
  adapters = DEFAULT_AGENT_ADAPTERS, find = findAgentBinary, spawnImpl = spawn, now = Date.now, jobsDir = JOBS_DIR, measure = measureEvidence, probeFlags = helpFlags,
327
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,
328
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;
329
458
  const found = new Map();
330
459
  const flagCache = new Map();
331
460
  const jobs = new Map();
332
461
  const binaryOf = (adapter) => {
333
- if (!found.has(adapter.id)) found.set(adapter.id, find(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));
334
464
  return found.get(adapter.id);
335
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 } } : {});
336
470
  const flagsOf = async (adapter) => {
337
471
  const b = binaryOf(adapter);
338
472
  if (b?.flags) return new Set(b.flags);
339
- if (!flagCache.has(adapter.id)) flagCache.set(adapter.id, b ? Promise.resolve(probeFlags(b.bin)).catch(() => null) : null);
473
+ if (!flagCache.has(adapter.id)) flagCache.set(adapter.id, b ? Promise.resolve(probeFlags(b.bin, adapter.helpArgs)).catch(() => null) : null);
340
474
  return flagCache.get(adapter.id);
341
475
  };
342
476
  /** Agent đã cài trên máy (theo thứ tự ưu tiên của danh sách adapter). */
343
- const installed = () => adapters.filter((a) => binaryOf(a));
477
+ const installed = () => adapters.filter((a) => !(runAs && a.multiUser === false) && binaryOf(a));
344
478
  const adapterFor = (id) => {
345
479
  const list = installed();
346
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(', ')})`);
@@ -352,37 +486,13 @@ export function createAgentRunner({
352
486
 
353
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).
354
488
  const dirOf = (id) => path.join(jobsDir, id);
355
- const RECORD_KEYS = ['id', 'agent', 'status', 'cwd', 'cwdShown', 'mode', 'model', 'session_id', 'worktree', 'baseCommit', 'contractId', 'contractSha', 'continuedFrom', 'delivery', 'worktreeRemoved', 'reportRepaired', 'startedAt', 'endedAt', 'result', 'error'];
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'];
356
490
  function persist(j) {
357
491
  try {
358
492
  fs.mkdirSync(dirOf(j.id), { recursive: true });
359
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));
360
494
  } catch { /* hồ sơ chỉ để trả lời sau khi khởi động lại */ }
361
495
  }
362
- /** 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. */
363
- function restore() {
364
- let names;
365
- try { names = fs.readdirSync(jobsDir); } catch { return; }
366
- for (const name of names) {
367
- if (!JOB_ID_RE.test(name)) continue;
368
- let rec;
369
- try { rec = JSON.parse(fs.readFileSync(path.join(dirOf(name), 'job.json'), 'utf8')); } catch { continue; }
370
- if (rec.id !== name) continue;
371
- if (now() - (rec.endedAt || rec.startedAt || 0) > KEEP_JOB_DIR_MS) {
372
- try { fs.rmSync(dirOf(name), { recursive: true, force: true }); } catch { /* lần sau */ }
373
- continue;
374
- }
375
- const j = { ...rec, prompt: rec.prompt || '', texts: [], tools: [], waiters: new Set(), child: null, restored: true };
376
- if (RUNNING.has(j.status)) {
377
- j.status = 'interrupted';
378
- j.error = 'The Aivin agent on this device restarted while this job was running — continue it with session set to its session_id';
379
- j.endedAt = now();
380
- persist(j);
381
- }
382
- jobs.set(j.id, j);
383
- }
384
- }
385
- restore();
386
496
 
387
497
  const prune = () => {
388
498
  for (const [id, j] of jobs) if (!RUNNING.has(j.status) && now() - j.endedAt > KEEP_DONE_MS && !j.contractId) jobs.delete(id);
@@ -391,12 +501,19 @@ export function createAgentRunner({
391
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; }
392
502
  };
393
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;
394
509
  const out = {
395
510
  job: j.id, agent: j.agent, status: j.status, session_id: j.session_id, cwd: j.cwdShown, mode: j.mode, model: j.model,
396
- new_text: j.texts.slice(sinceText).join('\n\n').slice(-MAX_ANSWER_CHARS) || undefined,
511
+ new_text: redact(rawText),
397
512
  tools_used: j.tools.slice(sinceTool).slice(-40),
398
- ...(j.result ? { result: j.result } : {}),
399
- ...(j.error ? { error: j.error } : {}),
513
+ ...(redactedResult ? { result: redactedResult } : {}),
514
+ ...(j.progress ? { progress: j.progress } : {}),
515
+ ...(j.questions?.length ? { questions: j.questions } : {}),
516
+ ...(j.error ? { error: redact(j.error) } : {}),
400
517
  next_text: j.texts.length, next_tool: j.tools.length,
401
518
  };
402
519
  if (j.contractId) {
@@ -435,7 +552,7 @@ export function createAgentRunner({
435
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ố
436
553
  * cho adapter. Mọi lỗi ở đây xảy ra TRƯỚC khi agent chạy (không có gì thay đổi).
437
554
  */
438
- async function prepareContract(args, env, jobId, prev) {
555
+ async function prepareContract(args, env, jobId, prev, adapter) {
439
556
  const text = String(args.contract);
440
557
  if (!args.contract_sha256) throw invalid('contract_sha256 is required with contract (the sha256 of CONTRACT.md Aivin issued)');
441
558
  const parsed = parseContract(text, { expectedSha: String(args.contract_sha256) });
@@ -456,10 +573,16 @@ export function createAgentRunner({
456
573
  if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd || contract.workspace.cwd}`);
457
574
  if (prev?.worktree && !fs.existsSync(prev.worktree)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `The worktree of ${prev.id} is gone: ${prev.worktree}`);
458
575
  const isolate = prev ? !!prev.worktree : contract.workspace.isolation === 'worktree';
459
- const baseCommit = prev ? prev.baseCommit : await resolveCommit(cwd, contract.workspace.base_ref);
576
+ const baseCommit = prev ? prev.baseCommit : await resolveCommit(cwd, contract.workspace.base_ref, gitOpts);
460
577
  if (isolate && !baseCommit) throw invalid(`worktree isolation needs a git repository with ${contract.workspace.base_ref} in ${args.cwd || cwd}`);
461
- if (!prev && isolate && contract.workspace.base_ref !== 'HEAD' && baseCommit !== (await resolveCommit(cwd, 'HEAD'))) {
462
- throw invalid(`the job worktree starts from HEAD — check out ${contract.workspace.base_ref} first, or set base_ref: HEAD`);
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);
463
586
  }
464
587
 
465
588
  const jobDir = dirOf(jobId);
@@ -467,24 +590,37 @@ export function createAgentRunner({
467
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 */ } };
468
591
  writeLocked('CONTRACT.md', text);
469
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);
470
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.
471
596
  const deny = [
472
597
  ...['CONTRACT.md', 'TEST_CHECK.md', 'evidence.json', 'job.json', 'logs/**'].flatMap((n) => ['Edit', 'Write'].map((t) => `${t}(${claudeAbsPath(path.join(jobDir, n))})`)),
473
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.
474
- ...(await scopeDenyRules(contract, cwd)),
599
+ ...(await scopeDenyRules(contract, cwd, { gitOpts })),
475
600
  ];
476
601
  return {
477
602
  job: {
478
603
  contract, contractId: contract.contract_id, contractSha: parsed.sha256, hasTestCheck: testCheckText !== null, testCheckText,
479
- baseCommit, mainStateBefore: isolate ? await worktreeState(cwd) : null, isolate,
604
+ baseCommit, mainStateBefore: isolate ? await worktreeState(cwd, gitOpts) : null, isolate,
480
605
  ...(prev ? { worktree: prev.worktree, fixedWorktree: !!prev.worktree, continuedFrom: prev.id } : {}),
606
+ ...(ownWorktree ? { worktree: ownWorktree, fixedWorktree: true } : {}),
481
607
  },
482
608
  cwd,
483
- spawnCwd: prev?.worktree || cwd,
609
+ spawnCwd: prev?.worktree || ownWorktree || cwd,
484
610
  agentOpts: {
485
611
  mode: contract.permissions.mode, budgetUsd: contract.limits.max_budget_usd, effort: contract.limits.effort,
486
- allowedTools: contract.permissions.allowed_tools, addDirs: [jobDir], worktree: isolate && !prev ? jobId : undefined, projectConfig: false,
612
+ allowedTools: contract.permissions.allowed_tools, addDirs: [jobDir], worktree: isolate && !prev && !ownWorktree ? jobId : undefined, projectConfig: false,
487
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),
488
624
  },
489
625
  wallMs: contract.limits.max_wall_ms,
490
626
  };
@@ -492,7 +628,7 @@ export function createAgentRunner({
492
628
 
493
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. */
494
630
  async function findJobWorktree(j) {
495
- const trees = await listWorktrees(j.cwd);
631
+ const trees = await listWorktrees(j.cwd, gitOpts);
496
632
  const same = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase();
497
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);
498
634
  return trees.find((t) => !same(t, j.cwd) && path.basename(t) === j.id) || null;
@@ -504,7 +640,11 @@ export function createAgentRunner({
504
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.
505
641
  */
506
642
  async function repairReport(j) {
507
- if (!j.respawn || !j.session_id || j.abort.signal.aborted) return;
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;
508
648
  const file = path.join(dirOf(j.id), 'REPORT.md');
509
649
  let text = null;
510
650
  try { text = fs.readFileSync(file, 'utf8'); } catch { /* chưa ghi */ }
@@ -512,11 +652,14 @@ export function createAgentRunner({
512
652
  if (parsed.ok) return;
513
653
  const { adapter, opts, flags, env, bin } = j.respawn;
514
654
  let argv;
515
- try { argv = agentArgs(adapter, { ...opts, worktree: undefined, resume: j.session_id }, flags); } catch { return; }
516
- const prompt = `${file} is not in the agreed format: ${parsed.errors.slice(0, 8).join('; ')}. Rewrite only REPORT.md, exactly in the format given at the start (keep every section heading, even when empty). Do not change any other file.`;
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}`;
517
660
  await new Promise((resolve) => {
518
661
  let child;
519
- try { child = spawnImpl(bin, argv, { cwd: j.worktree || j.respawn.cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }); } catch { resolve(); return; }
662
+ try { child = spawnOf(adapter)(bin, argv, { cwd: j.worktree || j.respawn.cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }); } catch { resolve(); return; }
520
663
  const timer = setTimeout(() => { try { child.kill(); } catch { /* đã thoát */ } }, REPORT_REPAIR_MS);
521
664
  const done = () => { clearTimeout(timer); resolve(); };
522
665
  child.stdout?.on?.('data', () => undefined);
@@ -531,12 +674,17 @@ export function createAgentRunner({
531
674
 
532
675
  async function finishContractJob(j) {
533
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
+ }
534
682
  // Sau khi biết worktree: phiên của agent nằm ở đó, nói tiếp phải đúng thư mục ấy.
535
683
  await repairReport(j).catch(() => undefined);
536
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.
537
685
  if (j.worktree && j.contract?.outputs?.some((o) => o.kind === 'git_branch')) {
538
686
  try {
539
- j.delivery = await commitJobWork(j.worktree, `aivin: ${j.contractId} v${j.contract.version} (job ${j.id})`, { jobId: j.id });
687
+ j.delivery = await commitJobWork(j.worktree, `aivin: ${j.contractId} v${j.contract.version} (job ${j.id})`, { jobId: j.id, ...(gitOpts || {}) });
540
688
  } catch (e) { j.delivery = { error: e.message.slice(0, 300) }; }
541
689
  }
542
690
  persist(j);
@@ -544,6 +692,7 @@ export function createAgentRunner({
544
692
  const evidence = await measure({
545
693
  job: { id: j.id, contractSha: j.contractSha, worktree: j.worktree, cwd: j.cwd, baseCommit: j.baseCommit, mainStateBefore: j.mainStateBefore, delivery: j.delivery },
546
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 }) } : {}),
547
696
  });
548
697
  if (j.isolate && !j.worktree) {
549
698
  evidence.worktree_missing = true;
@@ -555,6 +704,112 @@ export function createAgentRunner({
555
704
  }
556
705
  }
557
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
+
558
813
  async function run(args, ctx = {}, env = {}) {
559
814
  prune();
560
815
  const withContract = args.contract !== undefined && args.contract !== null && args.contract !== '';
@@ -564,6 +819,7 @@ export function createAgentRunner({
564
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`);
565
820
  const adapter = adapterFor(args.agent ? String(args.agent) : undefined);
566
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');
567
823
  const accountDir = account ? agentProfileDir(adapter, account, { root: profilesRoot }) : null;
568
824
  const jobId = `${adapter.id}-${randomUUID().slice(0, 8)}`;
569
825
 
@@ -580,7 +836,7 @@ export function createAgentRunner({
580
836
  if (!withContract) throw invalid('continue_job needs the contract (the same or a new version)');
581
837
  }
582
838
  if (withContract) {
583
- const prep = await prepareContract(args, env, jobId, prev);
839
+ const prep = await prepareContract(args, env, jobId, prev, adapter);
584
840
  ({ cwd, spawnCwd, agentOpts, wallMs } = prep);
585
841
  extra = prep.job;
586
842
  } else {
@@ -589,9 +845,16 @@ export function createAgentRunner({
589
845
  agentOpts = {
590
846
  mode: String(args.mode || AgentMode.MANUAL), budgetUsd: args.max_budget_usd ?? undefined, effort: args.effort ? String(args.effort) : undefined,
591
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),
592
855
  };
593
856
  }
594
- const session = prev ? prev.session_id : String(args.session || 'new');
857
+ const session = prev ? (adapter.resumable === false ? 'new' : prev.session_id) : String(args.session || 'new');
595
858
  const resume = session === 'new' ? undefined
596
859
  : session === 'continue' ? loadSessions().find((s) => s.agent === adapter.id && s.cwd === cwd && (s.account || '') === account)?.session_id
597
860
  : session;
@@ -603,9 +866,14 @@ export function createAgentRunner({
603
866
  const flags = await flagsOf(adapter);
604
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.
605
868
  if (withContract && !flags) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Cannot read the options of ${adapter.label} on this computer — contract jobs need them`);
606
- argv = agentArgs(adapter, { ...agentOpts, resume, model: args.model ? String(args.model) : undefined }, flags);
869
+ argv = agentArgs(adapter, { ...agentOpts, ...memberOpt(adapter), resume, model: args.model ? String(args.model) : undefined }, flags);
607
870
  } catch (e) {
608
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
+ }
609
877
  throw e;
610
878
  }
611
879
  const fullPrompt = withContract
@@ -615,60 +883,27 @@ export function createAgentRunner({
615
883
  const j = {
616
884
  id: jobId, agent: adapter.id, status: 'running', prompt: prompt || `contract ${extra.contractId}`, cwd, cwdShown: args.cwd || cwd, mode: agentOpts.mode,
617
885
  session_id: resume, model: undefined, texts: [], tools: [], result: null, error: null, startedAt: now(), endedAt: 0, waiters: new Set(), child: null,
618
- abort: new AbortController(), ...extra, ...(account ? { account } : {}),
886
+ abort: new AbortController(), ...(wallMs ? { wallMs } : {}), ...extra, ...(account ? { account } : {}),
619
887
  };
620
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 đó.
621
- const childEnv = accountDir ? { ...agentEnv(process.env), [adapter.profileEnv]: accountDir } : agentEnv(process.env);
622
- const child = spawnImpl(binaryOf(adapter).bin, argv, { cwd: spawnCwd || cwd, env: childEnv, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
623
- j.child = child;
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
+ });
624
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.
625
- 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 };
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 };
626
904
  jobs.set(j.id, j);
627
905
  persist(j);
628
- const wall = wallMs ? setTimeout(() => {
629
- if (j.status !== 'running') return;
630
- j.error = `Stopped at the contract time limit (${Math.round(wallMs / 60_000)} min)`;
631
- try { j.child?.kill(); } catch { /* đã thoát */ }
632
- }, wallMs) : null;
633
- wall?.unref?.();
634
- let buf = '';
635
- let stderr = '';
636
- child.stdout.on('data', (d) => {
637
- buf += d.toString();
638
- let nl;
639
- while ((nl = buf.indexOf('\n')) >= 0) {
640
- const line = buf.slice(0, nl).trim();
641
- buf = buf.slice(nl + 1);
642
- if (!line) continue;
643
- let msg;
644
- try { msg = JSON.parse(line); } catch { continue; }
645
- if (!msg || typeof msg !== 'object') continue;
646
- const shown = adapter.parse(j, msg);
647
- if (j.texts.length > MAX_TEXTS) j.texts.splice(0, j.texts.length - MAX_TEXTS);
648
- if (shown && typeof ctx.onOutput === 'function') { try { ctx.onOutput(`${shown}\n`); } catch { /* chỉ là tiến trình */ } }
649
- }
650
- });
651
- child.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-2000); });
652
- child.stdin.on?.('error', () => undefined);
653
- const finish = async (code) => {
654
- if (j.status !== 'running') return;
655
- clearTimeout(wall);
656
- const agentOk = !!j.result?.ok;
657
- if (!j.result && !j.error) j.error = (stderr.trim().split(/\r?\n/).slice(-3).join(' ') || `${adapter.id} exited with code ${code}`).slice(0, 500);
658
- if (j.contractId) {
659
- j.status = 'measuring';
660
- persist(j);
661
- await finishContractJob(j);
662
- if (j.status !== 'measuring') return; // bị dừng giữa lúc đo
663
- }
664
- j.status = agentOk && !j.error?.startsWith('contract_tampered') ? 'done' : 'failed';
665
- j.endedAt = now();
666
- remember(j);
667
- persist(j);
668
- wake(j);
669
- };
670
- child.on('error', (e) => { j.error = e.message; void finish(-1); });
671
- child.on('close', (code) => { void finish(code); });
906
+ attachChild(j, adapter, child, { wallMs, onOutput: ctx.onOutput });
672
907
  child.stdin.end(fullPrompt);
673
908
 
674
909
  await waitDone(j, Math.min(Number(args.wait_ms) || DEFAULT_WAIT_MS, MAX_WAIT_MS), ctx.signal);
@@ -734,23 +969,40 @@ export function createAgentRunner({
734
969
  if (RUNNING.has(j.status)) throw invalid(`${j.id} is still running`);
735
970
  if (!j.worktree || j.worktreeRemoved) return { job: j.id, removed: false, reason: 'no worktree to remove' };
736
971
  const wt = j.worktree;
737
- const known = (await listWorktrees(j.cwd)).some((t) => path.resolve(t).toLowerCase() === path.resolve(wt).toLowerCase());
972
+ const known = (await listWorktrees(j.cwd, gitOpts)).some((t) => path.resolve(t).toLowerCase() === path.resolve(wt).toLowerCase());
738
973
  if (!known) throw invalid(`${wt} is not a worktree of ${j.cwdShown}`);
739
974
  if (hasLinks(wt)) throw invalid(`${wt} contains links (symlink / junction) — remove it by hand so nothing outside it is deleted`);
740
- await gitWrite(j.cwd, ['worktree', 'unlock', wt]).catch(() => undefined);
741
- await gitWrite(j.cwd, ['worktree', 'remove', '--force', wt]);
975
+ await gitWrite(j.cwd, ['worktree', 'unlock', wt], gitOpts).catch(() => undefined);
976
+ await gitWrite(j.cwd, ['worktree', 'remove', '--force', wt], gitOpts);
742
977
  j.worktreeRemoved = true;
743
978
  persist(j);
744
979
  return { job: j.id, removed: true, worktree: wt, ...(j.delivery?.branch ? { branch_kept: j.delivery.branch } : {}) };
745
980
  }
746
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
+
747
997
  function sessions(args, _ctx, env = {}) {
748
998
  const cwd = args.cwd ? resolveInRoots(env.roots || [], String(args.cwd)) : null;
749
999
  return { sessions: loadSessions().filter((s) => (!cwd || s.cwd === cwd) && (!args.agent || s.agent === args.agent)).slice(0, 20) };
750
1000
  }
751
1001
 
1002
+ restore();
1003
+
752
1004
  return {
753
- run, status, stop, sessions, jobFile, cleanup,
1005
+ run, status, stop, sessions, jobFile, cleanup, preview,
754
1006
  profiles: () => ({ profiles: listAgentProfiles(installed(), { root: profilesRoot }) }),
755
1007
  installed: () => installed().map((a) => ({ id: a.id, label: a.label, version: binaryOf(a).version })),
756
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. */
@@ -775,6 +1027,13 @@ export function buildAgentTools(runner) {
775
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'),
776
1028
  continue_job: str('fix round: an earlier contract job — continue its session in its worktree (send the contract again)'),
777
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' },
778
1037
  wait_ms: num(`wait for the answer up to this long (default ${DEFAULT_WAIT_MS}, max ${MAX_WAIT_MS})`),
779
1038
  }) },
780
1039
  { name: 'agent.status', group: ToolGroup.PROC, read_only: true, handler: (a, c) => runner.status(a, c),
@@ -789,6 +1048,13 @@ export function buildAgentTools(runner) {
789
1048
  { name: 'agent.cleanup', group: ToolGroup.PROC, internal: true, handler: (a) => runner.cleanup(a),
790
1049
  description: "BE-only: remove a finished contract job's worktree (the delivery branch is kept).",
791
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']) },
792
1058
  { name: 'agent.profiles', group: ToolGroup.PROC, read_only: true, handler: () => runner.profiles(),
793
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.',
794
1060
  input_schema: schema({}) },