@aivin-labs/cli 1.0.75 → 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 +74 -2
- package/bin/lib/docHandoff.mjs +111 -0
- package/bin/lib/openFile.mjs +41 -10
- package/bin/lib/remote/agentContract.mjs +26 -0
- package/bin/lib/remote/client.mjs +68 -7
- package/bin/lib/remote/codingAgents.mjs +1065 -953
- package/bin/lib/remote/constants.mjs +2 -0
- package/bin/lib/remote/ephemeralAuth.mjs +99 -0
- package/bin/lib/remote/lightcodeAgent.mjs +1615 -0
- package/bin/lib/remote/localLlm.mjs +124 -2
- package/bin/lib/remote/localLlmLogin.mjs +293 -219
- package/bin/lib/remote/localLlmMembers.mjs +115 -96
- package/bin/lib/remote/localPolicy.mjs +345 -341
- package/bin/lib/remote/orgComputerLicense.mjs +99 -0
- package/bin/lib/remote/toolHandlers.mjs +18 -2
- package/package.json +1 -1
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
|
+
}
|
package/bin/lib/openFile.mjs
CHANGED
|
@@ -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
|
|
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
|
-
*
|
|
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 = [];
|
|
@@ -32,6 +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 { lightcodeOrgJobsEnabled, lightcodeReadiness, readHeadlessConnector, startLightcodeEventBridge } from './lightcodeAgent.mjs';
|
|
36
|
+
import { sanitizeAuthEnv } from './ephemeralAuth.mjs';
|
|
35
37
|
import { activeAgentRunner, activeLlmLogin, activeLocalLlm, buildTools, toolMap } from './toolHandlers.mjs';
|
|
36
38
|
import { createLocalLlm } from './localLlm.mjs';
|
|
37
39
|
import { localLlmAccounts } from './localLlmAccounts.mjs';
|
|
@@ -46,6 +48,7 @@ import { createWatchManager } from './deviceWatches.mjs';
|
|
|
46
48
|
import { createScheduleManager } from './schedule.mjs';
|
|
47
49
|
import { remoteDebuggingPage } from './dailyBrowser.mjs';
|
|
48
50
|
import { HOME_BASE, SHARED_DIR, createMultiUserHost, isMultiUserMode } from './multiUser.mjs';
|
|
51
|
+
import { LICENSE_RENEW_EVENT, createLicenseRenewHandler } from './orgComputerLicense.mjs';
|
|
49
52
|
import { createAutoUpdater } from './autoUpdate.mjs';
|
|
50
53
|
import { castLeadInConfig, createDesktopCastManager } from './desktop/desktopCast.mjs';
|
|
51
54
|
import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
|
|
@@ -70,6 +73,8 @@ import {
|
|
|
70
73
|
} from '../selfUpdate.mjs';
|
|
71
74
|
import { cliLaunchCommand, detectSupervisor } from './autoStart.mjs';
|
|
72
75
|
|
|
76
|
+
/** Cách nhau bao lâu thì xem lại LightCode đã dùng được chưa (người dùng đăng nhập tài khoản sau khi máy kết nối). */
|
|
77
|
+
const LIGHTCODE_WATCH_MS = 60_000;
|
|
73
78
|
const HEARTBEAT_MS = 20_000;
|
|
74
79
|
// Nhịp nối lại tối đa. Máy cá nhân giãn tới 30 s (nhiều máy cùng dội BE lúc deploy). Cloud Computer (`--multi-user`): một socket / org qua
|
|
75
80
|
// mạng nội bộ, BE có thể đang chờ máy nối về để giao việc — giãn 30 s (+50 % ngẫu nhiên) nghĩa là BE lên lại rồi vẫn chờ tới ~45 s (28/10/2026).
|
|
@@ -136,6 +141,7 @@ export function isValidDeviceCall(call) {
|
|
|
136
141
|
if (call.args !== undefined && call.args !== null && !isPlainObject(call.args)) return false;
|
|
137
142
|
if (call.timeout_ms !== undefined && call.timeout_ms !== null && !Number.isFinite(call.timeout_ms)) return false;
|
|
138
143
|
if (call.user_scope !== undefined && call.user_scope !== null && typeof call.user_scope !== 'string') return false;
|
|
144
|
+
if (call.auth_env !== undefined && call.auth_env !== null && !isPlainObject(call.auth_env)) return false;
|
|
139
145
|
if (call.idem_key !== undefined && call.idem_key !== null && (typeof call.idem_key !== 'string' || call.idem_key.length > 80)) return false;
|
|
140
146
|
if (call.purpose !== undefined && call.purpose !== null && typeof call.purpose !== 'string') return false;
|
|
141
147
|
return true;
|
|
@@ -402,7 +408,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
402
408
|
return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
|
|
403
409
|
},
|
|
404
410
|
}) : null;
|
|
405
|
-
|
|
411
|
+
// Cài xong LightCode (lightcode.install) → chào lại để BE thấy agent mới ngay, không chờ nối lại.
|
|
412
|
+
const env = { announceProfile: () => announceProfile?.(), 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
413
|
// 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
414
|
...(multiUser ? { localLlm: createLocalLlm({ memberMode: true }) } : {}) };
|
|
408
415
|
const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
|
|
@@ -410,17 +417,22 @@ export async function startRemoteClient(options = {}) {
|
|
|
410
417
|
const tools = buildTools(env);
|
|
411
418
|
const byName = toolMap(tools);
|
|
412
419
|
// 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.
|
|
413
|
-
|
|
420
|
+
// Tách thành hàm để gọi lại trong `announce()` mỗi khi LightCode được bật / tắt sau lúc daemon khởi động.
|
|
421
|
+
let lightcodeLlmSent = false;
|
|
422
|
+
const refreshLocalLlmProfile = () => {
|
|
423
|
+
if (!byName.has('llm.complete')) return;
|
|
414
424
|
const agents = activeLocalLlm()?.info().agents || [];
|
|
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
425
|
if (agents.length) {
|
|
417
426
|
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
427
|
const accounts = multiUser ? undefined : localLlmAccounts(ids);
|
|
421
428
|
profile.local_llm = { provider: ids[0], agents: ids, ...(accounts ? { accounts } : {}), ...(multiUser ? { per_member: true } : {}) };
|
|
429
|
+
lightcodeLlmSent = ids.includes('lightcode');
|
|
430
|
+
} else {
|
|
431
|
+
delete profile.local_llm;
|
|
432
|
+
lightcodeLlmSent = false;
|
|
422
433
|
}
|
|
423
|
-
}
|
|
434
|
+
};
|
|
435
|
+
refreshLocalLlmProfile();
|
|
424
436
|
// 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).
|
|
425
437
|
const deniedTools = new Set(policyGuard.read().deny_tools);
|
|
426
438
|
if (deniedTools.has('gui.act')) deniedTools.add('gui.do');
|
|
@@ -431,6 +443,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
431
443
|
const earlyDrops = [];
|
|
432
444
|
let earlyWorkDir = null;
|
|
433
445
|
let announceProfile = null;
|
|
446
|
+
/** Sự cố LightCode đã báo cho BE ở lần chào gần nhất (null = dùng được / chưa biết) — để chào lại đúng lúc nó đổi. */
|
|
447
|
+
let lightcodeIssueSent = null;
|
|
434
448
|
const applyWorkDir = (dir) => { if (mascotChat) mascotChat.setWorkDir(dir); else earlyWorkDir = dir; };
|
|
435
449
|
/** Chủ máy đồng ý mở thêm thư mục: có hiệu lực ngay (công cụ đọc env.roots lúc gọi), báo BE hồ sơ mới, lưu cho các lần chạy sau. */
|
|
436
450
|
const grantRoot = (dir) => {
|
|
@@ -465,7 +479,7 @@ export async function startRemoteClient(options = {}) {
|
|
|
465
479
|
onChoose: (id) => { void mascotChat?.choose(id); },
|
|
466
480
|
onCancel: () => { void mascotChat?.cancel(); },
|
|
467
481
|
onNewChat: () => { void mascotChat?.newChat(); },
|
|
468
|
-
onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
|
|
482
|
+
onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
|
|
469
483
|
onOpenLocal: (id) => mascotChat?.openLocal(id),
|
|
470
484
|
onNotifyFreq: (val) => { mascotChat?.setNotifyFreq(val); },
|
|
471
485
|
// Thả tệp vào bot → đi kèm câu gõ kế tiếp.
|
|
@@ -817,6 +831,31 @@ export async function startRemoteClient(options = {}) {
|
|
|
817
831
|
}
|
|
818
832
|
const pauseWatch = setInterval(checkPauseNow, PAUSE_POLL_MS);
|
|
819
833
|
pauseWatch.unref?.();
|
|
834
|
+
// Người dùng đăng nhập tài khoản AI (hoặc bật/tắt LightCode) sau khi máy đã kết nối → chào lại ngay để BE cập nhật agent và bộ chọn model, không đợi lần nối lại.
|
|
835
|
+
const lightcodeWatch = setInterval(async () => {
|
|
836
|
+
if (stopped || multiUser || !socket.connected) return;
|
|
837
|
+
const hasLightcodeLlmNow = !!(byName.has('llm.complete') && activeLocalLlm()?.info().agents?.some((a) => a.id === 'lightcode'));
|
|
838
|
+
if (hasLightcodeLlmNow !== lightcodeLlmSent) {
|
|
839
|
+
void announceProfile?.();
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
if (!activeAgentRunner()?.installed().some((a) => a.id === 'lightcode')) return;
|
|
843
|
+
const why = await lightcodeReadiness().catch(() => undefined);
|
|
844
|
+
if (why === undefined || (why || null) === lightcodeIssueSent) return;
|
|
845
|
+
void announceProfile?.();
|
|
846
|
+
}, LIGHTCODE_WATCH_MS);
|
|
847
|
+
lightcodeWatch.unref?.();
|
|
848
|
+
// Cầu đẩy sự kiện từ LightCode (`job.finished`, `job.attention` — gồm cả deploy): báo ngay lên BE và hiện thông báo hệ thống khi cần chú ý.
|
|
849
|
+
const lightcodeEventBridge = (!multiUser && process.platform === 'win32') ? startLightcodeEventBridge({
|
|
850
|
+
onEvent: (ev) => {
|
|
851
|
+
if (socket.connected) socket.emit(DeviceEvent.LIGHTCODE_EVENT, ev);
|
|
852
|
+
if (ev?.type === 'job.attention' && !isPaused()) {
|
|
853
|
+
const title = `LightCode · ${String(ev.title || 'Needs attention').slice(0, 80)}`;
|
|
854
|
+
const body = String(ev.data?.summary || ev.data?.kind || 'A LightCode job needs your input').slice(0, 200);
|
|
855
|
+
showOSNotification(title, body);
|
|
856
|
+
}
|
|
857
|
+
},
|
|
858
|
+
}) : null;
|
|
820
859
|
// `aivin remote pause` / nút ở khay / lệnh ngắt cast ở cửa sổ khác: phản ứng ngay khi tệp đổi (fs.watch), không đợi tới 1–2 s của lượt kiểm
|
|
821
860
|
// định kỳ — trong lúc đó màn hình vẫn đang phát cho người xem. Tên tệp có thể vắng (Windows) → kiểm cả hai.
|
|
822
861
|
let configWatcher = null;
|
|
@@ -858,6 +897,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
858
897
|
stopped = true;
|
|
859
898
|
clearInterval(heartbeat);
|
|
860
899
|
clearInterval(pauseWatch);
|
|
900
|
+
clearInterval(lightcodeWatch);
|
|
901
|
+
lightcodeEventBridge?.stop();
|
|
861
902
|
clearInterval(castActionTimer);
|
|
862
903
|
try { configWatcher?.close(); } catch { /* đã đóng */ }
|
|
863
904
|
clearTimeout(confirmTimer);
|
|
@@ -963,6 +1004,22 @@ export async function startRemoteClient(options = {}) {
|
|
|
963
1004
|
const announce = async () => {
|
|
964
1005
|
try {
|
|
965
1006
|
if (!multiUser) profile.update = updateProfile({ enabled: autoUpdateEnabled });
|
|
1007
|
+
refreshLocalLlmProfile();
|
|
1008
|
+
// Agent lập trình chạy được HỢP ĐỒNG trên máy (20/11/2026: gồm LightCode — cài / bật sau khi daemon chạy nên đọc lại mỗi lần chào).
|
|
1009
|
+
// Luôn gửi (kể cả rỗng): BE coi đây là danh sách đầy đủ, không còn đoán "có agent.run là có Claude".
|
|
1010
|
+
// Container: LightCode headless chỉ được quảng bá khi bật cờ AIVIN_LIGHTCODE_ORG_JOBS=1 (mặc định tắt → org dùng Claude Code / Codex).
|
|
1011
|
+
const runner = multiUser ? null : activeAgentRunner();
|
|
1012
|
+
const headlessLc = multiUser && lightcodeOrgJobsEnabled() ? readHeadlessConnector() : null;
|
|
1013
|
+
if (runner || headlessLc) {
|
|
1014
|
+
profile.coding_agents = runner ? runner.installed().map((a) => a.id) : (headlessLc ? ['lightcode'] : []);
|
|
1015
|
+
// LightCode cài rồi mà chưa dùng được (chưa đăng nhập tài khoản AI nào / hết bản quyền) → BE không giao việc cho nó, thay vì thất bại ngay lượt đầu.
|
|
1016
|
+
delete profile.coding_agent_issues;
|
|
1017
|
+
lightcodeIssueSent = null;
|
|
1018
|
+
if (profile.coding_agents.includes('lightcode')) {
|
|
1019
|
+
const why = await lightcodeReadiness().catch(() => null);
|
|
1020
|
+
if (why) { profile.coding_agent_issues = { lightcode: why }; lightcodeIssueSent = why; }
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
966
1023
|
const hello = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.HELLO, { protocol: PROTOCOL_VERSION, profile, catalog_hash: hash, inflight: ledger.heldIds() });
|
|
967
1024
|
const userLang = hello?.user_lang || hello?.lang;
|
|
968
1025
|
if (userLang && mascot.enabled) {
|
|
@@ -1096,6 +1153,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
1096
1153
|
callEnv = host.envFor(call.user_scope);
|
|
1097
1154
|
host.assertQuota(call.tool);
|
|
1098
1155
|
}
|
|
1156
|
+
const authEnv = sanitizeAuthEnv(call.auth_env);
|
|
1157
|
+
if (authEnv) callEnv = { ...callEnv, authEnv };
|
|
1099
1158
|
await localGate(call, tool);
|
|
1100
1159
|
if (!tool.read_only) await waitConfirmBarrier(call);
|
|
1101
1160
|
// Chủ máy có thể vừa tạm dừng trong lúc chờ hộp xác nhận (của chính lời gọi này hoặc của lời gọi khác).
|
|
@@ -1286,6 +1345,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
1286
1345
|
console.log(chalk.red('❌ Máy này đã bị thu hồi quyền điều khiển từ xa.'));
|
|
1287
1346
|
stopForGood();
|
|
1288
1347
|
}));
|
|
1348
|
+
// Gia han ve LightCode: BE gui payload { token, expiresAt? } qua socket khi ve sap het han (< 6h). Handler ghi de tep ve nguyen tu, ack {ok}.
|
|
1349
|
+
if (multiUser) socket.on(LICENSE_RENEW_EVENT, guarded(LICENSE_RENEW_EVENT, (payload, ack) => createLicenseRenewHandler({ log: (msg) => say(chalk.gray(msg)) })(payload, ack)));
|
|
1289
1350
|
socket.on(DeviceEvent.CALLS, guarded(DeviceEvent.CALLS, (payload) => {
|
|
1290
1351
|
// Chỉ nhận / ACK lời gọi đúng dạng — `{ calls: [null] }` từng làm sập daemon (null.call_id trong listener).
|
|
1291
1352
|
const calls = (Array.isArray(payload?.calls) ? payload.calls : []).filter(isValidDeviceCall);
|