Files
Agent-Workbench/src/core/models/messages-stream.mjs
T
2026-11-06 06:21:59 +08:00

79 lines
6.0 KiB
JavaScript

import { protocolFailure } from './protocols.mjs';
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const fail = message => { throw protocolFailure('Messages 流:' + message); };
// Each block and the whole message must close before any tool becomes dispatchable.
export function messagesStream(config = {}) {
let message = null, active = null, deltaSeen = false, stopped = false, text = '', toolCount = 0;
const blocks = [];
return {
consume(event) {
if (event.type === 'ping') return;
if (stopped) fail('终结后新增了事件。');
if (event.type === 'message_start') {
const start = event.message;
if (message || start?.type !== 'message' || start.role !== 'assistant' || typeof start.id !== 'string' || !start.id
|| !Array.isArray(start.content) || start.content.length || start.stop_reason != null) fail('创建事件重复或消息身份/内容无效。');
message = structuredClone(start);
} else if (!message) fail('事件缺少原 message_start。');
else if (event.type === 'content_block_start') {
if (deltaSeen || active !== null || !Number.isSafeInteger(event.index) || event.index !== blocks.length || config.executionMode !== 'unrestricted' && blocks.length >= 128) fail('内容块索引重复、逆序或上个块未完成。');
const block = event.content_block;
if (!object(block) || !['text', 'tool_use', 'thinking', 'redacted_thinking'].includes(block.type)) fail('未接入的内容块类型。');
if (block.type === 'text' && typeof block.text !== 'string' || block.type === 'tool_use' && (!object(block.input) || typeof block.id !== 'string' || !block.id || typeof block.name !== 'string' || !block.name)
|| block.type === 'thinking' && (typeof block.thinking !== 'string' || block.signature !== undefined && typeof block.signature !== 'string') || block.type === 'redacted_thinking' && typeof block.data !== 'string') fail('初始内容块格式无效。');
if (block.type === 'tool_use' && (++toolCount > 12 && config.executionMode !== 'unrestricted' || blocks.some(item => item.block.id === block.id))) fail('工具数量超限或身份重复。');
// Thinking signatures normally arrive in a later signature_delta.
// Final protocol normalization still requires a complete signature.
const initial = structuredClone(block);
if (initial.type === 'thinking') initial.signature ??= '';
blocks.push({ block: initial, json: '', jsonSeen: false, closed: false }); active = event.index;
if (block.type === 'text') text += block.text;
} else if (event.type === 'content_block_delta') {
if (active === null || event.index !== active || deltaSeen || !object(event.delta)) fail('内容片段缺少所属未完成块。');
const entry = blocks[active], block = entry.block, delta = event.delta;
if (block.type === 'text' && delta.type === 'text_delta' && typeof delta.text === 'string') { block.text += delta.text; text += delta.text; }
else if (block.type === 'text' && delta.type === 'citations_delta' && object(delta.citation)) (block.citations ??= []).push(structuredClone(delta.citation));
else if (block.type === 'tool_use' && delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
if (Object.keys(block.input).length) fail('工具初始 input 与增量参数同时存在。');
entry.jsonSeen = true; entry.json += delta.partial_json;
} else if (block.type === 'thinking' && delta.type === 'thinking_delta' && typeof delta.thinking === 'string') block.thinking += delta.thinking;
else if (block.type === 'thinking' && delta.type === 'signature_delta' && typeof delta.signature === 'string') block.signature += delta.signature;
else fail('增量类型与原内容块不一致或尚未接入。');
} else if (event.type === 'content_block_stop') {
if (active === null || event.index !== active || deltaSeen) fail('块终结缺少所属原内容。');
const entry = blocks[active];
if (entry.jsonSeen) {
try { entry.block.input = JSON.parse(entry.json); } catch { fail('工具参数不是完整 JSON。'); }
if (!object(entry.block.input)) fail('工具参数必须是对象。');
}
entry.closed = true; active = null;
} else if (event.type === 'message_delta') {
if (active !== null || !object(event.delta) || !object(event.usage)) fail('消息终结前内容块未完成或 delta/usage 无效。');
const reason = event.delta.stop_reason;
if (deltaSeen && reason != null && reason !== message.stop_reason) fail('消息停止原因发生变化。');
if (reason != null) { message.stop_reason = reason; deltaSeen = true; }
message.stop_sequence = event.delta.stop_sequence ?? message.stop_sequence;
message.usage ??= {};
for (const [key, value] of Object.entries(event.usage)) if (value !== null && value !== undefined) {
if (['input_tokens', 'output_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens'].includes(key)
&& (!Number.isSafeInteger(value) || value < 0 || typeof message.usage[key] === 'number' && value < message.usage[key])) fail('累计用量无效或倒退。');
message.usage[key] = structuredClone(value);
}
} else if (event.type === 'message_stop') {
if (!deltaSeen || active !== null || blocks.some(entry => !entry.closed)) fail('缺少完整块或停止原因。');
stopped = true; message.content = blocks.map(entry => entry.block);
} else fail('未接入的事件类型 ' + String(event.type).slice(0, 100) + '。');
},
get text() { return text; },
get tools() { return toolCount; },
get usage() { return message?.usage ?? null; },
get stopped() { return stopped; },
finish() {
if (!stopped) throw protocolFailure('Messages 流断开或缺少 message_stop,工具未执行。', 'stream_interrupted');
return message;
},
};
}