mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-15 21:05:51 +00:00
* docs: 修复文档巡检发现的 4 处错误 - daemon.md: 反映实际实现状态(supervisor/worker 已实现而非 stub) - bridge-mode.md: API 操作数量从 7 修正为 9 - web-search-tool.md: 文件路径从 src/tools/ 修正为 packages/builtin-tools/src/tools/ - remote-control-self-hosting.md: 补充缺失的 RCS_WS_IDLE_TIMEOUT 和 RCS_WS_KEEPALIVE_INTERVAL 配置项 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 Safety 和 Context 文档中的代码引用和类型错误 - permission-model: 修正规则来源从"五层"到八层,优先级顺序对齐代码 - permission-model: PermissionUpdate 类型改为实际的 addRules/replaceRules 等 - permission-model: 补充 acceptEdits 和 dontAsk 两种权限模式 - permission-model: DENIAL_LIMITS 字段名对齐实际代码 - plan-mode: 工具路径从 src/tools/ 改为 packages/builtin-tools/src/tools/ - compaction: 修正 COMPACTABLE_TOOLS 和 POST_COMPACT_* 的行号 - project-memory: 修正 ENTRYPOINT_NAME 常量的行号 - system-prompt: 修正 SystemPrompt 类型定义文件路径和多个行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复 introduction 文档中的错误路径和行号引用 - why-this-whitepaper.mdx: BashTool 路径从 src/tools/ 修正为 packages/builtin-tools/src/tools/ - what-is-claude-code.mdx: 移除不存在的 Azure provider,改为实际的 7 种 provider - architecture-overview.mdx: State 类型行号从 204 修正为 207 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复 conversation/features 文档中的错误 - streaming.mdx: queryStreamRaw → queryModelWithStreaming 函数名修正 - streaming.mdx: Azure 提供商不存在,替换为实际 7 个提供商 - debug-mode.mdx: --inspect-wait 描述错误,实际使用 BUN_INSPECT 环境变量 - buddy.mdx: 补充缺失的 companionReact.ts、CompanionCard.tsx、index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修复文档巡检中的源码引用错误 - feature-flags.mdx: 修正 feature() 兜底描述,实际从 bun:bundle 导入而非 cli.tsx:3 内联 - feature-flags.mdx: 修正工具 require 路径为 @claude-code-best/builtin-tools 包路径 - ant-only-world.mdx: 修正 tools.ts 中 require 路径为包路径 - ant-only-world.mdx: 修正 INTERNAL_ONLY_COMMANDS 行号 (267-295) 和数量 (24+) - skills.mdx: 修正 COMMANDS memoize 行号 258 → 299 - mcp-protocol.mdx: 修正 fetchToolsForClient LRU 缓存上限 20 → 100 - streaming.mdx: 修正流式事件引用 - file-operations.mdx: 修正工具路径引用 - search-and-navigation.mdx: 修正搜索工具引用 - shell-execution.mdx: 修正 shell 工具引用 - buddy.mdx: 补充缺失的 frontmatter 字段 - debug-mode.mdx: 修正调试模式描述 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 tools/agent 文档中的文件路径和行号引用 - 修正 TodoWriteTool、AgentTool、ToolSearchTool 等工具路径 src/tools/ → packages/builtin-tools/src/tools/ - 更新 Tool.ts、tools.ts、BashTool.tsx 中过时的行号引用 - 修正 WebSearchTool/WebFetchTool/EnterWorktreeTool/ExitWorktreeTool 路径 - 修正 AgentTool.tsx 中多行行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature 文档中的文件路径和行号引用 - ultraplan.md: 更新文件行数(525/349/127) - fork-subagent.md: 路径迁移 src/tools/ → packages/builtin-tools/ - mcp-skills.md: 修正 getMcpSkillCommands 行号 547→604,client.ts 行号 117→129 - kairos.md: 修正 getBriefSection/getProactiveSection 行号 - proactive.md: 修正 getProactiveSection 行号 860→864 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正顶层文档中的路径迁移和行号引用 - auto-updater.md: config.ts 行号 1735→1737,标注未接入启动流程的函数 - external-dependencies.md: WebSearchTool/WebFetchTool 路径迁移到 builtin-tools 包,Vertex 行号修正 - lsp-integration.md: LSPTool 路径从 src/tools/ 迁移到 packages/builtin-tools/ - stub-recovery-design-1-4.md: 修正 Windows 绝对路径链接为标准代码引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 task 文档中的文件扩展名和路径引用 - task-004: AssistantSessionChooser.ts → .tsx, assistant.ts → .tsx - task-003: cli.tsx 行号 249→272, markdownConfigLoader.ts 行号 29→35 - lan-pipes: SendMessageTool 路径迁移到 packages/builtin-tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 补充 computer-use-tools-reference 缺失的 Windows 工具 添加遗漏的 open_terminal 和 activate_window 两个 Windows 专属工具, 修正工具总数 37→39,Windows 工具数 10→12。 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 audit/bash-classifier/token-budget/tree-sitter 文档 - feature-flags-audit: ScheduleCronTool 路径迁移、DAEMON 状态更新为 COMPLETE、assistant 文件标记已补全、UDS 标记已实现 - bash-classifier: BashPermissionRequest 文件路径修正、withRetry 行号移除 - token-budget: attachments.ts 行号范围修正 - tree-sitter-bash: bashPermissions.ts 路径迁移到 packages/builtin-tools Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 langfuse-monitoring AgentTool 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 bridgeApi 行号和 Tool.ts 行号引用 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 Safety/Extensibility 文档中的工具路径迁移和行号引用 - sandbox.mdx: shouldUseSandbox.ts 和 bashPermissions.ts 路径迁移至 packages/builtin-tools - why-safety-matters.mdx: bashPermissions.ts 路径迁移(3 处) - plan-mode.mdx: EnterPlanModeTool/prompt.ts 路径迁移 - auto-mode.mdx: Auto mode 指令行号 3464→3481 - hooks.mdx: AgentTool/runAgent.ts 路径迁移 - skills.mdx: SkillTool.ts 路径迁移 - custom-agents.mdx: Agent built-in 目录和 exploreAgent.ts 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 internals 文档引用计数和路径 - ant-only-world: USER_TYPE 引用计数 465→410+,工具路径迁移到 builtin-tools - growthbook-ab-testing: growthbook.ts 行数 1156→1258 - hidden-features: 语音模式状态更新(audio-napi 已恢复) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正工具文档中的行号引用 - sub-agents: AgentTool.call 入口行号 340→387 - shell-execution: ShellCommand onTimeout 行号 129→144 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature 文档中的状态、路径和计数 - all-features-guide: 修正 feature flag 启用范围(dev only vs dev+build) - tier3-stubs: 大量状态修正(stub→已实现),缩减过时条目 - workflow-scripts: 路径迁移到 builtin-tools,状态更新 - web-browser-tool: 工具状态缺失→已实现,路径迁移 - context-collapse: CtxInspectTool 状态缺失→已实现 - computer-use: 行号引用更新,平台分发描述修正 - computer-use-tools-reference: 工具数 39→38 - voice-mode: voiceModeEnabled 行数 55→54 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 更新 the-loop 查询循环行号引用 query.ts 代码变更后终止原因行号整体偏移约 40 行 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 补充 feature-flags-audit 完整 build 默认 feature 列表 添加 ULTRATHINK/LODESTONE/ACP/DAEMON 等 19 个缺失的 build 默认 feature, 修正 dev-only 特征标注(UDS_INBOX/LAN_PIPES/BG_SESSIONS/TEMPLATES) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit ConfigTool 路径迁移 ConfigTool 路径从 src/tools/ 迁移到 packages/builtin-tools/src/tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit BashTool 路径迁移 BashTool 路径从 src/tools/ 迁移到 packages/builtin-tools/src/tools/ Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 修正 feature-flags-audit SkillTool 路径迁移 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: 更新 feature-flags-audit WorkflowTool 状态为已实现 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
169 lines
7.1 KiB
Plaintext
169 lines
7.1 KiB
Plaintext
---
|
||
title: "命令执行工具 - BashTool 安全设计与实现"
|
||
description: "从源码角度解析 Claude Code BashTool:只读命令判定、AST 安全解析、自动后台化、输出截断和专用工具 vs shell 命令的设计权衡。"
|
||
keywords: ["Bash 工具", "命令执行", "Shell 执行", "安全命令", "AI 执行命令"]
|
||
---
|
||
|
||
{/* 本章目标:从源码角度揭示 BashTool 的安全设计、执行链路和关键工程决策 */}
|
||
|
||
## 执行链路总览
|
||
|
||
一条 Bash 命令从 AI 决策到实际执行的完整路径:
|
||
|
||
```
|
||
AI 生成 tool_use: { command: "npm test" }
|
||
↓
|
||
BashTool.validateInput() ← 基础输入校验
|
||
↓
|
||
BashTool.checkPermissions() ← 权限检查(详见安全体系章节)
|
||
├── isReadOnly()? → 自动 allow(只读命令免审批)
|
||
├── bashToolHasPermission() ← AST 解析 + 语义检查 + 规则匹配
|
||
└── 未匹配 → 弹窗确认
|
||
↓
|
||
BashTool.call() → runShellCommand()
|
||
↓
|
||
shouldUseSandbox(input) ← 是否需要沙箱包裹
|
||
↓
|
||
Shell.exec(command, { shouldUseSandbox, shouldAutoBackground })
|
||
↓
|
||
spawn(wrapped_command) ← 实际进程创建
|
||
```
|
||
|
||
## 只读命令的判定:为什么 Read 免审批而 Bash 不一定
|
||
|
||
BashTool 的 `isReadOnly()` 方法(`packages/builtin-tools/src/tools/BashTool/BashTool.tsx:655`)决定一条命令是否被视为"只读":
|
||
|
||
```typescript
|
||
isReadOnly(input) {
|
||
const compoundCommandHasCd = commandHasAnyCd(input.command)
|
||
const result = checkReadOnlyConstraints(input, compoundCommandHasCd)
|
||
return result.behavior === 'allow'
|
||
}
|
||
```
|
||
|
||
判定逻辑基于 4 个命令集合(`BashTool.tsx:120-166`):
|
||
|
||
| 集合 | 命令 | 性质 |
|
||
|------|------|------|
|
||
| `BASH_SEARCH_COMMANDS` | find, grep, rg, ag, ack, locate, which, whereis | 搜索类 |
|
||
| `BASH_READ_COMMANDS` | cat, head, tail, wc, stat, file, jq, awk, sort, uniq... | 读取/分析类 |
|
||
| `BASH_LIST_COMMANDS` | ls, tree, du | 列表类 |
|
||
| `BASH_SEMANTIC_NEUTRAL_COMMANDS` | echo, printf, true, false, : | 语义中性(不影响判定) |
|
||
|
||
对于复合命令(`ls dir && echo "---" && ls dir2`),系统拆分后逐段检查——**所有非中性段都必须属于上述集合**,整条命令才被视为只读。
|
||
|
||
```typescript
|
||
// BashTool.tsx — 简化的判定逻辑
|
||
for (const part of partsWithOperators) {
|
||
if (BASH_SEMANTIC_NEUTRAL_COMMANDS.has(baseCommand)) continue // 跳过中性段
|
||
if (!isPartSearch && !isPartRead && !isPartList) {
|
||
return { isSearch: false, isRead: false, isList: false } // 有任何一段不通过 → 非只读
|
||
}
|
||
}
|
||
```
|
||
|
||
## AST 安全解析:tree-sitter bash 解析
|
||
|
||
`preparePermissionMatcher()`(`BashTool.tsx:663`)在权限检查前用 `parseForSecurity()` 解析命令结构:
|
||
|
||
```typescript
|
||
async preparePermissionMatcher({ command }) {
|
||
const parsed = await parseForSecurity(command)
|
||
if (parsed.kind !== 'simple') {
|
||
return () => true // 解析失败 → fail-safe,触发所有 hook
|
||
}
|
||
// 提取子命令列表,剥离 VAR=val 前缀
|
||
const subcommands = parsed.commands.map(c => c.argv.join(' '))
|
||
return pattern => {
|
||
return subcommands.some(cmd => matchWildcardPattern(pattern, cmd))
|
||
}
|
||
}
|
||
```
|
||
|
||
关键安全点:对于复合命令 `ls && git push`,解析后拆分为 `["ls", "git push"]`,确保 `git push` 不会因为前半段是只读命令而绕过权限检查。解析失败时采用 fail-safe 策略——假设不安全,触发所有安全 hook。
|
||
|
||
## 超时控制:分级策略
|
||
|
||
```
|
||
用户指定 timeout → 直接使用
|
||
↓ 未指定
|
||
getDefaultTimeoutMs()
|
||
├── 默认上限:120,000ms(2 分钟)
|
||
└── 最大上限:600,000ms(10 分钟,用户显式设置时)
|
||
```
|
||
|
||
超时后系统不会直接杀进程——`ShellCommand`(`src/utils/ShellCommand.ts:144`)通过 `onTimeout` 回调通知调用方,由调用方决定是终止还是后台化。
|
||
|
||
## 自动后台化
|
||
|
||
长时间运行的命令可以自动转为后台任务,不阻塞 AI 的 agentic loop:
|
||
|
||
```typescript
|
||
// BashTool.tsx:1158
|
||
const shouldAutoBackground = !isBackgroundTasksDisabled
|
||
&& isAutobackgroundingAllowed(command)
|
||
```
|
||
|
||
自动后台化的完整链路:
|
||
|
||
```
|
||
命令开始执行
|
||
↓ 进度轮询
|
||
15 秒内未完成(ASSISTANT_BLOCKING_BUDGET_MS)
|
||
↓
|
||
检查 isAutobackgroundingAllowed(command)
|
||
↓ 允许
|
||
将前台任务转为后台任务(backgroundExistingForegroundTask)
|
||
↓
|
||
shellCommand.onTimeout → spawnBackgroundTask()
|
||
↓
|
||
返回 taskId 给 AI,AI 可以继续做其他事
|
||
↓
|
||
后台任务完成后通过通知机制汇报结果
|
||
```
|
||
|
||
主线程 Agent 有 15 秒的阻塞预算——超过这个时间,系统自动将命令后台化。这防止了一个 `npm install` 阻塞整个 agentic loop 数分钟。
|
||
|
||
## 输出截断策略
|
||
|
||
命令输出过长时会触发截断,防止把海量日志塞进 AI 的上下文窗口:
|
||
|
||
| 截断点 | 位置 | 行为 |
|
||
|--------|------|------|
|
||
| `maxResultSizeChars` | 工具级(通常 100K 字符) | 超长输出在写入消息前截断 |
|
||
| 进度轮询截断 | `onProgress` 回调 | 只传递最后几行作为进度显示 |
|
||
| `totalBytes` 标记 | `isIncomplete` 参数 | 告知 AI 输出被截断 |
|
||
|
||
截断不是简单砍尾——`isIncomplete` 标记确保 AI 知道输出不完整,可以决定是否需要用更精确的命令重新获取。
|
||
|
||
## 为什么用专用工具而不是直接调 shell
|
||
|
||
Claude Code 为文件读写、代码搜索等操作提供了专用工具(Read、Grep、Glob),而不是让 AI 用 `cat`、`grep` 等 shell 命令。这不仅是用户体验的选择,更是架构层面的设计决策:
|
||
|
||
| 维度 | 专用工具 | Bash 命令 |
|
||
|------|---------|----------|
|
||
| **权限粒度** | `Read` 是只读操作 → 自动放行 | `Bash: cat file` 需要审批整条命令(cat 在只读集合中但走不同路径) |
|
||
| **输出结构化** | 返回结构化数据,UI 可渲染 diff、高亮 | 纯文本输出,无渲染优化 |
|
||
| **性能优化** | 文件缓存、分页、token 预算控制 | 每次都是新进程,无缓存 |
|
||
| **并发安全** | `isConcurrencySafe()` 返回 `true` → 可并行执行 | Bash 命令可能有副作用,串行执行 |
|
||
| **安全审计** | 工具名精确匹配权限规则 | 需 AST 解析命令结构后匹配 |
|
||
|
||
`isConcurrencySafe()`(`BashTool.tsx:652`)是一个常被忽视但重要的设计——只有只读命令可以在 agentic loop 中并行执行,有副作用的命令必须串行,防止竞态条件。
|
||
|
||
## 进度反馈的流式设计
|
||
|
||
BashTool 的命令执行是流式的,通过 `onProgress` 回调逐行推送输出:
|
||
|
||
```
|
||
runShellCommand()
|
||
├── Shell.exec() 启动子进程
|
||
├── 每秒轮询输出文件
|
||
├── onProgress(lastLines, allLines, totalLines, totalBytes, isIncomplete)
|
||
│ ├── 更新 lastProgressOutput / fullOutput
|
||
│ └── resolveProgress() → 唤醒 generator yield
|
||
├── yield { type: 'progress', output, fullOutput, elapsedTimeSeconds }
|
||
└── return { code, stdout, interrupted, ... }
|
||
```
|
||
|
||
UI 层通过 `useToolCallProgress` hook 实时展示命令输出。`resolveProgress()` 信号机制让 generator 在有新数据时才 yield,避免了忙等待。
|