夜雨聆风学习资料网

ARTICLE · 1387735

Claude Code 源码-消息模型与会话流

Claude Code 源码-消息模型与会话流

Claude Code 源码解析系列

第 10 讲:消息模型与会话流

基于 Claude Code 源码快照 · 2026-11-20

💡 本讲一句话:Claude Code 把"一条消息从流式 token 变成 API payload"的全过程压进一个 5512 行的 utils/messages.ts——本地合成消息、逐块拆分、流式拼接、相邻合并、配对修复,五道工序全在这里。读完你能看懂它为什么用 "<synthetic>" 假模型名标记本地消息、为什么把用户文本"塞进" tool_result(A/B 实验从 92% 降到 0%)、以及那个能救活死锁会话的 ensureToolResultPairing。

一、为什么一个文件有 5512 行

前几讲我们拆了 QueryEngine 的 turn 状态机(第 5 讲)、SSE 事件循环(第 6 讲)、请求构造与流式解析(第 7/8 讲)。但有一个问题一直悬着:消息本身长什么样?模型吐出的 token、用户敲下的字、工具执行的结果,在内存里到底是一个什么结构?

答案就在 src/utils/messages.ts——5512 行,约 193KB。它不定义类型(类型在 types/message.js,这个泄露快照里恰好缺失,我们从用法反推),而是承担全部消息加工逻辑:创建、拆分、合并、流式拼接、API 归一化、配对修复。换句话说,它是消息流的"交通枢纽"——每条进出的消息都要过它的手。

先建立两个核心概念:Message(带 type 判别字段的信封)和 content block(信封里的内容块:text / tool_use / tool_result / thinking...)。一条 assistant 消息的 content 可以同时包含"一段文字 + 三个工具调用",而 UI 渲染要求"每条消息只有一个块"——这个矛盾就是后面 normalizeMessages 存在的原因。

二、本地合成消息:假模型名 "<synthetic>"

Claude Code 里大量"assistant 消息"根本不是模型说的——权限被拒、用户中断、API 报错,都要以 assistant 身份插一条消息进会话流(因为 API 要求角色交替)。怎么区分真假?看 baseCreateAssistantMessage:

📄 src/utils/messages.ts (第 355-409 行,节选)

function baseCreateAssistantMessage({          // 本地"assistant 消息"工厂:所有非真实 API 响应的 assistant 消息都走这里  content,                                     // 内容块数组:text / tool_use / thinking...  isApiErrorMessage = false,                   // 是否标记为"API 错误消息"(UI 和管线都会特殊对待)  apiError,                                    // SDK 原始错误对象  error,                                       // 给 SDK 消费者的结构化错误信息  errorDetails,                                // 人类可读的错误详情  isVirtual,                                   // true = 仅展示的虚拟消息,永远不发往 API  usage = { input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, ... },  // 默认全零 token 统计(本地消息没有真实用量)}: {                                           // 参数类型声明(content: BetaContentBlock[] 等,其余可选字段略)  content: BetaContentBlock[]                  // 内容必须是块数组}): AssistantMessage {                         // 返回类型:assistant 消息  return {                                     // 组装完整消息信封    type: 'assistant',                         // 判别字段——下游所有 switch 都靠它分派    uuid: randomUUID(),                        // 本地唯一 ID;UI 去重、[id:] 引用标签(见 deriveShortMessageId)都用它    timestamp: new Date().toISOString(),       // ISO 时间戳,用于排序和 transcript 落盘    message: {                                 // 内层是 API 协议的 Message 结构——本地消息也长这个样      id: randomUUID(),                        // API 侧消息 ID;本地生成占位(真实值来自服务端响应)      container: null,                         // 服务端容器预留字段(如代码执行沙箱)      model: SYNTHETIC_MODEL,                  // '<synthetic>'——"这条不是真模型生成的"标记,全文件多处靠它识别合成消息      role: 'assistant',                       // API 协议要求的角色      stop_reason: 'stop_sequence',            // 填一个合法值;本地消息没有真实停止原因      stop_sequence: '',                       // 空串占位,满足类型要求      type: 'message',                         // SDK 消息信封类型      usage,                                   // token 统计(默认全零)      content,                                 // 内容块数组      context_management: null,                // API 预留的上下文管理字段    },    requestId: undefined,                      // 真实请求 ID 只在来自真 API 响应时才有值    apiError,                                  // 透传错误对象(如有)    error,                                     // 透传结构化错误    errorDetails,                              // 透传错误详情    isApiErrorMessage,                         // 透传"API 错误消息"标记    isVirtual,                                 // 透传虚拟标记  }                                            // 返回组装好的消息}

为什么这样设计:本地合成消息和真实 API 响应共用同一个结构(内层就是 SDK 的 BetaMessage),下游代码不需要两套处理路径。区分真假不靠额外字段,而是把 model 填成假值 '<synthetic>'——isSyntheticApiErrorMessage()(第 321-329 行)就是拿这个标记做识别的。这种"用协议字段当标记位"的手法很省:不新增类型、不改序列化,一个字符串常量就解决了。

三、合成消息的文案就是 prompt

权限被拒时插进会话流的那条消息,措辞不是随便写的——它直接决定模型下一步行为。看第 207-247 行的一组常量:

📄 src/utils/messages.ts (第 207-247 行,节选)

export const INTERRUPT_MESSAGE = '[Request interrupted by user]'                    // 用户按 Esc 中断;这句话原样喂回模型,告诉它"人类接管了"export const CANCEL_MESSAGE = "The user doesn't want to take this action right now. STOP what you are doing and wait for the user to tell you how to proceed."  // 权限取消:明确命令模型停下等待,防止它自作主张重试export const REJECT_MESSAGE = "The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed."  // 工具调用被拒:特意强调"副作用没有发生",防止模型以为写入已成功export const SUBAGENT_REJECT_MESSAGE = 'Permission for this tool use was denied. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). Try a different approach or report the limitation to complete your task.'  // 子代理版:没有用户可等——改为指示"换条路走,或如实上报限制"export const NO_RESPONSE_REQUESTED = 'No response requested.'                       // 工具不需要结果时的占位文案(如 TodoWrite)export const SYNTHETIC_TOOL_RESULT_PLACEHOLDER = '[Tool result missing due to internal error]'  // 合成 tool_result 的占位内容;HFI 训练数据提交会拒绝任何含此串的 payload——内容是假的,提交了就污染训练数据

为什么这样设计:注意 REJECT_MESSAGE 里那句 "the new_string was NOT written to the file"——模型被拒后最容易犯的错是"假设操作成功了"继续往下走,这句括号注释就是专门堵这个幻觉的。而子代理版把"STOP and wait for user"换成"Try a different approach or report the limitation":子代理没有用户可等,等待指令会让它卡死,所以文案按场景分化。这些字符串本身就是 prompt engineering,改一个词都可能改变模型行为。

再看 SYNTHETIC_TOOL_RESULT_PLACEHOLDER:第 242-245 行的注释说得很直白——这个占位符"结构上满足了配对要求,但内容是假的"。所以 HFI(人类反馈)数据提交管线会主动拒绝任何包含它的 payload。一个字符串常量同时服务两个系统:运行时修复 + 训练数据卫生。

消息类型
来源 / 含义
发往 API?
assistant
模型输出,或本地合成(model='<synthetic>')
✅ 发(isVirtual 的除外)
user
人类输入 / tool_result / 系统注入的 meta 内容(isMeta)
✅ 发(含 isMeta,只是打标)
system(local_command)
本地命令输出(/bash、slash 命令)
转成 user 消息后发
progress
工具执行进度(REPL 展示用)
❌ 发送前被过滤
attachment
hook / 附件内容(如 system-reminder)
上移重排后参与发送
tombstone / stream_event
删除标记 / SSE 传输层事件
❌ 控制信号,不是消息

为什么这样设计:一张表看清"谁进 API、谁只给 UI 看"。关键洞察:会话流是超集,API payload 是子集——progress、tombstone、虚拟消息都活在 REPL 里但永远不上线;反过来 local_command 的 system 消息要伪装成 user 才能上线(第 2078-2093 行)。这个"双视图"模型贯穿整个文件。

四、normalizeMessages:一条消息拆成多条

UI 渲染要求"每条消息一个内容块"(这样每个工具调用能独立折叠、独立高亮),但 API 返回的 assistant 消息 content 里可能同时有 text + 3 个 tool_use。拆分本身不难,难的是UUID:拆出来的多条消息不能共用原 UUID(UI 靠它去重),又不能每次随机生成(resume 后要稳定)。解法是确定性派生:

📄 src/utils/messages.ts (第 725-823 行,节选)

export function deriveUUID(parentUUID: UUID, index: number): UUID {   // 从父 UUID + 序号确定性派生子 UUID  const hex = index.toString(16).padStart(12, '0')                    // 序号转 12 位十六进制(正好是 UUID 尾段长度)  return `${parentUUID.slice(0, 24)}${hex}` as UUID                  // 保留父 ID 前 24 字符 + 换掉尾段——同一父消息永远派生出同样的子 ID}   // deriveUUID 结束// Split messages, so each content block gets its own message   // UI 渲染要求"每条消息一个内容块"export function normalizeMessages(messages: Message[]): NormalizedMessage[] {   // 消息拆分入口:一条输入可展开成多条输出  let isNewChain = false   // 一旦遇到多块消息,后续所有消息都要换新 UUID(防止拆出的子 ID 与后面某条原 ID 撞车)  return messages.flatMap(message => {                            // flatMap:一条输入消息可以展开成多条输出    switch (message.type) {   // 按消息类型分派      case 'assistant': {   // assistant 分支        isNewChain = isNewChain || message.message.content.length > 1   // 多内容块 → 从这里开始进入"新链"        return message.message.content.map((_, index) => {             // 每个块产出一条消息          const uuid = isNewChain ? deriveUUID(message.uuid, index) : message.uuid  // 新链:确定性派生;否则保留原 UUID          return {   // 组装单条归一化消息            type: 'assistant' as const,   // 判别字段照抄            timestamp: message.timestamp, // 时间戳继承            message: { ...message.message, content: [_], context_management: message.message.context_management ?? null },  // 关键:content 只留这一块            isMeta: message.isMeta,       // meta 标记透传(系统注入的消息)            isVirtual: message.isVirtual, // 虚拟标记透传            requestId: message.requestId, // 请求 ID 透传            uuid,                         // 新派生或原 UUID            error: message.error,         // 错误信息跟着拆出的片段走            isApiErrorMessage: message.isApiErrorMessage,  // API 错误标记也跟随            advisorModel: message.advisorModel,            // advisor 模型标记(如有)          } as NormalizedAssistantMessage   // 断言为归一化 assistant 类型        })   // map 回调结束(每块一条)      }   // assistant 分支结束      case 'attachment': return [message]   // attachment 不拆,原样通过      case 'progress':   return [message]   // progress 不拆      case 'system':     return [message]   // system 不拆      case 'user': {   // user 分支:字符串内容先包成 text 块再逐块拆        if (typeof message.message.content === 'string') {  // user 的 content 可能是纯字符串:包成单个 text 块          const uuid = isNewChain ? deriveUUID(message.uuid, 0) : message.uuid   // 单块情形:序号固定为 0          return [{ ...message, uuid, message: { ...message.message, content: [{ type: 'text', text: message.message.content }] } } as NormalizedMessage]   // 把字符串包成单个 text 块,以数组形式返回        }   // 字符串内容分支结束        isNewChain = isNewChain || message.message.content.length > 1   // user 多块消息同样触发新链        let imageIndex = 0   // 图片块计数器:用来对齐原消息的 imagePasteIds 数组        return message.message.content.map((_, index) => {             // 每个块产出一条          const isImage = _.type === 'image'                           // 判断是否图片块          const imageId = isImage && message.imagePasteIds ? message.imagePasteIds[imageIndex] : undefined  // 拆出的片段只携带属于自己的那个图片 ID          if (isImage) imageIndex++                                     // 计数器前进          return { ...createUserMessage({ content: [_], toolUseResult: message.toolUseResult, mcpMeta: message.mcpMeta, isMeta: message.isMeta, isVisibleInTranscriptOnly: message.isVisibleInTranscriptOnly, isVirtual: message.isVirtual, timestamp: message.timestamp, imagePasteIds: imageId !== undefined ? [imageId] : undefined, origin: message.origin }), uuid: isNewChain ? deriveUUID(message.uuid, index) : message.uuid } as NormalizedMessage  // 走工厂函数重建(保证字段完整),再覆盖为派生 UUID        })   // map 回调结束(每块一条)      }   // user 分支结束    }   // switch 结束  })   // flatMap 回调结束}   // normalizeMessages 结束

为什么这样设计:isNewChain 这个标志位是最精妙的地方——它不是"这条消息要不要拆",而是"从这条开始,后面所有消息的 UUID 都要换"。因为拆出的子 ID(父前缀+序号)理论上可能和会话里后面某条真实消息的 UUID 撞车;一旦进入新链就全部重派生,用确定性算法保证 resume 后结果一致。deriveUUID 保留父 ID 前 24 字符还有个隐藏好处:子 ID 肉眼可辨地"属于"父消息,调试 transcript 时一眼看出血缘。

user 分支里 imageIndex 的对齐逻辑也值得注意:一条 user 消息可能带两张粘贴截图(imagePasteIds: [7, 9]),拆成两条后必须各自只带自己的 ID,否则 UI 会把同一张图渲染两遍。

五、流式拼接:handleMessageFromStream

第 6 讲拆过 SSE 事件循环,但"事件怎么变成 UI 状态"的最后一环在这里。这个函数(第 2930-3094 行)是唯一消费流事件的入口:SSE 解析器每吐一个事件就调它一次。注意它的参数——全是回调,而且更新状态的回调都是 (f: (state) => state) 的 reducer 形式:

📄 src/utils/messages.ts (第 2930-2999 行)

export function handleMessageFromStream(   // 流事件分派器:SSE 到 UI 状态的唯一入口  message: Message | TombstoneMessage | StreamEvent | RequestStartEvent | ToolUseSummaryMessage,  // 所有可能的流事件联合类型  onMessage: (message: Message) => void,        // 完整消息回调 → push 进 messages 数组  onUpdateLength: (newContent: string) => void, // delta 长度回调 → 驱动 token 计数器动画  onSetStreamMode: (mode: SpinnerMode) => void, // 切换 spinner 模式(thinking / responding / tool-input...)  onStreamingToolUses: (f: (s: StreamingToolUse[]) => StreamingToolUse[]) => void,  // 更新流式工具输入状态(reducer 形式,避免读到过期闭包值)  onTombstone?: (message: Message) => void,     // tombstone 回调 → 从数组里删除指定消息  onStreamingThinking?: (f: (c: StreamingThinking | null) => StreamingThinking | null) => void,  // 更新 thinking 流式状态  onApiMetrics?: (metrics: { ttftMs: number }) => void,  // 上报首 token 延迟 TTFT  onStreamingText?: (f: (current: string | null) => string | null) => void,  // 累积流式文本(reducer 形式)): void {   // 参数列表结束,函数体开始  if (message.type !== 'stream_event' && message.type !== 'stream_request_start') {   // 非流事件 = 完整消息或控制信号    if (message.type === 'tombstone') { onTombstone?.(message.message); return }      // tombstone:删除目标消息,而不是新增    if (message.type === 'tool_use_summary') { return }                                // SDK-only 的摘要消息;流处理里直接忽略    if (message.type === 'assistant') {                                                // 完整 assistant 消息到达      const thinkingBlock = message.message.content.find(block => block.type === 'thinking')  // 找完整的 thinking 块      if (thinkingBlock && thinkingBlock.type === 'thinking') {   // 找到了完整的 thinking 块        onStreamingThinking?.(() => ({ thinking: thinkingBlock.thinking, isStreaming: false, streamingEndedAt: Date.now() }))  // 捕获下来,供 transcript 模式实时展示      }   // thinking 捕获分支结束    }   // assistant 处理结束    onStreamingText?.(() => null)   // 先清空流式文本:渲染层在同一批次里从 deferredMessages 切到 messages——原子切换,无空隙也无重复    onMessage(message)              // 再 push 完整消息(顺序不能反!)    return   // 完整消息处理完毕,直接退出  }   // 非流事件分支结束  if (message.type === 'stream_request_start') { onSetStreamMode('requesting'); return }  // 请求已发出:spinner 切到"等首 token"  if (message.event.type === 'message_start') {   // SSE 第一个事件    if (message.ttftMs != null) { onApiMetrics?.({ ttftMs: message.ttftMs }) }  // 携带 TTFT 指标(从发请求到收到第一字节的毫秒数)  }   // 函数体结束  if (message.event.type === 'message_stop') { onSetStreamMode('tool-use'); onStreamingToolUses(() => []); return }  // 消息结束:清空流式工具状态

为什么这样设计:onStreamingText?.(() => null) 必须在 onMessage(message)之前执行——注释写得很清楚:渲染层要在同一批次里完成"流式文本 → 最终消息"的切换。如果顺序反了,用户会看到文字闪一下消失再出现(重复),或者中间空一帧(空隙)。这种"先清后推"的原子性约定,是终端 UI 不闪烁的关键。

再看 reducer 形式的回调 (f) => void:调用方传一个函数进去,函数接收当前最新状态返回新状态。为什么不直接传值?因为流事件处理可能跨多个微任务,闭包里捕获的旧状态会过期;reducer 形式让状态更新永远基于"此刻的值",和 React 的 setState(fn) 是同一个思想。

📄 src/utils/messages.ts (第 3001-3094 行,节选)

  switch (message.event.type) {   // SSE 事件类型分派    case 'content_block_start':   // 一个新的内容块开始      onStreamingText?.(() => null)  // 重置文本累积器:上一个块的文本已定稿,不能混进新块      if (feature('CONNECTOR_TEXT') && isConnectorTextBlock(message.event.content_block)) { onSetStreamMode('responding'); return }  // connector text 块(内部特性):只切模式不累积      switch (message.event.content_block.type) {   // 按块类型设置 UI 模式        case 'thinking': case 'redacted_thinking': onSetStreamMode('thinking'); return   // thinking 块 → thinking 模式        case 'text': onSetStreamMode('responding'); return                                // text 块 → responding 模式        case 'tool_use': {                                                                // 工具调用开始:UI 可以显示"正在生成参数"          onSetStreamMode('tool-input')   // 切到 tool-input 模式          const contentBlock = message.event.content_block   // 块头(id / name,此时还没有 input)          const index = message.event.index                  // 该块在消息内的序号——并行工具调用靠它区分          onStreamingToolUses(_ => [..._, { index, contentBlock, unparsedToolInput: '' }])  // 注册进流式状态;input 从空字符串开始累积          return   // 注册完流式状态,退出该 case        }   // tool_use 分支结束        case 'server_tool_use': case 'web_search_tool_result': case 'code_execution_tool_result': /* ...另有 7 种服务端块类型... */ onSetStreamMode('tool-input'); return  // 服务端工具块(web search / code execution 等)→ 同样进 tool-input 模式      }   // 块类型分派结束      return   // content_block_start 处理完毕    case 'content_block_delta':   // 增量内容到达      switch (message.event.delta.type) {   // 按 delta 类型分派        case 'text_delta': {   // text_delta:文本增量          const deltaText = message.event.delta.text         // 这一小段文本          onUpdateLength(deltaText)                           // 更新长度 → token 计数器动画          onStreamingText?.(text => (text ?? '') + deltaText)  // 追加到流式文本缓冲          return   // 本段累积完成,退出        }   // text_delta 分支结束        case 'input_json_delta': {                            // 工具 input 以 JSON 字符串碎片到达          const delta = message.event.delta.partial_json      // 这一小段 partial JSON          const index = message.event.index                   // 属于哪个 tool_use 块          onUpdateLength(delta)                               // 同样计入长度          onStreamingToolUses(_ => {                          // 更新对应流式状态            const element = _.find(_ => _.index === index)    // 按序号找到已注册的 tool_use            if (!element) return _                            // 找不到(理论上不会):原样返回            return [..._.filter(_ => _ !== element), { ...element, unparsedToolInput: element.unparsedToolInput + delta }]  // 追加碎片;此刻仍是字符串——解析在 normalizeContentFromAPI 里做          })   // 流式工具更新回调结束          return   // JSON 碎片追加完成,退出        }   // input_json_delta 分支结束        case 'thinking_delta': onUpdateLength(message.event.delta.thinking); return  // thinking 文本也计入长度        case 'signature_delta': return  // signature 是加密认证串,不是模型输出:不计入 OTPS / token 计数器(否则会虚增指标)      }   // delta 分派结束      return   // 块结束无需动作,直接退出    case 'content_block_stop': return   // 块结束:无需动作(定稿发生在消息级)    case 'message_delta': onSetStreamMode('responding'); return  // 消息级 delta(stop_reason 等)→ 回到 responding 模式    default: onSetStreamMode('responding'); return               // 未知事件类型:兜底回 responding  }   // switch 结束}   // 函数体结束

为什么这样设计:两个细节最见功力。其一,input_json_delta 只累积不解析——工具参数可能几十 KB,边流边 parse 既浪费又会在中途 JSON 不完整时抛错;先攒字符串、等块结束统一解析(第六节),是典型的"延迟求值"。其二,signature_delta 被显式排除在长度统计外:thinking 的加密签名不是模型"说"的内容,算进 token 计数器会让用户看到虚高的速度——注释里明说了这是为了防止"inflate the OTPS metric"。

🔍 对照 Hermes:Hermes Agent 的流式渲染也是"delta 累积 + 定稿替换",但状态更新走的是事件总线;Claude Code 这里用 reducer 回调把"读旧值"的坑从机制上堵死了——本地模型窗口小、事件密集时,这种写法更不容易出竞态。

六、相邻 user 消息合并:Bedrock 的锅 + A/B 实验的果

API 有个硬约束:连续两条 user 消息在 Bedrock 上会报错(1P API 支持但会合并成一个 turn)。而 Claude Code 的会话流里 user 消息天然扎堆——工具结果、hook 注入、排队命令全是 user。所以发送前必须合并,合并时又有两个坑要填:

📄 src/utils/messages.ts (第 2411-2503 行,节选)

export function mergeUserMessages(a: UserMessage, b: UserMessage): UserMessage {   // 把两条相邻 user 消息合成一条  const lastContent = normalizeUserTextContent(a.message.content)    // a 的 content 归一化成块数组(字符串 → [text])  const currentContent = normalizeUserTextContent(b.message.content) // b 同理  if (feature('HISTORY_SNIP')) { /* ...snip 特性门控分支:isMeta 语义改为"两者都 meta 才 meta"... */ }  // 仅 snip runtime 开启时生效(改 isMeta 会影响下游 VCR fixture 哈希,所以必须门控)  return {   // 组装合并后的消息    ...a,   // 以 a 的全部字段为基底    uuid: a.isMeta ? b.uuid : a.uuid,   // 保留非 meta 消息的 UUID:[id:] 引用标签由 UUID 派生,跨 API 调用必须稳定(meta 消息每次都是新 UUID)    message: {   // 只覆盖内层 message      ...a.message,   // 保留 a 的内层结构(id / role 等)      content: hoistToolResults(joinTextAtSeam(lastContent, currentContent)),  // 先缝合接缝文本,再把 tool_result 全部提到最前    },   // 内层 message 对象结束  }   // 返回对象结束}   // mergeUserMessages 结束// In the content[] list on a UserMessage, tool_result blocks must come first to avoid "tool result must follow tool use" API errors.   // user 消息的 content[] 里 tool_result 必须排最前,否则 API 报"工具结果必须紧跟工具调用"function hoistToolResults(content: ContentBlockParam[]): ContentBlockParam[] {   // 把所有 tool_result 提到数组头部  const toolResults: ContentBlockParam[] = []   // tool_result 桶  const otherBlocks: ContentBlockParam[] = []    // 其他块(text / image...)桶  for (const block of content) {   // 遍历所有块,按类型分桶    if (block.type === 'tool_result') { toolResults.push(block) }  // 分进前桶    else { otherBlocks.push(block) }                                // 其余进后桶  }   // hoistToolResults 结束  return [...toolResults, ...otherBlocks]   // 重组:tool_result 全部在前// Concatenate two content block arrays, appending \n to a's last text block when the seam is text-text. The API concatenates adjacent text blocks in a user message without a separator, so two queued prompts "2 + 2" + "3 + 3" would otherwise reach the model as "2 + 23 + 3".   // 接缝是 text-text 时给 a 的末块补 \n——API 拼接相邻文本块不带分隔符,不补的话两条排队提示会粘成一句

为什么这样设计:joinTextAtSeam 的注释里藏着一个真实 bug:用户在模型思考时连敲两条 "2 + 2" 和 "3 + 3",合并后 API 会把相邻 text 块无分隔符拼接——模型看到的是 "2 + 23 + 3"。补一个换行就解决了,但注意它把 \n 加在 a 的末块上而不是 b 的首块:这样任何块的 startsWith 都不变(下游 smooshSystemReminderSiblings 靠 startsWith 分类),是个很讲究的位置选择。

而 UUID 的选择逻辑(a.isMeta ? b.uuid : a.uuid)呼应了第二节的 [id:] 引用系统:真实用户消息的 ID 必须跨调用稳定,模型才能用 snip 工具引用"你刚才那条";meta 注入的消息每次都是新的,无所谓。

📄 src/utils/messages.ts (第 2600-2647 行)

export function mergeUserContentBlocks(a: ContentBlockParam[], b: ContentBlockParam[]): ContentBlockParam[] {   // 合并两条相邻 user 的 content 数组(API 管线调用)  // See https://anthropic.slack.com/archives/C06FE2FP0Q2/p1747586370117479 and ... :   // Slack 讨论记录(内部链接)  // any sibling after tool_result renders as </function_results>\n\nHuman:<...> on the wire. Repeated mid-conversation, this teaches capy to emit Human: at a bare tail → 3-token empty end_turn. A/B (sai-20260310-161901) validated: smoosh into tool_result.content → 92% → 0%.   // tool_result 后面的兄弟块在线上会渲染成 "Human:<...>";会话中反复出现,教会模型在裸结尾处输出 Human: → 3 token 的空 end_turn。A/B 实验验证:塞进 tool_result.content 后 92% → 0%  const lastBlock = last(a)   // 看 a 的最后一个块  if (lastBlock?.type !== 'tool_result') { return [...a, ...b] }      // 不以 tool_result 结尾:普通拼接即可  if (!checkStatsigFeatureGate_CACHED_MAY_BE_STALE('tengu_chair_sermon')) {   // 特性门控分支:通用 smoosh 关闭时走旧行为    // Legacy (ungated) smoosh: only string-content tool_result + all-text siblings → joined string. Matches pre-universal-smoosh behavior on main.   // 旧版(无门控)smoosh:仅当 tool_result 是字符串内容且兄弟块全是 text 时,拼成字符串    if (typeof lastBlock.content === 'string' && b.every(x => x.type === 'text')) {   // 旧版条件:tool_result 是字符串且兄弟块全是 text      const copy = a.slice()   // 浅拷贝——绝不原地修改原消息(transcript 还要用它)      copy[copy.length - 1] = smooshIntoToolResult(lastBlock, b)!  // 末块替换为合并后的 tool_result      return copy   // 返回合并结果(新数组,绝不原地修改)    }   // 旧版分支结束    return [...a, ...b]        // 不满足旧版条件:退回普通拼接  }   // 门控检查结束  // Universal smoosh (gated): fold all non-tool_result block types (text, image, document, search_result) into tool_result.content. tool_result blocks stay as siblings (hoisted later by hoistToolResults).   // 通用 smoosh(门控):把所有非 tool_result 块塞进 tool_result.content;tool_result 保持兄弟地位  const toSmoosh = b.filter(x => x.type !== 'tool_result')   // 可合并的块  const toolResults = b.filter(x => x.type === 'tool_result') // tool_result 必须独立(稍后由 hoistToolResults 提头)  if (toSmoosh.length === 0) { return [...a, ...b] }          // 没有可合并的:普通拼接  const smooshed = smooshIntoToolResult(lastBlock, toSmoosh)  // 尝试合并  if (smooshed === null) { return [...a, ...b] }              // tool_reference 约束——退回兄弟块(见下)  return [...a.slice(0, -1), smooshed, ...toolResults]        // 重组:a 去掉末块 + 合并结果 + 独立 tool_results}   // mergeUserContentBlocks 结束

为什么这样设计:这是全文件最"有故事"的一段。注释里的 A/B 实验编号 sai-20260310-161901 和结论 92% → 0% 是硬证据:tool_result 后面挂一个 text 兄弟块,线上 wire format 会渲染成 </function_results>\n\nHuman:<...>——模型在会话中反复看到这种模式后,学会了在没有 Human: 前缀的裸结尾处也输出 "Human:",产生 3 token 的空 end_turn(浪费 + 行为异常)。把兄弟块"smoosh"进 tool_result.content 内部,这个模式就消失了。一个渲染细节引发的模型行为退化,靠一次 A/B 实验定位并修复——这就是为什么注释里连 Slack 链接都留着。

smooshIntoToolResult(第 2534-2598 行)还有两个约束值得注意:is_error 的 tool_result 只能装 text 块(API 硬限制,所以排队命令里粘贴的截图会被过滤掉、作为独立 user turn 发送——注释说"图片不会丢");以及 tool_reference 不能和其他类型混在 content 里(服务端直接 ValueError),遇到就返回 null 退回兄弟块。两个"看似小优化"的操作,背后都是 API 的暗礁。

七、normalizeContentFromAPI:修复模型的"字符串化 JSON"

流式结束后,assistant 消息里的 tool_use.input 可能还是字符串——而且不是普通字符串:开启细粒度流式后,API 会返回"嵌套的字符串化 JSON"(JSON 里套着被转义的 JSON)。第 2651-2751 行的 normalizeContentFromAPI 负责把它修回对象:

📄 src/utils/messages.ts (第 2651-2751 行,节选)

export function normalizeContentFromAPI(contentBlocks: BetaMessage['content'], tools: Tools, agentId?: AgentId): BetaMessage['content'] {   // 发送前修复 assistant 消息的内容块  if (!contentBlocks) { return [] }   // content 为空 → 返回空数组(不把 undefined 发给 API)  return contentBlocks.map(contentBlock => {   // 逐块遍历,按类型修复    switch (contentBlock.type) {   // 按块类型分派      case 'tool_use': {   // tool_use:input 可能是字符串化 JSON        if (typeof contentBlock.input !== 'string' && !isObject(contentBlock.input)) {   // 两种合法形态都不是 → fail loud,不静默放行          throw new Error('Tool use input must be a string or object')  // fail loud:两种合法形态都不是 → 直接抛错,不静默放行        }   // 类型守卫分支结束        // With fine-grained streaming on, we are getting a stringified JSON back from the API. The API has strange behaviour, where it returns nested stringified JSONs, and so we need to recursively parse these. If the top-level value returned from the API is an empty string, this should become an empty object (nested values should be empty strings).   // 细粒度流式下 API 返回字符串化 JSON,甚至有嵌套的——需要递归解析;顶层空串应变成空对象        let normalizedInput: unknown   // 修复后的输入值(先放宽为 unknown)        if (typeof contentBlock.input === 'string') {   // 字符串形态:需要解析 JSON          const parsed = safeParseJSON(contentBlock.input)   // 安全 JSON 解析:失败返回 null 而不是抛异常          if (parsed === null && contentBlock.input.length > 0) {   // 解析失败且非空串 → 值得埋点            logEvent('tengu_tool_input_json_parse_fail', { toolName: sanitizeToolNameForAnalytics(contentBlock.name), inputLen: contentBlock.input.length })  // 埋点:模型吐了不可解析的 JSON——按工具名 + 长度统计(不发原始内容,避免 PII)          }   // 埋点分支结束          normalizedInput = parsed ?? {}   // 解析失败 → 兜底空对象;下游校验看到的是"空输入"而不是崩溃        } else {   // 对象形态:直接使用          normalizedInput = contentBlock.input  // 本来就是对象:直接用        }   // input 归一化结束        if (typeof normalizedInput === 'object' && normalizedInput !== null) {   // 是对象才做工具专属修正          const tool = findToolByName(tools, contentBlock.name)   // 按名字找到对应工具          if (tool) {   // 找到了对应工具定义            try {   // 尝试修正(可能抛错)              normalizedInput = normalizeToolInput(tool, normalizedInput as { [key: string]: unknown }, agentId)  // 应用工具专属修正(字段改名 / 类型纠正等)            } catch (error) {   // 修正失败:保留原始输入,不让一条坏消息毁掉整个会话              logError(new Error('Error normalizing tool input: ' + error))  // 修正失败 → 保留原始输入(fail soft,不让一条坏消息毁掉整个会话)            }   // 异常处理结束          }   // 工具查找结束        }   // input 修复结束        return { ...contentBlock, input: normalizedInput }   // 返回修复后的块      }   // tool_use 分支结束      case 'text':   // text 块:一个字都不改(prompt caching 对前缀字节敏感)        if (contentBlock.text.trim().length === 0) { logEvent('tengu_model_whitespace_response', { length: contentBlock.text.length }) }  // 纯空白响应埋点(模型偶尔只回 "\n\n")        return contentBlock   // 原样返回以保留精确内容供 prompt caching;空文本块由展示层处理,这里绝不能改      case 'server_tool_use':   // 服务端工具调用:同样的字符串化 JSON 问题        if (typeof contentBlock.input === 'string') {   // 是字符串也解析一下          return { ...contentBlock, input: (safeParseJSON(contentBlock.input) ?? {}) as { [key: string]: unknown } }  // 服务端工具调用有同样的"字符串化 JSON"问题 → 解析或兜底 {}        }   // 服务端工具修复分支结束        return contentBlock   // 原样通过      default:   // 其他块类型(thinking 等)        return contentBlock   // thinking / redacted_thinking 等:原样通过    }   // switch 结束  })   // map 回调结束}   // normalizeContentFromAPI 结束

为什么这样设计:这段代码的哲学是"fail soft + 可观测":模型输出不可信(JSON 可能截断、嵌套转义),所以解析失败不抛错而是兜底 {},同时埋点记录"哪个工具、多长输入"——注意它只记长度不记内容,注释明说"no PII-tagged proto column exists for it yet"。而 text 块的处理是反方向的:一个字都不改(哪怕全是空白),因为 prompt caching 对前缀字节敏感,改了缓存就失效;空文本的展示问题交给 UI 层。一个函数里同时体现"对模型宽容、对协议严格"。

八、ensureToolResultPairing:救活死锁会话的修复器

API 最硬的约束:每个 tool_use 必须有配对的 tool_result,且 ID 全局唯一、角色严格交替。但现实里会话会坏——流被中断(tool_use 没等到结果)、resume 时 transcript 从半截开始(tool_result 的 assistant 配对已被压缩掉)、孤儿处理器重复运行产生重复块……第 5133-5460 行的 ensureToolResultPairing 是最后一道防线,注释里带着两个真实事故编号:

📄 src/utils/messages.ts (第 5133-5400 行,节选)

export function ensureToolResultPairing(messages: (UserMessage | AssistantMessage)[]): (UserMessage | AssistantMessage)[] {   // tool_use/tool_result 配对修复的最后一道防线  const result: (UserMessage | AssistantMessage)[] = []   // 输出数组  let repaired = false   // 是否发生过修复(结尾埋点用)  // Cross-message tool_use ID tracking. ... When two assistants with DIFFERENT message.id carry the same tool_use ID — e.g. orphan handler re-pushed an assistant already present in mutableMessages with a fresh message.id, or normalizeMessagesForAPI's backward walk broke on an intervening user message — the dup lived in separate result entries and the API rejected with "tool_use ids must be unique", deadlocking the session (CC-1212).   // 跨消息 tool_use ID 跟踪:两条不同 message.id 的 assistant 携带同一 tool_use ID(孤儿处理器重推 / 回溯被 user 消息打断)→ API 报"ID 必须唯一",会话死锁(事故 CC-1212)  const allSeenToolUseIds = new Set<string>()   // 全局 tool_use ID 集合:跨消息去重  for (let i = 0; i < messages.length; i++) {   // 逐条遍历消息,边检查边修复    const msg = messages[i]!   // 当前消息(非空断言)    if (msg.type !== 'assistant') {   // user / 其他类型:先查孤儿 tool_result      // A user message with tool_result blocks but NO preceding assistant message in the output has orphaned tool_results. ... This happens on resume when the transcript starts mid-turn (e.g. messages[0] is a tool_result whose assistant pair was dropped by earlier compaction — API rejects with "messages.0.content: unexpected tool_use_id").   // 输出里没有前置 assistant 的 user 消息 = 孤儿 tool_result。resume 时 transcript 从半截开始(配对被压缩掉)就会发生——API 报"unexpected tool_use_id"      if (msg.type === 'user' && Array.isArray(msg.message.content) && result.at(-1)?.type !== 'assistant') {   // resume 半截 transcript:配对的 assistant 已被压缩掉        const stripped = msg.message.content.filter(block => !(typeof block === 'object' && 'type' in block && block.type === 'tool_result'))  // 剥掉所有孤儿 tool_result        if (stripped.length !== msg.message.content.length) {   // 确实剥掉了东西 → 标记已修复          repaired = true   // 标记已修复          const content = stripped.length > 0 ? stripped : result.length === 0 ? [{ type: 'text' as const, text: '[Orphaned tool result removed due to conversation resume]' }] : null  // 剥空且位于数组头部 → 保留占位(payload 必须以 user 消息开头)          if (content !== null) { result.push({ ...msg, message: { ...msg.message, content } }) }   // 把剥离后的消息放回输出          continue   // 跳过原 push 逻辑        }   // 孤儿 tool_result 处理结束      }   // 非 assistant 分支检查结束      result.push(msg)   // 普通 user 消息:原样通过      continue   // 跳过本条,进入下一轮    }   // if-not-assistant 块结束    const serverResultIds = new Set<string>()   // 收集服务端工具结果 ID(*_tool_result 块带 tool_use_id)    for (const c of msg.message.content) {   // 收集服务端工具结果 ID(web_search 等)      if ('tool_use_id' in c && typeof c.tool_use_id === 'string') { serverResultIds.add(c.tool_use_id) }  // web_search 等服务端结果也按 ID 配对    }   // ID 收集结束    const seenToolUseIds = new Set<string>()   // 本条 assistant 的 tool_use ID 集合(孤儿/缺失检测用"单消息视角")    const finalContent = msg.message.content.filter(block => {   // 逐块过滤:剥掉重复与孤儿服务端调用      if (block.type === 'tool_use') {   // tool_use 块:先查跨消息重复        if (allSeenToolUseIds.has(block.id)) { repaired = true; return false }  // 跨消息重复 → 剥掉(CC-1212)        allSeenToolUseIds.add(block.id)   // 登记到全局集合        seenToolUseIds.add(block.id)      // 同时登记到本条集合      }   // tool_use 去重分支结束      if ((block.type === 'server_tool_use' || block.type === 'mcp_tool_use') && !serverResultIds.has((block as { id: string }).id)) {   // 服务端 / MCP 工具调用:检查其结果是否到达        repaired = true; return false   // 孤儿服务端工具调用(流在结果到达前中断)→ 剥掉,否则 API 报"advisor tool use without corresponding advisor_tool_result"      }   // 孤儿服务端调用分支结束      return true   // 其他块通过    })   // filter 回调结束    if (finalContent.length === 0) {   // 全被剥空 → 必须留占位      finalContent.push({ type: 'text' as const, text: '[Tool use interrupted]', citations: [] })  // 剥空了 → 塞占位,防止 API 拒绝空的 assistant content    }   // 空内容保护结束    result.push(finalContent.length !== msg.message.content.length ? { ...msg, message: { ...msg.message, content: finalContent } } : msg)   // push 修复后的消息(没变化则用原对象)    const toolUseIds = [...seenToolUseIds]   // 本条 assistant 幸存的 tool_use ID    const nextMsg = messages[i + 1]   // 看下一条(正常应是 user)    const existingToolResultIds = new Set<string>()   // 已有 tool_result ID 集合(缺失/重复检测用)    let hasDuplicateToolResults = false   // 重复结果标记    if (nextMsg?.type === 'user' && Array.isArray(nextMsg.message.content)) {   // 下一条是带块内容的 user:扫描其 tool_results      for (const block of nextMsg.message.content) {   // 遍历下一条的每个块        if (typeof block === 'object' && 'type' in block && block.type === 'tool_result') {   // 找到 tool_result 块          const trId = (block as ToolResultBlockParam).tool_use_id   // 提取 tool_result 引用的 ID          if (existingToolResultIds.has(trId)) { hasDuplicateToolResults = true }  // 同一 ID 出现两次 → 标记重复(孤儿处理器跑多遍的产物)          existingToolResultIds.add(trId)   // 登记该 ID(重复在上面已标记)        }   // tool_result 扫描结束      }   // 块循环结束    }   // 下一条检查结束    const toolUseIdSet = new Set(toolUseIds)   // 集合化,O(1) 查询    const missingIds = toolUseIds.filter(id => !existingToolResultIds.has(id))   // 正向:有 tool_use 没 tool_result(流中断 / 用户打断)    const orphanedIds = [...existingToolResultIds].filter(id => !toolUseIdSet.has(id))  // 反向:有 tool_result 没 tool_use    if (missingIds.length === 0 && orphanedIds.length === 0 && !hasDuplicateToolResults) { continue }   // 配对完整:无需修复    repaired = true   // 触发修复    const syntheticBlocks: ToolResultBlockParam[] = missingIds.map(id => ({ type: 'tool_result' as const, tool_use_id: id, content: SYNTHETIC_TOOL_RESULT_PLACEHOLDER, is_error: true }))  // 为缺失 ID 合成错误 tool_result(占位文案 + is_error 标记——模型会看到"出错了"而不是假数据)    if (nextMsg?.type === 'user') {   // 下一条是 user:就地修复而不是插新消息      let content = Array.isArray(nextMsg.message.content) ? nextMsg.message.content : [{ type: 'text' as const, text: nextMsg.message.content }]  // 归一化成数组形式      if (orphanedIds.length > 0 || hasDuplicateToolResults) {   // 需要从下一条里剥掉孤儿/重复结果        const orphanedSet = new Set(orphanedIds)   // 孤儿 ID 集合,O(1) 查询        const seenTrIds = new Set<string>()        // 去重集合        content = content.filter(block => {   // 重建 content 数组,剔除坏块          if (typeof block === 'object' && 'type' in block && block.type === 'tool_result') {   // 只处理 tool_result 块            const trId = (block as ToolResultBlockParam).tool_use_id   // 提取它引用的 ID            if (orphanedSet.has(trId)) return false   // 孤儿 → 剥掉            if (seenTrIds.has(trId)) return false      // 重复 → 只留第一个            seenTrIds.add(trId)   // 标记为已保留(首个胜出)          }   // 非 tool_result 块原样通过          return true   // filter 回调结束        })   // 剥离分支结束      }   // 还有内容:并入下一条消息      const patchedContent = [...syntheticBlocks, ...content]  // 合成的错误结果放最前(满足"tool_result 紧跟 tool_use"的顺序约束)      if (patchedContent.length > 0) {   // 全剥空了:也要留一条 user 维持角色交替        i++   // 消费掉 nextMsg(已并入本次修复结果)        result.push(checkStatsigFeatureGate_CACHED_MAY_BE_STALE('tengu_chair_sermon') ? smooshSystemReminderSiblings([patchedNext])[0]! : patchedNext)  // 合并后重新 smoosh——pairing 跑在 normalize 之后,可能产生新的 [tool_result, text] 兄弟      } else {   // 就地修复分支结束        i++   // 消费掉 nextMsg        result.push(createUserMessage({ content: NO_CONTENT_MESSAGE, isMeta: true }))  // 剥空了也要留一条 user 消息维持角色交替——否则两条 assistant 相邻,API 报 role-alternation 400(和重复 ID 的 400 是两种错)      }   // 后面没有 user 消息:合成新的承载错误结果    } else {   // 合成消息分支结束      if (syntheticBlocks.length > 0) { result.push(createUserMessage({ content: syntheticBlocks, isMeta: true })) }  // 后面没有 user 消息 → 合成一条承载错误结果    }   // 本轮配对检查结束  }   // 主循环结束(修复逻辑完成)

为什么这样设计:这段代码的注释是"事故考古现场"。三层修复对应三类真实故障:① 跨消息重复 ID(CC-1212,孤儿处理器重推导致同一 tool_use 出现在两条 assistant 里——单消息内去重抓不到,必须全局 Set);② resume 半截 transcript(messages[0] 就是 tool_result,配对已被压缩掉——注意它连"剥空后要不要留占位"都分情况:数组头部必须留,否则 payload 以 assistant 开头是另一种 400);③ 重复 tool_result(孤儿处理器跑多遍产生 [asst(X), user(tr_X)]×2)。每一层修复的注释里都写着 API 会报什么错——这不是防御性编程,是被生产事故逼出来的精确手术。

还有一个设计取舍:合成的 tool_result 用 is_error: true + 占位文案,而不是伪造一个"成功结果"。模型看到错误会如实上报或换路,看到假成功则会基于不存在的事实继续推理——前者可恢复,后者是幻觉链。

📄 src/utils/messages.ts (第 5402-5459 行)

  if (repaired) {    const messageTypes = messages.map((m, idx) => { /* ...逐条生成诊断串:assistant(id=..., tool_uses=[...]) / user(tool_results=[...])... */ })   // 构建"消息结构快照",用于定位根因    if (getStrictToolResultPairing()) {      throw new Error(`ensureToolResultPairing: tool_use/tool_result pairing mismatch detected (strict mode). Refusing to repair — would inject synthetic placeholders into model context. Message structure: ${messageTypes.join('; ')}. See inc-4977.`)  // 严格模式拒绝修复直接抛错:注入合成占位会污染模型上下文(事故 inc-4977)    }    logEvent('tengu_tool_result_pairing_repaired', { messageCount: messages.length, repairedMessageCount: result.length, messageTypes: messageTypes.join('; ') })   // 埋点:修了多少条 + 结构快照(离线分析根因用)    logError(new Error(`ensureToolResultPairing: repaired missing tool_result blocks (${messages.length} -> ${result.length} messages). Message structure: ${messageTypes.join('; ')}`))  // 同时写错误日志  }  return result   // 返回修复后的消息序列

为什么这样设计:结尾的严格模式是点睛之笔:同一个函数,普通模式下"尽力修复保会话",严格模式下(getStrictToolResultPairing())直接抛错——因为合成占位符会进入模型上下文,在某些场景(如训练数据回流)这是不可接受的污染。注释里的 inc-4977 说明这个模式也是事故驱动的:先有"修了但引入新问题"的案例,才加了"宁死不修"的开关。修复本身也要可被禁止——这是成熟系统的标志。

九、normalizeMessagesForAPI:发送前的完整管线

前面各节是零件,第 1989 行起的 normalizeMessagesForAPI 把它们串成流水线。最精彩的是开头的"错误驱动修复表"——记住上次 API 报了什么错,这次主动把肇事内容删掉:

📄 src/utils/messages.ts (第 1989-2093 行,节选)

export function normalizeMessagesForAPI(messages: Message[], tools: Tools = []): (UserMessage | AssistantMessage)[] {   // 发送前完整管线:重排 → 切除 → 转换 → 修复 → 配对  const availableToolNames = new Set(tools.map(t => t.name))   // 可用工具名集合:用于过滤"已不存在"的工具引用(如 MCP server 断连)  // First, reorder attachments to bubble up until they hit a tool result or assistant message. Then strip virtual messages — they're display-only (e.g. REPL inner tool calls) and must never reach the API.   // 先重排 attachment(上移直到撞上 tool_result / assistant),再剥掉虚拟消息——它们只给 UI 看  const reorderedMessages = reorderAttachmentsForAPI(messages).filter(m => !((m.type === 'user' || m.type === 'assistant') && m.isVirtual))   // 重排 + 过滤一步完成  // Build a map from error text → which block types to strip from the preceding user message.   // 错误文案 → 该从哪类块下手,建一张映射表  const errorToBlockTypes: Record<string, Set<string>> = {   // "错误文案 → 该剥哪类块"映射表    [getPdfTooLargeErrorMessage()]: new Set(['document']),      // PDF 太大 → 删 document 块    [getPdfPasswordProtectedErrorMessage()]: new Set(['document']),  // 加密 PDF → 同样处理    [getPdfInvalidErrorMessage()]: new Set(['document']),        // 损坏的 PDF → 同样处理    [getImageTooLargeErrorMessage()]: new Set(['image']),        // 图片太大 → 删 image 块    [getRequestTooLargeErrorMessage()]: new Set(['document', 'image']),  // 请求体超限 → 两类重内容都删  }   // 映射表定义结束  const stripTargets = new Map<string, Set<string>>()   // 定向删除表:userMessageUUID → 要剥掉的块类型集合  for (let i = 0; i < reorderedMessages.length; i++) {   // 遍历消息,构建定向删除表    const msg = reorderedMessages[i]!   // 当前消息    if (!isSyntheticApiErrorMessage(msg)) { continue }   // 只处理合成 API 错误消息(第 321-329 行的识别器)    const errorText = Array.isArray(msg.message.content) && msg.message.content[0]?.type === 'text' ? msg.message.content[0].text : undefined  // 取第一个 text 块当错误文案    if (!errorText) { continue }   // 没有文本内容:无法匹配错误,跳过    const blockTypesToStrip = errorToBlockTypes[errorText]   // 查这张错误对应哪类块    if (!blockTypesToStrip) { continue }                      // 不认识的错误:不动    for (let j = i - 1; j >= 0; j--) {                        // 向前回溯找最近的 isMeta user 消息(肇事者)      const candidate = reorderedMessages[j]!   // 候选"肇事者"消息(向前回溯)      if (candidate.type === 'user' && candidate.isMeta) {    // 找到了:登记进删除表        const existing = stripTargets.get(candidate.uuid)   // 查这个肇事者是否已有删除条目        if (existing) { for (const t of blockTypesToStrip) { existing.add(t) } }  // 已有条目 → 合并类型集合        else { stripTargets.set(candidate.uuid, new Set(blockTypesToStrip)) }     // 新建条目        break   // 找到了,停止回溯      }   // 肇事者登记结束      if (isSyntheticApiErrorMessage(candidate)) { continue } // 跳过其他合成错误消息(连续报错的情况)      break   // 撞到 assistant 或非 meta user 就停——不跨 turn 边界乱删    }   // 回溯循环结束  }   // 删除表构建结束  const result: (UserMessage | AssistantMessage)[] = []   // 最终 API payload  reorderedMessages.filter((_,): _ is UserMessage | AssistantMessage | AttachmentMessage | SystemLocalCommandMessage => {   // 类型守卫 + 过滤一步完成    if (_.type === 'progress' || (_.type === 'system' && !isSystemLocalCommandMessage(_)) || isSyntheticApiErrorMessage(_)) { return false }   // 过滤:progress / 非 local_command 的 system / 合成 API 错误——都不进模型    return true   // 其余全部通过  }).forEach(message => {   // 逐条按类型转换    switch (message.type) {   // 按消息类型分派      case 'system': {   // local command 输出:必须转成 user 消息        // local_command system messages need to be included as user messages so the model can reference previous command output in later turns   // local_command 要转成 user 消息,模型才能在后续 turn 引用之前的命令输出        const userMsg = createUserMessage({ content: message.content, uuid: message.uuid, timestamp: message.timestamp })  // 转换(保留原 UUID)        const lastMessage = last(result)   // 看已 push 的最后一条        if (lastMessage?.type === 'user') { result[result.length - 1] = mergeUserMessages(lastMessage, userMsg); return }  // 上一条也是 user → 合并(Bedrock 不支持连续 user)        result.push(userMsg)   // 否则直接 push        return   // 本条处理完毕,退出      }   // system 分支结束      case 'user': { /* ...剥 tool_reference、执行 stripTargets 删除表、"Tool loaded." turn boundary 注入、相邻合并——见第 2094-2198 行... */ }      case 'assistant': { /* ...normalizeContentFromAPI 修 input、剥 caller 字段等——见第 2201 行起... */ }    }   // 类型分派结束(user / assistant 分支见省略段)  })   // forEach 回调结束(管线完成)

为什么这样设计:errorToBlockTypes + stripTargets 是全文件最"聪明"的机制:PDF 太大导致 API 400 后,错误消息留在会话流里;下一次发请求时,管线回溯找到那条 isMeta user 消息(肇事者),把它的 document 块删掉——否则同一个坏 PDF 会在之后每次 API 调用里反复触发 400。这是"从错误中学习"的客户端实现:不重试、不降级模型,而是精确切除病灶。回溯时"撞到 assistant 就停"的边界控制也很关键——不能跨 turn 乱删用户真实内容。

user 分支里还有一段第 2139-2158 行的注释值得单独拎出来:tool_reference 展开在 prompt 尾部时,capybara 模型有 ~10% 概率采样到 stop sequence(A/B:21/200 vs 0/200),解法是注入一个 "Tool loaded." 兄弟块制造干净的 turn boundary——又是"wire format 细节 → 模型行为退化 → A/B 验证修复"的三段式。这个文件里藏着至少三次这样的实验记录,是研究 Anthropic 内部 prompt 工程的一手材料。

管线阶段
函数(行号)
修复 / 转换行为
① 重排 + 过滤
reorderAttachmentsForAPI (1481)
attachment 上移;isVirtual / progress / 合成错误被剔除
② 定向切除
stripTargets (2004-2054)
按上次 API 错误文案,删肇事 meta 消息里的 document/image 块
③ 角色转换
system→user (2078-2093)
local_command 输出转 user 消息,相邻则合并
④ 内容修复
normalizeContentFromAPI (2651)
字符串化 JSON → 对象;解析失败兜底 {} + 埋点
⑤ 配对修复
ensureToolResultPairing (5133)
去重 / 剥孤儿 / 合成错误 tool_result;严格模式直接抛错

为什么这样设计:五个阶段顺序不能乱:先过滤(减少后续工作量)→ 再切除(基于历史错误)→ 转角色(满足交替约束)→ 修内容(块级修复)→ 最后配对(消息级结构修复)。越靠后越"重"——配对修复会增删整条消息,必须放在所有块级操作之后。这条管线就是 Claude Code 会话流的"出口海关"。

十、全景:一条消息的一生

写路径(流式 → 定稿)

① 请求发出:stream_request_start → requesting 模式

spinner 切到"等首 token";message_start 事件携带 TTFT 指标。

▼

② 增量累积:content_block_start / delta

🔹 text_delta → streamingText 缓冲 + token 计数🔹 input_json_delta → unparsedToolInput 字符串累积(不解析)🔹 signature_delta → 显式排除,不计入指标

▼

③ 定稿:assistant 消息到达

先清 streamingText 再 push——同批次原子切换,无闪烁无重复。

▼

④ UI 拆分:normalizeMessages

一条多块消息拆成多条;isNewChain 触发确定性 UUID 派生。

读路径(API 发送管线)

① 重排 + 过滤:reorderAttachmentsForAPI

attachment 上移;isVirtual / progress / 合成错误剔除。

▼

② 定向切除:stripTargets

按上次 API 错误文案,回溯删掉肇事 meta 消息的 document/image 块。

▼

③ 合并 + smoosh:mergeUserMessages

🔹 相邻 user 合并(Bedrock 约束)+ 接缝补 \n🔹 tool_result 提头 + 兄弟块塞进 content(A/B:92% → 0%)

▼

④ 内容修复:normalizeContentFromAPI

字符串化 JSON → 对象;失败兜底 {} + tengu_tool_input_json_parse_fail 埋点。

▼

⑤ 配对修复:ensureToolResultPairing

🔹 普通模式:去重 / 剥孤儿 / 合成 is_error tool_result🔹 严格模式(inc-4977):拒绝修复,直接抛错

5512 行代码,本质上是两套视图之间的翻译器:UI 要"每块一条、可折叠、带进度"的细粒度消息流;API 要"角色交替、配对完整、无重复 ID"的粗粒度 payload。中间所有摩擦——Bedrock 的连续 user 限制、wire format 教会模型的坏习惯、模型吐出的坏 JSON、中断留下的孤儿块——都在这一个文件里被消化掉了。

这也是为什么第 11 讲(会话持久化与 resume/fork)会格外精彩:transcript 落盘的就是这套消息结构,而 resume 时"半截 transcript"正是 ensureToolResultPairing 注释里反复出现的那个场景。下一讲我们看 sessionStorage.ts(5105 行)怎么把这条流存下来、再原样接回去。

📚 系列导航

← 第 9 讲:认证 / OAuth / 额度护栏

→ 第 11 讲:会话持久化与 resume/fork

关注公众号「AI技术推荐官」获取更多源码解析内容

📌 每天 30 条,挑出真能用的 AI 东西

UnitAI 每天从 GitHub / Hacker News / Hugging Face 抓一遍 AI 热榜,还收录了 50+ 个上过榜的项目,能按分类、星级、上榜天数筛。免费看,不用注册。

长按识别二维码打开 · 或点左下角「阅读原文」

回首页,搜索你想要的文档

在首页搜索框输入关键词,快速定位资料

文库首页搜索指引 立即搜索

相关学习资料