Claude Code 源码分析Claude Code 源码分析
首页
源码统计
系统架构
UML 图表
工具系统
CodeGraph
首页
源码统计
系统架构
UML 图表
工具系统
CodeGraph
  • 概览

    • Claude Code 源码分析
    • 源码统计
    • CodeGraph 图谱
  • 架构

    • 系统架构
    • UML 图表索引
    • 查询引擎
    • 核心流程
    • 消息系统
    • 状态管理
  • 功能模块

    • 工具系统
    • 斜杠命令
    • 服务层
    • MCP 协议
    • Skills 技能
    • 子代理系统
  • 分层深度

    • 入口层
    • UI / Ink 层
    • utils 基础设施
    • 桥接 / 远程
    • 上下文压缩
  • 原理与安全

    • 底层原理
    • 技术难点
    • 权限与安全
    • 内部机制
    • 遥测与分析
  • 深度专题

    • Hooks 系统
    • 插件系统
    • 记忆系统
    • API 通信层
    • Ink 终端 UI
    • 认证系统
    • 构建与发布
    • 术语表
  • 调用分析

    • 调用链分析
    • 核心文件索引
  • 模块详解

    • utils

      • 模块: utils
      • messages · 消息工厂与规范化
      • session-storage · JSONL 会话持久化
      • permissions · 工具权限决策
      • shell-hooks · 用户 Shell Hook 系统
    • components

      • 模块: components
      • REPL · 主屏编排
      • messages · 消息行渲染
      • PermissionRequest · 权限弹窗
      • PromptInput · 底部输入
    • services

      • 模块: services
      • api-claude · Anthropic API 流式与重试
      • mcp-client · MCP 连接与工具调用
      • compact · 上下文压缩与自动触发
      • analytics · GrowthBook、Datadog 与 1P 事件
    • tools

      • 模块: tools
      • tool-interface · Tool 契约与注册表
      • bash-tool · Shell 执行与权限
      • streaming-executor · 流式工具并发调度
      • agent-tool · 子 Agent 委派
    • commands

      • 模块: commands
      • command-registry · commands.ts 注册与分派
      • model-command · /model 模型选择
      • mcp-commands · /mcp 服务器管理
      • compact-memory-commands · /compact 与 /memory
    • ink

      • 模块: ink
      • Ink 渲染管线 · Screen 与终端输出
      • 终端事件 · resize、paste、stdin
      • Ink Hooks · 输入、搜索、终端状态
      • Ink 组件 · Box、Text、ScrollBox 原语
    • hooks

      • 模块: hooks
      • useCanUseTool · 权限 UI 接缝
      • 输入与快捷键 Hook
      • 合并态 Hook(MCP + 本地)
      • notifs 通知 Hook
    • bridge

      • 模块: bridge
      • repl-bridge · REPL 桥初始化与传输
      • bridge-messaging · 桥消息路由与入站处理
      • remote-bridge-core · env-less 核心与守护主循环
      • bridge-permissions-ui · 权限、API 与 TUI
    • cli

      • 模块: cli
      • Structured IO · NDJSON SDK 协议
      • CLI Transports · Session Ingress 传输层
      • CLI Handlers · 子命令懒加载实现
      • Update & Upload · 自更新与串行上传原语
    • screens

      • 模块: screens
      • REPL 屏 · Screen 类型与顶层路由
      • ResumeConversation · 会话恢复选择器
      • Doctor · 安装诊断全屏
    • entrypoints

      • 模块: entrypoints
      • cli-entrypoint · Bootstrap 与快路径
      • sdk-types · core / control / runtime 类型体系
      • mcp-entrypoint · MCP stdio 服务器
      • sandbox-types · 沙箱配置单一真相源
    • skills

      • 模块: skills
      • skills-loading · 磁盘加载与 bundled 注册表
      • bundled-skills · 内置 skill 与 initBundledSkills
      • mcp-skills · MCP prompt 转 skill
      • skill-tool-integration · SkillTool 与命令注册
    • types

      • 模块: types
      • message-types · Message 联合与 content blocks
      • tool-permission-types · Tool、Permission、Command 类型
      • api-sdk-types · API 与 Hooks 协议类型
      • misc-types · ids、plugin、generated 与其余类型
    • tasks

      • 模块: tasks
      • local-agent-task · 本地 Agent 与主会话后台化
      • remote-agent-task · 远程 CCR 与 In-Process Teammate
      • shell-workflow-tasks · Bash 后台、Workflow 与 stopTask
      • dream-monitor-tasks · Dream、Monitor MCP 与 pill 文案
    • keybindings

      • 模块: keybindings
      • keybinding-registry · 注册、Provider 与 useKeybinding
      • default-bindings · 默认键位表与平台差异
      • command-bindings · command:* 动态斜杠命令绑定
      • vim-bindings · Vim 模式与 keybindings 边界
    • memdir

      • 模块: memdir
      • memdir-core · 路径、加载与 MEMORY.md
      • memory-extraction · extractMemories 与 SessionMemory
      • memdir-commands · /memory、/remember 与命令集成
    • state

      • 模块: state
      • app-state-core · store、AppState 类型与 Provider
      • app-state-selectors · selectors 与 onChangeAppState
      • teammate-state · 队友视图与 swarm 状态
      • state-boundaries · bootstrap、sessionStorage、FileStateCache
    • query

      • 模块: query
      • query config 与 deps · 配置快照与依赖注入
      • query tokenBudget · +500k 自动续跑
      • query transitions · Continue / Terminal 状态机
      • query stopHooks · Stop 事件与 turn 结束编排
  • 模块详解(扩展)

    • messages · 消息工厂与规范化
    • session-storage · JSONL 会话持久化
    • permissions · 工具权限决策
    • shell-hooks · 用户 Shell Hook 系统
    • REPL · 主屏编排
    • messages · 消息行渲染
    • PermissionRequest · 权限弹窗
    • PromptInput · 底部输入
    • api-claude · Anthropic API 流式与重试
    • mcp-client · MCP 连接与工具调用
    • compact · 上下文压缩与自动触发
    • analytics · GrowthBook、Datadog 与 1P 事件
    • tool-interface · Tool 契约与注册表
    • bash-tool · Shell 执行与权限
    • streaming-executor · 流式工具并发调度
    • agent-tool · 子 Agent 委派
    • command-registry · commands.ts 注册与分派
    • model-command · /model 模型选择
    • mcp-commands · /mcp 服务器管理
    • compact-memory-commands · /compact 与 /memory
    • Ink 渲染管线 · Screen 与终端输出
    • 终端事件 · resize、paste、stdin
    • Ink Hooks · 输入、搜索、终端状态
    • Ink 组件 · Box、Text、ScrollBox 原语
    • useCanUseTool · 权限 UI 接缝
    • 输入与快捷键 Hook
    • 合并态 Hook(MCP + 本地)
    • notifs 通知 Hook
    • repl-bridge · REPL 桥初始化与传输
    • bridge-messaging · 桥消息路由与入站处理
    • remote-bridge-core · env-less 核心与守护主循环
    • bridge-permissions-ui · 权限、API 与 TUI
    • Structured IO · NDJSON SDK 协议
    • CLI Transports · Session Ingress 传输层
    • CLI Handlers · 子命令懒加载实现
    • Update & Upload · 自更新与串行上传原语
    • REPL 屏 · Screen 类型与顶层路由
    • ResumeConversation · 会话恢复选择器
    • Doctor · 安装诊断全屏
    • cli-entrypoint · Bootstrap 与快路径
    • sdk-types · core / control / runtime 类型体系
    • mcp-entrypoint · MCP stdio 服务器
    • sandbox-types · 沙箱配置单一真相源
    • skills-loading · 磁盘加载与 bundled 注册表
    • bundled-skills · 内置 skill 与 initBundledSkills
    • mcp-skills · MCP prompt 转 skill
    • skill-tool-integration · SkillTool 与命令注册
    • message-types · Message 联合与 content blocks
    • tool-permission-types · Tool、Permission、Command 类型
    • api-sdk-types · API 与 Hooks 协议类型
    • misc-types · ids、plugin、generated 与其余类型
    • local-agent-task · 本地 Agent 与主会话后台化
    • remote-agent-task · 远程 CCR 与 In-Process Teammate
    • shell-workflow-tasks · Bash 后台、Workflow 与 stopTask
    • dream-monitor-tasks · Dream、Monitor MCP 与 pill 文案
    • keybinding-registry · 注册、Provider 与 useKeybinding
    • default-bindings · 默认键位表与平台差异
    • command-bindings · command:* 动态斜杠命令绑定
    • vim-bindings · Vim 模式与 keybindings 边界
    • memdir-core · 路径、加载与 MEMORY.md
    • memory-extraction · extractMemories 与 SessionMemory
    • memdir-commands · /memory、/remember 与命令集成
    • app-state-core · store、AppState 类型与 Provider
    • app-state-selectors · selectors 与 onChangeAppState
    • teammate-state · 队友视图与 swarm 状态
    • state-boundaries · bootstrap、sessionStorage、FileStateCache
    • query config 与 deps · 配置快照与依赖注入
    • query tokenBudget · +500k 自动续跑
    • query transitions · Continue / Terminal 状态机
    • query stopHooks · Stop 事件与 turn 结束编排
  • 工具详解

    • tool-interface · Tool 契约与注册表
    • tool-permission-types · Tool、Permission、Command 类型
    • 工具: Bash
    • 工具: PowerShell
    • 工具: Agent
    • 工具: LSP
    • 工具: FileEdit
    • 工具: FileRead
    • 工具: Skill
    • 工具: WebFetch
    • 工具: MCP
    • 工具: SendMessage
    • 工具: FileWrite
    • 工具: Config
    • 工具: Grep
    • 工具: Brief
    • 工具: ExitPlanMode
    • 工具: ToolSearch
    • 工具: NotebookEdit
    • 工具: TaskOutput
    • 工具: WebSearch
    • 工具: ScheduleCron

本章总览

Claude Code Agent SDK 的公开类型从 entrypoints/sdk/ 导出,经 agentSdkTypes.ts 聚合。三套分工:coreTypes(可序列化消息/配置,Zod 生成)、runtimeTypes(Session 回调、Query 接口)、controlTypes(stdin/stdout 控制协议,@alpha)。本章说明 schema 生成链、HOOK_EVENTS 常量与 SDK 消费者应 import 哪一层。

学完本章你应该能

  • 解释 coreSchemas.ts → generate-sdk-types → coreTypes.generated.ts 流程
  • 区分 SDKControlRequest 与 SDKMessage 的使用场景
  • 说明 runtimeTypes 中 Record<string, unknown> 占位与 @internal toolTypes
  • 理解 sandboxTypes 被 coreTypes re-export 的原因
  • 定位 agentSdkTypes.ts 中 tool() helper 与 query() 签名
  • 知道 HOOK_EVENTS 与 EXIT_REASONS 常量数组的用途

核心概念(先读懂这些)

core = 线上 JSON 线协议

coreTypes.generated.ts 由脚本生成,对应 SDK 与 CLI 之间 JSON 消息。HOOK_EVENTS、EXIT_REASONS 等 const 数组在 coreTypes.ts 手写维护,供 runtime 校验 hook 名。修改消息 shape 必须改 coreSchemas.ts 再跑生成器,避免 hand-edit generated 文件。

control = SDK builder 专用

controlTypes.ts 描述 type: control_request / control_response 帧,用于 embed Claude Code 进程并通过 stdin 发 initialize、cancel、permission。agentSdkTypes 以 @alpha re-export 部分 control 类型;应用集成者通常只需 core + runtime。

建议学习步骤

  1. 阅读 coreTypes.ts 头注释与 re-export(源码块 A)
  2. 阅读 HOOK_EVENTS / EXIT_REASONS(源码块 B)
  3. 阅读 controlTypes 联合类型(源码块 C)
  4. 阅读 runtimeTypes SdkMcpToolDefinition(源码块 D)
  5. 阅读 agentSdkTypes 聚合 export(源码块 E、F)
  6. 对照 sandboxTypes re-export 理解 SDK 单一 import 路径

常见误区

注意

coreTypes.generated.ts 和 settingsTypes.generated.ts 勿手改

注意

toolTypes 全标记 @internal,外部文档不应依赖

注意

NonNullableUsage 等 utility 类型在 sdkUtilityTypes.ts,无法 Zod 表达

类型目录与生成链

entrypoints/sdk/ 布局:

文件角色
coreSchemas.tsZod schema 源(公开 API 不 export schema)
coreTypes.generated.ts生成 TypeScript 类型
coreTypes.ts手写 const + re-export generated + sandbox
controlSchemas.ts / controlTypes.ts控制协议
runtimeTypes.ts非序列化接口占位
toolTypes.tsTool 定义(@internal)
settingsTypes.generated.tssettings.json schema 生成
sdkUtilityTypes.tsNonNullableUsage 等

工作流:

# 修改 coreSchemas.ts 后
bun scripts/generate-sdk-types.ts

agentSdkTypes.ts 文件头注释说明:SDK 消费者 import 此文件;control 消费者可直 import controlTypes。

源码引用: src/entrypoints/sdk/coreTypes.ts · 第 1–22 行(共 63 行)

   1| // SDK Core Types - Common serializable types used by both SDK consumers and SDK builders.
   2| //
   3| // Types are generated from Zod schemas in coreSchemas.ts.
   4| // To modify types:
   5| // 1. Edit Zod schemas in coreSchemas.ts
   6| // 2. Run: bun scripts/generate-sdk-types.ts
   7| //
   8| // Schemas are available in coreSchemas.ts for runtime validation but are not
   9| // part of the public API.
  10| 
  11| // Re-export sandbox types for SDK consumers
  12| export type {
  13|   SandboxFilesystemConfig,
  14|   SandboxIgnoreViolations,
  15|   SandboxNetworkConfig,
  16|   SandboxSettings,
  17| } from '../sandboxTypes.js'
  18| // Re-export all generated types
  19| export * from './coreTypes.generated.js'
  20| 
  21| // Re-export utility types that can't be expressed as Zod schemas
  22| export type { NonNullableUsage } from './sdkUtilityTypes.js'

源码引用: src/entrypoints/agentSdkTypes.ts · 第 1–31 行(共 444 行)

   1| /**
   2|  * Main entrypoint for Claude Code Agent SDK types.
   3|  *
   4|  * This file re-exports the public SDK API from:
   5|  * - sdk/coreTypes.ts - Common serializable types (messages, configs)
   6|  * - sdk/runtimeTypes.ts - Non-serializable types (callbacks, interfaces)
   7|  *
   8|  * SDK builders who need control protocol types should import from
   9|  * sdk/controlTypes.ts directly.
  10|  */
  11| 
  12| import type {
  13|   CallToolResult,
  14|   ToolAnnotations,
  15| } from '@modelcontextprotocol/sdk/types.js'
  16| 
  17| // Control protocol types for SDK builders (bridge subpath consumers)
  18| /** @alpha */
  19| export type {
  20|   SDKControlRequest,
  21|   SDKControlResponse,
  22| } from './sdk/controlTypes.js'
  23| // Re-export core types (common serializable types)
  24| export * from './sdk/coreTypes.js'
  25| // Re-export runtime types (callbacks, interfaces with methods)
  26| export * from './sdk/runtimeTypes.js'
  27| 
  28| // Re-export settings types (generated from settings JSON schema)
  29| export type { Settings } from './sdk/settingsTypes.generated.js'
  30| // Re-export tool types (all marked @internal until SDK API stabilizes)
  31| export * from './sdk/toolTypes.js'

coreTypes:sandbox re-export 与 HOOK_EVENTS

coreTypes.ts 显式 re-export sandbox 配置类型:

export type { SandboxSettings, SandboxNetworkConfig, ... } from '../sandboxTypes.js'

这使 SDK 消费者 单一 import 路径 即可获得沙箱配置类型,与 settings 校验共用 Zod schema(见 sandbox-types 章)。

HOOK_EVENTS 数组列出 28+ hook 名:PreToolUse、PostToolUse、SessionStart、PermissionRequest、WorktreeCreate 等。运行时用于校验用户 hooks.json。

EXIT_REASONS — clear、resume、logout、prompt_input_exit、bypass_permissions_disabled 等,供 SDK 解析会话结束原因。

源码引用: src/entrypoints/sdk/coreTypes.ts · 第 11–62 行(共 63 行)

  11| // Re-export sandbox types for SDK consumers
  12| export type {
  13|   SandboxFilesystemConfig,
  14|   SandboxIgnoreViolations,
  15|   SandboxNetworkConfig,
  16|   SandboxSettings,
  17| } from '../sandboxTypes.js'
  18| // Re-export all generated types
  19| export * from './coreTypes.generated.js'
  20| 
  21| // Re-export utility types that can't be expressed as Zod schemas
  22| export type { NonNullableUsage } from './sdkUtilityTypes.js'
  23| 
  24| // Const arrays for runtime usage
  25| export const HOOK_EVENTS = [
  26|   'PreToolUse',
  27|   'PostToolUse',
  28|   'PostToolUseFailure',
  29|   'Notification',
  30|   'UserPromptSubmit',
  31|   'SessionStart',
  32|   'SessionEnd',
  33|   'Stop',
  34|   'StopFailure',
  35|   'SubagentStart',
  36|   'SubagentStop',
  37|   'PreCompact',
  38|   'PostCompact',
  39|   'PermissionRequest',
  40|   'PermissionDenied',
  41|   'Setup',
  42|   'TeammateIdle',
  43|   'TaskCreated',
  44|   'TaskCompleted',
  45|   'Elicitation',
  46|   'ElicitationResult',
  47|   'ConfigChange',
  48|   'WorktreeCreate',
  49|   'WorktreeRemove',
  50|   'InstructionsLoaded',
  51|   'CwdChanged',
  52|   'FileChanged',
  53| ] as const
  54| 
  55| export const EXIT_REASONS = [
  56|   'clear',
  57|   'resume',
  58|   'logout',
  59|   'prompt_input_exit',
  60|   'other',
  61|   'bypass_permissions_disabled',
  62| ] as const

源码引用: src/entrypoints/sdk/coreTypes.ts · 第 55–62 行(共 63 行)

  55| export const EXIT_REASONS = [
  56|   'clear',
  57|   'resume',
  58|   'logout',
  59|   'prompt_input_exit',
  60|   'other',
  61|   'bypass_permissions_disabled',
  62| ] as const

controlTypes:进程间控制帧

控制协议消息形状:

SDKControlRequest {
  type: 'control_request'
  request_id: string
  request: SDKControlRequestInner
}

Inner subtype:
  - initialize
  - cancel
  - permission
  - { subtype: string; ... }  // 扩展

SDKControlResponse 对称,带 request_id 与 response: Record<string, unknown>。

StdinMessage / StdoutMessage 为 loose 类型,允许协议演进。

SDK embedder 用 control 通道:

  • initialize → 握手 ok
  • permission → 转发 tool permission 到宿主 UI
  • cancel → 中止 in-flight query

源码引用: src/entrypoints/sdk/controlTypes.ts · 第 1–47 行(共 63 行)

   1| export type SDKControlInitializeRequest = {
   2|   subtype: 'initialize'
   3|   [key: string]: unknown
   4| }
   5| 
   6| export type SDKControlCancelRequest = {
   7|   subtype: 'cancel'
   8|   [key: string]: unknown
   9| }
  10| 
  11| export type SDKControlPermissionRequest = {
  12|   subtype: 'permission'
  13|   [key: string]: unknown
  14| }
  15| 
  16| export type SDKControlRequestInner =
  17|   | SDKControlInitializeRequest
  18|   | SDKControlCancelRequest
  19|   | SDKControlPermissionRequest
  20|   | { subtype: string; [key: string]: unknown }
  21| 
  22| export type SDKControlRequest = {
  23|   type: 'control_request'
  24|   request_id: string
  25|   request: SDKControlRequestInner
  26| }
  27| 
  28| export type SDKControlInitializeResponse = {
  29|   ok?: boolean
  30|   [key: string]: unknown
  31| }
  32| 
  33| export type SDKControlMcpSetServersResponse = {
  34|   ok?: boolean
  35|   [key: string]: unknown
  36| }
  37| 
  38| export type SDKControlReloadPluginsResponse = {
  39|   ok?: boolean
  40|   [key: string]: unknown
  41| }
  42| 
  43| export type SDKControlResponse = {
  44|   type: 'control_response'
  45|   request_id?: string
  46|   response: Record<string, unknown>
  47| }

源码引用: src/entrypoints/sdk/controlTypes.ts · 第 49–62 行(共 63 行)

  49| export type SDKPartialAssistantMessage = {
  50|   type: 'assistant'
  51|   [key: string]: unknown
  52| }
  53| 
  54| export type StdinMessage = {
  55|   type: string
  56|   [key: string]: unknown
  57| }
  58| 
  59| export type StdoutMessage = {
  60|   type: string
  61|   [key: string]: unknown
  62| }

runtimeTypes:Session 与 Query 占位

runtimeTypes.ts 大量 Record&lt;string, unknown&gt; 占位类型:

  • SDKSession、Options、Query、InternalQuery
  • ListSessionsOptions、ForkSessionOptions、ForkSessionResult
  • McpSdkServerConfigWithInstance

SdkMcpToolDefinition<Schema> 保留 schema 泛型字段,供 SDK 内 MCP tool 注册。

InferShape<T> 与 AnyZodRawShape 辅助 agentSdkTypes 的 tool() 函数推断 args 类型。

这些类型在 SDK 实现完善前保持宽松,避免每次内部 refactor 破坏 npm 包类型 semver。

源码引用: src/entrypoints/sdk/runtimeTypes.ts · 第 1–22 行(共 23 行)

   1| export type EffortLevel = 'low' | 'medium' | 'high' | string
   2| export type SDKSession = Record<string, unknown>
   3| export type SDKSessionOptions = Record<string, unknown>
   4| export type SDKSessionInfo = Record<string, unknown>
   5| export type SessionMessage = Record<string, unknown>
   6| export type ListSessionsOptions = Record<string, unknown>
   7| export type GetSessionInfoOptions = Record<string, unknown>
   8| export type GetSessionMessagesOptions = Record<string, unknown>
   9| export type SessionMutationOptions = Record<string, unknown>
  10| export type ForkSessionOptions = Record<string, unknown>
  11| export type ForkSessionResult = Record<string, unknown>
  12| export type Options = Record<string, unknown>
  13| export type InternalOptions = Record<string, unknown>
  14| export type Query = Record<string, unknown>
  15| export type InternalQuery = Record<string, unknown>
  16| export type McpSdkServerConfigWithInstance = Record<string, unknown>
  17| export type AnyZodRawShape = Record<string, unknown>
  18| export type InferShape<T> = T
  19| export type SdkMcpToolDefinition<Schema> = {
  20|   schema?: Schema
  21|   [key: string]: unknown
  22| }

源码引用: src/entrypoints/sdk/runtimeTypes.ts · 第 19–22 行(共 23 行)

  19| export type SdkMcpToolDefinition<Schema> = {
  20|   schema?: Schema
  21|   [key: string]: unknown
  22| }

agentSdkTypes:公共聚合层

agentSdkTypes.ts re-export:

export * from './sdk/coreTypes.js'
export * from './sdk/runtimeTypes.js'
export type { Settings } from './sdk/settingsTypes.generated.js'
export * from './sdk/toolTypes.js'  // @internal
export type { SDKControlRequest, SDKControlResponse } from './sdk/controlTypes.js'  // @alpha

文件后半 Functions 区 import core/runtime 类型定义:

  • tool(name, description, inputSchema, handler) — MCP SDK CallToolResult
  • query() / session API(签名在 generated 区)

@alpha control 类型提醒:embed API 尚未稳定。

源码引用: src/entrypoints/agentSdkTypes.ts · 第 17–31 行(共 444 行)

  17| // Control protocol types for SDK builders (bridge subpath consumers)
  18| /** @alpha */
  19| export type {
  20|   SDKControlRequest,
  21|   SDKControlResponse,
  22| } from './sdk/controlTypes.js'
  23| // Re-export core types (common serializable types)
  24| export * from './sdk/coreTypes.js'
  25| // Re-export runtime types (callbacks, interfaces with methods)
  26| export * from './sdk/runtimeTypes.js'
  27| 
  28| // Re-export settings types (generated from settings JSON schema)
  29| export type { Settings } from './sdk/settingsTypes.generated.js'
  30| // Re-export tool types (all marked @internal until SDK API stabilizes)
  31| export * from './sdk/toolTypes.js'

源码引用: src/entrypoints/agentSdkTypes.ts · 第 37–71 行(共 444 行)

  37| import type {
  38|   SDKMessage,
  39|   SDKResultMessage,
  40|   SDKSessionInfo,
  41|   SDKUserMessage,
  42| } from './sdk/coreTypes.js'
  43| // Import types needed for function signatures
  44| import type {
  45|   AnyZodRawShape,
  46|   ForkSessionOptions,
  47|   ForkSessionResult,
  48|   GetSessionInfoOptions,
  49|   GetSessionMessagesOptions,
  50|   InferShape,
  51|   InternalOptions,
  52|   InternalQuery,
  53|   ListSessionsOptions,
  54|   McpSdkServerConfigWithInstance,
  55|   Options,
  56|   Query,
  57|   SDKSession,
  58|   SDKSessionOptions,
  59|   SdkMcpToolDefinition,
  60|   SessionMessage,
  61|   SessionMutationOptions,
  62| } from './sdk/runtimeTypes.js'
  63| 
  64| export type {
  65|   ListSessionsOptions,
  66|   GetSessionInfoOptions,
  67|   SessionMutationOptions,
  68|   ForkSessionOptions,
  69|   ForkSessionResult,
  70|   SDKSessionInfo,
  71| }

tool() helper 与 MCP 互操作

agentSdkTypes tool() 函数签名(约 73 行):

export function tool<Schema extends AnyZodRawShape>(
  _name: string,
  _description: string,
  _inputSchema: Schema,
  _handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>,
)

import CallToolResult、ToolAnnotations 自 @modelcontextprotocol/sdk/types.js,保证 SDK 定义的 MCP tool 与 MCP 规范一致。

这与 entrypoints/mcp.ts 暴露的 ListTools / CallTool 形成 对内实现 vs 对外 SDK 定义 的对称。

源码引用: src/entrypoints/agentSdkTypes.ts · 第 73–85 行(共 444 行)

  73| export function tool<Schema extends AnyZodRawShape>(
  74|   _name: string,
  75|   _description: string,
  76|   _inputSchema: Schema,
  77|   _handler: (
  78|     args: InferShape<Schema>,
  79|     extra: unknown,
  80|   ) => Promise<CallToolResult>,
  81|   _extras?: {
  82|     annotations?: ToolAnnotations
  83|     searchHint?: string
  84|     alwaysLoad?: boolean
  85|   },

源码引用: src/entrypoints/agentSdkTypes.ts · 第 12–15 行(共 444 行)

  12| import type {
  13|   CallToolResult,
  14|   ToolAnnotations,
  15| } from '@modelcontextprotocol/sdk/types.js'

coreSchemas 与 sdkUtilityTypes

coreSchemas.ts 嵌入 sandbox、message、config 等 Zod schema,runtime validate SDK 线协议 JSON。

sdkUtilityTypes.ts 导出 NonNullableUsage 等 hand-written utility,coreTypes re-export——因 Zod 无法表达某些 TS utility 类型。

集成测试 import coreTypes message 做 snapshot,避免 import main.tsx 图。

修改 workflow:edit coreSchemas → generate-sdk-types → 更新 consumer snapshot。

源码引用: src/entrypoints/sdk/coreSchemas.ts · 第 1–25 行(共 1890 行)

   1| /**
   2|  * SDK Core Schemas - Zod schemas for serializable SDK data types.
   3|  *
   4|  * These schemas are the single source of truth for SDK data types.
   5|  * TypeScript types are generated from these schemas and committed for IDE support.
   6|  *
   7|  * @see scripts/generate-sdk-types.ts for type generation
   8|  */
   9| 
  10| import { z } from 'zod/v4'
  11| import { lazySchema } from '../../utils/lazySchema.js'
  12| 
  13| // ============================================================================
  14| // Usage & Model Types
  15| // ============================================================================
  16| 
  17| export const ModelUsageSchema = lazySchema(() =>
  18|   z.object({
  19|     inputTokens: z.number(),
  20|     outputTokens: z.number(),
  21|     cacheReadInputTokens: z.number(),
  22|     cacheCreationInputTokens: z.number(),
  23|     webSearchRequests: z.number(),
  24|     costUSD: z.number(),
  25|     contextWindow: z.number(),

源码引用: src/entrypoints/sdk/sdkUtilityTypes.ts · 第 1–7 行(共 7 行)

   1| export type NonNullableUsage = {
   2|   input_tokens: number
   3|   output_tokens: number
   4|   cache_creation_input_tokens?: number
   5|   cache_read_input_tokens?: number
   6| }
   7| 

SDKMessage 与生成类型

coreTypes.generated.ts 含 SDKMessage、SDKUserMessage、SDKResultMessage 等线协议 discriminated union。agentSdkTypes 的 query()、session API 签名 import 这些类型。

修改 message shape 时,integration test 与 VS Code extension 可能同时 break——优先跑 generate-sdk-types 与 SDK 包 typecheck。

settingsTypes.generated.ts 与 CLI settings.json schema 锁步,避免 Settings 类型与 ValidationPipe 不一致。

toolTypes 与 settingsTypes

toolTypes.ts 导出 SDK 内部 tool 形状,agentSdkTypes 全量 re-export 但文档标记 @internal——外部 npm 消费者不应依赖,semver 不保证稳定。

settingsTypes.generated.ts 从 settings JSON schema 生成 Settings 类型,与 CLI settings.json 校验同源。

controlSchemas.ts 与 coreSchemas 并列,供 SDK builder 校验 control 帧;不经过 agentSdkTypes 公开 export。

集成方应只依赖 coreTypes + runtimeTypes + Settings,control 仅 embed 场景 @alpha 使用。

源码引用: src/entrypoints/agentSdkTypes.ts · 第 28–31 行(共 444 行)

  28| // Re-export settings types (generated from settings JSON schema)
  29| export type { Settings } from './sdk/settingsTypes.generated.js'
  30| // Re-export tool types (all marked @internal until SDK API stabilizes)
  31| export * from './sdk/toolTypes.js'

源码引用: src/entrypoints/sdk/toolTypes.ts · 第 1–2 行(共 2 行)

   1| export type SDKToolDefinition = Record<string, unknown>
   2| 

本章小结与延伸

SDK 类型 = core(JSON)+ runtime(接口)+ control(进程控制)。sandbox 类型从 sandboxTypes 汇入 core。修改 schema 后务必跑 generate-sdk-types 并更新 snapshot 测试。 继续学习:

  • sandbox-types
  • mcp-entrypoint
Prev
cli-entrypoint · Bootstrap 与快路径
Next
mcp-entrypoint · MCP stdio 服务器