Compare commits

...

312 Commits

Author SHA1 Message Date
claude-code-best
34154ee3f5 feat: 支持 acp-link 包进行 acp 通用的 remote-control (#292)
* fix: 修复超时问题

* feat: 添加 acp-link 代码

* refactor: 样式重构完成

* feat: RCS 添加 ACP 后端支持

- 新增 ACP WebSocket handler (agent 注册、EventBus 订阅)
- 新增 relay handler (前端 WS → acp-link 透传 + EventBus inbound 转发)
- 新增 SSE event stream 供外部消费者订阅 channel group 事件
- ACP REST 接口无鉴权 (agents、channel-groups)
- WebSocket 端点保留 token 鉴权
- SPA 路由 /acp/ 指向 acp.html

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: 添加 ACP 专属前端界面

- 新增 /acp/ SPA 页面 (agent 列表 + 实时交互)
- Agent 列表按 channel group 分组,显示在线状态
- 通过 RCS WebSocket relay 与 agent 通信
- Vite multi-page 构建 (index.html + acp.html)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: acp-link 支持 RCS relay 双向通信

- rcs-upstream 新增 messageHandler 转发非控制消息
- server.ts 新增虚拟 WS + relay client state 处理 relay ACP 消息
- newSession/loadSession 补充 mcpServers 参数
- 连接成功后显示 ACP Dashboard URL

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 移除 FileExplorer 及文件操作相关代码

- 删除 FileExplorer 组件
- ACPMain 移除 Files tab,仅保留 Chat 和 History
- client.ts 移除 listDir/readFile/onFileChanges 等方法
- types.ts 移除 FileItem/FileContent/FileChange 等类型

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 修复类型问题

* feat: RCS 后端统一 ACP/Bridge 注册逻辑

- store: EnvironmentRecord 增加 capabilities 字段、storeFindEnvironmentByMachineName 复用逻辑
- store: 新增 storeGetSessionOwners,支持未绑定 session 自动 claim
- environment: registerEnvironment 支持 ACP 复用已有记录,返回 session_id
- session: resolveOwnedWebSessionId 支持无 owner session 自动绑定
- acp-ws-handler: 新增 handleIdentify 支持 REST+WS 两步注册
- acp routes: /acp/relay 和 /acp/agents 支持 UUID 认证
- event-bus: 增加 error 类型 payload 日志

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: acp-link 改 REST 注册 + WS identify 两步流程

- rcs-upstream: 新增 registerViaRest() 通过 POST /v1/environments/bridge 注册
- rcs-upstream: WS 连接后发送 identify 替代 register,携带 agentId
- rcs-upstream: 入口链接改为 /code/?sid=${sessionId} 实现用户绑定
- server: 修复心跳跳过 relay 虚拟连接的 bug
- server: maxSessions 配置传入 RCS upstream

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: 前端统一 Chat 组件 + ACP 聊天界面重构

- 新增 chat/ 组件: ChatView, ChatInput, MessageBubble, ToolCallGroup, PermissionPanel, SessionSidebar, CommandMenu
- ACPMain: 重构支持完整 ACP 协议交互(session/prompt/permission)
- rcs-chat-adapter: 统一 bridge session SSE 适配器
- ACPClient: 增强 session 管理、permission 流程、streaming 支持
- index.css: 新增 chat 相关样式、动画、布局
- useCommands: 新增快捷命令 hook

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 删除 /acp/ 独立页面,ACP 聊天统一到 /code/:sessionId

- 删除 acp.html、acp-main.tsx 入口文件和 pages/acp/ 目录
- SessionDetail: ACP session 在同一页面渲染 ACPSessionDetail 组件
- App.tsx: ?sid= 参数自动调用 apiBind 绑定用户 UUID
- Dashboard: 统一 session 列表导航,ACP 显示紫色标签
- relay-client: 改用 UUID 认证替代 API token
- EnvironmentList: 显示 workerType 标签(ACP Agent / Claude Code)
- index.ts: 移除 /acp/ SPA 路由,vite.config 移除 acp 入口

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* build: 更新构建及测试修复

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 17:59:29 +08:00
claude-code-best
29cc74a170 docs: 更新 CLAUDE.md 2026-04-17 21:37:43 +08:00
claude-code-best
d2b66d9d2c docs: update contributors 2026-04-17 12:45:56 +00:00
claude-code-best
d70e7f7f05 feat: 支持 langfuse 工具调用映射 2026-04-17 20:45:14 +08:00
Cheng Zi Feng
72a2093cd6 feat(remote-control): 优化 Web 展示、状态同步与桥接控制流程 (#288)
Co-authored-by: chengzifeng <chengzifeng@meituan.com>
2026-04-17 16:21:27 +08:00
claude-code-best
b5c299f5d2 build: CI 添加通过过滤 2026-04-17 11:33:57 +08:00
claude-code-best
ac42ce2d67 fix: 解决 node 下 loading 按钮计算错误问题 2026-04-17 10:42:40 +08:00
claude-code-best
c659912517 docs: 更新说明 2026-04-17 10:22:56 +08:00
claude-code-best
a14b7f352b test: 修正 mock 的滥用情况 2026-04-17 10:13:09 +08:00
claude-code-best
c5ab83a3fc fix: 修复 linux 端的安装问题 2026-04-17 09:51:59 +08:00
claude-code-best
03b7f9b453 chore: 1.4.1 2026-04-17 09:45:36 +08:00
claude-code-best
bddd146f25 feat: 重构供应商层次 (#286)
* refactor: 创建 @anthropic-ai/model-provider 包骨架与类型定义

- 新建 workspace 包 packages/@anthropic-ai/model-provider
- 定义 ModelProviderHooks 接口(依赖注入:分析、成本、日志等)
- 定义 ClientFactories 接口(Anthropic/OpenAI/Gemini/Grok 客户端工厂)
- 搬入核心类型:Message 体系、NonNullableUsage、EMPTY_USAGE、SystemPrompt、错误常量
- 主项目 src/types/message.ts 等改为 re-export,保持向后兼容

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 提升 OpenAI 转换器和模型映射到 model-provider 包

- 搬入 OpenAI 消息转换(convertMessages)、工具转换(convertTools)、流适配(streamAdapter)
- 搬入 OpenAI 和 Grok 模型映射(resolveOpenAIModel、resolveGrokModel)
- 主项目文件改为 thin re-export proxy

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 搬入 Gemini 兼容层到 model-provider 包

- 搬入 Gemini 类型定义、消息转换、工具转换、流适配、模型映射
- 主项目 gemini/ 目录下文件改为 thin re-export proxy

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 搬入 errorUtils 并迁移消费者导入到 model-provider

- 搬入 formatAPIError、extractConnectionErrorDetails 等 errorUtils
- 迁移 10 个消费者文件直接从 @anthropic-ai/model-provider 导入
- 更新 emptyUsage、sdkUtilityTypes、systemPromptType 为 re-export proxy

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: compact 模型降级为 -1 模式(Opus→Sonnet, Sonnet→Haiku)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: 添加 agent-loop 绘图

* Revert "feat: compact 模型降级为 -1 模式(Opus→Sonnet, Sonnet→Haiku)"

This reverts commit e458d6391d.

* docs: 添加简化版 agent loop

* fix: 修复 n 快捷键导致关闭的问题

* fix: 修复 node 下 ws 没打包问题

* docs: 修复链接

* test: 添加测试支持

* fix: 修复类型问题(#267) (#271)

* fix: 修复 Bun 的 polyfill 问题

* fix: 类型修复完成

* feat: 统一所有包的类型文件

* fix: 修复构建问题

* test: 修复类型校验 (#279)

* fix: 修复 Bun 的 polyfill 问题

* fix: 类型修复完成

* feat: 统一所有包的类型文件

* fix: 修复构建问题

* fix(remote-control): harden self-hosted session flows (#278)

Co-authored-by: chengzifeng <chengzifeng@meituan.com>

* docs: update contributors

* build: 新增 vite 构建流程

* feat: 添加环境变量支持以覆盖 max_tokens 设置

* feat(langfuse): LLM generation 记录工具定义

将 Anthropic 格式的工具定义转换为 Langfuse 兼容的 OpenAI 格式,
并在 generation 的 input 中以 { messages, tools } 结构传入,
以便在 Langfuse UI 中查看完整的工具定义信息。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: 添加对 ACP 协议的支持 (#284)

* feat: 适配 zed acp 协议

* docs: 完善 acp 文档

* chore: 1.4.0

* conflict: 解决冲突

* feat: 添加测试覆盖率上报

* style: 改名加移动文件夹位置

* refactor: 移动测试用例及实现

* test: 修复测试用例完成

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cheng Zi Feng <1154238323@qq.com>
Co-authored-by: chengzifeng <chengzifeng@meituan.com>
Co-authored-by: claude-code-best <272536312+claude-code-best@users.noreply.github.com>
2026-04-17 09:33:14 +08:00
claude-code-best
c8d08d235b Feat/integrate lint preview (#285)
* feat: 适配 zed acp 协议

* docs: 完善 acp 文档

* feat: integrate feature branches + daemon/job 命令层级化 + 跨平台后台引擎

Cherry-picked from origin/lint/preview (637c908), excluding lint-only changes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: correct detectMimeFromBase64 to decode raw bytes from base64

Cherry-picked from origin/lint/preview (ee36954).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: daemon 子进程 spawn 跨平台修复 + CliLaunchSpec 集中化重构

Cherry-picked from origin/lint/preview (c5f52cd), excluding lint-only formatting changes.

- 新建 src/utils/cliLaunch.ts: 集中化 CLI 子进程启动层
- 修复 --daemon-worker=kind 等号格式解析
- 修复 daemon/bg fast path 缺少 setShellIfWindows()
- 修复 checkPathExists 用 existsSync 替代 execSync('dir')
- 7 个 spawn 站点迁移到 CliLaunchSpec

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: merge tsconfig.base.json into tsconfig.json with full compiler options

The cherry-pick from 637c908 dropped jsx/strict/etc settings when removing
tsconfig.base.json. This commit restores them in a single tsconfig.json.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: merge tsconfig.base.json into tsconfig.json with full compiler options

The cherry-pick from 637c908 dropped jsx/strict/etc settings when removing
tsconfig.base.json. This commit restores them in a single tsconfig.json.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 20:59:29 +08:00
claude-code-best
a02dc0bded chore: 1.4.0 2026-04-16 20:48:09 +08:00
claude-code-best
3cb1e50b25 feat: 添加对 ACP 协议的支持 (#284)
* feat: 适配 zed acp 协议

* docs: 完善 acp 文档
2026-04-16 20:31:50 +08:00
claude-code-best
cfab161e28 feat(langfuse): LLM generation 记录工具定义
将 Anthropic 格式的工具定义转换为 Langfuse 兼容的 OpenAI 格式,
并在 generation 的 input 中以 { messages, tools } 结构传入,
以便在 Langfuse UI 中查看完整的工具定义信息。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 15:31:18 +08:00
claude-code-best
90027279e6 feat: 添加环境变量支持以覆盖 max_tokens 设置 2026-04-16 13:01:07 +08:00
claude-code-best
3470783ced build: 新增 vite 构建流程 2026-04-16 12:39:19 +08:00
claude-code-best
8169b96250 docs: update contributors 2026-04-16 02:46:47 +00:00
Cheng Zi Feng
fe08cacf8d fix(remote-control): harden self-hosted session flows (#278)
Co-authored-by: chengzifeng <chengzifeng@meituan.com>
2026-04-16 10:46:31 +08:00
claude-code-best
5a4c820e1d test: 修复类型校验 (#279)
* fix: 修复 Bun 的 polyfill 问题

* fix: 类型修复完成

* feat: 统一所有包的类型文件

* fix: 修复构建问题
2026-04-16 10:28:47 +08:00
claude-code-best
1a4e9702c2 fix: 修复类型问题(#267) (#271)
* fix: 修复 Bun 的 polyfill 问题

* fix: 类型修复完成

* feat: 统一所有包的类型文件

* fix: 修复构建问题
2026-04-15 10:54:00 +08:00
claude-code-best
2273a0bcfe docs: 修复链接 2026-04-14 21:19:36 +08:00
claude-code-best
b80483c23e fix: 修复 node 下 ws 没打包问题 2026-04-14 21:19:25 +08:00
claude-code-best
8442aaadd2 fix: 修复 n 快捷键导致关闭的问题 2026-04-14 21:18:36 +08:00
claude-code-best
dad3ad2b8d docs: 添加浏览器说明支持 2026-04-13 21:22:41 +08:00
claude-code-best
b5b81dfe49 chore: 更改 chrome 的依赖 2026-04-13 20:55:04 +08:00
claude-code-best
ecbd5a93e4 fix: 修复 Bun.hash 不存在的问题 2026-04-13 20:21:14 +08:00
claude-code-best
be80da4ce0 fix: 修复缓存 2026-04-13 20:09:23 +08:00
claude-code-best
fce40fed1f feat: 加上 userId 的传递 2026-04-13 19:04:51 +08:00
claude-code-best
a7e03a5b30 fix: 修复 interrupt 日志不上传 2026-04-13 18:12:23 +08:00
claude-code-best
05cabbbd73 feat: langfuse 工具调用显示为嵌套结构 2026-04-13 18:09:12 +08:00
claude-code-best
d4b30d32c3 fix: 修复 chrome 链接版本 2026-04-13 17:30:47 +08:00
claude-code-best
e0484e2817 fix: 使用简化版本的 chrome 桥接器 2026-04-13 16:03:47 +08:00
claude-code-best
2fb1c9dcd8 feat: 工具层及 mcp 大重构 (#252)
* feat: 第一版大重构

* fix: 修复类型问题

* chore: 更新版本到 1.3.2

* Add brave as alternative WebSearchTool

* fix: 修正顺序

* fix: 修复对穷鬼模式的 auto dream 和 session memory 越过

* feat: 穷鬼模式去除 session-summary

* feat: 创建 builtin-tools 包,搬运所有工具实现

将 src/tools/ 下的全部 60 个工具目录迁移至 packages/builtin-tools/src/tools/,
内部导入路径已更新为 src/ alias 模式。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 更新 src/ 中所有工具引用至 builtin-tools 包,删除 src/tools/

- src/tools.ts 及 178 个 src/ 文件的 import 路径从 ./tools/ 改为 builtin-tools/tools/
- 删除 src/tools/ 整个目录(已迁移至 packages/builtin-tools/)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: 添加 builtin-tools 路径别名至 tsconfig,更新 bun.lock

- tsconfig.json 新增 builtin-tools/* 和 builtin-tools 路径映射
- 新增 packages/builtin-tools/src 至 include

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 为 builtin-tools、mcp-client、agent-tools 添加 @claude-code-best 作用域前缀

所有包名及 import 路径统一添加 @claude-code-best/ 前缀:
- builtin-tools → @claude-code-best/builtin-tools
- mcp-client → @claude-code-best/mcp-client
- agent-tools → @claude-code-best/agent-tools

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 修复 node 环境没有 bun 的问题

---------

Co-authored-by: Eric-Guo <eric.guocz@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 09:52:05 +08:00
claude-code-best
bbb8b613a9 docs: update contributors 2026-04-13 01:51:00 +00:00
claude-code-best
c63b875ae3 chore: 1.3.3 版本 2026-04-13 09:50:38 +08:00
claude-code-best
9b8503d13d fix: 修复 node 环境没有 bun 的问题 2026-04-13 09:47:33 +08:00
claude-code-best
3cf94fbda0 fix: 修复对穷鬼模式的 auto dream 和 session memory 越过 2026-04-12 23:24:12 +08:00
claude-code-best
9a3081dff6 Merge branch 'pr/Eric-Guo/245' 2026-04-12 23:12:23 +08:00
claude-code-best
bd6448ecda fix: 修正顺序 2026-04-12 23:12:09 +08:00
claude-code-best
1071270ce3 chore: 更新版本到 1.3.2 2026-04-12 22:47:03 +08:00
Eric-Guo
711440474c Add brave as alternative WebSearchTool 2026-04-12 22:23:11 +08:00
claude-code-best
8399d9ed20 fix: 修复类型问题 2026-04-12 22:19:54 +08:00
claude-code-best
513ccc3003 fix: 修复需要鉴权的问题 2026-04-12 21:45:22 +08:00
claude-code-best
e770f1ef9d feat: 完成第一个 mcp-chrome 接入版本 2026-04-12 21:32:09 +08:00
claude-code-best
227083d31f fix: 修复截图 MIME 类型硬编码导致 API 拒绝的问题
macOS screencapture 输出 PNG,但代码硬编码 mimeType 为 image/jpeg,
导致 API 报错 "specified using image/jpeg but appears to be image/png"。
改为通过 magic bytes 检测实际图片格式。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 17:32:28 +08:00
claude-code-best
14c46df881 docs: 清理垃圾文档 2026-04-12 17:32:28 +08:00
Dosion
e0e4ee41c2 docs: add complete features guide and rewrite LAN Pipes docs (#246)
- Add docs/features/all-features-guide.md — comprehensive guide covering
  all 18 features across 13 PRs (Buddy, Remote Control, Voice, Chrome,
  Computer Use, GrowthBook, Ultraplan, Daemon, Pipe IPC, LAN Pipes,
  Monitor, Workflow, Coordinator, Proactive, History/Snip, Fork, etc.)

- Rewrite docs/features/lan-pipes.md — user-facing guide with step-by-step
  quickstart, firewall config (Windows/macOS/Linux), command reference,
  keyboard shortcuts, routing modes, permission forwarding, FAQ

- Rewrite docs/features/lan-pipes-implementation.md — developer reference
  with updated architecture (hook extraction, ndjsonFramer, module singletons),
  corrected code references, NDJSON protocol spec, attach flow sequence

Co-authored-by: unraid <local@unraid.local>
2026-04-12 11:37:51 +08:00
claude-code-best
e9861415c0 fix: 修复穷鬼模式的写入问题 2026-04-12 09:15:12 +08:00
claude-code-best
423f114db6 docs: 更新 langfuse 文档 2026-04-11 23:53:21 +08:00
claude-code-best
c8a502f81f chore: 删除重复 feature 定义 2026-04-11 23:27:28 +08:00
claude-code-best
09fc515edb feat: 远程群控 (#243)
* feat: restore pipe IPC, LAN pipes, monitor tool, and PR-package features

Core IPC system (UDS_INBOX):
- PipeServer/PipeClient with UDS + TCP dual transport, NDJSON protocol
- PipeRegistry: machineId-based role assignment, file locking
- Master/slave attach, prompt relay, permission forwarding
- Heartbeat lifecycle with parallel isPipeAlive probes
- Commands: /pipes, /attach, /detach, /send, /claim-main, /pipe-status

LAN Pipes (LAN_PIPES):
- UDP multicast beacon (224.0.71.67:7101) for zero-config LAN discovery
- PipeServer TCP listener, PipeClient TCP connect mode
- Heartbeat auto-attaches LAN peers via TCP
- Cross-machine attach allowed regardless of role
- /pipes shows [LAN] peers with role + hostname/IP
- SendMessageTool supports tcp: scheme with user consent

Architecture — extracted hooks from REPL.tsx (~830 lines → ~20 lines):
- usePipeIpc: lifecycle (bootstrap, handlers, heartbeat, cleanup)
- usePipeRelay: slave→master message relay via module singleton
- usePipePermissionForward: permission request/cancel forwarding
- usePipeRouter: selected pipe input routing with role+IP labels
- Shared ndjsonFramer.ts replaces 3 duplicate NDJSON parsers

Key fixes applied during development:
- Multicast binds to correct LAN interface (not WSL/Docker)
- Beacon ref stored as module singleton (not Zustand state mutation)
- Heartbeat preserves LAN peers in discoveredPipes and selectedPipes
- Disconnect handler calls removeSlaveClient (fixes listener leak)
- cleanupStaleEntries probes without lock, writes briefly under lock
- getMachineId uses async execFile (not blocking execSync)
- globalThis.__pipeSendToMaster replaced with setPipeRelay singleton
- M key only toggles route mode when selector panel is expanded
- User prompt displayed in message list on pipe broadcast
- Broadcast notifications show [role] + hostname/IP for LAN peers

Other restored features:
- Monitor tool: /monitor command, MonitorTool, MonitorMcpTask lifecycle
- Daemon supervisor and remoteControlServer command
- Tools: SnipTool, SleepTool, ListPeersTool, SendUserFileTool,
  WebBrowserTool, WorkflowTool, and 10+ stub→implementation rewrites
- Feature flags: UDS_INBOX, LAN_PIPES, MONITOR_TOOL, FORK_SUBAGENT,
  KAIROS, COORDINATOR_MODE, WORKFLOW_SCRIPTS, HISTORY_SNIP

Tests: 2190 pass / 0 fail (15 new: lanBeacon 7, peerAddress 8)

* fix: resolve merge conflicts and fix all tsc/test errors after main merge

- Export ToolResultBlockParam from Tool.ts (14 tool files fixed)
- Migrate ink imports from ../../ink.js to @anthropic/ink (7 files)
- Fix toolUseID → toolUseId typo in monitor.ts and MonitorTool.tsx
- Add fallback values for string|undefined type errors (8 locations)
- Fix AppState type in assistant.ts, add NewInstallWizard stubs
- Fix ParsedRepository.repo → .name in subscribe-pr.ts
- Fix AgentId/string type mismatch in BackgroundTasksDialog.tsx
- Fix PipeRelayFn return type in pipePermissionRelay.ts
- Use PipeMessage type in usePipeRelay.ts
- Fix lanBeacon.test.ts mock type assertions
- Create missing MouseActionEvent class for ink package
- Use ansi: color format instead of bare "green"/"red"
- Resolve theme.permission access via getTheme()

Result: 0 tsc errors, 2496 tests pass, 0 fail

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 恢复 /poor 的说明

---------

Co-authored-by: unraid <local@unraid.local>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 23:22:55 +08:00
claude-code-best
2fea429dc6 feat: 添加对 langfuse 监控的支持 (#242)
* docs: 更新类型检查的 CLAUDE.md

* feat: 添加模型 1M 上下文切换

* chore: remove prefetchOfficialMcpUrls call on startup

* docs: 添加 git commit 规范

* feat: 第一次接入 langfuse

* fix: 修复 generation 的计时的错误

* feat: 添加多 agent 的监控

* feat: 添加 /poor 省流模式,toggle 关闭 extract_memories 和 prompt_suggestion

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: 修复 lock 文件

* chore: 更新类型依赖

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 22:07:38 +08:00
claude-code-best
6a9da9d546 docs: 添加 git commit 规范 2026-04-11 15:13:41 +08:00
claude-code-best
d27c6cbc64 chore: remove prefetchOfficialMcpUrls call on startup 2026-04-11 15:13:41 +08:00
claude-code-best
ffd1c366eb feat: 添加模型 1M 上下文切换 2026-04-11 15:13:41 +08:00
claude-code-best
5beeebad59 docs: 更新类型检查的 CLAUDE.md 2026-04-11 15:13:41 +08:00
claude-code-best
c676ac4693 docs: update contributors 2026-04-11 05:19:38 +00:00
claude-code-best
eeb0f2776e docs: update contributors 2026-04-11 02:24:22 +00:00
claude-code-best
6a70056910 feat: 全部类型问题解决 2026-04-11 10:24:00 +08:00
claude-code-best
7088fe3c8b Merge remote-tracking branch 'guunergooner/fix/openai-stop-reason-usage' 2026-04-10 22:27:16 +08:00
claude-code-best
b060eabda9 chore: 添加类型测试 2026-04-10 22:24:17 +08:00
sobird
9da7345f8e Add Ultraplan Feature for Advanced Multi-Agent Planning (#232)
* feat: add ultraplan feature for advanced multi-agent planning

Implement ultraplan command with web-based planning interface,
supporting multiple prompt modes and interactive plan approval.

* chore: add semi

* chore: add semi
2026-04-10 22:17:00 +08:00
claude-code-best
8137b66a46 fix: 修复初次登陆的校验问题 2026-04-10 22:06:02 +08:00
claude-code-best
b681139b63 docs: update contributors 2026-04-10 10:14:34 +00:00
claude-code-best
0b1e678fb7 fix: 修复 mintlify ignore, 修复侧边栏 2026-04-10 18:14:07 +08:00
CyberScrubber
81073135e2 docs: 审校 Agent 文档术语与架构描述准确性(docs/agent) (#231)
基于源码验证和官方文档对照,修正三份 Agent 文档的内容准确性:

coordinator-and-swarm.mdx:
- 对齐官方术语:Leader→Team Lead, teammate→Teammate, 引入 Mailbox 消息系统
- 修正 Swarm 门控为 CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1(原文"默认启用"不准确)
- 拓扑描述改为"星型+P2P混合"(官方有 Team Lead 角色,非纯网状)
- 新增架构组件表、Mailbox 消息系统、Hook 事件(TeammateIdle/TaskCreated/TaskCompleted)、限制说明
- 新增持久化存储路径(~/.claude/teams/, ~/.claude/tasks/)
- 移除虚构的"高水位标记"(claimTask 仅使用文件锁)
- 修正 Scratchpad 描述(Workers 获得,非 Coordinator 拥有)
- 修复引号不匹配

sub-agents.mdx:
- 修正为三路径路由(命名 Agent / Fork / GP 回退),原文仅两种
- 补充 isForkSubagentEnabled() 三前提(feature flag + 非Coordinator + 非非交互式)
- 新增模型解析优先级(4级链 + inherit 运行时解析)
- 新增内置 Agent 表(Explore/Plan/GP/statusline-setup/claude-code-guide)
- 新增 Hook 事件表(frontmatter + settings.json 双级别)
- 补充异步生命周期完整链路(finalizeAgentTool → getWorktreeResult)
- 补充 transcript 存储路径和结果格式细节

worktree-isolation.mdx:
- 区分 createWorktreeForSession vs createAgentWorktree 两种函数
- 修正清理机制为 cleanupWorktreeIfNeeded(非 ExitWorktreeTool 手动操作)
- 补充 usedSparsePaths 字段
2026-04-10 18:00:42 +08:00
claude-code-best
ff03fe7fcb fix: 修复类型问题 2026-04-10 17:34:01 +08:00
guunergooner
c82f59943c fix(openai): fix stop_reason null, zero usage fields and max_tokens forwarding
- Fix stop_reason always null in assembled AssistantMessage by applying
  the value captured from message_delta event
- Reset partialMessage to null after message_stop to prevent duplicate
  AssistantMessage emission causing doubled content in next API request
- Forward computed maxTokens into buildOpenAIRequestBody as max_tokens
  so OpenAI-compatible endpoints receive the intended output cap
- Extract assembleFinalAssistantOutputs helper to deduplicate message
  assembly logic between message_stop handler and post-loop fallback
- Fix test helper to use events parameter instead of hidden global
- Add regression test for max_tokens request forwarding

Signed-off-by: guunergooner <tongchao0923@gmail.com>
2026-04-10 12:17:52 +08:00
claude-code-best
e70319e8f5 docs: 更新远程控制及 rg 下载 2026-04-10 12:11:04 +08:00
claude-code-best
609e91143f docs: 尝试 docs 文档更新 2026-04-10 10:15:19 +08:00
claude-code-best
637531f81f fix(types): simplify bridge transport message type
Replace StdoutMessageWithSession conditional type with simpler
TransportMessage intersection type. The conditional type was
over-engineered for what is just StdoutMessage & { session_id? }.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 23:55:54 +08:00
claude-code-best
875510e1eb docs: update CLAUDE.md with architecture details and type safety guidelines
- Update build/dev mode descriptions to reflect current feature flags
- Add workspace packages table and multi-API compatibility layer docs
- Add Type Safety Guidelines section: prohibit `as any` in non-test code,
  document proper alternatives (Record<string, unknown>, dual assertion,
  type guards, specific SDK types)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 23:55:05 +08:00
claude-code-best
34bbc1d403 fix(types): replace all as any with proper type assertions
Eliminate unsafe `as any` casts across 21 non-test source files,
replacing them with specific type annotations:

- Bridge transport: use StdoutMessage type for write/writeBatch calls
- print.ts: type msg.request as Record<string, unknown> for unknown
  SDK control subtypes; use StdoutMessage for output.enqueue()
- API providers (openai/grok/gemini): import ChatCompletion types,
  type streams as AsyncIterable<ChatCompletionChunk>, type request
  bodies as ChatCompletionCreateParamsStreaming
- Computer use executor: use Partial<ResolvePrepareCaptureResult>
  for cross-platform screenshot result
- Components: replace Ink color string casts with proper typing
- Win32 bridge: type stdin as Writable after null check

All 2453 tests pass with 0 failures.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 23:51:33 +08:00
claude-code-best
a14d3dc8f0 fix(types): clean type fixes across 92 files
Apply proper TypeScript type corrections without any unsafe casts:
- Fix unknown/never/{} types from decompilation
- Correct function signatures and parameter types
- Add missing type declarations and interfaces
- Fix Ink component prop types
- Update API client/provider type annotations

Test files with mock data casts are included as-is (acceptable pattern).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 23:45:56 +08:00
claude-code-best
ab3d8ef87e docs: update contributors 2026-04-09 14:04:36 +00:00
claude-code-best
dfce6d02f9 docs: 更新私有部署文档 2026-04-09 22:03:54 +08:00
claude-code-best
01cf45f4ac fix: 修复 permission 面板 2026-04-09 22:03:54 +08:00
HitMargin
e6affc7053 1. 修复 src/commands/fork/index.ts — 将空 stub 改为有效的 Command 定义 2. 新增 src/commands/fork/fork.tsx — 完整实现 /fork 命令,复用了 AgentTool 的 fork 子 agent 逻辑 (#221)
* 1. 修复 src/commands/fork/index.ts — 将空 stub 改为有效的 Command 定义
  2. 新增 src/commands/fork/fork.tsx — 完整实现 /fork 命令,复用了 AgentTool 的 fork 子 agent 逻辑

* Update src/commands/fork/fork.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix

---------

Co-authored-by: HitMargin <hitmargin@qq.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-04-09 21:53:07 +08:00
Alan
bb07836231 fix: support CRLF SSE frame parsing (#223) 2026-04-09 21:52:28 +08:00
claude-code-best
87230cf3bf docs: update contributors 2026-04-09 12:47:35 +00:00
claude-code-best
8c619a215c build: 修复构建报错 2026-04-09 20:47:13 +08:00
claude-code-best
2b0d31aaca feat: 对齐构建时的目标 2026-04-09 20:30:53 +08:00
bonerush
562e9daadd fix: Handle undefined command names in getCommandName function (#217)
* fix: reorder tool and user messages for OpenAI API compatibility (#168)
Fixes #168
OpenAI requires that an assistant message with tool_calls be immediately
followed by tool messages. Previously, convertInternalUserMessage
output user content before tool results, causing 400 errors.
Now tool messages are pushed first.

* fix: 修复OpenAI兼容层中deferred tools处理问题

  提交描述:
  修复了在使用OpenAI兼容API时TaskCreate工具调用失败的问题。

  问题:
  - 当使用OpenAI兼容API模型时,调用TaskCreate工具出现"InputValidationError: The required
  parameter `subject` is missing"错误
  - OpenAI兼容层没有正确处理deferred tools的过滤逻辑,导致工具schema没有被正确发送给模型

  修复:
  1. 在OpenAI兼容层中添加了与Anthropic API路径一致的deferred tools处理逻辑
  2. 导入必要的工具搜索相关函数: isToolSearchEnabled, extractDiscoveredToolNames,
  isDeferredTool等
  3. 实现工具过滤逻辑:
     - 检查工具搜索是否启用
     - 构建deferred tools集合
     - 过滤工具列表: 只包含非deferred工具或已发现的deferred工具
     - 为deferred tools设置deferLoading标志
  4. 修正了extractDiscoveredToolNames函数的导入路径错误

  影响:
  - 解决了TaskCreate工具调用时的参数验证错误
  - 确保OpenAI兼容层与Anthropic API路径在处理deferred tools时行为一致
  - 支持工具搜索功能在OpenAI兼容模式下正常工作

  修改的文件:
  - src/services/api/openai/index.ts - 主要修复文件

  测试建议:
  1. 使用OpenAI兼容API模型时,TaskCreate工具应该可以正常调用
  2. 如果工具搜索功能启用,可能需要先使用ToolSearchTool来发现TaskCreate工具
  3. 验证工具调用时不再出现"InputValidationError"错误

  这个修复确保了当使用OpenAI兼容API(如Ollama、DeepSeek、vLLM等)时,deferred
  tools(如TaskCreate)能够被正确处理,解决了工具调用失败的问题。

* fix: 更新未发送工具架构提示,提供OpenAI兼容模型的使用步骤

* fix: Handle undefined command names in getCommandName function

- Modified getCommandName in src/types/command.ts to return empty string instead of undefined when cmd.name is undefined
- Added null checks in src/hooks/useTypeahead.tsx to safely handle command names
- Prevents "undefined is not an object" error when FEATURE_BUDDY=1 and FEATURE_FORK_SUBAGENT=1 are enabled

The error occurred because getCommandName(cmd) could return undefined when cmd.name was undefined, causing .length access to fail.
2026-04-09 17:53:43 +08:00
CyberScrubber
8b2532a9c1 docs: fix documentation deviations from source code (#220)
* docs: 修正 docs/conversation 文档与源码的偏差(multi-turn/streaming/the-loop)

- multi-turn: TranscriptWriter→Project 私有类, 会话路径改用 sanitized-cwd,
  补充 StoredCostState.lastDuration 字段, 模型切换改为 setModel(),
  QueryEngine 状态补全 loadedNestedMemoryPaths/hasHandledOrphanedPermission,
  行号改为符号引用
- streaming: STALL_THRESHOLD_MS 10s→30s, 新增 90s 主动空闲看门狗描述,
  非流式降级补充 didFallBackToNonStreaming/executeNonStreamingRequest,
  行号改为符号引用
- the-loop: 终止条件 7→11, 继续条件重整为 5 组层级结构,
  max_output_tokens 拆分 escalate/recovery 子阶段,
  prompt-too-long 拆分 collapse_drain/reactive_compact 子策略,
  State 类型修正 autoCompactTracking 为可选, 行号改为符号引用
- 全部: 添加 sourceRef 版本锚定(3ec5675)

* docs: 修正 docs/extensibility 文档与源码的偏差(custom-agents/hooks/skills)

- custom-agents: Verification 模型修正为 inherit, 补充 Plugin Agent 字段限制
  (permissionMode/hooks/mcpServers 被安全忽略, isolation 仅 worktree),
  加载流程修正为 6 层优先级, 补充 memory snapshot 门控条件
- hooks: 事件数 22→27(补充 Notification), Hook 类型定义位置修正为 3 个文件,
  行号改为符号引用, Zod schema 范围修正, 去重键修正为四部分复合键,
  registerFrontmatterHooks/clearSessionHooks 区分定义位置和调用位置
- skills: 字段数 17→16, 权限层级 4→5(补充 remote canonical auto-allow),
  SAFE_SKILL_PROPERTIES 28→30, skillUsageTracking 路径修正,
  行号改为符号引用
- mcp-protocol: 全部验证通过, 无需修改
- 全部: 添加 sourceRef 版本锚定(3ec5675)

* Revert "docs: 修正 docs/extensibility 文档与源码的偏差(custom-agents/hooks/skills)"

* docs: 修正 docs/extensibility 文档与源码的偏差(hooks/skills/mcp-protocol)

hooks:
- 事件数 22→27(补充 Notification 事件)
- Hook 类型定义位置修正为 3 个文件分布
  (schemas/hooks.ts / types/hooks.ts / utils/hooks/sessionHooks.ts)
- Zod schema 引用从硬编码行号改为符号引用
- hookSpecificOutput 表从 6 扩展至 15 个事件
  (补全 permissionDecisionReason / PostToolUseFailure / SubagentStart 等)
- 去重键从 pluginRoot\0command 修正为四部分复合键
  (pluginRoot\0shell\0command\0ifCondition)
- 全部硬编码行号改为符号引用以避免版本漂移

skills:
- parseSkillFrontmatterFields 字段数 17→16
- SAFE_SKILL_PROPERTIES 属性数 28→30
- checkPermissions 层级 4→5
- 第 2 层描述从"官方市场"修正为"远程 canonical"

mcp-protocol:
- 配置层级从"三级"修正为
  "enterprise 独占或合并 user/project/local + plugin + claude.ai"

* docs: 修正 system-prompt.mdx 中 Boundary 章节的层级与可读性

- Boundary 插入条件从 ### 降为 blockquote,不再打断三种分块模式的并列结构
- 表格中 Boundary 缓存策略列补充说明其分割作用
- 新增 Boundary 概念释义(blockquote),解释其分割静态区/动态区以实现全局缓存的设计意图
2026-04-09 17:53:11 +08:00
claude-code-best
2da6514095 feat: 支持自托管的 remote-control-server (#214)
* feat: 支持自托管的 remote-control-server (#214)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-04-09 17:40:50 +08:00
HitMargin
f17b7c7163 修复使用/help 后再按左右键报错 (#212)
* 添加status命令里更多模型api介绍

* Fix: /help error

---------

Co-authored-by: HitMargin <hitmargin@qq.com>
2026-04-09 09:18:35 +08:00
claude-code-best
7f694168d0 docs: update contributors 2026-04-08 13:33:42 +00:00
guunergooner
a3505aeec4 feat: Add DeepSeek thinking mode support for OpenAI compatibility layer (#206)
* feat: Add DeepSeek thinking mode support for OpenAI compatibility layer

- Add DeepSeek reasoning models support (deepseek-reasoner and DeepSeek-V3.2)
- Automatic thinking mode detection based on model name
- Inject thinking parameters in request body (both official API and vLLM formats)
- Preserve reasoning_content in message conversion for tool call iterations
- Extract buildOpenAIRequestBody() for testability
- Treat multimodal inputs (e.g. images) as new turn boundaries
- Fix env var cleanup in tests to prevent state leak

Signed-off-by: guunergooner <tongchao0923@gmail.com>

* docs: update contributors

---------

Signed-off-by: guunergooner <tongchao0923@gmail.com>
Co-authored-by: guunergooner <18660867+guunergooner@users.noreply.github.com>
2026-04-08 21:33:26 +08:00
CyberScrubber
73a18c30db docs: 完善上下文工程核心定义与架构说明(docs/context) Provider 系统、Boundary 条件及兼容层说明 (#204)
- system-prompt.mdx: 新增 Provider 概述(1P/3P)与 Boundary 插入条件
- system-prompt.mdx: 新增 OpenAI/Gemini 兼容层章节
- compaction.mdx: 修正 COMPACTABLE_TOOLS 示例并补充 Microcompact 类型
- token-budget.mdx: 补充 3P Provider Token 计数差异说明
2026-04-08 18:09:26 +08:00
claude-code-best
ae6ae6cfb0 docs: update contributors 2026-04-08 10:09:13 +00:00
bonerush
91ee1428fa Fix bug OpenAI tooluse,Improve error messaging for deferred-loading tools under OpenAI‑compatible models. (#199)
* fix: reorder tool and user messages for OpenAI API compatibility (#168)
Fixes #168
OpenAI requires that an assistant message with tool_calls be immediately
followed by tool messages. Previously, convertInternalUserMessage
output user content before tool results, causing 400 errors.
Now tool messages are pushed first.

* fix: 修复OpenAI兼容层中deferred tools处理问题

  提交描述:
  修复了在使用OpenAI兼容API时TaskCreate工具调用失败的问题。

  问题:
  - 当使用OpenAI兼容API模型时,调用TaskCreate工具出现"InputValidationError: The required
  parameter `subject` is missing"错误
  - OpenAI兼容层没有正确处理deferred tools的过滤逻辑,导致工具schema没有被正确发送给模型

  修复:
  1. 在OpenAI兼容层中添加了与Anthropic API路径一致的deferred tools处理逻辑
  2. 导入必要的工具搜索相关函数: isToolSearchEnabled, extractDiscoveredToolNames,
  isDeferredTool等
  3. 实现工具过滤逻辑:
     - 检查工具搜索是否启用
     - 构建deferred tools集合
     - 过滤工具列表: 只包含非deferred工具或已发现的deferred工具
     - 为deferred tools设置deferLoading标志
  4. 修正了extractDiscoveredToolNames函数的导入路径错误

  影响:
  - 解决了TaskCreate工具调用时的参数验证错误
  - 确保OpenAI兼容层与Anthropic API路径在处理deferred tools时行为一致
  - 支持工具搜索功能在OpenAI兼容模式下正常工作

  修改的文件:
  - src/services/api/openai/index.ts - 主要修复文件

  测试建议:
  1. 使用OpenAI兼容API模型时,TaskCreate工具应该可以正常调用
  2. 如果工具搜索功能启用,可能需要先使用ToolSearchTool来发现TaskCreate工具
  3. 验证工具调用时不再出现"InputValidationError"错误

  这个修复确保了当使用OpenAI兼容API(如Ollama、DeepSeek、vLLM等)时,deferred
  tools(如TaskCreate)能够被正确处理,解决了工具调用失败的问题。

* fix: 更新工具模式未发送提示,增加OpenAI兼容模型使用指南
2026-04-08 18:08:59 +08:00
Slayer
d52300ff44 完善沙箱文档 (#195)
* document sandbox design and behavior

* expand sandbox design details
2026-04-08 16:49:24 +08:00
claude-code-best
79b472f9d1 docs: update contributors 2026-04-08 06:06:29 +00:00
bonerush
bdea5a2632 fix: Fix deferred tools handling in OpenAI compatibility layer (#193)
* fix: reorder tool and user messages for OpenAI API compatibility (#168)
Fixes #168
OpenAI requires that an assistant message with tool_calls be immediately
followed by tool messages. Previously, convertInternalUserMessage
output user content before tool results, causing 400 errors.
Now tool messages are pushed first.

* fix: 修复OpenAI兼容层中deferred tools处理问题

  提交描述:
  修复了在使用OpenAI兼容API时TaskCreate工具调用失败的问题。

  问题:
  - 当使用OpenAI兼容API模型时,调用TaskCreate工具出现"InputValidationError: The required
  parameter `subject` is missing"错误
  - OpenAI兼容层没有正确处理deferred tools的过滤逻辑,导致工具schema没有被正确发送给模型

  修复:
  1. 在OpenAI兼容层中添加了与Anthropic API路径一致的deferred tools处理逻辑
  2. 导入必要的工具搜索相关函数: isToolSearchEnabled, extractDiscoveredToolNames,
  isDeferredTool等
  3. 实现工具过滤逻辑:
     - 检查工具搜索是否启用
     - 构建deferred tools集合
     - 过滤工具列表: 只包含非deferred工具或已发现的deferred工具
     - 为deferred tools设置deferLoading标志
  4. 修正了extractDiscoveredToolNames函数的导入路径错误

  影响:
  - 解决了TaskCreate工具调用时的参数验证错误
  - 确保OpenAI兼容层与Anthropic API路径在处理deferred tools时行为一致
  - 支持工具搜索功能在OpenAI兼容模式下正常工作

  修改的文件:
  - src/services/api/openai/index.ts - 主要修复文件

  测试建议:
  1. 使用OpenAI兼容API模型时,TaskCreate工具应该可以正常调用
  2. 如果工具搜索功能启用,可能需要先使用ToolSearchTool来发现TaskCreate工具
  3. 验证工具调用时不再出现"InputValidationError"错误

  这个修复确保了当使用OpenAI兼容API(如Ollama、DeepSeek、vLLM等)时,deferred
  tools(如TaskCreate)能够被正确处理,解决了工具调用失败的问题。
2026-04-08 12:56:10 +08:00
HitMargin
3683f22529 补全status界面里的信息 (#189)
* docs: update contributors

* docs: update contributors

* docs: update contributors

* docs: update contributors

* 添加status命令里更多模型api介绍

---------

Co-authored-by: HitMargin <hitmargin@qq.com>
2026-04-08 10:56:46 +08:00
claude-code-best
4e4111be92 Merge branch 'refactor/ink-v2' 2026-04-07 23:56:47 +08:00
claude-code-best
e86573ac2f fix: 修复 -r 模式下键盘输入无响应
两个根因:

1. earlyInput 的 readableHandler 残留在 stdin 上
   setAppCallbacks() 在反编译项目中从未被调用,导致
   stopCapturingEarlyInput() 是 no-op,readableHandler
   在 Ink 的 handleReadable 之前消费所有 stdin 数据。
   修复:在 handleSetRawMode(true) 时移除非自身的 readable listeners。

2. React 19 layout effect cleanup 顺序问题
   React 19 先运行新树的 layout effects,再清理旧树。
   当旧树(showSetupDialog)比新树(launchResumeChooser)
   有更多 useInput hooks 时,旧树 cleanup 把
   rawModeEnabledCount 降到 0,错误关闭 raw mode。
   修复:当 count=0 但仍有活跃 EventEmitter listeners 时恢复 count。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 23:54:09 +08:00
claude-code-best
3e1c6bcc3f Merge branch 'main' into refactor/ink-v2 2026-04-07 22:41:35 +08:00
claude-code-best
cf26c73e39 docs: update contributors 2026-04-07 14:41:24 +00:00
claude-code-best
d6bfc34b71 fix: 修复 ant 模式 2026-04-07 22:40:59 +08:00
claude-code-best
91b9366f64 refactor: 大规模迁移原有组件到 ink 包内 2026-04-07 22:26:45 +08:00
claude-code-best
042e186b0b docs: update contributors 2026-04-07 11:54:11 +00:00
mcjjin
0d8f494c4b fix(computer-use): 修复权限检查和应用列表获取的问题 (#157)
* docs: update contributors

* fix(computer-use): 修复权限检查和应用列表获取的问题

修复 macOS 平台下权限检查的 JXA 回退逻辑,确保在没有原生模块时仍能正确检测权限
改进应用列表获取方式,使用 mdls 获取真实的 bundleId 而非生成伪 ID

* docs: update contributors

* docs: update contributors

* docs: update contributors

---------

Co-authored-by: mcjjin <8590489+mcjjin@users.noreply.github.com>
Co-authored-by: claude-code-best <claude-code-best@proton.me>
Co-authored-by: claude-code-best <272536312+claude-code-best@users.noreply.github.com>
2026-04-07 19:53:59 +08:00
bonerush
5d7e54751a fix: reorder tool and user messages for OpenAI API compatibility (#168) (#177)
Fixes #168
OpenAI requires that an assistant message with tool_calls be immediately
followed by tool messages. Previously, convertInternalUserMessage
output user content before tool results, causing 400 errors.
Now tool messages are pushed first.
2026-04-07 19:27:25 +08:00
claude-code-best
52a9cc0414 fix: 修复 ant 模式 2026-04-07 19:15:29 +08:00
claude-code-best
f268b16b31 feat: 将 keybinding 纳入 ink 管辖 2026-04-07 17:51:01 +08:00
claude-code-best
e5782e732c Revert "Revert "feat: 第一个可以用的 ink 组件抽象 (#158)" (#175)"
This reverts commit 88d4c3ba24.
2026-04-07 16:17:48 +08:00
claude-code-best
4e1e681a46 fix: 删除 debug 限制 2026-04-07 16:13:15 +08:00
claude-code-best
a7d9a220bf fix: 修复 main 文件及 "production" 的问题 2026-04-07 16:13:15 +08:00
claude-code-best
dab0783941 docs: update contributors 2026-04-07 07:36:44 +00:00
Dosion
0c53796d15 feat: restore daemon supervisor and remoteControlServer command (#170)
Reverse-engineer the missing daemon + remoteControlServer implementation
by tracing the call chain from existing code:

- src/daemon/main.ts: restore from stub to full supervisor (spawn/monitor
  workers, exponential backoff restart, graceful shutdown)
- src/daemon/workerRegistry.ts: restore from stub to worker dispatcher
  (remoteControl kind → runBridgeHeadless())
- src/commands/remoteControlServer/: new slash command /remote-control-server
  (alias /rcs) for managing the daemon from REPL
- build.ts + scripts/dev.ts: enable DAEMON feature flag

Both official CLI 2.1.92 and our codebase had the command registered in
commands.ts but the directory and daemon implementation were missing.
The bottom layer (runBridgeHeadless in bridgeMain.ts) was already complete.

Co-authored-by: unraid <local@unraid.local>
2026-04-07 15:36:29 +08:00
guunergooner
4b44047931 fix: prevent iTerm2 terminal response sequences from leaking into REPL input (#172)
The earlyInput capture's escape sequence detection was too simplistic — it
only checked if the byte after ESC fell in 0x40-0x7E range, treating it as
a terminator. This caused DCS sequences (e.g. XTVERSION `\x1bP>|iTerm2
3.6.4\x1b\\`) and CSI parameter sequences (e.g. DA1 `\x1b[?64;...c`) to
partially leak into the input buffer as `>|iTerm2 3.6.4?64;1;2;4;6;17;18;21;22c`.

Fix by handling each escape sequence type per ECMA-48:
- CSI (`ESC [`): skip parameter + intermediate bytes, then final byte
- DCS/OSC/SOS/PM (`ESC P/]/X/^`): scan to BEL or ST terminator
- Other: keep single-byte skip

Closes #171

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-07 15:11:06 +08:00
claude-code-best
88d4c3ba24 Revert "feat: 第一个可以用的 ink 组件抽象 (#158)" (#175)
This reverts commit c445f43f8d.
2026-04-07 15:05:03 +08:00
claude-code-best
ca0c3265e6 docs: update contributors 2026-04-07 05:59:56 +00:00
uk0
70baa6f7db feat: add Grok (xAI) API adapter with custom model mapping (#152)
Add xAI Grok as a new API provider. Reuses OpenAI-compatible message/tool
converters and stream adapter with Grok-specific client and model mapping.

Default model mapping:
  opus   → grok-4.20-reasoning
  sonnet → grok-3-mini-fast
  haiku  → grok-3-mini-fast

Users can customize mapping via:
  - GROK_MODEL env var (override all)
  - GROK_MODEL_MAP env var (JSON family map, e.g. {"opus":"grok-4"})
  - GROK_DEFAULT_{FAMILY}_MODEL env vars

Activation: CLAUDE_CODE_USE_GROK=1 or modelType: "grok" in settings.json
Also integrates with /provider command for runtime switching.
2026-04-07 09:24:55 +08:00
claude-code-best
dfa7aa1d29 docs: update contributors 2026-04-06 15:57:02 +00:00
claude-code-best
c445f43f8d feat: 第一个可以用的 ink 组件抽象 (#158) 2026-04-06 23:56:45 +08:00
claude-code-best
3ea64eeb0f docs: update contributors 2026-04-06 14:09:43 +00:00
Dosion
33949ce5a2 Merge pull request #156 from amDosion/feat/ultraplan-enablement
feat: enable /ultraplan and harden GrowthBook fallback chain
2026-04-06 22:09:28 +08:00
claude-code-best
35bc4f395d Merge pull request #153 from amDosion/feat/growthbook-enablement
feat: enable GrowthBook local gate defaults for P0/P1 features
2026-04-06 17:18:59 +08:00
claude-code-best
379e40f12a fix: 回退全屏模式 2026-04-06 17:10:16 +08:00
unraid
1b47333d72 feat: enable GrowthBook local gate defaults for P0/P1 features
Add LOCAL_GATE_DEFAULTS mapping in growthbook.ts with 27 feature gate
defaults (25 boolean + 2 object config). Insert local defaults into the
fallback chain of all getter functions so they work regardless of whether
GrowthBook is enabled or disabled:

  env overrides → config overrides → in-memory cache → disk cache
  → LOCAL_GATE_DEFAULTS → caller defaultValue

P0 (local): keybindings, streaming tool exec, cron, JSON tools,
ultrathink, explore/plan agents, deep link, immediate model switch
P1 (API): session memory, auto memory, prompt suggestions, brief mode,
verification agent, away summary, auto dream, idle return prompt
Kill switches: 10 gates kept true to prevent remote disable

New compile flags: AGENT_TRIGGERS, ULTRATHINK, BUILTIN_EXPLORE_PLAN_AGENTS,
LODESTONE, EXTRACT_MEMORIES, VERIFICATION_AGENT, KAIROS_BRIEF, AWAY_SUMMARY

Bypass all local defaults: CLAUDE_CODE_DISABLE_LOCAL_GATES=1
2026-04-06 17:00:30 +08:00
claude-code-best
2c660daf2c docs: 加点 emoji 好看点 2026-04-06 15:07:21 +08:00
claude-code-best
4d62f6312a docs: update contributors 2026-04-06 06:59:29 +00:00
claude-code-best
dc8ce1bbb0 feat: 添加 interview 模式 2026-04-06 14:59:06 +08:00
claude-code-best
3fff2a0743 feat: 新增 teach-me skill 帮助大家学习 2026-04-06 14:34:44 +08:00
claude-code-best
dd2bd12626 feat: 为 project 级 skill 添加黄色 [local] 标签区分显示
在斜杠命令列表和 SkillsMenu 中,对 projectSettings/localSettings
来源的 skill 显示黄色 [local] 标签,方便区分项目级和用户级技能。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 14:34:44 +08:00
claude-code-best
ca630488c6 docs: update contributors 2026-04-06 06:18:59 +00:00
claude-code-best
f05a6c9fdd Merge pull request #129 from 2228293026/main
provider  (api) 指令查询/切换模型api类型 分离OpenAl和Anthropic模型的环境变量 分离 Gemini和Anthropic环境变量 通过github action更新contributors
2026-04-06 14:18:47 +08:00
HitMargin
767d6fae06 Merge branch 'claude-code-best:main' into main 2026-04-06 13:50:34 +08:00
claude-code-best
6e598fc4c9 Merge pull request #149 from uk0/fix/openai-tool-compat
fix: OpenAI adapter tool calling compatibility
2026-04-06 13:48:36 +08:00
uk0
e88dcb2f9e fix: OpenAI adapter tool calling compatibility
Two fixes for OpenAI-compatible provider compatibility:

1. Sanitize JSON Schema `const` → `enum` in tool parameters.
   Many OpenAI-compatible endpoints (Ollama, DeepSeek, vLLM, etc.)
   do not support the `const` keyword in JSON Schema. Recursively
   convert `const: value` to `enum: [value]` which is semantically
   equivalent.

2. Force stop_reason to `tool_use` when tool_calls are present.
   Some backends incorrectly return finish_reason "stop" even when
   the response contains tool_calls. Without this fix, the query
   loop treats the response as a normal end_turn and never executes
   the requested tools.
2026-04-06 13:31:28 +08:00
2228293026
7d88b4df97 docs: update contributors 2026-04-06 05:02:32 +00:00
HitMargin
fec8ec6abd fix: correct contributors link in README 2026-04-06 13:02:09 +08:00
HitMargin
5bf3c93895 feat: add contributors auto-update workflow
- Add GitHub Actions workflow to auto-generate contributors.svg
- Update README to use local contributors.svg file
- Use dynamic repository detection for forked repos

🤖 Generated with Claude Code
2026-04-06 12:55:19 +08:00
HitMargin
a15340f555 Merge branch 'claude-code-best:main' into main 2026-04-06 12:30:53 +08:00
HitMargin
eb62b4704e e 2026-04-06 12:23:59 +08:00
HitMargin
81ecd82b65 Test 2026-04-06 11:53:11 +08:00
claude-code-best
919011a372 fix: 修复 login 表单的 enter 覆盖问题 2026-04-06 11:28:01 +08:00
claude-code-best
3923af4834 fix: 修复 login 面板的左右切换能力 2026-04-06 11:23:49 +08:00
HitMargin
14dc54a093 gemini模型环境变量分离 provider指令支持切换gemini 2026-04-06 11:23:05 +08:00
claude-code-best
258cc720f4 docs: 新增留影文档 2026-04-06 11:04:13 +08:00
claude-code-best
fc0bebf6b3 fix MACRO fallback (#146) 2026-04-06 10:54:35 +08:00
claude-code-best
eca1acc662 feat: 支持 openai 图片兼容 2026-04-06 10:48:27 +08:00
HitMargin
6f80e96fee fix: make modelType take precedence over all env vars in getAPIProvider 2026-04-06 10:38:16 +08:00
HitMargin
a7a9659ddd 解决报错 2026-04-06 10:34:11 +08:00
claude-code-best
dee2ffd638 feat: 支持简化版本的 rg 下载 2026-04-06 10:31:15 +08:00
HitMargin
26245e0bd0 Merge branch 'main' into main 2026-04-06 10:21:02 +08:00
uk0
cd70c1b7fd fix MACRO fallback 2026-04-06 10:15:56 +08:00
claude-code-best
ced5080019 feat: 开启鼠标点击功能 2026-04-06 10:11:03 +08:00
yi7503
522a1a366d feat: enable Computer Use on Windows and Linux (#145)
Remove macOS-only guards so Computer Use works cross-platform:
- main.tsx: allow CHICAGO_MCP on any known platform (not just macos)
- swiftLoader.ts: remove darwin-only throw, let the backend handle it
- computer-use-input: dispatch to darwin/win32/linux backends
- computer-use-swift: rename loadDarwin→loadBackend, dispatch all platforms

Co-authored-by: yi7503 <yi7503@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 09:57:55 +08:00
SaltedFish555
0da5ec09e8 feat: 添加gemini协议适配 (#125)
* feat: 添加gemini协议适配

* Remove unrelated local files from Gemini PR
2026-04-06 09:55:20 +08:00
HitMargin
1f8f90eb62 Merge branch 'claude-code-best:main' into main 2026-04-05 22:18:21 +08:00
claude-code-best
27825293bb Merge pull request #140 from amDosion/feat/enable-safe-feature-flags
feat: enable SHOT_STATS, PROMPT_CACHE_BREAK_DETECTION, TOKEN_BUDGET
2026-04-05 21:10:50 +08:00
unraid
5916ecffdc docs: add DEV-LOG entry for feature flags enablement
Document the SHOT_STATS, TOKEN_BUDGET, PROMPT_CACHE_BREAK_DETECTION
enablement process including verification methodology, Codex review
findings, and key discoveries about audit report accuracy.
2026-04-05 21:10:15 +08:00
unraid
96f6d2c7d5 feat: enable SHOT_STATS, PROMPT_CACHE_BREAK_DETECTION, TOKEN_BUDGET feature flags
Enable 3 verified compile-only feature flags in build.ts and dev.ts defaults:

- SHOT_STATS: local shot distribution statistics in /stats panel
- PROMPT_CACHE_BREAK_DETECTION: internal cache key change diagnostics
- TOKEN_BUDGET: support +500k syntax for minimum output token targets

All 3 flags verified by 6 parallel sub-agents + independent Codex CLI review.
Build passes (475 files), zero new test failures.

Also adds:
- docs/features/feature-flags-codex-review.md: Codex review findings
- Marks all enabled flags in feature-flags-audit-complete.md
- Adds openai dependency (needed for OpenAI compat layer)
2026-04-05 21:07:38 +08:00
claude-code-best
2b84333913 Merge pull request #137 from amDosion/feat/computer-use-windows
feat: Computer Use v2 — 跨平台 Executor + Python Bridge + GUI 无障碍
2026-04-05 21:02:32 +08:00
HitMargin
ecac0ab978 Merge branch 'claude-code-best:main' into main 2026-04-05 20:12:04 +08:00
claude-code-best
ba97889c93 Merge pull request #135 from xuzhongpeng/fix/dev-script-path-resolution
fix: resolve absolute path in dev.ts for cross-directory execution
2026-04-05 19:39:28 +08:00
xuzhongpeng
714ef13e68 fix: resolve absolute path in dev.ts for cross-directory execution
The dev script previously used a relative path "src/entrypoints/cli.tsx" which would fail when executed from outside the project root directory.

Changes:
- Add path resolution using import.meta.url to locate project root
- Use absolute path for cli.tsx entry point
- Set cwd option in Bun.spawnSync to ensure correct working directory

This allows running "bun run /path/to/scripts/dev.ts" from any directory.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 18:04:12 +08:00
HitMargin
2f95d1a395 Merge branch 'claude-code-best:main' into main 2026-04-05 17:02:07 +08:00
claude-code-best
918defad44 Merge pull request #127 from xutianyi1999/main
fix: improve size calculation for LRU cache and handle nested object …
2026-04-05 15:50:58 +08:00
claude-code-best
4e5a0dd22f fix: 修复代码不能在终端高亮的问题 (#126)
* fix: 修复代码不能在终端高亮的问题

highlight.js v11 result = hljs().highlight(); 已经不存在result.emitter,使用result._emitter替代

* chore: update
2026-04-05 15:50:23 +08:00
unraid
c17edcb12e feat: Computer Use — Windows 跨平台支持 + GUI 无障碍增强 + Python Bridge
三平台 Computer Use (macOS + Windows + Linux),Windows 专项增强。

- MCP server: toolCalls/tools/executor/mcpServer 等 12 文件完整实现
- 平台抽象层: platforms/{win32,darwin,linux}.ts
- 跨平台 executor: executorCrossPlatform.ts
- CHICAGO_MCP + VOICE_MODE feature flags 启用

- windowMessage.ts: SendMessageW (WM_CHAR Unicode + 剪贴板粘贴)
- windowBorder.ts: 4 叠加窗口边框 (30fps 跟踪)
- uiAutomation.ts: UI Automation 元素树/点击/写值
- accessibilitySnapshot.ts: 无障碍快照 → 模型感知 GUI
- bridge.py + bridgeClient.ts: Python 长驻进程 (替代 per-call PS)

- window_management: min/max/restore/close/focus (Win32 API)
- click_element / type_into_element: 按名称操作 (无需坐标)
- 截图自动附带 Accessibility Snapshot

- 17 种方法, stdin/stdout JSON 通信
- 窗口枚举 1.5ms vs PS 500ms, 截图 360ms vs PS 800ms
- 依赖: mss + Pillow + pywinauto
2026-04-05 15:47:20 +08:00
unraid
7a2ade0a02 chore: add .agents/.codex/.omx to .gitignore 2026-04-05 15:38:45 +08:00
HitMargin
a50971f26f ConsoleOAuthFlow: 添加 base_url URL 格式验证 2026-04-05 14:17:40 +08:00
HitMargin
41f733a60f 验证 OAuth 流程中的 base_url 防止无效 URL 2026-04-05 13:58:50 +08:00
HitMargin
282f2f4367 删除误导注释 2026-04-05 13:37:12 +08:00
HitMargin
1e53943e06 修复小问题 2026-04-05 13:29:52 +08:00
HitMargin
a0141c1ba5 ConsoleOAuthFlow格式化恢复 2026-04-05 11:59:48 +08:00
sobird
c16fc62877 chore: update 2026-04-05 09:12:48 +08:00
HitMargin
eb6fbe518e 分离OpenAI和Anthropic模型的环境变量 2026-04-05 03:31:06 +08:00
xutianyi
354c11f035 fix: improve size calculation for LRU cache and handle nested object content 2026-04-05 01:43:18 +08:00
sobird
d3a607e4e5 fix: 修复代码不能在终端高亮的问题
highlight.js v11 result = hljs().highlight(); 已经不存在result.emitter,使用result._emitter替代
2026-04-05 01:37:21 +08:00
HitMargin
ec5dfed19e fix provider指令切换模型类型 2026-04-05 00:53:04 +08:00
HitMargin
c33d5dcb1a Merge branch 'claude-code-best:main' into main 2026-04-04 23:34:02 +08:00
claude-code-best
f49c7d7e8c Revert "docs: 更新 README,新增 Run.ps1/TODO.md,删除 V6.md"
This reverts commit 32804623e0.
2026-04-04 23:31:21 +08:00
HitMargin
0c9fd37e01 Merge branch 'claude-code-best:main' into main 2026-04-04 23:30:38 +08:00
claude-code-best
5b1a52b8e0 更新大量 tsx 原始文件; 已经迁移 login panel; 部分 (#121)
* style(B1-1): 格式化 ink/buddy/cli/context/screens/tasks/services/keybindings/state (43 files)

纯格式化:移除分号、React Compiler import、import 多行展开。
修复了 Box.tsx 和 ScrollBox.tsx 中无效的 global.d.ts import。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style(B1-2): 格式化 commands (79 files)

纯格式化:移除分号、React Compiler import、import 多行展开。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style(B1-3): 格式化 components/messages,permissions,mcp,sandbox,shell (104 files)

纯格式化:移除分号、React Compiler import、import 多行展开。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style(B1-4): 格式化 components/PromptInput,FeedbackSurvey,tasks,agents,skills,design-system,wizard (73 files)

纯格式化:移除分号、React Compiler import、import 多行展开。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style(B1-5): 格式化 components其余 + hooks + tools (232 files)

纯格式化:移除分号、React Compiler import、import 多行展开。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style(B1-6): 格式化 main/entrypoints/utils/moreright (21 files)

纯格式化:移除分号、React Compiler import、import 多行展开。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: 更新 README,新增 Run.ps1/TODO.md,删除 V6.md

- README.md: 大幅重写,更详细版本历史和配置示例
- Run.ps1: 新增 Windows 启动脚本
- TODO.md: 新增包完成清单
- V6.md: 删除(架构重构规划已不适用)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 修复以前的问题

* fix: 修复 login 面板的问题

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 23:24:27 +08:00
HitMargin
b5d1dbc9d0 provider指令切换模型类型 2026-04-04 23:15:49 +08:00
HitMargin
ad104449f9 Merge branch 'claude-code-best:main' into main 2026-04-04 21:11:29 +08:00
claude-code-best
02694918b5 docs: 更新文档及构建脚本 2026-04-04 21:09:21 +08:00
HitMargin
e548369f14 ReWrite 2026-04-04 19:14:06 +08:00
HitMargin
3ae973c7e2 ReWrite 2026-04-04 19:11:25 +08:00
HitMargin
7631c0f463 Merge remote main and resolve conflicts 2026-04-04 19:06:31 +08:00
HitMargin
4fa758240d Merge branch 'claude-code-best:main' into main 2026-04-04 17:04:28 +08:00
claude-code-best
c99021d5a3 fix: 尝试修复 windows 下面没有 unzip 的问题 2026-04-04 17:02:39 +08:00
HitMargin
affc826b78 Merge branch 'claude-code-best:main' into main 2026-04-04 16:49:30 +08:00
claude-code-best
d720580e75 docs: 添加对 rg 下载的提示 2026-04-04 16:44:45 +08:00
claude-code-best
bd6707ad14 Merge remote-tracking branch 'AgentArc/main' 2026-04-04 16:43:01 +08:00
claude-code-best
e8f417e59f Merge remote-tracking branch 'origin/feature/computer-use/mac-support' 2026-04-04 16:42:51 +08:00
claude-code-best
f83198e506 feat: 删除 npm deprecation-warning 的黄色指引 2026-04-04 16:40:10 +08:00
claude-code-best
462fe69d80 fix: 修复 openai 的 cost 计算问题 2026-04-04 16:37:50 +08:00
claude-code-best
ab7556e355 feat: auto dream 开启 2026-04-04 16:28:09 +08:00
claude-code-best
ea06f50749 docs: 添加 computer use 的说明 2026-04-04 15:53:48 +08:00
arc
840d4574da fix issues/79: F5 直接调试 2026-04-04 14:57:31 +08:00
arc
6a3fd223fc fix issues/114: bun install报错download-ripgrep MODULE_NOT_FOUND 2026-04-04 14:49:04 +08:00
claude-code-best
765569b3cf feat: 更新 Computer Use 用户指南,添加 macOS 和 Windows 支持文档链接 2026-04-04 12:24:11 +08:00
claude-code-best
ad1f90a00e feat: 恢复 mac 版本的 Computer Use 2026-04-04 11:36:43 +08:00
HitMargin
dfe25b1885 Merge branch 'claude-code-best:main' into main 2026-04-04 10:58:52 +08:00
HitMargin
6fefff2ef2 claude-code with OpenAI mode fix (#102)
Co-authored-by: HitMargin <hitmargin@qq.com>
2026-04-04 10:54:13 +08:00
claude-code-best
419d1e8bcc docs: 更新 CLAUDE.md 2026-04-04 10:39:14 +08:00
claude-code-best
fc9faa2af2 docs: 更新文档 2026-04-04 09:57:41 +08:00
HitMargin
21b2854537 1.0.4 2026-04-04 03:11:50 +08:00
HitMargin
fa5329db20 Merge remote main: keep OpenAI fix 2026-04-04 02:13:10 +08:00
HitMargin
c9f95fc34d claude-code with OpenAI mode fix 2026-04-04 01:21:00 +08:00
claude-code-best
a67b4a40b0 docs: 更新最新说明 2026-04-04 00:16:13 +08:00
Dosion
913702d97e feat: built-in status line with usage quota display (#89)
* feat: built-in status line with usage quota display

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 00:15:23 +08:00
claude-code-best
86d2c8f9e8 Merge remote-tracking branch 'amDosion/feat/computer-use-windows' 2026-04-04 00:12:52 +08:00
claude-code-best
131465097f Merge branch 'pr/amDosion/92' 2026-04-04 00:12:15 +08:00
unraid
ca086b045a fix: resolve Windows Computer Use request_access and screenshot errors
Two root causes fixed:

1. swiftLoader.ts: require('@ant/computer-use-swift') returns a module
   with { ComputerUseAPI } class, not an instance. macOS native .node
   exports a plain object. Fixed by detecting class export and calling
   new ComputerUseAPI().

2. executor.ts resolvePrepareCapture: toolCalls.ts expects result to have
   { hidden: string[], displayId: number } fields. Our ComputerUseAPI
   returns { base64, width, height } only. Fixed by backfilling missing
   fields with defaults.

Verified: request_access → screenshot → left_click all work on Windows.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 00:09:51 +08:00
claude-code-best
52d8b83b24 docs: 更新 Readme 2026-04-04 00:03:58 +08:00
claude-code-best
8cb1a15ca5 Merge branch 'pr/amDosion/93' 2026-04-04 00:00:40 +08:00
claude-code-best
8cef1b6a93 Merge remote-tracking branch 'amDosion/feat/enable-chrome-mcp' 2026-04-04 00:00:34 +08:00
unraid
3707c3c0ba feat: Windows Computer Use enhancement — PrintWindow, UI Automation, OCR
New Windows-native capabilities:
- windowCapture.ts: PrintWindow API for per-window screenshot (works on
  occluded/background windows)
- windowEnum.ts: EnumWindows for precise window enumeration with HWND
- uiAutomation.ts: IUIAutomation for UI tree reading, element clicking,
  text input, and coordinate-based element identification
- ocr.ts: Windows.Media.Ocr for screen text recognition (en-US + zh-CN)

Updated win32.ts backend to use EnumWindows for listRunning() and added
captureWindowTarget() for window-specific screenshots.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 00:00:02 +08:00
claude-code-best
4c0b2aaedb feat: 绕过 Claude Code 内的 claude 的账号需要; 但是浏览器扩展还是要权限 2026-04-03 23:57:27 +08:00
JiayuWang(王嘉宇)
fdb2442ad4 test: add coverage for toRelativePath and getDirectoryForPath (#95)
These two exported functions in src/utils/path.ts lacked unit tests.

toRelativePath wraps Node's path.relative() and keeps the absolute
path when the result would start with '..' (i.e. the target is outside
the CWD). Four tests cover: child-of-cwd, outside-cwd, cwd-itself,
and the type-safety invariant.

getDirectoryForPath uses statSync to distinguish directories from files,
falling back to dirname() for non-existent paths and bypassing the
filesystem for UNC paths (NTLM credential-leak prevention). Three tests
cover: existing directory, known file, and non-existent path.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 23:36:19 +08:00
claude-code-best
00b044e8b2 支持 OpenAI Chat 兼容协议 (#99)
* feat: 完成 openai 接口兼容

* feat: 完成 openai 协议兼容

* fix: 修复测试用例
2026-04-03 23:33:17 +08:00
unraid
e3264a1691 feat: enable Computer Use with macOS + Windows + Linux support
Phase 1: Replace @ant/computer-use-mcp stub (12 files, 6517 lines).

Phase 2: Remove 8 macOS-only guards in src/:
- main.tsx: remove getPlatform()==='macos' check
- swiftLoader.ts: remove darwin-only throw
- executor.ts: extend platform guard, clipboard dispatch, paste key
- drainRunLoop.ts: skip CFRunLoop pump on non-darwin
- escHotkey.ts: non-darwin returns false (Ctrl+C fallback)
- hostAdapter.ts: non-darwin permissions granted
- common.ts: dynamic platform + screenshotFiltering
- gates.ts: enabled:true, subscription check removed

Phase 3: Add Linux backends (xdotool/scrot/xrandr/wmctrl):
- computer-use-input/backends/linux.ts (173 lines)
- computer-use-swift/backends/linux.ts (278 lines)

Verified on Windows x64: mouse, screenshot, displays, foreground app.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 23:17:14 +08:00
JiayuWang(王嘉宇)
465e9f01c6 test: add coverage for formatRelativeTimeAgo and formatLogMetadata (#94)
These two exported functions in src/utils/format.ts had no test
coverage. formatRelativeTimeAgo wraps formatRelativeTime and forces
numeric:'always' for past dates; formatLogMetadata assembles parts
(time, branch, size/count, tag, agentSetting, prNumber) into a
' · '-separated string.

Added 8 tests for formatRelativeTimeAgo covering past dates, future
dates, equal-to-now, and the no-'ago'-for-future invariant. Added
9 tests for formatLogMetadata covering all optional fields and the
separator format.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 22:17:58 +08:00
unraid
6738a76152 feat: enable Claude in Chrome MCP with full browser control
Replace the 6-line stub in @ant/claude-for-chrome-mcp with the complete
implementation (8 files, 3038 lines) from the reference project.

Provides 17 browser tools: navigate, screenshot, click, type, read DOM,
execute JS, record GIF, monitor console/network, manage tabs, etc.

No feature flag needed. No changes to src/ (already matches official).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 21:46:07 +08:00
unraid
7ae94327fb feat: enable /voice mode with native audio binaries
Restore voice input by:
- Copying official cpal-based audio-capture.node binaries (6 platforms)
- Replacing SoX subprocess stub with native .node loader
- Adding VOICE_MODE to default build features

All voice source files in src/ already match the official CLI.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 21:14:44 +08:00
claude-code-best
29db9d99de docs: 添加文本好使一些 2026-04-03 20:57:33 +08:00
claude-code-best
9e6fe9b410 feat: 添加 discord 群 2026-04-03 20:55:58 +08:00
claude-code-best
4a9e9185b1 docs: 更新文档 2026-04-03 20:23:51 +08:00
claude-code-best
2cc626c1c3 fix: 修复测试文件 2026-04-03 20:11:09 +08:00
Dosion
eb86e34094 Merge pull request #88 from amDosion/feat/enable-schedule-remote-agents
feat: enable /schedule by adding AGENT_TRIGGERS_REMOTE to default features
2026-04-03 20:07:21 +08:00
claude-code-best
4c5a12228c docs: 调整文档 2026-04-03 19:56:35 +08:00
claude-code-best
a6bef45113 fix: 修复 rg 文件的传入 2026-04-03 19:45:43 +08:00
claude-code-best
7e888ce38d feat: 添加 测试 agent 及一些文档 2026-04-03 19:27:23 +08:00
claude-code-best
5a7d06fe99 refactor(buddy): align companion system with official CLI (#82)
* refactor(buddy): align companion system with official CLI

## Summary

Reverse-engineered the official Claude Code CLI (v2.1.91) buddy/companion
system and aligned our implementation to match.

## Changes (7 files)

### Added
- `src/buddy/CompanionCard.tsx` (+109)
  JSX bordered card matching official vc8: rarity header, colored sprite,
  name, personality, 10-bar stats, last reaction in nested border.

- `src/buddy/companionReact.ts` (+156)
  Reaction system matching official ZUK+Dc8: 45s rate limiting, @-mention
  detection, transcript builder (12 msgs, 5000 chars), POST buddy_react API.

### Modified
- `src/commands/buddy/index.ts`
  type: local -> local-jsx, description/argumentHint/immediate/isHidden.

- `src/commands/buddy/buddy.ts`
  LocalCommandCall -> LocalJSXCommandCall signature (onDone, context, args).
  Removed mute/unmute/rehatch (official uses off/on only).
  /buddy show returns CompanionCard JSX instead of plain text.
  Pet auto-unmutes. companionMuted writes globalConfig (matches UI read source).

- `src/screens/REPL.tsx` (line 2808)
  globalThis.fireCompanionObserver -> import triggerCompanionReaction.

- `src/state/AppStateStore.ts` — comment fix.
- `src/types/global.d.ts` — removed fireCompanionObserver declaration.

## Data flow (verified consistent)
- companionMuted: saveGlobalConfig() <-> getGlobalConfig() (6 read sites)
- companionReaction: setAppState() <-> useAppState() (4 sites)
- companionPetAt: setAppState() <-> useAppState() (2 sites)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(buddy): address CodeRabbit review findings

- buddy.ts: return type Promise<null> → Promise<React.ReactNode>
  to match LocalJSXCommandCall interface (CompanionCard path returns
  ReactElement, not null).
- CompanionCard.tsx: clamp stat value to 0..100 before .repeat()
  to prevent negative count runtime error on out-of-range values.

Import path alias suggestions (src/ vs ../) dismissed — project
convention uses relative paths (verified against color.ts, help.ts).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(buddy): address second round CodeRabbit findings

- buddy.ts:105: remove unsafe (context as any).messages cast.
  ToolUseContext already declares messages: Message[] at Tool.ts:250,
  so context.messages is properly typed. Other commands (feedback,
  copy, export) access it the same way without cast.

- companionReact.ts:154: wrap resp.json() in try/catch for defensive
  JSON parsing. Malformed 200 responses now return null instead of
  propagating to the outer catch.

Rate-limit timing (set before API call) kept as-is — matches official
ZUK pattern: prevents retry-storm on transient failures.

src/ path alias suggestions dismissed — project uses relative paths.
Auto-unmute on /buddy view kept — matches official behavior.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: unraid <local@unraid.local>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 17:22:54 +08:00
claude-code-best
cf44cc32e4 Merge branch 'pr/amDosion/60' 2026-04-03 17:21:09 +08:00
unraid
e74d1f0836 fix(buddy): address second round CodeRabbit findings
- buddy.ts:105: remove unsafe (context as any).messages cast.
  ToolUseContext already declares messages: Message[] at Tool.ts:250,
  so context.messages is properly typed. Other commands (feedback,
  copy, export) access it the same way without cast.

- companionReact.ts:154: wrap resp.json() in try/catch for defensive
  JSON parsing. Malformed 200 responses now return null instead of
  propagating to the outer catch.

Rate-limit timing (set before API call) kept as-is — matches official
ZUK pattern: prevents retry-storm on transient failures.

src/ path alias suggestions dismissed — project uses relative paths.
Auto-unmute on /buddy view kept — matches official behavior.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 17:16:16 +08:00
claude-code-best
9dd180dcd3 Merge branch 'pr/amDosion/82' 2026-04-03 17:14:14 +08:00
unraid
7d4adce1b6 fix(buddy): address CodeRabbit review findings
- buddy.ts: return type Promise<null> → Promise<React.ReactNode>
  to match LocalJSXCommandCall interface (CompanionCard path returns
  ReactElement, not null).
- CompanionCard.tsx: clamp stat value to 0..100 before .repeat()
  to prevent negative count runtime error on out-of-range values.

Import path alias suggestions (src/ vs ../) dismissed — project
convention uses relative paths (verified against color.ts, help.ts).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 17:00:01 +08:00
claude-code-best
c9c14c816f feat: 简化 debug 方式 2026-04-03 16:47:24 +08:00
unraid
991119491c refactor(buddy): align companion system with official CLI
## Summary

Reverse-engineered the official Claude Code CLI (v2.1.91) buddy/companion
system and aligned our implementation to match.

## Changes (7 files)

### Added
- `src/buddy/CompanionCard.tsx` (+109)
  JSX bordered card matching official vc8: rarity header, colored sprite,
  name, personality, 10-bar stats, last reaction in nested border.

- `src/buddy/companionReact.ts` (+156)
  Reaction system matching official ZUK+Dc8: 45s rate limiting, @-mention
  detection, transcript builder (12 msgs, 5000 chars), POST buddy_react API.

### Modified
- `src/commands/buddy/index.ts`
  type: local -> local-jsx, description/argumentHint/immediate/isHidden.

- `src/commands/buddy/buddy.ts`
  LocalCommandCall -> LocalJSXCommandCall signature (onDone, context, args).
  Removed mute/unmute/rehatch (official uses off/on only).
  /buddy show returns CompanionCard JSX instead of plain text.
  Pet auto-unmutes. companionMuted writes globalConfig (matches UI read source).

- `src/screens/REPL.tsx` (line 2808)
  globalThis.fireCompanionObserver -> import triggerCompanionReaction.

- `src/state/AppStateStore.ts` — comment fix.
- `src/types/global.d.ts` — removed fireCompanionObserver declaration.

## Data flow (verified consistent)
- companionMuted: saveGlobalConfig() <-> getGlobalConfig() (6 read sites)
- companionReaction: setAppState() <-> useAppState() (4 sites)
- companionPetAt: setAppState() <-> useAppState() (2 sites)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 16:36:22 +08:00
claude-code-best
7935bfb4b8 fix: 修复debug启动方式 2026-04-03 14:40:45 +08:00
claude-code-best
a7604f6591 feat: /login 命令新增自定义 anthropic 终端登陆 2026-04-03 14:22:47 +08:00
claude-code-best
a02a9fc4c2 fix: 修复定义导入缺失的问题 2026-04-03 14:14:35 +08:00
claude-code-best
e944633dd8 fix: 修复 ERROR getAntModels is not defined
Fixes #69
2026-04-03 11:56:49 +08:00
claude-code-best
cb046b4df0 docs: 添加文档 2026-04-03 11:52:14 +08:00
unraid
67caa5d017 docs: add Remote Control (BRIDGE_MODE) entry to DEV-LOG
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 11:30:58 +08:00
claude-code-best
8e4aea45a8 docs: 维护两个新的文档 2026-04-03 11:01:17 +08:00
claude-code-best
5278ce1f3a docs: 新增两份文档 2026-04-03 10:56:52 +08:00
claude-code-best
e74c009e02 feat: 添加 GrowthBook 自定义服务器适配器
通过 CLAUDE_GB_ADAPTER_URL/KEY 环境变量连接自定义 GrowthBook 实例,
无配置时所有 feature 读取返回代码默认值。支持 GrowthBook Cloud(非 remoteEval),
含完整文档和 feature key 列表。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 10:37:15 +08:00
claude-code-best
78144b4dba feat: 关闭 Datadog 日志发送 2026-04-03 09:49:59 +08:00
claude-code-best
e32c159f35 feat: 关闭自动更新 2026-04-03 09:39:32 +08:00
claude-code-best
119518599e feat: 更新 sentry 错误上报 2026-04-03 09:39:25 +08:00
unraid
e784f231d4 fix: validate and encode target sessionId in peer messages
- Trim and normalize target before use
- Validate with validateBridgeId allowlist (same as bridgeApi.ts)
- URL-encode compatTarget to prevent path traversal/injection

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 04:23:32 +08:00
unraid
8645d37b25 fix: add Authorization header to peer message requests
getBridgeAccessToken() provides the OAuth Bearer token, matching
the auth pattern used by bridgeApi.ts and codeSessionApi.ts.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 04:15:24 +08:00
unraid
1d38eae536 fix: address CodeRabbit review findings
- webhookSanitizer: redact before truncate to avoid split secrets at boundary
- webhookSanitizer: return safe placeholder on error instead of raw content
- peerSessions: use discriminated union return type for type safety

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 04:08:04 +08:00
unraid
74e51e7e73 feat: enable Remote Control (BRIDGE_MODE) with stub completions
- Add BRIDGE_MODE to DEFAULT_FEATURES in dev.ts
- Implement peerSessions.ts: cross-session messaging via bridge API
- Implement webhookSanitizer.ts: redact secrets from webhook payloads
- Replace any stubs in controlTypes.ts with Zod schema-inferred types
- Fix tengu_bridge_system_init default to true for app "active" status

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 03:50:36 +08:00
claude-code-best
1f0a2e44c8 feat: 完成 debug 配置 2026-04-03 01:11:14 +08:00
claude-code-best
e48da3956c feat: 修正 web search 工具 2026-04-03 00:47:37 +08:00
claude-code-best
d04e00fc2c feat: 调整预先检查的代码 2026-04-02 23:00:48 +08:00
claude-code-best
c252294dd7 feat: 移除反蒸馏代码 2026-04-02 22:56:23 +08:00
claude-code-best
5ee49fd106 docs: 添加一大堆 feature 的描述 2026-04-02 22:52:32 +08:00
claude-code-best
22ca3a1181 Merge remote-tracking branch 'origin/main' 2026-04-02 21:57:12 +08:00
claude-code-best
919cf55591 feat: 添加开发者默认开启的 feature 2026-04-02 21:48:50 +08:00
mingyangxu46-prog
b6f37082cf Learn/20260401 (#39)
* docs: 添加 Claude Code 源码学习笔记(第一、二阶段)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 21:47:49 +08:00
claude-code-best
4337b82e6c Merge branch 'pr/programming-pupil/33' 2026-04-02 21:41:55 +08:00
claude-code-best
7dfbcd0e79 feat: 更新 buddy 的一些功能 2026-04-02 21:41:19 +08:00
claude-code-best
0d0304d6a5 Merge branch 'pr/smallflyingpig/36' 2026-04-02 21:38:12 +08:00
claude-code-best
47d88478c9 docs: 修正 feature 的正确用法 2026-04-02 21:37:30 +08:00
claude-code-best
70f32e25f3 Merge branch 'main' into pr/smallflyingpig/36
# Conflicts:
#	src/entrypoints/cli.tsx
2026-04-02 21:25:53 +08:00
claude-code-best
87fdd455cc chore: 删除调试代码 2026-04-02 21:23:36 +08:00
claude-code-best
991ccc673c chore: 删除 src 下面的 src 2026-04-02 21:22:31 +08:00
claude-code-best
be82b71c3e feat: 补全 auto mode 分类器 prompt 模板,支持 FEATURE_* 环境变量注入
- 重建 yolo-classifier-prompts/ 三个缺失的 prompt 文件
- dev.ts/build.ts 扫描 FEATURE_* 环境变量注入 Bun --feature
- AUTO_MODE_ENABLED_DEFAULT 由 feature flag 决定,开 feature 即开 auto mode
- 补充 docs/safety/auto-mode.mdx prompt 模板章节

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 21:18:39 +08:00
claude-code-best
88b45e0e6c chore: 删除垃圾脚本 2026-04-02 21:00:41 +08:00
claude-code-best
68ccf28be8 feat: 尝试修复 auto mode 2026-04-02 20:57:52 +08:00
claude-code-best
4ab4506de2 fix: 修复 USER_TYPE=ant 时 TUI 无法启动的问题
反编译版本中 global.d.ts 声明的全局函数运行时未定义,
通过显式 import、stub 组件和全局 polyfill 修复。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 20:31:04 +08:00
claude-code-best
ce29527a67 test: 添加一大堆测试文件 2026-04-02 20:28:08 +08:00
claude-code-best
6f5623b26c docs: 完成新版测试文档 2026-04-02 17:37:06 +08:00
claude-code-best
ac1f02958c fix: 批量修正 external 字面量 2026-04-02 17:01:39 +08:00
claude-code-best
799dacc407 test: 新增一波测试文件 2026-04-02 16:21:24 +08:00
claude-code-best
8697c91668 feat: 完成测试 16-17 2026-04-02 16:03:20 +08:00
claude-code-best
1086f68381 docs: 增加测试及 auto mode 文档 2026-04-02 15:06:51 +08:00
claude-code-best
006ad97fbb test: 新增测试代码文件 2026-04-02 14:44:56 +08:00
claude-code-best
9c3803d16b docs: 指定测试计划 2026-04-02 14:14:35 +08:00
Jiguo Li
e815002f96 Merge branch 'main' into main 2026-04-02 13:35:28 +08:00
claude-code-best
5fda87246d docs: 更新一下文档 2026-04-02 11:33:15 +08:00
claude-code-best
3c5eb0edbd Merge branch 'test/test-most-core-func' 2026-04-02 11:32:17 +08:00
编程界的小学生
2e4d6e2122 Update hooks.ts 2026-04-02 11:12:36 +08:00
Jiguo Li
4d1bc87eb4 Merge branch 'claude-code-best:main' into main 2026-04-02 10:12:49 +08:00
claude-code-best
4f323efb61 test: Phase 5 — 添加 12 个测试文件 (+209 tests, 1177 total)
新增覆盖: effort, tokenBudget, displayTags, taggedId,
controlMessageCompat, MCP normalization/envExpansion,
gitConfigParser, formatBriefTimestamp, hyperlink, windowsPaths, notebook

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 10:11:43 +08:00
claude-code-best
28e40ddc67 refactor: 用 Bun 原生 define 替换 cli.tsx 中的 globalThis 注入
- 删除 cli.tsx 顶部的 globalThis.MACRO / BUILD_* / feature polyfill
- 新增 scripts/defines.ts 作为 MACRO define 映射的单一来源
- 新增 scripts/dev.ts,通过 bun run -d 在转译时注入 MACRO 常量
- build.ts 引用 getMacroDefines() 实现构建时内联
- 清理 global.d.ts (移除 BUILD_*, MACRO 函数声明)
- 55 个 MACRO 消费文件零改动

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 09:51:48 +08:00
claude-code-best
21ac9e441f test: Phase 2-4 — 添加 12 个测试文件 (+321 tests, 968 total)
Phase 2 (轻 Mock): envUtils, sleep/sequential, memoize, groupToolUses, dangerousPatterns, outputLimits
Phase 3 (补全): zodToJsonSchema, PermissionMode, envValidation
Phase 4 (工具模块): mcpStringUtils, destructiveCommandWarning, commandSemantics

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 09:29:01 +08:00
claude-code-best
2d9c2adce3 docs: 排查 test 文件夹 2026-04-02 09:14:49 +08:00
claude-code-best
acfaac5f14 test: Phase 1 — 添加 8 个纯函数测试文件 (+134 tests)
- errors.test.ts: 28 tests (isAbortError, toError, errorMessage, getErrnoCode, isFsInaccessible, classifyAxiosError 等)
- shellRuleMatching.test.ts: 22 tests (permissionRuleExtractPrefix, hasWildcards, matchWildcardPattern, parsePermissionRule 等)
- argumentSubstitution.test.ts: 18 tests (parseArguments, parseArgumentNames, generateProgressiveArgumentHint, substituteArguments)
- CircularBuffer.test.ts: 12 tests (add, addAll, getRecent, toArray, clear, length)
- sanitization.test.ts: 14 tests (partiallySanitizeUnicode, recursivelySanitizeUnicode)
- slashCommandParsing.test.ts: 8 tests (parseSlashCommand)
- contentArray.test.ts: 6 tests (insertBlockAfterToolResults)
- objectGroupBy.test.ts: 5 tests (objectGroupBy)

总计:781 tests / 40 files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 08:50:29 +08:00
claude-code-best
2ca56977bf Merge pull request #30 from claude-code-best/test/test-most-core-func
Test/test most core func
2026-04-02 08:50:23 +08:00
claude-code-best
91c5bea27a docs: 添加后续测试覆盖计划 (Phase 1-4)
4 个阶段共计 ~213 tests / 20 files,目标从 647 提升至 ~860 tests

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 08:46:09 +08:00
claude-code-best
717cc55195 docs: 更改 readme 2026-04-02 08:43:01 +08:00
claude-code-best
0d89079694 docs: 更新测试覆盖状态至 647 tests / 32 files
- 新增 json/truncate/path/tokens/FileEditTool/permissions 测试记录
- 更新已知限制(Bun.JSONL bug, spawnMultiAgent 重依赖)
- 添加 Mock 策略总结章节

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 08:08:35 +08:00
claude-code-best
a28a44f9f7 test: 添加 FileEditTool/permissions/filterToolsByDenyRules 测试
- FileEditTool/utils.test.ts: 24 tests (normalizeQuotes, stripTrailingWhitespace, findActualString, preserveQuoteStyle, applyEditToFile)
- permissions/permissions.test.ts: 13 tests (getDenyRuleForTool, getAskRuleForTool, getDenyRuleForAgent, filterDeniedAgents)
- tools.test.ts: 扩展 5 tests (filterToolsByDenyRules 过滤逻辑)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 07:36:50 +08:00
claude-code-best
43af260322 test: 添加 json/truncate/path/tokens 模块测试
- json.test.ts: 27 tests (safeParseJSON, safeParseJSONC, parseJSONL, addItemToJSONCArray)
- truncate.test.ts: 24 tests (truncateToWidth, truncateStartToWidth, truncatePathMiddle, truncate, wrapText)
- path.test.ts: 15 tests (containsPathTraversal, normalizePathForConfigKey)
- tokens.test.ts: 22 tests (getTokenCountFromUsage, getTokenUsage, tokenCountFromLastAPIResponse, etc.)

使用 mock.module() 切断 log.ts/tokenEstimation.ts/slowOperations.ts 重依赖链

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 23:56:37 +08:00
claude-code-best
fd2ad71a4e docs: 更新测试规范,记录当前 517 个测试的覆盖状态
在 testing-spec.md 新增第 11 节,按 P0/P1/P2 分类记录 25 个
测试文件的覆盖范围、测试数量及已知的重依赖限制。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:50:47 +08:00
claude-code-best
c57950e15e test: 添加消息处理单元测试 (测试计划 06)
为消息创建、查询、文本提取、规范化等函数添加 56 个测试用例,
覆盖 createAssistantMessage、createUserMessage、isSyntheticMessage、
extractTag、isNotEmptyMessage、normalizeMessages 等核心功能。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:43:31 +08:00
claude-code-best
183421361e test: 添加配置与设置系统单元测试 (测试计划 09)
为 SettingsSchema、PermissionsSchema、AllowedMcpServerEntrySchema
验证,MCP 类型守卫,设置常量函数,以及 validation 工具函数添加
62 个测试用例。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:39:21 +08:00
claude-code-best
3df4b95ff9 test: 添加 Git 工具函数单元测试 (测试计划 08)
为 normalizeGitRemoteUrl 添加 18 个测试用例,覆盖 SSH、HTTPS、
ssh://、CCR 代理 URL 格式、大小写规范化及边界条件。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:30:45 +08:00
claude-code-best
f81a767f83 test: 添加 Cron 调度单元测试 (测试计划 07)
覆盖 parseCronExpression、computeNextCronRun、cronToHuman,
包含有效/无效表达式、字段范围验证、下次运行计算、人类可读描述,
共 38 个测试用例。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:23:26 +08:00
claude-code-best
25839ab454 test: 添加模型路由单元测试 (测试计划 05)
覆盖 isModelAlias、isModelFamilyAlias、getAPIProvider、
isFirstPartyAnthropicBaseUrl、firstPartyNameToCanonical,共 40 个测试用例。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:20:25 +08:00
claude-code-best
583d04331b test: 添加权限规则解析器单元测试 (测试计划 04)
覆盖 escapeRuleContent、unescapeRuleContent、permissionRuleValueFromString、
permissionRuleValueToString、normalizeLegacyToolName,共 25 个测试用例。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:18:00 +08:00
claude-code-best
c4344c4df0 test: 添加 Context 构建单元测试 (测试计划 03)
覆盖 stripHtmlComments、isMemoryFilePath、getLargeMemoryFiles、
buildEffectiveSystemPrompt 等函数,共 25 个测试用例全部通过。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:14:23 +08:00
claude-code-best
cad6409bfe test: 添加 Utils 纯函数单元测试 (测试计划 02)
覆盖 xml, hash, stringUtils, semver, uuid, format, frontmatterParser,
file, glob, diff 共 10 个模块的纯函数测试。
json.ts 因模块加载链路过重暂跳过。
共 190 个测试用例(含已有 array/set)全部通过。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 22:03:02 +08:00
claude-code-best
67baea3c7f test: 添加 Tool 系统单元测试 (测试计划 01)
覆盖 buildTool、toolMatchesName、findToolByName、getEmptyToolPermissionContext、
filterToolProgressMessages、parseToolPreset、parseGitCommitId、detectGitOperation
共 46 个测试用例全部通过。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 21:32:45 +08:00
claude-code-best
a426a50c0e docs: 完善测试文档编写 2026-04-01 21:19:41 +08:00
Jiguo Li
8e9933ee59 Merge branch 'claude-code-best:main' into main 2026-04-01 19:30:34 +08:00
lijiguo
f71530a10c 修复buddy rehatch的问题 2026-04-01 18:18:23 +08:00
lijiguo
c57ad656ad 支持buddy命令 2026-04-01 17:55:35 +08:00
2117 changed files with 241262 additions and 110274 deletions

View File

@@ -0,0 +1,17 @@
---
name: hello-agent
description: A friendly greeting agent that introduces the project
---
You are a friendly greeting agent. Your job is to greet the user and provide helpful information about the current project.
Instructions:
1. Read the project's CLAUDE.md to understand the project context.
2. Greet the user warmly.
3. Provide a brief summary of the project based on what you learned from CLAUDE.md.
4. Offer to help with any questions about the project.
Style:
- Be concise and friendly.
- Respond in 简体中文.
- Keep responses short — no more than a few sentences.

View File

@@ -0,0 +1,12 @@
---
name: interview
description: "Interview me about my requirements"
---
Analyze these requirements "$ARGUMENTS" and interview me in detail using the AskUserQuestionTool about literally anything: technical implementation, UI & UX, concerns, tradeoffs, etc. but make sure the questions are not obvious.
Be very in-depth and continue interviewing me continually until it's complete, then proceed in plan mode.
Rules:
- Every question MUST have a recommended option: place it first in options, append "(推荐)" to its label, and start its description with the recommendation reason.
- All user-facing text (question, header, label, description) MUST be in Chinese.

View File

@@ -0,0 +1,325 @@
---
name: teach-me
description: "Personalized 1-on-1 AI tutor. Diagnoses level, builds learning path, teaches via guided questions, tracks misconceptions. Use when user wants to learn/study/understand a topic, says 'teach me', 'help me understand', or invokes /teach-me."
---
# Teach Me
Personalized mastery tutor. Diagnose, question, advance on understanding.
## Usage
```bash
/teach-me Python decorators
/teach-me 量子力学 --level beginner
/teach-me React hooks --resume
```
## Arguments
| Argument | Description |
|----------|-------------|
| `<topic>` | Subject to learn (required, or prompted) |
| `--level <level>` | Starting level: beginner, intermediate, advanced (default: diagnose) |
| `--resume` | Resume previous session from `.claude/skills/teach-me/records/{topic-slug}/` |
## Core Rules
1. **Minimize lecturing, but don't be dogmatic.** Prefer questions that lead to discovery. For complete beginners with zero context, a brief 1-2 sentence framing is acceptable before asking.
2. **Diagnose first.** Always probe current understanding before teaching.
3. **Mastery gate.** Advance to next concept only when the learner can explain it clearly and apply it.
4. **1-2 questions per round.** No more.
5. **Patience + rigor.** Encouraging tone, but never hand-wave past gaps.
6. **Language follows user.** Match the user's language. Technical terms can stay in English.
7. **Always use AskUserQuestion.** Every question to the learner MUST use AskUserQuestion with predefined options. Never ask open-ended plain-text questions — users need options to anchor their thinking. Even conceptual/deep questions should offer 3-4 options plus let the user pick "Other" for free-form input. Options serve as scaffolding, not just convenience.
## Output Directory
All teach-me data is stored under `.claude/skills/teach-me/records/`:
```
.claude/skills/teach-me/records/
├── learner-profile.md # Cross-topic notes (created on first session)
└── {topic-slug}/
└── session.md # Learning state: concepts, status, notes
```
**Slug**: Topic in kebab-case, 2-5 words. Example: "Python decorators" → `python-decorators`
## Workflow
```
Input → [Load Profile] → [Diagnose] → [Build Concept List] → [Tutor Loop] → [Session End]
```
### Step 0: Parse Input
1. Extract topic. If none, use AskUserQuestion to ask what they want to learn (provide common categories as options).
2. Detect language from user input.
3. Load learner profile if `.claude/skills/teach-me/records/learner-profile.md` exists.
4. Check for existing session:
- If `--resume`: read `session.md`, restore state, continue.
- If exists without `--resume`: use AskUserQuestion to ask whether to resume or start fresh.
5. Create output directory: `.claude/skills/teach-me/records/{topic-slug}/`
### Step 1: Diagnose Level
Ask 2-3 questions to calibrate understanding, all via AskUserQuestion with predefined options.
If learner profile exists, use it to skip known strengths and probe known weak areas.
If `--level` provided, use as hint but still ask 1-2 probing questions.
**Example for "Python decorators"**:
Round 1 (AskUserQuestion):
```
header: "Level check"
question: "Which of these Python concepts are you comfortable with?"
multiSelect: true
options:
- label: "Functions as values"
- label: "Closures"
- label: "The @ syntax"
- label: "Writing custom decorators"
```
Round 2 (AskUserQuestion — conceptual question with options as scaffolding):
```
header: "Understanding"
question: "When Python sees @my_decorator above a function, what do you think happens?"
multiSelect: false
options:
- label: "It replaces the function with a new one"
description: "The decorator wraps or replaces the original function"
- label: "It's just syntax sugar for calling the decorator"
description: "@decorator is equivalent to func = decorator(func)"
- label: "It modifies the function in-place"
description: "The original function object is changed directly"
- label: "I'm not sure"
description: "No worries, we'll figure it out together"
```
### Step 2: Build Concept List
Decompose topic into 5-15 atomic concepts, ordered by dependency. Save to `session.md`:
```markdown
# Session: {topic}
- Level: {diagnosed}
- Started: {timestamp}
## Concepts
1. ✅ Functions as first-class objects (mastered)
2. 🔵 Higher-order functions (in progress)
3. ⬜ Closures
4. ⬜ Decorator basics
...
## Misconceptions
- [concept]: "{what learner said}" → likely root cause: {analysis}
## Log
- [timestamp] Diagnosed: intermediate
- [timestamp] Concept 1: pre-existing knowledge, skipped
- [timestamp] Concept 2: started
```
Use simple status: ✅ mastered | 🔵 in progress | ⬜ not started | ❌ needs review
Present the concept list to the learner as a brief text outline so they see the path ahead.
### Step 3: Tutor Loop
For each concept:
#### 3a. Introduce (Brief)
Set context with 1-2 sentences max, then ask an opening question via AskUserQuestion. Options serve as thinking scaffolds:
Example for "closures":
```
header: "Closures"
question: "A closure is a function that remembers variables from where it was created. Why might that be useful?"
multiSelect: false
options:
- label: "To create private state"
description: "Keep variables hidden from outside code"
- label: "To pass data between functions"
description: "Share information without global variables"
- label: "To cache expensive computations"
description: "Remember results for reuse"
- label: "I'm not sure yet"
description: "We'll explore this together"
```
#### 3b. Question Cycle
ALL questions use AskUserQuestion. Design options that probe understanding — include a mix of correct, partially correct, and common-wrong-answer distractors. The user can always use "Other" for free-form input when they have a specific idea.
**Option design tips**:
- Include 1-2 correct answers (split nuance into separate options)
- Include 1 distractor based on a common misconception
- Include "I'm not sure" or "Let me think about it" as a safe option
- Use descriptions to add hints or context to each option
**Interleaving** (every 3-4 questions): Mix a previously mastered concept into the current question's options naturally. Don't announce it as review.
Example (learning closures, already mastered higher-order functions):
```
header: "Prediction"
question: "Here's a function that takes a callback and returns a new function. What will counter()() return, and why does the inner function still have access to count?"
multiSelect: false
options:
- label: "0, because count starts at 0"
description: "The inner function reads the initial value"
- label: "1, because count was incremented before returning"
description: "Closure captures the live variable, not a copy"
- label: "Error, because count is out of scope"
description: "The outer function already returned, so count is gone"
- label: "Undefined behavior"
description: "Depends on how the function was defined"
```
#### 3c. Respond to Answers
| Answer Quality | Response |
|----------------|----------|
| Correct + good explanation | Brief acknowledgment, harder follow-up via AskUserQuestion |
| Correct but shallow | "Good. Can you explain *why*?" — as AskUserQuestion with why-options |
| Partially correct | "On the right track with [part]." — follow up with a more targeted AskUserQuestion |
| Incorrect | "Interesting. Let's step back." — simpler AskUserQuestion to re-anchor |
| "I don't know" / "Not sure" | "That's fine." — give a concrete example, then ask via AskUserQuestion with simpler options |
**Hint escalation**: rephrase → simpler question → concrete example → point to principle → walk through minimal example together.
#### 3d. Misconception Tracking
On incorrect or partially correct answers, diagnose the underlying wrong mental model:
1. Present a counter-example via AskUserQuestion — ask the learner to predict what happens, where the wrong mental model leads to a clearly wrong answer:
```
header: "Check this"
question: "Given [counter-example], what do you think the output will be?"
multiSelect: false
options:
- label: "[wrong prediction from their mental model]"
description: "Based on what we discussed earlier"
- label: "[correct prediction]"
description: "A different perspective"
- label: "[another wrong prediction]"
description: "Yet another possibility"
- label: "I need to think more"
description: "Take your time"
```
2. Record in session.md under `## Misconceptions`
3. When the learner sees the contradiction (their model predicts the wrong thing), guide them to articulate why.
4. A misconception is resolved when the learner articulates why their old thinking was wrong AND handles a new scenario correctly.
Never say "that's a misconception." Let them discover it.
#### 3e. Mastery Check
After 3-5 question rounds, assess qualitatively. The learner demonstrates mastery when they can:
- Explain the concept in their own words
- Apply it to a new scenario
- Distinguish it from similar concepts
- Find errors in incorrect usage
If not ready: identify the specific gap and cycle back with targeted questions.
#### 3f. Practice Phase
Before marking mastered, give a small hands-on task via AskUserQuestion. Present the task as a code/output prediction or scenario choice:
- **Programming**: Show a small code snippet and ask what it outputs or which fix is correct:
```
header: "Practice"
question: "Here's a buggy decorator. What's wrong with it?"
multiSelect: false
options:
- label: "Missing return wrapper"
description: "The decorator doesn't return the inner function"
- label: "Wrong function signature"
description: "The wrapper doesn't accept *args, **kwargs"
- label: "Missing @functools.wraps"
description: "Metadata from the original function is lost"
- label: "I'd like to try writing one from scratch"
description: "Use 'Other' to write your own code"
```
- **Non-programming**: Ask to identify which scenario best applies the concept:
```
header: "Apply it"
question: "Which real-world scenario best demonstrates [concept]?"
multiSelect: false
options:
- label: "[scenario A]"
- label: "[scenario B]"
- label: "[scenario C]"
- label: "I have my own example"
description: "Use 'Other' to share your own"
```
Keep it 2-5 minutes. Pass = mastered. Fail = diagnose gap, cycle back.
#### 3g. Sync Progress (Every Round)
Update `session.md` after each round:
- Change concept status if applicable
- Add new misconceptions or resolve existing ones
- Append to log
### Step 4: Session End
When all concepts mastered or user ends session:
1. Update `session.md` with final state.
2. Update `.claude/skills/teach-me/records/learner-profile.md` (keep under 30 lines):
```markdown
# Learner Profile
Updated: {timestamp}
## Style
- Learns best with: {concrete examples / abstract principles / visual ...}
- Pace: {fast / moderate / needs-time}
## Patterns
- Tends to confuse X with Y
- Recurring difficulty with: {area}
## Topics
- Python decorators (8/10 concepts, 2025-01-15)
```
3. Give a brief text summary of what was covered, key insights, and areas for further study.
## Resuming Sessions
On `--resume`:
1. Read `session.md` and `learner-profile.md`
2. Quick check on 1-2 previously mastered concepts via AskUserQuestion:
```
header: "Quick review"
question: "Last time you mastered [concept X]. Can you recall which of these is true about it?"
multiSelect: false
options:
- label: "[correct statement]"
- label: "[plausible distractor]"
- label: "[plausible distractor]"
- label: "I forgot this one"
description: "No worries, we'll revisit it"
```
3. If forgotten, mark as ❌ needs review and revisit before continuing
4. Recap: "Last time you mastered [X]. You were working on [Y]."
5. Continue from first in-progress or not-started concept
## Notes
- Keep it conversational, not mechanical
- Vary question types: predict, compare, debug, extend, teach-back, connect
- Slow down when struggling, speed up when flying
- Interleaving should feel natural, not like a pop quiz
- Wrong answers are more informative than right ones — never rush past them

View File

@@ -0,0 +1,235 @@
# Pedagogy Guide
## Bloom's 2-Sigma Effect
Benjamin Bloom (1984) found that students tutored 1-on-1 with mastery learning performed 2 standard deviations above conventional classroom students. The two key ingredients:
1. **Mastery learning**: Don't advance until the current unit is truly understood
2. **1-on-1 tutoring**: Adapt pace, style, and content to the individual learner
## Socratic Method Integration
Never lecture. Instead:
- Ask questions that lead the learner to discover the answer
- When they're stuck, don't explain — ask a simpler question
- When they answer correctly, don't just confirm — ask them to explain why
## Question Design Patterns
### Diagnostic Questions (Step 1)
Purpose: Quickly map what the learner knows and doesn't know.
| Type | Example | Probes |
|------|---------|--------|
| Vocabulary check | "What does [term] mean to you?" | Do they know the words? |
| Concept sorting | "Which of these are examples of X?" (AskUserQuestion) | Can they categorize? |
| Prediction | "What do you think happens when...?" | Intuition level |
| Explain-back | "Explain [concept] as if to a 10-year-old" | Depth of understanding |
### Teaching Questions (Step 3)
| Pattern | When | Example |
|---------|------|---------|
| **Predict** | Introducing new behavior | "What will this code print?" |
| **Compare** | Distinguishing similar concepts | "How is X different from Y?" |
| **Debug** | Testing careful reading | "This code has a bug. Can you find it?" |
| **Extend** | Testing transfer | "Now how would you modify this to also handle...?" |
| **Teach-back** | Confirming mastery | "Explain to me how [concept] works" |
| **Connect** | Building knowledge graph | "How does [new concept] relate to [previous concept]?" |
### Mastery Check Questions (Step 3g)
These should be synthesis-level:
- Combine the current concept with 1-2 previous concepts
- Require application, not just recall
- Include at least one novel scenario not seen during teaching
### Interleaving Questions (Step 3b)
Interleaving means mixing questions about old concepts into the current learning flow. Research (Rohrer & Taylor 2007, Dunlosky et al. 2013) shows interleaved practice improves long-term retention by ~43% compared to blocked practice.
**Why it works**: Interleaving forces the learner to discriminate between concepts ("which tool applies here?"), which is a higher cognitive demand than applying a known concept. This discrimination practice is what builds durable, flexible knowledge.
**How to design interleaving questions**:
- The question must require BOTH the old concept and the current concept
- Don't announce it as review — embed it naturally
- Prioritize concepts that are easily confused with the current one
- If the learner fails the old-concept part, it's a signal the old concept is decaying — note it for spaced repetition
| Interleaving Pattern | Example |
|---------------------|---------|
| **Combine** | "Use both [old concept] and [new concept] to solve this" |
| **Discriminate** | "Would you use [old concept] or [new concept] here? Why?" |
| **Contrast** | "This looks similar to [old concept]. What's different?" |
| **Layer** | "We used [old concept] to do X. Now add [new concept] on top." |
## Mastery Scoring (Calibrated)
### Rubric-Based Assessment
Do NOT score based on vague impression. Use these 4 criteria for each mastery check question:
| Criterion | Weight | What to look for |
|-----------|--------|------------------|
| **Accurate** | 1 point | Factually/logically correct answer |
| **Explained** | 1 point | Learner articulates the WHY, not just the WHAT |
| **Novel application** | 1 point | Can apply to a scenario not seen during teaching |
| **Discrimination** | 1 point | Can distinguish from similar/related concepts |
Score per question = criteria met / 4. Concept mastery requires >= 3/4 on each mastery check question AND >= 80% overall concept score.
### Self-Assessment Calibration
Ask the learner to self-assess BEFORE revealing your evaluation. Compare:
| Self vs Rubric | What it means | Action |
|----------------|---------------|--------|
| Both high | Good metacognition, true mastery | Proceed to practice phase |
| Self HIGH, rubric LOW | **Fluency illusion** — most dangerous | Flag explicitly, show evidence of gaps |
| Self LOW, rubric HIGH | Under-confidence | Reassure with specific evidence |
| Both low | Honest awareness of gaps | Cycle back, adjust approach |
**Fluency illusion** (Bjork, 1994): The feeling of understanding that comes from familiarity rather than actual comprehension. Common triggers: seeing a worked example and thinking "I could do that", recognizing terminology without being able to apply it, confusing passive exposure with active mastery.
### Qualitative Signals
Beyond the rubric, these signals indicate genuine mastery:
- Learner can explain concept in their own words
- Learner can give novel examples
- Learner can identify errors in incorrect examples
- Learner can connect concept to broader context
## Misconception Handling
### Why Misconceptions Matter More Than Gaps
A gap in knowledge ("I don't know X") is easy to fill — just teach X. A misconception ("I know X, but my version of X is wrong") is far harder because the wrong model must be dismantled before the correct one can take hold. Research (Vosniadou 2013, Chi 2005) shows that misconceptions are the #1 barrier to learning in most domains.
### Types of Misconceptions
| Type | Example | Why it's sticky |
|------|---------|----------------|
| **Overgeneralization** | "All functions return values" | Correct in many cases, fails in edge cases |
| **False analogy** | "Electricity flows like water" | Useful at first, breaks down at depth |
| **Vocabulary confusion** | "Parameter and argument are the same" | Language reinforces the error daily |
| **Causal reversal** | "Practice makes talent" (vs talent enables practice) | Correlation mistaken for causation |
| **Incomplete model** | "Closures copy variables" (actually capture references) | Partially correct, fails under mutation |
### The Counter-Example Method
The most effective way to dislodge a misconception is NOT to say "that's wrong." It's to construct a scenario where the wrong model makes a clear, testable prediction — and then show reality contradicts it.
Steps:
1. **Identify** the wrong model from the learner's answer
2. **Construct** a scenario where the wrong model predicts outcome A
3. **Ask** the learner to predict the outcome (they'll predict A)
4. **Reveal** that the actual outcome is B
5. **Ask** the learner to explain the discrepancy
6. **Wait** — let the learner wrestle with the contradiction. Do NOT explain immediately.
7. **Guide** toward the correct model only after they've engaged with the contradiction
### Misconception Resolution Criteria
A misconception is resolved ONLY when BOTH conditions are met:
1. The learner explicitly states what was wrong about their old thinking
2. The learner correctly handles a new scenario that would have triggered the old misconception
Getting the right answer once is NOT enough — they must also articulate why the old answer was wrong.
## Spaced Repetition
### The Forgetting Curve
Ebbinghaus (1885) demonstrated that without review, memory decays exponentially:
- After 1 hour: ~50% forgotten
- After 1 day: ~70% forgotten
- After 1 week: ~90% forgotten
The only way to counteract this is **spaced review** — re-testing at increasing intervals.
### Interval Schedule
Sigma uses a simplified SM-2 inspired schedule:
| Event | Next Review Interval |
|-------|---------------------|
| Concept first mastered | 1 day |
| Review: correct | Double the interval (1d → 2d → 4d → 8d → 16d → 32d) |
| Review: incorrect | Reset to 1 day |
| Maximum interval | 32 days |
### Review Question Design
Review questions should be:
- **Brief**: 1 question per concept, not a full mastery check
- **Application-level**: Not "what is X?" but "use X to solve this small problem"
- **Connected**: Where possible, connect the review concept to the current concept being learned (this also serves as interleaving)
### Session Review Protocol
On `--resume`, before continuing new content:
1. Identify all mastered concepts where `days_since_review >= review_interval`
2. Sort by most overdue first
3. Review max 5 concepts per session (don't turn the session into all review)
4. Adjust intervals based on results
5. If a concept drops back to `in-progress`, address it before continuing forward
## Deliberate Practice
### Understanding ≠ Ability
Ericsson's research on expert performance (1993) established that knowing how something works is fundamentally different from being able to do it. The gap between declarative knowledge ("I can explain decorators") and procedural knowledge ("I can write a decorator") requires practice to bridge.
### Practice Task Design
Good practice tasks for Sigma:
| Property | Good | Bad |
|----------|------|-----|
| **Size** | 2-5 minutes | 30-minute project |
| **Scope** | Tests one concept | Tests everything at once |
| **Novelty** | New scenario, same concept | Repeat of a teaching example |
| **Output** | Learner produces something | Learner answers more questions |
| **Feedback** | Clear right/wrong signal | Ambiguous quality |
### Practice vs More Questions
Practice is NOT more Q&A. The key differences:
| Dimension | Questions (3b) | Practice (3h) |
|-----------|----------------|---------------|
| Mode | Reactive (answer what's asked) | Generative (produce something new) |
| Cognitive load | Recognition + recall | Planning + execution + self-monitoring |
| Output | Words | Artifact (code, design, example, explanation) |
| Feedback | Immediate from tutor | Self-discovered through doing |
### The Generation Effect
Slamecka & Graf (1978) showed that information the learner generates themselves is remembered 2-3x better than information they read. Practice tasks leverage this effect — the learner constructs knowledge through the act of doing.
## Adaptive Pacing
| Signal | Action |
|--------|--------|
| Answers quickly and correctly | Skip to harder questions, consider merging concepts |
| Answers correctly but slowly | Proceed normally, give time |
| Partially correct | Ask follow-up probing questions before moving on |
| Consistently wrong | Break down into sub-concepts, use more concrete examples |
| Frustrated | Switch to a visual aid, use analogy, acknowledge difficulty |
| Bored | Increase difficulty, introduce real-world application |
## Visual Aid Selection
Use the right format for the right purpose:
| Need | Format | When |
|------|--------|------|
| Show relationships | Excalidraw concept map | Concepts have dependencies or hierarchy |
| Walk through process | HTML step-by-step | Code execution, algorithm steps |
| Abstract idea | Generated image (nano-banana-pro) | Metaphors, mental models |
| Compare options | HTML table/grid | Feature comparison, trade-offs |
| Show flow/logic | Excalidraw flowchart | Decision trees, control flow |
| Summarize progress | HTML dashboard | Milestones, session end |
Don't generate visuals for every round — use them when they genuinely help understanding or when the learner seems stuck.

11
.dockerignore Normal file
View File

@@ -0,0 +1,11 @@
node_modules
dist
.git
.githooks
.github
docs
*.md
packages/remote-control-server/data/*.db
packages/remote-control-server/data/*.db-wal
packages/remote-control-server/data/*.db-shm
.claude

0
.githooks/pre-commit Executable file → Normal file
View File

View File

@@ -20,11 +20,19 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Type check
run: bunx tsc --noEmit
- name: Test
run: bun test
- name: Test with Coverage
run: |
set -o pipefail
bun test --coverage --coverage-reporter=lcov 2>&1 | grep -vE '^\s*(\(pass\)|\(skip\))' | sed '/^.*\/__tests__\/.*:$/d' | cat -s
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
with:
file: ./coverage/lcov.info
token: ${{ secrets.CODECOV_TOKEN }}
- name: Build
run: bun run build
run: bun run build:vite

75
.github/workflows/release-rcs.yml vendored Normal file
View File

@@ -0,0 +1,75 @@
name: Release RCS Docker Image
on:
push:
tags:
- 'rcs-v*'
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository_owner }}/remote-control-server
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Extract version
id: version
run: echo "VERSION=${GITHUB_REF_NAME#rcs-v}" >> "$GITHUB_OUTPUT"
- name: Generate tags
id: tags
run: |
VERSION="${{ steps.version.outputs.VERSION }}"
IMAGE="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
TAGS="${IMAGE}:${VERSION}"
IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION"
if [ -n "$MAJOR" ] && [ -n "$MINOR" ]; then
TAGS="${TAGS},${IMAGE}:${MAJOR}.${MINOR}"
fi
TAGS="${TAGS},${IMAGE}:latest"
echo "tags=$TAGS" >> "$GITHUB_OUTPUT"
- name: Build Docker image
uses: docker/build-push-action@v5
with:
context: .
file: packages/remote-control-server/Dockerfile
push: false
load: true
tags: ${{ steps.tags.outputs.tags }}
build-args: VERSION=${{ steps.version.outputs.VERSION }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Verify image
run: |
IMAGE_TAG=$(echo "${{ steps.tags.outputs.tags }}" | cut -d',' -f1)
docker run -d --name rcs-test -p 3000:3000 "$IMAGE_TAG"
sleep 5
curl -sf http://localhost:3000/health || { docker logs rcs-test; exit 1; }
docker stop rcs-test
docker rm rcs-test
- name: Push Docker image
run: |
IFS=',' read -ra TAGS <<< "${{ steps.tags.outputs.tags }}"
for TAG in "${TAGS[@]}"; do
docker push "$TAG"
done

View File

@@ -0,0 +1,31 @@
name: Update Contributors
on:
push:
branches:
- main
schedule:
- cron: '0 0 * * *' # 每天更新一次
permissions:
contents: write
jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
- uses: jaywcjlove/github-action-contributors@main
with:
token: ${{ secrets.GITHUB_TOKEN }}
output: "contributors.svg"
repository: ${{ github.repository }}
- uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "docs: update contributors"
file_pattern: "contributors.svg"
branch: main

32
.gitignore vendored
View File

@@ -7,4 +7,34 @@ coverage
.idea
.vscode
*.suo
*.lock
*.lock
src/utils/vendor/
# AI tool runtime directories
.agents/
.claude/
.omx/
.docs/task/
# Binary / screenshot files (root only)
/*.png
*.bmp
# Agent / tool state dirs
.swarm/
.agents/__pycache__/
# Python bytecode
__pycache__/
*.pyc
logs
data
.omc
.codex/*
!.codex/agents/
!.codex/agents/**
!.codex/skills/
!.codex/skills/**
.codex/skills/.system/**
!.codex/prompts/
!.codex/prompts/**

2
.mintignore Normal file
View File

@@ -0,0 +1,2 @@
src/
packages/

13
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,13 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "bun",
"request": "attach",
"name": "Attach to Claude Code",
"url": "ws://localhost:8888/2dc3gzl5xot",
"stopOnEntry": false,
"internalConsoleOptions": "neverOpen"
}
]
}

27
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,27 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "Start Claude Code TUI",
"type": "shell",
"command": "bun run dev:inspect",
"isBackground": true,
"presentation": {
"reveal": "always",
"focus": true,
"panel": "dedicated",
"clear": true
},
"problemMatcher": {
"pattern": {
"regexp": "^$"
},
"background": {
"activeOnStart": true,
"beginsPattern": ".*Bun Inspector.*",
"endsPattern": ".*Listening:.*"
}
}
}
]
}

231
CLAUDE.md
View File

@@ -4,7 +4,22 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
This is a **reverse-engineered / decompiled** version of Anthropic's official Claude Code CLI tool. The goal is to restore core functionality while trimming secondary capabilities. Many modules are stubbed or feature-flagged off. The codebase has ~1341 tsc errors from decompilation (mostly `unknown`/`never`/`{}` types) — these do **not** block Bun runtime execution.
This is a **reverse-engineered / decompiled** version of Anthropic's official Claude Code CLI tool. The goal is to restore core functionality while trimming secondary capabilities. Many modules are stubbed or feature-flagged off. TypeScript strict mode is enforced见 Working with This Codebase 段的 tsc 要求)。
## Git Commit Message Convention
使用 **Conventional Commits** 规范:
```
<type>: <描述>
```
常见 type`feat``fix``docs``chore``refactor`
示例:
- `feat: 添加模型 1M 上下文切换`
- `fix: 修复初次登陆的校验问题`
- `chore: remove prefetchOfficialMcpUrls call on startup`
## Commands
@@ -12,36 +27,78 @@ This is a **reverse-engineered / decompiled** version of Anthropic's official Cl
# Install dependencies
bun install
# Dev mode (direct execution via Bun)
# Dev mode (runs cli.tsx with MACRO defines injected via -d flags)
bun run dev
# equivalent to: bun run src/entrypoints/cli.tsx
# Dev mode with debugger (set BUN_INSPECT=9229 to pick port)
bun run dev:inspect
# Pipe mode
echo "say hello" | bun run src/entrypoints/cli.tsx -p
# Build (outputs dist/cli.js, ~25MB)
# Build (code splitting, outputs dist/cli.js + chunk files)
bun run build
# Build with Vite (alternative build pipeline)
bun run build:vite
# Test
bun test # run all tests (3066 tests / 205 files / 0 fail)
bun test src/utils/__tests__/hash.test.ts # run single file
bun test --coverage # with coverage report
# Lint & Format (Biome)
bun run lint # check only
bun run lint:fix # auto-fix
bun run format # format all src/
# Health check
bun run health
# Check unused exports
bun run check:unused
bun run typecheck
# Remote Control Server
bun run rcs
# Docs dev server (Mintlify)
bun run docs:dev
```
No test runner is configured. No linter is configured.
详细的测试规范、覆盖状态和改进计划见 `docs/testing-spec.md`
## Architecture
### Runtime & Build
- **Runtime**: Bun (not Node.js). All imports, builds, and execution use Bun APIs.
- **Build**: `bun build src/entrypoints/cli.tsx --outdir dist --target bun` — single-file bundle.
- **Build**: `build.ts` 执行 `Bun.build()` with `splitting: true`,入口 `src/entrypoints/cli.tsx`,输出 `dist/cli.js` + chunk files。Build 默认启用 19 个 feature见下方 Feature Flag 段)。构建后自动替换 `import.meta.require` 为 Node.js 兼容版本(产物 bun/node 都可运行)。
- **Dev mode**: `scripts/dev.ts` 通过 Bun `-d` flag 注入 `MACRO.*` defines运行 `src/entrypoints/cli.tsx`。默认启用全部 feature。
- **Module system**: ESM (`"type": "module"`), TSX with `react-jsx` transform.
- **Monorepo**: Bun workspaces — internal packages live in `packages/` resolved via `workspace:*`.
- **Monorepo**: Bun workspaces — 15 个 workspace packages + 若干辅助目录 in `packages/` resolved via `workspace:*`
- **Lint/Format**: Biome (`biome.json`)。`bun run lint` / `bun run lint:fix` / `bun run format`
- **Defines**: 集中管理在 `scripts/defines.ts`。当前版本 `2.1.888`
- **CI**: GitHub Actions — `ci.yml`(构建+测试)、`release-rcs.yml`RCS 发布)、`update-contributors.yml`(自动更新贡献者)。
### Entry & Bootstrap
1. **`src/entrypoints/cli.tsx`** — True entrypoint. Injects runtime polyfills at the top:
- `feature()` always returns `false` (all feature flags disabled, skipping unimplemented branches).
- `globalThis.MACRO` — simulates build-time macro injection (VERSION, BUILD_TIME, etc.).
- `BUILD_TARGET`, `BUILD_ENV`, `INTERFACE_TYPE` globals.
2. **`src/main.tsx`** — Commander.js CLI definition. Parses args, initializes services (auth, analytics, policy), then launches the REPL or runs in pipe mode.
3. **`src/entrypoints/init.ts`** — One-time initialization (telemetry, config, trust dialog).
1. **`src/entrypoints/cli.tsx`** (373 行) — True entrypoint`main()` 函数按优先级处理多条快速路径:
- `--version` / `-v` — 零模块加载
- `--dump-system-prompt` — feature-gated (DUMP_SYSTEM_PROMPT)
- `--claude-in-chrome-mcp` / `--chrome-native-host`
- `--computer-use-mcp` — 独立 MCP server 模式
- `--daemon-worker=<kind>` — feature-gated (DAEMON)
- `remote-control` / `rc` / `remote` / `sync` / `bridge` — feature-gated (BRIDGE_MODE)
- `daemon` [subcommand] — feature-gated (DAEMON)
- `ps` / `logs` / `attach` / `kill` / `--bg` — feature-gated (BG_SESSIONS)
- `new` / `list` / `reply` — Template job commands
- `environment-runner` / `self-hosted-runner` — BYOC runner
- `--tmux` + `--worktree` 组合
- 默认路径:加载 `main.tsx` 启动完整 CLI
2. **`src/main.tsx`** (~6981 行) — Commander.js CLI definition。注册大量 subcommands`mcp` (serve/add/remove/list...)、`server``ssh``open``auth``plugin``agents``auto-mode``doctor``update` 等。主 `.action()` 处理器负责权限、MCP、会话恢复、REPL/Headless 模式分发。
3. **`src/entrypoints/init.ts`** — One-time initialization (telemetry, config, trust dialog)。
### Core Loop
@@ -52,32 +109,77 @@ No test runner is configured. No linter is configured.
### API Layer
- **`src/services/api/claude.ts`** — Core API client. Builds request params (system prompt, messages, tools, betas), calls the Anthropic SDK streaming endpoint, and processes `BetaRawMessageStreamEvent` events.
- Supports multiple providers: Anthropic direct, AWS Bedrock, Google Vertex, Azure.
- Provider selection in `src/utils/model/providers.ts`.
- **7 providers**: `firstParty` (Anthropic direct), `bedrock` (AWS), `vertex` (Google Cloud), `foundry`, `openai`, `gemini`, `grok` (xAI)。
- Provider selection in `src/utils/model/providers.ts`。优先级modelType 参数 > 环境变量 > 默认 firstParty。
### Tool System
- **`src/Tool.ts`** — Tool interface definition (`Tool` type) and utilities (`findToolByName`, `toolMatchesName`).
- **`src/tools.ts`** — Tool registry. Assembles the tool list; some tools are conditionally loaded via `feature()` flags or `process.env.USER_TYPE`.
- **`src/tools/<ToolName>/`** — Each tool in its own directory (e.g., `BashTool`, `FileEditTool`, `GrepTool`, `AgentTool`).
- Tools define: `name`, `description`, `inputSchema` (JSON Schema), `call()` (execution), and optionally a React component for rendering results.
- **`src/tools.ts`** (392 行) — Tool registry. Assembles the tool list; tools are imported from `@claude-code-best/builtin-tools` package. Some tools are conditionally loaded via `feature()` flags or `process.env.USER_TYPE`.
- **`packages/builtin-tools/src/tools/`** — 59 个子目录(含 shared/testing 等工具目录),通过 `@claude-code-best/builtin-tools` 包导出。主要分类:
- **文件操作**: FileEditTool, FileReadTool, FileWriteTool, GlobTool, GrepTool
- **Shell/执行**: BashTool, PowerShellTool, REPLTool
- **Agent 系统**: AgentTool, TaskCreateTool, TaskUpdateTool, TaskListTool, TaskGetTool
- **规划**: EnterPlanModeTool, ExitPlanModeV2Tool, VerifyPlanExecutionTool
- **Web/MCP**: WebFetchTool, WebSearchTool, MCPTool, McpAuthTool
- **调度**: CronCreateTool, CronDeleteTool, CronListTool
- **其他**: LSPTool, ConfigTool, SkillTool, EnterWorktreeTool, ExitWorktreeTool 等
### UI Layer (Ink)
- **`src/ink.ts`** — Ink render wrapper with ThemeProvider injection.
- **`src/ink/`** — Custom Ink framework (forked/internal): custom reconciler, hooks (`useInput`, `useTerminalSize`, `useSearchHighlight`), virtual list rendering.
- **`src/components/`** — React components rendered in terminal via Ink. Key ones:
- `App.tsx` — Root provider (AppState, Stats, FpsMetrics).
- `Messages.tsx` / `MessageRow.tsx` — Conversation message rendering.
- `PromptInput/` — User input handling.
- `permissions/` — Tool permission approval UI.
- **`packages/@ant/ink/`** — Custom Ink frameworkforked/internal),包含 components、core、hooks、keybindings、theme、utils。注意不是 `src/ink/`
- **`src/components/`** — 149 个组件目录/文件,渲染于终端 Ink 环境中。关键组件:
- `App.tsx` — Root provider (AppState, Stats, FpsMetrics)
- `Messages.tsx` / `MessageRow.tsx` — Conversation message rendering
- `PromptInput/` — User input handling
- `permissions/` — Tool permission approval UI
- `design-system/` — 复用 UI 组件Dialog, FuzzyPicker, ProgressBar, ThemeProvider 等)
- Components use React Compiler runtime (`react/compiler-runtime`) — decompiled output has `_c()` memoization calls throughout.
### State Management
- **`src/state/AppState.tsx`** — Central app state type and context provider. Contains messages, tools, permissions, MCP connections, etc.
- **`src/state/store.ts`** — Zustand-style store for AppState.
- **`src/bootstrap/state.ts`** — Module-level singletons for session-global state (session ID, CWD, project root, token counts).
- **`src/state/AppStateStore.ts`** — Default state and store factory.
- **`src/state/store.ts`** — Zustand-style store for AppState (`createStore`).
- **`src/state/selectors.ts`** — State selectors.
- **`src/bootstrap/state.ts`** — Module-level singletons for session-global state (session ID, CWD, project root, token counts, model overrides, client type, permission mode).
### Workspace Packages
| Package | 说明 |
|---------|------|
| `packages/@ant/ink/` | Forked Ink 框架components、hooks、keybindings、theme |
| `packages/@ant/computer-use-mcp/` | Computer Use MCP server截图/键鼠/剪贴板/应用管理) |
| `packages/@ant/computer-use-input/` | 键鼠模拟dispatcher + darwin/win32/linux backend |
| `packages/@ant/computer-use-swift/` | 截图 + 应用管理dispatcher + per-platform backend |
| `packages/@ant/claude-for-chrome-mcp/` | Chrome 浏览器控制(通过 `--chrome` 启用) |
| `packages/@ant/model-provider/` | Model provider 抽象层 |
| `packages/builtin-tools/` | 内置工具集60 个 tool 实现,通过 `@claude-code-best/builtin-tools` 导出) |
| `packages/agent-tools/` | Agent 工具集 |
| `packages/cc-knowledge/` | Claude Code 知识库(非 workspace 包) |
| `packages/langfuse-dashboard/` | Langfuse 可观测性面板(非 workspace 包) |
| `packages/mcp-client/` | MCP 客户端库 |
| `packages/mcp-server/` | MCP 服务端库(非 workspace 包) |
| `packages/remote-control-server/` | 自托管 Remote Control ServerDocker 部署,含 Web UI |
| `packages/swarm/` | Swarm 解耦模块(非 workspace 包) |
| `packages/shell/` | Shell 抽象(非 workspace 包) |
| `packages/audio-capture-napi/` | 原生音频捕获(已恢复) |
| `packages/color-diff-napi/` | 颜色差异计算完整实现11 tests |
| `packages/image-processor-napi/` | 图像处理(已恢复) |
| `packages/modifiers-napi/` | 键盘修饰键检测stub |
| `packages/url-handler-napi/` | URL scheme 处理stub |
### Bridge / Remote Control
- **`src/bridge/`** (~38 files) — Remote Control / Bridge 模式。feature-gated by `BRIDGE_MODE`。包含 bridge API、会话管理、JWT 认证、消息传输、权限回调等。Entry: `bridgeMain.ts`
- **`packages/remote-control-server/`** — 自托管 RCS支持 Docker 部署,含 Web UI 控制面板。通过 `bun run rcs` 启动。
- CLI 快速路径: `claude remote-control` / `claude rc` / `claude bridge`
- 详见 `docs/features/remote-control-self-hosting.md`
### Daemon Mode
- **`src/daemon/`** — Daemon 模式(长驻 supervisor。feature-gated by `DAEMON`。包含 `main.ts`entry`workerRegistry.ts`worker 管理)。
### Context & System Prompt
@@ -86,16 +188,38 @@ No test runner is configured. No linter is configured.
### Feature Flag System
All `feature('FLAG_NAME')` calls come from `bun:bundle` (a build-time API). In this decompiled version, `feature()` is polyfilled to always return `false` in `cli.tsx`. This means all Anthropic-internal features (COORDINATOR_MODE, KAIROS, PROACTIVE, etc.) are disabled.
Feature flags control which functionality is enabled at runtime. 代码中统一通过 `import { feature } from 'bun:bundle'` 导入,调用 `feature('FLAG_NAME')` 返回 `boolean`
**启用方式**: 环境变量 `FEATURE_<FLAG_NAME>=1`。例如 `FEATURE_BUDDY=1 bun run dev`
**Build 默认 features**19 个,见 `build.ts`:
- 基础: `BUDDY`, `TRANSCRIPT_CLASSIFIER`, `BRIDGE_MODE`, `AGENT_TRIGGERS_REMOTE`, `CHICAGO_MCP`, `VOICE_MODE`
- 统计/缓存: `SHOT_STATS`, `PROMPT_CACHE_BREAK_DETECTION`, `TOKEN_BUDGET`
- P0 本地: `AGENT_TRIGGERS`, `ULTRATHINK`, `BUILTIN_EXPLORE_PLAN_AGENTS`, `LODESTONE`
- P1 API 依赖: `EXTRACT_MEMORIES`, `VERIFICATION_AGENT`, `KAIROS_BRIEF`, `AWAY_SUMMARY`, `ULTRAPLAN`
- P2: `DAEMON`
**Dev mode 默认**: 全部启用(见 `scripts/dev.ts`)。
**类型声明**: `src/types/internal-modules.d.ts` 中声明了 `bun:bundle` 模块的 `feature` 函数签名。
**新增功能的正确做法**: 保留 `import { feature } from 'bun:bundle'` + `feature('FLAG_NAME')` 的标准模式,在运行时通过环境变量或配置控制,不要绕过 feature flag 直接 import。
### Multi-API 兼容层
支持 OpenAI、Gemini、Grok 三种第三方 API通过 `/login` 命令配置,均采用流适配器模式转为 Anthropic 内部格式。详见各兼容层的 docs 文档。
### Stubbed/Deleted Modules
| Module | Status |
|--------|--------|
| Computer Use (`@ant/*`) | Stub packages in `packages/@ant/` |
| `*-napi` packages (audio, image, url, modifiers) | Stubs in `packages/` (except `color-diff-napi` which is fully implemented) |
| Computer Use (`@ant/*`) | Restored — macOS + Windows + Linux后端完整度不一 |
| `*-napi` packages | `audio-capture-napi``image-processor-napi` 已恢复;`color-diff-napi` 完整;`modifiers-napi``url-handler-napi` 仍为 stub |
| Voice Mode | Restored — Push-to-Talk 语音输入(需 Anthropic OAuth |
| OpenAI/Gemini/Grok 兼容层 | Restored |
| Remote Control Server | Restored — 自托管 RCS + Web UI |
| Analytics / GrowthBook / Sentry | Empty implementations |
| Magic Docs / Voice Mode / LSP Server | Removed |
| Magic Docs / LSP Server | Removed |
| Plugins / Marketplace | Removed |
| MCP OAuth | Simplified |
@@ -106,10 +230,51 @@ All `feature('FLAG_NAME')` calls come from `bun:bundle` (a build-time API). In t
- **`src/types/message.ts`** — Message type hierarchy (UserMessage, AssistantMessage, SystemMessage, etc.).
- **`src/types/permissions.ts`** — Permission mode and result types.
## Testing
- **框架**: `bun:test`(内置断言 + mock
- **当前状态**: 3066 tests / 205 files / 0 fail
- **单元测试**: 就近放置于 `src/**/__tests__/`,文件名 `<module>.test.ts`
- **集成测试**: `tests/integration/` — 4 个文件cli-arguments, context-build, message-pipeline, tool-chain
- **共享 mock/fixture**: `tests/mocks/`api-responses, file-system, fixtures/
- **命名**: `describe("functionName")` + `test("behavior description")`,英文
- **包测试**: `packages/` 下各包也有独立测试(如 `color-diff-napi` 11 tests
### Mock 使用规范
**只 mock 有副作用的依赖链,不 mock 纯函数/纯数据模块。**
被迫 mock 的根源:`log.ts` / `debug.ts``bootstrap/state.ts`(模块级 `realpathSync` / `randomUUID` 副作用)。必须 mock 的模块:`log.ts``debug.ts``bun:bundle``settings/settings.js``config.ts``auth.ts`、第三方网络库。
不要 mock纯函数模块`errors.ts``stringUtils.js`、mock 值与真实实现相同的模块、mock 路径与实际 import 不匹配的模块。
路径规则:统一用 `.ts` 扩展名 + `src/*` 别名路径,禁止双重 mock 同一模块。
### 类型检查
项目使用 TypeScript strict 模式,**tsc 必须零错误**。每次修改后运行:
```bash
bun run typecheck # equivalent to bun run typecheck
```
**类型规范**
- 生产代码禁止 `as any`;测试文件中 mock 数据可用 `as any`
- 类型不匹配优先用 `as unknown as SpecificType` 双重断言,或补充 interface
- 未知结构对象用 `Record<string, unknown>` 替代 `any`
- 联合类型用类型守卫type guard收窄不要强转
- `msg.request` 属性访问:`const req = msg.request as Record<string, unknown>`
- Ink `color` prop`as keyof Theme` 而非 `as any`
## Working with This Codebase
- **Don't try to fix all tsc errors** — they're from decompilation and don't affect runtime.
- **`feature()` is always `false`** — any code behind a feature flag is dead code in this build.
- **tsc must pass** — `bun run typecheck` 必须零错误,任何修改都不能引入新的类型错误。
- **Feature flags** — 默认全部关闭(`feature()` 返回 `false`。Dev/build 各有自己的默认启用列表。不要在 `cli.tsx` 中重定义 `feature` 函数。
- **React Compiler output** — Components have decompiled memoization boilerplate (`const $ = _c(N)`). This is normal.
- **`bun:bundle` import** — In `src/main.tsx` and other files, `import { feature } from 'bun:bundle'` works at build time. At dev-time, the polyfill in `cli.tsx` provides it.
- **`bun:bundle` import** — `import { feature } from 'bun:bundle'` 是 Bun 内置模块,由运行时/构建器解析。不要用自定义函数替代它。**`feature()` 只能直接用在 `if` 语句或三元表达式的条件位置**Bun 编译器限制),不能赋值给变量、不能放在箭头函数体里、不能作为 `&&` 链的一部分。正确:`if (feature('X')) {}``feature('X') ? a : b`
- **`src/` path alias** — tsconfig maps `src/*` to `./src/*`. Imports like `import { ... } from 'src/utils/...'` are valid.
- **MACRO defines** — 集中管理在 `scripts/defines.ts`。Dev mode 通过 `bun -d` 注入build 通过 `Bun.build({ define })` 注入。修改版本号等常量只改这个文件。
- **构建产物兼容 Node.js** — `build.ts` 会自动后处理 `import.meta.require`,产物可直接用 `node dist/cli.js` 运行。
- **Biome 配置** — 大量 lint 规则被关闭decompiled 代码不适合严格 lint`.tsx` 文件用 120 行宽 + 强制分号;其他文件 80 行宽 + 按需分号。
- **Ink 框架在 `packages/@ant/ink/`** — 不是 `src/ink/`该目录不存在。Ink 相关的组件、hooks、keybindings 都在 packages 中。
- **Provider 优先级** — `modelType` 参数 > 环境变量 > 默认 `firstParty`。新增 provider 需在 `src/utils/model/providers.ts` 注册。

994
DEV-LOG.md Normal file
View File

@@ -0,0 +1,994 @@
# DEV-LOG
## /poor 省流模式 (2026-04-11)
新增 `/poor` 命令toggle 关闭 `extract_memories``prompt_suggestion`,省 token。
- 新增 `POOR` feature flagbuild.ts + dev.ts
- `src/commands/poor/` — 命令定义 + toggle 实现 + 状态管理
- `src/query/stopHooks.ts` — POOR 模式激活时跳过 extract_memories 和 prompt_suggestion
---
## Pipe IPC + LAN Pipes + Monitor Tool + 工具恢复 (2026-04-08 ~ 2026-04-11)
**分支**: `feat/pr-package-adapt`
### 背景
从 decompiled 代码恢复大量 stub 为完整实现,同时新增 LAN 跨机器通讯能力。本次 PR 覆盖Pipe IPC 系统、LAN Pipes、Monitor Tool、20+ 工具/组件<E7BB84><E4BBB6><EFBFBD>复、REPL hook 架构重构。
### 实现
#### 1. PipeServer TCP 双模式(`src/utils/pipeTransport.ts`
从原始的纯 UDS 服务器扩展为 UDS + TCP 双模式:
- 提取 `setupSocket()` 共享方法UDS 和 TCP 的 socket 处理逻辑完全一致
- `start(options?: PipeServerOptions)` 新增可选参数 `{ enableTcp, tcpPort }`
- 内部维护两个 `net.Server`UDS + TCP共享同一组 `clients: Set<Socket>``handlers`
- TCP server 绑定 `0.0.0.0` + 动态端口port=0 由 OS 分配)
- `tcpAddress` getter 暴露 TCP 端口信息
- `close()` 同时关闭两个 server
- 新增类型:`PipeTransportMode``TcpEndpoint``PipeServerOptions`
PipeClient 对应扩展:
- 构造函数新增可选 `TcpEndpoint` 参数
- `connect()` 根据是否有 TCP endpoint 分派到 `connectTcp()``connectUds()`
- TCP 连接不需要文件存在轮询,直接建立连接
#### 2. LAN Beacon — UDP Multicast 发现(`src/utils/lanBeacon.ts`,新文件)
零配置局域网 peer 发现:
- **协议**UDP multicast 组 `224.0.71.67`"CC" ASCII端口 `7101`TTL=1
- **Announce 包**JSON `{ proto, pipeName, machineId, hostname, ip, tcpPort, role, ts }`
- **广播间隔**3 秒,首次在 socket bind 完成后立即发送
- **Peer 超时**15 秒无 announce 视为 lost
- **事件**`peer-discovered``peer-lost`
- **存储**module-level singleton `getLanBeacon()`/`setLanBeacon()`,不挂在 Zustand state 上
关键修复:
- `addMembership(group, localIp)` + `setMulticastInterface(localIp)` 指定 LAN 网卡,解决 Windows 上 WSL/Docker 虚拟网卡劫持 multicast 的问题
- announce/cleanup 定时器移入 `bind()` 回调内,修复 socket 未就绪时发送的竞态
#### 3. Registry 扩展(`src/utils/pipeRegistry.ts`
- `PipeRegistryEntry` 新增 `tcpPort?``lanVisible?` 字段
- `mergeWithLanPeers(registry, lanPeers)` 合并本地 registry 和 LAN beacon peers本地优先
#### 4. Peer Address 扩展(`src/utils/peerAddress.ts`
- `parseAddress()` 新增 `tcp` scheme`tcp:192.168.1.20:7100`
- 新增 `parseTcpTarget()` 解析 `host:port` 字符串
#### 5. REPL 集成(`src/screens/REPL.tsx`
三个阶段的改动:
**Bootstrap**`createPipeServer()` 时根据 `feature('LAN_PIPES')` 传入 TCP 选项 → 启动 `LanBeacon` → 注册 entry 携带 tcpPort
**Heartbeat**(每 5 秒):
- `refreshDiscoveredPipes()` 同时包含本地 subs 和 LAN beacon peers防止 LAN peer 状态被覆盖
- auto-attach 循环统一遍历本地 subs + LAN peersLAN peers 通过 TCP endpoint 连接
- cleanup 检查 LAN beacon peers 列表,避免误删存活的 LAN 连接
- attach 请求携带 `machineId`,接收方区分 LAN peer不要求 sub 角色)
**Cleanup**:通过 `getLanBeacon()` 获取并 `stop()``setLanBeacon(null)` 清除
#### 6. 命令更新
- `/pipes``src/commands/pipes/pipes.ts`):显示 `[LAN]` 标记的远端实例
- `/attach``src/commands/attach/attach.ts`):自动查找 LAN beacon 获取 TCP endpoint
- `SendMessageTool``src/tools/SendMessageTool/SendMessageTool.ts`):支持 `tcp:` scheme权限检查要求用户确认
#### 7. Feature Flag
`LAN_PIPES` — 在 `scripts/dev.ts``build.ts` 的默认 features 列表中启用。所有 LAN 代码路径均通过 `feature('LAN_PIPES')` 门控。
#### 8. Pipe IPC 基础系统(`UDS_INBOX` feature
- `PipeServer`/`PipeClient`UDS 传输NDJSON 协议(共享 `ndjsonFramer.ts`
- `PipeRegistry`machineId 绑定的角色分配main/sub文件锁并行探测
- Master/slave attach 流程、prompt 转发、permission 转发
- Heartbeat 生命周期5s 间隔stale entry 清理busy flag 防重叠)
- 命令:`/pipes``/attach``/detach``/send``/claim-main``/pipe-status`
#### 9. Monitor Tool`MONITOR_TOOL` feature
- `MonitorTool`AI 可调用的后台 shell 监控工具
- `/monitor` 命令用户快捷入口Windows 兼容watch → PowerShell 循环)
- `MonitorMcpTask`:从 stub 恢复完整生命周期register/complete/fail/kill
- `MonitorPermissionRequest`React 权限确认 UI
- `MonitorMcpDetailDialog`Shift+Down 详情面板
#### 10. 工具恢复stub → 实现)
- SnipTool、SleepTool、ListPeersTool、SendUserFileTool
- WebBrowserTool、SubscribePRTool、PushNotificationTool
- CtxInspectTool、TerminalCaptureTool、WorkflowTool
- REPLTool (.js → .ts)、VerifyPlanExecutionTool (.js → .ts)、SuggestBackgroundPRTool (.js → .ts)
- 组件 .ts → .tsx 重写MonitorPermissionRequest、ReviewArtifactPermissionRequest、MonitorMcpDetailDialog、WorkflowDetailDialog、WorkflowPermissionRequest
#### 11. REPL Hook 架构重构
从 REPL.tsx 提取 ~830 行 Pipe IPC 内联代码为 4 个独立 hook
| Hook | 行数 | 职责 |
|------|------|------|
| `usePipeIpc` | 623 | 生命周期bootstrap、handlers、heartbeat、cleanup |
| `usePipeRelay` | 38 | slave→master 消息回传(通过 `setPipeRelay` singleton |
| `usePipePermissionForward` | 159 | 权限请求转发 + 流式通知显示 |
| `usePipeRouter` | 130 | selected pipe 输入路由 + role/IP 标签显示 |
共享工具:`ndjsonFramer.ts` 替换 3 份重复的 NDJSON 解析。
#### 12. Feature Flags 新增启用
UDS_INBOX、LAN_PIPES、MONITOR_TOOL、FORK_SUBAGENT、KAIROS、COORDINATOR_MODE、WORKFLOW_SCRIPTS、HISTORY_SNIP、CONTEXT_COLLAPSE
### 踩坑记录
1. **Multicast 绑错网卡**Windows 上 `addMembership(group)` 不指定本地接口时,默认绑到 WSL/Docker 虚拟网卡(`172.19.112.1`LAN 上的真实机器收不到。必须 `addMembership(group, localIp)` + `setMulticastInterface(localIp)`
2. **Beacon ref 丢失**:最初用 `(store.getState() as any)._lanBeacon` 挂载 beacon 引用,但 Zustand `setState` 展开 `prev` 时不包含 `_lanBeacon` 属性,下次读取就是 `undefined`。改为 module-level singleton 解决。
3. **Heartbeat 清洗 LAN 连接**`refreshDiscoveredPipes()` 每 5 秒用仅含本地 registry subs 的列表完全覆盖 `discoveredPipes` + `selectedPipes`LAN peer 的发现和选择状态被持续清空。必须在 refresh 中同时包含 beacon peers。
4. **Heartbeat cleanup 误删**`!aliveSubNames.has(slaveName)` 导致 LAN peer不在本地 registry被判定为死连接每 5 秒清除一次。需要同时检查 beacon peers 列表。
5. **跨机器 attach 被拒**:两台机器各自为 `main`attach handler 硬编码 `role !== 'sub'` 拒绝。通过 attach_request 携带 `machineId`,接收方对不同 machineId 的请求放行。
6. **`feature()` 使用约束**Bun 的 `feature()` 是编译时常量,只能在 `if` 语句或三元条件中直接使用,不能赋值给变量(如 `const x = feature('...')`),否则构建报错。
### 已知限制
- TCP 无认证:同 LAN 内任何设备知道端口号即可连接
- JSON.parse 无 schema 验证code review 建议增加 Zod 校验
- Beacon 明文广播 IP/hostname/machineId建议后续 hash 处理
- `getLocalIp()` 可能返回 VPN 地址:多网卡环境需更精确的接口选择
### 测试
- `src/utils/__tests__/lanBeacon.test.ts`7 个测试mock dgram
- `src/utils/__tests__/peerAddress.test.ts`8 个测试(纯函数)
- 全量2190 pass / 0 fail
### 防火墙配置
**Windows**(管理员 PowerShell
```powershell
New-NetFirewallRule -DisplayName "Claude Code LAN Beacon (UDP)" -Direction Inbound -Protocol UDP -LocalPort 7101 -Action Allow -Profile Private
New-NetFirewallRule -DisplayName "Claude Code LAN Pipes (TCP)" -Direction Inbound -Protocol TCP -LocalPort 1024-65535 -Program (Get-Command bun).Source -Action Allow -Profile Private
New-NetFirewallRule -DisplayName "Claude Code LAN Beacon Out (UDP)" -Direction Outbound -Protocol UDP -RemotePort 7101 -Action Allow -Profile Private
```
**macOS**(首次运行时系统会弹出"允许接受传入连接"对话框,点击允许即可。手动放行):
```bash
# 如果使用 pf <20><><EFBFBD>火墙添加规则
echo "pass in proto udp from any to any port 7101" | sudo pfctl -ef -
# 或<><E68896>接在 System Settings → Network → Firewall 中允许 bun 进程
```
**Linux**firewalld
```bash
sudo firewall-cmd --zone=trusted --add-port=7101/udp --permanent
sudo firewall-cmd --zone=trusted --add-port=1024-65535/tcp --permanent
sudo firewall-cmd --reload
```
**Linux**iptables
```bash
sudo iptables -A INPUT -p udp --dport 7101 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 1024:65535 -m owner --uid-owner $(id -u) -j ACCEPT
sudo iptables-save | sudo tee /etc/iptables/rules.v4
```
**通用验证**:确认网络为局域网(非公共 WiFi<EFBC8C><E8B7AF><EFBFBD>器未开启 AP 隔离。
---
## Daemon + Remote Control Server 还原 (2026-04-07)
**分支**: `feat/daemon-remote-control-server`
### 背景
`src/commands.ts` 注册了 `remoteControlServer` 命令(双重门控 `feature('DAEMON') && feature('BRIDGE_MODE')`),但 `src/commands/remoteControlServer/` 目录缺失,`src/daemon/main.ts``src/daemon/workerRegistry.ts` 均为 stub。官方 CLI 2.1.92 中情况一致——Anthropic 已预留注册点和底层 `runBridgeHeadless()` 实现但中间层daemon supervisor + command 入口)未发布。
通过逐级反向追踪调用链还原完整实现:
```
/remote-control-server (slash command)
→ spawn: claude daemon start
→ daemonMain() (supervisor管理 worker 生命周期)
→ spawn: claude --daemon-worker=remoteControl
→ runDaemonWorker('remoteControl')
→ runBridgeHeadless(opts, signal) ← 已有完整实现
→ runBridgeLoop() → 接受远程会话
```
### 实现
#### 1. Worker Registry`src/daemon/workerRegistry.ts`
从 stub 还原为 worker 分发器:
- `runDaemonWorker(kind)``kind` 分发到不同 worker 实现
- `runRemoteControlWorker()` 从环境变量(`DAEMON_WORKER_*`)读取配置,构造 `HeadlessBridgeOpts`,调用 `runBridgeHeadless()`
- 区分 permanent`EXIT_CODE_PERMANENT = 78`)和 transient 错误supervisor 据此决定重试或 park
- SIGTERM/SIGINT 信号处理,通过 `AbortController` 传递给 bridge loop
#### 2. Daemon Supervisor`src/daemon/main.ts`
从 stub 还原为完整 supervisor 进程:
- `daemonMain(args)` 支持子命令:`start`(启动)、`status``stop``--help`
- `runSupervisor()` spawn `remoteControl` worker 子进程,通过环境变量传递配置
- 指数退避重启2s → 120s10s 内连续崩溃 5 次则 park worker
- permanent exit code78直接 park不重试
- graceful shutdownSIGTERM → 转发给 worker → 30s grace → SIGKILL
- CLI 参数支持:`--dir``--spawn-mode``--capacity``--permission-mode``--sandbox``--name`
#### 3. Remote Control Server 命令(`src/commands/remoteControlServer/`
**`index.ts`** — Command 注册:
- 类型 `local-jsx`,名称 `/remote-control-server`,别名 `/rcs`
- 双 feature 门控:`feature('DAEMON') && feature('BRIDGE_MODE')` + `isBridgeEnabled()`
- lazy load `remoteControlServer.tsx`
**`remoteControlServer.tsx`** — REPL 内 UI
- 首次调用前置检查bridge 可用性 + OAuth token→ spawn daemon 子进程
- 再次调用:弹出管理对话框(停止/重启/继续),显示 PID 和最近 5 行日志
- 模块级 state 跨调用保持 daemon 进程引用
- graceful stopSIGTERM → 10s grace → SIGKILL
#### 4. Feature Flag 启用
`build.ts` / `scripts/dev.ts``DEFAULT_BUILD_FEATURES` / `DEFAULT_FEATURES` 新增 `DAEMON`
DAEMON 仅有编译时 feature flag 门控,无 GrowthBook gate。
### 与 `/remote-control` 的区别
| | `/remote-control` | `/remote-control-server` (daemon) |
|---|---|---|
| 模式 | 单会话REPL 内交互式 bridge | 多会话daemon 持久化服务器 |
| 生命周期 | 跟 REPL 会话绑定 | 独立后台进程,崩溃自动重启 |
| 并发 | 1 个远程连接 | 默认 4 个,可配置 `--capacity` |
| 隔离 | 共享当前目录 | 支持 `worktree` 模式隔离 |
| 底层 | `initReplBridge()` | `runBridgeHeadless()``runBridgeLoop()` |
### 修改文件
| 文件 | 变更 |
|------|------|
| `build.ts` | `DEFAULT_BUILD_FEATURES` 新增 `DAEMON` |
| `scripts/dev.ts` | `DEFAULT_FEATURES` 新增 `DAEMON` |
| `src/daemon/main.ts` | 从 stub 还原为 supervisor 实现 |
| `src/daemon/workerRegistry.ts` | 从 stub 还原为 worker 分发器 |
| `src/commands/remoteControlServer/index.ts` | **新增** command 注册 |
| `src/commands/remoteControlServer/remoteControlServer.tsx` | **新增** REPL UI |
### 验证
| 项目 | 结果 |
|------|------|
| `bun run build` | ✅ 成功 (490 files) |
| tsc 新文件检查 | ✅ 无新增类型错误 |
### 使用方式
```bash
# CLI 直接启动 daemon
bun run dev daemon start
bun run dev daemon start --spawn-mode=worktree --capacity=8
# REPL 内
/remote-control-server # 或 /rcs
```
前提:需要 Anthropic OAuth 登录(`claude login`)。
---
## /ultraplan 启用 + GrowthBook Fallback 加固 + Away Summary 改进 (2026-04-06)
**分支**: `feat/ultraplan-enablement`
**Commit**: `feat: enable /ultraplan and harden GrowthBook fallback chain`
### 背景
`/ultraplan` 是 Claude Code 的高级多代理规划功能:将任务发送到 Claude Code on the webCCR由 Opus 进行深度规划,计划完成后返回终端供用户审批和执行。此功能被 3 层门控锁定:`feature('ULTRAPLAN')` 编译 flag + `isEnabled: () => USER_TYPE === 'ant'` + `INTERNAL_ONLY_COMMANDS` 列表。
另外发现 GrowthBook fallback 链在 config 未初始化时会抛异常跳过 `LOCAL_GATE_DEFAULTS`,以及 Away Summary 在不支持 DECSET 1004 focus 事件的终端CMD/PowerShell上不工作。
### 实现
#### 1. Ultraplan 启用
- `build.ts` / `scripts/dev.ts`: 添加 `ULTRAPLAN` 到默认编译 flag
- `src/commands.ts`: 将 ultraplan 从 `INTERNAL_ONLY_COMMANDS` 移入公开 `COMMANDS` 列表
- `src/commands/ultraplan.tsx`: `isEnabled` 改为 `() => true`
- `src/screens/REPL.tsx`: 添加 `UltraplanChoiceDialog``UltraplanLaunchDialog``launchUltraplan` 的 importHEAD 版使用但未 import构建报 `not defined`
#### 2. 反编译 UltraplanChoiceDialog / UltraplanLaunchDialog
REPL.tsx 引用这两个组件但代码库中不存在。从官方 CLI 2.1.92 的 `cli.js` 中定位 minified 函数 `M15`UltraplanChoiceDialog`P15`UltraplanLaunchDialog通过符号映射表反编译为可读 TSX。
**`src/components/ultraplan/UltraplanChoiceDialog.tsx`** — 远程计划批准后的选择对话框:
- 3 个选项Implement here注入当前会话/ Start new session清空会话重开/ Cancel保存到 .md 文件)
- 可滚动计划预览ctrl+u/d 翻页,鼠标滚轮),自适应终端高度
- 选择后标记远程 task 完成、清除 `ultraplanPendingChoice` 状态、归档远程 CCR session
**`src/components/ultraplan/UltraplanLaunchDialog.tsx`** — 启动确认对话框:
- 显示功能说明、时间估计(~1030 min、服务条款链接
- 处理 Remote Control bridge 冲突(选择 run 时自动断开 bridge
- 首次使用时持久化 `hasSeenUltraplanTerms` 到全局配置
反编译要点:剥离 React Compiler `_c(N)` 缓存数组,还原为标准 `useMemo`/`useCallback``useFocusedInputDialog()` 注册 hook 省略REPL 内部计算 `focusedInputDialog`GrowthBook 配置查询替换为本地默认值。
#### 3. GrowthBook Fallback 加固
`src/services/analytics/growthbook.ts`:
- `getFeatureValue_CACHED_MAY_BE_STALE`: 将 `getLocalGateDefault()` 查找移到 try/catch 外层
- `checkStatsigFeatureGate_CACHED_MAY_BE_STALE`: 同上config 读取包裹在 try/catch 中
修复前config 未初始化 → `getGlobalConfig()` 抛异常 → catch 直接返回 `defaultValue` → 跳过 `LOCAL_GATE_DEFAULTS`
修复后config 未初始化 → catch 静默 → 继续查 `LOCAL_GATE_DEFAULTS` → 有默认值就用,没有才 fallback
#### 4. Away Summary 改进Windows 终端兼容)
**问题**Away Summary`feature('AWAY_SUMMARY')` + `tengu_sedge_lantern` gate上一轮已启用依赖 DECSET 1004 终端 focus 事件检测用户是否离开。但 Windows 的 CMD 和 PowerShell 不支持此协议,`getTerminalFocusState()` 始终返回 `'unknown'`,原逻辑对 `'unknown'` 状态执行 no-op导致 Windows 用户永远无法触发离开摘要。
**修改**`src/hooks/useAwaySummary.ts`
1. **focus 状态处理**`'unknown'` 现在视同 `'blurred'`(可能已离开),订阅时即启动 idle timer5 分钟)
2. **idle-based 在场检测**:新增 `isLoading` 转换监听作为用户活跃信号替代 focus 事件:
- 用户发起新 turn`isLoading``true`)→ 说明在场,取消 idle timer + abort 进行中的生成
- turn 结束(`isLoading``false`)→ 重启 idle timer
- timer 到期且无进行中 turn → 触发 away summary 生成
3. **兼容性**:仅在 `getTerminalFocusState() === 'unknown'` 时激活 idle 逻辑,支持 DECSET 1004 的终端iTerm2、Windows Terminal、kitty 等)仍走原有 blur/focus 路径
**效果**Windows CMD/PowerShell 用户离开终端 5 分钟后,系统自动调用 API 生成摘要并作为 `away_summary` 类型的系统消息追加到对话流中,用户回来时直接在 UI 中看到,无需执行任何命令
#### 5. Cron 定时任务管理技能
`src/skills/bundled/cronManage.ts`**新增**+ `src/skills/bundled/index.ts`
KAIROS 定时任务系统(`tengu_kairos_cron` gate已在上一轮 GrowthBook 启用中开启)提供了 `ScheduleCronTool` 来创建定时任务,但缺少用户可调用的 list/delete 技能。新增两个 bundled skill 补全管理闭环:
| 技能 | 用法 | 功能 |
|------|------|------|
| `/cron-list` | `/cron-list` | 调用 `CronListTool` 列出所有定时任务,表格显示 ID、Schedule、Prompt、Recurring、Durable |
| `/cron-delete` | `/cron-delete <job-id>` | 调用 `CronDeleteTool` 按 ID 取消指定定时任务 |
两个技能均受 `isKairosCronEnabled()` 门控(`feature('AGENT_TRIGGERS') && tengu_kairos_cron` gate`ScheduleCronTool` 保持一致。
#### 6. Fullscreen 门控修复
- `src/utils/fullscreen.ts`: `isFullscreenEnvEnabled()` 从无条件返回 `true` 改为 `process.env.USER_TYPE === 'ant'`,避免非 ant 用户意外触发全屏模式
### 修改文件
| 文件 | 变更 |
|------|------|
| `build.ts` | `DEFAULT_BUILD_FEATURES` 新增 `ULTRAPLAN` |
| `scripts/dev.ts` | `DEFAULT_FEATURES` 新增 `ULTRAPLAN` |
| `src/commands.ts` | ultraplan 移入公开命令列表 |
| `src/commands/ultraplan.tsx` | `isEnabled` 移除 ant-only 限制 |
| `src/components/ultraplan/UltraplanChoiceDialog.tsx` | **新增** 从 2.1.92 反编译 |
| `src/components/ultraplan/UltraplanLaunchDialog.tsx` | **新增** 从 2.1.92 反编译 |
| `src/screens/REPL.tsx` | 添加 3 个 import |
| `src/services/analytics/growthbook.ts` | fallback 链加固 |
| `src/hooks/useAwaySummary.ts` | idle-based 离开检测 |
| `src/skills/bundled/index.ts` | 注册 cron 技能 |
| `src/skills/bundled/cronManage.ts` | **新增** cron list/delete 技能 |
| `src/utils/fullscreen.ts` | fullscreen 门控修复 |
### 验证
| 项目 | 结果 |
|------|------|
| `bun run build` | ✅ 成功 (480 files) |
| `bun run lint` | ✅ 仅已有 biome-ignore 警告 |
| `/ultraplan` 手动测试 | ✅ 命令注册可见、能启动远程会话、能接收回传计划并显示 ChoiceDialog |
### Ultraplan 工作流
```
/ultraplan <prompt>
→ UltraplanLaunchDialog 确认
→ teleportToRemote 创建 CCR 远程会话
→ pollForApprovedExitPlanMode 轮询3s 间隔30min 超时)
→ ExitPlanModeScanner 解析事件流
→ 计划 approved → UltraplanChoiceDialog 显示选择
→ Implement here / Start new session / Cancel
```
需要 Anthropic OAuth`/login`)。远程会话在 claude.ai/code 上运行。
---
## GrowthBook Local Gate Defaults + P0/P1 Feature Enablement (2026-04-06)
**分支**: `feat/growthbook-enablement`
### 背景
Claude Code 使用 GrowthBookAnthropic 自建 proxy at api.anthropic.com进行远程功能开关控制代码中使用 `tengu_*` 前缀命名。在反编译版本中 GrowthBook 不启动analytics 空实现),导致 70+ 个功能被 gate 拦截。
经 4 个并行研究代理深度分析,确认**所有被 gate 控制的功能代码都是真实现**(非 stub
### 实现方案
**Commit 1** (`feat`): 在 `growthbook.ts` 中添加 `LOCAL_GATE_DEFAULTS` 映射表25+ boolean gates + 2 object config gates修改 4 个 getter 函数在 `isGrowthBookEnabled() === false` 时查找本地默认值。
**Commit 2** (`fix`): 发现 `LOCAL_GATE_DEFAULTS` 在有 API key 的用户环境下无效——因为 `isGrowthBookEnabled()` 返回 `true`analytics 未禁用),代码走 GrowthBook 路径但缓存为空,直接返回 `defaultValue` 跳过了本地默认值。修复:在 3 个 getter 函数的缓存 miss 路径中插入 `LOCAL_GATE_DEFAULTS` 查找。同时修复 `tengu_onyx_plover` 值类型(`JSON.stringify` → 直接对象)和新增 `tengu_kairos_brief_config` 对象型 gate。
修复后的 fallback 链:
```
env overrides → config overrides → [GrowthBook 启用?]
→ 内存缓存 → 磁盘缓存 → LOCAL_GATE_DEFAULTS → defaultValue
```
可通过 `CLAUDE_CODE_DISABLE_LOCAL_GATES=1` 环境变量一键禁用。
### 启用的功能
**P0 — 纯本地功能7 个 gate**
| Gate | 功能 |
|------|------|
| `tengu_keybinding_customization_release` | 自定义快捷键(~/.claude/keybindings.json |
| `tengu_streaming_tool_execution2` | 流式工具执行(边收边执行) |
| `tengu_kairos_cron` | 定时任务系统 |
| `tengu_amber_json_tools` | Token 高效 JSON 工具格式(省 ~4.5% |
| `tengu_immediate_model_command` | 运行中即时切换模型 |
| `tengu_basalt_3kr` | MCP 指令增量传输 |
| `tengu_pebble_leaf_prune` | 会话存储叶剪枝优化 |
**P1 — API 依赖功能8 个 gate**
| Gate | 功能 |
|------|------|
| `tengu_session_memory` | 会话记忆(跨会话上下文持久化) |
| `tengu_passport_quail` | 自动记忆提取 |
| `tengu_chomp_inflection` | 提示建议 |
| `tengu_hive_evidence` | 验证代理(对抗性验证) |
| `tengu_kairos_brief` | Brief 精简输出模式 |
| `tengu_sedge_lantern` | 离开摘要 |
| `tengu_onyx_plover` | 自动梦境(记忆巩固) |
| `tengu_willow_mode` | 空闲返回提示 |
**Kill Switch10 个 gate 保持 true**
`tengu_turtle_carbon``tengu_amber_stoat``tengu_amber_flint``tengu_slim_subagent_claudemd``tengu_birch_trellis``tengu_collage_kaleidoscope``tengu_compact_cache_prefix``tengu_kairos_cron_durable``tengu_attribution_header``tengu_slate_prism`
**新增编译 flag**
| Flag | build.ts | dev.ts | 用途 |
|------|:--------:|:------:|------|
| `AGENT_TRIGGERS` | ON | ON | 定时任务系统 |
| `EXTRACT_MEMORIES` | ON | ON | 自动记忆提取 |
| `VERIFICATION_AGENT` | ON | ON | 对抗性验证代理 |
| `KAIROS_BRIEF` | ON | ON | Brief 精简模式 |
| `AWAY_SUMMARY` | ON | ON | 离开摘要 |
| `ULTRATHINK` | ON | ON | Ultrathink 扩展思考(双重门控修复) |
| `BUILTIN_EXPLORE_PLAN_AGENTS` | ON | ON | 内置 Explore/Plan agents双重门控修复 |
| `LODESTONE` | ON | ON | Deep link 协议注册(双重门控修复) |
**排除的编译 flag**
- `KAIROS` — 拉入 `useProactive.js`(缺失文件),`KAIROS_BRIEF` 足够
- `TERMINAL_PANEL` — 拉入 `TerminalCaptureTool`(缺失文件)
**双重门控修复说明:**
部分功能同时被编译 flag 和 GrowthBook gate 控制(双重门控),仅开 GrowthBook gate 不够。
审计发现 3 个被卡住的:`ULTRATHINK``BUILTIN_EXPLORE_PLAN_AGENTS``LODESTONE`
### 修改文件
| 文件 | 变更 |
|------|------|
| `build.ts` | `DEFAULT_BUILD_FEATURES` 新增 8 个编译 flag |
| `scripts/dev.ts` | `DEFAULT_FEATURES` 新增 8 个编译 flag |
| `src/services/analytics/growthbook.ts` | 新增 `LOCAL_GATE_DEFAULTS` 映射27 gates+ `getLocalGateDefault()` + 修改 4 个 getter 的 fallback 链 |
| `scripts/verify-gates.ts` | 新增 gate 验证脚本30 gates |
| `docs/features/growthbook-enablement-plan.md` | 完整研究报告和启用计划 |
| `docs/features/feature-flags-audit-complete.md` | 更新启用状态表 |
### 验证
| 项目 | 结果 |
|------|------|
| `bun run build` | ✅ 成功 (481 files) |
| `bun test` | ✅ 2106 pass / 23 fail均为已有问题/ 0 新增失败 |
| `verify-gates.ts` | ✅ 30/30 PASS |
| `/brief` 手动测试 | ✅ 可用fallback 修复后) |
---
## Enable SHOT_STATS, TOKEN_BUDGET, PROMPT_CACHE_BREAK_DETECTION (2026-04-05)
**PR**: [claude-code-best/claude-code#140](https://github.com/claude-code-best/claude-code/pull/140)
**分支**: `feat/enable-safe-feature-flags`
对 22 个被标记为 "COMPLETE" 的编译时 feature flag 进行实际源码验证6 个并行子代理 + Codex CLI 独立复核),发现审计报告存在大量误判。最终确认仅 3 个 flag 为真正 compile-only安全启用。
**验证流程:**
1. 6 个并行子代理分别检查每个 flag 的 `feature('FLAG_NAME')` 引用点、依赖模块完整性、外部服务依赖
2. Codex CLI (v0.118.0, 240K tokens) 独立复核,将原 7 个 "compile-only" 进一步缩减为 3 个
3. 3 个专项代理逐一验证代码路径完整性和运行时安全性
**新启用的 3 个 flag**
| Flag | 功能 | 用户可感知效果 |
|------|------|---------------|
| `SHOT_STATS` | shot 分布统计 | `/stats` 面板显示 shot 分布和 one-shot rate |
| `TOKEN_BUDGET` | token 预算目标 | 支持 `+500k` / `spend 2M tokens` 语法,自动续写直到达标,带进度条 |
| `PROMPT_CACHE_BREAK_DETECTION` | cache key 变化检测 | 内部诊断,`--debug` 模式可见,写 diff 到临时目录 |
**修改文件:**
| 文件 | 变更 |
|------|------|
| `build.ts` | `DEFAULT_BUILD_FEATURES` 新增 3 个 flag |
| `scripts/dev.ts` | `DEFAULT_FEATURES` 新增 3 个 flag |
| `package.json` / `bun.lock` | 新增 `openai` 依赖OpenAI 兼容层需要) |
**新增文档:**
| 文件 | 说明 |
|------|------|
| `docs/features/feature-flags-codex-review.md` | Codex 独立复核报告:修正后的 5 类分类、恢复优先级、三轴分类标准建议 |
| `docs/features/feature-flags-audit-complete.md` | 标记所有已启用 flag 的状态(`[build: ON]` / `[dev: ON]` |
**Codex 复核关键发现:**
- 原 22 个 "COMPLETE" flag 中8 个核心模块是 stub3 个依赖远程服务
- `TEAMMEM``AGENT_TRIGGERS``EXTRACT_MEMORIES``KAIROS_BRIEF` 被降级为"有条件可用"(受 GrowthBook 门控)
- 建议审计分类标准改为三轴:实现完整度 × 激活条件 × 运行风险
- 恢复优先级REACTIVE_COMPACT > BG_SESSIONS > PROACTIVE > CONTEXT_COLLAPSE
**验证结果:**
- `bun run build` → 475 files ✅
- `bun test` → 零新增失败 ✅
- 3 个 flag 代码路径全部完整,无缺失依赖,无 crash 风险 ✅
---
## /dream 手动触发 + DreamTask 类型补全 (2026-04-04)
`/dream` 命令从 KAIROS feature gate 中解耦,作为 bundled skill 无条件注册;补全 DreamTask 类型存根。
**新增文件:**
| 文件 | 说明 |
|------|------|
| `src/skills/bundled/dream.ts` | `/dream` skill 注册,调用 `buildConsolidationPrompt()` 生成整理提示词 |
**修改文件:**
| 文件 | 变更 |
|------|------|
| `src/skills/bundled/index.ts` | 导入并注册 `registerDreamSkill()` |
| `src/components/tasks/src/tasks/DreamTask/DreamTask.ts` | `any` 存根 → 从 `src/tasks/DreamTask/DreamTask.js` 重新导出完整类型 |
**新增文档:**
| 文件 | 说明 |
|------|------|
| `docs/features/auto-dream.md` | Auto Dream 原理、触发机制、使用场景完整说明 |
---
## Computer Use macOS 适配修复 (2026-04-04)
**分支**: `feature/computer-use/mac-support`
- **darwin.ts** — 应用枚举改用 Spotlight `mdfind` + `mdls`,获取真实 bundleId旧方案合成 `com.app.xxx`),覆盖 `/Applications` + `/System/Applications` + CoreServices
- **index.ts** — 新增 `hotkey` backend fallback非原生模块不崩溃
- **toolCalls.ts** — `resolveRequestedApps()` 新增子串模糊匹配(`"Chrome"``"Google Chrome"`
- **hostAdapter.ts** — `ensureOsPermissions()` 检查 `cu.tcc` 存在性,跨平台 JS backend 安全降级
- **测试**: 17 个 MCP 工具中 10 个完全通过6 个在 full tier 应用上通过IDE click tier 受限为预期行为),`screenshot` 未返回图片(疑似屏幕录制权限问题)
---
## Computer Use Windows 增强:窗口绑定截图 + UI Automation + OCR (2026-04-03)
在三平台基础实现之上,利用 Windows 原生 API 增强 Computer Use 的 Windows 专属能力。
**新增文件:**
| 文件 | 行数 | 说明 |
|------|------|------|
| `src/utils/computerUse/win32/windowCapture.ts` | — | `PrintWindow` 窗口绑定截图,支持被遮挡/后台窗口 |
| `src/utils/computerUse/win32/windowEnum.ts` | — | `EnumWindows` 精确窗口枚举HWND + PID + 标题) |
| `src/utils/computerUse/win32/uiAutomation.ts` | — | `IUIAutomation` UI 元素树读取、按钮点击、文本写入、坐标识别 |
| `src/utils/computerUse/win32/ocr.ts` | — | `Windows.Media.Ocr` 截图+文字识别(英语+中文) |
**修改文件:**
| 文件 | 变更 |
|------|------|
| `packages/@ant/computer-use-swift/src/backends/win32.ts` | `listRunning` 改用 EnumWindows新增 `captureWindowTarget` 窗口级截图 |
**验证结果Windows x64**
- 窗口枚举38 个可见窗口 ✅
- 窗口截图VS Code 2575x1415, 444KB ✅PrintWindow, 即使被遮挡)
- UI Automation坐标元素识别 ✅
- OCR识别 VS Code 界面文字34 行 ✅
---
## Enable Computer Use — macOS + Windows + Linux (2026-04-03)
恢复 Computer Use 屏幕操控功能。参考项目仅 macOS本次扩展为三平台支持。
**Phase 1 — MCP server stub 替换:**
从参考项目复制 `@ant/computer-use-mcp` 完整实现12 文件6517 行)。
**Phase 2 — 移除 src/ 中 8 处 macOS 硬编码:**
| 文件 | 改动 |
|------|------|
| `src/main.tsx:1605` | 去掉 `getPlatform() === 'macos'` |
| `src/utils/computerUse/swiftLoader.ts` | 移除 darwin-only throw |
| `src/utils/computerUse/executor.ts` | 平台守卫扩展为 darwin+win32+linux剪贴板按平台分发pbcopy→PowerShell→xclippaste 快捷键 command→ctrl |
| `src/utils/computerUse/drainRunLoop.ts` | 非 darwin 直接执行 fn() |
| `src/utils/computerUse/escHotkey.ts` | 非 darwin 返回 falseCtrl+C fallback |
| `src/utils/computerUse/hostAdapter.ts` | 非 darwin 权限检查返回 granted |
| `src/utils/computerUse/common.ts` | platform + screenshotFiltering 动态化 |
| `src/utils/computerUse/gates.ts` | enabled:true + hasRequiredSubscription→true |
**Phase 3 — input/swift 包 dispatcher + backends 三平台架构:**
```
packages/@ant/computer-use-{input,swift}/src/
├── index.ts ← dispatcher
├── types.ts ← 共享接口
└── backends/
├── darwin.ts ← macOS AppleScript原样拆出不改逻辑
├── win32.ts ← Windows PowerShell
└── linux.ts ← Linux xdotool/scrot/xrandr/wmctrl
```
**编译开关:** `CHICAGO_MCP` 加入 DEFAULT_FEATURES + DEFAULT_BUILD_FEATURES
**验证结果Windows x64**
- `isSupported: true`
- 鼠标定位 + 前台窗口信息 ✅
- 双显示器检测 2560x1440 × 2 ✅
- 全屏截图 3MB base64 ✅
- `bun run build` 463 files ✅
---
## Enable Voice Mode / VOICE_MODE (2026-04-03)
恢复 `/voice` 语音输入功能。`src/` 下所有 voice 相关源码已与官方一致0 行差异),问题出在:① `VOICE_MODE` 编译开关未开,命令不显示;② `audio-capture-napi` 是 SoX 子进程 stubWindows 不支持),缺少官方原生 `.node` 二进制。
**新增文件:**
| 文件 | 说明 |
|------|------|
| `vendor/audio-capture/{platform}/audio-capture.node` | 6 个平台的原生音频二进制cpal来自参考项目 |
| `vendor/audio-capture-src/index.ts` | 原生模块加载器(按 `${arch}-${platform}` 动态 require `.node` |
---
## Enable Claude in Chrome MCP (2026-04-03)
恢复 Chrome 浏览器控制功能。`src/` 下所有 claudeInChrome 相关源码已与官方一致0 行差异),问题出在 `@ant/claude-for-chrome-mcp` 包是 6 行 stub返回空工具列表和 null server
**替换文件:**
| 文件 | 变更 |
|------|------|
| `packages/@ant/claude-for-chrome-mcp/src/index.ts` | 6 行 stub → 15 行完整导出 |
**新增文件:**
| 文件 | 行数 | 说明 |
|------|------|------|
| `packages/@ant/claude-for-chrome-mcp/src/types.ts` | 134 | 类型定义 |
| `packages/@ant/claude-for-chrome-mcp/src/browserTools.ts` | 546 | 17 个浏览器工具定义 |
| `packages/@ant/claude-for-chrome-mcp/src/mcpServer.ts` | 96 | MCP Server |
| `packages/@ant/claude-for-chrome-mcp/src/mcpSocketClient.ts` | 493 | Unix Socket 客户端 |
| `packages/@ant/claude-for-chrome-mcp/src/mcpSocketPool.ts` | 327 | 多 Profile 连接池 |
| `packages/@ant/claude-for-chrome-mcp/src/bridgeClient.ts` | 1126 | Bridge WebSocket 客户端 |
| `packages/@ant/claude-for-chrome-mcp/src/toolCalls.ts` | 301 | 工具调用路由 |
**不需要 feature flag不需要改 dev.ts/build.ts不改 src/ 下任何文件。**
**运行时依赖:** Chrome 浏览器 + Claude in Chrome 扩展https://claude.ai/chrome
---
## OpenAI 接口兼容 (2026-04-03)
**分支**: `feature/openai`
`/login` 流程中新增 "OpenAI Compatible" 选项,支持 Ollama、DeepSeek、vLLM、One API 等兼容 OpenAI Chat Completions API 的第三方服务。用户通过 `/login` 配置后,所有 API 请求自动走 OpenAI 路径。
**改动文件10 个,+384 / -134**
| 文件 | 变更 |
|------|------|
| `.github/workflows/ci.yml` | CI runner 从 `ubuntu-latest` 改为 `macos-latest` |
| `README.md` | TODO 列表新增 "OpenAI 接口兼容" 条目 |
| `src/components/ConsoleOAuthFlow.tsx` | 新增 `openai_chat_api` OAuth state含 Base URL / API Key / 3 个模型映射字段idle 选择列表新增 "OpenAI Compatible" 选项;完整表单 UITab 切换、Enter 保存);保存时写入 `modelType: 'openai'` + env 到 settings.jsonOAuth 登录时重置 `modelType``anthropic` |
| `src/services/api/openai/index.ts` | 从直接 `yield* adaptOpenAIStreamToAnthropic()` 改为完整流处理循环:累积 content blockstext/tool_use/thinking、按 `content_block_stop` yield `AssistantMessage`、同时 yield `StreamEvent` 用于实时显示;错误处理改用新签名 `createAssistantAPIErrorMessage({ content, apiError, error })` |
| `src/services/api/openai/convertMessages.ts` | 输入类型从 Anthropic SDK `BetaMessageParam[]` 改为内部 `(UserMessage \| AssistantMessage)[]`;通过 `msg.type` 而非 `msg.role` 判断角色;从 `msg.message.content` 读取内容;跳过 `cache_edits` / `server_tool_use` 等内部 block 类型 |
| `src/services/api/openai/modelMapping.ts` | 移除 `OPENAI_MODEL_MAP` JSON 环境变量 + 缓存机制;新增 `getModelFamily()` 按 haiku/sonnet/opus 分类;解析优先级改为:`OPENAI_MODEL``ANTHROPIC_DEFAULT_{FAMILY}_MODEL``DEFAULT_MODEL_MAP` → 原名透传 |
| `src/services/api/openai/__tests__/convertMessages.test.ts` | 测试输入从裸 `{ role, content }` 改为 `makeUserMsg()` / `makeAssistantMsg()` 包装的内部格式 |
| `src/services/api/openai/__tests__/modelMapping.test.ts` | 测试从 `OPENAI_MODEL_MAP` 改为 `ANTHROPIC_DEFAULT_{HAIKU,SONNET,OPUS}_MODEL`;新增 3 个 env var override 测试 |
| `src/utils/model/providers.ts` | `getAPIProvider()` 新增最高优先级:从 settings.json `modelType` 字段判断;环境变量 `CLAUDE_CODE_USE_OPENAI` 降为次优先 |
| `src/utils/settings/types.ts` | `SettingsSchema` 新增 `modelType` 字段:`z.enum(['anthropic', 'openai']).optional()` |
**关键设计决策:**
1. **`modelType` 存入 settings.json** — 而非纯环境变量,使 `/login` 配置持久化,重启后仍然生效
2. **复用 `ANTHROPIC_DEFAULT_*_MODEL` 环境变量** — 而非新增 `OPENAI_MODEL_MAP`,与 Custom Platform 共用同一套模型映射配置,减少用户认知负担
3. **流处理双 yield** — 同时 yield `AssistantMessage`(给消费方处理工具调用)和 `StreamEvent`(给 REPL 实时渲染),与 Anthropic 路径行为对齐
4. **OAuth 登录重置 modelType** — 用户切换回官方 Anthropic 登录时自动重置为 `anthropic`,避免残留配置导致请求走错误路径
**配置方式:**
```
/login → 选择 "OpenAI Compatible" → 填写 Base URL / API Key / 模型名称
```
或手动编辑 `~/.claude/settings.json`
```json
{
"modelType": "openai",
"env": {
"OPENAI_BASE_URL": "http://localhost:11434/v1",
"OPENAI_API_KEY": "ollama",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "qwen3:32b"
}
}
```
---
## Enable Remote Control / BRIDGE_MODE (2026-04-03)
**PR**: [claude-code-best/claude-code#60](https://github.com/claude-code-best/claude-code/pull/60)
Remote Control 功能将本地 CLI 注册为 bridge 环境,生成可分享的 URL`https://claude.ai/code/session_xxx`),允许从浏览器、手机或其他设备远程查看输出、发送消息、审批工具调用。
**改动文件:**
| 文件 | 变更 |
|------|------|
| `scripts/dev.ts` | `DEFAULT_FEATURES` 加入 `"BRIDGE_MODE"`dev 模式默认启用 |
| `src/bridge/peerSessions.ts` | stub → 完整实现:通过 bridge API 发送跨会话消息含三层安全防护trim + validateBridgeId 白名单 + encodeURIComponent |
| `src/bridge/webhookSanitizer.ts` | stub → 完整实现:正则 redact 8 类 secretGitHub/Anthropic/AWS/npm/Slack token先 redact 再截断,失败返回安全占位符 |
| `src/entrypoints/sdk/controlTypes.ts` | 12 个 `any` stub → `z.infer<ReturnType<typeof XxxSchema>>` 从现有 Zod schema 推导类型 |
| `src/hooks/useReplBridge.tsx` | `tengu_bridge_system_init` 默认值 `false``true`,使 app 端显示 "active" 而非卡在 "connecting" |
**关键设计决策:**
1. **不改现有代码逻辑** — 只补全 stub、修正默认值、开启编译开关
2. **`tengu_bridge_system_init`** — Anthropic 通过 GrowthBook 给订阅用户推送 `true`,但我们的 build 收不到推送;改默认值是唯一不侵入其他代码的方案
3. **`peerSessions.ts` 认证** — 使用 `getBridgeAccessToken()` 获取 OAuth Bearer token`bridgeApi.ts`/`codeSessionApi.ts` 认证模式一致
4. **`webhookSanitizer.ts` 安全** — fail-closed出错返回 `[webhook content redacted due to sanitization error]`),不泄露原始内容
**验证结果:**
- `/remote-control` 命令可见且可用
- CLI 连接 Anthropic CCR生成可分享 URL
- App 端claude.ai/code显示 "Remote Control active"
- 手机端Claude iOS app通过 URL 连接,双向消息正常
![Remote Control on Mobile](docs/images/remote-control-mobile.png)
---
## GrowthBook 自定义服务器适配器 (2026-04-03)
GrowthBook 功能开关系统原为 Anthropic 内部构建设计,硬编码 SDK key 和 API 地址,外部构建因 `is1PEventLoggingEnabled()` 门控始终禁用。新增适配器模式,通过环境变量连接自定义 GrowthBook 服务器,无配置时所有 feature 读取返回代码默认值。
**修改文件:**
| 文件 | 变更 |
|------|------|
| `src/constants/keys.ts` | `getGrowthBookClientKey()` 优先读取 `CLAUDE_GB_ADAPTER_KEY` 环境变量 |
| `src/services/analytics/growthbook.ts` | `isGrowthBookEnabled()` 适配器模式下直接返回 `true`,绕过 1P event logging 门控 |
| `src/services/analytics/growthbook.ts` | `getGrowthBookClient()` base URL 优先使用 `CLAUDE_GB_ADAPTER_URL` |
| `docs/internals/growthbook-adapter.mdx` | 新增适配器配置文档,含全部 ~58 个 feature key 列表 |
**用法:** `CLAUDE_GB_ADAPTER_URL=https://gb.example.com/ CLAUDE_GB_ADAPTER_KEY=sdk-xxx bun run dev`
---
## Datadog 日志端点可配置化 (2026-04-03)
将 Datadog 硬编码的 Anthropic 内部端点改为环境变量驱动,默认禁用。
**修改文件:**
| 文件 | 变更 |
|------|------|
| `src/services/analytics/datadog.ts` | `DATADOG_LOGS_ENDPOINT``DATADOG_CLIENT_TOKEN` 从硬编码常量改为读取 `process.env.DATADOG_LOGS_ENDPOINT` / `process.env.DATADOG_API_KEY`,默认空字符串;`initializeDatadog()` 增加守卫:端点或 Token 未配置时直接返回 `false` |
| `docs/telemetry-remote-config-audit.md` | 更新第 1 节,反映新的环境变量配置方式 |
**效果:** 默认不向任何外部发送数据;设置两个环境变量即可接入自己的 Datadog 实例。原有 `DISABLE_TELEMETRY`、privacy level、sink killswitch 等防线保留。
**用法:** `DATADOG_LOGS_ENDPOINT=https://http-intake.logs.datadoghq.com/api/v2/logs DATADOG_API_KEY=xxx bun run dev`
---
## Sentry 错误上报集成 (2026-04-03)
恢复反编译过程中被移除的 Sentry 集成。通过 `SENTRY_DSN` 环境变量控制,未设置时所有函数为 no-op不影响正常运行。
**新增文件:**
| 文件 | 说明 |
|------|------|
| `src/utils/sentry.ts` | 核心模块:`initSentry()``captureException()``setTag()``setUser()``closeSentry()``beforeSend` 过滤 auth headers 等敏感信息;忽略 ECONNREFUSED/AbortError 等非 actionable 错误 |
**修改文件:**
| 文件 | 变更 |
|------|------|
| `src/utils/errorLogSink.ts` | `logErrorImpl` 末尾调用 `captureException()`,所有经 `logError()` 的错误自动上报 |
| `src/components/SentryErrorBoundary.ts` | 添加 `componentDidCatch`React 组件渲染错误上报到 Sentry含 componentStack |
| `src/entrypoints/init.ts` | 网络配置后调用 `initSentry()` |
| `src/utils/gracefulShutdown.ts` | 优雅关闭时 flush Sentry 事件 |
| `src/screens/REPL.tsx:2809` | `fireCompanionObserver` 调用增加 `typeof` 防护BUDDY feature 启用时不报错TODO: 待实现) |
| `package.json` | devDependencies 新增 `@sentry/node` |
**用法:** `SENTRY_DSN=https://xxx@xxx.ingest.sentry.io/xxx bun run dev`
---
## 默认关闭自动更新 (2026-04-03)
修改 `src/utils/config.ts``getAutoUpdaterDisabledReason()`,在原有检查逻辑前插入默认关闭逻辑。未设置 `ENABLE_AUTOUPDATER=1` 时,自动更新始终返回 `{ type: 'config' }` 被禁用。
**启用方式:** `ENABLE_AUTOUPDATER=1 bun run dev`
**原因:** 本项目为逆向工程/反编译版本,自动更新会覆盖本地修改的代码。
**同时新增文档:** `docs/auto-updater.md` — 自动更新机制完整审计,涵盖三种安装类型的更新策略、后台轮询、版本门控、原生安装器架构、文件锁、配置项等。
---
## WebSearch Bing 适配器补全 (2026-04-03)
原始 `WebSearchTool` 仅支持 Anthropic API 服务端搜索(`web_search_20250305` server tool在非官方 API 端点(第三方代理)下搜索功能不可用。本次改动引入适配器架构,新增 Bing 搜索页面解析作为 fallback。
**新增文件:**
| 文件 | 说明 |
|------|------|
| `src/tools/WebSearchTool/adapters/types.ts` | 适配器接口定义:`WebSearchAdapter``SearchResult``SearchOptions``SearchProgress` |
| `src/tools/WebSearchTool/adapters/apiAdapter.ts` | API 适配器 — 将原有 `queryModelWithStreaming` 逻辑封装为 `ApiSearchAdapter` |
| `src/tools/WebSearchTool/adapters/bingAdapter.ts` | Bing 适配器 — 直接抓取 Bing HTML正则提取搜索结果 |
| `src/tools/WebSearchTool/adapters/index.ts` | 适配器工厂 — 根据环境变量 / API Base URL 选择后端 |
| `src/tools/WebSearchTool/__tests__/bingAdapter.test.ts` | Bing 适配器单元测试32 casesdecodeHtmlEntities、extractBingResults、search mock |
| `src/tools/WebSearchTool/__tests__/bingAdapter.integration.ts` | Bing 适配器集成测试 — 真实网络请求验证 |
**重构文件:**
| 文件 | 变更 |
|------|------|
| `src/tools/WebSearchTool/WebSearchTool.ts` | 从直接调用 API 改为 `createAdapter()` 工厂模式;`isEnabled()` 始终返回 true删除 ~200 行内联 API 调用逻辑 |
| `src/tools/WebFetchTool/utils.ts` | `skipWebFetchPreflight` 默认值从 `!undefined`(即 true改为显式 `=== false`,使域名预检默认启用 |
**Bing 适配器关键技术细节:**
1. **反爬绕过**:使用完整 Edge 浏览器请求头(含 `Sec-Ch-Ua``Sec-Fetch-*` 等 13 个标头),避免 Bing 返回 JS 渲染的空页面;`setmkt=en-US` 参数强制美式英语市场,避免 IP 地理定位导致的区域化结果(德语论坛、新加坡金价等不相关内容)
2. **URL 解码**`resolveBingUrl()`Bing 返回的重定向 URL`bing.com/ck/a?...&u=a1aHR0cHM6Ly9...`)中 `u` 参数为 base64 编码的真实 URL需解码后使用
3. **摘要提取**`extractSnippet()`):三级降级策略 — `b_lineclamp``b_caption <p>``b_caption` 直接文本
4. **HTML 实体解码**`decodeHtmlEntities()`):处理 7 种常见 HTML 实体
5. **域过滤**:客户端侧 `allowedDomains` / `blockedDomains` 过滤,支持子域名匹配
**当前状态**`adapters/index.ts``createAdapter()` 硬编码返回 `BingSearchAdapter`,跳过了 API/Bing 自动选择逻辑(原逻辑被注释保留)。未来可通过取消注释恢复自动选择。
---
## 移除反蒸馏机制 (2026-04-02)
项目中发现三处 anti-distillation 相关代码,全部移除。
**移除内容:**
- `src/services/api/claude.ts` — 删除 fake_tools 注入逻辑(原第 302-314 行),该代码通过 `ANTI_DISTILLATION_CC` feature flag 在 API 请求中注入 `anti_distillation: ['fake_tools']`,使服务端在响应中混入虚假工具调用以污染蒸馏数据
- `src/utils/betas.ts` — 删除 connector-text summarization beta 注入块及 `SUMMARIZE_CONNECTOR_TEXT_BETA_HEADER` 导入,该机制让服务端缓冲工具调用间的 assistant 文本并摘要化返回
- `src/constants/betas.ts` — 删除 `SUMMARIZE_CONNECTOR_TEXT_BETA_HEADER` 常量定义(原第 23-25 行)
- `src/utils/streamlinedTransform.ts` — 注释从 "distillation-resistant" 改为 "compact"streamlined 模式本身是有效的输出压缩功能,仅修正描述
---
## Buddy 命令合入 + Feature Flag 规范修正 (2026-04-02)
合入 `pr/smallflyingpig/36` 分支(支持 buddy 命令 + 修复 rehatch并修正 feature flag 使用方式。
**合入内容(来自 PR**
- `src/commands/buddy/buddy.ts` — 新增 `/buddy` 命令,支持 hatch / rehatch / pet / mute / unmute 子命令
- `src/commands/buddy/index.ts` — 从 stub 改为正确的 `Command` 类型导出
- `src/buddy/companion.ts` — 新增 `generateSeed()``getCompanion()` 支持 seed 驱动的可复现 rolling
- `src/buddy/types.ts``CompanionSoul` 增加 `seed?` 字段
**合并后修正:**
- `src/entrypoints/cli.tsx` — PR 硬编码了 `const feature = (name) => name === "BUDDY"`,违反 feature flag 规范,恢复为标准 `import { feature } from 'bun:bundle'`
- `src/commands.ts` — PR 用静态 `import buddy` 绕过了 feature gate恢复为 `feature('BUDDY') ? require(...) : null` + 条件展开
- `src/commands/buddy/buddy.ts` — 删除未使用的 `companionInfoText` 函数和多余的 `Roll`/`SPECIES` import
- `CLAUDE.md` — 重写 Feature Flag System 章节,明确规范:代码中统一用 `import { feature } from 'bun:bundle'`,启用走环境变量 `FEATURE_<NAME>=1`
**用法:** `FEATURE_BUDDY=1 bun run dev`
---
## Auto Mode 补全 (2026-04-02)
反编译丢失了 auto mode 分类器的三个 prompt 模板文件,代码逻辑完整但无法运行。
**新增:**
- `yolo-classifier-prompts/auto_mode_system_prompt.txt` — 主系统提示词
- `yolo-classifier-prompts/permissions_external.txt` — 外部权限模板(用户规则替换默认值)
- `yolo-classifier-prompts/permissions_anthropic.txt` — 内部权限模板(用户规则追加)
**改动:**
- `scripts/dev.ts` + `build.ts` — 扫描 `FEATURE_*` 环境变量注入 Bun `--feature`
- `cli.tsx` — 启动时打印已启用的 feature
- `permissionSetup.ts``AUTO_MODE_ENABLED_DEFAULT``feature('TRANSCRIPT_CLASSIFIER')` 决定,开 feature 即开 auto mode
- `docs/safety/auto-mode.mdx` — 补充 prompt 模板章节
**用法:** `FEATURE_TRANSCRIPT_CLASSIFIER=1 bun run dev`
**注意:** prompt 模板为重建产物。
---
## USER_TYPE=ant TUI 修复 (2026-04-02)
`global.d.ts` 声明的全局函数在反编译版本运行时未定义,导致 `USER_TYPE=ant` 时 TUI 崩溃。
修复方式:显式 import / 本地 stub / 全局 stub / 新建 stub 文件。涉及文件:
`cli.tsx`, `model.ts`, `context.ts`, `effort.ts`, `thinking.ts`, `undercover.ts`, `Spinner.tsx`, `AntModelSwitchCallout.tsx`(新建), `UndercoverAutoCallout.tsx`(新建)
注意:
- `USER_TYPE=ant` 启用 alt-screen 全屏模式,中心区域满屏是预期行为
- `global.d.ts` 中剩余未 stub 的全局函数(`getAntModels` 等)遇到 `X is not defined` 时按同样模式处理
---
## /login 添加 Custom Platform 选项 (2026-04-03)
`/login` 命令的登录方式选择列表中新增 "Custom Platform" 选项(位于第一位),允许用户直接在终端配置第三方 API 兼容服务的 Base URL、API Key 和三种模型映射,保存到 `~/.claude/settings.json`
**修改文件:**
| 文件 | 变更 |
|------|------|
| `src/components/ConsoleOAuthFlow.tsx` | `OAuthStatus` 类型新增 `custom_platform` state`baseUrl``apiKey``haikuModel``sonnetModel``opusModel``activeField``idle` case Select 选项新增 Custom Platform 并排第一位;新增 `custom_platform` case 渲染 5 字段表单Tab/Shift+Tab 切换、focus 高亮、Enter 跳转/保存Select onChange 处理 `custom_platform` 初始状态(从 `process.env` 预填当前值);`OAuthStatusMessageProps` 类型及调用处新增 `onDone` prop |
| `src/components/ConsoleOAuthFlow.tsx` | 新增 `updateSettingsForSource` import |
**UI 交互:**
- 5 个字段同屏Base URL、API Key、Haiku Model、Sonnet Model、Opus Model
- 当前活动字段的标签用 `suggestion` 背景色 + `inverseText` 反色高亮
- Tab / Shift+Tab 在字段间切换,各自保留输入值
- 每个字段按 Enter 跳到下一个,最后一个字段 (Opus) 按 Enter 保存
- 模型字段自动从 `process.env` 读取当前配置作为预填值,无值则空
- 保存时调用 `updateSettingsForSource('userSettings', { env })` 写入 settings.json同时更新 `process.env`
**保存的 settings.json env 字段:**
```json
{
"ANTHROPIC_BASE_URL": "...",
"ANTHROPIC_AUTH_TOKEN": "...",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "...",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "...",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "..."
}
```
非空字段才写入,保存后立即生效(`onDone()` 触发 `onChangeAPIKey()` 刷新 API 客户端)。

38
Friends.md Normal file
View File

@@ -0,0 +1,38 @@
# 社区项目 & Blog 合集
> 每日更新,欢迎自荐!
## 工具 & 应用
| 项目 | 描述 | 作者 |
|------|------|------|
| [4qtask.vercel.app](https://4qtask.vercel.app/) | 免费四象限时间管理工具 | @kevinhuky |
| [kaying.studio](https://kaying.studio/) | 个人 AI 工具箱 | @kayingai |
| [supsub.ai](https://supsub.ai/) | 高效阅读工具 | @hidumou |
| [x-video-download.net](https://x-video-download.net/) | 视频下载工具 | @syakadou |
| [1openapi.com](https://1openapi.com/) | API 中转站 | @thinker007 |
| [claw-z.com](https://claw-z.com/) | 一键部署 OpenClaw AI Agent场景驱动、全面管理 | @uhhc |
| [gemini-watermark-remover.net](https://gemini-watermark-remover.net/) | Gemini 水印移除工具 | @syakadou |
## GitHub 开源项目
| 项目 | 描述 | 作者 |
|------|------|------|
| [VersperClaw](https://github.com/versperai/VersperClaw) | 全自动科研流 | @versperai |
| [claude-reviews-claude](https://github.com/openedclaude/claude-reviews-claude) | 原汤化原食——Claude 如何看待眼中的老己 | @openedclaude |
| [agentica](https://github.com/shibing624/agentica) | 自研 Agent 框架,借鉴 claude-code 多 Agent 处理 | @shibing624 |
| [macman](https://github.com/tonngw/macman) | Mac 从 0 到 1 保姆级配置教程 | @tonngw |
| [SuperSpec](https://github.com/asasugar/SuperSpec) | SDD / Spec-Driven Development | @asasugar |
| [adnify](https://github.com/adnaan-worker/adnify) | 高颜值高定制化 AI 编辑器 | @adnaan-worker |
| [another-rule-engine](https://github.com/eatmoreduck/another-rule-engine) | 基于 Groovy 的开源多功能决策引擎 | @eatmoreduck |
| [creative_master](https://github.com/chatabc/creative_master) | AI 驱动的创意灵感管理工具 | @chatabc |
| [RapidDoc](https://github.com/RapidAI/RapidDoc) | Office 文件解析工具转 Markdown支持 PDF/Image/Word/PPT/Excel | @hzkitt |
| [token-share](https://github.com/leemysw/token-share) | macOS 原生菜单栏 LLM API 网关,支持 OpenAI 与 Anthropic 协议间的实时互译与流式转发 | @leemysw |
| [feishu-docx](https://github.com/leemysw/feishu-docx) | 飞书知识库导出、写入与云空间管理工具(支持 Markdown、公众号导入、CLI、TUI | @leemysw |
| [web-search-fast](https://github.com/uk0/web-search-fast) | 快速网页搜索 | @uk0 |
## Blog
| 链接 | 作者 |
|------|------|
| [blog.xiaohuangyu.space](https://blog.xiaohuangyu.space/) | @eatmoreduck |

512
README.md
View File

@@ -1,49 +1,68 @@
# Claude Code Best V3 (CCB)
# Claude Code Best V5 (CCB)
牢 A (Anthropic) 官方 [Claude Code](https://docs.anthropic.com/en/docs/claude-code) CLI 工具的源码反编译/逆向还原项目。目标是将 Claude Code 大部分功能及工程化能力复现。虽然很难绷, 但是它叫做 CCB(踩踩背)...
[![GitHub Stars](https://img.shields.io/github/stars/claude-code-best/claude-code?style=flat-square&logo=github&color=yellow)](https://github.com/claude-code-best/claude-code/stargazers)
[![GitHub Contributors](https://img.shields.io/github/contributors/claude-code-best/claude-code?style=flat-square&color=green)](https://github.com/claude-code-best/claude-code/graphs/contributors)
[![GitHub Issues](https://img.shields.io/github/issues/claude-code-best/claude-code?style=flat-square&color=orange)](https://github.com/claude-code-best/claude-code/issues)
[![GitHub License](https://img.shields.io/github/license/claude-code-best/claude-code?style=flat-square)](https://github.com/claude-code-best/claude-code/blob/main/LICENSE)
[![Last Commit](https://img.shields.io/github/last-commit/claude-code-best/claude-code?style=flat-square&color=blue)](https://github.com/claude-code-best/claude-code/commits/main)
[![Bun](https://img.shields.io/badge/runtime-Bun-black?style=flat-square&logo=bun)](https://bun.sh/)
[![Discord](https://img.shields.io/badge/Discord-Join-5865F2?style=flat-square&logo=discord)](https://discord.gg/qZU6zS7Q)
[文档在这里, 支持投稿 PR](https://ccb.agent-aura.top/)
> Which Claude do you like? The open source one is the best.
赞助商占位符
牢 A (Anthropic) 官方 [Claude Code](https://docs.anthropic.com/en/docs/claude-code) CLI 工具的源码反编译/逆向还原项目。目标是将 Claude Code 大部分功能及工程化能力复现 (问就是老佛爷已经付过钱了)。虽然很难绷, 但是它叫做 CCB(踩踩背)... 而且, 我们实现了企业版或者需要登陆 Claude 账号才能使用的特性, 实现技术普惠
- [x] v1 会完成跑通及基本的类型检查通过;
- [x] V2 会完整实现工程化配套设施;
- [ ] Biome 格式化可能不会先实施, 避免代码冲突
- [x] 构建流水线完成, 产物 Node/Bun 都可以运行
- [x] V3 会写大量文档, 完善文档站点
- [ ] V4 会完成大量的测试文件, 以提高稳定性
[文档在这里, 支持投稿 PR](https://ccb.agent-aura.top/) | [留影文档在这里](./Friends.md) | [Discord 群组](https://discord.gg/qZU6zS7Q)
> 我不知道这个项目还会存在多久, Star + Fork + git clone + .zip 包最稳健;
>
> 这个项目更新很快, 后台有 Opus 持续优化, 所以你可以提 issues, 但是 PR 暂时不会接受;
>
> Claude 已经烧了 800$ 以上, 如果你个人想赞助, 请随便找个机构捐款, 然后截图在 issues, 大家的力量是温暖的;
>
> 某些模型提供商想要赞助, 那么请私发一个 1w 额度以上的账号到 <claude-code-best@proton.me>; 我们会在赞助商栏直接给你最亮的位置
| 特性 | 说明 | 文档 |
|------|------|------|
| **Claude 群控技术** | Pipe IPC 多实例协作:同机 main/sub 自动编排 + LAN 跨机器零配置发现与通讯,`/pipes` 选择面板 + `Shift+↓` 交互 + 消息广播路由 | [Pipe IPC](https://ccb.agent-aura.top/docs/features/pipes-and-lan) / [LAN](https://ccb.agent-aura.top/docs/features/lan-pipes) |
| **ACP 协议一等一支持** | 支持接入 Zed、Cursor 等 IDE支持会话恢复、Skills、权限桥接 | [文档](https://ccb.agent-aura.top/docs/features/acp-zed) |
| **Remote Control 私有部署** | Docker 自托管远程界面, 可以手机上看 CC | [文档](https://ccb.agent-aura.top/docs/features/remote-control-self-hosting) |
| **Langfuse 监控** | 企业级 Agent 监控, 可以清晰看到每次 agent loop 细节, 可以一键转化为数据集 | [文档](https://ccb.agent-aura.top/docs/features/langfuse-monitoring) |
| **Web Search** | 内置网页搜索工具, 支持 bing 和 brave 搜索 | [文档](https://ccb.agent-aura.top/docs/features/web-browser-tool) |
| **Poor Mode** | 穷鬼模式,关闭记忆提取和键入建议,大幅度减少并发请求 | /poor 可以开关 |
| **自定义模型供应商** | OpenAI/Anthropic/Gemini/Grok 兼容 | [文档](https://ccb.agent-aura.top/docs/features/custom-platform-login) |
| Voice Mode | Push-to-Talk 语音输入 | [文档](https://ccb.agent-aura.top/docs/features/voice-mode) |
| Computer Use | 屏幕截图、键鼠控制 | [文档](https://ccb.agent-aura.top/docs/features/computer-use) |
| Chrome Use | 浏览器自动化、表单填写、数据抓取 | [自托管](https://ccb.agent-aura.top/docs/features/chrome-use-mcp) [原生版](https://ccb.agent-aura.top/docs/features/claude-in-chrome-mcp) |
| Sentry | 企业级错误追踪 | [文档](https://ccb.agent-aura.top/docs/internals/sentry-setup) |
| GrowthBook | 企业级特性开关 | [文档](https://ccb.agent-aura.top/docs/internals/growthbook-adapter) |
| /dream 记忆整理 | 自动整理和优化记忆文件 | [文档](https://ccb.agent-aura.top/docs/features/auto-dream) |
存活记录:
- 🚀 [想要启动项目](#快速开始源码版)
- 🐛 [想要调试项目](#vs-code-调试)
- 📖 [想要学习项目](#teach-me-学习项目)
1. 开源后 24 小时: 突破 6k Star, 感谢各位支持. 完成 docs 文档的站点构建, 达到 v3 版本, 后续开始进行测试用例维护, 完成之后可以接受 PR; 看来牢 A 是不想理我们了;
2. 开源后 15 小时: 完成了构建产物的 node 支持, 现在是完全体了; star 快到 3k 了; 等待牢 A 的邮件
3. 开源后 12 小时: 愚人节, star 破 1k, 并且牢 A 没有发邮件搞这个项目
4. 如果你想要私人咨询服务, 那么可以发送邮件到 <claude-code-best@proton.me>, 备注咨询与联系方式即可; 由于后续工作非常多, 可能会忽略邮件, 半天没回复, 可以多发;
## 快速开始
## 快速开始(安装版)
### 环境要求
不用克隆仓库, 从 NPM 下载后, 直接使用
```sh
bun i -g claude-code-best
bun pm -g trust claude-code-best
ccb # 以 nodejs 打开 claude code
ccb-bun # 以 bun 形态打开
CLAUDE_BRIDGE_BASE_URL=https://remote-control.claude-code-best.win/ CLAUDE_BRIDGE_OAUTH_TOKEN=test-my-key ccb --remote-control # 我们有自部署的远程控制
```
## ⚡ 快速开始(源码版)
### ⚙️ 环境要求
一定要最新版本的 bun 啊, 不然一堆奇奇怪怪的 BUG!!! bun upgrade!!!
- [Bun](https://bun.sh/) >= 1.3.11
- 常规的配置 CC 的方式, 各大提供商都有自己的配置方式
- 📦 [Bun](https://bun.sh/) >= 1.3.11
- ⚙️ 常规的配置 CC 的方式, 各大提供商都有自己的配置方式
### 安装
### 📥 安装
```bash
bun install
```
### 运行
### ▶️ 运行
```bash
# 开发模式, 看到版本号 888 说明就是对了
@@ -59,9 +78,86 @@ bun run build
如果遇到 bug 请直接提一个 issues, 我们优先解决
### 👤 新人配置 /login
首次运行后,在 REPL 中输入 `/login` 命令进入登录配置界面,选择 **Anthropic Compatible** 即可对接第三方 API 兼容服务(无需 Anthropic 官方账号)。
选择 OpenAI 和 Gemini 对应的栏目都是支持相应协议的
需要填写的字段:
| 📌 字段 | 📝 说明 | 💡 示例 |
|------|------|------|
| Base URL | API 服务地址 | `https://api.example.com/v1` |
| API Key | 认证密钥 | `sk-xxx` |
| Haiku Model | 快速模型 ID | `claude-haiku-4-5-20251001` |
| Sonnet Model | 均衡模型 ID | `claude-sonnet-4-6` |
| Opus Model | 高性能模型 ID | `claude-opus-4-6` |
- ⌨️ **Tab / Shift+Tab** 切换字段,**Enter** 确认并跳到下一个,最后一个字段按 Enter 保存
> 支持所有 Anthropic API 兼容服务(如 OpenRouter、AWS Bedrock 代理等),只要接口兼容 Messages API 即可。
## Feature Flags
所有功能开关通过 `FEATURE_<FLAG_NAME>=1` 环境变量启用,例如:
```bash
FEATURE_BUDDY=1 FEATURE_FORK_SUBAGENT=1 bun run dev
```
各 Feature 的详细说明见 [`docs/features/`](docs/features/) 目录,欢迎投稿补充。
## VS Code 调试
TUI (REPL) 模式需要真实终端,无法直接通过 VS Code launch 启动调试。使用 **attach 模式**
### 步骤
1. **终端启动 inspect 服务**
```bash
bun run dev:inspect
```
会输出类似 `ws://localhost:8888/xxxxxxxx` 的地址。
2. **VS Code 附着调试器**
- 在 `src/` 文件中打断点
- F5 → 选择 **"Attach to Bun (TUI debug)"**
## Teach Me 学习项目
我们新加了一个 teach-me skills, 通过问答式引导帮你理解这个项目的任何模块。(调整 [sigma skill 而来](https://github.com/sanyuan0704/sanyuan-skills))
```bash
# 在 REPL 中直接输入
/teach-me Claude Code 架构
/teach-me React Ink 终端渲染 --level beginner
/teach-me Tool 系统 --resume
```
### 它能做什么
- **诊断水平** — 自动评估你对相关概念的掌握程度,跳过已知的、聚焦薄弱的
- **构建学习路径** — 将主题拆解为 5-15 个原子概念,按依赖排序逐步推进
- **苏格拉底式提问** — 用选项引导思考,而非直接给答案
- **错误概念追踪** — 发现并纠正深层误解
- **断点续学** — `--resume` 从上次进度继续
### 学习记录
学习进度保存在 `.claude/skills/teach-me/` 目录下,支持跨主题学习者档案。
## 相关文档及网站
<https://deepwiki.com/claude-code-best/claude-code>
- **在线文档Mintlify**: [ccb.agent-aura.top](https://ccb.agent-aura.top/) — 文档源码位于 [`docs/`](docs/) 目录,欢迎投稿 PR
- **DeepWiki**: <https://deepwiki.com/claude-code-best/claude-code>
## Contributors
<a href="https://github.com/claude-code-best/claude-code/graphs/contributors">
<img src="contributors.svg" alt="Contributors" />
</a>
## Star History
@@ -73,364 +169,6 @@ bun run build
</picture>
</a>
## 能力清单
> ✅ = 已实现 ⚠️ = 部分实现 / 条件启用 ❌ = stub / 移除 / feature flag 关闭
### 核心系统
| 能力 | 状态 | 说明 |
|------|------|------|
| REPL 交互界面Ink 终端渲染) | ✅ | 主屏幕 5000+ 行,完整交互 |
| API 通信 — Anthropic Direct | ✅ | 支持 API Key + OAuth |
| API 通信 — AWS Bedrock | ✅ | 支持凭据刷新、Bearer Token |
| API 通信 — Google Vertex | ✅ | 支持 GCP 凭据刷新 |
| API 通信 — Azure Foundry | ✅ | 支持 API Key + Azure AD |
| 流式对话与工具调用循环 (`query.ts`) | ✅ | 1700+ 行含自动压缩、token 追踪 |
| 会话引擎 (`QueryEngine.ts`) | ✅ | 1300+ 行,管理对话状态与归因 |
| 上下文构建git status / CLAUDE.md / memory | ✅ | `context.ts` 完整实现 |
| 权限系统plan/auto/manual 模式) | ✅ | 6300+ 行,含 YOLO 分类器、路径验证、规则匹配 |
| Hook 系统pre/post tool use | ✅ | 支持 settings.json 配置 |
| 会话恢复 (`/resume`) | ✅ | 独立 ResumeConversation 屏幕 |
| Doctor 诊断 (`/doctor`) | ✅ | 版本、API、插件、沙箱检查 |
| 自动压缩 (compaction) | ✅ | auto-compact / micro-compact / API compact |
### 工具 — 始终可用
| 工具 | 状态 | 说明 |
|------|------|------|
| BashTool | ✅ | Shell 执行,沙箱,权限检查 |
| FileReadTool | ✅ | 文件 / PDF / 图片 / Notebook 读取 |
| FileEditTool | ✅ | 字符串替换式编辑 + diff 追踪 |
| FileWriteTool | ✅ | 文件创建 / 覆写 + diff 生成 |
| NotebookEditTool | ✅ | Jupyter Notebook 单元格编辑 |
| AgentTool | ✅ | 子代理派生fork / async / background / remote |
| WebFetchTool | ✅ | URL 抓取 → Markdown → AI 摘要 |
| WebSearchTool | ✅ | 网页搜索 + 域名过滤 |
| AskUserQuestionTool | ✅ | 多问题交互提示 + 预览 |
| SendMessageTool | ✅ | 消息发送peers / teammates / mailbox |
| SkillTool | ✅ | 斜杠命令 / Skill 调用 |
| EnterPlanModeTool | ✅ | 进入计划模式 |
| ExitPlanModeTool (V2) | ✅ | 退出计划模式 |
| TodoWriteTool | ✅ | Todo 列表 v1 |
| BriefTool | ✅ | 简短消息 + 附件发送 |
| TaskOutputTool | ✅ | 后台任务输出读取 |
| TaskStopTool | ✅ | 后台任务停止 |
| ListMcpResourcesTool | ⚠️ | MCP 资源列表(被 specialTools 过滤,特定条件下加入) |
| ReadMcpResourceTool | ⚠️ | MCP 资源读取(同上) |
| SyntheticOutputTool | ⚠️ | 仅在非交互会话SDK/pipe 模式)下创建 |
| CronCreateTool | ✅ | 定时任务创建(已移除 AGENT_TRIGGERS gate |
| CronDeleteTool | ✅ | 定时任务删除 |
| CronListTool | ✅ | 定时任务列表 |
| EnterWorktreeTool | ✅ | 进入 Git Worktree`isWorktreeModeEnabled()` 已硬编码为 true |
| ExitWorktreeTool | ✅ | 退出 Git Worktree |
### 工具 — 条件启用
| 工具 | 状态 | 启用条件 |
|------|------|----------|
| GlobTool | ✅ | 未嵌入 bfs/ugrep 时启用(默认启用) |
| GrepTool | ✅ | 同上 |
| TaskCreateTool | ⚠️ | `isTodoV2Enabled()` 为 true 时 |
| TaskGetTool | ⚠️ | 同上 |
| TaskUpdateTool | ⚠️ | 同上 |
| TaskListTool | ⚠️ | 同上 |
| TeamCreateTool | ⚠️ | `isAgentSwarmsEnabled()` |
| TeamDeleteTool | ⚠️ | 同上 |
| ToolSearchTool | ⚠️ | `isToolSearchEnabledOptimistic()` |
| PowerShellTool | ⚠️ | Windows 平台检测 |
| LSPTool | ⚠️ | `ENABLE_LSP_TOOL` 环境变量 |
| ConfigTool | ❌ | `USER_TYPE === 'ant'`(永远为 false |
### 工具 — Feature Flag 关闭(全部不可用)
| 工具 | Feature Flag |
|------|-------------|
| SleepTool | `PROACTIVE` / `KAIROS` |
| RemoteTriggerTool | `AGENT_TRIGGERS_REMOTE` |
| MonitorTool | `MONITOR_TOOL` |
| SendUserFileTool | `KAIROS` |
| OverflowTestTool | `OVERFLOW_TEST_TOOL` |
| TerminalCaptureTool | `TERMINAL_PANEL` |
| WebBrowserTool | `WEB_BROWSER_TOOL` |
| SnipTool | `HISTORY_SNIP` |
| WorkflowTool | `WORKFLOW_SCRIPTS` |
| PushNotificationTool | `KAIROS` / `KAIROS_PUSH_NOTIFICATION` |
| SubscribePRTool | `KAIROS_GITHUB_WEBHOOKS` |
| ListPeersTool | `UDS_INBOX` |
| CtxInspectTool | `CONTEXT_COLLAPSE` |
### 工具 — Stub / 不可用
| 工具 | 说明 |
|------|------|
| TungstenTool | ANT-ONLY stub |
| REPLTool | ANT-ONLY`isEnabled: () => false` |
| SuggestBackgroundPRTool | ANT-ONLY`isEnabled: () => false` |
| VerifyPlanExecutionTool | 需 `CLAUDE_CODE_VERIFY_PLAN=true` 环境变量,且为 stub |
| ReviewArtifactTool | stub未注册到 tools.ts |
| DiscoverSkillsTool | stub未注册到 tools.ts |
### 斜杠命令 — 可用
| 命令 | 状态 | 说明 |
|------|------|------|
| `/add-dir` | ✅ | 添加目录 |
| `/advisor` | ✅ | Advisor 配置 |
| `/agents` | ✅ | 代理列表/管理 |
| `/branch` | ✅ | 分支管理 |
| `/btw` | ✅ | 快速备注 |
| `/chrome` | ✅ | Chrome 集成 |
| `/clear` | ✅ | 清屏 |
| `/color` | ✅ | Agent 颜色 |
| `/compact` | ✅ | 压缩对话 |
| `/config` (`/settings`) | ✅ | 配置管理 |
| `/context` | ✅ | 上下文信息 |
| `/copy` | ✅ | 复制最后消息 |
| `/cost` | ✅ | 会话费用 |
| `/desktop` | ✅ | Claude Desktop 集成 |
| `/diff` | ✅ | 显示 diff |
| `/doctor` | ✅ | 健康检查 |
| `/effort` | ✅ | 设置 effort 等级 |
| `/exit` | ✅ | 退出 |
| `/export` | ✅ | 导出对话 |
| `/extra-usage` | ✅ | 额外用量信息 |
| `/fast` | ✅ | 切换 fast 模式 |
| `/feedback` | ✅ | 反馈 |
| `/loop` | ✅ | 定时循环执行bundled skill可通过 `CLAUDE_CODE_DISABLE_CRON` 关闭) |
| `/heapdump` | ✅ | Heap dump调试 |
| `/help` | ✅ | 帮助 |
| `/hooks` | ✅ | Hook 管理 |
| `/ide` | ✅ | IDE 连接 |
| `/init` | ✅ | 初始化项目 |
| `/install-github-app` | ✅ | 安装 GitHub App |
| `/install-slack-app` | ✅ | 安装 Slack App |
| `/keybindings` | ✅ | 快捷键管理 |
| `/login` / `/logout` | ✅ | 登录 / 登出 |
| `/mcp` | ✅ | MCP 服务管理 |
| `/memory` | ✅ | Memory / CLAUDE.md 管理 |
| `/mobile` | ✅ | 移动端 QR 码 |
| `/model` | ✅ | 模型选择 |
| `/output-style` | ✅ | 输出风格 |
| `/passes` | ✅ | 推荐码 |
| `/permissions` | ✅ | 权限管理 |
| `/plan` | ✅ | 计划模式 |
| `/plugin` | ✅ | 插件管理 |
| `/pr-comments` | ✅ | PR 评论 |
| `/privacy-settings` | ✅ | 隐私设置 |
| `/rate-limit-options` | ✅ | 限速选项 |
| `/release-notes` | ✅ | 更新日志 |
| `/reload-plugins` | ✅ | 重载插件 |
| `/remote-env` | ✅ | 远程环境配置 |
| `/rename` | ✅ | 重命名会话 |
| `/resume` | ✅ | 恢复会话 |
| `/review` | ✅ | 代码审查(本地) |
| `/ultrareview` | ✅ | 云端审查 |
| `/rewind` | ✅ | 回退对话 |
| `/sandbox-toggle` | ✅ | 切换沙箱 |
| `/security-review` | ✅ | 安全审查 |
| `/session` | ✅ | 会话信息 |
| `/skills` | ✅ | Skill 管理 |
| `/stats` | ✅ | 会话统计 |
| `/status` | ✅ | 状态信息 |
| `/statusline` | ✅ | 状态栏 UI |
| `/stickers` | ✅ | 贴纸 |
| `/tasks` | ✅ | 任务管理 |
| `/theme` | ✅ | 终端主题 |
| `/think-back` | ✅ | 年度回顾 |
| `/upgrade` | ✅ | 升级 CLI |
| `/usage` | ✅ | 用量信息 |
| `/insights` | ✅ | 使用分析报告 |
| `/vim` | ✅ | Vim 模式 |
### 斜杠命令 — Feature Flag 关闭
| 命令 | Feature Flag |
|------|-------------|
| `/voice` | `VOICE_MODE` |
| `/proactive` | `PROACTIVE` / `KAIROS` |
| `/brief` | `KAIROS` / `KAIROS_BRIEF` |
| `/assistant` | `KAIROS` |
| `/remote-control` (alias `rc`) | `BRIDGE_MODE` |
| `/remote-control-server` | `DAEMON` + `BRIDGE_MODE` |
| `/force-snip` | `HISTORY_SNIP` |
| `/workflows` | `WORKFLOW_SCRIPTS` |
| `/web-setup` | `CCR_REMOTE_SETUP` |
| `/subscribe-pr` | `KAIROS_GITHUB_WEBHOOKS` |
| `/ultraplan` | `ULTRAPLAN` |
| `/torch` | `TORCH` |
| `/peers` | `UDS_INBOX` |
| `/fork` | `FORK_SUBAGENT` |
| `/buddy` | `BUDDY` |
### 斜杠命令 — ANT-ONLY不可用
`/files` `/tag` `/backfill-sessions` `/break-cache` `/bughunter` `/commit` `/commit-push-pr` `/ctx_viz` `/good-claude` `/issue` `/init-verifiers` `/mock-limits` `/bridge-kick` `/version` `/reset-limits` `/onboarding` `/share` `/summary` `/teleport` `/ant-trace` `/perf-issue` `/env` `/oauth-refresh` `/debug-tool-call` `/agents-platform` `/autofix-pr`
### CLI 子命令
| 子命令 | 状态 | 说明 |
|--------|------|------|
| `claude`(默认) | ✅ | 主 REPL / 交互 / print 模式 |
| `claude mcp serve/add/remove/list/get/...` | ✅ | MCP 服务管理7 个子命令) |
| `claude auth login/status/logout` | ✅ | 认证管理 |
| `claude plugin validate/list/install/...` | ✅ | 插件管理7 个子命令) |
| `claude setup-token` | ✅ | 长效 Token 配置 |
| `claude agents` | ✅ | 代理列表 |
| `claude doctor` | ✅ | 健康检查 |
| `claude update` / `upgrade` | ✅ | 自动更新 |
| `claude install [target]` | ✅ | Native 安装 |
| `claude server` | ❌ | `DIRECT_CONNECT` flag |
| `claude ssh <host>` | ❌ | `SSH_REMOTE` flag |
| `claude open <cc-url>` | ❌ | `DIRECT_CONNECT` flag |
| `claude auto-mode` | ❌ | `TRANSCRIPT_CLASSIFIER` flag |
| `claude remote-control` | ❌ | `BRIDGE_MODE` + `DAEMON` flag |
| `claude assistant` | ❌ | `KAIROS` flag |
| `claude up/rollback/log/error/export/task/completion` | ❌ | ANT-ONLY |
### 服务层
| 服务 | 状态 | 说明 |
|------|------|------|
| API 客户端 (`services/api/`) | ✅ | 3400+ 行4 个 provider |
| MCP (`services/mcp/`) | ✅ | 34 个文件12000+ 行 |
| OAuth (`services/oauth/`) | ✅ | 完整 OAuth 流程 |
| 插件 (`services/plugins/`) | ✅ | 基础设施完整,无内置插件 |
| LSP (`services/lsp/`) | ⚠️ | 实现存在,默认关闭 |
| 压缩 (`services/compact/`) | ✅ | auto / micro / API 压缩 |
| Hook 系统 (`services/tools/toolHooks.ts`) | ✅ | pre/post tool use hooks |
| 会话记忆 (`services/SessionMemory/`) | ✅ | 会话记忆管理 |
| 记忆提取 (`services/extractMemories/`) | ✅ | 自动记忆提取 |
| Skill 搜索 (`services/skillSearch/`) | ✅ | 本地/远程 skill 搜索 |
| 策略限制 (`services/policyLimits/`) | ✅ | 策略限制执行 |
| 分析 / GrowthBook / Sentry | ⚠️ | 框架存在,实际 sink 为空 |
| Voice (`services/voice.ts`) | ❌ | `VOICE_MODE` flag 关闭 |
### 内部包 (`packages/`)
| 包 | 状态 | 说明 |
|------|------|------|
| `color-diff-napi` | ✅ | 1006 行完整 TypeScript 实现(语法高亮 diff |
| `audio-capture-napi` | ✅ | 151 行完整实现(跨平台音频录制,使用 SoX/arecord |
| `image-processor-napi` | ✅ | 125 行完整实现macOS 剪贴板图片读取,使用 osascript + sharp |
| `modifiers-napi` | ✅ | 67 行完整实现macOS 修饰键检测bun:ffi + CoreGraphics |
| `url-handler-napi` | ❌ | stub`waitForUrlEvent()` 返回 null |
| `@ant/claude-for-chrome-mcp` | ❌ | stub`createServer()` 返回 null |
| `@ant/computer-use-mcp` | ⚠️ | 类型安全 stub265 行,完整类型定义但函数返回空值) |
| `@ant/computer-use-input` | ✅ | 183 行完整实现macOS 键鼠模拟AppleScript/JXA/CGEvent |
| `@ant/computer-use-swift` | ✅ | 388 行完整实现macOS 显示器/应用管理/截图JXA/screencapture |
### Feature Flags31 个,全部返回 `false`
`ABLATION_BASELINE` `AGENT_MEMORY_SNAPSHOT` `BG_SESSIONS` `BRIDGE_MODE` `BUDDY` `CCR_MIRROR` `CCR_REMOTE_SETUP` `CHICAGO_MCP` `COORDINATOR_MODE` `DAEMON` `DIRECT_CONNECT` `EXPERIMENTAL_SKILL_SEARCH` `FORK_SUBAGENT` `HARD_FAIL` `HISTORY_SNIP` `KAIROS` `KAIROS_BRIEF` `KAIROS_CHANNELS` `KAIROS_GITHUB_WEBHOOKS` `LODESTONE` `MCP_SKILLS` `PROACTIVE` `SSH_REMOTE` `TORCH` `TRANSCRIPT_CLASSIFIER` `UDS_INBOX` `ULTRAPLAN` `UPLOAD_USER_SETTINGS` `VOICE_MODE` `WEB_BROWSER_TOOL` `WORKFLOW_SCRIPTS`
## 项目结构
```
claude-code/
├── src/
│ ├── entrypoints/
│ │ ├── cli.tsx # 入口文件(含 MACRO/feature polyfill
│ │ └── sdk/ # SDK 子模块 stub
│ ├── main.tsx # 主 CLI 逻辑Commander 定义)
│ └── types/
│ ├── global.d.ts # 全局变量/宏声明
│ └── internal-modules.d.ts # 内部 npm 包类型声明
├── packages/ # Monorepo workspace 包
│ ├── color-diff-napi/ # 完整实现(终端 color diff
│ ├── modifiers-napi/ # stubmacOS 修饰键检测)
│ ├── audio-capture-napi/ # stub
│ ├── image-processor-napi/# stub
│ ├── url-handler-napi/ # stub
│ └── @ant/ # Anthropic 内部包 stub
│ ├── claude-for-chrome-mcp/
│ ├── computer-use-mcp/
│ ├── computer-use-input/
│ └── computer-use-swift/
├── scripts/ # 自动化 stub 生成脚本
├── build.ts # 构建脚本Bun.build + code splitting + Node.js 兼容后处理)
├── dist/ # 构建输出(入口 cli.js + ~450 chunk 文件)
└── package.json # Bun workspaces monorepo 配置
```
## 技术说明
### 运行时 Polyfill
入口文件 `src/entrypoints/cli.tsx` 顶部注入了必要的 polyfill
- `feature()` — 所有 feature flag 返回 `false`,跳过未实现分支
- `globalThis.MACRO` — 模拟构建时宏注入VERSION 等)
### Monorepo
项目采用 Bun workspaces 管理内部包。原先手工放在 `node_modules/` 下的 stub 已统一迁入 `packages/`,通过 `workspace:*` 解析。
## Feature Flags 详解
原版 Claude Code 通过 `bun:bundle``feature()` 在构建时注入 feature flag由 GrowthBook 等 A/B 实验平台控制灰度发布。本项目中 `feature()` 被 polyfill 为始终返回 `false`,因此以下 30 个 flag 全部关闭。
### 自主 Agent
| Flag | 用途 |
|------|------|
| `KAIROS` | Assistant 模式 — 长期运行的自主 Agent含 brief、push 通知、文件发送) |
| `KAIROS_BRIEF` | Kairos Brief — 向用户发送简报摘要 |
| `KAIROS_CHANNELS` | Kairos 频道 — 多频道通信 |
| `KAIROS_GITHUB_WEBHOOKS` | GitHub Webhook 订阅 — PR 事件实时推送给 Agent |
| `PROACTIVE` | 主动模式 — Agent 主动执行任务,含 SleepTool 定时唤醒 |
| `COORDINATOR_MODE` | 协调器模式 — 多 Agent 编排调度 |
| `BUDDY` | Buddy 配对编程功能 |
| `FORK_SUBAGENT` | Fork 子代理 — 从当前会话分叉出独立子代理 |
### 远程 / 分布式
| Flag | 用途 |
|------|------|
| `BRIDGE_MODE` | 远程控制桥接 — 允许外部客户端远程操控 Claude Code |
| `DAEMON` | 守护进程 — 后台常驻服务,支持 worker 和 supervisor |
| `BG_SESSIONS` | 后台会话 — `ps`/`logs`/`attach`/`kill`/`--bg` 等后台进程管理 |
| `SSH_REMOTE` | SSH 远程 — `claude ssh <host>` 连接远程主机 |
| `DIRECT_CONNECT` | 直连模式 — `cc://` URL 协议、server 命令、`open` 命令 |
| `CCR_REMOTE_SETUP` | 网页端远程配置 — 通过浏览器配置 Claude Code |
| `CCR_MIRROR` | Claude Code Runtime 镜像 — 会话状态同步/复制 |
### 通信
| Flag | 用途 |
|------|------|
| `UDS_INBOX` | Unix Domain Socket 收件箱 — Agent 间本地通信(`/peers` |
### 增强工具
| Flag | 用途 |
|------|------|
| `CHICAGO_MCP` | Computer Use MCP — 计算机操作(屏幕截图、鼠标键盘控制) |
| `WEB_BROWSER_TOOL` | 网页浏览器工具 — 在终端内嵌浏览器交互 |
| `VOICE_MODE` | 语音模式 — 语音输入输出,麦克风 push-to-talk |
| `WORKFLOW_SCRIPTS` | 工作流脚本 — 用户自定义自动化工作流 |
| `MCP_SKILLS` | 基于 MCP 的 Skill 加载机制 |
### 对话管理
| Flag | 用途 |
|------|------|
| `HISTORY_SNIP` | 历史裁剪 — 手动裁剪对话历史中的片段(`/force-snip` |
| `ULTRAPLAN` | 超级计划 — 远程 Agent 协作的大规模规划功能 |
| `AGENT_MEMORY_SNAPSHOT` | Agent 运行时的记忆快照功能 |
### 基础设施 / 实验
| Flag | 用途 |
|------|------|
| `ABLATION_BASELINE` | 科学实验 — 基线消融测试,用于 A/B 实验对照组 |
| `HARD_FAIL` | 硬失败模式 — 遇错直接中断而非降级 |
| `TRANSCRIPT_CLASSIFIER` | 对话分类器 — `auto-mode` 命令,自动分析和分类对话记录 |
| `UPLOAD_USER_SETTINGS` | 设置同步上传 — 将本地配置同步到云端 |
| `LODESTONE` | 深度链接协议处理器 — 从外部应用跳转到 Claude Code 指定位置 |
| `EXPERIMENTAL_SKILL_SEARCH` | 实验性 Skill 搜索索引 |
| `TORCH` | Torch 功能(具体用途未知,可能是某种高亮/追踪机制) |
## 许可证
本项目仅供学习研究用途。Claude Code 的所有权利归 [Anthropic](https://www.anthropic.com/) 所有。

158
README_EN.md Normal file
View File

@@ -0,0 +1,158 @@
# Claude Code Best V5 (CCB)
[![GitHub Stars](https://img.shields.io/github/stars/claude-code-best/claude-code?style=flat-square&logo=github&color=yellow)](https://github.com/claude-code-best/claude-code/stargazers)
[![GitHub Contributors](https://img.shields.io/github/contributors/claude-code-best/claude-code?style=flat-square&color=green)](https://github.com/claude-code-best/claude-code/graphs/contributors)
[![GitHub Issues](https://img.shields.io/github/issues/claude-code-best/claude-code?style=flat-square&color=orange)](https://github.com/claude-code-best/claude-code/issues)
[![GitHub License](https://img.shields.io/github/license/claude-code-best/claude-code?style=flat-square)](https://github.com/claude-code-best/claude-code/blob/main/LICENSE)
[![Last Commit](https://img.shields.io/github/last-commit/claude-code-best/claude-code?style=flat-square&color=blue)](https://github.com/claude-code-best/claude-code/commits/main)
[![Bun](https://img.shields.io/badge/runtime-Bun-black?style=flat-square&logo=bun)](https://bun.sh/)
> Which Claude do you like? The open source one is the best.
A reverse-engineered / decompiled source restoration of Anthropic's official [Claude Code](https://docs.anthropic.com/en/docs/claude-code) CLI tool. The goal is to reproduce most of Claude Code's functionality and engineering capabilities. It's abbreviated as CCB.
[Documentation (Chinese)](https://ccb.agent-aura.top/) — PR contributions welcome.
Sponsor placeholder.
- [x] v1: Basic runability and type checking pass
- [x] V2: Complete engineering infrastructure
- [ ] Biome formatting may not be implemented first to avoid code conflicts
- [x] Build pipeline complete, output runnable on both Node.js and Bun
- [x] V3: Extensive documentation and documentation site improvements
- [x] V4: Large-scale test suite for improved stability
- [x] Buddy pet feature restored [Docs](https://ccb.agent-aura.top/docs/features/buddy)
- [x] Auto Mode restored [Docs](https://ccb.agent-aura.top/docs/safety/auto-mode)
- [x] All features now configurable via environment variables instead of `bun --feature`
- [x] V5: Enterprise-grade monitoring/reporting, missing tools补全, restrictions removed
- [x] Removed anti-distillation code
- [x] Web search capability (using Bing) [Docs](https://ccb.agent-aura.top/docs/features/web-browser-tool)
- [x] Debug mode support [Docs](https://ccb.agent-aura.top/docs/features/debug-mode)
- [x] Disabled auto-updates
- [x] Custom Sentry error reporting support [Docs](https://ccb.agent-aura.top/docs/internals/sentry-setup)
- [x] Custom GrowthBook support (GB is open source — configure your own feature flag platform) [Docs](https://ccb.agent-aura.top/docs/internals/growthbook-adapter)
- [x] Custom login mode — configure Claude models your way
- [ ] V6: Large-scale refactoring, full modular packaging
- [ ] V6 will be a new branch; main branch will be archived as a historical version
> I don't know how long this project will survive. Star + Fork + git clone + .zip is the safest bet.
>
> This project updates rapidly — Opus continuously optimizes in the background, with new changes almost every few hours.
>
> Claude has burned over $1000, out of budget, switching to GLM to continue; @zai-org GLM 5.1 is quite capable.
## Quick Start
### Prerequisites
Make sure you're on the latest version of Bun, otherwise you'll run into all sorts of weird bugs. Run `bun upgrade`!
- [Bun](https://bun.sh/) >= 1.3.11
- Standard Claude Code configuration — each provider has its own setup method
### Install
```bash
bun install
```
### Run
```bash
# Dev mode — if you see version 888, it's working
bun run dev
# Build
bun run build
```
The build uses code splitting (`build.ts`), outputting to `dist/` (entry `dist/cli.js` + ~450 chunk files).
The build output runs on both Bun and Node.js — you can publish to a private registry and run directly.
If you encounter a bug, please open an issue — we'll prioritize it.
### First-time Setup /login
After the first run, enter `/login` in the REPL to access the login configuration screen. Select **Anthropic Compatible** to connect to third-party API-compatible services (no Anthropic account required).
Fields to fill in:
| Field | Description | Example |
|-------|-------------|---------|
| Base URL | API service URL | `https://api.example.com/v1` |
| API Key | Authentication key | `sk-xxx` |
| Haiku Model | Fast model ID | `claude-haiku-4-5-20251001` |
| Sonnet Model | Balanced model ID | `claude-sonnet-4-6` |
| Opus Model | High-performance model ID | `claude-opus-4-6` |
- **Tab / Shift+Tab** to switch fields, **Enter** to confirm and move to the next, press Enter on the last field to save
- Model fields auto-fill from current environment variables
- Configuration saves to `~/.claude/settings.json` under the `env` key, effective immediately
You can also edit `~/.claude/settings.json` directly:
```json
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.example.com/v1",
"ANTHROPIC_AUTH_TOKEN": "sk-xxx",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-haiku-4-5-20251001",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-4-6",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-4-6"
}
}
```
> Supports all Anthropic API-compatible services (e.g., OpenRouter, AWS Bedrock proxies, etc.) as long as the interface is compatible with the Messages API.
## Feature Flags
All feature toggles are enabled via `FEATURE_<FLAG_NAME>=1` environment variables, for example:
```bash
FEATURE_BUDDY=1 FEATURE_FORK_SUBAGENT=1 bun run dev
```
See [`docs/features/`](docs/features/) for detailed descriptions of each feature. Contributions welcome.
## VS Code Debugging
The TUI (REPL) mode requires a real terminal and cannot be launched directly via VS Code's launch config. Use **attach mode**:
### Steps
1. **Start inspect server in terminal**:
```bash
bun run dev:inspect
```
This outputs an address like `ws://localhost:8888/xxxxxxxx`.
2. **Attach debugger from VS Code**:
- Set breakpoints in `src/` files
- Press F5 → select **"Attach to Bun (TUI debug)"**
## Documentation & Links
- **Online docs (Mintlify)**: [ccb.agent-aura.top](https://ccb.agent-aura.top/) — source in [`docs/`](docs/), PR contributions welcome
- **DeepWiki**: <https://deepwiki.com/claude-code-best/claude-code>
## Contributors
<a href="https://github.com/claude-code-best/claude-code/graphs/contributors">
<img src="https://contrib.rocks/image?repo=claude-code-best/claude-code" />
</a>
## Star History
<a href="https://www.star-history.com/?repos=claude-code-best%2Fclaude-code&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/image?repos=claude-code-best%2Fclaude-code&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/image?repos=claude-code-best%2Fclaude-code&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/image?repos=claude-code-best%2Fclaude-code&type=date&legend=top-left" />
</picture>
</a>
## License
This project is for educational and research purposes only. All rights to Claude Code belong to [Anthropic](https://www.anthropic.com/).

26
TODO.md
View File

@@ -1,26 +0,0 @@
# TODO
尽可能实现下面的包, 使得与主包的关系完全吻合
## Packages
- [x] `url-handler-napi` — URL 处理 NAPI 模块 (签名修正,保持 null fallback)
- [x] `modifiers-napi` — 修饰键检测 NAPI 模块 (Bun FFI + Carbon)
- [x] `audio-capture-napi` — 音频捕获 NAPI 模块 (SoX/arecord)
- [x] `color-diff-napi` — 颜色差异计算 NAPI 模块 (纯 TS 实现)
- [x] `image-processor-napi` — 图像处理 NAPI 模块 (sharp + osascript 剪贴板)
- [x] `@ant/computer-use-swift` — Computer Use Swift 原生模块 (macOS JXA/screencapture 实现)
- [x] `@ant/computer-use-mcp` — Computer Use MCP 服务 (类型安全 stub + sentinel apps + targetImageSize)
- [x] `@ant/computer-use-input` — Computer Use 输入模块 (macOS AppleScript/JXA 实现)
<!-- - [ ] `@ant/claude-for-chrome-mcp` — Chrome MCP 扩展 -->
## 工程化能力
- [x] 代码格式化与校验
- [x] 冗余代码检查
- [x] git hook 的配置
- [x] 代码健康度检查
- [x] Biome lint 规则调优(适配反编译代码,关闭格式化避免大规模 diff
- [x] 单元测试基础设施搭建 (test runner 配置)
- [x] CI/CD 流水线 (GitHub Actions)

1330
V6.md Normal file

File diff suppressed because it is too large Load Diff

167
build.ts
View File

@@ -1,47 +1,152 @@
import { readdir, readFile, writeFile } from "fs/promises";
import { join } from "path";
import { readdir, readFile, writeFile, cp } from 'fs/promises'
import { join } from 'path'
import { getMacroDefines } from './scripts/defines.ts'
const outdir = "dist";
const outdir = 'dist'
// Step 1: Clean output directory
const { rmSync } = await import("fs");
rmSync(outdir, { recursive: true, force: true });
const { rmSync } = await import('fs')
rmSync(outdir, { recursive: true, force: true })
// Default features that match the official CLI build.
// Additional features can be enabled via FEATURE_<NAME>=1 env vars.
const DEFAULT_BUILD_FEATURES = [
'AGENT_TRIGGERS_REMOTE',
'CHICAGO_MCP',
'VOICE_MODE',
'SHOT_STATS',
'PROMPT_CACHE_BREAK_DETECTION',
'TOKEN_BUDGET',
// P0: local features
'AGENT_TRIGGERS',
'ULTRATHINK',
'BUILTIN_EXPLORE_PLAN_AGENTS',
'LODESTONE',
// P1: API-dependent features
'EXTRACT_MEMORIES',
'VERIFICATION_AGENT',
'KAIROS_BRIEF',
'AWAY_SUMMARY',
'ULTRAPLAN',
// P2: daemon + remote control server
'DAEMON',
// ACP (Agent Client Protocol) agent mode
'ACP',
// PR-package restored features
'WORKFLOW_SCRIPTS',
'HISTORY_SNIP',
'CONTEXT_COLLAPSE',
'MONITOR_TOOL',
'FORK_SUBAGENT',
// 'UDS_INBOX',
'KAIROS',
'COORDINATOR_MODE',
'LAN_PIPES',
'BG_SESSIONS',
'TEMPLATES',
// 'REVIEW_ARTIFACT', // API 请求无响应,需进一步排查 schema 兼容性
// P3: poor mode (disable extract_memories + prompt_suggestion)
'POOR',
]
// Collect FEATURE_* env vars → Bun.build features
const envFeatures = Object.keys(process.env)
.filter(k => k.startsWith('FEATURE_'))
.map(k => k.replace('FEATURE_', ''))
const features = [...new Set([...DEFAULT_BUILD_FEATURES, ...envFeatures])]
// Step 2: Bundle with splitting
const result = await Bun.build({
entrypoints: ["src/entrypoints/cli.tsx"],
outdir,
target: "bun",
splitting: true,
});
entrypoints: ['src/entrypoints/cli.tsx'],
outdir,
target: 'bun',
splitting: true,
define: getMacroDefines(),
features,
})
if (!result.success) {
console.error("Build failed:");
for (const log of result.logs) {
console.error(log);
}
process.exit(1);
console.error('Build failed:')
for (const log of result.logs) {
console.error(log)
}
process.exit(1)
}
// Step 3: Post-process — replace Bun-only `import.meta.require` with Node.js compatible version
const files = await readdir(outdir);
const IMPORT_META_REQUIRE = "var __require = import.meta.require;";
const COMPAT_REQUIRE = `var __require = typeof import.meta.require === "function" ? import.meta.require : (await import("module")).createRequire(import.meta.url);`;
const files = await readdir(outdir)
const IMPORT_META_REQUIRE = 'var __require = import.meta.require;'
const COMPAT_REQUIRE = `var __require = typeof import.meta.require === "function" ? import.meta.require : (await import("module")).createRequire(import.meta.url);`
let patched = 0;
let patched = 0
for (const file of files) {
if (!file.endsWith(".js")) continue;
const filePath = join(outdir, file);
const content = await readFile(filePath, "utf-8");
if (content.includes(IMPORT_META_REQUIRE)) {
await writeFile(
filePath,
content.replace(IMPORT_META_REQUIRE, COMPAT_REQUIRE),
);
patched++;
}
if (!file.endsWith('.js')) continue
const filePath = join(outdir, file)
const content = await readFile(filePath, 'utf-8')
if (content.includes(IMPORT_META_REQUIRE)) {
await writeFile(
filePath,
content.replace(IMPORT_META_REQUIRE, COMPAT_REQUIRE),
)
patched++
}
}
// Also patch unguarded globalThis.Bun destructuring from third-party deps
// (e.g. @anthropic-ai/sandbox-runtime) so Node.js doesn't crash at import time.
let bunPatched = 0
const BUN_DESTRUCTURE = /var \{([^}]+)\} = globalThis\.Bun;?/g
const BUN_DESTRUCTURE_SAFE = 'var {$1} = typeof globalThis.Bun !== "undefined" ? globalThis.Bun : {};'
for (const file of files) {
if (!file.endsWith('.js')) continue
const filePath = join(outdir, file)
const content = await readFile(filePath, 'utf-8')
if (BUN_DESTRUCTURE.test(content)) {
await writeFile(
filePath,
content.replace(BUN_DESTRUCTURE, BUN_DESTRUCTURE_SAFE),
)
bunPatched++
}
}
BUN_DESTRUCTURE.lastIndex = 0
console.log(
`Bundled ${result.outputs.length} files to ${outdir}/ (patched ${patched} for Node.js compat)`,
);
`Bundled ${result.outputs.length} files to ${outdir}/ (patched ${patched} for import.meta.require, ${bunPatched} for Bun destructure)`,
)
// Step 4: Copy native .node addon files (audio-capture)
const vendorDir = join(outdir, 'vendor', 'audio-capture')
await cp('vendor/audio-capture', vendorDir, { recursive: true })
console.log(`Copied vendor/audio-capture/ → ${vendorDir}/`)
// Step 5: Bundle download-ripgrep script as standalone JS for postinstall
const rgScript = await Bun.build({
entrypoints: ['scripts/download-ripgrep.ts'],
outdir,
target: 'node',
})
if (!rgScript.success) {
console.error('Failed to bundle download-ripgrep script:')
for (const log of rgScript.logs) {
console.error(log)
}
// Non-fatal — postinstall fallback to bun run scripts/download-ripgrep.ts
} else {
console.log(`Bundled download-ripgrep script to ${outdir}/`)
}
// Step 6: Generate cli-bun and cli-node executable entry points
const cliBun = join(outdir, 'cli-bun.js')
const cliNode = join(outdir, 'cli-node.js')
await writeFile(cliBun, '#!/usr/bin/env bun\nimport "./cli.js"\n')
await writeFile(cliNode, '#!/usr/bin/env node\nimport "./cli.js"\n')
// Make both executable
const { chmodSync } = await import('fs')
chmodSync(cliBun, 0o755)
chmodSync(cliNode, 0o755)
console.log(`Generated ${cliBun} (shebang: bun) and ${cliNode} (shebang: node)`)

2023
bun.lock

File diff suppressed because it is too large Load Diff

50
contributors.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 1.6 MiB

188
docs.json Normal file
View File

@@ -0,0 +1,188 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "mint",
"name": "Claude Code Architecture",
"colors": {
"primary": "#D97706",
"light": "#F59E0B",
"dark": "#B45309"
},
"favicon": "/docs/favicon.svg",
"navigation": {
"groups": [
{
"group": "开始",
"pages": [
{
"group": "介绍",
"pages": [
"docs/introduction/what-is-claude-code",
"docs/introduction/why-this-whitepaper",
"docs/introduction/architecture-overview"
]
}
]
},
{
"group": "对话是如何运转的",
"pages": [
"docs/conversation/the-loop",
"docs/conversation/streaming",
"docs/conversation/multi-turn"
]
},
{
"group": "工具AI 的双手",
"pages": [
"docs/tools/what-are-tools",
"docs/tools/file-operations",
"docs/tools/shell-execution",
"docs/tools/search-and-navigation",
"docs/tools/task-management"
]
},
{
"group": "上下文工程",
"pages": [
"docs/context/system-prompt",
"docs/context/project-memory",
"docs/context/compaction",
"docs/context/token-budget"
]
},
{
"group": "多 Agent 协作",
"pages": [
"docs/agent/sub-agents",
"docs/agent/worktree-isolation",
"docs/agent/coordinator-and-swarm"
]
},
{
"group": "可扩展性",
"pages": [
"docs/extensibility/mcp-protocol",
"docs/extensibility/hooks",
"docs/extensibility/skills",
"docs/extensibility/custom-agents"
]
},
{
"group": "安全与权限",
"pages": [
"docs/safety/why-safety-matters",
"docs/safety/permission-model",
"docs/safety/sandbox",
"docs/safety/plan-mode",
"docs/safety/auto-mode"
]
},
{
"group": "揭秘:隐藏功能与内部机制",
"pages": [
"docs/internals/three-tier-gating",
"docs/internals/feature-flags",
"docs/internals/growthbook-ab-testing",
"docs/internals/growthbook-adapter",
"docs/internals/sentry-setup",
"docs/internals/hidden-features",
"docs/internals/ant-only-world",
"docs/features/debug-mode",
"docs/features/buddy"
]
},
{
"group": "隐藏功能详解",
"pages": [
{
"group": "Agent 与协作",
"pages": [
"docs/features/coordinator-mode",
"docs/features/fork-subagent",
"docs/features/daemon",
"docs/features/teammem"
]
},
{
"group": "运行模式",
"pages": [
"docs/features/kairos",
"docs/features/voice-mode",
"docs/features/bridge-mode",
"docs/features/remote-control-self-hosting",
"docs/features/proactive",
"docs/features/ultraplan"
]
},
{
"group": "工具增强",
"pages": [
"docs/features/mcp-skills",
"docs/features/tree-sitter-bash",
"docs/features/bash-classifier",
"docs/features/web-browser-tool",
"docs/features/experimental-skill-search"
]
},
{
"group": "上下文与自动化",
"pages": [
"docs/features/token-budget",
"docs/features/context-collapse",
"docs/features/workflow-scripts",
"docs/features/auto-dream"
]
},
"docs/features/tier3-stubs"
]
},
{
"group": "基础设施与依赖",
"pages": [
"docs/auto-updater",
"docs/lsp-integration",
"docs/external-dependencies",
"docs/telemetry-remote-config-audit"
]
}
]
},
"logo": {
"light": "/docs/logo/light.svg",
"dark": "/docs/logo/dark.svg"
},
"background": {
"color": {
"light": "#FFFFFF",
"dark": "#0F172A"
}
},
"navbar": {
"primary": {
"type": "github",
"href": "https://github.com/claude-code-best/claude-code"
}
},
"search": {
"prompt": "搜索 Claude Code 架构文档..."
},
"seo": {
"metatags": {
"og:image": "https://ccb.agent-aura.top/docs/images/og-cover.png",
"twitter:image": "https://ccb.agent-aura.top/docs/images/og-cover.png",
"twitter:card": "summary_large_image"
},
"indexing": "navigable"
},
"footer": {
"socials": {
"github": "https://github.com/anthropics/claude-code"
}
},
"redirects": [
{
"source": "/docs/introduction",
"destination": "/docs/introduction/what-is-claude-code"
}
]
}

View File

@@ -1,128 +0,0 @@
# 文档修正计划
> 目标:补充源码级洞察,让每篇文档从"概念科普"升级为"逆向工程白皮书"水准。
---
## 第一梯队:空壳页,需要大幅重写
### 1. `safety/sandbox.mdx` — 沙箱机制 ✅ DONE
**现状**35 行,只列了"文件系统/网络/进程/时间"四个维度,没有任何实现细节。
**修正方向**
- 补充 macOS `sandbox-exec` 的实际调用方式,展示沙箱 profile 的关键片段
- 说明 `getSandboxConfig()` 的判定逻辑:哪些命令走沙箱、哪些跳过
- 补充 `dangerouslyDisableSandbox` 参数的设计权衡
- 加入 Linux 平台的沙箱差异对比seatbelt vs namespace
- 展示一次命令执行从权限检查→沙箱包裹→实际执行的完整链路
---
### 2. `introduction/what-is-claude-code.mdx` — 什么是 Claude Code ✅ DONE
**现状**39 行,纯营销文案,和"普通聊天 AI"的对比表太低级。
**修正方向**
- 砍掉"能做什么"的泛泛列表,改为一个具体的端到端示例(从用户输入→系统处理→最终输出)
- 用一张简化架构图替代文字描述,让读者 30 秒建立直觉
- 补充 Claude Code 的技术定位:不是 IDE 插件、不是 Web Chat而是 terminal-native agentic system
- 加入与 Cursor / Copilot / Aider 等工具的定位差异(架构层面而非功能清单)
---
### 3. `introduction/why-this-whitepaper.mdx` — 为什么写这份白皮书 ✅ DONE
**现状**40 行,全是空话,四张 Card 只是后续章节标题的预告。
**修正方向**
- 明确定位:这是对 Anthropic 官方 CLI 的逆向工程分析,不是官方文档
- 列出逆向过程中发现的 3-5 个最意外/最精妙的设计决策(吊住读者胃口)
- 说明白皮书的阅读路线图:推荐的阅读顺序和每个章节解决什么问题
- 补充"这份白皮书不是什么"——不是使用教程,不是 API 文档
---
### 4. `safety/why-safety-matters.mdx` — 为什么安全至关重要 ✅ DONE
**现状**40 行,只列了显而易见的风险,"安全 vs 效率的平衡"只有 3 个 bullet。
**修正方向**
- 从源码角度展示安全体系的全景图:权限规则 → 沙箱 → Plan Mode → 预算上限 → Hooks 的纵深防御链
- 补充 Claude 自身 System Prompt 中的安全指令("执行前确认"、"优先可逆操作"等),展示 AI 端的安全约束
- 用真实场景说明"安全 vs 效率"的工程权衡:比如 Read 工具为什么免审批、Bash 工具为什么要逐条确认
- 加入 Prompt Injection 防御的简要说明tool result 中的恶意内容如何被系统标记)
---
## 第二梯队:有骨架但太浅,需要补肉
### 5. `conversation/streaming.mdx` — 流式响应 ✅ DONE
**现状**43 行,只说了"流式好"和 3 行 provider 表。
**修正方向**
- 补充 `BetaRawMessageStreamEvent` 的核心事件类型及其含义
- 展示文本 chunk 和 tool_use block 交织的状态机流转
- 说明流式中的错误处理网络断开、API 限流、token 超限时的重试/降级策略
- 补充 `processStreamEvents()` 的核心逻辑如何从事件流中分离出文本、工具调用、usage 统计
---
### 6. `tools/search-and-navigation.mdx` — 搜索与导航 ✅ DONE
**现状**43 行,只说 Glob 和 Grep 存在。
**修正方向**
- 补充 ripgrep 二进制的内嵌方式vendor 目录、平台适配)
- 说明搜索结果的 head_limit 默认 250 的设计原因token 预算)
- 展示 ToolSearch 的实现:如何用语义匹配在 50+ 工具(含 MCP中找到最相关的
- 补充 Glob 按修改时间排序的意义:最近修改的文件最可能与当前任务相关
---
### 7. `tools/task-management.mdx` — 任务管理 ✅ DONE
**现状**50 行,只有流程 Steps 和状态展示的 4 个 bullet。
**修正方向**
- 补充任务的数据模型id / subject / description / status / blockedBy / blocks / owner
- 说明依赖管理的实现blockedBy 如何阻止任务被认领、完成一个任务后如何自动解锁下游
- 展示任务与 Agent 工具的联动:子 Agent 如何认领任务、报告进度
- 补充 activeForm 字段的 UX 设计:进行中任务的 spinner 动画文案
---
### 8. `context/token-budget.mdx` — Token 预算管理 ✅ DONE
**现状**55 行,预算控制只有 3 张 Card 各一句话。
**修正方向**
- 补充 `contextWindowTokens``maxOutputTokens` 的动态计算逻辑
- 说明缓存 breakpoint 的放置策略System Prompt 中不变内容在前、变化内容在后的原因
- 展示工具输出截断的具体机制:超长结果如何被 truncate、何时触发 micro-compact
- 补充 token 计数的实现:`countTokens` 的调用时机和近似 vs 精确计数的权衡
---
### 9. `agent/worktree-isolation.mdx` — Worktree 隔离 ✅ DONE
**现状**55 行,只描述了 git worktree 的概念。
**修正方向**
- 展示 `.claude/worktrees/` 的目录结构和分支命名规则
- 说明 worktree 的生命周期:创建时机(`isolation: "worktree"`)→ 子 Agent 执行 → 完成/放弃 → 自动清理
- 补充 worktree 与子 Agent 的绑定关系Agent 结束时如何判断 keep or remove
- 加入 EnterWorktree / ExitWorktree 工具的交互设计
---
### 10. `extensibility/custom-agents.mdx` — 自定义 Agent ✅ DONE
**现状**56 行,只有配置表和示例表。
**修正方向**
- 展示 agent markdown 文件的完整 frontmatter 格式name / description / model / allowedTools 等)
- 说明 agent 如何被加载和注入 System Prompt`loadAgentDefinitions()` 的发现和合并逻辑
- 展示工具限制的实现allowedTools 如何过滤工具列表
- 补充 agent 与 subagent_type 参数的关联Agent 工具如何指定使用自定义 Agent

View File

@@ -10,13 +10,13 @@ keywords: ["协调者模式", "蜂群模式", "Agent Swarm", "多 Agent 协作",
| 维度 | Coordinator Mode | Agent Swarms |
|------|-----------------|--------------|
| **门控** | `feature('COORDINATOR_MODE')` + `CLAUDE_CODE_COORDINATOR_MODE=1` | 任务系统 V2默认启用 |
| **拓扑** | 星型Coordinator 居中Worker 外围 | 网状:对等 Agent 共享任务列表 |
| **角色** | 明确分工Coordinator 编排、Worker 执行 | 模糊:每个 Agent 自主认领任务 |
| **通信** | `SendMessage` 定向通信 + `<task-notification>` | 任务文件系统 + 邮箱广播 |
| **适用** | 需要集中决策的复杂任务 | 并行度高的独立子任务 |
| **门控** | `feature('COORDINATOR_MODE')` + `CLAUDE_CODE_COORDINATOR_MODE=1` | `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` 环境变量 |
| **拓扑** | 星型Coordinator 居中Worker 外围 | 星型+P2P 混合Team Lead 协调Teammate 间可直接通信 |
| **角色** | 明确分工Coordinator 编排、Worker 执行 | Team Lead 协调 + Teammate 自主认领任务 |
| **通信** | `SendMessage` 定向通信 + `<task-notification>` | Mailbox 消息系统message / broadcast |
| **适用** | 需要集中决策的复杂任务 | 并行度高、需要 Teammate 间直接协作的任务 |
两者不是互斥的——Coordinator Mode 可以在 Swarm 架构之上运行,将 Coordinator 作为特殊的 Leader Agent
两者不是互斥的——理论上 Coordinator Mode 可以在 Agent Teams 架构之上运行(概念层叠加,非嵌套团队),将 Coordinator 作为特殊的 Team Lead但这部分集成`workerAgent.ts` 中的 `getCoordinatorAgents`)目前为 stub 实现,尚未完整落地
## Coordinator Mode星型编排架构
@@ -45,7 +45,7 @@ Coordinator 被剥夺了所有"动手"工具,只保留编排能力:
| **TaskStop** | 中途停止走错方向的 Worker |
| **subscribe_pr_activity** | 订阅 GitHub PR 事件review comments、CI 结果) |
Coordinator **不写代码、不读文件、不执行命令**——它只做三件事:理解需求、分配任务、综合结果。
Coordinator **不写代码、不读文件、不执行命令**——它的核心职责是:理解需求、分配任务、综合结果,以及在无需工具时直接回答用户问题
### Worker 的工具权限
@@ -53,7 +53,7 @@ Worker 的可用工具由 `getCoordinatorUserContext()``coordinatorMode.ts:80
```typescript
// 简化模式下:只有 Bash + Read + Edit
const workerTools = isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE')
const workerTools = isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)
? [BASH_TOOL_NAME, FILE_READ_TOOL_NAME, FILE_EDIT_TOOL_NAME]
: Array.from(ASYNC_AGENT_ALLOWED_TOOLS)
.filter(name => !INTERNAL_WORKER_TOOLS.has(name))
@@ -63,7 +63,7 @@ const workerTools = isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE')
### Scratchpad跨 Worker 的共享知识库
当 `tengu_scratch` feature flag 启用时Coordinator 拥有一个 Scratchpad 目录
当 `isScratchpadGateEnabled()`(内部检查 `tengu_scratch` feature gate启用时Workers 获得一个 Scratchpad 目录Coordinator 通过其系统上下文知晓该目录的存在
```
Scratchpad 目录:
@@ -113,32 +113,84 @@ Coordinator System Prompt`coordinatorMode.ts:111-369`,约 260 行)明确
这是 Coordinator Mode 最核心的设计约束Coordinator 必须先理解,再分配。
## Agent Swarms:蜂群式协作
## Agent Teams (Swarm):蜂群式协作
Swarm 模式基于任务系统 V2详见[任务管理](../tools/task-management.mdx)),核心机制是**共享任务列表 + 竞争认领**
Swarm 模式基于任务系统 V2详见[任务管理](../tools/task-management.mdx)),核心机制是**共享任务列表 + 竞争认领 + Mailbox 消息系统**
### 团队初始化
```
Leader 创建团队TeamCreateTool
Team Lead 创建团队TeamCreateTool
设置 teamName → setLeaderTeamName()
所有 teammate 自动获得相同的 taskListId
所有 Teammate 自动获得相同的 taskListId
teammate 启动时:
Teammate 启动时:
1. CLAUDE_CODE_TASK_LIST_ID 环境变量(显式覆盖)
2. teammate 上下文的 teamName共享 leader 的任务列表)
2. Teammate 上下文的 teamName共享 Lead 的任务列表)
3. CLAUDE_CODE_TEAM_NAME 环境变量
4. leader 设置的 teamName
4. Lead 设置的 teamName
5. getSessionId()(兜底)
```
多级优先级确保了 Leader 和所有 Teammate 指向同一个任务列表,无需额外协调。
多级优先级确保了 Team Lead 和所有 Teammate 指向同一个任务列表,无需额外协调。
### 架构组件
官方 Agent Teams 架构定义了四个核心组件:
| 组件 | 角色 |
|------|------|
| **Team Lead** | 创建团队、分配任务、综合结果的主 Claude Code 会话 |
| **Teammate** | 独立的 Claude Code 实例,各自拥有独立的上下文窗口 |
| **Task List** | 共享的任务列表Teammate 竞争认领和完成 |
| **Mailbox** | 消息系统,支持 Teammate 间直接通信 |
### Mailbox 消息系统
官方架构中的 Mailbox 是 Teammate 间通信的核心原语,支持两种消息模式(`broadcast` 模式来自源码推断,官方文档未明确细分):
| 模式 | 作用 | 场景 |
|------|------|------|
| **message** | 定向发送给指定 Teammate | 传递具体指令、请求协作 |
| **broadcast** | 广播给所有 Teammate | 全局通知、状态同步 |
Mailbox 的关键特性:
- **自动投递**:消息自动送达目标 Teammate 的对话上下文
- **空闲通知**TeammateIdleTeammate 完成当前任务进入空闲时,自动通过 Mailbox 通知 Team Lead
- **直接通信**:与 Coordinator Mode 不同Teammate 之间可以直接通信,无需经过 Lead 中转
### Hook 事件
Agent Teams 提供三个关键 Hook 事件,用于在团队生命周期中注入自定义逻辑:
| Hook | 触发时机 | 典型用途 |
|------|---------|---------|
| **TaskCreated** | 新任务添加到任务列表时 | 自动分配、优先级排序 |
| **TaskCompleted** | 任务标记为完成时 | 结果通知、依赖解锁 |
| **TeammateIdle** | Teammate 完成所有任务进入空闲时 | Lead 重新分配、动态扩缩容 |
### 限制
当前 Agent Teams 实现的限制:
- **不支持嵌套团队**Teammate 不能再创建子团队
- **每 session 一个团队**:一个会话只能属于一个团队
- **Lead 固定**Team Lead 创建后不可更换
- **不支持 in-process Teammate 的会话恢复**:进程重启后 in-process 类型 Teammate 的状态丢失
### 持久化存储
团队状态通过文件系统持久化,确保进程重启后可恢复:
```
~/.claude/teams/{team-name}/config.json ← 团队配置
~/.claude/tasks/{team-name}/ ← 共享任务列表(文件锁保护)
```
### 任务认领与竞争
`claimTask()` 是 Swarm 的核心并发原语:
`claimTask()` 是 Agent Teams 的核心并发原语:
```
Teammate A 调用 TaskList → 发现 task #3 是 pending
@@ -146,7 +198,7 @@ Teammate B 同时发现 task #3 是 pending
两者同时尝试 TaskUpdate(task #3, {status: "in_progress"})
文件锁 + 高水位标记保证原子性:
文件锁保证原子性:
- 第一个写入者获得 owner 锁定
- 第二个写入者收到 already_claimed 错误
@@ -166,8 +218,11 @@ unassignTeammateTasks()
→ 扫描任务列表,找到 owner === teammateName 的未完成任务
→ 重置为 pending + owner=undefined
Leader 通过 mailbox 收到通知
→ 重新分配或创建新 Teammate
Team Lead 感知途径:
1. 任务状态变化pending 重置)—— 通过共享任务列表
2. Mailbox 空闲通知TeammateIdle hook—— Teammate 停止时自动通知 Lead
Team Lead 重新分配任务或创建新 Teammate
```
## 任务类型全景
@@ -186,11 +241,11 @@ Leader 通过 mailbox 收到通知
`InProcessTeammateTask` 与 `LocalAgentTask` 的关键差异:前者共享进程的内存空间和基础设施状态(如 MCP 连接池),但有独立的对话上下文和工具权限;后者是完全隔离的子进程,启动开销更大但更安全。
## Coordinator vs Swarm 的选择
## Coordinator vs Agent Teams 的选择
| 场景 | 推荐模式 | 原因 |
|------|---------|------|
| "重构认证系统,需要多模块协调" | Coordinator | 需要集中决策Worker 间有依赖 |
| "修复 10 个独立的 lint 警告" | Swarm | 任务独立,可完全并行 |
| "修复 10 个独立的 lint 警告" | Agent Teams | 任务独立Teammate 可完全并行 |
| "研究方案 A 和方案 B然后选一个实现" | Coordinator | 先并行研究,再集中决策 |
| "在大仓库中搜索所有 TODO 并分类" | Swarm | 无依赖,各自领任务即可 |
| "在大仓库中搜索所有 TODO 并分类" | Agent Teams | 无依赖,各自领任务即可 |

View File

@@ -14,8 +14,8 @@ keywords: ["子 Agent", "AgentTool", "任务委派", "forkSubagent", "子进程
AI 生成 tool_use: { prompt: "修复 bug", subagent_type: "Explore" }
AgentTool.call() ← 入口AgentTool.tsx:239
├── 解析 effectiveTypefork vs 命名 agent
├── filterDeniedAgents() ← 权限过滤
├── 解析 effectiveTypefork vs 命名 agent vs GP 回退
├── filterDeniedAgents() ← 仅命名 Agent 路径执行:权限过滤
├── 检查 requiredMcpServers ← MCP 依赖验证(最长等 30s
├── assembleToolPool(workerPermissionContext) ← 独立组装工具池
├── createAgentWorktree() ← 可选 worktree 隔离
@@ -26,26 +26,30 @@ runAgent() ← 核心执行runAgent.ts:248
├── executeSubagentStartHooks() ← Hook 注入
├── query() ← 进入标准 agentic loop
│ ├── 消息流逐条 yield
│ └── recordSidechainTranscript() ← JSONL 持久化
│ └── recordSidechainTranscript() ← JSONL 持久化~/.claude/projects/{project}/{session}/subagents/
finalizeAgentTool() ← 结果汇总
├── 提取文本内容 + usage 统计
└── mapToolResultToToolResultBlockParam() ← 格式化为 tool_result
```
## 两种子 Agent 路径:命名 Agent vs Fork
## 子 Agent 的三种路径
`AgentTool.call()` 根据是否提供 `subagent_type` 走两条完全不同的路径(`AgentTool.tsx:322-356`
`AgentTool.call()` 根据 `subagent_type` 参数和 Fork 实验开关,走三条不同的路径
| 维度 | 命名 Agent`subagent_type` 指定) | Fork 子进程(`subagent_type` 省略) |
|------|-------------------------------------|--------------------------------------|
| **触发条件** | `subagent_type` 有值 | `isForkSubagentEnabled()` && 未指定类型 |
| **System Prompt** | Agent 自身的 `getSystemPrompt()` | 继承父 Agent 的完整 System Prompt |
| **工具池** | `assembleToolPool()` 独立组装 | 父 Agent 的原始工具池(`useExactTools: true` |
| **上下文** | 仅任务描述 | 父 Agent 的完整对话历史(`forkContextMessages` |
| **模型** | 可独立指定 | 继承父模型(`model: 'inherit'` |
| **权限模式** | Agent 定义的 `permissionMode` | `'bubble'`(上浮到父终端) |
| **目的** | 专业任务委派 | Prompt Cache 命中率优化 |
| 维度 | 命名 Agent`subagent_type` 指定) | Fork 子进程(Fork 启用 + 类型省略) | General-purpose 回退Fork 关闭 + 类型省略) |
|------|-------------------------------------|--------------------------------------|---------------------------------------------|
| **触发条件** | `subagent_type` 有值 | `isForkSubagentEnabled() === true` 且未指定类型 | `isForkSubagentEnabled() === false` 且未指定类型 |
| **System Prompt** | Agent 自身的 `getSystemPrompt()` | 继承父 Agent 的完整 System Prompt | General-purpose Agent 的 `getSystemPrompt()` |
| **工具池** | `assembleToolPool()` 独立组装 | 父 Agent 的原始工具池(`useExactTools: true` | `assembleToolPool()` 独立组装 |
| **上下文** | 仅任务描述 | 父 Agent 的完整对话历史(`forkContextMessages` | 仅任务描述 |
| **模型** | 可独立指定 | 继承父模型(`model: 'inherit'` | 可独立指定 |
| **权限模式** | Agent 定义的 `permissionMode` | `'bubble'`(上浮到父终端) | Agent 定义的 `permissionMode` |
| **目的** | 专业任务委派 | Prompt Cache 命中率优化 | 通用任务处理 |
<Note>
Fork 实验的门控函数 `isForkSubagentEnabled()` 需要同时满足三个前提:`FORK_SUBAGENT` feature flag 已启用、当前不在 Coordinator 模式中、且不是非交互式会话。任一条件不满足时,省略 `subagent_type` 会静默降级为 General-purpose Agent而非触发 Fork。
</Note>
Fork 路径的设计核心是 **Prompt Cache 共享**:所有 fork 子进程共享父 Agent 的完整 `assistant` 消息(所有 `tool_use` 块),用相同的占位符 `tool_result` 填充,只有最后一个 `text` 块包含各自的指令。这使得 API 请求前缀字节完全一致,最大化缓存命中。
@@ -64,9 +68,41 @@ Fork 子进程保留 Agent 工具(为了 cache-identical tool defs但通
1. **`querySource` 检查**(压缩安全):`context.options.querySource === 'agent:builtin:fork'`
2. **消息扫描**(降级兜底):检测 `<fork-boilerplate>` 标签
## 工具池的独立组装
### 模型解析优先级
子 Agent 不继承父 Agent 的工具限制——它的工具池完全独立组装(`AgentTool.tsx:573-577`
子 Agent 的模型选择遵循严格的优先级链(`src/utils/model/agent.ts`
```
1. CLAUDE_CODE_SUBAGENT_MODEL 环境变量 ← 全局覆盖
↓(未设置时)
2. 每次调用的 model 参数 ← AgentTool 入参
↓(未指定时)
3. Agent 定义的 model frontmatter ← 如 "sonnet", "haiku", "inherit"
↓(未定义时)
4. 继承父对话模型conversation model ← getDefaultSubagentModel() 返回 "inherit"
```
其中 `inherit` 不是简单的模型传递——它经过 `getRuntimeMainLoopModel()` 解析,确保 plan mode 下的 `opusplan→Opus` 等运行时映射正确生效。当 Agent 指定的模型族(如 `haiku`)与父模型同族时,直接复用父模型的精确 ID避免跨 provider 降级。
## 命名 Agent 的工具池独立组装
### 内置 Agent
系统预定义了几个内置 Agent`src/tools/AgentTool/builtinAgents.ts`),各有明确的职责和模型配置:
| Agent | 模型 | 权限 | 用途 |
|-------|------|------|------|
| **Explore** | Haiku轻量快速 | 只读Read/Grep/Glob | 代码库搜索与探索 |
| **Plan** | 继承父模型 | 只读 | 为 Plan Mode 收集研究信息 |
| **General-purpose** | 继承父模型 | 全部工具 | 复杂的通用任务处理 |
| **statusline-setup** | 继承父模型 | 受限 | 配置状态栏设置 |
| **claude-code-guide** | 继承父模型 | 受限 | 解答 Claude Code 使用问题 |
用户还可通过 `.claude/agents/` 目录或 settings 定义自定义 Agent作用域优先级为managed settings > CLI `--agents` > 项目级 `.claude/agents/` > 用户级 `~/.claude/agents/` > plugin。
命名 Agent包括 General-purpose 回退)不继承父 Agent 的工具限制——它的工具池完全独立组装。Fork 子进程则通过 `useExactTools: true` 直接继承父 Agent 的原始工具池,以保持 Prompt Cache 中工具定义的字节一致性。
命名 Agent 的工具池组装逻辑:
```typescript
const workerPermissionContext = {
@@ -93,6 +129,17 @@ const resolvedTools = useExactTools
`resolveAgentTools()` 会根据 Agent 定义中的 `tools` 字段过滤可用工具,将 `['*']` 映射为全量工具。
### Hook 事件
子 Agent 支持 Agent 定义 frontmatter 和全局 settings.json 两种级别的 Hook
| 来源 | 事件 | 说明 |
|------|------|------|
| Agent frontmatter `hooks` | `PreToolUse` / `PostToolUse` | 工具调用前后拦截 |
| Agent frontmatter `hooks` | `Stop` | 自动转换为 `SubagentStop``registerFrontmatterHooks` 传入 `isAgent=true` |
| settings.json | `SubagentStart` | 子 Agent 启动时触发(`executeSubagentStartHooks()` |
| settings.json | `SubagentStop` | 子 Agent 停止时触发 |
## Worktree 隔离机制
`isolation: "worktree"` 参数让子 Agent 在独立的 git worktree 中工作(`AgentTool.tsx:590-593`
@@ -115,19 +162,23 @@ Worktree 生命周期:
### 异步 Agent后台运行
当 `run_in_background=true``selectedAgent.background=true` Agent 立即返回 `async_launched` 状态`AgentTool.tsx:686-764`
当 `run_in_background=true``selectedAgent.background=true`、或系统判定应强制异步(如 `assistantForceAsync`、`proactiveModule` 激活)Agent 立即返回 `async_launched` 状态:
```
registerAsyncAgent(agentId, ...) ← 注册到 AppState.tasks
↓ (void — 火后不管)
runAsyncAgentLifecycle() ← 后台执行
runAsyncAgentLifecycle() ← 后台执行agentToolUtils.ts
├── runAgent().onCacheSafeParams ← 进度摘要初始化
├── 消息流迭代
├── completeAsyncAgent() ← 标记完成
├── classifyHandoffIfNeeded() ← 安全检查
├── finalizeAgentTool() 结果汇总(提取文本 + usage 统计)
├── completeAsyncAgent() ← 标记完成(先于通知,确保 TaskOutput 尽快解除阻塞)
├── classifyHandoffIfNeeded() ← 安全分类(需 TRANSCRIPT_CLASSIFIER feature
├── getWorktreeResult() ← Worktree 清理(如有隔离)
└── enqueueAgentNotification() ← 通知主 Agent
```
如果异步 Agent 提供了 `name` 参数,还会注册到 `agentNameRegistry`,支撑 `SendMessage` 工具通过名称路由到该 Agent。
异步 Agent 获得独立的 `AbortController`,不与父 Agent 共享——用户按 ESC 取消主线程不会杀掉后台 Agent。
### 同步 Agent前台运行
@@ -154,16 +205,16 @@ const raceResult = await Promise.race([
## 结果回传格式
`mapToolResultToToolResultBlockParam()` 根据状态返回不同格式`AgentTool.tsx:1298-1375`
`mapToolResultToToolResultBlockParam()` 根据状态返回不同格式:
| 状态 | 返回内容 |
|------|---------|
| `completed` | 内容 + `<usage>` 块token/tool_calls/duration |
| `async_launched` | agentId + outputFile 路径 + 操作指引 |
| `completed` | 内容 + `<usage>` 块token/tool_calls/duration;无内容时插入占位文本 `"(Subagent completed but returned no output.)"` 防止模型误判为空 |
| `async_launched` | agentId + outputFile 路径 + 操作指引(指引内容取决于 `canReadOutputFile`:有读取权限时提示通过 Read/Bash 查看进度,否则仅告知已启动) |
| `teammate_spawned` | agent_id + name + team_name |
| `remote_launched` | taskId + sessionUrl + outputFile |
对于一次性内置 AgentExplore、Plan`<usage>` 块被省略——每周节省约 1-2 Gtok 的上下文窗口
对于一次性内置 AgentExplore、Plan当**不存在** worktree 隔离时,`<usage>` 块和 agentId 尾部被省略——每周节省约 1-2 Gtok 的上下文窗口。存在 worktree 时仍需返回 `worktreePath` 和 `worktreeBranch` 信息
## MCP 依赖的等待机制
@@ -174,7 +225,7 @@ const MAX_WAIT_MS = 30_000 // 最长等 30 秒
const POLL_INTERVAL_MS = 500 // 每 500ms 轮询
```
早期退出条件:任何必需服务器进入 `failed` 状态时立即停止等待。工具可用性通过 `mcp__` 前缀工具名解析(`mcp__serverName__toolName`)判断。
早期退出条件:任何必需服务器进入 `failed` 状态时立即停止等待。工具可用性通过 `mcp__` 前缀工具名解析(`mcp__serverName__toolName`)判断。等待结束后如果仍有必需服务器未就绪,`call()` 会抛出错误并明确列出缺失的服务器名称。
## 适用场景

View File

@@ -143,14 +143,18 @@ call() — 实际执行
## 与 Agent 工具的联动
Agent 工具(`AgentTool`)的 `isolation` 参数决定子 Agent 是否在 worktree 中运行:
Agent 工具(`AgentTool`)的 `isolation` 参数决定子 Agent 是否在 worktree 中运行。注意 Agent 工具使用**专用的** `createAgentWorktree()``src/utils/worktree.ts`),而非用户会话用的 `createWorktreeForSession()`,两者有关键差异
- `isolation: "worktree"` → 调用 `createWorktreeForSession()`,子 Agent 在独立 worktree 中执行
- 无 isolation → 子 Agent 共享主工作目录
| 维度 | `createWorktreeForSession`(用户会话) | `createAgentWorktree`(子 Agent |
|------|---------------------------------------|----------------------------------|
| 调用者 | EnterWorktreeTool | AgentTool |
| Session 管理 | 设置 `currentWorktreeSession` | **不设置** `currentWorktreeSession` |
| 恢复已有 worktree | 直接复用 | 复用并 bump mtime防止被周期性清理误删 |
子 Agent 结束时的处理:
- **成功**:主 Agent 通过 `ExitWorktreeTool(action: "keep")` 保留 worktree然后手动合并
- **失败/放弃**:主 Agent 通过 `ExitWorktreeTool(action: "remove", discard_changes: true)` 清理
子 Agent 结束时的处理由 `cleanupWorktreeIfNeeded()` 自动完成——它不走 `ExitWorktreeTool`(因为 Agent worktree 没有会话状态,`ExitWorktreeTool` 的 `validateInput` 会拒绝)
- **有变更** → 保留 worktree返回 `worktreePath` 供主 Agent 后续合并
- **无变更** → 自动删除
- **Hook-based** → 始终保留
## Session 状态持久化
@@ -168,6 +172,7 @@ Agent 工具(`AgentTool`)的 `isolation` 参数决定子 Agent 是否在 wor
tmuxSessionName?: string, // 关联的 tmux session
hookBased?: boolean, // 是否由 hook 创建
creationDurationMs?: number, // 创建耗时(分析用)
usedSparsePaths?: boolean, // 是否使用了 sparse checkout
}
```

312
docs/auto-updater.md Normal file
View File

@@ -0,0 +1,312 @@
# 自动更新机制
## 概述
Claude Code 拥有一套复杂的多策略自动更新系统,支持三种安装方式、后台静默更新、手动 CLI 命令、服务端版本门控以及更新日志展示。系统设计目标是在最小用户干预下保持 CLI 最新,同时提供回滚和手动控制的兜底手段。
---
## 安装类型与更新策略
更新策略由安装方式决定,通过 `src/utils/doctorDiagnostic.ts` 检测:
| 安装类型 | 更新策略 | 自动安装? |
|---|---|---|
| `native` | 从 GCS/Artifactory 下载二进制文件,通过符号链接激活 | 是(静默) |
| `npm-global` | `npm install -g` / `bun install -g` | 是(静默) |
| `npm-local` | `npm install``~/.claude/local/` | 是(静默) |
| `package-manager` | 显示通知,附带对应操作系统的升级命令 | 否(仅通知) |
| `development` | 不适用 — 执行 `claude update` 时报错 | 不适用 |
### 策略路由
`src/components/AutoUpdaterWrapper.tsx` — 挂载在 React/Ink UI 树中 — 检测安装类型并渲染对应的更新组件:
- `native``NativeAutoUpdater`(二进制下载 + 符号链接)
- `package-manager``PackageManagerAutoUpdater`(仅通知)
- 其他 → `AutoUpdater`(基于 JS/npm
---
## 后台自动更新循环
三个更新组件共享相同的轮询模式:
```typescript
useInterval(checkForUpdates, 30 * 60 * 1000); // 每 30 分钟
```
组件挂载时(即启动时)也会执行一次检查。
### 前置检查门控
任何更新尝试之前,系统会依次检查:
1. **自动更新是否被禁用?**`getAutoUpdaterDisabledReason()``src/utils/config.ts:1735`
- `NODE_ENV === 'development'`
- 设置了 `DISABLE_AUTOUPDATER` 环境变量
- 仅限必要流量模式
- `config.autoUpdates === false`native 安装的保护模式除外)
2. **最大版本上限?**`getMaxVersion()``src/utils/autoUpdater.ts:108`)— 服务端熔断开关,防止更新到已知有问题的版本
3. **是否跳过该版本?**`shouldSkipVersion()``src/utils/autoUpdater.ts:145`)— 尊重用户的 `minimumVersion` 设置,防止切换到 stable 频道时发生意外的版本降级
### Native 自动更新器(`src/components/NativeAutoUpdater.tsx`
1. 调用 `src/utils/nativeInstaller/installer.ts` 中的 `installLatest()`
2. 通过 `src/utils/nativeInstaller/download.ts` 下载二进制文件GCS 或 Artifactory
3. 验证 SHA256 校验和3 次重试60 秒卡顿检测)
4. 将版本化二进制文件存储到 XDG 目录
5. 更新符号链接(`~/.local/bin/claude` → 新版本二进制文件)
6. 保留最近 2 个版本,清理旧版本
7. 将错误分类上报分析超时、校验和、权限、磁盘空间不足、npm、网络
### JS/npm 自动更新器(`src/components/AutoUpdater.tsx`
1. 调用 `getLatestVersion()` 获取当前 npm dist-tag
2. 通过 semver `gte()` 比较版本
3. 根据安装类型路由到本地或全局安装
4. 使用文件锁(`acquireLock()` / `releaseLock()`)防止并发更新
### 包管理器通知器(`src/components/PackageManagerAutoUpdater.tsx`
每 30 分钟通过 GCS 存储桶(非 npm检查更新。**不会自动安装** — 仅显示对应操作系统的升级命令:
- macOS: `brew upgrade claude-code`
- Windows: `winget upgrade Anthropic.ClaudeCode`
- Alpine: `apk upgrade claude-code`
---
## 启动版本门控
`src/utils/autoUpdater.ts:70``assertMinVersion()`
`src/main.tsx:1775` 在启动时调用:
```typescript
void assertMinVersion();
```
1. 从 GrowthBook 动态配置获取 `tengu_version_config`
2. 如果 `MACRO.VERSION < minVersion`,打印错误信息并调用 `gracefulShutdownSync(1)` — 强制用户更新
3. 这是一个**硬性门控** — 低于最低版本的 CLI 将无法启动
---
## 手动 CLI 命令
### `claude update` / `claude upgrade`
**文件**: `src/cli/update.ts`
完整流程:
1. 运行 `getDoctorDiagnostic()` 检查系统健康状态
2. 检查是否存在多个安装及配置不一致
3. 根据安装类型路由:
- `development` → 报错("开发版本不支持自动更新"
- `package-manager` → 打印对应操作系统的更新命令
- `native` → 使用原生安装器的 `updateLatest()`
- `npm-local` → 在 `~/.claude/local/` 执行 `npm install`
- `npm-global` → 执行 `npm install -g`(含权限检查)
4. 报告当前版本、最新版本、成功/失败状态
### `claude rollback [target]`(仅限内部)
回滚到之前的版本。支持 `--list``--dry-run``--safe` 标志。
### `claude install [target]`
安装或重新安装原生构建版本。接受可选的版本目标参数。
### `claude doctor`
检查自动更新器的健康状态,报告状态、权限和配置信息。
---
## 原生安装器架构
**文件**: `src/utils/nativeInstaller/installer.ts`
### 二进制文件存储布局
```
~/.local/share/claude-code/
├── versions/ # 版本化二进制文件 (claude-1.0.3, claude-1.0.4, ...)
├── staging/ # 临时下载暂存区
└── locks/ # 基于 PID 和 mtime 的锁文件
~/.local/bin/claude # 指向当前版本二进制文件的符号链接
```
Windows 系统使用文件复制而非符号链接。
### 核心操作
| 函数 | 说明 |
|---|---|
| `updateLatest()` | 核心更新流程:最大版本上限 → 跳过检查 → 加锁 → 下载 → 安装 → 更新符号链接 |
| `installLatest()` | Singleflight 包装版本,防止重复的进行中安装 |
| `cleanupOldVersions()` | 保留最近 2 个版本,清理过期的暂存区和临时文件 |
| `lockCurrentVersion()` | 进程生命周期锁,防止正在运行的版本被删除 |
| `cleanupNpmInstallations()` | 迁移到原生安装时清理旧的 npm 安装 |
### 下载与校验
**文件**: `src/utils/nativeInstaller/download.ts`
1. 路由到 Artifactory内部用户或 GCS 存储桶(外部用户)
2. 下载二进制文件并跟踪进度
3. SHA256 校验和验证
4. 60 秒卡顿检测(中止停滞的下载)
5. 失败时自动重试 3 次
---
## 文件锁机制
**文件**: `src/utils/autoUpdater.ts:176-268`
防止并发更新进程破坏安装:
- 锁文件:`~/.claude/update.lock`(或等效路径)
- 5 分钟超时 — 超过 5 分钟的锁被视为过期,强制获取
- 进程将其 PID 写入锁文件
- `acquireLock()``releaseLock()` 同时被 JS/npm 和原生安装器使用
---
## 配置
### 设置项
**文件**: `src/utils/settings/types.ts`
| 设置项 | 类型 | 说明 |
|---|---|---|
| `autoUpdatesChannel` | `'latest' \| 'stable'` | 自动更新的发布频道 |
| `minimumVersion` | string | 最低版本要求,防止意外的版本降级 |
### 全局配置
**文件**: `src/utils/config.ts:191-193`
| 字段 | 类型 | 说明 |
|---|---|---|
| `autoUpdates` | boolean | 启用/禁用自动更新(旧版) |
| `autoUpdatesProtectedForNative` | boolean | 原生安装始终自动更新 |
### 配置迁移
**文件**: `src/migrations/migrateAutoUpdatesToSettings.ts`
一次性将旧版 `globalConfig.autoUpdates = false` 迁移为 settings 中的 `DISABLE_AUTOUPDATER=1` 环境变量。从 `src/main.tsx:325` 在启动时调用。
---
## 更新通知去重
**文件**: `src/hooks/useUpdateNotification.ts`
React hook `useUpdateNotification(updatedVersion)` — 确保每次 semver 变更major.minor.patch只显示一次"重启以更新"消息,避免同一版本的重复通知。
---
## 更新日志
**文件**: `src/utils/releaseNotes.ts`
1.`src/setup.ts:387` 在每次启动时调用
2. 从 GitHub 获取 changelog
3. 缓存到 `~/.claude/cache/changelog.md`
4. 展示比 `lastReleaseNotesSeen` 更新的版本的更新日志
5. 使用 semver 比较确定需要展示哪些日志
---
## 版本比较
**文件**: `src/utils/semver.ts`
- 提供 `gt()``gte()``lt()``lte()``satisfies()``order()`
- 在 Bun 环境下使用 `Bun.semver.order()`(快 20 倍)
- 在 Node.js 环境下回退到 npm `semver`
---
## 分析事件
所有更新相关的遥测数据使用 `tengu_` 前缀的事件:
| 类别 | 事件 |
|---|---|
| 版本检查 | `tengu_version_check_success``tengu_version_check_failure` |
| JS 自动更新器 | `tengu_auto_updater_start/success/fail/up_to_date/lock_contention` |
| 原生自动更新器 | `tengu_native_auto_updater_start/success/fail` |
| 原生更新 | `tengu_native_update_complete/skipped_max_version/skipped_minimum_version` |
| 锁机制 | `tengu_version_lock_acquired/failed``tengu_native_update_lock_failed` |
| 二进制下载 | `tengu_binary_download_attempt/success/failure``tengu_binary_manifest_fetch_failure` |
| 清理 | `tengu_native_version_cleanup``tengu_native_staging_cleanup``tengu_native_stale_locks_cleanup` |
| 安装 | `tengu_native_install_package_success/failure``tengu_native_install_binary_success/failure` |
| 手动更新 | `tengu_update_check` |
| 迁移 | `tengu_migrate_autoupdates_to_settings``tengu_migrate_autoupdates_error` |
---
## 关键文件索引
| 文件 | 职责 |
|---|---|
| `src/utils/autoUpdater.ts` | 核心逻辑版本检查、npm 安装、文件锁、最低/最高版本门控 |
| `src/cli/update.ts` | `claude update` 命令处理 |
| `src/utils/nativeInstaller/installer.ts` | 原生二进制安装器:下载、版本管理、符号链接、清理 |
| `src/utils/nativeInstaller/download.ts` | 从 GCS/Artifactory 下载二进制文件并校验 |
| `src/utils/localInstaller.ts` | 本地安装器(`~/.claude/local/`)基于 npm |
| `src/components/AutoUpdaterWrapper.tsx` | 基于安装类型的策略路由 |
| `src/components/AutoUpdater.tsx` | JS/npm 后台自动更新器30 分钟间隔) |
| `src/components/NativeAutoUpdater.tsx` | 原生二进制后台自动更新器30 分钟间隔) |
| `src/components/PackageManagerAutoUpdater.tsx` | 包管理器通知30 分钟,仅展示) |
| `src/hooks/useUpdateNotification.ts` | 按 semver 去重更新通知 |
| `src/utils/releaseNotes.ts` | Changelog 获取、缓存与展示 |
| `src/utils/semver.ts` | Semver 版本比较Bun 原生 + npm 回退) |
| `src/utils/doctorDiagnostic.ts` | 安装类型检测与健康诊断 |
| `src/utils/config.ts:1735` | `getAutoUpdaterDisabledReason()` — 禁用检查逻辑 |
| `src/migrations/migrateAutoUpdatesToSettings.ts` | 旧版配置迁移 |
| `src/screens/Doctor.tsx` | Doctor 命令 UI展示自动更新状态 |
---
## 流程图
```
启动阶段
├── assertMinVersion() → 版本过低时硬性拦截,拒绝启动
├── migrateAutoUpdatesToSettings() → 一次性配置迁移
└── checkForReleaseNotes() → 展示新版本的更新日志
REPL 运行中(每 30 分钟)
├── AutoUpdaterWrapper 检测安装类型
├── native → NativeAutoUpdater
│ ├── 从 GCS/Artifactory 获取版本
│ ├── 检查最大版本上限(服务端控制)
│ ├── 检查 minimumVersion 设置(跳过)
│ ├── acquireLock()
│ ├── downloadAndVerifyBinary()SHA256 校验3 次重试)
│ ├── 安装到 versions/ 目录
│ ├── 更新符号链接
│ └── cleanupOldVersions()(保留 2 个版本)
├── npm-global/local → AutoUpdater
│ ├── 从 npm registry 获取最新版本
│ ├── semver 版本比较
│ ├── acquireLock()
│ └── npm install -g / 本地安装
└── package-manager → PackageManagerAutoUpdater
├── 从 GCS 获取版本
└── 显示 "Run: brew upgrade ..."(不自动安装)
手动操作
└── claude update → 完整诊断 + 安装编排
```

View File

@@ -48,15 +48,16 @@ const messagesForCompact = microcompactResult.messages
MicroCompact 不压缩整个对话,而是**清除旧工具输出的内容**。它维护一个白名单:
```typescript
// src/services/compact/microCompact.ts:41-48
const COMPACTABLE_TOOLS = new Set([
'Read', // 文件读取
'Bash', // 命令输出
'Grep', // 搜索结果
'Glob', // 文件列表
'WebSearch', // 搜索结果
'WebFetch', // 网页内容
'Edit', // 编辑输出
'Write', // 写入输出
FILE_READ_TOOL_NAME, // 'Read' - 文件读取
...SHELL_TOOL_NAMES, // 'Bash' - 命令输出
GREP_TOOL_NAME, // 'Grep' - 搜索结果
GLOB_TOOL_NAME, // 'Glob' - 文件列表
WEB_SEARCH_TOOL_NAME, // 'WebSearch' - 搜索结果
WEB_FETCH_TOOL_NAME, // 'WebFetch' - 网页内容
FILE_EDIT_TOOL_NAME, // 'Edit' - 编辑输出
FILE_WRITE_TOOL_NAME, // 'Write' - 写入输出
])
```
@@ -201,6 +202,31 @@ boundaryMarker.compactMetadata.preservedSegment = {
这在会话恢复时帮助加载器正确重建消息链,避免重复压缩已保留的消息。
### Microcompact Boundary
Microcompact 操作使用单独的 boundary 类型,与全量压缩的 `compact_boundary` 不同:
```typescript
// src/utils/messages.ts:4599-4614
type SystemMicrocompactBoundaryMessage = {
type: 'system'
subtype: 'microcompact_boundary'
content: 'Context microcompacted'
compactMetadata: {
trigger: 'auto' // Microcompact 只有自动触发
preTokens: number // 压缩前 token 数
tokensSaved: number // 节省的 token 数
compactedToolIds: string[] // 被压缩的工具 ID 列表
clearedAttachmentUUIDs: string[] // 被清除的附件 UUID
}
}
```
与 `compact_boundary` 的区别:
- **保留原始消息**Microcompact 仅清除工具输出内容,不删除消息本身
- **可追溯性**`compactedToolIds` 记录了哪些工具结果被清除
- **轻量级**:不生成摘要,不调用 API
## PTL 紧急降级Prompt Too Long
当压缩后仍然超出 token 限制(`PROMPT_TOO_LONG` 错误),系统会进入紧急降级路径:

View File

@@ -43,9 +43,11 @@ export function asSystemPrompt(value: readonly string[]): SystemPrompt {
| 阶段 | 内容 | 缓存策略 |
|------|------|----------|
| **静态区** | Intro Section、System Rules、Doing Tasks、Actions、Using Tools、Tone & Style、Output Efficiency | 可跨组织缓存(`scope: 'global'` |
| **BOUNDARY** | `SYSTEM_PROMPT_DYNAMIC_BOUNDARY = '__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__'` | 分界标记(不发送给 API |
| **BOUNDARY** | `SYSTEM_PROMPT_DYNAMIC_BOUNDARY = '__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__'` | 分界标记(不发送给 API,仅用于分割静态区与动态区以实现全局缓存 |
| **动态区** | Session Guidance、Memory、Model Override、Env Info、Language、Output Style、MCP Instructions、Scratchpad、FRC、Summarize Tool Results、Token Budget、Brief | 每次会话不同(`scope: 'org'` 或无缓存) |
> **Boundary 是什么**:它把 System Prompt 分成"不变的静态区"和"因用户/会话而异的动态区"。静态区对所有用户相同,可获得 `scope: 'global'` 跨组织缓存;动态区每次不同,只能 `scope: 'org'` 或不缓存。它本身是一个特殊字符串,在发送给 API 前被移除AI 永远看不到。
### 动态区的 Section 注册表
动态区通过 `systemPromptSection()` / `DANGEROUS_uncachedSystemPromptSection()` 注册,这两个工厂函数定义于 `src/constants/systemPromptSections.ts`
@@ -88,6 +90,36 @@ DANGEROUS_uncachedSystemPromptSection(
`appendSystemPrompt` 始终追加到末尾Override 除外)。
## Provider 系统概述
Claude Code 支持多种 API 提供商,分为两大类:
| 类别 | Provider | 环境变量 | 说明 |
|------|----------|---------|------|
| **1P (First Party)** | `firstParty` | 默认 | Anthropic 官方 API 直连 |
| **3P (Third Party)** | `bedrock` | `CLAUDE_CODE_USE_BEDROCK=1` | AWS Bedrock 托管服务 |
| **3P** | `vertex` | `CLAUDE_CODE_USE_VERTEX=1` | Google Vertex AI |
| **3P** | `openai` | `CLAUDE_CODE_USE_OPENAI=1` | OpenAI 兼容层Ollama/DeepSeek/vLLM |
| **3P** | `gemini` | `CLAUDE_CODE_USE_GEMINI=1` | Google Gemini API |
| **3P** | `grok` | `CLAUDE_CODE_USE_GROK=1` | xAI Grok |
Provider 决定了:
- **可用的 beta headers**:部分 beta 功能仅限 1P 用户
- **缓存策略**:全局缓存 `scope: 'global'` 仅 1P 可用
- **Token 计数方式**Bedrock 有独立的 countTokens 端点OpenAI/Gemini 依赖估算
```typescript
// src/utils/model/providers.ts:5-13
export type APIProvider =
| 'firstParty' // 1P - Anthropic 直连
| 'bedrock' // 3P - AWS Bedrock
| 'vertex' // 3P - Google Vertex
| 'foundry' // 3P - Anthropic Foundry
| 'openai' // 3P - OpenAI 兼容层
| 'gemini' // 3P - Google Gemini
| 'grok' // 3P - xAI Grok
```
## 缓存策略:分块、标记、命中
这是 System Prompt 设计中最精密的部分。
@@ -121,6 +153,28 @@ MCP 工具列表在会话中可能变化(连接/断开),破坏了跨组织
这是缓存效率最高的模式。`SYSTEM_PROMPT_DYNAMIC_BOUNDARY` 之前的静态内容Intro、Rules、Tone & Style 等)对所有用户相同,可跨组织缓存。
> **Boundary 插入条件**`SYSTEM_PROMPT_DYNAMIC_BOUNDARY` 标记**仅在特定条件**下插入:
```typescript
// src/utils/betas.ts:226-229
export function shouldUseGlobalCacheScope(): boolean {
return (
getAPIProvider() === 'firstParty' &&
!isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS)
)
}
```
```typescript
// src/constants/prompts.ts:574
...(shouldUseGlobalCacheScope() ? [SYSTEM_PROMPT_DYNAMIC_BOUNDARY] : []),
```
这意味着:
- **3P 用户Bedrock/Vertex/OpenAI/Gemini**Boundary 永远不存在,始终使用模式 3
- **1P 用户禁用实验性功能**:设置 `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`Boundary 不插入
- **1P 用户默认**Boundary 存在,使用模式 2最高缓存效率
#### 模式 3默认3P 提供商 或 Boundary 缺失)
```
@@ -250,3 +304,65 @@ Header 始终 `cacheScope: null`——它因版本和指纹不同而变化,不
4. `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` 标记允许 `splitSysPromptPrefix()` 精确地将静态区标记为 `scope: 'global'`,动态区不标记或标记为 `scope: 'org'`
这是 Claude Code 在 token 成本优化上的核心设计——一次典型的 System Prompt 约 20K+ tokens通过缓存分块可以节省 30-50% 的输入 token 费用。
## 兼容层OpenAI 与 Gemini
Claude Code 提供了 OpenAI 和 Gemini 协议的兼容层,允许使用非 Anthropic 端点。
### OpenAI 兼容层
通过 `CLAUDE_CODE_USE_OPENAI=1` 启用,支持任意 OpenAI Chat Completions 协议端点Ollama、DeepSeek、vLLM 等)。
实现采用**流适配器模式**
1. 将 Anthropic 格式请求转换为 OpenAI 格式
2. 调用 OpenAI 兼容端点
3. 将 SSE 流转换回 `BetaRawMessageStreamEvent`
4. 下游代码完全无感知
```
src/services/api/openai/
├── client.ts # OpenAI 客户端配置
├── convertMessages.ts # 消息格式转换Anthropic → OpenAI
├── convertTools.ts # 工具定义转换
├── streamAdapter.ts # SSE 流适配OpenAI → Anthropic
├── modelMapping.ts # 模型名称映射
└── index.ts # 入口函数 queryModelOpenAI()
```
关键环境变量:
- `CLAUDE_CODE_USE_OPENAI=1` — 启用 OpenAI provider
- `OPENAI_API_KEY` — API 密钥
- `OPENAI_BASE_URL` — API 端点(默认 `https://api.openai.com/v1`
- `OPENAI_MODEL` — 直接指定模型名
### Gemini 兼容层
通过 `CLAUDE_CODE_USE_GEMINI=1` 启用,支持 Google Gemini API。
```
src/services/api/gemini/
├── client.ts # Gemini 客户端配置
├── convertMessages.ts # 消息格式转换
├── convertTools.ts # 工具定义转换
├── streamAdapter.ts # 流适配
├── modelMapping.ts # 模型名称映射
├── types.ts # 类型定义
└── index.ts # 入口函数
```
关键环境变量:
- `CLAUDE_CODE_USE_GEMINI=1` — 启用 Gemini provider
- `GEMINI_API_KEY` — API 密钥
- `GEMINI_BASE_URL` — API 端点(默认 `https://generativelanguage.googleapis.com/v1beta`
- `GEMINI_MODEL` — 直接指定模型名
- `GEMINI_DEFAULT_SONNET_MODEL` / `GEMINI_DEFAULT_OPUS_MODEL` — 按能力级别映射
### 兼容层的限制
使用 3P 兼容层时,部分功能受限:
- **无精确 token 计数**:系统退回到近似估算,影响自动压缩触发时机
- **无全局缓存**:只能使用组织级缓存 `scope: 'org'`
- **部分 beta 功能不可用**:依赖 Anthropic 特有 beta headers 的功能受限
详见 `docs/plans/openai-compatibility.md` 和 `CLAUDE.md` 中的相关章节。

View File

@@ -64,6 +64,33 @@ function roughTokenCountEstimation(content: string, bytesPerToken = 4): number {
精确计数在关键决策点使用压缩前后对比、warning 判断),近似估算在热路径使用(每轮循环的 shouldAutoCompact 检查)。
### 3P Provider 的 Token 计数差异
不同 Provider 的精确 token 计数实现方式不同,部分 provider 甚至不支持精确计数:
| Provider | 计数方式 | 注意事项 |
|----------|---------|---------|
| **Anthropic 直连** | `anthropic.beta.messages.countTokens()` | 标准 API最准确 |
| **AWS Bedrock** | `CountTokensCommand` | 需要动态加载 279KB AWS SDK |
| **Google Vertex** | Anthropic SDK + beta 过滤 | 需要特定 beta headers |
| **OpenAI 兼容层** | 无精确计数 | **退回到近似估算** |
| **Gemini 兼容层** | 无精确计数 | **退回到近似估算** |
| **Bedrock 不支持时** | 用 Haiku 发送 `max_tokens=1` 请求 | 读取 `usage.input_tokens` |
OpenAI 和 Gemini 兼容层**不支持精确 token 计数**,系统会退回到近似估算。这会影响:
- **自动压缩触发时机**:可能略有偏差
- **压缩前后 token 对比**:仅为估算值,非精确
- **Warning/Error 阈值判断**:基于估算而非精确计数
```typescript
// src/services/tokenEstimation.ts - 近似估算函数
function roughTokenCountEstimation(content: string, bytesPerToken = 4): number {
return Math.round(content.length / bytesPerToken)
}
```
源码路径:`src/services/tokenEstimation.ts`
## 自动压缩的触发阈值
```

View File

@@ -2,6 +2,7 @@
title: "多轮对话管理 - QueryEngine 会话编排与持久化"
description: "从源码角度解析 Claude Code 多轮对话管理QueryEngine 的会话状态机、JSONL transcript 持久化、成本追踪模型和模型热切换机制。"
keywords: ["多轮对话", "会话管理", "QueryEngine", "transcript", "成本追踪"]
sourceRef: "3ec5675 (2026-04-08)"
---
{/* 本章目标:从源码角度揭示会话编排、持久化存储、成本追踪和模型切换的完整链路 */}
@@ -11,15 +12,17 @@ keywords: ["多轮对话", "会话管理", "QueryEngine", "transcript", "成本
- **单轮**(一次 Agentic Loop`query()` 函数的一次完整执行——组装上下文 → 调 API → 处理工具调用 → 循环直到结束
- **多轮**(一个 Session`QueryEngine` 类管理的一次会话——跨越数十轮 `submitMessage()` 调用,持续数小时
`QueryEngine``src/QueryEngine.ts:186`)是单轮 Agentic Loop 之上的**会话编排器**,它管理的状态远不止消息列表:
`QueryEngine``src/QueryEngine.ts`,类定义)是单轮 Agentic Loop 之上的**会话编排器**,它管理的状态远不止消息列表:
```
QueryEngine 内部状态
QueryEngine 内部状态src/QueryEngine.ts 构造函数)
├── mutableMessages: Message[] ← 完整对话历史,跨 turn 累积
├── readFileState: FileStateCache ← 已读文件内容缓存,避免重复读取
├── totalUsage: NonNullableUsage ← 累计 token 消耗input/output/cache
├── permissionDenials: SDKPermissionDenial[] ← 权限拒绝记录
├── discoveredSkillNames: Set<string> ← 当前 turn 已发现的 skill
├── loadedNestedMemoryPaths: Set<string> ← 已加载的嵌套 memory 路径(防重复)
├── hasHandledOrphanedPermission: boolean ← 是否已处理孤立权限请求
└── abortController: AbortController ← 会话级中断控制
```
@@ -28,29 +31,37 @@ QueryEngine 内部状态
每次用户输入一条消息REPL 或 SDK 调用 `submitMessage()`,它会执行完整的 turn 初始化链路:
```typescript
// src/QueryEngine.ts:211 — 简化的 submitMessage 流程
async *submitMessage(prompt, options?): AsyncGenerator<SDKMessage> {
// src/QueryEngine.ts — QueryEngine.submitMessage() 简化流程
async *submitMessage(
prompt: string | ContentBlockParam[],
options?: { uuid?: string; isMeta?: boolean },
): AsyncGenerator<SDKMessage> {
// 1. 清除 turn 级追踪状态
this.discoveredSkillNames.clear()
// 2. 解析模型(用户可能中途切换了模型)
const mainLoopModel = userSpecifiedModel
? parseUserSpecifiedModel(userSpecifiedModel)
// 2. 解析模型(用户可能中途通过 setModel() 切换了模型)
const mainLoopModel = this.config.userSpecifiedModel
? parseUserSpecifiedModel(this.config.userSpecifiedModel)
: getMainLoopModel()
// 3. 动态组装 System Prompt每次 turn 都重新构建)
const { defaultSystemPrompt, userContext, systemContext } =
await fetchSystemPromptParts({ tools, mainLoopModel, mcpClients })
// 4. 包装权限检查(追踪每次拒绝)
const wrappedCanUseTool = async (tool, input, ...) => {
const result = await canUseTool(tool, input, ...)
if (result.behavior !== 'allow') {
this.permissionDenials.push({ tool_name: tool.name, ... })
this.permissionDenials.push({
type: 'permission_denial',
tool_name: sdkCompatToolName(tool.name),
tool_use_id: toolUseID,
tool_input: input,
})
}
return result
}
// 5. 调用核心 query() 函数执行 agentic loop
yield* query({
systemPrompt, messages: this.mutableMessages,
@@ -68,36 +79,43 @@ async *submitMessage(prompt, options?): AsyncGenerator<SDKMessage> {
### 存储路径
```
~/.claude/projects/<project-hash>/<session-id>.jsonl
~/.claude/projects/<sanitized-cwd>/<session-uuid>.jsonl
```
- `project-hash` 由 `getProjectDir(originalCwd)` 生成,同一项目目录的会话归入同一子目录
- 路径由 `getProjectDir(originalCwd)` 生成,使用 `sanitizePath()` 将项目目录路径转换为安全的目录名(非 hash同一项目目录的会话归入同一子目录
- 每条记录是一行 JSONJSONL 格式),支持追加写入而不需要读取-修改-写入整个文件
- 读取上限为 50MB`MAX_TRANSCRIPT_READ_BYTES`),防止超大会话导致 OOM
- 读取上限为 50MB`MAX_TRANSCRIPT_READ_BYTES` 常量,`src/utils/sessionStorage.ts`),防止超大会话导致 OOM
### Transcript 写入器
`TranscriptWriter``src/utils/sessionStorage.ts:1200+`)是一个写队列,确保并发消息追加不会互相覆盖:
`Project` 类`src/utils/sessionStorage.ts`,私有类)管理 transcript 的写入。它通过 `writeQueues`(按文件分组的写队列)和 `drainWriteQueue()`(定时批量刷写)确保并发消息追加不会互相覆盖:
```
写入流程:
appendEntryToFile(sessionId, entry)
写入流程(异步排队路径)
recordTranscript(sessionId, entry)
ensureCurrentSessionFile() ← 懒初始化:首次写入时才创建文件
project.enqueueWrite(filePath, entry) 入列到 writeQueues
序列化为 JSON + 换行符
scheduleDrain() ← 设置定时器FLUSH_INTERVAL_MS
appendFile(path, line) ← 原子追加
drainWriteQueue() ← 按 MAX_CHUNK_BYTES 分批
↓ 写入每批
appendToFile(path, batchContent) ← 批量追加
如果配置了远程持久化:
persistToRemote(sessionId, entry)
├── CCR v2: internalEventWriter('transcript', entry)
└── v1 Ingress: sessionIngress.appendSessionLog(...)
同步直写路径(用于元数据重写等场景):
appendEntryToFile(fullPath, entry) ← 同步 appendFileSync
失败时 mkdir + 重试
```
### 会话恢复链路
`--resume` 参数触发的恢复流程(`src/main.tsx:3620+`
`--resume` 参数触发的恢复流程(`src/main.tsx` 中 `--resume` 分支
```
1. 解析 resume 参数:
@@ -130,7 +148,7 @@ async *submitMessage(prompt, options?): AsyncGenerator<SDKMessage> {
### 累计层cost-tracker.ts
```typescript
// src/cost-tracker.ts — StoredCostState 数据模型
// src/cost-tracker.ts — StoredCostState 类型定义
type StoredCostState = {
totalCostUSD: number // 累计美元花费
totalAPIDuration: number // API 调用总时长(含重试)
@@ -138,7 +156,8 @@ type StoredCostState = {
totalToolDuration: number // 工具执行总时长
totalLinesAdded: number // 代码增加行数
totalLinesRemoved: number // 代码删除行数
modelUsage: { [modelName: string]: ModelUsage } // 按模型分拆的用量
lastDuration: number | undefined // 最近一次会话时长
modelUsage: { [modelName: string]: ModelUsage } | undefined // 按模型分拆的用量
}
```
@@ -156,18 +175,18 @@ saveCurrentSessionCosts(sessionId)
### 预算熔断
`QueryEngineConfig.maxBudgetUsd` 提供了会话级的硬性预算上限。在 REPL 中,当累计费用超过 $5 时(`src/screens/REPL.tsx:2208`),弹出费用提醒对话框——这不是硬性阻断,而是"软提醒"。
`QueryEngineConfig.maxBudgetUsd` 提供了会话级的硬性预算上限。在 REPL 中,当累计费用超过 $5 时(`src/screens/REPL.tsx` 中费用阈值 `useEffect`),弹出费用提醒对话框——这不是硬性阻断,而是"软提醒",且仅在 `hasConsoleBillingAccess()` 为 true 时显示
## 模型热切换
在一个会话中切换模型不会丢失对话历史——因为 `mutableMessages` 与模型选择是解耦的:
```
/model sonnet → setMainLoopModelOverride('claude-sonnet-4-20250514')
/model sonnet → QueryEngine.setModel('claude-sonnet-4-20250514')
实际操作this.config.userSpecifiedModel = modelQueryEngine.setModel() 方法)
下一次 submitMessage() 开始时:
parseUserSpecifiedModel(userSpecifiedModel)
parseUserSpecifiedModel(this.config.userSpecifiedModel)
→ 返回新的模型配置
fetchSystemPromptParts({ mainLoopModel: newModel })

View File

@@ -2,6 +2,7 @@
title: "流式响应机制 - Claude Code 打字机效果原理"
description: "解析 Claude Code 流式响应实现:如何通过 SSE 逐 token 接收 AI 输出,实现实时打字机效果,提升用户等待体验。"
keywords: ["流式响应", "SSE", "streaming", "实时输出", "API streaming"]
sourceRef: "3ec5675 (2026-04-08)"
---
## 为什么需要流式
@@ -31,7 +32,7 @@ message_stop ← 消息结束
### 事件处理状态机
`src/services/api/claude.ts:1980-2298` 实现了一个基于 `switch(part.type)` 的状态机:
`src/services/api/claude.ts` 中 `queryStreamRaw()` 函数的事件处理循环实现了一个基于 `switch(part.type)` 的状态机:
| 事件类型 | 处理逻辑 | 状态变更 |
|----------|----------|----------|
@@ -76,7 +77,7 @@ content_block_stop (index=2)
`stop_reason` 要等到 `message_delta` 才确定(可能是 `end_turn`、`tool_use`、`max_tokens` 等),所以最后一条消息的 `stop_reason` 是**回写**的:
```typescript
// claude.ts:2246 — 直接属性修改,不用对象替换
// claude.ts — stop_reason 回写逻辑(直接属性修改,不用对象替换
// 因为 transcript 写队列持有 message.message 的引用
const lastMsg = newMessages.at(-1)
if (lastMsg) {
@@ -89,16 +90,21 @@ if (lastMsg) {
### 网络断开
流式连接依赖 SSEServer-Sent Events。当连接中断时
流式连接依赖 SSEServer-Sent Events。当连接中断时,系统有两层检测机制
1. **Stream idle watchdog**:定时检测事件间隔超过阈值(stall触发告警和重试
2. **Stream abort**:如果 watchdog 检测到长时间无事件,抛出错误进入重试流程
3. **非流式降级**:作为最后手段,回退到非流式请求(一次性获取完整响应)
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:2338-2355 — 检测空流
// 1. 完全没有事件 → 代理返回了非 SSE 响应
// 2. 有 message_start 但没有 content_block_stop → 流被截断
// 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 限流
@@ -118,7 +124,7 @@ if (lastMsg) {
| **上下文窗口超限** | `model_context_window_exceeded` | 触发 compaction 压缩对话历史后重试 |
```typescript
// claude.ts:2267-2293
// claude.ts — stop_reason 处理
if (stopReason === 'max_tokens') {
yield createAssistantAPIErrorMessage({ error: 'max_output_tokens', ... })
}
@@ -133,8 +139,8 @@ if (stopReason === 'model_context_window_exceeded') {
系统持续监控事件到达间隔,检测"停滞"stall
```typescript
// claude.ts:1940-1966
const STALL_THRESHOLD_MS = 10_000 // 10 秒无事件视为停滞
// claude.ts — stall 检测逻辑
const STALL_THRESHOLD_MS = 30_000 // 30 秒无事件视为停滞
if (timeSinceLastEvent > STALL_THRESHOLD_MS) {
stallCount++
totalStallTime += timeSinceLastEvent
@@ -142,7 +148,7 @@ if (timeSinceLastEvent > STALL_THRESHOLD_MS) {
}
```
多个 stall 累积后watchdog 可能决定中断流并触发重试
这是**被动检测**——仅在下一个 chunk 到达时才触发比较。与之互补的是 90 秒主动空闲超时看门狗(`STREAM_IDLE_TIMEOUT_MS`),会直接中断长时间无响应的流
## 工具执行的流式反馈

View File

@@ -2,6 +2,7 @@
title: "Agentic LoopAI 自主循环的核心机制"
description: "深入解析 Claude Code 的 query() 异步生成器循环——从流式 API 调用、工具并行执行、上下文压缩、错误恢复到终止条件的完整状态机,基于 src/query.ts 的源码级分析。"
keywords: ["Agentic Loop", "query loop", "tool_use", "状态机", "auto-compact", "streaming", "recovery"]
sourceRef: "3ec5675 (2026-04-08)"
---
{/* 本章目标:基于 src/query.ts 揭示 Agentic Loop 的完整状态机 */}
@@ -11,7 +12,7 @@ keywords: ["Agentic Loop", "query loop", "tool_use", "状态机", "auto-compact"
传统聊天机器人:你问一句,它答一句。
Claude Code 不一样:你说一个需求,它可能连续执行十几步操作才给你最终结果。
这背后的机制叫做 **Agentic Loop**(智能体循环),核心实现在 `src/query.ts` 的 `queryLoop()` 异步生成器函数(第 241 行)。它是一个 `while(true)` 无限循环,每次迭代代表一次"思考→行动→观察"周期。
这背后的机制叫做 **Agentic Loop**(智能体循环),核心实现在 `src/query.ts` 的 `queryLoop()` 异步生成器函数。它是一个 `while(true)` 无限循环,每次迭代代表一次"思考→行动→观察"周期。
<Frame caption="Agentic Loop 循环示意">
<img src="/docs/images/agentic-loop.png" alt="Agentic Loop 循环图" />
@@ -19,7 +20,7 @@ Claude Code 不一样:你说一个需求,它可能连续执行十几步操
## 循环的完整结构
`queryLoop()` 的每次迭代(`src/query.ts:307` `while(true)`)包含以下阶段:
`queryLoop()` 的每次迭代(`src/query.ts` 中 `while(true)` 主循环)包含以下阶段:
### 阶段 1上下文预处理Pre-Processing Pipeline
@@ -39,7 +40,7 @@ messagesForQuery处理后的消息→ 发往 API
### 阶段 2流式 API 调用Streaming Loop
`deps.callModel()` 发起流式请求(第 659 行),返回一个 AsyncGenerator。在流式过程中
`deps.callModel()` 发起流式请求(`src/query.ts` 中 `attemptWithFallback` 循环内),返回一个 AsyncGenerator。在流式过程中
- **AssistantMessage** 被收集到 `assistantMessages[]` 数组
- **tool_use 块** 被提取到 `toolUseBlocks[]`,设置 `needsFollowUp = true`
@@ -47,8 +48,8 @@ messagesForQuery处理后的消息→ 发往 API
- 可恢复的错误prompt-too-long、max-output-tokens被**暂扣**withheld先尝试恢复
流式回调中的关键守卫:
- `backfillObservableInput()`(第 763 行)—— 为 tool_use 块回填可观察字段(如文件路径展开),但只在添加了新字段时才克隆消息,避免破坏 prompt cache 的字节一致性
- 流式降级检测——如果 `streamingFallbackOccured`,已收集的消息被标记为 tombstone(第 717 行),清空后重试
- `backfillObservableInput()` —— 为 tool_use 块回填可观察字段(如文件路径展开),但只在添加了新字段时才克隆消息,避免破坏 prompt cache 的字节一致性
- 流式降级检测——如果 `streamingFallbackOccured`,已收集的消息被标记为 tombstone清空后重试
### 阶段 3工具执行Tool Execution
@@ -67,42 +68,50 @@ const toolUpdates = streamingToolExecutor
每次迭代结束时,根据条件决定 `return`(终止)或 `continue`(继续):
## 7 种终止条件(源码级)
## 终止条件(源码级)
循环有多种终止路径,按触发时机排列:
| 终止原因 | 触发位置 | 机制 |
|----------|---------|------|
| **completed** | 第 1360 行 | AI 未发出 tool_use → `needsFollowUp = false` → 经过 stop hooks → 返回 |
| **blocking_limit** | 第 646 行 | Token 计数超过硬限制(非 autocompact 模式)→ 生成 PTL 错误消息 → 返回 |
| **aborted_streaming** | 第 1054 行 | `abortController.signal.aborted` → 为未完成的 tool_use 生成合成 tool_result → 返回 |
| **model_error** | 第 999 行 | `callModel()` 抛出异常 → 生成错误消息 → 返回 |
| **prompt_too_long** | 第 1178 行 | 413 错误且 reactive compact 无法恢复 → 暂扣的错误消息被释放 → 返回 |
| **image_error** | 第 980/1178 行 | 图片尺寸/大小错误 → 直接返回 |
| **image_error** | 第 980 行 | `ImageSizeError` / `ImageResizeError` 异常直接返回 |
| **model_error** | 第 999 行 | `callModel()` 抛出不可恢复异常 → 生成错误消息 → 返回 |
| **aborted_streaming** | 第 1054 行 | `abortController.signal.aborted`(流式阶段)→ 为未完成的 tool_use 生成合成 tool_result → 返回 |
| **prompt_too_long** | 第 1178/1185 行 | 413 错误且 reactive compact 无法恢复 → 暂扣的错误消息被释放 → 返回 |
| **completed** | 第 1267 行 | API 错误(限流、认证失败等)导致无法继续 → 返回 |
| **stop_hook_prevented** | 第 1282 行 | Stop hook 返回 `preventContinuation: true` → 返回 |
| **completed** | 第 1360 行 | 正常完成AI 未发出 tool_use → `needsFollowUp = false` → 经过 stop hooks → 返回 |
| **aborted_tools** | 第 1518 行 | `abortController.signal.aborted`(工具执行阶段)→ 返回 |
| **hook_stopped** | 第 1523 行 | 工具执行期间 hook 返回 `shouldPreventContinuation` → 返回 |
| **max_turns** | 第 1714 行 | 轮次计数超过 `maxTurns` 限制 → 返回 |
## 4 种继续条件(恢复路径)
## 继续条件(恢复路径)
循环不仅是一个简单的"有 tool_use 就继续",它还包含多种恢复/重试路径:
### 1. 正常工具循环
`needsFollowUp = true` → 执行工具 → 新消息追加到 `messagesForQuery` → `continue`
### 1. 正常工具循环`next_turn`
`needsFollowUp = true` → 执行工具 → 新消息追加到 `messagesForQuery` → state 重新赋值 → `continue`
### 2. max_output_tokens 恢复(第 1191-1255 行
当 AI 输出被截断时(`apiError === 'max_output_tokens'`
- **首次**:尝试将 `maxOutputTokens` 从默认值提升到 `ESCALATED_MAX_TOKENS`64K,无 meta 消息,静默重试
- **后续**注入恢复消息"Output token limit hit. Resume directly...",最多重试 `MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3` 次
- 恢复耗尽后,暂扣的错误消息被释放
### 2. max_output_tokens 恢复(`max_output_tokens_escalate` / `max_output_tokens_recovery`
当 AI 输出被截断时(`apiError === 'max_output_tokens'`,分两阶段恢复
- **提升阶段**`max_output_tokens_escalate`):首次截断时,将 `maxOutputTokens` 从默认值提升到 `ESCALATED_MAX_TOKENS`64K。静默重试,不注入 meta 消息
- **恢复阶段**`max_output_tokens_recovery`):提升后仍然截断时,注入恢复消息"Output token limit hit. Resume directly...",最多重试 `MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3` 次。恢复耗尽后,暂扣的错误消息被释放。
### 3. Prompt-Too-Long 恢复(第 1088-1186 行
当遇到 413 错误时,有两个恢复阶段
- **Context Collapse Drain**第 1097 行):提交所有已暂存的折叠,释放空间后重试。如果上一轮已经是 collapse_drain_retry 则跳过
- **Reactive Compact**第 1123 行):触发即时压缩,生成摘要后重试。`hasAttemptedReactiveCompact` 防止无限循环
### 3. Prompt-Too-Long 恢复(`collapse_drain_retry` / `reactive_compact_retry`
当遇到 413 错误时,按优先级尝试两种压缩策略
- **Context Collapse Drain**`collapse_drain_retry`):提交所有已暂存的折叠collapse,释放空间后重试。如果上一轮已经是 `collapse_drain_retry` 则跳过,避免无限循环。
- **Reactive Compact**`reactive_compact_retry`):如果 collapse drain 无法恢复触发即时压缩reactive compact,生成摘要后重试。`hasAttemptedReactiveCompact` 标志防止无限循环
### 4. Stop Hook 阻塞重试(第 1285-1308 行
### 4. Stop Hook 阻塞重试(`stop_hook_blocking`
Stop hook 可以注入阻塞错误消息,强制 AI 重新思考。新的消息(包含阻塞错误)被追加到对话中,`stopHookActive = true`,进入下一轮迭代。
### 5. Token Budget 继续提示(`token_budget_continuation`
当 `TOKEN_BUDGET` feature 启用时,如果 token 消耗达到阈值但未超出预算,注入 nudge 消息让 AI 加速收尾,然后继续。
## 模型降级Fallback
当主模型不可用时(`FallbackTriggeredError`第 897 行
当主模型不可用时(`FallbackTriggeredError``src/query.ts` 中 `attemptWithFallback` 循环的 catch 分支
1. 已收集的 `assistantMessages` 被清空tool_use 块收到合成 tool_result"Model fallback triggered"
2. 思维签名块被移除(`stripSignatureBlocks`)—— 因为思维签名与模型绑定,跨模型回放会 400
@@ -112,13 +121,14 @@ Stop hook 可以注入阻塞错误消息,强制 AI 重新思考。新的消息
## 状态机State 对象
每次迭代的状态通过 `State` 类型(第 204 行)传递:
每次迭代的状态通过 `State` 类型(`src/query.ts`,类型定义)传递:
```typescript
// src/query.ts — State 类型定义
type State = {
messages: Message[] // 当前对话消息
toolUseContext: ToolUseContext // 工具上下文(含权限)
autoCompactTracking: AutoCompactTrackingState // 压缩跟踪
autoCompactTracking: AutoCompactTrackingState | undefined // 压缩跟踪
maxOutputTokensRecoveryCount: number // 输出截断恢复计数
hasAttemptedReactiveCompact: boolean // 是否已尝试即时压缩
maxOutputTokensOverride: number | undefined // 输出 token 上限覆盖
@@ -133,7 +143,7 @@ type State = {
## Token Budget实验性
当 `TOKEN_BUDGET` feature 启用时(第 1311 行),循环在终止前会检查 token 消耗:
当 `TOKEN_BUDGET` feature 启用时(`src/query.ts` 中 `!needsFollowUp` 分支内的预算检查逻辑),循环在终止前会检查 token 消耗:
- **continuation**:未达到预算但超过阈值 → 注入 nudge 消息,让 AI 加速收尾
- **diminishing_returns**:检测到收益递减 → 提前终止
@@ -157,26 +167,31 @@ type State = {
```
迭代 1: 思考→行动
预处理: 无需压缩(上下文很短)
预处理管道: applyToolResultBudget → snipCompact(HISTORY_SNIP feature) → microcompact → applyCollapses(CONTEXT_COLLAPSE feature) → autocompact
→ 上下文很短,无需压缩
API 调用: 返回 tool_use(Glob, "**/*.ts")
工具执行: 返回 42 个文件路径
→ needsFollowUp = true, continue
→ needsFollowUp = true
→ transition: { reason: 'next_turn' }, continue
迭代 2: 思考→行动
预处理: 42 个文件结果仍在预算内
预处理管道: 42 个文件结果仍在预算内
API 调用: 返回 tool_use(Grep, "import.*from")
工具执行: 在 15 个文件中找到 120 条 import
→ needsFollowUp = true, continue
→ needsFollowUp = true
→ transition: { reason: 'next_turn' }, continue
迭代 3: 思考→行动(多轮)
预处理: 120 条 Grep 结果触发 microcompact → 摘要化
预处理管道: 120 条 Grep 结果触发 microcompact → 摘要化
API 调用: 返回 3 个 tool_use(FileEdit, ...)
工具执行: 删除 5 条未使用导入
→ needsFollowUp = true, continue
→ needsFollowUp = true
→ transition: { reason: 'next_turn' }, continue
迭代 4: 总结
API 调用: 返回纯文本"已清理 3 个文件中的 5 条未使用导入"
→ needsFollowUp = false
→ Stop hooks 通过
→ Token Budget 检查通过(如果启用)
→ return { reason: 'completed' }
```

View File

@@ -0,0 +1,17 @@
flowchart TB
START((输入)) --> CTX["Context 管理"]
CTX --> LLM["LLM 流式输出"]
LLM --> TC{tool_use?}
TC --> |是| EXEC["执行工具"]
EXEC --> CTX
TC --> |否| DONE((完成))
classDef proc fill:#eef,stroke:#66c,color:#224
classDef decision fill:#fee,stroke:#c66,color:#422
classDef io fill:#eff,stroke:#6cc,color:#244
class CTX,LLM,EXEC proc
class TC decision
class START,DONE io

View File

@@ -0,0 +1,40 @@
flowchart TB
START((输入)) --> CTX["Context 管理"]
CTX --> PRE["Pre-sampling Hook"]
PRE --> LLM["LLM 流式输出"]
LLM --> TC{tool_use?}
TC --> |是| PERM{需权限?}
PERM --> |是| USER["👤 用户审批"]
USER --> |allow| TOOL_PRE
USER --> |deny| DENIED["拒绝"]
PERM --> |否| TOOL_PRE["Pre-tool Hook"]
TOOL_PRE --> EXEC["并发执行工具"]
EXEC --> TOOL_POST["Post-tool Hook"]
TOOL_POST --> CTX
DENIED --> CTX
TC --> |否| POST["Post-sampling Hook"]
POST --> STOP{"Stop Hook"}
STOP --> |不通过| CTX
STOP --> |通过| BUDGET{"Token Budget"}
BUDGET --> |继续| CTX
BUDGET --> |完成| DONE((完成))
subgraph SUB["子 Agent"]
FORK["AgentTool"] --> RECURSE["递归调用"]
end
EXEC -.-> FORK
classDef proc fill:#eef,stroke:#66c,color:#224
classDef decision fill:#fee,stroke:#c66,color:#422
classDef hook fill:#ffe,stroke:#cc6,color:#442
classDef io fill:#eff,stroke:#6cc,color:#244
classDef sub fill:#efe,stroke:#6a6,color:#242
class CTX,LLM,EXEC proc
class TC,PERM,STOP,BUDGET decision
class PRE,TOOL_PRE,TOOL_POST,POST hook
class START,DONE,USER,DENIED io
class FORK,RECURSE sub

View File

@@ -1,14 +1,14 @@
---
title: "Hooks 生命周期钩子 - 执行引擎与拦截协议"
description: "从源码角度解析 Claude Code Hooks 系统22 种 Hook 事件、6 种 Hook 类型、同步/异步执行协议、JSON 输出 schema、if 条件匹配、以及 Hook 如何注入上下文和拦截工具调用。"
description: "从源码角度解析 Claude Code Hooks 系统27 种 Hook 事件、6 种 Hook 类型、同步/异步执行协议、JSON 输出 schema、if 条件匹配、以及 Hook 如何注入上下文和拦截工具调用。"
keywords: ["Hooks", "生命周期钩子", "拦截器", "PreToolUse", "Hook 协议"]
---
{/* 本章目标:从源码角度揭示 Hook 的执行引擎、匹配机制、返回值协议和生命周期管理 */}
## 22 种 Hook 事件
## 27 种 Hook 事件
Claude Code 定义了 22 种 Hook 事件(`coreTypes.ts:25-53`),覆盖完整的 Agent 生命周期:
Claude Code 定义了 27 种 Hook 事件(`HOOK_EVENTS` 数组,`src/entrypoints/sdk/coreTypes.ts`),覆盖完整的 Agent 生命周期:
| 阶段 | 事件 | 触发时机 | 匹配字段 |
|------|------|---------|---------|
@@ -32,6 +32,7 @@ Claude Code 定义了 22 种 Hook 事件(`coreTypes.ts:25-53`),覆盖完
| | `TaskCompleted` | 任务完成 | — |
| **MCP** | `Elicitation` | MCP 服务器请求用户输入 | `mcp_server_name` |
| | `ElicitationResult` | Elicitation 结果返回 | `mcp_server_name` |
| **通知** | `Notification` | 系统通知事件 | `notification_type` |
| **环境** | `ConfigChange` | 配置变更 | `source` |
| | `CwdChanged` | 工作目录变更 | — |
| | `FileChanged` | 文件变更 | `file_path` |
@@ -40,7 +41,11 @@ Claude Code 定义了 22 种 Hook 事件(`coreTypes.ts:25-53`),覆盖完
## 6 种 Hook 类型
Hooks 配置支持 6 种执行方式`src/types/hooks.ts`
Hooks 配置支持 6 种执行方式,类型定义分布在 3 个文件中
- **可持久化类型**`command`、`prompt`、`agent`、`http`)— Zod schema 定义在 `src/schemas/hooks.ts`,通过 `z.discriminatedUnion('type', [...])` 声明
- **callback 类型** — TypeScript 接口定义在 `src/types/hooks.ts`,用于 SDK 注册的内部 JS 函数
- **function 类型** — 定义在 `src/utils/hooks/sessionHooks.ts`,用于运行时动态注册的函数 Hook
| 类型 | 执行方式 | 适用场景 |
|------|---------|---------|
@@ -53,7 +58,7 @@ Hooks 配置支持 6 种执行方式(`src/types/hooks.ts`
## 执行引擎execCommandHook
`execCommandHook()``src/utils/hooks.ts:829-1417`)是命令型 Hook 的执行核心:
`execCommandHook()``src/utils/hooks.ts``execCommandHook` 函数)是命令型 Hook 的执行核心:
```
execCommandHook(hook, hookEvent, hookName, jsonInput, signal)
@@ -75,7 +80,7 @@ execCommandHook(hook, hookEvent, hookName, jsonInput, signal)
### 异步 Hook 的检测协议
Hook 进程的 stdout 第一行如果是 `{"async":true}`,系统将其转为后台任务(`hooks.ts:1199-1246`
Hook 进程的 stdout 第一行如果是 `{"async":true}`,系统将其转为后台任务(`isAsyncHookJSONOutput` 检测 + `executeInBackground` 调用
```typescript
const firstLine = firstLineOf(stdout).trim()
@@ -96,7 +101,7 @@ if (isAsyncHookJSONOutput(parsed)) {
## Hook 输出的 JSON Schema
同步 Hook 的输出遵循严格的 Zod schema`src/types/hooks.ts:49-567`
同步 Hook 的输出遵循严格的 Zod schema`syncHookResponseSchema`,定义在 `src/types/hooks.ts``hookJSONOutputSchema` 定义在 `src/schemas/hooks.ts`
```json
{
@@ -120,16 +125,25 @@ if (isAsyncHookJSONOutput(parsed)) {
| 事件 | 专有字段 | 作用 |
|------|---------|------|
| `PreToolUse` | `permissionDecision`, `updatedInput`, `additionalContext` | 拦截/修改工具输入 |
| `UserPromptSubmit` | `additionalContext` | 注入额外上下文 |
| `PreToolUse` | `permissionDecision`, `permissionDecisionReason`, `updatedInput`, `additionalContext` | 拦截/修改工具输入 |
| `PostToolUse` | `additionalContext`, `updatedMCPToolOutput` | 修改 MCP 工具输出 |
| `SessionStart` | `initialUserMessage`, `watchPaths` | 设置初始消息和文件监控 |
| `PostToolUseFailure` | `additionalContext` | 失败后注入上下文 |
| `UserPromptSubmit` | `additionalContext` | 注入额外上下文 |
| `SessionStart` | `additionalContext`, `initialUserMessage`, `watchPaths` | 设置初始消息和文件监控 |
| `PermissionRequest` | `decision`(含 `allow`/`deny` 子字段) | 权限请求的 Hook 决策 |
| `PermissionDenied` | `retry` | 指示是否重试 |
| `SubagentStart` | `additionalContext` | 子 Agent 启动时注入上下文 |
| `Elicitation` | `action`, `content` | 控制用户输入对话框 |
| `ElicitationResult` | `action`, `content` | Elicitation 结果处理 |
| `Notification` | `additionalContext` | 通知事件注入上下文 |
| `Setup` | `additionalContext` | 初始化时注入上下文 |
| `CwdChanged` | `watchPaths` | 目录变更后更新监控路径 |
| `FileChanged` | `watchPaths` | 文件变更后更新监控路径 |
| `WorktreeCreate` | `worktreePath` | Worktree 创建通知 |
## Hook 匹配机制getMatchingHooks
`getMatchingHooks()``hooks.ts:1685-1956`)负责从所有来源中查找匹配的 Hook
`getMatchingHooks()``src/utils/hooks.ts``getMatchingHooks` 函数)负责从所有来源中查找匹配的 Hook
### 多来源合并
@@ -143,7 +157,7 @@ getHooksConfig()
### 匹配规则
`matcher` 字段支持三种模式(`matchesPattern()`, `hooks.ts:1428-1463`
`matcher` 字段支持三种模式(`matchesPattern()` 函数,`src/utils/hooks.ts`
```
"Write" → 精确匹配
@@ -154,7 +168,7 @@ getHooksConfig()
### if 条件过滤
Hook 可以指定 `if` 条件,只在特定输入时触发。`prepareIfConditionMatcher()``hooks.ts:1472-1503`)预编译匹配器:
Hook 可以指定 `if` 条件,只在特定输入时触发。`prepareIfConditionMatcher()``src/utils/hooks.ts``prepareIfConditionMatcher` 函数)预编译匹配器:
```json
{
@@ -169,11 +183,11 @@ Hook 可以指定 `if` 条件,只在特定输入时触发。`prepareIfConditio
### Hook 去重
同一个 Hook 命令在不同配置层级user/project/local可能重复。系统按 `pluginRoot\0command` 做 Map 去重,保留**最后合并的层级**。
同一个 Hook 命令在不同配置层级user/project/local可能重复。系统按四部分复合键做 Map 去重:`${pluginRoot}\0${shell}\0${command}\0${ifCondition}`(由 `hookDedupKey()` 函数构建),保留**最后合并的层级**。
## 工作区信任检查
**所有 Hook 都要求工作区信任**`shouldSkipHookDueToTrust()`, `hooks.ts:286-296`)。这是纵深防御措施——防止恶意仓库的 `.claude/settings.json` 在未信任的情况下执行任意命令。
**所有 Hook 都要求工作区信任**`shouldSkipHookDueToTrust()` 函数,`src/utils/hooks.ts`)。这是纵深防御措施——防止恶意仓库的 `.claude/settings.json` 在未信任的情况下执行任意命令。
```typescript
// 交互模式下,所有 Hook 要求信任
@@ -226,13 +240,13 @@ SDK 非交互模式下信任是隐式的(`getIsNonInteractiveSession()` 为 tr
## Session Hook 的生命周期
Agent 和 Skill 的前置 Hook 通过 `registerFrontmatterHooks()` 注册(`runAgent.ts:567-575`),绑定到 agent 的 session ID。Agent 结束时通过 `clearSessionHooks()` 清理。
Agent 和 Skill 的前置 Hook 通过 `registerFrontmatterHooks()` 注册(调用位置:`src/tools/AgentTool/runAgent.ts`;定义位置:`src/utils/hooks/registerFrontmatterHooks.ts`),绑定到 agent 的 session ID。Agent 结束时通过 `clearSessionHooks()`(定义位置:`src/utils/hooks/sessionHooks.ts`清理。
```typescript
// runAgent.ts:567 — 注册 agent 的前置 Hook
// runAgent.ts — 注册 agent 的前置 Hook
registerFrontmatterHooks(rootSetAppState, agentId, agentDefinition.hooks, ...)
// runAgent.ts:820 — finally 块清理
// runAgent.ts — finally 块清理
clearSessionHooks(rootSetAppState, agentId)
```

View File

@@ -0,0 +1,346 @@
---
title: "MCP 配置 - 多来源合并、作用域与策略管控"
description: "详细说明 Claude Code MCP 配置的来源层次、合并优先级、传输类型、企业策略管控、插件集成和保留名称机制。"
keywords: ["MCP", "配置", "settings.json", ".mcp.json", "企业策略", "插件"]
---
## 配置来源与作用域
Claude Code 的 MCP 配置来自多个来源,每个来源对应一个 `scope`(作用域)。配置按优先级合并,高优先级来源的同名配置覆盖低优先级。
### 来源列表
| 来源 | Scope | 文件/接口 | 说明 |
|------|-------|----------|------|
| 企业管控 | `enterprise` | 系统管理路径 `managed-mcp.json` | **排他模式**:存在时忽略所有其他来源 |
| 本地项目 | `local` | `<project>/.claude/settings.local.json` | 项目级私有配置(不提交到 VCS |
| 项目配置 | `project` | `<project>/.mcp.json` | 项目级共享配置(可提交到 VCS |
| 用户全局 | `user` | `~/.claude/settings.json` | 用户级配置,所有项目共享 |
| 插件 | `dynamic` | 插件 manifest 中 `.mcp.json` / `.mcpb` | 插件提供的 MCP 服务器 |
| claude.ai | `claudeai` | 通过 API 获取 | claude.ai 网页端配置的连接器 |
| 内置动态 | `dynamic` | 代码中注册 | Computer Use / Chrome 等内置服务器 |
| IDE SDK | `sdk` | IDE 传入 | VS Code / JetBrains 嵌入模式 |
### 合并优先级(从低到高)
```
claude.ai 连接器 ← 最低优先级
↓ 去重
插件服务器
↓ 去重
用户全局配置
项目配置(.mcp.json ← 需要用户审批
本地项目配置
动态配置(内置 MCP ← 最高优先级
```
`Object.assign({}, dedupedPluginServers, userServers, approvedProjectServers, localServers)` 实现合并——后出现的同名键覆盖前者。
## 企业管控模式
当 `managed-mcp.json` 文件存在时,进入 **排他模式**
```typescript
// config.ts:1084
if (doesEnterpriseMcpConfigExist()) {
// 只返回企业配置,忽略所有用户/项目/插件/claude.ai 配置
return { servers: filtered, errors: [] }
}
```
特性:
- 路径由系统管理决定(`getManagedFilePath()` + `managed-mcp.json`
- 覆盖所有用户级、项目级、插件和 claude.ai 配置
- 仍然应用策略过滤allowlist/denylist
- 无法通过 CLI 添加新服务器(`addMcpConfig` 会拒绝)
## 传输类型与配置 Schema
### stdio默认
启动子进程,通过 stdin/stdout JSON-RPC 通信。
```json
{
"my-server": {
"command": "npx",
"args": ["-y", "@my-org/mcp-server"],
"env": { "API_KEY": "..." }
}
}
```
`type` 字段可省略(默认为 `stdio`)。环境变量通过 `env` 传递给子进程,会与当前进程环境合并。
**Windows 注意**:使用 `npx` 需要包装为 `cmd /c npx`,否则会报错。
### SSEServer-Sent Events
通过 HTTP SSE 连接远程 MCP 服务器。
```json
{
"my-remote": {
"type": "sse",
"url": "https://mcp.example.com/sse",
"headers": { "Authorization": "Bearer ..." },
"oauth": {
"clientId": "...",
"authServerMetadataUrl": "https://auth.example.com/.well-known/oauth-authorization-server"
}
}
}
```
支持 OAuth 认证流程。认证失败时进入 `needs-auth` 状态15 分钟 TTL 缓存避免重复提示。
### HTTPStreamable HTTP
HTTP 流式传输。
```json
{
"my-http": {
"type": "http",
"url": "https://mcp.example.com/mcp",
"headers": { "X-API-Key": "..." }
}
}
```
支持与 SSE 相同的 OAuth 配置。
### WebSocket
```json
{
"my-ws": {
"type": "ws",
"url": "wss://mcp.example.com/ws"
}
}
```
### IDE 专用类型(内部)
`sse-ide` 和 `ws-ide` 是 IDE 扩展专用类型,不由用户直接配置。
- `sse-ide`:使用 lockfile token 认证
- `ws-ide`:使用 `X-Claude-Code-Ide-Authorization` header
### SDK 类型(内部)
`type: "sdk"` 由 IDE 嵌入模式传入,不经过保留名称检查和企业管控排他限制。
### claude.ai 代理类型(内部)
`type: "claudeai-proxy"` 由 claude.ai 网页端配置的连接器使用,通过 OAuth bearer token 认证并支持 401 重试。
## 配置操作
### 添加 MCP 服务器
通过 CLI 命令 `claude mcp add` 或 API 调用 `addMcpConfig()`
```bash
# 添加到用户配置
claude mcp add my-server -s user -- npx @my-org/mcp-server
# 添加到项目配置
claude mcp add my-server -s project -- npx @my-org/mcp-server
# 添加 HTTP 类型
claude mcp add my-remote -s user -t http -u https://mcp.example.com/mcp
```
添加时的验证流程:
1. **名称校验**:只允许字母、数字、连字符和下划线
2. **保留名检查**`claude-in-chrome` 和 `computer-use` 被保留
3. **企业管控检查**:企业模式下拒绝添加
4. **Schema 验证**Zod 校验配置格式
5. **策略检查**denylist 拒绝、allowlist 验证
### 移除 MCP 服务器
```bash
claude mcp remove my-server -s user
```
### 列出 MCP 服务器
```bash
claude mcp list
```
## 项目配置审批
`.mcp.json` 中的项目配置需要用户显式审批才能生效:
```typescript
// config.ts:1166
const approvedProjectServers: Record<string, ScopedMcpServerConfig> = {}
for (const [name, config] of Object.entries(projectServers)) {
if (getProjectMcpServerStatus(name) === 'approved') {
approvedProjectServers[name] = config
}
}
```
首次打开项目时Claude Code 会提示用户审批 `.mcp.json` 中的每个服务器。审批状态持久化在本地配置中。
## 插件 MCP 集成
插件通过 manifest 中的 `.mcp.json` 或 `.mcpb` 文件声明 MCP 服务器:
```typescript
// 插件 MCP 加载流程
const pluginResult = await loadAllPluginsCacheOnly()
const pluginServerResults = await Promise.all(
pluginResult.enabled.map(plugin => getPluginMcpServers(plugin, mcpErrors))
)
```
### 插件命名空间
插件 MCP 服务器名格式为 `plugin:<pluginName>:<serverName>`,不会与手动配置的名称冲突。
### 去重机制
插件服务器通过内容签名去重(`dedupPluginMcpServers`
- **stdio 类型**:签名 = `stdio:` + JSON.stringify([command, ...args])
- **URL 类型**:签名 = `url:` + 原始 URLunwrap CCR proxy URL
- **sdk 类型**:签名为 null不去重
去重规则:
1. 手动配置优先于插件配置
2. 先加载的插件优先于后加载的
3. 被抑制的插件服务器在 `/plugin` UI 中显示提示
### claude.ai 连接器去重
claude.ai 连接器使用相同的内容签名机制去重(`dedupClaudeAiMcpServers`
- 仅启用的手动配置参与去重(禁用的手动配置不应抑制连接器)
- 连接器名格式为 `claude.ai <DisplayName>`
## 策略管控
### Allowlist / Denylist
企业策略通过 allowlist 和 denylist 控制可用的 MCP 服务器:
```typescript
// config.ts:1243 - 最终策略过滤
for (const [name, serverConfig] of Object.entries(configs)) {
if (!isMcpServerAllowedByPolicy(name, serverConfig)) {
continue // 跳过策略禁止的服务器
}
filtered[name] = serverConfig
}
```
策略检查考虑:
- 服务器名称匹配
- stdio 类型的 command + args 匹配
- URL 类型的 URL 模式匹配(支持通配符)
### 插件专用模式
`isRestrictedToPluginOnly('mcp')` 启用时,只允许插件提供的 MCP 服务器——用户/项目级配置被忽略。
## 环境变量展开
MCP 配置中的环境变量支持 `$VAR` 和 `${VAR}` 语法展开:
```json
{
"my-server": {
"command": "npx",
"args": ["@my-org/mcp-server"],
"env": {
"API_KEY": "$MY_API_KEY",
"DB_URL": "${DATABASE_URL}"
}
}
}
```
展开时缺失的变量会生成警告信息,但不阻止配置加载。
## 内置 MCP 动态注册
内置 MCP 服务器在 `main.tsx` 启动流程中动态注入配置:
### Computer Use MCP
```typescript
// src/utils/computerUse/setup.ts
export function setupComputerUseMCP(): {
mcpConfig: Record<string, ScopedMcpServerConfig>
allowedTools: string[]
} {
return {
mcpConfig: {
"computer-use": {
type: "stdio",
command: process.execPath,
args: ["--computer-use-mcp"],
scope: "dynamic",
}
},
allowedTools: ["mcp__computer-use__screenshot", ...]
}
}
```
启用条件:
- Feature flag `CHICAGO_MCP` 开启
- `getPlatform() !== "unknown"`macOS/Windows/Linux
- 非非交互式会话
- GrowthBook gate `getChicagoEnabled()` 返回 true
### Claude in Chrome MCP
```typescript
// 类似 Computer Use在 main.tsx 中注册
const { mcpConfig, allowedTools, systemPrompt } = setupClaudeInChrome()
dynamicMcpConfig = { ...dynamicMcpConfig, ...mcpConfig }
```
启用条件:
- `--chrome` 参数或 `claudeInChromeDefaultEnabled` 配置
- Chrome 扩展已安装
### VSCode SDK MCP
IDE 嵌入模式通过初始化消息传入 `type:'sdk'` 的配置,由 `setupVscodeSdkMcp()` 设置双向通知。
## 保留名称
以下 MCP 服务器名称被保留,用户无法手动配置同名服务器:
| 名称 | 用途 | 检查条件 |
|------|------|---------|
| `claude-in-chrome` | Chrome 浏览器控制 | 始终检查 |
| `computer-use` | 桌面自动化 | `CHICAGO_MCP` feature flag 开启时检查 |
| `claude-vscode` | VSCode IDE 集成 | 由 SDK 传入,不经过名称检查 |
保留名检查在两个位置:
1. `addMcpConfig()``config.ts:636-648`)— 运行时拒绝
2. `main.tsx` 启动检查(`main.tsx:2351-2368`)— 启动时退出
## 关键源文件索引
| 文件 | 职责 |
|------|------|
| `src/services/mcp/config.ts` | 配置管理核心:合并、去重、策略、添加/删除 |
| `src/services/mcp/types.ts` | Zod Schema 定义、类型声明 |
| `src/services/mcp/client.ts` | 连接管理、传输层选择 |
| `src/utils/plugins/mcpPluginIntegration.ts` | 插件 MCP 配置加载 |
| `src/utils/computerUse/setup.ts` | Computer Use 动态注册 |
| `src/utils/claudeInChrome/common.ts` | Chrome MCP 保留名与工具名 |
| `src/services/mcp/vscodeSdkMcp.ts` | VSCode SDK 双向通知 |

View File

@@ -1,25 +1,32 @@
---
title: "MCP 协议 - 连接管理、工具发现与执行链路"
description: "从源码角度解析 Claude Code 的 MCP 集成7 种传输层实现、connectToServer 的 memoize 缓存、工具发现的 LRU 策略、认证状态机、以及 MCP 工具如何进入权限检查链路。"
keywords: ["MCP", "Model Context Protocol", "工具扩展", "MCP 客户端", "工具发现"]
description: "从源码角度解析 Claude Code 的 MCP 集成:内置 MCP 与外部 MCP 的区别、7 种传输层实现、connectToServer 的 memoize 缓存、工具发现的 LRU 策略、认证状态机、以及 MCP 工具如何进入权限检查链路。"
keywords: ["MCP", "Model Context Protocol", "工具扩展", "MCP 客户端", "工具发现", "内置 MCP", "外部 MCP"]
---
{/* 本章目标:从源码角度揭示 MCP 客户端的连接管理、工具发现协议和执行链路 */}
{/* 本章目标:从源码角度揭示 MCP 客户端的两种运行模式(内置/外部)、连接管理、工具发现协议和执行链路 */}
## 架构总览:从配置到可用工具
```
settings.json: { mcpServers: { "my-db": { command: "npx", args: [...] } } }
配置层(多来源合并)
├── settings.json: { mcpServers: { "my-db": { command: "npx", args: [...] } } } ← 外部
├── .mcp.json: 项目级 MCP 配置 ← 外部
├── 插件 manifest (.mcp.json / .mcpb) ← 外部(插件)
├── claude.ai connectors ← 外部(远程)
├── enterprise managed-mcp.json ← 外部(企业管控)
├── setupComputerUseMCP() / setupClaudeInChrome() ← 内置(动态注册)
└── SDK 传入 (type:'sdk') ← 内置IDE 嵌入)
getAllMcpConfigs() ← 合并 user/project/local 三级配置
getAllMcpConfigs() ← enterprise 独占 或 合并 user/project/local + plugin + claude.ai
useManageMCPConnections() ← React Hook 管理连接生命周期
connectToServer(name, config) ← memoize 缓存lodash memoize
├── 创建 Transportstdio/sse/http/...
├── new Client() ← @modelcontextprotocol/sdk
├── client.connect(transport) ← 超时控制MCP_TIMEOUT, 默认 30s
└── 返回 MCPServerConnection ← { connected | failed | needs-auth | pending }
├── 判断:内置 MCP → InProcessTransport同进程
├── 判断:外部 stdio → StdioClientTransport子进程
├── 判断:远程 SSE/HTTP/WS → 网络传输
└── 返回 MCPServerConnection ← { connected | failed | needs-auth | pending | disabled }
fetchToolsForClient(client) ← LRU(20) 缓存
├── client.request({ method: 'tools/list' })
@@ -30,19 +37,208 @@ assembleToolPool() ← 合并内置工具 + MCP 工具
工具名格式: mcp__<serverName>__<toolName> ← buildMcpToolName()
```
## 两种 MCP 模式:内置 vs 外部
Claude Code 的 MCP 实现区分 **内置 MCP 服务器** 和 **外部 MCP 服务器**。两者使用相同的客户端协议和工具发现机制,但在连接方式、生命周期管理和配置来源上完全不同。
### 内置 MCP 服务器
内置 MCP 服务器由 Claude Code 自身提供,无需用户手动配置。它们在启动时自动注册为 `dynamic` scope 的配置,并在同进程内运行。
| 服务器 | 名称 | 包路径 | Feature Flag | 启用方式 |
|--------|------|--------|-------------|---------|
| Computer Use | `computer-use` | `@ant/computer-use-mcp` | `CHICAGO_MCP` | GrowthBook gate + macOS + interactive |
| Claude in Chrome | `claude-in-chrome` | `@ant/claude-for-chrome-mcp` | — | `--chrome` 参数或 `claudeInChromeDefaultEnabled` 配置 |
| VSCode SDK | `claude-vscode` | — | — | IDE 嵌入模式 (type:`sdk`) |
#### InProcessTransport零开销同进程通信
内置服务器通过 `InProcessTransport``src/services/mcp/InProcessTransport.ts`)运行,**不启动子进程**
```typescript
// 创建一对 linked transport —— 消息在两端之间直接传递
const [clientTransport, serverTransport] = createLinkedTransportPair()
// server 端连接到 serverTransport
inProcessServer = createComputerUseMcpServerForCli()
await inProcessServer.connect(serverTransport)
// client 端使用 clientTransport与外部 MCP 的 Client 相同接口)
transport = clientTransport
```
`InProcessTransport` 的核心设计:
- `send()` 通过 `queueMicrotask()` 异步投递消息到对端,避免同步请求/响应的栈深度问题
- `close()` 双向关闭,任一端关闭都会触发两端的 `onclose` 回调
- 无网络开销、无 IPC 序列化、无进程启动时间
#### 动态注册流程
内置服务器在 `main.tsx` 的启动流程中注册,注入 `dynamicMcpConfig`
```typescript
// main.tsx: Computer Use MCP 动态注册
if (feature("CHICAGO_MCP") && getPlatform() !== "unknown" && !getIsNonInteractiveSession()) {
const { getChicagoEnabled } = await import("src/utils/computerUse/gates.js")
if (getChicagoEnabled()) {
const { setupComputerUseMCP } = await import("src/utils/computerUse/setup.js")
const { mcpConfig, allowedTools } = setupComputerUseMCP()
dynamicMcpConfig = { ...dynamicMcpConfig, ...mcpConfig }
allowedTools.push(...cuTools)
}
}
```
`setupComputerUseMCP()` 返回的配置(`src/utils/computerUse/setup.ts`
```typescript
{
"computer-use": {
type: "stdio", // 类型标记为 stdio但 client.ts 会拦截为 InProcessTransport
command: process.execPath,
args: ["--computer-use-mcp"],
scope: "dynamic", // 动态作用域,不持久化
}
}
```
#### 连接时拦截
`connectToServer()` 在 `client.ts:906-944` 中根据服务器名拦截内置服务器:
```typescript
// Chrome MCP — 在 process 内运行,避免 ~325MB 子进程
if (isClaudeInChromeMCPServer(name)) {
const { createChromeContext } = await import('../../utils/claudeInChrome/mcpServer.js')
const { createClaudeForChromeMcpServer } = await import('@ant/claude-for-chrome-mcp')
const { createLinkedTransportPair } = await import('./InProcessTransport.js')
const context = createChromeContext(config.env)
inProcessServer = createClaudeForChromeMcpServer(context)
const [clientTransport, serverTransport] = createLinkedTransportPair()
await inProcessServer.connect(serverTransport)
transport = clientTransport
}
// Computer Use MCP — 同理
if (feature('CHICAGO_MCP') && isComputerUseMCPServer(name)) {
const { createComputerUseMcpServerForCli } = await import('../../utils/computerUse/mcpServer.js')
const { createLinkedTransportPair } = await import('./InProcessTransport.js')
inProcessServer = await createComputerUseMcpServerForCli()
const [clientTransport, serverTransport] = createLinkedTransportPair()
await inProcessServer.connect(serverTransport)
transport = clientTransport
}
```
#### 保留名称保护
内置服务器的名称被保留,用户无法手动添加同名配置(`config.ts:636-648`
```typescript
// 添加 MCP 配置时检查保留名
if (isClaudeInChromeMCPServer(name)) {
throw new Error(`Cannot add MCP server "${name}": this name is reserved.`)
}
if (feature('CHICAGO_MCP') && isComputerUseMCPServer(name)) {
throw new Error(`Cannot add MCP server "${name}": this name is reserved.`)
}
```
启动时也有全局检查(`main.tsx:2351-2368`):如果用户配置中包含保留名(非 `type:'sdk'`),直接 `process.exit(1)`。
#### VSCode SDK MCP
VSCode SDK MCP 是特殊的内置模式。IDE如 VS Code、JetBrains通过嵌入方式启动 Claude Code并传入 `type:'sdk'` 的 MCP 配置。这类配置:
- 不经过保留名称检查IDE 可以使用任意名称)
- 不参与 enterprise MCP 的排他控制
- 通过 VSCode SDK transport 连接
- 支持双向通知(如 `file_updated`、`experiment_gates`
```typescript
// src/services/mcp/vscodeSdkMcp.ts
export function setupVscodeSdkMcp(sdkClients: MCPServerConnection[]): void {
const client = sdkClients.find(client => client.name === 'claude-vscode')
if (client && client.type === 'connected') {
// 注册 log_event 通知处理器
client.client.setNotificationHandler(LogEventNotificationSchema(), ...)
// 发送实验门控到 VSCode
client.client.notification({ method: 'experiment_gates', params: { gates } })
}
}
```
### 外部 MCP 服务器
外部 MCP 服务器由用户在配置文件中声明,通过子进程或网络连接运行。
#### 配置来源
| 来源 | Scope | 文件位置 | 优先级 |
|------|-------|---------|--------|
| 项目配置 | `project` | `<project>/.mcp.json` | 最高(同名覆盖) |
| 本地配置 | `local` | `<project>/.claude/settings.local.json` | 高 |
| 用户配置 | `user` | `~/.claude/settings.json` | 中 |
| 插件 | `dynamic` | 插件 manifest 中 `.mcp.json` | 中 |
| claude.ai | `claudeai` | 通过 API 获取 | 低 |
| 企业管控 | `enterprise` | 系统管理路径 `managed-mcp.json` | 排他(存在时覆盖全部) |
#### 配置示例
```json
// settings.json / .mcp.json 中的 MCP 配置
{
"mcpServers": {
// stdio 类型 — 启动子进程
"my-database": {
"command": "npx",
"args": ["@my-org/db-mcp-server"],
"env": { "DB_URL": "postgres://..." }
},
// HTTP 流类型 — 远程服务器
"remote-api": {
"type": "http",
"url": "https://api.example.com/mcp"
},
// SSE 类型 — Server-Sent Events
"realtime-feed": {
"type": "sse",
"url": "https://feed.example.com/sse"
},
// WebSocket 类型
"ws-service": {
"type": "ws",
"url": "wss://ws.example.com/mcp"
}
}
}
```
#### 配置合并与去重
`getAllMcpConfigs()``config.ts`)按优先级合并多个来源的配置:
1. 企业管控配置存在时,**独占返回**(忽略所有其他来源)
2. 否则合并user → project → local → plugin → claude.ai
3. 插件与手动配置去重:通过 `getMcpServerSignature()` 生成内容签名(基于 command/args/url插件配置被同名手动配置抑制
4. `addScopeToServers()` 为每个配置项标注来源 scope
## 7 种传输层实现
`connectToServer()``client.ts:596-1643`)根据 `config.type` 分发到不同的 Transport 实现:
| 传输类型 | Transport 类 | 适用场景 | 认证方式 |
|----------|-------------|---------|---------|
| `stdio`(默认) | `StdioClientTransport` | 本地子进程 | 无 |
| `stdio`(默认) | `StdioClientTransport` | 外部本地子进程 | 无 |
| `sse` | `SSEClientTransport` | 远程 SSE 服务 | `ClaudeAuthProvider` + OAuth |
| `http` | `StreamableHTTPClientTransport` | HTTP 流 | `ClaudeAuthProvider` + OAuth |
| `sse-ide` | `SSEClientTransport` | IDE 集成 | lockfile token |
| `ws-ide` | `WebSocketTransport` | IDE WebSocket | `X-Claude-Code-Ide-Authorization` |
| `ws` | `WebSocketTransport` | WebSocket 服务 | session ingress token |
| `claudeai-proxy` | `StreamableHTTPClientTransport` | claude.ai 代理 | OAuth bearer + 401 重试 |
| InProcess内置 | `InProcessTransport` | Computer Use / Chrome | 无(同进程) |
### stdio 传输的进程管理
@@ -112,9 +308,17 @@ timer.unref?.() // 不阻止进程退出
```typescript
const fullyQualifiedName = buildMcpToolName(client.name, tool.name)
// 结果: "mcp__my-db__query"
// 结果: "mcp__my-database__query"
```
### 内置 MCP 的工具发现
内置 MCP 服务器虽然使用 InProcessTransport但工具发现流程与外部服务器完全一致
- **Computer Use**`createComputerUseMcpServerForCli()` 在 `src/utils/computerUse/mcpServer.ts` 中构建 MCP Server 对象,注册 `ListToolsRequestSchema` handler。工具描述包含平台特定的已安装应用列表1s 超时枚举)。
- **Claude in Chrome**`createClaudeForChromeMcpServer()` 在 `@ant/claude-for-chrome-mcp` 包中构建 Server提供 17+ 个浏览器控制工具。
- **VSCode SDK**:由 IDE 端提供工具列表,通过 SDK transport 传递。
### 工具描述截断
MCP 工具描述上限 2048 字符(`MAX_MCP_DESCRIPTION_LENGTH`。OpenAPI 生成的 MCP 服务器曾观察到 15-60KB 的描述文档。
@@ -134,6 +338,8 @@ MCP 工具描述上限 2048 字符(`MAX_MCP_DESCRIPTION_LENGTH`。OpenAPI
MCP 工具默认返回 `{ behavior: 'passthrough' }``client.ts:1816-1834`),意味着它们始终进入权限确认流程。工具名使用 `mcp__` 前缀精确匹配权限规则。
内置 MCP 服务器的工具通过 `allowedTools` 列表自动授权——在 `main.tsx` 启动时加入,绕过普通权限提示。例如 Computer Use 工具的 `request_access` 自行处理会话级审批。
## MCP 工具的执行链路
```
@@ -169,23 +375,33 @@ getRemoteMcpServerConnectionBatchSize() // 默认 20
本地 MCP 服务器stdio是重量级的子进程默认限制 3 个并发连接。远程服务器是轻量级 HTTP 请求,允许 20 个并发。
## 实际配置示例
## 内置 vs 外部 MCP 对比总结
```json
// settings.json 中的 MCP 配置
{
"mcpServers": {
"my-database": {
"command": "npx",
"args": ["@my-org/db-mcp-server"],
"env": { "DB_URL": "postgres://..." }
},
"remote-api": {
"type": "http",
"url": "https://api.example.com/mcp"
}
}
}
```
| 维度 | 内置 MCP | 外部 MCP |
|------|---------|---------|
| **Transport** | `InProcessTransport`(同进程) | stdio / SSE / HTTP / WebSocket |
| **配置来源** | `setupComputerUseMCP()` / `setupClaudeInChrome()` 等动态注册 | settings.json / .mcp.json / 插件 / claude.ai |
| **Scope** | `dynamic` | `user` / `project` / `local` / `enterprise` / `claudeai` |
| **进程模型** | 同进程,零开销 | 子进程stdio或网络连接 |
| **名称保护** | 保留名,用户不可添加同名 | 自由命名(字母数字 + `-_` |
| **生命周期** | 随 CLI 启停 | 连接缓存 + 按需重连 |
| **权限** | `allowedTools` 自动授权 | `passthrough` 进入权限确认 |
| **Feature Flag** | `CHICAGO_MCP`Computer Use等 | 无(始终可用) |
| **工具发现** | 与外部相同MCP 协议) | 标准 MCP `tools/list` |
| **清理** | `inProcessServer.close()` | 信号升级策略 SIGINT→SIGTERM→SIGKILL |
配置后AI 的工具列表中会出现 `mcp__my-database__query` 和 `mcp__remote-api__*` 工具——与内置工具使用相同的权限检查链路和 UI 渲染。
## 关键源文件索引
| 文件 | 职责 |
|------|------|
| `src/services/mcp/client.ts` | 核心客户端connectToServer、fetchToolsForClient、MCPTool.call |
| `src/services/mcp/config.ts` | 配置管理getAllMcpConfigs、addMcpConfig、removeMcpConfig |
| `src/services/mcp/types.ts` | 类型定义:配置 Schema、连接状态类型 |
| `src/services/mcp/InProcessTransport.ts` | 内置 MCP 传输层linked transport pair |
| `src/services/mcp/vscodeSdkMcp.ts` | VSCode SDK MCP双向通知、实验门控 |
| `src/services/mcp/useManageMCPConnections.ts` | React Hook连接生命周期、重连 |
| `src/utils/computerUse/mcpServer.ts` | Computer Use MCP Server 构建 |
| `src/utils/computerUse/setup.ts` | Computer Use 动态注册 |
| `src/utils/claudeInChrome/mcpServer.ts` | Chrome MCP Server 构建 + Bridge 配置 |
| `src/tools/MCPTool/MCPTool.ts` | MCP 工具包装:统一 Tool 接口 |
| `src/entrypoints/mcp.ts` | MCP server 入口Claude Code 作为 MCP server |

View File

@@ -48,7 +48,7 @@ Skill 的核心洞见:**复杂任务的关键不在代码逻辑,而在 Promp
1. `readdir` 扫描目录 → 仅保留 `isDirectory()` 或 `isSymbolicLink()` 的条目
2. 在每个子目录中查找 `SKILL.md`,未找到则跳过
3. `parseFrontmatter()` 解析 YAML 头部,提取 `whenToUse`、`allowedTools`、`context` 等字段
4. `parseSkillFrontmatterFields()`(第 185 行)统一解析 17 个 frontmatter 字段
4. `parseSkillFrontmatterFields()`(第 185 行)统一解析 16 个 frontmatter 字段
5. `createSkillCommand()`(第 270 行)构造 `Command` 对象
**去重机制**:使用 `realpath()` 解析符号链接获得规范路径(`getFileIdentity`,第 118 行),避免通过符号链接或重叠父目录导致的重复加载。
@@ -94,7 +94,7 @@ shell: ["bash"] # Shell 执行环境
---
```
解析后有 17 个字段被提取,其中 `allowedTools`、`model`、`effort` 在执行时动态修改 `toolPermissionContext`。
解析后有 16 个字段被提取,其中 `allowedTools`、`model`、`effort` 在执行时动态修改 `toolPermissionContext`。
## 两条执行路径Inline vs Fork
@@ -128,12 +128,12 @@ Fork 模式适用于需要强隔离的场景(如长时间运行的审查任务
## 权限模型Safe Properties 白名单
`checkPermissions()`(第 433 行)实现了一个层权限检查:
`checkPermissions()`(第 433 行)实现了一个层权限检查:
```
1. Deny 规则匹配(支持精确匹配和 prefix:* 通配符)
↓ 未命中
2. 官方市场 Skill 自动放行plugin + isOfficialMarketplaceName
2. 远程 canonical Skill 自动放行EXPERIMENTAL_SKILL_SEARCH + USER_TYPE === 'ant'
↓ 未命中
3. Allow 规则匹配
↓ 未命中
@@ -142,7 +142,7 @@ Fork 模式适用于需要强隔离的场景(如长时间运行的审查任务
5. Ask 用户确认(附带精确匹配和前缀匹配两条建议规则)
```
**Safe Properties**`SAFE_SKILL_PROPERTIES`,第 876 行)是一个包含 28 个属性名的白名单。任何不在白名单中的**有意义的属性值**(排除 `undefined`、`null`、空数组、空对象)都会触发权限请求。这是**正向安全**设计——未来新增的属性默认需要权限。
**Safe Properties**`SAFE_SKILL_PROPERTIES`,第 876 行)是一个包含 30 个属性名的白名单(覆盖 `PromptCommand` 和 `CommandBase` 两个类型的所有安全属性)。任何不在白名单中的**有意义的属性值**(排除 `undefined`、`null`、空数组、空对象)都会触发权限请求。这是**正向安全**设计——未来新增的属性默认需要权限。
## Prompt 预算1% 上下文窗口的截断策略
@@ -205,7 +205,7 @@ score = usageCount × max(0.5^(daysSinceUse / 7), 0.1)
```
磁盘 SKILL.md
↓ parseFrontmatter()
↓ parseSkillFrontmatterFields() → 17 个字段
↓ parseSkillFrontmatterFields() → 16 个字段
↓ createSkillCommand() → Command 对象
↓ 去重realpath + seenFileIds
↓ 条件 Skill → conditionalSkills Map等待路径匹配激活
@@ -214,7 +214,7 @@ score = usageCount × max(0.5^(daysSinceUse / 7), 0.1)
↓ formatCommandsWithinBudget() → 截断后的 Skill 列表注入 System Prompt
↓ AI 选择匹配的 Skill
↓ SkillTool.validateInput() → 名称校验 + 存在性检查
↓ SkillTool.checkPermissions() → 层权限检查
↓ SkillTool.checkPermissions() → 层权限检查
↓ SkillTool.call() → inline 或 fork 执行
↓ contextModifier() → 注入 allowedTools + model + effort
↓ recordSkillUsage() → 更新使用频率排名

View File

@@ -0,0 +1,214 @@
# Claude Code 远程服务器依赖
> 只列出代码中实际发起网络请求的远程服务。本地服务、npm 包依赖、展示用 URL 不包含在内。
## 总览表
| # | 服务 | 远程端点 | 协议 | 状态 |
|---|---|---|---|---|
| 1 | Anthropic API | `api.anthropic.com` | HTTPS | 默认启用 |
| 2 | AWS Bedrock | `bedrock-runtime.*.amazonaws.com` | HTTPS | 需 `CLAUDE_CODE_USE_BEDROCK=1` |
| 3 | Google Vertex AI | `{region}-aiplatform.googleapis.com` | HTTPS | 需 `CLAUDE_CODE_USE_VERTEX=1` |
| 4 | Azure Foundry | `{resource}.services.ai.azure.com` | HTTPS | 需 `CLAUDE_CODE_USE_FOUNDRY=1` |
| 5 | OAuth (Anthropic) | `platform.claude.com`, `claude.com`, `claude.ai` | HTTPS | 用户登录时 |
| 6 | GrowthBook | `api.anthropic.com` (remoteEval) | HTTPS | 默认启用 |
| 7 | Sentry | 可配置 (`SENTRY_DSN`) | HTTPS | 需设环境变量 |
| 8 | Datadog | 可配置 (`DATADOG_LOGS_ENDPOINT`) | HTTPS | 需设环境变量 |
| 9 | OpenTelemetry Collector | 可配置 (`OTEL_EXPORTER_OTLP_ENDPOINT`) | gRPC/HTTP | 需设环境变量 |
| 10 | 1P Event Logging | `api.anthropic.com/api/event_logging/batch` | HTTPS | 默认启用 |
| 11 | BigQuery Metrics | `api.anthropic.com/api/claude_code/metrics` | HTTPS | 默认启用 |
| 12 | MCP Proxy | `mcp-proxy.anthropic.com` | HTTPS+WS | 使用 MCP 工具时 |
| 13 | MCP Registry | `api.anthropic.com/mcp-registry` | HTTPS | 查询 MCP 服务器时 |
| 14 | Web Search Pages | `www.bing.com`, `search.brave.com` | HTTPS | WebSearch 工具,可通过 `WEB_SEARCH_ADAPTER=bing|brave` 切换 |
| 15 | Google Cloud Storage (更新) | `storage.googleapis.com` | HTTPS | 版本检查 |
| 16 | GitHub Raw (Changelog/Stats) | `raw.githubusercontent.com` | HTTPS | 更新提示 |
| 17 | Claude in Chrome Bridge | `bridge.claudeusercontent.com` | WSS | Chrome 集成 |
| 18 | CCR Upstream Proxy | `api.anthropic.com` | WS | CCR 远程会话 |
| 19 | Voice STT | `api.anthropic.com/api/ws/...` | WSS | Voice Mode |
| 20 | Desktop App Download | `claude.ai/api/desktop/...` | HTTPS | 下载引导 |
---
## 详细说明
### 1. Anthropic Messages API
核心 LLM 推理服务,发送对话消息、接收流式响应。
- **端点**: `https://api.anthropic.com` (生产) / `https://api-staging.anthropic.com` (staging)
- **覆盖**: `ANTHROPIC_BASE_URL` 环境变量
- **认证**: API Key / OAuth Token
- **文件**: `src/services/api/client.ts`, `src/services/api/claude.ts`
### 2. AWS Bedrock
- **端点**: `bedrock-runtime.{region}.amazonaws.com`
- **认证**: AWS 凭证链 / `AWS_BEARER_TOKEN_BEDROCK`
- **文件**: `src/services/api/client.ts:153-190`, `src/utils/aws.ts`
### 3. Google Vertex AI
- **端点**: `{region}-aiplatform.googleapis.com`
- **认证**: `GoogleAuth` + `cloud-platform` scope
- **文件**: `src/services/api/client.ts:228-298`
### 4. Azure Foundry
- **端点**: `https://{resource}.services.ai.azure.com/anthropic/v1/messages`
- **认证**: API Key 或 Azure AD `DefaultAzureCredential`
- **文件**: `src/services/api/client.ts:191-220`
### 5. OAuth
OAuth 2.0 + PKCE 授权码流程。
- **端点**:
- `https://platform.claude.com/oauth/authorize` — 授权页
- `https://claude.com/cai/oauth/authorize` — Claude.ai 授权
- `https://platform.claude.com/v1/oauth/token` — Token 交换
- `https://api.anthropic.com/api/oauth/claude_cli/create_api_key` — 创建 API Key
- `https://api.anthropic.com/api/oauth/claude_cli/roles` — 获取角色
- `https://claude.ai/oauth/claude-code-client-metadata` — MCP 客户端元数据
- `https://claude.fedstart.com` — FedStart 政府部署
- **文件**: `src/constants/oauth.ts`, `src/services/oauth/`
### 6. GrowthBook (功能开关)
- **端点**: `https://api.anthropic.com/` (remoteEval 模式) 或 `CLAUDE_GB_ADAPTER_URL`
- **SDK Keys**: `sdk-zAZezfDKGoZuXXKe` (外部), `sdk-xRVcrliHIlrg4og4` (ant prod), `sdk-yZQvlplybuXjYh6L` (ant dev)
- **文件**: `src/services/analytics/growthbook.ts`, `src/constants/keys.ts`
### 7. Sentry (错误追踪)
- **激活**: 设置 `SENTRY_DSN` (默认未配置)
- **行为**: 仅错误上报,自动过滤敏感 header
- **文件**: `src/utils/sentry.ts`
### 8. Datadog (日志)
- **激活**: 同时设 `DATADOG_LOGS_ENDPOINT` + `DATADOG_API_KEY` (默认未配置)
- **文件**: `src/services/analytics/datadog.ts`
### 9. OpenTelemetry Collector
- **激活**: `CLAUDE_CODE_ENABLE_TELEMETRY=1``OTEL_*` 环境变量
- **协议**: gRPC / HTTP / Protobuf支持 OTLP 和 Prometheus 导出
- **文件**: `src/utils/telemetry/instrumentation.ts`
### 10. 1P Event Logging (内部事件)
- **端点**: `https://api.anthropic.com/api/event_logging/batch`
- **协议**: 批量导出 (10s 间隔, 每批 200 事件)
- **文件**: `src/services/analytics/firstPartyEventLoggingExporter.ts`
### 11. BigQuery Metrics
- **端点**: `https://api.anthropic.com/api/claude_code/metrics`
- **文件**: `src/utils/telemetry/bigqueryExporter.ts`
### 12. MCP Proxy
Anthropic 托管的 MCP 服务器代理。
- **端点**: `https://mcp-proxy.anthropic.com/v1/mcp/{server_id}`
- **认证**: Claude.ai OAuth tokens
- **文件**: `src/services/mcp/client.ts`, `src/constants/oauth.ts`
### 13. MCP Registry
获取官方 MCP 服务器列表。
- **端点**: `https://api.anthropic.com/mcp-registry/v0/servers?version=latest&visibility=commercial`
- **文件**: `src/services/mcp/officialRegistry.ts`
### 14. Web Search Pages
WebSearch 工具支持直接抓取 Bing 搜索结果页面,也支持通过 Brave 的 LLM Context API
获取搜索上下文;可通过 `WEB_SEARCH_ADAPTER=bing|brave` 显式切换后端。
- **Bing 端点**: `https://www.bing.com/search?q={query}&setmkt=en-US`
- **Brave 端点**: `https://api.search.brave.com/res/v1/llm/context?q={query}`
- **文件**:
- `src/tools/WebSearchTool/adapters/bingAdapter.ts`
- `src/tools/WebSearchTool/adapters/braveAdapter.ts`
另外还有 Domain Blocklist 查询:
- **端点**: `https://api.anthropic.com/api/web/domain_info?domain={domain}`
- **文件**: `src/tools/WebFetchTool/utils.ts`
### 15. Google Cloud Storage (自动更新)
- **端点**: `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases`
- **文件**: `src/utils/autoUpdater.ts`
### 16. GitHub Raw Content
- **端点**: `https://raw.githubusercontent.com/anthropics/claude-code/refs/heads/main/CHANGELOG.md`
- **端点**: `https://raw.githubusercontent.com/anthropics/claude-plugins-official/refs/heads/stats/stats/plugin-installs.json`
- **文件**: `src/utils/releaseNotes.ts`, `src/utils/plugins/installCounts.ts`
### 17. Claude in Chrome Bridge
- **端点**: `wss://bridge.claudeusercontent.com` (生产) / `wss://bridge-staging.claudeusercontent.com` (staging)
- **文件**: `src/utils/claudeInChrome/mcpServer.ts`
### 18. CCR Upstream Proxy
- **端点**: `ws://api.anthropic.com/v1/code/upstreamproxy/ws`
- **激活**: `CLAUDE_CODE_REMOTE=1` + `CCR_UPSTREAM_PROXY_ENABLED=1`
- **文件**: `src/upstreamproxy/upstreamproxy.ts`
### 19. Voice STT
- **端点**: `wss://api.anthropic.com/api/ws/...`
- **文件**: `src/services/voiceStreamSTT.ts`
### 20. Desktop App Download
- **端点**: `https://claude.ai/api/desktop/win32/x64/exe/latest/redirect` (Windows)
- **端点**: `https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect` (macOS)
- **文件**: `src/components/DesktopHandoff.tsx`
---
## Anthropic API 辅助端点汇总
以下端点都挂在 `api.anthropic.com` 上,按功能分类:
| 端点路径 | 用途 | 文件 |
|---|---|---|
| `/api/event_logging/batch` | 事件批量上报 | `src/services/analytics/firstPartyEventLoggingExporter.ts` |
| `/api/claude_code/metrics` | BigQuery 指标导出 | `src/utils/telemetry/bigqueryExporter.ts` |
| `/api/oauth/claude_cli/create_api_key` | 创建 API Key | `src/constants/oauth.ts` |
| `/api/oauth/claude_cli/roles` | 获取用户角色 | `src/constants/oauth.ts` |
| `/api/oauth/accounts/grove` | 通知设置 | `src/services/api/grove.ts` |
| `/api/oauth/organizations/{id}/referral/*` | 推荐活动 | `src/services/api/referral.ts` |
| `/api/oauth/organizations/{id}/overage_credit_grant` | 超额信用 | `src/services/api/overageCreditGrant.ts` |
| `/api/oauth/organizations/{id}/admin_requests` | 管理请求 | `src/services/api/adminRequests.ts` |
| `/api/web/domain_info?domain={}` | 域名安全检查 | `src/tools/WebFetchTool/utils.ts` |
| `/api/claude_code/settings` | 设置同步 | `src/services/settingsSync/index.ts` |
| `/api/claude_code/managed_settings` | 企业托管设置 (1h 轮询) | `src/services/remoteManagedSettings/index.ts` |
| `/api/claude_code/team_memory?repo={}` | 团队记忆同步 | `src/services/teamMemorySync/index.ts` |
| `/api/auth/trusted_devices` | 可信设备注册 | `src/bridge/trustedDevice.ts` |
| `/api/organizations/{id}/claude_code/buddy_react` | Companion 反应 | `src/buddy/companionReact.ts` |
| `/mcp-registry/v0/servers` | MCP 服务器注册表 | `src/services/mcp/officialRegistry.ts` |
| `/v1/files` | 文件上传/下载 | `src/services/api/filesApi.ts` |
| `/v1/sessions/{id}/events` | 会话历史 | `src/assistant/sessionHistory.ts` |
| `/v1/code/triggers` | 远程触发器 | `src/tools/RemoteTriggerTool/RemoteTriggerTool.ts` |
| `/v1/organizations/{id}/mcp_servers` | 组织 MCP 配置 | `src/services/mcp/claudeai.ts` |
## 非 Anthropic 远程域名汇总
| 域名 | 服务 | 协议 |
|---|---|---|
| `bedrock-runtime.*.amazonaws.com` | AWS Bedrock | HTTPS |
| `{region}-aiplatform.googleapis.com` | Google Vertex AI | HTTPS |
| `{resource}.services.ai.azure.com` | Azure Foundry | HTTPS |
| `www.bing.com` | Bing 搜索 | HTTPS |
| `search.brave.com` | Brave 搜索 | HTTPS |
| `storage.googleapis.com` | 自动更新 | HTTPS |
| `raw.githubusercontent.com` | Changelog / 插件统计 | HTTPS |
| `bridge.claudeusercontent.com` | Chrome Bridge | WSS |
| `platform.claude.com` | OAuth 授权页 | HTTPS |
| `claude.com` / `claude.ai` | OAuth / 下载 | HTTPS |
| `claude.fedstart.com` | FedStart OAuth | HTTPS |

189
docs/features/acp-zed.md Normal file
View File

@@ -0,0 +1,189 @@
# ACP (Agent Client Protocol) — Zed / IDE 集成
> Feature Flag: `FEATURE_ACP=1`build 和 dev 模式默认启用)
> 实现状态:可用(支持 Zed、Cursor 等 ACP 客户端)
> 源码目录:`src/services/acp/`
## 一、功能概述
ACP (Agent Client Protocol) 是一种标准化的 stdio 协议,允许 IDE 和编辑器通过 stdin/stdout 的 NDJSON 流驱动 AI Agent。CCB 实现了完整的 ACP agent 端,可以被 Zed、Cursor 等支持 ACP 的客户端直接调用。
### 核心特性
- **会话管理**:新建 / 恢复 / 加载 / 分叉 / 关闭会话
- **历史回放**:恢复会话时自动加载并回放对话历史
- **权限桥接**ACP 客户端的权限决策映射到 CCB 的工具权限系统
- **斜杠命令 & Skills**:加载真实命令列表,支持 `/commit``/review` 等 prompt 型 skill
- **Context Window 跟踪**:精确的 usage_update含 model prefix matching
- **Prompt 排队**:支持连续发送多条 prompt自动排队处理
- **模式切换**auto / default / acceptEdits / plan / dontAsk / bypassPermissions
- **模型切换**:运行时切换 AI 模型
## 二、架构
```
┌──────────────┐ NDJSON/stdio ┌──────────────────┐
│ Zed / IDE │ ◄────────────────► │ CCB ACP Agent │
│ (Client) │ stdin / stdout │ (Agent) │
└──────────────┘ │ │
│ entry.ts │ ← stdio → NDJSON stream
│ agent.ts │ ← ACP protocol handler
│ bridge.ts │ ← SDKMessage → ACP SessionUpdate
│ permissions.ts │ ← 权限桥接
│ utils.ts │ ← 通用工具
│ │
│ QueryEngine │ ← 内部查询引擎
└──────────────────┘
```
### 文件职责
| 文件 | 职责 |
|------|------|
| `entry.ts` | 入口,创建 stdio → NDJSON stream启动 `AgentSideConnection` |
| `agent.ts` | 实现 ACP `Agent` 接口:会话 CRUD、prompt、cancel、模式/模型切换 |
| `bridge.ts` | `SDKMessage` → ACP `SessionUpdate` 转换:文本/思考/工具/用量/编辑 diff |
| `permissions.ts` | ACP `requestPermission()` → CCB `CanUseToolFn` 桥接 |
| `utils.ts` | Pushable、流转换、权限模式解析、session fingerprint、路径显示 |
## 三、配置 Zed 编辑器
### 3.1 Zed settings.json 配置
打开 Zed 的 `settings.json``Cmd+,` → Open Settings添加 `agent_servers` 配置:
```json
{
"agent_servers": {
"ccb": {
"type": "custom",
"command": "ccb",
"args": ["--acp"]
}
}
}
```
### 3.3 API 认证配置
CCB 的 ACP agent 在启动时会自动加载 `settings.json` 中的环境变量(`ANTHROPIC_BASE_URL``ANTHROPIC_AUTH_TOKEN` 等)。确保已通过 `/login` 配置好 API 供应商。
也可通过环境变量传入:
```json
{
"agent_servers": {
"claude-code": {
"command": "ccb",
"args": ["--acp"],
"env": {
"ANTHROPIC_BASE_URL": "https://api.example.com/v1",
"ANTHROPIC_AUTH_TOKEN": "sk-xxx"
}
}
}
}
```
### 3.4 在 Zed 中使用
1. 配置完成后重启 Zed
2. 打开任意项目目录
3.`Cmd+'`macOS`Ctrl+'`Linux打开 Agent Panel
4. 在 Agent Panel 顶部的下拉菜单中选择 **claude-code**
5. 开始对话
### 3.5 功能说明
| 功能 | 操作 |
|------|------|
| 对话 | 在 Agent Panel 中直接输入消息 |
| 斜杠命令 | 输入 `/` 查看可用 skills 列表(如 `/commit``/review` |
| 工具权限 | 弹出权限请求时选择 Allow / Reject / Always Allow |
| 模式切换 | 通过 Agent Panel 的设置菜单切换 auto/default/plan 等模式 |
| 模型切换 | 通过 Agent Panel 的设置菜单切换 AI 模型 |
| 会话恢复 | 关闭重开 Zed 后,之前的会话可自动恢复(含历史消息) |
## 四、配置其他 ACP 客户端
ACP 是开放协议,任何支持 ACP 的客户端都可以连接 CCB。通用配置模式
```
命令: ccb --acp
参数: ["--acp"]
通信: stdin/stdout NDJSON
协议版本: ACP v1
```
### 4.1 Cursor
在 Cursor 的设置中配置 MCP / Agent Server使用同样的 `ccb --acp` 命令。
### 4.2 自定义客户端
使用 `@agentclientprotocol/sdk` 可以快速构建 ACP 客户端:
```typescript
import { ClientSideConnection, ndJsonStream } from '@agentclientprotocol/sdk'
// 创建连接(将 ccb --acp 作为子进程启动)
const child = spawn('ccb', ['--acp'])
const stream = ndJsonStream(
Writable.toWeb(child.stdin),
Readable.toWeb(child.stdout),
)
const client = new ClientSideConnection(stream)
// 初始化
await client.initialize({ clientCapabilities: {} })
// 创建会话
const { sessionId } = await client.newSession({
cwd: '/path/to/project',
})
// 发送 prompt
const response = await client.prompt({
sessionId,
prompt: [{ type: 'text', text: 'Hello, explain this project' }],
})
// 监听 session 更新
client.on('sessionUpdate', (update) => {
console.log('Update:', update)
})
```
## 五、ACP 协议支持矩阵
| 方法 | 状态 | 说明 |
|------|------|------|
| `initialize` | ✅ | 返回 agent 信息和能力 |
| `authenticate` | ✅ | 无需认证(自托管) |
| `newSession` | ✅ | 创建新会话 |
| `resumeSession` | ✅ | 恢复已有会话(含历史回放) |
| `loadSession` | ✅ | 加载指定会话(含历史回放) |
| `listSessions` | ✅ | 列出可用会话 |
| `forkSession` | ✅ | 分叉会话 |
| `closeSession` | ✅ | 关闭会话 |
| `prompt` | ✅ | 发送消息,支持排队 |
| `cancel` | ✅ | 取消当前/排队的 prompt |
| `setSessionMode` | ✅ | 切换权限模式 |
| `setSessionModel` | ✅ | 切换 AI 模型 |
| `setSessionConfigOption` | ✅ | 动态修改配置 |
### SessionUpdate 类型
| 类型 | 状态 | 说明 |
|------|------|------|
| `agent_message_chunk` | ✅ | 助手文本消息 |
| `agent_thought_chunk` | ✅ | 思考/推理内容 |
| `user_message_chunk` | ✅ | 用户消息(历史回放) |
| `tool_call` | ✅ | 工具调用开始 |
| `tool_call_update` | ✅ | 工具调用结果/状态更新 |
| `usage_update` | ✅ | token 用量 + context window |
| `plan` | ✅ | TodoWrite → plan entries |
| `available_commands_update` | ✅ | 斜杠命令 & skills 列表 |
| `current_mode_update` | ✅ | 模式切换通知 |
| `config_option_update` | ✅ | 配置更新通知 |

View File

@@ -0,0 +1,562 @@
# Claude Code Best (CCB) — 全功能使用指南
本文档覆盖我们通过 13 个 PR 为 CCB 恢复/新增的**全部功能**,按类别组织,每个功能包含说明、使用方法和示例。
---
## 目录
1. [Buddy 伴侣系统](#1-buddy-伴侣系统)
2. [Remote Control 远程控制](#2-remote-control-远程控制)
3. [定时任务 /schedule](#3-定时任务-schedule)
4. [Voice Mode 语音模式](#4-voice-mode-语音模式)
5. [Chrome 浏览器控制](#5-chrome-浏览器控制)
6. [Computer Use 屏幕操控](#6-computer-use-屏幕操控)
7. [Feature Flags 与 GrowthBook](#7-feature-flags-与-growthbook)
8. [/ultraplan 高级规划](#8-ultraplan-高级规划)
9. [Daemon 后台守护](#9-daemon-后台守护)
10. [Pipe IPC 多实例协作](#10-pipe-ipc-多实例协作)
11. [LAN Pipes 局域网群控](#11-lan-pipes-局域网群控)
12. [Monitor 后台监控](#12-monitor-后台监控)
13. [Workflow 工作流脚本](#13-workflow-工作流脚本)
14. [Coordinator 多Worker协调](#14-coordinator-多worker协调)
15. [Proactive 自主模式](#15-proactive-自主模式)
16. [History / Snip 历史管理](#16-history--snip-历史管理)
17. [Fork 子Agent](#17-fork-子agent)
18. [其他恢复的工具](#18-其他恢复的工具)
---
## 1. Buddy 伴侣系统
**PR**: #82 `refactor(buddy): align companion system with official CLI`
**Feature Flag**: `BUDDY`
### 说明
Buddy 是一个后台运行的伴侣 AI在你主对话进行的同时异步观察会话内容并提供建议。
### 使用
```bash
# 启动时自动加载feature 默认开启)
bun run dev
# 在对话中Buddy 会在适当时机自动提供建议
# 例如当你在调试时Buddy 可能提示你检查日志
```
---
## 2. Remote Control 远程控制
**PR**: #60 `feat: enable Remote Control (BRIDGE_MODE)` + #170 `feat: restore daemon supervisor`
**Feature Flag**: `BRIDGE_MODE`
### 说明
通过 WebSocket 远程控制 Claude Code 会话。支持自托管私有部署。
### 使用
```bash
# 启动远程控制模式
bun run dev -- remote-control
# 使用自托管服务器
CLAUDE_BRIDGE_BASE_URL=https://your-server.com CLAUDE_BRIDGE_OAUTH_TOKEN=your-token bun run dev --remote-control
# 或通过 /remote-control 命令在会话中启动
/remote-control
```
### 命令
- `claude remote-control` / `claude rc` — 启动远程控制客户端
- `claude bridge` — 同上(别名)
---
## 3. 定时任务 /schedule
**PR**: #88 `feat: enable /schedule by adding AGENT_TRIGGERS_REMOTE`
**Feature Flag**: `AGENT_TRIGGERS_REMOTE`
### 说明
创建定时执行的远程 agent 任务,支持 cron 表达式。
### 使用
```
/schedule create "每天检查依赖更新" --cron "0 9 * * *" --prompt "检查 package.json 中的过期依赖并创建更新 PR"
/schedule list — 列出所有定时任务
/schedule delete <id> — 删除指定任务
```
---
## 4. Voice Mode 语音模式
**PR**: #92 `feat: enable /voice mode with native audio binaries`
**Feature Flag**: `VOICE_MODE`
### 说明
Push-to-Talk 语音输入,音频通过 WebSocket 流式传输到 Anthropic STTNova 3。需要 Anthropic OAuth 认证(非 API key
### 使用
```bash
# 确保已通过 OAuth 登录
claude auth login
# 在会话中按住指定键说话
# 松开后自动转写为文字输入
```
### 前提条件
- Anthropic OAuth 认证(不支持 API key 模式)
- 系统麦克风权限
---
## 5. Chrome 浏览器控制
**PR**: #93 `feat: enable Claude in Chrome MCP with full browser control`
**Feature Flag**: `CHICAGO_MCP`
### 说明
通过 Chrome 扩展控制浏览器:导航、点击、填表、截图、执行 JS。
### 使用
```bash
# 启动带 Chrome 控制的模式
bun run dev -- --chrome
# 安装 Chrome 扩展后AI 可以:
# - 打开网页、点击按钮
# - 填写表单
# - 截取页面内容
# - 执行 JavaScript
```
### AI 可用工具
- `navigate` — 导航到 URL
- `click` / `find` / `form_input` — 页面交互
- `get_page_text` / `read_page` — 读取内容
- `javascript_tool` — 执行 JS
- `gif_creator` — 录制操作 GIF
---
## 6. Computer Use 屏幕操控
**PR**: #98 + #137 `feat: Computer Use — 跨平台 Executor + Python Bridge + GUI 无障碍`
**Feature Flag**: `CHICAGO_MCP`
### 说明
跨平台屏幕操控:截图、键鼠模拟、应用管理。支持 macOS + WindowsLinux 后端待完成。
### 使用
```bash
# 启动后 AI 可自动调用屏幕操控工具
bun run dev
# AI 可以:
# - 截取屏幕/窗口截图
# - 模拟键盘输入和鼠标操作
# - 列出运行的应用
# - 使用剪贴板
```
### 平台支持
| 平台 | 截图 | 键鼠 | 应用管理 |
|------|------|------|----------|
| macOS | ✅ | ✅ | ✅ |
| Windows | ✅ | ✅ | ✅ |
| Linux | ⏳ | ⏳ | ⏳ |
---
## 7. Feature Flags 与 GrowthBook
**PR**: #140 + #153 `feat: enable GrowthBook local gate defaults`
**Feature Flags**: `SHOT_STATS`, `PROMPT_CACHE_BREAK_DETECTION`, `TOKEN_BUDGET`
### 说明
本地 GrowthBook gate defaults 机制,绕过远程 feature flag 服务,确保功能在无网络时也可使用。
### 使用
```bash
# 通过环境变量启用任意 feature
FEATURE_PROACTIVE=1 bun run dev
# dev/build 模式有各自的默认启用列表
# 查看 scripts/dev.ts 中的 DEFAULT_FEATURES
```
### 关键 feature flags
| Flag | 说明 |
|------|------|
| `SHOT_STATS` | API 调用统计 |
| `TOKEN_BUDGET` | Token 预算控制 |
| `PROMPT_CACHE_BREAK_DETECTION` | Prompt 缓存命中检测 |
---
## 8. /ultraplan 高级规划
**PR**: #156 `feat: enable /ultraplan and harden GrowthBook fallback chain`
**Feature Flag**: `ULTRAPLAN`
### 说明
高级多 agent 规划模式。将复杂任务分解为多个阶段,每阶段可分配给不同 agent 并行执行。
### 使用
```
/ultraplan 实现一个完整的用户认证系统包括注册、登录、密码重置、OAuth 集成
```
AI 会生成:
1. 任务分解(多阶段)
2. 每阶段的 agent 分配
3. 依赖关系图
4. 并行执行计划
---
## 9. Daemon 后台守护
**PR**: #170 `feat: restore daemon supervisor and remoteControlServer command`
**Feature Flag**: `DAEMON`
### 说明
Daemon 模式允许 Claude Code 作为后台长驻进程运行,管理多个 worker。
### 使用
```bash
# 启动 daemon
claude daemon start
# 查看状态
claude daemon status
# 停止
claude daemon stop
# 启动远程控制服务器
bun run rcs
```
---
## 10. Pipe IPC 多实例协作
**PR**: #241 `feat: restore pipe IPC, LAN pipes, monitor tool`
**Feature Flag**: `UDS_INBOX`
### 说明
同一台机器上的多个 Claude Code 实例通过 UDSUnix Domain Socket / Windows Named Pipe自动发现并协作。首个启动的实例成为 main后续自动注册为 sub。
### 使用
**启动多实例**
```bash
# 终端 1
bun run dev
# → 自动成为 main
# 终端 2
bun run dev
# → 自动成为 sub-1被 main attach
```
**管理实例**
```
/pipes — 显示所有实例Shift+↓ 展开选择面板
/pipes select <name> — 选中实例
/pipes all — 全选
/pipes none — 取消全选
/attach <name> — 手动 attach 某实例
/detach <name> — 断开连接
/send <name> <msg> — 向指定实例发送消息
/claim-main — 强制声明为 main
/pipe-status — 显示详细状态
/peers — 列出所有已发现的 peer
```
**选择面板操作**
1.`Shift+↓` 展开面板
2. `↑/↓` 移动光标
3. `Space` 选中/取消 pipe
4. `Enter` 确认关闭
5. `←/→` 切换路由模式selected pipes ↔ local main
**消息广播**
选中 pipe 后,输入的消息自动路由到所有选中的 slave 执行,结果流式回传到 main。
**权限转发**
slave 执行需要权限的工具时(如 BashTool权限请求自动转发到 main 的确认队列。
---
## 11. LAN Pipes 局域网群控
**PR**: #241(同上)
**Feature Flag**: `LAN_PIPES`
### 说明
在 Pipe IPC 基础上增加 TCP 传输层和 UDP Multicast 发现,实现跨机器零配置协作。
### 使用
**局域网多机器**
```bash
# 机器 A (192.168.50.22)
bun run dev
# 机器 B (192.168.50.27)
bun run dev
# 两边启动后 3-5 秒自动发现和 attach
# /pipes 显示 [LAN] 标记的远端实例
```
**防火墙配置**(每台机器都需要):
Windows管理员 PowerShell
```powershell
New-NetFirewallRule -DisplayName "CCB LAN Beacon (UDP)" -Direction Inbound -Protocol UDP -LocalPort 7101 -Action Allow -Profile Private
New-NetFirewallRule -DisplayName "CCB LAN Pipes (TCP)" -Direction Inbound -Protocol TCP -LocalPort 1024-65535 -Program (Get-Command bun).Source -Action Allow -Profile Private
New-NetFirewallRule -DisplayName "CCB LAN Beacon Out (UDP)" -Direction Outbound -Protocol UDP -RemotePort 7101 -Action Allow -Profile Private
```
macOS
```bash
# 首次运行时系统弹对话框,点"允许"即可
```
Linux
```bash
sudo firewall-cmd --zone=trusted --add-port=7101/udp --permanent
sudo firewall-cmd --zone=trusted --add-port=1024-65535/tcp --permanent
sudo firewall-cmd --reload
```
**通知显示格式**
```
# 本机 sub
Routed to [sub-1]; main can continue other tasks
# LAN peer
Routed to [main] vmwin11/192.168.50.27; main can continue other tasks
```
---
## 12. Monitor 后台监控
**PR**: #241(同上)
**Feature Flag**: `MONITOR_TOOL`
### 说明
在后台运行 shell 命令持续监控输出(类似 `watch` 命令。AI 也可自主调用 MonitorTool。
### 使用
**用户命令**
```
/monitor tail -f /var/log/syslog
/monitor watch -n 5 docker ps
/monitor "while true; do curl -s localhost:3000/health; sleep 10; done"
```
**查看监控**
-`Shift+Down` 展开后台任务面板
- 查看监控输出和状态
**Windows 兼容**
`watch -n <sec> <cmd>` 自动转为 PowerShell 循环:
```powershell
while($true){ <cmd>; Start-Sleep -Seconds <sec> }
```
**AI 调用**
AI 可在对话中自动调用 `MonitorTool` 监控日志、构建输出等。
---
## 13. Workflow 工作流脚本
**PR**: #241(同上)
**Feature Flag**: `WORKFLOW_SCRIPTS`
### 说明
执行 `.claude/workflows/` 目录下的用户定义工作流脚本。
### 使用
**创建工作流**
```bash
mkdir -p .claude/workflows
cat > .claude/workflows/deploy.sh << 'EOF'
#!/bin/bash
echo "Running tests..."
bun test
echo "Building..."
bun run build
echo "Deploying..."
EOF
chmod +x .claude/workflows/deploy.sh
```
**列出可用工作流**
```
/workflows
```
**AI 调用**
AI 可通过 `WorkflowTool` 自动执行工作流:
```
请执行 deploy 工作流
```
---
## 14. Coordinator 多Worker协调
**PR**: #241(同上)
**Feature Flag**: `COORDINATOR_MODE`
### 说明
启用 coordinator 模式后AI 可自动将任务分配给多个 worker 并行执行。
### 使用
```
/coordinator — 切换 coordinator 模式开/关
```
启用后AI 在处理复杂任务时会:
1. 分析任务可并行的部分
2. 自动创建 worker 分支
3. 分配子任务
4. 汇总结果
---
## 15. Proactive 自主模式
**PR**: #241(同上)
**Feature Flag**: `PROACTIVE` / `KAIROS`
### 说明
启用后 AI 会主动发起操作(而不仅回应用户输入),例如自动检测文件变更、主动提出优化建议。
### 使用
```
/proactive — 切换 proactive 模式开/关
```
---
## 16. History / Snip 历史管理
**PR**: #241(同上)
**Feature Flag**: `HISTORY_SNIP`
### 说明
查看和管理对话历史,支持手动截断以释放上下文窗口空间。
### 使用
```
/history — 显示对话历史摘要
/force-snip — 强制在当前位置截断历史
```
AI 也可通过 `SnipTool` 自动截断过长的对话:
```
对话太长了,请帮我截断历史
```
---
## 17. Fork 子Agent
**PR**: #241(同上)
**Feature Flag**: `FORK_SUBAGENT`
### 说明
在当前对话上下文中 fork 一个独立的子 agent继承完整会话状态独立执行。
### 使用
```
/fork — 基于当前上下文 fork 子 agent
```
子 agent 会:
- 继承当前的全部对话历史
- 在独立的执行环境中运行
- 不影响主会话状态
---
## 18. 其他恢复的工具
以下工具从 stub 恢复为完整实现:
| 工具 | 说明 | 使用 |
|------|------|------|
| `SleepTool` | 暂停执行指定时间 | AI 在轮询场景自动调用 |
| `WebBrowserTool` | 终端内网页交互 | AI 需要查看网页时调用 |
| `SubscribePRTool` | 订阅 GitHub PR 变更 | `/subscribe-pr` 或 AI 调用 |
| `PushNotificationTool` | 推送桌面通知 | AI 在长任务完成时调用 |
| `CtxInspectTool` | 检查上下文窗口使用 | AI 判断上下文剩余空间 |
| `TerminalCaptureTool` | 截取终端屏幕 | AI 需要看终端输出时调用 |
| `SendUserFileTool` | 向用户发送文件 | AI 导出文件时调用 |
| `REPLTool` | 启动子 REPL 会话 | AI 需要独立交互环境时调用 |
| `VerifyPlanExecutionTool` | 验证执行计划完成度 | AI 完成计划后自动验证 |
| `SuggestBackgroundPRTool` | 建议创建后台 PR | AI 发现可独立的变更时提议 |
| `ListPeersTool` | 列出已发现的 peer | AI 查询多实例状态时调用 |
---
## 附录:全部 Feature Flags
| Flag | 默认 | 说明 |
|------|------|------|
| `BUDDY` | ✅ dev/build | 伴侣系统 |
| `BRIDGE_MODE` | ✅ dev/build | 远程控制 |
| `VOICE_MODE` | ✅ dev/build | 语音模式 |
| `CHICAGO_MCP` | ✅ dev/build | Computer Use + Chrome |
| `AGENT_TRIGGERS_REMOTE` | ✅ dev/build | 定时任务 |
| `SHOT_STATS` | ✅ dev/build | API 统计 |
| `TOKEN_BUDGET` | ✅ dev/build | Token 预算 |
| `PROMPT_CACHE_BREAK_DETECTION` | ✅ dev/build | 缓存检测 |
| `ULTRAPLAN` | ✅ dev/build | 高级规划 |
| `DAEMON` | ✅ dev/build | 后台守护 |
| `UDS_INBOX` | ✅ dev/build | Pipe IPC |
| `LAN_PIPES` | ✅ dev/build | LAN 群控 |
| `MONITOR_TOOL` | ✅ dev/build | 后台监控 |
| `WORKFLOW_SCRIPTS` | ✅ dev/build | 工作流脚本 |
| `FORK_SUBAGENT` | ✅ dev/build | 子 Agent |
| `KAIROS` | ✅ dev/build | Kairos 调度 |
| `COORDINATOR_MODE` | ✅ dev/build | 多 Worker |
| `HISTORY_SNIP` | ✅ dev/build | 历史管理 |
| `CONTEXT_COLLAPSE` | ✅ dev/build | 上下文折叠 |
手动启用任意 flag
```bash
FEATURE_FLAG_NAME=1 bun run dev
```
---
## 附录PR 列表
| PR | 日期 | 标题 |
|----|------|------|
| #60 | 2026-04-02 | feat: enable Remote Control (BRIDGE_MODE) |
| #82 | 2026-04-03 | refactor(buddy): align companion system |
| #88 | 2026-04-03 | feat: enable /schedule (AGENT_TRIGGERS_REMOTE) |
| #89 | 2026-04-03 | feat: built-in status line |
| #92 | 2026-04-03 | feat: enable /voice mode |
| #93 | 2026-04-03 | feat: enable Chrome MCP |
| #98 | 2026-04-03 | feat: enable Computer Use (macOS + Windows + Linux) |
| #137 | 2026-04-05 | feat: Computer Use v2 — 跨平台 Executor |
| #140 | 2026-04-05 | feat: enable SHOT_STATS, TOKEN_BUDGET |
| #153 | 2026-04-06 | feat: enable GrowthBook local gate defaults |
| #156 | 2026-04-06 | feat: enable /ultraplan |
| #170 | 2026-04-07 | feat: restore daemon supervisor |
| #241 | 2026-04-11 | feat: restore pipe IPC, LAN pipes, monitor tool |

182
docs/features/auto-dream.md Normal file
View File

@@ -0,0 +1,182 @@
# Auto Dream — 自动记忆整理
## 概述
Auto Dream 是 Claude Code 的后台记忆整合机制。它在会话间自动审查、组织和修剪持久化记忆文件,确保未来会话能快速获得准确的上下文。
记忆系统存储在文件系统中(默认 `~/.claude/projects/<project-slug>/memory/`),由 `MEMORY.md` 索引文件和若干主题文件(如 `user_language.md``project_overview.md`组成。随着会话积累记忆会变得过时、冗余或矛盾——Dream 负责清理这些堆积。
## 架构
### 核心模块
| 模块 | 路径 | 职责 |
|------|------|------|
| 调度器 | `src/services/autoDream/autoDream.ts` | 时间/会话/锁三重门控,触发 forked agent |
| 配置 | `src/services/autoDream/config.ts` | 读取 `isAutoDreamEnabled()` 开关 |
| 提示词 | `src/services/autoDream/consolidationPrompt.ts` | 构建 4 阶段整理提示词 |
| 锁文件 | `src/services/autoDream/consolidationLock.ts` | PID 锁 + mtime 作为 `lastConsolidatedAt` |
| 任务 UI | `src/tasks/DreamTask/DreamTask.ts` | 后台任务注册footer pill + Shift+Down 可见 |
| 手动入口 | `src/skills/bundled/dream.ts` | `/dream` 命令,无条件可用 |
### 记忆路径解析
优先级(`src/memdir/paths.ts`
1. `CLAUDE_COWORK_MEMORY_PATH_OVERRIDE` 环境变量(完整路径覆盖)
2. `autoMemoryDirectory` 设置项(`settings.json`,支持 `~/` 展开)
3. 默认:`<memoryBase>/projects/<sanitized-git-root>/memory/`
其中 `memoryBase` = `CLAUDE_CODE_REMOTE_MEMORY_DIR``~/.claude`
## 触发机制
### 自动触发Auto Dream
每个对话轮次结束后,`executeAutoDream()` 按顺序检查三重门控:
```
┌─────────────────────────────────────────────────────┐
│ Gate 1: 全局开关 │
│ isAutoMemoryEnabled() && isAutoDreamEnabled() │
│ 排除: KAIROS 模式 / Remote 模式 │
├─────────────────────────────────────────────────────┤
│ Gate 2: 时间门控 │
│ hoursSince(lastConsolidatedAt) >= minHours │
│ 默认: 24 小时 │
├─────────────────────────────────────────────────────┤
│ Gate 3: 会话门控 │
│ sessionsTouchedSince(lastConsolidatedAt) >= minSessions │
│ 默认: 5 个会话(排除当前会话) │
├─────────────────────────────────────────────────────┤
│ Lock: PID 锁文件 │
│ .consolidate-lock (mtime = lastConsolidatedAt) │
│ 死进程检测 + 1 小时过期 │
└─────────────────────────────────────────────────────┘
```
全部通过后,以 **forked agent**(受限子代理)方式运行整理任务:
- Bash 工具限制为只读命令(`ls``grep``cat` 等)
- 只能读写记忆目录内的文件
- 用户可在 Shift+Down 后台任务面板中查看进度或终止
### 手动触发(`/dream` 命令)
通过 `/dream` 命令随时触发,无门控限制:
- 在主循环中运行(非 forked agent拥有完整工具权限
- 用户可实时观察操作过程
- 执行前自动更新锁文件 mtime
### 配置开关
| 开关 | 位置 | 作用 |
|------|------|------|
| `autoDreamEnabled` | `settings.json` | `true`/`false` 显式开关 |
| `autoMemoryEnabled` | `settings.json` | 总开关,关闭后所有记忆功能禁用 |
| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | 环境变量 | `1`/`true` 关闭所有记忆功能 |
| `tengu_onyx_plover` | GrowthBook | 官方远程配置,控制 `enabled`/`minHours`/`minSessions` |
默认值(无 GrowthBook 连接时):
```typescript
minHours: 24 // 距上次整理至少 24 小时
minSessions: 5 // 至少有 5 个新会话
```
## 整理流程4 阶段)
Dream agent 执行的提示词包含 4 个阶段:
### Phase 1 — 定位Orient
- `ls` 记忆目录,查看现有文件
- 读取 `MEMORY.md` 索引
- 浏览现有主题文件,避免重复创建
### Phase 2 — 采集信号Gather
按优先级收集新信息:
1. **日志文件**`logs/YYYY/MM/YYYY-MM-DD.md`KAIROS 模式下的追加式日志)
2. **过时记忆** — 与当前代码库状态矛盾的事实
3. **会话记录** — 窄关键词 grep JSONL 文件(不全文读取)
### Phase 3 — 整合Consolidate
- 合并新信号到现有主题文件,而非创建近似重复
- 将相对日期("昨天"、"上周")转为绝对日期
- 删除被推翻的事实
### Phase 4 — 修剪与索引Prune
- `MEMORY.md` 保持在 200 行以内、25KB 以内
- 每条索引项一行,不超过 150 字符
- 移除过时/错误/被取代的指针
## 记忆类型
记忆系统使用 4 种类型(`src/memdir/memoryTypes.ts`
| 类型 | 用途 | 示例 |
|------|------|------|
| `user` | 用户角色、偏好、知识 | 用户是高级后端工程师,偏好中文交流 |
| `feedback` | 工作方式指导 | 不要 mock 数据库测试;代码审查用 bundled PR |
| `project` | 项目上下文(非代码可推导的) | 合并冻结从 3 月 5 日开始;认证重写是合规需求 |
| `reference` | 外部系统指针 | Linear INGEST 项目跟踪 pipeline bugs |
**不保存的内容**代码模式、架构、文件路径可从代码推导Git 历史(`git log` 权威);调试方案(代码中已有)。
## 锁文件机制
`.consolidate-lock` 文件位于记忆目录内:
- **文件内容**:持有者 PID
- **mtime**:即 `lastConsolidatedAt` 时间戳
- **过期**1 小时(防 PID 复用)
- **竞态处理**:双进程同时写入时,后读验证 PID失败者退出
- **回滚**forked agent 失败或被用户终止时mtime 回退到获取前的值
## 使用场景
### 场景 1日常开发中的自动整理
开发者连续多天使用 Claude Code 处理不同任务。Auto Dream 在积累 5+ 个会话且距上次整理 24 小时后自动触发,整合分散在多次会话中的用户偏好和项目决策。
### 场景 2手动整理记忆
用户发现 Claude 重复犯相同错误或遗忘之前的决策。输入 `/dream` 立即触发整理,无需等待自动触发周期。
### 场景 3新会话快速上下文
新会话启动时,`MEMORY.md` 被加载到上下文中。经过 Dream 整理的记忆文件结构清晰、信息准确,让 Claude 快速了解用户和项目。
### 场景 4KAIROS 模式下的日志蒸馏
KAIROS长驻助手模式agent 以追加方式写入日期日志文件。Dream 负责将这些日志蒸馏为主题文件和 `MEMORY.md` 索引。
## 与其他系统的关系
```
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ 会话交互 │────▶│ 记忆写入 │────▶│ MEMORY.md │
│ (主 agent) │ │ (即时保存) │ │ + 主题文件 │
└─────────────┘ └──────────────┘ └───────┬───────┘
┌───────────────────────────────────────┘
┌──────────────┐ ┌──────────────┐
│ Auto Dream │────▶│ 整理/修剪 │
│ (后台触发) │ │ 去重/纠错 │
└──────────────┘ └──────────────┘
┌──────────────┐
│ /dream 命令 │
│ (手动触发) │
└──────────────┘
```
- **extractMemories**`src/services/extractMemories/`每轮次结束时从对话中提取新记忆并写入。Dream 不负责提取,只负责整理。
- **CLAUDE.md**:项目级指令文件,加载到上下文中但不属于记忆系统。
- **Team Memory**`TEAMMEM` feature团队共享记忆目录与个人记忆使用相同的 Dream 机制。

View File

@@ -0,0 +1,107 @@
# BASH_CLASSIFIER — Bash 命令分类器
> Feature Flag: `FEATURE_BASH_CLASSIFIER=1`
> 实现状态bashClassifier.ts 全部 StubyoloClassifier.ts 完整实现可参考
> 引用数45
## 一、功能概述
BASH_CLASSIFIER 使用 LLM 对 bash 命令进行意图分类(允许/拒绝/询问),实现自动权限决策。用户不需要逐个审批 bash 命令,分类器根据命令内容和上下文自动判断安全性。
### 核心特性
- **LLM 驱动分类**:使用 Opus 模型评估命令安全性
- **两阶段分类**:快速阻止/允许 → 深度思考链
- **自动审批**:分类器判定安全的命令自动通过
- **UI 集成**:权限对话框显示分类器状态和审核选项
## 二、实现架构
### 2.1 模块状态
| 模块 | 文件 | 状态 | 说明 |
|------|------|------|------|
| Bash 分类器 | `src/utils/permissions/bashClassifier.ts` | **Stub** | 所有函数返回空操作。注释:"ANT-ONLY" |
| YOLO 分类器 | `src/utils/permissions/yoloClassifier.ts` | **完整** | 1496 行,两阶段 XML 分类器 |
| 审批信号 | `src/utils/classifierApprovals.ts` | **完整** | Map + 信号管理分类器决策 |
| 权限 UI | `src/components/permissions/BashPermissionRequest.tsx` | **布线** | 分类器状态显示、审核选项 |
| 权限管道 | `src/hooks/toolPermission/handlers/*.ts` | **布线** | 分类器结果路由到决策 |
| API beta 标头 | `src/services/api/withRetry.ts` | **布线** | 启用时发送 `bash_classifier` beta |
### 2.2 参考实现yoloClassifier.ts
文件:`src/utils/permissions/yoloClassifier.ts`1496 行)
这是已实现的完整分类器,可作为 bashClassifier.ts 的参考:
```
两阶段分类:
1. 快速阶段:构建对话记录 → 调用 sideQueryOpus→ 快速阻止/允许
2. 深度阶段:思考链分析 → 最终决策
```
特性:
- 构建完整对话记录上下文
- 调用安全系统提示的 sideQuery
- GrowthBook 配置和指标
- 错误处理和降级
### 2.3 分类器在权限管道中的位置
```
bash 命令到达
bashPermissions.ts 权限检查
├── 传统规则匹配(字符串级别)
└── [BASH_CLASSIFIER] LLM 分类
├── allow → 自动通过
├── deny → 自动拒绝
└── ask → 显示权限对话框
├── 分类器自动审批标记
└── 审核选项(用户可覆盖)
```
## 三、需要补全的内容
| 函数 | 需要实现 | 说明 |
|------|---------|------|
| `classifyBashCommand()` | LLM 调用评估安全性 | 参考 yoloClassifier.ts 的两阶段模式 |
| `isClassifierPermissionsEnabled()` | GrowthBook/配置检查 | 控制分类器是否激活 |
| `getBashPromptDenyDescriptions()` | 返回基于提示的拒绝规则 | 权限设置描述 |
| `getBashPromptAskDescriptions()` | 返回询问规则 | 需要用户确认的命令 |
| `getBashPromptAllowDescriptions()` | 返回允许规则 | 自动通过的命令 |
| `generateGenericDescription()` | LLM 生成命令描述 | 为权限对话框提供说明 |
| `extractPromptDescription()` | 解析规则内容 | 从规则中提取描述 |
## 四、关键设计决策
1. **ANT-ONLY 标记**bashClassifier.ts 标注为 "ANT-ONLY",可能是 Anthropic 内部服务端分类器的客户端适配
2. **两阶段分类**:快速阶段处理明确情况(减少延迟),深度阶段处理模糊情况
3. **分类器结果可审核**:权限 UI 显示分类器决策,用户可覆盖
4. **YOLO 分类器参考**yoloClassifier.ts 提供完整的分类器实现模式,可直接参考
## 五、使用方式
```bash
# 启用 feature
FEATURE_BASH_CLASSIFIER=1 bun run dev
# 配合 TREE_SITTER_BASH 使用AST + LLM 双重安全)
FEATURE_BASH_CLASSIFIER=1 FEATURE_TREE_SITTER_BASH=1 bun run dev
```
## 六、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/utils/permissions/bashClassifier.ts` | — | Bash 分类器stubANT-ONLY |
| `src/utils/permissions/yoloClassifier.ts` | 1496 | YOLO 分类器(完整参考实现) |
| `src/utils/classifierApprovals.ts` | — | 分类器审批信号管理 |
| `src/components/permissions/BashPermissionRequest.tsx:261-469` | — | 分类器 UI |
| `src/hooks/toolPermission/handlers/interactiveHandler.ts` | — | 交互式权限处理 |
| `src/services/api/withRetry.ts:81` | — | API beta 标头 |

View File

@@ -0,0 +1,158 @@
# BRIDGE_MODE — 远程控制
> Feature Flag: `FEATURE_BRIDGE_MODE=1`
> 实现状态完整可用v1 + v2 实现)
> 引用数28
## 一、功能概述
BRIDGE_MODE 将本地 CLI 注册为"bridge 环境",可从 claude.ai 或其他控制面远程驱动。本地终端变为一个"执行者",接受远程指令并执行。
### 核心特性
- **环境注册**:本地 CLI 向 Anthropic 服务器注册为可用的 bridge 环境
- **工作轮询**长轮询long-poll等待远程任务分配
- **会话管理**:创建、恢复、归档远程会话
- **权限透传**:远程权限请求发送到控制面,用户在 claude.ai 上批准/拒绝
- **心跳保活**:定期发送 heartbeat 延长任务租约
- **可信设备**v2 支持可信设备令牌增强安全性
## 二、实现架构
### 2.1 版本演进
| 版本 | 实现 | 特点 |
|------|------|------|
| v1env-based | `src/bridge/replBridge.ts` | 基于环境变量的传统 bridge |
| v2env-less | `src/bridge/remoteBridgeCore.ts` | 无需环境变量,更安全的 bridge |
### 2.2 API 协议
文件:`src/bridge/bridgeApi.ts`
Bridge API Client 提供 7 个核心操作:
| 操作 | HTTP | 说明 |
|------|------|------|
| `registerBridgeEnvironment` | POST `/v1/environments/bridge` | 注册本地环境,获取 `environment_id` + `environment_secret` |
| `pollForWork` | GET `/v1/environments/{id}/work/poll` | 长轮询等待任务10s 超时) |
| `acknowledgeWork` | POST `/v1/environments/{id}/work/{workId}/ack` | 确认接收任务 |
| `stopWork` | POST `/v1/environments/{id}/work/{workId}/stop` | 停止任务 |
| `heartbeatWork` | POST `/v1/environments/{id}/work/{workId}/heartbeat` | 续约任务租约 |
| `deregisterEnvironment` | DELETE `/v1/environments/bridge/{id}` | 注销环境 |
| `archiveSession` | POST `/v1/sessions/{id}/archive` | 归档会话409 = 已归档,幂等) |
| `sendPermissionResponseEvent` | POST `/v1/sessions/{id}/events` | 发送权限审批结果 |
| `reconnectSession` | POST `/v1/environments/{id}/bridge/reconnect` | 重连已存在的会话 |
### 2.3 认证流程
```
注册: OAuth Bearer Token → 获取 environment_secret
轮询: environment_secret 作为 Authorization
├── 401 → 尝试 OAuth token 刷新onAuth401
└── 刷新成功 → 重试一次
```
**OAuth 刷新**API client 内置 `withOAuthRetry` 机制。401 时调用 `handleOAuth401Error`(同 withRetry.ts 的 v1/messages 模式),刷新后重试一次。
### 2.4 安全设计
- **路径穿越防护**`validateBridgeId()` 使用 `/^[a-zA-Z0-9_-]+$/` 白名单验证所有服务端 ID
- **BridgeFatalError**不可重试的错误401/403/404/410直接抛出阻止重试循环
- **可信设备令牌**v2 通过 `X-Trusted-Device-Token` header 增强安全层级
- **幂关注册**:支持 `reuseEnvironmentId` 实现会话恢复,避免重复创建环境
### 2.5 数据流
```
claude.ai 用户选择远程环境
POST /v1/environments/bridge (注册)
◀── environment_id + environment_secret
GET .../work/poll (长轮询)
◀── WorkResponse { id, data: { type, sessionId } }
POST .../work/{id}/ack (确认)
sessionRunner 创建 REPL session
├── 权限请求 → sendPermissionResponseEvent
├── 心跳 → heartbeatWork (续约)
└── 任务完成 → 自动归档
```
### 2.6 模块结构
| 模块 | 文件 | 职责 |
|------|------|------|
| API Client | `bridgeApi.ts` | HTTP 通信(注册/轮询/确认/心跳/注销) |
| Session Runner | `sessionRunner.ts` | 创建/恢复 REPL 会话 |
| Bridge Config | `bridgeConfig.ts` | 配置管理machine name、max sessions 等) |
| Transport | `replBridgeTransport.ts` | Bridge 传输层 |
| Permission Callbacks | `bridgePermissionCallbacks.ts` | 权限请求处理 |
| Pointer | `bridgePointer.ts` | 当前活跃 bridge 状态指针 |
| Flush Gate | `flushGate.ts` | 刷新控制 |
| JWT Utils | `jwtUtils.ts` | JWT 令牌工具 |
| Trusted Device | `trustedDevice.ts` | 可信设备管理 |
| Debug Utils | `debugUtils.ts` | 调试日志 |
| Types | `types.ts` | 类型定义 |
## 三、关键设计决策
1. **长轮询而非 WebSocket**`pollForWork` 使用 HTTP GET + 10s 超时。简单可靠,无需维护 WebSocket 连接
2. **OAuth 刷新内嵌**API client 自带 `withOAuthRetry`,无需外层重试逻辑
3. **ETag 条件请求**:注册时支持 `reuseEnvironmentId` 实现幂等会话恢复
4. **v1/v2 共存**代码中同时存在两套实现v2 是更安全的升级版
5. **权限双向流动**:本地权限请求发送到 claude.ai用户在 web 上审批
## 四、使用方式
```bash
# 启用 bridge mode
FEATURE_BRIDGE_MODE=1 bun run dev
# 从 claude.ai/code 远程连接
# 在 web 界面选择已注册的环境
# 配合 DAEMON 使用(后台守护)
FEATURE_BRIDGE_MODE=1 FEATURE_DAEMON=1 bun run dev
```
## 五、外部依赖
| 依赖 | 说明 |
|------|------|
| Anthropic OAuth | claude.ai 订阅登录 |
| GrowthBook | `tengu_ccr_bridge` 门控 |
| Bridge API | `/v1/environments/bridge` 系列端点 |
## 六、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/bridge/bridgeApi.ts` | 540 | API Client核心 |
| `src/bridge/sessionRunner.ts` | — | 会话运行器 |
| `src/bridge/bridgeConfig.ts` | — | 配置管理 |
| `src/bridge/replBridgeTransport.ts` | — | 传输层 |
| `src/bridge/bridgePermissionCallbacks.ts` | — | 权限回调 |
| `src/bridge/bridgePointer.ts` | — | 状态指针 |
| `src/bridge/flushGate.ts` | — | 刷新控制 |
| `src/bridge/jwtUtils.ts` | — | JWT 工具 |
| `src/bridge/trustedDevice.ts` | — | 可信设备 |
| `src/bridge/remoteBridgeCore.ts` | — | v2 核心实现 |
| `src/bridge/types.ts` | — | 类型定义 |
| `src/bridge/debugUtils.ts` | — | 调试工具 |
| `src/bridge/pollConfigDefaults.ts` | — | 轮询配置默认值 |
| `src/bridge/bridgeUI.ts` | — | UI 组件 |
| `src/bridge/codeSessionApi.ts` | — | 代码会话 API |
| `src/bridge/peerSessions.ts` | — | 对等会话管理 |
| `src/bridge/sessionIdCompat.ts` | — | Session ID 兼容层 |
| `src/bridge/createSession.ts` | — | 会话创建 |
| `src/bridge/replBridgeHandle.ts` | — | Bridge 句柄 |

87
docs/features/buddy.mdx Normal file
View File

@@ -0,0 +1,87 @@
---
title: "Buddy 宠物系统"
description: "Buddy 是 CLI 中的虚拟宠物伴侣,通过 /buddy 命令孵化、互动,会出现在输入框旁边陪伴你写代码。"
keywords: ["buddy", "宠物", "companion", "伴侣", "虚拟宠物"]
---
## 概述
Buddy 是 Claude Code 内置的虚拟宠物系统。在 REPL 中通过 `/buddy` 命令可以孵化一只随机生成的宠物伴侣,它会出现在输入框旁边,陪伴你的编码过程。
> Feature Flag: `FEATURE_BUDDY=1`
## 启用方式
```bash
FEATURE_BUDDY=1 bun run dev
```
孵化窗口2026 年 4 月 1-7 日期间启动时,会在 REPL 顶部显示彩虹色的 `/buddy` 提示。4 月 7 日之后命令仍然可用,但不再自动提示。
## 命令
| 命令 | 说明 |
|---|---|
| `/buddy` | 查看当前宠物信息和属性 |
| `/buddy hatch` | 孵化一只新宠物(首次使用) |
| `/buddy rehatch` | 重新随机生成宠物(替换现有) |
| `/buddy pet` | 撸宠物,触发爱心动画 |
| `/buddy mute` | 静音宠物(隐藏) |
| `/buddy unmute` | 取消静音 |
## 宠物属性
### 物种18 种)
| | | | |
|---|---|---|---|
| Duck | Goose | Blob | Cat |
| Dragon | Octopus | Owl | Penguin |
| Turtle | Snail | Ghost | Axolotl |
| Capybara | Cactus | Robot | Rabbit |
| Mushroom | Chonk | | |
### 稀有度
| 稀有度 | 星级 | 权重 |
|---|---|---|
| Common | ★ | 60% |
| Uncommon | ★★ | 25% |
| Rare | ★★★ | 10% |
| Epic | ★★★★ | 4% |
| Legendary | ★★★★★ | 1% |
孵化时基于种子随机决定,存在极低概率出现 Shiny闪光变体。
### 属性值
每只宠物拥有 5 项属性0-100
- **DEBUGGING** — 调试能力
- **PATIENCE** — 耐心程度
- **CHAOS** — 混乱指数
- **WISDOM** — 智慧值
- **SNARK** — 毒舌度
### 外观
每只宠物还有随机的外观配件:
- **眼睛**: `·` `✦` `×` `◉` `@` `°`
- **帽子**: none, crown, tophat, propeller, halo, wizard, beanie, tinyduck
## 数据存储
宠物信息存储在 `~/.claude.json` 的 `companion` 字段中。宠物的外观属性(物种、稀有度、属性值等)基于用户 ID 的哈希确定性生成,不可通过编辑配置文件来篡改稀有度。
## 相关源码
| 文件 | 说明 |
|---|---|
| `src/commands/buddy/buddy.ts` | `/buddy` 命令处理 |
| `src/buddy/companion.ts` | 宠物生成与加载 |
| `src/buddy/types.ts` | 类型定义(物种、稀有度、属性) |
| `src/buddy/sprites.ts` | 终端像素画渲染 |
| `src/buddy/CompanionSprite.tsx` | React 组件(输入框旁显示) |
| `src/buddy/useBuddyNotification.tsx` | 启动提示通知 |
| `src/buddy/prompt.ts` | 宠物相关 prompt 模板 |

View File

@@ -0,0 +1,30 @@
# Chrome Use — 浏览器自动化快速指南
让 Claude Code 直接控制你的 Chrome 浏览器,用自然语言完成网页操作。
## 快速开始3 分钟)
### 第一步:安装 Chrome 扩展
1. 下载扩展https://github.com/hangwin/mcp-chrome/releases
2. 解压 zip 文件
3. 打开 Chrome 访问 `chrome://extensions/`
4. 开启右上角「开发者模式」
5. 点击「加载已解压的扩展程序」,选择解压后的文件夹
### 第二步:启动 Claude Code
```bash
bun run dev
ccb # 或者 ccb 安装版也行
```
### 第三步:启用 Chrome MCP
1. 在 REPL 中输入 `/mcp` 打开 MCP 面板
2. 找到 `mcp-chrome`,按空格键启用
3. 按 Enter 确认
## 相关文档
- GitHub 仓库https://github.com/hangwin/mcp-chrome

View File

@@ -0,0 +1,137 @@
# Claude in Chrome — 用户操作指南
## 1. 功能简介
Claude in Chrome 让 Claude Code 直接控制你的 Chrome 浏览器。你可以用自然语言让 Claude 帮你:
- 打开网页、导航、前进后退
- 填写表单、上传图片
- 截图、录制 GIF
- 读取页面内容DOM、纯文本
- 执行 JavaScript
- 监控网络请求和控制台日志
- 管理标签页
## 2. 前置条件
| 条件 | 说明 |
|------|------|
| Claude Code 订阅 | 需要 Claude Pro、Max 或 Team 订阅,浏览器插件功能不向免费用户开放 |
| Chrome 浏览器 | 需已安装 Google Chrome |
| Claude in Chrome 扩展 | 从 Chrome Web Store 安装(`claude.ai/chrome` |
| Claude Code CLI | 已通过 `bun run dev` 或构建产物运行 |
## 3. 启用方式
### Dev 模式
```bash
bun run dev -- --chrome
```
启动后 Claude 会自动检测 Chrome 扩展是否已安装,并注册浏览器控制工具。
### 构建产物
```bash
node dist/cli.js --chrome
```
### 禁用
```bash
bun run dev -- --no-chrome
```
或在 REPL 中通过 `/chrome` 命令切换启用/禁用状态。
### 通过配置默认启用
在 Claude Code 设置中将 `claudeInChromeDefaultEnabled` 设为 `true`,以后启动无需加 `--chrome` 参数。
## 4. 使用流程
1. **启动 CLI** — 加 `--chrome` 参数启动 Claude Code
2. **确认连接** — REPL 中输入 `/chrome`,查看扩展状态是否显示 "Installed / Connected"
3. **开始对话** — 正常与 Claude 对话,当需要操作浏览器时直接说,例如:
- "打开 https://example.com 并截图"
- "在当前页面搜索关键词 xxx"
- "填写登录表单,用户名 admin"
- "帮我录制当前操作的 GIF"
4. **权限审批** — 首次执行浏览器操作时Claude 会请求你的确认
5. **操作完成** — Claude 完成操作后会返回结果(截图、文本、执行结果等)
## 5. 可用操作
### 页面交互
| 操作 | 说明 |
|------|------|
| `navigate` | 导航到指定 URL或前进/后退 |
| `computer` | 鼠标点击、移动、拖拽、键盘输入、截图等13 种 action |
| `form_input` | 填写表单字段 |
| `upload_image` | 上传图片到文件输入框或拖拽区域 |
| `javascript_tool` | 在页面上下文执行 JavaScript |
### 页面读取
| 操作 | 说明 |
|------|------|
| `read_page` | 获取页面可访问性树DOM 结构) |
| `get_page_text` | 提取页面纯文本内容 |
| `find` | 用自然语言搜索页面元素 |
### 标签页管理
| 操作 | 说明 |
|------|------|
| `tabs_context_mcp` | 获取当前标签组信息 |
| `tabs_create_mcp` | 创建新标签页 |
### 监控与调试
| 操作 | 说明 |
|------|------|
| `read_console_messages` | 读取浏览器控制台日志 |
| `read_network_requests` | 读取网络请求记录 |
### 其他
| 操作 | 说明 |
|------|------|
| `resize_window` | 调整浏览器窗口尺寸 |
| `gif_creator` | 录制 GIF 并导出 |
| `shortcuts_list` | 列出可用快捷方式 |
| `shortcuts_execute` | 执行快捷方式 |
| `update_plan` | 向你提交操作计划供审批 |
| `switch_browser` | 切换到其他 Chrome 浏览器(仅 Bridge 模式) |
## 6. 通信模式
Claude in Chrome 支持两种与浏览器通信的方式:
### 本地 Socket默认
Chrome 扩展通过 Native Messaging Host 与 CLI 建立 Unix socket 连接。适用于本地开发,无需额外配置。
### Bridge WebSocket
通过 Anthropic 的 bridge 服务中转,支持远程操控浏览器。需要 claude.ai OAuth 登录。
## 7. 常见问题
### 扩展显示未安装
确认已从 Chrome Web Store 安装 "Claude in Chrome" 扩展,安装后重启浏览器。
### 工具未出现在工具列表
检查启动时是否加了 `--chrome` 参数,或通过 `/chrome` 命令确认状态。
### 连接超时
确保 Chrome 浏览器正在运行且扩展已启用。Native Messaging Host 在扩展安装时自动注册,如果重装过扩展需要重启浏览器。
### 不使用 Chrome 功能时
不带 `--chrome` 参数正常启动即可,不会加载任何浏览器相关模块,不影响其他功能。

View File

@@ -0,0 +1,325 @@
# Computer Use 架构修正方案 v2
更新时间2026-04-04
## 1. 当前架构的问题
### 问题 A平台代码混在错误的包里
`@ant/computer-use-swift` 是 macOS Swift 原生模块的包装器,但我们把 Windows`backends/win32.ts`)和 Linux`backends/linux.ts`)的截图/应用管理代码塞进了这个包。"swift" 在名字里就意味着 macOS后期维护者无法区分。
`@ant/computer-use-input` 同样——原本是 macOS enigo Rust 模块,我们也往里面塞了 win32/linux 后端。
### 问题 B输入方式不对
当前 Windows 后端(`packages/@ant/computer-use-input/src/backends/win32.ts`)使用 `SetCursorPos` + `SendInput` + `keybd_event`——这是**全局输入**
- 鼠标真的会移动到屏幕上
- 键盘真的打到当前前台窗口
- **会影响用户当前的操作**
绑定窗口句柄后,应该用 `SendMessage`/`PostMessage` 向目标 HWND 发送消息:
- `WM_CHAR` — 发送字符,不移动光标
- `WM_KEYDOWN`/`WM_KEYUP` — 发送按键
- `WM_LBUTTONDOWN`/`WM_LBUTTONUP` — 发送鼠标点击(窗口客户区相对坐标)
- `PrintWindow` — 截取窗口内容,不需要窗口在前台
- **不抢焦点、不影响用户当前操作**
已验证:向记事本 `SendMessage(WM_CHAR)` 成功写入文字,记事本在后台,终端保持前台。
### 问题 C截图是公共能力不属于 swift
截图screenshot、显示器枚举display、应用管理apps是所有平台都需要的公共能力不应该放在 `@ant/computer-use-swift`macOS 专属包名)里。
## 2. 修正后的架构
### 2.1 分层原则
```
packages/@ant/ ← macOS 原生模块包装器(不放其他平台代码)
├── computer-use-input/ ← macOS: enigo .node 键鼠(仅 darwin
├── computer-use-swift/ ← macOS: Swift .node 截图/应用(仅 darwin
└── computer-use-mcp/ ← 跨平台: MCP server + 工具定义(不改)
src/utils/computerUse/
├── platforms/ ← 新增: 跨平台抽象层
│ ├── types.ts ← 公共接口: InputPlatform, ScreenshotPlatform, AppsPlatform, DisplayPlatform
│ ├── index.ts ← 平台分发器: 按 process.platform 加载后端
│ ├── darwin.ts ← macOS: 委托给 @ant/computer-use-{input,swift}
│ ├── win32.ts ← Windows: SendMessage 输入 + PrintWindow 截图 + EnumWindows + UIA + OCR
│ └── linux.ts ← Linux: xdotool + scrot + xrandr + wmctrl
├── win32/ ← Windows 专属增强能力(不在公共接口中)
│ ├── windowCapture.ts ← PrintWindow 窗口绑定截图
│ ├── windowEnum.ts ← EnumWindows 窗口枚举
│ ├── windowMessage.ts ← SendMessage/PostMessage 无焦点输入(新增)
│ ├── uiAutomation.ts ← IUIAutomation UI 元素操作
│ └── ocr.ts ← Windows.Media.Ocr 文字识别
├── executor.ts ← 改: 通过 platforms/ 获取平台实现,不直接调 @ant 包
├── swiftLoader.ts ← 改: 仅 darwin 使用
├── inputLoader.ts ← 改: 仅 darwin 使用
└── ...其他文件不动
```
### 2.2 公共接口(`platforms/types.ts`
```typescript
/** 窗口标识 — 跨平台 */
export interface WindowHandle {
id: string // macOS: bundleId, Windows: HWND string, Linux: window ID
pid: number
title: string
exePath?: string // Windows/Linux: 进程路径
}
/** 输入平台接口 — 两种模式 */
export interface InputPlatform {
// 模式 A: 全局输入macOS/Linux 默认,向前台窗口发送)
moveMouse(x: number, y: number): Promise<void>
click(x: number, y: number, button: 'left' | 'right' | 'middle'): Promise<void>
typeText(text: string): Promise<void>
key(name: string, action: 'press' | 'release'): Promise<void>
keys(combo: string[]): Promise<void>
scroll(amount: number, direction: 'vertical' | 'horizontal'): Promise<void>
mouseLocation(): Promise<{ x: number; y: number }>
// 模式 B: 窗口绑定输入Windows SendMessage不抢焦点
sendChar?(hwnd: string, char: string): Promise<void>
sendKey?(hwnd: string, vk: number, action: 'down' | 'up'): Promise<void>
sendClick?(hwnd: string, x: number, y: number, button: 'left' | 'right'): Promise<void>
sendText?(hwnd: string, text: string): Promise<void>
}
/** 截图平台接口 */
export interface ScreenshotPlatform {
// 全屏截图
captureScreen(displayId?: number): Promise<ScreenshotResult>
// 区域截图
captureRegion(x: number, y: number, w: number, h: number): Promise<ScreenshotResult>
// 窗口截图Windows: PrintWindowmacOS: SCContentFilterLinux: xdotool+import
captureWindow?(hwnd: string): Promise<ScreenshotResult | null>
}
/** 显示器平台接口 */
export interface DisplayPlatform {
listAll(): DisplayInfo[]
getSize(displayId?: number): DisplayInfo
}
/** 应用管理平台接口 */
export interface AppsPlatform {
listRunning(): WindowHandle[]
listInstalled(): Promise<InstalledApp[]>
open(name: string): Promise<void>
getFrontmostApp(): FrontmostAppInfo | null
findWindowByTitle(title: string): WindowHandle | null
}
export interface ScreenshotResult {
base64: string
width: number
height: number
}
export interface DisplayInfo {
width: number
height: number
scaleFactor: number
displayId: number
}
export interface InstalledApp {
id: string // macOS: bundleId, Windows: exe path, Linux: .desktop name
displayName: string
path: string
}
export interface FrontmostAppInfo {
id: string
appName: string
}
```
### 2.3 平台分发器(`platforms/index.ts`
```typescript
import type { InputPlatform, ScreenshotPlatform, DisplayPlatform, AppsPlatform } from './types.js'
export interface Platform {
input: InputPlatform
screenshot: ScreenshotPlatform
display: DisplayPlatform
apps: AppsPlatform
}
export function loadPlatform(): Platform {
switch (process.platform) {
case 'darwin':
return require('./darwin.js').platform
case 'win32':
return require('./win32.js').platform
case 'linux':
return require('./linux.js').platform
default:
throw new Error(`Computer Use not supported on ${process.platform}`)
}
}
```
### 2.4 各平台实现
**`platforms/darwin.ts`** — 委托给 @ant 包(保持兼容):
```typescript
// macOS: 通过 @ant/computer-use-input 和 @ant/computer-use-swift
// 这两个包的 darwin 后端保留不动
import { requireComputerUseInput } from '../inputLoader.js'
import { requireComputerUseSwift } from '../swiftLoader.js'
export const platform = {
input: { /* 委托给 requireComputerUseInput() */ },
screenshot: { /* 委托给 requireComputerUseSwift().screenshot */ },
display: { /* 委托给 requireComputerUseSwift().display */ },
apps: { /* 委托给 requireComputerUseSwift().apps */ },
}
```
**`platforms/win32.ts`** — 使用 `src/utils/computerUse/win32/` 模块:
```typescript
// Windows: SendMessage 输入 + PrintWindow 截图 + EnumWindows 应用
import { sendChar, sendKey, sendClick, sendText } from '../win32/windowMessage.js'
import { captureWindow } from '../win32/windowCapture.js'
import { listWindows } from '../win32/windowEnum.js'
// ... PowerShell P/Invoke 全局输入作为 fallback
export const platform = {
input: {
// 全局模式: PowerShell SetCursorPos/SendInputfallback
// 窗口模式: SendMessage首选
sendChar, sendKey, sendClick, sendText, // 窗口绑定
moveMouse, click, typeText, ... // 全局 fallback
},
screenshot: {
captureScreen, // CopyFromScreen
captureRegion, // CopyFromScreen(rect)
captureWindow, // PrintWindow不抢焦点
},
display: { /* Screen.AllScreens */ },
apps: { /* EnumWindows */ },
}
```
**`platforms/linux.ts`** — 使用 xdotool/scrot
```typescript
// Linux: xdotool + scrot + xrandr + wmctrl
export const platform = {
input: { /* xdotool mousemove/click/key/type */ },
screenshot: { /* scrot */ },
display: { /* xrandr */ },
apps: { /* wmctrl + ps */ },
}
```
### 2.5 executor.ts 改造
```typescript
// 之前: 直接调 requireComputerUseSwift() 和 requireComputerUseInput()
// 之后: 通过 platforms/ 统一获取
import { loadPlatform } from './platforms/index.js'
const platform = loadPlatform()
// 截图
platform.screenshot.captureScreen()
platform.screenshot.captureWindow(hwnd) // 窗口绑定
// 输入(窗口绑定模式,不抢焦点)
platform.input.sendText?.(hwnd, 'Hello')
platform.input.sendClick?.(hwnd, 100, 200, 'left')
// 输入全局模式fallback
platform.input.moveMouse(500, 500)
platform.input.click(500, 500, 'left')
```
## 3. Windows 输入模式对比
| 方式 | API | 抢焦点 | 移鼠标 | 窗口可最小化 | 适用场景 |
|------|-----|--------|--------|-------------|---------|
| **全局输入** | `SetCursorPos` + `SendInput` | ✅ 抢 | ✅ 动 | ❌ 不行 | 需要坐标点击fallback |
| **窗口消息** | `SendMessage(WM_CHAR/WM_KEYDOWN)` | ❌ 不抢 | ❌ 不动 | ✅ 可以 | 打字、按键(首选) |
| **窗口消息** | `SendMessage(WM_LBUTTONDOWN)` | ❌ 不抢 | ❌ 不动 | ⚠️ 部分 | 窗口内点击 |
| **窗口截图** | `PrintWindow(hwnd, PW_RENDERFULLCONTENT)` | ❌ 不抢 | ❌ 不动 | ✅ 可以 | 窗口截图 |
| **UI 操作** | `UIAutomation InvokePattern` | ❌ 不抢 | ❌ 不动 | ✅ 可以 | 按钮点击、文本写入 |
**策略**:优先用窗口消息 + UIAutomation不干扰用户全局输入作为 fallback。
## 4. 需要新增的文件
| 文件 | 说明 |
|------|------|
| `src/utils/computerUse/platforms/types.ts` | 公共接口定义 |
| `src/utils/computerUse/platforms/index.ts` | 平台分发器 |
| `src/utils/computerUse/platforms/darwin.ts` | macOS: 委托给 @ant 包 |
| `src/utils/computerUse/platforms/win32.ts` | Windows: 组合 win32/ 下各模块 |
| `src/utils/computerUse/platforms/linux.ts` | Linux: xdotool/scrot |
| `src/utils/computerUse/win32/windowMessage.ts` | **新增**: SendMessage 无焦点输入 |
## 5. 需要移除/清理的文件
| 文件 | 操作 | 原因 |
|------|------|------|
| `packages/@ant/computer-use-input/src/backends/win32.ts` | 删除 | Windows 代码不应在 macOS 包里 |
| `packages/@ant/computer-use-input/src/backends/linux.ts` | 删除 | Linux 代码不应在 macOS 包里 |
| `packages/@ant/computer-use-swift/src/backends/win32.ts` | 删除 | 同上 |
| `packages/@ant/computer-use-swift/src/backends/linux.ts` | 删除 | 同上 |
| `packages/@ant/computer-use-input/src/types.ts` | 删除 | 移到 platforms/types.ts |
| `packages/@ant/computer-use-swift/src/types.ts` | 删除 | 移到 platforms/types.ts |
## 6. 需要修改的文件
| 文件 | 改动 |
|------|------|
| `packages/@ant/computer-use-input/src/index.ts` | 恢复为仅 darwin dispatcher去掉 win32/linux case |
| `packages/@ant/computer-use-swift/src/index.ts` | 恢复为仅 darwin dispatcher去掉 win32/linux case |
| `src/utils/computerUse/executor.ts` | 通过 `platforms/` 获取平台实现,不直接调 @ant 包 |
| `src/utils/computerUse/swiftLoader.ts` | 仅 darwin 加载 |
| `src/utils/computerUse/inputLoader.ts` | 仅 darwin 加载 |
## 7. @ant 包的定位(修正后)
| 包 | 职责 | 平台 |
|---|------|------|
| `@ant/computer-use-input` | macOS enigo 键鼠原生模块包装 | **仅 darwin** |
| `@ant/computer-use-swift` | macOS Swift 截图/应用原生模块包装 | **仅 darwin** |
| `@ant/computer-use-mcp` | MCP Server + 工具定义 + 调用路由 | **跨平台**(不含平台代码) |
Windows/Linux 的平台实现全部在 `src/utils/computerUse/platforms/``src/utils/computerUse/win32/` 中。
## 8. 执行顺序
```
Phase 1: 创建 platforms/ 抽象层
├── platforms/types.ts公共接口
├── platforms/index.ts分发器
└── platforms/darwin.ts委托 @ant 包)
Phase 2: 创建 Windows 平台实现
├── win32/windowMessage.tsSendMessage 无焦点输入)
└── platforms/win32.ts组合 win32/ 各模块)
Phase 3: 创建 Linux 平台实现
└── platforms/linux.tsxdotool/scrot
Phase 4: 改造 executor.ts
└── 通过 platforms/ 获取实现,不直接调 @ant
Phase 5: 清理 @ant 包
├── 删除 @ant/computer-use-input/src/backends/{win32,linux}.ts
├── 删除 @ant/computer-use-swift/src/backends/{win32,linux}.ts
└── 恢复 index.ts 为 darwin-only
Phase 6: 验证 + PR
```

View File

@@ -0,0 +1,277 @@
# Computer Use MCP 工具测试报告
> 测试日期: 2026-04-04
> 测试环境: macOS Darwin 25.4.0, Cursor (IDE tier: click)
> MCP Server: `@ant/computer-use-mcp`
## 工具总览
共 17 个工具(含 batch 复合操作),分为 5 大类:
| 类别 | 工具 | 数量 |
|------|------|------|
| 截图/显示 | `screenshot`, `switch_display`, `zoom` | 3 |
| 鼠标操作 | `left_click`, `right_click`, `double_click`, `triple_click`, `middle_click`, `left_click_drag`, `mouse_move` | 7 |
| 键盘操作 | `key`, `type`, `hold_key` | 3 |
| 状态查询 | `cursor_position`, `request_access` | 2 |
| 复合/辅助 | `computer_batch`, `wait` | 2 |
---
## 测试结果
### 1. 权限管理
#### `request_access` — 请求应用访问权限
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 行为 | 弹出系统对话框请求用户授权,支持批量申请多个应用 |
| 返回 | `{ granted: [...], denied: [...], tierGuidance: "..." }` |
| 权限分级 | `click`(仅点击), `full`(完整控制) |
| 说明 | IDE 类应用Cursor、VSCode、Terminal默认授予 `click` tier限制键盘输入和右键操作系统应用System Settings授予 `full` tier |
#### 已授权应用
| 应用 | Tier | 能力 |
|------|------|------|
| Cursor | click | 可见 + 纯左键点击(无键盘输入、右键、修饰键点击、拖拽) |
| Terminal | click | 同上 |
| System Settings | full | 完整控制(键鼠、拖拽等) |
| Finder | — | 已授权 |
---
### 2. 截图与显示
#### `screenshot` — 截取屏幕截图
| 项目 | 结果 |
|------|------|
| 状态 | ⚠️ 部分通过 |
| 执行 | 工具成功执行,返回 `ok: true` |
| 图片 | **未返回可视图片内容**output 为空字符串) |
| `save_to_disk` | 设置后仍无输出 |
| 分析 | 可能原因:(1) macOS 屏幕录制权限未授予;(2) 当前前台应用未被过滤导致截图为空;(3) MCP 传输层未正确编码图片数据 |
| 建议 | 检查 **系统设置 → 隐私与安全性 → 屏幕录制** 是否授权给运行 Claude Code 的应用 |
#### `switch_display` — 切换显示器
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 行为 | 接受显示器名称或 `"auto"`(自动选择) |
| 返回 | 确认消息 |
#### `zoom` — 区域放大截图
| 项目 | 结果 |
|------|------|
| 状态 | ⏭️ 跳过 |
| 原因 | 依赖 `screenshot` 返回的图片坐标,截图未返回图片无法测试 |
---
### 3. 鼠标操作
> 以下测试在 Cursor 窗口上执行tier: click
#### `mouse_move` — 移动鼠标
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 输入 | `coordinate: [500, 500]` |
| 返回 | `"Moved."` |
#### `left_click` — 左键单击
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 输入 | `coordinate: [500, 500]` |
| 返回 | `"Clicked."` |
#### `double_click` — 双击
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 输入 | `coordinate: [500, 500]` |
| 返回 | `"Clicked."` |
#### `triple_click` — 三击
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 输入 | `coordinate: [500, 500]` |
| 返回 | `"Clicked."` |
#### `right_click` — 右键点击
| 项目 | 结果 |
|------|------|
| 状态 | ⚠️ 受 tier 限制 |
| Cursor (click tier) | ❌ 被拒绝 — `"Code" is granted at tier "click" — right-click, middle-click, and clicks with modifier keys require tier "full"` |
| Finder (full tier) | ✅ 通过 — 返回 `"Clicked."` |
| 结论 | 功能正常IDE 安全限制符合预期 |
#### `middle_click` — 中键点击
| 项目 | 结果 |
|------|------|
| 状态 | ⚠️ 受 tier 限制 |
| Cursor (click tier) | ❌ 被拒绝 — 同 `right_click`,需要 full tier |
| Finder (full tier) | ✅ 通过 — 返回 `"Clicked."` |
| 结论 | 功能正常IDE 安全限制符合预期 |
#### `left_click_drag` — 拖拽
| 项目 | 结果 |
|------|------|
| 状态 | ⚠️ 受 tier 限制 |
| Cursor (click tier) | ❌ 被拒绝 — 拖拽被视为修饰键点击,需要 full tier |
| Finder (full tier) | ✅ 通过 — 返回 `"Dragged."` |
| 结论 | 功能正常IDE 安全限制符合预期 |
#### `scroll` — 滚轮滚动
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 输入 | `coordinate: [500, 500]`, `scroll_direction: "down"`, `scroll_amount: 3` |
| 返回 | `"Scrolled."` |
| 反向 | ✅ `scroll_direction: "up"` 也通过 |
---
### 4. 键盘操作
> 以下测试在 Cursor 窗口上执行tier: click— 所有键盘操作均被拒绝
#### `key` — 按键/快捷键
| 项目 | 结果 |
|------|------|
| 状态 | ⚠️ 受 tier 限制 |
| Cursor (click tier) | ❌ 被拒绝 — IDE tier 限制键盘输入 |
| Finder (full tier) | ✅ 通过 — `escape` 按键成功,返回 `"Key pressed."` |
| 结论 | 功能正常IDE 安全限制符合预期 |
#### `type` — 输入文本
| 项目 | 结果 |
|------|------|
| 状态 | ⚠️ 受 tier 限制 |
| Cursor (click tier) | ❌ 被拒绝 — IDE tier 限制文本输入 |
| Finder (full tier) | ✅ 通过 — 输入 `"hello"` 成功,返回 `"Typed 5 grapheme(s)."` |
| 结论 | 功能正常IDE 安全限制符合预期 |
#### `hold_key` — 按住按键
| 项目 | 结果 |
|------|------|
| 状态 | ⚠️ 受 tier 限制 |
| Cursor (click tier) | ❌ 被拒绝 — IDE tier 限制键盘输入 |
| Finder (full tier) | ✅ 通过 — 按住 `shift` 1 秒成功,返回 `"Key held."` |
| 结论 | 功能正常IDE 安全限制符合预期 |
---
### 5. 状态查询
#### `cursor_position` — 获取鼠标位置
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 返回 | `{"x": null, "y": null, "coordinateSpace": "image_pixels"}` |
| 说明 | 坐标为 null 是因为没有成功截图,无参考坐标系 |
---
### 6. 复合/辅助操作
#### `computer_batch` — 批量执行操作
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 行为 | 按顺序执行操作列表,遇到失败则停止后续操作 |
| 返回 | `{ completed: [...], failed: {...}, remaining: N }` |
| 特点 | 单次 API 调用执行多个操作,减少往返延迟 |
| 错误处理 | 失败的操作会中断后续操作,返回已完成和剩余数量 |
#### `wait` — 等待
| 项目 | 结果 |
|------|------|
| 状态 | ✅ 通过 |
| 输入 | `duration: 1` (秒) |
| 返回 | `"Waited 1s."` |
| 最大值 | 100 秒 |
---
## 汇总统计
| 状态 | 数量 | 工具 |
|------|------|------|
| ✅ 通过 | 10 | `request_access`, `switch_display`, `mouse_move`, `left_click`, `double_click`, `triple_click`, `scroll`, `cursor_position`, `computer_batch`, `wait` |
| ⚠️ 部分通过 | 7 | `screenshot`(执行成功但无图片返回), `right_click`, `middle_click`, `left_click_drag`, `key`, `type`, `hold_key`(均在 full tier 应用上通过IDE click tier 限制是预期行为) |
| ❌ 被拒绝 | 0 | — |
| ⏭️ 跳过 | 1 | `zoom`(依赖截图) |
---
## 已知问题
### P0: 截图无图片返回
`screenshot` 工具执行成功但未返回图片内容,导致:
- 无法获取屏幕坐标参考
- `cursor_position` 返回 null 坐标
- `zoom` 无法使用
- 所有点击操作只能盲点(无截图验证)
**可能原因**:
1. macOS 屏幕录制权限未授予
2. MCP 图片传输/编码问题
3. 截图内容被安全过滤机制过滤
**建议排查**: 检查 `系统设置 → 隐私与安全性 → 屏幕录制` 权限。
### P1: IDE 应用键盘操作受限 — ✅ 已确认功能正常
IDE 类应用Cursor、VSCode、Terminal被限制在 `click` tier无法执行
- 键盘输入(`key`, `type`, `hold_key`
- 右键/中键点击(`right_click`, `middle_click`
- 拖拽操作(`left_click_drag`
这是安全设计,防止 AI 操控 IDE 终端。**在 full tier 应用Finder、System Settings以上 6 个操作均测试通过,功能完全正常。**
---
## 权限模型说明
Computer Use MCP 采用分级权限模型:
```
┌─────────────────────────────────────────┐
│ Tier: full │
│ - 所有鼠标操作(左键、右键、中键、拖拽) │
│ - 键盘输入type, key, hold_key
│ - 适用于: 系统应用、Finder 等 │
├─────────────────────────────────────────┤
│ Tier: click │
│ - 仅纯左键点击 │
│ - 滚轮滚动 │
│ - 适用于: IDE、Terminal 等 │
├─────────────────────────────────────────┤
│ 未授权 │
│ - 所有操作被拒绝 │
│ - 需通过 request_access 申请 │
└─────────────────────────────────────────┘
```

View File

@@ -0,0 +1,496 @@
# Computer Use 工具参考文档
## 概览
Computer Use 提供 37 个工具,分为三类:
| 分类 | 平台 | 工具数 | 说明 |
|------|------|--------|------|
| 通用工具 | 全平台 | 24 | 官方 Computer Use 标准能力 |
| Windows 专属工具 | Win32 | 10 | 绑定窗口模式下的增强能力 |
| 教学工具 | 全平台 | 3 | 分步引导模式(需 teachMode 开启) |
---
## 一、通用工具24 个)
全平台可用。未绑定窗口时,操作对象是整个屏幕。
### 权限与会话
| 工具 | 参数 | 说明 |
|------|------|------|
| `request_access` | `apps[]`, `reason`, `clipboardRead?`, `clipboardWrite?`, `systemKeyCombos?` | 请求操作应用的权限。所有其他工具的前置条件 |
| `list_granted_applications` | — | 列出当前会话已授权的应用 |
### 截图与显示
| 工具 | 参数 | 说明 |
|------|------|------|
| `screenshot` | `save_to_disk?` | 截取当前屏幕。绑定窗口时截取绑定窗口PrintWindow。返回图片 + GUI 元素列表Windows |
| `zoom` | `region: [x1,y1,x2,y2]` | 截取指定区域的高分辨率图片。坐标基于最近一次全屏截图 |
| `switch_display` | `display` | 切换截图的目标显示器 |
### 鼠标操作
| 工具 | 参数 | 说明 |
|------|------|------|
| `left_click` | `coordinate: [x,y]`, `text?` (修饰键) | 左键点击。`text` 可传 "shift"/"ctrl"/"alt" 实现组合点击 |
| `double_click` | `coordinate`, `text?` | 双击 |
| `triple_click` | `coordinate`, `text?` | 三击(选整行) |
| `right_click` | `coordinate`, `text?` | 右键点击 |
| `middle_click` | `coordinate`, `text?` | 中键点击 |
| `mouse_move` | `coordinate` | 移动鼠标(不点击) |
| `left_click_drag` | `coordinate` (终点), `start_coordinate?` (起点) | 拖拽 |
| `left_mouse_down` | — | 按下左键不松 |
| `left_mouse_up` | — | 松开左键 |
| `cursor_position` | — | 获取当前鼠标位置 |
### 键盘操作
| 工具 | 参数 | 说明 |
|------|------|------|
| `type` | `text` | 输入文字 |
| `key` | `text` (如 "ctrl+s"), `repeat?` | 按键/组合键 |
| `hold_key` | `text`, `duration` (秒) | 按住键指定时长 |
### 滚动
| 工具 | 参数 | 说明 |
|------|------|------|
| `scroll` | `coordinate`, `scroll_direction`, `scroll_amount` | 滚动。方向: up/down/left/right |
### 应用管理
| 工具 | 参数 | 说明 |
|------|------|------|
| `open_application` | `app` | 打开应用。Windows 上自动绑定窗口 |
### 剪贴板
| 工具 | 参数 | 说明 |
|------|------|------|
| `read_clipboard` | — | 读取剪贴板文字 |
| `write_clipboard` | `text` | 写入剪贴板 |
### 其他
| 工具 | 参数 | 说明 |
|------|------|------|
| `wait` | `duration` (秒) | 等待 |
| `computer_batch` | `actions[]` | 批量执行多个动作(减少 API 往返) |
---
## 二、Windows 专属工具10 个)
仅 Windows 平台可见。核心能力:**绑定窗口后的独立操作——不抢占用户鼠标键盘**。
### 工作模式
```
┌──────────────────────────────────────────────────┐
│ 未绑定模式 │
│ 使用通用工具 (left_click/type/key/scroll) │
│ 操作对象:整个屏幕 │
│ 输入方式:全局 SendInput会移动真实鼠标
└──────────────────────────────────────────────────┘
bind_window / open_application
┌──────────────────────────────────────────────────┐
│ 绑定窗口模式 │
│ 使用 Win32 工具 (virtual_mouse/virtual_keyboard) │
│ 操作对象:绑定的窗口 │
│ 输入方式SendMessageW不动真实鼠标/键盘) │
│ 可视化DWM 绿色边框 + 虚拟光标 + 状态指示器 │
└──────────────────────────────────────────────────┘
```
### 窗口绑定
| 工具 | 参数 | 说明 |
|------|------|------|
| `bind_window` | `action`: list/bind/unbind/status | 窗口绑定管理 |
**动作详情:**
| action | 参数 | 说明 |
|--------|------|------|
| `list` | — | 列出所有可见窗口hwnd、pid、title |
| `bind` | `title?`, `hwnd?`, `pid?` | 绑定到指定窗口。设置 DWM 绿色边框 + 启动虚拟光标 + 启动状态指示器 + 短暂激活窗口确保可接收输入 |
| `unbind` | — | 解除绑定,恢复全屏模式 |
| `status` | — | 查看当前绑定状态hwnd、title、pid、窗口矩形 |
### 窗口管理
| 工具 | 参数 | 说明 |
|------|------|------|
| `window_management` | `action`, `x?`, `y?`, `width?`, `height?` | 窗口操作Win32 API不走全局快捷键 |
**动作详情:**
| action | 说明 |
|--------|------|
| `minimize` | ShowWindow(SW_MINIMIZE) |
| `maximize` | ShowWindow(SW_MAXIMIZE) |
| `restore` | ShowWindow(SW_RESTORE) — 恢复最小化/最大化 |
| `close` | SendMessage(WM_CLOSE) — 优雅关闭 |
| `focus` | SetForegroundWindow + BringWindowToTop — 激活窗口 |
| `move_offscreen` | SetWindowPos(-32000,-32000) — 移到屏幕外(仍可 SendMessage/PrintWindow |
| `move_resize` | SetWindowPos — 移动/缩放到指定位置和大小 |
| `get_rect` | GetWindowRect — 获取当前位置和大小 |
### 虚拟鼠标
| 工具 | 参数 | 说明 |
|------|------|------|
| `virtual_mouse` | `action`, `coordinate: [x,y]`, `start_coordinate?` | 在绑定窗口内操作虚拟鼠标 |
**动作详情:**
| action | 说明 |
|--------|------|
| `click` | 左键点击。虚拟光标移动到坐标 + 闪烁动画 |
| `double_click` | 双击 |
| `right_click` | 右键点击 |
| `move` | 移动虚拟光标(不点击) |
| `drag` | 按住 → 移动 → 松开。需 `start_coordinate` 指定起点 |
| `down` | 按下左键不松 |
| `up` | 松开左键 |
**与通用鼠标工具的区别:**
| | 通用 (`left_click` 等) | `virtual_mouse` |
|---|---|---|
| 输入方式 | SendInput全局 | SendMessageW窗口级 |
| 真实鼠标 | 会移动 | **不动** |
| 用户干扰 | 有 | **无** |
| 适用场景 | 未绑定时 | **绑定后** |
### 虚拟键盘
| 工具 | 参数 | 说明 |
|------|------|------|
| `virtual_keyboard` | `action`, `text`, `duration?`, `repeat?` | 在绑定窗口内操作虚拟键盘 |
**动作详情:**
| action | text 含义 | 说明 |
|--------|----------|------|
| `type` | 要输入的文字 | SendMessageW(WM_CHAR),支持 Unicode 中文/emoji |
| `combo` | 组合键 (如 "ctrl+s") | WM_KEYDOWN/UP 序列 |
| `press` | 单个键名 | 按下不松(配合 release 使用) |
| `release` | 单个键名 | 松开按键 |
| `hold` | 键名或组合 | 按住指定秒数后松开 |
**与通用键盘工具的区别:**
| | 通用 (`type`/`key`) | `virtual_keyboard` |
|---|---|---|
| 输入方式 | SendInput全局 | SendMessageW窗口级 |
| 物理键盘 | 会冲突 | **不冲突** |
| 适用场景 | 未绑定时 | **绑定后** |
**注意:** SendMessageW 对 Windows Terminal (ConPTY) 等现代应用无效。这些应用需要使用通用工具 + 窗口激活方式操作。
### 鼠标滚轮
| 工具 | 参数 | 说明 |
|------|------|------|
| `mouse_wheel` | `coordinate: [x,y]`, `delta`, `direction?` | WM_MOUSEWHEEL 鼠标中键滚轮 |
**参数说明:**
- `delta`: 正值=向上,负值=向下。每 1 单位 ≈ 3 行
- `direction`: "vertical"(默认)或 "horizontal"
- `coordinate`: 滚轮作用点——决定哪个面板/区域接收滚动
**与通用 `scroll` 的区别:**
| | `scroll` | `mouse_wheel` |
|---|---|---|
| 原理 | WM_VSCROLL/WM_HSCROLL | **WM_MOUSEWHEEL** |
| Excel | ❌ | ✅ |
| 浏览器 | ❌ | ✅ |
| 代码编辑器 | ❌ | ✅ |
### 元素级操作
| 工具 | 参数 | 说明 |
|------|------|------|
| `click_element` | `name?`, `role?`, `automationId?` | 按无障碍名称/角色点击 GUI 元素 |
| `type_into_element` | `name?`, `role?`, `automationId?`, `text` | 按名称向元素输入文字 |
**工作原理:**
1. 通过 UI Automation 在绑定窗口中查找匹配元素
2. `click_element`: 先尝试 InvokePattern按钮/菜单),失败则 SendMessage 点击 BoundingRect 中心
3. `type_into_element`: 先尝试 ValuePattern 直接设值,失败则点击聚焦 + WM_CHAR 输入
**适用场景:**
- 截图中看到元素名称但坐标不精确时
- Accessibility Snapshot 列出了元素的 name/automationId 时
- 比坐标点击更可靠(不受窗口缩放/DPI 影响)
### 终端交互
| 工具 | 参数 | 说明 |
|------|------|------|
| `prompt_respond` | `response_type`, `arrow_direction?`, `arrow_count?`, `text?` | 处理终端 Yes/No/选择提示 |
**response_type 详情:**
| response_type | 操作 | 场景 |
|---------------|------|------|
| `yes` | 发送 'y' + Enter | npm "Continue? (y/n)" |
| `no` | 发送 'n' + Enter | 拒绝确认 |
| `enter` | 发送 Enter | 接受默认选项 |
| `escape` | 发送 Escape | 取消操作 |
| `select` | ↑/↓ 箭头 × N + Enter | inquirer 选择菜单 |
| `type` | 输入文字 + Enter | 文本输入提示 |
### 状态指示器
| 工具 | 参数 | 说明 |
|------|------|------|
| `status_indicator` | `action`: show/hide/status, `message?` | 控制绑定窗口底部的浮动状态标签 |
---
## 三、教学工具3 个)
需要 `teachMode` 开启。
| 工具 | 说明 |
|------|------|
| `request_teach_access` | 请求教学引导模式权限 |
| `teach_step` | 显示一步引导提示,等用户点 Next |
| `teach_batch` | 批量排队多步引导 |
---
## 操作流程
### 流程 1全屏操作未绑定
```
request_access(apps=["Notepad"])
open_application(app="Notepad") ← 自动绑定窗口
screenshot ← PrintWindow 截图 + GUI 元素列表
left_click(coordinate=[500, 300]) ← 全局 SendInput
type(text="hello world") ← 全局 SendInput
key(text="ctrl+s") ← 全局 SendInput
```
### 流程 2绑定窗口操作推荐不干扰用户
```
request_access(apps=["Notepad"])
bind_window(action="list") ← 列出所有窗口
bind_window(action="bind", title="记事本") ← 绑定 + 绿色边框 + 虚拟光标
screenshot ← PrintWindow 截取绑定窗口
virtual_mouse(action="click", coordinate=[500, 300]) ← SendMessageW不动真实鼠标
virtual_keyboard(action="type", text="hello world") ← SendMessageW不动物理键盘
virtual_keyboard(action="combo", text="ctrl+s") ← 保存
mouse_wheel(coordinate=[500, 400], delta=-5) ← 向下滚动
bind_window(action="unbind") ← 解除绑定
```
### 流程 3按元素名称操作
```
bind_window(action="bind", title="记事本")
screenshot ← 返回截图 + GUI elements 列表
click_element(name="保存", role="Button") ← UI Automation 查找并点击
type_into_element(role="Edit", text="new content")
```
### 流程 4终端交互
```
bind_window(action="bind", title="PowerShell")
screenshot
prompt_respond(response_type="yes") ← 回答 y + Enter
prompt_respond(response_type="select", arrow_direction="down", arrow_count=2) ← 选第3项
```
### 流程 5Excel/浏览器滚动
```
bind_window(action="bind", title="Excel")
screenshot
mouse_wheel(coordinate=[600, 400], delta=-10) ← 向下滚动 10 格
mouse_wheel(coordinate=[600, 400], delta=5, direction="horizontal") ← 向右滚动
```
---
## 应用兼容性
| 应用类型 | SendMessageW (virtual_*) | 元素操作 (click_element) | 注意 |
|---------|--------------------------|------------------------|------|
| 传统 Win32 (记事本/写字板) | ✅ | ✅ | 完美支持 |
| Office (Excel/Word) | ✅ (COM 自动化) | ✅ | 通过 COM API |
| WPF 应用 | ✅ | ✅ | 标准 UIA 支持 |
| Electron/Chrome | ⚠️ 部分 | ⚠️ 部分 | 内部渲染不走 Win32 消息 |
| UWP/WinUI (Windows Terminal) | ❌ | ❌ | ConPTY 不接受 SendMessageW |
| 浏览器网页内容 | ❌ | ❌ | 需要全局 SendInput |
**对于不支持 SendMessageW 的应用**,使用通用工具 (`left_click`/`type`/`key`) + `window_management(action="focus")` 先激活窗口。
---
## 绑定窗口时的可视化
绑定窗口后自动启动三层可视化:
1. **DWM 绿色边框** — 窗口自身的边框颜色变绿,零偏移
2. **虚拟鼠标光标** — 红色箭头图标,跟随 virtual_mouse 操作移动,点击时闪烁
3. **状态指示器** — 窗口底部浮动标签,显示当前操作(通过 status_indicator 控制)
---
## Accessibility Snapshot
每次 `screenshot` 时,如果窗口已绑定,会自动附带 GUI 元素列表:
```
GUI elements in this window:
[Button] "Save" (120,50 80x30) enabled
[Edit] "" (200,80 400x25) enabled value="hello" id=textBox1
[MenuItem] "File" (10,0 40x25) enabled
[MenuItem] "Edit" (50,0 40x25) enabled
[CheckBox] "Auto-save" (300,50 100x20) enabled id=chkAutoSave
```
模型同时收到 **截图图片 + 结构化元素列表**,可以选择:
- 用坐标操作:`virtual_mouse(action="click", coordinate=[120, 50])`
- 用名称操作:`click_element(name="Save")`
---
## UI Automation Control Patterns 参考
`click_element` / `type_into_element` 底层使用 UI Automation Control Patterns。当前已实现的和可扩展的
| Pattern | 用途 | 当前状态 | 可用于 |
|---------|------|---------|--------|
| `InvokePattern` | 触发点击 | ✅ 已实现 (`click_element`) | 按钮、菜单项、链接 |
| `ValuePattern` | 读写文本值 | ✅ 已实现 (`type_into_element`) | 文本框、组合框 |
| `TogglePattern` | 切换状态 | ❌ 未实现 | 复选框、开关 |
| `SelectionPattern` | 选择项目 | ❌ 未实现 | 下拉菜单、列表 |
| `ScrollPattern` | 编程滚动 | ❌ 未实现(用 `mouse_wheel` 替代) | 列表、树、面板 |
| `ExpandCollapsePattern` | 展开/折叠 | ❌ 未实现 | 树节点、折叠面板 |
| `WindowPattern` | 窗口操作 | ❌ 未实现(用 `window_management` 替代) | 窗口最大化/关闭 |
| `TextPattern` | 读取文档文本 | ❌ 未实现 | 文档、富文本 |
| `GridPattern` | 表格操作 | ❌ 未实现 | Excel 单元格、数据网格 |
| `TablePattern` | 表格结构 | ❌ 未实现 | 表头、行列关系 |
| `RangeValuePattern` | 范围值操作 | ❌ 未实现 | 滑块、进度条 |
| `TransformPattern` | 移动/缩放 | ❌ 未实现 | 可拖拽元素 |
**扩展路线:** 优先实现 `TogglePattern`(复选框)和 `SelectionPattern`(下拉菜单),这两个在表单自动化中最常用。
---
## 屏幕截取技术方案对比
当前使用 Python Bridge (mss) 进行截图,底层是 GDI BitBlt。三种方案对比
| 方案 | API | 当前状态 | 性能 | 优势 | 限制 |
|------|-----|---------|------|------|------|
| **GDI BitBlt** | `BitBlt` / `PrintWindow` | ✅ 当前使用 (mss/bridge.py) | ~300ms | 简单稳定,支持后台窗口 (PrintWindow) | 不支持硬件加速内容、DPI 处理复杂 |
| **DXGI Desktop Duplication** | `IDXGIOutputDuplication` | ❌ 未实现 | ~16ms (60fps) | 硬件加速,支持 HDRGPU 直接读取 | 不支持单窗口截取,需 D3D11 |
| **Windows.Graphics.Capture** | `GraphicsCaptureItem` | ❌ 未实现 | ~16ms | 最新 API支持单窗口/单显示器,系统级权限管理 | Win10 1903+,首次需用户确认 |
### 推荐升级路径
```
当前: GDI BitBlt (mss) ─── 全屏 ~300ms, 窗口 ~300ms (PrintWindow)
├─ 近期: DXGI Desktop Duplication ─── 全屏 ~16ms, 但不支持单窗口
└─ 远期: Windows.Graphics.Capture ─── 全屏 + 单窗口都 ~16ms
```
### DXGI Desktop Duplication 实现要点
```python
# bridge.py 中可添加 DXGI 截图(通过 d3dshot 或 dxcam 库)
import dxcam # pip install dxcam
camera = dxcam.create()
frame = camera.grab() # numpy array, ~5ms
# 转为 JPEG base64 发送
```
### Windows.Graphics.Capture 实现要点
```python
# 需要 WinRT Python 绑定
# pip install winrt-Windows.Graphics.Capture winrt-Windows.Graphics.DirectX
# 限制:首次调用需要用户在系统弹窗中确认权限
```
---
## 输入方式技术矩阵
不同应用类型需要不同的输入方式:
| 输入方式 | API | 优势 | 限制 | 适用应用 |
|---------|-----|------|------|---------|
| **SendMessageW** | `WM_CHAR` / `WM_KEYDOWN` | 不抢焦点,不动真实键鼠 | 现代应用不支持 | Win32 传统应用 (记事本/Office/WPF) |
| **SendInput** | `INPUT` 结构体 | 所有应用都支持 | **必须前台焦点**,会干扰用户 | 所有应用(通用后备) |
| **WriteConsoleInput** | 控制台 API | 直接写入控制台缓冲区 | 需要 AttachConsole可能被拒绝 | cmd/PowerShell非 Windows Terminal |
| **UI Automation** | `InvokePattern` / `ValuePattern` | 语义级操作,最可靠 | 部分应用不暴露 UIA 接口 | 支持 UIA 的应用 |
| **COM Automation** | Excel/Word COM | 完全编程控制 | 仅 Office 应用 | Excel / Word |
| **剪贴板 + 粘贴** | `SetClipboardData` + `Ctrl+V` | 绕过输入限制 | 会覆盖用户剪贴板 | 通用后备 |
### 按应用类型的推荐输入策略
| 应用类型 | 首选 | 后备 | 说明 |
|---------|------|------|------|
| 传统 Win32 (记事本/写字板) | SendMessageW | UIA ValuePattern | 虚拟输入完美工作 |
| Office (Excel/Word) | COM Automation | SendMessageW | COM 提供结构化操作 |
| WPF 应用 | SendMessageW | UIA | 标准 Win32 消息循环 |
| Electron/Chrome 应用 | UIA | 剪贴板粘贴 | 内部渲染不走 Win32 |
| Windows Terminal (ConPTY) | SendInput (需前台) | 剪贴板粘贴 | ConPTY 不接受外部消息 |
| UWP/WinUI 应用 | SendInput (需前台) | UIA | XAML 渲染不走 Win32 消息 |
---
## 已知限制与待解决
| 限制 | 影响 | 计划 |
|------|------|------|
| Windows Terminal 不接受 SendMessageW | 虚拟键盘/鼠标对终端无效 | 自动检测应用类型,终端类切换到 SendInput + 短暂激活 |
| PrintWindow 截不到 alternate screen buffer | Ink REPL 画面截不到 | 切换到 Windows.Graphics.Capture |
| Accessibility Snapshot 对大应用慢 (>30s) | Excel 等复杂应用超时 | 限制遍历深度 + 超时保护 |
| DWM 边框对自定义标题栏应用可能无效 | 某些 Electron 应用看不到边框 | 检测并回退到叠加窗口方案 |
| 虚拟光标是 PowerShell WinForms 进程 | 启动慢 (~1s),资源占用 | 考虑用 Win32 原生窗口替代 |
---
## 技术路线图
### Phase 1当前— 基础功能
- ✅ SendMessageW 虚拟输入
- ✅ PrintWindow/mss 截图
- ✅ UI Automation (InvokePattern + ValuePattern)
- ✅ Accessibility Snapshot
- ✅ DWM 边框指示
- ✅ Python Bridge
### Phase 2近期— 兼容性增强
- ⬜ 应用类型自动检测Win32 vs Terminal vs UWP
- ⬜ 终端类应用自动切换 SendInput + 短暂激活
- ⬜ TogglePattern / SelectionPattern 支持
- ⬜ DXGI Desktop Duplication 高速截图
- ⬜ Accessibility Snapshot 超时保护
### Phase 3远期— 高级能力
- ⬜ Windows.Graphics.Capture单窗口实时截图
- ⬜ 截图元素标注(在截图上标记 ID 数字)
- ⬜ 浏览器 DOM 提取(绑定浏览器时提取网页结构)
- ⬜ GridPattern / TablePatternExcel 单元格级操作)
- ⬜ TextPattern文档内容读取
- ⬜ 多窗口协同操作

View File

@@ -0,0 +1,315 @@
# Computer Use Windows 增强实施计划
更新时间2026-04-03
依赖文档:`docs/features/windows-ai-desktop-control.md``docs/features/computer-use.md`
## 1. 目标
在已有的 PowerShell 子进程方案基础上,利用 Windows 原生 API 增强 Computer Use 的 Windows 实现,解决 3 个核心问题:
1. **窗口绑定截图**:当前 `CopyFromScreen` 只能全屏截图,无法对指定窗口截图(尤其是被遮挡/最小化窗口)
2. **UI 结构感知**:当前只能通过坐标点击,无法像 macOS Accessibility 那样理解 UI 元素树
3. **性能**:每次 PowerShell 启动约 273ms剪贴板/窗口枚举等高频操作需要更快的方式
## 2. 已验证的 Windows API 能力
以下 API 全部通过 PowerShell P/Invoke 实测通过:
| 能力 | API | 验证结果 |
|------|-----|---------|
| 窗口绑定截图 | `PrintWindow(hwnd, hdc, PW_RENDERFULLCONTENT)` | ✅ VS Code 342KB, Chrome 273KB |
| 枚举窗口+HWND | `EnumWindows` + `GetWindowText` + `GetWindowThreadProcessId` | ✅ 38 个窗口,含 HWND/PID/标题 |
| UI 元素树 | `System.Windows.Automation.AutomationElement` | ✅ 记事本 39 个元素 |
| UI 写值 | `ValuePattern.SetValue()` | ✅ 成功写入记事本文本 |
| UI 点击 | `InvokePattern.Invoke()` | ✅ 按钮可程序化点击 |
| 坐标元素识别 | `AutomationElement.FromPoint(x, y)` | ✅ 返回元素类型+名称 |
| OCR | `Windows.Media.Ocr.OcrEngine` | ✅ 英语+中文引擎可用 |
| 全局热键 | `RegisterHotKey` | ✅ API 可调 |
| 剪贴板直接操作 | `System.Windows.Forms.Clipboard` | ✅ 读/写/图片检测 |
| Shell 启动 | `ShellExecute` | ✅ 打开文件/URL/应用 |
## 3. 架构设计
### 3.1 文件结构
在现有 `backends/win32.ts` 基础上新增 Windows 专属模块:
```
packages/@ant/computer-use-input/src/
├── backends/
│ ├── darwin.ts ← 不动
│ ├── win32.ts ← 增强:直接 Win32 API 替代部分 PowerShell
│ └── linux.ts ← 不动
packages/@ant/computer-use-swift/src/
├── backends/
│ ├── darwin.ts ← 不动
│ ├── win32.ts ← 增强PrintWindow 窗口截图 + EnumWindows
│ └── linux.ts ← 不动
packages/@ant/computer-use-mcp/src/
│ └── tools.ts ← 增加 Windows 专属工具定义UI Automation、OCR
src/utils/computerUse/
│ └── win32/ ← 新增目录Windows 专属能力
│ ├── uiAutomation.ts ← UI 元素树、点击、写值
│ ├── ocr.ts ← 截图 + OCR 文字识别
│ ├── windowCapture.ts ← PrintWindow 窗口绑定截图
│ └── windowEnum.ts ← EnumWindows 窗口枚举
```
### 3.2 分层
```
┌──────────────────────────────────────────────┐
│ Computer Use MCP Tools │
│ screenshot / click / type / request_access │
│ + Windows 专属: ui_tree / ocr / window_cap │
├──────────────────────────────────────────────┤
│ src/utils/computerUse/ │
│ executor.ts → 按平台 dispatch │
│ win32/ → Windows 专属能力模块 │
├──────────────────────────────────────────────┤
│ packages/@ant/computer-use-{input,swift} │
│ backends/win32.ts → PowerShell + Win32 API │
├──────────────────────────────────────────────┤
│ Windows Native API │
│ PrintWindow / EnumWindows / UI Automation │
│ SendInput / Clipboard / OCR / ShellExecute │
└──────────────────────────────────────────────┘
```
## 4. 实施计划
### Phase A窗口绑定截图解决核心问题
**问题**:当前 `CopyFromScreen` 只能全屏截图,无法对指定窗口截图。
**方案**:用 `PrintWindow` + `FindWindow` 实现窗口级截图。
| 步骤 | 文件 | 改动 |
|------|------|------|
| A.1 | `src/utils/computerUse/win32/windowCapture.ts` | 新建:`captureWindow(title)` 用 PrintWindow 截取指定窗口 |
| A.2 | `src/utils/computerUse/win32/windowEnum.ts` | 新建:`listWindows()` 用 EnumWindows 返回 {hwnd, pid, title}[] |
| A.3 | `packages/@ant/computer-use-swift/src/backends/win32.ts` | `screenshot.captureExcluding` 增加按窗口截图能力 |
| A.4 | `packages/@ant/computer-use-swift/src/backends/win32.ts` | `apps.listRunning` 用 EnumWindows 替代 Get-Process返回 HWND |
**PowerShell 脚本核心**
```powershell
# PrintWindow 截取指定窗口
Add-Type -AssemblyName System.Drawing
Add-Type -ReferencedAssemblies System.Drawing @'
using System; using System.Runtime.InteropServices; using System.Drawing; using System.Drawing.Imaging;
public class WinCap {
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr FindWindow(string c, string t);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr h, out RECT r);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr h, IntPtr hdc, uint f);
[StructLayout(LayoutKind.Sequential)]
public struct RECT { public int L, T, R, B; }
// ... CaptureByTitle(string title) → base64
}
'@
```
**验证标准**
- 能按窗口标题截图
- 被遮挡的窗口也能截图
- 返回 base64 + width + height
### Phase BUI AutomationWindows 专属新能力)
**问题**macOS 有 Accessibility API 可以读取/操作 UI 元素Windows 当前只能坐标点击。
**方案**:用 `System.Windows.Automation` 实现 UI 树读取和元素操作。
| 步骤 | 文件 | 改动 |
|------|------|------|
| B.1 | `src/utils/computerUse/win32/uiAutomation.ts` | 新建:核心 UIA 操作封装 |
| B.2 | `packages/@ant/computer-use-mcp/src/tools.ts` | 增加 Windows 专属工具定义 |
**uiAutomation.ts 导出函数**
```typescript
// 获取窗口的 UI 元素树
getUITree(windowTitle: string, depth: number): UIElement[]
// 按名称/类型/AutomationId 查找元素
findElement(windowTitle: string, query: {name?, controlType?, automationId?}): UIElement | null
// 点击元素InvokePattern
clickElement(windowTitle: string, automationId: string): boolean
// 设置元素值ValuePattern
setValue(windowTitle: string, automationId: string, value: string): boolean
// 获取坐标处的元素
elementAtPoint(x: number, y: number): UIElement | null
```
**UIElement 类型**
```typescript
interface UIElement {
name: string
controlType: string // Button, Edit, Text, List, etc.
automationId: string
boundingRect: { x: number, y: number, w: number, h: number }
isEnabled: boolean
value?: string // ValuePattern 可用时
children?: UIElement[]
}
```
**PowerShell 脚本核心**
```powershell
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
# 读取 UI 树
$root = [AutomationElement]::RootElement
$window = $root.FindFirst([TreeScope]::Children,
[PropertyCondition]::new([AutomationElement]::NameProperty, $title))
$elements = $window.FindAll([TreeScope]::Descendants, [Condition]::TrueCondition)
# 写入文本
$element.GetCurrentPattern([ValuePattern]::Pattern).SetValue($text)
# 点击按钮
$element.GetCurrentPattern([InvokePattern]::Pattern).Invoke()
```
**验证标准**
- 能读取记事本的 UI 树(按钮、文本框、菜单)
- 能向文本框写入内容
- 能点击按钮
- 能识别坐标处的元素
### Phase COCR 屏幕文字识别
**问题**:截图后 AI 只能看到图片,无法直接读取文字。
**方案**:用 `Windows.Media.Ocr` 对截图进行文字识别。
| 步骤 | 文件 | 改动 |
|------|------|------|
| C.1 | `src/utils/computerUse/win32/ocr.ts` | 新建:截图 + OCR 识别 |
| C.2 | `packages/@ant/computer-use-mcp/src/tools.ts` | 增加 `screen_ocr` 工具定义 |
**ocr.ts 导出函数**
```typescript
// 对屏幕区域 OCR
ocrRegion(x: number, y: number, w: number, h: number, lang?: string): OcrResult
// 对指定窗口 OCR
ocrWindow(windowTitle: string, lang?: string): OcrResult
interface OcrResult {
text: string
lines: { text: string, bounds: {x,y,w,h} }[]
language: string
}
```
**已确认可用语言**:英语 (en-US) + 中文 (zh-Hans-CN)
**验证标准**
- 能识别屏幕区域中的英文和中文
- 返回文字内容 + 每行的位置信息
### Phase D高频操作性能优化
**问题**:每次 PowerShell 启动 273ms鼠标移动等高频操作太慢。
**方案**:用 .NET `System.Windows.Forms.Clipboard` 等直接 API 替代 PowerShell 子进程。
| 步骤 | 文件 | 改动 |
|------|------|------|
| D.1 | `src/utils/computerUse/executor.ts` | 剪贴板操作用直接 API 替代 PowerShell |
| D.2 | 考虑驻留 PowerShell 进程 | 通过 stdin/stdout 交互,摊平启动成本 |
**剪贴板直接 API**(不需要 PowerShell 子进程):
```powershell
# 读50ms → <1ms
[System.Windows.Forms.Clipboard]::GetText()
# 写50ms → <1ms
[System.Windows.Forms.Clipboard]::SetText($text)
# 图片检测
[System.Windows.Forms.Clipboard]::ContainsImage()
```
### Phase E`request_access` Windows 适配
**问题**`request_access` 依赖 macOS bundleId 识别应用Windows 没有这个概念。
**方案**:在 Windows 上用 exe 路径 + 窗口标题替代 bundleId。
| 步骤 | 文件 | 改动 |
|------|------|------|
| E.1 | `packages/@ant/computer-use-mcp/src/toolCalls.ts` | `resolveRequestedApps` 在 Windows 上用 exe 路径匹配 |
| E.2 | `packages/@ant/computer-use-mcp/src/sentinelApps.ts` | 增加 Windows 危险应用列表cmd.exe, powershell.exe 等) |
| E.3 | `packages/@ant/computer-use-mcp/src/deniedApps.ts` | 增加 Windows 浏览器/终端识别规则 |
| E.4 | `src/utils/computerUse/hostAdapter.ts` | `ensureOsPermissions` Windows 上检查 UAC 状态 |
**Windows 应用标识映射**
```
macOS bundleId → Windows 等价
com.apple.Safari → C:\Program Files\...\msedge.exe或窗口标题匹配
com.google.Chrome → chrome.exe
com.apple.Terminal → WindowsTerminal.exe / cmd.exe
```
### Phase F全局热键ESC 拦截)
**问题**:当前非 darwin 直接跳过 ESC 热键,用 Ctrl+C 替代。
**方案**:用 `RegisterHotKey``SetWindowsHookEx(WH_KEYBOARD_LL)` 实现。
| 步骤 | 文件 | 改动 |
|------|------|------|
| F.1 | `src/utils/computerUse/escHotkey.ts` | Windows 分支RegisterHotKey 注册 ESC |
**优先级低**——当前 Ctrl+C fallback 可用ESC 热键是体验优化。
## 5. 执行优先级
```
Phase A: 窗口绑定截图 ← P0 核心需求,解决"操作其他界面"
Phase B: UI Automation ← P0 核心能力AI 理解 UI 结构
Phase C: OCR ← P1 增值能力AI 读屏幕文字
Phase D: 性能优化 ← P1 体验优化,高频操作提速
Phase E: request_access 适配 ← P1 功能完整性,权限模型适配
Phase F: ESC 热键 ← P2 体验优化,可后做
```
## 6. 每个 Phase 的改动量估算
| Phase | 新增文件 | 修改文件 | 新增代码行 | 风险 |
|-------|---------|---------|-----------|------|
| A 窗口截图 | 2 | 1 | ~200 | 低 |
| B UI Automation | 1 | 1 | ~300 | 中 |
| C OCR | 1 | 1 | ~150 | 低 |
| D 性能优化 | 0 | 2 | ~50 | 低 |
| E request_access | 0 | 3 | ~100 | 中 |
| F ESC 热键 | 0 | 1 | ~50 | 低 |
| **总计** | **4** | **9** | **~850** | — |
## 7. 不动的文件
- `backends/darwin.ts`(两个包都不动)
- `backends/linux.ts`(两个包都不动)
- `src/utils/computerUse/` 中 macOS 相关代码路径不动
- `packages/@ant/computer-use-mcp/src/` 中已复制的参考项目代码不动(只追加 Windows 工具)
## 8. 与 macOS/Linux 方案的对比
| 能力 | macOS | Windows (增强后) | Linux |
|------|-------|-----------------|-------|
| 截图方式 | SCContentFilter (per-app) | **PrintWindow (per-window)** | scrot (全屏/区域) |
| UI 结构 | Accessibility API | **UI Automation** | 无 |
| OCR | 无内置 | **Windows.Media.Ocr** | 无内置 |
| 键鼠 | CGEvent + enigo | SendInput + keybd_event | xdotool |
| 窗口管理 | NSWorkspace | **EnumWindows + Win32** | wmctrl |
| 剪贴板 | pbcopy/pbpaste | **Clipboard 直接 API** | xclip |
| ESC 热键 | CGEventTap | RegisterHotKey | 无 |
| 应用标识 | bundleId | exe 路径 + 窗口标题 | /proc + wmctrl |
**Windows 增强后将在 UI Automation 和 OCR 方面超过 macOS 方案**——这两项 macOS 原始实现也没有Anthropic 用的是截图 + Claude 视觉理解,没有结构化 UI 数据)。

View File

@@ -0,0 +1,197 @@
# Computer Use — macOS / Windows / Linux 跨平台实施计划
更新时间2026-04-03
参考项目:`E:\源码\claude-code-source-main\claude-code-source-main`
## 1. 现状
参考项目的 Computer Use **仅支持 macOS**——从入口到底层全部写死 darwin。我们的项目在 Phase 1-3 中已经完成了:
-`@ant/computer-use-mcp` stub 替换为完整实现12 文件)
-`@ant/computer-use-input` 拆为 dispatcher + backendsdarwin + win32
-`@ant/computer-use-swift` 拆为 dispatcher + backendsdarwin + win32
-`CHICAGO_MCP` 编译开关已开
-`src/` 层有 6 处 macOS 硬编码阻塞
## 2. 阻塞点全景
### 2.1 入口层
| # | 文件:行号 | 阻塞代码 | 影响 |
|---|----------|---------|------|
| 1 | `src/main.tsx:1605` | `getPlatform() === 'macos'` | 整个 CU 初始化被跳过 |
### 2.2 加载层
| # | 文件:行号 | 阻塞代码 | 影响 |
|---|----------|---------|------|
| 2 | `src/utils/computerUse/swiftLoader.ts:16` | `process.platform !== 'darwin'` → throw | 截图、应用管理全部不可用 |
| 3 | `src/utils/computerUse/executor.ts:263` | `process.platform !== 'darwin'` → throw | 整个 executor 工厂函数不可用 |
### 2.3 macOS 特有依赖
| # | 文件:行号 | 依赖 | macOS 实现 | 需要替代方案 |
|---|----------|------|-----------|------------|
| 4 | `executor.ts:70-88` | 剪贴板 | `pbcopy`/`pbpaste` | Win: PowerShell `Get/Set-Clipboard`Linux: `xclip`/`wl-copy` |
| 5 | `drainRunLoop.ts:21` | CFRunLoop pump | `cu._drainMainRunLoop()` | 非 darwin直接执行 fn(),不需要 pump |
| 6 | `escHotkey.ts:28` | ESC 热键 | CGEventTap | 非 darwin返回 false已有 Ctrl+C fallback |
| 7 | `hostAdapter.ts:48-54` | 系统权限 | TCC accessibility + screenRecording | Win直接 grantedLinux检查 xdotool |
| 8 | `common.ts:56` | 平台标识 | `platform: 'darwin'` 硬编码 | 动态获取 |
| 9 | `executor.ts:180` | 粘贴快捷键 | `command+v` | Win/Linux`ctrl+v` |
### 2.4 缺失的 Linux 后端
| 包 | macOS | Windows | Linux |
|---|-------|---------|-------|
| `computer-use-input/backends/` | ✅ darwin.ts | ✅ win32.ts | ❌ 需新建 linux.ts |
| `computer-use-swift/backends/` | ✅ darwin.ts | ✅ win32.ts | ❌ 需新建 linux.ts |
## 3. 每个平台的能力依赖
### 3.1 computer-use-input键鼠
| 功能 | macOS | Windows | Linux |
|------|-------|---------|-------|
| 鼠标移动 | CGEvent JXA | SetCursorPos P/Invoke | xdotool mousemove |
| 鼠标点击 | CGEvent JXA | SendInput P/Invoke | xdotool click |
| 鼠标滚轮 | CGEvent JXA | SendInput MOUSEEVENTF_WHEEL | xdotool scroll |
| 键盘按键 | System Events osascript | keybd_event P/Invoke | xdotool key |
| 组合键 | System Events osascript | keybd_event 组合 | xdotool key combo |
| 文本输入 | System Events keystroke | SendKeys.SendWait | xdotool type |
| 前台应用 | System Events osascript | GetForegroundWindow P/Invoke | xdotool getactivewindow + /proc |
| 工具依赖 | osascript内置 | powershell内置 | xdotool需安装 |
### 3.2 computer-use-swift截图 + 应用管理)
| 功能 | macOS | Windows | Linux |
|------|-------|---------|-------|
| 全屏截图 | screencapture | CopyFromScreen | gnome-screenshot / scrot / grim |
| 区域截图 | screencapture -R | CopyFromScreen(rect) | gnome-screenshot -a / scrot -a / grim -g |
| 显示器列表 | CGGetActiveDisplayList JXA | Screen.AllScreens | xrandr --query |
| 运行中应用 | System Events JXA | Get-Process | wmctrl -l / ps |
| 打开应用 | osascript activate | Start-Process | xdg-open / gtk-launch |
| 隐藏/显示 | System Events visibility | ShowWindow/SetForegroundWindow | wmctrl -c / xdotool |
| 工具依赖 | screencapture + osascript | powershell | xdotool + scrot/grim + wmctrl |
### 3.3 executor 层
| 功能 | macOS | Windows | Linux |
|------|-------|---------|-------|
| drainRunLoop | CFRunLoop pump | 不需要 | 不需要 |
| ESC 热键 | CGEventTap | 跳过Ctrl+C fallback | 跳过Ctrl+C fallback |
| 剪贴板读 | pbpaste | `powershell Get-Clipboard` | xclip -o / wl-paste |
| 剪贴板写 | pbcopy | `powershell Set-Clipboard` | xclip / wl-copy |
| 粘贴快捷键 | command+v | ctrl+v | ctrl+v |
| 终端检测 | __CFBundleIdentifier | WT_SESSION / TERM_PROGRAM | TERM_PROGRAM |
| 系统权限 | TCC check | 直接 granted | 检查 xdotool 安装 |
## 4. 执行步骤
### Phase 1已完成 ✅
- [x] `@ant/computer-use-mcp` stub → 完整实现
- [x] `@ant/computer-use-input` dispatcher + darwin/win32 backends
- [x] `@ant/computer-use-swift` dispatcher + darwin/win32 backends
- [x] `CHICAGO_MCP` 编译开关
### Phase 2移除 6 处 macOS 硬编码(解锁 macOS + Windows
**改动原则macOS 代码路径不变,只在每处 darwin 守卫后加 win32/linux 分支。**
| 步骤 | 文件 | 改动 |
|------|------|------|
| 2.1 | `src/main.tsx:1605` | `getPlatform() === 'macos'` → 去掉平台限制,或改为 `!== 'unknown'` |
| 2.2 | `src/utils/computerUse/swiftLoader.ts:16-18` | 移除 `process.platform !== 'darwin'` throw。`@ant/computer-use-swift/index.ts` 已有跨平台 dispatch |
| 2.3 | `src/utils/computerUse/executor.ts:263-267` | 移除 `process.platform !== 'darwin'` throw。改为检查 input/swift isSupported |
| 2.4 | `src/utils/computerUse/executor.ts:70-88` | 剪贴板函数按平台分发darwin→pbcopy/pbpastewin32→PowerShell Get/Set-Clipboardlinux→xclip |
| 2.5 | `src/utils/computerUse/executor.ts:180` | `typeViaClipboard``command+v` → 非 darwin 时用 `ctrl+v` |
| 2.6 | `src/utils/computerUse/executor.ts:273` | `const cu = requireComputerUseSwift()` → 改为 `new ComputerUseAPI()`(从 package 直接实例化,不走 swiftLoader throw |
| 2.7 | `src/utils/computerUse/drainRunLoop.ts` | 开头加 `if (process.platform !== 'darwin') return fn()` |
| 2.8 | `src/utils/computerUse/escHotkey.ts` | `registerEscHotkey` 非 darwin 返回 false已有 Ctrl+C fallback |
| 2.9 | `src/utils/computerUse/hostAdapter.ts:48-54` | `ensureOsPermissions` 非 darwin 返回 `{ granted: true }` |
| 2.10 | `src/utils/computerUse/common.ts:56` | `platform: 'darwin'``platform: process.platform === 'win32' ? 'windows' : process.platform === 'linux' ? 'linux' : 'darwin'` |
| 2.11 | `src/utils/computerUse/common.ts:55` | `screenshotFiltering: 'native'` → 非 darwin 时 `'none'`Windows/Linux 截图不支持 per-app 过滤) |
| 2.12 | `src/utils/computerUse/gates.ts:13` | `enabled: false``enabled: true`(无 GrowthBook 时默认可用) |
| 2.13 | `src/utils/computerUse/gates.ts:39-43` | `hasRequiredSubscription()` → 直接返回 `true` |
### Phase 3新增 Linux 后端
| 步骤 | 文件 | 内容 |
|------|------|------|
| 3.1 | `packages/@ant/computer-use-input/src/backends/linux.ts` | xdotool 键鼠mousemove/click/key/type/getactivewindow |
| 3.2 | `packages/@ant/computer-use-swift/src/backends/linux.ts` | scrot/grim 截图 + xrandr 显示器 + wmctrl 窗口管理 |
| 3.3 | `packages/@ant/computer-use-input/src/index.ts` | dispatcher 加 `case 'linux'` |
| 3.4 | `packages/@ant/computer-use-swift/src/index.ts` | dispatcher 加 `case 'linux'` |
### Phase 4验证
| 测试项 | macOS | Windows | Linux |
|--------|-------|---------|-------|
| build 成功 | ✅ | 验证 | 验证 |
| MCP 工具列表非空 | 验证 | 验证 | 验证 |
| 鼠标移动 | 验证 | ✅ 已通过 | 验证 |
| 截图 | 验证 | ✅ 已通过 | 验证 |
| 键盘输入 | 验证 | 验证 | 验证 |
| 前台窗口 | 验证 | ✅ 已通过 | 验证 |
| 剪贴板 | 验证 | 验证 | 验证 |
## 5. 文件改动总览
### 不动的文件14 个)
`cleanup.ts``computerUseLock.ts``wrapper.tsx``toolRendering.tsx``mcpServer.ts``setup.ts``appNames.ts``inputLoader.ts``src/services/mcp/client.ts``@ant/computer-use-mcp/src/*`Phase 1 已完成)、`backends/darwin.ts`(两个包都不动)
### 改 src/ 的文件8 个)
| 文件 | 改动量 | 风险 |
|------|--------|------|
| `main.tsx` | 1 行 | 低 |
| `swiftLoader.ts` | 2 行 | 低 |
| `executor.ts` | ~40 行(剪贴板分发 + 平台守卫 + paste 快捷键) | **中** |
| `drainRunLoop.ts` | 1 行 | 低 |
| `escHotkey.ts` | 3 行 | 低 |
| `hostAdapter.ts` | 5 行 | 低 |
| `common.ts` | 3 行 | 低 |
| `gates.ts` | 3 行 | 低 |
### 新增文件2 个)
| 文件 | 行数估算 |
|------|---------|
| `packages/@ant/computer-use-input/src/backends/linux.ts` | ~150 行 |
| `packages/@ant/computer-use-swift/src/backends/linux.ts` | ~200 行 |
## 6. Linux 依赖工具
| 工具 | 用途 | 安装命令Ubuntu |
|------|------|-------------------|
| `xdotool` | 键鼠模拟 + 窗口管理 | `sudo apt install xdotool` |
| `scrot``gnome-screenshot` | 截图 | `sudo apt install scrot` |
| `xrandr` | 显示器信息 | 通常已预装 |
| `xclip` | 剪贴板 | `sudo apt install xclip` |
| `wmctrl` | 窗口列表/切换 | `sudo apt install wmctrl` |
Wayland 环境需要替代工具:`ydotool`(替代 xdotool`grim`(替代 scrot`wl-clipboard`(替代 xclip。初期可先只支持 X11Wayland 标记为 todo。
## 7. 执行顺序建议
```
Phase 2解锁 macOS + Windows
├── 2.1-2.3 移除 3 处硬编码 throw/skip
├── 2.4-2.5 剪贴板 + 粘贴快捷键平台分发
├── 2.6 swiftLoader → 直接实例化
├── 2.7-2.9 drainRunLoop / escHotkey / permissions 平台分支
├── 2.10-2.11 common.ts 平台标识动态化
├── 2.12-2.13 gates.ts 默认值
└── 验证 Windows
Phase 3Linux 后端)
├── 3.1 input/backends/linux.ts
├── 3.2 swift/backends/linux.ts
├── 3.3-3.4 dispatcher 加 linux case
└── 验证 Linux
Phase 4集成验证 + PR
```
每个 Phase 可独立验证、独立提交。Phase 2 完成后 macOS + Windows 可用Phase 3 完成后三平台全部可用。

View File

@@ -0,0 +1,140 @@
# CONTEXT_COLLAPSE — 上下文折叠
> Feature Flag: `FEATURE_CONTEXT_COLLAPSE=1`
> 子 Feature: `FEATURE_HISTORY_SNIP=1`
> 实现状态:核心逻辑全部 Stub布线完整
> 引用数CONTEXT_COLLAPSE 20 + HISTORY_SNIP 16 = 36
## 一、功能概述
CONTEXT_COLLAPSE 让模型内省上下文窗口使用情况,并智能压缩旧消息。当对话接近上下文限制时,自动将旧消息折叠为压缩摘要,保留关键信息的同时释放 token 空间。
### 子 Feature
| Feature | 功能 |
|---------|------|
| `CONTEXT_COLLAPSE` | 上下文折叠引擎(后台 LLM 调用压缩旧消息) |
| `HISTORY_SNIP` | SnipTool — 标记消息进行折叠/修剪 |
## 二、实现架构
### 2.1 模块状态
| 模块 | 文件 | 状态 |
|------|------|------|
| 折叠核心 | `src/services/contextCollapse/index.ts` | **Stub** — 接口完整(`ContextCollapseStats``CollapseResult``DrainResult`),函数全部空操作 |
| 折叠操作 | `src/services/contextCollapse/operations.ts` | **Stub**`projectView` 为恒等函数 |
| 折叠持久化 | `src/services/contextCollapse/persist.ts` | **Stub**`restoreFromEntries` 为空操作 |
| CtxInspectTool | `src/tools/CtxInspectTool/` | **缺失** — 目录不存在 |
| SnipTool 提示 | `src/tools/SnipTool/prompt.ts` | **Stub** — 空工具名 |
| SnipTool 实现 | `src/tools/SnipTool/SnipTool.ts` | **缺失** |
| force-snip 命令 | `src/commands/force-snip.js` | **缺失** |
| 折叠读取搜索 | `src/utils/collapseReadSearch.ts` | **完整** — Snip 作为静默吸收操作 |
| QueryEngine 集成 | `src/QueryEngine.ts` | **布线** — 导入并使用 snip 投影 |
| Token 警告 UI | `src/components/TokenWarning.tsx` | **布线** — 折叠进度标签 |
### 2.2 核心接口(已定义,待实现)
```ts
// contextCollapse/index.ts
interface ContextCollapseStats {
// 上下文使用统计
}
interface CollapseResult {
// 折叠操作结果
}
interface DrainResult {
// 紧急释放结果
}
// 关键函数(全部 stub
isContextCollapseEnabled() // → false
applyCollapsesIfNeeded(messages) // 透传
recoverFromOverflow(messages) // 透传413 恢复)
initContextCollapse() // 空操作
```
### 2.3 预期数据流
```
对话持续增长
上下文接近限制(由 query.ts 检测)
├── 溢出检测 (query.ts:440,616,802)
applyCollapsesIfNeeded(messages) [需要实现]
├── 后台 LLM 调用压缩旧消息
├── 保留关键信息(决策、文件路径、错误)
└── 替换旧消息为压缩摘要
├── 413 恢复 (query.ts:1093,1179)
│ └── recoverFromOverflow() 紧急折叠
projectView() 过滤折叠后的消息视图
模型继续工作(在压缩后的上下文中)
```
### 2.4 HISTORY_SNIP 子功能
SnipTool 提供手动折叠能力:
- `/force-snip` 命令 — 强制执行折叠
- SnipTool — 标记特定消息进行折叠/修剪
- `collapseReadSearch.ts` 已完整实现,将 Snip 作为静默吸收操作处理
### 2.5 集成点
| 文件 | 位置 | 说明 |
|------|------|------|
| `src/query.ts` | 18,440,616,802,1093,1179 | 溢出检测、413 恢复、折叠应用 |
| `src/QueryEngine.ts` | 124,127,1301 | Snip 投影使用 |
| `src/utils/analyzeContext.ts` | 1122 | 跳过保留缓冲区显示 |
| `src/utils/sessionRestore.ts` | 127,494 | 恢复折叠状态 |
| `src/services/compact/autoCompact.ts` | 179,215 | 自动压缩时考虑折叠 |
## 三、需要补全的内容
| 优先级 | 模块 | 工作量 | 说明 |
|--------|------|--------|------|
| 1 | `services/contextCollapse/index.ts` | 大 | 折叠状态机、LLM 调用、消息压缩 |
| 2 | `services/contextCollapse/operations.ts` | 中 | `projectView()` 消息过滤 |
| 3 | `services/contextCollapse/persist.ts` | 小 | `restoreFromEntries()` 磁盘持久化 |
| 4 | `tools/CtxInspectTool/` | 中 | 上下文内省工具token 计数、已折叠范围) |
| 5 | `tools/SnipTool/SnipTool.ts` | 中 | Snip 工具实现 |
| 6 | `commands/force-snip.js` | 小 | `/force-snip` 命令 |
## 四、关键设计决策
1. **后台 LLM 压缩**:折叠不是简单截断,而是用 LLM 生成压缩摘要保留关键信息
2. **413 恢复**:当 API 返回 413请求过大紧急折叠是最重要的恢复手段
3. **与 autoCompact 协作**折叠和自动压缩compact是不同的机制折叠在消息级别压缩在对话级别
4. **持久化**:折叠状态持久化到磁盘,会话恢复时重载
## 五、使用方式
```bash
# 启用 context collapse
FEATURE_CONTEXT_COLLAPSE=1 bun run dev
# 启用 snip 子功能
FEATURE_CONTEXT_COLLAPSE=1 FEATURE_HISTORY_SNIP=1 bun run dev
```
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/services/contextCollapse/index.ts` | 折叠核心stub接口已定义 |
| `src/services/contextCollapse/operations.ts` | 投影操作stub |
| `src/services/contextCollapse/persist.ts` | 持久化stub |
| `src/utils/collapseReadSearch.ts` | Snip 吸收操作(完整) |
| `src/query.ts` | 溢出检测和 413 恢复集成 |
| `src/QueryEngine.ts` | Snip 投影使用 |
| `src/components/TokenWarning.tsx` | 折叠进度 UI |

View File

@@ -0,0 +1,151 @@
# COORDINATOR_MODE — 多 Agent 编排
> Feature Flag: `FEATURE_COORDINATOR_MODE=1` + 环境变量 `CLAUDE_CODE_COORDINATOR_MODE=1`
> 实现状态编排者完整可用worker agent 为通用 AgentTool worker
> 引用数32
## 一、功能概述
COORDINATOR_MODE 将 CLI 变为"编排者"角色。编排者不直接操作文件,而是通过 AgentTool 派发任务给多个 worker 并行执行。适用于大型任务拆分、并行研究、实现+验证分离等场景。
### 核心约束
- 编排者只能使用:`Agent`(派发 worker`SendMessage`(继续 worker`TaskStop`(停止 worker
- Worker 可以使用所有标准工具Bash、Read、Edit 等)+ MCP 工具 + Skill 工具
- 编排者的每条消息都是给用户看的worker 结果以 `<task-notification>` XML 形式到达
## 二、用户交互
### 启用方式
```bash
FEATURE_COORDINATOR_MODE=1 CLAUDE_CODE_COORDINATOR_MODE=1 bun run dev
```
需要同时设置 feature flag 和环境变量。`CLAUDE_CODE_COORDINATOR_MODE` 可在会话恢复时自动切换(`matchSessionMode`)。
### 典型工作流
```
用户: "修复 auth 模块的 null pointer"
编排者:
1. 并行派发两个 worker:
- Agent({ description: "调查 auth bug", prompt: "..." })
- Agent({ description: "研究 auth 测试", prompt: "..." })
2. 收到 <task-notification>:
- Worker A: "在 validate.ts:42 发现 null pointer"
- Worker B: "测试覆盖情况..."
3. 综合发现,继续 Worker A:
- SendMessage({ to: "agent-a1b", message: "修复 validate.ts:42..." })
4. 收到修复结果,派发验证:
- Agent({ description: "验证修复", prompt: "..." })
```
## 三、实现架构
### 3.1 模式检测
文件:`src/coordinator/coordinatorMode.ts:36-41`
```ts
export function isCoordinatorMode(): boolean {
return feature('COORDINATOR_MODE') &&
isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE)
}
```
### 3.2 会话模式恢复
`matchSessionMode(sessionMode)` 在恢复旧会话时检查存储的模式,如果当前环境变量与存储不一致,自动翻转环境变量。防止在普通模式下恢复编排会话(或反之)。
### 3.3 Worker 工具集
`getCoordinatorUserContext()` 告知编排者 worker 可用的工具列表:
- **标准模式**`ASYNC_AGENT_ALLOWED_TOOLS` 排除内部工具TeamCreate、TeamDelete、SendMessage、SyntheticOutput
- **Simple 模式**`CLAUDE_CODE_SIMPLE=1`):仅 Bash、Read、Edit
- **MCP 工具**:列出已连接的 MCP 服务器名称
- **Scratchpad**:如果 GrowthBook `tengu_scratch` 启用,提供跨 worker 共享的 scratchpad 目录
### 3.4 系统提示
文件:`src/coordinator/coordinatorMode.ts:111-369`
编排者系统提示(`getCoordinatorSystemPrompt()`)约 370 行,包含:
| 章节 | 内容 |
|------|------|
| 1. Your Role | 编排者职责定义 |
| 2. Your Tools | Agent/SendMessage/TaskStop 使用说明 |
| 3. Workers | Worker 能力和限制 |
| 4. Task Workflow | Research → Synthesis → Implementation → Verification 流程 |
| 5. Writing Worker Prompts | 自包含 prompt 编写指南 + 好坏示例对比 |
| 6. Example Session | 完整示例对话 |
### 3.5 Worker Agent
文件:`src/coordinator/workerAgent.ts`
当前为 stub。Worker 实际使用通用 AgentTool 的 `worker` subagent_type。
### 3.6 数据流
```
用户消息
编排者 REPL受限工具集
├──→ Agent({ subagent_type: "worker", prompt: "..." })
│ │
│ ▼
│ Worker Agent完整工具集
│ ├── 执行任务Bash/Read/Edit/...
│ └── 返回 <task-notification>
├──→ SendMessage({ to: "agent-id", message: "..." })
│ │
│ ▼
│ 继续已存在的 Worker
└──→ TaskStop({ task_id: "agent-id" })
停止运行中的 Worker
```
## 四、关键设计决策
1. **双开关设计**feature flag 控制代码可用性,环境变量控制实际激活。允许编译时包含但不默认启用
2. **编排者受限**:只能用 Agent/SendMessage/TaskStop确保编排者专注于派发而非执行
3. **Worker 不可见编排者对话**:每个 worker 的 prompt 必须自包含(所有必要上下文)
4. **并行优先**:系统提示强调"Parallelism is your superpower",鼓励并行派发独立任务
5. **综合而非转发**:编排者必须理解 worker 发现,再写出具体的实现指令。禁止 "based on your findings" 类懒惰委托
6. **Scratchpad 可选共享**:通过 GrowthBook 门控的共享目录,让 worker 之间持久化共享知识
## 五、使用方式
```bash
# 基本启用
FEATURE_COORDINATOR_MODE=1 CLAUDE_CODE_COORDINATOR_MODE=1 bun run dev
# 配合 Fork Subagent
FEATURE_COORDINATOR_MODE=1 FEATURE_FORK_SUBAGENT=1 \
CLAUDE_CODE_COORDINATOR_MODE=1 bun run dev
# Simple 模式worker 只有 Bash/Read/Edit
FEATURE_COORDINATOR_MODE=1 CLAUDE_CODE_COORDINATOR_MODE=1 \
CLAUDE_CODE_SIMPLE=1 bun run dev
```
## 六、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/coordinator/coordinatorMode.ts` | 370 | 模式检测 + 系统提示 + 用户上下文 |
| `src/coordinator/workerAgent.ts` | — | Worker agent 定义stub |
| `src/constants/tools.ts` | — | `ASYNC_AGENT_ALLOWED_TOOLS` 工具白名单 |

View File

@@ -0,0 +1,318 @@
# Daemon 重构设计方案
> 分支: `feat/integrate-5-branches`
> 基于: `f41745cb` (= main `11bb3f62` 内容)
> 日期: 2026-04-13
## 一、问题概述
### 1.1 命令结构散乱
当前后台进程相关的命令分布在三个不同的位置,没有统一的命名空间:
| 命令 | 注册位置 | 入口 |
|------|---------|------|
| `claude daemon start/status/stop` | `cli.tsx` 快速路径 L203 | `daemon/main.ts` |
| `claude ps` | `cli.tsx` 快速路径 L220 | `cli/bg.ts` |
| `claude logs <x>` | `cli.tsx` 快速路径 L232 | `cli/bg.ts` |
| `claude attach <x>` | `cli.tsx` 快速路径 L236 | `cli/bg.ts` |
| `claude kill <x>` | `cli.tsx` 快速路径 L238 | `cli/bg.ts` |
| `claude --bg` | `cli.tsx` 快速路径 L244 | `cli/bg.ts` |
| `claude new/list/reply` | `cli.tsx` 快速路径 L250 | `cli/handlers/templateJobs.ts` |
| `claude rollback` | `main.tsx` Commander.js L6525 | `cli/rollback.ts` |
| `claude up` | `main.tsx` Commander.js L6511 | `cli/up.ts` |
**问题**:
- `ps/logs/attach/kill``daemon` 逻辑上都是后台进程管理,但互不关联
- 这些命令都**只有 CLI 入口**REPL 里输入 `/daemon``/ps` 不存在
- `new/list/reply` 是模板任务系统的顶级命令,容易与其他命令冲突(特别是 `list`
### 1.2 Windows 不支持
`--bg``attach` 硬依赖 tmux
- `bg.ts:handleBgFlag()` 第一步就检查 tmux不可用直接报错退出
- `bg.ts:attachHandler()``tmux attach-session`,无 tmux 替代方案
- Windows (包括 VS Code 终端) 完全无法使用后台会话功能
### 1.3 无 REPL 入口
对比 `/mcp` 的双注册模式:
- **CLI**: `claude mcp serve/add/remove/list` (Commander.js, `main.tsx:5760`)
- **REPL**: `/mcp enable/disable/reconnect` (slash command, `commands/mcp/index.ts`)
`daemon`/`bg`/`job` 系列只有 CLI 快速路径REPL 中完全不可用。
## 二、目标
1. **层级化命令结构**: 参照 `/mcp` 模式,将后台管理收归 `/daemon`,模板任务收归 `/job`
2. **跨平台后台会话**: Windows / macOS / Linux 都能启动、附着、终止后台会话
3. **双注册**: CLI (`claude daemon ...`) + REPL (`/daemon ...`) 同时可用
4. **向后兼容**: 旧命令保留但输出 deprecation 提示
## 三、命令结构设计
### 3.1 `/daemon` — 后台进程管理
合并 daemon supervisor + bg sessions 为统一命名空间:
```
claude daemon <subcommand> ← CLI 入口 (cli.tsx 快速路径)
/daemon <subcommand> ← REPL 入口 (slash command, local-jsx)
子命令:
status 综合状态面板 (daemon + 所有会话)
start [--dir <path>] 启动 daemon supervisor
stop 停止 daemon
bg [args...] 启动后台会话
attach [target] 附着到后台会话
logs [target] 查看会话日志
kill [target] 终止会话
(无参数) 等同于 status
```
**CLI 快速路径路由** (`cli.tsx`):
```typescript
// 新: 统一入口
if (feature('DAEMON') && args[0] === 'daemon') {
const sub = args[1] || 'status'
switch (sub) {
case 'start': case 'stop': case 'status':
await daemonMain([sub, ...args.slice(2)])
break
case 'bg':
await bg.handleBgStart(args.slice(2))
break
case 'attach': case 'logs': case 'kill':
await bg[`${sub}Handler`](args[2])
break
}
}
// 向后兼容 (deprecated)
if (feature('BG_SESSIONS') && ['ps','logs','attach','kill'].includes(args[0])) {
console.warn(`[deprecated] Use: claude daemon ${args[0] === 'ps' ? 'status' : args[0]}`)
// ... delegate to daemon subcommand
}
```
**REPL 斜杠命令** (`commands/daemon/index.ts`):
```typescript
const daemon = {
type: 'local-jsx',
name: 'daemon',
description: 'Manage background sessions and daemon',
argumentHint: '[status|start|stop|bg|attach|logs|kill]',
isEnabled: () => feature('DAEMON') || feature('BG_SESSIONS'),
load: () => import('./daemon.js'),
} satisfies Command
```
### 3.2 `/job` — 模板任务管理
```
claude job <subcommand> ← CLI 入口
/job <subcommand> ← REPL 入口
子命令:
list 列出模板和活跃任务
new <template> [args] 从模板创建任务
reply <id> <text> 回复任务
status <id> 查看任务状态
(无参数) 等同于 list
```
### 3.3 独立命令 (不变)
```
claude up 保持顶级 (简短的 bootstrap 命令)
claude rollback [target] 保持顶级 (低频运维命令)
```
## 四、跨平台后台引擎
### 4.1 引擎抽象
```typescript
// src/cli/bg/engine.ts
export interface BgEngine {
readonly name: string
/** 当前平台是否可用 */
available(): Promise<boolean>
/** 启动后台会话 */
start(opts: BgStartOptions): Promise<BgStartResult>
/** 附着到后台会话blocking */
attach(session: SessionEntry): Promise<void>
}
export interface BgStartOptions {
sessionName: string
args: string[]
env: Record<string, string | undefined>
logPath: string
cwd: string
}
export interface BgStartResult {
pid: number
sessionName: string
logPath: string
engineUsed: string
}
```
### 4.2 三种引擎实现
| 引擎 | 平台 | 启动方式 | attach 方式 |
|------|------|---------|------------|
| TmuxEngine | macOS/Linux (有 tmux) | `tmux new-session -d` | `tmux attach-session` |
| DetachedEngine | Windows / 无 tmux 的 macOS/Linux | `spawn({ detached, stdio→logFile })` | `tail -f` 日志文件 |
#### DetachedEngine 详细设计
**启动 (`start`)**:
```typescript
// 1. 打开日志文件 fd
const logFd = fs.openSync(logPath, 'a')
// 2. detached spawn, stdout/stderr 重定向到日志
const child = spawn(process.execPath, execArgs, {
detached: true,
stdio: ['ignore', logFd, logFd],
env,
cwd,
})
child.unref()
fs.closeSync(logFd)
// 3. 写 sessions/<PID>.json
```
**附着 (`attach`)**:
```typescript
// 跨平台 tail -f 实现
// 1. 读取已有日志内容输出到 stdout
// 2. fs.watch(logPath) 监听变化
// 3. 每次变化读取新增内容
// 4. Ctrl+C 退出 tail不杀后台进程
```
#### 引擎选择逻辑
```typescript
// src/cli/bg/engines/index.ts
export async function selectEngine(): Promise<BgEngine> {
if (process.platform === 'win32') {
return new DetachedEngine()
}
const tmux = new TmuxEngine()
if (await tmux.available()) {
return tmux
}
return new DetachedEngine()
}
```
### 4.3 SessionEntry 扩展
```typescript
interface SessionEntry {
// ... 现有字段
engine: 'tmux' | 'detached' // 新增: 记录使用的引擎
tmuxSessionName?: string // tmux 引擎才有
logPath?: string // 两种引擎都有
}
```
`attach` 时根据 `session.engine` 选择对应的 attach 策略。
## 五、文件变更清单
### 新增文件 (10 个)
```
src/cli/bg/engine.ts BgEngine 接口定义
src/cli/bg/engines/tmux.ts TmuxEngine (从 bg.ts 提取)
src/cli/bg/engines/detached.ts DetachedEngine (新实现)
src/cli/bg/engines/index.ts 引擎选择 + re-export
src/cli/bg/tail.ts 跨平台日志 tail (用于 detached attach)
src/commands/daemon/index.ts /daemon REPL 斜杠命令注册
src/commands/daemon/daemon.tsx /daemon 子命令路由 + status UI
src/commands/job/index.ts /job REPL 斜杠命令注册
src/commands/job/job.tsx /job 子命令路由 + UI
docs/features/daemon-restructure-design.md 本设计文档
```
### 修改文件 (6 个)
```
src/cli/bg.ts 重构: handler 函数改为调用 BgEngine
src/entrypoints/cli.tsx 快速路径: daemon 统一入口 + 向后兼容
src/commands.ts 注册 /daemon 和 /job 斜杠命令
src/daemon/main.ts daemonMain() 增加 bg/ps/logs 子命令分发
src/main.tsx Commander.js: 可选注册 daemon/job 子命令
src/cli/handlers/templateJobs.ts 适配 /job 入口 (可能不需改)
```
### 不动的文件
```
src/daemon/state.ts daemon PID 状态管理 (无需改)
src/jobs/state.ts job 状态管理 (无需改)
src/jobs/templates.ts 模板发现 (无需改)
src/jobs/classifier.ts 任务分类器 (无需改)
src/cli/rollback.ts 保持顶级命令 (无需改)
src/cli/up.ts 保持顶级命令 (无需改)
```
## 六、可行性分析
### 6.1 风险评估
| 风险 | 级别 | 缓解措施 |
|------|------|---------|
| cli.tsx 快速路径修改影响启动性能 | 低 | 仅改路由逻辑import 仍然 lazy |
| DetachedEngine 的 attach 在 Windows 上 fs.watch 不可靠 | 中 | 使用轮询 fallback (setInterval + fs.stat) |
| 向后兼容的 deprecation 可能破坏脚本 | 低 | 旧命令保持可用,仅输出 stderr 警告 |
| REPL 中 /daemon bg 需要 spawn 子进程 | 中 | 参考 /assistant 的 NewInstallWizard (已有 spawn 先例) |
| tsc 类型兼容 | 低 | 接口定义清晰,不引入 any |
### 6.2 工作量估计
| Task | 文件数 | 复杂度 |
|------|--------|--------|
| Task 013: BgEngine 抽象 + 引擎实现 | 5 新增 + 1 修改 | 中 |
| Task 014: /daemon 命令层级化 | 3 新增 + 3 修改 | 中 |
| Task 015: /job 命令层级化 | 2 新增 + 2 修改 | 低 |
| Task 016: 向后兼容 + 测试 | 0 新增 + 2 修改 | 低 |
### 6.3 依赖关系
```
Task 013 (BgEngine) ← 无依赖,可独立开发
Task 014 (/daemon) ← 依赖 Task 013 (引擎选择)
Task 015 (/job) ← 无依赖,可与 013 并行
Task 016 (兼容) ← 依赖 Task 014 + 015
```
## 七、设计决策记录
### D1: 为什么 daemon + bg sessions 合为一个命名空间?
用户视角:都是"后台运行的东西"。分开会导致 `claude daemon status` 看 supervisor + `claude ps` 看会话,割裂感强。合并后 `claude daemon status` 一次性展示 supervisor 状态 + 所有会话列表。
### D2: 为什么 rollback/up 不收入 daemon
它们本质是**版本管理/环境初始化**,不是后台进程管理。`claude up` 是同步阻塞的 setup 脚本,不涉及 daemon 或后台会话。保持顶级更直观。
### D3: 为什么 DetachedEngine 的 attach 用 tail 而不是 IPC
1. 日志文件是最简单的跨平台方案,无需额外依赖
2. UDS Pipe IPC 系统 (usePipeIpc) 设计用于实例间通信,不是终端附着
3. tmux attach 的体验(完整 PTY无法在纯 detached 模式下复制tail 是最诚实的替代
### D4: 为什么不用 Windows Terminal 的 tab/pane API
Windows Terminal 的 `wt.exe` 新窗口/标签功能不够通用——用户可能在 VS Code、ConEmu、cmder 等终端中。detached + log 是唯一跨终端方案。

102
docs/features/daemon.md Normal file
View File

@@ -0,0 +1,102 @@
# DAEMON — 后台守护进程
> Feature Flag: `FEATURE_DAEMON=1`
> 实现状态:主进程和 worker 注册为 StubCLI 路由完整
> 引用数3
## 一、功能概述
DAEMON 将 Claude Code 变为后台守护进程。主进程supervisor管理多个 worker 进程的生命周期,通过 Unix 域套接字进行 IPC。适用于持续运行的后台服务场景如配合 BRIDGE_MODE 提供远程控制服务)。
## 二、实现架构
### 2.1 模块状态
| 模块 | 文件 | 状态 |
|------|------|------|
| 守护主进程 | `src/daemon/main.ts` | **Stub**`daemonMain: () => Promise.resolve()` |
| Worker 注册 | `src/daemon/workerRegistry.ts` | **Stub**`runDaemonWorker: () => Promise.resolve()` |
| CLI 路由 | `src/entrypoints/cli.tsx` | **布线**`--daemon-worker``daemon` 子命令 |
| 命令注册 | `src/commands.ts` | **布线** — DAEMON + BRIDGE_MODE 门控 |
### 2.2 CLI 入口
```
# 启动守护进程
claude daemon
# 以 worker 身份启动
claude --daemon-worker=<kind>
```
### 2.3 预期架构
```
Supervisor (daemonMain)
├── Worker 1: assistant-mode
│ └── 接收和处理 assistant 会话
├── Worker 2: bridge-sync
│ └── bridge 消息同步
└── Worker 3: proactive
└── 主动任务执行
IPC via Unix Domain Sockets
- 生命周期管理(启动、停止、重启)
- 工作分发
- 状态报告
```
### 2.4 与 BRIDGE_MODE 的关系
DAEMON 和 BRIDGE_MODE 常组合使用:
```ts
// src/commands.ts
if (feature('DAEMON') && feature('BRIDGE_MODE')) {
// 加载 remoteControlServer 命令
}
```
双重门控:两个 feature 都需要开启才能使用远程控制服务器。
## 三、需要补全的内容
| 模块 | 工作量 | 说明 |
|------|--------|------|
| `daemon/main.ts` | 大 | Supervisor 主进程:启动 worker、生命周期管理、IPC |
| `daemon/workerRegistry.ts` | 中 | Worker 类型分发assistant/bridge-sync/proactive |
| Worker 实现 | 大 | 各类型 worker 的具体实现 |
| IPC 协议 | 中 | Supervisor-Worker 通信层 |
## 四、关键设计决策
1. **多进程架构**:一个 supervisor + 多个 worker进程隔离
2. **Unix 域套接字 IPC**:本地进程间通信,低延迟
3. **与 BRIDGE_MODE 强绑定**:守护进程最常见的用途是提供远程控制服务
4. **CLI 子命令路由**`daemon` 子命令和 `--daemon-worker` 参数在 `cli.tsx` 中路由
## 五、使用方式
```bash
# 启用守护进程模式
FEATURE_DAEMON=1 FEATURE_BRIDGE_MODE=1 bun run dev
# 启动守护进程
claude daemon
# 以特定 worker 启动
claude --daemon-worker=assistant
```
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/daemon/main.ts` | Supervisor 主进程stub |
| `src/daemon/workerRegistry.ts` | Worker 注册stub |
| `src/entrypoints/cli.tsx:95,149` | CLI 路由 |
| `src/commands.ts:77` | 命令注册(双重门控) |

View File

@@ -0,0 +1,48 @@
---
title: "Debug 模式"
description: "通过 VS Code attach 模式调试 CLI 运行时,支持断点、单步执行和变量查看。"
keywords: ["debug", "调试", "VS Code", "inspect", "断点"]
---
## 概述
TUI (REPL) 模式需要真实终端,无法直接通过 VS Code launch 启动调试。使用 **attach 模式**连接到正在运行的 Bun 进程。
## 步骤
### 1. 终端启动 inspect 服务
```bash
bun run dev:inspect
```
会输出类似 `ws://localhost:8888/xxxxxxxx` 的地址。
### 2. VS Code 附着调试器
1. 在 `src/` 文件中打断点
2. F5 → 选择 **"Attach to Bun (TUI debug)"**
> **注意**`dev:inspect` 和 `launch.json` 中的 WebSocket 地址会在每次启动时变化,需要同步更新两处。
## 原理
`dev:inspect` 脚本实际执行的是:
```bash
bun --inspect-wait=localhost:8888/<token> run scripts/dev.ts
```
Bun 的 `--inspect-wait` 参数启动一个 Chrome DevTools Protocol 兼容的 inspect 服务等待调试器连接后才开始执行。VS Code 的 `bun` 扩展通过 WebSocket 连接到这个地址实现 attach。
## JetBrains IDE
理论上 JetBrains 系列WebStorm / IntelliJ 等)也支持 attach 到 Bun inspect 服务Run → Attach to Process但尚未实际验证过。如果你验证成功欢迎补充文档。
## 相关文件
| 文件 | 说明 |
|---|---|
| `package.json` → `dev:inspect` | 启动 inspect 服务的 npm script |
| `.vscode/launch.json` | VS Code attach 调试配置 |
| `scripts/dev.ts` | dev 模式入口,注入 MACRO defines |

View File

@@ -0,0 +1,99 @@
# EXPERIMENTAL_SKILL_SEARCH — 技能语义搜索
> Feature Flag: `FEATURE_EXPERIMENTAL_SKILL_SEARCH=1`
> 实现状态:全部 Stub8 个文件),布线完整
> 引用数21
## 一、功能概述
EXPERIMENTAL_SKILL_SEARCH 提供 DiscoverSkills 工具,根据当前任务语义搜索可用技能。目标是让模型在执行任务时自动发现和推荐相关的技能(包括本地和远程),无需用户手动查找。
## 二、实现架构
### 2.1 模块状态
| 模块 | 文件 | 状态 | 说明 |
|------|------|------|------|
| DiscoverSkillsTool | `src/tools/DiscoverSkillsTool/prompt.ts` | **Stub** | 空工具名 |
| 预取 | `src/services/skillSearch/prefetch.ts` | **Stub** | 3 个函数全部空操作 |
| 远程加载 | `src/services/skillSearch/remoteSkillLoader.ts` | **Stub** | 返回空结果 |
| 远程状态 | `src/services/skillSearch/remoteSkillState.ts` | **Stub** | 返回 null/undefined |
| 信号 | `src/services/skillSearch/signals.ts` | **Stub** | `DiscoverySignal = any` |
| 遥测 | `src/services/skillSearch/telemetry.ts` | **Stub** | 空操作日志 |
| 本地搜索 | `src/services/skillSearch/localSearch.ts` | **Stub** | 空操作缓存 |
| 功能检查 | `src/services/skillSearch/featureCheck.ts` | **Stub** | `isSkillSearchEnabled => false` |
| SkillTool 集成 | `src/tools/SkillTool/SkillTool.ts` | **布线** | 动态加载所有远程技能模块 |
| 提示集成 | `src/constants/prompts.ts` | **布线** | DiscoverSkills schema 注入 |
### 2.2 预期数据流
```
模型处理用户任务
DiscoverSkills 工具触发 [需要实现]
├── 本地搜索:索引已安装技能元数据
│ └── localSearch.ts → 技能名称/描述/关键字匹配
└── 远程搜索:查询技能市场/注册表
└── remoteSkillLoader.ts → fetch + 解析
结果排序和过滤
返回推荐技能列表
模型使用 SkillTool 调用推荐技能
```
### 2.3 预取机制
`prefetch.ts` 预期在用户提交输入前分析消息内容,提前搜索相关技能:
- `startSkillDiscoveryPrefetch()` — 开始预取
- `collectSkillDiscoveryPrefetch()` — 收集预取结果
- `getTurnZeroSkillDiscovery()` — 获取 turn 0 的技能发现结果
## 三、需要补全的内容
| 优先级 | 模块 | 工作量 | 说明 |
|--------|------|--------|------|
| 1 | `DiscoverSkillsTool` | 大 | 语义搜索工具 schema + 执行 |
| 2 | `skillSearch/prefetch.ts` | 中 | 用户输入分析和预取逻辑 |
| 3 | `skillSearch/remoteSkillLoader.ts` | 大 | 远程市场/注册表获取 |
| 4 | `skillSearch/remoteSkillState.ts` | 小 | 已发现技能状态管理 |
| 5 | `skillSearch/localSearch.ts` | 中 | 本地索引构建/查询 |
| 6 | `skillSearch/featureCheck.ts` | 小 | GrowthBook/配置门控 |
| 7 | `skillSearch/signals.ts` | 小 | `DiscoverySignal` 类型定义 |
## 四、关键设计决策
1. **预取优化**:在用户提交前就开始搜索,减少首次响应延迟
2. **本地+远程双搜索**:本地索引快速匹配 + 远程市场深度搜索
3. **SkillTool 集成**:发现的技能通过 SkillTool 调用,不需要新的调用机制
4. **独立于 MCP_SKILLS**MCP_SKILLS 从 MCP 服务器发现EXPERIMENTAL_SKILL_SEARCH 从技能市场发现
## 五、使用方式
```bash
# 启用 feature需要补全后才能真正使用
FEATURE_EXPERIMENTAL_SKILL_SEARCH=1 bun run dev
```
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/tools/DiscoverSkillsTool/prompt.ts` | 工具 schemastub |
| `src/services/skillSearch/prefetch.ts` | 预取逻辑stub |
| `src/services/skillSearch/remoteSkillLoader.ts` | 远程加载stub |
| `src/services/skillSearch/remoteSkillState.ts` | 远程状态stub |
| `src/services/skillSearch/signals.ts` | 信号类型stub |
| `src/services/skillSearch/telemetry.ts` | 遥测stub |
| `src/services/skillSearch/localSearch.ts` | 本地搜索stub |
| `src/services/skillSearch/featureCheck.ts` | 功能检查stub |
| `src/tools/SkillTool/SkillTool.ts` | SkillTool 集成点 |
| `src/constants/prompts.ts:95,335,778` | 提示增强 |

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,160 @@
# Feature Flags 审查报告 — Codex 复核
> 审查日期: 2026-04-05
> 审查工具: Codex CLI v0.118.0 (本地, full-auto mode)
> 消耗 tokens: 240,306
> 审查范围: docs/feature-flags-audit-complete.md 中标记为 COMPLETE 的 22 个编译时 feature flag
---
## 审查背景
原始审计报告 (`docs/feature-flags-audit-complete.md`) 声称 22 个 feature flag 被标记为 "COMPLETE",只需在 `build.ts` / `scripts/dev.ts` 中启用即可工作。
Claude Code 团队通过 6 个并行子代理实际读取源码后初步发现大量误判,随后将分析结果传递给 Codex CLI 进行独立二次验证。
---
## Codex 发现摘要
### High 级发现
1. **`CONTEXT_COLLAPSE` 不是 COMPLETE**
- `src/services/contextCollapse/index.ts:43``isContextCollapseEnabled()` 硬编码为 `false`
- `src/services/contextCollapse/index.ts:47``applyCollapsesIfNeeded()` 只是原样返回消息
- `src/services/contextCollapse/index.ts:59``recoverFromOverflow()` 也是 no-op
- `src/services/contextCollapse/operations.ts:3``persist.ts:3` 同样是 stub
- 审计报告把 UI/命令文件算进去了,但真正被查询循环消费的是 stub 后端
2. **原分类"真正只需编译开关"的 7 个 flag只有 3 个准确**
-`SHOT_STATS` — 零额外门控compile-only
-`PROMPT_CACHE_BREAK_DETECTION` — 有 try-catch 兜底compile-only
-`TOKEN_BUDGET` — 纯本地计算compile-only
-`TEAMMEM` — 还要求 AutoMem + GrowthBook `tengu_herring_clock` + GitHub repo (`teamMemPaths.ts:73`, `watcher.ts:256`, `watcher.ts:259`)
-`AGENT_TRIGGERS` — 受 `isKairosCronEnabled()` GrowthBook 控制 (`useScheduledTasks.ts:61`, `useScheduledTasks.ts:119`)
-`EXTRACT_MEMORIES` — 受 `tengu_passport_quail` + AutoMem + 非 remote 限制 (`extractMemories.ts:536`, `:545`, `:550`)
-`KAIROS_BRIEF` — 受 `tengu_kairos_brief` + opt-in/kairosActive 限制 (`BriefTool.ts:95`, `:126`, `:132`)
### Medium 级发现
3. **`BG_SESSIONS``BASH_CLASSIFIER` 不适合简单归为"全 stub"**
- `BG_SESSIONS` — 会话注册/清理是真实现 (`concurrentSessions.ts:44`, `:55`),但任务摘要核心是 stub (`taskSummary.ts:2`)
- `BASH_CLASSIFIER` — 权限编排很大一块是真实现 (`bashPermissions.ts` 2621行),但分类后端 `bashClassifier.ts:24` 永远返回 disabled
4. **审计口径问题**
- 把"代码量/周边 UI 很多"误当成"可独立启用"
- `PROACTIVE``index.ts:3` 只有 state stub`commands.ts:64``REPL.tsx:415` 引用缺失文件
- `REACTIVE_COMPACT``reactiveCompact.ts:13` 整块是 stub
- `CACHED_MICROCOMPACT``cachedMicrocompact.ts:22` 全部 stub
---
## Codex 修正后的分类
### 第一类:真正 compile-only3 个)
| Flag | 说明 | Crash 风险 |
|------|------|-----------|
| **SHOT_STATS** | 纯本地 shot 分布统计ant-only 数据路径 | 低 |
| **PROMPT_CACHE_BREAK_DETECTION** | 本地 cache key 变化检测,写 diff 有兜底 | 低 |
| **TOKEN_BUDGET** | 本地 token 预算追踪,纯计算逻辑 | 低 |
### 第二类compile + 运行时条件7 个)
| Flag | 条件 | Crash 风险 |
|------|------|-----------|
| **TEAMMEM** | AutoMem + GrowthBook `tengu_herring_clock` + GitHub repo | 低 (clean no-op) |
| **AGENT_TRIGGERS** | GrowthBook `isKairosCronEnabled()` | 低 (clean no-op) |
| **EXTRACT_MEMORIES** | `tengu_passport_quail` + AutoMem + 非 remote | 低 (clean no-op) |
| **KAIROS_BRIEF** | `tengu_kairos_brief` + opt-in/kairosActive可用 `CLAUDE_CODE_BRIEF=1` 绕过 | 低 |
| **COORDINATOR_MODE** | 需 `CLAUDE_CODE_COORDINATOR_MODE=1``workerAgent.ts` 是 stub 但不阻塞 | 低 |
| **COMMIT_ATTRIBUTION** | 仅对 `isInternal=true` 的 repo 生效 | 低 |
| **VERIFICATION_AGENT** | 受 GrowthBook `tengu_hive_evidence` 双重门控 | 低 |
### 第三类:混合型 — 部分实现 + stub 核心5 个)
| Flag | 真实现部分 | Stub 核心 |
|------|-----------|----------|
| **BG_SESSIONS** | 会话注册/清理 (`concurrentSessions.ts`) | `bg.ts`/`taskSummary.ts`/`udsClient.ts` 全 stub + 依赖 tmux |
| **BASH_CLASSIFIER** | 权限编排 (`bashPermissions.ts` 2621行) | `bashClassifier.ts` 分类后端 stub + 需 API beta |
| **PROACTIVE** | REPL/命令注册框架 | `index.ts` stub + 3 文件缺失 |
| **REACTIVE_COMPACT** | 调用点已在主查询环路 | `reactiveCompact.ts` 22行全 no-op |
| **CACHED_MICROCOMPACT** | 调用点已布线 | `cachedMicrocompact.ts` 全 stub + 需未公开 API |
### 第四类:纯 stub1 个)
| Flag | 问题 |
|------|------|
| **CONTEXT_COLLAPSE** | 3 核心文件全 stub + CtxInspectTool 目录不存在 |
### 第五类依赖远程服务3 个)
| Flag | 依赖 |
|------|------|
| **ULTRAPLAN** | CCR 远程 agent 基础设施 + OAuth |
| **CCR_REMOTE_SETUP** | claude.ai OAuth + GitHub CLI + CCR 后端 |
| **BRIDGE_MODE** (build端) | claude.ai 订阅 + GrowthBook + WebSocket 后端 |
---
## 第三类恢复优先级建议
Codex 推荐的恢复顺序:
1. **REACTIVE_COMPACT** — 收益最直接,调用点在主查询环路,改完最容易立刻见效
2. **BG_SESSIONS** — 已有会话注册基础,补齐摘要和后台运行链路的 ROI 高
3. **PROACTIVE** — 产品面大,但缺文件比 stub 更严重,范围比前两项大
4. **CONTEXT_COLLAPSE** — collapse engine 全 stub恢复成本和设计不确定性都高
5. **BASH_CLASSIFIER** — 若无 API beta 能力不值得优先;若有则升到第 2
6. **CACHED_MICROCOMPACT** — 受未公开 API 约束,最后做
---
## 审计报告分类标准修正建议
Codex 建议将原来的单轴分类COMPLETE/PARTIAL/STUB改为**三轴**
| 轴 | 取值 | 说明 |
|----|------|------|
| **实现完整度** | `full` / `mixed` / `stub` | 活跃调用链上的核心模块是否有真实现 |
| **激活条件** | `compile-only` / `compile+env` / `compile+GrowthBook` / `compile+remote` / `compile+private API` | 启用需要什么 |
| **运行风险** | `safe no-op` / `background IO` / `startup critical` | 启用后条件不满足时的行为 |
**COMPLETE 的最低标准应满足:**
1. 活跃调用链上的核心模块不能是 stub
2. "可启用"不能只看编译 flag还要单列运行时 gate
按此标准,`CONTEXT_COLLAPSE``BG_SESSIONS``BASH_CLASSIFIER``PROACTIVE``REACTIVE_COMPACT``CACHED_MICROCOMPACT` 都应从 COMPLETE 降级。
---
## 已采取的行动
基于审查结果,已将以下 3 个确认安全的 flag 加入默认构建:
**build.ts:**
```typescript
const DEFAULT_BUILD_FEATURES = [
"AGENT_TRIGGERS_REMOTE", "CHICAGO_MCP", "VOICE_MODE",
"SHOT_STATS", "PROMPT_CACHE_BREAK_DETECTION", "TOKEN_BUDGET"
];
```
**scripts/dev.ts:**
```typescript
const DEFAULT_FEATURES = [
"BUDDY", "TRANSCRIPT_CLASSIFIER", "BRIDGE_MODE",
"AGENT_TRIGGERS_REMOTE", "CHICAGO_MCP", "VOICE_MODE",
"SHOT_STATS", "PROMPT_CACHE_BREAK_DETECTION", "TOKEN_BUDGET"
];
```
### 验证结果
| 项目 | 结果 |
|------|------|
| `bun run build` | ✅ 成功 (475 files) |
| `bun test` | ✅ 无新增失败 (23 fail 为已有问题) |
| SHOT_STATS 代码路径 | ✅ 完整 — stats 面板显示 shot 分布 |
| TOKEN_BUDGET 代码路径 | ✅ 完整 — 支持 `+500k` 语法,带进度条 |
| PROMPT_CACHE_BREAK_DETECTION 代码路径 | ✅ 完整 — 内部诊断debug 模式可见 |

View File

@@ -0,0 +1,195 @@
# FORK_SUBAGENT — 上下文继承子 Agent
> Feature Flag: `FEATURE_FORK_SUBAGENT=1`
> 实现状态:完整可用
> 引用数4
## 一、功能概述
FORK_SUBAGENT 让 AgentTool 生成"fork 子 agent",继承父级完整对话上下文。子 agent 看到父级的所有历史消息、工具集和系统提示,并且与父级共享 API 请求前缀以最大化 prompt cache 命中率。
### 核心优势
- **Prompt Cache 最大化**:多个并行 fork 共享相同的 API 请求前缀,只有最后的 directive 文本块不同
- **上下文完整性**:子 agent 继承父级的完整对话历史(包括 thinking config
- **权限冒泡**:子 agent 的权限提示上浮到父级终端显示
- **Worktree 隔离**:支持 git worktree 隔离,子 agent 在独立分支工作
## 二、用户交互
### 触发方式
`FORK_SUBAGENT` 启用时AgentTool 调用不指定 `subagent_type` 时自动走 fork 路径:
```
// Fork 路径(继承上下文)
Agent({ prompt: "修复这个 bug" }) // 无 subagent_type
// 普通 agent 路径(全新上下文)
Agent({ subagent_type: "general-purpose", prompt: "..." })
```
### /fork 命令
注册了 `/fork` 斜杠命令(当前为 stub。当 FORK_SUBAGENT 开启时,`/branch` 命令失去 `fork` 别名,避免冲突。
## 三、实现架构
### 3.1 门控与互斥
文件:`src/tools/AgentTool/forkSubagent.ts:32-39`
```ts
export function isForkSubagentEnabled(): boolean {
if (feature('FORK_SUBAGENT')) {
if (isCoordinatorMode()) return false // Coordinator 有自己的委派模型
if (getIsNonInteractiveSession()) return false // pipe/SDK 模式禁用
return true
}
return false
}
```
### 3.2 FORK_AGENT 定义
```ts
export const FORK_AGENT = {
agentType: 'fork',
tools: ['*'], // 通配符:使用父级完整工具集
maxTurns: 200,
model: 'inherit', // 继承父级模型
permissionMode: 'bubble', // 权限冒泡到父级终端
getSystemPrompt: () => '', // 不使用:直接传递父级已渲染 prompt
}
```
### 3.3 核心调用流程
```
AgentTool.call({ prompt, name })
isForkSubagentEnabled() && !subagent_type?
├── No → 普通 agent 路径
└── Yes → Fork 路径
递归防护检查
├── querySource === 'agent:builtin:fork' → 拒绝
└── isInForkChild(messages) → 拒绝
获取父级 system prompt
├── toolUseContext.renderedSystemPrompt首选
└── buildEffectiveSystemPrompt回退
buildForkedMessages(prompt, assistantMessage)
├── 克隆父级 assistant 消息
├── 生成占位符 tool_result
└── 附加 directive 文本块
[可选] buildWorktreeNotice()
runAgent({
useExactTools: true,
override.systemPrompt: 父级,
forkContextMessages: 父级消息,
availableTools: 父级工具,
})
```
### 3.4 消息构建buildForkedMessages
文件:`src/tools/AgentTool/forkSubagent.ts:107-169`
构建的消息结构:
```
[
...history (filterIncompleteToolCalls), // 父级完整历史
assistant(所有 tool_use 块), // 父级当前 turn 的 assistant 消息
user(
占位符 tool_result × N + // 相同占位符文本
<fork-boilerplate> directive // 每个 fork 不同
)
]
```
**所有 fork 使用相同的占位符文本**`"Fork started — processing in background"`。这确保多个并行 fork 的 API 请求前缀完全一致,最大化 prompt cache 命中。
### 3.5 递归防护
两层检查防止 fork 嵌套:
1. **querySource 检查**`toolUseContext.options.querySource === 'agent:builtin:fork'`。在 `context.options` 上设置抗自动压缩autocompact 只重写消息不改 options
2. **消息扫描**`isInForkChild()` 扫描消息历史中的 `<fork-boilerplate>` 标签
### 3.6 Worktree 隔离通知
当 fork + worktree 组合时,追加通知告知子 agent
> "你继承了父 agent 在 `{parentCwd}` 的对话上下文,但你在独立的 git worktree `{worktreeCwd}` 中操作。路径需要转换,编辑前重新读取。"
### 3.7 强制异步
`isForkSubagentEnabled()` 为 true 时,所有 agent 启动都强制异步。`run_in_background` 参数从 schema 中移除。统一通过 `<task-notification>` XML 消息交互。
## 四、Prompt Cache 优化
这是整个 fork 设计的核心优化目标:
| 优化点 | 实现 |
|--------|------|
| **相同 system prompt** | 直传 `renderedSystemPrompt`避免重新渲染GrowthBook 状态可能不一致) |
| **相同工具集** | `useExactTools: true` 直接使用父级工具,不经过 `resolveAgentTools` 过滤 |
| **相同 thinking config** | 继承父级 thinking 配置(非 fork agent 默认禁用 thinking |
| **相同占位符结果** | 所有 fork 使用 `FORK_PLACEHOLDER_RESULT` 相同文本 |
| **ContentReplacementState 克隆** | 默认克隆父级替换状态,保持 wire prefix 一致 |
## 五、子 Agent 指令
`buildChildMessage()` 生成 `<fork-boilerplate>` 包裹的指令:
- 你是 fork worker不是主 agent
- 禁止再次 spawn sub-agent直接执行
- 不要闲聊、不要元评论
- 直接使用工具
- 修改文件后要 commit报告 commit hash
- 报告格式:`Scope:` / `Result:` / `Key files:` / `Files changed:` / `Issues:`
## 六、关键设计决策
1. **Fork ≠ 普通 agent**fork 继承完整上下文,普通 agent 从零开始。选择依据是 `subagent_type` 是否存在
2. **renderedSystemPrompt 直传**:避免 fork 时重新调用 `getSystemPrompt()`。父级在 turn 开始时冻结 prompt 字节
3. **占位符结果共享**:多个并行 fork 使用完全相同的占位符,只有 directive 不同
4. **Coordinator 互斥**Coordinator 模式下禁用 fork两者有不兼容的委派模型
5. **非交互式禁用**pipe 模式和 SDK 模式下禁用,避免不可见的 fork 嵌套
## 七、使用方式
```bash
# 启用 feature
FEATURE_FORK_SUBAGENT=1 bun run dev
# 在 REPL 中使用(不指定 subagent_type 即走 fork
# Agent({ prompt: "研究这个模块的结构" })
# Agent({ prompt: "实现这个功能" })
```
## 八、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/tools/AgentTool/forkSubagent.ts` | ~210 | 核心定义 + 消息构建 + 递归防护 |
| `src/tools/AgentTool/AgentTool.tsx` | — | Fork 路由 + 强制异步 |
| `src/tools/AgentTool/prompt.ts` | — | "When to Fork" 提示词段落 |
| `src/tools/AgentTool/runAgent.ts` | — | useExactTools 路径 |
| `src/tools/AgentTool/resumeAgent.ts` | — | Fork agent 恢复 |
| `src/constants/xml.ts` | — | XML 标签常量 |
| `src/utils/forkedAgent.ts` | — | CacheSafeParams + ContentReplacementState 克隆 |
| `src/commands/fork/index.ts` | — | /fork 命令stub |

View File

@@ -0,0 +1,334 @@
# GrowthBook 功能启用计划
> 编制日期: 2026-04-06
> 基于: feature-flags-codex-review.md + 4 个并行研究代理的深度分析
> 前提: 我们是付费订阅用户,拥有有效的 Anthropic API key
---
## 背景
Claude Code 使用三层门控系统:
1. **编译时 feature flag**`feature('FLAG_NAME')` from `bun:bundle`
2. **GrowthBook 远程开关**`tengu_*` 前缀,通过 SDK 连接 Anthropic 服务端
3. **运行时环境变量**`USER_TYPE``CLAUDE_CODE_*`
在我们的反编译版本中GrowthBook 不启动analytics 链空实现),导致所有 `tengu_*` 检查默认返回 `false`
**核心发现:所有被 GrowthBook 门控的功能代码都是真实现,没有 stub。**
---
## 启用方式说明
### 方式 1硬编码绕过推荐先用
`src/services/analytics/growthbook.ts``getFeatureValueInternal()` 函数中添加默认值映射。
### 方式 2自建 GrowthBook 服务器
```bash
docker run -p 3100:3100 growthbook/growthbook
# 设置环境变量
CLAUDE_GB_ADAPTER_URL=http://localhost:3100
CLAUDE_GB_ADAPTER_KEY=sdk-xxx
```
### 方式 3恢复原生 1P 连接
`is1PEventLoggingEnabled()` 返回 `true`,连接 Anthropic 的 GrowthBook 服务端。
注意:会发送使用统计(不含代码/对话内容)。
---
## 优先级 P0纯本地功能零外部依赖立即可用
这些功能不需要 API 调用,开启 gate 即可工作。
### P0-1. 自定义快捷键
- **Gate**: `tengu_keybinding_customization_release``true`
- **编译 flag**: 无(已内置)
- **代码量**: 473 行,完整实现
- **功能**: 加载 `~/.claude/keybindings.json`,支持热重载、重复键检测、结构验证
- **效果**: 用户可自定义所有快捷键
- **风险**: 无
### P0-2. 流式工具执行
- **Gate**: `tengu_streaming_tool_execution2``true`
- **编译 flag**: 无(已内置)
- **代码量**: 577 行StreamingToolExecutor完整实现
- **功能**: API 响应还在流式返回时就开始执行工具,减少等待时间
- **效果**: 显著提升交互速度
- **风险**: 低(生产级代码,有错误处理)
### P0-3. 定时任务系统
- **Gate**: `tengu_kairos_cron``true`(额外:`tengu_kairos_cron_durable` 默认 `true`
- **编译 flag**: `AGENT_TRIGGERS`(需新增)或 `AGENT_TRIGGERS_REMOTE`(已启用)
- **代码量**: 1025 行cronTasks + cronScheduler完整实现
- **功能**: 本地 cron 调度,支持一次性/周期性任务、防雷群效应 jitter、自动过期
- **效果**: 可设置定时执行的 Claude 任务
- **风险**: 低
### P0-4. Agent 团队 / Swarm
- **Gate**: `tengu_amber_flint``true`(这是 kill switch默认已 `true`
- **编译 flag**: 无(已内置)
- **代码量**: 45 行gate 层),实际 swarm 实现在 teammate tools 中
- **功能**: 多 agent 协作,需额外设置 `--agent-teams``CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`
- **效果**: 允许创建和管理 agent 团队
- **风险**: 无kill switch 默认就是 true
### P0-5. Token 高效 JSON 工具格式
- **Gate**: `tengu_amber_json_tools``true`
- **编译 flag**: 无(已内置)
- **代码量**: betas.ts 中几行 gate 检查
- **功能**: 启用 FC v3 格式,减少约 4.5% 的输出 token
- **效果**: 省钱
- **风险**: 低(需要模型支持该 beta header
### P0-6. Ultrathink 扩展思考
- **Gate**: `tengu_turtle_carbon``true`(默认已 `true`kill switch
- **编译 flag**: 无
- **功能**: 通过关键词触发扩展思考模式
- **效果**: 已默认启用,确保不被远程关闭即可
- **风险**: 无
### P0-7. 即时模型切换
- **Gate**: `tengu_immediate_model_command``true`
- **编译 flag**: 无
- **功能**: 在 query 运行过程中即时执行 `/model``/fast``/effort` 命令
- **效果**: 无需等当前任务完成就能切换
- **风险**: 低
---
## 优先级 P1需要 Claude API 的功能(有 API key 即可用)
这些功能需要调用 Claude API使用 forked subagent 或 queryModel有订阅即可。
### P1-1. 会话记忆
- **Gate**: `tengu_session_memory``true`(配置:`tengu_sm_config``{}`
- **编译 flag**: 无(已内置)
- **代码量**: 1127 行,完整实现
- **功能**: 跨会话上下文持久化。用 forked agent 定期提取会话笔记到 markdown 文件
- **效果**: Claude 记住跨会话的工作上下文
- **依赖**: Claude APIforked subagent
- **风险**: 低(额外 API token 消耗)
### P1-2. 自动记忆提取
- **Gate**: `tengu_passport_quail``true`(相关:`tengu_moth_copse``tengu_coral_fern`
- **编译 flag**: `EXTRACT_MEMORIES`(需新增)
- **代码量**: 616 行,完整实现
- **功能**: 对话中自动提取持久记忆到 `~/.claude/projects/<path>/memory/`
- **效果**: 自动构建项目知识库
- **依赖**: Claude APIforked subagent
- **风险**: 低
### P1-3. 提示建议
- **Gate**: `tengu_chomp_inflection``true`
- **编译 flag**: 无(已内置)
- **代码量**: 525 行,完整实现
- **功能**: 自动生成下一步操作建议带投机预取speculation prefetch
- **效果**: 更流畅的交互体验
- **依赖**: Claude APIforked subagent
- **风险**: 低(额外 API 消耗,但有缓存感知)
### P1-4. 验证代理
- **Gate**: `tengu_hive_evidence``true`
- **编译 flag**: `VERIFICATION_AGENT`(需新增)
- **代码量**: 153 行agent 定义),完整实现
- **功能**: 对抗性验证 agent主动尝试打破你的实现只读模式
- **效果**: 自动化代码验证
- **依赖**: Claude APIsubagent
- **风险**: 低(只读,不修改代码)
### P1-5. Brief 模式
- **Gate**: `tengu_kairos_brief``true`
- **编译 flag**: `KAIROS``KAIROS_BRIEF`(需新增)
- **代码量**: 335 行,完整实现
- **功能**: `/brief` 命令切换精简输出模式
- **效果**: 减少冗余输出
- **依赖**: Claude API
- **风险**: 低
### P1-6. 离开摘要
- **Gate**: `tengu_sedge_lantern``true`
- **编译 flag**: `AWAY_SUMMARY`(需新增)
- **代码量**: 176 行,完整实现
- **功能**: 离开终端 5 分钟后返回时自动总结期间发生了什么
- **效果**: 快速恢复上下文
- **依赖**: Claude API + 终端焦点事件支持
- **风险**: 低
### P1-7. 自动梦境
- **Gate**: `tengu_onyx_plover``{"enabled": true}`
- **编译 flag**: 无(已内置,但检查 auto-memory 是否启用)
- **代码量**: 349 行,完整实现
- **功能**: 后台自动整理/巩固记忆(等同于自动执行 `/dream`
- **效果**: 记忆自动保持整洁有序
- **依赖**: Claude APIforked subagent+ auto-memory 启用
- **风险**: 低
### P1-8. 空闲返回提示
- **Gate**: `tengu_willow_mode``"dialog"``"hint"`
- **编译 flag**: 无
- **功能**: 对话太大且缓存过期时,提示用户开新会话
- **效果**: 避免在过期缓存上浪费 token
- **风险**: 无
---
## 优先级 P2增强型功能提升体验但非必须
### P2-1. MCP 指令增量传输
- **Gate**: `tengu_basalt_3kr``true`
- **功能**: 只发送变化的 MCP 指令而非全量
- **效果**: 减少 token 消耗
- **风险**: 低
### P2-2. 叶剪枝优化
- **Gate**: `tengu_pebble_leaf_prune``true`
- **功能**: 会话存储中移除死胡同消息分支
- **效果**: 减少存储和加载时间
- **风险**: 低
### P2-3. 消息合并
- **Gate**: `tengu_chair_sermon``true`
- **功能**: 合并相邻的 tool_result + text 块
- **效果**: 减少 token 消耗
- **风险**: 低
### P2-4. 深度链接
- **Gate**: `tengu_lodestone_enabled``true`
- **功能**: 注册 `claude://` URL 协议处理器
- **效果**: 可从浏览器直接打开 Claude Code
- **风险**: 低
### P2-5. Agent 自动转后台
- **Gate**: `tengu_auto_background_agents``true`
- **功能**: Agent 任务运行 120s 后自动转为后台
- **效果**: 不再阻塞主交互
- **风险**: 低
### P2-6. 细粒度工具状态
- **Gate**: `tengu_fgts``true`
- **功能**: 系统提示中包含细粒度工具状态信息
- **效果**: 模型更好地理解工具可用性
- **风险**: 低
### P2-7. 文件操作 git diff
- **Gate**: `tengu_quartz_lantern``true`
- **功能**: 文件写入/编辑时计算 git diff仅远程会话
- **效果**: 更好的变更追踪
- **风险**: 低
---
## 优先级 P3需要自建服务或 Anthropic OAuth
### P3-1. 团队记忆
- **Gate**: `tengu_herring_clock``true`
- **编译 flag**: `TEAMMEM`(需新增)
- **代码量**: 1180+ 行,完整实现
- **功能**: 跨 agent 共享记忆,同步到 Anthropic API
- **依赖**: Anthropic OAuth + GitHub remote
- **状态**: 需要 Anthropic 的 `/api/claude_code/team_memory` 端点
- **可行性**: 除非自建兼容 API否则无法使用
### P3-2. 设置同步
- **Gate**: `tengu_enable_settings_sync_push` + `tengu_strap_foyer``true`
- **编译 flag**: `UPLOAD_USER_SETTINGS` / `DOWNLOAD_USER_SETTINGS`(需新增)
- **代码量**: 582 行,完整实现
- **功能**: 跨设备设置同步
- **依赖**: Anthropic OAuth + `/api/claude_code/user_settings`
- **可行性**: 同上
### P3-3. Bridge 远程控制
- **Gate**: `tengu_ccr_bridge``true`(已有编译 flag `BRIDGE_MODE` dev 模式启用)
- **代码量**: 12,619 行,完整实现
- **功能**: claude.ai 网页端远程控制 CLI
- **依赖**: claude.ai 订阅 + WebSocket 后端
- **可行性**: 需要 Anthropic 的 CCR 后端
### P3-4. 远程定时 Agent
- **Gate**: `tengu_surreal_dali``true`
- **功能**: 创建在远程执行的定时 agent
- **依赖**: Anthropic CCR 基础设施
- **可行性**: 需要远程服务
---
## Kill Switch 清单(确保不被远程关闭)
这些 gate 默认为 `true`,是 kill switch。应确保它们保持 `true`
| Gate | 默认 | 控制什么 |
|---|---|---|
| `tengu_turtle_carbon` | `true` | Ultrathink 扩展思考 |
| `tengu_amber_stoat` | `true` | 内置 Explore/Plan agent |
| `tengu_amber_flint` | `true` | Agent 团队/Swarm |
| `tengu_slim_subagent_claudemd` | `true` | 子 agent 精简 CLAUDE.md |
| `tengu_birch_trellis` | `true` | tree-sitter bash 安全分析 |
| `tengu_collage_kaleidoscope` | `true` | macOS 剪贴板图片读取 |
| `tengu_compact_cache_prefix` | `true` | 压缩时复用 prompt cache |
| `tengu_kairos_cron_durable` | `true` | 持久化 cron 任务 |
| `tengu_attribution_header` | `true` | API 请求署名 |
| `tengu_slate_prism` | `true` | Agent 进度摘要 |
---
## 需要新增的编译 flag
以下编译时 flag 尚未在 `build.ts` / `scripts/dev.ts` 中启用,但功能代码完整:
| Flag | 用于 | 优先级 |
|---|---|---|
| `AGENT_TRIGGERS` | 定时任务系统P0-3 | P0 |
| `EXTRACT_MEMORIES` | 自动记忆提取P1-2 | P1 |
| `VERIFICATION_AGENT` | 验证代理P1-4 | P1 |
| `KAIROS``KAIROS_BRIEF` | Brief 模式P1-5 | P1 |
| `AWAY_SUMMARY` | 离开摘要P1-6 | P1 |
| `TEAMMEM` | 团队记忆P3-1 | P3 |
---
## 实施路线图
### Phase 1硬编码 P0 纯本地 gate最快见效
1. 在 growthbook.ts 添加默认值映射
2. 在 build.ts / dev.ts 添加 `AGENT_TRIGGERS` 编译 flag
3. 验证 7 个 P0 功能正常工作
4. 预计工作量1-2 小时
### Phase 2启用 P1 API 依赖功能
1. 添加编译 flag`EXTRACT_MEMORIES``VERIFICATION_AGENT``KAIROS_BRIEF``AWAY_SUMMARY`
2. 添加 P1 gate 默认值
3. 验证 8 个 P1 功能正常工作
4. 预计工作量2-3 小时
### Phase 3评估自建 GrowthBook可选
1. Docker 部署 GrowthBook 服务器
2. 迁移硬编码值到 GrowthBook 后台管理
3. 获得 Web UI 管理所有 flag 的能力
4. 预计工作量:半天
### Phase 4评估远程功能可选
1. 研究是否可以使用 Anthropic OAuth
2. 评估团队记忆、设置同步的自建可行性
3. 预计工作量:待评估
---
## 隐私说明
### 硬编码绕过(方案 A
- **零数据外发**
- GrowthBook SDK 不启动
- 完全离线运行
### 自建 GrowthBook方案 B
- 数据仅发送到你自己的服务器
- Anthropic 无法获取任何数据
- 可通过 Web UI 实时管理所有 flag
### 恢复原生 1P方案 C
- 会发送使用统计到 `api.anthropic.com`
- **不发送**代码、对话内容、API key
- **会发送**:邮箱、设备 ID、机器指纹、仓库哈希、订阅类型
- 可用 `DISABLE_TELEMETRY=1` 关闭遥测(但同时关闭 GrowthBook

182
docs/features/kairos.md Normal file
View File

@@ -0,0 +1,182 @@
# KAIROS — 常驻助手模式
> Feature Flag: `FEATURE_KAIROS=1`(及子 Feature
> 实现状态:核心框架完整,部分子模块为 stubproactive/sleep 节奏控制已可用
> 引用数154全库最大
## 一、功能概述
KAIROS 将 Claude Code CLI 从"问答工具"转变为"常驻助手"。开启后CLI 持续运行在后台,支持:
- **持久化 bridge 会话**:跨终端重启复用 session通过 Anthropic OAuth 连接 claude.ai
- **后台执行任务**:用户离开终端时继续工作(配合 PROACTIVE feature
- **推送通知到移动端**:任务完成或需要输入时推送(配合 `KAIROS_PUSH_NOTIFICATION`
- **每日记忆日志**:自动记录和回顾工作内容(配合 `KAIROS_DREAM`
- **外部频道消息接入**Slack/Discord/Telegram 消息转发到 CLI配合 `KAIROS_CHANNELS`
- **结构化 Brief 输出**:通过 BriefTool 输出结构化消息(配合 `KAIROS_BRIEF`
### 子 Feature 依赖关系
```
KAIROS (主开关)
├── KAIROS_BRIEF (BriefTool, 结构化输出)
├── KAIROS_CHANNELS (外部频道消息)
├── KAIROS_PUSH_NOTIFICATION (移动端推送)
├── KAIROS_GITHUB_WEBHOOKS (GitHub PR webhook)
└── KAIROS_DREAM (记忆蒸馏)
```
**注意**PROACTIVE 与 KAIROS 强绑定。所有代码检查都是 `feature('PROACTIVE') || feature('KAIROS')`,即 KAIROS 开启时自动获得 proactive 能力。
## 二、系统提示
KAIROS 在系统提示中注入两大段落:
### 2.1 Brief 段落 (`getBriefSection`)
文件:`src/constants/prompts.ts:843-858`
`feature('KAIROS') || feature('KAIROS_BRIEF')` 时注入。Brief 工具(`SendUserMessage`)的结构化消息输出指令。`/brief` toggle 和 `--brief` flag 只控制显示过滤,不影响模型行为。
### 2.2 Proactive/Autonomous Work 段落 (`getProactiveSection`)
文件:`src/constants/prompts.ts:860-914`
`feature('PROACTIVE') || feature('KAIROS')``isProactiveActive()` 时注入。核心行为指令:
- **Tick 驱动**:通过 `<tick_tag>` prompt 保持存活,每个 tick 包含用户当前本地时间
- **节奏控制**:使用 `SleepTool` 控制等待间隔prompt cache 5 分钟过期)
- **空操作时必须 Sleep**:禁止输出 "still waiting" 类文本(浪费 turn 和 token
- **偏向行动**读文件、搜索代码、修改文件、commit — 都不需询问
- **终端焦点感知**`terminalFocus` 字段指示用户是否在看终端
- Unfocused → 高度自主行动
- Focused → 更协作,展示选择
## 三、实现架构
### 3.1 核心模块
| 模块 | 文件 | 状态 | 职责 |
|------|------|------|------|
| Assistant 入口 | `src/assistant/index.ts` | Stub | `isAssistantMode()``initializeAssistantTeam()` |
| Session 发现 | `src/assistant/sessionDiscovery.ts` | Stub | 发现可用 bridge session |
| Session 历史 | `src/assistant/sessionHistory.ts` | Stub | 持久化 session 历史 |
| Gate 控制 | `src/assistant/gate.ts` | Stub | GrowthBook 门控检查 |
| Session 选择器 | `src/assistant/AssistantSessionChooser.ts` | Stub | UI 选择 session |
| BriefTool | `src/tools/BriefTool/` | Stub | 结构化消息输出工具 |
| Channel Notification | `src/services/mcp/channelNotification.ts` | Stub | 外部频道消息接入 |
| Dream Task | `src/components/tasks/src/tasks/DreamTask/` | Stub | 记忆蒸馏任务 |
| Memory Directory | `src/memdir/memdir.ts` | Stub | 记忆目录管理 |
### 3.2 SleepTool与 Proactive 共享)
文件:`src/tools/SleepTool/prompt.ts`
SleepTool 是 KAIROS/Proactive 的节奏控制核心。工具描述让模型理解"休眠"概念:
- 工具名:`Sleep`
- 功能:等待指定时间后响应 tick prompt若队列出现新工作或 proactive 被关闭,会提前唤醒
-`<tick_tag>` 配合实现心跳式自主工作
- 远程控制 surfaces 可通过 `automation_state` 看到 `standby` / `sleeping` 两种状态
### 3.3 Bridge 集成
KAIROS 通过 Bridge Mode`src/bridge/`)连接到 claude.ai 服务器:
```
claude.ai web/app
▼ (HTTPS long-poll)
┌──────────────────────┐
│ Bridge API Client │ src/bridge/bridgeApi.ts
│ (register/poll/ │
│ acknowledge) │
└──────────┬───────────┘
┌──────────────────────┐
│ Session Runner │ src/bridge/sessionRunner.ts
│ (创建/恢复 REPL) │
└──────────┬───────────┘
┌──────────────────────┐
│ REPL + Proactive │ Tick 驱动自主工作
│ Tick Loop │
└──────────────────────┘
```
### 3.4 数据流
```
用户从 claude.ai 发送消息
Bridge pollForWork() 收到 WorkResponse
acknowledgeWork() 确认接收
sessionRunner 创建/恢复 REPL session
用户消息注入到 REPL 对话
模型处理 → 工具调用 → BriefTool 结构化输出
结果通过 Bridge API 回传到 claude.ai
```
## 四、关键设计决策
1. **Tick 驱动而非事件驱动**:模型通过 SleepTool 自行控制唤醒频率,而非外部事件推送。简化架构但增加 API 调用开销
2. **KAIROS ⊃ PROACTIVE**:所有 proactive 检查都包含 KAIROS无需同时开启两个 flag
3. **Brief 显示/行为分离**`/brief` toggle 只控制 UI 过滤,模型始终可以使用 BriefTool
4. **Terminal Focus 感知**:模型根据用户是否在看终端自动调节自主程度
5. **GrowthBook 门控**:部分功能(如推送通知)即使 feature flag 开启还需要服务端 GrowthBook 开关
## 五、使用方式
```bash
# 最小启用(常驻助手 + Brief
FEATURE_KAIROS=1 FEATURE_KAIROS_BRIEF=1 bun run dev
# 全功能启用
FEATURE_KAIROS=1 \
FEATURE_KAIROS_BRIEF=1 \
FEATURE_KAIROS_CHANNELS=1 \
FEATURE_KAIROS_PUSH_NOTIFICATION=1 \
FEATURE_KAIROS_GITHUB_WEBHOOKS=1 \
FEATURE_PROACTIVE=1 \
bun run dev
# 配合 Token Budget 使用
FEATURE_KAIROS=1 FEATURE_TOKEN_BUDGET=1 bun run dev
```
## 六、外部依赖
- **Anthropic OAuth**:必须使用 claude.ai 订阅登录(非 API key
- **GrowthBook**:服务端特性门控(`tengu_ccr_bridge` 等)
- **Bridge API**`/v1/environments/bridge` 系列端点
## 七、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/assistant/index.ts` | 9 | Assistant 模块入口stub |
| `src/assistant/gate.ts` | — | GrowthBook 门控stub |
| `src/assistant/sessionDiscovery.ts` | — | Session 发现stub |
| `src/assistant/sessionHistory.ts` | — | Session 历史stub |
| `src/assistant/AssistantSessionChooser.ts` | — | Session 选择 UIstub |
| `src/tools/BriefTool/` | — | BriefTool 实现stub |
| `src/tools/SleepTool/prompt.ts` | ~30 | SleepTool 工具提示 |
| `src/tools/SleepTool/SleepTool.ts` | ~200 | 休眠/唤醒与 automation metadata |
| `src/services/mcp/channelNotification.ts` | 5 | 频道消息接入stub |
| `src/memdir/memdir.ts` | — | 记忆目录管理stub |
| `src/constants/prompts.ts:552-554,843-914` | 72 | 系统提示注入 |
| `src/components/tasks/src/tasks/DreamTask/` | 3 | Dream 任务stub |
| `src/proactive/index.ts` | — | Proactive 核心KAIROS 共享) |
| `src/utils/sessionState.ts` | — | 向 bridge/CCR 暴露 automation 状态 |

View File

@@ -0,0 +1,321 @@
# LAN Pipes — 技术实现文档
面向开发者的实现细节。用户指南见 [lan-pipes.md](./lan-pipes.md)。
---
## 架构
```
Machine A (192.168.50.22) Machine B (192.168.50.27)
┌───────────────────────────┐ ┌───────────────────────────┐
│ PipeServer │ │ PipeServer │
│ UDS: ~/.claude/pipes/ │ │ UDS: ~/.claude/pipes/ │
│ cli-abc.sock │ │ cli-def.sock │
│ TCP: 0.0.0.0:<random> │◄──TCP───►│ TCP: 0.0.0.0:<random> │
├───────────────────────────┤ ├───────────────────────────┤
│ LanBeacon │ │ LanBeacon │
│ UDP 224.0.71.67:7101 │◄──UDP───►│ UDP 224.0.71.67:7101 │
├───────────────────────────┤ ├───────────────────────────┤
│ usePipeIpc (hook) │ │ usePipeIpc (hook) │
│ initPipeServer │ │ initPipeServer │
│ registerMessageHandlers │ │ registerMessageHandlers │
│ runMainHeartbeat │ │ runSubHeartbeat │
│ cleanupPipeIpc │ │ cleanupPipeIpc │
└───────────────────────────┘ └───────────────────────────┘
```
## Feature Flag
`LAN_PIPES` — 在 `scripts/dev.ts``build.ts``DEFAULT_FEATURES` 中启用。
所有 LAN 代码路径通过 `feature('LAN_PIPES')` 编译时门控。`feature()` 只能在 `if` 或三元中使用Bun 编译时常量约束)。
---
## 核心文件
| 文件 | 说明 |
|------|------|
| `src/utils/pipeTransport.ts` | PipeServer/PipeClientUDS + TCP 双模式) |
| `src/utils/lanBeacon.ts` | UDP multicast beacon + module singleton |
| `src/utils/ndjsonFramer.ts` | 共享 NDJSON socket 帧解析 |
| `src/utils/pipeRegistry.ts` | 文件注册表 + `mergeWithLanPeers()` |
| `src/utils/peerAddress.ts` | 地址解析uds/bridge/tcp scheme |
| `src/utils/pipePermissionRelay.ts` | 权限转发 + `setPipeRelay`/`getPipeRelay` singleton |
| `src/hooks/usePipeIpc.ts` | 生命周期 hook从 REPL.tsx 提取) |
| `src/hooks/usePipeRelay.ts` | 消息回传 hook |
| `src/hooks/usePipePermissionForward.ts` | 权限转发 hook |
| `src/hooks/usePipeRouter.ts` | 输入路由 hook |
| `src/hooks/useMasterMonitor.ts` | slave 注册表 + 消息订阅 |
---
## PipeServer TCP 扩展
`src/utils/pipeTransport.ts`
### 类型
```typescript
export type PipeTransportMode = 'uds' | 'tcp'
export type TcpEndpoint = { host: string; port: number }
export type PipeServerOptions = { enableTcp?: boolean; tcpPort?: number }
```
### PipeServer 变更
- `setupSocket(socket)` — 从 start() 提取的共享方法UDS 和 TCP 共用
- `start(options?)` — 可选启用 TCPport=0 让 OS 分配
- 内部维护两个 `net.Server`,共享同一组 `clients: Set<Socket>``handlers`
- `tcpAddress` getter 暴露 TCP 端口
- `close()` 同时关闭两个 server
socket 帧解析使用 `attachNdjsonFramer()` from `ndjsonFramer.ts`(替代原先 3 份重复代码)。
### PipeClient 变更
- 构造函数新增可选 `TcpEndpoint` 参数
- `connect()` 根据 tcpEndpoint 分派到 `connectTcp()``connectUds()`
- TCP 不需要文件存在轮询,直接建连
---
## LAN Beacon
`src/utils/lanBeacon.ts`
### 协议参数
| 参数 | 值 |
|------|-----|
| Multicast 组 | `224.0.71.67` |
| 端口 | `7101` |
| 广播间隔 | `3000ms` |
| Peer 超时 | `15000ms` |
| TTL | `1` |
### Announce 包
```typescript
type LanAnnounce = {
proto: 'claude-pipe-v1'
pipeName: string
machineId: string
hostname: string
ip: string
tcpPort: number
role: 'main' | 'sub'
ts: number
}
```
### API
```typescript
class LanBeacon extends EventEmitter {
constructor(announce: Omit<LanAnnounce, 'proto' | 'ts'>)
start(): void
stop(): void
getPeers(): Map<string, LanAnnounce> // 防御性拷贝
updateAnnounce(partial): void // 使用 spread不可变更新
on('peer-discovered', (peer: LanAnnounce) => void)
on('peer-lost', (pipeName: string) => void)
}
```
### 存储
module-level singleton`getLanBeacon()` / `setLanBeacon()`。不挂在 Zustand state 上(避免 `setState` 展开时丢失引用)。
### 网卡绑定
`addMembership(group, localIp)` + `setMulticastInterface(localIp)` 指定 LAN 网卡。解决 Windows 上 WSL/Docker 虚拟网卡劫持 multicast 的问题。
---
## Hook 架构
从 REPL.tsx 提取的 ~830 行 Pipe IPC 代码:
### usePipeIpc生命周期
`src/hooks/usePipeIpc.ts`623 行)
在 REPL.tsx 顶层通过 feature-gated require 加载:
```typescript
const usePipeIpc = feature('UDS_INBOX')
? require('../hooks/usePipeIpc.js').usePipeIpc
: () => undefined;
// 组件内
usePipeIpc({ store, handleIncomingPrompt });
```
内部使用 **lazy getter** 函数加载依赖(避免循环依赖导致 Bun 运行时崩溃):
```typescript
const pt = () => require('../utils/pipeTransport.js')
const pr = () => require('../utils/pipeRegistry.js')
const mm = () => require('./useMasterMonitor.js')
// ...
```
`import type` 用于静态类型(不会触发模块加载)。
### 四个阶段函数
| 函数 | 职责 |
|------|------|
| `initPipeServer` | 角色判定 + server 创建 + beacon 启动 |
| `registerMessageHandlers` | ping、attach、prompt、permission、detach 五个 handler |
| `runMainHeartbeat` | cleanup + 发现 + auto-attach + 清理死连接 |
| `runSubHeartbeat` | 检测 main 是否存活,死亡则接管或独立 |
### usePipeRelay消息回传
`src/hooks/usePipeRelay.ts`38 行)
提供 `relayPipeMessage()``pipeReturnHadErrorRef`。relay 函数通过 `getPipeRelay()` module singleton 读取(替代 `globalThis.__pipeSendToMaster`)。
### usePipePermissionForward权限转发
`src/hooks/usePipePermissionForward.ts`159 行)
订阅 `subscribePipeEntries()`,处理:
- `permission_request` → 解析 payload → 查找 tool → 加入确认队列
- `permission_cancel` → 从队列移除
- `stream/error/done` → 转为系统消息显示(含 role + IP 标签)
### usePipeRouter输入路由
`src/hooks/usePipeRouter.ts`130 行)
提供 `routeToSelectedPipes(input): boolean`。读取 `selectedPipes` + `routeMode`,逐个发送到已连接目标。通知显示 `[role] hostname/ip`LAN peer`[role]`(本机)。
---
## Registry 并行探测
`src/utils/pipeRegistry.ts`
### getAliveSubs()
```typescript
export async function getAliveSubs(): Promise<PipeRegistrySub[]> {
const registry = await readRegistry()
const results = await Promise.all(
registry.subs.map(sub =>
isPipeAlive(sub.pipeName, 1000).then(alive => alive ? sub : null)
)
)
return results.filter(Boolean)
}
```
### cleanupStaleEntries()
两阶段:
1. **无锁并行探测**`Promise.all` 探测 main + 所有 subs
2. **短暂持锁写入**`acquireLock()` → 重新读取 → 应用变更 → 写入 → `releaseLock()`
持锁时间从 N 秒降至 ~10ms。
### getMachineId()
Windows/macOS 使用 `execFile`(异步),不阻塞主线程。结果缓存,仅首次调用执行。
---
## NDJSON 协议
### 消息类型
| 类型 | 方向 | 数据 |
|------|------|------|
| `ping` / `pong` | 双向 | 无 |
| `attach_request` | M→S | `meta: { machineId }` |
| `attach_accept` / `attach_reject` | S→M | `data: reason` |
| `detach` | M→S | 无 |
| `prompt` | M→S | `data: prompt_text` |
| `prompt_ack` | S→M | `data: 'accepted'` |
| `stream` | S→M | `data: partial_text` |
| `done` | S→M | 无 |
| `error` | 双向 | `data: error_message` |
| `permission_request` | S→M | `data: JSON(PipePermissionRequestPayload)` |
| `permission_response` | M→S | `data: JSON(PipePermissionResponsePayload)` |
| `permission_cancel` | M→S | `data: JSON({ requestId, reason })` |
### 帧格式
每行一个 JSON 对象,`\n` 分隔:
```
{"type":"ping","from":"cli-abc","ts":"2026-04-11T00:00:00.000Z"}\n
{"type":"prompt","data":"检查 git status","from":"cli-abc"}\n
```
---
## 跨机器 Attach 流程
```
CLI-B (192.168.50.27) 心跳循环
→ beacon.getPeers() 发现 CLI-A (192.168.50.22)
→ connectToPipe(pName, myName, 3000, { host: '192.168.50.22', port: 58853 })
→ PipeClient.connectTcp() → net.createConnection({ host, port })
→ client.send({ type: 'attach_request', meta: { machineId } })
→ CLI-A 收到:
isLanPeer = (msg.meta.machineId !== myMachineId) → true
→ 不检查 role直接 reply({ type: 'attach_accept' })
→ setPipeRelay(socket.write)
→ CLI-B 收到 attach_accept
→ addSlaveClient(pName, client)
→ store.setState: role='master', slaves[pName] = { status: 'idle' }
```
关键:跨机器 attach 不要求对方是 sub 角色。通过 `machineId` 区分 LAN peer。
---
## SendMessageTool TCP 支持
`src/tools/SendMessageTool/SendMessageTool.ts`
- `to` 字段支持 `tcp:host:port` 格式
- `checkPermissions``tcp:` scheme 返回 `behavior: 'ask'``classifierApprovable: false`
- `call()`:创建临时 `PipeClient` → connect → send → disconnect
---
## 测试
| 文件 | 测试数 | 覆盖 |
|------|--------|------|
| `lanBeacon.test.ts` | 7 | socket 初始化、announce、peer 发现/过滤/清理 |
| `peerAddress.test.ts` | 8 | scheme 解析、parseTcpTarget、端口范围验证 |
| `pipePermissionRelay.test.ts` | 2 | setPipeRelay singleton、权限请求/响应 |
| `pipeTransport.test.ts` | 2 | UDS 基础行为 |
| `useMasterMonitor.test.ts` | 5 | slave 注册/移除、事件发射 |
全量2190 pass / 0 fail
---
## 已知限制
1. **TCP 无认证** — 同 LAN 内知道端口号即可连接
2. **Beacon 明文广播** — IP/hostname/machineId 未 hash
3. **单网卡选择**`getLocalIp()` 返回首个非内部 IPv4可能选到 VPN
4. **端口随机** — 每次启动不同端口,依赖 beacon 发现
5. **SendMessageTool 每次创建新连接** — 未复用已有 slave client
## 后续改进方向
1. HMAC-SHA256 TCP 握手认证
2. machineId hash 后再广播
3. 多网卡选择(优先 RFC 1918 地址)
4. 固定端口范围配置
5. TLS 加密传输
6. SendMessageTool 复用已连接的 slave client

193
docs/features/lan-pipes.md Normal file
View File

@@ -0,0 +1,193 @@
# LAN Pipes — 局域网多机器群控指南
## 什么是 LAN Pipes
LAN Pipes 让多台机器上的 Claude Code 实例通过局域网自动发现并协作。你可以在一台机器main上操控其他机器sub上的 Claude Code发送 prompt、查看执行结果、审批权限请求——全程零配置。
基于本机 Pipe IPC`UDS_INBOX`)扩展,新增 TCP 传输层 + UDP Multicast 发现。
## 前置条件
- 两台或以上机器在同一局域网
- 每台机器安装了 CCB 并能 `bun run dev`
- Feature flag `LAN_PIPES`dev/build 默认开启)
- 防火墙允许 UDP 7101 + TCP 动态端口(见下方配置)
## 快速开始
### 第一步:配置防火墙
**每台机器都需要执行。**
**Windows**(管理员 PowerShell
```powershell
New-NetFirewallRule -DisplayName "CCB LAN Beacon (UDP)" -Direction Inbound -Protocol UDP -LocalPort 7101 -Action Allow -Profile Private
New-NetFirewallRule -DisplayName "CCB LAN Pipes (TCP)" -Direction Inbound -Protocol TCP -LocalPort 1024-65535 -Program (Get-Command bun).Source -Action Allow -Profile Private
New-NetFirewallRule -DisplayName "CCB LAN Beacon Out (UDP)" -Direction Outbound -Protocol UDP -RemotePort 7101 -Action Allow -Profile Private
```
验证网络为"专用"(非公共):`Get-NetConnectionProfile`
**macOS**
首次运行时系统弹出"允许接受传入连接"对话框,点击"允许"。
如果使用 pf 防火墙:
```bash
echo "pass in proto udp from any to any port 7101" | sudo pfctl -ef -
```
**Linux**firewalld
```bash
sudo firewall-cmd --zone=trusted --add-port=7101/udp --permanent
sudo firewall-cmd --zone=trusted --add-port=1024-65535/tcp --permanent
sudo firewall-cmd --reload
```
**Linux**iptables
```bash
sudo iptables -A INPUT -p udp --dport 7101 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 1024:65535 -m owner --uid-owner $(id -u) -j ACCEPT
```
### 第二步:启动
```bash
# 机器 A例如 192.168.50.22
bun run dev
# 机器 B例如 192.168.50.27
bun run dev
```
启动后等待 3-5 秒beacon 广播间隔),两边自动发现并连接。
### 第三步:查看和操作
在任一台机器上:
```
/pipes
```
输出示例:
```
pipe: cli-a91bad56 (main) 192.168.50.22 2/3 selected
Main machine: 205d6c3a... (this machine)
[main] cli-a91bad56 XC/192.168.50.22 [alive] (you)
☑ [sub-1] cli-da029538 XC/192.168.50.22 [alive] [connected]
LAN Peers:
☐ [main] cli-04d67950 vmwin11/192.168.50.27 tcp:192.168.50.27:58853 [LAN]
```
### 第四步:选中目标并发送任务
1.`Shift+↓` 展开选择面板
2. `↑↓` 移动到 LAN peer
3. `Space` 选中
4. `Enter` 确认
5. 输入 prompt自动路由到远端执行
远端执行结果会流式回传到你的消息列表:
```
[main vmwin11/192.168.50.27 / cli-04d67950] 正在检查 git status...
[main vmwin11/192.168.50.27 / cli-04d67950] Completed
```
## 完整命令参考
| 命令 | 说明 |
|------|------|
| `/pipes` | 显示所有实例(本机 + LANShift+↓ 展开选择面板 |
| `/pipes select <name>` | 选中某实例 |
| `/pipes all` | 全选 |
| `/pipes none` | 取消全选 |
| `/attach <name>` | 手动 attach自动识别 LAN peer 并通过 TCP 连接) |
| `/detach <name>` | 断开连接 |
| `/send <name> <msg>` | 向指定 pipe 发送消息 |
| `/send tcp:host:port <msg>` | 直接通过 TCP 地址发送 |
| `/claim-main` | 强制声明为 main |
| `/pipe-status` | 显示详细状态 |
| `/peers` | 列出所有已发现的 peer |
## 快捷键
| 快捷键 | 场景 | 作用 |
|--------|------|------|
| `Shift+↓` | 状态栏可见时 | 展开/收起选择面板 |
| `↑ / ↓` | 面板展开时 | 移动光标 |
| `Space` | 面板展开时 | 选中/取消 |
| `Enter` | 面板展开时 | 确认关闭 |
| `Esc` | 面板展开时 | 取消关闭 |
| `← / →` | 有选中 pipe 时 | 切换路由模式 |
| `M` | 面板展开时 | 同 ←/→ 切换路由模式 |
## 路由模式
| 模式 | 显示 | 行为 |
|------|------|------|
| `selected pipes only` | 绿色 | prompt 仅发送到选中的 pipe本地不执行 |
| `local main` | 灰色 | prompt 仅在本地执行,不转发 |
切换路由模式不会清空选择。
## 权限转发
当远端 slave 执行需要权限的工具(如 BashTool
1. slave 发送 `permission_request` 到 main
2. main 弹出权限确认对话框,显示 `[role hostname/ip / pipeName]`
3. 用户确认/拒绝
4. 结果发回 slave继续或中断
## 工作原理
### 发现机制
- 每台机器启动时创建 UDP multicast beacon
- 组地址 `224.0.71.67`,端口 `7101`TTL=1不跨路由器
- 每 3 秒广播一次自身信息pipeName、IP、TCP 端口、角色)
- 15 秒未收到广播则标记 peer 丢失
### 通信机制
- 本机实例UDSUnix Domain Socket / Named Pipe
- 跨机器TCP动态端口通过 beacon 发现)
- 协议NDJSON每行一个 JSON 对象)
- 消息类型ping/pong、attach/detach、prompt/stream/done/error、permission
### 角色模型
| 角色 | 说明 |
|------|------|
| `main` | 首个启动的实例 |
| `sub` | 同机后续启动的实例 |
| `master` | attach 了至少一个 slave 的实例 |
| `slave` | 被 master attach 的实例 |
跨机器 attach 时,两边都可以是 main——不要求对方必须是 sub。
## 常见问题
### 看不到 LAN peer
1. 检查防火墙是否放行 UDP 7101
2. `Get-NetConnectionProfile`Windows确认网络为"专用"
3. 确认两台机器在同一子网(`ping` 能通)
4. 路由器未开启 AP 隔离
### 连接超时
1. 检查 TCP 入站防火墙规则
2. 确认没有 VPN 劫持流量
3. 尝试 `/send tcp:ip:port hello` 直接测试
### beacon 绑到了错误网卡
Windows 上 WSL/Docker 虚拟网卡可能劫持 multicast。beacon 会自动选择非内部 IPv4 接口。如果选错,检查 `getLocalIp()` 返回值。
## 安全说明
- TCP 连接当前**无认证**——同 LAN 内知道端口号即可连接
- Multicast TTL=1不跨路由器
- AI 通过 `SendMessageTool` 发送 `tcp:` 消息时需**用户显式确认**
- 建议仅在信任的局域网中使用

View File

@@ -0,0 +1,205 @@
# 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` | 工具执行中的观察记录 |
| `src/tools/AgentTool/runAgent.ts` | 子 Agent Trace 创建 |

118
docs/features/mcp-skills.md Normal file
View File

@@ -0,0 +1,118 @@
# MCP_SKILLS — MCP 技能发现
> Feature Flag: `FEATURE_MCP_SKILLS=1`
> 实现状态功能性实现config 门控筛选器完整,核心 fetcher 为 stub
> 引用数9
## 一、功能概述
MCP_SKILLS 将 MCP 服务器暴露的资源(`skill://` URI 方案发现并转换为可调用的技能命令。MCP 服务器可以同时提供 tools、prompts 和 resources启用此 feature 后,带有 `skill://` URI 的资源被识别为技能。
### 核心特性
- **自动发现**MCP 服务器连接时自动获取 `skill://` 资源
- **命令转换**:将 MCP 资源转换为 `prompt` 类型的 Command 对象
- **实时刷新**prompts/resources 列表变化时重新获取技能
- **缓存一致性**:连接关闭时清除技能缓存
## 二、实现架构
### 2.1 数据流
```
MCP Server 连接
client.ts: connectToServer / setupMcpClientConnections
├── fetchToolsForClient (MCP tools)
├── fetchCommandsForClient (MCP prompts → Command 对象)
├── fetchMcpSkillsForClient (MCP skill:// 资源 → Command 对象) [MCP_SKILLS]
└── fetchResourcesForClient (MCP resources)
commands = [...mcpPrompts, ...mcpSkills]
AppState.mcp.commands 更新
getMcpSkillCommands() 过滤 → SkillTool 调用
```
### 2.2 技能筛选
文件:`src/commands.ts:547-558`
`getMcpSkillCommands(mcpCommands)` 过滤条件:
```ts
cmd.type === 'prompt' // 必须是 prompt 类型
cmd.loadedFrom === 'mcp' // 必须来自 MCP 服务器
!cmd.disableModelInvocation // 必须可由模型调用
feature('MCP_SKILLS') // feature flag 必须开启
```
### 2.3 条件加载
文件:`src/services/mcp/client.ts:117-121`
`fetchMcpSkillsForClient` 通过 `require()` 条件加载feature flag 关闭时不加载任何模块:
```ts
const fetchMcpSkillsForClient = feature('MCP_SKILLS')
? require('../../skills/mcpSkills.js').fetchMcpSkillsForClient
: null
```
### 2.4 缓存管理
技能获取函数维护 `.cache`Map在以下时机清除
| 事件 | 行为 |
|------|------|
| 连接关闭 | 清除该 client 的技能缓存 |
| `disconnectMcpServer()` | 清除技能缓存 |
| `prompts/list_changed` 通知 | 刷新 prompts + 并行获取技能 |
| `resources/list_changed` 通知 | 刷新 resources + prompts + 技能 |
### 2.5 集成点
| 文件 | 行 | 说明 |
|------|------|------|
| `src/commands.ts` | 547-558, 561-608 | 命令过滤和 SkillTool 命令收集 |
| `src/services/mcp/client.ts` | 117-121, 1394, 1672, 2173-2181, 2346-2358 | 技能获取、缓存清除、连接时获取 |
| `src/services/mcp/useManageMCPConnections.ts` | 22-26, 682-740 | 实时刷新prompts/resources 变化) |
## 三、关键设计决策
1. **Feature gate 隔离**`feature('MCP_SKILLS')` 守护条件 `require()` 和所有调用点。关闭时无模块加载、无获取操作
2. **资源到技能映射**:技能从 MCP 服务器的 `skill://` URI 资源中发现。`fetchMcpSkillsForClient` 负责转换(当前为 stub
3. **循环依赖避免**`mcpSkillBuilders.ts` 作为依赖图叶节点,避免 `client.ts ↔ mcpSkills.ts ↔ loadSkillsDir.ts` 循环
4. **服务器能力检查**:技能获取还需要 MCP 服务器支持 resources (`!!client.capabilities?.resources`)
## 四、使用方式
```bash
# 启用 feature
FEATURE_MCP_SKILLS=1 bun run dev
# 前提条件:
# 1. 配置了支持 skill:// 资源的 MCP 服务器
# 2. MCP 服务器声明了 resources 能力
```
## 五、需要补全的内容
| 文件 | 状态 | 需要实现 |
|------|------|---------|
| `src/skills/mcpSkills.ts` | Stub | `fetchMcpSkillsForClient()` — 从 MCP 资源列表中筛选 `skill://` URI 并转换为 Command 对象 |
| `src/skills/mcpSkillBuilders.ts` | Stub | 技能构建器注册(避免循环依赖) |
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/commands.ts:547-608` | 技能命令过滤 |
| `src/services/mcp/client.ts:117-2358` | 技能获取 + 缓存管理 |
| `src/services/mcp/useManageMCPConnections.ts` | 实时刷新 |
| `src/skills/mcpSkills.ts` | 核心转换逻辑stub |

View File

@@ -0,0 +1,342 @@
# Pipes + LAN Pipes 完整功能指南
## 概述
Pipes 系统提供 Claude Code CLI 实例之间的通讯能力,分两层:
1. **Pipes本机**:同一台机器上的多个 CLI 实例通过 UDSUnix Domain Socket / Windows Named Pipe协作
2. **LAN Pipes局域网**:不同机器上的 CLI 实例通过 TCP + UDP Multicast 协作
两层使用同一套协议NDJSON和同一套命令`/pipes``/attach``/send` 等),对用户透明。
## Feature Flags
| Flag | 控制范围 | 默认 |
|------|----------|------|
| `UDS_INBOX` | 本机 Pipe IPC 全部功能 | dev/build 启用 |
| `LAN_PIPES` | 局域网 TCP + beacon 扩展 | dev/build 启用 |
手动启用:`FEATURE_UDS_INBOX=1 FEATURE_LAN_PIPES=1 bun run dev`
## 快速上手
### 本机多实例
```bash
# 终端 1
bun run dev
# 启动后自动注册为 main
# 终端 2
bun run dev
# 自动注册为 sub-1被 main 自动 attach
```
在终端 1 中输入 `/pipes`,可以看到两个实例。选中 sub-1 后,输入的消息会自动转发到 sub-1 执行。
### 局域网多机器
```bash
# 机器 A (192.168.50.22)
bun run dev
# 机器 B (192.168.50.27)
bun run dev
```
两边启动后等 3-5 秒beacon 广播间隔LAN peers 会自动发现并 attach。输入 `/pipes` 可看到标记 `[LAN]` 的远端实例。
### 防火墙配置(两台机器都需要)
**Windows**(管理员 PowerShell
```powershell
New-NetFirewallRule -DisplayName "Claude Code LAN Beacon (UDP)" -Direction Inbound -Protocol UDP -LocalPort 7101 -Action Allow -Profile Private
New-NetFirewallRule -DisplayName "Claude Code LAN Pipes (TCP)" -Direction Inbound -Protocol TCP -LocalPort 1024-65535 -Program (Get-Command bun).Source -Action Allow -Profile Private
New-NetFirewallRule -DisplayName "Claude Code LAN Beacon Out (UDP)" -Direction Outbound -Protocol UDP -RemotePort 7101 -Action Allow -Profile Private
# 确认网络为"专用"Get-NetConnectionProfile
```
**macOS**(首次运行时系统弹出对话框,点击"允许"即可):
```bash
# 如果需要手动放行 pf 防火墙:
echo "pass in proto udp from any to any port 7101" | sudo pfctl -ef -
```
**Linux**firewalld / iptables
```bash
# firewalld
sudo firewall-cmd --zone=trusted --add-port=7101/udp --permanent
sudo firewall-cmd --zone=trusted --add-port=1024-65535/tcp --permanent
sudo firewall-cmd --reload
# 或 iptables
sudo iptables -A INPUT -p udp --dport 7101 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 1024:65535 -m owner --uid-owner $(id -u) -j ACCEPT
```
确认:网络为局域网(非公共 WiFi路由器未开启 AP 隔离。
## 交互面板与快捷键
### 状态栏
执行 `/pipes` 后,输入框底部出现 pipe 状态栏(单行):
```
pipe: cli-a91bad56 (main) 192.168.50.22 2/3 selected selected pipes only · ←/→ or m switch · Shift+↓ edit
```
状态栏始终可见(直到会话结束),显示:当前 pipe 名、角色、IP、已选数/总数、路由模式。
### 展开选择面板
**Shift+↓**Shift + 下箭头)展开选择面板:
```
pipe: cli-a91bad56 (main) 192.168.50.22 ↑↓ move Space select ←/→ or m route Enter/Esc close Shift+↓ toggle
当前普通 prompt 走 已选 sub切换不会清空选择
☑ cli-da029538 (sub-1 XC/192.168.50.22)
☐ cli-04d67950 (main vmwin11/192.168.50.27)
☑ cli-893747d3 [offline] (sub-2 vmwin11/192.168.50.27)
```
### 面板内快捷键
| 快捷键 | 场景 | 作用 |
|--------|------|------|
| **Shift+↓** | 状态栏可见时 | 展开/收起选择面板 |
| **↑ / ↓** | 面板展开时 | 上下移动光标 |
| **Space** | 面板展开时 | 切换当前光标所在 pipe 的选中状态(☑ ↔ ☐) |
| **Enter** | 面板展开时 | 确认并关闭面板 |
| **Esc** | 面板展开时 | 取消并关闭面板 |
| **← / → 或 M** | 状态栏可见且有选中 pipe 时 | 切换路由模式(`selected pipes only``local main` |
### M 键 — 路由模式切换
M 键(或 ← / →)用于在两种路由模式之间切换,**无需展开面板**
| 模式 | 状态栏显示 | 行为 |
|------|-----------|------|
| `selected pipes only` | 绿色高亮 | 输入的 prompt **仅**发送到选中的 pipe本地不执行 |
| `local main` | 灰色 | 输入的 prompt 在**本地 main** 执行,不转发到任何 pipe |
切换路由模式**不会清空选择**。你可以在 `local main` 模式下保持选择,随时按 M 切回 `selected pipes only` 继续向远端发送。
### 完整操作流程示例
```
1. 输入 /pipes → 状态栏出现,显示发现的实例
2. 按 Shift+↓ → 展开选择面板
3. 按 ↓ 移动到目标 pipe → 光标移到 cli-04d67950
4. 按 Space → 选中 ☑ cli-04d67950
5. 按 Enter → 确认,面板收起
6. 输入 "帮我检查 git status" → prompt 自动发送到 cli-04d67950 执行
7. 按 M → 切换到 local main 模式
8. 输入 "本地做点什么" → 仅在本地执行
9. 按 M → 切回 selected pipes only
10. 输入 "继续远端任务" → 又发送到 cli-04d67950
```
## 命令参考
### /pipes
显示所有发现的实例,管理选择状态。再次执行 `/pipes` 切换面板展开/收起。
```
/pipes — 显示所有实例 + 切换选择面板
/pipes select <name> — 选中某实例(消息会广播到它)
/pipes deselect <name> — 取消选中
/pipes all — 全选
/pipes none — 全部取消
```
输出示例:
```
Your pipe: cli-a91bad56
Role: main
Machine ID: 205d6c3a...
IP: 192.168.50.22
Host: XC
Main machine: 205d6c3a... (this machine)
[main] cli-a91bad56 XC/192.168.50.22 [alive] (you)
☑ [sub-1] cli-da029538 XC/192.168.50.22 [alive] [connected]
LAN Peers:
☐ [main] cli-04d67950 vmwin11/192.168.50.27 tcp:192.168.50.27:58853 [LAN]
Selected: cli-da029538
```
### /attach <name>
手动 attach 到一个实例,使其成为你的 slave。
```
/attach cli-04d67950 — 连接到指定 pipe自动解析 LAN TCP 端点)
```
attach 后,对方变为 slave你变为 master。可以向它发送 prompt。通常不需要手动 attach——heartbeat 会自动发现并连接。
### /detach <name>
断开与某个 slave 的连接。
```
/detach cli-04d67950
```
### /send <name> <message>
向指定 pipe 发送消息(不依赖选择状态,直接指定目标)。
```
/send cli-04d67950 请帮我检查一下日志
/send tcp:192.168.50.27:58853 hello — 直接通过 TCP 地址发送
```
### /claim-main
强制声明当前机器为 main用于 main 意外退出后的恢复)。
## 消息路由
### 选中 pipe 后的自动路由
1. 通过 `/pipes select` 或 Shift+Down 面板选中一个或多个 pipe
2. 在输入框中正常输入消息
3. 消息自动发送到所有选中的已连接 pipe
4. 每个 pipe 独立执行,结果流式回传到 main 的消息列表
### 路由模式
| 模式 | 行为 |
|------|------|
| `selected`(默认) | 消息发送到选中的 pipe |
| `local` | 消息仅在本地执行,不转发 |
## 架构
### 通信协议
所有通讯使用 NDJSONNewline-Delimited JSON每行一个消息
```json
{"type":"ping","from":"cli-abc","ts":"2026-04-11T00:00:00.000Z"}
{"type":"prompt","data":"帮我查看 git status","from":"cli-abc","ts":"..."}
{"type":"stream","data":"正在执行...","from":"cli-def","ts":"..."}
{"type":"done","data":"","from":"cli-def","ts":"..."}
```
### 消息类型
| 类型 | 方向 | 说明 |
|------|------|------|
| `ping`/`pong` | 双向 | 健康检查 |
| `attach_request`/`accept`/`reject` | M→S/S→M | 连接控制 |
| `detach` | M→S | 断开连接 |
| `prompt` | M→S | 主向从发送 prompt |
| `prompt_ack` | S→M | 从确认接收 |
| `stream` | S→M | 从流式回传 AI 输出 |
| `tool_start`/`tool_result` | S→M | 工具执行通知 |
| `done` | S→M | 本轮完成 |
| `error` | 双向 | 错误通知 |
| `permission_request`/`response`/`cancel` | 双向 | 权限审批转发 |
### 传输层
```
本机 LAN
┌──────────────┐ ┌──────────────┐
│ PipeServer │ │ PipeServer │
│ UDS sock │ │ UDS sock │
│ TCP :rand │◄───TCP───►│ TCP :rand │
├──────────────┤ ├──────────────┤
│ LanBeacon │◄──UDP────►│ LanBeacon │
│ 224.0.71.67 │ mcast │ 224.0.71.67 │
└──────────────┘ └──────────────┘
```
- **UDS**:本机实例间通讯,通过文件系统路径寻址(`~/.claude/pipes/cli-xxx.sock`
- **TCP**LAN 实例间通讯,动态端口,通过 beacon 发现
- **UDP Multicast**peer 发现3 秒广播一次 announce 包
### 角色模型
| 角色 | 说明 |
|------|------|
| `main` | 首个启动的实例,管理 registry |
| `sub` | 后续启动的同机实例(或被 attach 的 LAN 实例) |
| `master` | attach 了至少一个 slave 的实例 |
| `slave` | 被 master attach 控制的实例 |
角色转换:
- 首个启动 → `main`
- 同机后续启动 → `sub`(自动被 main attach → `slave`
- LAN 发现 → 两边都是 `main`heartbeat 自动互相 attach
- 被 attach → 变为 `slave`(可通过 `/detach` 恢复)
### 发现机制
**本机**:通过 `~/.claude/pipes/registry.json` 文件(带文件锁),`machineId` 绑定主机身份。
**LAN**:通过 UDP multicast beacon
1. 每 3 秒广播 `{ proto, pipeName, machineId, ip, tcpPort, role }`
2. 收到其他实例的 announce → 记入 peers Map
3. 15 秒未收到 → 标记 peer lost
4. Heartbeat 合并 local registry + beacon peers → 统一 attach 目标列表
### Heartbeat 循环5 秒间隔)
```
main/master 角色:
1. cleanupStaleEntries() — 清理 registry 中死掉的条目
2. getAliveSubs() — 获取存活的本地 subs
3. refreshDiscoveredPipes() — 刷新 discoveredPipes包含 LAN peers
4. 合并 LAN peers 到 state
5. 构建统一 attach 目标列表 — 本地 subs + LAN peers
6. 遍历未连接的目标 → 自动 attach
7. 清理断开的 slave 连接 — 同时检查 local registry 和 beacon
sub 角色:
1. 检测 main 是否存活
2. main 死亡 → 同机则接管 main 角色,跨机则独立
```
## 关键文件
| 文件 | 职责 |
|------|------|
| `src/utils/pipeTransport.ts` | PipeServer双模 UDS+TCP、PipeClient、类型定义 |
| `src/utils/lanBeacon.ts` | UDP multicast beacon、singleton 管理 |
| `src/utils/pipeRegistry.ts` | Registry CRUD、角色判定、machineId、LAN merge |
| `src/utils/peerAddress.ts` | 地址解析uds:/bridge:/tcp: scheme |
| `src/screens/REPL.tsx` | Bootstrap、heartbeat、cleanup、prompt 路由 |
| `src/hooks/useMasterMonitor.ts` | Slave client registry、消息订阅 |
| `src/hooks/useSlaveNotifications.ts` | Slave 端通知处理 |
| `src/commands/pipes/pipes.ts` | /pipes 命令 |
| `src/commands/attach/attach.ts` | /attach 命令 |
| `src/commands/send/send.ts` | /send 命令 |
| `src/tools/SendMessageTool/SendMessageTool.ts` | AI 发消息工具(含 tcp: 支持) |
## 后续优化方向
### 安全P0
1. **TCP 认证**:首次连接时交换 HMAC-SHA256 token基于 machineId + session secret防止未授权设备连接
2. **JSON schema 验证**:在所有 `JSON.parse` 入口点增加 Zod 校验,防止 prototype pollution
3. **Beacon 信息脱敏**hash machineId 后再广播,不暴露硬件序列号
### 可靠性P1
4. **多网卡选择**`getLocalIp()` 应优先选择 RFC 1918 地址,排除 VPN/Docker 接口
5. **TCP target 验证**`parseTcpTarget()` 应限制目标为已知 beacon peers 或 RFC 1918 范围
6. **PipeServer close()**:改为 `Promise.allSettled` 并行关闭 UDS + TCP`_closing` guard
### 功能P2
7. **mDNS/DNS-SD**:作为 multicast 受限环境下的 beacon 替代方案
8. **固定端口配置**:允许用户指定 TCP 端口范围,便于防火墙精确配置
9. **TLS 加密**TCP 传输加密,防中间人窃听
10. **双向 prompt**:当前只有 master → slave 方向,可考虑 slave 主动向 master 发送结果/请求

113
docs/features/proactive.md Normal file
View File

@@ -0,0 +1,113 @@
# PROACTIVE — 主动模式
> Feature Flag: `FEATURE_PROACTIVE=1`(与 `FEATURE_KAIROS=1` 共享功能)
> 实现状态:核心循环与 SleepTool 已落地,部分外围文档仍在补齐
> 引用数37
## 一、功能概述
PROACTIVE 实现 Tick 驱动的自主代理。CLI 在用户不输入时也能持续工作:定时唤醒执行任务,配合 SleepTool 控制节奏。适用于长时间运行的后台任务(等待 CI、监控文件变化、定时检查等
### 与 KAIROS 的关系
所有代码检查都是 `feature('PROACTIVE') || feature('KAIROS')`,即:
- 单独开 `FEATURE_PROACTIVE=1` → 获得 proactive 能力
- 单独开 `FEATURE_KAIROS=1` → 自动获得 proactive 能力
- 两者都开 → 相同效果(不重复)
## 二、实现架构
### 2.1 模块状态
| 模块 | 文件 | 状态 | 说明 |
|------|------|------|------|
| 核心逻辑 | `src/proactive/index.ts` | **已实现** | `activateProactive()``deactivateProactive()``pause/resume``nextTickAt` 调度状态 |
| SleepTool 提示 | `src/tools/SleepTool/prompt.ts` | **完整** | 工具提示定义(工具名:`Sleep` |
| 命令注册 | `src/commands.ts:62-65` | **布线** | 动态加载 `./commands/proactive.js` |
| 工具注册 | `src/tools.ts:26-28` | **布线** | SleepTool 动态加载 |
| REPL 集成 | `src/screens/REPL.tsx` | **已实现** | tick 驱动、standby/sleeping 状态、页脚与 bridge automation metadata 上报 |
| 系统提示 | `src/constants/prompts.ts:860-914` | **完整** | 自主工作行为指令(~55 行详细 prompt |
| 远控状态镜像 | `src/utils/sessionState.ts` | **已实现** | 向 remote-control/CCR 暴露 `automation_state` 元数据 |
### 2.2 系统提示内容
`getProactiveSection()` 注入的自主工作指令包含:
| 章节 | 内容 |
|------|------|
| Tick 驱动 | `<tick_tag>` prompt 保持存活,包含用户本地时间 |
| 节奏控制 | SleepTool 控制等待间隔prompt cache 5 分钟过期 |
| 空操作规则 | 无事可做时**必须**调用 Sleep禁止输出 "still waiting" |
| 首次唤醒 | 简短问候,等待方向(不主动探索) |
| 后续唤醒 | 寻找有用工作:调查、验证、检查(不 spam 用户) |
| 偏向行动 | 读文件、搜索代码、commit — 不需询问 |
| 终端焦点 | `terminalFocus` 字段调节自主程度 |
### 2.3 数据流
```
activateProactive()
Tick 调度器启动
├── 定时生成 <tick_tag> 消息
│ ├── 包含用户当前本地时间
│ └── 注入到对话流sessionStorage
模型处理 tick
├── 有事可做 → 使用工具执行 → 可能再次 Sleep
└── 无事可做 → 必须调用 SleepTool
SleepTool 等待
├── 用户插入新工作 / 队列中有命令 → 立即唤醒
├── proactive 被关闭 → 立即中断
└── 进入休眠时向远端 surfaces 上报 `automation_state = sleeping`
下一个 tick 到达
```
## 三、当前行为补充
- `standby`proactive 已开启,当前没有执行中的 turn且已调度下一个 tick。
- `sleeping`:模型显式调用 `SleepTool` 进入等待窗口。
- remote-control/CCR 通过 `external_metadata.automation_state` 接收这两个状态,用于 Web UI 的 Autopilot 状态显示。
- `SleepTool` 现在不是纯定时器;它会在共享命令队列出现新工作时提前醒来。
## 四、关键设计决策
1. **Tick 驱动**:模型通过 SleepTool 自行控制唤醒频率,不是外部事件推送
2. **空操作必须 Sleep**:防止 "still waiting" 类空消息浪费 turn 和 token
3. **Prompt cache 考量**SleepTool 提示中提到 cache 5 分钟过期,建议平衡等待时间
4. **Terminal Focus 感知**:模型根据用户是否在看终端调整自主程度
## 五、使用方式
```bash
# 单独启用 proactive
FEATURE_PROACTIVE=1 bun run dev
# 通过 KAIROS 间接启用
FEATURE_KAIROS=1 bun run dev
# 组合使用
FEATURE_PROACTIVE=1 FEATURE_KAIROS=1 FEATURE_KAIROS_BRIEF=1 bun run dev
```
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/proactive/index.ts` | 核心逻辑与 next-tick 状态 |
| `src/tools/SleepTool/prompt.ts` | SleepTool 工具提示 |
| `src/tools/SleepTool/SleepTool.ts` | 休眠/唤醒执行逻辑 |
| `src/constants/prompts.ts:860-914` | 自主工作系统提示 |
| `src/screens/REPL.tsx` | REPL tick 集成与 automation 状态上报 |
| `src/utils/sessionStorage.ts:4892-4912` | Tick 消息注入 |
| `src/utils/sessionState.ts` | bridge/CCR metadata 镜像 |
| `src/components/PromptInput/PromptInputFooterLeftSide.tsx` | 页脚 UI 状态 |

View File

@@ -0,0 +1,293 @@
# Remote Control Server 私有化部署指南
本指南说明如何将 Remote Control Server (RCS) 部署到私有环境,并通过 Claude Code CLI 连接使用。
## 架构概览
```
┌──────────────────┐ ┌──────────────────────┐
│ Claude Code CLI │ ◄── HTTP/SSE/WS ─►│ Remote Control │
│ (Bridge Worker) │ 长轮询 + 心跳 │ Server (RCS) │
└──────────────────┘ │ │
│ ┌──────────────┐ │
┌──────────────────┐ HTTP/SSE │ │ In-Memory │ │
│ Web UI 控制面板 │ ◄─────────────── │ │ Store │ │
│ (/code/*) │ │ └──────────────┘ │
└──────────────────┘ │ ┌──────────────┐ │
│ │ JWT Auth │ │
│ └──────────────┘ │
└──────────────────────┘
```
**RCS 是一个纯内存的中间服务**,它的职责是:
- 接收 Claude Code CLI 的环境注册和工作轮询
- 提供 Web UI 供操作者远程监控和审批
- 通过 WebSocket/SSE 双向传输消息
- 管理会话、环境、权限请求
## 前置条件
- 一台可被 Claude Code CLI 和 Web 浏览器同时访问的服务器物理机、VM、容器均可
- [Docker](https://www.docker.com/)
- 启用 `BRIDGE_MODE` feature flag 的 Claude Code 构建
## 部署
### 构建 Docker 镜像
在项目根目录执行:
```bash
docker build -t rcs:latest -f packages/remote-control-server/Dockerfile .
```
### 启动容器
```bash
docker run -d \
--name rcs \
-p 3000:3000 \
-e RCS_API_KEYS=sk-rcs-your-secret-key-here \
-e RCS_BASE_URL=https://rcs.example.com \
-v rcs-data:/app/data \
--restart unless-stopped \
rcs:latest
```
### Docker Compose
```yaml
version: "3.8"
services:
rcs:
build:
context: .
dockerfile: packages/remote-control-server/Dockerfile
args:
VERSION: "0.1.0"
ports:
- "3000:3000"
environment:
- RCS_API_KEYS=sk-rcs-your-secret-key-here
- RCS_BASE_URL=https://rcs.example.com
volumes:
- rcs-data:/app/data
restart: unless-stopped
volumes:
rcs-data:
```
启动:
```bash
docker compose up -d
```
## 环境变量参考
### 服务器端
| 变量 | 必填 | 默认值 | 说明 |
|------|------|--------|------|
| `RCS_API_KEYS` | **是** | _(空)_ | API 密钥列表,逗号分隔。用于客户端认证和 JWT 签名。**务必设置强密钥** |
| `RCS_PORT` | 否 | `3000` | 服务监听端口 |
| `RCS_HOST` | 否 | `0.0.0.0` | 服务监听地址 |
| `RCS_BASE_URL` | 否 | `http://localhost:3000` | 外部访问 URL。用于生成 WebSocket 连接地址,必须与客户端实际访问的地址一致 |
| `RCS_VERSION` | 否 | `0.1.0` | 版本号,显示在 `/health` 响应中 |
| `RCS_POLL_TIMEOUT` | 否 | `8` | V1 工作轮询超时(秒) |
| `RCS_HEARTBEAT_INTERVAL` | 否 | `20` | 心跳间隔(秒) |
| `RCS_JWT_EXPIRES_IN` | 否 | `3600` | JWT 令牌有效期(秒) |
| `RCS_DISCONNECT_TIMEOUT` | 否 | `300` | 断线判定超时(秒) |
### 客户端Claude Code CLI
| 变量 | 必填 | 说明 |
|------|------|------|
| `CLAUDE_BRIDGE_BASE_URL` | **是** | RCS 服务器地址,例如 `https://rcs.example.com`。设置此变量即启用自托管模式,跳过 GrowthBook 门控 |
| `CLAUDE_BRIDGE_OAUTH_TOKEN` | **是** | 认证令牌,必须与服务器端 `RCS_API_KEYS` 中的某个值匹配 |
| `CLAUDE_BRIDGE_SESSION_INGRESS_URL` | 否 | WebSocket 入口地址(默认与 `CLAUDE_BRIDGE_BASE_URL` 相同) |
| `CLAUDE_CODE_REMOTE` | 否 | 设为 `1` 时标记为远程执行模式 |
## Claude Code 客户端连接
### 1. 设置环境变量
在运行 Claude Code 的机器上设置:
```bash
export CLAUDE_BRIDGE_BASE_URL="https://rcs.example.com"
export CLAUDE_BRIDGE_OAUTH_TOKEN="sk-rcs-your-secret-key-here"
```
### 2. 启动 Claude Code
```bash
# 使用 dev 模式BRIDGE_MODE 默认启用)
bun run dev
# 或使用构建产物
bun run dist/cli.js
```
### 3. 执行 /remote-control 命令
在 Claude Code 的 REPL 中输入:
```
/remote-control
```
环境型 Remote Control例如 `claude remote-control` 子命令)会向 RCS 注册环境,注册成功后在终端显示连接 URL
```
https://rcs.example.com/code?bridge=<environmentId>
```
交互式 REPL 方式(`--remote-control``/remote-control`)在某些桥接模式下也可能直接给出会话 URL
```
https://rcs.example.com/code/session_<id>
```
两种 URL 都可以直接在浏览器打开并远程操控当前会话;只有 environment 模式才会出现在 Web UI 的环境列表中。
若已连接,再次执行 `/remote-control` 会显示对话框,包含以下选项:
- **Disconnect this session** — 断开远程连接
- **Show QR code** — 显示/隐藏二维码
- **Continue** — 保持连接,继续使用
也可通过 CLI 参数直接启动:
```bash
claude remote-control
# 或简写
claude rc
# 或
claude bridge
```
## Web UI 控制面板
通过 `/remote-control` 命令获取 URL 后,在浏览器打开即可使用。功能:
- 查看已注册的运行环境environment 模式)
- 创建和管理会话
- 实时查看对话消息和工具调用
- 查看 Autopilot 状态(`standby` / `sleeping`)和自动运行指示
- 查看 authoritative task snapshots 驱动的 Tasks 面板
- 审批 Claude Code 的工具权限请求
Web UI 使用 UUID 认证(无需用户账户),适合受信任网络环境。
## 工作流程详解
```
┌──────────────────────────────────────────────────────────┐
│ 完整工作流程 │
└──────────────────────────────────────────────────────────┘
1. Claude Code CLI 启动,设置环境变量指向自托管 RCS
2. 用户执行 /remote-control 命令
3. 注册环境
CLI ──POST /v1/environments/bridge──► RCS
CLI ◄── { environment_id, environment_secret } ── RCS
4. 终端显示连接 URL
https://rcs.example.com/code?bridge=<environmentId>
5. 开始工作轮询(循环)
CLI ──GET /v1/environments/:id/work/poll──► RCS
(长轮询,等待任务分配,超时 8 秒后重试)
6. 浏览器打开 URL → Web UI 创建任务
Browser ──POST /web/sessions──► RCS
RCS 分配 work 给正在轮询的 CLI
7. CLI 收到任务并确认
CLI ◄── { id, data: { type, sessionId } } ── RCS
CLI ──POST /v1/environments/:id/work/:workId/ack──► RCS
8. 建立会话连接
CLI ──WebSocket /v1/session_ingress──► RCS
(或使用 V2 的 SSE + HTTP POST
9. 双向通信
CLI ──消息/工具调用结果──► RCS ──► Browser
CLI ◄──权限审批/指令───── RCS ◄──── Browser
CLI ──automation_state / task_state──► RCS ──► Browser
10. 心跳保活(每 20 秒)
CLI ──POST /v1/environments/:id/work/:workId/heartbeat──► RCS
11. 任务完成 → 归档会话 → 注销环境
```
## 故障排查
### Web UI 看不到当前 Autopilot 状态
- `standby`proactive 已开启,正在等待下一个 tick
- `sleeping`:模型正在 `SleepTool` 等待窗口中
这两个状态通过 worker `external_metadata.automation_state` 上报。如果页面只显示普通 working spinner优先检查 CLI 和 RCS 之间的 worker metadata PUT 是否成功。
### CLI 无法连接
```
Error: Remote Control is not available in this build.
```
**原因**`BRIDGE_MODE` feature flag 未启用。
**解决**:使用 dev 模式(默认启用)或确保构建时包含 `BRIDGE_MODE` flag。
### 认证失败 (401)
```
Error: Unauthorized
```
**检查项**
1. `CLAUDE_BRIDGE_OAUTH_TOKEN` 是否与 `RCS_API_KEYS` 中的值匹配
2. API Key 是否包含多余的空格或换行
3. 两个环境变量是否都已正确设置
### WebSocket 连接中断
**检查项**
1. 如果使用反向代理,确认已正确配置 WebSocket 升级(`Upgrade` / `Connection` 头)
2. 代理的 `proxy_read_timeout` 是否足够大(建议 86400 秒)
3. 网络防火墙是否允许 WebSocket 流量
### 健康检查
```bash
curl https://rcs.example.com/health
# 预期: {"status":"ok","version":"0.1.0"}
```
## 限制与注意事项
| 项目 | 说明 |
|------|------|
| 存储 | 纯内存存储Map服务器重启后所有会话和环境数据丢失 |
| 扩展 | 不支持水平扩展(无共享状态),单实例部署 |
| 并发 | 适合中小规模使用,大量并发会话可能需要性能调优 |
| 数据持久化 | `/app/data` 卷已预留但当前未使用,未来可能用于持久化 |
| Web UI 认证 | 基于 UUID无用户账户系统适合受信任网络环境 |
## 与云端模式对比
| 特性 | 云端 (Anthropic CCR) | 自托管 (RCS) |
|------|---------------------|--------------|
| 认证方式 | claude.ai OAuth 订阅 | API Key |
| GrowthBook 门控 | 需要 `tengu_ccr_bridge` 通过 | 自动跳过 |
| 功能标志 | 需要 `BRIDGE_MODE=1` | 同样需要 |
| 部署位置 | Anthropic 云端 | 用户自有服务器 |
| 数据流经 | Anthropic 基础设施 | 用户私有网络 |
| 依赖 | claude.ai 订阅 + OAuth | 仅需 API Key |
自托管模式的核心优势是:设置 `CLAUDE_BRIDGE_BASE_URL` 后,代码自动调用 `isSelfHostedBridge()` 返回 `true`,跳过所有 GrowthBook 和订阅检查,无需 claude.ai 账户即可使用。

View File

@@ -0,0 +1,310 @@
# Stub 恢复设计 1-4
> 日期2026-04-12
> 目标:基于当前代码边界,为下一阶段 4 个 stub/半 stub 命令面给出可实施的设计方案。
> 排序原则:按建议实施顺序排序,不按问题严重性排序。
## 设计原则
- 先做能独立闭环、收益明确、改动边界清晰的项。
- 大项拆成 `MVP``Phase 2+`,避免一次性掉进大范围恢复。
- 优先复用已有状态、传输层、日志与配置能力,不重造协议。
- 设计以当前仓库实际代码为准,不以旧文档的理想状态为准。
## 1. `claude daemon status` / `claude daemon stop`
### 现状
- `start` 路径已有完整 supervisor + worker 生命周期:
[src/daemon/main.ts](</e:/Source_code/Claude-code-bast/src/daemon/main.ts:1>)
[src/daemon/workerRegistry.ts](</e:/Source_code/Claude-code-bast/src/daemon/workerRegistry.ts:1>)
- `status` / `stop` 目前只是占位输出:
[src/daemon/main.ts](</e:/Source_code/Claude-code-bast/src/daemon/main.ts:49>)
- `/remote-control-server` 有自己的命令内 UI 状态,但只维护当前进程内的 `daemonProcess`,并不适合作为跨进程 CLI 管理基础:
[src/commands/remoteControlServer/remoteControlServer.tsx](</e:/Source_code/Claude-code-bast/src/commands/remoteControlServer/remoteControlServer.tsx:32>)
### 目标
-`claude daemon status``claude daemon stop` 在另一个 CLI 进程中也能正确工作。
- 不依赖 TUI 内存态,不要求当前命令进程就是启动 daemon 的那个进程。
### MVP 方案
- 新增 daemon 状态文件,例如:
`~/.claude/daemon/remote-control.json`
- `start` 时写入:
- supervisor pid
- cwd
- startedAt
- worker kinds
- 最近状态
- `status`
- 读取状态文件
- 用现有进程探测能力验证 pid 是否存活
- 输出 `running / stopped / stale`
- stale 时自动清理状态文件
- `stop`
- 读取 pid
- 发送 `SIGTERM`
- 等待退出
- 超时后 `SIGKILL`
- 清理状态文件
### 代码范围
- 新增 `src/daemon/state.ts`
- 修改 [src/daemon/main.ts](</e:/Source_code/Claude-code-bast/src/daemon/main.ts:1>)
- 轻量修改 [src/commands/remoteControlServer/remoteControlServer.tsx](</e:/Source_code/Claude-code-bast/src/commands/remoteControlServer/remoteControlServer.tsx:32>),让 UI 尽量读取同一份状态文件
### 验证
1. `claude daemon start`
2. 新开终端执行 `claude daemon status`
3. 执行 `claude daemon stop`
4. 再次执行 `claude daemon status`,确认返回 `stopped` 或清晰的 `stale cleaned`
### 风险
- Windows 信号模型和 Unix 不同,`stop` 需要超时兜底。
- 当前设计默认单 supervisor不处理多实例并发。
### 工作量判断
-
- 适合作为下一步的首选实现项
## 2. `BG_SESSIONS`
### 现状
- fast-path 已接好:
[src/entrypoints/cli.tsx](</e:/Source_code/Claude-code-bast/src/entrypoints/cli.tsx:218>)
- session registry 已有真实实现:
[src/utils/concurrentSessions.ts](</e:/Source_code/Claude-code-bast/src/utils/concurrentSessions.ts:1>)
- `exit` 在 bg session 内已会 `tmux detach-client`
[src/commands/exit/exit.tsx](</e:/Source_code/Claude-code-bast/src/commands/exit/exit.tsx:20>)
- 但 CLI handler 仍全空:
[src/cli/bg.ts](</e:/Source_code/Claude-code-bast/src/cli/bg.ts:1>)
- task summary 仍然是 stub
[src/utils/taskSummary.ts](</e:/Source_code/Claude-code-bast/src/utils/taskSummary.ts:1>)
### 目标
- 先把 `ps` / `logs` / `kill` 做成真正有用的 session 管理命令。
- 不在第一阶段就强行补完 `attach` / `--bg`
### Phase 2AMVP
- 实现 `ps`
- 从 registry 读取 live sessions
- 展示 pid、kind、sessionId、cwd、name、startedAt、bridgeSessionId
- 如果有 activity/status则一并展示
- 实现 `logs`
- 支持按 `sessionId / pid / name` 查找
- 优先复用本地 transcript/log 读取能力
- 如果 registry 里存在 `logPath`,支持 tail 文件
- 实现 `kill`
- 解析目标 session
- 发退出信号
- 清理 stale registry
### Phase 2B后续
- 实现 `attach`
- 实现 `--bg`
- 实现 `taskSummary` 的中途状态更新
### 为什么要拆
- 现有 registry 记录了 `pid / sessionId / name / logPath`
- 但没有可靠的 tmux attach target
- 所以 `attach``--bg` 不是简单补 handler而是需要补启动/附着元数据设计
### 代码范围
- 修改 [src/cli/bg.ts](</e:/Source_code/Claude-code-bast/src/cli/bg.ts:1>)
- 修改 [src/utils/concurrentSessions.ts](</e:/Source_code/Claude-code-bast/src/utils/concurrentSessions.ts:1>) 以便后续 attach/--bg 扩展
- 修改 [src/utils/taskSummary.ts](</e:/Source_code/Claude-code-bast/src/utils/taskSummary.ts:1>)
- 复用:
[src/utils/sessionStorage.ts](</e:/Source_code/Claude-code-bast/src/utils/sessionStorage.ts:3870>)
[src/utils/udsClient.ts](</e:/Source_code/Claude-code-bast/src/utils/udsClient.ts:1>)
### 验证
1. `ps` 能列出 live sessions
2. `logs <sessionId|pid|name>` 能输出对应日志
3. `kill <sessionId|pid|name>` 能结束目标 session
### 风险
- `attach` / `--bg` 第二阶段需要 tmux 元数据设计
- Windows 下 tmux 路径需要明确降级策略
### 工作量判断
- `ps/logs/kill` 中等
- `attach/--bg` 明显更大,应分阶段
## 3. `TEMPLATES`
### 现状
- 命令入口只有 fast-path
[src/entrypoints/cli.tsx](</e:/Source_code/Claude-code-bast/src/entrypoints/cli.tsx:249>)
- handler 是空的:
[src/cli/handlers/templateJobs.ts](</e:/Source_code/Claude-code-bast/src/cli/handlers/templateJobs.ts:1>)
- `markdownConfigLoader` 已把 `templates` 纳入配置目录:
[src/utils/markdownConfigLoader.ts](</e:/Source_code/Claude-code-bast/src/utils/markdownConfigLoader.ts:29>)
- `query / stopHooks` 已预留 job classifier 链路:
[src/query/stopHooks.ts](</e:/Source_code/Claude-code-bast/src/query/stopHooks.ts:103>)
- `jobs/classifier.ts` 仍是 stub
[src/jobs/classifier.ts](</e:/Source_code/Claude-code-bast/src/jobs/classifier.ts:1>)
### 目标
-`new / list / reply` 做成可用的模板任务系统。
- 第一阶段不碰复杂的自动分类与自动执行。
### MVP 方案
- 模板来源:
`.claude/templates/*.md`
- 模板格式:
复用现有 markdown + frontmatter 解析,不另外设计 DSL
- `list`
- 列出所有模板
- 显示模板名、description、路径
- `new <template> [args...]`
- 解析模板
-`~/.claude/jobs/<job-id>/` 下创建 job 目录
- 写入 `template.md``input.txt``state.json`
- 返回 job id 与目录
- `reply <job-id> <text>`
- 将回复写入 `replies.jsonl``input.txt`
- 更新 `state.json`
### Phase 2
- 恢复 [src/jobs/classifier.ts](</e:/Source_code/Claude-code-bast/src/jobs/classifier.ts:1>)
- 让带 `CLAUDE_JOB_DIR` 的 job session 在 turn 完成后自动更新 `state.json`
- 再决定是否补自动 job runner
### 为什么要拆
- 当前证据表明这是“template job commands”不是单纯模板列表
- 但自动 job 运行链路没有足够现成实现,先做文件系统 job lifecycle 更稳
### 代码范围
- 修改 [src/cli/handlers/templateJobs.ts](</e:/Source_code/Claude-code-bast/src/cli/handlers/templateJobs.ts:1>)
- 新增 `src/jobs/state.ts`
- 新增 `src/jobs/templates.ts`
- Phase 2 再改 [src/jobs/classifier.ts](</e:/Source_code/Claude-code-bast/src/jobs/classifier.ts:1>)
### 验证
1. `list` 能列出 `.claude/templates`
2. `new` 能创建 job 目录和状态文件
3. `reply` 能更新 job 内容和状态
4. Phase 2 再验证 classifier 写状态
### 风险
- frontmatter schema 需要先定义最小字段集
- 一旦扩展到“自动运行 job”范围会明显膨胀
### 工作量判断
- MVP 中等
- 完整 job 系统偏大
## 4. `assistant [sessionId]`
### 现状
- attach 主流程其实已经存在:
[src/main.tsx](</e:/Source_code/Claude-code-bast/src/main.tsx:4708>)
- 远端 viewer 所需基础模块已存在:
[src/remote/RemoteSessionManager.ts](</e:/Source_code/Claude-code-bast/src/remote/RemoteSessionManager.ts:1>)
[src/hooks/useAssistantHistory.ts](</e:/Source_code/Claude-code-bast/src/hooks/useAssistantHistory.ts:1>)
[src/assistant/sessionHistory.ts](</e:/Source_code/Claude-code-bast/src/assistant/sessionHistory.ts:1>)
- 真正 stub 的主要是:
[src/assistant/sessionDiscovery.ts](</e:/Source_code/Claude-code-bast/src/assistant/sessionDiscovery.ts:1>)
[src/assistant/AssistantSessionChooser.ts](</e:/Source_code/Claude-code-bast/src/assistant/AssistantSessionChooser.ts:1>)
[src/commands/assistant/assistant.ts](</e:/Source_code/Claude-code-bast/src/commands/assistant/assistant.ts:7>)
[src/assistant/index.ts](</e:/Source_code/Claude-code-bast/src/assistant/index.ts:1>)
### 目标
- 不一次性恢复整个 KAIROS 助手系统。
- 先做“明确 sessionId 的 viewer attach 可用”,再逐步补 discovery / chooser / install。
### Phase 4AMVP
- 只支持 `claude assistant <sessionId>`
-`claude assistant` 无参数模式,先返回明确提示:
- 当前版本需要显式 `sessionId`
- discovery 尚未启用
- 这样可以直接复用现有 attach 分支,不必先恢复 chooser/install wizard
### Phase 4B
- 恢复 `discoverAssistantSessions()`
- 数据来源优先复用现有 sessions / bridge / teleport API而不是新协议
-`claude assistant` 无参数时能拿到候选 session 列表
### Phase 4C
- 恢复 `AssistantSessionChooser`
- 多 session 时可交互选择
### Phase 4D
- 最后考虑 install wizard 辅助函数
- 这部分属于“没有 session 时如何引导”,不是 attach 核心路径
### 为什么要拆
- attach 渲染层与远端消息通道大部分已经在
- 真正缺的是“如何发现目标 session”和“如何交互选择”
- 如果把 `src/assistant/index.ts` 的整套 KAIROS 正常模式也一起拉进来,范围会失控
### 代码范围
- Phase 4A
- [src/main.tsx](</e:/Source_code/Claude-code-bast/src/main.tsx:4708>)
- [src/commands/assistant/index.ts](</e:/Source_code/Claude-code-bast/src/commands/assistant/index.ts:1>)
- Phase 4B
- [src/assistant/sessionDiscovery.ts](</e:/Source_code/Claude-code-bast/src/assistant/sessionDiscovery.ts:1>)
- Phase 4C
- [src/assistant/AssistantSessionChooser.ts](</e:/Source_code/Claude-code-bast/src/assistant/AssistantSessionChooser.ts:1>)
- Phase 4D
- [src/commands/assistant/assistant.ts](</e:/Source_code/Claude-code-bast/src/commands/assistant/assistant.ts:7>)
### 验证
1. `claude assistant <sessionId>` 能进入 remote viewer
2. 历史懒加载工作正常
3. 无参数模式先给出明确提示
4. 后续阶段再分别验证 discovery / chooser / install
### 风险
- 这是四项里范围最大的
- 一旦把 KAIROS 正常模式整体拉入会从“viewer attach”膨胀成“完整 assistant mode 恢复”
### 工作量判断
- Phase 4A 中等
- 4A-4D 全做完很大
## 建议执行顺序
1. `claude daemon status` / `claude daemon stop`
2. `BG_SESSIONS` 先做 `ps/logs/kill`
3. `TEMPLATES` 先做 job 文件系统 MVP
4. `assistant [sessionId]` 先做显式 sessionId attach再补 discovery/chooser/install
## 简短结论
这四项里,最适合立刻实现的是 `daemon status/stop``BG_SESSIONS``TEMPLATES` 适合按 MVP 先补 handler 与文件系统闭环。`assistant [sessionId]` 不能整块硬上应该按“attach → discovery → chooser → install”拆开恢复。

167
docs/features/teammem.md Normal file
View File

@@ -0,0 +1,167 @@
# TEAMMEM — 团队共享记忆
> Feature Flag: `FEATURE_TEAMMEM=1`
> 实现状态:完整可用(需要 Anthropic OAuth + GitHub remote
> 引用数51
## 一、功能概述
TEAMMEM 实现基于 GitHub 仓库的团队共享记忆系统。`memory/team/` 目录中的文件双向同步到 Anthropic 服务器,团队所有认证成员可共享项目知识。
### 核心特性
- **增量同步**只上传内容哈希变化的文件delta upload
- **冲突解决**:基于 ETag 的乐观锁 + 412 冲突重试
- **密钥扫描**上传前检测并跳过包含密钥的文件PSR M22174
- **路径穿越防护**:所有写入路径验证在 `memory/team/` 边界内
- **分批上传**:自动拆分超过 200KB 的 PUT 请求避免网关拒绝
## 二、用户交互
### 同步行为
| 事件 | 行为 |
|------|------|
| 项目启动 | 自动 pull 团队记忆到 `memory/team/` |
| 本地文件编辑 | watcher 检测变更,自动 push |
| 服务端更新 | 下次 pull 时覆盖本地server-wins |
| 密钥检测 | 跳过该文件,记录警告,不阻止其他文件同步 |
### API 端点
```
GET /api/claude_code/team_memory?repo={owner/repo} → 完整数据 + entryChecksums
GET /api/claude_code/team_memory?repo={owner/repo}&view=hashes → 仅 checksums冲突解决用
PUT /api/claude_code/team_memory?repo={owner/repo} → 上传 entriesupsert 语义)
```
## 三、实现架构
### 3.1 同步状态
```ts
type SyncState = {
lastKnownChecksum: string | null // ETag 条件请求
serverChecksums: Map<string, string> // sha256:<hex> 逐文件哈希
serverMaxEntries: number | null // 从 413 学习的服务端容量
}
```
### 3.2 Pull 流程Server → Local
文件:`src/services/teamMemorySync/index.ts:770-867`
```
pullTeamMemory(state)
检查 OAuth + GitHub remote
fetchTeamMemory(state, repo, etag)
├── 304 Not Modified → 返回(无变化)
├── 404 → 返回(服务端无数据)
└── 200 → 解析 TeamMemoryData
刷新 serverChecksumsper-key hashes
writeRemoteEntriesToLocal(entries)
├── 路径穿越验证validateTeamMemKey
├── 文件大小检查(> 250KB 跳过)
├── 内容比较(相同则跳过写入)
└── 并行写入Promise.all
```
### 3.3 Push 流程Local → Server
文件:`src/services/teamMemorySync/index.ts:889-1146`
```
pushTeamMemory(state)
readLocalTeamMemory(maxEntries)
├── 递归扫描 memory/team/ 目录
├── 跳过超大文件(> 250KB
├── 密钥扫描scanForSecretsgitleaks 规则)
└── 按 serverMaxEntries 截断(如果已知)
计算 delta = 本地文件 - serverChecksums
(只包含哈希不同的文件)
batchDeltaByBytes(delta)
(拆分为 ≤200KB 的批次)
逐批 uploadTeamMemory(state, repo, batch, etag)
├── 200 成功 → 更新 serverChecksums
├── 412 冲突 → fetchTeamMemoryHashes() 刷新 checksums
│ → 重试 delta 计算(最多 2 次)
└── 413 超容量 → 学习 serverMaxEntries
```
### 3.4 密钥扫描
文件:`src/services/teamMemorySync/secretScanner.ts`
使用 gitleaks 规则模式扫描文件内容。检测到密钥时:
- 跳过该文件(不上传)
- 记录 `tengu_team_mem_secret_skipped` 事件(仅记录规则 ID不记录值
- 不阻止其他文件同步
### 3.5 文件监视
文件:`src/services/teamMemorySync/watcher.ts`
监视 `memory/team/` 目录变更,触发自动 push。抑制由 pull 写入引起的假变更。
### 3.6 路径安全
文件:`src/memdir/teamMemPaths.ts`
- `validateTeamMemKey(relPath)` — 验证相对路径不超出 `memory/team/` 边界
- `getTeamMemPath()` — 返回 team memory 根目录路径
## 四、关键设计决策
1. **Server-wins on pull, Local-wins on push**pull 时服务端内容覆盖本地push 时本地编辑覆盖服务端。本地用户正在编辑,不应被静默丢弃
2. **Delta upload**:只上传哈希变化的条目,节省带宽。首次 push 为全量,后续增量
3. **分批 PUT**:单次 PUT ≤200KB避免 API 网关(~256-512KB拒绝。每批独立 upsert部分失败不影响已提交批次
4. **密钥扫描在上传前**PSR M22174 要求密钥永不离开本机。扫描在 `readLocalTeamMemory` 中执行,密钥文件不进入上传集
5. **ETag 乐观锁**push 使用 `If-Match` header。412 时 probe `?view=hashes`(只获取 checksums不下载内容刷新后重试
6. **服务端容量动态学习**:不假设客户端容量上限,从 413 的 `extra_details.max_entries` 学习
## 五、使用方式
```bash
# 启用 feature
FEATURE_TEAMMEM=1 bun run dev
# 前提条件:
# 1. 已通过 Anthropic OAuth 登录
# 2. 项目有 GitHub remotegit remote -v 显示 origin
# 3. memory/team/ 目录自动创建
```
## 六、外部依赖
| 依赖 | 说明 |
|------|------|
| Anthropic OAuth | first-party 认证 |
| GitHub Remote | `getGithubRepo()` 获取 `owner/repo` 作为同步 scope |
| Team Memory API | `/api/claude_code/team_memory` 端点 |
## 七、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/services/teamMemorySync/index.ts` | 1257 | 核心同步逻辑pull/push/sync |
| `src/services/teamMemorySync/watcher.ts` | — | 文件监视 + 自动同步触发 |
| `src/services/teamMemorySync/secretScanner.ts` | — | gitleaks 密钥扫描 |
| `src/services/teamMemorySync/types.ts` | — | Zod schema + 类型定义 |
| `src/services/teamMemorySync/teamMemSecretGuard.ts` | — | 密钥防护辅助 |
| `src/memdir/teamMemPaths.ts` | — | 路径验证 + 目录管理 |

View File

@@ -0,0 +1,75 @@
# Tier 3 — 纯 Stub / N/A 低优先级 Feature 概览
> 本文档汇总所有 Tier 3 feature。这些功能要么是纯 Stub所有函数返回空值
> 要么是 Anthropic 内部基础设施N/A要么是引用量极低的辅助功能。
## 概览
| Feature | 引用 | 状态 | 类别 | 简要说明 |
|---------|------|------|------|---------|
| CHICAGO_MCP | 16 | N/A | 内部基础设施 | Anthropic 内部 MCP 基础设施,非外部可用 |
| MONITOR_TOOL | 13 | Stub | 工具 | 文件/进程监控工具,检测变更并通知 |
| BG_SESSIONS | 11 | Stub | 会话管理 | 后台会话管理,支持多会话并行 |
| SHOT_STATS | 10 | 无实现 | 统计 | 逐 prompt 统计信息收集 |
| EXTRACT_MEMORIES | 7 | 无实现 | 记忆 | 自动从对话中提取重要信息作为记忆 |
| TEMPLATES | 6 | Stub | 项目管理 | 项目/提示模板系统 |
| LODESTONE | 6 | N/A | 内部基础设施 | 内部基础设施模块 |
| STREAMLINED_OUTPUT | 1 | — | 输出 | 精简输出模式,减少终端输出量 |
| HOOK_PROMPTS | 1 | — | 钩子 | Hook 提示词,自定义钩子的提示注入 |
| CCR_AUTO_CONNECT | 3 | — | 远程控制 | CCR 自动连接,自动建立远程控制会话 |
| CCR_MIRROR | 4 | — | 远程控制 | CCR 镜像模式,会话状态同步 |
| CCR_REMOTE_SETUP | 1 | — | 远程控制 | CCR 远程设置,初始化远程控制配置 |
| NATIVE_CLIPBOARD_IMAGE | 2 | — | 系统集成 | 原生剪贴板图片,从剪贴板读取图片 |
| CONNECTOR_TEXT | 7 | — | 连接器 | 连接器文本,外部系统文本适配 |
| COMMIT_ATTRIBUTION | 12 | — | Git | Commit 归因,标记 commit 来源 |
| CACHED_MICROCOMPACT | 12 | — | 压缩 | 缓存微压缩,优化 compaction 性能 |
| PROMPT_CACHE_BREAK_DETECTION | 9 | — | 性能 | Prompt cache 中断检测,监控 cache miss |
| MEMORY_SHAPE_TELEMETRY | 3 | — | 遥测 | 记忆形态遥测,记忆使用模式追踪 |
| MCP_RICH_OUTPUT | 3 | — | MCP | MCP 富输出,增强 MCP 工具输出格式 |
| FILE_PERSISTENCE | 3 | — | 持久化 | 文件持久化,跨会话保持状态 |
| TREE_SITTER_BASH_SHADOW | 5 | Shadow | 安全 | Bash AST Shadow 模式(见 tree-sitter-bash.md |
| QUICK_SEARCH | 5 | — | 搜索 | 快速搜索,优化的文件/内容搜索 |
| MESSAGE_ACTIONS | 5 | — | UI | 消息操作,对消息执行后处理动作 |
| DOWNLOAD_USER_SETTINGS | 5 | — | 配置 | 下载用户设置,从服务端同步配置 |
| DIRECT_CONNECT | 5 | — | 网络 | 直连模式,绕过代理直接连接 API |
| VERIFICATION_AGENT | 4 | — | Agent | 验证 Agent专门用于验证代码变更 |
| TERMINAL_PANEL | 4 | — | UI | 终端面板,嵌入式终端输出显示 |
| SSH_REMOTE | 4 | — | 远程 | SSH 远程,通过 SSH 连接远程 Claude |
| REVIEW_ARTIFACT | 4 | — | 审查 | Review Artifact代码审查产出物 |
| REACTIVE_COMPACT | 4 | — | 压缩 | 响应式压缩,基于上下文变化触发 compaction |
| HISTORY_PICKER | 4 | — | UI | 历史选择器,浏览和选择历史对话 |
| UPLOAD_USER_SETTINGS | 2 | — | 配置 | 上传用户设置,同步配置到服务端 |
| POWERSHELL_AUTO_MODE | 2 | — | 平台 | PowerShell 自动模式Windows 权限自动化 |
| OVERFLOW_TEST_TOOL | 2 | — | 测试 | 溢出测试工具,测试上下文溢出处理 |
| NEW_INIT | 2 | — | 初始化 | 新版初始化流程 |
| HARD_FAIL | 2 | — | 错误处理 | 硬失败模式,不可恢复错误直接终止 |
| ENHANCED_TELEMETRY_BETA | 2 | — | 遥测 | 增强遥测 Beta详细的性能指标收集 |
| COWORKER_TYPE_TELEMETRY | 2 | — | 遥测 | 协作者类型遥测,追踪协作模式 |
| BREAK_CACHE_COMMAND | 2 | — | 缓存 | 中断缓存命令,强制刷新 prompt cache |
| AWAY_SUMMARY | 2 | — | 摘要 | 离开摘要,用户返回时总结期间工作 |
| AUTO_THEME | 2 | — | UI | 自动主题,根据终端设置切换主题 |
| ALLOW_TEST_VERSIONS | 2 | — | 版本 | 允许测试版本,跳过版本检查 |
| AGENT_TRIGGERS_REMOTE | 2 | — | Agent | Agent 远程触发,从远程触发 Agent 任务 |
| AGENT_MEMORY_SNAPSHOT | 2 | — | Agent | Agent 记忆快照,保存/恢复 Agent 状态 |
## 单引用 Feature40+ 个)
以下 feature 各只有 1 处引用,多为内部标记或实验性功能:
UNATTENDED_RETRY, ULTRATHINK, TORCH, SLOW_OPERATION_LOGGING, SKILL_IMPROVEMENT,
SELF_HOSTED_RUNNER, RUN_SKILL_GENERATOR, PERFETTO_TRACING, NATIVE_CLIENT_ATTESTATION,
KAIROS_DREAM见 kairos.md, IS_LIBC_MUSL, IS_LIBC_GLIBC, DUMP_SYSTEM_PROMPT,
COMPACTION_REMINDERS, CCR_REMOTE_SETUP, BYOC_ENVIRONMENT_RUNNER, BUILTIN_EXPLORE_PLAN_AGENTS,
BUILDING_CLAUDE_APPS, ANTI_DISTILLATION_CC, AGENT_TRIGGERS, ABLATION_BASELINE
## 优先级说明
这些 feature 被列为 Tier 3 的原因:
1. **内部基础设施**CHICAGO_MCP, LODESTONEAnthropic 内部使用,外部无法运行
2. **纯 Stub 且引用低**MONITOR_TOOL, BG_SESSIONS需要大量工作才能实现
3. **实验性功能**SHOT_STATS, EXTRACT_MEMORIES尚在概念阶段
4. **辅助功能**STREAMLINED_OUTPUT, HOOK_PROMPTS影响范围小
5. **CCR 系列**:依赖远程控制基础设施,需要 BRIDGE_MODE 先完善
如需深入了解某个 Tier 3 feature可以在代码库中搜索 `feature('FEATURE_NAME')` 查看具体使用场景。

View File

@@ -0,0 +1,198 @@
# TOKEN_BUDGET — Token 预算自动持续模式
> Feature Flag: `FEATURE_TOKEN_BUDGET=1`
> 实现状态:完整可用
## 一、功能概述
TOKEN_BUDGET 让用户在 prompt 中指定一个 output token 预算目标(如 `+500k``spend 2M tokens`Claude 会**自动持续工作**直到达到目标,无需用户反复按回车催促继续。
适用于大型重构、批量修改、大规模代码生成等需要多轮工具调用的长任务。
## 二、用户交互
### 语法
| 格式 | 示例 | 说明 |
|------|------|------|
| 简写(开头) | `+500k` | 输入开头直接写 |
| 简写(结尾) | `帮我重构这个模块 +2m` | 输入末尾追加 |
| 完整语法 | `spend 2M tokens``use 1B tokens` | 自然语言嵌入 |
单位支持:`k`(千)、`m`(百万)、`b`(十亿),大小写不敏感。
### UI 反馈
- **输入框高亮**:输入包含预算语法时,对应文字会被高亮标记(`PromptInput.tsx` 通过 `findTokenBudgetPositions` 计算)
- **Spinner 进度**:底部 spinner 显示实时进度,格式如:
- 未完成:`Target: 125,000 / 500,000 (25%) · ~2m 30s`
- 已完成:`Target: 510,000 used (500,000 min ✓)`
- 包含 ETA基于当前 token 产出速率计算)
## 三、实现架构
### 数据流
```
用户输入 "+500k"
┌─────────────────────────┐
│ parseTokenBudget() │ src/utils/tokenBudget.ts
│ 正则解析 → 500,000 │
└────────┬────────────────┘
┌─────────────────────────┐
│ REPL.tsx │ 提交时调用
│ snapshotOutputTokens │ snapshotOutputTokensForTurn(500000)
│ ForTurn(500000) │ 记录 turn 起始 token 数 + 预算
└────────┬────────────────┘
┌─────────────────────────┐
│ query.ts 主循环 │ 每轮结束后检查
│ checkTokenBudget() │ 当前 output tokens vs 预算
└────────┬────────────────┘
┌────┴─────┐
│ │
▼ ▼
continue stop
(未达 90%) (已达 90% 或收益递减)
│ │
▼ ▼
注入 nudge 正常结束
消息继续 发送完成事件
```
### 核心模块
#### 1. 解析层 — `src/utils/tokenBudget.ts`
三个正则表达式解析用户输入:
```
SHORTHAND_START_RE = /^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i // "+500k" 在开头
SHORTHAND_END_RE = /\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i // "+2m" 在结尾
VERBOSE_RE = /\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i // "spend 2M tokens"
```
- `parseTokenBudget(text)` — 提取预算数值,返回 `number | null`
- `findTokenBudgetPositions(text)` — 返回匹配位置数组,用于输入框高亮
- `getBudgetContinuationMessage(pct, turnTokens, budget)` — 生成继续消息
#### 2. 状态层 — `src/bootstrap/state.ts`
模块级单例变量追踪当前 turn 的预算状态:
```
outputTokensAtTurnStart — 本 turn 开始时的累计 output token 数
currentTurnTokenBudget — 本 turn 的预算目标null 表示无预算)
budgetContinuationCount — 本 turn 已自动续接的次数
```
关键函数:
- `getTotalOutputTokens()` — 从 `STATE.modelUsage` 汇总所有模型的 output tokens
- `getTurnOutputTokens()``getTotalOutputTokens() - outputTokensAtTurnStart`
- `snapshotOutputTokensForTurn(budget)` — 重置 turn 起点,设置新预算
- `getCurrentTurnTokenBudget()` — 返回当前预算
#### 3. 决策层 — `src/query/tokenBudget.ts`
`checkTokenBudget(tracker, agentId, budget, globalTurnTokens)` 做出 continue/stop 决策:
**继续条件**
- 不在子 agent 中(`agentId` 为空)
- 预算存在且 > 0
- 当前 token 未达预算的 **90%**
- 非收益递减(连续 3 轮 nudge 后,每轮新增 < 500 tokens
**停止条件**
- 达到预算 90%
- 收益递减(模型已经"做不动了"
- 子 agent 模式下直接跳过
**收益递减检测**`continuationCount >= 3` 且最近两次 nudge 的 delta 都 < 500 tokens。
#### 4. 主循环集成 — `src/query.ts`
```
query() 函数内:
1. 创建 budgetTracker = createBudgetTracker()
2. 进入 while 循环
3. 每轮结束后调用 checkTokenBudget()
4. decision.action === 'continue' 时:
- 注入 meta user messagenudge
- continue 回到循环顶部
5. decision.action === 'stop' 时:
- 记录完成事件(含 diminishingReturns 标记)
- 正常返回
```
#### 5. UI 层
| 文件 | 职责 |
|------|------|
| `components/PromptInput/PromptInput.tsx:534` | 输入框中高亮预算语法 |
| `components/Spinner.tsx:319-338` | spinner 显示进度百分比 + ETA |
| `screens/REPL.tsx:2897` | 提交时解析预算并快照 |
| `screens/REPL.tsx:2138` | 用户取消时清除预算 |
| `screens/REPL.tsx:2963` | turn 结束时捕获预算信息用于显示 |
#### 6. 系统提示 — `src/constants/prompts.ts:538-551`
注入 `token_budget` section
> "When the user specifies a token target (e.g., '+500k', 'spend 2M tokens', 'use 1B tokens'), your output token count will be shown each turn. Keep working until you approach the target — plan your work to fill it productively. The target is a hard minimum, not a suggestion. If you stop early, the system will automatically continue you."
注意:这段 prompt **无条件缓存**(不随预算开关变化),因为 "When the user specifies..." 的措辞在没有预算时是空操作。
#### 7. API 附件 — `src/utils/attachments.ts:3830-3845`
每轮 API 调用附带 `output_token_usage` attachment
```json
{
"type": "output_token_usage",
"turn": 125000, // 本 turn 产出
"session": 350000, // 会话总产出
"budget": 500000 // 预算目标
}
```
让模型能看到自己的进度。
## 四、关键设计决策
1. **90% 阈值而非 100%**:在 `COMPLETION_THRESHOLD = 0.9` 处停止,避免最后一轮 nudge 产生远超预算的 token
2. **收益递减保护**:连续 3 轮 nudge 后如果每轮产出 < 500 tokens判定模型已无实质进展提前终止
3. **子 agent 豁免**AgentTool 内部的子任务不做预算检查,避免子任务重复触发续接
4. **无条件缓存系统提示**:预算 prompt 始终注入(不随预算变化 toggle避免每次切换预算导致 ~20K token 的 cache miss
5. **用户取消清预算**:按 Escape 取消时调用 `snapshotOutputTokensForTurn(null)`,防止残留预算触发续接
## 五、使用方式
```bash
# 启用 feature
FEATURE_TOKEN_BUDGET=1 bun run dev
# 在 prompt 中使用
> +500k 重构所有测试文件
> spend 2M tokens 把这个项目从 JS 迁移到 TS
> 帮我写完整的 CRUD 模块 +1m
```
## 六、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/utils/tokenBudget.ts` | 73 | 正则解析 + 位置查找 + 续接消息生成 |
| `src/query/tokenBudget.ts` | 93 | 预算追踪器 + continue/stop 决策 |
| `src/bootstrap/state.ts:724-743` | 20 | turn 级 token 快照状态 |
| `src/constants/prompts.ts:538-551` | 14 | 系统提示注入 |
| `src/utils/attachments.ts:3829-3845` | 17 | API attachment 附加 |
| `src/query.ts:280,1311-1358` | 48 | 主循环集成 |
| `src/screens/REPL.tsx:2897,2963,2138` | 20 | REPL 提交/完成/取消处理 |
| `src/components/Spinner.tsx:319-338` | 20 | 进度条 UI |
| `src/components/PromptInput/PromptInput.tsx:534` | 1 | 输入高亮 |

View File

@@ -0,0 +1,161 @@
# TREE_SITTER_BASH — Bash AST 解析
> Feature Flag: `FEATURE_TREE_SITTER_BASH=1`
> 实现状态:完整可用(纯 TypeScript 实现,~7000+ 行)
> 引用数3
## 一、功能概述
TREE_SITTER_BASH 启用一个完整的 Bash AST 解析器,用于安全验证 Bash 命令。它用完整的树遍历安全分析器取代了旧的基于正则表达式的 shell-quote 解析器。关键属性是 **fail-closed**:任何无法识别的内容都被归类为 `too-complex` 并需要用户批准。
### 关联 Feature
| Feature | 说明 |
|---------|------|
| `TREE_SITTER_BASH` | 激活用于权限检查的 AST 解析器 |
| `TREE_SITTER_BASH_SHADOW` | Shadow/观测模式:运行解析器但丢弃结果,仅记录遥测 |
## 二、安全架构
### 2.1 Fail-Closed 设计
核心设计使用 **allowlist** 遍历模式:
- `walkArgument()` 只处理已知安全的节点类型(`word``number``raw_string``string``concatenation``arithmetic_expansion``simple_expansion`
- 任何未知节点类型 → `tooComplex()` → 需要用户批准
- 解析器加载但失败(超时/节点预算/panic→ 返回 `PARSE_ABORTED` 符号(区别于"模块未加载"
### 2.2 解析结果
```ts
parseForSecurity(cmd)
{ kind: 'simple', commands: SimpleCommand[] } // 可静态分析
{ kind: 'too-complex', reason, nodeType } // 需要用户批准
{ kind: 'parse-unavailable' } // 解析器未加载
```
### 2.3 安全检查层次
```
parseForSecurity(cmd)
parseCommandRaw(cmd) → AST root node
预检查控制字符、Unicode 空白、反斜杠+空白、
zsh ~[ ] 语法、zsh =cmd 展开、大括号+引号混淆
walkProgram(root) → collectCommands(root, commands, varScope)
├── 'command' → walkCommand()
├── 'pipeline'/'list' → 结构性,递归子节点
├── 'for_statement' → 跟踪循环变量为 VAR_PLACEHOLDER
├── 'if/while' → 作用域隔离的分支
├── 'subshell' → 作用域复制
├── 'variable_assignment' → walkVariableAssignment()
├── 'declaration_command' → 验证 declare/export flags
├── 'test_command' → walk test expressions
└── 其他 → tooComplex()
checkSemantics(commands)
├── EVAL_LIKE_BUILTINSeval, source, exec, trap...
├── ZSH_DANGEROUS_BUILTINSzmodload, emulate...
├── SUBSCRIPT_EVAL_FLAGStest -v, printf -v, read -a
├── Shell keywords as argv[0](误解析检测)
├── /proc/*/environ 访问
├── jq system() 和危险 flags
└── 包装器剥离time, nohup, timeout, nice, env, stdbuf
```
## 三、实现架构
### 3.1 核心模块
| 模块 | 文件 | 行数 | 职责 |
|------|------|------|------|
| 门控入口 | `src/utils/bash/parser.ts` | ~110 | `parseCommand()``parseCommandRaw()``ensureInitialized()` |
| Bash 解析器 | `src/utils/bash/bashParser.ts` | 4437 | 纯 TS 词法分析 + 递归下降解析器 |
| 安全分析器 | `src/utils/bash/ast.ts` | 2680 | 树遍历安全分析 + `parseForSecurity()` |
| AST 分析辅助 | `src/utils/bash/treeSitterAnalysis.ts` | 507 | 引号上下文、复合结构、危险模式提取 |
| 权限检查入口 | `src/tools/BashTool/bashPermissions.ts` | — | 集成 AST 结果到权限决策 |
### 3.2 Bash 解析器
文件:`src/utils/bash/bashParser.ts`4437 行)
- 纯 TypeScript 实现(无原生依赖)
- 生成与 tree-sitter-bash 兼容的 AST
- 关键类型:`TsNode`type、text、startIndex、endIndex、children
- 安全限制:`PARSE_TIMEOUT_MS = 50``MAX_NODES = 50_000` — 防止对抗性输入导致 OOM
### 3.3 安全分析器
文件:`src/utils/bash/ast.ts`2680 行)
核心函数:
| 函数 | 职责 |
|------|------|
| `parseForSecurity(cmd)` | 顶层入口,返回 `simple/too-complex/parse-unavailable` |
| `parseForSecurityFromAst(cmd, root)` | 接受预解析 AST |
| `checkSemantics(commands)` | 后解析语义检查 |
| `walkCommand()` | 提取 argv、envVars、redirects |
| `walkArgument()` | Allowlist 参数遍历 |
| `collectCommands()` | 递归收集所有命令 |
### 3.4 AST 分析辅助
文件:`src/utils/bash/treeSitterAnalysis.ts`507 行)
| 函数 | 职责 |
|------|------|
| `extractQuoteContext()` | 识别单引号、双引号、ANSI-C 字符串、heredoc |
| `extractCompoundStructure()` | 检测管道、子 shell、命令组 |
| `hasActualOperatorNodes()` | 区分真实 `;`/`&&`/`||` 与转义形式 |
| `extractDangerousPatterns()` | 检测命令替换、参数展开、heredocs |
| `analyzeCommand()` | 单次遍历提取 |
### 3.5 Shadow 模式
`TREE_SITTER_BASH_SHADOW` 运行解析器但**从不影响权限决策**
```ts
// Shadow 模式:记录遥测,然后强制使用旧版路径
astResult = { kind: 'parse-unavailable' }
astRoot = null
// 记录: available, astTooComplex, astSemanticFail, subsDiffer, ...
```
记录 `tengu_tree_sitter_shadow` 事件,包含与旧版 `splitCommand()` 的对比数据。用于在不影响行为的情况下收集遥测。
## 四、关键设计决策
1. **Allowlist 遍历**:只处理已知安全的节点类型,未知类型直接 `tooComplex()`
2. **PARSE_ABORTED 符号**:区分"解析器未加载"和"解析器加载但失败"。后者阻止回退旧版(旧版缺少 `EVAL_LIKE_BUILTINS` 检查)
3. **变量作用域跟踪**`VAR=value && cmd $VAR` 模式。静态值解析为真实字符串,`$()` 输出使用 `VAR_PLACEHOLDER`
4. **PS4/IFS Allowlist**PS4 赋值使用严格字符白名单 `[A-Za-z0-9 _+:.\/=\[\]-]`,只允许 `${VAR}` 引用
5. **包装器剥离**:从 argv 前面剥离 `time/nohup/timeout/nice/env/stdbuf`,未知标志 → fail-closed
6. **Shadow 安全性**Shadow 模式**总是**强制 `astResult = { kind: 'parse-unavailable' }`,绝不影响权限
## 五、使用方式
```bash
# 激活 AST 解析用于权限检查
FEATURE_TREE_SITTER_BASH=1 bun run dev
# Shadow 模式(仅遥测,不影响行为)
FEATURE_TREE_SITTER_BASH_SHADOW=1 bun run dev
```
## 六、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/utils/bash/parser.ts` | ~110 | 门控入口点 |
| `src/utils/bash/bashParser.ts` | 4437 | 纯 TS bash 解析器 |
| `src/utils/bash/ast.ts` | 2680 | 安全分析器(核心) |
| `src/utils/bash/treeSitterAnalysis.ts` | 507 | AST 分析辅助 |
| `src/tools/BashTool/bashPermissions.ts:1670-1810` | ~140 | 权限集成 + Shadow 遥测 |

114
docs/features/uds-inbox.md Normal file
View File

@@ -0,0 +1,114 @@
# UDS_INBOX / pipes
## 概述
`UDS_INBOX` 现在不是一个“空壳 flag”而是一套已经落地的本机 IPC 能力。但它同时承载了两层不同目标,必须拆开理解:
1. **UDS peer messaging**
- 面向任意 Claude Code 进程。
- 使用 `src/utils/udsMessaging.ts``src/utils/udsClient.ts`
- 对外入口是 `/peers``SendMessageTool``uds:<socket-path>` 地址。
2. **pipes control plane**
- 面向交互式 REPL 会话之间的主从协作。
- 使用 `src/utils/pipeTransport.ts``src/utils/pipeRegistry.ts``src/screens/REPL.tsx` 中的内联 bootstrap。
- 对外入口是 `/pipes``/attach``/detach``/send``/pipe-status``/history``/claim-main`
这两层都依赖本机 socket但职责不同。`/peers` 解决“找到其他会话并发消息”,`/pipes` 解决“把一个 REPL 变成另一个 REPL 的受控 worker”。
## 为什么要有单独的 `pipes`
单独的 `pipes` 层有三个实际理由:
1. **命名与角色模型不同**
- UDS peer 层按 `messagingSocketPath` 寻址。
- pipes 层按 `cli-xxxxxxxx` 会话名、`main/sub/master/slave` 角色和 `machineId` 注册表工作。
2. **交互语义不同**
- peer 层是通用消息投递。
- pipes 层需要 attach、detach、历史收集、选择性广播、状态栏和 REPL 快捷键。
3. **UI 集成不同**
- peer 层主要服务工具调用。
- pipes 层直接影响 REPL 提交路径和 PromptInput 页脚。
如果把两者硬合并,`SendMessageTool` 的通用寻址和 REPL 的主从控制会互相污染,命令语义也会变得混乱。
## 当前通信模型
### 1. UDS peer messaging
- 服务端:`src/utils/udsMessaging.ts`
- 客户端:`src/utils/udsClient.ts`
- 发现方式:读取 `~/.claude/sessions/*.json`
- 地址方式:`uds:<socket-path>`
- 传输方式:**本机 Unix socket / Windows named pipe**
这层是真正的“通用收件箱”。
### 2. pipes control plane
- 服务端/客户端:`src/utils/pipeTransport.ts`
- 注册表:`src/utils/pipeRegistry.ts`
- 生效入口:`src/screens/REPL.tsx`
- 发现方式:扫描 `~/.claude/pipes/` + `registry.json`
- 会话名:`cli-${sessionId.slice(0, 8)}`
- 传输方式:**本机 Unix socket / Windows named pipe**
这层是真正的“主从 REPL 协调平面”。
## 关于“局域网通信”的事实
当前实现**不是**真正的局域网传输。
代码里虽然保存了这些字段:
- `localIp`
- `hostname`
- `machineId`
- `mac`
但这些字段当前只用于:
1. 注册表展示
2. main/sub 身份判定
3. `claim-main` 的机器级归属切换
4. 状态输出与排障信息
它们**没有**被用于创建 TCP/WebSocket 连接。真正的传输仍然是 `getPipePath(name)` 返回的本机 socket 路径。
所以目前更准确的描述应该是:
- `pipes` 支持 **本机多实例协作**
- `registry` 带有 **机器身份元数据**
-**尚未实现跨机器局域网 transport**
如果未来要做真局域网版本,至少还需要:
1. TCP/WebSocket transport
2. 认证与会话授权
3. 发现与地址交换
4. 超时、重连和安全边界
## 当前 REPL 行为
当前线上行为由 `src/screens/REPL.tsx` 的内联实现负责:
1. 启动时创建当前 REPL 的 pipe server
2. 通过 `pipeRegistry` 判定 `main` / `sub`
3. 处理 `attach_request` / `detach` / `prompt`
4. 主实例心跳探测并维护 `slaves`
5. `/pipes` 打开状态栏并维护选择器
6. 提交普通消息时,仅向**已连接**的 selected pipes 广播
最近的收敛点:
- 过去遗留了一套未接线的 hook 方案
- 当前已明确以 `REPL.tsx` 内联 bootstrap 为唯一生效实现
- 选中但未连接的 pipe 不再导致本地处理被错误跳过
## 文档与代码对齐约定
后续关于 `UDS_INBOX` / `pipes` 的说明应遵守以下表述:
1. 默认称为“本机 IPC / 本机多实例协作”
2. 不把 `localIp` / `hostname` 元数据表述成已完成的 LAN transport
3. 明确区分 `/peers``/pipes` 的两层职责
4.`src/screens/REPL.tsx``src/utils/pipeTransport.ts``src/utils/pipeRegistry.ts` 为事实来源

107
docs/features/ultraplan.md Normal file
View File

@@ -0,0 +1,107 @@
# ULTRAPLAN — 增强规划
> Feature Flag: `FEATURE_ULTRAPLAN=1`
> 实现状态关键字检测完整命令处理完整CCR 远程会话完整
> 引用数10
## 一、功能概述
ULTRAPLAN 在用户输入中检测 "ultraplan" 关键字时,自动进入增强计划模式。相比普通 plan modeultraplan 提供更深入的规划能力支持本地和远程CCR执行。
### 触发方式
| 方式 | 行为 |
|------|------|
| 输入含 "ultraplan" 的文本 | 自动重定向到 `/ultraplan` 命令 |
| `/ultraplan` 斜杠命令 | 直接执行 |
| 彩虹高亮 | 输入框中 "ultraplan" 关键字彩虹动画 |
## 二、实现架构
### 2.1 模块状态
| 模块 | 文件 | 行数 | 状态 |
|------|------|------|------|
| 命令处理器 | `src/commands/ultraplan.tsx` | 472 | **完整** |
| CCR 会话 | `src/utils/ultraplan/ccrSession.ts` | 350 | **完整** |
| 关键字检测 | `src/utils/ultraplan/keyword.ts` | 128 | **完整** |
| 嵌入式提示 | `src/utils/ultraplan/prompt.txt` | 1 | **完整** |
| REPL 对话框 | `src/screens/REPL.tsx` | — | **布线** |
| 关键字高亮 | `src/components/PromptInput/PromptInput.tsx` | — | **布线** |
### 2.2 关键字检测
文件:`src/utils/ultraplan/keyword.ts`128 行)
`findUltraplanTriggerPositions(text)` 智能过滤:
- 排除引号内的 "ultraplan"
- 排除路径中的 "ultraplan"(如 `/path/to/ultraplan/`
- 排除斜杠命令以外的上下文
- `replaceUltraplanKeyword(text)` 清理关键字
### 2.3 CCR 远程会话
文件:`src/utils/ultraplan/ccrSession.ts`350 行)
`ExitPlanModeScanner` 类实现完整的事件状态机:
- `pollForApprovedExitPlanMode()` — 3 秒轮询间隔
- 超时处理和重试
- 支持远程teleport和本地执行
### 2.4 数据流
```
用户输入 "帮我 ultraplan 重构这个模块"
processUserInput 检测 "ultraplan"
重定向到 /ultraplan 命令
├── 本地执行 → EnterPlanMode
└── 远程执行 → teleportToRemote → CCR 会话
ExitPlanModeScanner 轮询
用户在远程审批 → 本地收到结果
```
## 三、需要补全的内容
| 模块 | 说明 |
|------|------|
| `src/screens/REPL.tsx` 中的 UltraplanChoiceDialog / UltraplanLaunchDialog | 用户选择本地/远程执行的对话框组件 |
| `src/commands/ultraplan/` | 空目录,可能是未合并的子命令结构 |
## 四、关键设计决策
1. **智能关键字过滤**:排除引号和路径中的 "ultraplan",避免误触发
2. **本地/远程双模式**:支持本地 plan mode 和 CCR 远程会话
3. **彩虹高亮反馈**:输入框中 "ultraplan" 关键字使用彩虹动画,暗示这是特殊功能
4. **processUserInput 集成**:在用户输入处理管道中拦截,无缝重定向
## 五、使用方式
```bash
# 启用 feature
FEATURE_ULTRAPLAN=1 bun run dev
# 在 REPL 中使用
# > ultraplan 重构认证模块
# > /ultraplan
```
## 六、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/commands/ultraplan.tsx` | 472 | 斜杠命令处理器 |
| `src/utils/ultraplan/ccrSession.ts` | 350 | CCR 远程会话管理 |
| `src/utils/ultraplan/keyword.ts` | 128 | 关键字检测和替换 |
| `src/utils/ultraplan/prompt.txt` | 1 | 嵌入式提示 |
| `src/utils/processUserInput/processUserInput.ts:468` | — | 关键字重定向 |
| `src/components/PromptInput/PromptInput.tsx` | — | 彩虹高亮 |

125
docs/features/voice-mode.md Normal file
View File

@@ -0,0 +1,125 @@
# VOICE_MODE — 语音输入
> Feature Flag: `FEATURE_VOICE_MODE=1`
> 实现状态:完整可用(需要 Anthropic OAuth
> 引用数46
## 一、功能概述
VOICE_MODE 实现"按键说话"Push-to-Talk语音输入。用户按住空格键录音音频通过 WebSocket 流式传输到 Anthropic STT 端点Nova 3实时转录显示在终端中。
### 核心特性
- **Push-to-Talk**:长按空格键录音,释放后自动发送
- **流式转录**:录音过程中实时显示中间转录结果
- **无缝集成**:转录文本直接作为用户消息提交到对话
## 二、用户交互
| 操作 | 行为 |
|------|------|
| 长按空格 | 开始录音,显示录音状态 |
| 释放空格 | 停止录音,等待最终转录 |
| 转录完成 | 自动插入到输入框并提交 |
| `/voice` 命令 | 切换语音模式开关 |
### UI 反馈
- **录音指示器**:录音时显示红色/脉冲动画
- **中间转录**:录音过程中显示 STT 实时识别文本
- **最终转录**:完成后替换中间结果
## 三、实现架构
### 3.1 门控逻辑
文件:`src/voice/voiceModeEnabled.ts`
三层检查:
```ts
isVoiceModeEnabled() = hasVoiceAuth() && isVoiceGrowthBookEnabled()
```
1. **Feature Flag**`feature('VOICE_MODE')` — 编译时/运行时开关
2. **GrowthBook Kill-Switch**`!getFeatureValue_CACHED_MAY_BE_STALE('tengu_amber_quartz_disabled', false)` — 紧急关闭开关(默认 false = 未禁用)
3. **Auth 检查**`hasVoiceAuth()` — 需要 Anthropic OAuth token非 API key
### 3.2 核心模块
| 模块 | 职责 |
|------|------|
| `src/voice/voiceModeEnabled.ts` | Feature flag + GrowthBook + Auth 三层门控 |
| `src/hooks/useVoice.ts` | React hook 管理录音状态和 WebSocket 连接 |
| `src/services/voiceStreamSTT.ts` | WebSocket 流式传输到 Anthropic STT |
### 3.3 数据流
```
用户按下空格键
useVoice hook 激活
macOS 原生音频 / SoX 开始录音
WebSocket 连接到 Anthropic STT 端点
├──→ 中间转录结果 → 实时显示
用户释放空格键
停止录音,等待最终转录
转录文本 → 插入输入框 → 自动提交
```
### 3.4 音频录制
支持两种音频后端:
- **macOS 原生音频**:优先使用,低延迟
- **SoXSound eXchange**:回退方案,跨平台
音频流通过 WebSocket 发送到 Anthropic 的 Nova 3 STT 模型。
## 四、关键设计决策
1. **OAuth 独占**:语音模式使用 `voice_stream` 端点claude.ai仅 Anthropic OAuth 用户可用。API key、Bedrock、Vertex 用户无法使用
2. **GrowthBook 负向门控**`tengu_amber_quartz_disabled` 默认 `false`,新安装自动可用(无需等 GrowthBook 初始化)
3. **Keychain 缓存**`getClaudeAIOAuthTokens()` 首次调用访问 macOS keychain~20-50ms后续缓存命中
4. **独立于主 feature flag**`isVoiceGrowthBookEnabled()` 在 feature flag 关闭时短路返回 `false`,不触发任何模块加载
## 五、使用方式
```bash
# 启用 feature
FEATURE_VOICE_MODE=1 bun run dev
# 在 REPL 中使用
# 1. 确保已通过 OAuth 登录claude.ai 订阅)
# 2. 按住空格键说话
# 3. 释放空格键等待转录
# 4. 或使用 /voice 命令切换开关
```
## 六、外部依赖
| 依赖 | 说明 |
|------|------|
| Anthropic OAuth | claude.ai 订阅登录,非 API key |
| GrowthBook | `tengu_amber_quartz_disabled` 紧急关闭 |
| macOS 原生音频 或 SoX | 音频录制 |
| Nova 3 STT | 语音转文本模型 |
## 七、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/voice/voiceModeEnabled.ts` | 55 | 三层门控逻辑 |
| `src/hooks/useVoice.ts` | — | React hook录音状态 + WebSocket |
| `src/services/voiceStreamSTT.ts` | — | STT WebSocket 流式传输 |

View File

@@ -0,0 +1,69 @@
# WEB_BROWSER_TOOL — 浏览器工具
> Feature Flag: `FEATURE_WEB_BROWSER_TOOL=1`
> 实现状态:核心实现缺失,面板为 Stub布线完整
> 引用数4
## 一、功能概述
WEB_BROWSER_TOOL 让模型可以启动浏览器实例、导航网页、与页面元素交互。使用 Bun 的内置 WebView API 提供无头/有头浏览器能力。
## 二、实现架构
### 2.1 模块状态
| 模块 | 文件 | 状态 |
|------|------|------|
| 浏览器面板 | `src/tools/WebBrowserTool/WebBrowserPanel.ts` | **Stub** — 返回 null |
| 浏览器工具 | `src/tools/WebBrowserTool/WebBrowserTool.ts` | **缺失** |
| REPL 集成 | `src/screens/REPL.tsx` | **布线** — 渲染 WebBrowserPanel |
| 工具注册 | `src/tools.ts` | **布线** — 动态加载 |
| WebView 检测 | `src/main.tsx` | **布线**`'WebView' in Bun` 检测 |
### 2.2 预期数据流
```
模型调用 WebBrowserTool
Bun WebView 创建浏览器实例
├── navigate(url) — 导航到 URL
├── click(selector) — 点击元素
├── screenshot() — 截取页面截图
└── extract(selector) — 提取页面内容
结果返回给模型
WebBrowserPanel 在 REPL 侧边显示浏览器状态
```
## 三、需要补全的内容
| 模块 | 工作量 | 说明 |
|------|--------|------|
| `WebBrowserTool.ts` | 大 | 工具 schema + Bun WebView API 执行 |
| `WebBrowserPanel.tsx` | 中 | REPL 侧边栏浏览器状态面板 |
## 四、关键设计决策
1. **Bun WebView API**:使用 Bun 内置的 WebView 而非外部浏览器驱动Puppeteer/Playwright
2. **REPL 侧边面板**:浏览器状态在 REPL 布局中独立渲染
3. **Bun 特性检测**`'WebView' in Bun` 检查运行时是否支持
## 五、使用方式
```bash
FEATURE_WEB_BROWSER_TOOL=1 bun run dev
```
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/tools/WebBrowserTool/WebBrowserPanel.ts` | 面板组件stub |
| `src/tools/WebBrowserTool/WebBrowserTool.ts` | 工具实现(缺失) |
| `src/screens/REPL.tsx:273,4582` | 面板渲染 |
| `src/tools.ts:115-116` | 工具注册 |

View File

@@ -0,0 +1,188 @@
# WEB_SEARCH_TOOL — 网页搜索工具
> 实现状态:适配器架构完成,支持 API / Bing / Brave 三种后端
> 引用数:核心工具,无 feature flag 门控(始终启用)
## 一、功能概述
WebSearchTool 让模型可以搜索互联网获取最新信息。原始实现仅支持 Anthropic API 服务端搜索(`web_search_20250305` server tool在第三方代理端点下不可用。现已重构为适配器架构支持 API 服务端搜索,以及 Bing / Brave 两个 HTML 解析后端,确保任何 API 端点都能使用搜索功能。
## 二、实现架构
### 2.1 适配器模式
```
WebSearchTool.call()
createAdapter() ← 适配器工厂
├── ApiSearchAdapter — Anthropic 官方 API 服务端搜索
│ └── 使用 web_search_20250305 server tool
│ 通过 queryModelWithStreaming 二次调用 API
├── BingSearchAdapter — Bing HTML 抓取 + 正则提取
│ └── 直接抓取 Bing 搜索页 HTML
│ 正则提取 b_algo 块中的标题/URL/摘要
└── BraveSearchAdapter — Brave LLM Context API
└── 调用 Brave HTTPS GET 接口
将 grounding payload 映射为标题/URL/摘要
```
### 2.2 模块结构
| 模块 | 文件 | 说明 |
|------|------|------|
| 工具入口 | `src/tools/WebSearchTool/WebSearchTool.ts` | `buildTool()` 定义schema、权限、执行、输出格式化 |
| 工具 prompt | `src/tools/WebSearchTool/prompt.ts` | 搜索工具的系统提示词 |
| UI 渲染 | `src/tools/WebSearchTool/UI.tsx` | 搜索结果的终端渲染组件 |
| 适配器接口 | `src/tools/WebSearchTool/adapters/types.ts` | `WebSearchAdapter` 接口、`SearchResult`/`SearchOptions`/`SearchProgress` 类型 |
| 适配器工厂 | `src/tools/WebSearchTool/adapters/index.ts` | `createAdapter()` 工厂函数,选择后端 |
| API 适配器 | `src/tools/WebSearchTool/adapters/apiAdapter.ts` | 封装原有 `queryModelWithStreaming` 逻辑,使用 server tool |
| Bing 适配器 | `src/tools/WebSearchTool/adapters/bingAdapter.ts` | Bing HTML 抓取 + 正则解析 |
| Brave 适配器 | `src/tools/WebSearchTool/adapters/braveAdapter.ts` | Brave LLM Context API 适配与结果映射 |
| 单元测试 | `src/tools/WebSearchTool/__tests__/bingAdapter.test.ts`, `src/tools/WebSearchTool/__tests__/braveAdapter*.test.ts`, `src/tools/WebSearchTool/__tests__/adapterFactory.test.ts` | Bing / Brave 解析与工厂逻辑测试 |
| 集成测试 | `src/tools/WebSearchTool/__tests__/bingAdapter.integration.ts`, `src/tools/WebSearchTool/__tests__/braveAdapter.integration.ts` | 真实网络请求验证 |
### 2.3 数据流
```
模型调用 WebSearchTool(query, allowed_domains, blocked_domains)
validateInput() — 校验 query 非空、allowed/block 不共存
createAdapter() → ApiSearchAdapter | BingSearchAdapter | BraveSearchAdapter
adapter.search(query, { allowedDomains, blockedDomains, signal, onProgress })
├── onProgress({ type: 'query_update', query })
├── axios.get(search-engine-url)
│ └── API 鉴权请求头
├── extractResults(payload) — 按后端提取结果
│ └── grounding → SearchResult[] 映射
├── 客户端域名过滤 (allowedDomains / blockedDomains)
├── onProgress({ type: 'search_results_received', resultCount })
格式化为 markdown 链接列表返回给模型
```
## 三、Bing 适配器技术细节
### 3.1 反爬绕过
使用 13 个 Edge 浏览器请求头(含 `Sec-Ch-Ua``Sec-Fetch-*` 等),避免 Bing 返回 JS 渲染的空页面:
```typescript
const BROWSER_HEADERS = {
'User-Agent': '...Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
'Sec-Ch-Ua': '"Microsoft Edge";v="131", "Chromium";v="131", ...',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
// ... 共 13 个标头
}
```
`setmkt=en-US` 参数强制美式英语市场,避免 IP 地理定位导致区域化结果。
### 3.2 URL 解码(`resolveBingUrl()`
Bing 返回的重定向 URL 格式:`bing.com/ck/a?...&u=a1aHR0cHM6Ly9...`
- `u` 参数前 2 字符为协议前缀:`a1` = https`a0` = http
- 剩余部分为 base64url 编码的真实 URL
- Bing 内部链接和相对路径被过滤返回 `undefined`
### 3.3 摘要提取(`extractSnippet()`
三级降级策略:
1. `<p class="b_lineclamp...">` — Bing 的搜索摘要段落
2. `<div class="b_caption">` 内的 `<p>` — 备选摘要位置
3. `<div class="b_caption">` 直接文本 — 最终 fallback
### 3.4 域名过滤
客户端侧实现,支持子域名匹配:
- `allowedDomains`:白名单,结果域名必须匹配列表中的某项(含子域名)
- `blockedDomains`:黑名单,匹配的结果被过滤
- 两者不可同时使用(`validateInput` 校验)
## 四、适配器选择逻辑
`createAdapter()` 按以下优先级选择后端,并按选中的后端 key 缓存适配器实例:
```typescript
export function createAdapter(): WebSearchAdapter {
// 1. WEB_SEARCH_ADAPTER=api|bing|brave 显式指定
// 2. Anthropic 官方 API Base URL → ApiSearchAdapter
// 3. 第三方代理 / 非官方端点 → BingSearchAdapter
}
```
显式指定 `WEB_SEARCH_ADAPTER=brave` 时,会改用 Brave LLM Context API 后端,并要求
`BRAVE_SEARCH_API_KEY``BRAVE_API_KEY`
## 五、接口定义
### WebSearchAdapter
```typescript
interface WebSearchAdapter {
search(query: string, options: SearchOptions): Promise<SearchResult[]>
}
interface SearchResult {
title: string
url: string
snippet?: string
}
interface SearchOptions {
allowedDomains?: string[]
blockedDomains?: string[]
signal?: AbortSignal
onProgress?: (progress: SearchProgress) => void
}
interface SearchProgress {
type: 'query_update' | 'search_results_received'
query?: string
resultCount?: number
}
```
### 工具 Input Schema
```typescript
{
query: string // 搜索关键词,最少 2 字符
allowed_domains?: string[] // 域名白名单
blocked_domains?: string[] // 域名黑名单
}
```
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/tools/WebSearchTool/WebSearchTool.ts` | 工具定义入口 |
| `src/tools/WebSearchTool/prompt.ts` | 搜索工具 prompt |
| `src/tools/WebSearchTool/UI.tsx` | 终端 UI 渲染 |
| `src/tools/WebSearchTool/adapters/types.ts` | 适配器接口 |
| `src/tools/WebSearchTool/adapters/index.ts` | 适配器工厂 |
| `src/tools/WebSearchTool/adapters/apiAdapter.ts` | API 服务端搜索适配器 |
| `src/tools/WebSearchTool/adapters/bingAdapter.ts` | Bing HTML 解析适配器 |
| `src/tools/WebSearchTool/__tests__/bingAdapter.test.ts` | 单元测试 (32 cases) |
| `src/tools/WebSearchTool/__tests__/bingAdapter.integration.ts` | 集成测试 |
| `src/tools.ts` | 工具注册 |

View File

@@ -0,0 +1,105 @@
# WORKFLOW_SCRIPTS — 工作流自动化
> Feature Flag: `FEATURE_WORKFLOW_SCRIPTS=1`
> 实现状态:全部 Stub7 个文件),布线完整
> 引用数10
## 一、功能概述
WORKFLOW_SCRIPTS 实现基于文件的多步自动化工作流。用户可以定义 YAML/JSON 格式的工作流描述文件,系统将其解析为可执行的多 agent 步骤序列。提供 `/workflows` 命令管理和触发工作流。
## 二、实现架构
### 2.1 模块状态
| 模块 | 文件 | 状态 |
|------|------|------|
| WorkflowTool | `src/tools/WorkflowTool/WorkflowTool.ts` | **Stub** — 空对象 |
| Workflow 权限 | `src/tools/WorkflowTool/WorkflowPermissionRequest.ts` | **Stub** — 返回 null |
| 常量 | `src/tools/WorkflowTool/constants.ts` | **Stub** — 空工具名 |
| 命令创建 | `src/tools/WorkflowTool/createWorkflowCommand.ts` | **Stub** — 空操作 |
| 捆绑工作流 | `src/tools/WorkflowTool/bundled/` | **缺失** — 目录不存在 |
| 本地工作流任务 | `src/tasks/LocalWorkflowTask/LocalWorkflowTask.ts` | **Stub** — 类型 + 空操作 |
| UI 任务组件 | `src/components/tasks/src/tasks/LocalWorkflowTask/` | **Stub** — 空导出 |
| 详情对话框 | `src/components/tasks/WorkflowDetailDialog.ts` | **Stub** — 返回 null |
| 任务注册 | `src/tasks.ts` | **布线** — 动态加载 |
| 工具注册 | `src/tools.ts` | **布线** — 包含 bundled 工作流初始化 |
| 命令注册 | `src/commands.ts` | **布线**`/workflows` 命令 |
### 2.2 预期数据流
```
用户定义工作流YAML/JSON 文件)
/workflows 命令发现工作流文件
createWorkflowCommand() 解析为 Command 对象 [需要实现]
WorkflowTool 执行工作流 [需要实现]
├── 步骤 1: Agent({ task: "..." })
├── 步骤 2: Agent({ task: "..." })
└── 步骤 N: Agent({ task: "..." })
LocalWorkflowTask 协调步骤执行 [需要实现]
WorkflowDetailDialog 显示进度 [需要实现]
```
### 2.3 预期工作流 DSL
```
# workflow.yaml预期格式需要设计
name: "代码审查工作流"
steps:
- name: "静态分析"
agent: { type: "general-purpose", prompt: "运行 lint 和类型检查" }
- name: "测试"
agent: { type: "general-purpose", prompt: "运行测试套件" }
- name: "综合报告"
agent: { type: "general-purpose", prompt: "综合分析结果写报告" }
```
## 三、需要补全的内容
| 优先级 | 模块 | 工作量 | 说明 |
|--------|------|--------|------|
| 1 | `WorkflowTool.ts` | 大 | Schema 定义 + 多步执行引擎 |
| 2 | `bundled/index.js` | 中 | 内置工作流定义initBundledWorkflows |
| 3 | `createWorkflowCommand.ts` | 中 | 从文件解析创建命令对象 |
| 4 | `LocalWorkflowTask.ts` | 大 | 步骤协调、kill/skip/retry |
| 5 | `WorkflowDetailDialog.ts` | 中 | 进度详情 UI |
| 6 | `WorkflowPermissionRequest.ts` | 小 | 权限对话框 |
| 7 | `constants.ts` | 小 | 工具名常量 |
## 四、关键设计决策
1. **基于文件的 DSL**工作流定义为文件YAML/JSON版本控制友好
2. **多 Agent 步骤**:每个步骤是独立的 agent 任务,支持并行/串行
3. **内置工作流**`bundled/` 目录提供开箱即用的常用工作流
4. **/workflows 命令**:统一的发现和触发入口
## 五、使用方式
```bash
# 启用 feature需要补全后才能真正使用
FEATURE_WORKFLOW_SCRIPTS=1 bun run dev
```
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/tools/WorkflowTool/WorkflowTool.ts` | 工具定义stub |
| `src/tools/WorkflowTool/WorkflowPermissionRequest.ts` | 权限对话框stub |
| `src/tools/WorkflowTool/constants.ts` | 常量stub |
| `src/tools/WorkflowTool/createWorkflowCommand.ts` | 命令创建stub |
| `src/tasks/LocalWorkflowTask/LocalWorkflowTask.ts` | 任务协调stub |
| `src/components/tasks/WorkflowDetailDialog.ts` | 详情对话框stub |
| `src/tools.ts:127-132` | 工具注册 |
| `src/commands.ts:86-89` | 命令注册 |

View File

@@ -11,13 +11,13 @@ keywords: ["Ant 特权", "USER_TYPE", "身份门控", "内部功能", "Anthropic
`USER_TYPE` 是一个构建时常量,通过 Bun 打包器的 `--define` 注入。在 Anthropic 的内部构建中它被设为 `'ant'`,在公开发布的版本中是 `'external'`
```typescript
// 反编译版本src/entrypoints/cli.tsx16 行)
(globalThis as any).BUILD_TARGET = "external";
// 反编译版本src/types/global.d.ts 第 63 行)
// Build-time constants BUILD_TARGET/BUILD_ENV/INTERFACE_TYPE — removed (zero runtime usage)
```
由于这是编译时常量Bun 会进行**常量折叠**——所有 `process.env.USER_TYPE === 'ant'` 在外部构建中直接变为 `false`,后续代码被 DCE 移除。但在反编译版本中,这些代码保留完整。
`BUILD_TARGET` 等构建时常量在反编译版本中已被移除。`USER_TYPE` 通过 Bun 的 `--define` 或环境变量注入Bun 会进行**常量折叠**——所有 `process.env.USER_TYPE === 'ant'` 在外部构建中直接变为 `false`,后续代码被 DCE 移除。但在反编译版本中,这些代码保留完整。
`USER_TYPE === 'ant'` 出现在代码库的 **60+ 个位置**控制着工具、命令、API、UI 等方方面面。
`USER_TYPE === 'ant'` 在代码库中出现 **377+ 次**(含 `=== 'ant'` 291 次、`(process.env.USER_TYPE) === 'ant'` 86 次),另有 `!== 'ant'` 53 次、其他引用约 35 次,总计 **465 处引用**控制着工具、命令、API、UI 等方方面面。
## Ant-Only 工具
@@ -31,7 +31,9 @@ keywords: ["Ant 特权", "USER_TYPE", "身份门控", "内部功能", "Anthropic
| **TungstenTool** | `src/tools/TungstenTool/` | 基于 tmux 的终端面板工具(反编译版中已 stub |
```typescript
// src/tools.ts 第 16-24 行
// src/tools.ts 第 14-24 行——条件导入 + Dead Code Elimination 标记
// Dead code elimination: conditional import for ant-only tools
/* eslint-disable custom-rules/no-process-env-top-level, @typescript-eslint/no-require-imports */
const REPLTool =
process.env.USER_TYPE === 'ant'
? require('./tools/REPLTool/REPLTool.js').REPLTool
@@ -45,7 +47,7 @@ const SuggestBackgroundPRTool =
## Ant-Only 命令
`src/commands.ts` 注册了 25+ 个仅在内部构建中可用的斜杠命令:
`src/commands.ts` 注册了 **28** 个仅在内部构建中可用的斜杠命令`INTERNAL_ONLY_COMMANDS`lines 225-254在 `USER_TYPE === 'ant' && !IS_DEMO` 时才加载line 343-345
<AccordionGroup>
<Accordion title="调试类">
@@ -55,6 +57,7 @@ const SuggestBackgroundPRTool =
- `env` — 显示环境变量
- `mockLimits` — 模拟速率限制
- `resetLimits` — 重置速率限制
- `resetLimitsNonInteractive` — 重置速率限制(非交互式)
</Accordion>
<Accordion title="实验类">
- `bughunter` — Bug 猎人模式
@@ -69,6 +72,9 @@ const SuggestBackgroundPRTool =
- `autofixPr` — 自动修复 PR 中的问题
- `share` — 分享会话
- `summary` — 生成摘要
- `subscribePr` — 订阅 PR需要 `KAIROS_GITHUB_WEBHOOKS` feature flag
- `forceSnip` — 强制截断历史(需要 `HISTORY_SNIP` feature flag
- `ultraplan` — 超级规划(需要 `ULTRAPLAN` feature flag
</Accordion>
<Accordion title="基础设施类">
- `backfillSessions` — 回填会话数据
@@ -88,30 +94,72 @@ const SuggestBackgroundPRTool =
## Beta API Headers
Claude Code 向 API 发送的 beta headers 也分为公开和内部两类:
Claude Code 向 API 发送的 beta headers 分布在 `src/constants/betas.ts`(主注册表)和其他文件中,按可见性分为以下几类:
| Header | 功能 | 可见性 |
|--------|------|--------|
| `claude-code-20250219` | Claude Code 标识 | 公开 |
| `interleaved-thinking-2025-05-14` | 交错思考模式 | 公开 |
| `context-1m-2025-08-07` | 1M 上下文窗口 | 公开 |
| `context-management-2025-06-27` | 上下文管理 | 公开 |
| `web-search-2025-03-05` | 网页搜索 | 公开 |
| `effort-2025-11-24` | 推理强度控制 | 公开 |
| `fast-mode-2026-02-01` | 快速模式 | 公开 |
| `token-efficient-tools-2026-03-28` | Token 高效工具 | 公开 |
| `advisor-tool-2026-03-01` | 顾问工具 | 公开 |
| **`cli-internal-2026-02-09`** | 内部 CLI 功能 | **Ant-Only** |
| **`afk-mode-2026-01-31`** | AFK 模式(离开键盘自动审批) | **Feature Flag** |
| **`summarize-connector-text-2026-03-13`** | 连接器文本摘要 | **Feature Flag** |
### 公开 Headers所有构建均发送
| Header | 功能 | 额外条件 |
|--------|------|----------|
| `claude-code-20250219` | Claude Code 标识 | 非 Haiku 时始终发送Haiku 在 agentic 模式下也发送 |
| `effort-2025-11-24` | 推理强度控制 | 动态注入 |
| `task-budgets-2026-03-13` | 任务预算 | 始终通过 `addAgenticBetas()` 注入 |
| `fast-mode-2026-02-01` | 快速模式 | 通过 sticky-on latch 动态注入 |
| `advisor-tool-2026-03-01` | 顾问工具 | 启用 advisor 时动态注入 |
| `advanced-tool-use-2025-11-20` | 工具搜索1P | Claude API / Foundry |
| `tool-search-tool-2025-10-19` | 工具搜索3P | Vertex / Bedrock |
### 模型能力相关(有条件发送)
| Header | 功能 | 条件 |
|--------|------|------|
| `interleaved-thinking-2025-05-14` | 交错思考模式 | 模型支持 ISP 且未禁用 |
| `context-1m-2025-08-07` | 1M 上下文窗口 | 模型支持 1M context |
| `context-management-2025-06-27` | 上下文管理 | Claude 4+ 或 ant 手动启用 |
| `structured-outputs-2025-12-15` | 结构化输出 | Claude 4.5/4.6 + GrowthBook `tengu_tool_pear` |
| `web-search-2025-03-05` | 网页搜索 | Vertex (Claude 4+) / Foundry |
| `redact-thinking-2026-02-12` | 思维摘要/脱敏 | ISP 模型 + 非交互 + 未强制显示思维 |
| `prompt-caching-scope-2026-01-05` | 提示缓存作用域 | firstParty/foundry + 全局缓存 |
### Ant-Only Headers
| Header | 功能 | 条件 |
|--------|------|------|
| **`cli-internal-2026-02-09`** | 内部 CLI 功能 | `USER_TYPE === 'ant'` + CLI 入口 |
| **`token-efficient-tools-2026-03-28`** | Token 高效工具 | `USER_TYPE === 'ant'` + GrowthBook `tengu_amber_json_tools` |
### Feature Flag Gated
| Header | 功能 | 条件 |
|--------|------|------|
| **`afk-mode-2026-01-31`** | AFK 模式(离开键盘自动审批) | `feature('TRANSCRIPT_CLASSIFIER')` |
### 其他特殊 Headers
| Header | 功能 | 来源 |
|--------|------|------|
| `oauth-2025-04-20` | OAuth 订阅者标识 | `src/constants/oauth.ts`Pro/Max/Team/Enterprise |
| `environments-2025-11-01` | Bridge 环境 API | `src/bridge/bridgeApi.ts`,仅 Bridge 模式 |
```typescript
// src/constants/betas.ts 第 29-30 行
// src/constants/betas.ts — 常量定义
export const TOKEN_EFFICIENT_TOOLS_BETA_HEADER =
'token-efficient-tools-2026-03-28'
export const CLI_INTERNAL_BETA_HEADER =
process.env.USER_TYPE === 'ant' ? 'cli-internal-2026-02-09' : ''
```
`cli-internal` header 意味着 Anthropic 的 API 服务端也维护着一套 ant-only 的服务端行为——这不仅仅是客户端的门控。
```typescript
// src/utils/betas.ts 第 315-321 行——TOKEN_EFFICIENT_TOOLS 的实际门控逻辑
if (
process.env.USER_TYPE === 'ant' &&
includeFirstPartyOnlyBetas &&
tokenEfficientToolsEnabled // GrowthBook 'tengu_amber_json_tools' flag
) {
betaHeaders.push(TOKEN_EFFICIENT_TOOLS_BETA_HEADER)
}
```
`cli-internal` header 意味着 Anthropic 的 API 服务端也维护着一套 ant-only 的服务端行为——这不仅仅是客户端的门控。`token-efficient-tools` 进一步需要 GrowthBook flag 开启,说明 Ant 员工内部也有分层灰度。
## 内部代号体系
@@ -138,6 +186,8 @@ Anthropic 有浓厚的"动物命名"文化:
- `DISABLE_AUTO_COMPACT` — 禁用自动压缩
- `CLAUDE_CODE_DISABLE_AUTO_MEMORY` — 禁用自动记忆
- `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` — 禁用后台任务
- `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` — 禁用实验性 beta headers
- `USE_API_CONTEXT_MANAGEMENT` — 上下文管理工具清除(需 ant
</Accordion>
<Accordion title="功能启用开关">
- `CLAUDE_CODE_VERIFY_PLAN` — 启用 VerifyPlanExecutionTool
@@ -151,6 +201,7 @@ Anthropic 有浓厚的"动物命名"文化:
- `CLAUDE_CODE_COORDINATOR_MODE` — 启用 Coordinator 模式
- `CLAUDE_INTERNAL_FC_OVERRIDES` — GrowthBook flag 覆盖ant-only
- `IS_DEMO` — 演示模式(隐藏内部命令和敏感信息)
- `CLAUDE_CODE_ENTRYPOINT` — 入口类型标识(`cli` | 其他)
</Accordion>
</AccordionGroup>

View File

@@ -0,0 +1,169 @@
---
title: "GrowthBook 适配器 - 自定义 Feature Flag 服务器接入"
description: "通过环境变量连接自定义 GrowthBook 服务器,实现远程 feature flag 控制。无配置时自动回退到代码默认值。"
keywords: ["growthbook", "feature flags", "远程配置", "适配器", "环境变量"]
---
## 概述
Claude Code 的 GrowthBook 系统支持通过环境变量连接自定义 GrowthBook 服务器,实现远程 feature flag 控制。
- **有配置时**:连接你的 GrowthBook 实例,拉取并缓存 feature 值
- **无配置时**:所有 feature 读取直接返回代码中的默认值,零网络请求
## 环境变量
| 变量 | 必填 | 说明 |
|---|---|---|
| `CLAUDE_GB_ADAPTER_URL` | 是 | GrowthBook API 地址,如 `https://gb.example.com/` |
| `CLAUDE_GB_ADAPTER_KEY` | 是 | GrowthBook SDK Client Key如 `sdk-xxxxx` |
两个变量都设置时启用适配器模式,否则完全跳过 GrowthBook。
## 使用方式
### 基本用法
```bash
CLAUDE_GB_ADAPTER_URL=https://gb.example.com/ \
CLAUDE_GB_ADAPTER_KEY=sdk-abc123 \
bun run dev
```
### 不使用 GrowthBook默认行为
```bash
bun run dev
# 所有 getFeatureValue_CACHED_MAY_BE_STALE("xxx", defaultValue) 直接返回 defaultValue
```
## GrowthBook 服务端配置
### 步骤
1. **部署 GrowthBook 服务端**Docker 自托管或 Cloud 版)
2. **创建 Environment**(如 `production`
3. **创建 SDK Connection**,获得 SDK Key即 `CLAUDE_GB_ADAPTER_KEY`
4. **按需添加 Feature**key 和类型见下方列表
### 核心原则
- **不配置任何 feature 也能正常运行**——代码中每个调用都提供了默认值
- 只创建你想远程控制的 feature其余走代码默认
- GrowthBook 上配了某个 feature 后,其值会覆盖代码中的默认值
## Feature Key 列表
### 高频使用
| Feature Key | 类型 | 代码默认值 | 用途 |
|---|---|---|---|
| `tengu_hive_evidence` | boolean | `false` | 任务证据系统 |
| `tengu_quartz_lantern` | boolean | `false` | 文件写入/编辑保护 |
| `tengu_auto_background_agents` | boolean | `false` | 自动后台 Agent |
| `tengu_agent_list_attach` | boolean | `false` | Agent 列表附件 |
| `tengu_amber_stoat` | boolean | `true` | 内置 Agents |
| `tengu_slim_subagent_claudemd` | boolean | `true` | 子 Agent CLAUDE.md |
| `tengu_attribution_header` | boolean | `true` | API 归因 Header |
| `tengu_cobalt_harbor` | boolean | `false` | Bridge 模式 |
| `tengu_ccr_bridge` | boolean | `false` | CCR Bridge |
| `tengu_cicada_nap_ms` | number | `0` | 后台刷新节流(毫秒) |
| `tengu_miraculo_the_bard` | boolean | `false` | 启动欢迎信息 |
### Agent / 工具控制
| Feature Key | 类型 | 代码默认值 | 用途 |
|---|---|---|---|
| `tengu_surreal_dali` | boolean | `false` | 远程触发工具 |
| `tengu_glacier_2xr` | boolean | `false` | 工具搜索增强 |
| `tengu_plum_vx3` | boolean | `false` | Web Search 使用 Haiku |
| `tengu_destructive_command_warning` | boolean | `false` | 危险命令警告 |
| `tengu_birch_trellis` | boolean | `true` | Bash 权限控制 |
| `tengu_harbor_permissions` | boolean | `false` | Harbor 权限模式 |
### Bridge / 远程连接
| Feature Key | 类型 | 代码默认值 | 用途 |
|---|---|---|---|
| `tengu_bridge_repl_v2` | boolean | `false` | Bridge REPL v2 |
| `tengu_copper_bridge` | boolean | `false` | Copper Bridge |
| `tengu_ccr_mirror` | boolean | `false` | CCR Mirror |
### 内存 / 上下文
| Feature Key | 类型 | 代码默认值 | 用途 |
|---|---|---|---|
| `tengu_coral_fern` | boolean | `false` | 内存目录功能 |
| `tengu_passport_quail` | boolean | `false` | 内存路径配置 |
| `tengu_slate_thimble` | boolean | `false` | Slate Thimble |
| `tengu_herring_clock` | boolean | `false` | 跳过索引 |
| `tengu_session_memory` | boolean | `false` | 会话内存 |
| `tengu_pebble_leaf_prune` | boolean | `false` | 内存修剪 |
### UI / 体验
| Feature Key | 类型 | 代码默认值 | 用途 |
|---|---|---|---|
| `tengu_terminal_sidebar` | boolean | `false` | 终端侧边栏 |
| `tengu_terminal_panel` | boolean | `false` | 终端面板 |
| `tengu_willow_mode` | boolean | `false` | Willow 模式 |
| `tengu_collage_kaleidoscope` | boolean | `false` | UI 效果 |
| `tengu_chrome_auto_enable` | boolean | `false` | Chrome 自动启用 |
| `tengu_immediate_model_command` | boolean | `false` | 即时模型切换 |
| `tengu_remote_backend` | boolean | `false` | 远程后端 |
### 配置对象(动态配置)
| Feature Key | 类型 | 代码默认值 | 用途 |
|---|---|---|---|
| `tengu_file_read_limits` | object | `null` | 文件读取限制配置 |
| `tengu_cobalt_raccoon` | object | `null` | Cobalt 配置 |
| `tengu_cobalt_lantern` | object | `null` | Lantern 配置 |
| `tengu_desktop_upsell` | object | `null` | 桌面版引导 |
| `tengu_marble_sandcastle` | object | `null` | Marble 配置 |
| `tengu_marble_fox` | object | `null` | Marble Fox 配置 |
| `tengu_ultraplan_model` | string | `null` | Ultraplan 模型名 |
### Gate布尔门控
| Gate Key | 代码默认值 | 用途 |
|---|---|---|
| `tengu_chair_sermon` | `false` | 功能门控 |
| `tengu_scratch` | `false` | Scratch 功能 |
| `tengu_thinkback` | `false` | Thinkback 功能 |
| `tengu_tool_pear` | `false` | Tool Pear 功能 |
## 读取优先级链
每个 feature 的值按以下顺序解析,第一个命中即返回:
```
1. CLAUDE_INTERNAL_FC_OVERRIDES 环境变量JSON 对象覆盖)
↓ 未命中
2. growthBookOverrides 配置(~/.claude.json仅 ant 构建)
↓ 未命中
3. 内存缓存remoteEvalFeatureValues本次进程从服务器拉取
↓ 未命中
4. 磁盘缓存(~/.claude.json 的 cachedGrowthBookFeatures
↓ 未命中
5. 代码中的 defaultValue 参数
```
## 缓存与刷新机制
| 机制 | 说明 |
|---|---|
| **磁盘缓存** | `~/.claude.json` 的 `cachedGrowthBookFeatures` 字段,跨进程持久化 |
| **周期刷新** | 每 6 小时自动从服务器拉取最新值(`setInterval` + `unref` |
| **初始化超时** | 首次连接超时 5 秒,超时后使用磁盘缓存或默认值 |
| **Auth 变更** | 登录/登出时自动销毁并重建客户端 |
## 实现细节
修改了 2 个文件共 3 处:
1. **`src/constants/keys.ts`** — `getGrowthBookClientKey()` 优先读取 `CLAUDE_GB_ADAPTER_KEY`
2. **`src/services/analytics/growthbook.ts`** — `isGrowthBookEnabled()` 适配器模式下直接启用
3. **`src/services/analytics/growthbook.ts`** — base URL 优先使用 `CLAUDE_GB_ADAPTER_URL`
所有 130+ 个调用方文件无需修改。

View File

@@ -0,0 +1,106 @@
---
title: "自定义 Sentry 错误上报配置"
description: "通过环境变量连接自托管或 Cloud Sentry实现 CLI 运行时的错误捕获与上报。不配置则完全静默。"
keywords: ["sentry", "错误上报", "监控", "DSN", "自托管"]
---
## 概述
Claude Code 支持通过 Sentry 捕获运行时异常并上报到你自己指定的 Sentry 实例。
- **配置了 `SENTRY_DSN`**:自动初始化 Sentry SDK捕获未处理异常和关键错误
- **未配置**:所有 Sentry 调用均为 no-op零开销
## 环境变量
| 变量 | 必填 | 说明 |
|---|---|---|
| `SENTRY_DSN` | 是 | Sentry 项目 DSN如 `https://xxx@o123456.ingest.sentry.io/789` |
只需要这一个变量,设置后即启用。
## 使用方式
### 自托管 Sentry
```bash
SENTRY_DSN=https://public_key@your-sentry.example.com/123 \
bun run dev
```
### Sentry Cloud (SaaS)
```bash
SENTRY_DSN=https://public_key@o123456.ingest.sentry.io/789 \
bun run dev
```
### 不使用 Sentry默认行为
```bash
bun run dev
# SENTRY_DSN 未设置,所有 sentry 函数为 no-op
```
## Sentry 服务端配置
### 步骤
1. **部署 Sentry 实例**Docker 自托管 或 使用 [sentry.io](https://sentry.io) Cloud
2. **创建 Project**,选择 **Node.js** 平台
3. 获取项目的 **DSN**Settings → Projects → Client Keys → DSN
4. 将 DSN 设置为 `SENTRY_DSN` 环境变量
## 功能详情
### 错误捕获
- **自动捕获**`SentryErrorBoundary` 包裹关键 React 组件,捕获渲染错误
- **手动上报**`errorLogSink` 在写入错误日志时同步上报到 Sentry
- **优雅关闭**:进程退出时 `closeSentry()` 确保事件发送完毕2s 超时)
### 安全过滤
`beforeSend` 钩子会自动剥离以下敏感 header
- `authorization`
- `x-api-key`
- `cookie`
- `set-cookie`
### 忽略的错误类型
以下错误模式会被忽略,不会上报:
| 错误 | 原因 |
|---|---|
| `ECONNREFUSED` / `ECONNRESET` / `ENOTFOUND` / `ETIMEDOUT` | 网络不可达,不可操作 |
| `AbortError` / `The user aborted a request` | 用户主动取消 |
| `CancelError` | 交互式取消信号 |
### 其他配置
- **采样率**`sampleRate: 1.0`(捕获全部错误事件)
- **面包屑上限**`maxBreadcrumbs: 20`(控制 payload 体积)
- **性能事务**:已关闭(`beforeSendTransaction` 返回 `null`),仅上报错误
## API
| 函数 | 说明 |
|---|---|
| `initSentry()` | 初始化 SDK在 `src/entrypoints/init.ts` 中自动调用 |
| `captureException(error, context?)` | 手动上报异常,可附加额外上下文 |
| `setTag(key, value)` | 设置标签,用于 Sentry 面板分组过滤 |
| `setUser({ id, email, username })` | 设置用户上下文,用于错误归因 |
| `closeSentry(timeoutMs?)` | 刷出队列并关闭客户端,进程退出时调用 |
| `isSentryInitialized()` | 检查是否已初始化 |
## 实现文件
| 文件 | 说明 |
|---|---|
| `src/utils/sentry.ts` | 核心 SDK 初始化与封装 |
| `src/components/SentryErrorBoundary.ts` | React Error Boundary 组件 |
| `src/utils/errorLogSink.ts` | 错误日志 sink集成 `captureException` |
| `src/utils/gracefulShutdown.ts` | 优雅退出,调用 `closeSentry()` |
| `src/entrypoints/init.ts` | 启动时调用 `initSentry()` |

264
docs/lsp-integration.md Normal file
View File

@@ -0,0 +1,264 @@
# LSP Integration
Claude Code 内置了 Language Server Protocol (LSP) 集成,提供代码智能功能(跳转定义、查找引用、悬停信息、文档符号等)和被动的诊断反馈。
## 快速开始
### 1. 安装 LSP 插件
在 Claude Code REPL 中使用 `/plugin` 命令搜索并安装 LSP 插件:
```
/plugin
```
搜索 `lsp`,找到对应语言的插件(如 `typescript-lsp`),选择安装。
安装后运行 `/reload-plugins` 使插件生效。
LSP 插件安装后,后台的 LSP Server Manager 会自动加载并启动对应的语言服务器,无需手动配置。
### 2. 启用 LSP Tool
LSP Tool 需要通过环境变量显式启用Claude 才能主动发起代码智能查询:
```bash
ENABLE_LSP_TOOL=1 bun run dev
```
不启用时LSP 服务器仍然在后台运行并推送被动的诊断反馈(类型错误等)。
## 自动推荐
除了手动 `/plugin` 搜索安装外Claude Code 会在编辑文件时自动检测:
1. 监听 `fileHistory.trackedFiles`,发现有新文件被编辑
2. 扫描已安装的 marketplace找到声明支持该文件扩展名的 LSP 插件
3. 检查系统上是否已安装对应的 LSP 二进制(如 `typescript-language-server`
4. 满足条件时弹出推荐对话框,可选择安装
```
┌───── LSP Plugin Recommendation ─────────────┐
│ │
│ LSP provides code intelligence like │
│ go-to-definition and error checking │
│ │
│ Plugin: typescript-lsp │
│ Triggered by: .ts files │
│ │
│ Would you like to install this LSP plugin? │
│ │
│ > Yes, install typescript-lsp │
│ No, not now │
│ Never for typescript-lsp │
│ Disable all LSP recommendations │
└───────────────────────────────────────────────┘
```
- 30 秒不操作自动关闭(算作 "No"
- 选 "Never" 不再推荐该插件
- 选 "Disable" 关闭所有 LSP 推荐
- 连续忽略 5 次后自动禁用推荐
## 架构概览
```
┌─────────────────────────────────────────────────────┐
│ LSP Tool │
│ src/tools/LSPTool/LSPTool.ts │
│ (Claude 可调用的工具9 种操作) │
└──────────────────────┬──────────────────────────────┘
┌──────────────────────▼──────────────────────────────┐
│ LSP Server Manager (Singleton) │
│ src/services/lsp/manager.ts │
│ - initializeLspServerManager() │
│ - reinitializeLspServerManager() │
│ - shutdownLspServerManager() │
└──────────────────────┬──────────────────────────────┘
┌──────────────────────▼──────────────────────────────┐
│ LSP Server Manager (实例) │
│ src/services/lsp/LSPServerManager.ts │
│ - 管理多个 LSPServerInstance │
│ - 按文件扩展名路由请求 │
│ - 文件同步 (didOpen/didChange/didSave/didClose) │
└──────────────────────┬──────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ LSPServer │ │ LSPServer │ │ LSPServer │
│ Instance │ │ Instance │ │ Instance │
│ (typescript) │ │ (python) │ │ (rust...) │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ │ │
┌──────▼───────┐ ┌──────▼───────┐ ┌──────▼───────┐
│ LSPClient │ │ LSPClient │ │ LSPClient │
│ (JSON-RPC) │ │ (JSON-RPC) │ │ (JSON-RPC) │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ │ │
子进程 (stdio) 子进程 (stdio) 子进程 (stdio)
```
### 被动诊断反馈
```
LSP Server ──publishDiagnostics──▶ passiveFeedback.ts
LSPDiagnosticRegistry
(去重、容量限制)
Attachment System
(异步注入到对话)
```
LSP 服务器会异步推送 `textDocument/publishDiagnostics` 通知,经去重和容量限制后作为 attachment 注入到 Claude 的对话上下文中。
## 核心模块
| 文件 | 职责 |
|------|------|
| `src/services/lsp/manager.ts` | 全局单例,初始化/重初始化/关闭生命周期管理 |
| `src/services/lsp/LSPServerManager.ts` | 多服务器管理,按文件扩展名路由,文件同步 |
| `src/services/lsp/LSPServerInstance.ts` | 单个 LSP 服务器实例生命周期(启动/停止/重启/健康检查) |
| `src/services/lsp/LSPClient.ts` | JSON-RPC 通信层(基于 `vscode-jsonrpc`),子进程管理 |
| `src/services/lsp/config.ts` | 从插件加载 LSP 服务器配置 |
| `src/services/lsp/LSPDiagnosticRegistry.ts` | 诊断信息注册、去重、容量限制 |
| `src/services/lsp/passiveFeedback.ts` | 注册 `publishDiagnostics` 通知处理器 |
| `src/tools/LSPTool/LSPTool.ts` | LSP Tool 实现(暴露给 Claude |
| `src/tools/LSPTool/schemas.ts` | 输入 schema9 种操作的 discriminated union |
| `src/tools/LSPTool/formatters.ts` | 各操作结果的格式化 |
| `src/tools/LSPTool/prompt.ts` | Tool 描述文本 |
| `src/utils/plugins/lspPluginIntegration.ts` | 从插件加载、验证、环境变量解析、作用域管理 |
## LSP Tool 支持的操作
| 操作 | LSP Method | 说明 |
|------|-----------|------|
| `goToDefinition` | `textDocument/definition` | 跳转到符号定义 |
| `findReferences` | `textDocument/references` | 查找所有引用 |
| `hover` | `textDocument/hover` | 获取悬停信息(文档、类型) |
| `documentSymbol` | `textDocument/documentSymbol` | 获取文档内所有符号 |
| `workspaceSymbol` | `workspace/symbol` | 全工作区符号搜索 |
| `goToImplementation` | `textDocument/implementation` | 查找接口/抽象方法的实现 |
| `prepareCallHierarchy` | `textDocument/prepareCallHierarchy` | 获取位置处的调用层级项 |
| `incomingCalls` | `callHierarchy/incomingCalls` | 查找调用此函数的所有函数 |
| `outgoingCalls` | `callHierarchy/outgoingCalls` | 查找此函数调用的所有函数 |
所有操作需要 `filePath``line`1-based`character`1-based参数。
## 插件开发LSP 服务器配置
LSP 服务器通过插件提供。插件的 `manifest.json` 中可以声明 LSP 服务器,支持三种格式:
**1. 内联配置(在 manifest 中直接定义)**
```json
{
"lspServers": {
"typescript": {
"command": "typescript-language-server",
"args": ["--stdio"],
"extensionToLanguage": {
".ts": "typescript",
".tsx": "typescriptreact"
}
}
}
}
```
**2. 引用外部 .lsp.json 文件**
```json
{
"lspServers": "path/to/.lsp.json"
}
```
**3. 数组混合格式**
```json
{
"lspServers": [
"path/to/.lsp.json",
{
"another-server": { "command": "...", "extensionToLanguage": { "...": "..." } }
}
]
}
```
也可以在插件目录下直接放置 `.lsp.json` 文件,无需在 manifest 中声明。
### LSP 服务器配置 Schema
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `command` | string | 是 | LSP 服务器可执行命令(不含空格) |
| `args` | string[] | 否 | 命令行参数 |
| `extensionToLanguage` | Record<string, string> | 是 | 文件扩展名到语言 ID 的映射(至少一个) |
| `transport` | `"stdio"` \| `"socket"` | 否 | 通信方式,默认 `stdio` |
| `env` | Record<string, string> | 否 | 启动服务器时设置的环境变量 |
| `initializationOptions` | unknown | 否 | 传给服务器的初始化选项 |
| `settings` | unknown | 否 | 通过 `workspace/didChangeConfiguration` 传递的设置 |
| `workspaceFolder` | string | 否 | 工作区目录路径 |
| `startupTimeout` | number | 否 | 启动超时时间(毫秒) |
| `maxRestarts` | number | 否 | 最大重启次数(默认 3 |
### 环境变量替换
配置中的 `command``args``env``workspaceFolder` 支持:
- `${CLAUDE_PLUGIN_ROOT}` — 插件根目录
- `${CLAUDE_PLUGIN_DATA}` — 插件数据目录
- `${user_config.KEY}` — 用户在插件启用时配置的值
- `${VAR}` — 系统环境变量
## 生命周期管理
### 服务器状态机
```
stopped → starting → running
running → stopping → stopped
any → error (失败时)
error → starting (重试时)
```
### 崩溃恢复
- LSP 服务器崩溃时状态设为 `error`
- 下次请求时自动尝试重启(通过 `ensureServerStarted`
- 超过 `maxRestarts`(默认 3次后放弃
### 瞬态错误重试
- `ContentModified` 错误LSP 错误码 -32801会自动重试最多 3 次
- 使用指数退避500ms → 1000ms → 2000ms
- 常见于 rust-analyzer 等仍在索引项目的服务器
### 诊断信息容量限制
- 每个文件最多 10 条诊断
- 总计最多 30 条诊断
- 超出部分按严重性排序后截断Error > Warning > Info > Hint
- 跨 turn 去重:已发送过的相同诊断不会重复发送
- 文件编辑后清除该文件的已发送记录,允许新诊断通过
### 插件刷新
安装/卸载插件后使用 `/reload-plugins`,会调用 `reinitializeLspServerManager()`
1. 异步关闭旧服务器实例
2. 重置状态为 `not-started`
3. 调用 `initializeLspServerManager()` 重新加载插件配置
## 依赖
- `vscode-jsonrpc` — JSON-RPC 通信(懒加载,仅在实际创建服务器实例时才 require
- `vscode-languageserver-protocol` — LSP 协议类型
- `vscode-languageserver-types` — LSP 类型定义
- `lru-cache` — 诊断去重缓存

263
docs/safety/auto-mode.mdx Normal file
View File

@@ -0,0 +1,263 @@
---
title: "Auto Mode - AI 分类器驱动的自主执行模式"
description: "详解 Claude Code 的 auto mode基于 transcript classifier 的自动权限决策、两阶段分类流水线、危险权限剥离机制、模式切换状态管理、以及与 plan mode 的协作方式。"
keywords: ["auto mode", "yoloClassifier", "transcript classifier", "权限分类", "自动执行", "两阶段分类"]
---
## 概述
Auto mode 是 Claude Code 的一种权限模式,让 AI 进入**连续自主执行**状态。与传统模式每个敏感操作都弹出权限对话框等待用户审批不同auto mode 使用 AI 分类器transcript classifier自动判断每个工具调用是否安全从而实现无中断的执行体验。
```
权限模式层级:
default → auto → bypassPermissions
(逐项确认) AI 分类器审批) (全部放行)
```
## 核心架构
### 1. AI 分类器yoloClassifier
分类器是 auto mode 的核心,位于 `src/utils/permissions/yoloClassifier.ts`。
每个工具调用经过分类器评估,返回三种裁决之一:
| 裁决 | 含义 | 处理方式 |
|------|------|---------|
| **allow** | 操作安全 | 直接执行,用户无感知 |
| **deny** | 操作危险 | 拒绝执行,向 AI 返回拒绝消息 |
| **ask** | 无法确定 | 回退到传统权限对话框 |
分类器的判断基于完整的对话上下文transcript而不仅仅看单条命令——它能理解操作的意图和上下文。
### 2. 两阶段分类流水线
分类器支持两阶段 XML 分类(`classifyYoloActionXml`
```
Stage 1 — "fast"(快速判断)
├── max_tokens=64stop_sequences 触发即时 yes/no
├── 如果 allow → 直接放行(最快路径)
└── 如果 block → 进入 Stage 2
Stage 2 — "thinking"(深度思考)
├── chain-of-thought 推理
├── 减少误报false positives
└── 最终决定 allow / deny / ask
```
两个阶段共享相同的 system prompt 和 user content利用 API 的 prompt caching1 小时 TTL优化性能。
可通过配置选择模式:
- `'both'`(默认)— 两阶段都跑
- `'fast'` — 只跑 Stage 1
- `'thinking'` — 只跑 Stage 2
### 3. 分类器结果类型
```typescript
// src/types/permissions.ts
type YoloClassifierResult = {
thinking?: string // 分类器的推理过程
shouldBlock: boolean // 是否阻止
reason: string // 决策原因
unavailable?: boolean // 分类器是否不可用
transcriptTooLong?: boolean // 对话是否超出上下文窗口
model: string // 使用的分类器模型
stage?: 'fast' | 'thinking' // 哪个阶段做出的决定
// ... token 使用量、耗时等监控字段
}
```
## 安全机制
### 危险权限剥离
进入 auto mode 时,系统调用 `stripDangerousPermissionsForAutoMode()``permissionSetup.ts:510`),移除所有可能绕过分类器的 allow 规则。
被剥离的规则类型(`dangerousPatterns.ts`
| 规则类型 | 示例 | 剥离原因 |
|---------|------|---------|
| **Bash 代码执行** | `Bash(python:*)`, `Bash(node:*)` | 解释器可执行任意代码,绕过分类器审查 |
| **Shell 入口** | `Bash(bash:*)`, `Bash(sh:*)` | 直接 shell 访问等同无限制 |
| **Agent 规则** | `Agent(*)` | 任何 Agent allow 规则会绕过分类器审批子代理 |
| **PowerShell 代码执行** | `PowerShell(node:*)` | 同 Bash 逻辑 |
| **权限提升** | `Bash(sudo:*)`, `Bash(eval:*)` | 可执行任意命令 |
剥离的规则被暂存在 `strippedDangerousRules` 中,退出 auto mode 时通过 `restoreDangerousPermissions()` 恢复。
### 模型支持检测
不是所有模型都支持 auto mode。`modelSupportsAutoMode()``src/utils/betas.ts`)检查当前模型是否具备安全分类能力。不支持的模型无法进入 auto mode。
### Circuit Breaker 机制
`autoModeState.ts` 维护一个 circuit breaker 标志:
```typescript
let autoModeCircuitBroken = false // 由远程配置控制
```
当远程配置GrowthBook `tengu_auto_mode_config.enabled`)设为 `'disabled'` 时circuit breaker 触发,阻止 auto mode 的进入和继续使用。这为 Anthropic 提供了远程紧急关停能力。
## 模式切换状态管理
### 进入 Auto Mode
`transitionPermissionMode()``permissionSetup.ts:597`)处理所有模式切换:
```
1. 检查 auto mode gate 是否开启isAutoModeGateEnabled
2. 设置 autoModeActive = true
3. 调用 stripDangerousPermissionsForAutoMode() 剥离危险规则
4. 向对话注入 Auto Mode 系统提示
```
### 退出 Auto Mode
```
1. 设置 autoModeActive = false
2. 设置 needsAutoModeExitAttachment = true触发退出通知
3. 调用 restoreDangerousPermissions() 恢复被剥离的规则
4. 向对话注入 "Exited Auto Mode" 提示
```
### 触发路径
Auto mode 可通过以下方式激活:
- CLI 参数 `--enable-auto-mode`
- settings.json 中的 `autoMode` 配置
- Plan mode 默认使用 auto mode 语义(`useAutoModeDuringPlan`,默认 true
- SDK 控制消息
- REPL 中 Shift+Tab 切换
## 系统提示词
### 进入时Full Instructions
注入到对话中的指令(`messages.ts:3464`
> Auto mode is active. The user chose continuous, autonomous execution. You should:
>
> 1. **Execute immediately** — 直接实现,做合理假设
> 2. **Minimize interruptions** — 常规决策自行判断,减少提问
> 3. **Prefer action over planning** — 默认直接编码,不进 plan mode
> 4. **Expect course corrections** — 用户可随时纠正
> 5. **Do not take overly destructive actions** — 删除数据/修改生产系统仍需确认
> 6. **Avoid data exfiltration** — 不主动分享密钥/内部文档
### 持续运行时Sparse Instructions
后续轮次注入简短提醒:
> Auto mode still active. Execute autonomously, minimize interruptions, prefer action over planning.
### 退出时Exit Instructions
> You have exited auto mode. Ask clarifying questions when the approach is ambiguous rather than making assumptions.
## 与 Plan Mode 的协作
Plan mode 默认使用 auto mode 语义(`getUseAutoModeDuringPlan()`,默认 true。这意味着
- Plan mode 进入时,如果 auto mode 可用,也会激活分类器
- `isAutoModeActive()` 是权威信号(`prePlanMode`/`strippedDangerousRules` 不可靠)
- 退出 plan mode 时会同时退出 auto mode
## 分类器不可用的降级策略
当分类器 API 不可用时(`unavailable: true` 或 `transcriptTooLong: true`
- 不会直接 allow — 回退到传统的权限对话框ask
- 向 AI 发送消息:"{model} is temporarily unavailable, so auto mode cannot determine the safety of {toolName} right now."
- 确定性错误(如对话过长)不重试,直接降级
## 分类器 Prompt 模板
分类器的行为由三个 prompt 文件控制,位于 `src/utils/permissions/yolo-classifier-prompts/`。这些文件在构建时通过 `require()` 内联为字符串常量,运行时不可修改。
### auto_mode_system_prompt.txt
主系统提示词,定义分类器的角色、分类流程和决策类别。包含:
- **分类流程**:理解操作 → 检查用户意图 → 评估风险
- **BLOCK 始终阻止**:外部代码执行、不可逆删除、未授权持久化、安全削弱、提权、网络服务
- **BLOCK 除非明确意图**CWD 外写入、系统包管理、git push、大规模变更
- **ALLOW 安全操作**读文件、搜索、git 只读命令、测试/lint/构建、CWD 内编辑
- `<permissions_template>` 占位符 — 运行时替换为具体权限模板external 或 anthropic
- 末尾 `Use the classify_result tool to report your classification.` — XML 模式下被替换为 `<block>` 标签格式说明
### permissions_external.txt
外部用户版本的权限模板。三个 `<user_*_to_replace>` 标签内包裹默认规则bullet 格式),用户自定义规则**整体替换**默认值:
```
<user_allow_rules_to_replace>
- 默认 allow 规则 1
- 默认 allow 规则 2
</user_allow_rules_to_replace>
```
- **allow**9 条默认规则只读命令、版本检查、git 只读、测试/lint/构建、包安装、CWD 内文件操作等)
- **soft_deny**10 条默认规则外部代码执行、递归删除、shell 配置修改、提权、网络服务等)
- **environment**4 条环境描述终端环境、auto mode 上下文、开发工具可用、语言/框架不限)
`getDefaultExternalAutoModeRules()` 从此文件提取 bullet 项,供 `claude auto-mode defaults` 命令输出。
### permissions_anthropic.txt
Anthropic 内部版本的权限模板。默认规则在标签**外部**,标签内为空,用户自定义规则以**追加**方式叠加:
```
- 默认规则(在标签外,始终生效)
<user_allow_rules_to_replace>
</user_allow_rules_to_replace>
```
相比 external 版本,额外包含:
- 云 CLI 只读命令aws describe, gcloud describe, kubectl get 等)
- 基础设施即代码 plan 命令terraform plan, pulumi preview 等)
- 对应的 deny 规则(云资源创建/修改/删除、IaC apply、生产环境访问等
### 模板替换流程
```
buildYoloSystemPrompt()
├── BASE_PROMPT.replace('<permissions_template>', EXTERNAL/ANTHROPIC_TEMPLATE)
├── .replace(<user_allow_rules_to_replace>, userAllow ?? defaults)
├── .replace(<user_deny_rules_to_replace>, userDeny ?? defaults)
└── .replace(<user_environment_to_replace>, userEnvironment ?? defaults)
```
- 外部模板:用户设置非空时**替换**对应标签内容,否则保留默认值
- 内部模板:用户设置**追加**到默认值之后(标签在末尾为空)
## 当前状态说明
> **注意**auto mode 的完整代码逻辑已存在于代码库中,但依赖 `feature('TRANSCRIPT_CLASSIFIER')` feature flag。
> 在当前反编译版本中,`feature()` 始终返回 `false`,因此 auto mode 不可用。
> 要启用需将 `feature('TRANSCRIPT_CLASSIFIER')` 改为 `true`,并确保 GrowthBook 配置源有合理的 fallback 默认值。
Prompt 模板文件为**重建产物**——原始文件在反编译过程中丢失,已根据代码逻辑和 `yoloClassifier.ts` 中的替换模式重新编写。
## 相关源码索引
| 文件 | 职责 |
|------|------|
| `src/utils/permissions/yoloClassifier.ts` | 分类器核心实现 |
| `src/utils/permissions/autoModeState.ts` | Auto mode 状态管理 |
| `src/utils/permissions/permissionSetup.ts` | 模式切换、危险权限剥离 |
| `src/utils/permissions/dangerousPatterns.ts` | 危险命令模式列表 |
| `src/utils/permissions/classifierDecision.ts` | 分类器决策处理 |
| `src/utils/permissions/classifierShared.ts` | 分类器共享逻辑 |
| `src/utils/permissions/bashClassifier.ts` | Bash 命令分类规则 |
| `src/utils/permissions/bypassPermissionsKillswitch.ts` | bypass 权限熔断器 |
| `src/utils/permissions/yolo-classifier-prompts/auto_mode_system_prompt.txt` | 分类器主系统提示词 |
| `src/utils/permissions/yolo-classifier-prompts/permissions_external.txt` | 外部权限模板 |
| `src/utils/permissions/yolo-classifier-prompts/permissions_anthropic.txt` | 内部权限模板 |
| `src/cli/handlers/autoMode.ts` | CLI `auto-mode` 子命令处理 |
| `src/utils/messages.ts` | Auto mode 系统提示词注入 |
| `src/types/permissions.ts` | 权限类型定义 |
| `src/utils/betas.ts` | 模型 auto mode 支持检测 |

View File

@@ -1,215 +1,564 @@
---
title: "沙箱机制 - 权限之外的第二道防线"
description: "深入 Claude Code 沙箱机制:文件系统隔离、网络限制和资源约束,即使命令通过权限审批,沙箱仍可限制其行为范围。"
keywords: ["沙箱", "sandbox", "文件隔离", "安全沙箱", "命令隔离"]
title: "沙箱机制 - 权限系统之外的第二道防线"
description: "系统性梳理 Claude Code 沙箱设计:什么时候会进沙箱、什么时候不会、如何与权限系统联动、默认限制了什么、不同平台下行为有什么差异,以及用户在被拦截时会看到什么。"
keywords: ["沙箱", "sandbox", "权限", "Bash", "PowerShell", "bubblewrap", "sandbox-exec", "纵深防御"]
---
## 权限之外的第二道防线
## 一句话结论
权限系统决定"这条命令能不能执行",沙箱决定"执行时能做到什么程度"。
这个项目里的沙箱不是用来替代权限系统,而是用来给 **shell 命令** 再套一层 OS 级能力边界:
即使一条命令通过了权限审批,沙箱仍然可以限制它的行为。两者构成纵深防御的两层:
- **权限层**(应用级):在工具调用前检查,决定是否弹窗审批
- **沙箱层**OS 级):在进程级别强制约束,即使 AI 生成了恶意命令也无法突破
- 权限系统决定:这次工具调用要不要执行
- 沙箱决定:就算执行了,这个子进程最多能碰到哪些文件、哪些网络目标
## 执行链路:从用户输入到沙箱包裹
两者组合起来,才构成真正的 Defense-in-Depth。
一条 Bash 命令的完整执行路径如下:
## 实现分层:仓库里的适配器,加底层运行时
```
用户输入 → BashTool.call()
→ shouldUseSandbox(input) ─── 是否需要沙箱?
→ Shell.exec(command, { shouldUseSandbox })
→ SandboxManager.wrapWithSandbox(command)
→ spawn(wrapped_command) ─── 实际进程创建
这个项目的“沙箱实现”其实分成两层:
- 这一层仓库自己负责:策略、配置转换、启停判断、命令包裹、清理和权限联动
- 真正做 OS 级隔离的是外部运行时 `@anthropic-ai/sandbox-runtime`
在 `src/utils/sandbox/sandbox-adapter.ts` 里,可以很清楚地看到这条边界:项目导入 `SandboxManager as BaseSandboxManager`、`SandboxViolationStore` 等运行时对象,然后在外面再包一层符合 Claude Code 自身权限模型的适配器。
底层隔离在不同平台上的落地也不是同一套实现:
- macOS 走 `sandbox-exec`
- Linux / WSL2 走 `bubblewrap + seccomp`
- Windows 原生不支持这套 shell 沙箱
所以如果只看这个仓库,容易误以为“沙箱都是它自己做的”。更准确的说法是:这个仓库决定**该不该启、该怎么配、该怎么接进工具链**,真正的 OS 级约束由外部 runtime 执行。
## 它到底解决什么问题
如果只有应用层权限系统Claude Code 需要在命令执行前尽量判断:
- 这条命令是不是只读
- 会不会写危险路径
- 会不会连到外网
- 会不会通过复合命令、重定向、子进程、解释器脚本绕过检查
这些检查都很有价值,但它们本质上仍然是“执行前推断”。而 shell 命令的真实副作用经常取决于运行时行为:
- `bash script.sh`
- `python -c "..."`
- `make`
- `npm install`
- 某个命令再启动另一个子进程
沙箱的作用,就是把这些运行时行为的能力范围压缩到一个明确边界内。即使应用层检查漏了,命令也不能随意写系统目录或访问不允许的网络目标。
## 为什么“拦住它”本身就是价值
很多人第一次看到沙箱会直觉觉得:
> 如果连 `/etc/hosts` 这种文件都默认不让我改,那沙箱是不是没什么用?
这个项目的答案正好相反。沙箱不是为了让 `/etc/...` 这种系统路径也能随便改,而是为了把 shell 命令的能力压缩到一个可接受的安全边界里:
- 权限系统负责判断“要不要执行”
- 沙箱负责限制“就算执行了,最多能做到什么”
`/etc/...` 被默认拦住,说明这条边界真的在生效,而不是说明沙箱没价值。更具体地说,沙箱至少补上了 4 件权限系统单独做不好的事。
### 1. 给 shell 一个 OS 级兜底
`src/utils/bash/ast.ts` 开头就写得很明确Bash AST 分析不是沙箱,它只是在判断我们能不能可靠地理解命令结构,不能阻止危险命令真的运行。
这就是为什么应用层再聪明,也很难仅靠“执行前推断”覆盖完整风险面。像下面这些命令,真实副作用都要到运行时才完全展开:
- `bash script.sh`
- `python -c "..."`
- `make`
- `npm install`
- 一个命令再起新的子进程
沙箱的价值就在这里。即使前面的分析漏了,进程到了 OS 层以后,仍然只能写允许目录、访问允许域名,真正把 shell 的能力压缩进运行时边界。
### 2. 让“安全边界内”的命令可以少弹窗甚至自动放行
默认沙箱白名单里就包含当前工作目录和 Claude 临时目录,这也是为什么工作区内的大多数开发命令都能顺畅运行:
- `npm test`
- `rg`
- `git status`
- 工作区内的构建、测试和生成文件
项目专门提供了 `autoAllowBashIfSandboxed`。它的核心思路不是“更大胆地信任模型”,而是“既然命令已经被 OS 级边界收紧,就没必要再让用户为大量低风险 Bash 命令反复点确认”。
换句话说,没有沙箱的话,系统通常只剩两种都不太理想的选择:
- 频繁弹窗,让工作流很碎
- 更激进地信任应用层判断,把风险全压在静态分析上
### 3. 把“出错”的后果从系统级破坏,降成一次受限失败
这也是 Defense-in-Depth 最实际的一层收益。模型偶尔会出错,应用层规则也可能有漏判。沙箱的意义不是假设前面永远正确,而是即使前面偶尔判错,后果也尽量可控。
例如这类命令:
- `sudo tee /etc/hosts`
- `mv ... ~/.ssh/...`
- `curl 外网 | bash`
如果它们发生在没有运行时约束的环境里,可能就是直接修改系统、用户配置或把未知脚本落到机器上。放进沙箱之后,更常见的结果会变成:因为写权限或网络权限不满足而失败。它不是“什么都没发生”,而是把一次潜在的系统级破坏降成一次受限失败。
### 4. 拦截运行时绕过和逃逸路径
这个仓库在 `src/utils/sandbox/sandbox-adapter.ts` 里专门把一些高风险路径额外加入 `denyWrite`,例如:
- `settings.json`
- `.claude/skills`
- 一些 bare git repo 相关路径
它还专门处理 bare git repo 逃逸这一类攻击面。它们的意义不是“让更多命令通过”,而是“即使命令已经执行,也别让它顺手把护栏本身拆掉”,避免通过改配置、改技能、改 git 结构来扩大后续权限。
所以更准确的表述不是:
- “沙箱把 `/etc` 拦了,所以没用”
而是:
- “沙箱把 shell 的默认权限收缩到工作区和白名单里,因此系统级路径默认写不了;正因为这样,项目才敢把一大批工作区内命令自动放行。”
## 设计边界:它保护什么,不保护什么
### 保护对象
- Bash / shell 命令执行
- 在支持平台上的 PowerShell 执行
- shell 子进程的文件系统写入范围
- shell 子进程的网络访问范围
- 一些已知的高风险路径和沙箱逃逸向量
### 不直接保护的对象
- `FileEditTool` / `FileWriteTool` 这类直接文件工具
- 纯应用层的权限弹窗和规则匹配
- Bash AST 解析本身
尤其要注意一点Bash AST 分析不是沙箱。源码自己写得很明确,它只回答“我们能不能可信地提取 argv 结构”,并不负责阻止危险命令真正运行。
## 哪些场景会走沙箱
### 1. 启动阶段先判断“沙箱能不能用”
沙箱不是等到第一条命令执行时才临时判断的。REPL / CLI 启动时,就会先检查当前环境是否真的具备沙箱条件。核心判断包括:
1. 当前平台是否受底层 runtime 支持
2. 依赖是否齐全
3. `sandbox.enabled` 是否打开
4. 当前平台是否落在 `enabledPlatforms` 范围内
如果用户显式开启了沙箱,但当前环境不满足条件,启动期会先给出 warning如果同时配置了 `sandbox.failIfUnavailable`,则会直接拒绝启动,而不是悄悄降级成无沙箱模式。
另外,启动时不只是“看一眼能不能用”,而是真的会调用初始化流程,把当前设置转换成 runtime 配置并交给底层 `BaseSandboxManager.initialize(...)`。后续如果设置变化,还会通过 `updateConfig(...)` 热更新,而不是要求重启整个会话。
### 2. BashTool 默认会走
只要满足下面条件Bash 命令默认会进入沙箱:
1. 当前平台支持沙箱
2. 沙箱依赖齐全
3. `sandbox.enabled` 打开
4. 当前平台在 `enabledPlatforms` 范围内
5. 这条命令没有被显式排除
6. 这次调用没有被允许以 `dangerouslyDisableSandbox` 绕过
对应入口在 `src/tools/BashTool/shouldUseSandbox.ts` 和 `src/utils/sandbox/sandbox-adapter.ts`。
### 3. PowerShell 只在支持平台上走
PowerShell 的处理要更细一点:
- Linux / macOS / WSL2可以走沙箱
- Windows 原生:不支持沙箱,直接返回 `shouldUseSandbox: false`
也就是说Windows 原生上的 PowerShell 只能依赖权限系统,不会有 OS 级沙箱兜底。
### 4. Hook 命令会复用“网络专用沙箱”
Hook 不是完整复用 Bash 那套文件系统限制,而是额外套了一层 **network-only sandbox**
- 重点拦网络访问
- 文件系统不额外收紧到 Bash 那个程度
这是因为 Hook 往往不是模型直接下发的 Bash 工具调用,而是系统/插件的外部扩展点。
## 哪些场景不会走沙箱
### 1. FileEditTool / FileWriteTool
这类工具不是靠 shell 修改文件,而是直接在应用层做文件 I/O所以它们不通过 `Shell.exec()`,自然也不会被 `wrapWithSandbox()` 包裹。
它们走的是另一条链路:
- `checkWritePermissionForTool()`
- `checkPathSafetyForAutoEdit()`
- 工作目录检查
- allow/ask/deny 规则
因此:
- “shell 改 `/etc/hosts`”通常是沙箱在 OS 层拦
- “FileEdit 改 `/etc/hosts`”通常是权限系统在应用层拦
### 2. 明确排除的命令
如果命中 `sandbox.excludedCommands`,这条命令会直接跳过沙箱。
支持三类模式:
- 精确匹配
- 前缀匹配
- 通配符匹配
### 3. 允许 unsandboxed fallback 的命令
如果:
- 这次调用显式设置了 `dangerouslyDisableSandbox: true`
- 并且策略允许 `allowUnsandboxedCommands`
那它也可以不进沙箱。
这个设计是有意保留的,但命名也故意写得很重:`dangerouslyDisableSandbox`,提醒这是例外路径,不应当成为默认习惯。
## 完整执行链路
可以把整个过程拆成两段来看:启动期先把沙箱准备好,命令期再决定“这条命令要不要进去”。
### 启动期链路
```text
REPL / CLI 启动
-> isSandboxingEnabled()
-> convertToSandboxRuntimeConfig(settings)
-> BaseSandboxManager.initialize(runtimeConfig, callback)
-> 设置变化时 BaseSandboxManager.updateConfig(newConfig)
```
关键判定发生在 `shouldUseSandbox()``src/tools/BashTool/shouldUseSandbox.ts`),它执行以下检查:
这一段回答的是:当前会话里有没有一个可用、已初始化、能处理网络授权回调的沙箱 runtime。
1. **全局开关**`SandboxManager.isSandboxingEnabled()` — 检查平台支持 + 依赖完整性 + 用户设置
2. **显式跳过**:如果 `dangerouslyDisableSandbox: true` 且策略允许(`allowUnsandboxedCommands`),则不走沙箱
3. **排除列表**:用户可在 `settings.json` 中配置 `sandbox.excludedCommands`,匹配的命令跳过沙箱
4. **默认行为**:以上条件都不满足时,**进入沙箱**
### 命令期链路
## `shouldUseSandbox()` 判定逻辑详解
典型 Bash 执行链路如下:
```typescript
// src/tools/BashTool/shouldUseSandbox.ts
function shouldUseSandbox(input: Partial<SandboxInput>): boolean {
// 1. 全局未启用 → 直接跳过
if (!SandboxManager.isSandboxingEnabled()) return false
// 2. 显式禁用 + 策略允许 → 跳过
if (input.dangerouslyDisableSandbox &&
SandboxManager.areUnsandboxedCommandsAllowed()) return false
// 3. 无命令 → 跳过
if (!input.command) return false
// 4. 匹配排除列表 → 跳过
if (containsExcludedCommand(input.command)) return false
// 5. 其他情况 → 必须沙箱化
return true
}
```text
用户请求
-> BashTool.checkPermissions()
-> shouldUseSandbox(input)
-> Shell.exec(command, { shouldUseSandbox: true/false })
-> SandboxManager.wrapWithSandbox(...)
-> spawn(wrapped command)
-> 运行结束后 cleanupAfterCommand()
```
`containsExcludedCommand()` 的匹配机制值得注意——它不只是简单的前缀匹配,而是支持三种模式:
这里真正把命令“包进沙箱”的关键点是 `Shell.exec()`。它会在真正 `spawn(...)` 之前调用 `SandboxManager.wrapWithSandbox(...)`,把原始命令改写成底层 runtime 可执行的沙箱命令串。命令结束后如果本次是 sandboxed execution再调用 `cleanupAfterCommand()` 清理运行时残留。
| 模式 | 示例 | 匹配行为 |
|------|------|----------|
| **精确匹配** | `npm run lint` | 完全相等 |
| **前缀匹配** | `npm run test:*` | 前缀 + 空格或完全相等 |
| **通配符** | `docker*` | 使用 `matchWildcardPattern` |
其中有两个容易混淆的判定点:
对于复合命令(如 `docker ps && curl evil.com`),系统会先拆分为子命令,逐一检查。还会迭代剥离环境变量前缀(`FOO=bar bazel ...`)和包装命令(`timeout 30 bazel ...`),直到不动点——防止通过嵌套包装绕过。
### 判定点 A要不要进沙箱
## 沙箱的配置模型
这是 `shouldUseSandbox()` 的职责。
沙箱配置来自 `settings.json` 中的 `sandbox` 字段(`src/entrypoints/sandboxTypes.ts`
它回答的是
```jsonc
{
"sandbox": {
"enabled": true, // 主开关
"autoAllowBashIfSandboxed": true, // 沙箱中的命令自动允许(跳过审批)
"allowUnsandboxedCommands": true, // 是否允许 dangerouslyDisableSandbox
"failIfUnavailable": false, // 沙箱依赖缺失时是否报错退出
"network": {
"allowedDomains": ["github.com"], // 网络白名单
"deniedDomains": [], // 网络黑名单
"allowLocalBinding": true, // 允许 localhost 绑定
"httpProxyPort": 8888 // HTTP 代理端口MITM
},
"filesystem": {
"allowWrite": ["~/projects"], // 额外可写路径
"denyWrite": ["~/.ssh"], // 禁止写入路径
"denyRead": [], // 禁止读取路径
"allowRead": [] // 在 denyRead 中重新放行
},
"excludedCommands": ["docker", "npm:*"] // 不走沙箱的命令
}
}
```
> 这条命令要不要被 OS 级沙箱包起来执行?
`SandboxSettingsSchema` 定义了完整的 Zod 验证规则,包含一些未公开的设置如 `enabledPlatforms`(限制沙箱只在特定平台生效)。
### 判定点 B这条命令要不要弹权限确认
## 平台实现差异
这是权限系统和 Bash 权限检查的职责。
### macOSsandbox-execSeatbelt
它回答的是:
macOS 使用 Apple 的 Seatbelt 沙箱(`sandbox-exec` 命令),这是 macOS 原生的进程隔离机制。
> 这条命令在应用层看来,是 `allow`、`ask` 还是 `deny`
执行流程:
1. `SandboxManager.wrapWithSandbox()` 调用 `@anthropic-ai/sandbox-runtime` 的 `BaseSandboxManager`
2. 运行时生成 Seatbelt profile基于配置中的网络/文件系统规则)
3. 通过 `sandbox-exec -p <profile> -- <command>` 包裹原始命令
4. Seatbelt 在内核级别强制执行约束
这两个判定点是并列协作的,不是互相替代的。
网络隔离的实现方式:
- 通过代理端口拦截 HTTP/HTTPS 请求
- 域名白名单/黑名单在代理层过滤
- Unix socket 可单独配置允许路径
## 默认沙箱到底限制了什么
### Linuxbubblewrapbwrap+ seccomp
沙箱运行时配置最终由 `convertToSandboxRuntimeConfig()` 生成。它会把项目自己的设置、权限规则和安全加固逻辑,转换成底层运行时需要的配置。
Linux 使用 `bubblewrap`bwrap创建命名空间隔离配合 seccomp 过滤系统调用:
这一步很关键,因为这个项目的沙箱配置不是一份静态表,而是从 Claude Code 自己的权限系统里“翻译”出来的。
依赖项(`apt install`
| 包 | 作用 |
|----|------|
| `bubblewrap` | 创建 mount/PID/network 命名空间 |
| `socat` | 网络代理HTTP/SOCKS |
| `libseccomp` / seccomp filter | 过滤 Unix socket 系统调用 |
### 这些限制是怎么从权限系统推导出来的
bwrap 的实现差异:
- **不支持 glob 路径模式**macOS 的 Seatbelt 支持)— Linux 上带 glob 的权限规则会触发警告
- 执行后会在当前目录留下 0 字节的 mount-point 文件(如 `.bashrc`),需要 `cleanupAfterCommand()` 清理
- seccomp 无法按路径过滤 Unix socket只能全允许或全拒绝与 macOS 的按路径放行形成差异
- `WebFetch(domain:...)` 和 `sandbox.network.allowedDomains` 会被合并成网络白名单
- `Edit(...)` / `Read(...)` 这类权限规则会被翻译成文件系统读写限制
- `sandbox.filesystem.allowWrite` / `allowRead` / `denyWrite` / `denyRead` 会继续叠加到最终 runtime 配置上
### 平台支持矩阵
也就是说沙箱不是独立维护另一套完全平行的安全策略而是把“Claude 认为哪些路径或域名应该被允许”落地成 OS 级约束。
| 特性 | macOS | Linux | WSL |
|------|-------|-------|-----|
| 沙箱引擎 | sandbox-exec (Seatbelt) | bubblewrap + seccomp | 仅 WSL2 |
| 文件 glob | ✅ 完整支持 | ⚠️ 仅 `/**` 后缀 | 同 Linux |
| 网络 Unix socket 按路径 | ✅ | ❌ | ❌ |
| 依赖检查 | ripgrep | bwrap + socat + ripgrep + seccomp | 同 Linux |
### 文件系统默认写入范围
## 沙箱初始化流程
默认 `allowWrite` 只有两类:
```
REPL/SDK 启动
→ main.tsx → init.ts
→ SandboxManager.initialize(sandboxAskCallback)
→ detectWorktreeMainRepoPath() // 检测 git worktree放行主仓库 .git
→ convertToSandboxRuntimeConfig() // 构建 SandboxRuntimeConfig
→ BaseSandboxManager.initialize() // 启动底层运行时
→ settingsChangeDetector.subscribe() // 订阅设置变更,动态更新配置
```
- 当前工作目录 `.`
- Claude 的临时目录
`convertToSandboxRuntimeConfig()``src/utils/sandbox/sandbox-adapter.ts`)完成从用户设置到运行时配置的转换
这意味着
1. **网络规则**:从 `WebFetch(domain:...)` 权限规则提取域名 → `allowedDomains`
2. **文件系统规则**:从 `Edit(...)` / `Read(...)` 权限规则提取路径 → `allowWrite` / `denyWrite` / `denyRead`
3. **安全加固**
- 自动将项目目录加入 `allowWrite`
- 自动将 `settings.json` 路径加入 `denyWrite`(防止沙箱逃逸)
- 自动将 `.claude/skills` 加入 `denyWrite`(防止技能注入)
- 检测 bare git repo 攻击向量,对 `HEAD`/`objects`/`refs` 做保护
- 工作区内的构建、测试、生成临时文件通常能正常运行
- 根路径如 `/etc/...`、`/usr/...`、`/var/...` 默认不在写白名单里
## `dangerouslyDisableSandbox` 的设计权衡
### 文件系统额外写入来源
这个参数的命名本身就传达了设计意图——它不是"关闭沙箱",而是"**危险地禁用沙箱**"。
额外允许写入的路径,主要来自这些来源:
双重保险机制:
1. **调用侧**:模型在 BashTool 的 `inputSchema` 中可以设置 `dangerouslyDisableSandbox: true`
2. **策略侧**:管理员可通过 `allowUnsandboxedCommands: false` 完全禁止此参数(企业部署场景)
- `sandbox.filesystem.allowWrite`
- `Edit(...)` 规则推导出的路径
- `/add-dir` 或 `--add-dir` 增加的目录
- git worktree 主仓库所需路径
```typescript
// 即使 AI 请求了 dangerouslyDisableSandbox策略层仍可覆盖
if (input.dangerouslyDisableSandbox &&
SandboxManager.areUnsandboxedCommandsAllowed()) {
return false // 只有策略允许时才真正跳过沙箱
}
```
这里还有一个很容易漏掉的细节:适配层会专门处理 worktree 主仓库和 bare git repo 这种仓库级特殊路径,避免在隔离后把正常开发流程误伤,或者反过来留下逃逸面。
`autoAllowBashIfSandboxed` 进一步补充了这个模型:当启用时,**在沙箱中的命令自动获得执行许可**,无需逐条审批。这基于一个信任假设——如果 OS 级沙箱已经限制了命令的能力,那么应用层的逐条审批就变得多余。
### 强制 deny 的路径
## 沙箱违规处理
即使有别的配置,项目还会额外加固一些高风险路径,例如:
当命令尝试违反沙箱约束时:
- settings 文件
- `.claude/skills`
- 一些 bare git repo 相关路径
1. 运行时捕获违规事件(文件/网络访问被拒绝)
2. `SandboxManager.annotateStderrWithSandboxFailures()` 在输出中注入 `<sandbox_violations>` 标签
3. UI 层通过 `removeSandboxViolationTags()` 清理显示
4. 违规事件通过 `SandboxViolationStore` 持久化,可用于审计
这样做的原因是:这些路径一旦可写,攻击者可能反过来修改 Claude Code 自己的配置、技能或 git 行为,从而扩大权限。
## 完整执行链路示例
### 网络限制
以 `npm install` 为例
网络白名单来自两部分
```
1. 用户在 REPL 中输入 → Claude 决定调用 BashTool
2. BashTool.validateInput() → 通过
3. BashTool.checkPermissions() → 检查权限规则
├── autoAllowBashIfSandboxed = true 且沙箱可用 → 自动允许
└── 否则 → 弹窗请用户确认
4. BashTool.call() → runShellCommand()
5. shouldUseSandbox({ command: "npm install" })
├── SandboxManager.isSandboxingEnabled() → true
├── dangerouslyDisableSandbox → undefined
└── containsExcludedCommand() → false除非用户配置了排除 npm
→ 结果: true需要沙箱
6. Shell.exec() → SandboxManager.wrapWithSandbox("npm install")
├── macOS: sandbox-exec -p <generated-profile> -- bash -c 'npm install'
└── Linux: bwrap ... bash -c 'npm install'
7. spawn(wrapped_command) → 子进程在沙箱内执行
8. 执行完成 → SandboxManager.cleanupAfterCommand()
├── 清理 bwrap 残留文件Linux
└── scrubBareGitRepoFiles()(安全清理)
9. 结果返回给 Claude → 展示给用户
```
- `sandbox.network.allowedDomains`
- `WebFetch(domain:...)` 这类权限规则
被允许的域名会进入沙箱网络配置;不在白名单里的访问,在运行时会被拦截或触发额外的网络授权流程。
## `autoAllowBashIfSandboxed` 的真实意义
这是沙箱设计里最值得注意的开关之一。
它表达的是这样一个信任假设:
> 如果命令已经被 OS 级沙箱约束在安全边界内,那么应用层就没有必要再对大量低风险 Bash 命令逐条弹确认框。
因此,当这个开关开启时:
- 命令会先检查显式 `deny` / `ask` 规则
- 如果没有命中这些硬规则
- 且命令确实会在沙箱里执行
- 那么 BashTool 可以直接自动允许它运行
这里还有一个边界条件特别值得写清楚:它只对“真正会进沙箱的命令”生效。像这些情况,仍然不能直接吃到这个 shortcut
- 命中了 `excludedCommands`
- 显式使用了 `dangerouslyDisableSandbox: true`
- 当前平台根本不支持沙箱
这些命令依然要遵守正常的 `ask` 规则,因为它们没有拿到 OS 级约束带来的那层安全兜底。
这也是沙箱存在的一个核心产品价值:不是让更多危险操作通过,而是让更多**受限范围内的常规命令**可以无感运行。
## 为什么“沙箱把 `/etc` 拦了”反而说明它有用
前面的“四个核心价值”解释的是原理,这里把结论再落回最常见的直觉疑问上:为什么一个默认不让你写 `/etc` 的系统,反而更值得信任?
因为 Claude Code 日常最常跑的不是系统管理命令,而是开发命令。例如:
- `npm test`
- `npm install`
- `cargo build`
- `pytest`
- `rg`
- `git status`
这些命令本来就应该只在工作区和少量临时目录里活动。沙箱把 shell 的默认能力收缩到这个范围后,项目才敢在应用层减少弹窗、启用 `autoAllowBashIfSandboxed`、提高自动化程度。
所以这个问题的正确落点不是“它为什么不帮我改 `/etc`”,而是“它能不能在不碰 `/etc` 的前提下,让大量正常开发命令更安全、更顺滑地运行”。从这个角度看,`/etc` 默认写不了并不是缺点,而是整个自动化体验成立的前提。
## 平台差异
### macOS
- 底层使用 `sandbox-exec`
- 路径和网络规则通过 Seatbelt profile 落地
- 属于原生 OS 级进程隔离
### Linux
- 底层使用 `bubblewrap + seccomp`
- 会建立 mount / PID / network 等隔离
- Linux 上对 glob 路径的支持比 macOS 弱一些
- 某些运行后残留需要在 `cleanupAfterCommand()` 中清理
### WSL
- 只支持 WSL2
- WSL1 视为不支持平台
### Windows 原生
- 原生 PowerShell/Bash 不支持这个沙箱体系
- 因此只能依赖权限系统和工具级检查
这也是为什么你前面问“改 C 盘文件会不会走沙箱”时,答案会分成:
- Windows 原生:通常不走
- Linux/macOS/WSL2shell 才可能走
## 工作区内外:应用层与沙箱层如何配合
### 工作区内路径
工作区内路径通常有两层保护:
1. 应用层权限检查
2. 沙箱默认允许写当前工作目录
这使得“工作区内构建/测试/格式化/生成文件”成为最顺滑的一条路径。
### 工作区外路径
工作区外路径则更严格:
- 应用层通常会视为高风险,要求确认或阻止
- 即使应用层允许,如果不在沙箱白名单里,运行时也会失败
这就形成了双保险。
### Linux 根路径 `/etc/...`
对于 Linux 上的根路径文件,通常会出现两种情况:
- **shell 路径**:命令会进沙箱,但沙箱默认没有 `/etc` 写权限,所以运行时被拦
- **文件工具路径**:不走沙箱,而是在应用层直接被文件权限检查拦住
## 用户真的会看到什么
被拦截并不是同一种体验,至少有三类。
### 1. 执行前的权限确认
如果应用层在执行前就判定为 `ask`,用户会看到标准权限对话框:
- Bash 权限确认
- FileEdit / FileWrite 权限确认
- 其他工具自己的权限确认 UI
这种提示发生在命令还没真正运行之前。
### 2. 执行中的沙箱违规
如果命令已经进入沙箱,运行时才触发违规:
- 命令会失败
- stderr 会被附加 `<sandbox_violations>` 标签供模型理解
- UI 会清理这些标签再显示给用户
- 同时 `SandboxViolationStore` 会记录违规事件
这意味着用户通常能看到:
- 命令失败本身
- 以及“最近有多少次 sandbox blocked”之类的界面提示
### 3. 网络越界请求
网络是个特例。
当沙箱外的 host 访问需要额外确认时,项目会弹出一个专门的网络授权对话框,例如:
- `Network request outside of sandbox`
这里和文件系统运行时拦截不同,它有明确的交互式授权 UI。
## 为什么文件系统越界通常不弹“再放行一次”
这是一个非常有意的设计选择。
对文件系统来说,项目更倾向于:
- 执行前在应用层 ask
- 或者执行后让命令直接因沙箱失败
而不是在运行到一半时再弹出一个“是否允许写这个系统路径”的新对话框。
这样做的好处是:
- 边界更稳定
- 用户心智更清晰
- 不容易把 shell 运行时逐步升级成越来越宽松的环境
网络访问则更适合做按 host 的临时授权,因此单独做了授权对话框。
## 常见误区
### 误区 1沙箱会保护所有文件修改
不是。它主要保护 **shell 子进程**。
直接文件编辑工具走的是应用层权限系统,不是 shell 沙箱。
### 误区 2只要启用了沙箱就不会再需要权限系统
不是。沙箱只限制进程能力,不负责解释用户意图、路径安全语义、工具模式、审批体验。
项目之所以还保留复杂的 `allow / ask / deny` 体系,就是因为两者职责不同。
### 误区 3如果某个危险操作被沙箱拦住就说明应用层检查没价值
不是。应用层检查的价值在于:
- 更早提示
- 更好的用户体验
- 更细的语义判断
- 对不走 shell 的工具同样生效
而沙箱负责的是最终兜底。
## 推荐的阅读路径
如果你想继续顺着源码深入,推荐按下面顺序看:
1. `src/tools/BashTool/shouldUseSandbox.ts`
2. `src/utils/Shell.ts`
3. `src/utils/sandbox/sandbox-adapter.ts`
4. `src/utils/permissions/permissions.ts`
5. `src/tools/BashTool/bashPermissions.ts`
6. `src/utils/permissions/pathValidation.ts`
7. `src/utils/permissions/filesystem.ts`
按这条线读,会更容易把“权限系统”和“沙箱系统”在脑中拆开。
## FAQ
### Q1Linux 下 `echo hi > /etc/hosts` 会怎样?
如果是 BashTool
- 通常会进沙箱
- 默认沙箱不允许写 `/etc`
- 所以命令会在运行时失败
如果是 FileEditTool
- 不进沙箱
- 通常会在应用层文件权限检查里先被拦下
### Q2Windows 下改 `C:\Windows\System32\drivers\etc\hosts` 会怎样?
在 Windows 原生环境里,通常没有这套 shell 沙箱兜底,所以主要依赖应用层权限系统和工具自己的检查逻辑。
### Q3既然沙箱这么强为什么还保留 `dangerouslyDisableSandbox`
因为有些真实开发任务确实需要越过默认边界,例如:
- 访问未加入白名单的工具链目录
- 调试系统级环境
- 做管理员明确允许的例外操作
但项目把这个入口做得非常显眼,也允许管理员通过策略直接禁掉,避免它变成默认路径。
### Q4什么时候最能感受到沙箱的价值
当你开启 `autoAllowBashIfSandboxed` 时最明显。
这时大量工作区内命令可以少弹窗甚至不弹窗,但即使模型偶尔给出过界命令,系统级写入和网络能力仍然被边界限制住。

View File

@@ -0,0 +1,77 @@
# Task 001: daemon status / stop
> 来源: [stub-recovery-design-1-4.md](../features/stub-recovery-design-1-4.md) 第 1 项
> 优先级: P0 (首选实现项)
> 工作量: 小
> 状态: DONE
## 目标
`claude daemon status``claude daemon stop` 在任意 CLI 进程中都能正确工作,不依赖 TUI 内存态。
## 背景
- `start` 路径已有完整 supervisor + worker 生命周期 (`src/daemon/main.ts`, `src/daemon/workerRegistry.ts`)
- `status` / `stop` 目前只是占位输出 (`src/daemon/main.ts:49`)
- `/remote-control-server` 有自己的命令内 UI 状态,但只维护当前进程内的 `daemonProcess`,不适合跨进程管理
## 实现方案
### 新增文件
| 文件 | 说明 |
|------|------|
| `src/daemon/state.ts` | daemon 状态文件读写模块 |
### 修改文件
| 文件 | 改动 |
|------|------|
| `src/daemon/main.ts` | `start` 写入状态文件;`status`/`stop` 调用 state 模块 |
| `src/commands/remoteControlServer/remoteControlServer.tsx` | 读取同一份状态文件(轻量改动) |
### 状态文件
路径: `~/.claude/daemon/remote-control.json`
```json
{
"pid": 12345,
"cwd": "/path/to/project",
"startedAt": "2026-04-12T10:00:00Z",
"workerKinds": ["bridge", "rcs"],
"lastStatus": "running"
}
```
### status 逻辑
1. 读取状态文件
2. 用进程探测验证 pid 是否存活
3. 输出 `running` / `stopped` / `stale`
4. stale 时自动清理状态文件
### stop 逻辑
1. 读取 pid
2. 发送 `SIGTERM`
3. 等待退出(超时兜底)
4. 超时后 `SIGKILL`
5. 清理状态文件
## 验证步骤
- [ ] `claude daemon start` 正常启动并写入状态文件
- [ ] 新开终端执行 `claude daemon status`,显示 `running`
- [ ] 执行 `claude daemon stop`daemon 正常退出
- [ ] 再次执行 `claude daemon status`,返回 `stopped``stale cleaned`
- [ ] Windows 下 stop 超时兜底正常工作
## 风险
- Windows 信号模型和 Unix 不同,`stop` 需要超时兜底
- 当前设计默认单 supervisor不处理多实例并发
## 依赖
无外部依赖,可独立实施。

View File

@@ -0,0 +1,80 @@
# Task 002: BG_SESSIONS — ps / logs / kill
> 来源: [stub-recovery-design-1-4.md](../features/stub-recovery-design-1-4.md) 第 2 项
> 优先级: P1
> 工作量: 中等
> 状态: DONE
> 阶段: Phase 2A (MVP)
## 目标
`ps` / `logs` / `kill` 做成真正有用的 session 管理命令。不在第一阶段补完 `attach` / `--bg`
## 背景
- fast-path 已接好 (`src/entrypoints/cli.tsx:218`)
- session registry 已有真实实现 (`src/utils/concurrentSessions.ts`)
- `exit` 在 bg session 内已会 `tmux detach-client` (`src/commands/exit/exit.tsx:20`)
- CLI handler 仍全空 (`src/cli/bg.ts`)
- task summary 仍然是 stub (`src/utils/taskSummary.ts`)
## 实现方案
### 修改文件
| 文件 | 改动 |
|------|------|
| `src/cli/bg.ts` | 实现 `ps` / `logs` / `kill` handler |
| `src/utils/concurrentSessions.ts` | 扩展以便后续 attach/--bg 使用 |
| `src/utils/taskSummary.ts` | 补充基础实现 |
### 复用模块
- `src/utils/sessionStorage.ts` — session 存储
- `src/utils/udsClient.ts` — UDS 通信
### ps 命令
- 从 registry 读取 live sessions
- 展示: pid, kind, sessionId, cwd, name, startedAt, bridgeSessionId
- 如果有 activity/status一并展示
### logs 命令
- 支持按 `sessionId` / `pid` / `name` 查找
- 优先复用本地 transcript/log 读取能力
- 如果 registry 里存在 `logPath`,支持 tail 文件
### kill 命令
- 解析目标 session
- 发退出信号
- 清理 stale registry
## 验证步骤
- [ ] `ps` 能列出当前 live sessions
- [ ] `logs <sessionId|pid|name>` 能输出对应日志
- [ ] `kill <sessionId|pid|name>` 能结束目标 session 并清理 registry
- [ ] 无 live session 时各命令有明确提示
## Phase 2B (后续)
- [ ] 实现 `attach`
- [ ] 实现 `--bg`
- [ ] 实现 `taskSummary` 的中途状态更新
### 为什么拆分
- 现有 registry 记录了 `pid / sessionId / name / logPath`
- 但没有可靠的 tmux attach target
- `attach``--bg` 需要补启动/附着元数据设计,不是简单补 handler
## 风险
- `attach` / `--bg` 第二阶段需要 tmux 元数据设计
- Windows 下 tmux 路径需要明确降级策略
## 依赖
- Task 001 (daemon 状态管理可复用模式,但非硬性依赖)

View File

@@ -0,0 +1,87 @@
# Task 003: TEMPLATES — job 文件系统 MVP
> 来源: [stub-recovery-design-1-4.md](../features/stub-recovery-design-1-4.md) 第 3 项
> 优先级: P2
> 工作量: 中等
> 状态: DONE
> 阶段: MVP
## 目标
`new` / `list` / `reply` 做成可用的模板任务系统。第一阶段不碰复杂的自动分类与自动执行。
## 背景
- 命令入口只有 fast-path (`src/entrypoints/cli.tsx:249`)
- handler 是空的 (`src/cli/handlers/templateJobs.ts`)
- `markdownConfigLoader` 已把 `templates` 纳入配置目录 (`src/utils/markdownConfigLoader.ts:29`)
- `query/stopHooks` 已预留 job classifier 链路 (`src/query/stopHooks.ts:103`)
- `jobs/classifier.ts` 仍是 stub (`src/jobs/classifier.ts`)
## 实现方案
### 新增文件
| 文件 | 说明 |
|------|------|
| `src/jobs/state.ts` | job 状态管理 |
| `src/jobs/templates.ts` | 模板解析与列表 |
### 修改文件
| 文件 | 改动 |
|------|------|
| `src/cli/handlers/templateJobs.ts` | 实现 `new` / `list` / `reply` handler |
### 模板来源
`.claude/templates/*.md`
### 模板格式
复用现有 markdown + frontmatter 解析,不另外设计 DSL。
### list 命令
- 列出所有模板
- 显示: 模板名, description, 路径
### new 命令
- 解析模板
-`~/.claude/jobs/<job-id>/` 下创建 job 目录
- 写入 `template.md`, `input.txt`, `state.json`
- 返回 job id 与目录路径
### reply 命令
- 将回复写入 `replies.jsonl``input.txt`
- 更新 `state.json`
## 验证步骤
- [ ] `list` 能列出 `.claude/templates` 下的所有模板
- [ ] `new <template> [args...]` 能创建 job 目录和状态文件
- [ ] `reply <job-id> <text>` 能更新 job 内容和状态
- [ ] frontmatter schema 最小字段集已定义
## Phase 2 (后续)
- [ ] 恢复 `src/jobs/classifier.ts`
- [ ] 让带 `CLAUDE_JOB_DIR` 的 job session 在 turn 完成后自动更新 `state.json`
- [ ] 再决定是否补自动 job runner
### 为什么拆分
- 当前是 "template job commands",不是单纯模板列表
- 自动 job 运行链路没有足够现成实现
- 先做文件系统 job lifecycle 更稳
## 风险
- frontmatter schema 需要先定义最小字段集
- 一旦扩展到"自动运行 job",范围会明显膨胀
## 依赖
无硬性依赖,可独立实施。

View File

@@ -0,0 +1,103 @@
# Task 004: assistant [sessionId] — 分阶段恢复
> 来源: [stub-recovery-design-1-4.md](../features/stub-recovery-design-1-4.md) 第 4 项
> 优先级: P3
> 工作量: Phase 4A 中等4A-4D 全做完很大
> 状态: Phase 4A DONE, 4B-4D TODO
## 目标
不一次性恢复整个 KAIROS 助手系统。先做"明确 sessionId 的 viewer attach 可用",再逐步补 discovery / chooser / install。
## 背景
- attach 主流程已存在 (`src/main.tsx:4708`)
- 远端 viewer 所需基础模块已存在:
- `src/remote/RemoteSessionManager.ts`
- `src/hooks/useAssistantHistory.ts`
- `src/assistant/sessionHistory.ts`
- 真正 stub 的主要是:
- `src/assistant/sessionDiscovery.ts`
- `src/assistant/AssistantSessionChooser.ts`
- `src/commands/assistant/assistant.ts:7`
- `src/assistant/index.ts`
## 分阶段实现
### Phase 4A: MVP — 显式 sessionId attach
**修改文件:**
| 文件 | 改动 |
|------|------|
| `src/main.tsx` | 确保 attach 分支可用 |
| `src/commands/assistant/index.ts` | 实现显式 sessionId 参数入口 |
**行为:**
- `claude assistant <sessionId>` — 进入 remote viewer
- `claude assistant` (无参数) — 返回明确提示: 当前版本需要显式 sessionIddiscovery 尚未启用
**验证:**
- [ ] `claude assistant <sessionId>` 能进入 remote viewer
- [ ] 历史懒加载工作正常
- [ ] 无参数模式给出明确提示
### Phase 4B: session discovery
**修改文件:**
| 文件 | 改动 |
|------|------|
| `src/assistant/sessionDiscovery.ts` | 恢复 `discoverAssistantSessions()` |
**行为:**
- 数据来源优先复用现有 sessions / bridge / teleport API不新增协议
- `claude assistant` 无参数时能拿到候选 session 列表
**验证:**
- [ ] 无参数调用能列出可用 sessions
- [ ] 数据来源复用现有通道
### Phase 4C: session chooser
**修改文件:**
| 文件 | 改动 |
|------|------|
| `src/assistant/AssistantSessionChooser.ts` | 恢复交互式选择器 |
**行为:**
- 多 session 时可交互选择
**验证:**
- [ ] 多个 session 时弹出选择器
- [ ] 选择后正确 attach
### Phase 4D: install wizard
**修改文件:**
| 文件 | 改动 |
|------|------|
| `src/commands/assistant/assistant.ts` | 恢复 install wizard 辅助函数 |
**行为:**
- 没有 session 时如何引导用户
**验证:**
- [ ] 无可用 session 时引导用户创建/连接
## 为什么拆分
- attach 渲染层与远端消息通道大部分已在
- 真正缺的是"如何发现目标 session"和"如何交互选择"
- 如果把 `src/assistant/index.ts` 的整套 KAIROS 正常模式也一起拉进来,范围会失控
## 风险
- 这是四项里范围最大的
- 一旦把 KAIROS 正常模式整体拉入,会从"viewer attach"膨胀成"完整 assistant mode 恢复"
## 依赖
- Task 002 的 session registry 模式可复用

View File

@@ -0,0 +1,196 @@
# Task 013: BgEngine 跨平台后台引擎抽象
> 设计文档: [daemon-restructure-design.md](../features/daemon-restructure-design.md) § 四
> 依赖: 无
> 分支: `feat/integrate-5-branches`
## 目标
`src/cli/bg.ts` 中硬编码的 tmux 逻辑提取为引擎抽象层,实现 TmuxEngine + DetachedEngine使后台会话功能在 Windows / macOS / Linux 上都能工作。
## 背景
当前 `bg.ts``handleBgFlag()``attachHandler()` 直接调用 tmux 命令。Windows 上 `--bg` 直接报错退出。需要一个引擎抽象层,根据平台和可用工具自动选择最佳方案。
## 文件清单
### 新增
| 文件 | 说明 |
|------|------|
| `src/cli/bg/engine.ts` | BgEngine 接口 + BgStartOptions/BgStartResult 类型 |
| `src/cli/bg/engines/tmux.ts` | TmuxEngine: 从 `bg.ts` 提取 tmux 相关逻辑 |
| `src/cli/bg/engines/detached.ts` | DetachedEngine: spawn({ detached }) + logFile 重定向 |
| `src/cli/bg/engines/index.ts` | selectEngine() 自动选择 + re-export |
| `src/cli/bg/tail.ts` | 跨平台日志 tail: fs.watch + 轮询 fallback |
### 修改
| 文件 | 变更 |
|------|------|
| `src/cli/bg.ts` | `handleBgFlag()` 改为调用 `selectEngine().start()``attachHandler()` 改为调用 `engine.attach()` |
## 实现方案
### 1. BgEngine 接口 (`src/cli/bg/engine.ts`)
```typescript
export interface BgEngine {
readonly name: string
available(): Promise<boolean>
start(opts: BgStartOptions): Promise<BgStartResult>
attach(session: SessionEntry): Promise<void>
}
export interface BgStartOptions {
sessionName: string
args: string[] // CLI args (去除 --bg)
env: Record<string, string | undefined>
logPath: string
cwd: string
}
export interface BgStartResult {
pid: number
sessionName: string
logPath: string
engineUsed: 'tmux' | 'detached'
}
```
### 2. TmuxEngine (`src/cli/bg/engines/tmux.ts`)
`bg.ts:handleBgFlag()``bg.ts:attachHandler()` 提取:
- `available()`: `execFileNoThrow('tmux', ['-V'])` 返回 code === 0
- `start()`: `tmux new-session -d -s <name> <cmd>`
- `attach()`: `tmux attach-session -t <session.tmuxSessionName>`
### 3. DetachedEngine (`src/cli/bg/engines/detached.ts`)
```typescript
export class DetachedEngine implements BgEngine {
readonly name = 'detached'
async available(): Promise<boolean> {
return true // 总是可用
}
async start(opts: BgStartOptions): Promise<BgStartResult> {
const logFd = openSync(opts.logPath, 'a')
const child = spawn(process.execPath, [process.argv[1]!, ...opts.args], {
detached: true,
stdio: ['ignore', logFd, logFd],
env: opts.env,
cwd: opts.cwd,
})
child.unref()
closeSync(logFd)
return {
pid: child.pid!,
sessionName: opts.sessionName,
logPath: opts.logPath,
engineUsed: 'detached',
}
}
async attach(session: SessionEntry): Promise<void> {
// 委托给 tail.ts
await tailLog(session.logPath!)
}
}
```
### 4. 日志 Tail (`src/cli/bg/tail.ts`)
```typescript
/**
* 跨平台实时日志输出。Ctrl+C 退出,不杀后台进程。
*
* 策略:
* 1. 读取已有内容输出
* 2. fs.watch() 监听文件变化 (主方案)
* 3. 如果 fs.watch 不可靠 (某些 Windows 网络驱动器)fallback 到 500ms 轮询
*/
export async function tailLog(logPath: string): Promise<void>
```
### 5. 引擎选择 (`src/cli/bg/engines/index.ts`)
```typescript
export async function selectEngine(): Promise<BgEngine> {
if (process.platform === 'win32') {
return new DetachedEngine()
}
const tmux = new TmuxEngine()
if (await tmux.available()) {
return tmux
}
return new DetachedEngine()
}
```
### 6. bg.ts 重构
`handleBgFlag()` 改名为 `handleBgStart()`,内部逻辑:
```typescript
export async function handleBgStart(args: string[]): Promise<void> {
const engine = await selectEngine()
const sessionName = `claude-bg-${randomUUID().slice(0, 8)}`
const logPath = join(getClaudeConfigHomeDir(), 'sessions', 'logs', `${sessionName}.log`)
const result = await engine.start({
sessionName,
args: filteredArgs,
env: { ...process.env, CLAUDE_CODE_SESSION_KIND: 'bg', ... },
logPath,
cwd: process.cwd(),
})
console.log(`Background session started: ${result.sessionName}`)
console.log(` Engine: ${result.engineUsed}`)
console.log(` Log: ${result.logPath}`)
console.log(` Use \`claude daemon attach ${result.sessionName}\` to reconnect.`)
}
```
`attachHandler()` 根据 `session.engine` 字段选择引擎:
```typescript
export async function attachHandler(target: string | undefined): Promise<void> {
// ... 找到 session
if (session.engine === 'tmux' && session.tmuxSessionName) {
const tmux = new TmuxEngine()
await tmux.attach(session)
} else {
const detached = new DetachedEngine()
await detached.attach(session)
}
}
```
## SessionEntry 扩展
`sessions/<PID>.json` 新增 `engine` 字段:
```json
{
"pid": 12345,
"engine": "detached",
"logPath": "~/.claude/sessions/logs/claude-bg-a1b2c3d4.log",
"sessionId": "...",
"cwd": "..."
}
```
兼容旧格式: 如果 `engine` 字段缺失,检查 `tmuxSessionName` 存在则为 `tmux`,否则为 `detached`
## 验证清单
- [ ] Windows: `claude daemon bg` 启动后台会话,无 tmux 依赖
- [ ] Windows: `claude daemon attach <name>` 以 tail 模式附着Ctrl+C 退出不杀进程
- [ ] macOS/Linux (有 tmux): 行为与当前一致
- [ ] macOS/Linux (无 tmux): 自动 fallback 到 detached 引擎
- [ ] `claude daemon status` 正确显示 engine 类型
- [ ] 旧格式 session JSON (无 engine 字段) 兼容
- [ ] tsc --noEmit 零错误
- [ ] bun test 通过

View File

@@ -0,0 +1,275 @@
# Task 014: /daemon 命令层级化
> 设计文档: [daemon-restructure-design.md](../features/daemon-restructure-design.md) § 三.1
> 依赖: Task 013 (BgEngine 抽象)
> 分支: `feat/integrate-5-branches`
## 目标
将散落的 `daemon start/stop/status` + `ps/logs/attach/kill` + `--bg` 统一收归 `/daemon` 命名空间,实现 CLI + REPL 双注册。
## 背景
当前这些命令注册在两个互不关联的位置:
- `cli.tsx:203-212`: `daemon [start|status|stop]``daemon/main.ts`
- `cli.tsx:217-246`: `ps|logs|attach|kill|--bg``cli/bg.ts`
需要合并为统一的 `claude daemon <subcommand>` 入口,并新增 REPL `/daemon` 斜杠命令。
## 文件清单
### 新增
| 文件 | 说明 |
|------|------|
| `src/commands/daemon/index.ts` | `/daemon` REPL 斜杠命令注册 (type: local-jsx) |
| `src/commands/daemon/daemon.tsx` | `/daemon` 子命令路由 + status UI 组件 |
### 修改
| 文件 | 变更 |
|------|------|
| `src/entrypoints/cli.tsx` | 统一 daemon 快速路径: `daemon <sub>` 路由到对应 handler。旧命令 `ps/logs/attach/kill` 保留但输出 deprecation 警告后代理 |
| `src/commands.ts` | 注册 `/daemon` 斜杠命令 (feature-gated: DAEMON \|\| BG_SESSIONS) |
| `src/daemon/main.ts` | `daemonMain()` 扩展: 支持 `bg/attach/logs/kill/ps` 子命令 (委托给 bg.ts handlers) |
## 实现方案
### 1. CLI 快速路径统一 (`cli.tsx`)
**改前** (两段独立路由):
```typescript
// 段 1: daemon
if (feature('DAEMON') && args[0] === 'daemon') {
await daemonMain(args.slice(1))
}
// 段 2: bg sessions
if (feature('BG_SESSIONS') && ['ps','logs','attach','kill'].includes(args[0])) {
// ...switch/case
}
```
**改后** (统一入口):
```typescript
// 统一 daemon 入口 — 合并 daemon supervisor + bg sessions
if (
(feature('DAEMON') || feature('BG_SESSIONS')) &&
args[0] === 'daemon'
) {
profileCheckpoint('cli_daemon_path')
const { enableConfigs } = await import('../utils/config.js')
enableConfigs()
const { initSinks } = await import('../utils/sinks.js')
initSinks()
const { daemonMain } = await import('../daemon/main.js')
await daemonMain(args.slice(1))
return
}
// --bg 快捷方式 → daemon bg
if (
feature('BG_SESSIONS') &&
(args.includes('--bg') || args.includes('--background'))
) {
profileCheckpoint('cli_daemon_path')
const { enableConfigs } = await import('../utils/config.js')
enableConfigs()
const bg = await import('../cli/bg.js')
await bg.handleBgStart(args.filter(a => a !== '--bg' && a !== '--background'))
return
}
// 向后兼容: ps/logs/attach/kill → daemon <sub> (deprecated)
if (
feature('BG_SESSIONS') &&
['ps', 'logs', 'attach', 'kill'].includes(args[0] ?? '')
) {
const mapped = args[0] === 'ps' ? 'status' : args[0]
console.error(`[deprecated] Use: claude daemon ${mapped} ${args.slice(1).join(' ')}`.trim())
const { enableConfigs } = await import('../utils/config.js')
enableConfigs()
const { daemonMain } = await import('../daemon/main.js')
await daemonMain([args[0]!, ...args.slice(1)])
return
}
```
### 2. daemonMain 扩展 (`daemon/main.ts`)
```typescript
export async function daemonMain(args: string[]): Promise<void> {
const subcommand = args[0] || 'status'
switch (subcommand) {
// --- Supervisor 管理 ---
case 'start':
await runSupervisor(args.slice(1))
break
case 'stop':
await handleDaemonStop()
break
// --- 会话管理 (委托给 bg.ts) ---
case 'status':
case 'ps':
await showUnifiedStatus() // 新: daemon 状态 + 会话列表
break
case 'bg':
const bg = await import('../cli/bg.js')
await bg.handleBgStart(args.slice(1))
break
case 'attach':
const bg2 = await import('../cli/bg.js')
await bg2.attachHandler(args[1])
break
case 'logs':
const bg3 = await import('../cli/bg.js')
await bg3.logsHandler(args[1])
break
case 'kill':
const bg4 = await import('../cli/bg.js')
await bg4.killHandler(args[1])
break
case '--help': case '-h': case 'help':
printHelp()
break
default:
console.error(`Unknown daemon subcommand: ${subcommand}`)
printHelp()
process.exitCode = 1
}
}
```
### 3. 统一状态面板 (`showUnifiedStatus`)
```typescript
async function showUnifiedStatus(): Promise<void> {
// 1. Daemon supervisor 状态
const daemonResult = queryDaemonStatus()
console.log('=== Daemon Supervisor ===')
switch (daemonResult.status) {
case 'running':
console.log(` Status: running (PID: ${daemonResult.state!.pid})`)
console.log(` Workers: ${daemonResult.state!.workerKinds.join(', ')}`)
break
case 'stopped':
console.log(' Status: stopped')
break
case 'stale':
console.log(' Status: stale (cleaned up)')
break
}
// 2. 后台会话列表
console.log('\n=== Background Sessions ===')
const bg = await import('../cli/bg.js')
await bg.psHandler([])
}
```
### 4. REPL 斜杠命令注册
**`src/commands/daemon/index.ts`**:
```typescript
import type { Command } from '../../commands.js'
import { feature } from 'bun:bundle'
const daemon = {
type: 'local-jsx',
name: 'daemon',
description: 'Manage background sessions and daemon',
argumentHint: '[status|start|stop|bg|attach|logs|kill]',
isEnabled: () => {
if (feature('DAEMON')) return true
if (feature('BG_SESSIONS')) return true
return false
},
load: () => import('./daemon.js'),
} satisfies Command
export default daemon
```
**`src/commands/daemon/daemon.tsx`**:
```typescript
export async function call(
onDone: LocalJSXCommandOnDone,
context: LocalJSXCommandContext,
args: string,
): Promise<React.ReactNode> {
const parts = args.trim().split(/\s+/)
const sub = parts[0] || 'status'
switch (sub) {
case 'status':
case 'ps':
// 调用 showUnifiedStatus捕获输出
// 返回文本结果
break
case 'bg':
// REPL 中启动后台会话
break
case 'start':
case 'stop':
case 'attach':
case 'logs':
case 'kill':
// 委托给对应 handler
break
default:
onDone(`Unknown: ${sub}. Use: status|start|stop|bg|attach|logs|kill`)
return null
}
}
```
**`src/commands.ts`** 添加:
```typescript
// 条件导入
const daemonCmd =
feature('DAEMON') || feature('BG_SESSIONS')
? require('./commands/daemon/index.js').default
: null
// COMMANDS 数组中添加
...(daemonCmd ? [daemonCmd] : []),
```
### 5. 更新 help 文本 (`daemon/main.ts`)
```
Claude Code Daemon — background process management
USAGE
claude daemon [subcommand]
SUBCOMMANDS
status Show daemon and session status (default)
start Start the daemon supervisor
stop Stop the daemon
bg Start a background session
attach Attach to a background session
logs Show session logs
kill Kill a session
help Show this help
REPL
/daemon [subcommand] Same commands available in interactive mode
```
## 验证清单
- [ ] `claude daemon` (无参数) 显示统一状态面板
- [ ] `claude daemon status` 显示 supervisor + 会话列表
- [ ] `claude daemon start/stop` 与当前行为一致
- [ ] `claude daemon bg` 启动后台会话 (调用 BgEngine)
- [ ] `claude daemon attach/logs/kill <target>` 功能正常
- [ ] `claude ps` 输出 deprecation 警告 + 正常工作
- [ ] `claude logs/attach/kill` 同上
- [ ] `claude --bg` 快捷方式正常
- [ ] REPL 中 `/daemon` 可用tab 补全显示
- [ ] REPL 中 `/daemon status` 显示状态信息
- [ ] tsc --noEmit 零错误
- [ ] bun test 通过

View File

@@ -0,0 +1,177 @@
# Task 015: /job 命令层级化
> 设计文档: [daemon-restructure-design.md](../features/daemon-restructure-design.md) § 三.2
> 依赖: 无 (可与 Task 013 并行)
> 分支: `feat/integrate-5-branches`
## 目标
`claude new/list/reply` 收归 `/job` 命名空间,实现 CLI + REPL 双注册。
## 背景
当前 `new`, `list`, `reply` 是顶级 CLI 命令 (`cli.tsx:250-261`),容易与其他命令冲突(特别是 `list` 这种通用词)。需要收归 `claude job <subcommand>` 并新增 REPL `/job` 入口。
## 文件清单
### 新增
| 文件 | 说明 |
|------|------|
| `src/commands/job/index.ts` | `/job` REPL 斜杠命令注册 |
| `src/commands/job/job.tsx` | `/job` 子命令路由 |
### 修改
| 文件 | 变更 |
|------|------|
| `src/entrypoints/cli.tsx` | 新增 `job` 快速路径 + 旧 `new/list/reply` deprecation 代理 |
| `src/commands.ts` | 注册 `/job` 斜杠命令 |
### 不动
| 文件 | 说明 |
|------|------|
| `src/cli/handlers/templateJobs.ts` | 内部 handler 不变,只是被调用方式变了 |
| `src/jobs/state.ts` | job 状态管理不变 |
| `src/jobs/templates.ts` | 模板发现不变 |
| `src/jobs/classifier.ts` | 任务分类器不变 |
## 实现方案
### 1. CLI 快速路径 (`cli.tsx`)
**改后**:
```typescript
// 新: claude job <subcommand>
if (
feature('TEMPLATES') &&
args[0] === 'job'
) {
profileCheckpoint('cli_templates_path')
const { templatesMain } = await import('../cli/handlers/templateJobs.js')
await templatesMain(args.slice(1))
process.exit(0)
}
// 向后兼容 (deprecated)
if (
feature('TEMPLATES') &&
(args[0] === 'new' || args[0] === 'list' || args[0] === 'reply')
) {
console.error(`[deprecated] Use: claude job ${args[0]} ${args.slice(1).join(' ')}`.trim())
profileCheckpoint('cli_templates_path')
const { templatesMain } = await import('../cli/handlers/templateJobs.js')
await templatesMain(args)
process.exit(0)
}
```
### 2. templateJobs.ts 新增 status 子命令
在现有 `switch` 中增加:
```typescript
case 'status':
handleStatus(args.slice(1))
break
```
```typescript
function handleStatus(args: string[]): void {
const jobId = args[0]
if (!jobId) {
console.error('Usage: claude job status <job-id>')
process.exitCode = 1
return
}
const state = readJobState(jobId)
if (!state) {
console.error(`Job not found: ${jobId}`)
process.exitCode = 1
return
}
console.log(`Job: ${state.jobId}`)
console.log(` Template: ${state.templateName}`)
console.log(` Status: ${state.status}`)
console.log(` Created: ${state.createdAt}`)
console.log(` Updated: ${state.updatedAt}`)
}
```
### 3. REPL 斜杠命令
**`src/commands/job/index.ts`**:
```typescript
import type { Command } from '../../commands.js'
import { feature } from 'bun:bundle'
const job = {
type: 'local-jsx',
name: 'job',
description: 'Manage template jobs',
argumentHint: '[list|new|reply|status]',
isEnabled: () => {
if (feature('TEMPLATES')) return true
return false
},
load: () => import('./job.js'),
} satisfies Command
export default job
```
**`src/commands/job/job.tsx`**:
```typescript
export async function call(
onDone: LocalJSXCommandOnDone,
_context: LocalJSXCommandContext,
args: string,
): Promise<React.ReactNode> {
const parts = args.trim().split(/\s+/)
const sub = parts[0] || 'list'
// 委托给 templatesMain
const { templatesMain } = await import('../../cli/handlers/templateJobs.js')
// 捕获 console.log 输出作为结果返回给 REPL
const lines: string[] = []
const origLog = console.log
const origError = console.error
console.log = (...a: unknown[]) => lines.push(a.join(' '))
console.error = (...a: unknown[]) => lines.push(a.join(' '))
try {
await templatesMain([sub, ...parts.slice(1)])
} finally {
console.log = origLog
console.error = origError
}
onDone(lines.join('\n') || 'Done.', { display: 'system' })
return null
}
```
### 4. commands.ts 注册
```typescript
const jobCmd = feature('TEMPLATES')
? require('./commands/job/index.js').default
: null
// COMMANDS 数组:
...(jobCmd ? [jobCmd] : []),
```
## 验证清单
- [ ] `claude job list` 列出模板
- [ ] `claude job new <template>` 创建任务
- [ ] `claude job reply <id> <text>` 回复任务
- [ ] `claude job status <id>` 显示任务状态
- [ ] `claude job` (无参数) 等同于 `claude job list`
- [ ] `claude new/list/reply` 输出 deprecation 警告 + 正常工作
- [ ] REPL 中 `/job` 可用
- [ ] REPL 中 `/job list` 显示模板列表
- [ ] tsc --noEmit 零错误
- [ ] bun test 通过

View File

@@ -0,0 +1,123 @@
# Task 016: 向后兼容 + 测试
> 设计文档: [daemon-restructure-design.md](../features/daemon-restructure-design.md) § 五
> 依赖: Task 014, Task 015
> 分支: `feat/integrate-5-branches`
## 目标
确保旧命令向后兼容 (deprecation 警告 + 正常代理),并为重构后的命令结构编写测试。
## 文件清单
### 新增
| 文件 | 说明 |
|------|------|
| `src/daemon/__tests__/daemonMain.test.ts` | daemonMain 子命令路由测试 |
| `src/cli/bg/__tests__/engine.test.ts` | BgEngine 选择逻辑测试 |
| `src/cli/bg/__tests__/detached.test.ts` | DetachedEngine 启动/停止测试 |
| `src/cli/bg/__tests__/tail.test.ts` | 日志 tail 功能测试 |
### 修改
| 文件 | 变更 |
|------|------|
| `src/entrypoints/cli.tsx` | 确认 deprecation 路径正确代理 |
## 实现方案
### 1. 向后兼容矩阵
| 旧命令 | 新命令 | 处理方式 |
|--------|--------|---------|
| `claude ps` | `claude daemon status` | stderr 输出 `[deprecated] Use: claude daemon status`,然后执行 |
| `claude logs <x>` | `claude daemon logs <x>` | 同上 |
| `claude attach <x>` | `claude daemon attach <x>` | 同上 |
| `claude kill <x>` | `claude daemon kill <x>` | 同上 |
| `claude --bg` | `claude daemon bg` | 保留为快捷方式,**不** deprecate (太常用) |
| `claude new <t>` | `claude job new <t>` | stderr deprecation + 执行 |
| `claude list` | `claude job list` | stderr deprecation + 执行 |
| `claude reply <id>` | `claude job reply <id>` | stderr deprecation + 执行 |
**关键**: deprecation 输出到 stderr 而非 stdout不影响脚本管道。
### 2. 测试计划
#### 2.1 daemonMain 路由测试
```typescript
describe('daemonMain', () => {
test('无参数默认 status', async () => { ... })
test('start 调用 runSupervisor', async () => { ... })
test('stop 调用 handleDaemonStop', async () => { ... })
test('bg 委托给 bg.handleBgStart', async () => { ... })
test('attach 委托给 bg.attachHandler', async () => { ... })
test('logs 委托给 bg.logsHandler', async () => { ... })
test('kill 委托给 bg.killHandler', async () => { ... })
test('未知子命令设置 exitCode=1', async () => { ... })
})
```
#### 2.2 引擎选择测试
```typescript
describe('selectEngine', () => {
test('win32 返回 DetachedEngine', async () => { ... })
test('darwin + tmux 可用返回 TmuxEngine', async () => { ... })
test('darwin + tmux 不可用返回 DetachedEngine', async () => { ... })
test('linux + tmux 可用返回 TmuxEngine', async () => { ... })
})
```
#### 2.3 DetachedEngine 测试
```typescript
describe('DetachedEngine', () => {
test('available 始终返回 true', async () => { ... })
test('start 创建 detached 子进程并写入日志', async () => { ... })
test('start 返回的 PID 文件存在', async () => { ... })
})
```
#### 2.4 Tail 测试
```typescript
describe('tailLog', () => {
test('输出已有日志内容', async () => { ... })
test('追加内容时实时输出', async () => { ... })
test('SIGINT 退出 tail', async () => { ... })
})
```
### 3. 集成验证脚本
可选: 在 `scripts/` 下添加一个手动验证脚本:
```bash
#!/bin/bash
# scripts/verify-daemon-restructure.sh
echo "=== 1. claude daemon status ==="
bun run dev -- daemon status
echo "=== 2. claude daemon bg (should start) ==="
bun run dev -- daemon bg --help
echo "=== 3. claude ps (deprecated) ==="
bun run dev -- ps 2>&1 | head -1
echo "=== 4. claude job list ==="
bun run dev -- job list
echo "=== 5. claude list (deprecated) ==="
bun run dev -- list 2>&1 | head -1
```
## 验证清单
- [ ] 旧命令全部正常工作 (仅多一行 stderr 警告)
- [ ] `--bg` 保持无警告
- [ ] 所有新增测试通过
- [ ] 现有 2695 个测试无回归
- [ ] tsc --noEmit 零错误
- [ ] 手动在 Windows + macOS/Linux 上验证关键路径

View File

@@ -0,0 +1,155 @@
# 遥测与远程配置下发系统审计(除 Sentry 外)
## 1. Datadog 日志
**文件**: `src/services/analytics/datadog.ts`
- **端点**: 通过环境变量 `DATADOG_LOGS_ENDPOINT` 配置(默认为空,即禁用)
- **客户端 token**: 通过环境变量 `DATADOG_API_KEY` 配置(默认为空,即禁用)
- **行为**: 批量发送日志15s flush 间隔100 条上限),仅限 1P直连 Anthropic API用户
- **事件白名单**: `tengu_*` 系列事件启动、错误、OAuth、工具调用等 ~35 种)
- **基线数据**: 收集 model、platform、arch、version、userBucket用户 hash 到 30 个桶)等
- **仅限**: `NODE_ENV === 'production'`
- **配置示例**: `DATADOG_LOGS_ENDPOINT=https://http-intake.logs.datadoghq.com/api/v2/logs DATADOG_API_KEY=xxx bun run dev`
## 2. 1P 事件日志BigQuery
**文件**: `src/services/analytics/firstPartyEventLogger.ts` + `firstPartyEventLoggingExporter.ts`
- **端点**: `https://api.anthropic.com/api/event_logging/batch`staging 可切换)
- **行为**: 使用 OpenTelemetry SDK 的 `BatchLogRecordProcessor`,批量导出到 Anthropic 自有的 BQ 管道
- **数据**: 完整事件 metadatasession、model、env context、用户数据、subscription type 等)
- **弹性**: 本地磁盘持久化失败事件JSONL二次退避重试最多 8 次尝试
- **Proto schema**: 事件序列化为 `ClaudeCodeInternalEvent` / `GrowthbookExperimentEvent` protobuf 格式
- **Auth fallback**: 401 时自动去掉 auth header 重试
## 3. GrowthBook 远程 Feature Flags / 动态配置
**文件**: `src/services/analytics/growthbook.ts`
- **服务端**: `https://api.anthropic.com/`remote eval 模式)
- **行为**: 启动时拉取全量 feature flags每 6h外部用户/ 20minant定时刷新
- **磁盘缓存**: feature values 写入 `~/.claude.json``cachedGrowthBookFeatures`
- **用途**:
- 控制 Datadog 开关(`tengu_log_datadog_events`
- 控制事件采样率(`tengu_event_sampling_config`
- 控制 sink killswitch`tengu_frond_boric`
- 控制 BQ batch 配置(`tengu_1p_event_batch_config`
- 控制版本上限/自动更新 kill switch
- 控制远程管理设置的安全检查 gate
- **用户属性**: 发送 deviceId, sessionId, organizationUUID, accountUUID, email, subscriptionType 等
## 4. Remote Managed Settings企业远程配置下发
**文件**: `src/services/remoteManagedSettings/index.ts`
- **端点**: `{BASE_API_URL}/api/claude_code/settings`
- **行为**: 企业用户配置下发,支持 ETag/304 缓存,每小时后台轮询
- **安全**: 变更包含"危险设置"时弹窗让用户确认
- **适用**: API key 用户全部可拉取OAuth 用户仅 Enterprise/C4E/Team
- **Fail-open**: 请求失败时使用本地缓存,无缓存则跳过
## 5. Settings Sync设置同步
**文件**: `src/services/settingsSync/index.ts`
- **端点**: `{BASE_API_URL}/api/claude_code/user_settings`
- **行为**: CLI 上传本地设置/memory 到远程CCR 模式从远程下载
- **同步内容**: userSettings、userMemory、projectSettings、projectMemory
- **Feature gate**: `UPLOAD_USER_SETTINGS` / `DOWNLOAD_USER_SETTINGS`
- **文件大小限制**: 500KB/文件
## 6. OpenTelemetry 三方遥测
**文件**: `src/utils/telemetry/instrumentation.ts`
- **行为**: 完整的 OTEL SDK 初始化,支持 metrics / logs / traces 三种信号
- **协议**: gRPC / http-json / http-protobuf通过 `OTEL_EXPORTER_OTLP_PROTOCOL` 选择)
- **exporter**: console / otlp / prometheus
- **触发**: `CLAUDE_CODE_ENABLE_TELEMETRY=1` 环境变量
- **增强 trace**: `feature('ENHANCED_TELEMETRY_BETA')` + GrowthBook gate `enhanced_telemetry_beta`
## 7. BigQuery Metrics Exporter内部指标
**文件**: `src/utils/telemetry/bigqueryExporter.ts`
- **端点**: `https://api.anthropic.com/api/claude_code/metrics`
- **行为**: 定期5min 间隔)导出 OTel metrics 到内部 BQ
- **适用**: API 客户、C4E/Team 订阅者
- **组织级 opt-out**: 通过 `checkMetricsEnabled()` API 查询(见下方第 8 项)
## 8. 组织级 Metrics Opt-out 查询
**文件**: `src/services/api/metricsOptOut.ts`
- **端点**: `https://api.anthropic.com/api/claude_code/organizations/metrics_enabled`
- **行为**: 查询组织是否启用了 metrics二级缓存内存 1h + 磁盘 24h
- **作用**: 控制 BigQuery metrics exporter 是否导出
## 9. Startup Profiling
**文件**: `src/utils/startupProfiler.ts`
- **行为**: 采样启动性能数据100% ant / 0.5% 外部),通过 `logEvent('tengu_startup_perf')` 上报
- **详细模式**: `CLAUDE_CODE_PROFILE_STARTUP=1` 输出完整性能报告到文件
## 10. Beta Session Tracing
**文件**: `src/utils/telemetry/betaSessionTracing.ts`
- **行为**: 详细调试 trace发送 system prompt、model output、tool schema 等
- **触发**: `ENABLE_BETA_TRACING_DETAILED=1` + `BETA_TRACING_ENDPOINT`
- **外部用户**: SDK/headless 模式自动启用,交互模式需要 GrowthBook gate `tengu_trace_lantern`
## 11. Bridge Poll Config远程轮询间隔配置
**文件**: `src/bridge/pollConfig.ts`
- **行为**: 从 GrowthBook 拉取 bridge 轮询间隔配置(`tengu_bridge_poll_interval_config`
- **控制**: 单会话和多会话的各种 poll interval
## 12. Plugin/MCP 遥测
**文件**: `src/utils/plugins/fetchTelemetry.ts`
- **行为**: 记录 plugin/marketplace 的网络请求安装计数、marketplace clone/pull 等)
- **事件**: `tengu_plugin_remote_fetch`,包含 host已脱敏、outcome、duration
---
## 全局禁用方式
```bash
# 禁用所有遥测Datadog + 1P + 调查问卷)
DISABLE_TELEMETRY=1
# 更激进禁用所有非必要网络包括自动更新、grove、release notes 等)
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
# 3P 提供商自动禁用
CLAUDE_CODE_USE_BEDROCK=1 # 或 VERTEX/FOUNDRY
```
`src/utils/privacyLevel.ts` 是集中控制点,三个级别:`default < no-telemetry < essential-traffic`
---
## 数据流架构
```
用户操作 → logEvent()
sink.ts (路由层)
↙ ↘
trackDatadogEvent() logEventTo1P()
↓ ↓
Datadog HTTP API OTel BatchLogRecordProcessor
(us5.datadoghq.com) ↓
FirstPartyEventLoggingExporter
api.anthropic.com/api/event_logging/batch
BigQuery (ClaudeCodeInternalEvent proto)
```
GrowthBook 作为独立通道,同时驱动上述两个 sink 的开关和配置。

View File

@@ -0,0 +1,88 @@
# OpenClaw Autonomy Baseline Test Spec
## Purpose
This test spec locks the current behavior of the existing trigger and context layers before any formal autonomy-subsystem implementation begins.
At this stage, production code is read-only. Only test files, fixtures, and planning documents may change.
## Goal
Establish a stable baseline around the parts of `Claude-code-bast` that later autonomy work is most likely to touch:
- proactive state handling
- cron task storage semantics
- cron scheduler helper semantics
- user-context cache and `CLAUDE.md` injection behavior
## Out of Scope for This Baseline Round
- New authority behavior (`AGENTS.md` / `HEARTBEAT.md`)
- New detached-run ledger behavior
- New flow behavior
- UI redesign
## Files Under Baseline Protection
- `src/proactive/index.ts`
- `src/utils/cronTasks.ts`
- `src/utils/cronScheduler.ts`
- `src/context.ts`
## Test Files Added In This Round
- `src/proactive/__tests__/state.baseline.test.ts`
- `src/commands/__tests__/proactive.baseline.test.ts`
- `src/utils/__tests__/cronTasks.baseline.test.ts`
- `src/utils/__tests__/cronScheduler.baseline.test.ts`
- `src/__tests__/context.baseline.test.ts`
## Baseline Assertions
### Proactive state
1. Activating proactive mode sets active state and activation source.
2. Pausing proactive mode suppresses `shouldTick()` and clears `nextTickAt`.
3. Blocking context suppresses `shouldTick()` and clears `nextTickAt`.
4. Subscribers are notified on state transitions.
5. The `/proactive` command enables proactive mode and emits the expected hidden reminder.
6. The `/proactive` command disables proactive mode on the second invocation.
### Cron task storage
1. Session-only cron tasks remain in memory only.
2. Durable cron tasks are persisted to `.claude/scheduled_tasks.json`.
3. Daemon-style `dir`-scoped reads exclude session-only cron tasks.
4. `removeCronTasks()` without `dir` can remove session-only tasks.
5. `removeCronTasks()` with `dir` does not mutate session-only task storage.
### Cron scheduler helpers
1. `isRecurringTaskAged()` preserves current aging semantics.
2. `buildMissedTaskNotification()` preserves the current AskUserQuestion safety wording.
3. `buildMissedTaskNotification()` preserves code-fence hardening for prompt bodies that contain backticks.
### User context caching
1. `getUserContext()` includes `currentDate`.
2. `getUserContext()` includes mocked `claudeMd` content when memory loading is enabled.
3. `CLAUDE_CODE_DISABLE_CLAUDE_MDS` suppresses `claudeMd`.
4. `setSystemPromptInjection()` clears the memoized user-context cache.
5. `getSystemContext()` reflects the injection after cache invalidation.
## Remaining Baseline Gaps
The following areas are intentionally deferred because they require higher-cost harnessing and should still avoid production-code changes:
1. `useScheduledTasks.ts` hook-level runtime behavior
2. `src/cli/print.ts` full headless scheduler loop behavior
3. `useProactive.ts` hook timer behavior
4. end-to-end queue interaction between proactive ticks and `SleepTool`
## Acceptance
This baseline round is complete when:
1. The four new test files pass.
2. No production source files are modified.
3. The tests are stable enough to serve as a pre-implementation guardrail.

Some files were not shown because too many files have changed in this diff Show More