@bolloon/bolloon-agent 0.2.5 → 0.2.7
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.
- package/dist/agents/chat-segmenter.js +298 -0
- package/dist/web/server.js +32 -0
- package/dist/web/ui/message-renderer.js +56 -45
- package/package.json +1 -1
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chat-segmenter — 把 LLM 原始输出切成结构化 segments (前后端分离核心)
|
|
3
|
+
*
|
|
4
|
+
* 2026-07-01 (v0.2.6): 抽到独立模块. 目标: 前端只渲染, 不做正则.
|
|
5
|
+
*
|
|
6
|
+
* 设计:
|
|
7
|
+
* 后端跑完 LLM 一轮后, 调 segmentChatReply() 把 reply 切成:
|
|
8
|
+
* [{type: 'think', content: '...'}, {type: 'text', content: '...'}, ...]
|
|
9
|
+
* 然后序列化发给前端, 前端按 type 渲染 — 不知道任何 <invoke> / <function_calls>
|
|
10
|
+
* /<tool_call> / {tool:...} 这些 LLM 输出格式细节.
|
|
11
|
+
*
|
|
12
|
+
* 与 parse-tool-call.ts 的区别:
|
|
13
|
+
* - parse-tool-call: 找 **第一个** tool_call, 提取 name+args (用于 dispatch)
|
|
14
|
+
* - chat-segmenter: 切**整段** reply 为展示 segments, **完全去掉** tool_call 标记
|
|
15
|
+
* 复用 parse-tool-call 的 tool_call 检测逻辑保证一致性
|
|
16
|
+
*
|
|
17
|
+
* 返回类型: ChatSegment[] 序列化 JSON 给前端:
|
|
18
|
+
* {type: 'think'|'text'|'env_details'|'tool_call'|'final', content?: string, tool?: {...}}
|
|
19
|
+
*
|
|
20
|
+
* 顺序按 LLM 输出流排, 不重排.
|
|
21
|
+
*/
|
|
22
|
+
import { parseToolCall } from './parse-tool-call.js';
|
|
23
|
+
/** 切分 LLM 输出. */
|
|
24
|
+
export function segmentChatReply(reply, ctx) {
|
|
25
|
+
if (!reply)
|
|
26
|
+
return [];
|
|
27
|
+
const segments = [];
|
|
28
|
+
let remaining = reply;
|
|
29
|
+
// === 1. 启发式: 开头"让我.../First I'll.../I should..." 句子进 think 段 ===
|
|
30
|
+
// LLM 偶尔不写 <think> 标签但直接出思考. 启发式: 文本首句以这些模式开头 → think
|
|
31
|
+
// 必须在 step 1 (显式 <think> 切分) 之前 — 因为显式切分 push 完会反序
|
|
32
|
+
if (!remaining.startsWith('<think>')) {
|
|
33
|
+
remaining = extractLeadingThinking(remaining, segments);
|
|
34
|
+
}
|
|
35
|
+
// === 2. 切 <think>...</think> (内容保留, wrap 成 think segment) ===
|
|
36
|
+
remaining = extractAndPush('think', remaining, segments, /<think>([\s\S]*?)<\/think>/g);
|
|
37
|
+
// === 3. 切 <environment_details>...</environment_details> ===
|
|
38
|
+
remaining = extractAndPush('env_details', remaining, segments, /<environment_details>([\s\S]*?)<\/environment_details>/g);
|
|
39
|
+
// === 4. 切 tool_call 标记 (核心: 完全去掉, 不让前端看到) ===
|
|
40
|
+
// 2026-07-01 修: 这步必须在 final 之前 — final 标记之前的 tool_call 是
|
|
41
|
+
// "LLM 在 final 之前还在调工具", 这部分 content 应进 text (中间过程), 不应进 final.
|
|
42
|
+
remaining = stripToolCallMarkers(remaining, segments, ctx);
|
|
43
|
+
// === 5. 过滤 LLM 填充词 ("好了"/"完成"/"可以" 等单句 text 不上屏) ===
|
|
44
|
+
if (remaining.trim()) {
|
|
45
|
+
remaining = filterFillerText(remaining);
|
|
46
|
+
}
|
|
47
|
+
// === 6. final 之前的 text 段 (中间对话) push — 必须在 final push 之前 ===
|
|
48
|
+
// 注意: 这时 remaining 还含 <final gen> 标记 + 标记后内容. 切 final 前先把 <final gen> 之后内容清掉
|
|
49
|
+
// 实际: 切 final 后再切 text 更清楚
|
|
50
|
+
const finalIdx = remaining.indexOf('<final gen>');
|
|
51
|
+
let beforeFinalText = remaining;
|
|
52
|
+
if (finalIdx >= 0) {
|
|
53
|
+
beforeFinalText = remaining.substring(0, finalIdx);
|
|
54
|
+
}
|
|
55
|
+
const textContent = beforeFinalText.trim();
|
|
56
|
+
if (textContent) {
|
|
57
|
+
segments.push({ type: 'text', content: textContent });
|
|
58
|
+
}
|
|
59
|
+
// === 7. 切 <final gen>...</final gen> (永远最后 push, 渲染时在最后) ===
|
|
60
|
+
if (finalIdx >= 0) {
|
|
61
|
+
const afterFinal = remaining.substring(finalIdx + '<final gen>'.length).trim();
|
|
62
|
+
if (afterFinal) {
|
|
63
|
+
segments.push({ type: 'final', content: afterFinal });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return segments;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* 修 extractAndPush 的 reverse 删除 bug (2026-07-01)
|
|
70
|
+
* 之前: 用 mutate 后的 next 算切片, idx 错位 → 多 match 时删除错
|
|
71
|
+
* 现在: 用 lastIndex 累加在原文上标记删除区, 最后一次性 slice
|
|
72
|
+
*/
|
|
73
|
+
function extractAndPush(type, text, out, re) {
|
|
74
|
+
const matches = [];
|
|
75
|
+
const localRe = new RegExp(re.source, re.flags);
|
|
76
|
+
let m;
|
|
77
|
+
while ((m = localRe.exec(text)) !== null) {
|
|
78
|
+
const content = m[1] ? m[1].trim() : '';
|
|
79
|
+
matches.push({
|
|
80
|
+
start: m.index,
|
|
81
|
+
end: m.index + m[0].length,
|
|
82
|
+
content,
|
|
83
|
+
});
|
|
84
|
+
if (m[0].length === 0)
|
|
85
|
+
localRe.lastIndex++;
|
|
86
|
+
}
|
|
87
|
+
if (matches.length === 0)
|
|
88
|
+
return text;
|
|
89
|
+
// push 正向 (保顺序)
|
|
90
|
+
for (const m of matches) {
|
|
91
|
+
if (m.content)
|
|
92
|
+
out.push({ type, content: m.content });
|
|
93
|
+
}
|
|
94
|
+
// 删除: 在原文上基于 start/end 切片, 不在 mutate 后算 idx
|
|
95
|
+
let next = '';
|
|
96
|
+
let cursor = 0;
|
|
97
|
+
for (const m of matches) {
|
|
98
|
+
next += text.substring(cursor, m.start);
|
|
99
|
+
cursor = m.end;
|
|
100
|
+
}
|
|
101
|
+
next += text.substring(cursor);
|
|
102
|
+
return next;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* 启发式: 提取开头的"思考"句子 (2026-07-01 新增)
|
|
106
|
+
* 模式: 文本开头遇到这些起手式, 整句 (到下一个 \n 或 . 或 句号) 切到 think 段
|
|
107
|
+
* 例子:
|
|
108
|
+
* "让我先想想用户的需求" + 正文 → think(让我先想想用户的需求) + 正文
|
|
109
|
+
* "First I'll check the project structure" → think(...)
|
|
110
|
+
* 不命中 → 整段保留, 走 text
|
|
111
|
+
*/
|
|
112
|
+
function extractLeadingThinking(text, out) {
|
|
113
|
+
// 模式 1: 显式/隐式思考句首 (一句到第一个 \n 或 \.\?\! 结束)
|
|
114
|
+
// "让我..." / "我先..." / "先来..." / "接下来..." / "First, ..." / "I'll ..."
|
|
115
|
+
// 整句进 think, 后续 content 进 text
|
|
116
|
+
// 模式 2: 整行都是思考 (一行 \n 间隔)
|
|
117
|
+
const firstLineEnd = text.indexOf('\n');
|
|
118
|
+
const firstLine = firstLineEnd === -1 ? text : text.substring(0, firstLineEnd);
|
|
119
|
+
const rest = firstLineEnd === -1 ? '' : text.substring(firstLineEnd + 1);
|
|
120
|
+
// 中文/英文思考起手词
|
|
121
|
+
const thinkingStartRe = /^(让我|我先|我应该|先来|先|接下来|好的[,,]?\s*我|让我先|先看看|让我看看|思考|考虑)/;
|
|
122
|
+
const enThinkingStartRe = /^(Let me|I'll|I will|First,|Next,|Now,|So,|Alright[,.]\s+(?:let me|I'll|I will))/i;
|
|
123
|
+
if (firstLine.trim().length === 0) {
|
|
124
|
+
return text; // 空开头不动
|
|
125
|
+
}
|
|
126
|
+
// 单行启发式: 整行 < 120 字符 + 起始 match → 整行进 think
|
|
127
|
+
if (firstLine.length <= 120 && (thinkingStartRe.test(firstLine) || enThinkingStartRe.test(firstLine))) {
|
|
128
|
+
out.push({ type: 'think', content: firstLine.trim() });
|
|
129
|
+
return rest;
|
|
130
|
+
}
|
|
131
|
+
// 多行启发式: 第一段 (到第一个空行) 是思考
|
|
132
|
+
if (firstLine.length <= 80 && (thinkingStartRe.test(firstLine) || enThinkingStartRe.test(firstLine))) {
|
|
133
|
+
out.push({ type: 'think', content: firstLine.trim() });
|
|
134
|
+
return rest;
|
|
135
|
+
}
|
|
136
|
+
return text;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* 过滤 LLM 填充词 (2026-07-01 新增)
|
|
140
|
+
* 单独的"好了"/"完成"/"可以"/"答完了"等单句不显示在气泡
|
|
141
|
+
* 配合 segmentChatReply 步骤 6
|
|
142
|
+
*/
|
|
143
|
+
function filterFillerText(text) {
|
|
144
|
+
// 整行 = filler 词 → 整行丢
|
|
145
|
+
const lines = text.split('\n');
|
|
146
|
+
const filtered = [];
|
|
147
|
+
for (const line of lines) {
|
|
148
|
+
const t = line.trim();
|
|
149
|
+
if (!t)
|
|
150
|
+
continue;
|
|
151
|
+
// 匹配: 整行 = 填充词 (可带标点)
|
|
152
|
+
if (/^(好|好了|好的|完成|完成了|任务完成|可以|可以了|答完了|说完了|就这样|完了|done|ok|OK|Okay|okay|alright|fine|let me check|我来)\.?$/i.test(t)) {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
filtered.push(line);
|
|
156
|
+
}
|
|
157
|
+
return filtered.join('\n').trim();
|
|
158
|
+
}
|
|
159
|
+
/** 提取正则匹配的 group(1) 内容, 包装为 segment; 原文位置去掉 */
|
|
160
|
+
function stripToolCallMarkers(text, out, ctx) {
|
|
161
|
+
// 1. 解析 [TOOL_CALL]...[/TOOL_CALL]
|
|
162
|
+
let result = text.replace(/\[TOOL_CALL\][\s\S]*?\[\/TOOL_CALL\]/g, (m) => {
|
|
163
|
+
const parsed = parseToolCall(m, { tools: ctx.knownToolNames });
|
|
164
|
+
if (parsed)
|
|
165
|
+
out.push({ type: 'tool_call', tool: { name: parsed.name, args: parsed.args } });
|
|
166
|
+
return '';
|
|
167
|
+
});
|
|
168
|
+
// 2.<tool_call>...</tool_call> (OpenAI Hermes)
|
|
169
|
+
result = result.replace(/<tool_call>[\s\S]*?<\/tool_call>/gi, (m) => {
|
|
170
|
+
const parsed = parseToolCall(m, { tools: ctx.knownToolNames });
|
|
171
|
+
if (parsed)
|
|
172
|
+
out.push({ type: 'tool_call', tool: { name: parsed.name, args: parsed.args } });
|
|
173
|
+
return '';
|
|
174
|
+
});
|
|
175
|
+
// 3. <invoke name="X">...</invoke> (minimax/Hermes)
|
|
176
|
+
result = result.replace(/<invoke\s+name=["']([\w]+)["']>([\s\S]*?)<\/invoke>/g, (_m, name, inner) => {
|
|
177
|
+
if (ctx.knownToolNames.has(name)) {
|
|
178
|
+
const args = extractSimpleArgs(inner);
|
|
179
|
+
out.push({ type: 'tool_call', tool: { name, args } });
|
|
180
|
+
}
|
|
181
|
+
return '';
|
|
182
|
+
});
|
|
183
|
+
// 4. <function_calls>...</function_calls> 整块
|
|
184
|
+
result = result.replace(/<function_calls>[\s\S]*?<\/function_calls>/g, (m) => {
|
|
185
|
+
const parsed = parseToolCall(m, { tools: ctx.knownToolNames });
|
|
186
|
+
if (parsed)
|
|
187
|
+
out.push({ type: 'tool_call', tool: { name: parsed.name, args: parsed.args } });
|
|
188
|
+
return '';
|
|
189
|
+
});
|
|
190
|
+
// 5. JSON 形式 {"name": "X", "arguments": {...}}
|
|
191
|
+
result = result.replace(/\{\s*"name"\s*:\s*"([\w]+)"\s*,\s*"(?:arguments|input|args|params)"\s*:\s*(\{[\s\S]*?\})\s*\}/g, (_m, name, argsJson) => {
|
|
192
|
+
if (!ctx.knownToolNames.has(name))
|
|
193
|
+
return '';
|
|
194
|
+
let args = {};
|
|
195
|
+
try {
|
|
196
|
+
const parsed = JSON.parse(argsJson);
|
|
197
|
+
if (parsed && typeof parsed === 'object') {
|
|
198
|
+
args = Object.fromEntries(Object.entries(parsed).map(([k, v]) => [k, String(v)]));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
catch { }
|
|
202
|
+
out.push({ type: 'tool_call', tool: { name, args } });
|
|
203
|
+
return '';
|
|
204
|
+
});
|
|
205
|
+
// 6. tool => "X", args => {...} (Perplexity-style 内部)
|
|
206
|
+
result = result.replace(/\{\s*tool\s*=>\s*["']([\w]+)["']\s*(?:,\s*args\s*=>\s*(\{[\s\S]*?\}))?\s*\}/g, (_m, name, argsJson) => {
|
|
207
|
+
if (!ctx.knownToolNames.has(name))
|
|
208
|
+
return '';
|
|
209
|
+
let args = {};
|
|
210
|
+
if (argsJson) {
|
|
211
|
+
try {
|
|
212
|
+
const parsed = JSON.parse(argsJson);
|
|
213
|
+
if (parsed && typeof parsed === 'object') {
|
|
214
|
+
args = Object.fromEntries(Object.entries(parsed).map(([k, v]) => [k, String(v)]));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
catch { }
|
|
218
|
+
}
|
|
219
|
+
out.push({ type: 'tool_call', tool: { name, args } });
|
|
220
|
+
return '';
|
|
221
|
+
});
|
|
222
|
+
// 7. [Function calling]...[/Function calling] 旧 bolloon
|
|
223
|
+
result = result.replace(/\[Function[^\]]*\]\s*/g, '');
|
|
224
|
+
// 8. (2026-07-01) 未闭合的 tool_call 起始标签 (LLM 偶输出截断)
|
|
225
|
+
// 例子: "<tool_call><invoke name="shell_exec"><command>ls</command></invoke>" 缺少 </tool_call>
|
|
226
|
+
// 上面 1-7 步的正则都要求完整闭合对, 不闭合会留残文.
|
|
227
|
+
// 修法: 扫到孤立起始标签 (后面没有匹配的闭合) → 整段删到 \n\n 或 end
|
|
228
|
+
result = stripUnclosedToolCallTags(result);
|
|
229
|
+
return result;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* 删未闭合的 tool_call 起始标签 + 后面到段结束 (2026-07-01)
|
|
233
|
+
* 例子: "<tool_call><invoke name="shell_exec"><command>ls</command></invoke>"
|
|
234
|
+
* → 检查每个起始标签 (<tool_call>, <invoke, <function_calls, [TOOL_CALL])
|
|
235
|
+
* → 如果没找到对应闭合, 删整段
|
|
236
|
+
*/
|
|
237
|
+
function stripUnclosedToolCallTags(text) {
|
|
238
|
+
const startTags = [
|
|
239
|
+
{ tag: '<tool_call>', closeTag: '</tool_call>', openRe: /<tool_call>/g },
|
|
240
|
+
{ tag: '<invoke ', closeTag: '</invoke>', openRe: /<invoke\s+name=["']([\w]+)["']>/g },
|
|
241
|
+
{ tag: '<function_calls>', closeTag: '</function_calls>', openRe: /<function_calls>/g },
|
|
242
|
+
{ tag: '[TOOL_CALL]', closeTag: '[/TOOL_CALL]', openRe: /\[TOOL_CALL\]/g },
|
|
243
|
+
];
|
|
244
|
+
let result = text;
|
|
245
|
+
for (const { tag, closeTag, openRe } of startTags) {
|
|
246
|
+
let m;
|
|
247
|
+
while ((m = openRe.exec(result)) !== null) {
|
|
248
|
+
// 检查 startIdx 之后是否还有 closeTag
|
|
249
|
+
const tail = result.substring(m.index);
|
|
250
|
+
const closeIdx = tail.indexOf(closeTag);
|
|
251
|
+
if (closeIdx === -1) {
|
|
252
|
+
// 未闭合 — 删起始标签 + 之后所有内容 (到 \n\n 或 end)
|
|
253
|
+
const nextBlank = result.indexOf('\n\n', m.index);
|
|
254
|
+
const endIdx = nextBlank === -1 ? result.length : nextBlank;
|
|
255
|
+
result = result.substring(0, m.index) + result.substring(endIdx);
|
|
256
|
+
break; // 重新开始本 tag 扫描
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return result;
|
|
261
|
+
}
|
|
262
|
+
/** 从 <invoke>...</invoke> inner XML 抽 <command> / <args> / <parameter> 简易 args */
|
|
263
|
+
function extractSimpleArgs(inner) {
|
|
264
|
+
const args = {};
|
|
265
|
+
// <parameter name="X">value</parameter>
|
|
266
|
+
const paramRe = /<parameter\s+name=["'](\w+)["']>([\s\S]*?)<\/parameter>/g;
|
|
267
|
+
let m;
|
|
268
|
+
while ((m = paramRe.exec(inner)) !== null) {
|
|
269
|
+
args[m[1]] = m[2].trim();
|
|
270
|
+
}
|
|
271
|
+
// <param name="X">value</param>
|
|
272
|
+
if (Object.keys(args).length === 0) {
|
|
273
|
+
const shortRe = /<param\s+name=["'](\w+)["']>([\s\S]*?)<\/param>/g;
|
|
274
|
+
while ((m = shortRe.exec(inner)) !== null) {
|
|
275
|
+
args[m[1]] = m[2].trim().replace(/^["']|["']$/g, '');
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
// <command>X</command> + <args>Y</args>
|
|
279
|
+
if (Object.keys(args).length === 0) {
|
|
280
|
+
const cmdM = inner.match(/<command>([\s\S]*?)<\/command>/);
|
|
281
|
+
const argsM = inner.match(/<args>([\s\S]*?)<\/args>/);
|
|
282
|
+
if (cmdM) {
|
|
283
|
+
const cmd = cmdM[1].trim();
|
|
284
|
+
// auto-split (跟 parse-tool-call 一致: 含空格 → split)
|
|
285
|
+
if (cmd.includes(' ') && !argsM) {
|
|
286
|
+
const parts = cmd.split(/\s+/);
|
|
287
|
+
args.command = parts[0];
|
|
288
|
+
args.args = parts.slice(1).join(' ');
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
args.command = cmd;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (argsM)
|
|
295
|
+
args.args = argsM[1].trim();
|
|
296
|
+
}
|
|
297
|
+
return args;
|
|
298
|
+
}
|
package/dist/web/server.js
CHANGED
|
@@ -7,6 +7,7 @@ import * as fsSync from 'fs';
|
|
|
7
7
|
import * as path from 'path';
|
|
8
8
|
import * as os from 'os';
|
|
9
9
|
import { validateMessageInput, validateChannelInput, healthCheck, } from './input-validator.js';
|
|
10
|
+
import { segmentChatReply } from '../agents/chat-segmenter.js';
|
|
10
11
|
// 读自身 package.json 拿 version (health endpoint 用)
|
|
11
12
|
// 路径: src/web/server.ts → ../../package.json (编译后 dist/web/server.js)
|
|
12
13
|
let cachedVersion = null;
|
|
@@ -1408,6 +1409,12 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1408
1409
|
next();
|
|
1409
1410
|
});
|
|
1410
1411
|
app.use(express.static(webRoot));
|
|
1412
|
+
// 2026-07-01 (v0.2.6 修复): 前端 message-renderer import 了 src/agents/chat-segmenter.js,
|
|
1413
|
+
// 浏览器加载时按相对路径解析成 /agents/chat-segmenter.js. 这个路径在 webRoot (dist/web) 之外.
|
|
1414
|
+
// 解决: 把 dist/agents 也 mount 到 /agents 静态路径, 让前端 import 解析成功.
|
|
1415
|
+
// 这条不破坏 segmenter 内部 import (Node 走文件系统, 浏览器走 HTTP).
|
|
1416
|
+
const agentsRoot = path.join(webRoot, '..', 'agents');
|
|
1417
|
+
app.use('/agents', express.static(agentsRoot));
|
|
1411
1418
|
app.get('/', (req, res) => {
|
|
1412
1419
|
res.sendFile(join(webRoot, 'index.html'));
|
|
1413
1420
|
});
|
|
@@ -1466,6 +1473,31 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1466
1473
|
app.get('/api/health', (_req, res) => {
|
|
1467
1474
|
res.json(healthCheck(getPackageVersion()));
|
|
1468
1475
|
});
|
|
1476
|
+
// 2026-07-01 (v0.2.6): 前后端分离核心 — 后端切 LLM 输出为结构化 segments
|
|
1477
|
+
// - POST /api/segment-reply { reply, knownTools }
|
|
1478
|
+
// - 返回 ChatSegment[] (think / text / env_details / tool_call / final)
|
|
1479
|
+
// 前端拿到 segments 后只渲染, 不知道任何 LLM 格式 (minimax <invoke>, Hermes <tool_call>, Qwen function_calls, JSON 形式)
|
|
1480
|
+
app.post('/api/segment-reply', async (req, res) => {
|
|
1481
|
+
try {
|
|
1482
|
+
const body = req.body ?? {};
|
|
1483
|
+
const reply = typeof body.reply === 'string' ? body.reply : '';
|
|
1484
|
+
const knownToolsArr = Array.isArray(body.knownTools) ? body.knownTools : [];
|
|
1485
|
+
const knownToolNames = new Set(knownToolsArr.filter((s) => typeof s === 'string'));
|
|
1486
|
+
const segments = segmentChatReply(reply, { knownToolNames });
|
|
1487
|
+
res.json({
|
|
1488
|
+
ok: true,
|
|
1489
|
+
input_length: reply.length,
|
|
1490
|
+
segments,
|
|
1491
|
+
segments_count: segments.length,
|
|
1492
|
+
has_think: segments.some(s => s.type === 'think'),
|
|
1493
|
+
has_tool_call: segments.some(s => s.type === 'tool_call'),
|
|
1494
|
+
has_final: segments.some(s => s.type === 'final'),
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
catch (e) {
|
|
1498
|
+
res.status(400).json({ ok: false, reason: e?.message ?? 'parse error' });
|
|
1499
|
+
}
|
|
1500
|
+
});
|
|
1469
1501
|
// 全局兜底: 任何 next(err) 走到这里, 给出结构化 4xx/5xx 而不是默认 HTML
|
|
1470
1502
|
app.use((err, req, res, _next) => {
|
|
1471
1503
|
console.error('[server] unhandled error on', req.method, req.path, '-', err?.message || err);
|
|
@@ -40,6 +40,9 @@
|
|
|
40
40
|
// 类型定义
|
|
41
41
|
// ---------------------------------------------------------------------------
|
|
42
42
|
import { mountStepTimeline, pushStepToTimeline, migrateStepTimeline, getStepTimeline, } from './step-timeline.js';
|
|
43
|
+
// 2026-07-01 (v0.2.6): 共享后端切 LLM 输出. 消除 <invoke>/<function_calls>/<tool_call>
|
|
44
|
+
// 等各种 LLM 格式在前端气泡里出现的 bug.
|
|
45
|
+
import { segmentChatReply } from '../../agents/chat-segmenter.js';
|
|
43
46
|
// ---------------------------------------------------------------------------
|
|
44
47
|
// 模块私有状态
|
|
45
48
|
// ---------------------------------------------------------------------------
|
|
@@ -117,55 +120,63 @@ export function addMessage(content, type, save = true, container, usedJudgmentId
|
|
|
117
120
|
}
|
|
118
121
|
const div = document.createElement('div');
|
|
119
122
|
div.className = `message message-${type}`;
|
|
120
|
-
//
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
// think 折叠
|
|
130
|
-
const thinkMatch = cleanContent.match(/<think>([\s\S]*?)<\/think>/);
|
|
131
|
-
let mainContent = cleanContent;
|
|
132
|
-
let thinkContainer = null;
|
|
133
|
-
if (thinkMatch) {
|
|
134
|
-
const thinkContent = thinkMatch[1].trim();
|
|
135
|
-
mainContent = cleanContent.replace(/<think>[\s\S]*?<\/think>/, '').trim();
|
|
136
|
-
thinkContainer = buildThinkContainer(thinkContent);
|
|
137
|
-
}
|
|
138
|
-
// environment_details 折叠 + 身份头
|
|
139
|
-
const envMatch = mainContent.match(/^(.+?)\n<environment_details>([\s\S]*?)<\/environment_details>\n([\s\S]*)$/);
|
|
140
|
-
if (envMatch) {
|
|
141
|
-
const identity = envMatch[1].trim();
|
|
142
|
-
const envDetails = envMatch[2].trim();
|
|
143
|
-
const messageBody = envMatch[3].trim();
|
|
144
|
-
const header = document.createElement('div');
|
|
145
|
-
header.className = 'message-header';
|
|
146
|
-
header.textContent = identity;
|
|
147
|
-
div.appendChild(header);
|
|
148
|
-
div.appendChild(buildEnvContainer(envDetails));
|
|
149
|
-
if (thinkContainer)
|
|
150
|
-
div.appendChild(thinkContainer);
|
|
151
|
-
if (messageBody)
|
|
152
|
-
div.appendChild(buildBubble(messageBody, type));
|
|
123
|
+
// 2026-07-01 (v0.2.6 前后端分离): 改用 chat-segmenter 纯函数切 LLM 输出.
|
|
124
|
+
// 之前 8 行正则漏 minimax <invoke> / Qwen function_calls / <tool_call> / {tool:..}.
|
|
125
|
+
// 单一来源: src/agents/chat-segmenter.ts (server + client 共享).
|
|
126
|
+
// knownToolNames: 用 ctx 传入的注册表, fallback 空集 (不识别 tool_call 就 strip 不显示).
|
|
127
|
+
const knownToolNames = (ctx && ctx.knownToolNames) || new Set();
|
|
128
|
+
const segments = segmentChatReply(content, { knownToolNames });
|
|
129
|
+
// 没有可显示的 segment, 不上屏
|
|
130
|
+
if (segments.length === 0) {
|
|
131
|
+
return;
|
|
153
132
|
}
|
|
154
|
-
|
|
155
|
-
|
|
133
|
+
// 渲染各 segment (按 type 走不同容器)
|
|
134
|
+
let thinkContainer = null;
|
|
135
|
+
let renderedAny = false;
|
|
136
|
+
for (const seg of segments) {
|
|
137
|
+
if (seg.type === 'think' && seg.content) {
|
|
138
|
+
thinkContainer = buildThinkContainer(seg.content);
|
|
156
139
|
div.appendChild(thinkContainer);
|
|
157
|
-
|
|
140
|
+
renderedAny = true;
|
|
141
|
+
}
|
|
142
|
+
else if (seg.type === 'env_details' && seg.content) {
|
|
143
|
+
div.appendChild(buildEnvContainer(seg.content));
|
|
144
|
+
renderedAny = true;
|
|
145
|
+
}
|
|
146
|
+
else if (seg.type === 'text' && seg.content) {
|
|
147
|
+
if (thinkContainer)
|
|
148
|
+
div.appendChild(thinkContainer);
|
|
149
|
+
thinkContainer = null;
|
|
150
|
+
div.appendChild(buildBubble(seg.content, type));
|
|
151
|
+
renderedAny = true;
|
|
152
|
+
}
|
|
153
|
+
else if (seg.type === 'final' && seg.content) {
|
|
154
|
+
if (thinkContainer)
|
|
155
|
+
div.appendChild(thinkContainer);
|
|
156
|
+
thinkContainer = null;
|
|
157
|
+
// final 段渲染为特殊气泡 (顶部有标记, 表示 LLM 显式终止)
|
|
158
|
+
const finalEl = buildBubble(seg.content, type);
|
|
159
|
+
finalEl.classList.add('bubble-final');
|
|
160
|
+
div.appendChild(finalEl);
|
|
161
|
+
renderedAny = true;
|
|
162
|
+
}
|
|
163
|
+
else if (seg.type === 'tool_call' && seg.tool) {
|
|
164
|
+
// tool_call segment 不渲染文字 — 走 step-timeline (步骤状态条)
|
|
165
|
+
// 这里只记录到 ctx 让外层在 addMessage 后挂到 timeline
|
|
166
|
+
if (ctx && ctx.toolCallCallback) {
|
|
167
|
+
ctx.toolCallCallback(seg.tool, div);
|
|
168
|
+
}
|
|
169
|
+
renderedAny = true; // 即使没文字, tool_call 也算"有意义"
|
|
170
|
+
}
|
|
158
171
|
}
|
|
159
|
-
|
|
160
|
-
return; //
|
|
172
|
+
if (!renderedAny) {
|
|
173
|
+
return; // 没有渲染任何东西, 不上屏
|
|
161
174
|
}
|
|
162
|
-
// 纯文本用于复制按钮
|
|
163
|
-
const rawContent =
|
|
164
|
-
.
|
|
165
|
-
.
|
|
166
|
-
.
|
|
167
|
-
.replace(/&/g, '&')
|
|
168
|
-
.replace(/ /g, ' ');
|
|
175
|
+
// 纯文本用于复制按钮 — 现在从 segments 拼, 不再依赖 cleanContent 变量
|
|
176
|
+
const rawContent = segments
|
|
177
|
+
.filter(s => s.type === 'text' || s.type === 'final')
|
|
178
|
+
.map(s => s.content || '')
|
|
179
|
+
.join('\n');
|
|
169
180
|
// 时间
|
|
170
181
|
const time = document.createElement('div');
|
|
171
182
|
time.className = 'time';
|