@aivin-labs/cli 1.0.66 → 1.0.75
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 +99 -3
- package/bin/lib/remote/agentPreview.mjs +151 -0
- package/bin/lib/remote/client.mjs +24 -6
- package/bin/lib/remote/codingAgents.mjs +953 -636
- package/bin/lib/remote/desktop/agentOverlay.mjs +382 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +3 -1
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +23 -4
- package/bin/lib/remote/desktop/desktopCastSource.mjs +58 -17
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +2 -3
- package/bin/lib/remote/gui/index.mjs +52 -1
- package/bin/lib/remote/localLlm.mjs +626 -533
- package/bin/lib/remote/localLlmAccounts.mjs +57 -0
- package/bin/lib/remote/localLlmLogin.mjs +219 -0
- package/bin/lib/remote/localLlmMembers.mjs +96 -0
- package/bin/lib/remote/mascot/ask.mjs +30 -9
- package/bin/lib/remote/mascot/askHostSource.mjs +22 -8
- package/bin/lib/remote/mascot/emojiSource.mjs +60 -3
- package/bin/lib/remote/mascot/hostSource.mjs +9 -3
- package/bin/lib/remote/mascot/index.mjs +4 -2
- package/bin/lib/remote/mascot/localOpen.mjs +79 -0
- package/bin/lib/remote/mascot/strings.mjs +8 -5
- package/bin/lib/remote/toolHandlers.mjs +26 -2
- 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) {
|
|
@@ -394,7 +489,8 @@ export async function measureEvidence({ job, contract, testCheck, jobDir, signal
|
|
|
394
489
|
|
|
395
490
|
const missing = [];
|
|
396
491
|
for (const o of contract.outputs.filter((x) => x.required)) {
|
|
397
|
-
|
|
492
|
+
// Lỗi khuôn cụ thể đi kèm — vòng sửa nói đúng chỗ sai (17/11/2026: Codex ghi kết quả cho ca mới NEW-x vào `results`, vòng sửa chỉ biết "sai khuôn").
|
|
493
|
+
if (o.kind === 'report_md' && !report?.ok) missing.push(`${o.id}: REPORT.md is ${report ? `not in the agreed format (${(report.errors || []).slice(0, 3).join('; ')})` : 'missing'}`);
|
|
398
494
|
if (o.kind === 'git_branch' && !diff?.files.length) missing.push(`${o.id}: no code change in the job worktree`);
|
|
399
495
|
}
|
|
400
496
|
evidence.checks.push(check(CheckKind.OUTPUTS_COMPLETE, missing.length ? 'fail' : 'pass', missing.length ? { missing } : {}));
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import http from 'http';
|
|
3
|
+
import https from 'https';
|
|
4
|
+
import os from 'os';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
import { spawn } from 'child_process';
|
|
7
|
+
import { LOCAL_BROWSERS, resolveBrowserInstall } from '../localBrowser.mjs';
|
|
8
|
+
import { verifySpawnArgs } from './agentEvidence.mjs';
|
|
9
|
+
import { agentEnv } from './sandbox.mjs';
|
|
10
|
+
import { killWindowsTree } from './winTree.mjs';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Chụp app của một job lập trình đang chạy thật (cổng khớp wireframe, 18/11/2026). BE gọi `agent.preview` SAU khi job đo xong và trước khi gỡ
|
|
14
|
+
* worktree: chạy lệnh mở app (`preview.argv` của hồ sơ dự án) TRONG worktree của job, chờ địa chỉ trả lời, chụp từng đường dẫn bằng Chrome / Edge
|
|
15
|
+
* không giao diện (hồ sơ tạm riêng, không đụng trình duyệt của người dùng), rồi tắt cả cây tiến trình. Ảnh PNG trả về dạng base64 — BE so với
|
|
16
|
+
* wireframe bằng model nhìn.
|
|
17
|
+
*
|
|
18
|
+
* An toàn: địa chỉ phải là máy này (localhost / 127.0.0.1 / ::1); địa chỉ đã có ai trả lời TRƯỚC khi chạy lệnh → từ chối (đang chụp nhầm một
|
|
19
|
+
* app khác, vd bản dev ở thư mục chính). Không ném lỗi khi app không lên — trả `error` để BE ghi "không đo được".
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export const PREVIEW_MAX_SHOTS = 8;
|
|
23
|
+
/** Ảnh thô; base64 phình ~4/3 — giữ dưới MAX_RESULT_BYTES (8 MB) của một kết quả công cụ. */
|
|
24
|
+
const PREVIEW_MAX_TOTAL_BYTES = Math.floor(4.5 * 1024 * 1024);
|
|
25
|
+
const POLL_MS = 500;
|
|
26
|
+
const SHOT_TIMEOUT_MS = 45_000;
|
|
27
|
+
const DEFAULT_READY_MS = 90_000;
|
|
28
|
+
const LOG_TAIL_CHARS = 2000;
|
|
29
|
+
const STOP_WAIT_MS = 8000;
|
|
30
|
+
const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
31
|
+
const VIEWPORTS = { desktop: [1280, 800], tablet: [820, 1180], mobile: [390, 844] };
|
|
32
|
+
|
|
33
|
+
/** Chrome / Edge cài trên máy (ưu tiên Chrome) — null khi không có. */
|
|
34
|
+
export function findPreviewBrowser(resolve = resolveBrowserInstall) {
|
|
35
|
+
for (const b of [...LOCAL_BROWSERS].sort((a, z) => (a.id === 'chrome' ? -1 : z.id === 'chrome' ? 1 : 0))) {
|
|
36
|
+
const found = resolve(b);
|
|
37
|
+
if (found?.exe) return found.exe;
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Kiểm đầu vào: địa chỉ cục bộ http(s), đường dẫn bắt đầu bằng `/`, tối đa PREVIEW_MAX_SHOTS ảnh. Ném Error khi sai. */
|
|
43
|
+
export function normalizePreviewArgs(args) {
|
|
44
|
+
let base;
|
|
45
|
+
try { base = new URL(String(args?.url || '')); } catch { throw new Error('url must be an http(s) address on this computer'); }
|
|
46
|
+
if (!/^https?:$/.test(base.protocol) || !LOCAL_HOSTS.has(base.hostname)) throw new Error('url must be http(s)://localhost (or 127.0.0.1) — the app started for this job');
|
|
47
|
+
const argv = Array.isArray(args?.argv) ? args.argv.map(String) : [];
|
|
48
|
+
if (!argv.length || argv.some((a) => !a || /[\r\n]/.test(a))) throw new Error('argv: the command that starts the app, as words');
|
|
49
|
+
const shots = (Array.isArray(args?.shots) ? args.shots : []).slice(0, PREVIEW_MAX_SHOTS).map((s, i) => {
|
|
50
|
+
const p = String(s?.path || '/');
|
|
51
|
+
if (!p.startsWith('/') || /\s/.test(p)) throw new Error(`shots[${i}].path must start with /`);
|
|
52
|
+
const vp = VIEWPORTS[s?.device] || VIEWPORTS.desktop;
|
|
53
|
+
return { id: String(s?.id || `shot_${i + 1}`).slice(0, 40), url: new URL(p, base).toString(), width: vp[0], height: vp[1] };
|
|
54
|
+
});
|
|
55
|
+
if (!shots.length) throw new Error('shots: at least one { id, path }');
|
|
56
|
+
const ready = Math.min(Math.max(5_000, Number(args?.ready_timeout_ms) || DEFAULT_READY_MS), 600_000);
|
|
57
|
+
return { base: base.toString(), argv, shots, readyTimeoutMs: ready };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Địa chỉ có trả lời HTTP không (bất kỳ mã nào). */
|
|
61
|
+
export function urlResponds(url, { timeoutMs = 3000 } = {}) {
|
|
62
|
+
return new Promise((resolve) => {
|
|
63
|
+
const lib = url.startsWith('https:') ? https : http;
|
|
64
|
+
const req = lib.get(url, { timeout: timeoutMs, rejectUnauthorized: false }, (res) => { res.resume(); resolve(true); });
|
|
65
|
+
req.on('timeout', () => { req.destroy(); resolve(false); });
|
|
66
|
+
req.on('error', () => resolve(false));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function runHeadless(browser, args, { spawnImpl, timeoutMs }) {
|
|
71
|
+
return new Promise((resolve) => {
|
|
72
|
+
let child;
|
|
73
|
+
try { child = spawnImpl(browser, args, { stdio: 'ignore', windowsHide: true }); } catch { resolve(false); return; }
|
|
74
|
+
const timer = setTimeout(() => { try { child.kill(); } catch { /* đã thoát */ } resolve(false); }, timeoutMs);
|
|
75
|
+
child.on('error', () => { clearTimeout(timer); resolve(false); });
|
|
76
|
+
child.on('close', () => { clearTimeout(timer); resolve(true); });
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Chạy app trong `cwd`, chụp các ảnh, tắt app. Trả `{ shots: [{ id, url, png_base64?, error? }], error?, log_tail? }`.
|
|
82
|
+
* `spawnApp` / `spawnBrowser` / `responds` cho test.
|
|
83
|
+
*/
|
|
84
|
+
export async function capturePreview(args, {
|
|
85
|
+
cwd, browser = findPreviewBrowser(), spawnApp = spawn, spawnBrowser = spawn, responds = urlResponds, signal, tmpRoot = os.tmpdir(), env: baseEnv = process.env,
|
|
86
|
+
} = {}) {
|
|
87
|
+
const p = normalizePreviewArgs(args);
|
|
88
|
+
if (!cwd || !fs.existsSync(cwd)) return { error: 'the job worktree is gone — nothing to start', shots: [] };
|
|
89
|
+
if (!browser) return { error: 'no Chrome / Edge on this computer to take screenshots', shots: [] };
|
|
90
|
+
if (await responds(p.base)) return { error: `${p.base} already answers before the app was started — another program uses that address; stop it or change preview.url`, shots: [] };
|
|
91
|
+
|
|
92
|
+
const env = { ...agentEnv(baseEnv), BROWSER: 'none', CI: 'true' };
|
|
93
|
+
let spawnArgs;
|
|
94
|
+
try { spawnArgs = verifySpawnArgs(p.argv, { env }); } catch (e) { return { error: e.message, shots: [] }; }
|
|
95
|
+
const [file, cmdArgs, extra] = spawnArgs;
|
|
96
|
+
const startedAt = Date.now();
|
|
97
|
+
let tail = '';
|
|
98
|
+
let exited = null;
|
|
99
|
+
let app;
|
|
100
|
+
try {
|
|
101
|
+
app = spawnApp(file, cmdArgs, { cwd, env, windowsHide: true, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'], ...extra });
|
|
102
|
+
} catch (e) {
|
|
103
|
+
return { error: `cannot start the app: ${e.message}`, shots: [] };
|
|
104
|
+
}
|
|
105
|
+
const onData = (d) => { tail = (tail + String(d)).slice(-LOG_TAIL_CHARS); };
|
|
106
|
+
app.stdout?.on('data', onData);
|
|
107
|
+
app.stderr?.on('data', onData);
|
|
108
|
+
app.on?.('exit', (code) => { exited = code ?? -1; });
|
|
109
|
+
app.on?.('error', (e) => { exited = -1; tail += `\n${e.message}`; });
|
|
110
|
+
// Tắt app và CHỜ nó thoát (taskkill chạy nền): job sau / bản dev của người dùng dùng lại được địa chỉ ngay.
|
|
111
|
+
const stopApp = async () => {
|
|
112
|
+
if (exited !== null) return;
|
|
113
|
+
const gone = new Promise((r) => { app.once?.('exit', r); setTimeout(r, STOP_WAIT_MS); });
|
|
114
|
+
if (process.platform === 'win32') killWindowsTree(app, startedAt);
|
|
115
|
+
else { try { process.kill(-app.pid, 'SIGKILL'); } catch { try { app.kill('SIGKILL'); } catch { /* đã thoát */ } } }
|
|
116
|
+
await gone;
|
|
117
|
+
// Cây con (vd npm → vite) còn giữ địa chỉ sau khi tiến trình gốc thoát: chờ địa chỉ thôi trả lời.
|
|
118
|
+
for (let i = 0; i < STOP_WAIT_MS / POLL_MS && await responds(p.base); i++) await new Promise((r) => setTimeout(r, POLL_MS));
|
|
119
|
+
};
|
|
120
|
+
const profile = fs.mkdtempSync(path.join(tmpRoot, 'aivin-preview-'));
|
|
121
|
+
try {
|
|
122
|
+
const deadline = Date.now() + p.readyTimeoutMs;
|
|
123
|
+
let up = false;
|
|
124
|
+
while (!up && Date.now() < deadline && exited === null && !signal?.aborted) {
|
|
125
|
+
await new Promise((r) => setTimeout(r, POLL_MS));
|
|
126
|
+
up = await responds(p.base);
|
|
127
|
+
}
|
|
128
|
+
if (signal?.aborted) return { error: 'cancelled', shots: [] };
|
|
129
|
+
if (!up) return { error: exited !== null ? `the app exited (code ${exited}) before ${p.base} answered` : `${p.base} did not answer within ${Math.round(p.readyTimeoutMs / 1000)} s`, shots: [], log_tail: tail.trim() || undefined };
|
|
130
|
+
const shots = [];
|
|
131
|
+
let total = 0;
|
|
132
|
+
for (const s of p.shots) {
|
|
133
|
+
const png = path.join(profile, `${s.id.replace(/[^A-Za-z0-9_-]/g, '_')}.png`);
|
|
134
|
+
await runHeadless(browser, [
|
|
135
|
+
'--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check', '--disable-extensions', '--disable-sync', '--hide-scrollbars',
|
|
136
|
+
// Máy tổ chức: daemon chạy bằng root — Chromium từ chối chạy root khi còn sandbox.
|
|
137
|
+
...(process.getuid?.() === 0 ? ['--no-sandbox'] : []),
|
|
138
|
+
`--user-data-dir=${path.join(profile, 'profile')}`, `--window-size=${s.width},${s.height}`, '--virtual-time-budget=6000', `--screenshot=${png}`, s.url,
|
|
139
|
+
], { spawnImpl: spawnBrowser, timeoutMs: SHOT_TIMEOUT_MS });
|
|
140
|
+
if (!fs.existsSync(png)) { shots.push({ id: s.id, url: s.url, error: 'screenshot failed' }); continue; }
|
|
141
|
+
const buf = fs.readFileSync(png);
|
|
142
|
+
if (total + buf.length > PREVIEW_MAX_TOTAL_BYTES) { shots.push({ id: s.id, url: s.url, error: 'too large to send' }); continue; }
|
|
143
|
+
total += buf.length;
|
|
144
|
+
shots.push({ id: s.id, url: s.url, width: s.width, height: s.height, png_base64: buf.toString('base64') });
|
|
145
|
+
}
|
|
146
|
+
return { shots, log_tail: tail.trim() || undefined };
|
|
147
|
+
} finally {
|
|
148
|
+
await stopApp();
|
|
149
|
+
try { fs.rmSync(profile, { recursive: true, force: true }); } catch { /* thư mục tạm */ }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -32,7 +32,9 @@ import { showOSNotification } from './notify.mjs';
|
|
|
32
32
|
import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs';
|
|
33
33
|
import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
|
|
34
34
|
import { createClipboard } from './clipboard.mjs';
|
|
35
|
-
import { activeAgentRunner, activeLocalLlm, buildTools, toolMap } from './toolHandlers.mjs';
|
|
35
|
+
import { activeAgentRunner, activeLlmLogin, activeLocalLlm, buildTools, toolMap } from './toolHandlers.mjs';
|
|
36
|
+
import { createLocalLlm } from './localLlm.mjs';
|
|
37
|
+
import { localLlmAccounts } from './localLlmAccounts.mjs';
|
|
36
38
|
import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
|
|
37
39
|
import { createGuiController, detectGui } from './gui/index.mjs';
|
|
38
40
|
import { createWindowsHost } from './gui/windowsHost.mjs';
|
|
@@ -57,6 +59,7 @@ import { castViewerInfo, castViewerLabel, createCastTrust, createDeviceProver }
|
|
|
57
59
|
import { createCastTouchViewers, shouldDrawCursorInFrame } from './desktop/castTouchViewers.mjs';
|
|
58
60
|
import { prepareHumanIdle, readHumanIdleMs } from './desktop/humanIdle.mjs';
|
|
59
61
|
import { prepareIdentify, showIdentify } from './desktop/identifyOverlay.mjs';
|
|
62
|
+
import { createAgentOverlay, prepareAgentOverlay } from './desktop/agentOverlay.mjs';
|
|
60
63
|
import { findWindowTitle, prepareWindowProbe } from './desktop/windowProbe.mjs';
|
|
61
64
|
import { isOwnAddress } from './desktop/desktopWebRtc.mjs';
|
|
62
65
|
import { createConfirmBarrier } from './confirmBarrier.mjs';
|
|
@@ -323,8 +326,10 @@ export async function startRemoteClient(options = {}) {
|
|
|
323
326
|
const guiHost = guiProfile ? createWindowsHost() : null;
|
|
324
327
|
const officeHost = officeApps.length ? createWindowsHost() : null;
|
|
325
328
|
// 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).
|
|
329
|
+
// 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).
|
|
330
|
+
const agentOverlay = guiProfile ? createAgentOverlay({ lang: () => mascotLang(process.env, process.platform, creds?.lang) }) : null;
|
|
326
331
|
const gui = guiProfile ? createGuiController({
|
|
327
|
-
fullAccess, host: guiHost, say: (m) => say(chalk.magenta(m)),
|
|
332
|
+
fullAccess, host: guiHost, say: (m) => say(chalk.magenta(m)), indicator: agentOverlay,
|
|
328
333
|
defaultWindow: () => (mascot.pid() ? { avoid_pid: mascot.pid(), fallback: mascotChat?.userWindow()?.window } : null),
|
|
329
334
|
}) : null;
|
|
330
335
|
// 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.
|
|
@@ -397,7 +402,9 @@ export async function startRemoteClient(options = {}) {
|
|
|
397
402
|
return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
|
|
398
403
|
},
|
|
399
404
|
}) : null;
|
|
400
|
-
const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: officeHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard()
|
|
405
|
+
const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: officeHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard(),
|
|
406
|
+
// Máy tính tổ chức: agent làm mô hình chạy dưới tài khoản từng thành viên, bằng đăng nhập của chính họ (localLlmMembers.mjs).
|
|
407
|
+
...(multiUser ? { localLlm: createLocalLlm({ memberMode: true }) } : {}) };
|
|
401
408
|
const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
|
|
402
409
|
host?.start();
|
|
403
410
|
const tools = buildTools(env);
|
|
@@ -405,7 +412,14 @@ export async function startRemoteClient(options = {}) {
|
|
|
405
412
|
// 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
413
|
if (byName.has('llm.complete')) {
|
|
407
414
|
const agents = activeLocalLlm()?.info().agents || [];
|
|
408
|
-
|
|
415
|
+
// `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).
|
|
416
|
+
if (agents.length) {
|
|
417
|
+
const ids = agents.map((a) => a.id);
|
|
418
|
+
// Máy tính tổ chức: mỗi thành viên một tài khoản agent riêng → không có vân tay chung của máy; `per_member` = BE tính đăng nhập +
|
|
419
|
+
// hạn mức theo từng thành viên.
|
|
420
|
+
const accounts = multiUser ? undefined : localLlmAccounts(ids);
|
|
421
|
+
profile.local_llm = { provider: ids[0], agents: ids, ...(accounts ? { accounts } : {}), ...(multiUser ? { per_member: true } : {}) };
|
|
422
|
+
}
|
|
409
423
|
}
|
|
410
424
|
// 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
425
|
const deniedTools = new Set(policyGuard.read().deny_tools);
|
|
@@ -451,7 +465,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
451
465
|
onChoose: (id) => { void mascotChat?.choose(id); },
|
|
452
466
|
onCancel: () => { void mascotChat?.cancel(); },
|
|
453
467
|
onNewChat: () => { void mascotChat?.newChat(); },
|
|
454
|
-
onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
|
|
468
|
+
onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
|
|
469
|
+
onOpenLocal: (id) => mascotChat?.openLocal(id),
|
|
455
470
|
onNotifyFreq: (val) => { mascotChat?.setNotifyFreq(val); },
|
|
456
471
|
// Thả tệp vào bot → đi kèm câu gõ kế tiếp.
|
|
457
472
|
// "Gửi cho AIVIN Bot" từ Explorer có thể tới trước khi ô hỏi dựng xong (daemon vừa được khay mở) → giữ lại, dựng xong thì đính.
|
|
@@ -789,6 +804,7 @@ export async function startRemoteClient(options = {}) {
|
|
|
789
804
|
cancelGating([...gating.keys()]);
|
|
790
805
|
browserTunnels?.closeAll();
|
|
791
806
|
guiHost?.close();
|
|
807
|
+
agentOverlay?.close();
|
|
792
808
|
officeHost?.close();
|
|
793
809
|
processes.stopAll();
|
|
794
810
|
activeAgentRunner()?.stopAll('Remote control was paused on this device');
|
|
@@ -863,11 +879,13 @@ export async function startRemoteClient(options = {}) {
|
|
|
863
879
|
void meetings?.shutdown();
|
|
864
880
|
gui?.close();
|
|
865
881
|
guiHost?.close();
|
|
882
|
+
agentOverlay?.close();
|
|
866
883
|
officeHost?.close();
|
|
867
884
|
processes.stopAll();
|
|
868
885
|
// 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.
|
|
869
886
|
activeAgentRunner()?.stopAll();
|
|
870
887
|
activeLocalLlm()?.stopAll();
|
|
888
|
+
activeLlmLogin()?.closeAll();
|
|
871
889
|
keepAwake.close();
|
|
872
890
|
castAwake.close();
|
|
873
891
|
watches?.closeAll();
|
|
@@ -1203,7 +1221,7 @@ export async function startRemoteClient(options = {}) {
|
|
|
1203
1221
|
announceProfile = () => (socket.connected ? announce() : undefined);
|
|
1204
1222
|
socket.on('connect', guarded('connect', async () => {
|
|
1205
1223
|
// 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());
|
|
1224
|
+
void prepareHumanIdle().then(() => prepareIdentify()).then(() => prepareWindowProbe()).then(() => (guiProfile ? prepareAgentOverlay() : null));
|
|
1207
1225
|
confirmServerCredentialMigration(serverUrl);
|
|
1208
1226
|
await announce();
|
|
1209
1227
|
flushUnsent();
|