mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-15 21:05:51 +00:00
* docs: 修复文档巡检发现的 4 处错误 - daemon.md: 反映实际实现状态(supervisor/worker 已实现而非 stub) - bridge-mode.md: API 操作数量从 7 修正为 9 - web-search-tool.md: 文件路径从 src/tools/ 修正为 packages/builtin-tools/src/tools/ - remote-control-self-hosting.md: 补充缺失的 RCS_WS_IDLE_TIMEOUT 和 RCS_WS_KEEPALIVE_INTERVAL 配置项 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 Safety 和 Context 文档中的代码引用和类型错误 - permission-model: 修正规则来源从"五层"到八层,优先级顺序对齐代码 - permission-model: PermissionUpdate 类型改为实际的 addRules/replaceRules 等 - permission-model: 补充 acceptEdits 和 dontAsk 两种权限模式 - permission-model: DENIAL_LIMITS 字段名对齐实际代码 - plan-mode: 工具路径从 src/tools/ 改为 packages/builtin-tools/src/tools/ - compaction: 修正 COMPACTABLE_TOOLS 和 POST_COMPACT_* 的行号 - project-memory: 修正 ENTRYPOINT_NAME 常量的行号 - system-prompt: 修正 SystemPrompt 类型定义文件路径和多个行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复 introduction 文档中的错误路径和行号引用 - why-this-whitepaper.mdx: BashTool 路径从 src/tools/ 修正为 packages/builtin-tools/src/tools/ - what-is-claude-code.mdx: 移除不存在的 Azure provider,改为实际的 7 种 provider - architecture-overview.mdx: State 类型行号从 204 修正为 207 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复 conversation/features 文档中的错误 - streaming.mdx: queryStreamRaw → queryModelWithStreaming 函数名修正 - streaming.mdx: Azure 提供商不存在,替换为实际 7 个提供商 - debug-mode.mdx: --inspect-wait 描述错误,实际使用 BUN_INSPECT 环境变量 - buddy.mdx: 补充缺失的 companionReact.ts、CompanionCard.tsx、index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复文档巡检中的源码引用错误 - feature-flags.mdx: 修正 feature() 兜底描述,实际从 bun:bundle 导入而非 cli.tsx:3 内联 - feature-flags.mdx: 修正工具 require 路径为 @claude-code-best/builtin-tools 包路径 - ant-only-world.mdx: 修正 tools.ts 中 require 路径为包路径 - ant-only-world.mdx: 修正 INTERNAL_ONLY_COMMANDS 行号 (267-295) 和数量 (24+) - skills.mdx: 修正 COMMANDS memoize 行号 258 → 299 - mcp-protocol.mdx: 修正 fetchToolsForClient LRU 缓存上限 20 → 100 - streaming.mdx: 修正流式事件引用 - file-operations.mdx: 修正工具路径引用 - search-and-navigation.mdx: 修正搜索工具引用 - shell-execution.mdx: 修正 shell 工具引用 - buddy.mdx: 补充缺失的 frontmatter 字段 - debug-mode.mdx: 修正调试模式描述 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 tools/agent 文档中的文件路径和行号引用 - 修正 TodoWriteTool、AgentTool、ToolSearchTool 等工具路径 src/tools/ → packages/builtin-tools/src/tools/ - 更新 Tool.ts、tools.ts、BashTool.tsx 中过时的行号引用 - 修正 WebSearchTool/WebFetchTool/EnterWorktreeTool/ExitWorktreeTool 路径 - 修正 AgentTool.tsx 中多行行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature 文档中的文件路径和行号引用 - ultraplan.md: 更新文件行数(525/349/127) - fork-subagent.md: 路径迁移 src/tools/ → packages/builtin-tools/ - mcp-skills.md: 修正 getMcpSkillCommands 行号 547→604,client.ts 行号 117→129 - kairos.md: 修正 getBriefSection/getProactiveSection 行号 - proactive.md: 修正 getProactiveSection 行号 860→864 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正顶层文档中的路径迁移和行号引用 - auto-updater.md: config.ts 行号 1735→1737,标注未接入启动流程的函数 - external-dependencies.md: WebSearchTool/WebFetchTool 路径迁移到 builtin-tools 包,Vertex 行号修正 - lsp-integration.md: LSPTool 路径从 src/tools/ 迁移到 packages/builtin-tools/ - stub-recovery-design-1-4.md: 修正 Windows 绝对路径链接为标准代码引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 task 文档中的文件扩展名和路径引用 - task-004: AssistantSessionChooser.ts → .tsx, assistant.ts → .tsx - task-003: cli.tsx 行号 249→272, markdownConfigLoader.ts 行号 29→35 - lan-pipes: SendMessageTool 路径迁移到 packages/builtin-tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 补充 computer-use-tools-reference 缺失的 Windows 工具 添加遗漏的 open_terminal 和 activate_window 两个 Windows 专属工具, 修正工具总数 37→39,Windows 工具数 10→12。 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 audit/bash-classifier/token-budget/tree-sitter 文档 - feature-flags-audit: ScheduleCronTool 路径迁移、DAEMON 状态更新为 COMPLETE、assistant 文件标记已补全、UDS 标记已实现 - bash-classifier: BashPermissionRequest 文件路径修正、withRetry 行号移除 - token-budget: attachments.ts 行号范围修正 - tree-sitter-bash: bashPermissions.ts 路径迁移到 packages/builtin-tools Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 langfuse-monitoring AgentTool 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 bridgeApi 行号和 Tool.ts 行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 Safety/Extensibility 文档中的工具路径迁移和行号引用 - sandbox.mdx: shouldUseSandbox.ts 和 bashPermissions.ts 路径迁移至 packages/builtin-tools - why-safety-matters.mdx: bashPermissions.ts 路径迁移(3 处) - plan-mode.mdx: EnterPlanModeTool/prompt.ts 路径迁移 - auto-mode.mdx: Auto mode 指令行号 3464→3481 - hooks.mdx: AgentTool/runAgent.ts 路径迁移 - skills.mdx: SkillTool.ts 路径迁移 - custom-agents.mdx: Agent built-in 目录和 exploreAgent.ts 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 internals 文档引用计数和路径 - ant-only-world: USER_TYPE 引用计数 465→410+,工具路径迁移到 builtin-tools - growthbook-ab-testing: growthbook.ts 行数 1156→1258 - hidden-features: 语音模式状态更新(audio-napi 已恢复) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正工具文档中的行号引用 - sub-agents: AgentTool.call 入口行号 340→387 - shell-execution: ShellCommand onTimeout 行号 129→144 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature 文档中的状态、路径和计数 - all-features-guide: 修正 feature flag 启用范围(dev only vs dev+build) - tier3-stubs: 大量状态修正(stub→已实现),缩减过时条目 - workflow-scripts: 路径迁移到 builtin-tools,状态更新 - web-browser-tool: 工具状态缺失→已实现,路径迁移 - context-collapse: CtxInspectTool 状态缺失→已实现 - computer-use: 行号引用更新,平台分发描述修正 - computer-use-tools-reference: 工具数 39→38 - voice-mode: voiceModeEnabled 行数 55→54 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 更新 the-loop 查询循环行号引用 query.ts 代码变更后终止原因行号整体偏移约 40 行 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 补充 feature-flags-audit 完整 build 默认 feature 列表 添加 ULTRATHINK/LODESTONE/ACP/DAEMON 等 19 个缺失的 build 默认 feature, 修正 dev-only 特征标注(UDS_INBOX/LAN_PIPES/BG_SESSIONS/TEMPLATES) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit ConfigTool 路径迁移 ConfigTool 路径从 src/tools/ 迁移到 packages/builtin-tools/src/tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit BashTool 路径迁移 BashTool 路径从 src/tools/ 迁移到 packages/builtin-tools/src/tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit SkillTool 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 更新 feature-flags-audit WorkflowTool 状态为已实现 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
193 lines
9.0 KiB
Plaintext
193 lines
9.0 KiB
Plaintext
---
|
||
title: "流式响应机制 - Claude Code 打字机效果原理"
|
||
description: "解析 Claude Code 流式响应实现:如何通过 SSE 逐 token 接收 AI 输出,实现实时打字机效果,提升用户等待体验。"
|
||
keywords: ["流式响应", "SSE", "streaming", "实时输出", "API streaming"]
|
||
sourceRef: "3ec5675 (2026-04-08)"
|
||
---
|
||
|
||
## 为什么需要流式
|
||
|
||
想象 AI 需要 30 秒才能生成完整回答——如果等 30 秒后才一次性显示,用户体验是灾难性的。
|
||
|
||
流式响应让用户**实时看到 AI 的思考过程**:
|
||
- 文字逐字出现,用户能提前判断方向是否正确
|
||
- 工具调用的参数在生成过程中就能预览
|
||
- 长时间任务不会让用户觉得"卡死了"
|
||
|
||
## `BetaRawMessageStreamEvent` 核心事件类型
|
||
|
||
流式 API 返回的是一系列 `BetaRawMessageStreamEvent`,每种事件类型对应流式响应的不同阶段(`src/services/api/claude.ts`):
|
||
|
||
```
|
||
message_start ← 消息开始,包含 model、usage 初始值
|
||
├── content_block_start ← 内容块开始(text / tool_use / thinking)
|
||
│ ├── content_block_delta ← 增量数据(text_delta / input_json_delta / thinking_delta)
|
||
│ ├── content_block_delta ← ... 持续到达
|
||
│ └── content_block_stop ← 内容块结束,yield AssistantMessage
|
||
├── content_block_start ← 下一个内容块...
|
||
│ └── ...
|
||
└── message_delta ← stop_reason + 最终 usage
|
||
message_stop ← 消息结束
|
||
```
|
||
|
||
### 事件处理状态机
|
||
|
||
`src/services/api/claude.ts` 中 `queryModelWithStreaming()` 函数的事件处理循环实现了一个基于 `switch(part.type)` 的状态机:
|
||
|
||
| 事件类型 | 处理逻辑 | 状态变更 |
|
||
|----------|----------|----------|
|
||
| `message_start` | 初始化 `partialMessage`,记录 TTFT(首字节延迟) | `usage` 初始化 |
|
||
| `content_block_start` | 按 `part.index` 创建对应类型的内容块 | `contentBlocks[index]` 初始化 |
|
||
| `content_block_delta` | 按子类型增量追加数据 | text / thinking / input 累加 |
|
||
| `content_block_stop` | 构建完整 `AssistantMessage` 并 yield | 消息推入 `newMessages` |
|
||
| `message_delta` | 更新 stop_reason 和最终 usage | 写回最后一条消息 |
|
||
| `message_stop` | 无操作(流结束标记) | — |
|
||
|
||
### 内容块类型及其增量数据
|
||
|
||
`content_block_start` 中的 `content_block.type` 决定了如何处理后续 delta:
|
||
|
||
| 内容块类型 | Delta 类型 | 累加逻辑 |
|
||
|-----------|-----------|----------|
|
||
| `text` | `text_delta` | `text += delta.text` |
|
||
| `thinking` | `thinking_delta` + `signature_delta` | `thinking += delta.thinking`,`signature = delta.signature` |
|
||
| `tool_use` | `input_json_delta` | `input += delta.partial_json`(JSON 字符串增量拼接) |
|
||
| `server_tool_use` | `input_json_delta` | 同 tool_use |
|
||
| `connector_text` | `connector_text_delta` | 特殊连接器文本(feature flag 控制) |
|
||
|
||
关键设计:`content_block_start` 时所有文本字段初始化为空字符串,只通过 `content_block_delta` 累加。这是因为 SDK 有时在 start 和 delta 中重复发送相同文本。
|
||
|
||
## 文本 chunk 和 tool_use block 的交织
|
||
|
||
一次 AI 响应可能包含多个内容块,交替出现:
|
||
|
||
```
|
||
content_block_start (text, index=0) "我来帮你修复这个 bug。"
|
||
content_block_delta (text_delta) "首先..."
|
||
content_block_stop (index=0)
|
||
content_block_start (tool_use, index=1) { name: "Read", input: "..." }
|
||
content_block_delta (input_json_delta) '{"file_p' → 'ath":' → '"src/foo.ts"}'
|
||
content_block_stop (index=1)
|
||
content_block_start (text, index=2) "我已经看到了问题所在..."
|
||
content_block_stop (index=2)
|
||
```
|
||
|
||
每个 `content_block_stop` 触发一次 `yield`,将完整的 AssistantMessage 推送给消费者。这意味着一个 AI 响应会产生**多条** `AssistantMessage`——文本消息和工具调用消息交替产出。
|
||
|
||
`stop_reason` 要等到 `message_delta` 才确定(可能是 `end_turn`、`tool_use`、`max_tokens` 等),所以最后一条消息的 `stop_reason` 是**回写**的:
|
||
|
||
```typescript
|
||
// claude.ts — stop_reason 回写逻辑(直接属性修改,不用对象替换)
|
||
// 因为 transcript 写队列持有 message.message 的引用
|
||
const lastMsg = newMessages.at(-1)
|
||
if (lastMsg) {
|
||
lastMsg.message.usage = usage
|
||
lastMsg.message.stop_reason = stopReason
|
||
}
|
||
```
|
||
|
||
## 流式中的错误处理
|
||
|
||
### 网络断开
|
||
|
||
流式连接依赖 SSE(Server-Sent Events)。当连接中断时,系统有两层检测机制:
|
||
|
||
1. **被动停滞检测**(`src/services/api/claude.ts` 中 stall 检测逻辑):当下一个事件到达时,计算与上一个事件的时间间隔。超过阈值(30 秒,`STALL_THRESHOLD_MS = 30_000`)记录为一次 stall,累积计数并写入遥测日志。这是被动检测——仅在下一个 chunk 到达时才触发,不会主动中断流。
|
||
2. **主动空闲超时看门狗**(`src/services/api/claude.ts` 中 `STREAM_IDLE_TIMEOUT_MS` 看门狗逻辑):使用 `setTimeout` 设置 90 秒(可通过 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 环境变量覆盖)的硬性超时。如果在此期间没有收到任何事件,主动终止流并抛出错误进入重试流程。
|
||
3. **非流式降级**:作为最后手段,设置 `didFallBackToNonStreaming` 标志,通过 `executeNonStreamingRequest()` 回退到非流式请求(一次性获取完整响应)。
|
||
|
||
```typescript
|
||
// claude.ts — 被动停滞检测
|
||
const STALL_THRESHOLD_MS = 30_000 // 30 秒无事件视为停滞
|
||
let totalStallTime = 0
|
||
let stallCount = 0
|
||
|
||
// claude.ts — 主动空闲超时
|
||
const STREAM_IDLE_TIMEOUT_MS =
|
||
parseInt(process.env.CLAUDE_STREAM_IDLE_TIMEOUT_MS || '', 10) || 90_000
|
||
```
|
||
|
||
### API 限流
|
||
|
||
当 API 返回限流错误时,系统使用 `withRetry` 包装器进行指数退避重试。重试逻辑考虑了:
|
||
- 错误类型(429 限流 vs 500 服务器错误)
|
||
- 重试次数上限
|
||
- 退避间隔
|
||
|
||
### Token 超限
|
||
|
||
两种 token 超限场景有不同的处理:
|
||
|
||
| 场景 | stop_reason | 处理方式 |
|
||
|------|------------|----------|
|
||
| **输出超限** | `max_tokens` | 生成错误消息,建议设置 `CLAUDE_CODE_MAX_OUTPUT_TOKENS` |
|
||
| **上下文窗口超限** | `model_context_window_exceeded` | 触发 compaction 压缩对话历史后重试 |
|
||
|
||
```typescript
|
||
// claude.ts — stop_reason 处理
|
||
if (stopReason === 'max_tokens') {
|
||
yield createAssistantAPIErrorMessage({ error: 'max_output_tokens', ... })
|
||
}
|
||
if (stopReason === 'model_context_window_exceeded') {
|
||
// 复用 max_output_tokens 的恢复路径
|
||
yield createAssistantAPIErrorMessage({ error: 'max_output_tokens', ... })
|
||
}
|
||
```
|
||
|
||
### 流式停滞检测
|
||
|
||
系统持续监控事件到达间隔,检测"停滞"(stall):
|
||
|
||
```typescript
|
||
// claude.ts — stall 检测逻辑
|
||
const STALL_THRESHOLD_MS = 30_000 // 30 秒无事件视为停滞
|
||
if (timeSinceLastEvent > STALL_THRESHOLD_MS) {
|
||
stallCount++
|
||
totalStallTime += timeSinceLastEvent
|
||
logEvent('tengu_streaming_stall', { stall_duration_ms, stall_count, ... })
|
||
}
|
||
```
|
||
|
||
这是**被动检测**——仅在下一个 chunk 到达时才触发比较。与之互补的是 90 秒主动空闲超时看门狗(`STREAM_IDLE_TIMEOUT_MS`),会直接中断长时间无响应的流。
|
||
|
||
## 工具执行的流式反馈
|
||
|
||
BashTool 的命令执行也是流式的——通过 `onProgress` 回调逐行推送输出:
|
||
|
||
```
|
||
BashTool.call() → runShellCommand() → AsyncGenerator
|
||
├── 每秒轮询输出文件 → onProgress(lastLines, allLines, ...)
|
||
├── yield { type: 'progress', output, fullOutput, elapsedTimeSeconds }
|
||
└── return { code, stdout, interrupted, ... }
|
||
```
|
||
|
||
UI 层通过 `useToolCallProgress` hook 实时展示命令输出,而不是等命令完全结束。长时间运行的命令还支持自动后台化(`shouldAutoBackground`)。
|
||
|
||
## 多 Provider 适配
|
||
|
||
| Provider | 流式协议 | 特殊处理 |
|
||
|----------|----------|----------|
|
||
| **firstParty** (Anthropic Direct) | 原生 SSE | 延迟最低,TTFT 最快 |
|
||
| **AWS Bedrock** | AWS SDK 流式接口 | 需要额外的 beta header 和认证 |
|
||
| **Google Vertex** | gRPC → 事件流 | 通过 `getMergedBetas()` 适配 |
|
||
| **foundry** | Anthropic 兼容 API | 内部部署 |
|
||
| **openai** | OpenAI 流式适配器 | 转换为 Anthropic 内部格式 |
|
||
| **gemini** | Gemini 流式适配器 | 转换为 Anthropic 内部格式 |
|
||
| **grok** (xAI) | Grok 流式适配器 | 转换为 Anthropic 内部格式 |
|
||
|
||
所有 Provider 通过统一的 `Stream<BetaRawMessageStreamEvent>` 抽象层屏蔽差异。上层代码(QueryEngine、REPL)不需要关心底层用的是哪个 Provider。
|
||
|
||
### Provider 选择
|
||
|
||
`src/utils/model/providers.ts` 中的 `getAPIProvider()` 根据配置决定使用哪个 Provider:
|
||
|
||
```typescript
|
||
// 根据 api_provider 配置选择:
|
||
// "anthropic" → 直连
|
||
// "bedrock" → AWS SDK
|
||
// "vertex" → Google SDK
|
||
// 第三方 base URL → 自动检测
|
||
```
|
||
|
||
每个 Provider 需要适配的细节包括:认证方式、beta header、请求参数格式、错误码映射——但这些差异在 `claude.ts` 的 `queryStream()` 函数中被统一处理。
|