@aivin-labs/cli 1.0.75 → 1.0.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,219 +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
-
25
- export const LoginState = Object.freeze({ PENDING: 'pending', SUCCEEDED: 'succeeded', FAILED: 'failed', EXPIRED: 'expired' });
26
-
27
- const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
28
- const failed = (msg, code = DeviceErrorCode.EXECUTION_FAILED) => new DeviceToolError(code, msg);
29
-
30
- /** Link / mã trong chữ agent in ra (đã bỏ mã màu). null = chưa đủ. */
31
- export const LOGIN_FLOWS = Object.freeze({
32
- claude: {
33
- argv: ['auth', 'login', '--claudeai'],
34
- needsCode: true,
35
- parse(text) {
36
- const url = (text.match(URL_RE) || []).find((u) => /\/oauth\/authorize\?/.test(u));
37
- return url ? { url } : null;
38
- },
39
- logout: ['auth', 'logout'],
40
- },
41
- codex: {
42
- argv: ['login', '--device-auth'],
43
- needsCode: false,
44
- parse(text) {
45
- const url = (text.match(URL_RE) || []).find((u) => /\/device\b/.test(u));
46
- const code = /\b([A-Z0-9]{4}-[A-Z0-9]{4,8})\b/.exec(text)?.[1];
47
- return url && code ? { url, user_code: code } : null;
48
- },
49
- logout: ['logout'],
50
- },
51
- });
52
-
53
- /** 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. */
54
- const publicOf = (s) => ({
55
- 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,
56
- expires_at: s.expiresAt, ...(s.error ? { error: s.error } : {}),
57
- });
58
-
59
- /**
60
- * `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".
61
- * 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ũ.
62
- */
63
- export function createLlmLogin({ llm, spawnImpl = spawn, now = Date.now, ttlMs = LOGIN_TTL_MS, startWaitMs = START_WAIT_MS, codeWaitMs = CODE_WAIT_MS } = {}) {
64
- const sessions = new Map();
65
-
66
- const accountOf = (ctx) => {
67
- const account = ctx?.runAs;
68
- if (!account?.name) throw invalid('Sign-in on this shared computer needs a member');
69
- return account;
70
- };
71
- const adapterOf = (agent) => {
72
- const flow = LOGIN_FLOWS[agent];
73
- if (!flow) throw invalid(`Sign-in from Aivin is not available for "${agent}" on this computer`);
74
- return { adapter: llm.adapterFor(agent), flow };
75
- };
76
- const own = (id, account) => {
77
- const s = sessions.get(String(id || ''));
78
- if (!s || s.account.name !== account.name) throw failed('This sign-in is not running any more — start again', DeviceErrorCode.NOT_FOUND);
79
- return s;
80
- };
81
-
82
- function end(s, state, error) {
83
- if (s.state !== LoginState.PENDING) return;
84
- s.state = state;
85
- if (error) s.error = String(error).replace(ANSI_RE, '').trim().slice(-300);
86
- clearTimeout(s.timer);
87
- try { s.child.stdin?.end(); } catch { /* đã đóng */ }
88
- if (state !== LoginState.SUCCEEDED) try { s.child.kill(); } catch { /* đã thoát */ }
89
- llm.signIn?.forget(s.agent, s.account);
90
- for (const fn of s.waiters.splice(0)) fn();
91
- }
92
-
93
- function sweep() {
94
- for (const [id, s] of sessions) if (s.state !== LoginState.PENDING && now() - s.endedAt > ttlMs) sessions.delete(id);
95
- }
96
-
97
- /** Chờ tới khi `test()` đúng, lần đăng nhập kết thúc, hoặc hết `ms`. */
98
- function waitFor(s, test, ms) {
99
- if (test() || s.state !== LoginState.PENDING) return Promise.resolve();
100
- return new Promise((resolve) => {
101
- const timer = setTimeout(done, ms);
102
- function done() { clearTimeout(timer); const i = s.waiters.indexOf(check); if (i >= 0) s.waiters.splice(i, 1); resolve(); }
103
- function check() { if (test() || s.state !== LoginState.PENDING) done(); }
104
- s.waiters.push(check);
105
- });
106
- }
107
-
108
- async function start(args = {}, ctx = {}) {
109
- const account = accountOf(ctx);
110
- const agent = String(args.agent || '');
111
- const { adapter, flow } = adapterOf(agent);
112
- sweep();
113
- 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');
114
- const [cmd, argv, opts] = memberSpawnArgs(account, llm.binOf(adapter).bin, flow.argv, { dir: llm.memberDir });
115
- const child = spawnImpl(cmd, argv, { ...opts, stdio: ['pipe', 'pipe', 'pipe'] });
116
- const s = {
117
- id: randomUUID(), agent, account, child, needsCode: flow.needsCode, state: LoginState.PENDING, output: '', url: null, user_code: null,
118
- expiresAt: now() + ttlMs, endedAt: 0, waiters: [], timer: null, codeSent: false,
119
- };
120
- sessions.set(s.id, s);
121
- const onData = (d) => {
122
- s.output = (s.output + String(d)).slice(-MAX_OUTPUT);
123
- if (!s.url) {
124
- const found = flow.parse(s.output.replace(ANSI_RE, ''));
125
- if (found) Object.assign(s, found);
126
- }
127
- for (const fn of [...s.waiters]) fn();
128
- };
129
- child.stdout?.on('data', onData);
130
- child.stderr?.on('data', onData);
131
- child.once('error', (e) => end(s, LoginState.FAILED, `Could not start ${adapter.label}: ${e.message}`));
132
- child.once('exit', (code) => {
133
- s.endedAt = now();
134
- if (code === 0) end(s, LoginState.SUCCEEDED);
135
- else end(s, LoginState.FAILED, s.output || `${adapter.label} sign-in exited (${code})`);
136
- });
137
- s.timer = setTimeout(() => { s.endedAt = now(); end(s, LoginState.EXPIRED, 'Sign-in expired'); }, ttlMs);
138
- s.timer.unref?.();
139
- await waitFor(s, () => !!s.url, startWaitMs);
140
- if (!s.url && s.state === LoginState.PENDING) end(s, LoginState.FAILED, `${adapter.label} did not print a sign-in link`);
141
- return publicOf(s);
142
- }
143
-
144
- /** Claude Code: mã trang đăng nhập hiện ra → ghi vào stdin, chờ agent đổi mã lấy phiên đăng nhập (thoát 0). */
145
- async function submitCode(args = {}, ctx = {}) {
146
- const account = accountOf(ctx);
147
- const s = own(args.login_id, account);
148
- const code = String(args.code || '').trim();
149
- if (!s.needsCode) throw invalid('This sign-in does not take a code — finish it in the browser');
150
- if (!CODE_RE.test(code)) throw invalid('That does not look like a sign-in code — copy the whole code from the sign-in page');
151
- if (s.state !== LoginState.PENDING) return publicOf(s);
152
- if (s.codeSent) throw invalid('A code was already sent for this sign-in — start again if it failed');
153
- s.codeSent = true;
154
- try { s.child.stdin.write(`${code}\n`); } catch (e) { end(s, LoginState.FAILED, e.message); }
155
- await waitFor(s, () => false, codeWaitMs);
156
- return publicOf(s);
157
- }
158
-
159
- /** 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). */
160
- async function poll(args = {}, ctx = {}) {
161
- const account = accountOf(ctx);
162
- const s = own(args.login_id, account);
163
- const waitMs = Math.min(Math.max(0, Number(args.wait_ms) || 0), 25_000);
164
- if (waitMs) await waitFor(s, () => false, waitMs);
165
- return publicOf(s);
166
- }
167
-
168
- /** 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ớ). */
169
- async function status(_args = {}, ctx = {}) {
170
- const account = accountOf(ctx);
171
- const agents = await Promise.all(llm.agents().map(async (a) => {
172
- const signedIn = await llm.signIn.status(llm.adapterFor(a.id), account, { fresh: true }).catch(() => false);
173
- return { id: a.id, label: a.label, ...(a.version ? { version: a.version } : {}), signed_in: signedIn, can_sign_in: !!LOGIN_FLOWS[a.id] };
174
- }));
175
- return { agents };
176
- }
177
-
178
- async function logout(args = {}, ctx = {}) {
179
- const account = accountOf(ctx);
180
- const agent = String(args.agent || '');
181
- const { adapter, flow } = adapterOf(agent);
182
- for (const s of sessions.values()) if (s.account.name === account.name && s.agent === agent) end(s, LoginState.FAILED, 'Signed out');
183
- const r = await llm.signIn.run(account, llm.binOf(adapter).bin, flow.logout, { dir: llm.memberDir, timeoutMs: 20_000 });
184
- llm.signIn.forget(agent, account);
185
- const signedIn = await llm.signIn.status(adapter, account, { fresh: true }).catch(() => false);
186
- return { agent, signed_in: signedIn, ok: !signedIn, ...(r.code !== 0 && signedIn ? { error: (r.err || r.out).trim().slice(-300) } : {}) };
187
- }
188
-
189
- function closeAll() {
190
- for (const s of sessions.values()) end(s, LoginState.FAILED, 'Computer is shutting down');
191
- sessions.clear();
192
- }
193
-
194
- return { start, submitCode, poll, status, logout, closeAll };
195
- }
196
-
197
- const str = (description) => ({ type: 'string', description });
198
- const schema = (properties, required = []) => ({ type: 'object', properties, required });
199
-
200
- /** 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. */
201
- export function buildLlmLoginTools(login) {
202
- const call = (fn) => (a, c, e) => fn(a, { ...c, runAs: e?.runAs });
203
- const base = { group: ToolGroup.PROC, read_only: true, internal: true };
204
- return [
205
- { ...base, name: 'llm.status', handler: call(login.status),
206
- description: 'BE-only: coding agents on this shared computer and whether this member is signed in to each.', input_schema: schema({}) },
207
- { ...base, name: 'llm.login_start', handler: call(login.start),
208
- description: "BE-only: start signing this member in to an agent. Returns a link (and a one-time code for codex) to open on the member's own device.",
209
- input_schema: schema({ agent: str('claude | codex') }, ['agent']) },
210
- { ...base, name: 'llm.login_code', handler: call(login.submitCode),
211
- description: 'BE-only: give the code shown after signing in (claude) to the running sign-in, wait for it to finish.',
212
- input_schema: schema({ login_id: str('from llm.login_start'), code: str('code from the sign-in page') }, ['login_id', 'code']) },
213
- { ...base, name: 'llm.login_poll', handler: call(login.poll),
214
- description: 'BE-only: state of a running sign-in (pending | succeeded | failed | expired); wait_ms waits for it to finish.',
215
- input_schema: schema({ login_id: str('from llm.login_start'), wait_ms: { type: 'number', description: 'max 25000' } }, ['login_id']) },
216
- { ...base, name: 'llm.logout', handler: call(login.logout),
217
- description: 'BE-only: sign this member out of an agent on this shared computer.', input_schema: schema({ agent: str('claude | codex') }, ['agent']) },
218
- ];
219
- }
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
+ }