@aivin-labs/cli 1.0.66 → 1.0.68
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.
- package/bin/lib/remote/agentContract.mjs +10 -1
- package/bin/lib/remote/agentEvidence.mjs +97 -2
- package/bin/lib/remote/client.mjs +14 -3
- package/bin/lib/remote/codingAgents.mjs +171 -8
- package/bin/lib/remote/desktop/agentOverlay.mjs +382 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +56 -17
- package/bin/lib/remote/gui/index.mjs +52 -1
- package/bin/lib/remote/localLlm.mjs +59 -16
- package/bin/lib/remote/localLlmAccounts.mjs +57 -0
- package/bin/lib/remote/mascot/hostSource.mjs +1 -1
- package/bin/lib/tasks.mjs +391 -389
- package/package.json +1 -1
|
@@ -172,6 +172,15 @@ export function parseContract(text, { expectedSha } = {}) {
|
|
|
172
172
|
for (const t of permissions.allowed_tools) if (UNBOUNDED_SHELL.has(t)) errors.push(`permissions.allowed_tools: ${t} without a command pattern allows every command — write e.g. ${t}(npm test *)`);
|
|
173
173
|
if (risk === Risk.READ_ONLY && permissions.mode !== 'plan') errors.push('permissions.mode: read_only work runs in plan mode');
|
|
174
174
|
|
|
175
|
+
// Lệnh chuẩn bị (cài phụ thuộc…) — daemon chạy trong worktree TRƯỚC các lệnh verify; agent cũng được báo chạy trước khi test.
|
|
176
|
+
const setup = f.list(fm.setup, 'setup').map((v, i) => ({
|
|
177
|
+
id: f.id(v.id, `setup[${i}].id`),
|
|
178
|
+
argv: f.strList(v.argv, `setup[${i}].argv`, { dflt: undefined, what: 'command words (argv)' }),
|
|
179
|
+
timeout_ms: f.int(v.timeout_ms, `setup[${i}].timeout_ms`, { min: 1000, max: 3_600_000, dflt: 600_000 }),
|
|
180
|
+
}));
|
|
181
|
+
setup.forEach((v, i) => { if (!v.argv?.length) errors.push(`setup[${i}].argv: is required`); });
|
|
182
|
+
for (const v of setup) { if (v.id && verifyIds.has(v.id)) errors.push(`setup: id ${v.id} is also a verify id`); }
|
|
183
|
+
|
|
175
184
|
const outputs = f.list(fm.outputs, 'outputs').map((o, i) => ({
|
|
176
185
|
id: f.id(o.id, `outputs[${i}].id`), kind: f.oneOf(o.kind, `outputs[${i}].kind`, OUTPUT_KINDS),
|
|
177
186
|
required: f.bool(o.required, `outputs[${i}].required`, true), consumer: f.id(o.consumer, `outputs[${i}].consumer`, { optional: true }),
|
|
@@ -205,7 +214,7 @@ export function parseContract(text, { expectedSha } = {}) {
|
|
|
205
214
|
feature_group: f.id(fm.feature_group, 'feature_group', { optional: true }),
|
|
206
215
|
project_id: typeof fm.project_id === 'string' ? fm.project_id : undefined, task_id: typeof fm.task_id === 'string' ? fm.task_id : undefined,
|
|
207
216
|
risk, spec_refs: Array.isArray(fm.spec_refs) ? fm.spec_refs : [], depends_on: Array.isArray(fm.depends_on) ? fm.depends_on : [],
|
|
208
|
-
test_check: testCheck, workspace, scope: scope || { deny_paths: [], protected_paths: [] }, verify, acceptance, limits, permissions, outputs,
|
|
217
|
+
test_check: testCheck, workspace, scope: scope || { deny_paths: [], protected_paths: [] }, setup, verify, acceptance, limits, permissions, outputs,
|
|
209
218
|
};
|
|
210
219
|
return { ok: !errors.length, errors, contract, body: split.body, sha256: digest };
|
|
211
220
|
}
|
|
@@ -18,6 +18,11 @@ import { killWindowsTree } from './winTree.mjs';
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
export const EVIDENCE_FILE = 'evidence.json';
|
|
21
|
+
export const PATCH_FILE = 'diff.patch';
|
|
22
|
+
/** Trần của diff.patch — đủ cho giám khảo đọc; lớn hơn thì cắt và ghi rõ. */
|
|
23
|
+
const MAX_PATCH_BYTES = 4 * 1024 ** 2;
|
|
24
|
+
/** Người viết commit giao kết quả (không phụ thuộc cấu hình git của máy). */
|
|
25
|
+
const DELIVERY_IDENT = ['-c', 'user.name=Aivin coding job', '-c', 'user.email=noreply@aivin.cloud', '-c', 'commit.gpgsign=false'];
|
|
21
26
|
const MAX_LOG_BYTES = 20 * 1024 ** 2;
|
|
22
27
|
const LOG_TAIL_CHARS = 4000;
|
|
23
28
|
const MAX_DIFF_BYTES = 16 * 1024 ** 2;
|
|
@@ -174,6 +179,76 @@ export function gitRead(cwd, sub, { maxBytes = MAX_DIFF_BYTES, spawnImpl = spawn
|
|
|
174
179
|
});
|
|
175
180
|
}
|
|
176
181
|
|
|
182
|
+
/**
|
|
183
|
+
* Lệnh git có GHI (add / commit / worktree) — cùng lớp khoá cấu hình của gitRead (không hook, không fsmonitor, bỏ biến GIT_*). `pre` là các
|
|
184
|
+
* `-c` thêm trước lệnh con.
|
|
185
|
+
*/
|
|
186
|
+
export function gitWrite(cwd, sub, { pre = [], spawnImpl = spawn } = {}) {
|
|
187
|
+
return new Promise((resolve, reject) => {
|
|
188
|
+
const argv = safeGitArgv(cwd, sub);
|
|
189
|
+
const at = argv.indexOf('-C');
|
|
190
|
+
argv.splice(at, 0, ...pre);
|
|
191
|
+
const child = spawnImpl('git', argv, { cwd, env: safeGitEnv(scrubEnv()), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
192
|
+
let out = '';
|
|
193
|
+
let err = '';
|
|
194
|
+
const timer = setTimeout(() => child.kill(), GIT_TIMEOUT_MS);
|
|
195
|
+
child.stdout.on('data', (c) => { out = (out + c).slice(-4000); });
|
|
196
|
+
child.stderr.on('data', (c) => { err = (err + c).slice(-1000); });
|
|
197
|
+
child.on('error', (e) => { clearTimeout(timer); reject(e); });
|
|
198
|
+
child.on('close', (code) => {
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
if (code !== 0) reject(new Error(`git ${sub[0]} failed: ${err.trim() || out.trim() || `exit ${code}`}`));
|
|
201
|
+
else resolve(out);
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Giao kết quả ở dạng nhánh: commit mọi thay đổi trong worktree của job lên nhánh đang đứng (nhánh `worktree-<job>` do agent tạo). Đây là
|
|
208
|
+
* cách GIAO (đầu ra `git_branch` của hợp đồng), không phải cách làm. Không có thay đổi → không commit. Trả `{ branch, commit, committed }`.
|
|
209
|
+
*/
|
|
210
|
+
export async function commitJobWork(tree, message, { jobId, ...opts } = {}) {
|
|
211
|
+
const status = (await gitRead(tree, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], opts)).toString('utf8');
|
|
212
|
+
let branch = null;
|
|
213
|
+
try { branch = (await gitRead(tree, ['symbolic-ref', '--quiet', '--short', 'HEAD'], opts)).toString().trim() || null; } catch { /* HEAD tách rời */ }
|
|
214
|
+
// HEAD tách rời: commit chỉ còn worktree giữ — gỡ worktree là mất. Tạo nhánh của job trước.
|
|
215
|
+
if (!branch && status.length && jobId) {
|
|
216
|
+
branch = `aivin/${jobId}`;
|
|
217
|
+
await gitWrite(tree, ['checkout', '-q', '-b', branch], opts);
|
|
218
|
+
}
|
|
219
|
+
if (status.length) {
|
|
220
|
+
await gitWrite(tree, ['add', '-A'], opts);
|
|
221
|
+
await gitWrite(tree, ['commit', '-q', '--no-verify', '-m', message], { ...opts, pre: DELIVERY_IDENT });
|
|
222
|
+
}
|
|
223
|
+
return { branch, commit: await resolveCommit(tree, 'HEAD', opts), committed: !!status.length };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Một tệp chữ mới (chưa theo dõi) dạng khối diff "new file". Tệp nhị phân / quá lớn → chỉ một dòng ghi chú. */
|
|
227
|
+
function newFilePatch(tree, rel) {
|
|
228
|
+
const head = `diff --git a/${rel} b/${rel}\nnew file\n--- /dev/null\n+++ b/${rel}\n`;
|
|
229
|
+
try {
|
|
230
|
+
const abs = path.join(tree, rel);
|
|
231
|
+
if (fs.statSync(abs).size > MAX_UNTRACKED_READ) return `${head}@@ (file larger than ${MAX_UNTRACKED_READ} bytes — not shown) @@\n`;
|
|
232
|
+
const buf = fs.readFileSync(abs);
|
|
233
|
+
if (buf.includes(0)) return `${head}@@ (binary file — not shown) @@\n`;
|
|
234
|
+
const lines = buf.toString('utf8').replace(/\r?\n$/, '').split(/\r?\n/);
|
|
235
|
+
return `${head}@@ -0,0 +1,${lines.length} @@\n${lines.map((l) => `+${l}`).join('\n')}\n`;
|
|
236
|
+
} catch { return ''; }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Ghi toàn bộ thay đổi (đã theo dõi + tệp mới) ra `diff.patch` cho giám khảo / người duyệt. Trả `{ bytes, truncated }`. */
|
|
240
|
+
export async function writePatch(tree, base, untracked, file, opts) {
|
|
241
|
+
let text = (await gitRead(tree, ['diff', '--no-color', '--no-renames', base, '--'], { ...opts, maxBytes: MAX_DIFF_BYTES })).toString('utf8');
|
|
242
|
+
for (const rel of untracked) {
|
|
243
|
+
if (text.length > MAX_PATCH_BYTES) break;
|
|
244
|
+
text += newFilePatch(tree, rel);
|
|
245
|
+
}
|
|
246
|
+
const truncated = Buffer.byteLength(text) > MAX_PATCH_BYTES;
|
|
247
|
+
if (truncated) text = `${Buffer.from(text).subarray(0, MAX_PATCH_BYTES).toString('utf8')}\n… (diff cut at ${MAX_PATCH_BYTES} bytes)\n`;
|
|
248
|
+
fs.writeFileSync(file, text);
|
|
249
|
+
return { bytes: Buffer.byteLength(text), truncated };
|
|
250
|
+
}
|
|
251
|
+
|
|
177
252
|
/** Commit của một ref (đã kiểm là commit), hoặc null. */
|
|
178
253
|
export async function resolveCommit(cwd, ref = 'HEAD', opts) {
|
|
179
254
|
if (!ref || String(ref).startsWith('-')) return null;
|
|
@@ -255,7 +330,7 @@ export async function diffSince(cwd, base, opts) {
|
|
|
255
330
|
for (const text of fs.readFileSync(abs, 'utf8').replace(/\r?\n$/, '').split(/\r?\n/)) added.push({ path: f.path, text });
|
|
256
331
|
} catch { /* tệp vừa bị xoá */ }
|
|
257
332
|
}
|
|
258
|
-
return { files, added, removed };
|
|
333
|
+
return { files, added, removed, untracked };
|
|
259
334
|
}
|
|
260
335
|
|
|
261
336
|
const listed = (items) => (items.length > MAX_LISTED ? [...items.slice(0, MAX_LISTED), `… ${items.length - MAX_LISTED} more`] : items);
|
|
@@ -291,6 +366,13 @@ function coverage({ contract, testCheck, report, junitCases }) {
|
|
|
291
366
|
}
|
|
292
367
|
}
|
|
293
368
|
}
|
|
369
|
+
// Ca agent tự đề xuất (mã tạm NEW-n trong REPORT.md): test đặt tên theo NEW-n được đo như ca auto — Agentic cấp mã CK khi gộp, kèm kết quả.
|
|
370
|
+
for (const n of report?.new_checks || []) {
|
|
371
|
+
if (n.method !== 'auto') continue;
|
|
372
|
+
const runs = junitCases.filter((j) => mentions(j, n.id));
|
|
373
|
+
tests.push({ check_id: n.id, flow_id: n.flow_id, rule_id: n.rule_id, method: 'auto', new: true,
|
|
374
|
+
measured: !runs.length ? 'missing' : runs.some((j) => j.status === 'fail' || j.status === 'error') ? 'fail' : runs.every((j) => j.status === 'skipped') ? 'skipped' : 'pass' });
|
|
375
|
+
}
|
|
294
376
|
const mismatches = tests.filter((t) => t.mismatch).map((t) => `${t.check_id}: reported ${t.reported}, measured ${t.measured}`);
|
|
295
377
|
return { result: check(CheckKind.CHECK_FILE_COVERED, problems.length ? 'fail' : 'pass', { problems: listed(problems), ...(mismatches.length ? { mismatches: listed(mismatches) } : {}) }), tests };
|
|
296
378
|
}
|
|
@@ -304,7 +386,7 @@ export async function measureEvidence({ job, contract, testCheck, jobDir, signal
|
|
|
304
386
|
const evidence = {
|
|
305
387
|
job_id: job.id, contract_id: contract.contract_id, contract_version: contract.version, contract_sha256: job.contractSha,
|
|
306
388
|
feature_group: contract.feature_group, mode: 'shadow', measured_at: new Date().toISOString(),
|
|
307
|
-
base_commit: job.baseCommit || null, head_commit: null, worktree: job.worktree || null,
|
|
389
|
+
base_commit: job.baseCommit || null, head_commit: null, worktree: job.worktree || null, ...(job.delivery ? { delivery: job.delivery } : {}),
|
|
308
390
|
commands: [], diff: null, checks: [], acceptance: [], tests: [], report: null,
|
|
309
391
|
};
|
|
310
392
|
const write = () => {
|
|
@@ -334,15 +416,28 @@ export async function measureEvidence({ job, contract, testCheck, jobDir, signal
|
|
|
334
416
|
diff = await diffSince(tree, base, gitOpts);
|
|
335
417
|
evidence.head_commit = await resolveCommit(tree, 'HEAD', gitOpts);
|
|
336
418
|
evidence.diff = { files: listed(diff.files.map((f) => `${f.status} ${f.path}`)), changed: diff.files.length };
|
|
419
|
+
const patch = await writePatch(tree, base, diff.untracked, path.join(jobDir, PATCH_FILE), gitOpts);
|
|
420
|
+
Object.assign(evidence.diff, { patch_file: PATCH_FILE, patch_bytes: patch.bytes, ...(patch.truncated ? { patch_truncated: true } : {}) });
|
|
337
421
|
} catch (e) {
|
|
338
422
|
evidence.diff = { error: e.message };
|
|
339
423
|
}
|
|
340
424
|
} else evidence.diff = { error: 'not a git repository (or no base commit) — diff checks cannot run' };
|
|
341
425
|
|
|
426
|
+
// Lệnh chuẩn bị (cài phụ thuộc) trước; hỏng một lệnh → không chạy verify (kết quả vô nghĩa), mọi command_passed trượt kèm lý do.
|
|
427
|
+
evidence.setup = [];
|
|
428
|
+
let setupFailed = null;
|
|
429
|
+
for (const cmd of contract.setup || []) {
|
|
430
|
+
if (signal?.aborted || setupFailed) break;
|
|
431
|
+
const res = await runCommand(cmd, { cwd: tree, logFile: path.join(jobDir, 'logs', `${cmd.id}.log`), signal });
|
|
432
|
+
evidence.setup.push({ id: cmd.id, argv: cmd.argv, ...res, log: `logs/${cmd.id}.log` });
|
|
433
|
+
if (res.error || res.timed_out || res.exit_code !== 0) setupFailed = `setup ${cmd.id} failed (${res.error || (res.timed_out ? 'timed out' : `exit code ${res.exit_code}`)})`;
|
|
434
|
+
}
|
|
435
|
+
|
|
342
436
|
// Lệnh kiểm chứng, lần lượt, trong cây của job.
|
|
343
437
|
const junitCases = [];
|
|
344
438
|
for (const cmd of contract.verify) {
|
|
345
439
|
if (signal?.aborted) break;
|
|
440
|
+
if (setupFailed) { evidence.checks.push(check(CheckKind.COMMAND_PASSED, 'fail', { command_id: cmd.id, problems: [setupFailed] })); continue; }
|
|
346
441
|
const res = await runCommand(cmd, { cwd: tree, logFile: path.join(jobDir, 'logs', `${cmd.id}.log`), signal });
|
|
347
442
|
const entry = { id: cmd.id, argv: cmd.argv, ...res, log: `logs/${cmd.id}.log` };
|
|
348
443
|
if (cmd.report) {
|
|
@@ -33,6 +33,7 @@ import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs'
|
|
|
33
33
|
import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
|
|
34
34
|
import { createClipboard } from './clipboard.mjs';
|
|
35
35
|
import { activeAgentRunner, activeLocalLlm, buildTools, toolMap } from './toolHandlers.mjs';
|
|
36
|
+
import { localLlmAccounts } from './localLlmAccounts.mjs';
|
|
36
37
|
import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
|
|
37
38
|
import { createGuiController, detectGui } from './gui/index.mjs';
|
|
38
39
|
import { createWindowsHost } from './gui/windowsHost.mjs';
|
|
@@ -57,6 +58,7 @@ import { castViewerInfo, castViewerLabel, createCastTrust, createDeviceProver }
|
|
|
57
58
|
import { createCastTouchViewers, shouldDrawCursorInFrame } from './desktop/castTouchViewers.mjs';
|
|
58
59
|
import { prepareHumanIdle, readHumanIdleMs } from './desktop/humanIdle.mjs';
|
|
59
60
|
import { prepareIdentify, showIdentify } from './desktop/identifyOverlay.mjs';
|
|
61
|
+
import { createAgentOverlay, prepareAgentOverlay } from './desktop/agentOverlay.mjs';
|
|
60
62
|
import { findWindowTitle, prepareWindowProbe } from './desktop/windowProbe.mjs';
|
|
61
63
|
import { isOwnAddress } from './desktop/desktopWebRtc.mjs';
|
|
62
64
|
import { createConfirmBarrier } from './confirmBarrier.mjs';
|
|
@@ -323,8 +325,10 @@ export async function startRemoteClient(options = {}) {
|
|
|
323
325
|
const guiHost = guiProfile ? createWindowsHost() : null;
|
|
324
326
|
const officeHost = officeApps.length ? createWindowsHost() : null;
|
|
325
327
|
// Không nói cửa sổ mà focus đang ở linh vật (chủ máy vừa gõ vào ô hỏi) → cửa sổ họ đang dùng lúc hỏi (mascot/ask.mjs).
|
|
328
|
+
// Viền màu quanh màn hình + nhãn "AIVIN đang bấm · Excel" khi AI dùng máy (desktop/agentOverlay.mjs).
|
|
329
|
+
const agentOverlay = guiProfile ? createAgentOverlay({ lang: () => mascotLang(process.env, process.platform, creds?.lang) }) : null;
|
|
326
330
|
const gui = guiProfile ? createGuiController({
|
|
327
|
-
fullAccess, host: guiHost, say: (m) => say(chalk.magenta(m)),
|
|
331
|
+
fullAccess, host: guiHost, say: (m) => say(chalk.magenta(m)), indicator: agentOverlay,
|
|
328
332
|
defaultWindow: () => (mascot.pid() ? { avoid_pid: mascot.pid(), fallback: mascotChat?.userWindow()?.window } : null),
|
|
329
333
|
}) : null;
|
|
330
334
|
// Kho hoàn tác (xoá → thùng rác của kho, ghi đè → giữ bản cũ). Máy tính tổ chức: công cụ tệp chạy dưới tài khoản thành viên, không có kho.
|
|
@@ -405,7 +409,12 @@ export async function startRemoteClient(options = {}) {
|
|
|
405
409
|
// Mô hình trên máy (`llm.complete`, công cụ BE-only nên BE biết qua cờ này) — BE dùng cho tier nặng khi phiên chat gắn với máy này.
|
|
406
410
|
if (byName.has('llm.complete')) {
|
|
407
411
|
const agents = activeLocalLlm()?.info().agents || [];
|
|
408
|
-
|
|
412
|
+
// `accounts`: băm tài khoản từng agent — BE tính hạn mức theo tài khoản + nhóm model (localLlmAccounts.mjs).
|
|
413
|
+
if (agents.length) {
|
|
414
|
+
const ids = agents.map((a) => a.id);
|
|
415
|
+
const accounts = localLlmAccounts(ids);
|
|
416
|
+
profile.local_llm = { provider: ids[0], agents: ids, ...(accounts ? { accounts } : {}) };
|
|
417
|
+
}
|
|
409
418
|
}
|
|
410
419
|
// Công cụ chủ máy tắt (`aivin remote policy deny`) không vào danh mục — Planner không lập kế hoạch với nó (gọi tới vẫn bị chặn ở sàn luật).
|
|
411
420
|
const deniedTools = new Set(policyGuard.read().deny_tools);
|
|
@@ -789,6 +798,7 @@ export async function startRemoteClient(options = {}) {
|
|
|
789
798
|
cancelGating([...gating.keys()]);
|
|
790
799
|
browserTunnels?.closeAll();
|
|
791
800
|
guiHost?.close();
|
|
801
|
+
agentOverlay?.close();
|
|
792
802
|
officeHost?.close();
|
|
793
803
|
processes.stopAll();
|
|
794
804
|
activeAgentRunner()?.stopAll('Remote control was paused on this device');
|
|
@@ -863,6 +873,7 @@ export async function startRemoteClient(options = {}) {
|
|
|
863
873
|
void meetings?.shutdown();
|
|
864
874
|
gui?.close();
|
|
865
875
|
guiHost?.close();
|
|
876
|
+
agentOverlay?.close();
|
|
866
877
|
officeHost?.close();
|
|
867
878
|
processes.stopAll();
|
|
868
879
|
// Job của agent lập trình: dừng + ghi hồ sơ (`stopped`) — lần chạy sau `agent.status` vẫn đọc được, nói tiếp bằng session_id.
|
|
@@ -1203,7 +1214,7 @@ export async function startRemoteClient(options = {}) {
|
|
|
1203
1214
|
announceProfile = () => (socket.connected ? announce() : undefined);
|
|
1204
1215
|
socket.on('connect', guarded('connect', async () => {
|
|
1205
1216
|
// Dựng sẵn exe đọc thời gian rảnh tay + exe hiện tên máy (lần đầu ~1–2 s csc) để lần máy chủ hỏi đầu tiên không quá hạn.
|
|
1206
|
-
void prepareHumanIdle().then(() => prepareIdentify()).then(() => prepareWindowProbe());
|
|
1217
|
+
void prepareHumanIdle().then(() => prepareIdentify()).then(() => prepareWindowProbe()).then(() => (guiProfile ? prepareAgentOverlay() : null));
|
|
1207
1218
|
confirmServerCredentialMigration(serverUrl);
|
|
1208
1219
|
await announce();
|
|
1209
1220
|
flushUnsent();
|
|
@@ -5,8 +5,72 @@ 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, parseTestCheck, reportTemplate, sha256 } from './agentContract.mjs';
|
|
9
|
-
|
|
8
|
+
import { parseContract, parseReport, parseTestCheck, reportTemplate, sha256 } from './agentContract.mjs';
|
|
9
|
+
|
|
10
|
+
/** 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
|
+
const REPORT_REPAIR_MS = 5 * 60_000;
|
|
12
|
+
import { commitJobWork, gitRead, gitWrite, globToRegExp, listWorktrees, measureEvidence, resolveCommit, worktreeState } from './agentEvidence.mjs';
|
|
13
|
+
|
|
14
|
+
const MAX_SCOPE_RULES = 400;
|
|
15
|
+
/** Mẫu kiểu gitignore → mẫu luật quyền của Claude Code, neo ở mọi tầng (`package.json` → `**\/package.json`). */
|
|
16
|
+
const anyDepth = (p) => {
|
|
17
|
+
const q = String(p).replace(/\\/g, '/').replace(/^\.?\/+/, '');
|
|
18
|
+
return q.startsWith('**/') ? q : `**/${q}`;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 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
|
|
23
|
+
* đú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.*`)
|
|
24
|
+
* 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.
|
|
25
|
+
*/
|
|
26
|
+
export async function scopeDenyRules(contract, cwd, { gitOpts } = {}) {
|
|
27
|
+
const rules = [];
|
|
28
|
+
const add = (pattern) => { for (const t of ['Edit', 'Write']) rules.push(`${t}(${pattern})`); };
|
|
29
|
+
for (const p of contract.scope?.deny_paths || []) add(anyDepth(p));
|
|
30
|
+
// 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 đó).
|
|
31
|
+
const wildcardName = (p) => { const last = String(p).replace(/\\/g, '/').split('/').filter(Boolean).pop() || ''; return last !== '**' && /[*?[]/.test(last); };
|
|
32
|
+
const direct = (contract.scope?.protected_paths || []).filter((p) => !wildcardName(p));
|
|
33
|
+
const globbed = (contract.scope?.protected_paths || []).filter(wildcardName);
|
|
34
|
+
for (const p of direct) add(anyDepth(p));
|
|
35
|
+
if (globbed.length) {
|
|
36
|
+
let tracked = [];
|
|
37
|
+
try { tracked = (await gitRead(cwd, ['ls-files', '-z'], gitOpts)).toString('utf8').split('\0').filter(Boolean); } catch { /* không phải kho */ }
|
|
38
|
+
const res = globbed.map((g) => globToRegExp(g));
|
|
39
|
+
for (const f of tracked) if (res.some((re) => re.test(f))) add(anyDepth(f));
|
|
40
|
+
}
|
|
41
|
+
return [...new Set(rules)].slice(0, MAX_SCOPE_RULES);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 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. */
|
|
45
|
+
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)$/;
|
|
46
|
+
const MAX_JOB_FILE_CHUNK = 1024 * 1024;
|
|
47
|
+
const MAX_LINK_SCAN = 200_000;
|
|
48
|
+
|
|
49
|
+
/** 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. */
|
|
50
|
+
function hasLinks(dir) {
|
|
51
|
+
const stack = [dir];
|
|
52
|
+
let seen = 0;
|
|
53
|
+
while (stack.length) {
|
|
54
|
+
const d = stack.pop();
|
|
55
|
+
let entries;
|
|
56
|
+
try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
|
|
57
|
+
for (const e of entries) {
|
|
58
|
+
if (++seen > MAX_LINK_SCAN) return true;
|
|
59
|
+
if (e.isSymbolicLink()) return true;
|
|
60
|
+
if (e.isDirectory()) stack.push(path.join(d, e.name));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 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. */
|
|
67
|
+
function utf8Boundary(buf, eof) {
|
|
68
|
+
if (eof) return buf.length;
|
|
69
|
+
let end = buf.length;
|
|
70
|
+
for (let back = 0; back < 4 && end > 0 && (buf[end - 1] & 0xc0) === 0x80; back++) end--;
|
|
71
|
+
if (end > 0 && buf[end - 1] >= 0xc0) end--;
|
|
72
|
+
return end;
|
|
73
|
+
}
|
|
10
74
|
|
|
11
75
|
/**
|
|
12
76
|
* 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
|
|
@@ -249,7 +313,9 @@ function contractPrompt({ jobId, jobDir, contract, hasTestCheck, note }) {
|
|
|
249
313
|
'- Stay inside the current folder for code changes. Do not touch paths the contract denies or protects (you may add new files).',
|
|
250
314
|
'- 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.',
|
|
251
315
|
'- Do not skip, disable or delete existing tests to make things pass.',
|
|
252
|
-
|
|
316
|
+
'- 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.',
|
|
317
|
+
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(' ; ')}.` : '',
|
|
318
|
+
`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:`,
|
|
253
319
|
'',
|
|
254
320
|
reportTemplate({ jobId, contractId: contract.contract_id }),
|
|
255
321
|
note ? `\nNote from Aivin: ${note}` : '',
|
|
@@ -286,7 +352,7 @@ export function createAgentRunner({
|
|
|
286
352
|
|
|
287
353
|
// --- 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).
|
|
288
354
|
const dirOf = (id) => path.join(jobsDir, id);
|
|
289
|
-
const RECORD_KEYS = ['id', 'agent', 'status', 'cwd', 'cwdShown', 'mode', 'model', 'session_id', 'worktree', 'baseCommit', 'contractId', 'contractSha', 'continuedFrom', 'startedAt', 'endedAt', 'result', 'error'];
|
|
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'];
|
|
290
356
|
function persist(j) {
|
|
291
357
|
try {
|
|
292
358
|
fs.mkdirSync(dirOf(j.id), { recursive: true });
|
|
@@ -334,7 +400,10 @@ export function createAgentRunner({
|
|
|
334
400
|
next_text: j.texts.length, next_tool: j.tools.length,
|
|
335
401
|
};
|
|
336
402
|
if (j.contractId) {
|
|
337
|
-
Object.assign(out, {
|
|
403
|
+
Object.assign(out, {
|
|
404
|
+
contract_id: j.contractId, contract_sha256: j.contractSha, job_dir: dirOf(j.id), worktree: j.worktree || undefined,
|
|
405
|
+
...(j.delivery ? { delivery: j.delivery } : {}), ...(j.worktreeRemoved ? { worktree_removed: true } : {}), ...(j.reportRepaired ? { report_repaired: true } : {}),
|
|
406
|
+
});
|
|
338
407
|
if (!RUNNING.has(j.status)) {
|
|
339
408
|
const evidence = readJobFile(j, 'evidence.json', 4 * 1024 * 1024);
|
|
340
409
|
try { if (evidence) out.evidence = JSON.parse(evidence); } catch { /* hỏng → không gửi */ }
|
|
@@ -399,7 +468,11 @@ export function createAgentRunner({
|
|
|
399
468
|
writeLocked('CONTRACT.md', text);
|
|
400
469
|
if (testCheckText !== null) writeLocked('TEST_CHECK.md', testCheckText);
|
|
401
470
|
// 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.
|
|
402
|
-
const deny = [
|
|
471
|
+
const deny = [
|
|
472
|
+
...['CONTRACT.md', 'TEST_CHECK.md', 'evidence.json', 'job.json', 'logs/**'].flatMap((n) => ['Edit', 'Write'].map((t) => `${t}(${claudeAbsPath(path.join(jobDir, n))})`)),
|
|
473
|
+
// 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)),
|
|
475
|
+
];
|
|
403
476
|
return {
|
|
404
477
|
job: {
|
|
405
478
|
contract, contractId: contract.contract_id, contractSha: parsed.sha256, hasTestCheck: testCheckText !== null, testCheckText,
|
|
@@ -426,12 +499,50 @@ export function createAgentRunner({
|
|
|
426
499
|
}
|
|
427
500
|
|
|
428
501
|
/** Agent xong → daemon đo. Lỗi đo không làm mất kết quả của agent. */
|
|
502
|
+
/**
|
|
503
|
+
* 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
|
|
504
|
+
* 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
|
+
*/
|
|
506
|
+
async function repairReport(j) {
|
|
507
|
+
if (!j.respawn || !j.session_id || j.abort.signal.aborted) return;
|
|
508
|
+
const file = path.join(dirOf(j.id), 'REPORT.md');
|
|
509
|
+
let text = null;
|
|
510
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { /* chưa ghi */ }
|
|
511
|
+
const parsed = text === null ? { ok: false, errors: ['REPORT.md was not written'] } : parseReport(text, { contractId: j.contractId });
|
|
512
|
+
if (parsed.ok) return;
|
|
513
|
+
const { adapter, opts, flags, env, bin } = j.respawn;
|
|
514
|
+
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.`;
|
|
517
|
+
await new Promise((resolve) => {
|
|
518
|
+
let child;
|
|
519
|
+
try { child = spawnImpl(bin, argv, { cwd: j.worktree || j.respawn.cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }); } catch { resolve(); return; }
|
|
520
|
+
const timer = setTimeout(() => { try { child.kill(); } catch { /* đã thoát */ } }, REPORT_REPAIR_MS);
|
|
521
|
+
const done = () => { clearTimeout(timer); resolve(); };
|
|
522
|
+
child.stdout?.on?.('data', () => undefined);
|
|
523
|
+
child.stderr?.on?.('data', () => undefined);
|
|
524
|
+
child.stdin?.on?.('error', () => undefined);
|
|
525
|
+
child.on('close', done);
|
|
526
|
+
child.on('error', done);
|
|
527
|
+
child.stdin.end(prompt);
|
|
528
|
+
});
|
|
529
|
+
j.reportRepaired = true;
|
|
530
|
+
}
|
|
531
|
+
|
|
429
532
|
async function finishContractJob(j) {
|
|
430
533
|
if (j.isolate && !j.fixedWorktree) j.worktree = await findJobWorktree(j).catch(() => null);
|
|
534
|
+
// Sau khi biết worktree: phiên của agent nằm ở đó, nói tiếp phải đúng thư mục ấy.
|
|
535
|
+
await repairReport(j).catch(() => undefined);
|
|
536
|
+
// Đầ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
|
+
if (j.worktree && j.contract?.outputs?.some((o) => o.kind === 'git_branch')) {
|
|
538
|
+
try {
|
|
539
|
+
j.delivery = await commitJobWork(j.worktree, `aivin: ${j.contractId} v${j.contract.version} (job ${j.id})`, { jobId: j.id });
|
|
540
|
+
} catch (e) { j.delivery = { error: e.message.slice(0, 300) }; }
|
|
541
|
+
}
|
|
431
542
|
persist(j);
|
|
432
543
|
try {
|
|
433
544
|
const evidence = await measure({
|
|
434
|
-
job: { id: j.id, contractSha: j.contractSha, worktree: j.worktree, cwd: j.cwd, baseCommit: j.baseCommit, mainStateBefore: j.mainStateBefore },
|
|
545
|
+
job: { id: j.id, contractSha: j.contractSha, worktree: j.worktree, cwd: j.cwd, baseCommit: j.baseCommit, mainStateBefore: j.mainStateBefore, delivery: j.delivery },
|
|
435
546
|
contract: j.contract, testCheck: j.hasTestCheck ? parseTestCheck(j.testCheckText) : null, jobDir: dirOf(j.id), signal: j.abort.signal,
|
|
436
547
|
});
|
|
437
548
|
if (j.isolate && !j.worktree) {
|
|
@@ -510,6 +621,8 @@ export function createAgentRunner({
|
|
|
510
621
|
const childEnv = accountDir ? { ...agentEnv(process.env), [adapter.profileEnv]: accountDir } : agentEnv(process.env);
|
|
511
622
|
const child = spawnImpl(binaryOf(adapter).bin, argv, { cwd: spawnCwd || cwd, env: childEnv, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
512
623
|
j.child = child;
|
|
624
|
+
// 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 };
|
|
513
626
|
jobs.set(j.id, j);
|
|
514
627
|
persist(j);
|
|
515
628
|
const wall = wallMs ? setTimeout(() => {
|
|
@@ -587,13 +700,57 @@ export function createAgentRunner({
|
|
|
587
700
|
return view(j);
|
|
588
701
|
}
|
|
589
702
|
|
|
703
|
+
const contractJob = (args) => {
|
|
704
|
+
const j = jobs.get(String(args.job || ''));
|
|
705
|
+
if (!j?.contractId) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No contract job ${args.job}`);
|
|
706
|
+
return j;
|
|
707
|
+
};
|
|
708
|
+
|
|
709
|
+
/** Đọc một tệp của thư mục job theo khúc (BE đưa lên kho file). */
|
|
710
|
+
function jobFile(args) {
|
|
711
|
+
const j = contractJob(args);
|
|
712
|
+
const name = String(args.name || '').replace(/\\/g, '/');
|
|
713
|
+
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');
|
|
714
|
+
const file = path.join(dirOf(j.id), name);
|
|
715
|
+
let fd;
|
|
716
|
+
try { fd = fs.openSync(file, 'r'); } catch { throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${name} is not in job ${j.id}`); }
|
|
717
|
+
try {
|
|
718
|
+
const size = fs.fstatSync(fd).size;
|
|
719
|
+
const offset = Math.max(0, Math.min(size, Math.trunc(Number(args.offset) || 0)));
|
|
720
|
+
const want = Math.max(1, Math.min(MAX_JOB_FILE_CHUNK, Math.trunc(Number(args.max_bytes) || 256 * 1024)));
|
|
721
|
+
const buf = Buffer.alloc(Math.min(want, size - offset));
|
|
722
|
+
const read = buf.length ? fs.readSync(fd, buf, 0, buf.length, offset) : 0;
|
|
723
|
+
const keep = utf8Boundary(buf.subarray(0, read), offset + read >= size);
|
|
724
|
+
return { job: j.id, name, size, offset, bytes: keep, next_offset: offset + keep, eof: offset + keep >= size, text: buf.subarray(0, keep).toString('utf8') };
|
|
725
|
+
} finally { fs.closeSync(fd); }
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* 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
|
|
730
|
+
* tay (xoá cưỡng bức đi theo junction là xoá dữ liệu thật ở nơi khác).
|
|
731
|
+
*/
|
|
732
|
+
async function cleanup(args) {
|
|
733
|
+
const j = contractJob(args);
|
|
734
|
+
if (RUNNING.has(j.status)) throw invalid(`${j.id} is still running`);
|
|
735
|
+
if (!j.worktree || j.worktreeRemoved) return { job: j.id, removed: false, reason: 'no worktree to remove' };
|
|
736
|
+
const wt = j.worktree;
|
|
737
|
+
const known = (await listWorktrees(j.cwd)).some((t) => path.resolve(t).toLowerCase() === path.resolve(wt).toLowerCase());
|
|
738
|
+
if (!known) throw invalid(`${wt} is not a worktree of ${j.cwdShown}`);
|
|
739
|
+
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]);
|
|
742
|
+
j.worktreeRemoved = true;
|
|
743
|
+
persist(j);
|
|
744
|
+
return { job: j.id, removed: true, worktree: wt, ...(j.delivery?.branch ? { branch_kept: j.delivery.branch } : {}) };
|
|
745
|
+
}
|
|
746
|
+
|
|
590
747
|
function sessions(args, _ctx, env = {}) {
|
|
591
748
|
const cwd = args.cwd ? resolveInRoots(env.roots || [], String(args.cwd)) : null;
|
|
592
749
|
return { sessions: loadSessions().filter((s) => (!cwd || s.cwd === cwd) && (!args.agent || s.agent === args.agent)).slice(0, 20) };
|
|
593
750
|
}
|
|
594
751
|
|
|
595
752
|
return {
|
|
596
|
-
run, status, stop, sessions,
|
|
753
|
+
run, status, stop, sessions, jobFile, cleanup,
|
|
597
754
|
profiles: () => ({ profiles: listAgentProfiles(installed(), { root: profilesRoot }) }),
|
|
598
755
|
installed: () => installed().map((a) => ({ id: a.id, label: a.label, version: binaryOf(a).version })),
|
|
599
756
|
/** 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. */
|
|
@@ -626,6 +783,12 @@ export function buildAgentTools(runner) {
|
|
|
626
783
|
{ name: 'agent.stop', group: ToolGroup.PROC, handler: (a) => runner.stop(a),
|
|
627
784
|
description: 'Stop a running coding-agent task.',
|
|
628
785
|
input_schema: schema({ job: str('job from agent.run') }, ['job']) },
|
|
786
|
+
{ name: 'agent.job_file', group: ToolGroup.PROC, read_only: true, internal: true, handler: (a) => runner.jobFile(a),
|
|
787
|
+
description: 'BE-only: read a file of a contract job (REPORT.md, evidence.json, diff.patch, logs/<command>.log…) in chunks from offset.',
|
|
788
|
+
input_schema: schema({ job: str('contract job'), name: str('file name'), offset: num('byte offset'), max_bytes: num('chunk size, max 1048576') }, ['job', 'name']) },
|
|
789
|
+
{ name: 'agent.cleanup', group: ToolGroup.PROC, internal: true, handler: (a) => runner.cleanup(a),
|
|
790
|
+
description: "BE-only: remove a finished contract job's worktree (the delivery branch is kept).",
|
|
791
|
+
input_schema: schema({ job: str('contract job') }, ['job']) },
|
|
629
792
|
{ name: 'agent.profiles', group: ToolGroup.PROC, read_only: true, handler: () => runner.profiles(),
|
|
630
793
|
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.',
|
|
631
794
|
input_schema: schema({}) },
|