agent-bridge-service 0.2.3 → 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 +104 -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 +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 +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,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,310 @@
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 { killCliProcess, spawnCliProcess } from './agent-adapters.js';
16
+ export function codexAppServerArgs() {
17
+ return ['app-server', '--stdio'];
18
+ }
19
+ function asObject(value) {
20
+ return typeof value === 'object' && value !== null ? value : {};
21
+ }
22
+ function errorText(value) {
23
+ if (typeof value === 'string')
24
+ return value;
25
+ if (value && typeof value === 'object' && typeof value['message'] === 'string') {
26
+ return String(value['message']);
27
+ }
28
+ return JSON.stringify(value);
29
+ }
30
+ export function codexTurnError(status, error) {
31
+ if (status === 'completed')
32
+ return undefined;
33
+ const detail = error === undefined ? '' : errorText(error);
34
+ return new Error(`Codex turn ${status || 'unknown'}${detail ? `:${detail}` : ''}`);
35
+ }
36
+ function deliveryFuture() {
37
+ let settle;
38
+ const promise = new Promise((resolvePromise) => {
39
+ settle = resolvePromise;
40
+ });
41
+ return { promise, settle };
42
+ }
43
+ export async function runCodexPrompt(opts) {
44
+ const child = spawnCliProcess(opts.command ?? 'codex', codexAppServerArgs(), {
45
+ cwd: opts.cwd,
46
+ env: process.env,
47
+ });
48
+ let nextId = 1;
49
+ let threadId = '';
50
+ let turnId = '';
51
+ let text = '';
52
+ let closed = false;
53
+ let turnSettled = false;
54
+ const responseWaiters = new Set();
55
+ const settleResponseWaiters = () => {
56
+ for (const finish of responseWaiters)
57
+ finish(false);
58
+ responseWaiters.clear();
59
+ };
60
+ let resolveTurn;
61
+ let rejectTurn;
62
+ const turnDone = new Promise((resolve, reject) => {
63
+ resolveTurn = resolve;
64
+ rejectTurn = reject;
65
+ });
66
+ const pending = new Map();
67
+ const send = (message) => {
68
+ if (closed || !child.stdin.writable || child.stdin.destroyed)
69
+ return false;
70
+ try {
71
+ child.stdin.write(`${JSON.stringify(message)}\n`);
72
+ // false 仅表示背压,数据已被流接受;不能据此误判成交付失败。
73
+ return true;
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ };
79
+ const request = (method, params, timeoutMs = 15_000) => new Promise((resolve, reject) => {
80
+ const id = nextId++;
81
+ const timer = setTimeout(() => {
82
+ pending.delete(id);
83
+ reject(new Error(`Codex ${method} 超时(${timeoutMs}ms)`));
84
+ }, timeoutMs);
85
+ pending.set(id, { resolve, reject, timer });
86
+ send({ jsonrpc: '2.0', id, method, params });
87
+ });
88
+ const writeResponse = (message) => {
89
+ if (closed || !child.stdin.writable)
90
+ return Promise.resolve(false);
91
+ return new Promise((resolvePromise) => {
92
+ let finished = false;
93
+ const finish = (delivered) => {
94
+ if (finished)
95
+ return;
96
+ finished = true;
97
+ responseWaiters.delete(finish);
98
+ resolvePromise(delivered);
99
+ };
100
+ responseWaiters.add(finish);
101
+ try {
102
+ child.stdin.write(`${JSON.stringify(message)}\n`, (error) => finish(!error));
103
+ }
104
+ catch {
105
+ finish(false);
106
+ }
107
+ });
108
+ };
109
+ const respond = (id, result) => {
110
+ if (typeof id !== 'number' && typeof id !== 'string')
111
+ return Promise.resolve(false);
112
+ return writeResponse({ jsonrpc: '2.0', id, result });
113
+ };
114
+ const respondError = (id, code, message) => {
115
+ if (typeof id !== 'number' && typeof id !== 'string')
116
+ return Promise.resolve(false);
117
+ return writeResponse({ jsonrpc: '2.0', id, error: { code, message } });
118
+ };
119
+ const failAll = (error) => {
120
+ for (const p of pending.values()) {
121
+ clearTimeout(p.timer);
122
+ p.reject(error);
123
+ }
124
+ pending.clear();
125
+ };
126
+ const handleServerRequest = async (message) => {
127
+ const delivery = deliveryFuture();
128
+ const method = String(message['method'] ?? '');
129
+ const params = asObject(message['params']);
130
+ const kind = method === 'item/fileChange/requestApproval'
131
+ ? 'file-change'
132
+ : method === 'item/tool/requestUserInput'
133
+ ? 'user-input'
134
+ : method === 'item/permissions/requestApproval'
135
+ ? 'permission'
136
+ : 'command';
137
+ try {
138
+ const decision = opts.onApproval
139
+ ? await opts.onApproval({
140
+ requestId: message['id'] ?? '',
141
+ method,
142
+ kind,
143
+ payload: params,
144
+ delivery: delivery.promise,
145
+ })
146
+ : undefined;
147
+ if (method === 'item/tool/requestUserInput') {
148
+ // The caller returns a JSON string or undefined; undefined means cancel the turn.
149
+ if (decision) {
150
+ try {
151
+ delivery.settle(await respond(message['id'], JSON.parse(decision)));
152
+ }
153
+ catch {
154
+ delivery.settle(await respond(message['id'], { answers: {} }));
155
+ }
156
+ }
157
+ else {
158
+ delivery.settle(await respondError(message['id'], -32000, 'user input cancelled'));
159
+ }
160
+ return;
161
+ }
162
+ delivery.settle(await respond(message['id'], { decision: decision ?? 'decline' }));
163
+ }
164
+ catch {
165
+ delivery.settle(false);
166
+ await respond(message['id'], { decision: 'decline' });
167
+ }
168
+ };
169
+ const handleNotification = (message) => {
170
+ const method = String(message['method'] ?? '');
171
+ const params = asObject(message['params']);
172
+ opts.onUpdate?.({ method, params });
173
+ if (method === 'item/agentMessage/delta') {
174
+ const delta = params['delta'];
175
+ if (typeof delta === 'string')
176
+ text += delta;
177
+ return;
178
+ }
179
+ if (method === 'turn/completed') {
180
+ if (turnSettled)
181
+ return;
182
+ turnSettled = true;
183
+ const turn = asObject(params['turn']);
184
+ const status = String(turn['status'] ?? 'unknown');
185
+ const error = codexTurnError(status, turn['error']);
186
+ if (error)
187
+ rejectTurn?.(error);
188
+ else
189
+ resolveTurn?.();
190
+ return;
191
+ }
192
+ };
193
+ const rl = createInterface({ input: child.stdout });
194
+ rl.on('line', (line) => {
195
+ const trimmed = line.trim();
196
+ if (!trimmed.startsWith('{'))
197
+ return;
198
+ let message;
199
+ try {
200
+ message = JSON.parse(trimmed);
201
+ }
202
+ catch {
203
+ return;
204
+ }
205
+ const id = message['id'];
206
+ if (typeof id === 'number' && pending.has(id)) {
207
+ const p = pending.get(id);
208
+ if (!p)
209
+ return;
210
+ pending.delete(id);
211
+ clearTimeout(p.timer);
212
+ if (message['error'])
213
+ p.reject(new Error(errorText(message['error'])));
214
+ else
215
+ p.resolve(message['result']);
216
+ return;
217
+ }
218
+ if (message['method']) {
219
+ if (id !== undefined)
220
+ void handleServerRequest(message);
221
+ else {
222
+ try {
223
+ handleNotification(message);
224
+ }
225
+ catch (error) {
226
+ failAll(error);
227
+ killCliProcess(child, opts.command ?? 'codex');
228
+ }
229
+ }
230
+ }
231
+ });
232
+ child.on('error', (error) => {
233
+ settleResponseWaiters();
234
+ failAll(error);
235
+ if (!turnSettled) {
236
+ turnSettled = true;
237
+ rejectTurn?.(error);
238
+ }
239
+ });
240
+ child.on('close', (code) => {
241
+ closed = true;
242
+ settleResponseWaiters();
243
+ const error = new Error(`Codex app-server 退出(code ${code ?? 'null'})`);
244
+ failAll(error);
245
+ if (!turnSettled) {
246
+ turnSettled = true;
247
+ rejectTurn?.(error);
248
+ }
249
+ });
250
+ const timeoutMs = opts.timeoutMs ?? 10 * 60_000;
251
+ const cancel = () => {
252
+ if (threadId && turnId) {
253
+ void request('turn/interrupt', { threadId, turnId }, 3000).catch(() => undefined);
254
+ }
255
+ killCliProcess(child, opts.command ?? 'codex');
256
+ };
257
+ const timer = setTimeout(cancel, timeoutMs);
258
+ const onAbort = () => cancel();
259
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
260
+ try {
261
+ await request('initialize', {
262
+ clientInfo: { name: 'agent-bridge', version: '1.0.0' },
263
+ });
264
+ if (opts.nativeThreadId) {
265
+ try {
266
+ const resumed = (await request('thread/resume', {
267
+ threadId: opts.nativeThreadId,
268
+ }));
269
+ threadId = String(asObject(resumed['thread'])['id'] ?? opts.nativeThreadId);
270
+ }
271
+ catch {
272
+ threadId = '';
273
+ }
274
+ }
275
+ if (!threadId) {
276
+ const started = (await request('thread/start', {
277
+ cwd: opts.cwd,
278
+ approvalPolicy: 'on-request',
279
+ }));
280
+ threadId = String(asObject(started['thread'])['id'] ?? '');
281
+ }
282
+ if (!threadId)
283
+ throw new Error('Codex thread/start 未返回 thread id');
284
+ const startedTurn = (await request('turn/start', {
285
+ threadId,
286
+ input: [{ type: 'text', text: opts.prompt }],
287
+ }));
288
+ turnId = String(asObject(startedTurn['turn'])['id'] ?? '');
289
+ if (!turnId)
290
+ throw new Error('Codex turn/start 未返回 turn id');
291
+ opts.onTurn?.({
292
+ threadId,
293
+ turnId,
294
+ steer: async (text) => {
295
+ await request('turn/steer', {
296
+ threadId,
297
+ expectedTurnId: turnId,
298
+ input: [{ type: 'text', text }],
299
+ });
300
+ },
301
+ });
302
+ await turnDone;
303
+ return { threadId, text, status: 'completed' };
304
+ }
305
+ finally {
306
+ clearTimeout(timer);
307
+ opts.signal?.removeEventListener('abort', onAbort);
308
+ killCliProcess(child, opts.command ?? 'codex');
309
+ }
310
+ }
@@ -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
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Minimal MCP elicitation client (stdio JSON-RPC).
3
+ *
4
+ * MCP servers may ask the client for structured input:
5
+ * server -> client elicitation/create { message, requestedSchema }
6
+ * client -> server { action: 'accept'|'decline'|'cancel', content? }
7
+ *
8
+ * This module is transport-only: it does not decide policy, persist forms, or wire bridge
9
+ * interactions. Callers provide the elicitation handler (which can map to task_interaction_request).
10
+ */
11
+ import { spawn } from 'node:child_process';
12
+ import { createInterface } from 'node:readline';
13
+ export class McpElicitationClient {
14
+ options;
15
+ child;
16
+ rl;
17
+ nextId = 1;
18
+ pending = new Map();
19
+ closed = false;
20
+ timeoutMs;
21
+ constructor(options) {
22
+ this.options = options;
23
+ this.timeoutMs = options.timeoutMs ?? 15_000;
24
+ }
25
+ async start() {
26
+ if (this.child)
27
+ return;
28
+ const { spec } = this.options;
29
+ const child = spawn(spec.command, spec.args ?? [], {
30
+ cwd: spec.cwd,
31
+ env: spec.env ?? process.env,
32
+ stdio: ['pipe', 'pipe', 'pipe'],
33
+ windowsHide: true,
34
+ });
35
+ this.child = child;
36
+ this.rl = createInterface({ input: child.stdout });
37
+ this.rl.on('line', (line) => void this.onLine(line));
38
+ child.on('error', (error) => this.failAll(error));
39
+ child.on('close', () => {
40
+ this.closed = true;
41
+ this.failAll(new Error('MCP 进程已退出'));
42
+ });
43
+ await this.request('initialize', {
44
+ protocolVersion: this.options.protocolVersion ?? '2025-06-18',
45
+ capabilities: { elicitation: {} },
46
+ clientInfo: this.options.clientInfo ?? { name: 'agent-bridge', version: '1.0.0' },
47
+ });
48
+ this.send({ jsonrpc: '2.0', method: 'notifications/initialized' });
49
+ }
50
+ async listTools() {
51
+ await this.start();
52
+ const result = (await this.request('tools/list', {}));
53
+ return Array.isArray(result.tools) ? result.tools : [];
54
+ }
55
+ async callTool(name, args = {}, timeoutMs = this.timeoutMs) {
56
+ await this.start();
57
+ return this.request('tools/call', { name, arguments: args }, timeoutMs);
58
+ }
59
+ close() {
60
+ this.closed = true;
61
+ this.rl?.close();
62
+ this.child?.kill();
63
+ this.child?.stdin.destroy();
64
+ this.child?.stdout.destroy();
65
+ this.child?.stderr.destroy();
66
+ this.child?.unref();
67
+ this.failAll(new Error('MCP 客户端已关闭'));
68
+ }
69
+ send(message) {
70
+ const child = this.child;
71
+ if (!child || this.closed || !child.stdin.writable)
72
+ return;
73
+ child.stdin.write(`${JSON.stringify(message)}\n`);
74
+ }
75
+ request(method, params, timeoutMs = this.timeoutMs) {
76
+ return new Promise((resolve, reject) => {
77
+ const id = this.nextId++;
78
+ const timer = setTimeout(() => {
79
+ this.pending.delete(id);
80
+ reject(new Error(`MCP ${method} 超时(${timeoutMs}ms)`));
81
+ }, timeoutMs);
82
+ this.pending.set(id, { resolve, reject, timer });
83
+ this.send({ jsonrpc: '2.0', id, method, params });
84
+ });
85
+ }
86
+ async onLine(line) {
87
+ const trimmed = line.trim();
88
+ if (!trimmed)
89
+ return;
90
+ let message;
91
+ try {
92
+ message = JSON.parse(trimmed);
93
+ }
94
+ catch {
95
+ return;
96
+ }
97
+ const id = message['id'];
98
+ if (typeof id === 'number' && (message['result'] !== undefined || message['error'] !== undefined)) {
99
+ const pending = this.pending.get(id);
100
+ if (!pending)
101
+ return;
102
+ this.pending.delete(id);
103
+ clearTimeout(pending.timer);
104
+ if (message['error'] !== undefined) {
105
+ pending.reject(new Error(`MCP 错误:${JSON.stringify(message['error'])}`));
106
+ }
107
+ else {
108
+ pending.resolve(message['result']);
109
+ }
110
+ return;
111
+ }
112
+ if (message['method'] === 'elicitation/create' && typeof id === 'number') {
113
+ const params = (message['params'] ?? {});
114
+ let response = { action: 'cancel' };
115
+ try {
116
+ response = this.options.onElicitation
117
+ ? await this.options.onElicitation({
118
+ message: String(params['message'] ?? ''),
119
+ requestedSchema: typeof params['requestedSchema'] === 'object' && params['requestedSchema'] !== null
120
+ ? params['requestedSchema']
121
+ : {},
122
+ raw: params,
123
+ })
124
+ : { action: 'cancel' };
125
+ }
126
+ catch {
127
+ response = { action: 'cancel' };
128
+ }
129
+ this.send({ jsonrpc: '2.0', id, result: response });
130
+ return;
131
+ }
132
+ // 其他 server -> client 请求:明确返回 method not found,避免 stdio 对端挂死。
133
+ if (typeof id === 'number' && typeof message['method'] === 'string') {
134
+ this.send({
135
+ jsonrpc: '2.0',
136
+ id,
137
+ error: { code: -32601, message: `unsupported client method: ${message['method']}` },
138
+ });
139
+ }
140
+ }
141
+ failAll(error) {
142
+ for (const pending of this.pending.values()) {
143
+ clearTimeout(pending.timer);
144
+ pending.reject(error);
145
+ }
146
+ this.pending.clear();
147
+ }
148
+ }