来源:Claude Code 技术文档 - v2.1.88 源码分析
类型系统参考
12.1 消息类型 (types/message.ts)
Claude Code 的消息系统支持多种消息类型:
type Message =
| UserMessage // 用户输入消息
| AssistantMessage // AI 助手回复
| AttachmentMessage // 附件消息(图片、文件等)
| SystemMessage // 系统消息(状态、错误等)12.1.1 消息生命周期
用户输入
│
├─ processUserInput() → UserMessage
│
├─ API 调用 → AssistantMessage
│ ├─ 文本内容
│ ├─ 工具调用 (ToolUseBlockParam)
│ └─ 思考块 (ThinkingBlock)
│
├─ 工具执行结果 → UserMessage (ToolResultBlockParam)
│
├─ 系统事件 → SystemMessage
│ ├─ 工具权限拒绝
│ ├─ 预算警告
│ └─ 状态更新
│
└─ 附件 → AttachmentMessage
├─ 图片引用
└─ 文件引用12.2 权限类型 (types/permissions.ts)
12.2.1 完整类型定义
// 权限模式
type ExternalPermissionMode =
| 'acceptEdits' | 'bypassPermissions' | 'default' | 'dontAsk' | 'plan'
type InternalPermissionMode = ExternalPermissionMode | 'auto' | 'bubble'
type PermissionMode = InternalPermissionMode
// 规则来源
type PermissionRuleSource =
| 'userSettings' | 'projectSettings' | 'localSettings'
| 'flagSettings' | 'policySettings' | 'cliArg'
| 'command' | 'session'
// 规则值
type PermissionRuleValue = {
toolName: string
ruleContent?: string
}
// 规则
type PermissionRule = {
source: PermissionRuleSource
ruleBehavior: 'allow' | 'deny' | 'ask'
ruleValue: PermissionRuleValue
}
// 权限决策
type PermissionDecision<Input = {[key: string]: unknown}> =
| PermissionAllowDecision<Input>
| PermissionAskDecision<Input>
| PermissionDenyDecision
type PermissionResult<Input = {[key: string]: unknown}> =
PermissionDecision<Input> | { behavior: 'passthrough' }12.2.2 分类器类型
type ClassifierResult = {
matches: boolean
matchedDescription?: string
confidence: 'high' | 'medium' | 'low'
reason: string
}
type YoloClassifierResult = {
thinking?: string
shouldBlock: boolean
reason: string
unavailable?: boolean
transcriptTooLong?: boolean
model: string
usage?: ClassifierUsage
durationMs?: number
stage?: 'fast' | 'thinking'
}12.2.3 权限上下文
type ToolPermissionContext = {
readonly mode: PermissionMode
readonly additionalWorkingDirectories: ReadonlyMap<string, AdditionalWorkingDirectory>
readonly alwaysAllowRules: ToolPermissionRulesBySource
readonly alwaysDenyRules: ToolPermissionRulesBySource
readonly alwaysAskRules: ToolPermissionRulesBySource
readonly isBypassPermissionsModeAvailable: boolean
readonly isAutoModeAvailable?: boolean
readonly strippedDangerousRules?: ToolPermissionRulesBySource
readonly shouldAvoidPermissionPrompts?: boolean
readonly awaitAutomatedChecksBeforeDialog?: boolean
readonly prePlanMode?: PermissionMode
}12.3 Hook 类型 (types/hooks.ts)
12.3.1 Hook 同步响应 Schema
const syncHookResponseSchema = z.object({
continue: z.boolean().optional(),
suppressOutput: z.boolean().optional(),
stopReason: z.string().optional(),
decision: z.enum(['approve', 'block']).optional(),
reason: z.string().optional(),
systemMessage: z.string().optional(),
hookSpecificOutput: z.union([...]) // 事件特定输出
})
type SyncHookJSONOutput = z.infer<ReturnType<typeof syncHookResponseSchema>>12.3.2 Hook 回调和结果
type HookCallback = {
type: 'callback'
callback: (
input: HookInput,
toolUseID: string | null,
abort: AbortSignal | undefined,
hookIndex?: number,
context?: HookCallbackContext
) => Promise<HookJSONOutput>
timeout?: number
internal?: boolean
}
type HookResult = {
message?: Message
systemMessage?: Message
blockingError?: HookBlockingError
outcome: 'success' | 'blocking' | 'non_blocking_error' | 'cancelled'
preventContinuation?: boolean
stopReason?: string
permissionBehavior?: 'ask' | 'deny' | 'allow' | 'passthrough'
hookPermissionDecisionReason?: string
additionalContext?: string
initialUserMessage?: string
updatedInput?: Record<string, unknown>
updatedMCPToolOutput?: unknown
permissionRequestResult?: PermissionRequestResult
retry?: boolean
}12.4 命令类型 (types/command.ts)
12.4.1 命令基底
type CommandBase = {
availability?: ('claude-ai' | 'console')[]
description: string
hasUserSpecifiedDescription?: boolean
isEnabled?: () => boolean
isHidden?: boolean
name: string
aliases?: string[]
isMcp?: boolean
argumentHint?: string
whenToUse?: string
version?: string
disableModelInvocation?: boolean
userInvocable?: boolean
loadedFrom?: 'commands_DEPRECATED' | 'skills' | 'plugin' | 'managed' | 'bundled' | 'mcp'
kind?: 'workflow'
immediate?: boolean
isSensitive?: boolean
userFacingName?: () => string
}12.4.2 命令联合类型
type Command = CommandBase & (
| PromptCommand // 技能/提示命令
| LocalCommand // 本地命令
| LocalJSXCommand // JSX 本地命令
)12.4.3 命令结果
type LocalCommandResult =
| { type: 'text'; value: string }
| { type: 'compact'; compactionResult: CompactionResult; displayText?: string }
| { type: 'skip' }12.5 工具类型 (types/tools.ts)
12.5.1 核心工具类型
type ToolInputJSONSchema = {
[x: string]: unknown
type: 'object'
properties?: { [x: string]: unknown }
}
type ValidationResult =
| { result: true }
| { result: false; message: string; errorCode: number }
type ToolResult<T> = {
data: T
newMessages?: (UserMessage | AssistantMessage | AttachmentMessage | SystemMessage)[]
contextModifier?: (context: ToolUseContext) => ToolUseContext
mcpMeta?: { _meta?: Record<string, unknown>; structuredContent?: Record<string, unknown> }
}
type Tools = readonly Tool[]12.5.2 SetToolJSXFn
type SetToolJSXFn = (args: {
jsx: React.ReactNode | null
shouldHidePromptInput: boolean
shouldContinueAnimation?: true
showSpinner?: boolean
isLocalJSXCommand?: boolean
isImmediate?: boolean
clearLocalJSX?: boolean
} | null) => void12.6 ID 系统 (types/ids.ts)
12.6.1 品牌标签类型安全
// 会话 ID — 品牌类型防止误用
type SessionId = string & { readonly __brand: 'SessionId' }
// 代理 ID — 品牌类型防止误用
type AgentId = string & { readonly __brand: 'AgentId' }
// 类型安全转换
function asSessionId(id: string): SessionId
function asAgentId(id: string): AgentId
// 验证转换 (可能返回 null)
function toAgentId(s: string): AgentId | null
// 验证格式: `a` + optional `<label>-` + 16 hex chars12.6.2 品牌类型的好处
// 编译时错误 — 防止不同类型 ID 混用
const sessionId: SessionId = asSessionId('abc-123')
const agentId: AgentId = asAgentId('a-def456')
// ❌ 编译错误: SessionId 不能赋值给 AgentId
const wrong: AgentId = sessionId
// ✅ 正确: 使用正确的类型
function getTask(id: AgentId): Task { ... }
getTask(agentId) // ✅ OK
getTask(sessionId) // ❌ 编译错误12.7 任务类型 (Task.ts)
type TaskType =
| 'local_bash' // 本地 Shell 任务
| 'local_agent' // 本地代理任务
| 'remote_agent' // 远程代理任务
| 'in_process_teammate' // 进程内队友
| 'local_workflow' // 本地工作流
| 'monitor_mcp' // MCP 监控
| 'dream' // 梦境任务
type TaskStatus =
| 'pending' // 等待中
| 'running' // 运行中
| 'completed' // 已完成
| 'failed' // 失败
| 'killed' // 被终止
type TaskHandle = {
taskId: string
cleanup?: () => void
}
type TaskStateBase = {
id: string
type: TaskType
status: TaskStatus
description: string
toolUseId?: string
startTime: number
endTime?: number
totalPausedMs?: number
outputFile: string
outputOffset: number
notified: boolean
}
type LocalShellSpawnInput = {
command: string
description: string
timeout?: number
toolUseId?: string
agentId?: AgentId
kind?: 'bash' | 'monitor'
}
// 终态检查
function isTerminalTaskStatus(status: TaskStatus): boolean
// → status === 'completed' || 'failed' || 'killed'
// 任务 ID 生成
function generateTaskId(type: TaskType): string
// 前缀映射: local_bash→'b', local_agent→'a', ...
// 格式: 前缀 + 8个 base-36 随机字符12.8 成本类型 (cost-tracker.ts)
type StoredCostState = {
totalCostUSD: number
totalAPIDuration: number
totalAPIDurationWithoutRetries: number
totalToolDuration: number
totalLinesAdded: number
totalLinesRemoved: number
lastDuration: number | undefined
modelUsage: {
[modelName: string]: ModelUsage
} | undefined
}12.9 历史类型 (history.ts)
type StoredPastedContent = {
id: number
type: 'text' | 'image'
content?: string // 小粘贴内联
contentHash?: string // 大粘贴 hash 引用
mediaType?: string
filename?: string
}
type LogEntry = {
display: string
pastedContents: Record<number, StoredPastedContent>
timestamp: number
project: string
sessionId?: string
}
type TimestampedHistoryEntry = {
display: string
timestamp: number
resolve: () => Promise<HistoryEntry> // 延迟加载
}12.10 查询链追踪
type QueryChainTracking = {
chainId: string // 查询链唯一 ID
depth: number // 当前链深度
}12.11 类型导出汇总表
文件
关键导出
Tool.ts
Tool<I,O,P>, ToolUseContext, ToolPermissionContext, Tools, ToolResult, ValidationResult, buildTool()
tools.ts
getTools(), getAllBaseTools(), assembleToolPool(), getMergedTools()
commands.ts
Command, getCommands(), COMMANDS(), findCommand(), getSkillToolCommands()
QueryEngine.ts
QueryEngine, QueryEngineConfig, ask()
context.ts
getSystemContext(), getUserContext(), getGitStatus()
history.ts
getHistory(), addToHistory(), expandPastedTextRefs()
cost-tracker.ts
StoredCostState, formatTotalCost(), addToTotalSessionCost()
Task.ts
Task, TaskType, TaskStatus, TaskStateBase, generateTaskId()
tasks.ts
getAllTasks(), getTaskByType()
types/permissions.ts
PermissionMode, PermissionRule, PermissionResult, ToolPermissionContext
types/command.ts
CommandBase, PromptCommand, LocalCommand, LocalJSXCommand
types/hooks.ts
HookCallback, HookResult, SyncHookJSONOutput
types/ids.ts
SessionId, AgentId, asSessionId(), asAgentId()
constants/prompts.ts
getSystemPrompt(), computeEnvInfo(), SYSTEM_PROMPT_DYNAMIC_BOUNDARY
constants/system.ts
getAttributionHeader(), CLISyspromptPrefix
constants/tools.ts
ALL_AGENT_DISALLOWED_TOOLS, ASYNC_AGENT_ALLOWED_TOOLS
constants/common.ts
getLocalISODate(), getSessionStartDate(), getLocalMonthYear()