ClaudeCliProtocol.js
18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/**
* ClaudeCliProtocol — Claude Code CLI stream-json 交互协议
*
* 使用 `claude --input-format stream-json --output-format stream-json --verbose
* --include-partial-messages --dangerously-skip-permissions` 与 Claude CLI 通信。
*
* 持久化进程:启动一次,跨多次 sendPrompt 调用复用。
*
* 与 AcpProtocol 的区别:
* - 不使用 JSON-RPC(Claude CLI 自有协议)
* - 输入:{"type":"user","message":{"role":"user","content":[{"type":"text","text":"..."}]}}
* - 输出:NDJSON 流
* - {type:"stream_event", event:{type:"content_block_delta", delta:{type:"text_delta",...}}}
* - {type:"assistant", message:{...}} (带 --include-partial-messages)
* - {type:"result", result:"...", stop_reason:"end_turn"}
* - initialize() / newSession() 为 no-op
*
* 事件兼容 AcpProtocol 接口:
* - emit('session_update', { update: { sessionUpdate, content: { text } } })
* - emit('acp_event', { type, method, params, timestamp })
* - emit('error', Error)
*/
const { EventEmitter } = require('events');
const { spawn } = require('child_process');
class ClaudeCliProtocol extends EventEmitter {
constructor(agentInfo = {}, options = {}) {
super();
this.agentInfo = agentInfo;
this.options = options;
this.isConnected = false;
this.sessionId = null;
this._child = null;
this._workingDir = null;
this._buffer = '';
this._promptResolve = null;
this._promptReject = null;
}
/**
* 连接:启动 Claude CLI 持久进程
* transport 参数被忽略:本协议自行管理子进程
*/
async connect(transport, workingDir) {
this._workingDir = workingDir;
const args = [
'--input-format', 'stream-json',
'--output-format', 'stream-json',
'--verbose',
'--include-partial-messages',
'--dangerously-skip-permissions',
];
// 支持禁用特定原生工具 (用于编排型 Agent,强制纯文本输出)
if (this.options.disallowedTools && this.options.disallowedTools.length > 0) {
args.push('--disallowedTools', ...this.options.disallowedTools);
}
// 支持仅开放特定工具 (空字符串 = 禁用全部)
if (this.options.allowedTools !== undefined) {
if (this.options.allowedTools === '') {
args.push('--tools', '');
} else if (Array.isArray(this.options.allowedTools)) {
args.push('--allowedTools', ...this.options.allowedTools);
}
}
// 支持 effort 级别控制 (low/medium/high/max)
// low = 禁用 extended thinking,大幅节省 token
const effort = this.options.effort || process.env.CLAUDE_EFFORT;
if (effort) {
args.push('--effort', effort);
console.log(`[ClaudeCliProtocol] 💡 effort=${effort}`);
}
const processEnv = { ...process.env };
delete processEnv.NODE_OPTIONS;
delete processEnv.ELECTRON_RUN_AS_NODE;
delete processEnv.CLAUDECODE;
console.log(`[ClaudeCliProtocol] 启动: claude ${args.join(' ')}`);
this._child = spawn('claude', args, {
stdio: ['pipe', 'pipe', 'pipe'],
env: processEnv,
cwd: workingDir,
});
// stdout → NDJSON 解析
this._child.stdout.on('data', (data) => {
const raw = data.toString();
console.log(`[ClaudeCliProtocol] 📥 stdout (${raw.length} bytes):`, raw.substring(0, 200));
this._buffer += raw;
const lines = this._buffer.split('\n');
this._buffer = lines.pop() || '';
// 有 stdout 活动 → 重置超时计时器
if (this._resetIdleTimer) this._resetIdleTimer();
for (const line of lines) {
if (!line.trim()) continue;
try {
const event = JSON.parse(line);
this._handleStreamEvent(event);
} catch (e) {
// 非 JSON 行:拦截纯文本的崩溃日志或 API 拒绝日志
const msg = line.trim();
if (msg) {
console.log(`[ClaudeCliProtocol] 📝 非JSON文本:`, msg.substring(0, 300));
// 触发类似 stderr 的检测逻辑
if (this._promptReject && /error|rate.?limit|429|401|403|authentication|api.?key|quota|billing|失败/i.test(msg)) {
const err = new Error(`API 请求失败 (Raw): ${msg.substring(0, 500)}`);
console.error(`[ClaudeCliProtocol] 拦截到底层纯文本错误:`, err.message);
if (this._idleTimer) { clearTimeout(this._idleTimer); this._idleTimer = null; }
this._promptReject(err);
this._promptResolve = null;
this._promptReject = null;
}
}
}
}
});
// stderr 转发 + 致命错误检测
this._child.stderr.on('data', (data) => {
const msg = data.toString().trim();
if (msg) {
console.log(`[ClaudeCliProtocol] 🚨 stderr (${msg.length} bytes):`, msg.substring(0, 500));
this.emit('stderr', msg);
// 检测致命错误:如果 sendPrompt 正在等待,主动 reject 防止 Promise 永远挂起
if (this._promptReject && /rate.?limit|usage.?limit|429|401|403|authentication|api.?key|quota|billing/i.test(msg)) {
const err = new Error(`Claude CLI 致命错误: ${msg.substring(0, 500)}`);
this._promptReject(err);
this._promptResolve = null;
this._promptReject = null;
console.error('[ClaudeCliProtocol] 致命错误已触发 Promise reject');
}
}
});
// 进程退出
this._child.on('exit', (code, signal) => {
console.log(`[ClaudeCliProtocol] 进程退出: code=${code} signal=${signal}`);
this.isConnected = false;
this._child = null;
if (this._promptReject) {
this._promptReject(new Error(`Claude CLI 进程退出: code=${code} signal=${signal}`));
this._promptResolve = null;
this._promptReject = null;
}
this.emit('disconnected', { code, signal });
});
this._child.on('error', (err) => {
console.error('[ClaudeCliProtocol] 进程错误:', err.message);
this.emit('error', err);
});
// 等待进程启动
await new Promise((resolve, reject) => {
this._child.on('error', reject);
setTimeout(resolve, 500);
});
this.isConnected = true;
console.log('[ClaudeCliProtocol] 进程已启动');
}
/**
* Claude CLI 不需要 JSON-RPC initialize — no-op
*/
async initialize() {
console.log('[ClaudeCliProtocol] skip initialize (Claude CLI 自有协议)');
return { protocolVersion: 1 };
}
/**
* Claude CLI 不需要 session/new — no-op
*/
async newSession(options = {}) {
this._workingDir = options.cwd || this._workingDir || '.';
this.sessionId = `claude-cli-${Date.now()}`;
console.log('[ClaudeCliProtocol] newSession (virtual):', this.sessionId);
return { sessionId: this.sessionId };
}
/**
* 发送 prompt 到 Claude CLI
*
* 写入 stream-json 格式消息到 stdin:
* {"type":"user","message":{"role":"user","content":[{"type":"text","text":"..."}]}}
*
* 等待 type=result 消息后 resolve。
*
* @param {string} text - prompt 文本
* @returns {Promise<void>}
*/
sendPrompt(text) {
return new Promise((resolve, reject) => {
if (!this._child || !this.isConnected) {
return reject(new Error('[ClaudeCliProtocol] 进程未启动'));
}
this._promptResolve = resolve;
this._promptReject = reject;
// 超时保护:如果 45 秒内没有任何 stdout 活动(API hang/rate limit 静默),自动 reject
const IDLE_TIMEOUT_MS = 45_000;
let idleTimer = setTimeout(() => {
if (this._promptReject) {
const err = new Error(`Claude CLI 响应超时 (${IDLE_TIMEOUT_MS / 1000}s 无活动)`);
console.error('[ClaudeCliProtocol]', err.message);
this._promptReject(err);
this._promptResolve = null;
this._promptReject = null;
this._idleTimer = null;
}
}, IDLE_TIMEOUT_MS);
// 每次收到 stdout 数据时重置超时(说明 CLI 还活着)
this._idleTimer = idleTimer;
this._resetIdleTimer = () => {
if (this._idleTimer) {
clearTimeout(this._idleTimer);
this._idleTimer = setTimeout(() => {
if (this._promptReject) {
const err = new Error(`Claude CLI 响应超时 (${IDLE_TIMEOUT_MS / 1000}s 无活动)`);
console.error('[ClaudeCliProtocol]', err.message);
this._promptReject(err);
this._promptResolve = null;
this._promptReject = null;
this._idleTimer = null;
}
}, IDLE_TIMEOUT_MS);
}
};
// Claude CLI stream-json 输入格式
const message = {
type: 'user',
message: {
role: 'user',
content: [{ type: 'text', text }],
},
};
const jsonLine = JSON.stringify(message) + '\n';
console.log(`[ClaudeCliProtocol] 发送 prompt (${text.length} chars)`);
try {
this._child.stdin.write(jsonLine);
} catch (e) {
clearTimeout(idleTimer);
this._promptResolve = null;
this._promptReject = null;
this._idleTimer = null;
reject(new Error(`[ClaudeCliProtocol] stdin 写入失败: ${e.message}`));
}
});
}
/**
* 处理 Claude CLI stream-json 输出事件
*
* 事件类型:
* - {type:"system"} — 系统初始化
* - {type:"stream_event", event:{type:"content_block_delta", delta:{...}}} — 流式增量
* - {type:"assistant", message:{content:[{type:"text",text:"..."}]}} — 完整/部分消息
* - {type:"result", result:"...", stop_reason:"end_turn"} — 最终结果
*
* @private
*/
_handleStreamEvent(event) {
console.log(`[ClaudeCliProtocol] 🔄 event.type=${event.type}`);
switch (event.type) {
case 'system':
this.sessionId = event.session_id || this.sessionId;
this.emit('acp_event', {
type: 'notification',
method: 'system/init',
params: event,
timestamp: Date.now(),
});
break;
case 'stream_event':
this._handleInnerStreamEvent(event.event, event.session_id);
break;
case 'assistant':
// 带 --include-partial-messages 时,每次 API 响应更新都发送完整 assistant 消息
// 仅提取增量文本(由 stream_event 处理),这里用于工具检测
if (event.message?.content) {
for (const block of event.message.content) {
if (block.type === 'text' && block.text) {
// assistant 消息的完整文本(包含已流式发送的内容)
// 不再 emit session_update 避免重复,stream_event 已处理增量
}
}
}
break;
case 'result':
this.sessionId = event.session_id || this.sessionId;
// 【核心发现】Claude CLI 会在自己内部重试(长达3分钟),最后如果依然失败,
// 会输出 result 事件,但带有 "is_error": true,并且 result 字段放着错误信息。
if (event.is_error) {
if (this._idleTimer) { clearTimeout(this._idleTimer); this._idleTimer = null; }
const err = new Error(`API 请求失败 (内部重试后放弃): ${event.result || 'Unknown HTTP/RateLimit Error'}`);
console.error(`[ClaudeCliProtocol] 收到错误 result:`, err.message);
if (this._promptReject) {
this._promptReject(err);
this._promptResolve = null;
this._promptReject = null;
}
// 不要再发送正常 result notification
break;
}
this.emit('acp_event', {
type: 'notification',
method: 'session/result',
params: {
result: event.result,
duration_ms: event.duration_ms,
cost_usd: event.total_cost_usd,
session_id: event.session_id,
stop_reason: event.stop_reason,
},
timestamp: Date.now(),
});
if (this._promptResolve) {
if (this._idleTimer) { clearTimeout(this._idleTimer); this._idleTimer = null; }
this._promptResolve();
this._promptResolve = null;
this._promptReject = null;
}
break;
case 'error':
this.emit('acp_event', {
type: 'notification',
method: 'claude/error',
params: event,
timestamp: Date.now(),
});
// API 报错(如 MiniMax 429)会通过 stdout 下发 error 对象,此时不会下发 result
if (this._promptReject) {
const errMsg = event.error?.message || event.message || JSON.stringify(event);
const err = new Error(`API 请求失败: ${errMsg}`);
console.error(`[ClaudeCliProtocol] 拦截到底层 API 错误:`, err.message);
if (this._idleTimer) { clearTimeout(this._idleTimer); this._idleTimer = null; }
this._promptReject(err);
this._promptResolve = null;
this._promptReject = null;
}
break;
default:
this.emit('acp_event', {
type: 'notification',
method: `claude/${event.type}`,
params: event,
timestamp: Date.now(),
});
}
}
/**
* 处理 stream_event 内层事件(Anthropic Streaming API 格式)
*
* event.type:
* - message_start — 消息开始
* - content_block_start — 内容块开始(text / thinking / tool_use)
* - content_block_delta — 增量内容
* - delta.type: "text_delta" → emit session_update
* - delta.type: "thinking_delta" → emit session_update (thought)
* - content_block_stop — 内容块结束
* - message_delta — 消息级更新(stop_reason 等)
* - message_stop — 消息结束
*
* @private
*/
_handleInnerStreamEvent(innerEvent, sessionId) {
if (!innerEvent) return;
switch (innerEvent.type) {
case 'content_block_delta':
if (innerEvent.delta?.type === 'text_delta' && innerEvent.delta.text) {
this.emit('session_update', {
update: {
sessionUpdate: 'agent_message_chunk',
content: { text: innerEvent.delta.text },
},
});
} else if (innerEvent.delta?.type === 'thinking_delta' && innerEvent.delta.thinking) {
this.emit('session_update', {
update: {
sessionUpdate: 'agent_thought_chunk',
content: { text: innerEvent.delta.thinking },
},
});
}
break;
case 'content_block_start':
// 可用于检测 tool_use 块开始
if (innerEvent.content_block?.type === 'tool_use') {
this.emit('acp_event', {
type: 'notification',
method: 'claude/tool_use_start',
params: {
tool_use_id: innerEvent.content_block.id,
name: innerEvent.content_block.name,
},
timestamp: Date.now(),
});
}
break;
case 'message_start':
case 'content_block_stop':
case 'message_delta':
case 'message_stop':
// 透传为 acp_event
this.emit('acp_event', {
type: 'notification',
method: `claude/stream/${innerEvent.type}`,
params: innerEvent,
timestamp: Date.now(),
});
break;
}
}
/**
* 断开连接 — 终止 Claude CLI 进程
*/
disconnect() {
if (this._child) {
try { this._child.stdin.end(); } catch { }
try { this._child.kill('SIGTERM'); } catch { }
this._child = null;
}
this.isConnected = false;
this.sessionId = null;
}
}
module.exports = { ClaudeCliProtocol };