mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-15 12:55: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>
206 lines
7.9 KiB
Markdown
206 lines
7.9 KiB
Markdown
# Langfuse 监控集成
|
||
|
||
> 实现状态:已完成,通过环境变量启用
|
||
> 依赖:`@langfuse/otel`、`@langfuse/tracing`、`@opentelemetry/sdk-trace-base`
|
||
|
||
## 一、功能概述
|
||
|
||
Langfuse 是一个开源的 LLM 可观测性平台,用于追踪、监控和调试 AI 应用的请求链路。CCB 通过 OpenTelemetry (OTel) 桥接层将 Langfuse 集成到查询流程中,实现:
|
||
|
||
- **LLM 调用追踪** — 记录每次 API 请求的模型、Provider、输入/输出、Token 用量
|
||
- **工具执行追踪** — 记录每个工具调用的名称、输入、输出、耗时和错误
|
||
- **多 Agent 追踪** — 主 Agent 和子 Agent 各自独立的 Trace 链路
|
||
- **数据脱敏** — 自动遮蔽敏感信息(API Key、文件内容、Shell 输出等)
|
||
|
||
## 二、启用方式
|
||
|
||
Langfuse 是开源项目,你可以 **自部署**(Docker / Kubernetes),也可以使用官方提供的 **[Langfuse Cloud](https://cloud.langfuse.com)** 免费测试。注册后在 Project Settings → API Keys 页面获取密钥。
|
||
|
||
核心只需要三个环境变量:
|
||
|
||
| 环境变量 | 说明 |
|
||
|---------|------|
|
||
| `LANGFUSE_PUBLIC_KEY` | Langfuse 公钥(必填) |
|
||
| `LANGFUSE_SECRET_KEY` | Langfuse 密钥(必填) |
|
||
| `LANGFUSE_BASE_URL` | 服务地址,默认 `https://cloud.langfuse.com`;自部署时改为你的地址(必填) |
|
||
|
||
未配置时所有追踪函数为 no-op,零开销。
|
||
|
||
### 通过 settings.json 配置(推荐)
|
||
|
||
在 `.claude/settings.json` 的 `env` 字段中添加,这样每次启动自动生效:
|
||
|
||
```json
|
||
{
|
||
"env": {
|
||
"LANGFUSE_PUBLIC_KEY": "pk-xxx",
|
||
"LANGFUSE_SECRET_KEY": "sk-xxx",
|
||
"LANGFUSE_BASE_URL": "https://cloud.langfuse.com"
|
||
}
|
||
}
|
||
```
|
||
|
||
### 其他可选参数
|
||
|
||
| 环境变量 | 默认值 | 说明 |
|
||
|---------|--------|------|
|
||
| `LANGFUSE_TRACING_ENVIRONMENT` | `development` | 环境标签,用于 Langfuse 面板筛选 |
|
||
| `LANGFUSE_FLUSH_AT` | `20` | 批量发送的 span 数量阈值 |
|
||
| `LANGFUSE_FLUSH_INTERVAL` | `10` | 定时刷新间隔(秒) |
|
||
| `LANGFUSE_EXPORT_MODE` | `batched` | 导出模式:`batched`(批量)或 `immediate`(即时) |
|
||
| `LANGFUSE_TIMEOUT` | `5` | 请求超时(秒) |
|
||
|
||
## 四、架构
|
||
|
||
### 4.1 模块结构
|
||
|
||
```
|
||
src/services/langfuse/
|
||
├── index.ts # 统一导出
|
||
├── client.ts # OTel Provider + LangfuseSpanProcessor 初始化
|
||
├── tracing.ts # Trace/Span 创建、LLM 和工具观察记录
|
||
├── convert.ts # 内部 Message 类型 → Langfuse OpenAI 兼容格式转换
|
||
└── sanitize.ts # 数据脱敏(敏感字段、文件路径、工具输出)
|
||
```
|
||
|
||
### 4.2 追踪层级
|
||
|
||
```
|
||
Trace (Agent Span) ← createTrace() / createSubagentTrace()
|
||
├── Generation (LLM 调用) ← recordLLMObservation()
|
||
├── Tool Observation (工具调用) ← recordToolObservation()
|
||
├── Tool Observation (工具调用) ← recordToolObservation()
|
||
└── ...
|
||
```
|
||
|
||
### 4.3 数据流
|
||
|
||
```
|
||
query.ts ──→ createTrace() # 每个 query turn 创建根 trace
|
||
│
|
||
├── claude.ts ──→ recordLLMObservation() # API 调用完成后记录 LLM 观察
|
||
│
|
||
├── toolExecution.ts ──→ recordToolObservation() # 每个工具执行记录
|
||
│
|
||
└── query.ts ──→ endTrace() # turn 结束时关闭 trace
|
||
|
||
runAgent.ts ──→ createSubagentTrace() # 子 Agent 有独立 trace
|
||
```
|
||
|
||
## 五、追踪详情
|
||
|
||
### 5.1 主 Agent Trace
|
||
|
||
每次 `query()` 调用(即用户一次对话 turn)创建一个类型为 `agent` 的根 Span:
|
||
|
||
- **名称**: `agent-run` 或 `agent-run:<querySource>`
|
||
- **元数据**: `provider`、`model`、`agentType: "main"`
|
||
- **Session ID**: 关联到 Langfuse 的 Session 功能,支持按会话聚合
|
||
|
||
### 5.2 子 Agent Trace
|
||
|
||
通过 `AgentTool` 启动的子 Agent 创建独立 Trace:
|
||
|
||
- **名称**: `agent:<agentType>`
|
||
- **元数据**: `provider`、`model`、`agentType`、`agentId`
|
||
- 独立于主 Trace,有自己的 Session 关联
|
||
|
||
### 5.3 LLM Generation
|
||
|
||
每次 API 调用记录为一个 `generation` 类型的 Span:
|
||
|
||
- **名称**: 按 Provider 映射(如 `ChatAnthropic`、`ChatOpenAI`、`ChatBedrockAnthropic` 等)
|
||
- **记录内容**: 输入消息、输出消息、Token 用量(input/output)
|
||
- **时间**: 精确记录 `startTime`、`endTime`、`completionStartTime`(TTFT 指标)
|
||
|
||
Provider 名称映射:
|
||
|
||
| Provider | Generation 名称 |
|
||
|----------|-----------------|
|
||
| `firstParty` | `ChatAnthropic` |
|
||
| `bedrock` | `ChatBedrockAnthropic` |
|
||
| `vertex` | `ChatVertexAnthropic` |
|
||
| `foundry` | `ChatFoundry` |
|
||
| `openai` | `ChatOpenAI` |
|
||
| `gemini` | `ChatGoogleGenerativeAI` |
|
||
| `grok` | `ChatXAI` |
|
||
|
||
### 5.4 工具执行
|
||
|
||
每个工具调用记录为一个 `tool` 类型的 Span:
|
||
|
||
- **名称**: 工具名(如 `FileEditTool`、`BashTool`)
|
||
- **记录内容**: 输入(经脱敏)、输出(经脱敏)、`toolUseId`
|
||
- **错误标记**: `isError` 标志 + `level: ERROR`
|
||
|
||
## 六、数据脱敏
|
||
|
||
所有上传到 Langfuse 的数据都会经过脱敏处理(`sanitize.ts`),确保敏感信息不会泄露:
|
||
|
||
### 6.1 全局脱敏(`sanitizeGlobal`)
|
||
|
||
- **Home 路径替换** — `/Users/xxx` → `~`
|
||
- **敏感字段遮蔽** — 匹配 `api_key`、`token`、`secret`、`password`、`credential`、`auth_header` 等关键字的字段值替换为 `[REDACTED]`
|
||
|
||
### 6.2 工具输入脱敏(`sanitizeToolInput`)
|
||
|
||
- 敏感字段遮蔽(同全局)
|
||
- `file_path`、`path`、`directory` 路径中的 Home 目录替换
|
||
|
||
### 6.3 工具输出脱敏(`sanitizeToolOutput`)
|
||
|
||
| 工具 | 脱敏策略 |
|
||
|------|---------|
|
||
| `FileReadTool`、`FileWriteTool`、`FileEditTool` | 完全遮蔽,仅保留字符数:`[file content redacted, N chars]` |
|
||
| `BashTool`、`PowerShellTool` | 截断至 500 字符 |
|
||
| `ConfigTool`、`MCPTool` | 完全遮蔽 |
|
||
| 其他工具 | 原样保留 |
|
||
|
||
## 七、消息格式转换
|
||
|
||
`convert.ts` 将 CCB 内部的 Message 类型转换为 Langfuse 期望的 OpenAI 兼容格式:
|
||
|
||
- **输入**: `UserMessage | AssistantMessage[]` + 可选 system prompt → `{ role, content }[]`
|
||
- **输出**: `AssistantMessage[]` → `{ role: 'assistant', content }`
|
||
- **Content Block 映射**:
|
||
- `text` → `{ type: 'text', text }`
|
||
- `thinking` / `redacted_thinking` → `{ type: 'thinking', thinking }`
|
||
- `tool_use` → `{ type: 'tool_use', id, name, input }`
|
||
- `tool_result` → `{ type: 'tool_result', tool_use_id, content }`
|
||
- `image` / `document` → 占位标记 `[image]` / `[document: name]`
|
||
|
||
## 八、生命周期
|
||
|
||
1. **初始化** — `initLangfuse()` 在 `src/entrypoints/init.ts` 启动时调用,创建 `LangfuseSpanProcessor` 和 `BasicTracerProvider`
|
||
2. **运行时** — 各追踪函数通过 `isLangfuseEnabled()` 检查,未配置时直接返回 `null`/跳过
|
||
3. **关闭** — `shutdownLangfuse()` 在进程退出时调用,强制 flush 并关闭 Processor
|
||
|
||
## 九、自部署 Langfuse
|
||
|
||
Langfuse 是开源项目,支持 Docker / Kubernetes 自部署:
|
||
|
||
```bash
|
||
docker run -d \
|
||
--name langfuse \
|
||
-p 3000:3000 \
|
||
-e DATABASE_URL=postgresql://... \
|
||
langfuse/langfuse:latest
|
||
```
|
||
|
||
自部署后,将 `LANGFUSE_BASE_URL` 指向你的实例地址即可。详见 [Langfuse 自部署文档](https://langfuse.com/docs/deployment/self-host)。
|
||
|
||
如果没有自部署需求,可以直接使用 [Langfuse Cloud](https://cloud.langfuse.com),提供免费额度可用于测试。
|
||
|
||
## 十、相关文件
|
||
|
||
| 文件 | 说明 |
|
||
|------|------|
|
||
| `src/services/langfuse/client.ts` | OTel Provider 初始化、生命周期管理 |
|
||
| `src/services/langfuse/tracing.ts` | Trace/Span 创建和观察记录 |
|
||
| `src/services/langfuse/convert.ts` | Message 格式转换 |
|
||
| `src/services/langfuse/sanitize.ts` | 数据脱敏 |
|
||
| `src/services/langfuse/__tests__/langfuse.test.ts` | 测试(568 行) |
|
||
| `src/query.ts` | 主查询流程中的 Trace 集成 |
|
||
| `src/services/tools/toolExecution.ts` | 工具执行中的观察记录 |
|
||
| `packages/builtin-tools/src/tools/AgentTool/runAgent.ts` | 子 Agent Trace 创建 |
|