handlers.js
2.83 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
/**
* Claude Stream 消息处理器
*
* 后端只做:内部状态管理 + 纯文本流式输出
* 工具调用等结构化信息通过 acp_event 原样透传,由前端自行解析展示
*/
/**
* 创建统一的 session_update 事件(纯文本流式块)
*/
function createSessionUpdate(text) {
return {
update: {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text }
}
};
}
/**
* 消息处理器集合
* key: message.type 或 message.type:message.subtype
*/
const handlers = {
/**
* system:init - 初始化消息
*/
'system:init': (msg, ctx) => {
ctx.protocol.sessionId = msg.session_id;
ctx.log(`init 收到, session_id: ${msg.session_id}`);
},
/**
* stream_event - 流式输出事件
* 只处理纯文本 delta,工具信息通过 acp_event 原样透传
*/
'stream_event': (msg, ctx) => {
const event = msg.event;
if (!event) return;
ctx.protocol._hasStreamEvents = true;
if (event.type === 'content_block_delta') {
if (event.delta?.type === 'text_delta') {
const text = event.delta.text || '';
if (text) {
ctx.appendOutput(text);
ctx.emit('session_update', createSessionUpdate(text));
}
}
}
},
/**
* assistant - AI 响应消息(完整消息,非流式模式下使用)
*/
'assistant': (msg, ctx) => {
if (ctx.protocol._hasStreamEvents) return;
if (!msg.message?.content) return;
for (const block of msg.message.content) {
if (block.type === 'text') {
ctx.appendOutput(block.text);
ctx.emit('session_update', createSessionUpdate(block.text));
}
// tool_use 等其他 block 类型通过 acp_event 原样透传
}
},
/**
* user - 用户消息(含工具执行结果)
* 不做任何转换,原始数据通过 acp_event 透传给前端
*/
'user': (msg, ctx) => { },
/**
* result - 最终结果
*/
'result': (msg, ctx) => {
ctx.log(`result: ${msg.subtype}, duration: ${msg.duration_ms}ms`);
}
};
/**
* 处理消息的入口函数
*/
function handleMessage(msg, ctx) {
const exactKey = msg.subtype ? `${msg.type}:${msg.subtype}` : null;
if (exactKey && handlers[exactKey]) {
handlers[exactKey](msg, ctx);
return true;
}
if (handlers[msg.type]) {
handlers[msg.type](msg, ctx);
return true;
}
ctx.log(`未处理的消息类型: ${msg.type}${msg.subtype ? ':' + msg.subtype : ''}`);
return false;
}
/**
* 注册自定义处理器
*/
function registerHandler(key, handler) {
handlers[key] = handler;
}
/**
* 注册自定义 content block 处理器(保留接口兼容)
*/
function registerContentBlockHandler(type, handler) {
// no-op: 工具信息不再在后端处理
}
module.exports = {
handleMessage,
registerHandler,
registerContentBlockHandler,
createSessionUpdate
};