mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-23 08:45:50 +00:00
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:
265
packages/builtin-tools/src/tools/AgentTool/resumeAgent.ts
Normal file
265
packages/builtin-tools/src/tools/AgentTool/resumeAgent.ts
Normal file
@@ -0,0 +1,265 @@
|
||||
import { promises as fsp } from 'fs'
|
||||
import { getSdkAgentProgressSummariesEnabled } from 'src/bootstrap/state.js'
|
||||
import { getSystemPrompt } from 'src/constants/prompts.js'
|
||||
import { isCoordinatorMode } from 'src/coordinator/coordinatorMode.js'
|
||||
import type { CanUseToolFn } from 'src/hooks/useCanUseTool.js'
|
||||
import type { ToolUseContext } from 'src/Tool.js'
|
||||
import { registerAsyncAgent } from 'src/tasks/LocalAgentTask/LocalAgentTask.js'
|
||||
import { assembleToolPool } from 'src/tools.js'
|
||||
import { asAgentId } from 'src/types/ids.js'
|
||||
import { runWithAgentContext } from 'src/utils/agentContext.js'
|
||||
import { runWithCwdOverride } from 'src/utils/cwd.js'
|
||||
import { logForDebugging } from 'src/utils/debug.js'
|
||||
import {
|
||||
createUserMessage,
|
||||
filterOrphanedThinkingOnlyMessages,
|
||||
filterUnresolvedToolUses,
|
||||
filterWhitespaceOnlyAssistantMessages,
|
||||
} from 'src/utils/messages.js'
|
||||
import { getAgentModel } from 'src/utils/model/agent.js'
|
||||
import { getQuerySourceForAgent } from 'src/utils/promptCategory.js'
|
||||
import {
|
||||
getAgentTranscript,
|
||||
readAgentMetadata,
|
||||
} from 'src/utils/sessionStorage.js'
|
||||
import { buildEffectiveSystemPrompt } from 'src/utils/systemPrompt.js'
|
||||
import type { SystemPrompt } from 'src/utils/systemPromptType.js'
|
||||
import { getTaskOutputPath } from 'src/utils/task/diskOutput.js'
|
||||
import { getParentSessionId } from 'src/utils/teammate.js'
|
||||
import { reconstructForSubagentResume } from 'src/utils/toolResultStorage.js'
|
||||
import { runAsyncAgentLifecycle } from './agentToolUtils.js'
|
||||
import { GENERAL_PURPOSE_AGENT } from './built-in/generalPurposeAgent.js'
|
||||
import { FORK_AGENT, isForkSubagentEnabled } from './forkSubagent.js'
|
||||
import type { AgentDefinition } from './loadAgentsDir.js'
|
||||
import { isBuiltInAgent } from './loadAgentsDir.js'
|
||||
import { runAgent } from './runAgent.js'
|
||||
|
||||
export type ResumeAgentResult = {
|
||||
agentId: string
|
||||
description: string
|
||||
outputFile: string
|
||||
}
|
||||
export async function resumeAgentBackground({
|
||||
agentId,
|
||||
prompt,
|
||||
toolUseContext,
|
||||
canUseTool,
|
||||
invokingRequestId,
|
||||
}: {
|
||||
agentId: string
|
||||
prompt: string
|
||||
toolUseContext: ToolUseContext
|
||||
canUseTool: CanUseToolFn
|
||||
invokingRequestId?: string
|
||||
}): Promise<ResumeAgentResult> {
|
||||
const startTime = Date.now()
|
||||
const appState = toolUseContext.getAppState()
|
||||
// In-process teammates get a no-op setAppState; setAppStateForTasks
|
||||
// reaches the root store so task registration/progress/kill stay visible.
|
||||
const rootSetAppState =
|
||||
toolUseContext.setAppStateForTasks ?? toolUseContext.setAppState
|
||||
const permissionMode = appState.toolPermissionContext.mode
|
||||
|
||||
const [transcript, meta] = await Promise.all([
|
||||
getAgentTranscript(asAgentId(agentId)),
|
||||
readAgentMetadata(asAgentId(agentId)),
|
||||
])
|
||||
if (!transcript) {
|
||||
throw new Error(`No transcript found for agent ID: ${agentId}`)
|
||||
}
|
||||
const resumedMessages = filterWhitespaceOnlyAssistantMessages(
|
||||
filterOrphanedThinkingOnlyMessages(
|
||||
filterUnresolvedToolUses(transcript.messages),
|
||||
),
|
||||
)
|
||||
const resumedReplacementState = reconstructForSubagentResume(
|
||||
toolUseContext.contentReplacementState,
|
||||
resumedMessages,
|
||||
transcript.contentReplacements,
|
||||
)
|
||||
// Best-effort: if the original worktree was removed externally, fall back
|
||||
// to parent cwd rather than crashing on chdir later.
|
||||
const resumedWorktreePath = meta?.worktreePath
|
||||
? await fsp.stat(meta.worktreePath).then(
|
||||
s => (s.isDirectory() ? meta.worktreePath : undefined),
|
||||
() => {
|
||||
logForDebugging(
|
||||
`Resumed worktree ${meta.worktreePath} no longer exists; falling back to parent cwd`,
|
||||
)
|
||||
return undefined
|
||||
},
|
||||
)
|
||||
: undefined
|
||||
if (resumedWorktreePath) {
|
||||
// Bump mtime so stale-worktree cleanup doesn't delete a just-resumed worktree (#22355)
|
||||
const now = new Date()
|
||||
await fsp.utimes(resumedWorktreePath, now, now)
|
||||
}
|
||||
|
||||
// Skip filterDeniedAgents re-gating — original spawn already passed permission checks
|
||||
let selectedAgent: AgentDefinition
|
||||
let isResumedFork = false
|
||||
if (meta?.agentType === FORK_AGENT.agentType) {
|
||||
selectedAgent = FORK_AGENT
|
||||
isResumedFork = true
|
||||
} else if (meta?.agentType) {
|
||||
const found = toolUseContext.options.agentDefinitions.activeAgents.find(
|
||||
a => a.agentType === meta.agentType,
|
||||
)
|
||||
selectedAgent = found ?? GENERAL_PURPOSE_AGENT
|
||||
} else {
|
||||
selectedAgent = GENERAL_PURPOSE_AGENT
|
||||
}
|
||||
|
||||
const uiDescription = meta?.description ?? '(resumed)'
|
||||
|
||||
let forkParentSystemPrompt: SystemPrompt | undefined
|
||||
if (isResumedFork) {
|
||||
if (toolUseContext.renderedSystemPrompt) {
|
||||
forkParentSystemPrompt = toolUseContext.renderedSystemPrompt
|
||||
} else {
|
||||
const mainThreadAgentDefinition = appState.agent
|
||||
? appState.agentDefinitions.activeAgents.find(
|
||||
a => a.agentType === appState.agent,
|
||||
)
|
||||
: undefined
|
||||
const additionalWorkingDirectories = Array.from(
|
||||
appState.toolPermissionContext.additionalWorkingDirectories.keys(),
|
||||
)
|
||||
const defaultSystemPrompt = await getSystemPrompt(
|
||||
toolUseContext.options.tools,
|
||||
toolUseContext.options.mainLoopModel,
|
||||
additionalWorkingDirectories,
|
||||
toolUseContext.options.mcpClients,
|
||||
)
|
||||
forkParentSystemPrompt = buildEffectiveSystemPrompt({
|
||||
mainThreadAgentDefinition,
|
||||
toolUseContext,
|
||||
customSystemPrompt: toolUseContext.options.customSystemPrompt,
|
||||
defaultSystemPrompt,
|
||||
appendSystemPrompt: toolUseContext.options.appendSystemPrompt,
|
||||
})
|
||||
}
|
||||
if (!forkParentSystemPrompt) {
|
||||
throw new Error(
|
||||
'Cannot resume fork agent: unable to reconstruct parent system prompt',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve model for analytics metadata (runAgent resolves its own internally)
|
||||
const resolvedAgentModel = getAgentModel(
|
||||
selectedAgent.model,
|
||||
toolUseContext.options.mainLoopModel,
|
||||
undefined,
|
||||
permissionMode,
|
||||
)
|
||||
|
||||
const workerPermissionContext = {
|
||||
...appState.toolPermissionContext,
|
||||
mode: selectedAgent.permissionMode ?? 'acceptEdits',
|
||||
}
|
||||
const workerTools = isResumedFork
|
||||
? toolUseContext.options.tools
|
||||
: assembleToolPool(workerPermissionContext, appState.mcp.tools)
|
||||
|
||||
const runAgentParams: Parameters<typeof runAgent>[0] = {
|
||||
agentDefinition: selectedAgent,
|
||||
promptMessages: [
|
||||
...resumedMessages,
|
||||
createUserMessage({ content: prompt }),
|
||||
],
|
||||
toolUseContext,
|
||||
canUseTool,
|
||||
isAsync: true,
|
||||
querySource: getQuerySourceForAgent(
|
||||
selectedAgent.agentType,
|
||||
isBuiltInAgent(selectedAgent),
|
||||
),
|
||||
model: undefined,
|
||||
// Fork resume: pass parent's system prompt (cache-identical prefix).
|
||||
// Non-fork: undefined → runAgent recomputes under wrapWithCwd so
|
||||
// getCwd() sees resumedWorktreePath.
|
||||
override: isResumedFork
|
||||
? { systemPrompt: forkParentSystemPrompt }
|
||||
: undefined,
|
||||
availableTools: workerTools,
|
||||
// Transcript already contains the parent context slice from the
|
||||
// original fork. Re-supplying it would cause duplicate tool_use IDs.
|
||||
forkContextMessages: undefined,
|
||||
...(isResumedFork && { useExactTools: true }),
|
||||
// Re-persist so metadata survives runAgent's writeAgentMetadata overwrite
|
||||
worktreePath: resumedWorktreePath,
|
||||
description: meta?.description,
|
||||
contentReplacementState: resumedReplacementState,
|
||||
}
|
||||
|
||||
// Skip name-registry write — original entry persists from the initial spawn
|
||||
const agentBackgroundTask = registerAsyncAgent({
|
||||
agentId,
|
||||
description: uiDescription,
|
||||
prompt,
|
||||
selectedAgent,
|
||||
setAppState: rootSetAppState,
|
||||
toolUseId: toolUseContext.toolUseId,
|
||||
})
|
||||
|
||||
const metadata = {
|
||||
prompt,
|
||||
resolvedAgentModel,
|
||||
isBuiltInAgent: isBuiltInAgent(selectedAgent),
|
||||
startTime,
|
||||
agentType: selectedAgent.agentType,
|
||||
isAsync: true,
|
||||
}
|
||||
|
||||
const asyncAgentContext = {
|
||||
agentId,
|
||||
parentSessionId: getParentSessionId(),
|
||||
agentType: 'subagent' as const,
|
||||
subagentName: selectedAgent.agentType,
|
||||
isBuiltIn: isBuiltInAgent(selectedAgent),
|
||||
invokingRequestId,
|
||||
invocationKind: 'resume' as const,
|
||||
invocationEmitted: false,
|
||||
}
|
||||
|
||||
const wrapWithCwd = <T>(fn: () => T): T =>
|
||||
resumedWorktreePath ? runWithCwdOverride(resumedWorktreePath, fn) : fn()
|
||||
|
||||
void runWithAgentContext(asyncAgentContext, () =>
|
||||
wrapWithCwd(() =>
|
||||
runAsyncAgentLifecycle({
|
||||
taskId: agentBackgroundTask.agentId,
|
||||
abortController: agentBackgroundTask.abortController!,
|
||||
makeStream: onCacheSafeParams =>
|
||||
runAgent({
|
||||
...runAgentParams,
|
||||
override: {
|
||||
...runAgentParams.override,
|
||||
agentId: asAgentId(agentBackgroundTask.agentId),
|
||||
abortController: agentBackgroundTask.abortController!,
|
||||
},
|
||||
onCacheSafeParams,
|
||||
}),
|
||||
metadata,
|
||||
description: uiDescription,
|
||||
toolUseContext,
|
||||
rootSetAppState,
|
||||
agentIdForCleanup: agentId,
|
||||
enableSummarization:
|
||||
isCoordinatorMode() ||
|
||||
isForkSubagentEnabled() ||
|
||||
getSdkAgentProgressSummariesEnabled(),
|
||||
getWorktreeResult: async () =>
|
||||
resumedWorktreePath ? { worktreePath: resumedWorktreePath } : {},
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
return {
|
||||
agentId,
|
||||
description: uiDescription,
|
||||
outputFile: getTaskOutputPath(agentId),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user