@aivin-labs/cli 1.0.68 → 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.
@@ -489,7 +489,8 @@ export async function measureEvidence({ job, contract, testCheck, jobDir, signal
489
489
 
490
490
  const missing = [];
491
491
  for (const o of contract.outputs.filter((x) => x.required)) {
492
- if (o.kind === 'report_md' && !report?.ok) missing.push(`${o.id}: REPORT.md is ${report ? 'not in the agreed format' : 'missing'}`);
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'}`);
493
494
  if (o.kind === 'git_branch' && !diff?.files.length) missing.push(`${o.id}: no code change in the job worktree`);
494
495
  }
495
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,8 @@ 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';
36
37
  import { localLlmAccounts } from './localLlmAccounts.mjs';
37
38
  import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
38
39
  import { createGuiController, detectGui } from './gui/index.mjs';
@@ -401,7 +402,9 @@ export async function startRemoteClient(options = {}) {
401
402
  return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
402
403
  },
403
404
  }) : null;
404
- 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 }) } : {}) };
405
408
  const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
406
409
  host?.start();
407
410
  const tools = buildTools(env);
@@ -412,8 +415,10 @@ export async function startRemoteClient(options = {}) {
412
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).
413
416
  if (agents.length) {
414
417
  const ids = agents.map((a) => a.id);
415
- const accounts = localLlmAccounts(ids);
416
- profile.local_llm = { provider: ids[0], agents: ids, ...(accounts ? { accounts } : {}) };
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 } : {}) };
417
422
  }
418
423
  }
419
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).
@@ -460,7 +465,8 @@ export async function startRemoteClient(options = {}) {
460
465
  onChoose: (id) => { void mascotChat?.choose(id); },
461
466
  onCancel: () => { void mascotChat?.cancel(); },
462
467
  onNewChat: () => { void mascotChat?.newChat(); },
463
- onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
468
+ onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
469
+ onOpenLocal: (id) => mascotChat?.openLocal(id),
464
470
  onNotifyFreq: (val) => { mascotChat?.setNotifyFreq(val); },
465
471
  // Thả tệp vào bot → đi kèm câu gõ kế tiếp.
466
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.
@@ -879,6 +885,7 @@ export async function startRemoteClient(options = {}) {
879
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.
880
886
  activeAgentRunner()?.stopAll();
881
887
  activeLocalLlm()?.stopAll();
888
+ activeLlmLogin()?.closeAll();
882
889
  keepAwake.close();
883
890
  castAwake.close();
884
891
  watches?.closeAll();