@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 +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/agentEvidence.mjs +2 -1
- package/bin/lib/remote/agentPreview.mjs +151 -0
- package/bin/lib/remote/client.mjs +75 -7
- package/bin/lib/remote/codingAgents.mjs +372 -106
- package/bin/lib/remote/constants.mjs +2 -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 +2 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +2 -3
- package/bin/lib/remote/ephemeralAuth.mjs +99 -0
- package/bin/lib/remote/lightcodeAgent.mjs +1615 -0
- package/bin/lib/remote/localLlm.mjs +748 -576
- package/bin/lib/remote/localLlmLogin.mjs +293 -0
- package/bin/lib/remote/localLlmMembers.mjs +115 -0
- package/bin/lib/remote/localPolicy.mjs +345 -341
- 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/orgComputerLicense.mjs +99 -0
- package/bin/lib/remote/toolHandlers.mjs +44 -4
- package/package.json +1 -1
|
@@ -0,0 +1,1615 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { EventEmitter } from 'events';
|
|
6
|
+
import { PassThrough } from 'stream';
|
|
7
|
+
import { execFile, spawn } from 'child_process';
|
|
8
|
+
import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
|
|
9
|
+
import { DeviceToolError, resolveInRoots } from './sandbox.mjs';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* LightCode làm agent thực thi cho hợp đồng lập trình (20/11/2026). Aivin = thầu sơ cấp: lập kế hoạch, phát hành hợp đồng, đo + nghiệm thu;
|
|
13
|
+
* LightCode (ứng dụng desktop độc lập của GOMEE, https://lightcode.live) = bên thực thi trên máy: chạy song song nhiều agent (Claude, Codex,
|
|
14
|
+
* Gemini, OpenCode, Antigravity), tự chuyển tài khoản dự phòng khi hết hạn mức, giữ ngữ cảnh khi đổi tài khoản.
|
|
15
|
+
*
|
|
16
|
+
* Nối qua CỬA CỤC BỘ của LightCode (server/src/aivin/connector.ts bên repo LightCode): `~/.lightcode/connector.json` { port, key, pid } —
|
|
17
|
+
* `POST /connector/v1/jobs` = một lượt, trả NDJSON (init · text · tool · status · result) tới khi lượt xong; đóng kết nối = LightCode dừng
|
|
18
|
+
* lượt (daemon cắt theo thời hạn hợp đồng / agent.stop vẫn hiệu lực). Không có tiến trình con thật: adapter tự dựng một "tiến trình" giả
|
|
19
|
+
* (stdout / stdin / kill / close) nên runner (codingAgents.mjs) dùng nguyên vẹn — worktree, luật cấm, đo bằng chứng, nhắc ghi lại
|
|
20
|
+
* REPORT.md, vòng sửa (nói tiếp phiên bằng session_id LightCode trả về).
|
|
21
|
+
*
|
|
22
|
+
* Quyền: LightCode chạy job KHÔNG người trông (headless) — hỏi quyền giữa chừng được trả lời theo `allowedTools` + luật cấm của hợp đồng,
|
|
23
|
+
* không chờ ai bấm. Luật cấm còn được đưa thẳng cho Claude Code (`--settings`); agent khác của LightCode chỉ bị bắt ở bước đo (diff_in_scope).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export const LIGHTCODE_CONNECTOR_FILE = path.join(os.homedir(), '.lightcode', 'connector.json');
|
|
27
|
+
/**
|
|
28
|
+
* Container Cloud Computer: LightCode chạy headless dưới tài khoản daemon `aivin-lc`; connector.json nằm ở thư mục nhà của daemon.
|
|
29
|
+
* entrypoint.sh đặt biến này; CLI đọc để nối vào cửa loopback mà không cần exe LightCode trên Windows.
|
|
30
|
+
*/
|
|
31
|
+
export const LIGHTCODE_HEADLESS_CONNECTOR_FILE = '/var/lib/aivin-lc/.lightcode/connector.json';
|
|
32
|
+
/**
|
|
33
|
+
* Cờ bật LightCode làm agent chạy việc của THÀNH VIÊN trong Cloud Computer (mặc định TẮT). Daemon `aivin-lc` không đọc được thư mục nhà 0700
|
|
34
|
+
* của thành viên và LightCode chưa có runAs → khi cờ tắt: không khởi động daemon, không quảng bá agent, org dùng đường Claude Code / Codex.
|
|
35
|
+
*/
|
|
36
|
+
export const LIGHTCODE_ORG_JOBS_ENV = 'AIVIN_LIGHTCODE_ORG_JOBS';
|
|
37
|
+
export const lightcodeOrgJobsEnabled = (env = process.env) => String(env?.[LIGHTCODE_ORG_JOBS_ENV] ?? '').trim() === '1';
|
|
38
|
+
export const LIGHTCODE_RELEASES_URL = 'https://lightcode.live/releases';
|
|
39
|
+
export const LIGHTCODE_SITE = 'https://lightcode.live';
|
|
40
|
+
const DOWNLOAD_DIR = path.join(REMOTE_CONFIG_DIR, 'downloads');
|
|
41
|
+
/** Chờ LightCode mở xong cửa cục bộ sau khi bật ứng dụng. */
|
|
42
|
+
const START_WAIT_MS = 90_000;
|
|
43
|
+
const INSTALL_TIMEOUT_MS = 10 * 60_000;
|
|
44
|
+
const MAX_INSTALLER_BYTES = 600 * 1024 * 1024;
|
|
45
|
+
/** Cờ duy nhất của adapter: toàn bộ tuỳ chọn của lượt nằm trong một JSON (không qua shell, không có tiến trình thật). */
|
|
46
|
+
const JOB_FLAG = '--job';
|
|
47
|
+
/** Bản giao thức cửa cục bộ mà adapter này nói (LightCode `GET /info` báo `protocol`); thấp hơn thì chạy kiểu cũ, không detach. */
|
|
48
|
+
export const CLIENT_PROTOCOL = 2;
|
|
49
|
+
/** Job tách khỏi kết nối: LightCode tự dừng nếu không ai theo dõi quá chừng này (daemon khởi động lại / sập). */
|
|
50
|
+
const ORPHAN_MS = 5 * 60_000;
|
|
51
|
+
const RECONNECT_MAX = 40;
|
|
52
|
+
const RECONNECT_BASE_MS = 1500;
|
|
53
|
+
const RECONNECT_CAP_MS = 10_000;
|
|
54
|
+
const STOP_TIMEOUT_MS = 4000;
|
|
55
|
+
const SIG_CHECK_TIMEOUT_MS = 15_000;
|
|
56
|
+
|
|
57
|
+
const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
|
|
58
|
+
const notFound = (msg) => new DeviceToolError(DeviceErrorCode.NOT_FOUND, msg);
|
|
59
|
+
|
|
60
|
+
/** Nơi bộ cài NSIS (một người dùng, mặc định của electron-builder) đặt LightCode, theo thứ tự hay gặp. */
|
|
61
|
+
export function lightcodeExeCandidates({ env = process.env, platform = process.platform } = {}) {
|
|
62
|
+
if (platform !== 'win32') return [];
|
|
63
|
+
const out = [];
|
|
64
|
+
if (env.LOCALAPPDATA) out.push(path.join(env.LOCALAPPDATA, 'Programs', 'LightCode', 'LightCode.exe'));
|
|
65
|
+
for (const pf of [env.ProgramFiles, env['ProgramFiles(x86)']].filter(Boolean)) out.push(path.join(pf, 'LightCode', 'LightCode.exe'));
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function findLightcodeExe(opts = {}) {
|
|
70
|
+
const exists = opts.exists || fs.existsSync;
|
|
71
|
+
return lightcodeExeCandidates(opts).find((p) => exists(p)) || null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function pidAlive(pid) {
|
|
75
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
76
|
+
try { process.kill(pid, 0); return true; } catch (e) { return e?.code === 'EPERM'; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Cửa cục bộ của LightCode đang mở (ứng dụng đang chạy) → { port, key, app_version }, không thì null. */
|
|
80
|
+
export function readConnector({ file = LIGHTCODE_CONNECTOR_FILE, alive = pidAlive } = {}) {
|
|
81
|
+
try {
|
|
82
|
+
const info = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
83
|
+
if (info?.app !== 'LightCode' || !Number.isInteger(info.port) || typeof info.key !== 'string' || !info.key) return null;
|
|
84
|
+
if (!alive(info.pid)) return null;
|
|
85
|
+
return info;
|
|
86
|
+
} catch { return null; }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Headless connector (Cloud Computer): LightCode daemon chạy dưới `aivin-lc`; connector.json ở /var/lib/aivin-lc/.lightcode/connector.json.
|
|
91
|
+
* Không kiểm pid (daemon chạy dưới uid khác, root không cần kill 0 — chỉ kiểm cổng mở là đủ).
|
|
92
|
+
* env.LIGHTCODE_HEADLESS_CONNECTOR_FILE cho phép test/deploy override đường dẫn.
|
|
93
|
+
*/
|
|
94
|
+
export function readHeadlessConnector({ file, env = process.env } = {}) {
|
|
95
|
+
const f = file || env.LIGHTCODE_HEADLESS_CONNECTOR_FILE || LIGHTCODE_HEADLESS_CONNECTOR_FILE;
|
|
96
|
+
try {
|
|
97
|
+
const info = JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
98
|
+
if (info?.app !== 'LightCode' || !Number.isInteger(info.port) || typeof info.key !== 'string' || !info.key) return null;
|
|
99
|
+
return info;
|
|
100
|
+
} catch { return null; }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const GATEWAY_MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* `aiGateway` {baseUrl, apiKey, model, expiresAt} từ BE (quota model mặc định AIVIN) → dạng nội bộ, hoặc undefined khi không có / đã hết hạn.
|
|
107
|
+
* Sai dạng → ném lỗi (không nuốt im lặng). Không bao giờ log / ghi đĩa; khoá chỉ nằm trong bộ nhớ của job.
|
|
108
|
+
*/
|
|
109
|
+
export function normalizeAiGateway(gw, now = Date.now()) {
|
|
110
|
+
if (gw === undefined || gw === null) return undefined;
|
|
111
|
+
const bad = (m) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `aiGateway: ${m}`);
|
|
112
|
+
if (typeof gw !== 'object' || Array.isArray(gw)) throw bad('must be an object');
|
|
113
|
+
const baseUrl = typeof gw.baseUrl === 'string' ? gw.baseUrl.trim() : '';
|
|
114
|
+
const apiKey = typeof gw.apiKey === 'string' ? gw.apiKey.trim() : '';
|
|
115
|
+
const model = typeof gw.model === 'string' ? gw.model.trim() : '';
|
|
116
|
+
let url = null;
|
|
117
|
+
try { url = new URL(baseUrl); } catch { /* báo ở dưới */ }
|
|
118
|
+
if (!url || !/^https?:$/.test(url.protocol)) throw bad('baseUrl must be an http(s) URL');
|
|
119
|
+
if (!apiKey || apiKey.length > 512 || /\s/.test(apiKey)) throw bad('bad apiKey');
|
|
120
|
+
if (!GATEWAY_MODEL_RE.test(model)) throw bad('bad model');
|
|
121
|
+
const exp = typeof gw.expiresAt === 'number' ? gw.expiresAt : Date.parse(String(gw.expiresAt ?? ''));
|
|
122
|
+
if (!Number.isFinite(exp)) throw bad('bad expiresAt');
|
|
123
|
+
if (exp <= now) return undefined; // hết hạn → bỏ, không gửi khoá chết
|
|
124
|
+
return { baseUrl: url.toString().replace(/\/+$/, ''), apiKey, model, expiresAt: new Date(exp).toISOString() };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Tài khoản Linux của thành viên ({uid,gid,home}) mà LightCode chạy CLI của job dưới đó (`run_as`). Chỉ nhận dạng đúng: uid / gid là số nguyên > 0,
|
|
129
|
+
* home là đường dẫn tuyệt đối sạch (không "..", không "//", không dấu "/" cuối). LightCode còn kiểm lại dải uid, chủ sở hữu thư mục, daemon uid.
|
|
130
|
+
*/
|
|
131
|
+
export function normalizeRunAs(runAs) {
|
|
132
|
+
const bad = (m) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `runAs: ${m}`);
|
|
133
|
+
if (!runAs || typeof runAs !== 'object' || Array.isArray(runAs)) throw bad('must be an object { uid, gid, home }');
|
|
134
|
+
for (const k of ['uid', 'gid']) if (!Number.isInteger(runAs[k]) || runAs[k] <= 0) throw bad(`${k} must be a positive integer`);
|
|
135
|
+
const home = runAs.home;
|
|
136
|
+
const clean = typeof home === 'string' && home.length > 1 && home.length <= 4096 && home.startsWith('/') && !home.endsWith('/') && !/[\u0000-\u0020]/.test(home)
|
|
137
|
+
&& !home.includes('//') && !home.split('/').some((seg) => seg === '..' || seg === '.');
|
|
138
|
+
if (!clean) throw bad('home must be a clean absolute path');
|
|
139
|
+
return { uid: runAs.uid, gid: runAs.gid, home };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Cổng AI của job ở dạng LightCode nhận (snake_case); hết hạn giữa chừng (vd. nối lại sau lâu) hoặc hỏng → không có. */
|
|
143
|
+
function gatewayFor(job) {
|
|
144
|
+
let gw;
|
|
145
|
+
try { gw = normalizeAiGateway(job?.aiGateway); } catch { return null; }
|
|
146
|
+
return gw ? { base_url: gw.baseUrl, api_key: gw.apiKey, model: gw.model, expires_at: gw.expiresAt } : null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Tình trạng LightCode trên máy (không gọi mạng). */
|
|
150
|
+
export function lightcodeLocalStatus(opts = {}) {
|
|
151
|
+
const connector = readConnector(opts);
|
|
152
|
+
const exe = findLightcodeExe(opts);
|
|
153
|
+
const platform = opts.platform || process.platform;
|
|
154
|
+
return {
|
|
155
|
+
supported: platform === 'win32',
|
|
156
|
+
installed: !!(connector || exe),
|
|
157
|
+
running: !!connector,
|
|
158
|
+
...(connector?.app_version ? { version: connector.app_version } : {}),
|
|
159
|
+
...(connector?.protocol ? { protocol: connector.protocol } : {}),
|
|
160
|
+
...(exe ? { exe } : {}),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Bật LightCode (nếu chưa chạy) và chờ cửa cục bộ mở. */
|
|
165
|
+
export async function ensureLightcodeRunning({ wait = START_WAIT_MS, spawnImpl = spawn, ...opts } = {}) {
|
|
166
|
+
const ready = readConnector(opts);
|
|
167
|
+
if (ready) return ready;
|
|
168
|
+
const exe = findLightcodeExe(opts);
|
|
169
|
+
if (!exe) throw notFound('LightCode is not installed on this computer — install it with lightcode.install (after the person agrees)');
|
|
170
|
+
const child = spawnImpl(exe, [], { detached: true, stdio: 'ignore', windowsHide: false });
|
|
171
|
+
child.on?.('error', () => undefined);
|
|
172
|
+
child.unref?.();
|
|
173
|
+
const deadline = Date.now() + wait;
|
|
174
|
+
while (Date.now() < deadline) {
|
|
175
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
176
|
+
const info = readConnector(opts);
|
|
177
|
+
if (info) return info;
|
|
178
|
+
}
|
|
179
|
+
throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `LightCode did not open its local connector within ${Math.round(wait / 1000)} s — open LightCode once by hand and try again`);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Mã job + tiêu đề hợp đồng từ đề bài của job có hợp đồng (đề bài trỏ tới `<jobs>/<job>/CONTRACT.md`). */
|
|
183
|
+
/** `verdict` của LightCode (done | partial | blocked | needs_input + từng tiêu chí / ràng buộc / lệnh kiểm tra / tệp bàn giao), rút gọn cho an toàn kích thước. */
|
|
184
|
+
export function slimVerdict(v) {
|
|
185
|
+
const list = (a, f) => (Array.isArray(a) ? a.slice(0, 40).filter((x) => x && typeof x === 'object').map(f) : []);
|
|
186
|
+
const t = (x, n = 300) => String(x ?? '').slice(0, n);
|
|
187
|
+
const deliverables = list(v.deliverables, (d) => ({
|
|
188
|
+
path: t(d.path, 300),
|
|
189
|
+
ok: d.ok === true,
|
|
190
|
+
exists: d.exists === true,
|
|
191
|
+
...(typeof d.size === 'number' ? { size: d.size } : {}),
|
|
192
|
+
...(d.sha256 ? { sha256: t(d.sha256, 80) } : {}),
|
|
193
|
+
...(d.format ? { format: t(d.format, 24) } : {}),
|
|
194
|
+
...(d.problem ? { problem: t(d.problem, 200) } : {}),
|
|
195
|
+
}));
|
|
196
|
+
return {
|
|
197
|
+
status: ['done', 'partial', 'blocked', 'needs_input'].includes(v.status) ? v.status : 'partial',
|
|
198
|
+
report: ['complete', 'partial', 'none', 'not_applicable'].includes(v.report) ? v.report : 'complete',
|
|
199
|
+
criteria: list(v.criteria, (c) => ({ text: t(c.text), met: c.met === true, ...(c.reported === false ? { reported: false } : {}), ...(c.evidence ? { evidence: t(c.evidence) } : {}) })),
|
|
200
|
+
constraints: list(v.constraints, (c) => ({ text: t(c.text), kept: c.kept === true, ...(c.reported === false ? { reported: false } : {}), ...(c.evidence ? { evidence: t(c.evidence) } : {}) })),
|
|
201
|
+
checks: list(v.checks, (c) => ({ cmd: t(c.cmd, 200), ok: c.ok === true, ...(c.skipped ? { skipped: t(c.skipped, 20) } : {}) })),
|
|
202
|
+
...(deliverables.length ? { deliverables } : {}),
|
|
203
|
+
issues: Array.isArray(v.issues) ? v.issues.slice(0, 40).map((x) => t(x)) : [],
|
|
204
|
+
summary: t(v.summary, 1500),
|
|
205
|
+
...(typeof v.cost_usd === 'number' ? { cost_usd: v.cost_usd } : {}),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function slimRisk(r) {
|
|
210
|
+
if (!r || typeof r !== 'object') return undefined;
|
|
211
|
+
const level = ['low', 'medium', 'high'].includes(r.level) ? r.level : 'medium';
|
|
212
|
+
return {
|
|
213
|
+
level,
|
|
214
|
+
auto_merge_ok: r.auto_merge_ok === true,
|
|
215
|
+
reasons: Array.isArray(r.reasons) ? r.reasons.slice(0, 12).map((x) => String(x ?? '').slice(0, 200)) : [],
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function slimGoal(g) {
|
|
220
|
+
if (!g || typeof g !== 'object' || !g.id) return undefined;
|
|
221
|
+
return {
|
|
222
|
+
id: String(g.id).slice(0, 60),
|
|
223
|
+
spent_usd: Number(g.spent_usd) || 0,
|
|
224
|
+
...(typeof g.budget_usd === 'number' ? { budget_usd: g.budget_usd } : {}),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function slimGit(g) {
|
|
229
|
+
if (!g || typeof g !== 'object') return undefined;
|
|
230
|
+
const out = {
|
|
231
|
+
...(typeof g.branch === 'string' && g.branch ? { branch: g.branch.slice(0, 120) } : {}),
|
|
232
|
+
...(typeof g.head === 'string' && g.head ? { head: g.head.slice(0, 64) } : {}),
|
|
233
|
+
...(typeof g.dirty === 'boolean' ? { dirty: g.dirty } : {}),
|
|
234
|
+
...(typeof g.diff_stat === 'string' && g.diff_stat ? { diff_stat: g.diff_stat.slice(0, 800) } : {}),
|
|
235
|
+
...(Array.isArray(g.commits) && g.commits.length ? { commits: g.commits.slice(0, 10).map((c) => String(c ?? '').slice(0, 200)) } : {}),
|
|
236
|
+
};
|
|
237
|
+
return Object.keys(out).length ? out : undefined;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function normalizeDeliverablesArg(list) {
|
|
241
|
+
if (!Array.isArray(list)) return [];
|
|
242
|
+
const out = [];
|
|
243
|
+
for (const item of list) {
|
|
244
|
+
if (typeof item === 'string' && item.trim()) out.push(item.trim().slice(0, 500));
|
|
245
|
+
else if (item && typeof item === 'object' && typeof item.path === 'string' && item.path.trim()) {
|
|
246
|
+
const min = Number(item.min_bytes);
|
|
247
|
+
out.push({ path: item.path.trim().slice(0, 500), ...(Number.isFinite(min) && min > 0 ? { min_bytes: Math.floor(min) } : {}) });
|
|
248
|
+
}
|
|
249
|
+
if (out.length >= 40) break;
|
|
250
|
+
}
|
|
251
|
+
return out;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function contractInfoFromPrompt(prompt) {
|
|
255
|
+
const m = /([A-Za-z]:)?[^\s"']*?[\\/]([a-z0-9]+-[0-9a-f]{8})[\\/]CONTRACT\.md/.exec(String(prompt || ''));
|
|
256
|
+
if (!m) return {};
|
|
257
|
+
const file = m[0];
|
|
258
|
+
const out = { job_id: m[2] };
|
|
259
|
+
try {
|
|
260
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
261
|
+
const id = /^contract_id:\s*["']?([^"'\r\n]+)["']?\s*$/m.exec(text);
|
|
262
|
+
if (id) out.contract_id = id[1].trim();
|
|
263
|
+
const title = /^# (.+)$/m.exec(text.replace(/^---[\s\S]*?\n---\s*\n/, ''));
|
|
264
|
+
if (title) out.title = title[1].trim().slice(0, 120);
|
|
265
|
+
} catch { /* không đọc được — chỉ thiếu nhãn */ }
|
|
266
|
+
return out;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Đọc một luồng NDJSON của LightCode, lọc trùng theo `seq`, chuyển nguyên văn sang `child.stdout`.
|
|
271
|
+
* Trả hàm `consume(stream)` cập nhật trạng thái `{ sessionId, lastSeq, finished }`.
|
|
272
|
+
*/
|
|
273
|
+
function createNdjsonConsumer(child, state, signal) {
|
|
274
|
+
const decoder = new TextDecoder();
|
|
275
|
+
const handleLine = (line) => {
|
|
276
|
+
const trimmed = line.trim();
|
|
277
|
+
if (!trimmed) return;
|
|
278
|
+
let msg = null;
|
|
279
|
+
try { msg = JSON.parse(trimmed); } catch { /* dòng hỏng — chuyển nguyên */ }
|
|
280
|
+
if (msg && Number.isInteger(msg.seq)) {
|
|
281
|
+
if (msg.seq <= state.lastSeq) return;
|
|
282
|
+
state.lastSeq = msg.seq;
|
|
283
|
+
}
|
|
284
|
+
if (msg?.type === 'init' && msg.session_id) state.sessionId = msg.session_id;
|
|
285
|
+
if (msg?.type === 'result') state.finished = true;
|
|
286
|
+
child.stdout.write(`${trimmed}\n`);
|
|
287
|
+
};
|
|
288
|
+
return async (stream) => {
|
|
289
|
+
let buf = '';
|
|
290
|
+
for await (const chunk of stream.body) {
|
|
291
|
+
if (signal.aborted) return;
|
|
292
|
+
buf += decoder.decode(chunk, { stream: true });
|
|
293
|
+
const lines = buf.split('\n');
|
|
294
|
+
buf = lines.pop() ?? '';
|
|
295
|
+
for (const line of lines) handleLine(line);
|
|
296
|
+
}
|
|
297
|
+
if (buf.trim()) handleLine(buf);
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Dựng "tiến trình" giả của LightCode + vòng nối lại khi đứt kết nối (dùng chung cho lượt mới và nối lại sau khi CLI khởi động lại).
|
|
303
|
+
*/
|
|
304
|
+
function createTurnShell({ fetchImpl, peek, sleep, initialSessionId = null, initialLastSeq = -1, initialTarget = null }) {
|
|
305
|
+
const child = new EventEmitter();
|
|
306
|
+
child.stdout = new PassThrough();
|
|
307
|
+
child.stderr = new PassThrough();
|
|
308
|
+
child.stdin = new PassThrough();
|
|
309
|
+
child.pid = undefined;
|
|
310
|
+
const abort = new AbortController();
|
|
311
|
+
const state = { sessionId: initialSessionId, lastSeq: initialLastSeq, finished: false, target: initialTarget };
|
|
312
|
+
let closed = false;
|
|
313
|
+
const close = (code) => {
|
|
314
|
+
if (closed) return;
|
|
315
|
+
closed = true;
|
|
316
|
+
child.stdout.end();
|
|
317
|
+
child.stderr.end();
|
|
318
|
+
// Runner đọc dữ liệu trên 'data' — để luồng xả hết trước 'close'.
|
|
319
|
+
setImmediate(() => child.emit('close', code));
|
|
320
|
+
};
|
|
321
|
+
const failLine = (answer, stopReason) => {
|
|
322
|
+
child.stdout.write(`${JSON.stringify({ type: 'result', ok: false, answer: String(answer).slice(0, 2000), stop_reason: stopReason })}\n`);
|
|
323
|
+
};
|
|
324
|
+
child.kill = () => {
|
|
325
|
+
if (closed) return true;
|
|
326
|
+
// Job tách khỏi kết nối vẫn chạy khi đóng kết nối → dừng thật bằng lệnh riêng (không chờ kết quả).
|
|
327
|
+
if (state.sessionId && state.target) {
|
|
328
|
+
const t = AbortSignal.timeout ? AbortSignal.timeout(STOP_TIMEOUT_MS) : undefined;
|
|
329
|
+
void Promise.resolve(fetchImpl(`http://127.0.0.1:${state.target.port}/connector/v1/sessions/${state.sessionId}/stop`, { method: 'POST', headers: { Authorization: `Bearer ${state.target.key}` }, signal: t })).catch(() => undefined);
|
|
330
|
+
}
|
|
331
|
+
abort.abort();
|
|
332
|
+
close(null);
|
|
333
|
+
return true;
|
|
334
|
+
};
|
|
335
|
+
const consume = createNdjsonConsumer(child, state, abort.signal);
|
|
336
|
+
/** Vòng nối lại vào `/sessions/:id/events?from=<lastSeq+1>` cho đến khi nhận được `result` hoặc mất hẳn lượt. */
|
|
337
|
+
const followUntilDone = async ({ detach, immediate = false }) => {
|
|
338
|
+
let attempts = 0;
|
|
339
|
+
while (!state.finished && !abort.signal.aborted) {
|
|
340
|
+
if (!detach) { failLine('The connection to LightCode closed before the job finished', 'connection_lost'); close(1); return; }
|
|
341
|
+
if (!state.sessionId) { failLine('The connection to LightCode closed before the job started', 'connection_lost'); close(1); return; }
|
|
342
|
+
if (++attempts > RECONNECT_MAX) { failLine('Lost the connection to LightCode and could not get it back', 'connection_lost'); close(1); return; }
|
|
343
|
+
if (!immediate || attempts > 1) await sleep(Math.min(RECONNECT_CAP_MS, RECONNECT_BASE_MS * attempts));
|
|
344
|
+
if (abort.signal.aborted) return;
|
|
345
|
+
const now = peek();
|
|
346
|
+
if (!now) continue; // LightCode đang tắt / bật lại — thử tiếp
|
|
347
|
+
state.target = now;
|
|
348
|
+
try {
|
|
349
|
+
const again = await fetchImpl(`http://127.0.0.1:${now.port}/connector/v1/sessions/${state.sessionId}/events?from=${Math.max(0, state.lastSeq + 1)}`, {
|
|
350
|
+
headers: { Authorization: `Bearer ${now.key}` }, signal: abort.signal,
|
|
351
|
+
});
|
|
352
|
+
if (again.status === 404) {
|
|
353
|
+
// LightCode v2.3+: khởi động lại vẫn lưu kết quả cuối cùng ở GET /sessions/:id → phục hồi thay vì báo mất lượt.
|
|
354
|
+
const snap = await Promise.resolve(fetchImpl(`http://127.0.0.1:${now.port}/connector/v1/sessions/${state.sessionId}`, {
|
|
355
|
+
headers: { Authorization: `Bearer ${now.key}` }, signal: abort.signal,
|
|
356
|
+
})).then((r) => (r?.ok ? r.json() : null)).catch(() => null);
|
|
357
|
+
if (snap?.restarted && snap.last_result && typeof snap.last_result === 'object') {
|
|
358
|
+
const lr = snap.last_result;
|
|
359
|
+
child.stdout.write(`${JSON.stringify({
|
|
360
|
+
type: 'result',
|
|
361
|
+
ok: lr.status === 'done',
|
|
362
|
+
answer: String(lr.summary || 'Recovered final result after LightCode restarted').slice(0, 12_000),
|
|
363
|
+
...(lr.stop_reason ? { stop_reason: lr.stop_reason } : {}),
|
|
364
|
+
...(Array.isArray(lr.questions) && lr.questions.length ? { questions: lr.questions.map((q) => (typeof q === 'string' ? { question: q } : q)) } : {}),
|
|
365
|
+
...(lr.risk ? { risk: { level: lr.risk, auto_merge_ok: lr.auto_merge_ok === true, reasons: [] } } : {}),
|
|
366
|
+
...(typeof lr.fix_rounds === 'number' ? { fix_rounds: lr.fix_rounds } : {}),
|
|
367
|
+
...(typeof lr.cost_usd === 'number' ? { usage: { cost_usd: lr.cost_usd } } : {}),
|
|
368
|
+
...(typeof lr.duration_ms === 'number' ? { duration_ms: lr.duration_ms } : {}),
|
|
369
|
+
restarted: true,
|
|
370
|
+
})}\n`);
|
|
371
|
+
state.finished = true;
|
|
372
|
+
break;
|
|
373
|
+
}
|
|
374
|
+
failLine('LightCode lost this job (it was restarted) — the work in the folder is kept', 'turn_lost');
|
|
375
|
+
close(1);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (!again.ok) continue;
|
|
379
|
+
await consume(again).catch(() => undefined);
|
|
380
|
+
} catch { /* thử lại */ }
|
|
381
|
+
}
|
|
382
|
+
if (abort.signal.aborted) return;
|
|
383
|
+
close(state.finished ? 0 : 1);
|
|
384
|
+
};
|
|
385
|
+
return { child, abort, state, close, failLine, consume, followUntilDone };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* "Tiến trình" của một lượt LightCode: stdin nhận đề bài, stdout là NDJSON của LightCode, kill = dừng lượt (gọi `/sessions/:id/stop`),
|
|
390
|
+
* `close` khi lượt xong / bị dừng. Lỗi trước khi LightCode nhận việc → một dòng `result` lỗi để runner có câu trả lời rõ ràng.
|
|
391
|
+
*
|
|
392
|
+
* Giao thức 2: job tách khỏi kết nối (`detach`) — rớt mạng / daemon khởi động lại không giết agent đang làm dở; mỗi sự kiện có `seq`,
|
|
393
|
+
* nối lại bằng `GET /sessions/:id/events?from=<seq kế>` không mất dòng nào. LightCode bản cũ (không báo protocol ≥ 2) → như trước:
|
|
394
|
+
* đóng kết nối = dừng lượt, không nối lại.
|
|
395
|
+
*/
|
|
396
|
+
export function spawnLightcodeTurn(argv, opts = {}, deps = {}) {
|
|
397
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
398
|
+
const ensure = deps.ensure || ensureLightcodeRunning;
|
|
399
|
+
const peek = deps.peek || (() => readConnector(deps));
|
|
400
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
401
|
+
const { child, abort, state, close, failLine, consume, followUntilDone } = createTurnShell({ fetchImpl, peek, sleep });
|
|
402
|
+
|
|
403
|
+
let job = {};
|
|
404
|
+
const i = argv.indexOf(JOB_FLAG);
|
|
405
|
+
try { job = i >= 0 ? JSON.parse(argv[i + 1]) : {}; } catch { job = {}; }
|
|
406
|
+
let prompt = '';
|
|
407
|
+
child.stdin.setEncoding('utf8');
|
|
408
|
+
child.stdin.on('data', (d) => { prompt += d; });
|
|
409
|
+
child.stdin.on('end', () => {
|
|
410
|
+
void (async () => {
|
|
411
|
+
try {
|
|
412
|
+
const info = await ensure();
|
|
413
|
+
state.target = info;
|
|
414
|
+
if (abort.signal.aborted) return;
|
|
415
|
+
if (Number(info.min_client_protocol) > CLIENT_PROTOCOL) {
|
|
416
|
+
failLine(`LightCode on this computer requires bridge protocol ${info.min_client_protocol}, but Aivin CLI speaks protocol ${CLIENT_PROTOCOL} — update Aivin CLI`, 'protocol_mismatch');
|
|
417
|
+
close(1);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
const detach = Number(info.protocol ?? 1) >= 2;
|
|
421
|
+
const source = { name: 'AIVIN', ...contractInfoFromPrompt(prompt) };
|
|
422
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/jobs`, {
|
|
423
|
+
method: 'POST',
|
|
424
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${info.key}` },
|
|
425
|
+
body: JSON.stringify({
|
|
426
|
+
cwd: opts.cwd, prompt, mode: job.mode, ...(job.model ? { model: job.model } : {}), ...(job.effort ? { effort: job.effort } : {}),
|
|
427
|
+
...(job.provider ? { provider: job.provider } : {}),
|
|
428
|
+
...(job.resume ? { resume: job.resume } : {}), add_dirs: job.addDirs || [], allowed_tools: job.allowedTools || [],
|
|
429
|
+
deny_rules: job.deny || [], source, headless: true,
|
|
430
|
+
// Cổng AI tạm theo từng job (chỉ trong body loopback — không env / đĩa / log); kiểm hạn lại lúc gửi, hết hạn thì bỏ.
|
|
431
|
+
...(gatewayFor(job) ? { ai_gateway: gatewayFor(job) } : {}),
|
|
432
|
+
// Tài khoản Linux của thành viên: LightCode chạy CLI của job dưới uid này (không rơi về daemon).
|
|
433
|
+
...(job.runAs ? { run_as: job.runAs } : {}),
|
|
434
|
+
...(detach && job.acceptance?.length ? { acceptance: job.acceptance } : {}),
|
|
435
|
+
...(detach && job.constraints?.length ? { constraints: job.constraints } : {}),
|
|
436
|
+
...(detach && job.verify?.length ? { verify: job.verify } : {}),
|
|
437
|
+
...(detach && job.clientJobId ? { client_job_id: job.clientJobId } : {}),
|
|
438
|
+
...(detach && job.goalId ? { goal_id: job.goalId } : {}),
|
|
439
|
+
...(detach && job.dependsOn?.length ? { depends_on: job.dependsOn } : {}),
|
|
440
|
+
...(detach && Number.isInteger(job.maxFixRounds) && job.maxFixRounds > 0 ? { max_fix_rounds: job.maxFixRounds } : {}),
|
|
441
|
+
...(detach && job.deliverables?.length ? { deliverables: job.deliverables } : {}),
|
|
442
|
+
...(detach ? {
|
|
443
|
+
detach: true, orphan_ms: ORPHAN_MS, on_question: job.clarify ? 'stop' : 'assume',
|
|
444
|
+
...(job.maxCost > 0 ? { max_cost_usd: job.maxCost } : {}),
|
|
445
|
+
} : {}),
|
|
446
|
+
}),
|
|
447
|
+
signal: abort.signal,
|
|
448
|
+
});
|
|
449
|
+
if (!res.ok) {
|
|
450
|
+
let err = `LightCode answered ${res.status}`;
|
|
451
|
+
let code = 'error';
|
|
452
|
+
try { const b = await res.json(); err = b.error || err; code = b.code || code; } catch { /* không phải JSON */ }
|
|
453
|
+
failLine(err, code);
|
|
454
|
+
close(1);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
await consume(res).catch(() => undefined);
|
|
458
|
+
await followUntilDone({ detach });
|
|
459
|
+
} catch (e) {
|
|
460
|
+
if (abort.signal.aborted) { close(null); return; }
|
|
461
|
+
failLine(e?.message || String(e), e?.code === DeviceErrorCode.NOT_FOUND ? 'not_installed' : 'error');
|
|
462
|
+
close(1);
|
|
463
|
+
}
|
|
464
|
+
})();
|
|
465
|
+
});
|
|
466
|
+
return child;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Nối lại vào một lượt LightCode đang chạy (hoặc vừa chạy xong) sau khi tiến trình AIVIN CLI khởi động lại.
|
|
471
|
+
* Cửa cục bộ LightCode không mở hoặc là bản giao thức cũ (< 2) → trả null để runner đánh dấu `interrupted` như trước.
|
|
472
|
+
*/
|
|
473
|
+
export function reattachLightcodeTurn({ sessionId, lastSeq = -1 } = {}, deps = {}) {
|
|
474
|
+
const peek = deps.peek || (() => readConnector(deps));
|
|
475
|
+
const initial = peek();
|
|
476
|
+
if (!sessionId || !initial || Number(initial.protocol ?? 1) < 2) return null;
|
|
477
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
478
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
479
|
+
const { child, abort, close, failLine, followUntilDone } = createTurnShell({
|
|
480
|
+
fetchImpl, peek, sleep, initialSessionId: sessionId, initialLastSeq: Number.isInteger(lastSeq) ? lastSeq : -1, initialTarget: initial,
|
|
481
|
+
});
|
|
482
|
+
setImmediate(() => {
|
|
483
|
+
void followUntilDone({ detach: true, immediate: true }).catch((e) => {
|
|
484
|
+
if (abort.signal.aborted) { close(null); return; }
|
|
485
|
+
failLine(e?.message || String(e), 'connection_lost');
|
|
486
|
+
close(1);
|
|
487
|
+
});
|
|
488
|
+
});
|
|
489
|
+
return child;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** Tài khoản AI LightCode đã dùng — chỉ gửi dấu băm lên Aivin (như `local_llm.accounts`), không gửi email. */
|
|
493
|
+
export const accountTag = (account) => `acc_${createHash('sha256').update(String(account).trim().toLowerCase()).digest('hex').slice(0, 16)}`;
|
|
494
|
+
|
|
495
|
+
export const LIGHTCODE_ADAPTER = Object.freeze({
|
|
496
|
+
id: 'lightcode',
|
|
497
|
+
label: 'LightCode',
|
|
498
|
+
/** Daemon dựng worktree (`.aivin-worktrees/<job>`); LightCode chạy phiên trong thư mục đó và nhận nó là một phần của dự án. */
|
|
499
|
+
selfWorktree: false,
|
|
500
|
+
/** session_id do LightCode cấp (UUID) — vòng sửa nói tiếp đúng phiên, trên tài khoản nào còn hạn mức. */
|
|
501
|
+
resumable: true,
|
|
502
|
+
/** Không có tài khoản riêng theo hồ sơ — LightCode tự quản nhiều tài khoản + chuyển dự phòng. */
|
|
503
|
+
profileEnv: null,
|
|
504
|
+
/**
|
|
505
|
+
* Cloud Computer (nhiều thành viên): chỉ khi bật cờ AIVIN_LIGHTCODE_ORG_JOBS=1 (mặc định TẮT — xem LIGHTCODE_ORG_JOBS_ENV).
|
|
506
|
+
* Tắt → runAs lọc LightCode ra, org dùng đường Claude Code / Codex cũ.
|
|
507
|
+
* Bật → job LUÔN phải kèm runAs của thành viên (args() từ chối nếu thiếu) — không bao giờ chạy dưới tài khoản daemon.
|
|
508
|
+
*/
|
|
509
|
+
get multiUser() { return lightcodeOrgJobsEnabled(); },
|
|
510
|
+
/** LightCode tự chạy CLI dưới tài khoản thành viên (`run_as`): runner theo thành viên dùng spawn của adapter, không bọc bằng memberSpawner. */
|
|
511
|
+
memberAware: true,
|
|
512
|
+
candidates: () => [],
|
|
513
|
+
/**
|
|
514
|
+
* Có LightCode (đang chạy, hoặc đã cài — bật lên lúc giao việc) → coi như agent đã cài; cờ cố định của adapter.
|
|
515
|
+
* Headless container: kiểm connector của daemon trước; không cần exe LightCode và không giới hạn platform Windows.
|
|
516
|
+
*/
|
|
517
|
+
locate(opts = {}) {
|
|
518
|
+
// Headless daemon trong container: chỉ khi cờ bật (mặc định tắt) — kiểm connector của aivin-lc trước
|
|
519
|
+
const headless = lightcodeOrgJobsEnabled(opts.env || process.env) ? readHeadlessConnector(opts) : null;
|
|
520
|
+
if (headless) return { bin: 'lightcode', version: headless.app_version || '0.0.0', flags: [JOB_FLAG], headless: true };
|
|
521
|
+
// Desktop Windows (thành viên dùng LightCode cá nhân): giữ nguyên hành vi cũ
|
|
522
|
+
if ((opts.platform || process.platform) !== 'win32' && !readConnector(opts)) return null;
|
|
523
|
+
const st = lightcodeLocalStatus(opts);
|
|
524
|
+
if (!st.installed) return null;
|
|
525
|
+
return { bin: 'lightcode', version: st.version || '0.0.0', flags: [JOB_FLAG] };
|
|
526
|
+
},
|
|
527
|
+
args({
|
|
528
|
+
mode, resume, model, effort, addDirs = [], allowedTools = [], settings, budgetUsd, clarify, provider, acceptance, constraints,
|
|
529
|
+
verify, clientJobId, goalId, dependsOn, maxFixRounds, deliverables, aiGateway, runAs,
|
|
530
|
+
}) {
|
|
531
|
+
const deny = settings?.permissions?.deny || [];
|
|
532
|
+
// `provider` = agent bên trong LightCode (claude | codex | gemini…); LightCode tự kiểm — sai tên thì để LightCode chọn.
|
|
533
|
+
const inner = provider && /^[a-z]{3,20}$/.test(String(provider)) ? String(provider) : undefined;
|
|
534
|
+
const fixRounds = Number.isInteger(Number(maxFixRounds)) ? Math.min(3, Math.max(0, Number(maxFixRounds))) : 0;
|
|
535
|
+
const normDeliverables = normalizeDeliverablesArg(deliverables);
|
|
536
|
+
const gateway = normalizeAiGateway(aiGateway);
|
|
537
|
+
// Cloud Computer (cờ bật): thiếu runAs → từ chối, không chạy dưới daemon. Ngoài chế độ đó runAs (nếu có) vẫn được chuyển đi.
|
|
538
|
+
if (lightcodeOrgJobsEnabled() && (runAs === undefined || runAs === null)) {
|
|
539
|
+
throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, "LightCode on an organisation computer needs the member's account (runAs) — refusing to run under the daemon account");
|
|
540
|
+
}
|
|
541
|
+
const member = runAs === undefined || runAs === null ? undefined : normalizeRunAs(runAs);
|
|
542
|
+
const deps = Array.isArray(dependsOn) ? dependsOn.map((d) => String(d ?? '').trim()).filter(Boolean).slice(0, 20) : [];
|
|
543
|
+
return [JOB_FLAG, JSON.stringify({
|
|
544
|
+
mode, ...(resume ? { resume } : {}), ...(model ? { model } : {}), ...(effort ? { effort } : {}), addDirs, allowedTools, deny,
|
|
545
|
+
...(Number(budgetUsd) > 0 ? { maxCost: Number(budgetUsd) } : {}), ...(clarify ? { clarify: true } : {}), ...(inner ? { provider: inner } : {}),
|
|
546
|
+
// Hợp đồng (bàn giao khoán): LightCode tự đối chiếu và trả `verdict` — daemon vẫn là bên đo cuối cùng.
|
|
547
|
+
...(Array.isArray(acceptance) && acceptance.length ? { acceptance: acceptance.map(String).slice(0, 40) } : {}),
|
|
548
|
+
...(Array.isArray(constraints) && constraints.length ? { constraints: constraints.map(String).slice(0, 40) } : {}),
|
|
549
|
+
...(Array.isArray(verify) && verify.length ? { verify: verify.map(String).slice(0, 12) } : {}),
|
|
550
|
+
...(clientJobId ? { clientJobId: String(clientJobId).trim().slice(0, 120) } : {}),
|
|
551
|
+
...(goalId ? { goalId: String(goalId).trim().slice(0, 60) } : {}),
|
|
552
|
+
...(deps.length ? { dependsOn: deps } : {}),
|
|
553
|
+
...(fixRounds > 0 ? { maxFixRounds: fixRounds } : {}),
|
|
554
|
+
...(normDeliverables.length ? { deliverables: normDeliverables } : {}),
|
|
555
|
+
...(gateway ? { aiGateway: gateway } : {}),
|
|
556
|
+
...(member ? { runAs: member } : {}),
|
|
557
|
+
})];
|
|
558
|
+
},
|
|
559
|
+
spawn: (bin, argv, opts) => {
|
|
560
|
+
// Headless container: dung readHeadlessConnector lam peek/ensure de khong can exe LightCode tren Linux.
|
|
561
|
+
if (lightcodeOrgJobsEnabled()) {
|
|
562
|
+
// Chặn lần cuối: argv không có runAs hợp lệ thì không chạm tới daemon (args() đã kiểm; đây là lưới an toàn cho đường gọi trực tiếp).
|
|
563
|
+
let job = {};
|
|
564
|
+
try { job = JSON.parse(argv[argv.indexOf(JOB_FLAG) + 1]); } catch { /* thiếu → từ chối ở dưới */ }
|
|
565
|
+
normalizeRunAs(job?.runAs);
|
|
566
|
+
return spawnLightcodeTurn(argv, opts, {
|
|
567
|
+
peek: () => readHeadlessConnector(),
|
|
568
|
+
ensure: () => {
|
|
569
|
+
const c = readHeadlessConnector();
|
|
570
|
+
if (c) return Promise.resolve(c);
|
|
571
|
+
return Promise.reject(new DeviceToolError(DeviceErrorCode.NOT_FOUND, 'LightCode headless daemon is not running in this container'));
|
|
572
|
+
},
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
return spawnLightcodeTurn(argv, opts);
|
|
576
|
+
},
|
|
577
|
+
reattach: (job, deps) => reattachLightcodeTurn({ sessionId: job?.session_id, lastSeq: Number.isInteger(job?.last_seq) ? job.last_seq : -1 }, deps),
|
|
578
|
+
/** Một dòng NDJSON của LightCode → cập nhật việc; trả đoạn chữ đáng đẩy lên Aivin. */
|
|
579
|
+
parse(job, msg) {
|
|
580
|
+
if (Number.isInteger(msg.seq) && (job.last_seq === undefined || msg.seq > job.last_seq)) job.last_seq = msg.seq;
|
|
581
|
+
if (msg.type === 'init') {
|
|
582
|
+
if (msg.session_id && !job.session_id) job.session_id = msg.session_id;
|
|
583
|
+
job.lightcode = { thread_id: msg.thread_id, project_id: msg.project_id, version: msg.app_version, protocol: msg.protocol };
|
|
584
|
+
return '';
|
|
585
|
+
}
|
|
586
|
+
if (msg.type === 'text' && typeof msg.text === 'string' && msg.text.trim()) { job.texts.push(msg.text); return msg.text; }
|
|
587
|
+
if (msg.type === 'tool' && typeof msg.text === 'string') { job.tools.push(msg.text.slice(0, 200)); return msg.text; }
|
|
588
|
+
if (msg.type === 'status' && typeof msg.text === 'string') return `⏳ ${msg.text}`;
|
|
589
|
+
if (msg.type === 'progress' && msg.progress && typeof msg.progress === 'object') {
|
|
590
|
+
const p = msg.progress;
|
|
591
|
+
job.progress = {
|
|
592
|
+
files_changed: p.files_changed, files: Array.isArray(p.files) ? p.files.slice(0, 30) : [], insertions: p.insertions, deletions: p.deletions,
|
|
593
|
+
tool_calls: p.tool_calls, tests_run: p.tests_run, elapsed_ms: p.elapsed_ms, ...(p.violations?.length ? { violations: p.violations.slice(0, 20) } : {}),
|
|
594
|
+
};
|
|
595
|
+
return `📊 ${p.files_changed ?? 0} file(s) changed (+${p.insertions ?? 0}/-${p.deletions ?? 0}), ${p.tests_run ?? 0} test run(s)`;
|
|
596
|
+
}
|
|
597
|
+
if (msg.type === 'question' && Array.isArray(msg.questions)) {
|
|
598
|
+
job.questions = [...(job.questions || []), ...msg.questions].slice(0, 12);
|
|
599
|
+
return `❓ ${msg.questions.map((q) => q.question).join(' / ').slice(0, 300)}`;
|
|
600
|
+
}
|
|
601
|
+
if (msg.type === 'intervention') {
|
|
602
|
+
job.intervened = true;
|
|
603
|
+
return `👤 A person took part in LightCode: ${String(msg.text || '').slice(0, 160)}`;
|
|
604
|
+
}
|
|
605
|
+
if (msg.type === 'result') {
|
|
606
|
+
job.result = {
|
|
607
|
+
ok: msg.ok === true, answer: String(msg.answer ?? '').slice(0, 12_000),
|
|
608
|
+
...(msg.provider ? { provider: msg.provider } : {}), ...(msg.account ? { account: accountTag(msg.account) } : {}),
|
|
609
|
+
...(msg.agent ? { inner_agent: msg.agent } : {}),
|
|
610
|
+
...(typeof msg.duration_ms === 'number' ? { duration_ms: msg.duration_ms } : {}),
|
|
611
|
+
...(msg.stop_reason ? { stop_reason: msg.stop_reason } : {}),
|
|
612
|
+
...(msg.usage && typeof msg.usage.cost_usd === 'number' ? { cost_usd: msg.usage.cost_usd, usage: { cost_usd: msg.usage.cost_usd, tokens: msg.usage.tokens, ...(msg.usage.approx ? { approx: true } : {}) } } : {}),
|
|
613
|
+
...(Array.isArray(msg.quota) && msg.quota.length ? {
|
|
614
|
+
quota: msg.quota.slice(0, 6).filter((q) => q && typeof q === 'object').map((q) => ({
|
|
615
|
+
provider: String(q.provider || ''),
|
|
616
|
+
...(typeof q.five_hour_used_pct === 'number' ? { five_hour_used_pct: q.five_hour_used_pct } : {}),
|
|
617
|
+
...(typeof q.weekly_used_pct === 'number' ? { weekly_used_pct: q.weekly_used_pct } : {}),
|
|
618
|
+
...(typeof q.resets_at === 'string' ? { resets_at: q.resets_at } : {}),
|
|
619
|
+
...(q.account ? { account: accountTag(q.account) } : {}),
|
|
620
|
+
})),
|
|
621
|
+
} : {}),
|
|
622
|
+
...(Array.isArray(msg.questions) && msg.questions.length ? { questions: msg.questions.slice(0, 12) } : job.questions?.length ? { questions: job.questions } : {}),
|
|
623
|
+
...(Array.isArray(msg.violations) && msg.violations.length ? { violations: msg.violations.slice(0, 20) } : {}),
|
|
624
|
+
...(msg.intervened || job.intervened ? { intervened: true } : {}),
|
|
625
|
+
...(msg.restarted ? { restarted: true } : {}),
|
|
626
|
+
...(msg.verdict && typeof msg.verdict === 'object' ? { verdict: slimVerdict(msg.verdict) } : {}),
|
|
627
|
+
...(slimRisk(msg.risk) ? { risk: slimRisk(msg.risk) } : {}),
|
|
628
|
+
...(slimGoal(msg.goal) ? { goal: slimGoal(msg.goal) } : {}),
|
|
629
|
+
...(slimGit(msg.git) ? { git: slimGit(msg.git) } : {}),
|
|
630
|
+
...(typeof msg.fix_rounds === 'number' && msg.fix_rounds > 0 ? { fix_rounds: msg.fix_rounds } : {}),
|
|
631
|
+
...(Array.isArray(msg.permission_denials) && msg.permission_denials.length ? { permission_denials: msg.permission_denials.slice(0, 20) } : {}),
|
|
632
|
+
};
|
|
633
|
+
if (msg.progress) job.progress = job.progress ? { ...job.progress, ...msg.progress } : msg.progress;
|
|
634
|
+
if (msg.provider) job.model = msg.model ? `${msg.provider}:${msg.model}` : msg.provider;
|
|
635
|
+
}
|
|
636
|
+
return '';
|
|
637
|
+
},
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
// --- Cài đặt -------------------------------------------------------------------------------------------------------------------------
|
|
641
|
+
|
|
642
|
+
/** `latest.yml` của electron-builder → { version, file, sha512, size }. */
|
|
643
|
+
export function parseLatestYml(text) {
|
|
644
|
+
const get = (k) => new RegExp(`^${k}:\\s*['"]?([^'"\\r\\n]+)['"]?\\s*$`, 'm').exec(String(text || ''))?.[1]?.trim();
|
|
645
|
+
const version = get('version');
|
|
646
|
+
const file = get('path');
|
|
647
|
+
const sha512 = get('sha512');
|
|
648
|
+
const size = Number(/^\s+size:\s*(\d+)/m.exec(String(text || ''))?.[1]) || undefined;
|
|
649
|
+
if (!version || !file || !sha512 || !/^[\w.-]+\.exe$/i.test(file)) return null;
|
|
650
|
+
return { version, file, sha512, ...(size ? { size } : {}) };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async function downloadVerified(url, dest, sha512, { fetchImpl = globalThis.fetch, onProgress, signal } = {}) {
|
|
654
|
+
const res = await fetchImpl(url, { signal, redirect: 'follow' });
|
|
655
|
+
if (!res.ok || !res.body) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Download failed (${res.status}) ${url}`);
|
|
656
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
657
|
+
const tmp = `${dest}.part`;
|
|
658
|
+
const out = fs.createWriteStream(tmp);
|
|
659
|
+
const hash = createHash('sha512');
|
|
660
|
+
let got = 0;
|
|
661
|
+
let shown = 0;
|
|
662
|
+
try {
|
|
663
|
+
for await (const chunk of res.body) {
|
|
664
|
+
got += chunk.length;
|
|
665
|
+
if (got > MAX_INSTALLER_BYTES) throw invalid('The LightCode installer is larger than expected — stopped');
|
|
666
|
+
hash.update(chunk);
|
|
667
|
+
if (!out.write(chunk)) await new Promise((r) => out.once('drain', r));
|
|
668
|
+
if (onProgress && got - shown > 10 * 1024 * 1024) { shown = got; onProgress(got); }
|
|
669
|
+
}
|
|
670
|
+
await new Promise((r, j) => out.end((e) => (e ? j(e) : r())));
|
|
671
|
+
} catch (e) {
|
|
672
|
+
out.destroy();
|
|
673
|
+
try { fs.rmSync(tmp, { force: true }); } catch { /* bỏ qua */ }
|
|
674
|
+
throw e;
|
|
675
|
+
}
|
|
676
|
+
if (hash.digest('base64') !== sha512) {
|
|
677
|
+
try { fs.rmSync(tmp, { force: true }); } catch { /* bỏ qua */ }
|
|
678
|
+
throw invalid('The downloaded LightCode installer does not match its published checksum — not installed');
|
|
679
|
+
}
|
|
680
|
+
fs.renameSync(tmp, dest);
|
|
681
|
+
return got;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Kiểm tra chữ ký Authenticode của bộ cài Windows qua PowerShell (truyền đường dẫn qua biến môi trường, không nội suy chuỗi).
|
|
686
|
+
* Chữ ký bị hỏng / không tin cậy (`HashMismatch`, `NotTrusted`…) luôn bị chặn; tệp chưa ký (`NotSigned`) chỉ chặn khi yêu cầu bắt buộc chữ ký
|
|
687
|
+
* hoặc có cấu hình tên nhà phát hành kỳ vọng.
|
|
688
|
+
*/
|
|
689
|
+
export function verifyInstallerSignature(filePath, { execFileImpl = execFile, requireSignature = false, expectedPublisher = '' } = {}) {
|
|
690
|
+
return new Promise((resolve, reject) => {
|
|
691
|
+
const cmd = "$s = Get-AuthenticodeSignature -LiteralPath $env:AIVIN_SIG_FILE; [pscustomobject]@{ status = [string]$s.Status; subject = if ($s.SignerCertificate) { [string]$s.SignerCertificate.Subject } else { '' }; thumbprint = if ($s.SignerCertificate) { [string]$s.SignerCertificate.Thumbprint } else { '' } } | ConvertTo-Json -Compress";
|
|
692
|
+
execFileImpl('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', cmd], {
|
|
693
|
+
encoding: 'utf8', timeout: SIG_CHECK_TIMEOUT_MS, windowsHide: true, env: { ...process.env, AIVIN_SIG_FILE: filePath },
|
|
694
|
+
}, (err, stdout) => {
|
|
695
|
+
if (err) {
|
|
696
|
+
if (requireSignature || expectedPublisher) return reject(invalid(`Could not verify the LightCode installer signature: ${err.message}`));
|
|
697
|
+
return resolve({ status: 'CheckUnavailable' });
|
|
698
|
+
}
|
|
699
|
+
let sig;
|
|
700
|
+
try { sig = JSON.parse(String(stdout || '').trim()); } catch { sig = null; }
|
|
701
|
+
const status = String(sig?.status || 'Unknown');
|
|
702
|
+
const subject = String(sig?.subject || '');
|
|
703
|
+
const thumbprint = String(sig?.thumbprint || '');
|
|
704
|
+
if (status === 'Valid') {
|
|
705
|
+
if (expectedPublisher && !subject.toLowerCase().includes(String(expectedPublisher).toLowerCase())) {
|
|
706
|
+
return reject(invalid(`The LightCode installer signature belongs to "${subject || 'unknown'}", not "${expectedPublisher}" — not installed`));
|
|
707
|
+
}
|
|
708
|
+
return resolve({ status, ...(subject ? { subject } : {}), ...(thumbprint ? { thumbprint } : {}) });
|
|
709
|
+
}
|
|
710
|
+
if (status === 'NotSigned') {
|
|
711
|
+
if (requireSignature || expectedPublisher) {
|
|
712
|
+
return reject(invalid('The downloaded LightCode installer is not digitally signed — not installed'));
|
|
713
|
+
}
|
|
714
|
+
return resolve({ status });
|
|
715
|
+
}
|
|
716
|
+
return reject(invalid(`The LightCode installer has an invalid signature (${status}) — not installed`));
|
|
717
|
+
});
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* Cài LightCode bằng bộ cài chính thức (NSIS, một người dùng, chạy im lặng `/S`) từ lightcode.live, kiểm SHA-512 theo `latest.yml` + chữ ký
|
|
723
|
+
* Authenticode trên Windows, rồi bật ứng dụng và chờ cửa cục bộ. Đã cài → chỉ bật. Chỉ Windows (LightCode chưa có bản macOS / Linux).
|
|
724
|
+
*/
|
|
725
|
+
export async function installLightcode(args = {}, ctx = {}, deps = {}) {
|
|
726
|
+
const platform = deps.platform || process.platform;
|
|
727
|
+
if (platform !== 'win32') throw invalid('LightCode is only available for Windows for now');
|
|
728
|
+
const say = (t) => { try { ctx.onOutput?.(`${t}\n`); } catch { /* chỉ là tiến trình */ } };
|
|
729
|
+
const before = lightcodeLocalStatus(deps);
|
|
730
|
+
if (before.installed && !args.reinstall) {
|
|
731
|
+
say('LightCode is already installed — starting it.');
|
|
732
|
+
const info = await (deps.ensure || ensureLightcodeRunning)(deps);
|
|
733
|
+
const issue = await lightcodeReadiness({ ...deps, connector: info }).catch(() => null);
|
|
734
|
+
return { installed: true, already: true, running: true, version: info.app_version, protocol: info.protocol ?? 1, agent: LIGHTCODE_ADAPTER.id, ...(issue ? { issue } : {}) };
|
|
735
|
+
}
|
|
736
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
737
|
+
const base = (process.env.AIVIN_LIGHTCODE_RELEASES || LIGHTCODE_RELEASES_URL).replace(/\/+$/, '');
|
|
738
|
+
say(`Checking the latest LightCode release (${base}/latest.yml)…`);
|
|
739
|
+
const ymlRes = await fetchImpl(`${base}/latest.yml`, { signal: ctx.signal });
|
|
740
|
+
if (!ymlRes.ok) throw notFound(`Cannot read ${base}/latest.yml (${ymlRes.status})`);
|
|
741
|
+
const latest = parseLatestYml(await ymlRes.text());
|
|
742
|
+
if (!latest) throw invalid('latest.yml of LightCode is not in the expected format');
|
|
743
|
+
const dest = path.join(deps.downloadDir || DOWNLOAD_DIR, latest.file);
|
|
744
|
+
say(`Downloading LightCode ${latest.version}${latest.size ? ` (${Math.round(latest.size / 1024 / 1024)} MB)` : ''}…`);
|
|
745
|
+
await downloadVerified(`${base}/${encodeURIComponent(latest.file)}`, dest, latest.sha512, {
|
|
746
|
+
fetchImpl, signal: ctx.signal, onProgress: (n) => say(` ${Math.round(n / 1024 / 1024)} MB`),
|
|
747
|
+
});
|
|
748
|
+
const requireSignature = args.require_signature === true || process.env.AIVIN_LIGHTCODE_REQUIRE_SIGNATURE === '1';
|
|
749
|
+
const expectedPublisher = String(args.expected_publisher || process.env.AIVIN_LIGHTCODE_PUBLISHER || '').trim();
|
|
750
|
+
const verifySig = deps.verifySignature || ((p) => verifyInstallerSignature(p, { execFileImpl: deps.execFileImpl, requireSignature, expectedPublisher }));
|
|
751
|
+
let signature;
|
|
752
|
+
try {
|
|
753
|
+
signature = await verifySig(dest);
|
|
754
|
+
} catch (e) {
|
|
755
|
+
try { fs.rmSync(dest, { force: true }); } catch { /* bỏ qua */ }
|
|
756
|
+
throw e;
|
|
757
|
+
}
|
|
758
|
+
say(`Checksum OK (signature: ${signature?.status || 'checked'}) — installing silently…`);
|
|
759
|
+
const spawnImpl = deps.spawnImpl || spawn;
|
|
760
|
+
const code = await new Promise((resolve, reject) => {
|
|
761
|
+
const child = spawnImpl(dest, ['/S'], { windowsHide: true, stdio: 'ignore' });
|
|
762
|
+
const t = setTimeout(() => { try { child.kill(); } catch { /* đã thoát */ } reject(invalid('The LightCode installer did not finish within 10 minutes')); }, INSTALL_TIMEOUT_MS);
|
|
763
|
+
child.on('error', (e) => { clearTimeout(t); reject(e); });
|
|
764
|
+
child.on('close', (c) => { clearTimeout(t); resolve(c); });
|
|
765
|
+
});
|
|
766
|
+
if (code !== 0) throw invalid(`The LightCode installer exited with code ${code}`);
|
|
767
|
+
try { fs.rmSync(dest, { force: true }); } catch { /* để lại cũng được */ }
|
|
768
|
+
say('Installed — starting LightCode…');
|
|
769
|
+
const info = await (deps.ensure || ensureLightcodeRunning)(deps);
|
|
770
|
+
// Cài mới = chưa đăng nhập tài khoản AI nào: báo để BE không giao việc cho nó trước khi người dùng đăng nhập.
|
|
771
|
+
const issue = await lightcodeReadiness({ ...deps, connector: info }).catch(() => null);
|
|
772
|
+
return {
|
|
773
|
+
...(issue ? { issue } : {}),
|
|
774
|
+
installed: true, running: true, version: info.app_version || latest.version, protocol: info.protocol ?? 1, agent: LIGHTCODE_ADAPTER.id,
|
|
775
|
+
...(signature ? { signature } : {}),
|
|
776
|
+
note: 'LightCode starts with a free trial. The person signs in to their AI accounts (Claude, Codex, Gemini…) once inside LightCode; Aivin then gives coding jobs to agent "lightcode".',
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
export async function lightcodeStatus(deps = {}) {
|
|
781
|
+
const info = deps.connector || readConnector(deps);
|
|
782
|
+
const st = deps.connector
|
|
783
|
+
? {
|
|
784
|
+
...lightcodeLocalStatus(deps),
|
|
785
|
+
installed: true,
|
|
786
|
+
running: true,
|
|
787
|
+
...(info.app_version ? { version: info.app_version } : {}),
|
|
788
|
+
...(info.protocol ? { protocol: info.protocol } : {}),
|
|
789
|
+
}
|
|
790
|
+
: lightcodeLocalStatus(deps);
|
|
791
|
+
if (!st.running || !info) return { ...st, client_protocol: CLIENT_PROTOCOL, site: LIGHTCODE_SITE };
|
|
792
|
+
try {
|
|
793
|
+
const res = await (deps.fetchImpl || globalThis.fetch)(`http://127.0.0.1:${info.port}/connector/v1/info`, { headers: { Authorization: `Bearer ${info.key}` } });
|
|
794
|
+
const body = res.ok ? await res.json() : null;
|
|
795
|
+
const protocol = body?.protocol ?? info.protocol ?? 1;
|
|
796
|
+
const minClient = body?.min_client_protocol ?? 1;
|
|
797
|
+
return {
|
|
798
|
+
...st, site: LIGHTCODE_SITE, client_protocol: CLIENT_PROTOCOL, protocol, min_client_protocol: minClient,
|
|
799
|
+
protocol_ok: CLIENT_PROTOCOL >= minClient,
|
|
800
|
+
...(body ? {
|
|
801
|
+
can_run: body.can_run, providers: body.providers, accounts: body.accounts, license: body.license,
|
|
802
|
+
...(Array.isArray(body.features) ? { features: body.features } : {}),
|
|
803
|
+
...(body.capacity ? { capacity: body.capacity } : {}),
|
|
804
|
+
} : {}),
|
|
805
|
+
};
|
|
806
|
+
} catch { return { ...st, client_protocol: CLIENT_PROTOCOL, site: LIGHTCODE_SITE }; }
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* LightCode đã cài + đang chạy nhưng chưa dùng được → lý do (để BE đừng giao việc cho nó rồi thất bại ngay lượt đầu); dùng được / chưa biết → null.
|
|
811
|
+
* `no_account` = chưa đăng nhập tài khoản AI nào trong LightCode · `license_expired` = hết bản dùng thử / chưa có bản quyền · `protocol_mismatch` = CLI cũ quá.
|
|
812
|
+
* Hết hạn mức tạm thời KHÔNG tính: LightCode tự đợi / chuyển tài khoản.
|
|
813
|
+
*/
|
|
814
|
+
export async function lightcodeReadiness(deps = {}) {
|
|
815
|
+
const st = await lightcodeStatus(deps);
|
|
816
|
+
if (!st.running || st.protocol === undefined) return null;
|
|
817
|
+
if (st.protocol_ok === false) return 'protocol_mismatch';
|
|
818
|
+
if (st.can_run === false) return 'license_expired';
|
|
819
|
+
if (st.accounts === 0) return 'no_account';
|
|
820
|
+
return null;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
824
|
+
const DEPLOY_WAIT_DEFAULT_MS = 5_000;
|
|
825
|
+
const DEPLOY_WAIT_MAX_MS = 60_000;
|
|
826
|
+
const DEPLOY_POLL_MS = 1_500;
|
|
827
|
+
|
|
828
|
+
function resolveOptionalCwd(rawCwd, roots) {
|
|
829
|
+
const cwd = String(rawCwd || '').trim();
|
|
830
|
+
if (!cwd) return undefined;
|
|
831
|
+
return Array.isArray(roots) && roots.length ? resolveInRoots(roots, cwd) : path.resolve(cwd);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** Đọc fallback `.lcagent/worklog.jsonl` trên đĩa khi LightCode đang tắt nhưng vẫn có thư mục dự án. */
|
|
835
|
+
function readWorklogFromDisk(cwd, { since, limit = 20, source } = {}) {
|
|
836
|
+
const file = path.join(cwd, '.lcagent', 'worklog.jsonl');
|
|
837
|
+
if (!fs.existsSync(file)) return [];
|
|
838
|
+
const entries = [];
|
|
839
|
+
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
|
|
840
|
+
if (!line.trim()) continue;
|
|
841
|
+
try {
|
|
842
|
+
const e = JSON.parse(line);
|
|
843
|
+
if (!e || typeof e.id !== 'string' || typeof e.at !== 'string') continue;
|
|
844
|
+
if (since && e.at < since) continue;
|
|
845
|
+
if (source && e.source !== source) continue;
|
|
846
|
+
entries.push(e);
|
|
847
|
+
} catch { /* bỏ qua dòng hỏng */ }
|
|
848
|
+
}
|
|
849
|
+
return entries.slice(-limit).reverse();
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/** Đọc fallback `.lcagent/workflow.json` trên đĩa khi LightCode đang tắt. */
|
|
853
|
+
function readDeployInfoFromDisk(cwd) {
|
|
854
|
+
const file = path.join(cwd, '.lcagent', 'workflow.json');
|
|
855
|
+
if (!fs.existsSync(file)) return { configured: false, parts: [], environments: [], recent_runs: [], pending_requests: [] };
|
|
856
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
857
|
+
const envs = Array.isArray(raw?.environments) ? raw.environments : [];
|
|
858
|
+
const ext = process.platform === 'win32' ? '.ps1' : '.sh';
|
|
859
|
+
return {
|
|
860
|
+
configured: true,
|
|
861
|
+
parts: Array.isArray(raw?.parts) ? raw.parts : [],
|
|
862
|
+
environments: envs.map((e) => ({
|
|
863
|
+
id: e.id, name: e.name, tier: e.tier, ...(e.url ? { url: e.url } : {}), approval: !!e.approval,
|
|
864
|
+
...(e.owner ? { owner: e.owner } : {}), ...(e.ownerRole ? { owner_role: e.ownerRole } : {}),
|
|
865
|
+
has_recipe: fs.existsSync(path.join(cwd, '.lcagent', 'deploy', `${e.id}.md`)),
|
|
866
|
+
has_script: fs.existsSync(path.join(cwd, '.lcagent', 'deploy', `${e.id}${ext}`)),
|
|
867
|
+
running: false,
|
|
868
|
+
targets: Array.isArray(e.targets) ? e.targets : [],
|
|
869
|
+
})),
|
|
870
|
+
recent_runs: [],
|
|
871
|
+
pending_requests: [],
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/** Đọc báo cáo kết quả công việc của các trợ lý AI trên LightCode (cả phiên đã xong lẫn đang chạy). */
|
|
876
|
+
export async function lightcodeWorklog(args = {}, deps = {}) {
|
|
877
|
+
const cwd = resolveOptionalCwd(args.cwd, deps.roots);
|
|
878
|
+
const projectId = args.project_id ? String(args.project_id).trim() : undefined;
|
|
879
|
+
const since = args.since ? String(args.since).trim() : undefined;
|
|
880
|
+
const limit = Math.min(100, Math.max(1, Number(args.limit) || 20));
|
|
881
|
+
const source = args.source === 'user' || args.source === 'aivin' ? args.source : undefined;
|
|
882
|
+
const info = deps.connector || readConnector(deps);
|
|
883
|
+
if (!info) {
|
|
884
|
+
if (cwd) return { running: false, fallback: 'disk', cwd, entries: readWorklogFromDisk(cwd, { since, limit, source }), active_sessions: [] };
|
|
885
|
+
return { running: false, entries: [], active_sessions: [], note: 'LightCode is not running — pass cwd of a project folder to read .lcagent/worklog.jsonl directly, or open LightCode.' };
|
|
886
|
+
}
|
|
887
|
+
const q = new URLSearchParams();
|
|
888
|
+
if (cwd) q.set('cwd', cwd);
|
|
889
|
+
if (projectId) q.set('project_id', projectId);
|
|
890
|
+
if (since) q.set('since', since);
|
|
891
|
+
q.set('limit', String(limit));
|
|
892
|
+
if (source) q.set('source', source);
|
|
893
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
894
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/worklog?${q.toString()}`, {
|
|
895
|
+
headers: { Authorization: `Bearer ${info.key}` },
|
|
896
|
+
});
|
|
897
|
+
if (!res.ok) {
|
|
898
|
+
let err = `LightCode answered ${res.status}`;
|
|
899
|
+
try { const b = await res.json(); err = b.error || err; } catch { /* bỏ qua */ }
|
|
900
|
+
if (res.status === 404 && cwd) return { running: true, fallback: 'disk', cwd, entries: readWorklogFromDisk(cwd, { since, limit, source }), active_sessions: [] };
|
|
901
|
+
throw new DeviceToolError(res.status === 404 ? DeviceErrorCode.NOT_FOUND : DeviceErrorCode.INVALID_ARGS, err);
|
|
902
|
+
}
|
|
903
|
+
const body = await res.json();
|
|
904
|
+
return { running: true, ...body };
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/** Xem cấu hình quy trình phát hành, lịch sử phát hành của dự án, hoặc tiến độ một phiên phát hành cụ thể (`thread_id`). */
|
|
908
|
+
export async function lightcodeDeployInfo(args = {}, deps = {}) {
|
|
909
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
910
|
+
const info = deps.connector || readConnector(deps);
|
|
911
|
+
const threadId = args.thread_id ? String(args.thread_id).trim() : '';
|
|
912
|
+
if (threadId) {
|
|
913
|
+
if (!info) throw notFound('LightCode is not running — cannot read deploy session status');
|
|
914
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/deploy/runs/${encodeURIComponent(threadId)}`, {
|
|
915
|
+
headers: { Authorization: `Bearer ${info.key}` },
|
|
916
|
+
});
|
|
917
|
+
if (!res.ok) {
|
|
918
|
+
let err = `LightCode answered ${res.status}`;
|
|
919
|
+
try { const b = await res.json(); err = b.error || err; } catch { /* bỏ qua */ }
|
|
920
|
+
throw new DeviceToolError(res.status === 404 ? DeviceErrorCode.NOT_FOUND : DeviceErrorCode.INVALID_ARGS, err);
|
|
921
|
+
}
|
|
922
|
+
return { running: true, ...(await res.json()) };
|
|
923
|
+
}
|
|
924
|
+
const cwd = resolveOptionalCwd(args.cwd, deps.roots);
|
|
925
|
+
const projectId = args.project_id ? String(args.project_id).trim() : undefined;
|
|
926
|
+
if (!cwd && !projectId) throw invalid('Give cwd (project folder) or project_id (or thread_id to check a running deploy)');
|
|
927
|
+
if (!info) {
|
|
928
|
+
if (cwd) return { running: false, fallback: 'disk', cwd, ...readDeployInfoFromDisk(cwd) };
|
|
929
|
+
throw notFound('LightCode is not running — pass cwd of the project folder or open LightCode');
|
|
930
|
+
}
|
|
931
|
+
const q = new URLSearchParams();
|
|
932
|
+
if (cwd) q.set('cwd', cwd);
|
|
933
|
+
if (projectId) q.set('project_id', projectId);
|
|
934
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/deploy/info?${q.toString()}`, {
|
|
935
|
+
headers: { Authorization: `Bearer ${info.key}` },
|
|
936
|
+
});
|
|
937
|
+
if (!res.ok) {
|
|
938
|
+
let err = `LightCode answered ${res.status}`;
|
|
939
|
+
try { const b = await res.json(); err = b.error || err; } catch { /* bỏ qua */ }
|
|
940
|
+
if (res.status === 404 && cwd) return { running: true, fallback: 'disk', cwd, ...readDeployInfoFromDisk(cwd) };
|
|
941
|
+
throw new DeviceToolError(res.status === 404 ? DeviceErrorCode.NOT_FOUND : DeviceErrorCode.INVALID_ARGS, err);
|
|
942
|
+
}
|
|
943
|
+
return { running: true, ...(await res.json()) };
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/** Đọc danh sách SSH host đã lưu trên LightCode, alias trong ~/.ssh/config và các nền tảng deploy được hỗ trợ (không bao giờ trả bí mật). */
|
|
947
|
+
export async function lightcodeDeployHosts(deps = {}) {
|
|
948
|
+
const info = deps.connector || readConnector(deps);
|
|
949
|
+
if (!info) return { running: false, hosts: [], ssh_config: [], adapters: [], note: 'LightCode is not running — open LightCode to list saved deploy hosts.' };
|
|
950
|
+
const body = await connectorJson(info, '/connector/v1/deploy/hosts', {}, deps);
|
|
951
|
+
return { running: true, ...body };
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/**
|
|
955
|
+
* Tạo hoặc cập nhật quy trình deploy `.lcagent/workflow.json` trên LightCode cho dự án (kể cả dự án mới chưa từng cấu hình).
|
|
956
|
+
* KHÔNG chạy deploy thật — chỉ lưu cấu hình và để LightCode chuẩn bị sẵn kịch bản; sau đó gọi `lightcode.deploy` khi người dùng xác nhận.
|
|
957
|
+
*/
|
|
958
|
+
export async function lightcodeDeploySetup(args = {}, ctx = {}, deps = {}) {
|
|
959
|
+
const cwd = resolveOptionalCwd(args.cwd, deps.roots);
|
|
960
|
+
const projectId = args.project_id ? String(args.project_id).trim() : undefined;
|
|
961
|
+
if (!cwd && !projectId) throw invalid('Give cwd (project folder) or project_id');
|
|
962
|
+
const info = deps.connector || await (deps.ensure || ensureLightcodeRunning)(deps);
|
|
963
|
+
let environments = Array.isArray(args.environments) ? args.environments : undefined;
|
|
964
|
+
// Lối tắt cho 1 môi trường: truyền trực tiếp env_name / where / host_id / adapter / url / notes.
|
|
965
|
+
if (!environments && (args.env_name || args.env_id || args.where || args.host_id || args.host || args.adapter || args.url)) {
|
|
966
|
+
const tier = ['test', 'staging', 'live'].includes(String(args.tier || '')) ? String(args.tier) : 'live';
|
|
967
|
+
const name = String(args.env_name || (tier === 'live' ? 'Production' : tier === 'staging' ? 'Staging' : 'Test')).trim();
|
|
968
|
+
const target = {
|
|
969
|
+
...(args.where ? { where: String(args.where) } : {}),
|
|
970
|
+
...(args.host_id ? { host_id: String(args.host_id) } : {}),
|
|
971
|
+
...(args.host ? { host: String(args.host) } : {}),
|
|
972
|
+
...(args.adapter ? { adapter: String(args.adapter) } : {}),
|
|
973
|
+
};
|
|
974
|
+
environments = [{
|
|
975
|
+
...(args.env_id ? { id: String(args.env_id) } : {}),
|
|
976
|
+
name,
|
|
977
|
+
tier,
|
|
978
|
+
targets: Object.keys(target).length ? [target] : [],
|
|
979
|
+
...(args.url ? { url: String(args.url) } : {}),
|
|
980
|
+
...(args.owner ? { owner: String(args.owner) } : {}),
|
|
981
|
+
...(args.notes ? { notes: String(args.notes) } : {}),
|
|
982
|
+
...(typeof args.approval === 'boolean' ? { approval: args.approval } : {}),
|
|
983
|
+
}];
|
|
984
|
+
}
|
|
985
|
+
const payload = {
|
|
986
|
+
...(cwd ? { cwd } : {}),
|
|
987
|
+
...(projectId ? { project_id: projectId } : {}),
|
|
988
|
+
...(Array.isArray(args.parts) ? { parts: args.parts } : {}),
|
|
989
|
+
...(environments ? { environments } : {}),
|
|
990
|
+
...(args.auto === true ? { auto: true } : {}),
|
|
991
|
+
...(typeof args.merge === 'boolean' ? { merge: args.merge } : {}),
|
|
992
|
+
...(args.lang ? { lang: String(args.lang) } : {}),
|
|
993
|
+
};
|
|
994
|
+
const body = await connectorJson(info, '/connector/v1/deploy/setup', {
|
|
995
|
+
method: 'POST',
|
|
996
|
+
headers: { 'Content-Type': 'application/json' },
|
|
997
|
+
body: JSON.stringify(payload),
|
|
998
|
+
signal: ctx.signal,
|
|
999
|
+
}, deps);
|
|
1000
|
+
return { running: true, ...body };
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
/** Kích hoạt phát hành theo đúng quy trình LightCode đã thiết lập cho dự án (cần người dùng xác nhận trước). */
|
|
1004
|
+
export async function lightcodeDeploy(args = {}, ctx = {}, deps = {}) {
|
|
1005
|
+
const cwd = resolveOptionalCwd(args.cwd, deps.roots);
|
|
1006
|
+
const projectId = args.project_id ? String(args.project_id).trim() : undefined;
|
|
1007
|
+
if (!cwd && !projectId) throw invalid('Give cwd (project folder) or project_id');
|
|
1008
|
+
const envIds = Array.isArray(args.envs) ? args.envs.map(String)
|
|
1009
|
+
: Array.isArray(args.env_ids) ? args.env_ids.map(String)
|
|
1010
|
+
: args.env ? [String(args.env)]
|
|
1011
|
+
: args.env_id ? [String(args.env_id)]
|
|
1012
|
+
: [];
|
|
1013
|
+
if (!envIds.length) throw invalid('Specify which environment to deploy (env or envs) — check lightcode.deploy_info first');
|
|
1014
|
+
const info = deps.connector || await (deps.ensure || ensureLightcodeRunning)(deps);
|
|
1015
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
1016
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
1017
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/deploy`, {
|
|
1018
|
+
method: 'POST',
|
|
1019
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${info.key}` },
|
|
1020
|
+
body: JSON.stringify({
|
|
1021
|
+
...(cwd ? { cwd } : {}), ...(projectId ? { project_id: projectId } : {}),
|
|
1022
|
+
env_ids: envIds,
|
|
1023
|
+
...(Array.isArray(args.parts) && args.parts.length ? { parts: args.parts.map(String) } : {}),
|
|
1024
|
+
...(args.note ? { note: String(args.note).slice(0, 1000) } : {}),
|
|
1025
|
+
}),
|
|
1026
|
+
signal: ctx.signal,
|
|
1027
|
+
});
|
|
1028
|
+
const body = await res.json().catch(() => ({}));
|
|
1029
|
+
if (!res.ok) {
|
|
1030
|
+
const avail = Array.isArray(body?.available_envs) ? ` (available: ${body.available_envs.map((e) => `${e.id} [${e.name}]`).join(', ')})` : '';
|
|
1031
|
+
throw new DeviceToolError(res.status === 404 ? DeviceErrorCode.NOT_FOUND : DeviceErrorCode.INVALID_ARGS, `${body?.error || `LightCode answered ${res.status}`}${avail}`);
|
|
1032
|
+
}
|
|
1033
|
+
const runs = Array.isArray(body?.runs) ? body.runs : [];
|
|
1034
|
+
const waitMs = Math.min(DEPLOY_WAIT_MAX_MS, Math.max(0, Number(args.wait_ms ?? DEPLOY_WAIT_DEFAULT_MS)));
|
|
1035
|
+
const deadline = Date.now() + waitMs;
|
|
1036
|
+
let statuses = runs.map((r) => ({ ...r, running: r.status === 'running' }));
|
|
1037
|
+
while (runs.length && Date.now() < deadline && !ctx.signal?.aborted) {
|
|
1038
|
+
await sleep(Math.min(DEPLOY_POLL_MS, Math.max(100, deadline - Date.now())));
|
|
1039
|
+
if (ctx.signal?.aborted) break;
|
|
1040
|
+
statuses = await Promise.all(runs.map(async (r) => {
|
|
1041
|
+
try {
|
|
1042
|
+
const s = await lightcodeDeployInfo({ thread_id: r.thread_id }, { ...deps, connector: info, fetchImpl });
|
|
1043
|
+
return {
|
|
1044
|
+
...r,
|
|
1045
|
+
status: s.status,
|
|
1046
|
+
running: s.running,
|
|
1047
|
+
ok: s.ok,
|
|
1048
|
+
...(s.needs_input ? { needs_input: true } : {}),
|
|
1049
|
+
...(s.support_request ? { support_request: s.support_request } : {}),
|
|
1050
|
+
...(s.report ? { report: s.report } : {}),
|
|
1051
|
+
};
|
|
1052
|
+
} catch {
|
|
1053
|
+
return { ...r, running: true };
|
|
1054
|
+
}
|
|
1055
|
+
}));
|
|
1056
|
+
if (statuses.every((s) => !s.running)) break;
|
|
1057
|
+
}
|
|
1058
|
+
const needsSupport = statuses.some((s) => s.needs_input || s.status === 'needs_input');
|
|
1059
|
+
const stillRunning = statuses.some((s) => s.running);
|
|
1060
|
+
return {
|
|
1061
|
+
project_id: body.project_id,
|
|
1062
|
+
project_name: body.project_name,
|
|
1063
|
+
runs: statuses,
|
|
1064
|
+
...(needsSupport ? {
|
|
1065
|
+
needs_user_support: true,
|
|
1066
|
+
hint: 'LightCode deploy needs user support — forward support_request to the user, then call lightcode.deploy_reply with thread_id and their reply to continue.',
|
|
1067
|
+
} : stillRunning ? {
|
|
1068
|
+
hint: 'Deploy is still running — call lightcode.deploy_info with thread_id to check its progress or any user support request.',
|
|
1069
|
+
} : {}),
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/** Chuyển tiếp câu trả lời / xác nhận đã hỗ trợ của người dùng quay lại đúng phiên deploy/setup đang chờ trên LightCode. */
|
|
1074
|
+
export async function lightcodeDeployReply(args = {}, ctx = {}, deps = {}) {
|
|
1075
|
+
const threadId = String(args.thread_id || '').trim();
|
|
1076
|
+
if (!threadId) throw invalid('thread_id is required');
|
|
1077
|
+
const info = deps.connector || await (deps.ensure || ensureLightcodeRunning)(deps);
|
|
1078
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
1079
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
1080
|
+
const payload = {
|
|
1081
|
+
...(args.message !== undefined ? { message: String(args.message) } : {}),
|
|
1082
|
+
...(args.answer !== undefined ? { answer: String(args.answer) } : {}),
|
|
1083
|
+
...(args.answers && typeof args.answers === 'object' ? { answers: args.answers } : {}),
|
|
1084
|
+
...(args.hil_id ? { hil_id: String(args.hil_id) } : {}),
|
|
1085
|
+
...(args.decision ? { decision: String(args.decision) } : {}),
|
|
1086
|
+
};
|
|
1087
|
+
const body = await connectorJson(info, `/connector/v1/deploy/runs/${encodeURIComponent(threadId)}/reply`, {
|
|
1088
|
+
method: 'POST',
|
|
1089
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1090
|
+
body: JSON.stringify(payload),
|
|
1091
|
+
signal: ctx.signal,
|
|
1092
|
+
}, { ...deps, fetchImpl });
|
|
1093
|
+
|
|
1094
|
+
const waitMs = Math.min(DEPLOY_WAIT_MAX_MS, Math.max(0, Number(args.wait_ms ?? DEPLOY_WAIT_DEFAULT_MS)));
|
|
1095
|
+
let latest = body;
|
|
1096
|
+
const deadline = Date.now() + waitMs;
|
|
1097
|
+
while (latest.running && Date.now() < deadline && !ctx.signal?.aborted) {
|
|
1098
|
+
await sleep(Math.min(DEPLOY_POLL_MS, Math.max(100, deadline - Date.now())));
|
|
1099
|
+
if (ctx.signal?.aborted) break;
|
|
1100
|
+
try {
|
|
1101
|
+
const s = await lightcodeDeployInfo({ thread_id: threadId }, { ...deps, connector: info, fetchImpl });
|
|
1102
|
+
latest = { ...latest, ...s };
|
|
1103
|
+
if (!s.running) break;
|
|
1104
|
+
} catch { break; }
|
|
1105
|
+
}
|
|
1106
|
+
const needsSupport = latest.needs_input === true || latest.status === 'needs_input';
|
|
1107
|
+
return {
|
|
1108
|
+
...latest,
|
|
1109
|
+
...(needsSupport ? {
|
|
1110
|
+
needs_user_support: true,
|
|
1111
|
+
hint: 'LightCode still needs user support — forward support_request to the user and call lightcode.deploy_reply again.',
|
|
1112
|
+
} : latest.running ? {
|
|
1113
|
+
hint: 'Deploy/setup session is still running — call lightcode.deploy_info with thread_id to check its progress.',
|
|
1114
|
+
} : {}),
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
// --- Cầu nối v2.3: answer / attention / strategy / metrics / events / webhook / preview ---------------------------------------------
|
|
1119
|
+
|
|
1120
|
+
function readStrategyFromDisk(cwd) {
|
|
1121
|
+
const readJson = (f, fallback) => {
|
|
1122
|
+
try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return fallback; }
|
|
1123
|
+
};
|
|
1124
|
+
const strategy = readJson(path.join(cwd, '.lcagent', 'strategy.json'), { goals: [], non_goals: [], principles: [] });
|
|
1125
|
+
const rawLessons = readJson(path.join(cwd, '.lcagent', 'lessons.json'), []);
|
|
1126
|
+
const lessons = Array.isArray(rawLessons) ? rawLessons.slice(0, 20) : [];
|
|
1127
|
+
return {
|
|
1128
|
+
goals: Array.isArray(strategy?.goals) ? strategy.goals : [],
|
|
1129
|
+
non_goals: Array.isArray(strategy?.non_goals) ? strategy.non_goals : [],
|
|
1130
|
+
principles: Array.isArray(strategy?.principles) ? strategy.principles : [],
|
|
1131
|
+
lessons,
|
|
1132
|
+
proposed_rules: lessons.filter((l) => Number(l?.count) >= 3).map((l) => l.text).filter(Boolean).slice(0, 10),
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
async function connectorJson(info, urlPath, init = {}, deps = {}) {
|
|
1137
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
1138
|
+
const headers = { Authorization: `Bearer ${info.key}`, ...(init.headers || {}) };
|
|
1139
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}${urlPath}`, { ...init, headers });
|
|
1140
|
+
const body = await res.json().catch(() => ({}));
|
|
1141
|
+
if (!res.ok) {
|
|
1142
|
+
const code = res.status === 404 ? DeviceErrorCode.NOT_FOUND : DeviceErrorCode.INVALID_ARGS;
|
|
1143
|
+
throw new DeviceToolError(code, body?.error || `LightCode answered ${res.status}`);
|
|
1144
|
+
}
|
|
1145
|
+
return body;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
/** Đọc mọi việc đang chờ người chú ý (câu hỏi mở, job chặn/lỗi, kết quả rủi ro cao, yêu cầu gộp nhánh). */
|
|
1149
|
+
export async function lightcodeAttention(args = {}, deps = {}) {
|
|
1150
|
+
const cwd = resolveOptionalCwd(args.cwd, deps.roots);
|
|
1151
|
+
const info = deps.connector || readConnector(deps);
|
|
1152
|
+
if (!info) return { running: false, items: [], note: 'LightCode is not running — open LightCode to inspect attention items.' };
|
|
1153
|
+
const q = new URLSearchParams();
|
|
1154
|
+
if (cwd) q.set('cwd', cwd);
|
|
1155
|
+
const qs = q.toString();
|
|
1156
|
+
const body = await connectorJson(info, `/connector/v1/attention${qs ? `?${qs}` : ''}`, {}, deps);
|
|
1157
|
+
return { running: true, ...body };
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
/** Đọc mục tiêu, ngân sách, nguyên tắc dự án (`.lcagent/strategy.json`) và bài học từ các lỗi lặp lại. */
|
|
1161
|
+
export async function lightcodeStrategy(args = {}, deps = {}) {
|
|
1162
|
+
const cwd = resolveOptionalCwd(args.cwd, deps.roots);
|
|
1163
|
+
if (!cwd) throw invalid('cwd (project folder) is required');
|
|
1164
|
+
const info = deps.connector || readConnector(deps);
|
|
1165
|
+
if (!info) return { running: false, fallback: 'disk', cwd, ...readStrategyFromDisk(cwd) };
|
|
1166
|
+
const q = new URLSearchParams({ cwd });
|
|
1167
|
+
const body = await connectorJson(info, `/connector/v1/strategy?${q.toString()}`, {}, deps);
|
|
1168
|
+
return { running: true, cwd, ...body };
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
/** Cập nhật bản đồ mục tiêu, ngân sách và nguyên tắc dự án trên LightCode (giữ nguyên spent_usd đã đo). */
|
|
1172
|
+
export async function lightcodeSetStrategy(args = {}, deps = {}) {
|
|
1173
|
+
const cwd = resolveOptionalCwd(args.cwd, deps.roots);
|
|
1174
|
+
if (!cwd) throw invalid('cwd (project folder) is required');
|
|
1175
|
+
const info = deps.connector || await (deps.ensure || ensureLightcodeRunning)(deps);
|
|
1176
|
+
const payload = {
|
|
1177
|
+
cwd,
|
|
1178
|
+
...(Array.isArray(args.goals) ? { goals: args.goals } : {}),
|
|
1179
|
+
...(Array.isArray(args.non_goals) ? { non_goals: args.non_goals } : {}),
|
|
1180
|
+
...(Array.isArray(args.principles) ? { principles: args.principles } : {}),
|
|
1181
|
+
};
|
|
1182
|
+
const body = await connectorJson(info, '/connector/v1/strategy', {
|
|
1183
|
+
method: 'PUT',
|
|
1184
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1185
|
+
body: JSON.stringify(payload),
|
|
1186
|
+
}, deps);
|
|
1187
|
+
return { running: true, cwd, ...body };
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
/** Đọc chỉ số kết quả chạy thực tế của các job LightCode (tỷ lệ đạt, chi phí, thời gian, vòng sửa). */
|
|
1191
|
+
export async function lightcodeMetrics(args = {}, deps = {}) {
|
|
1192
|
+
const cwd = resolveOptionalCwd(args.cwd, deps.roots);
|
|
1193
|
+
const since = args.since ? String(args.since).trim() : undefined;
|
|
1194
|
+
const info = deps.connector || readConnector(deps);
|
|
1195
|
+
if (!info) return { running: false, note: 'LightCode is not running — open LightCode to read metrics.' };
|
|
1196
|
+
const q = new URLSearchParams();
|
|
1197
|
+
if (cwd) q.set('cwd', cwd);
|
|
1198
|
+
if (since) q.set('since', since);
|
|
1199
|
+
const qs = q.toString();
|
|
1200
|
+
const body = await connectorJson(info, `/connector/v1/metrics${qs ? `?${qs}` : ''}`, {}, deps);
|
|
1201
|
+
return { running: true, ...body };
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
/** Đọc dòng sự kiện bền vững (`job.finished`, `job.attention`) từ LightCode và tùy chọn xác nhận đã đọc (`ack_seq` / `auto_ack`). */
|
|
1205
|
+
export async function lightcodeEvents(args = {}, deps = {}) {
|
|
1206
|
+
const info = deps.connector || readConnector(deps);
|
|
1207
|
+
if (!info) return { running: false, events: [], note: 'LightCode is not running.' };
|
|
1208
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
1209
|
+
if (args.ack_seq !== undefined && args.ack_seq !== null) {
|
|
1210
|
+
const seq = Number(args.ack_seq);
|
|
1211
|
+
if (!Number.isInteger(seq) || seq < 0) throw invalid('ack_seq must be a non-negative integer');
|
|
1212
|
+
const acked = await connectorJson(info, '/connector/v1/events/ack', {
|
|
1213
|
+
method: 'POST',
|
|
1214
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1215
|
+
body: JSON.stringify({ seq }),
|
|
1216
|
+
}, deps);
|
|
1217
|
+
if (args.only_ack) return { running: true, ...acked };
|
|
1218
|
+
}
|
|
1219
|
+
const q = new URLSearchParams();
|
|
1220
|
+
if (args.from !== undefined && args.from !== null && Number.isInteger(Number(args.from)) && Number(args.from) >= 0) {
|
|
1221
|
+
q.set('from', String(Number(args.from)));
|
|
1222
|
+
}
|
|
1223
|
+
const qs = q.toString();
|
|
1224
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/events${qs ? `?${qs}` : ''}`, {
|
|
1225
|
+
headers: { Authorization: `Bearer ${info.key}` },
|
|
1226
|
+
});
|
|
1227
|
+
if (!res.ok) {
|
|
1228
|
+
const b = await res.json().catch(() => ({}));
|
|
1229
|
+
throw new DeviceToolError(res.status === 404 ? DeviceErrorCode.NOT_FOUND : DeviceErrorCode.INVALID_ARGS, b?.error || `LightCode answered ${res.status}`);
|
|
1230
|
+
}
|
|
1231
|
+
const text = await res.text();
|
|
1232
|
+
const events = [];
|
|
1233
|
+
let lastSeq;
|
|
1234
|
+
let acked;
|
|
1235
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1236
|
+
const s = line.trim();
|
|
1237
|
+
if (!s) continue;
|
|
1238
|
+
try {
|
|
1239
|
+
const obj = JSON.parse(s);
|
|
1240
|
+
if (obj?.type === 'end') {
|
|
1241
|
+
lastSeq = obj.last_seq;
|
|
1242
|
+
acked = obj.acked;
|
|
1243
|
+
} else if (obj?.type !== 'ping') {
|
|
1244
|
+
events.push(obj);
|
|
1245
|
+
}
|
|
1246
|
+
} catch { /* bỏ dòng hỏng */ }
|
|
1247
|
+
}
|
|
1248
|
+
const limit = Math.min(200, Math.max(1, Number(args.limit) || 50));
|
|
1249
|
+
const slice = events.slice(0, limit);
|
|
1250
|
+
if (args.auto_ack === true && slice.length) {
|
|
1251
|
+
const maxSeq = slice.reduce((m, e) => (Number.isInteger(e?.seq) && e.seq > m ? e.seq : m), -1);
|
|
1252
|
+
if (maxSeq >= 0) {
|
|
1253
|
+
const a = await connectorJson(info, '/connector/v1/events/ack', {
|
|
1254
|
+
method: 'POST',
|
|
1255
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1256
|
+
body: JSON.stringify({ seq: maxSeq }),
|
|
1257
|
+
}, deps).catch(() => null);
|
|
1258
|
+
if (a) acked = a.acked;
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
return { running: true, events: slice, total: events.length, ...(lastSeq !== undefined ? { last_seq: lastSeq } : {}), ...(acked !== undefined ? { acked } : {}) };
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
/** Xem hoặc đặt URL webhook cục bộ (chỉ localhost / 127.0.0.1) để LightCode đẩy sự kiện trực tiếp. */
|
|
1265
|
+
export async function lightcodeWebhook(args = {}, deps = {}) {
|
|
1266
|
+
const info = deps.connector || readConnector(deps);
|
|
1267
|
+
if (!info) throw notFound('LightCode is not running');
|
|
1268
|
+
if (args.url === undefined) {
|
|
1269
|
+
const body = await connectorJson(info, '/connector/v1/webhook', {}, deps);
|
|
1270
|
+
return { running: true, ...body };
|
|
1271
|
+
}
|
|
1272
|
+
const body = await connectorJson(info, '/connector/v1/webhook', {
|
|
1273
|
+
method: 'PUT',
|
|
1274
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1275
|
+
body: JSON.stringify({ url: args.url }),
|
|
1276
|
+
}, deps);
|
|
1277
|
+
return { running: true, ...body };
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* Luồng nền nghe sự kiện đẩy từ LightCode (`GET /connector/v1/events?follow=1`), chuyển từng sự kiện cho `onEvent(ev)` rồi xác nhận
|
|
1282
|
+
* (`POST /connector/v1/events/ack`). Tự nối lại khi LightCode tắt/bật lại; gọi `stop()` để đóng sạch khi daemon dừng.
|
|
1283
|
+
*/
|
|
1284
|
+
export function startLightcodeEventBridge({ onEvent, peek, fetchImpl = globalThis.fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), idleMs = 5_000, maxBackoffMs = 30_000 } = {}) {
|
|
1285
|
+
const getConnector = peek || (() => readConnector());
|
|
1286
|
+
let stopped = false;
|
|
1287
|
+
let activeAbort = null;
|
|
1288
|
+
|
|
1289
|
+
const loop = async () => {
|
|
1290
|
+
let attempts = 0;
|
|
1291
|
+
while (!stopped) {
|
|
1292
|
+
const info = getConnector();
|
|
1293
|
+
if (!info || Number(info.protocol ?? 1) < 2) {
|
|
1294
|
+
await sleep(idleMs);
|
|
1295
|
+
continue;
|
|
1296
|
+
}
|
|
1297
|
+
const abort = new AbortController();
|
|
1298
|
+
activeAbort = abort;
|
|
1299
|
+
try {
|
|
1300
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/events?follow=1`, {
|
|
1301
|
+
headers: { Authorization: `Bearer ${info.key}` },
|
|
1302
|
+
signal: abort.signal,
|
|
1303
|
+
});
|
|
1304
|
+
if (!res.ok || !res.body) {
|
|
1305
|
+
attempts += 1;
|
|
1306
|
+
await sleep(Math.min(maxBackoffMs, 1500 * attempts));
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
attempts = 0;
|
|
1310
|
+
const decoder = new TextDecoder();
|
|
1311
|
+
let buf = '';
|
|
1312
|
+
const handleLine = async (line) => {
|
|
1313
|
+
const s = line.trim();
|
|
1314
|
+
if (!s) return;
|
|
1315
|
+
let ev;
|
|
1316
|
+
try { ev = JSON.parse(s); } catch { return; }
|
|
1317
|
+
if (!ev || ev.type === 'ping' || ev.type === 'end') return;
|
|
1318
|
+
try { await onEvent?.(ev); } catch { /* callback lỗi không làm rớt vòng nghe */ }
|
|
1319
|
+
if (Number.isInteger(ev.seq)) {
|
|
1320
|
+
await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/events/ack`, {
|
|
1321
|
+
method: 'POST',
|
|
1322
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${info.key}` },
|
|
1323
|
+
body: JSON.stringify({ seq: ev.seq }),
|
|
1324
|
+
signal: abort.signal,
|
|
1325
|
+
}).catch(() => undefined);
|
|
1326
|
+
}
|
|
1327
|
+
};
|
|
1328
|
+
for await (const chunk of res.body) {
|
|
1329
|
+
if (stopped) break;
|
|
1330
|
+
buf += decoder.decode(chunk, { stream: true });
|
|
1331
|
+
const lines = buf.split('\n');
|
|
1332
|
+
buf = lines.pop() ?? '';
|
|
1333
|
+
for (const line of lines) await handleLine(line);
|
|
1334
|
+
}
|
|
1335
|
+
if (!stopped && buf.trim()) await handleLine(buf);
|
|
1336
|
+
} catch {
|
|
1337
|
+
if (stopped) break;
|
|
1338
|
+
attempts += 1;
|
|
1339
|
+
await sleep(Math.min(maxBackoffMs, 1500 * attempts));
|
|
1340
|
+
} finally {
|
|
1341
|
+
if (activeAbort === abort) activeAbort = null;
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
};
|
|
1345
|
+
void loop();
|
|
1346
|
+
return {
|
|
1347
|
+
stop() {
|
|
1348
|
+
stopped = true;
|
|
1349
|
+
try { activeAbort?.abort(); } catch { /* đã đóng */ }
|
|
1350
|
+
},
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
/** Trả lời câu hỏi đang mở của một phiên LightCode (`POST /sessions/:id/answer`) và tiếp tục đúng phiên đó dưới cùng hợp đồng. */
|
|
1355
|
+
export async function lightcodeAnswer(args = {}, ctx = {}, deps = {}) {
|
|
1356
|
+
const sessionId = String(args.session_id || '').trim();
|
|
1357
|
+
if (!sessionId) throw invalid('session_id is required');
|
|
1358
|
+
const hasAnswers = Array.isArray(args.answers) && args.answers.length > 0;
|
|
1359
|
+
const single = String(args.answer ?? '').trim();
|
|
1360
|
+
if (!hasAnswers && !single) throw invalid('Give answer (string) or answers ([{question?, answer}])');
|
|
1361
|
+
const info = deps.connector || await (deps.ensure || ensureLightcodeRunning)(deps);
|
|
1362
|
+
const fetchImpl = deps.fetchImpl || globalThis.fetch;
|
|
1363
|
+
const payload = {
|
|
1364
|
+
...(hasAnswers ? { answers: args.answers } : { answer: single }),
|
|
1365
|
+
detach: true,
|
|
1366
|
+
orphan_ms: ORPHAN_MS,
|
|
1367
|
+
...(args.on_question === 'stop' || args.on_question === 'assume' ? { on_question: args.on_question } : {}),
|
|
1368
|
+
...(Number(args.max_cost_usd) > 0 ? { max_cost_usd: Number(args.max_cost_usd) } : {}),
|
|
1369
|
+
...(Number.isInteger(Number(args.max_fix_rounds)) && Number(args.max_fix_rounds) > 0 ? { max_fix_rounds: Math.min(3, Number(args.max_fix_rounds)) } : {}),
|
|
1370
|
+
};
|
|
1371
|
+
const res = await fetchImpl(`http://127.0.0.1:${info.port}/connector/v1/sessions/${encodeURIComponent(sessionId)}/answer`, {
|
|
1372
|
+
method: 'POST',
|
|
1373
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${info.key}` },
|
|
1374
|
+
body: JSON.stringify(payload),
|
|
1375
|
+
signal: ctx.signal,
|
|
1376
|
+
});
|
|
1377
|
+
if (!res.ok) {
|
|
1378
|
+
const b = await res.json().catch(() => ({}));
|
|
1379
|
+
throw new DeviceToolError(res.status === 404 ? DeviceErrorCode.NOT_FOUND : DeviceErrorCode.INVALID_ARGS, b?.error || `LightCode answered ${res.status}`);
|
|
1380
|
+
}
|
|
1381
|
+
const job = { texts: [], tools: [] };
|
|
1382
|
+
const decoder = new TextDecoder();
|
|
1383
|
+
let buf = '';
|
|
1384
|
+
const handle = (line) => {
|
|
1385
|
+
const s = line.trim();
|
|
1386
|
+
if (!s) return;
|
|
1387
|
+
let msg;
|
|
1388
|
+
try { msg = JSON.parse(s); } catch { return; }
|
|
1389
|
+
const shown = LIGHTCODE_ADAPTER.parse(job, msg);
|
|
1390
|
+
if (shown && typeof ctx.onOutput === 'function') {
|
|
1391
|
+
try { ctx.onOutput(`${shown}\n`); } catch { /* chỉ là tiến trình */ }
|
|
1392
|
+
}
|
|
1393
|
+
};
|
|
1394
|
+
if (res.body) {
|
|
1395
|
+
for await (const chunk of res.body) {
|
|
1396
|
+
if (ctx.signal?.aborted) break;
|
|
1397
|
+
buf += decoder.decode(chunk, { stream: true });
|
|
1398
|
+
const lines = buf.split('\n');
|
|
1399
|
+
buf = lines.pop() ?? '';
|
|
1400
|
+
for (const line of lines) handle(line);
|
|
1401
|
+
}
|
|
1402
|
+
if (buf.trim()) handle(buf);
|
|
1403
|
+
}
|
|
1404
|
+
return {
|
|
1405
|
+
session_id: job.session_id || sessionId,
|
|
1406
|
+
...(job.lightcode ? { lightcode: job.lightcode } : {}),
|
|
1407
|
+
...(job.progress ? { progress: job.progress } : {}),
|
|
1408
|
+
...(job.result ? { result: job.result } : { result: { ok: false, answer: 'Stream ended before result' } }),
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/** Quản lý bản xem trước giao diện (start / list / capture / smoke / stop) gắn với phiên LightCode. */
|
|
1413
|
+
export async function lightcodePreview(args = {}, ctx = {}, deps = {}) {
|
|
1414
|
+
const action = String(args.action || 'list').trim().toLowerCase();
|
|
1415
|
+
const info = deps.connector || (action === 'list' ? readConnector(deps) : await (deps.ensure || ensureLightcodeRunning)(deps));
|
|
1416
|
+
if (!info) return { running: false, previews: [], note: 'LightCode is not running.' };
|
|
1417
|
+
if (action === 'list') {
|
|
1418
|
+
const q = new URLSearchParams();
|
|
1419
|
+
if (args.session_id) q.set('session_id', String(args.session_id).trim());
|
|
1420
|
+
const qs = q.toString();
|
|
1421
|
+
const body = await connectorJson(info, `/connector/v1/previews${qs ? `?${qs}` : ''}`, { signal: ctx.signal }, deps);
|
|
1422
|
+
return { running: true, ...body };
|
|
1423
|
+
}
|
|
1424
|
+
if (action === 'start') {
|
|
1425
|
+
const sessionId = String(args.session_id || '').trim();
|
|
1426
|
+
if (!sessionId) throw invalid('session_id is required to start a preview');
|
|
1427
|
+
const body = await connectorJson(info, '/connector/v1/previews', {
|
|
1428
|
+
method: 'POST',
|
|
1429
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1430
|
+
body: JSON.stringify({
|
|
1431
|
+
session_id: sessionId,
|
|
1432
|
+
...(args.command ? { command: String(args.command) } : {}),
|
|
1433
|
+
...(args.wait_for ? { wait_for: String(args.wait_for) } : {}),
|
|
1434
|
+
...(Number(args.wait_seconds) > 0 ? { wait_seconds: Number(args.wait_seconds) } : {}),
|
|
1435
|
+
...(args.url ? { url: String(args.url) } : {}),
|
|
1436
|
+
...(Number(args.ttl_minutes) > 0 ? { ttl_minutes: Number(args.ttl_minutes) } : {}),
|
|
1437
|
+
}),
|
|
1438
|
+
signal: ctx.signal,
|
|
1439
|
+
}, deps);
|
|
1440
|
+
return { running: true, ...body };
|
|
1441
|
+
}
|
|
1442
|
+
const previewId = String(args.preview_id || args.id || '').trim();
|
|
1443
|
+
if (!previewId) throw invalid(`preview_id is required for preview action "${action}"`);
|
|
1444
|
+
if (action === 'capture') {
|
|
1445
|
+
const body = await connectorJson(info, `/connector/v1/previews/${encodeURIComponent(previewId)}/capture`, {
|
|
1446
|
+
method: 'POST',
|
|
1447
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1448
|
+
body: JSON.stringify({
|
|
1449
|
+
...(args.path ? { path: String(args.path) } : {}),
|
|
1450
|
+
...(args.full_page === true ? { full_page: true } : {}),
|
|
1451
|
+
...(args.inline === true ? { inline: true } : {}),
|
|
1452
|
+
}),
|
|
1453
|
+
signal: ctx.signal,
|
|
1454
|
+
}, deps);
|
|
1455
|
+
return { running: true, ...body };
|
|
1456
|
+
}
|
|
1457
|
+
if (action === 'smoke') {
|
|
1458
|
+
const steps = Array.isArray(args.steps) ? args.steps : [];
|
|
1459
|
+
if (!steps.length) throw invalid('steps ([{open, expect_text?, no_console_errors?}]) is required for smoke');
|
|
1460
|
+
const body = await connectorJson(info, `/connector/v1/previews/${encodeURIComponent(previewId)}/smoke`, {
|
|
1461
|
+
method: 'POST',
|
|
1462
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1463
|
+
body: JSON.stringify({ steps }),
|
|
1464
|
+
signal: ctx.signal,
|
|
1465
|
+
}, deps);
|
|
1466
|
+
return { running: true, ...body };
|
|
1467
|
+
}
|
|
1468
|
+
if (action === 'stop') {
|
|
1469
|
+
const body = await connectorJson(info, `/connector/v1/previews/${encodeURIComponent(previewId)}`, {
|
|
1470
|
+
method: 'DELETE',
|
|
1471
|
+
signal: ctx.signal,
|
|
1472
|
+
}, deps);
|
|
1473
|
+
return { running: true, ...body };
|
|
1474
|
+
}
|
|
1475
|
+
throw invalid(`Unknown preview action "${action}" — use list, start, capture, smoke, or stop`);
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
/** Công cụ LightCode cho danh mục của Planner (máy Windows của một người). */
|
|
1479
|
+
export function buildLightcodeTools({ onInstalled, roots } = {}) {
|
|
1480
|
+
const install = async (a, c) => {
|
|
1481
|
+
const res = await installLightcode(a, c);
|
|
1482
|
+
// Báo BE danh sách agent mới (profile.coding_agents có "lightcode") — Planner giao hợp đồng cho LightCode ngay lượt sau.
|
|
1483
|
+
try { await onInstalled?.(); } catch { /* lần nối lại sau vẫn báo */ }
|
|
1484
|
+
return res;
|
|
1485
|
+
};
|
|
1486
|
+
return [
|
|
1487
|
+
{ name: 'lightcode.status', group: ToolGroup.PROC, read_only: true, handler: () => lightcodeStatus(),
|
|
1488
|
+
description: 'Is LightCode on this computer (installed / running / version, signed-in AI accounts, can it run jobs)? LightCode is the local execution app Aivin hands coding contracts to (agent "lightcode" of agent.run).',
|
|
1489
|
+
input_schema: schema({}) },
|
|
1490
|
+
{ name: 'lightcode.install', group: ToolGroup.PROC, handler: install,
|
|
1491
|
+
description: 'Install LightCode (https://lightcode.live, Windows) from its official installer (SHA-512 checked) and start it. LightCode executes coding work on this computer: several AI agents in parallel (Claude, Codex, Gemini, OpenCode, Antigravity), automatic switch to a backup account when one runs out of quota, context kept across accounts — while Aivin keeps the plan, the contracts and the quality check. ONLY after the person agreed: first explain in one or two sentences what LightCode is and why (faster, no stalls when an account runs out, they can watch every job in LightCode; free trial, lifetime licence USD 2.99) and ask. Already installed → just starts it.',
|
|
1492
|
+
input_schema: schema({ reinstall: { type: 'boolean', description: 'download and run the installer even when LightCode is already installed (update / repair)' } }) },
|
|
1493
|
+
{ name: 'lightcode.worklog', group: ToolGroup.PROC, read_only: true, handler: (a) => lightcodeWorklog(a, { roots }),
|
|
1494
|
+
description: 'Read reports of what coding agents in LightCode have done (.lcagent/worklog.jsonl: request, final report, touched files, source user|aivin) plus currently running sessions. Omit cwd to see recent work across all local LightCode projects.',
|
|
1495
|
+
input_schema: schema({
|
|
1496
|
+
cwd: { type: 'string', description: 'project folder path (optional; omit to aggregate across all local projects)' },
|
|
1497
|
+
project_id: { type: 'string', description: 'LightCode project id (optional)' },
|
|
1498
|
+
since: { type: 'string', description: 'ISO timestamp — only entries at or after this time (optional)' },
|
|
1499
|
+
limit: { type: 'number', description: 'max entries to return (default 20, max 100)' },
|
|
1500
|
+
source: { type: 'string', enum: ['user', 'aivin'], description: 'filter by who started the work: user (direct in LightCode) or aivin' },
|
|
1501
|
+
}) },
|
|
1502
|
+
{ name: 'lightcode.deploy_hosts', group: ToolGroup.PROC, read_only: true, handler: () => lightcodeDeployHosts(),
|
|
1503
|
+
description: 'List deploy destinations already available on this machine: SSH hosts configured in LightCode (id, name, host, user — never passwords/keys), ~/.ssh/config aliases, and supported deploy adapters (vps-ssh, vercel, netlify, cloudflare, ftp, docker…). Check this before setting up deploy for a new project.',
|
|
1504
|
+
input_schema: schema({}) },
|
|
1505
|
+
{ name: 'lightcode.deploy_info', group: ToolGroup.PROC, read_only: true, handler: (a) => lightcodeDeployInfo(a, { roots }),
|
|
1506
|
+
description: 'Read a project deploy workflow configured in LightCode (environments/stages, targets, approval owners, whether a recipe or direct script exists, recent deploy runs and pending approval requests), OR check the progress/result of a running deploy session by thread_id. If configured is false, call lightcode.deploy_hosts and lightcode.deploy_setup first.',
|
|
1507
|
+
input_schema: schema({
|
|
1508
|
+
cwd: { type: 'string', description: 'project folder path' },
|
|
1509
|
+
project_id: { type: 'string', description: 'LightCode project id (alternative to cwd)' },
|
|
1510
|
+
thread_id: { type: 'string', description: 'check status and final report of a specific deploy session' },
|
|
1511
|
+
}) },
|
|
1512
|
+
{ name: 'lightcode.deploy_setup', group: ToolGroup.PROC, handler: (a, c) => lightcodeDeploySetup(a, c, { roots }),
|
|
1513
|
+
description: 'Create or update a project deploy workflow (.lcagent/workflow.json) in LightCode — works for newly created projects too (auto-registers cwd) and triggers script/recipe preparation WITHOUT running a real deploy. Never pass raw passwords or private keys; reference a saved host_id from lightcode.deploy_hosts or SSH key config. After setup, ask the person to confirm and call lightcode.deploy.',
|
|
1514
|
+
input_schema: schema({
|
|
1515
|
+
cwd: { type: 'string', description: 'project folder path' },
|
|
1516
|
+
project_id: { type: 'string', description: 'LightCode project id (alternative to cwd)' },
|
|
1517
|
+
auto: { type: 'boolean', description: 'true = let LightCode AI scan the repo and author workflow.json automatically' },
|
|
1518
|
+
merge: { type: 'boolean', description: 'keep existing environments not listed here (default true)' },
|
|
1519
|
+
parts: { type: 'array', items: { type: 'object' }, description: 'optional project parts [{ id, name }]' },
|
|
1520
|
+
environments: { type: 'array', items: { type: 'object' }, description: 'full list of stages [{ id?, name, tier, targets: [{ part?, where, host_id?, host?, adapter? }], url?, owner?, notes?, approval? }]' },
|
|
1521
|
+
env_id: { type: 'string', description: 'shortcut for 1 stage: stage id (e.g. production, staging)' },
|
|
1522
|
+
env_name: { type: 'string', description: 'shortcut for 1 stage: stage display name (default Production)' },
|
|
1523
|
+
tier: { type: 'string', enum: ['test', 'staging', 'live'], description: 'shortcut for 1 stage: color/safety tier (default live)' },
|
|
1524
|
+
where: { type: 'string', description: 'shortcut for 1 stage: destination description (e.g. "VPS Nginx /var/www/site", "Vercel")' },
|
|
1525
|
+
host_id: { type: 'string', description: 'shortcut for 1 stage: SSH host id from lightcode.deploy_hosts' },
|
|
1526
|
+
host: { type: 'string', description: 'shortcut for 1 stage: saved host name, IP/hostname, or user@host' },
|
|
1527
|
+
adapter: { type: 'string', description: 'shortcut for 1 stage: adapter id (vps-ssh | vercel | netlify | cloudflare | ftp | docker | custom)' },
|
|
1528
|
+
url: { type: 'string', description: 'shortcut for 1 stage: public URL to health-check after deploy' },
|
|
1529
|
+
owner: { type: 'string', description: 'shortcut for 1 stage: person/email to notify' },
|
|
1530
|
+
notes: { type: 'string', description: 'shortcut for 1 stage: deploy instructions (build dir, target path, restart command — no secrets)' },
|
|
1531
|
+
approval: { type: 'boolean', description: 'shortcut for 1 stage: require confirmation before deploy (default true for live)' },
|
|
1532
|
+
lang: { type: 'string', description: 'optional language tag for LightCode preparation prompts (e.g. vi)' },
|
|
1533
|
+
}) },
|
|
1534
|
+
{ name: 'lightcode.deploy', group: ToolGroup.PROC, handler: (a, c) => lightcodeDeploy(a, c, { roots }),
|
|
1535
|
+
description: 'Run a configured deploy environment in LightCode (runs the direct script with zero tokens when available, otherwise LightCode AI deploy session). ALWAYS inspect lightcode.deploy_info first (and use lightcode.deploy_setup if not configured yet), and only run after the person confirms. If it returns needs_user_support / status "needs_input", forward support_request to the user and pass their reply back with lightcode.deploy_reply.',
|
|
1536
|
+
input_schema: schema({
|
|
1537
|
+
cwd: { type: 'string', description: 'project folder path' },
|
|
1538
|
+
project_id: { type: 'string', description: 'LightCode project id (alternative to cwd)' },
|
|
1539
|
+
env: { type: 'string', description: 'environment id or name from lightcode.deploy_info (e.g. staging, production)' },
|
|
1540
|
+
envs: { type: 'array', items: { type: 'string' }, description: 'multiple environment ids/names to deploy together' },
|
|
1541
|
+
parts: { type: 'array', items: { type: 'string' }, description: 'optional subset of project part ids to deploy' },
|
|
1542
|
+
note: { type: 'string', description: 'short release note or instruction for this deploy' },
|
|
1543
|
+
wait_ms: { type: 'number', description: 'wait up to this long in ms for initial completion (default 5000, max 60000)' },
|
|
1544
|
+
}) },
|
|
1545
|
+
{ name: 'lightcode.deploy_reply', group: ToolGroup.PROC, handler: (a, c) => lightcodeDeployReply(a, c),
|
|
1546
|
+
description: 'Forward the user reply or approval back into a paused LightCode deploy / deploy-setup session (when lightcode.deploy, lightcode.deploy_setup, or lightcode.deploy_info returned status "needs_input" with support_request) so LightCode continues setting up or deploying.',
|
|
1547
|
+
input_schema: schema({
|
|
1548
|
+
thread_id: { type: 'string', description: 'deploy or deploy-setup thread_id from lightcode.deploy / deploy_setup / deploy_info' },
|
|
1549
|
+
message: { type: 'string', description: 'the user answer or confirmation (e.g. target path, domain, "logged in, continue")' },
|
|
1550
|
+
answers: { type: 'object', description: 'optional map of question text -> answer when replying to a structured HIL question' },
|
|
1551
|
+
hil_id: { type: 'string', description: 'optional hil_id from support_request' },
|
|
1552
|
+
decision: { type: 'string', enum: ['allow', 'deny', 'approve_plan'], description: 'optional decision when support_request is a permission or plan check' },
|
|
1553
|
+
wait_ms: { type: 'number', description: 'wait up to this long in ms for progress/completion after replying (default 5000, max 60000)' },
|
|
1554
|
+
}, ['thread_id']) },
|
|
1555
|
+
{ name: 'lightcode.attention', group: ToolGroup.PROC, read_only: true, handler: (a) => lightcodeAttention(a, { roots }),
|
|
1556
|
+
description: 'List everything waiting for a person in LightCode: open clarification questions, blocked/partial jobs, high-risk results, and pending merge requests. Pass cwd to scope to one project.',
|
|
1557
|
+
input_schema: schema({
|
|
1558
|
+
cwd: { type: 'string', description: 'project folder path (optional)' },
|
|
1559
|
+
}) },
|
|
1560
|
+
{ name: 'lightcode.strategy', group: ToolGroup.PROC, read_only: true, handler: (a) => lightcodeStrategy(a, { roots }),
|
|
1561
|
+
description: 'Read a project strategy map in LightCode (.lcagent/strategy.json: goals with measured spend/budget, non-goals, principles) plus lessons learned and proposed rules from repeated failures.',
|
|
1562
|
+
input_schema: schema({
|
|
1563
|
+
cwd: { type: 'string', description: 'project folder path' },
|
|
1564
|
+
}, ['cwd']) },
|
|
1565
|
+
{ name: 'lightcode.set_strategy', group: ToolGroup.PROC, handler: (a) => lightcodeSetStrategy(a, { roots }),
|
|
1566
|
+
description: 'Update a project strategy map in LightCode (.lcagent/strategy.json: goals with budgets, non-goals, principles). Existing measured spent_usd per goal is preserved by LightCode.',
|
|
1567
|
+
input_schema: schema({
|
|
1568
|
+
cwd: { type: 'string', description: 'project folder path' },
|
|
1569
|
+
goals: { type: 'array', items: { type: 'object' }, description: 'list of goals ({ id, title, status?, budget_usd?, notes? })' },
|
|
1570
|
+
non_goals: { type: 'array', items: { type: 'string' }, description: 'things explicitly out of scope' },
|
|
1571
|
+
principles: { type: 'array', items: { type: 'string' }, description: 'guiding engineering principles' },
|
|
1572
|
+
}, ['cwd']) },
|
|
1573
|
+
{ name: 'lightcode.metrics', group: ToolGroup.PROC, read_only: true, handler: (a) => lightcodeMetrics(a, { roots }),
|
|
1574
|
+
description: 'Read outcome metrics of finished LightCode jobs (pass rate, cost, duration, fix rounds, risk breakdown).',
|
|
1575
|
+
input_schema: schema({
|
|
1576
|
+
cwd: { type: 'string', description: 'project folder path (optional)' },
|
|
1577
|
+
since: { type: 'string', description: 'ISO timestamp to filter from (optional)' },
|
|
1578
|
+
}) },
|
|
1579
|
+
{ name: 'lightcode.events', group: ToolGroup.PROC, read_only: true, handler: (a) => lightcodeEvents(a, { roots }),
|
|
1580
|
+
description: 'Read durable job events emitted by LightCode (job.finished, job.attention) since the last ack or from a sequence number, and optionally acknowledge processed events.',
|
|
1581
|
+
input_schema: schema({
|
|
1582
|
+
from: { type: 'number', description: 'start sequence number (optional; default acked + 1)' },
|
|
1583
|
+
limit: { type: 'number', description: 'max events to return (default 50, max 200)' },
|
|
1584
|
+
ack_seq: { type: 'number', description: 'acknowledge events up to this sequence number' },
|
|
1585
|
+
auto_ack: { type: 'boolean', description: 'automatically acknowledge the highest returned event sequence' },
|
|
1586
|
+
only_ack: { type: 'boolean', description: 'only acknowledge ack_seq without fetching new events' },
|
|
1587
|
+
}) },
|
|
1588
|
+
{ name: 'lightcode.answer', group: ToolGroup.PROC, handler: (a, c) => lightcodeAnswer(a, c),
|
|
1589
|
+
description: 'Answer open clarification question(s) from a paused LightCode session (POST /sessions/:id/answer) and continue the same session under its saved contract and deliverables.',
|
|
1590
|
+
input_schema: schema({
|
|
1591
|
+
session_id: { type: 'string', description: 'LightCode session_id that stopped with needs_clarification' },
|
|
1592
|
+
answer: { type: 'string', description: 'plain answer text (use this or answers[])' },
|
|
1593
|
+
answers: { type: 'array', items: { type: 'object', properties: { question: { type: 'string' }, answer: { type: 'string' } } }, description: 'structured list of { question?, answer }' },
|
|
1594
|
+
on_question: { type: 'string', enum: ['assume', 'stop'], description: 'what to do if the agent asks again' },
|
|
1595
|
+
max_cost_usd: { type: 'number', description: 'optional budget cap override (USD)' },
|
|
1596
|
+
max_fix_rounds: { type: 'number', description: 'optional internal fix rounds (0-3)' },
|
|
1597
|
+
}, ['session_id']) },
|
|
1598
|
+
{ name: 'lightcode.preview', group: ToolGroup.PROC, handler: (a, c) => lightcodePreview(a, c),
|
|
1599
|
+
description: 'Start, list, capture (screenshot + console errors + failed requests), smoke-test, or stop a live dev-server preview for a LightCode session in its own worktree.',
|
|
1600
|
+
input_schema: schema({
|
|
1601
|
+
action: { type: 'string', enum: ['list', 'start', 'capture', 'smoke', 'stop'], description: 'preview operation (default list)' },
|
|
1602
|
+
session_id: { type: 'string', description: 'LightCode session_id (required for start, optional filter for list)' },
|
|
1603
|
+
preview_id: { type: 'string', description: 'preview id returned by start/list (required for capture, smoke, stop)' },
|
|
1604
|
+
command: { type: 'string', description: 'dev-server command (for start; optional if .lcagent/preview.json exists)' },
|
|
1605
|
+
wait_for: { type: 'string', description: 'ready regex/text to wait for (for start)' },
|
|
1606
|
+
wait_seconds: { type: 'number', description: 'max seconds to wait for startup (for start)' },
|
|
1607
|
+
url: { type: 'string', description: 'preview base URL if not printed by the command (for start)' },
|
|
1608
|
+
ttl_minutes: { type: 'number', description: 'auto-stop TTL in minutes (for start)' },
|
|
1609
|
+
path: { type: 'string', description: 'relative route to open (for capture)' },
|
|
1610
|
+
full_page: { type: 'boolean', description: 'capture full-page screenshot (for capture)' },
|
|
1611
|
+
inline: { type: 'boolean', description: 'return screenshot_base64 inline (for capture)' },
|
|
1612
|
+
steps: { type: 'array', items: { type: 'object', properties: { open: { type: 'string' }, expect_text: { type: 'string' }, no_console_errors: { type: 'boolean' } } }, description: 'smoke test steps (for smoke)' },
|
|
1613
|
+
}) },
|
|
1614
|
+
];
|
|
1615
|
+
}
|