agent-bridge-service 0.0.0-stage → 0.2.0

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +200 -0
  2. package/LICENSE +21 -0
  3. package/README.md +519 -2
  4. package/README.zh-CN.md +496 -0
  5. package/assets/agent-icons/claude-code.svg +1 -0
  6. package/assets/agent-icons/codebuddy-cli.svg +35 -0
  7. package/assets/agent-icons/codex.svg +1 -0
  8. package/assets/agent-icons/ds-harness.svg +1 -0
  9. package/assets/agent-icons/gemini.svg +1 -0
  10. package/assets/agent-icons/grok-cli.svg +1 -0
  11. package/assets/agent-icons/kimi-code.svg +1 -0
  12. package/assets/agent-icons/mimo-code.svg +1 -0
  13. package/assets/agent-icons/minimax-code.svg +1 -0
  14. package/assets/agent-icons/opencode.svg +1 -0
  15. package/assets/agent-icons/qoder-cli-light.svg +1 -0
  16. package/assets/agent-icons/qoder-cli.svg +1 -0
  17. package/assets/agent-icons/trae-cli.svg +1 -0
  18. package/dist/adapters/agent-adapters.js +437 -0
  19. package/dist/adapters/agent-logos.js +40 -0
  20. package/dist/adapters/win-exec.js +25 -0
  21. package/dist/app/bootstrap.js +101 -0
  22. package/dist/app/service-gate.js +43 -0
  23. package/dist/app/session-log.js +7 -0
  24. package/dist/app/session.js +107 -0
  25. package/dist/app/task-dispatch.js +81 -0
  26. package/dist/cli/dispatch.js +42 -0
  27. package/dist/cli/flags.js +40 -0
  28. package/dist/cli/help.js +36 -0
  29. package/dist/cli/hold.js +15 -0
  30. package/dist/cli/meta.js +16 -0
  31. package/dist/cli/render.js +53 -0
  32. package/dist/cli.js +26 -0
  33. package/dist/commands/connect.js +20 -0
  34. package/dist/commands/daemon.js +13 -0
  35. package/dist/commands/logout.js +18 -0
  36. package/dist/commands/serve.js +65 -0
  37. package/dist/commands/services.js +89 -0
  38. package/dist/commands/status.js +16 -0
  39. package/dist/core/emitter.js +119 -0
  40. package/dist/core/errors.js +89 -0
  41. package/dist/core/redact.js +34 -0
  42. package/dist/core/scan.js +55 -0
  43. package/dist/core/task-supervisor.js +277 -0
  44. package/dist/infra/audit.js +54 -0
  45. package/dist/infra/auth.js +174 -0
  46. package/dist/infra/config.js +191 -0
  47. package/dist/infra/git.js +141 -0
  48. package/dist/infra/service-token.js +198 -0
  49. package/dist/protocol.js +144 -0
  50. package/dist/runner.js +37 -0
  51. package/dist/transport/bridge-client.js +139 -0
  52. package/dist/transport/control-plane.js +482 -0
  53. package/dist/transport/outbox.js +95 -0
  54. package/package.json +80 -4
@@ -0,0 +1,277 @@
1
+ /**
2
+ * 任务调度领域对象(架构第二期)
3
+ *
4
+ * 之前的问题:`runner.ts` 用**模块级变量**承载调度状态(`runningTasks` / `queue` / `currentMaxTasks`),
5
+ * 而且 `currentMaxTasks` 会被"最近一次下发的请求"覆盖 —— 这是隐式全局配置,
6
+ * 两个用例会互相污染,也无法在一台机器上跑两个独立调度域。
7
+ *
8
+ * 现在:所有调度状态内聚进 `TaskSupervisor` 实例,可注入、可单测、可多实例。
9
+ * `runner.ts` 只保留一个薄兼容包装(现有调用方零改动)。
10
+ *
11
+ * 状态机(显式):
12
+ *
13
+ * submit ──▶ queued ──(有空位)──▶ running ──▶ settled
14
+ * │ │ │
15
+ * └──────────┴──(取消/超时)────────┴──▶ settled
16
+ *
17
+ * settled 是吸收态:只 settle 一次、只释放一次名额(终态上行的幂等由 Emitter 负责)。
18
+ */
19
+ import { spawn } from 'node:child_process';
20
+ import { existsSync, realpathSync, statSync } from 'node:fs';
21
+ import { resolve as resolvePath, sep } from 'node:path';
22
+ import { agentDefOf, resolveBin } from '../adapters/agent-adapters.js';
23
+ import { captureWorktreeDiff } from '../infra/git.js';
24
+ import { chunkLog } from '../protocol.js';
25
+ import { buildWinCommandLine, isWinShim } from '../adapters/win-exec.js';
26
+ import { BridgeError } from './errors.js';
27
+ export const DEFAULT_TIMEOUT_MS = 10 * 60_000;
28
+ export const KILL_GRACE_MS = 2000;
29
+ /** 默认并发上限:几个大模型 CLI 同时跑就能卡死整机 */
30
+ export const DEFAULT_MAX_TASKS = 3;
31
+ /** 默认队列上限:再长的排队对调用方也没意义 */
32
+ export const DEFAULT_MAX_QUEUED = 32;
33
+ /**
34
+ * `child` 是否位于 `parent` 目录之下(含相等)。
35
+ * 必须按目录边界判断;Windows 路径大小写不敏感,比较前统一折叠。
36
+ */
37
+ export function isUnder(child, parent) {
38
+ const fold = (p) => {
39
+ const abs = resolvePath(p);
40
+ return process.platform === 'win32' ? abs.toLowerCase() : abs;
41
+ };
42
+ const c = fold(child);
43
+ const p = fold(parent);
44
+ return c === p || c.startsWith(p.endsWith(sep) ? p : p + sep);
45
+ }
46
+ function buildArgs(template, prompt) {
47
+ return template.map((a) => (prompt === undefined ? a : a.replaceAll('{{prompt}}', prompt)));
48
+ }
49
+ function timeoutOf(req) {
50
+ return req.timeoutMs && req.timeoutMs > 0 ? req.timeoutMs : DEFAULT_TIMEOUT_MS;
51
+ }
52
+ function diffOf(req) {
53
+ if (!req.captureDiff)
54
+ return undefined;
55
+ return captureWorktreeDiff(req.cwd, { maxBytes: req.diffMaxBytes });
56
+ }
57
+ /** 把 diff 并进终态信息(无 diff 时不给调用方发空字段噪音) */
58
+ function withDiff(req, info) {
59
+ const cap = diffOf(req);
60
+ if (!cap)
61
+ return info;
62
+ return { ...info, diff: cap.diff, changedFiles: cap.changedFiles, diffTruncated: cap.truncated };
63
+ }
64
+ /** 命令与参数解析失败时,同时给出人类可读串与机器可读码 */
65
+ function reject(req, hooks, code, message) {
66
+ hooks.onStatus('failed', withDiff(req, { error: message, errorCode: code }));
67
+ return { taskId: req.taskId, cancel: () => undefined, done: Promise.resolve('failed') };
68
+ }
69
+ export class TaskSupervisor {
70
+ running = 0;
71
+ queue = [];
72
+ maxTasks;
73
+ constructor(maxConcurrent = DEFAULT_MAX_TASKS) {
74
+ this.maxTasks = maxConcurrent > 0 ? Math.floor(maxConcurrent) : DEFAULT_MAX_TASKS;
75
+ }
76
+ get runningCount() {
77
+ return this.running;
78
+ }
79
+ get queuedCount() {
80
+ return this.queue.length;
81
+ }
82
+ /** 提交任务:校验 → 排队或立即启动。返回句柄(可取消、可 await 终态) */
83
+ submit(req, hooks) {
84
+ const def = agentDefOf(req.agentType);
85
+ if (!def) {
86
+ return reject(req, hooks, 'tool_not_installed', `不支持的工具:${req.agentType}`);
87
+ }
88
+ if (!existsSync(req.cwd) || !statSync(req.cwd).isDirectory()) {
89
+ return reject(req, hooks, 'cwd_missing', `工作目录不存在:${req.cwd}`);
90
+ }
91
+ if (req.allowedCwd?.length && !req.allowedCwd.some((root) => isUnder(req.cwd, root))) {
92
+ return reject(req, hooks, 'cwd_not_allowed', `工作目录不在允许范围内:${req.cwd}`);
93
+ }
94
+ const args = req.args.length > 0 ? req.args : buildArgs(def.taskArgs, req.prompt ?? '');
95
+ let cmd;
96
+ let argv;
97
+ if (def.npxSpec && !resolveBin([def.bin, ...(def.altBins ?? [])])) {
98
+ cmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
99
+ argv = ['-y', def.npxSpec, ...args];
100
+ }
101
+ else {
102
+ const binPath = resolveBin([def.bin, ...(def.altBins ?? [])]);
103
+ if (!binPath) {
104
+ return reject(req, hooks, 'tool_not_installed', `本机没有安装 ${def.display}(未找到 ${def.bin})`);
105
+ }
106
+ cmd = binPath;
107
+ argv = args;
108
+ }
109
+ if (req.maxConcurrent && req.maxConcurrent > 0)
110
+ this.maxTasks = Math.floor(req.maxConcurrent);
111
+ const maxQueued = req.maxQueued !== undefined && req.maxQueued >= 0 ? Math.floor(req.maxQueued) : DEFAULT_MAX_QUEUED;
112
+ if (this.running >= this.maxTasks && this.queue.length >= maxQueued) {
113
+ return reject(req, hooks, 'device_busy', `任务队列已满(并发 ${this.maxTasks},排队 ${maxQueued}),请稍后重试`);
114
+ }
115
+ let resolve;
116
+ const done = new Promise((r) => {
117
+ resolve = r;
118
+ });
119
+ const entry = {
120
+ req,
121
+ hooks,
122
+ cmd,
123
+ argv,
124
+ state: 'queued',
125
+ status: 'running',
126
+ resolve,
127
+ done,
128
+ };
129
+ // timeoutMs 从入队开始算:排队也是调用方的等待时间
130
+ entry.timer = setTimeout(() => {
131
+ if (entry.state === 'settled')
132
+ return;
133
+ if (entry.state === 'queued') {
134
+ this.settle(entry, 'timeout', { error: `排队超时(等待超过 ${timeoutOf(req)}ms)`, errorCode: 'timeout' });
135
+ return;
136
+ }
137
+ entry.status = 'timeout';
138
+ this.terminate(entry);
139
+ }, timeoutOf(req));
140
+ if (this.running < this.maxTasks)
141
+ this.launch(entry);
142
+ else {
143
+ this.queue.push(entry);
144
+ hooks.onStatus('running', {
145
+ phase: 'queued',
146
+ queuePosition: this.queue.length,
147
+ error: `排队中(第 ${this.queue.length} 位,并发上限 ${this.maxTasks})`,
148
+ });
149
+ }
150
+ return {
151
+ taskId: req.taskId,
152
+ cancel: () => {
153
+ if (entry.state === 'settled')
154
+ return;
155
+ if (entry.state === 'queued') {
156
+ this.settle(entry, 'cancelled', { error: '任务已取消(排队中被取消)', errorCode: 'cancelled' });
157
+ return;
158
+ }
159
+ entry.status = 'cancelled';
160
+ this.terminate(entry);
161
+ },
162
+ done,
163
+ };
164
+ }
165
+ // ---------- 内部 ----------
166
+ pump() {
167
+ while (this.running < this.maxTasks && this.queue.length > 0) {
168
+ const next = this.queue.shift();
169
+ if (!next)
170
+ return;
171
+ this.launch(next);
172
+ }
173
+ }
174
+ launch(entry) {
175
+ if (entry.state !== 'queued')
176
+ return;
177
+ entry.state = 'running';
178
+ this.running += 1;
179
+ // 子进程环境恒为 bridge 自身进程环境:平台**不能**注入环境变量
180
+ const shim = isWinShim(entry.cmd);
181
+ const child = shim
182
+ ? spawn(buildWinCommandLine(entry.cmd, entry.argv), {
183
+ cwd: entry.req.cwd,
184
+ env: process.env,
185
+ shell: true,
186
+ windowsHide: true,
187
+ stdio: ['ignore', 'pipe', 'pipe'],
188
+ })
189
+ : spawn(entry.cmd, entry.argv, {
190
+ cwd: entry.req.cwd,
191
+ env: process.env,
192
+ windowsHide: true,
193
+ stdio: ['ignore', 'pipe', 'pipe'],
194
+ });
195
+ entry.child = child;
196
+ const emit = (stream, buf) => {
197
+ for (const piece of chunkLog(buf.toString('utf8')))
198
+ entry.hooks.onLog(stream, piece);
199
+ };
200
+ child.stdout?.on('data', (b) => emit('stdout', b));
201
+ child.stderr?.on('data', (b) => emit('stderr', b));
202
+ child.on('error', (e) => this.settle(entry, 'failed', {
203
+ error: `进程启动失败:${e.message}`,
204
+ errorCode: 'agent_error',
205
+ }));
206
+ child.on('close', (code) => {
207
+ if (entry.status === 'timeout') {
208
+ this.settle(entry, 'timeout', {
209
+ exitCode: code ?? undefined,
210
+ error: '任务超时,进程已终止',
211
+ errorCode: 'timeout',
212
+ });
213
+ }
214
+ else if (entry.status === 'cancelled') {
215
+ this.settle(entry, 'cancelled', {
216
+ exitCode: code ?? undefined,
217
+ error: '任务已取消',
218
+ errorCode: 'cancelled',
219
+ });
220
+ }
221
+ else if (code === 0) {
222
+ this.settle(entry, 'success', { exitCode: 0 });
223
+ }
224
+ else {
225
+ this.settle(entry, 'failed', {
226
+ exitCode: code ?? undefined,
227
+ error: `CLI 退出码 ${code ?? 'unknown'}`,
228
+ errorCode: 'agent_error',
229
+ });
230
+ }
231
+ });
232
+ entry.hooks.onStatus('running');
233
+ }
234
+ terminate(entry) {
235
+ if (!entry.child)
236
+ return;
237
+ entry.child.kill('SIGTERM');
238
+ entry.killTimer = setTimeout(() => entry.child?.kill('SIGKILL'), KILL_GRACE_MS);
239
+ }
240
+ /** 唯一终态收口:只 settle 一次、只释放一次名额 */
241
+ settle(entry, status, info = {}) {
242
+ if (entry.state === 'settled')
243
+ return;
244
+ if (entry.timer)
245
+ clearTimeout(entry.timer);
246
+ if (entry.killTimer)
247
+ clearTimeout(entry.killTimer);
248
+ if (entry.state === 'running') {
249
+ this.running = Math.max(0, this.running - 1);
250
+ }
251
+ else {
252
+ const idx = this.queue.indexOf(entry);
253
+ if (idx >= 0)
254
+ this.queue.splice(idx, 1);
255
+ }
256
+ entry.state = 'settled';
257
+ entry.status = status;
258
+ entry.hooks.onStatus(status, withDiff(entry.req, info));
259
+ entry.resolve(status);
260
+ this.pump();
261
+ }
262
+ }
263
+ /** 进程内的默认调度域(`runner.ts` 的 `startTask` 走它,保持 v1 调用方零改动) */
264
+ export const defaultSupervisor = new TaskSupervisor();
265
+ /** 给 CLI 展示用的摘要(不含任何路径/密钥细节) */
266
+ export function describeTask(req) {
267
+ return `${req.agentType} @ ${realpathOr(req.cwd)}`;
268
+ }
269
+ function realpathOr(p) {
270
+ try {
271
+ return realpathSync(p);
272
+ }
273
+ catch {
274
+ return p;
275
+ }
276
+ }
277
+ export { BridgeError };
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 审计流水:`~/.agent-bridge/audit.jsonl`(单行 JSON,追加,0600)
3
+ *
4
+ * 为什么单独一块:服务令牌校验、diff 捕获、任务执行都要留痕,且必须是**同一份**格式 ——
5
+ * 否则每处各写一个 appendFile,格式必然漂移。
6
+ *
7
+ * 红线(对齐 .harness/rules/always-on.md):
8
+ * - 绝不写令牌明文、凭据内容、diff 正文;只写 id / scope / purpose / 动作 / 结果;
9
+ * - 写失败(磁盘满、权限)**绝不抛异常** —— 审计是旁路,不能反过来搞挂任务执行。
10
+ */
11
+ import { appendFileSync, chmodSync, existsSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import { stateDir } from './config.js';
14
+ export function auditPath() {
15
+ return join(stateDir(), 'audit.jsonl');
16
+ }
17
+ /** 单行 JSON 字段上限:审计是给人排查用的,不是数据库 —— 超长一律截断 */
18
+ const MAX_FIELD = 300;
19
+ function clip(v) {
20
+ if (v === undefined)
21
+ return undefined;
22
+ const s = v.replace(/\r?\n/g, ' ');
23
+ return s.length > MAX_FIELD ? `${s.slice(0, MAX_FIELD)}…` : s;
24
+ }
25
+ export function writeAudit(entry) {
26
+ try {
27
+ const line = JSON.stringify({
28
+ at: entry.at ?? new Date().toISOString(),
29
+ action: entry.action,
30
+ outcome: entry.outcome,
31
+ taskId: clip(entry.taskId),
32
+ agent: clip(entry.agent),
33
+ cwd: clip(entry.cwd),
34
+ requestedBy: clip(entry.requestedBy),
35
+ purpose: clip(entry.purpose),
36
+ serviceId: clip(entry.serviceId),
37
+ scopes: entry.scopes?.slice(0, 16),
38
+ reason: clip(entry.reason),
39
+ });
40
+ const file = auditPath();
41
+ appendFileSync(file, `${line}\n`, { encoding: 'utf8', mode: 0o600 });
42
+ if (!existsSync(file))
43
+ return;
44
+ try {
45
+ chmodSync(file, 0o600);
46
+ }
47
+ catch {
48
+ // Windows 上 chmod 只改只读位;文件仍在用户目录内,属可接受范围
49
+ }
50
+ }
51
+ catch {
52
+ // 审计失败绝不影响主流程
53
+ }
54
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * 授权:B 方案(本地回环回调 + PKCE),兼容手动 token 与 Device Code 兜底
3
+ *
4
+ * 流程:bridge 起一个只监听 127.0.0.1 的临时 http 服务 → 唤起浏览器到平台授权页
5
+ * (复用用户已登录的 session)→ 平台 302 回 `http://127.0.0.1:<port>/callback?code=…`
6
+ * → bridge 用 code + code_verifier 换 device_token → 关掉临时服务。
7
+ *
8
+ * 安全:
9
+ * - 只绑 127.0.0.1(禁止 0.0.0.0),且只处理一次 callback 后立即关闭
10
+ * - PKCE S256 防授权码被劫持
11
+ * - 平台必须校验 redirect_uri 以 `http://127.0.0.1` 开头(平台侧职责)
12
+ */
13
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
14
+ import { createServer } from 'node:http';
15
+ import { spawn } from 'node:child_process';
16
+ export class AuthError extends Error {
17
+ }
18
+ const CALLBACK_TIMEOUT_MS = 180_000;
19
+ function base64url(buf) {
20
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
21
+ }
22
+ export function createPkce() {
23
+ const verifier = base64url(randomBytes(32));
24
+ const challenge = base64url(createHash('sha256').update(verifier).digest());
25
+ return { verifier, challenge };
26
+ }
27
+ export function openBrowser(url) {
28
+ const cmd = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';
29
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
30
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
31
+ child.on('error', () => {
32
+ /* 打不开浏览器由调用方降级到 device code */
33
+ });
34
+ child.unref();
35
+ }
36
+ function normalizeBase(url) {
37
+ return url.replace(/\/+$/, '');
38
+ }
39
+ /** 网络层错误要翻译成人话:地址写错 / 服务没起 / 被防火墙拦,都会是 "fetch failed" */
40
+ async function postJson(url, body, timeoutMs = 15_000) {
41
+ try {
42
+ return await fetch(url, {
43
+ method: 'POST',
44
+ headers: { 'content-type': 'application/json' },
45
+ body: JSON.stringify(body),
46
+ signal: AbortSignal.timeout(timeoutMs),
47
+ });
48
+ }
49
+ catch (e) {
50
+ const msg = e.message;
51
+ throw new AuthError(`连接平台失败(${url}):${msg}。请确认地址正确、平台在运行、且该端口可达。`);
52
+ }
53
+ }
54
+ /** 起临时回调服务,返回 { port, waitForCode } */
55
+ async function startCallbackServer() {
56
+ let resolveCode = () => undefined;
57
+ let rejectCode = () => undefined;
58
+ const waitForCode = new Promise((res, rej) => {
59
+ resolveCode = res;
60
+ rejectCode = rej;
61
+ });
62
+ const server = createServer((req, res) => {
63
+ const u = new URL(req.url ?? '/', 'http://127.0.0.1');
64
+ if (u.pathname !== '/callback') {
65
+ res.writeHead(404).end('not found');
66
+ return;
67
+ }
68
+ const code = u.searchParams.get('code');
69
+ const error = u.searchParams.get('error');
70
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
71
+ res.end(error
72
+ ? `<h2>授权失败</h2><p>${error}</p><p>可以关闭此页面回到终端。</p>`
73
+ : '<h2>设备绑定成功</h2><p>可以关闭此页面回到终端。</p>');
74
+ if (error)
75
+ rejectCode(new AuthError(`平台拒绝授权:${error}`));
76
+ else if (code)
77
+ resolveCode(code);
78
+ else
79
+ rejectCode(new AuthError('回调缺少 code'));
80
+ });
81
+ // listen 是异步的:必须等 listening 事件,否则 address() 还是 null
82
+ const port = await new Promise((resolve, reject) => {
83
+ server.once('error', reject);
84
+ server.listen(0, '127.0.0.1', () => {
85
+ const addr = server.address();
86
+ const p = typeof addr === 'object' && addr ? addr.port : 0;
87
+ if (!p)
88
+ reject(new AuthError('无法启动本地回调端口'));
89
+ else
90
+ resolve(p);
91
+ });
92
+ });
93
+ return { port, waitForCode, close: () => server.close() };
94
+ }
95
+ async function exchangeCode(platform, body) {
96
+ const res = await postJson(`${platform}/api/bridge/token`, {
97
+ ...body,
98
+ clientId: 'agent-bridge',
99
+ });
100
+ if (res.status === 404) {
101
+ throw new AuthError('平台还没有实现 /api/bridge/token(bridge 配套接口未上线)');
102
+ }
103
+ if (!res.ok) {
104
+ const text = await res.text().catch(() => '');
105
+ throw new AuthError(`换取 device_token 失败:HTTP ${res.status} ${text.slice(0, 200)}`);
106
+ }
107
+ const j = (await res.json());
108
+ if (!j.device_token || !j.device_id)
109
+ throw new AuthError('平台返回缺少 device_token / device_id');
110
+ return {
111
+ platformUrl: platform,
112
+ deviceId: j.device_id,
113
+ deviceToken: j.device_token,
114
+ refreshToken: j.refresh_token,
115
+ };
116
+ }
117
+ /** 回环回调授权(主路径):用户只需确认浏览器里的授权框 */
118
+ export async function authorizeWithBrowser(platformUrl, opts = {}) {
119
+ const platform = normalizeBase(platformUrl);
120
+ const { verifier, challenge } = createPkce();
121
+ const cb = await startCallbackServer();
122
+ const redirectUri = `http://127.0.0.1:${cb.port}/callback`;
123
+ const authUrl = `${platform}/bridge/authorize?client_id=agent-bridge` +
124
+ `&code_challenge=${encodeURIComponent(challenge)}&code_challenge_method=S256` +
125
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&state=${randomUUID()}`;
126
+ try {
127
+ opts.onPrompt?.(authUrl);
128
+ openBrowser(authUrl);
129
+ const timeout = new Promise((_, rej) => setTimeout(() => rej(new AuthError('等待浏览器授权超时(180s)')), CALLBACK_TIMEOUT_MS));
130
+ const code = await Promise.race([cb.waitForCode, timeout]);
131
+ return await exchangeCode(platform, { code, codeVerifier: verifier, redirectUri });
132
+ }
133
+ finally {
134
+ cb.close();
135
+ }
136
+ }
137
+ /** Device Code 兜底(SSH / 打不开浏览器):平台返回验证码,用户去任意浏览器确认 */
138
+ export async function authorizeWithDeviceCode(platformUrl, opts = {}) {
139
+ const platform = normalizeBase(platformUrl);
140
+ const start = await postJson(`${platform}/api/bridge/device-code`, {
141
+ clientId: 'agent-bridge',
142
+ });
143
+ if (start.status === 404) {
144
+ throw new AuthError('平台还没有实现 /api/bridge/device-code(且本机无法打开浏览器)');
145
+ }
146
+ if (!start.ok)
147
+ throw new AuthError(`申请设备码失败:HTTP ${start.status}`);
148
+ const j = (await start.json());
149
+ opts.onPrompt?.(j.verification_uri, j.user_code);
150
+ const deadline = Date.now() + (j.expires_in ?? 600) * 1000;
151
+ const interval = (j.interval ?? 5) * 1000;
152
+ while (Date.now() < deadline) {
153
+ await new Promise((r) => setTimeout(r, interval));
154
+ const res = await postJson(`${platform}/api/bridge/device-token`, {
155
+ device_code: j.device_code,
156
+ clientId: 'agent-bridge',
157
+ });
158
+ if (res.ok) {
159
+ const t = (await res.json());
160
+ if (t.device_token && t.device_id) {
161
+ return {
162
+ platformUrl: platform,
163
+ deviceId: t.device_id,
164
+ deviceToken: t.device_token,
165
+ refreshToken: t.refresh_token,
166
+ };
167
+ }
168
+ }
169
+ // 404/400 继续等;401 视为用户拒绝
170
+ if (res.status === 401)
171
+ throw new AuthError('设备码已被拒绝或过期');
172
+ }
173
+ throw new AuthError('设备码授权超时');
174
+ }