@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,293 @@
|
|
|
1
|
+
// Đăng nhập agent cho thành viên máy tính tổ chức, KHÔNG cần màn hình (17/11/2026). Máy không có trình duyệt / màn hình: CLI chạy lệnh đăng
|
|
2
|
+
// nhập của agent dưới tài khoản Linux của thành viên, đọc link (và mã) agent in ra, BE đưa cho người dùng mở trên máy / điện thoại của họ.
|
|
3
|
+
// Tệp đăng nhập agent ghi nằm trong HOME của thành viên — chỉ họ dùng.
|
|
4
|
+
//
|
|
5
|
+
// Đã đo trên container Linux sạch (node:22-bookworm-slim):
|
|
6
|
+
// - Claude Code 2.1.326 `claude auth login --claudeai`: in "If the browser didn't open, visit: https://claude.com/cai/oauth/authorize?…" rồi
|
|
7
|
+
// chờ "Paste code here if prompted >" trên stdin → người dùng đăng nhập, trang đích hiện mã, dán mã vào Aivin, CLI ghi mã vào stdin.
|
|
8
|
+
// - Codex 0.169.0 `codex login --device-auth`: in link https://auth.openai.com/codex/device + mã một lần (hết hạn 15 phút), tự chờ người
|
|
9
|
+
// dùng xác nhận rồi thoát — không cần nhập gì thêm.
|
|
10
|
+
import { randomUUID } from 'crypto';
|
|
11
|
+
import { spawn } from 'child_process';
|
|
12
|
+
import { DeviceErrorCode, ToolGroup } from './constants.mjs';
|
|
13
|
+
import { DeviceToolError } from './sandbox.mjs';
|
|
14
|
+
import { memberSpawnArgs } from './localLlmMembers.mjs';
|
|
15
|
+
|
|
16
|
+
// eslint-disable-next-line no-control-regex -- mã màu ANSI agent in ra
|
|
17
|
+
export const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/g;
|
|
18
|
+
const URL_RE = /https:\/\/[^\s'"<>`]+/g;
|
|
19
|
+
const LOGIN_TTL_MS = 15 * 60_000;
|
|
20
|
+
const START_WAIT_MS = 25_000;
|
|
21
|
+
const CODE_WAIT_MS = 60_000;
|
|
22
|
+
const MAX_OUTPUT = 16_000;
|
|
23
|
+
const CODE_RE = /^[A-Za-z0-9_\-#.~=+/]{6,1024}$/;
|
|
24
|
+
const CALLBACK_TIMEOUT_MS = 10_000;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Đọc cổng callback cục bộ từ tham số `redirect_uri` trong đường dẫn OAuth (vd `http://localhost:8085/oauth2callback`).
|
|
28
|
+
* Trả `{ port, path }` nếu đường dẫn OAuth trỏ về loopback, ngược lại `null`.
|
|
29
|
+
*/
|
|
30
|
+
export function parseLocalCallbackTarget(authUrl) {
|
|
31
|
+
try {
|
|
32
|
+
const outer = new URL(String(authUrl || ''));
|
|
33
|
+
const rawRedirect = outer.searchParams.get('redirect_uri') || '';
|
|
34
|
+
if (!rawRedirect) return null;
|
|
35
|
+
const redir = new URL(rawRedirect);
|
|
36
|
+
if (redir.protocol !== 'http:') return null;
|
|
37
|
+
const host = redir.hostname.toLowerCase();
|
|
38
|
+
if (host !== 'localhost' && host !== '127.0.0.1') return null;
|
|
39
|
+
const port = Number(redir.port || 80);
|
|
40
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535) return null;
|
|
41
|
+
return { port, path: redir.pathname || '/' };
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Kiểm tra đường dẫn callback người dùng dán vào có khớp chính xác cổng loopback của phiên đăng nhập này không (chống SSRF). */
|
|
48
|
+
export function normalizeLocalCallbackUrl(rawInput, expectedPort) {
|
|
49
|
+
const text = String(rawInput || '').trim();
|
|
50
|
+
if (!/^https?:\/\//i.test(text) || /[\r\n\0]/.test(text)) return null;
|
|
51
|
+
try {
|
|
52
|
+
const u = new URL(text);
|
|
53
|
+
if (u.protocol !== 'http:') return null;
|
|
54
|
+
const host = u.hostname.toLowerCase();
|
|
55
|
+
if (host !== 'localhost' && host !== '127.0.0.1') return null;
|
|
56
|
+
const port = Number(u.port || 80);
|
|
57
|
+
if (!expectedPort || port !== expectedPort) return null;
|
|
58
|
+
if (!u.searchParams.get('code') && !u.searchParams.get('token') && !u.searchParams.get('state')) return null;
|
|
59
|
+
return `http://127.0.0.1:${port}${u.pathname}${u.search}`;
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const LoginState = Object.freeze({ PENDING: 'pending', SUCCEEDED: 'succeeded', FAILED: 'failed', EXPIRED: 'expired' });
|
|
66
|
+
|
|
67
|
+
const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
|
|
68
|
+
const failed = (msg, code = DeviceErrorCode.EXECUTION_FAILED) => new DeviceToolError(code, msg);
|
|
69
|
+
|
|
70
|
+
/** Link / mã trong chữ agent in ra (đã bỏ mã màu). null = chưa đủ. */
|
|
71
|
+
export const LOGIN_FLOWS = Object.freeze({
|
|
72
|
+
claude: {
|
|
73
|
+
argv: ['auth', 'login', '--claudeai'],
|
|
74
|
+
needsCode: true,
|
|
75
|
+
parse(text) {
|
|
76
|
+
const url = (text.match(URL_RE) || []).find((u) => /\/oauth\/authorize\?/.test(u));
|
|
77
|
+
return url ? { url } : null;
|
|
78
|
+
},
|
|
79
|
+
logout: ['auth', 'logout'],
|
|
80
|
+
},
|
|
81
|
+
codex: {
|
|
82
|
+
argv: ['login', '--device-auth'],
|
|
83
|
+
needsCode: false,
|
|
84
|
+
parse(text) {
|
|
85
|
+
const url = (text.match(URL_RE) || []).find((u) => /\/device\b/.test(u));
|
|
86
|
+
const code = /\b([A-Z0-9]{4}-[A-Z0-9]{4,8})\b/.exec(text)?.[1];
|
|
87
|
+
return url && code ? { url, user_code: code } : null;
|
|
88
|
+
},
|
|
89
|
+
logout: ['logout'],
|
|
90
|
+
},
|
|
91
|
+
gemini: {
|
|
92
|
+
argv: ['auth', 'login', '--no-browser'],
|
|
93
|
+
needsCode: true,
|
|
94
|
+
parse(text) {
|
|
95
|
+
const url = (text.match(URL_RE) || []).find((u) => /accounts\.google\.com|oauth2|\/authorize\?/.test(u));
|
|
96
|
+
if (!url) return null;
|
|
97
|
+
const cb = parseLocalCallbackTarget(url);
|
|
98
|
+
return { url, ...(cb ? { callbackPort: cb.port, inputKind: 'callback_url' } : {}) };
|
|
99
|
+
},
|
|
100
|
+
logout: ['auth', 'logout'],
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
/** Bản ghi một lần đăng nhập trả cho BE — không kèm chữ thô agent in ra (có thể dài / lạ), chỉ lỗi rút gọn. */
|
|
105
|
+
const publicOf = (s) => ({
|
|
106
|
+
login_id: s.id, agent: s.agent, state: s.state, url: s.url || null, user_code: s.user_code || null, needs_code: s.needsCode && s.state === LoginState.PENDING,
|
|
107
|
+
...(s.inputKind ? { input_kind: s.inputKind } : {}),
|
|
108
|
+
expires_at: s.expiresAt, ...(s.error ? { error: s.error } : {}),
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* `llm` = bộ mô hình trên máy ở chế độ máy tổ chức (localLlm.mjs, memberMode) — dùng chung danh sách agent đã cài + bộ nhớ "đã đăng nhập".
|
|
113
|
+
* Mỗi (thành viên, agent) tối đa một lần đăng nhập đang chờ; bắt đầu lại thì huỷ lần cũ.
|
|
114
|
+
*/
|
|
115
|
+
export function createLlmLogin({ llm, spawnImpl = spawn, fetchImpl = globalThis.fetch, now = Date.now, ttlMs = LOGIN_TTL_MS, startWaitMs = START_WAIT_MS, codeWaitMs = CODE_WAIT_MS } = {}) {
|
|
116
|
+
const sessions = new Map();
|
|
117
|
+
|
|
118
|
+
const accountOf = (ctx) => {
|
|
119
|
+
const account = ctx?.runAs;
|
|
120
|
+
if (!account?.name) throw invalid('Sign-in on this shared computer needs a member');
|
|
121
|
+
return account;
|
|
122
|
+
};
|
|
123
|
+
const adapterOf = (agent) => {
|
|
124
|
+
const flow = LOGIN_FLOWS[agent];
|
|
125
|
+
if (!flow) throw invalid(`Sign-in from Aivin is not available for "${agent}" on this computer`);
|
|
126
|
+
return { adapter: llm.adapterFor(agent), flow };
|
|
127
|
+
};
|
|
128
|
+
const own = (id, account) => {
|
|
129
|
+
const s = sessions.get(String(id || ''));
|
|
130
|
+
if (!s || s.account.name !== account.name) throw failed('This sign-in is not running any more — start again', DeviceErrorCode.NOT_FOUND);
|
|
131
|
+
return s;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
function end(s, state, error) {
|
|
135
|
+
if (s.state !== LoginState.PENDING) return;
|
|
136
|
+
s.state = state;
|
|
137
|
+
if (error) s.error = String(error).replace(ANSI_RE, '').trim().slice(-300);
|
|
138
|
+
clearTimeout(s.timer);
|
|
139
|
+
try { s.child.stdin?.end(); } catch { /* đã đóng */ }
|
|
140
|
+
if (state !== LoginState.SUCCEEDED) try { s.child.kill(); } catch { /* đã thoát */ }
|
|
141
|
+
llm.signIn?.forget(s.agent, s.account);
|
|
142
|
+
for (const fn of s.waiters.splice(0)) fn();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function sweep() {
|
|
146
|
+
for (const [id, s] of sessions) if (s.state !== LoginState.PENDING && now() - s.endedAt > ttlMs) sessions.delete(id);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Chờ tới khi `test()` đúng, lần đăng nhập kết thúc, hoặc hết `ms`. */
|
|
150
|
+
function waitFor(s, test, ms) {
|
|
151
|
+
if (test() || s.state !== LoginState.PENDING) return Promise.resolve();
|
|
152
|
+
return new Promise((resolve) => {
|
|
153
|
+
const timer = setTimeout(done, ms);
|
|
154
|
+
function done() { clearTimeout(timer); const i = s.waiters.indexOf(check); if (i >= 0) s.waiters.splice(i, 1); resolve(); }
|
|
155
|
+
function check() { if (test() || s.state !== LoginState.PENDING) done(); }
|
|
156
|
+
s.waiters.push(check);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function start(args = {}, ctx = {}) {
|
|
161
|
+
const account = accountOf(ctx);
|
|
162
|
+
const agent = String(args.agent || '');
|
|
163
|
+
const { adapter, flow } = adapterOf(agent);
|
|
164
|
+
sweep();
|
|
165
|
+
for (const s of sessions.values()) if (s.account.name === account.name && s.agent === agent) end(s, LoginState.FAILED, 'Replaced by a new sign-in');
|
|
166
|
+
const [cmd, argv, opts] = memberSpawnArgs(account, llm.binOf(adapter).bin, flow.argv, { dir: llm.memberDir });
|
|
167
|
+
const child = spawnImpl(cmd, argv, { ...opts, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
168
|
+
const s = {
|
|
169
|
+
id: randomUUID(), agent, account, child, needsCode: flow.needsCode, state: LoginState.PENDING, output: '', url: null, user_code: null,
|
|
170
|
+
expiresAt: now() + ttlMs, endedAt: 0, waiters: [], timer: null, codeSent: false,
|
|
171
|
+
};
|
|
172
|
+
sessions.set(s.id, s);
|
|
173
|
+
const onData = (d) => {
|
|
174
|
+
s.output = (s.output + String(d)).slice(-MAX_OUTPUT);
|
|
175
|
+
if (!s.url) {
|
|
176
|
+
const found = flow.parse(s.output.replace(ANSI_RE, ''));
|
|
177
|
+
if (found) {
|
|
178
|
+
const cb = !found.callbackPort && found.url ? parseLocalCallbackTarget(found.url) : null;
|
|
179
|
+
Object.assign(s, found, cb ? { callbackPort: cb.port, inputKind: found.inputKind || 'callback_url' } : {});
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (const fn of [...s.waiters]) fn();
|
|
183
|
+
};
|
|
184
|
+
child.stdout?.on('data', onData);
|
|
185
|
+
child.stderr?.on('data', onData);
|
|
186
|
+
child.once('error', (e) => end(s, LoginState.FAILED, `Could not start ${adapter.label}: ${e.message}`));
|
|
187
|
+
child.once('exit', (code) => {
|
|
188
|
+
s.endedAt = now();
|
|
189
|
+
if (code === 0) end(s, LoginState.SUCCEEDED);
|
|
190
|
+
else end(s, LoginState.FAILED, s.output || `${adapter.label} sign-in exited (${code})`);
|
|
191
|
+
});
|
|
192
|
+
s.timer = setTimeout(() => { s.endedAt = now(); end(s, LoginState.EXPIRED, 'Sign-in expired'); }, ttlMs);
|
|
193
|
+
s.timer.unref?.();
|
|
194
|
+
await waitFor(s, () => !!s.url, startWaitMs);
|
|
195
|
+
if (!s.url && s.state === LoginState.PENDING) end(s, LoginState.FAILED, `${adapter.label} did not print a sign-in link`);
|
|
196
|
+
return publicOf(s);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Claude Code / Gemini / công cụ OAuth cục bộ:
|
|
201
|
+
* - Nếu phiên dùng cổng callback cục bộ (`callbackPort`) và người dùng dán đường dẫn `http://localhost:<port>/...?code=...`:
|
|
202
|
+
* CLI chuyển tiếp thẳng yêu cầu đó tới `127.0.0.1:<callbackPort>` bên trong container để tiến trình đăng nhập tự hoàn tất.
|
|
203
|
+
* - Ngược lại ghi mã vào stdin của tiến trình đang chờ (Claude Code).
|
|
204
|
+
*/
|
|
205
|
+
async function submitCode(args = {}, ctx = {}) {
|
|
206
|
+
const account = accountOf(ctx);
|
|
207
|
+
const s = own(args.login_id, account);
|
|
208
|
+
const code = String(args.code || '').trim();
|
|
209
|
+
if (!s.needsCode) throw invalid('This sign-in does not take a code — finish it in the browser');
|
|
210
|
+
const callbackUrl = s.callbackPort ? normalizeLocalCallbackUrl(code, s.callbackPort) : null;
|
|
211
|
+
if (!callbackUrl && !CODE_RE.test(code)) {
|
|
212
|
+
throw invalid(s.callbackPort
|
|
213
|
+
? 'Paste the full localhost callback URL from your browser address bar (or the sign-in code)'
|
|
214
|
+
: 'That does not look like a sign-in code — copy the whole code from the sign-in page');
|
|
215
|
+
}
|
|
216
|
+
if (s.state !== LoginState.PENDING) return publicOf(s);
|
|
217
|
+
if (s.codeSent) throw invalid('A code was already sent for this sign-in — start again if it failed');
|
|
218
|
+
s.codeSent = true;
|
|
219
|
+
if (callbackUrl) {
|
|
220
|
+
try {
|
|
221
|
+
const signal = AbortSignal.timeout ? AbortSignal.timeout(CALLBACK_TIMEOUT_MS) : undefined;
|
|
222
|
+
await fetchImpl(callbackUrl, { method: 'GET', redirect: 'manual', signal });
|
|
223
|
+
} catch (e) {
|
|
224
|
+
end(s, LoginState.FAILED, `Local OAuth callback delivery failed: ${e?.message || e}`);
|
|
225
|
+
}
|
|
226
|
+
} else {
|
|
227
|
+
try { s.child.stdin.write(`${code}\n`); } catch (e) { end(s, LoginState.FAILED, e.message); }
|
|
228
|
+
}
|
|
229
|
+
await waitFor(s, () => false, codeWaitMs);
|
|
230
|
+
return publicOf(s);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Trạng thái lần đăng nhập; `wait_ms` (≤ 25 s): chờ tới khi xong (Codex: người dùng xác nhận mã trên trình duyệt). */
|
|
234
|
+
async function poll(args = {}, ctx = {}) {
|
|
235
|
+
const account = accountOf(ctx);
|
|
236
|
+
const s = own(args.login_id, account);
|
|
237
|
+
const waitMs = Math.min(Math.max(0, Number(args.wait_ms) || 0), 25_000);
|
|
238
|
+
if (waitMs) await waitFor(s, () => false, waitMs);
|
|
239
|
+
return publicOf(s);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Agent đã cài + thành viên đã đăng nhập chưa (hỏi lại thật, không dùng kết quả nhớ). */
|
|
243
|
+
async function status(_args = {}, ctx = {}) {
|
|
244
|
+
const account = accountOf(ctx);
|
|
245
|
+
const agents = await Promise.all(llm.agents().map(async (a) => {
|
|
246
|
+
const signedIn = await llm.signIn.status(llm.adapterFor(a.id), account, { fresh: true }).catch(() => false);
|
|
247
|
+
return { id: a.id, label: a.label, ...(a.version ? { version: a.version } : {}), signed_in: signedIn, can_sign_in: !!LOGIN_FLOWS[a.id] };
|
|
248
|
+
}));
|
|
249
|
+
return { agents };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async function logout(args = {}, ctx = {}) {
|
|
253
|
+
const account = accountOf(ctx);
|
|
254
|
+
const agent = String(args.agent || '');
|
|
255
|
+
const { adapter, flow } = adapterOf(agent);
|
|
256
|
+
for (const s of sessions.values()) if (s.account.name === account.name && s.agent === agent) end(s, LoginState.FAILED, 'Signed out');
|
|
257
|
+
const r = await llm.signIn.run(account, llm.binOf(adapter).bin, flow.logout, { dir: llm.memberDir, timeoutMs: 20_000 });
|
|
258
|
+
llm.signIn.forget(agent, account);
|
|
259
|
+
const signedIn = await llm.signIn.status(adapter, account, { fresh: true }).catch(() => false);
|
|
260
|
+
return { agent, signed_in: signedIn, ok: !signedIn, ...(r.code !== 0 && signedIn ? { error: (r.err || r.out).trim().slice(-300) } : {}) };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function closeAll() {
|
|
264
|
+
for (const s of sessions.values()) end(s, LoginState.FAILED, 'Computer is shutting down');
|
|
265
|
+
sessions.clear();
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return { start, submitCode, poll, status, logout, closeAll };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const str = (description) => ({ type: 'string', description });
|
|
272
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
273
|
+
|
|
274
|
+
/** Công cụ BE-only của máy tổ chức: trạng thái đăng nhập + đăng nhập / đăng xuất agent cho thành viên của lời gọi. */
|
|
275
|
+
export function buildLlmLoginTools(login) {
|
|
276
|
+
const call = (fn) => (a, c, e) => fn(a, { ...c, runAs: e?.runAs });
|
|
277
|
+
const base = { group: ToolGroup.PROC, read_only: true, internal: true };
|
|
278
|
+
return [
|
|
279
|
+
{ ...base, name: 'llm.status', handler: call(login.status),
|
|
280
|
+
description: 'BE-only: coding agents on this shared computer and whether this member is signed in to each.', input_schema: schema({}) },
|
|
281
|
+
{ ...base, name: 'llm.login_start', handler: call(login.start),
|
|
282
|
+
description: "BE-only: start signing this member in to an agent. Returns a link (and a one-time code for codex, or callback_url prompt for gemini) to open on the member's own device.",
|
|
283
|
+
input_schema: schema({ agent: str('claude | codex | gemini') }, ['agent']) },
|
|
284
|
+
{ ...base, name: 'llm.login_code', handler: call(login.submitCode),
|
|
285
|
+
description: 'BE-only: give the code shown after signing in (claude) or the localhost callback URL (gemini) to the running sign-in, wait for it to finish.',
|
|
286
|
+
input_schema: schema({ login_id: str('from llm.login_start'), code: str('code or localhost callback URL from the sign-in page') }, ['login_id', 'code']) },
|
|
287
|
+
{ ...base, name: 'llm.login_poll', handler: call(login.poll),
|
|
288
|
+
description: 'BE-only: state of a running sign-in (pending | succeeded | failed | expired); wait_ms waits for it to finish.',
|
|
289
|
+
input_schema: schema({ login_id: str('from llm.login_start'), wait_ms: { type: 'number', description: 'max 25000' } }, ['login_id']) },
|
|
290
|
+
{ ...base, name: 'llm.logout', handler: call(login.logout),
|
|
291
|
+
description: 'BE-only: sign this member out of an agent on this shared computer.', input_schema: schema({ agent: str('claude | codex | gemini') }, ['agent']) },
|
|
292
|
+
];
|
|
293
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Mô hình trên máy ở MÁY TÍNH TỔ CHỨC (`--multi-user`, 17/11/2026): mỗi thành viên dùng agent (Claude Code / Codex) bằng TÀI KHOẢN CỦA CHÍNH
|
|
2
|
+
// HỌ — agent chạy dưới tài khoản Linux của thành viên (HOME = /home/<vùng>), nên tệp đăng nhập (~/.claude, ~/.codex) và hạn mức gói là của
|
|
3
|
+
// người đó, không ai dùng chung tài khoản của ai. Chưa đăng nhập → lời gọi báo `LOCAL_LLM_NOT_SIGNED_IN` ngay (không khởi động agent), BE
|
|
4
|
+
// chạy cloud và mời người dùng đăng nhập (localLlmLogin.mjs).
|
|
5
|
+
//
|
|
6
|
+
// Antigravity không có ở chế độ này: chưa có cách đăng nhập không màn hình, và tệp cài đặt không tách được theo người.
|
|
7
|
+
import fs from 'fs';
|
|
8
|
+
import path from 'path';
|
|
9
|
+
import { execFile } from 'child_process';
|
|
10
|
+
import { accountEnv, withProcessCap } from './multiUser.mjs';
|
|
11
|
+
import { agentEnv } from './sandbox.mjs';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Thư mục làm việc (cwd) của agent khi chạy cho thành viên: rỗng, của root, thành viên chỉ đọc / đi qua được (0755) — agent không thấy tệp
|
|
15
|
+
* dự án nào, thành viên cũng không ghi vào đây được (lớp ghi của container không có hạn mức đĩa). Không đặt trong /home/<vùng>: root không tạo
|
|
16
|
+
* / chown gì trong thư mục do thành viên điều khiển (liên kết tượng trưng).
|
|
17
|
+
*/
|
|
18
|
+
export const MEMBER_LLM_DIR = '/var/lib/aivin-llm';
|
|
19
|
+
export const MEMBER_LLM_AGENTS = Object.freeze(['claude', 'codex', 'gemini']);
|
|
20
|
+
|
|
21
|
+
/** Biến của agent mà tiến trình root có thể mang — không để lọt sang tài khoản thành viên (agent phải đọc đăng nhập trong HOME của họ). */
|
|
22
|
+
const ROOT_ONLY_ENV = ['CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN', 'OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'LCAGENT_LICENSE_FILE', 'AIVIN_LIGHTCODE_LICENSE_KEY', 'AIVIN_LIGHTCODE_MACHINE_ID'];
|
|
23
|
+
|
|
24
|
+
/** `env` của agent chạy cho thành viên: HOME / USER của họ, không tự cập nhật (bản cài thuộc root), không mở trình duyệt (máy không màn hình). */
|
|
25
|
+
export function memberAgentEnv(account, base = process.env) {
|
|
26
|
+
const env = { ...accountEnv(account, agentEnv(base)), DISABLE_AUTOUPDATER: '1', BROWSER: '/bin/true', NO_COLOR: '1' };
|
|
27
|
+
for (const k of ROOT_ONLY_ENV) delete env[k];
|
|
28
|
+
return env;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let dirReady = false;
|
|
32
|
+
function ensureMemberDir(dir) {
|
|
33
|
+
if (dirReady && dir === MEMBER_LLM_DIR) return;
|
|
34
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o755 });
|
|
35
|
+
try { fs.chmodSync(dir, 0o755); } catch { /* không phải chủ (thử nghiệm) */ }
|
|
36
|
+
if (dir === MEMBER_LLM_DIR) dirReady = true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `[lệnh, tham số, tuỳ chọn spawn]` để chạy `bin argv` dưới tài khoản thành viên, có trần số tiến trình (prlimit). */
|
|
40
|
+
export function memberSpawnArgs(account, bin, argv, { dir = MEMBER_LLM_DIR, base = process.env } = {}) {
|
|
41
|
+
ensureMemberDir(dir);
|
|
42
|
+
const [cmd, args] = withProcessCap(bin, argv);
|
|
43
|
+
return [cmd, args, { cwd: dir, env: memberAgentEnv(account, base), uid: account.uid, gid: account.gid, windowsHide: true }];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Lệnh hỏi "đã đăng nhập chưa" của từng agent (không gọi mạng, < 1 s). */
|
|
47
|
+
export const SIGN_IN_PROBES = Object.freeze({
|
|
48
|
+
claude: {
|
|
49
|
+
argv: ['auth', 'status', '--json'],
|
|
50
|
+
// `{"loggedIn": true, "authMethod": "claude.ai" …}` — mã thoát 1 khi chưa đăng nhập (đo 2.1.326).
|
|
51
|
+
parse: (code, out) => {
|
|
52
|
+
try { return JSON.parse(out)?.loggedIn === true; } catch { return code === 0; }
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
// "Not logged in", mã thoát 1 (đo 0.169.0).
|
|
56
|
+
codex: { argv: ['login', 'status'], parse: (code) => code === 0 },
|
|
57
|
+
// Gemini CLI lưu phiên OAuth cá nhân trong ~/.gemini/oauth_creds.json (không cần gọi mạng để kiểm tra).
|
|
58
|
+
gemini: {
|
|
59
|
+
check: (account) => {
|
|
60
|
+
if (!account?.home) return false;
|
|
61
|
+
for (const file of ['oauth_creds.json', 'google_accounts.json']) {
|
|
62
|
+
try {
|
|
63
|
+
const raw = fs.readFileSync(path.join(account.home, '.gemini', file), 'utf8').trim();
|
|
64
|
+
if (raw && raw !== '{}' && raw !== '[]') return true;
|
|
65
|
+
} catch { /* chưa đăng nhập */ }
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
function runAs(account, bin, argv, { timeoutMs = 15_000, dir } = {}) {
|
|
73
|
+
const [cmd, args, opts] = memberSpawnArgs(account, bin, argv, { dir });
|
|
74
|
+
return new Promise((resolve) => {
|
|
75
|
+
execFile(cmd, args, { ...opts, encoding: 'utf8', timeout: timeoutMs, maxBuffer: 256 * 1024 }, (err, stdout, stderr) => {
|
|
76
|
+
const code = err ? (typeof err.code === 'number' ? err.code : -1) : 0;
|
|
77
|
+
resolve({ code, out: String(stdout || ''), err: String(stderr || '') });
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* "Thành viên đã đăng nhập agent chưa", nhớ ngắn: đã đăng nhập 5 phút, chưa 20 s (vừa đăng nhập xong ở nơi khác thì sớm thấy). Lời gọi bị
|
|
84
|
+
* agent báo lỗi xác thực / đăng nhập, đăng xuất → `forget` để hỏi lại ngay.
|
|
85
|
+
*/
|
|
86
|
+
export function createSignInChecker({ binOf, run = runAs, now = Date.now, okTtlMs = 5 * 60_000, noTtlMs = 20_000, dir } = {}) {
|
|
87
|
+
const cache = new Map();
|
|
88
|
+
const keyOf = (agentId, account) => `${account.name}|${agentId}`;
|
|
89
|
+
|
|
90
|
+
async function status(adapter, account, { fresh = false } = {}) {
|
|
91
|
+
const probe = SIGN_IN_PROBES[adapter.id];
|
|
92
|
+
if (!probe) return false;
|
|
93
|
+
const key = keyOf(adapter.id, account);
|
|
94
|
+
const hit = cache.get(key);
|
|
95
|
+
if (!fresh && hit && now() - hit.at < (hit.ok ? okTtlMs : noTtlMs)) return hit.ok;
|
|
96
|
+
const bin = binOf(adapter)?.bin;
|
|
97
|
+
if (!bin) return false;
|
|
98
|
+
let ok = false;
|
|
99
|
+
if (typeof probe.check === 'function') {
|
|
100
|
+
ok = !!probe.check(account);
|
|
101
|
+
} else {
|
|
102
|
+
const r = await run(account, bin, probe.argv, { dir });
|
|
103
|
+
ok = !!probe.parse(r.code, r.out);
|
|
104
|
+
}
|
|
105
|
+
if (cache.size > 2000) cache.clear();
|
|
106
|
+
cache.set(key, { ok, at: now() });
|
|
107
|
+
return ok;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
status,
|
|
112
|
+
forget: (agentId, account) => cache.delete(keyOf(agentId, account)),
|
|
113
|
+
run: (account, bin, argv, opts) => run(account, bin, argv, { dir, ...opts }),
|
|
114
|
+
};
|
|
115
|
+
}
|