message flow

本章介绍 Claude Code 中消息的构建、发送和处理机制。

消息类型

Anthropic API 消息格式

type Message = {
  role: 'user' | 'assistant';
  content: string | ContentBlock[];
};

type ContentBlock =
  | { type: 'text'; text: string }
  | { type: 'tool_use'; id: string; name: string; input: any }
  | { type: 'tool_result'; tool_use_id: string; content: string };

内部消息格式

interface InternalMessage {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: number;
  metadata?: {
    tokenCount?: number;
    compressed?: boolean;
    toolCalls?: ToolCall[];
  };
}

消息构建流程

1

用户输入处理

2

System Prompt 构建

3

工具结果处理

消息压缩

Tool Result Budget

限制单个工具结果的大小:

Microcompact

压缩工具调用历史:

Context Collapse

折叠旧对话轮次:

消息路由

本地执行

Bridge 模式

下一步