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>
This commit is contained in:
claude-code-best
2026-04-13 09:52:05 +08:00
committed by GitHub
parent bbb8b613a9
commit 2fb1c9dcd8
559 changed files with 9346 additions and 1837 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,181 @@
import type { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs'
import * as React from 'react'
import { SubAgentProvider } from 'src/components/CtrlOToExpand.js'
import { FallbackToolUseErrorMessage } from 'src/components/FallbackToolUseErrorMessage.js'
import { FallbackToolUseRejectedMessage } from 'src/components/FallbackToolUseRejectedMessage.js'
import type { z } from 'zod/v4'
import type { Command } from 'src/commands.js'
import { Byline } from '@anthropic/ink'
import { Message as MessageComponent } from 'src/components/Message.js'
import { MessageResponse } from 'src/components/MessageResponse.js'
import { Box, Text } from '@anthropic/ink'
import type { Tools } from 'src/Tool.js'
import type { ProgressMessage } from 'src/types/message.js'
import { buildSubagentLookups, EMPTY_LOOKUPS } from 'src/utils/messages.js'
import { plural } from 'src/utils/stringUtils.js'
import type { inputSchema, Output, Progress } from './SkillTool.js'
type Input = z.infer<ReturnType<typeof inputSchema>>
const MAX_PROGRESS_MESSAGES_TO_SHOW = 3
const INITIALIZING_TEXT = 'Initializing…'
export function renderToolResultMessage(output: Output): React.ReactNode {
// Handle forked skill result
if ('status' in output && output.status === 'forked') {
return (
<MessageResponse height={1}>
<Text>
<Byline>{['Done']}</Byline>
</Text>
</MessageResponse>
)
}
const parts: string[] = ['Successfully loaded skill']
// Show tools count (only for inline skills)
if (
'allowedTools' in output &&
output.allowedTools &&
output.allowedTools.length > 0
) {
const count = output.allowedTools.length
parts.push(`${count} ${plural(count, 'tool')} allowed`)
}
// Show model if non-default (only for inline skills)
if ('model' in output && output.model) {
parts.push(output.model)
}
return (
<MessageResponse height={1}>
<Text>
<Byline>{parts}</Byline>
</Text>
</MessageResponse>
)
}
export function renderToolUseMessage(
{ skill }: Partial<Input>,
{ commands }: { commands?: Command[] },
): React.ReactNode {
if (!skill) {
return null
}
// Look up the command to check if it came from the legacy /commands folder
const command = commands?.find(c => c.name === skill)
const displayName =
command?.loadedFrom === 'commands_DEPRECATED' ? `/${skill}` : skill
return displayName
}
export function renderToolUseProgressMessage(
progressMessages: ProgressMessage<Progress>[],
{
tools,
verbose,
}: {
tools: Tools
verbose: boolean
},
): React.ReactNode {
if (!progressMessages.length) {
return (
<MessageResponse height={1}>
<Text dimColor>{INITIALIZING_TEXT}</Text>
</MessageResponse>
)
}
// Take only the last few messages for display in non-verbose mode
const displayedMessages = verbose
? progressMessages
: progressMessages.slice(-MAX_PROGRESS_MESSAGES_TO_SHOW)
const hiddenCount = progressMessages.length - displayedMessages.length
const { inProgressToolUseIDs } = buildSubagentLookups(
progressMessages.map(pm => pm.data),
)
return (
<MessageResponse>
<Box flexDirection="column">
<SubAgentProvider>
{displayedMessages.map(progressMessage => (
<Box key={progressMessage.uuid} height={1} overflow="hidden">
<MessageComponent
message={progressMessage.data.message}
lookups={EMPTY_LOOKUPS}
addMargin={false}
tools={tools}
commands={[]}
verbose={verbose}
inProgressToolUseIDs={inProgressToolUseIDs}
progressMessagesForMessage={[]}
shouldAnimate={false}
shouldShowDot={false}
style="condensed"
isTranscriptMode={false}
isStatic={true}
/>
</Box>
))}
</SubAgentProvider>
{hiddenCount > 0 && (
<Text dimColor>
+{hiddenCount} more tool {plural(hiddenCount, 'use')}
</Text>
)}
</Box>
</MessageResponse>
)
}
export function renderToolUseRejectedMessage(
_input: Input,
{
progressMessagesForMessage,
tools,
verbose,
}: {
progressMessagesForMessage: ProgressMessage<Progress>[]
tools: Tools
verbose: boolean
},
): React.ReactNode {
return (
<>
{renderToolUseProgressMessage(progressMessagesForMessage, {
tools,
verbose,
})}
<FallbackToolUseRejectedMessage />
</>
)
}
export function renderToolUseErrorMessage(
result: ToolResultBlockParam['content'],
{
progressMessagesForMessage,
tools,
verbose,
}: {
progressMessagesForMessage: ProgressMessage<Progress>[]
tools: Tools
verbose: boolean
},
): React.ReactNode {
return (
<>
{renderToolUseProgressMessage(progressMessagesForMessage, {
tools,
verbose,
})}
<FallbackToolUseErrorMessage result={result} verbose={verbose} />
</>
)
}

View File

@@ -0,0 +1 @@
export const SKILL_TOOL_NAME = 'Skill'

View File

@@ -0,0 +1,241 @@
import { memoize } from 'lodash-es'
import type { Command } from 'src/commands.js'
import {
getCommandName,
getSkillToolCommands,
getSlashCommandToolSkills,
} from 'src/commands.js'
import { COMMAND_NAME_TAG } from 'src/constants/xml.js'
import { stringWidth } from '@anthropic/ink'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from 'src/services/analytics/index.js'
import { count } from 'src/utils/array.js'
import { logForDebugging } from 'src/utils/debug.js'
import { toError } from 'src/utils/errors.js'
import { truncate } from 'src/utils/format.js'
import { logError } from 'src/utils/log.js'
// Skill listing gets 1% of the context window (in characters)
export const SKILL_BUDGET_CONTEXT_PERCENT = 0.01
export const CHARS_PER_TOKEN = 4
export const DEFAULT_CHAR_BUDGET = 8_000 // Fallback: 1% of 200k × 4
// Per-entry hard cap. The listing is for discovery only — the Skill tool loads
// full content on invoke, so verbose whenToUse strings waste turn-1 cache_creation
// tokens without improving match rate. Applies to all entries, including bundled,
// since the cap is generous enough to preserve the core use case.
export const MAX_LISTING_DESC_CHARS = 250
export function getCharBudget(contextWindowTokens?: number): number {
if (Number(process.env.SLASH_COMMAND_TOOL_CHAR_BUDGET)) {
return Number(process.env.SLASH_COMMAND_TOOL_CHAR_BUDGET)
}
if (contextWindowTokens) {
return Math.floor(
contextWindowTokens * CHARS_PER_TOKEN * SKILL_BUDGET_CONTEXT_PERCENT,
)
}
return DEFAULT_CHAR_BUDGET
}
function getCommandDescription(cmd: Command): string {
const desc = cmd.whenToUse
? `${cmd.description} - ${cmd.whenToUse}`
: cmd.description
return desc.length > MAX_LISTING_DESC_CHARS
? desc.slice(0, MAX_LISTING_DESC_CHARS - 1) + '\u2026'
: desc
}
function formatCommandDescription(cmd: Command): string {
// Debug: log if userFacingName differs from cmd.name for plugin skills
const displayName = getCommandName(cmd)
if (
cmd.name !== displayName &&
cmd.type === 'prompt' &&
cmd.source === 'plugin'
) {
logForDebugging(
`Skill prompt: showing "${cmd.name}" (userFacingName="${displayName}")`,
)
}
return `- ${cmd.name}: ${getCommandDescription(cmd)}`
}
const MIN_DESC_LENGTH = 20
export function formatCommandsWithinBudget(
commands: Command[],
contextWindowTokens?: number,
): string {
if (commands.length === 0) return ''
const budget = getCharBudget(contextWindowTokens)
// Try full descriptions first
const fullEntries = commands.map(cmd => ({
cmd,
full: formatCommandDescription(cmd),
}))
// join('\n') produces N-1 newlines for N entries
const fullTotal =
fullEntries.reduce((sum, e) => sum + stringWidth(e.full), 0) +
(fullEntries.length - 1)
if (fullTotal <= budget) {
return fullEntries.map(e => e.full).join('\n')
}
// Partition into bundled (never truncated) and rest
const bundledIndices = new Set<number>()
const restCommands: Command[] = []
for (let i = 0; i < commands.length; i++) {
const cmd = commands[i]!
if (cmd.type === 'prompt' && cmd.source === 'bundled') {
bundledIndices.add(i)
} else {
restCommands.push(cmd)
}
}
// Compute space used by bundled skills (full descriptions, always preserved)
const bundledChars = fullEntries.reduce(
(sum, e, i) =>
bundledIndices.has(i) ? sum + stringWidth(e.full) + 1 : sum,
0,
)
const remainingBudget = budget - bundledChars
// Calculate max description length for non-bundled commands
if (restCommands.length === 0) {
return fullEntries.map(e => e.full).join('\n')
}
const restNameOverhead =
restCommands.reduce((sum, cmd) => sum + stringWidth(cmd.name) + 4, 0) +
(restCommands.length - 1)
const availableForDescs = remainingBudget - restNameOverhead
const maxDescLen = Math.floor(availableForDescs / restCommands.length)
if (maxDescLen < MIN_DESC_LENGTH) {
// Extreme case: non-bundled go names-only, bundled keep descriptions
if (process.env.USER_TYPE === 'ant') {
logEvent('tengu_skill_descriptions_truncated', {
skill_count: commands.length,
budget,
full_total: fullTotal,
truncation_mode:
'names_only' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
max_desc_length: maxDescLen,
bundled_count: bundledIndices.size,
bundled_chars: bundledChars,
})
}
return commands
.map((cmd, i) =>
bundledIndices.has(i) ? fullEntries[i]!.full : `- ${cmd.name}`,
)
.join('\n')
}
// Truncate non-bundled descriptions to fit within budget
const truncatedCount = count(
restCommands,
cmd => stringWidth(getCommandDescription(cmd)) > maxDescLen,
)
if (process.env.USER_TYPE === 'ant') {
logEvent('tengu_skill_descriptions_truncated', {
skill_count: commands.length,
budget,
full_total: fullTotal,
truncation_mode:
'description_trimmed' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
max_desc_length: maxDescLen,
truncated_count: truncatedCount,
// Count of bundled skills included in this prompt (excludes skills with disableModelInvocation)
bundled_count: bundledIndices.size,
bundled_chars: bundledChars,
})
}
return commands
.map((cmd, i) => {
// Bundled skills always get full descriptions
if (bundledIndices.has(i)) return fullEntries[i]!.full
const description = getCommandDescription(cmd)
return `- ${cmd.name}: ${truncate(description, maxDescLen)}`
})
.join('\n')
}
export const getPrompt = memoize(async (_cwd: string): Promise<string> => {
return `Execute a skill within the main conversation
When users ask you to perform tasks, check if any of the available skills match. Skills provide specialized capabilities and domain knowledge.
When users reference a "slash command" or "/<something>" (e.g., "/commit", "/review-pr"), they are referring to a skill. Use this tool to invoke it.
How to invoke:
- Use this tool with the skill name and optional arguments
- Examples:
- \`skill: "pdf"\` - invoke the pdf skill
- \`skill: "commit", args: "-m 'Fix bug'"\` - invoke with arguments
- \`skill: "review-pr", args: "123"\` - invoke with arguments
- \`skill: "ms-office-suite:pdf"\` - invoke using fully qualified name
Important:
- Available skills are listed in system-reminder messages in the conversation
- When a skill matches the user's request, this is a BLOCKING REQUIREMENT: invoke the relevant Skill tool BEFORE generating any other response about the task
- NEVER mention a skill without actually calling this tool
- Do not invoke a skill that is already running
- Do not use this tool for built-in CLI commands (like /help, /clear, etc.)
- If you see a <${COMMAND_NAME_TAG}> tag in the current conversation turn, the skill has ALREADY been loaded - follow the instructions directly instead of calling this tool again
`
})
export async function getSkillToolInfo(cwd: string): Promise<{
totalCommands: number
includedCommands: number
}> {
const agentCommands = await getSkillToolCommands(cwd)
return {
totalCommands: agentCommands.length,
includedCommands: agentCommands.length,
}
}
// Returns the commands included in the SkillTool prompt.
// All commands are always included (descriptions may be truncated to fit budget).
// Used by analyzeContext to count skill tokens.
export function getLimitedSkillToolCommands(cwd: string): Promise<Command[]> {
return getSkillToolCommands(cwd)
}
export function clearPromptCache(): void {
getPrompt.cache?.clear?.()
}
export async function getSkillInfo(cwd: string): Promise<{
totalSkills: number
includedSkills: number
}> {
try {
const skills = await getSlashCommandToolSkills(cwd)
return {
totalSkills: skills.length,
includedSkills: skills.length,
}
} catch (error) {
logError(toError(error))
// Return zeros rather than throwing - let caller decide how to handle
return {
totalSkills: 0,
includedSkills: 0,
}
}
}

View File

@@ -0,0 +1,8 @@
// Auto-generated type stub — replace with real implementation
export type Tool = any;
export type ToolCallProgress = any;
export type ToolResult = any;
export type ToolUseContext = any;
export type ValidationResult = any;
export type buildTool = any;
export type ToolDef = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type getProjectRoot = any;

View File

@@ -0,0 +1,9 @@
// Auto-generated type stub — replace with real implementation
export type builtInCommandNames = any;
export type findCommand = any;
export type getCommands = any;
export type PromptCommand = any;
export type Command = any;
export type getCommandName = any;
export type getSkillToolCommands = any;
export type getSlashCommandToolSkills = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type SubAgentProvider = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type FallbackToolUseErrorMessage = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type FallbackToolUseRejectedMessage = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type Command = any;

View File

@@ -0,0 +1,6 @@
// Auto-generated type stub — replace with real implementation
export type AssistantMessage = any;
export type AttachmentMessage<T = any> = any;
export type Message = any;
export type SystemMessage = any;
export type UserMessage = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type logForDebugging = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type PermissionDecision = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type getRuleByContentsForTool = any;

View File

@@ -0,0 +1,3 @@
// Auto-generated type stub — replace with real implementation
export type isOfficialMarketplaceName = any;
export type parsePluginIdentifier = any;

View File

@@ -0,0 +1,2 @@
// Auto-generated type stub — replace with real implementation
export type buildPluginCommandTelemetryFields = any;