agent-bridge-service 0.2.2 → 1.0.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 (69) hide show
  1. package/CHANGELOG.md +112 -140
  2. package/README.md +508 -35
  3. package/README.zh-CN.md +443 -33
  4. package/assets/agent-icons/agy.svg +27 -0
  5. package/dist/adapters/acp-auth.js +51 -0
  6. package/dist/adapters/acp-codebuddy.js +507 -0
  7. package/dist/adapters/agent-adapters.js +466 -46
  8. package/dist/adapters/claude-stream.js +159 -0
  9. package/dist/adapters/codex-app-server.js +310 -0
  10. package/dist/adapters/host-env.js +48 -0
  11. package/dist/adapters/mcp-elicitation.js +148 -0
  12. package/dist/adapters/mcp-host.js +70 -0
  13. package/dist/adapters/step-parsers.js +583 -0
  14. package/dist/app/bootstrap.js +163 -74
  15. package/dist/app/claude-resident.js +204 -0
  16. package/dist/app/conversation.js +639 -0
  17. package/dist/app/service-gate.js +1 -1
  18. package/dist/app/session.js +425 -14
  19. package/dist/app/task-dispatch.js +883 -7
  20. package/dist/app/task-registry.js +168 -0
  21. package/dist/cli/dispatch.js +4 -0
  22. package/dist/cli/flags.js +11 -0
  23. package/dist/cli/help.js +25 -7
  24. package/dist/cli/panel.js +334 -0
  25. package/dist/cli/render.js +2 -0
  26. package/dist/commands/approvals.js +80 -0
  27. package/dist/commands/connect.js +122 -4
  28. package/dist/commands/daemon-service.js +81 -0
  29. package/dist/commands/daemon.js +269 -6
  30. package/dist/commands/logout.js +13 -10
  31. package/dist/commands/serve.js +98 -12
  32. package/dist/commands/sessions.js +106 -0
  33. package/dist/core/ansi.js +5 -0
  34. package/dist/core/artifact-extract.js +158 -0
  35. package/dist/core/artifact-transfer.js +583 -0
  36. package/dist/core/device-identity.js +22 -0
  37. package/dist/core/emitter.js +50 -8
  38. package/dist/core/errors.js +43 -0
  39. package/dist/core/form-schema.js +72 -0
  40. package/dist/core/interaction-broker.js +440 -0
  41. package/dist/core/interaction-url.js +63 -0
  42. package/dist/core/partial-messages.js +99 -0
  43. package/dist/core/permission-ledger.js +146 -0
  44. package/dist/core/permission-policy.js +88 -0
  45. package/dist/core/port-fallback.js +22 -0
  46. package/dist/core/redact.js +13 -0
  47. package/dist/core/scan.js +12 -7
  48. package/dist/core/session-store.js +1632 -0
  49. package/dist/core/task-supervisor.js +955 -30
  50. package/dist/infra/atomic-file.js +111 -0
  51. package/dist/infra/audit.js +7 -0
  52. package/dist/infra/auth.js +167 -42
  53. package/dist/infra/config.js +511 -72
  54. package/dist/infra/device-identity-store.js +87 -0
  55. package/dist/infra/jwt.js +149 -0
  56. package/dist/infra/profile-lock.js +295 -0
  57. package/dist/infra/proxy-env.js +60 -0
  58. package/dist/infra/service-token.js +25 -4
  59. package/dist/protocol.js +298 -2
  60. package/dist/transport/a2a-mapping.js +206 -0
  61. package/dist/transport/acp-gateway-mapping.js +186 -0
  62. package/dist/transport/bridge-client.js +31 -22
  63. package/dist/transport/control-plane-page.js +820 -0
  64. package/dist/transport/control-plane-sessions-page.js +90 -0
  65. package/dist/transport/control-plane.js +923 -71
  66. package/dist/transport/gateway.js +1005 -0
  67. package/dist/transport/office-preview.js +154 -0
  68. package/package.json +6 -3
  69. package/assets/agent-icons/gemini.svg +0 -1
@@ -0,0 +1,111 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { chmod, link, mkdir, open, rename, stat, unlink } from 'node:fs/promises';
4
+ import { basename, dirname, join } from 'node:path';
5
+ function codeOf(error) {
6
+ return typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string'
7
+ ? error.code
8
+ : 'UNKNOWN';
9
+ }
10
+ function atomicError(filePath, operation, error, published) {
11
+ const outcome = published
12
+ ? '目标可能已发布,但目录持久化状态不确定;请先读回核对,勿删除目标文件。'
13
+ : '旧文件未被替换;请检查父目录权限和可用存储后重试。';
14
+ return new Error(`原子文件操作失败(${operation},${codeOf(error)}):${filePath}。${outcome}`);
15
+ }
16
+ function runSystem(command, args) {
17
+ return new Promise((resolve, reject) => {
18
+ execFile(command, [...args], { encoding: 'utf8', windowsHide: true }, (error, stdout) => {
19
+ if (error)
20
+ reject(error);
21
+ else
22
+ resolve(stdout);
23
+ });
24
+ });
25
+ }
26
+ function windowsSystemTool(name) {
27
+ return join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', name);
28
+ }
29
+ async function secureWindowsFile(filePath) {
30
+ const identity = await runSystem(windowsSystemTool('whoami.exe'), ['/user', '/fo', 'csv', '/nh']);
31
+ const sid = identity.match(/"(S-1-\d+(?:-\d+)*)"/)?.[1];
32
+ if (!sid)
33
+ throw new Error('无法确认当前 Windows 用户 SID');
34
+ await runSystem(windowsSystemTool('icacls.exe'), [
35
+ filePath,
36
+ '/inheritance:r',
37
+ '/grant:r',
38
+ `*${sid}:(F)`,
39
+ '*S-1-5-18:(F)',
40
+ ]);
41
+ }
42
+ async function secureTemporaryFile(filePath) {
43
+ if (process.platform === 'win32') {
44
+ await secureWindowsFile(filePath);
45
+ return;
46
+ }
47
+ await chmod(filePath, 0o600);
48
+ if (((await stat(filePath)).mode & 0o777) !== 0o600) {
49
+ throw new Error('无法确认临时文件权限为 0600');
50
+ }
51
+ }
52
+ async function syncDirectory(directory) {
53
+ if (process.platform === 'win32')
54
+ return;
55
+ const handle = await open(directory, 'r');
56
+ try {
57
+ await handle.sync();
58
+ }
59
+ finally {
60
+ await handle.close();
61
+ }
62
+ }
63
+ export async function writeAtomicFile(filePath, content, options = {}) {
64
+ const directory = dirname(filePath);
65
+ const temporaryPath = join(directory, `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`);
66
+ let handle;
67
+ let published = false;
68
+ let operation = '创建父目录';
69
+ try {
70
+ await mkdir(directory, { recursive: true, mode: 0o700 });
71
+ operation = '创建临时文件';
72
+ handle = await open(temporaryPath, 'wx', 0o600);
73
+ operation = '写入临时文件';
74
+ await handle.writeFile(content, 'utf8');
75
+ operation = 'fsync 临时文件';
76
+ await handle.sync();
77
+ operation = '关闭临时文件';
78
+ await handle.close();
79
+ handle = undefined;
80
+ operation = '设置临时文件权限';
81
+ await secureTemporaryFile(temporaryPath);
82
+ if (options.overwrite === false) {
83
+ operation = '不覆盖发布';
84
+ try {
85
+ await link(temporaryPath, filePath);
86
+ }
87
+ catch (error) {
88
+ if (codeOf(error) === 'EEXIST')
89
+ return 'exists';
90
+ throw error;
91
+ }
92
+ }
93
+ else {
94
+ operation = '原子替换';
95
+ await rename(temporaryPath, filePath);
96
+ }
97
+ published = true;
98
+ operation = 'fsync 父目录';
99
+ await syncDirectory(directory);
100
+ return 'written';
101
+ }
102
+ catch (error) {
103
+ throw atomicError(filePath, operation, error, published);
104
+ }
105
+ finally {
106
+ if (handle)
107
+ await handle.close().catch(() => undefined);
108
+ if (!published)
109
+ await unlink(temporaryPath).catch(() => undefined);
110
+ }
111
+ }
@@ -36,6 +36,13 @@ export function writeAudit(entry) {
36
36
  serviceId: clip(entry.serviceId),
37
37
  scopes: entry.scopes?.slice(0, 16),
38
38
  reason: clip(entry.reason),
39
+ policy: clip(entry.policy),
40
+ permissionMode: clip(entry.permissionMode),
41
+ approvalId: clip(entry.approvalId),
42
+ requestId: clip(entry.requestId),
43
+ responseId: clip(entry.responseId),
44
+ kind: clip(entry.kind),
45
+ choice: clip(entry.choice),
39
46
  });
40
47
  const file = auditPath();
41
48
  appendFileSync(file, `${line}\n`, { encoding: 'utf8', mode: 0o600 });
@@ -13,7 +13,16 @@
13
13
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
14
14
  import { createServer } from 'node:http';
15
15
  import { spawn } from 'node:child_process';
16
+ import { DEVICE_ID_PATTERN } from '../core/device-identity.js';
16
17
  export class AuthError extends Error {
18
+ httpStatus;
19
+ code;
20
+ constructor(message, options = {}) {
21
+ super(message);
22
+ this.name = 'AuthError';
23
+ this.httpStatus = options.httpStatus;
24
+ this.code = options.code;
25
+ }
17
26
  }
18
27
  const CALLBACK_TIMEOUT_MS = 180_000;
19
28
  function base64url(buf) {
@@ -24,9 +33,31 @@ export function createPkce() {
24
33
  const challenge = base64url(createHash('sha256').update(verifier).digest());
25
34
  return { verifier, challenge };
26
35
  }
36
+ /**
37
+ * 唤起浏览器的命令(纯函数,可在非 Windows 上单测)。
38
+ *
39
+ * ⛔ Windows 不得走 `cmd /c start "" <url>`:Node 只在参数含空格时加引号,而授权 URL
40
+ * 里全是 `&`,cmd 会把 `&` 当成**命令分隔符** —— 浏览器只收到第一个 query 参数
41
+ * (2026-10-24 实测:`?client_id=agent-bridge` 之后的 `code_challenge` / `redirect_uri`
42
+ * 全被当成命令吞掉,平台授权页读不到 code_challenge,报「授权链接无效」)。
43
+ *
44
+ * ✅ 走 `rundll32 url.dll,FileProtocolHandler`:由 CreateProcess 直接收 argv,
45
+ * 全程不经任何 shell 解析,`&` 无需引号、无需转义,也不会引入 `shell: true`
46
+ * (对齐 always-on.md §4「参数一律字符串数组传给 spawn」)。
47
+ * 实测对照:cmd start 只送到 `?client_id=agent-bridge`;rundll32 整条送达(含 state)。
48
+ * 取舍:rundll32 对超长 URL(~2048 字符)有限制,而授权 URL 实测约 200 字符,够用。
49
+ * (`explorer.exe <url>` 是另一条零引号路径,但本机 Win11 实测不再转交默认浏览器,弃用。)
50
+ */
51
+ export function browserOpenCommand(platform, url) {
52
+ if (platform === 'win32') {
53
+ return { cmd: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] };
54
+ }
55
+ if (platform === 'darwin')
56
+ return { cmd: 'open', args: [url] };
57
+ return { cmd: 'xdg-open', args: [url] };
58
+ }
27
59
  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];
60
+ const { cmd, args } = browserOpenCommand(process.platform, url);
30
61
  const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
31
62
  child.on('error', () => {
32
63
  /* 打不开浏览器由调用方降级到 device code */
@@ -51,6 +82,75 @@ async function postJson(url, body, timeoutMs = 15_000) {
51
82
  throw new AuthError(`连接平台失败(${url}):${msg}。请确认地址正确、平台在运行、且该端口可达。`);
52
83
  }
53
84
  }
85
+ async function readPublicErrorCode(res) {
86
+ try {
87
+ const body = await res.json();
88
+ if (typeof body !== 'object' || body === null)
89
+ return undefined;
90
+ const code = body.code;
91
+ return typeof code === 'string' && code.length > 0 ? code : undefined;
92
+ }
93
+ catch {
94
+ return undefined;
95
+ }
96
+ }
97
+ function authErrorFromResponse(res, endpoint, code) {
98
+ const options = { httpStatus: res.status, code };
99
+ if (res.status === 404) {
100
+ const hint = endpoint === '/api/bridge/device-code'
101
+ ? '(且本机无法打开浏览器)'
102
+ : '(bridge 配套接口未上线)';
103
+ return new AuthError(`平台还没有实现 ${endpoint}${hint}`, options);
104
+ }
105
+ if (res.status === 400 && code === 'invalid_device_id') {
106
+ return new AuthError('本地设备身份格式无效,平台拒绝该 deviceId;请检查本地身份,不会自动更换设备 ID。', options);
107
+ }
108
+ if (res.status === 409 && code === 'device_bound_to_other_account') {
109
+ return new AuthError('设备已绑定其他账号;请联系平台管理员处理设备所有权,不会自动更换设备 ID。', options);
110
+ }
111
+ if (res.status === 409 && code === 'device_identity_ambiguous') {
112
+ return new AuthError('平台存在设备身份历史重复;请联系平台管理员处理,不会自动合并或更换设备 ID。', options);
113
+ }
114
+ if (res.status === 401 || res.status === 403) {
115
+ return new AuthError(`平台授权或凭证失败(HTTP ${res.status});本地设备身份已保留,请重新发起授权。`, options);
116
+ }
117
+ return new AuthError(`授权请求失败:HTTP ${res.status}。请检查平台状态后重新发起授权。`, options);
118
+ }
119
+ function protocolError(detail) {
120
+ return new AuthError(`平台授权响应协议错误:${detail}`);
121
+ }
122
+ async function parseTokenResponse(res, context) {
123
+ let body;
124
+ try {
125
+ body = await res.json();
126
+ }
127
+ catch {
128
+ throw protocolError('响应不是有效 JSON。');
129
+ }
130
+ if (typeof body !== 'object' || body === null)
131
+ throw protocolError('响应必须是 JSON 对象。');
132
+ const value = body;
133
+ const deviceToken = value['device_token'];
134
+ const refreshToken = value['refresh_token'];
135
+ const deviceId = value['device_id'];
136
+ if (typeof deviceToken !== 'string' || deviceToken.length === 0) {
137
+ throw protocolError('device_token 缺失或不是非空字符串。');
138
+ }
139
+ if (refreshToken !== undefined && (typeof refreshToken !== 'string' || refreshToken.length === 0)) {
140
+ throw protocolError('refresh_token 必须是非空字符串。');
141
+ }
142
+ if (typeof deviceId !== 'string' || !DEVICE_ID_PATTERN.test(deviceId)) {
143
+ throw protocolError('device_id 缺失或格式无效。');
144
+ }
145
+ if (deviceId !== context.deviceId) {
146
+ throw protocolError(`device_id 与本地身份不一致(预期 ${context.deviceId},实际 ${deviceId})。`);
147
+ }
148
+ return {
149
+ platformUrl: normalizeBase(context.platformUrl),
150
+ deviceToken,
151
+ ...(refreshToken === undefined ? {} : { refreshToken }),
152
+ };
153
+ }
54
154
  /** 起临时回调服务,返回 { port, waitForCode } */
55
155
  async function startCallbackServer() {
56
156
  let resolveCode = () => undefined;
@@ -92,60 +192,89 @@ async function startCallbackServer() {
92
192
  });
93
193
  return { port, waitForCode, close: () => server.close() };
94
194
  }
95
- async function exchangeCode(platform, body) {
195
+ async function exchangeCode(context, body) {
196
+ const platform = normalizeBase(context.platformUrl);
96
197
  const res = await postJson(`${platform}/api/bridge/token`, {
97
198
  ...body,
98
199
  clientId: 'agent-bridge',
200
+ deviceId: context.deviceId,
201
+ hostname: context.hostname,
202
+ platform: context.platform,
203
+ cliVersion: context.cliVersion,
99
204
  });
100
- if (res.status === 404) {
101
- throw new AuthError('平台还没有实现 /api/bridge/token(bridge 配套接口未上线)');
205
+ if (!res.ok) {
206
+ const code = await readPublicErrorCode(res);
207
+ throw authErrorFromResponse(res, '/api/bridge/token', code);
102
208
  }
209
+ return parseTokenResponse(res, context);
210
+ }
211
+ /**
212
+ * 用 refresh token 换新 device token。
213
+ * 平台需支持 `POST /api/bridge/token` + `grant_type=refresh_token`;不支持时抛 AuthError,
214
+ * 调用方必须回退到重新授权,而不是静默继续用失效 token。
215
+ */
216
+ export async function refreshDeviceToken(context, refreshToken) {
217
+ const platform = normalizeBase(context.platformUrl);
218
+ const res = await postJson(`${platform}/api/bridge/token`, {
219
+ grant_type: 'refresh_token',
220
+ refresh_token: refreshToken,
221
+ clientId: 'agent-bridge',
222
+ deviceId: context.deviceId,
223
+ hostname: context.hostname,
224
+ platform: context.platform,
225
+ cliVersion: context.cliVersion,
226
+ });
103
227
  if (!res.ok) {
104
- const text = await res.text().catch(() => '');
105
- throw new AuthError(`换取 device_token 失败:HTTP ${res.status} ${text.slice(0, 200)}`);
228
+ const code = await readPublicErrorCode(res);
229
+ throw authErrorFromResponse(res, '/api/bridge/token (refresh)', code);
106
230
  }
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
- };
231
+ return parseTokenResponse(res, context);
116
232
  }
117
233
  /** 回环回调授权(主路径):用户只需确认浏览器里的授权框 */
118
- export async function authorizeWithBrowser(platformUrl, opts = {}) {
119
- const platform = normalizeBase(platformUrl);
234
+ export async function authorizeWithBrowser(context, opts = {}) {
235
+ const platform = normalizeBase(context.platformUrl);
120
236
  const { verifier, challenge } = createPkce();
121
237
  const cb = await startCallbackServer();
122
238
  const redirectUri = `http://127.0.0.1:${cb.port}/callback`;
123
239
  const authUrl = `${platform}/bridge/authorize?client_id=agent-bridge` +
124
240
  `&code_challenge=${encodeURIComponent(challenge)}&code_challenge_method=S256` +
125
241
  `&redirect_uri=${encodeURIComponent(redirectUri)}&state=${randomUUID()}`;
242
+ let timeoutHandle;
126
243
  try {
127
244
  opts.onPrompt?.(authUrl);
128
- openBrowser(authUrl);
129
- const timeout = new Promise((_, rej) => setTimeout(() => rej(new AuthError('等待浏览器授权超时(180s)')), CALLBACK_TIMEOUT_MS));
245
+ if (opts.openBrowser)
246
+ await opts.openBrowser(authUrl);
247
+ else
248
+ openBrowser(authUrl);
249
+ const timeout = new Promise((_, rej) => {
250
+ timeoutHandle = setTimeout(() => rej(new AuthError('等待浏览器授权超时(180s)')), CALLBACK_TIMEOUT_MS);
251
+ });
130
252
  const code = await Promise.race([cb.waitForCode, timeout]);
131
- return await exchangeCode(platform, { code, codeVerifier: verifier, redirectUri });
253
+ return await exchangeCode(context, { code, codeVerifier: verifier, redirectUri });
132
254
  }
133
255
  finally {
256
+ if (timeoutHandle)
257
+ clearTimeout(timeoutHandle);
134
258
  cb.close();
135
259
  }
136
260
  }
137
261
  /** Device Code 兜底(SSH / 打不开浏览器):平台返回验证码,用户去任意浏览器确认 */
138
- export async function authorizeWithDeviceCode(platformUrl, opts = {}) {
139
- const platform = normalizeBase(platformUrl);
262
+ export async function authorizeWithDeviceCode(context, opts = {}) {
263
+ const platform = normalizeBase(context.platformUrl);
140
264
  const start = await postJson(`${platform}/api/bridge/device-code`, {
141
265
  clientId: 'agent-bridge',
142
266
  });
143
- if (start.status === 404) {
144
- throw new AuthError('平台还没有实现 /api/bridge/device-code(且本机无法打开浏览器)');
267
+ if (!start.ok) {
268
+ const code = await readPublicErrorCode(start);
269
+ throw authErrorFromResponse(start, '/api/bridge/device-code', code);
270
+ }
271
+ let j;
272
+ try {
273
+ j = (await start.json());
274
+ }
275
+ catch {
276
+ throw protocolError('设备码申请响应不是有效 JSON。');
145
277
  }
146
- if (!start.ok)
147
- throw new AuthError(`申请设备码失败:HTTP ${start.status}`);
148
- const j = (await start.json());
149
278
  opts.onPrompt?.(j.verification_uri, j.user_code);
150
279
  const deadline = Date.now() + (j.expires_in ?? 600) * 1000;
151
280
  const interval = (j.interval ?? 5) * 1000;
@@ -154,21 +283,17 @@ export async function authorizeWithDeviceCode(platformUrl, opts = {}) {
154
283
  const res = await postJson(`${platform}/api/bridge/device-token`, {
155
284
  device_code: j.device_code,
156
285
  clientId: 'agent-bridge',
286
+ deviceId: context.deviceId,
287
+ hostname: context.hostname,
288
+ platform: context.platform,
289
+ cliVersion: context.cliVersion,
157
290
  });
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('设备码已被拒绝或过期');
291
+ if (res.ok)
292
+ return parseTokenResponse(res, context);
293
+ const code = await readPublicErrorCode(res);
294
+ if (res.status === 428 && code === 'authorization_pending')
295
+ continue;
296
+ throw authErrorFromResponse(res, '/api/bridge/device-token', code);
172
297
  }
173
298
  throw new AuthError('设备码授权超时');
174
299
  }