* 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>
7.6 KiB
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 | nullfindTokenBudgetPositions(text)— 返回匹配位置数组,用于输入框高亮getBudgetContinuationMessage(pct, turnTokens, budget)— 生成继续消息
2. 状态层 — src/bootstrap/state.ts
模块级单例变量追踪当前 turn 的预算状态:
outputTokensAtTurnStart — 本 turn 开始时的累计 output token 数
currentTurnTokenBudget — 本 turn 的预算目标(null 表示无预算)
budgetContinuationCount — 本 turn 已自动续接的次数
关键函数:
getTotalOutputTokens()— 从STATE.modelUsage汇总所有模型的 output tokensgetTurnOutputTokens()—getTotalOutputTokens() - outputTokensAtTurnStartsnapshotOutputTokensForTurn(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 message(nudge)
- 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:
{
"type": "output_token_usage",
"turn": 125000, // 本 turn 产出
"session": 350000, // 会话总产出
"budget": 500000 // 预算目标
}
让模型能看到自己的进度。
四、关键设计决策
- 90% 阈值而非 100%:在
COMPLETION_THRESHOLD = 0.9处停止,避免最后一轮 nudge 产生远超预算的 token - 收益递减保护:连续 3 轮 nudge 后如果每轮产出 < 500 tokens,判定模型已无实质进展,提前终止
- 子 agent 豁免:AgentTool 内部的子任务不做预算检查,避免子任务重复触发续接
- 无条件缓存系统提示:预算 prompt 始终注入(不随预算变化 toggle),避免每次切换预算导致 ~20K token 的 cache miss
- 用户取消清预算:按 Escape 取消时调用
snapshotOutputTokensForTurn(null),防止残留预算触发续接
五、使用方式
# 启用 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:3830-3844 |
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 | 输入高亮 |