agent-bridge-service 0.2.3 → 1.1.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 +122 -140
  2. package/README.md +526 -36
  3. package/README.zh-CN.md +457 -34
  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 +470 -46
  8. package/dist/adapters/claude-stream.js +159 -0
  9. package/dist/adapters/codex-app-server.js +365 -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 +426 -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 +26 -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 +124 -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 +100 -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 +968 -30
  50. package/dist/infra/atomic-file.js +111 -0
  51. package/dist/infra/audit.js +7 -0
  52. package/dist/infra/auth.js +143 -40
  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 +81 -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 +935 -71
  66. package/dist/transport/gateway.js +1023 -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,159 @@
1
+ /**
2
+ * Claude Code bidirectional stream-json adapter; Qoder uses headless + native resume.
3
+ *
4
+ * Verified against Claude Code:
5
+ * claude -p --input-format stream-json --output-format stream-json --verbose
6
+ * stdin: {"type":"user","message":{"role":"user","content":[{"type":"text","text":"..."}]}}
7
+ * stdout: system/assistant/result NDJSON; result ends one turn.
8
+ *
9
+ * The CLI queues additional user frames but does NOT apply them to the active turn (verified:
10
+ * a second frame while a 1..50 task was running did not change the result). So this adapter is a
11
+ * stream-json execution mode only; same-turn steer remains Codex app-server exclusive.
12
+ * It is intentionally opt-in (`claudeStream`); permissions stay with the CLI (`acceptEdits`, no bypass).
13
+ */
14
+ import { createInterface } from 'node:readline';
15
+ import { killCliProcess, spawnCliProcess } from './agent-adapters.js';
16
+ export function claudeStreamArgs(nativeSessionId) {
17
+ const args = [
18
+ '-p',
19
+ '--input-format',
20
+ 'stream-json',
21
+ '--output-format',
22
+ 'stream-json',
23
+ '--verbose',
24
+ '--permission-mode',
25
+ 'acceptEdits',
26
+ ];
27
+ if (nativeSessionId)
28
+ args.push('--resume', nativeSessionId);
29
+ return args;
30
+ }
31
+ export function claudeResultError(event) {
32
+ if (event['type'] !== 'result')
33
+ return undefined;
34
+ const subtype = typeof event['subtype'] === 'string' ? event['subtype'] : undefined;
35
+ if (event['is_error'] !== true && (subtype === undefined || subtype === 'success'))
36
+ return undefined;
37
+ const detail = (typeof event['error'] === 'string' && event['error']) ||
38
+ (typeof event['result'] === 'string' && event['result']) ||
39
+ subtype ||
40
+ '未知终态错误';
41
+ return new Error(`Claude result${subtype ? ` ${subtype}` : ''}:${detail}`);
42
+ }
43
+ function textOf(message) {
44
+ if (!message || typeof message !== 'object')
45
+ return '';
46
+ const content = message.content;
47
+ if (!Array.isArray(content))
48
+ return '';
49
+ return content
50
+ .filter((block) => Boolean(block && typeof block === 'object'))
51
+ .filter((block) => block.type === 'text' && typeof block.text === 'string')
52
+ .map((block) => block.text ?? '')
53
+ .join('');
54
+ }
55
+ export async function runClaudeStreamPrompt(opts) {
56
+ const child = spawnCliProcess(opts.command ?? 'claude', claudeStreamArgs(opts.nativeSessionId), {
57
+ cwd: opts.cwd,
58
+ env: process.env,
59
+ });
60
+ let sessionId = '';
61
+ let text = '';
62
+ let stopReason = 'unknown';
63
+ let settled = false;
64
+ let closed = false;
65
+ const sendUser = (value) => {
66
+ if (closed || !child.stdin.writable)
67
+ return;
68
+ child.stdin.write(`${JSON.stringify({
69
+ type: 'user',
70
+ message: { role: 'user', content: [{ type: 'text', text: value }] },
71
+ })}\n`);
72
+ };
73
+ let resolveDone;
74
+ let rejectDone;
75
+ const done = new Promise((resolve, reject) => {
76
+ resolveDone = resolve;
77
+ rejectDone = reject;
78
+ });
79
+ const rl = createInterface({ input: child.stdout });
80
+ rl.on('line', (line) => {
81
+ const trimmed = line.trim();
82
+ if (!trimmed)
83
+ return;
84
+ let event;
85
+ try {
86
+ event = JSON.parse(trimmed);
87
+ }
88
+ catch {
89
+ return;
90
+ }
91
+ opts.onUpdate?.(event);
92
+ if (event['type'] === 'system' && typeof event['session_id'] === 'string') {
93
+ sessionId = event['session_id'];
94
+ opts.onSession?.(sessionId);
95
+ return;
96
+ }
97
+ if (event['type'] === 'assistant') {
98
+ const chunk = textOf(event['message']);
99
+ if (chunk)
100
+ text += chunk;
101
+ return;
102
+ }
103
+ if (event['type'] === 'result') {
104
+ if (typeof event['session_id'] === 'string')
105
+ sessionId = event['session_id'];
106
+ if (typeof event['result'] === 'string')
107
+ text = event['result'];
108
+ const resultError = claudeResultError(event);
109
+ if (resultError) {
110
+ if (!settled) {
111
+ settled = true;
112
+ rejectDone(resultError);
113
+ }
114
+ return;
115
+ }
116
+ stopReason = typeof event['stop_reason'] === 'string' ? event['stop_reason'] : 'end_turn';
117
+ if (!settled) {
118
+ settled = true;
119
+ resolveDone({ sessionId, text, stopReason });
120
+ }
121
+ }
122
+ });
123
+ const fail = (error) => {
124
+ if (settled)
125
+ return;
126
+ settled = true;
127
+ rejectDone(error);
128
+ };
129
+ child.on('error', fail);
130
+ child.on('close', (code) => {
131
+ closed = true;
132
+ if (!settled)
133
+ fail(new Error(`Claude stream 进程退出(code ${code ?? 'null'})`));
134
+ });
135
+ const timeoutMs = opts.timeoutMs ?? 10 * 60_000;
136
+ const timer = setTimeout(() => {
137
+ killCliProcess(child, opts.command ?? 'claude');
138
+ fail(new Error(`Claude stream 超时(${timeoutMs}ms)`));
139
+ }, timeoutMs);
140
+ const onAbort = () => {
141
+ killCliProcess(child, opts.command ?? 'claude');
142
+ fail(new Error('Claude stream 已取消'));
143
+ };
144
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
145
+ sendUser(opts.prompt);
146
+ try {
147
+ return await done;
148
+ }
149
+ finally {
150
+ clearTimeout(timer);
151
+ opts.signal?.removeEventListener('abort', onAbort);
152
+ rl.close();
153
+ killCliProcess(child, opts.command ?? 'claude');
154
+ child.stdin.destroy();
155
+ child.stdout?.destroy();
156
+ child.stderr?.destroy();
157
+ child.unref();
158
+ }
159
+ }
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Codex App Server adapter (JSON-RPC over stdio).
3
+ *
4
+ * Verified against codex-cli 0.163.0:
5
+ * codex app-server --stdio
6
+ * initialize -> thread/start -> turn/start -> turn/completed
7
+ *
8
+ * Approval requests arrive as server-initiated JSON-RPC requests:
9
+ * item/commandExecution/requestApproval
10
+ * item/fileChange/requestApproval
11
+ * item/tool/requestUserInput
12
+ * They pause the turn until the client replies.
13
+ */
14
+ import { createInterface } from 'node:readline';
15
+ import { externalProxyEnv } from '../infra/proxy-env.js';
16
+ import { killCliProcess, spawnCliProcess } from './agent-adapters.js';
17
+ import { withoutHostEnv } from './host-env.js';
18
+ export function codexAppServerArgs() {
19
+ return ['app-server', '--stdio'];
20
+ }
21
+ /** stderr 尾部保留上限:与 ACP 通道同量级,够看清最后一条错误栈又不塞满错误消息 */
22
+ export const CODEX_STDERR_TAIL_LIMIT = 4 * 1024;
23
+ export function codexChildEnv(base = process.env) {
24
+ return externalProxyEnv(withoutHostEnv(base));
25
+ }
26
+ /**
27
+ * 把 codex 的「非内容型」通知压成一行给人看的文本(`error` / `warning` / `configWarning`)。
28
+ *
29
+ * 这些通知不承载对话内容,却常常是**唯一能解释「回合为什么不动」**的信息:
30
+ * 2026-11-27 复盘到的 113s 静默就是 `error` 里的一串 `Reconnecting... n/5`。返回 undefined
31
+ * 表示这条通知不该上行。
32
+ */
33
+ export function codexNoticeText(notification) {
34
+ const method = String(notification['method'] ?? '');
35
+ const params = asObject(notification['params']);
36
+ if (method === 'warning' || method === 'configWarning') {
37
+ const text = params['message'] ?? params['summary'];
38
+ return typeof text === 'string' && text.trim() ? text.trim() : undefined;
39
+ }
40
+ if (method !== 'error')
41
+ return undefined;
42
+ const error = asObject(params['error']);
43
+ const message = typeof error['message'] === 'string' ? error['message'] : Object.keys(error).length ? JSON.stringify(error) : '';
44
+ const detail = typeof params['additionalDetails'] === 'string' ? params['additionalDetails'] : '';
45
+ const suffix = params['willRetry'] === true ? '[将自动重试]' : '';
46
+ const body = `${message}${detail ? `(${detail})` : ''}`.trim();
47
+ return body || suffix ? `${body}${suffix}`.trim() : undefined;
48
+ }
49
+ function asObject(value) {
50
+ return typeof value === 'object' && value !== null ? value : {};
51
+ }
52
+ function errorText(value) {
53
+ if (typeof value === 'string')
54
+ return value;
55
+ if (value && typeof value === 'object' && typeof value['message'] === 'string') {
56
+ return String(value['message']);
57
+ }
58
+ return JSON.stringify(value);
59
+ }
60
+ export function codexTurnError(status, error) {
61
+ if (status === 'completed')
62
+ return undefined;
63
+ const detail = error === undefined ? '' : errorText(error);
64
+ return new Error(`Codex turn ${status || 'unknown'}${detail ? `:${detail}` : ''}`);
65
+ }
66
+ function deliveryFuture() {
67
+ let settle;
68
+ const promise = new Promise((resolvePromise) => {
69
+ settle = resolvePromise;
70
+ });
71
+ return { promise, settle };
72
+ }
73
+ export async function runCodexPrompt(opts) {
74
+ const child = spawnCliProcess(opts.command ?? 'codex', codexAppServerArgs(), {
75
+ cwd: opts.cwd,
76
+ env: opts.env ?? codexChildEnv(),
77
+ });
78
+ /**
79
+ * stderr 必须持续读走:codex app-server 会往这里写配置告警、重连/回退提示与失败栈。
80
+ * 不读有两个后果 —— ①失败只剩一个退出码,用户无法自查;②pipe 缓冲(64 KiB)写满后
81
+ * 子进程阻塞在 write 上,协议流彻底停摆,外部只看得到 heartbeat(2026-11-27 复盘到的
82
+ * 「交互模式回合挂死」就是这么被误判的)。尾部同时用于错误消息后缀。
83
+ */
84
+ let stderrTail = '';
85
+ child.stderr?.on('data', (chunk) => {
86
+ const text = chunk.toString('utf8');
87
+ stderrTail = (stderrTail + text).slice(-CODEX_STDERR_TAIL_LIMIT);
88
+ try {
89
+ opts.onStderr?.(text);
90
+ }
91
+ catch {
92
+ /* 诊断旁路不得影响回合 */
93
+ }
94
+ });
95
+ const withStderr = (message) => {
96
+ const tail = stderrTail.trim();
97
+ return tail ? `${message}\n[stderr] ${tail}` : message;
98
+ };
99
+ let nextId = 1;
100
+ let threadId = '';
101
+ let turnId = '';
102
+ let text = '';
103
+ let closed = false;
104
+ let turnSettled = false;
105
+ const responseWaiters = new Set();
106
+ const settleResponseWaiters = () => {
107
+ for (const finish of responseWaiters)
108
+ finish(false);
109
+ responseWaiters.clear();
110
+ };
111
+ let resolveTurn;
112
+ let rejectTurn;
113
+ const turnDone = new Promise((resolve, reject) => {
114
+ resolveTurn = resolve;
115
+ rejectTurn = reject;
116
+ });
117
+ // 握手阶段(initialize/thread/start/turn/start)失败时 turnDone 永远不会被 await,
118
+ // 它的 rejection 会变成未处理拒绝(Node 默认直接终止进程)。先挂一个空 catch 标记已处理;
119
+ // 后面 `await turnDone` 仍然正常抛错,语义不变。
120
+ void turnDone.catch(() => undefined);
121
+ const pending = new Map();
122
+ const send = (message) => {
123
+ if (closed || !child.stdin.writable || child.stdin.destroyed)
124
+ return false;
125
+ try {
126
+ child.stdin.write(`${JSON.stringify(message)}\n`);
127
+ // false 仅表示背压,数据已被流接受;不能据此误判成交付失败。
128
+ return true;
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ };
134
+ const request = (method, params, timeoutMs = 15_000) => new Promise((resolve, reject) => {
135
+ const id = nextId++;
136
+ const timer = setTimeout(() => {
137
+ pending.delete(id);
138
+ reject(new Error(withStderr(`Codex ${method} 超时(${timeoutMs}ms)`)));
139
+ }, timeoutMs);
140
+ pending.set(id, { resolve, reject, timer });
141
+ send({ jsonrpc: '2.0', id, method, params });
142
+ });
143
+ const writeResponse = (message) => {
144
+ if (closed || !child.stdin.writable)
145
+ return Promise.resolve(false);
146
+ return new Promise((resolvePromise) => {
147
+ let finished = false;
148
+ const finish = (delivered) => {
149
+ if (finished)
150
+ return;
151
+ finished = true;
152
+ responseWaiters.delete(finish);
153
+ resolvePromise(delivered);
154
+ };
155
+ responseWaiters.add(finish);
156
+ try {
157
+ child.stdin.write(`${JSON.stringify(message)}\n`, (error) => finish(!error));
158
+ }
159
+ catch {
160
+ finish(false);
161
+ }
162
+ });
163
+ };
164
+ const respond = (id, result) => {
165
+ if (typeof id !== 'number' && typeof id !== 'string')
166
+ return Promise.resolve(false);
167
+ return writeResponse({ jsonrpc: '2.0', id, result });
168
+ };
169
+ const respondError = (id, code, message) => {
170
+ if (typeof id !== 'number' && typeof id !== 'string')
171
+ return Promise.resolve(false);
172
+ return writeResponse({ jsonrpc: '2.0', id, error: { code, message } });
173
+ };
174
+ const failAll = (error) => {
175
+ for (const p of pending.values()) {
176
+ clearTimeout(p.timer);
177
+ p.reject(error);
178
+ }
179
+ pending.clear();
180
+ };
181
+ const handleServerRequest = async (message) => {
182
+ const delivery = deliveryFuture();
183
+ const method = String(message['method'] ?? '');
184
+ const params = asObject(message['params']);
185
+ const kind = method === 'item/fileChange/requestApproval'
186
+ ? 'file-change'
187
+ : method === 'item/tool/requestUserInput'
188
+ ? 'user-input'
189
+ : method === 'item/permissions/requestApproval'
190
+ ? 'permission'
191
+ : 'command';
192
+ try {
193
+ const decision = opts.onApproval
194
+ ? await opts.onApproval({
195
+ requestId: message['id'] ?? '',
196
+ method,
197
+ kind,
198
+ payload: params,
199
+ delivery: delivery.promise,
200
+ })
201
+ : undefined;
202
+ if (method === 'item/tool/requestUserInput') {
203
+ // The caller returns a JSON string or undefined; undefined means cancel the turn.
204
+ if (decision) {
205
+ try {
206
+ delivery.settle(await respond(message['id'], JSON.parse(decision)));
207
+ }
208
+ catch {
209
+ delivery.settle(await respond(message['id'], { answers: {} }));
210
+ }
211
+ }
212
+ else {
213
+ delivery.settle(await respondError(message['id'], -32000, 'user input cancelled'));
214
+ }
215
+ return;
216
+ }
217
+ delivery.settle(await respond(message['id'], { decision: decision ?? 'decline' }));
218
+ }
219
+ catch {
220
+ delivery.settle(false);
221
+ await respond(message['id'], { decision: 'decline' });
222
+ }
223
+ };
224
+ const handleNotification = (message) => {
225
+ const method = String(message['method'] ?? '');
226
+ const params = asObject(message['params']);
227
+ opts.onUpdate?.({ method, params });
228
+ if (method === 'item/agentMessage/delta') {
229
+ const delta = params['delta'];
230
+ if (typeof delta === 'string')
231
+ text += delta;
232
+ return;
233
+ }
234
+ if (method === 'turn/completed') {
235
+ if (turnSettled)
236
+ return;
237
+ turnSettled = true;
238
+ const turn = asObject(params['turn']);
239
+ const status = String(turn['status'] ?? 'unknown');
240
+ const error = codexTurnError(status, turn['error']);
241
+ if (error)
242
+ rejectTurn?.(new Error(withStderr(error.message)));
243
+ else
244
+ resolveTurn?.();
245
+ return;
246
+ }
247
+ };
248
+ const rl = createInterface({ input: child.stdout });
249
+ rl.on('line', (line) => {
250
+ const trimmed = line.trim();
251
+ if (!trimmed.startsWith('{'))
252
+ return;
253
+ let message;
254
+ try {
255
+ message = JSON.parse(trimmed);
256
+ }
257
+ catch {
258
+ return;
259
+ }
260
+ const id = message['id'];
261
+ if (typeof id === 'number' && pending.has(id)) {
262
+ const p = pending.get(id);
263
+ if (!p)
264
+ return;
265
+ pending.delete(id);
266
+ clearTimeout(p.timer);
267
+ if (message['error'])
268
+ p.reject(new Error(withStderr(errorText(message['error']))));
269
+ else
270
+ p.resolve(message['result']);
271
+ return;
272
+ }
273
+ if (message['method']) {
274
+ if (id !== undefined)
275
+ void handleServerRequest(message);
276
+ else {
277
+ try {
278
+ handleNotification(message);
279
+ }
280
+ catch (error) {
281
+ failAll(error);
282
+ killCliProcess(child, opts.command ?? 'codex');
283
+ }
284
+ }
285
+ }
286
+ });
287
+ child.on('error', (error) => {
288
+ settleResponseWaiters();
289
+ failAll(error);
290
+ if (!turnSettled) {
291
+ turnSettled = true;
292
+ rejectTurn?.(error);
293
+ }
294
+ });
295
+ child.on('close', (code) => {
296
+ closed = true;
297
+ settleResponseWaiters();
298
+ const error = new Error(withStderr(`Codex app-server 退出(code ${code ?? 'null'})`));
299
+ failAll(error);
300
+ if (!turnSettled) {
301
+ turnSettled = true;
302
+ rejectTurn?.(error);
303
+ }
304
+ });
305
+ const timeoutMs = opts.timeoutMs ?? 10 * 60_000;
306
+ const cancel = () => {
307
+ if (threadId && turnId) {
308
+ void request('turn/interrupt', { threadId, turnId }, 3000).catch(() => undefined);
309
+ }
310
+ killCliProcess(child, opts.command ?? 'codex');
311
+ };
312
+ const timer = setTimeout(cancel, timeoutMs);
313
+ const onAbort = () => cancel();
314
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
315
+ try {
316
+ await request('initialize', {
317
+ clientInfo: { name: 'agent-bridge', version: '1.0.0' },
318
+ });
319
+ if (opts.nativeThreadId) {
320
+ try {
321
+ const resumed = (await request('thread/resume', {
322
+ threadId: opts.nativeThreadId,
323
+ }));
324
+ threadId = String(asObject(resumed['thread'])['id'] ?? opts.nativeThreadId);
325
+ }
326
+ catch {
327
+ threadId = '';
328
+ }
329
+ }
330
+ if (!threadId) {
331
+ const started = (await request('thread/start', {
332
+ cwd: opts.cwd,
333
+ approvalPolicy: 'on-request',
334
+ }));
335
+ threadId = String(asObject(started['thread'])['id'] ?? '');
336
+ }
337
+ if (!threadId)
338
+ throw new Error('Codex thread/start 未返回 thread id');
339
+ const startedTurn = (await request('turn/start', {
340
+ threadId,
341
+ input: [{ type: 'text', text: opts.prompt }],
342
+ }));
343
+ turnId = String(asObject(startedTurn['turn'])['id'] ?? '');
344
+ if (!turnId)
345
+ throw new Error('Codex turn/start 未返回 turn id');
346
+ opts.onTurn?.({
347
+ threadId,
348
+ turnId,
349
+ steer: async (text) => {
350
+ await request('turn/steer', {
351
+ threadId,
352
+ expectedTurnId: turnId,
353
+ input: [{ type: 'text', text }],
354
+ });
355
+ },
356
+ });
357
+ await turnDone;
358
+ return { threadId, text, status: 'completed' };
359
+ }
360
+ finally {
361
+ clearTimeout(timer);
362
+ opts.signal?.removeEventListener('abort', onAbort);
363
+ killCliProcess(child, opts.command ?? 'codex');
364
+ }
365
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 宿主注入环境变量的清理。
3
+ *
4
+ * 为什么需要:bridge 经常跑在 WorkBuddy / CodeBuddy 宿主进程里,宿主会把自己的会话上下文
5
+ * 塞进环境变量(`CODEBUDDY_SESSION_ID`、`CODEBUDDY_MCP_CONFIG`、`SERVER__PORT` …)。
6
+ * 子 CLI 继承它们会**冒充宿主会话**,最典型的症状是抢宿主的端口:
7
+ *
8
+ * 实测 codebuddy `-p --output-format stream-json --verbose`
9
+ * → `Error: listen EADDRINUSE: address already in use 127.0.0.1:57193`(exit 1)
10
+ * 清掉 `CODEBUDDY_*` 后立刻正常(exit 0,正常输出 stream-json)。
11
+ *
12
+ * 这类变量只对宿主自己有意义,平台任务不该继承 —— 继承了还会把宿主的 MCP 配置、
13
+ * 会话 id 一起带进去,任务行为跟着宿主漂。
14
+ */
15
+ /** 精确匹配(别的产品也可能注入同名变量,不做前缀匹配) */
16
+ const HOST_ENV_KEYS = [
17
+ 'SERVER__PORT',
18
+ 'CLAUDE_SESSION_ID',
19
+ // ACP 侧的原始清单(sanitizeHostEnv 一直依赖它,迁移到这里保持单一真源)
20
+ 'CODEBUDDY_SERVICE_PROXY_URL',
21
+ 'CODEBUDDY_SESSION_ID',
22
+ 'CODEBUDDY_TOOL_CALL_ID',
23
+ 'CODEBUDDY_ARTIFACTS',
24
+ 'CODEBUDDY_ROOT_REQUEST_ID',
25
+ 'CODEBUDDY_CONVERSATION_REQUEST_ID',
26
+ 'CODEBUDDY_CONVERSATION_MESSAGE_ID',
27
+ 'CODEBUDDY_MCP_CONFIG',
28
+ ];
29
+ /** 前缀匹配:宿主版本升级常新增同族变量,逐条维护必然漏 */
30
+ const HOST_ENV_PREFIXES = ['CODEBUDDY_'];
31
+ /** 例外:子进程**认证**要用,必须保留 */
32
+ const HOST_ENV_KEEP = new Set(['CODEBUDDY_AUTH_TOKEN']);
33
+ export function isHostInjectedEnv(key) {
34
+ if (HOST_ENV_KEEP.has(key))
35
+ return false;
36
+ if (HOST_ENV_KEYS.includes(key))
37
+ return true;
38
+ return HOST_ENV_PREFIXES.some((prefix) => key.startsWith(prefix));
39
+ }
40
+ /** 返回去掉宿主注入变量的**副本**(不改入参) */
41
+ export function withoutHostEnv(source) {
42
+ const out = {};
43
+ for (const [key, value] of Object.entries(source)) {
44
+ if (!isHostInjectedEnv(key))
45
+ out[key] = value;
46
+ }
47
+ return out;
48
+ }