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,87 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { parse as parseToml } from 'smol-toml';
4
+ import { assertDeviceId, resolveDeviceIdCandidate, } from '../core/device-identity.js';
5
+ import { writeAtomicFile } from './atomic-file.js';
6
+ function codeOf(error) {
7
+ return typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string'
8
+ ? error.code
9
+ : 'UNKNOWN';
10
+ }
11
+ async function readStoredDeviceId(identityPath) {
12
+ let content;
13
+ try {
14
+ content = await readFile(identityPath, 'utf8');
15
+ }
16
+ catch (error) {
17
+ if (codeOf(error) === 'ENOENT')
18
+ return undefined;
19
+ throw new Error(`无法读取设备身份文件(${codeOf(error)}):${identityPath};请检查权限,禁止以新身份替代。`);
20
+ }
21
+ let raw;
22
+ try {
23
+ raw = parseToml(content);
24
+ }
25
+ catch {
26
+ throw new Error(`设备身份文件损坏或无效:${identityPath};请修复 TOML,禁止以新身份替代。`);
27
+ }
28
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
29
+ throw new Error(`设备身份文件结构无效:${identityPath};请保留 schema_version = 1 和有效 device_id。`);
30
+ }
31
+ const record = raw;
32
+ if (record['schema_version'] !== 1) {
33
+ throw new Error(`设备身份 schema 不支持:${identityPath};仅支持 schema_version = 1。`);
34
+ }
35
+ try {
36
+ return assertDeviceId(record['device_id']);
37
+ }
38
+ catch {
39
+ throw new Error(`设备身份文件中的 device_id 无效:${identityPath};请修复格式,禁止以新身份替代。`);
40
+ }
41
+ }
42
+ function suppliedCandidates(options) {
43
+ return [
44
+ { source: '旧配置镜像', value: options.legacyDeviceId },
45
+ { source: '显式参数', value: options.explicitDeviceId },
46
+ { source: '环境变量', value: options.envDeviceId },
47
+ ];
48
+ }
49
+ async function reuseIdentity(identityPath, storedDeviceId, options) {
50
+ const deviceId = resolveDeviceIdCandidate([
51
+ { source: 'identity.toml', value: storedDeviceId },
52
+ ...suppliedCandidates(options),
53
+ ]);
54
+ if (deviceId === undefined)
55
+ throw new Error(`设备身份文件为空:${identityPath}`);
56
+ return { deviceId, source: 'reused' };
57
+ }
58
+ export async function ensureDeviceIdentity(options) {
59
+ if (!options.identityPath)
60
+ throw new Error('必须提供设备身份文件路径。');
61
+ const stored = await readStoredDeviceId(options.identityPath);
62
+ if (stored !== undefined)
63
+ return reuseIdentity(options.identityPath, stored, options);
64
+ const migrated = resolveDeviceIdCandidate(suppliedCandidates(options));
65
+ // 锁不是身份正确性的前提:生成或迁移前再次读取,缩小并发窗口。
66
+ const reread = await readStoredDeviceId(options.identityPath);
67
+ if (reread !== undefined)
68
+ return reuseIdentity(options.identityPath, reread, options);
69
+ let deviceId = migrated;
70
+ if (deviceId === undefined) {
71
+ if (options.hasReusableCredential) {
72
+ throw new Error('身份文件不存在但存在可复用凭证;请恢复身份或提供既有设备 ID,禁止随机生成。');
73
+ }
74
+ if (!options.allowCreate) {
75
+ throw new Error('身份文件不存在且没有可迁移 ID;请提供显式设备 ID,禁止随机生成。');
76
+ }
77
+ deviceId = `bd_${randomBytes(16).toString('hex')}`;
78
+ }
79
+ const result = await writeAtomicFile(options.identityPath, `schema_version = 1\ndevice_id = "${deviceId}"\n`, { overwrite: false });
80
+ if (result === 'exists') {
81
+ const published = await readStoredDeviceId(options.identityPath);
82
+ if (published === undefined)
83
+ throw new Error(`设备身份发布后无法读回:${options.identityPath}`);
84
+ return reuseIdentity(options.identityPath, published, options);
85
+ }
86
+ return { deviceId, source: migrated === undefined ? 'created' : 'migrated' };
87
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * 最小 JWT/JWKS 校验器(无第三方依赖)。
3
+ *
4
+ * 用途:控制面/网关接受 principal JWT,映射 tenant 与 scope;不替代设备令牌。
5
+ * 支持 RS256/384/512 与 ES256/384;JWKS 只支持 RSA/EC 公钥。
6
+ */
7
+ import { createPublicKey, verify as cryptoVerify } from 'node:crypto';
8
+ export class JwtError extends Error {
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ this.name = 'JwtError';
14
+ }
15
+ }
16
+ function decode(token) {
17
+ const parts = token.split('.');
18
+ if (parts.length !== 3)
19
+ throw new JwtError('malformed', 'JWT 必须是三段式');
20
+ const [head, body, sig] = parts;
21
+ let header;
22
+ let payload;
23
+ try {
24
+ header = JSON.parse(Buffer.from(head, 'base64url').toString('utf8'));
25
+ payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
26
+ }
27
+ catch {
28
+ throw new JwtError('malformed', 'JWT 头部或载荷不是合法 JSON');
29
+ }
30
+ return {
31
+ header,
32
+ payload,
33
+ signingInput: `${head}.${body}`,
34
+ signature: Buffer.from(sig, 'base64url'),
35
+ };
36
+ }
37
+ function num(value) {
38
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
39
+ }
40
+ function scopesOf(payload) {
41
+ const scope = payload['scope'];
42
+ if (typeof scope === 'string')
43
+ return scope.split(/\s+/).filter(Boolean);
44
+ const scp = payload['scp'];
45
+ if (Array.isArray(scp))
46
+ return scp.filter((item) => typeof item === 'string');
47
+ return [];
48
+ }
49
+ function algorithm(alg) {
50
+ switch (alg) {
51
+ case 'RS256':
52
+ return { hash: 'sha256', type: 'rsa' };
53
+ case 'RS384':
54
+ return { hash: 'sha384', type: 'rsa' };
55
+ case 'RS512':
56
+ return { hash: 'sha512', type: 'rsa' };
57
+ case 'ES256':
58
+ return { hash: 'sha256', type: 'ec' };
59
+ case 'ES384':
60
+ return { hash: 'sha384', type: 'ec' };
61
+ default:
62
+ throw new JwtError('unsupported_alg', `不支持的 JWT alg:${alg}`);
63
+ }
64
+ }
65
+ export class JwtVerifier {
66
+ options;
67
+ keys;
68
+ fetchedAt = 0;
69
+ constructor(options) {
70
+ this.options = options;
71
+ }
72
+ async verify(token) {
73
+ const decoded = decode(token);
74
+ const alg = String(decoded.header['alg'] ?? '');
75
+ const { hash, type } = algorithm(alg);
76
+ const kid = typeof decoded.header['kid'] === 'string' ? decoded.header['kid'] : undefined;
77
+ const key = await this.publicKey(kid, type);
78
+ const input = Buffer.from(decoded.signingInput, 'utf8');
79
+ const ok = type === 'rsa'
80
+ ? cryptoVerify(hash, input, key, decoded.signature)
81
+ : cryptoVerify(hash, input, { key, dsaEncoding: 'ieee-p1363' }, decoded.signature);
82
+ if (!ok)
83
+ throw new JwtError('bad_signature', 'JWT 签名不匹配');
84
+ const payload = decoded.payload;
85
+ const now = Math.floor(Date.now() / 1000);
86
+ const skew = this.options.clockToleranceSec ?? 30;
87
+ const exp = num(payload['exp']);
88
+ if (exp !== undefined && now - skew >= exp)
89
+ throw new JwtError('expired', 'JWT 已过期');
90
+ const nbf = num(payload['nbf']);
91
+ if (nbf !== undefined && now + skew < nbf)
92
+ throw new JwtError('not_yet_valid', 'JWT 尚未生效');
93
+ if (this.options.issuer && payload['iss'] !== this.options.issuer) {
94
+ throw new JwtError('bad_issuer', 'JWT issuer 不匹配');
95
+ }
96
+ if (this.options.audience) {
97
+ const aud = payload['aud'];
98
+ const audiences = Array.isArray(aud) ? aud : [aud];
99
+ if (!audiences.includes(this.options.audience)) {
100
+ throw new JwtError('bad_audience', 'JWT audience 不匹配');
101
+ }
102
+ }
103
+ const subject = typeof payload['sub'] === 'string' ? payload['sub'] : '';
104
+ if (!subject)
105
+ throw new JwtError('malformed', 'JWT 缺少 sub');
106
+ const tenantClaim = this.options.tenantClaim ?? 'tenant_id';
107
+ const tenant = payload[tenantClaim];
108
+ return {
109
+ subject,
110
+ ...(typeof tenant === 'string' && tenant ? { tenantId: tenant } : {}),
111
+ scopes: scopesOf(payload),
112
+ claims: payload,
113
+ };
114
+ }
115
+ async publicKey(kid, type) {
116
+ const keys = await this.loadKeys();
117
+ const candidates = keys.filter((key) => {
118
+ if (kid && key.kid !== kid)
119
+ return false;
120
+ const kty = key.kty ?? '';
121
+ return type === 'rsa' ? kty === 'RSA' : kty === 'EC';
122
+ });
123
+ if (candidates.length === 0)
124
+ throw new JwtError('unknown_kid', `JWKS 中找不到 kid=${kid ?? '(none)'}`);
125
+ // kid 缺失时只接受唯一候选,避免拿错 key 做签名验证。
126
+ if (!kid && candidates.length > 1) {
127
+ throw new JwtError('unknown_kid', 'JWT 无 kid 且 JWKS 有多个候选 key');
128
+ }
129
+ return createPublicKey({ key: candidates[0], format: 'jwk' });
130
+ }
131
+ async loadKeys() {
132
+ const source = this.options.jwks;
133
+ if (typeof source !== 'string')
134
+ return source.keys;
135
+ const cacheMs = this.options.cacheMs ?? 5 * 60_000;
136
+ if (this.keys && Date.now() - this.fetchedAt < cacheMs)
137
+ return this.keys;
138
+ const fetchImpl = this.options.fetchImpl ?? fetch;
139
+ const response = await fetchImpl(source, { headers: { accept: 'application/json' } });
140
+ if (!response.ok)
141
+ throw new JwtError('unknown_kid', `JWKS 拉取失败:HTTP ${response.status}`);
142
+ const body = (await response.json());
143
+ if (!Array.isArray(body.keys))
144
+ throw new JwtError('unknown_kid', 'JWKS 缺少 keys 数组');
145
+ this.keys = body.keys;
146
+ this.fetchedAt = Date.now();
147
+ return this.keys;
148
+ }
149
+ }
@@ -0,0 +1,295 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { spawn } from 'node:child_process';
3
+ import { mkdir, open, readFile, unlink } from 'node:fs/promises';
4
+ import { hostname } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ const processQueues = new Map();
7
+ function errorCode(error) {
8
+ return typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string'
9
+ ? error.code
10
+ : undefined;
11
+ }
12
+ function busyError(lockPath) {
13
+ return new Error(`该 profile 已有绑定进行中:${lockPath};请等待其完成,或确认无绑定进程后人工处理锁文件。`);
14
+ }
15
+ function unsafeError(lockPath, detail) {
16
+ return new Error(`无法安全回收 profile 锁:${lockPath}。${detail};请确认无绑定进程后人工删除该锁文件。`);
17
+ }
18
+ function parseLockRecord(text, lockPath) {
19
+ let value;
20
+ try {
21
+ value = JSON.parse(text);
22
+ }
23
+ catch {
24
+ throw unsafeError(lockPath, '锁记录不是有效 JSON');
25
+ }
26
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
27
+ throw unsafeError(lockPath, '锁记录结构无效');
28
+ }
29
+ const record = value;
30
+ if (typeof record['ownerToken'] !== 'string' || record['ownerToken'].length === 0
31
+ || typeof record['pid'] !== 'number' || !Number.isInteger(record['pid']) || record['pid'] <= 0
32
+ || typeof record['hostname'] !== 'string' || record['hostname'].length === 0
33
+ || typeof record['createdAt'] !== 'string' || Number.isNaN(Date.parse(record['createdAt']))) {
34
+ throw unsafeError(lockPath, '锁记录缺少有效 ownerToken/pid/hostname/createdAt');
35
+ }
36
+ return {
37
+ ownerToken: record['ownerToken'],
38
+ pid: record['pid'],
39
+ hostname: record['hostname'],
40
+ createdAt: record['createdAt'],
41
+ };
42
+ }
43
+ async function withRecoveryGuard(lockPath, fn) {
44
+ const guardPath = `${lockPath}.recovery`;
45
+ const ownerToken = randomUUID();
46
+ let handle;
47
+ let createdByUs = false;
48
+ try {
49
+ handle = await open(guardPath, 'wx', 0o600);
50
+ createdByUs = true;
51
+ await handle.writeFile(ownerToken, 'utf8');
52
+ await handle.sync();
53
+ await handle.close();
54
+ handle = undefined;
55
+ }
56
+ catch (error) {
57
+ if (handle)
58
+ await handle.close().catch(() => undefined);
59
+ if (createdByUs)
60
+ await unlink(guardPath).catch(() => undefined);
61
+ if (errorCode(error) === 'EEXIST')
62
+ throw busyError(lockPath);
63
+ throw unsafeError(lockPath, `获取 stale 回收互斥失败(${errorCode(error) ?? 'UNKNOWN'})`);
64
+ }
65
+ try {
66
+ return await fn();
67
+ }
68
+ finally {
69
+ try {
70
+ const current = await readFile(guardPath, 'utf8');
71
+ // guard 只允许短时的 stale 判定/删除临界区使用;不自动强拆,避免递归竞态。
72
+ if (current === ownerToken)
73
+ await unlink(guardPath);
74
+ }
75
+ catch (error) {
76
+ if (errorCode(error) !== 'ENOENT') {
77
+ throw unsafeError(lockPath, `释放 stale 回收互斥失败(${errorCode(error) ?? 'UNKNOWN'})`);
78
+ }
79
+ }
80
+ }
81
+ }
82
+ /**
83
+ * Windows 下读取进程创建时间(ISO 8601);拿不到返回 undefined(调用方保守处理)。
84
+ * 仅在 stale 回收冲突路径使用(频率极低);数组参数 spawn,不走 shell 字符串。
85
+ * 用途:`process.kill(pid, 0)` 只能证明「该 PID 有进程」,不能证明是锁的原持有者——
86
+ * PID 被复用时会把陈旧锁误判成占用(实测:10-29 的死锁在 24 天后挡住 connect)。
87
+ * 复用进程的创建时间必然**晚于**锁记录的 createdAt(先有进程后写锁),据此识别。
88
+ */
89
+ function windowsProcessStartTime(pid, timeoutMs = 3000) {
90
+ return new Promise((resolvePromise) => {
91
+ if (process.platform !== 'win32') {
92
+ resolvePromise(undefined);
93
+ return;
94
+ }
95
+ const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-Process -Id ${pid} -ErrorAction SilentlyContinue).StartTime.ToString('o')`], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
96
+ let out = '';
97
+ const timer = setTimeout(() => {
98
+ child.kill();
99
+ resolvePromise(undefined);
100
+ }, timeoutMs);
101
+ timer.unref?.();
102
+ child.stdout.on('data', (chunk) => {
103
+ out += chunk.toString('utf8');
104
+ });
105
+ child.on('error', () => {
106
+ clearTimeout(timer);
107
+ resolvePromise(undefined);
108
+ });
109
+ child.on('close', () => {
110
+ clearTimeout(timer);
111
+ const text = out.trim();
112
+ if (/^\d{4}-\d{2}-\d{2}T/.test(text))
113
+ resolvePromise(text);
114
+ else
115
+ resolvePromise(undefined);
116
+ });
117
+ });
118
+ }
119
+ async function recoverStaleLock(lockPath) {
120
+ await withRecoveryGuard(lockPath, async () => {
121
+ let text;
122
+ try {
123
+ text = await readFile(lockPath, 'utf8');
124
+ }
125
+ catch (error) {
126
+ if (errorCode(error) === 'ENOENT')
127
+ return;
128
+ throw unsafeError(lockPath, `读取锁失败(${errorCode(error) ?? 'UNKNOWN'})`);
129
+ }
130
+ const record = parseLockRecord(text, lockPath);
131
+ if (record.hostname !== hostname())
132
+ throw unsafeError(lockPath, '锁属于其他主机,不能判断 PID 是否存活');
133
+ let alive = true;
134
+ try {
135
+ process.kill(record.pid, 0);
136
+ }
137
+ catch (error) {
138
+ if (errorCode(error) === 'ESRCH')
139
+ alive = false;
140
+ else if (errorCode(error) !== 'EPERM') {
141
+ throw unsafeError(lockPath, `无法确认 PID ${record.pid} 状态(${errorCode(error) ?? 'UNKNOWN'})`);
142
+ }
143
+ }
144
+ if (alive) {
145
+ // PID 存活 ≠ 锁持有者存活:PID 复用会把陈旧锁误判成占用(Windows 实测)。
146
+ // 复用进程的创建时间必然晚于锁 createdAt;早于(含缓冲)则视为原持有者仍在。
147
+ const startedAt = await windowsProcessStartTime(record.pid);
148
+ if (startedAt === undefined)
149
+ throw busyError(lockPath);
150
+ const lockCreated = Date.parse(record.createdAt);
151
+ const processStarted = Date.parse(startedAt);
152
+ // 1 分钟缓冲吸收时钟抖动;创建时间晚于锁 → 复用 → 可回收
153
+ if (Number.isFinite(lockCreated) && Number.isFinite(processStarted) && processStarted > lockCreated + 60_000) {
154
+ alive = false;
155
+ }
156
+ else {
157
+ throw busyError(lockPath);
158
+ }
159
+ }
160
+ if (alive)
161
+ throw busyError(lockPath);
162
+ let confirmed;
163
+ try {
164
+ confirmed = await readFile(lockPath, 'utf8');
165
+ }
166
+ catch (error) {
167
+ if (errorCode(error) === 'ENOENT')
168
+ return;
169
+ throw unsafeError(lockPath, `回收前重读锁失败(${errorCode(error) ?? 'UNKNOWN'})`);
170
+ }
171
+ if (confirmed !== text)
172
+ throw unsafeError(lockPath, 'stale 判断期间锁记录已变化');
173
+ try {
174
+ await unlink(lockPath);
175
+ }
176
+ catch (error) {
177
+ if (errorCode(error) !== 'ENOENT') {
178
+ throw unsafeError(lockPath, `删除已确认 stale 锁失败(${errorCode(error) ?? 'UNKNOWN'})`);
179
+ }
180
+ }
181
+ });
182
+ }
183
+ async function acquireLock(stateDir, lockPath, record) {
184
+ await mkdir(stateDir, { recursive: true, mode: 0o700 });
185
+ for (let attempt = 0; attempt < 3; attempt += 1) {
186
+ let handle;
187
+ let createdByUs = false;
188
+ try {
189
+ handle = await open(lockPath, 'wx', 0o600);
190
+ createdByUs = true;
191
+ await handle.writeFile(JSON.stringify(record), 'utf8');
192
+ await handle.sync();
193
+ await handle.close();
194
+ return { path: lockPath, ownerToken: record.ownerToken };
195
+ }
196
+ catch (error) {
197
+ if (handle)
198
+ await handle.close().catch(() => undefined);
199
+ if (errorCode(error) !== 'EEXIST') {
200
+ // open('wx') 失败时锁可能属于另一进程;只有自己已创建后才允许清理。
201
+ if (createdByUs)
202
+ await unlink(lockPath).catch(() => undefined);
203
+ throw new Error(`获取 profile 锁失败(${errorCode(error) ?? 'UNKNOWN'}):${lockPath};请检查目录权限后重试。`);
204
+ }
205
+ await recoverStaleLock(lockPath);
206
+ }
207
+ }
208
+ throw busyError(lockPath);
209
+ }
210
+ async function releaseLock(lock) {
211
+ let text;
212
+ try {
213
+ text = await readFile(lock.path, 'utf8');
214
+ }
215
+ catch (error) {
216
+ if (errorCode(error) === 'ENOENT')
217
+ return;
218
+ throw new Error(`释放 profile 锁前读取失败:${lock.path};请核对锁 owner 后人工处理。`);
219
+ }
220
+ let current;
221
+ try {
222
+ current = JSON.parse(text);
223
+ }
224
+ catch {
225
+ return;
226
+ }
227
+ if (typeof current !== 'object' || current === null || !('ownerToken' in current) || current.ownerToken !== lock.ownerToken) {
228
+ return;
229
+ }
230
+ try {
231
+ await unlink(lock.path);
232
+ }
233
+ catch (error) {
234
+ if (errorCode(error) !== 'ENOENT') {
235
+ throw new Error(`释放 profile 锁失败:${lock.path};请确认锁 owner 后人工处理。`);
236
+ }
237
+ }
238
+ }
239
+ async function runWithLock(stateDir, fn) {
240
+ const lockPath = join(stateDir, 'profile.lock');
241
+ const record = {
242
+ ownerToken: randomUUID(),
243
+ pid: process.pid,
244
+ hostname: hostname(),
245
+ createdAt: new Date().toISOString(),
246
+ };
247
+ const lock = await acquireLock(stateDir, lockPath, record);
248
+ try {
249
+ return await fn();
250
+ }
251
+ finally {
252
+ await releaseLock(lock);
253
+ }
254
+ }
255
+ /**
256
+ * 运行期单实例锁:覆盖整个 connect/serve 生命周期。
257
+ * profile.lock 只保护启动阶段的身份/授权写入,释放后仍可能被第二个 connect 抢同一 deviceId;
258
+ * 平台会以 4000 replaced_by_new_connection 互踢,导致任务被判 lost。
259
+ */
260
+ export async function acquireBridgeRuntimeLock(stateDir) {
261
+ const lockPath = join(stateDir, 'runtime.lock');
262
+ const record = {
263
+ ownerToken: randomUUID(),
264
+ pid: process.pid,
265
+ hostname: hostname(),
266
+ createdAt: new Date().toISOString(),
267
+ };
268
+ let lock;
269
+ try {
270
+ lock = await acquireLock(stateDir, lockPath, record);
271
+ }
272
+ catch (error) {
273
+ if (/绑定进行中/.test(error.message)) {
274
+ throw new Error(`已有 bridge 运行实例占用该 profile:${lockPath};请先停止旧进程,或使用独立配置目录。`);
275
+ }
276
+ throw error;
277
+ }
278
+ return {
279
+ release: () => releaseLock(lock),
280
+ };
281
+ }
282
+ export async function withProfileLock(stateDir, fn) {
283
+ const key = resolve(stateDir);
284
+ const previous = processQueues.get(key) ?? Promise.resolve();
285
+ const run = previous.then(() => runWithLock(key, fn));
286
+ const tail = run.then(() => undefined, () => undefined);
287
+ processQueues.set(key, tail);
288
+ try {
289
+ return await run;
290
+ }
291
+ finally {
292
+ if (processQueues.get(key) === tail)
293
+ processQueues.delete(key);
294
+ }
295
+ }
@@ -0,0 +1,60 @@
1
+ /** 外部 CLI 的代理环境:显式配置优先,Windows 自动读取当前用户的系统代理。 */
2
+ import { execFileSync } from 'node:child_process';
3
+ const INTERNET_SETTINGS = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings';
4
+ function normalizeProxy(value) {
5
+ const trimmed = value.trim();
6
+ if (!trimmed)
7
+ return undefined;
8
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
9
+ }
10
+ export function parseWindowsProxyRegistry(enableOutput, serverOutput) {
11
+ if (!/ProxyEnable\s+REG_DWORD\s+0x1\b/i.test(enableOutput))
12
+ return undefined;
13
+ const match = /ProxyServer\s+REG_SZ\s+(.+)$/im.exec(serverOutput);
14
+ const value = match?.[1]?.trim();
15
+ if (!value)
16
+ return undefined;
17
+ if (!value.includes('='))
18
+ return normalizeProxy(value);
19
+ const entries = new Map(value
20
+ .split(';')
21
+ .map((part) => part.trim())
22
+ .filter(Boolean)
23
+ .map((part) => {
24
+ const at = part.indexOf('=');
25
+ return [part.slice(0, at).toLowerCase(), part.slice(at + 1)];
26
+ }));
27
+ return normalizeProxy(entries.get('https') ?? entries.get('http') ?? '');
28
+ }
29
+ function queryRegistry(value) {
30
+ return execFileSync('reg.exe', ['query', INTERNET_SETTINGS, '/v', value], {
31
+ encoding: 'utf8',
32
+ timeout: 1_000,
33
+ maxBuffer: 64 * 1024,
34
+ windowsHide: true,
35
+ });
36
+ }
37
+ export function detectWindowsSystemProxy() {
38
+ try {
39
+ return parseWindowsProxyRegistry(queryRegistry('ProxyEnable'), queryRegistry('ProxyServer'));
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ export function externalProxyEnv(base, opts = {}) {
46
+ const explicit = normalizeProxy(base['AGENT_BRIDGE_EXTERNAL_PROXY'] ?? '');
47
+ const proxy = explicit ??
48
+ ((opts.platform ?? process.platform) === 'win32'
49
+ ? (opts.detect ?? detectWindowsSystemProxy)()
50
+ : undefined);
51
+ if (!proxy)
52
+ return { ...base };
53
+ return {
54
+ ...base,
55
+ HTTPS_PROXY: proxy,
56
+ HTTP_PROXY: proxy,
57
+ https_proxy: proxy,
58
+ http_proxy: proxy,
59
+ };
60
+ }
@@ -18,7 +18,21 @@ import { dirname, join } from 'node:path';
18
18
  import { parse as parseToml, stringify as stringifyToml } from 'smol-toml';
19
19
  import { stateDir, tokenTail } from './config.js';
20
20
  /** 受控 scope 集合(新增 scope = 新增能力,必须同步文档) */
21
- export const SERVICE_SCOPES = ['task:create', 'task:cancel', 'task:read', 'device:read'];
21
+ export const SERVICE_SCOPES = [
22
+ 'task:create',
23
+ 'task:cancel',
24
+ 'task:read',
25
+ /**
26
+ * 只读会话侧内容(会话列表/快照/事件/交互)。比 `task:read` 窄:拿不到任务输出与 diff,
27
+ * 适合只做看板/审批的集成方。1.0 之前签发的 `task:read` 令牌仍可用(见 control-plane 的别名规则)。
28
+ */
29
+ 'session:read',
30
+ 'task:approve',
31
+ /** 允许把人工的「永久允许」写进持久授权账本(比 task:approve 更敏感:影响未来任务) */
32
+ 'approval:persist',
33
+ 'task:respond',
34
+ 'device:read',
35
+ ];
22
36
  const TOKEN_PREFIX = 'abs';
23
37
  const SECRET_BYTES = 32;
24
38
  const KID_HEX = 8;
@@ -106,7 +120,9 @@ function parseToken(token) {
106
120
  * 校验服务令牌 + scope。
107
121
  * 「没有令牌」与「令牌无效」是两件事:前者由调用方按 `requireServiceToken` 决定,后者一律拒绝。
108
122
  */
109
- export function verifyServiceToken(token, requiredScope, now = new Date()) {
123
+ export function verifyServiceToken(token,
124
+ /** 单个 scope = 必须命中;数组 = 任一命中即可(例如 `session:read` 与兼容别名 `task:read`) */
125
+ requiredScope, now = new Date()) {
110
126
  if (!token || !token.trim())
111
127
  return { ok: false, reason: 'missing', message: '未提供服务令牌' };
112
128
  const parsed = parseToken(token);
@@ -130,8 +146,13 @@ export function verifyServiceToken(token, requiredScope, now = new Date()) {
130
146
  return { ok: false, reason: 'revoked', message: '服务令牌已吊销' };
131
147
  }
132
148
  }
133
- if (!rec.scopes.includes(requiredScope)) {
134
- return { ok: false, reason: 'scope', message: `服务令牌缺少 scope:${requiredScope}` };
149
+ const required = Array.isArray(requiredScope) ? requiredScope : [requiredScope];
150
+ if (!required.some((scope) => rec.scopes.includes(scope))) {
151
+ return {
152
+ ok: false,
153
+ reason: 'scope',
154
+ message: `服务令牌缺少 scope:${required.join(' 或 ')}`,
155
+ };
135
156
  }
136
157
  // 记录最近使用(best-effort:写失败不影响本次判定)
137
158
  try {