@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.
package/bin/cli.mjs CHANGED
@@ -68,7 +68,8 @@ import { MascotText, mascotLang, mascotText } from './lib/remote/mascot/strings.
68
68
  import { DESKTOP_WEBRTC_WORKER_ARG, runDesktopWebRtcWorker } from './lib/remote/desktop/webrtcWorker.mjs';
69
69
  import { DemoScope, UiResult, showMascotDemo, showMascotUi } from './lib/remote/mascot/ui.mjs';
70
70
  import { desktopAppStatus, installDesktopApp, uninstallDesktopApp } from './lib/remote/autoStart.mjs';
71
- import { OpenDisplay, openFile, openText } from './lib/openFile.mjs';
71
+ import { OpenDisplay, openFile, openText, suggestDestinations } from './lib/openFile.mjs';
72
+ import { handoffCreateDoc } from './lib/docHandoff.mjs';
72
73
  import { OPEN_WITH_EXTENSIONS, SAFE_DEFAULT_EXTENSIONS, defaultAssociationsXml, openDefaultAppsSettings } from './lib/remote/desktop/fileAssociation.mjs';
73
74
  import { showOSNotification } from './lib/remote/notify.mjs';
74
75
  import { createMeetingManager, requestMeeting } from './lib/remote/meeting/index.mjs';
@@ -1181,9 +1182,36 @@ program
1181
1182
  .command('open <files...>')
1182
1183
  .description('Open files from this computer in your Aivin Drive (uploads once; the same content reopens the same Drive file). Windows: `aivin desktop install` adds "Open with AIVIN Bot" to Explorer.')
1183
1184
  .option('-w, --workspace <id>', 'Workspace to upload into (default: your personal workspace)')
1185
+ .option('-f, --folder <id>', 'Folder ID inside the workspace on Aivin Drive')
1186
+ .option('--suggest', 'Ask Aivin for the best Drive destination suggestions without uploading')
1187
+ .option('--topic <text>', 'Short document topic/summary (used with --suggest)')
1188
+ .option('--project-name <name>', 'Source project name (used with --suggest)')
1189
+ .option('--json', 'Output JSON (used with --suggest)')
1184
1190
  .option('--tab', 'Open in a normal browser tab instead of its own window')
1185
1191
  .option('--print', 'Print the Drive link instead of opening anything')
1186
1192
  .action(async (files, options) => {
1193
+ if (options.suggest) {
1194
+ try {
1195
+ const res = await suggestDestinations(files[0], {
1196
+ topic: options.topic,
1197
+ projectName: options.projectName,
1198
+ workspace: options.workspace,
1199
+ });
1200
+ if (options.json) {
1201
+ console.log(JSON.stringify(res));
1202
+ } else if (!res.suggestions.length) {
1203
+ console.log(chalk.gray('No suggestions available.'));
1204
+ } else {
1205
+ res.suggestions.forEach((s, i) => {
1206
+ console.log(`${i + 1}. ${chalk.cyan(s.label)} (${s.workspaceId}${s.folderId ? ` / ${s.folderId}` : ''})${s.reason ? ` — ${s.reason}` : ''}`);
1207
+ });
1208
+ }
1209
+ } catch (error) {
1210
+ console.error(chalk.red('❌'), error.message);
1211
+ process.exitCode = 1;
1212
+ }
1213
+ return;
1214
+ }
1187
1215
  // Gọi từ Explorer qua Aivin.exe --open (không có console) → báo bằng thông báo hệ điều hành.
1188
1216
  const toast = process.env.AIVIN_OPEN_UI === 'toast';
1189
1217
  for (const file of files) {
@@ -1207,7 +1235,7 @@ program
1207
1235
  }
1208
1236
  };
1209
1237
  const display = options.print ? OpenDisplay.NONE : options.tab ? OpenDisplay.TAB : OpenDisplay.WINDOW;
1210
- const res = await openFile(file, { workspace: options.workspace, display, onProgress });
1238
+ const res = await openFile(file, { workspace: options.workspace, folder: options.folder, display, onProgress });
1211
1239
  console.log(options.print ? res.url : chalk.green(`✅ ${res.name} → ${res.url}${res.reused ? ' (Drive copy reused)' : ''}${res.viewOnly ? ' (view only, not signed in - closes with its window)' : ''}`));
1212
1240
  } catch (error) {
1213
1241
  console.error(chalk.red('❌'), error.message);
@@ -1217,6 +1245,50 @@ program
1217
1245
  }
1218
1246
  });
1219
1247
 
1248
+ const docCommand = program
1249
+ .command('doc')
1250
+ .description('Hand off business document drafting (docx, xlsx, pptx, md) with source materials to AIVIN Drive');
1251
+
1252
+ docCommand
1253
+ .command('create')
1254
+ .description('Create a document directly on AIVIN Drive using AIVIN AI authoring engine and return the online link immediately')
1255
+ .requiredOption('-p, --prompt <text>', 'What document to draft')
1256
+ .option('-n, --name <title>', 'Optional document title')
1257
+ .option('-e, --ext <type>', 'Document format: docx | xlsx | pptx | md', 'docx')
1258
+ .option('-w, --workspace <id>', 'Target workspace ID (default: personal workspace)')
1259
+ .option('-f, --folder <id>', 'Target Drive folder ID inside the workspace')
1260
+ .option('--grounding <text>', 'Inline verified project facts / summary handed off to AIVIN')
1261
+ .option('--grounding-file <path>', 'UTF-8 file containing verified project facts handed off to AIVIN')
1262
+ .option('--material <path>', 'Attach a source material file (repeatable)', (v, prev) => [...prev, v], [])
1263
+ .option('--lang <lang>', 'Preferred document language (e.g. vi, en)')
1264
+ .option('--json', 'Output result as JSON')
1265
+ .option('--print', 'Print only the AIVIN Drive URL')
1266
+ .action(async (options) => {
1267
+ try {
1268
+ const res = await handoffCreateDoc({
1269
+ prompt: options.prompt,
1270
+ name: options.name,
1271
+ extension: options.ext,
1272
+ workspace: options.workspace,
1273
+ folder: options.folder,
1274
+ grounding: options.grounding,
1275
+ groundingFile: options.groundingFile,
1276
+ materialFiles: options.material,
1277
+ lang: options.lang,
1278
+ });
1279
+ if (options.json) {
1280
+ console.log(JSON.stringify(res));
1281
+ } else if (options.print) {
1282
+ console.log(res.url);
1283
+ } else {
1284
+ console.log(chalk.green(`✅ Created on AIVIN Drive (${res.status}) → ${res.url}`));
1285
+ }
1286
+ } catch (error) {
1287
+ console.error(chalk.red('❌'), error.message);
1288
+ process.exitCode = 1;
1289
+ }
1290
+ });
1291
+
1220
1292
  program
1221
1293
  .command('uninstall')
1222
1294
  .description('Windows: remove Aivin from this computer - the app, the aivin command, its PATH entry and this computer\'s connection to your account. Your data in .aivin stays unless you add --delete-data. Programs & Features runs this too.')
@@ -0,0 +1,111 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import axios from 'axios';
4
+ import { fetchWebUrl } from './context.mjs';
5
+ import { defaultWebUrl } from './servers.mjs';
6
+ import { missionAuthHeaders, missionServerUrl, resolveWorkspace } from './workspace.mjs';
7
+ import { driveOpenUrl, OpenFileError, OpenFileFailure } from './openFile.mjs';
8
+
9
+ const DEFAULT_WEB_URL = 'https://app.aivin.cloud';
10
+ const MAX_MATERIAL_FILES = 12;
11
+ const MAX_MATERIAL_BYTES = 60_000;
12
+ const ALLOWED_EXTS = new Set(['docx', 'xlsx', 'pptx', 'md']);
13
+
14
+ async function resolveWebUrl(serverUrl) {
15
+ return process.env.AIVIN_WEB_URL || (await fetchWebUrl(serverUrl)) || defaultWebUrl(serverUrl) || DEFAULT_WEB_URL;
16
+ }
17
+
18
+ function readUtf8Bounded(filePath, maxChars) {
19
+ const abs = path.resolve(filePath);
20
+ const raw = fs.readFileSync(abs, 'utf8');
21
+ return raw.slice(0, maxChars).trim();
22
+ }
23
+
24
+ /**
25
+ * Bàn giao ngược việc soạn tài liệu nghiệp vụ (docx / xlsx / pptx / md) từ công cụ ngoài (vd LightCode)
26
+ * lên bộ máy soạn thảo AI của AIVIN kèm gói nguyên liệu sự thật.
27
+ * Trả ngay link AIVIN Drive trong lúc AIVIN tiếp tục soạn ở nền.
28
+ */
29
+ export async function handoffCreateDoc({
30
+ prompt,
31
+ name,
32
+ extension = 'docx',
33
+ workspace,
34
+ folder,
35
+ grounding,
36
+ groundingFile,
37
+ materialFiles = [],
38
+ lang,
39
+ serverUrl: customServerUrl,
40
+ auth: customAuth,
41
+ webUrl: customWebUrl,
42
+ } = {}) {
43
+ if (!customAuth && !process.env.API_KEY) throw new OpenFileFailure(OpenFileError.NOT_LOGGED_IN);
44
+ const cleanPrompt = String(prompt || '').trim();
45
+ if (!cleanPrompt) throw new Error('Prompt is required to create a document on AIVIN.');
46
+
47
+ const ext = ALLOWED_EXTS.has(String(extension || '').toLowerCase())
48
+ ? String(extension).toLowerCase()
49
+ : 'docx';
50
+
51
+ const serverUrl = customServerUrl || missionServerUrl();
52
+ const auth = customAuth || missionAuthHeaders();
53
+ const ws = workspace && customServerUrl
54
+ ? { id: workspace }
55
+ : await resolveWorkspace(serverUrl, auth, workspace);
56
+ const workspaceId = String(ws.id || ws._id);
57
+
58
+ let groundingText = typeof grounding === 'string' ? grounding.trim() : '';
59
+ if (!groundingText && groundingFile) {
60
+ groundingText = readUtf8Bounded(groundingFile, 40_000);
61
+ }
62
+
63
+ const files = (Array.isArray(materialFiles) ? materialFiles : [])
64
+ .filter((f) => typeof f === 'string' && f.trim())
65
+ .slice(0, MAX_MATERIAL_FILES);
66
+
67
+ const materials = [];
68
+ for (const file of files) {
69
+ const content = readUtf8Bounded(file, MAX_MATERIAL_BYTES);
70
+ if (!content) continue;
71
+ materials.push({ name: path.basename(file), content });
72
+ }
73
+
74
+ const payload = {
75
+ prompt: cleanPrompt,
76
+ extension: ext,
77
+ ...(name ? { name: String(name).trim().slice(0, 200) } : {}),
78
+ ...(folder ? { folder_id: String(folder).trim() } : {}),
79
+ ...(groundingText ? { grounding: groundingText.slice(0, 40_000) } : {}),
80
+ ...(materials.length ? { materials } : {}),
81
+ ...(lang ? { lang: String(lang).trim() } : {}),
82
+ };
83
+
84
+ let res;
85
+ try {
86
+ res = await axios.post(
87
+ `${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/handoff-create`,
88
+ payload,
89
+ { ...auth, timeout: 60_000 },
90
+ );
91
+ } catch (e) {
92
+ const reason = e?.response?.data?.message || e?.message || e?.code || 'unknown error';
93
+ throw new Error(`AIVIN document handoff failed: ${reason}`, { cause: e });
94
+ }
95
+
96
+ const data = res.data ?? {};
97
+ const fileId = String(data.file_id || data.id || '');
98
+ if (!fileId) throw new Error('AIVIN did not return a file_id for the created document.');
99
+
100
+ const webUrl = customWebUrl || (await resolveWebUrl(serverUrl));
101
+ const url = driveOpenUrl(webUrl, { fileId, workspaceId });
102
+ return {
103
+ url,
104
+ fileId,
105
+ workspaceId,
106
+ ...(data.folder_id ? { folderId: String(data.folder_id) } : folder ? { folderId: String(folder) } : {}),
107
+ name: String(data.name || name || ''),
108
+ extension: String(data.extension || ext),
109
+ status: String(data.status || 'generating'),
110
+ };
111
+ }
@@ -73,9 +73,9 @@ export function fileSha256(buffer) {
73
73
  return createHash('sha256').update(buffer).digest('hex');
74
74
  }
75
75
 
76
- /** Khoá chỉ mục: cùng máy chủ + workspace + nội dung (đổi tài khoản / máy chủ không dùng nhầm tệp của nơi khác). */
77
- export function indexKey({ baseUrl, workspaceId, sha256 }) {
78
- return `${baseUrl}|${workspaceId}|${sha256}`;
76
+ /** Khoá chỉ mục: cùng máy chủ + workspace (+ thư mục nếu có) + nội dung (đổi nơi lưu không dùng nhầm tệp ở nơi khác). */
77
+ export function indexKey({ baseUrl, workspaceId, folderId, sha256 }) {
78
+ return folderId ? `${baseUrl}|${workspaceId}|${folderId}|${sha256}` : `${baseUrl}|${workspaceId}|${sha256}`;
79
79
  }
80
80
 
81
81
  export function readOpenIndex(file = OPEN_INDEX_FILE) {
@@ -123,9 +123,10 @@ async function driveFileExists(serverUrl, auth, { workspaceId, fileId }) {
123
123
  }
124
124
  }
125
125
 
126
- async function uploadToDrive(serverUrl, auth, { workspaceId, name, buffer }, onProgress) {
126
+ async function uploadToDrive(serverUrl, auth, { workspaceId, folderId, name, buffer }, onProgress) {
127
127
  const form = new FormData();
128
128
  form.append('file', new Blob([buffer]), name);
129
+ if (folderId) form.append('folder_id', String(folderId));
129
130
  try {
130
131
  const res = await axios.post(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/upload`, form, {
131
132
  ...auth, maxBodyLength: Infinity, maxContentLength: Infinity, timeout: 10 * 60_000,
@@ -204,29 +205,59 @@ async function resolveWebUrl(serverUrl) {
204
205
  }
205
206
 
206
207
  /**
207
- * Tải (hoặc dùng lại) rồi mở. Trả `{ url, fileId, workspaceId, reused }`; lỗi → OpenFileFailure.
208
+ * Hỏi AIVIN gợi ý 3–5 đích lưu phù hợp nhất trên Drive cho một tệp (không lộ cây thư mục ra ngoài).
209
+ * Trả `{ suggestions: [{ label, workspaceId, workspaceName, folderId?, folderPath?, reason }] }`.
210
+ */
211
+ export async function suggestDestinations(filePath, { topic, projectName, workspace, limit, serverUrl: customServerUrl, auth: customAuth } = {}) {
212
+ if (!customAuth && !process.env.API_KEY) throw new OpenFileFailure(OpenFileError.NOT_LOGGED_IN);
213
+ const serverUrl = customServerUrl || missionServerUrl();
214
+ const auth = customAuth || missionAuthHeaders();
215
+ // Metadata may contain Windows paths even when this process runs on Linux/macOS.
216
+ const fileName = filePath ? path.win32.basename(String(filePath)) : 'document';
217
+ const ext = path.extname(fileName).replace(/^\./, '').toLowerCase() || undefined;
218
+ let workspaceId;
219
+ if (workspace) {
220
+ const ws = await resolveWorkspace(serverUrl, auth, workspace);
221
+ workspaceId = String(ws.id || ws._id);
222
+ }
223
+ const payload = {
224
+ file_name: fileName,
225
+ ...(ext ? { extension: ext } : {}),
226
+ ...(topic ? { topic: String(topic).slice(0, 500) } : {}),
227
+ ...(projectName ? { project_name: String(projectName).slice(0, 150) } : {}),
228
+ ...(workspaceId ? { workspace_id: workspaceId } : {}),
229
+ ...(Number.isInteger(limit) && limit >= 1 ? { limit: Math.min(limit, 8) } : {}),
230
+ };
231
+ const res = await axios.post(`${serverUrl}/fileshare/suggest-destination`, payload, { ...auth, timeout: 25_000 });
232
+ const suggestions = Array.isArray(res.data?.suggestions) ? res.data.suggestions : [];
233
+ return { suggestions };
234
+ }
235
+
236
+ /**
237
+ * Tải (hoặc dùng lại) rồi mở. Trả `{ url, fileId, workspaceId, folderId, reused }`; lỗi → OpenFileFailure.
208
238
  * `display`: OpenDisplay — cửa sổ riêng (mặc định), tab thường, hoặc chỉ trả đường dẫn (--print).
209
239
  */
210
- export async function openLocalFile(filePath, { workspace, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE, onProgress } = {}) {
240
+ export async function openLocalFile(filePath, { workspace, folder, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE, onProgress } = {}) {
211
241
  if (!process.env.API_KEY) throw new OpenFileFailure(OpenFileError.NOT_LOGGED_IN);
212
242
  const local = readLocalFile(filePath);
213
243
  const serverUrl = missionServerUrl();
214
244
  const auth = missionAuthHeaders();
215
245
  const ws = await resolveWorkspace(serverUrl, auth, workspace);
216
246
  const workspaceId = String(ws.id || ws._id);
247
+ const folderId = folder ? String(folder).trim() : undefined;
217
248
  const sha256 = fileSha256(local.buffer);
218
- const key = indexKey({ baseUrl: serverUrl, workspaceId, sha256 });
249
+ const key = indexKey({ baseUrl: serverUrl, workspaceId, folderId, sha256 });
219
250
 
220
251
  const index = readOpenIndex(indexFile);
221
252
  const reusedId = await findReusable(serverUrl, auth, { index, key });
222
- const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, name: local.name, buffer: local.buffer }, onProgress);
253
+ const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, folderId, name: local.name, buffer: local.buffer }, onProgress);
223
254
 
224
- index[key] = { file_id: fileId, workspace_id: workspaceId, name: local.name, path: local.abs, opened_at: new Date().toISOString() };
255
+ index[key] = { file_id: fileId, workspace_id: workspaceId, ...(folderId ? { folder_id: folderId } : {}), name: local.name, path: local.abs, opened_at: new Date().toISOString() };
225
256
  try { writeOpenIndex(index, indexFile); } catch { /* chỉ mất lần dùng lại sau */ }
226
257
 
227
258
  const url = driveOpenUrl(await resolveWebUrl(serverUrl), { fileId, workspaceId });
228
259
  showUrl(url, displayMode);
229
- return { url, fileId, workspaceId, reused: !!reusedId, name: local.name };
260
+ return { url, fileId, workspaceId, ...(folderId ? { folderId } : {}), reused: !!reusedId, name: local.name };
230
261
  }
231
262
 
232
263
  const isAuthRejected = (error) => (error?.cause?.response?.status ?? error?.response?.status) === 401;
@@ -219,6 +219,32 @@ export function parseContract(text, { expectedSha } = {}) {
219
219
  return { ok: !errors.length, errors, contract, body: split.body, sha256: digest };
220
220
  }
221
221
 
222
+ /**
223
+ * Việc khoán cho agent tự đối chiếu (LightCode): câu chữ của từng tiêu chí + các quy tắc nghiệp vụ, lấy từ THÂN hợp đồng (Agentic ghi ở
224
+ * `## Tiêu chí đánh giá` — `- <khóa>: <câu>` — và `## Nghiệp vụ liên quan`). Tiêu chí do máy đo (`check`) và duyệt người (`human`) không đưa cho agent:
225
+ * máy đã đo, người sẽ duyệt — agent tự khai thêm chỉ là tiếng ồn. Trả `{ acceptance, constraints }` (chuỗi rỗng → danh sách rỗng).
226
+ */
227
+ export function contractBrief(body, contract) {
228
+ const sections = new Map();
229
+ let current = null;
230
+ for (const line of String(body || '').replace(/\r\n?/g, '\n').split('\n')) {
231
+ const h = /^##\s+(.+?)\s*$/.exec(line);
232
+ if (h) { current = h[1]; sections.set(current, []); continue; }
233
+ if (/^#\s/.test(line)) { current = null; continue; }
234
+ const item = current && /^\s*[-*]\s+(.+?)\s*$/.exec(line);
235
+ if (item) sections.get(current).push(item[1]);
236
+ }
237
+ const text = new Map();
238
+ for (const entry of sections.get('Tiêu chí đánh giá') || []) {
239
+ const m = /^`?([A-Za-z0-9][A-Za-z0-9_.-]*)`?\s*:\s*(.+)$/.exec(entry);
240
+ if (m) text.set(m[1], m[2]);
241
+ }
242
+ const acceptance = (contract?.acceptance || [])
243
+ .filter((x) => x && !x.check && x.verifier !== 'human')
244
+ .map((x) => (text.get(x.key) ? `${x.key}: ${text.get(x.key)}` : x.key));
245
+ return { acceptance, constraints: (sections.get('Nghiệp vụ liên quan') || []).slice(0, 40) };
246
+ }
247
+
222
248
  /** Các dòng H1..H4 của thân: [{ level, text, line }]. Bỏ qua phần trong khối ```. */
223
249
  function headings(lines) {
224
250
  const out = [];
@@ -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
+ }