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

本章总览

skills/bundled/ 目录通过 initBundledSkills() 在 main.tsx 启动时注册内置 skill:verify(测试验证)、remember(内存整理)、claude-api(多语言 API 文档)等。feature flag 与 isEnabled 回调控制外部 build 可见性。本章走读 index.ts 注册顺序与三个代表性 skill 实现。

学完本章你应该能

  • 列举 initBundledSkills 无条件与 feature-gated 注册项
  • 说明 verify skill 与 verifyContent / SKILL.md 关系
  • 解释 remember skill 的 ant-only gate 与 auto-memory 依赖
  • 描述 claudeApi.ts 语言检测与 claudeApiContent 懒加载
  • 理解新增 bundled skill 的三步流程(index 注释)
  • 区分 feature() DCE 与 isEnabled 运行时 gate

核心概念(先读懂这些)

bundled skill 与 disk skill 用户感知一致

用户看到 /verify、/remember 与自定义 SKILL.md 同为 slash command。差别在 source=bundled、compiled into binary、files 可能 extract 到 temp dir。disableModelInvocation 等 flag 仍可通过 registerBundledSkill 设置。

feature() + require 延迟加载 ant-only skill

dream、hunter、loop、claudeApi 等用 feature() 包裹 require("./xxx.js"),外部 build DCE 掉整个 block。loop 的 isEnabled 仍委托 isKairosCronEnabled 做 per-invocation 可见性。

建议学习步骤

  1. 阅读 initBundledSkills 全文(源码块 A)
  2. 阅读 registerVerifySkill(源码块 B)
  3. 阅读 registerRememberSkill(源码块 C)
  4. 阅读 registerClaudeApiSkill 语言检测(源码块 D、E)
  5. 阅读 loop / scheduleRemoteAgents feature gate(源码块 F)

常见误区

注意

remember 仅 USER_TYPE===ant 注册

注意

claudeApiContent.js 247KB 仅在 invoke 时 dynamic import

注意

verify bundled 目录含 examples/*.md 由 verifyContent 引用

initBundledSkills 启动注册

main.tsx 约 1925 行 initBundledSkills() 在 init 后、getCommands 前执行。

无条件注册(index.ts 24-34):

  • updateConfig, keybindings, verify, debug, loremIpsum
  • skillify, remember, simplify, batch, stuck

feature-gated:

FeatureSkill
KAIROS / KAIROS_DREAMdream
REVIEW_ARTIFACThunter
AGENT_TRIGGERSloop
AGENT_TRIGGERS_REMOTEscheduleRemoteAgents
BUILDING_CLAUDE_APPSclaude-api
RUN_SKILL_GENERATORrunSkillGenerator

shouldAutoEnableClaudeInChrome() → claude-in-chrome skill

源码引用: src/skills/bundled/index.ts · 第 15–79 行(共 80 行)

  15| /**
  16|  * Initialize all bundled skills.
  17|  * Called at startup to register skills that ship with the CLI.
  18|  *
  19|  * To add a new bundled skill:
  20|  * 1. Create a new file in src/skills/bundled/ (e.g., myskill.ts)
  21|  * 2. Export a register function that calls registerBundledSkill()
  22|  * 3. Import and call that function here
  23|  */
  24| export function initBundledSkills(): void {
  25|   registerUpdateConfigSkill()
  26|   registerKeybindingsSkill()
  27|   registerVerifySkill()
  28|   registerDebugSkill()
  29|   registerLoremIpsumSkill()
  30|   registerSkillifySkill()
  31|   registerRememberSkill()
  32|   registerSimplifySkill()
  33|   registerBatchSkill()
  34|   registerStuckSkill()
  35|   if (feature('KAIROS') || feature('KAIROS_DREAM')) {
  36|     /* eslint-disable @typescript-eslint/no-require-imports */
  37|     const { registerDreamSkill } = require('./dream.js')
  38|     /* eslint-enable @typescript-eslint/no-require-imports */
  39|     registerDreamSkill()
  40|   }
  41|   if (feature('REVIEW_ARTIFACT')) {
  42|     /* eslint-disable @typescript-eslint/no-require-imports */
  43|     const { registerHunterSkill } = require('./hunter.js')
  44|     /* eslint-enable @typescript-eslint/no-require-imports */
  45|     registerHunterSkill()
  46|   }
  47|   if (feature('AGENT_TRIGGERS')) {
  48|     /* eslint-disable @typescript-eslint/no-require-imports */
  49|     const { registerLoopSkill } = require('./loop.js')
  50|     /* eslint-enable @typescript-eslint/no-require-imports */
  51|     // /loop's isEnabled delegates to isKairosCronEnabled() — same lazy
  52|     // per-invocation pattern as the cron tools. Registered unconditionally;
  53|     // the skill's own isEnabled callback decides visibility.
  54|     registerLoopSkill()
  55|   }
  56|   if (feature('AGENT_TRIGGERS_REMOTE')) {
  57|     /* eslint-disable @typescript-eslint/no-require-imports */
  58|     const {
  59|       registerScheduleRemoteAgentsSkill,
  60|     } = require('./scheduleRemoteAgents.js')
  61|     /* eslint-enable @typescript-eslint/no-require-imports */
  62|     registerScheduleRemoteAgentsSkill()
  63|   }
  64|   if (feature('BUILDING_CLAUDE_APPS')) {
  65|     /* eslint-disable @typescript-eslint/no-require-imports */
  66|     const { registerClaudeApiSkill } = require('./claudeApi.js')
  67|     /* eslint-enable @typescript-eslint/no-require-imports */
  68|     registerClaudeApiSkill()
  69|   }
  70|   if (shouldAutoEnableClaudeInChrome()) {
  71|     registerClaudeInChromeSkill()
  72|   }
  73|   if (feature('RUN_SKILL_GENERATOR')) {
  74|     /* eslint-disable @typescript-eslint/no-require-imports */
  75|     const { registerRunSkillGeneratorSkill } = require('./runSkillGenerator.js')
  76|     /* eslint-enable @typescript-eslint/no-require-imports */
  77|     registerRunSkillGeneratorSkill()
  78|   }
  79| }

源码引用: src/main.tsx · 第 98–98 行(共 6604 行)

  98| import {

新增 bundled skill 流程

index.ts 头注释三步:

  1. 在 src/skills/bundled/ 新建 myskill.ts
  2. export registerMySkill() 内部调用 registerBundledSkill({...})
  3. 在 initBundledSkills import 并调用

可选:

  • files: { 'doc.md': '...' } 或单独 content module 懒加载
  • isEnabled: () => feature(...) 运行时隐藏
  • context: 'fork' 隔离 subagent 执行

与 disk skill 不同:无 SKILL.md 文件,prompt 在 TS 字符串或 imported content。

源码引用: src/skills/bundled/index.ts · 第 15–23 行(共 80 行)

  15| /**
  16|  * Initialize all bundled skills.
  17|  * Called at startup to register skills that ship with the CLI.
  18|  *
  19|  * To add a new bundled skill:
  20|  * 1. Create a new file in src/skills/bundled/ (e.g., myskill.ts)
  21|  * 2. Export a register function that calls registerBundledSkill()
  22|  * 3. Import and call that function here
  23|  */

verify skill

registerVerifySkill(verify.ts)注册 verify skill:

  • 引导模型按 repo 类型(CLI/server/web)执行验证流程
  • bundled/verify/SKILL.md 与 verifyContent.ts 提供静态 prompt 片段
  • examples/server.md、examples/cli.md 作 reference

userInvocable: true — 用户可 /verify;模型也可 SkillTool 调用。

与 REVIEW_ARTIFACT hunter 区分:verify 通用测试验证,hunter 面向 artifact review feature。

源码引用: src/skills/bundled/verify.ts · 第 1–31 行(共 31 行)

   1| import { parseFrontmatter } from '../../utils/frontmatterParser.js'
   2| import { registerBundledSkill } from '../bundledSkills.js'
   3| import { SKILL_FILES, SKILL_MD } from './verifyContent.js'
   4| 
   5| const { frontmatter, content: SKILL_BODY } = parseFrontmatter(SKILL_MD)
   6| 
   7| const DESCRIPTION =
   8|   typeof frontmatter.description === 'string'
   9|     ? frontmatter.description
  10|     : 'Verify a code change does what it should by running the app.'
  11| 
  12| export function registerVerifySkill(): void {
  13|   if (process.env.USER_TYPE !== 'ant') {
  14|     return
  15|   }
  16| 
  17|   registerBundledSkill({
  18|     name: 'verify',
  19|     description: DESCRIPTION,
  20|     userInvocable: true,
  21|     files: SKILL_FILES,
  22|     async getPromptForCommand(args) {
  23|       const parts: string[] = [SKILL_BODY.trimStart()]
  24|       if (args) {
  25|         parts.push(`## User Request\n\n${args}`)
  26|       }
  27|       return [{ type: 'text', text: parts.join('\n\n') }]
  28|     },
  29|   })
  30| }
  31| 

源码缺失

File not found: c:\Users\123\Desktop\jd\Claude code源码\claude-code-complete\claude-code-complete\src-readable\skills\bundled\verify\SKILL.md

remember skill

registerRememberSkill ant-only:

if (process.env.USER_TYPE !== 'ant') return

isEnabled: () => isAutoMemoryEnabled() — 无 auto-memory 时不显示。

SKILL_PROMPT 长字符串定义四步:

  1. 收集 CLAUDE.md / CLAUDE.local.md / auto-memory
  2. 分类 promotion 目标
  3. 识别 duplicate/outdated/conflict
  4. 结构化报告 不自动改文件

args 追加到 "## Additional context from user" 节。

源码引用: src/skills/bundled/remember.ts · 第 4–80 行(共 83 行)

   4| export function registerRememberSkill(): void {
   5|   if (process.env.USER_TYPE !== 'ant') {
   6|     return
   7|   }
   8| 
   9|   const SKILL_PROMPT = `# Memory Review
  10| 
  11| ## Goal
  12| Review the user's memory landscape and produce a clear report of proposed changes, grouped by action type. Do NOT apply changes — present proposals for user approval.
  13| 
  14| ## Steps
  15| 
  16| ### 1. Gather all memory layers
  17| Read CLAUDE.md and CLAUDE.local.md from the project root (if they exist). Your auto-memory content is already in your system prompt — review it there. Note which team memory sections exist, if any.
  18| 
  19| **Success criteria**: You have the contents of all memory layers and can compare them.
  20| 
  21| ### 2. Classify each auto-memory entry
  22| For each substantive entry in auto-memory, determine the best destination:
  23| 
  24| | Destination | What belongs there | Examples |
  25| |---|---|---|
  26| | **CLAUDE.md** | Project conventions and instructions for Claude that all contributors should follow | "use bun not npm", "API routes use kebab-case", "test command is bun test", "prefer functional style" |
  27| | **CLAUDE.local.md** | Personal instructions for Claude specific to this user, not applicable to other contributors | "I prefer concise responses", "always explain trade-offs", "don't auto-commit", "run tests before committing" |
  28| | **Team memory** | Org-wide knowledge that applies across repositories (only if team memory is configured) | "deploy PRs go through #deploy-queue", "staging is at staging.internal", "platform team owns infra" |
  29| | **Stay in auto-memory** | Working notes, temporary context, or entries that don't clearly fit elsewhere | Session-specific observations, uncertain patterns |
  30| 
  31| **Important distinctions:**
  32| - CLAUDE.md and CLAUDE.local.md contain instructions for Claude, not user preferences for external tools (editor theme, IDE keybindings, etc. don't belong in either)
  33| - Workflow practices (PR conventions, merge strategies, branch naming) are ambiguous — ask the user whether they're personal or team-wide
  34| - When unsure, ask rather than guess
  35| 
  36| **Success criteria**: Each entry has a proposed destination or is flagged as ambiguous.
  37| 
  38| ### 3. Identify cleanup opportunities
  39| Scan across all layers for:
  40| - **Duplicates**: Auto-memory entries already captured in CLAUDE.md or CLAUDE.local.md → propose removing from auto-memory
  41| - **Outdated**: CLAUDE.md or CLAUDE.local.md entries contradicted by newer auto-memory entries → propose updating the older layer
  42| - **Conflicts**: Contradictions between any two layers → propose resolution, noting which is more recent
  43| 
  44| **Success criteria**: All cross-layer issues identified.
  45| 
  46| ### 4. Present the report
  47| Output a structured report grouped by action type:
  48| 1. **Promotions** — entries to move, with destination and rationale
  49| 2. **Cleanup** — duplicates, outdated entries, conflicts to resolve
  50| 3. **Ambiguous** — entries where you need the user's input on destination
  51| 4. **No action needed** — brief note on entries that should stay put
  52| 
  53| If auto-memory is empty, say so and offer to review CLAUDE.md for cleanup.
  54| 
  55| **Success criteria**: User can review and approve/reject each proposal individually.
  56| 
  57| ## Rules
  58| - Present ALL proposals before making any changes
  59| - Do NOT modify files without explicit user approval
  60| - Do NOT create new files unless the target doesn't exist yet
  61| - Ask about ambiguous entries — don't guess
  62| `
  63| 
  64|   registerBundledSkill({
  65|     name: 'remember',
  66|     description:
  67|       'Review auto-memory entries and propose promotions to CLAUDE.md, CLAUDE.local.md, or shared memory. Also detects outdated, conflicting, and duplicate entries across memory layers.',
  68|     whenToUse:
  69|       'Use when the user wants to review, organize, or promote their auto-memory entries. Also useful for cleaning up outdated or conflicting entries across CLAUDE.md, CLAUDE.local.md, and auto-memory.',
  70|     userInvocable: true,
  71|     isEnabled: () => isAutoMemoryEnabled(),
  72|     async getPromptForCommand(args) {
  73|       let prompt = SKILL_PROMPT
  74| 
  75|       if (args) {
  76|         prompt += `\n## Additional context from user\n\n${args}`
  77|       }
  78| 
  79|       return [{ type: 'text', text: prompt }]
  80|     },

claude-api skill:语言检测

registerClaudeApiSkill(feature BUILDING_CLAUDE_APPS):

detectLanguage() 读 cwd 目录项:

  • python: .py, requirements.txt, pyproject.toml
  • typescript: .ts, .tsx, tsconfig.json
  • java/go/ruby/csharp/php 类似
  • curl: 无 indicator 时 fallback

getFilesForLanguage 从 claudeApiContent.SKILL_FILES 过滤 {lang}/ 与 shared/ 前缀。

247KB markdown 在 claudeApiContent.js,注释说明 lazy-load inside getPromptForCommand。

源码引用: src/skills/bundled/claudeApi.ts · 第 5–53 行(共 197 行)

   5| // claudeApiContent.js bundles 247KB of .md strings. Lazy-load inside
   6| // getPromptForCommand so they only enter memory when /claude-api is invoked.
   7| type SkillContent = typeof import('./claudeApiContent.js')
   8| 
   9| type DetectedLanguage =
  10|   | 'python'
  11|   | 'typescript'
  12|   | 'java'
  13|   | 'go'
  14|   | 'ruby'
  15|   | 'csharp'
  16|   | 'php'
  17|   | 'curl'
  18| 
  19| const LANGUAGE_INDICATORS: Record<DetectedLanguage, string[]> = {
  20|   python: ['.py', 'requirements.txt', 'pyproject.toml', 'setup.py', 'Pipfile'],
  21|   typescript: ['.ts', '.tsx', 'tsconfig.json', 'package.json'],
  22|   java: ['.java', 'pom.xml', 'build.gradle'],
  23|   go: ['.go', 'go.mod'],
  24|   ruby: ['.rb', 'Gemfile'],
  25|   csharp: ['.cs', '.csproj'],
  26|   php: ['.php', 'composer.json'],
  27|   curl: [],
  28| }
  29| 
  30| async function detectLanguage(): Promise<DetectedLanguage | null> {
  31|   const cwd = getCwd()
  32|   let entries: string[]
  33|   try {
  34|     entries = await readdir(cwd)
  35|   } catch {
  36|     return null
  37|   }
  38| 
  39|   for (const [lang, indicators] of Object.entries(LANGUAGE_INDICATORS) as [
  40|     DetectedLanguage,
  41|     string[],
  42|   ][]) {
  43|     if (indicators.length === 0) continue
  44|     for (const indicator of indicators) {
  45|       if (indicator.startsWith('.')) {
  46|         if (entries.some(e => e.endsWith(indicator))) return lang
  47|       } else {
  48|         if (entries.includes(indicator)) return lang
  49|       }
  50|     }
  51|   }
  52|   return null
  53| }

源码引用: src/skills/bundled/claudeApi.ts · 第 55–70 行(共 197 行)

  55| function getFilesForLanguage(
  56|   lang: DetectedLanguage,
  57|   content: SkillContent,
  58| ): string[] {
  59|   return Object.keys(content.SKILL_FILES).filter(
  60|     path => path.startsWith(`${lang}/`) || path.startsWith('shared/'),
  61|   )
  62| }
  63| 
  64| function processContent(md: string, content: SkillContent): string {
  65|   // Strip HTML comments. Loop to handle nested comments.
  66|   let out = md
  67|   let prev
  68|   do {
  69|     prev = out
  70|     out = out.replace(/<!--[\s\S]*?-->\n?/g, '')

claude-api 资源树

bundled/claude-api/ 含多语言 markdown:

claude-api/
  SKILL.md
  typescript/claude-api/*.md
  python/claude-api/*.md
  shared/models.md, error-codes.md, ...

register 时通过 files 或 content module 映射;首次 /claude-api 触发 extractBundledSkillFiles。

BUILDING_CLAUDE_APPS 外部 build 不包含此 skill,避免 bundle 体积膨胀。

SDK 文档类 skill 示范:大资源 + 懒加载 + language-aware 裁剪。

源码引用: src/skills/bundled/claudeApi.ts · 第 70–120 行(共 197 行)

  70|     out = out.replace(/<!--[\s\S]*?-->\n?/g, '')
  71|   } while (out !== prev)
  72| 
  73|   out = out.replace(
  74|     /\{\{(\w+)\}\}/g,
  75|     (match, key: string) =>
  76|       (content.SKILL_MODEL_VARS as Record<string, string>)[key] ?? match,
  77|   )
  78|   return out
  79| }
  80| 
  81| function buildInlineReference(
  82|   filePaths: string[],
  83|   content: SkillContent,
  84| ): string {
  85|   const sections: string[] = []
  86|   for (const filePath of filePaths.sort()) {
  87|     const md = content.SKILL_FILES[filePath]
  88|     if (!md) continue
  89|     sections.push(
  90|       `<doc path="${filePath}">\n${processContent(md, content).trim()}\n</doc>`,
  91|     )
  92|   }
  93|   return sections.join('\n\n')
  94| }
  95| 
  96| const INLINE_READING_GUIDE = `## Reference Documentation
  97| 
  98| The relevant documentation for your detected language is included below in \`<doc>\` tags. Each tag has a \`path\` attribute showing its original file path. Use this to find the right section:
  99| 
 100| ### Quick Task Reference
 101| 
 102| **Single text classification/summarization/extraction/Q&A:**
 103| → Refer to \`{lang}/claude-api/README.md\`
 104| 
 105| **Chat UI or real-time response display:**
 106| → Refer to \`{lang}/claude-api/README.md\` + \`{lang}/claude-api/streaming.md\`
 107| 
 108| **Long-running conversations (may exceed context window):**
 109| → Refer to \`{lang}/claude-api/README.md\` — see Compaction section
 110| 
 111| **Prompt caching / optimize caching / "why is my cache hit rate low":**
 112| → Refer to \`shared/prompt-caching.md\` + \`{lang}/claude-api/README.md\` (Prompt Caching section)
 113| 
 114| **Function calling / tool use / agents:**
 115| → Refer to \`{lang}/claude-api/README.md\` + \`shared/tool-use-concepts.md\` + \`{lang}/claude-api/tool-use.md\`
 116| 
 117| **Batch processing (non-latency-sensitive):**
 118| → Refer to \`{lang}/claude-api/README.md\` + \`{lang}/claude-api/batches.md\`
 119| 
 120| **File uploads across multiple requests:**

源码缺失

File not found: c:\Users\123\Desktop\jd\Claude code源码\claude-code-complete\claude-code-complete\src-readable\skills\bundled\claude-api\SKILL.md

verifyContent 与 bundled markdown

verifyContent.ts 聚合 bundled/verify/*.md 字符串,verify.ts register 时传入 getPromptForCommand。

与 claude-api 不同,verify 资源较小,可 eager import;claude-api 用 claudeApiContent.js 247KB lazy。

SKILL.md 在 bundled/verify/ 供人类阅读与 generator 同步;runtime 以 TS 常量为准。

源码引用: src/skills/bundled/verifyContent.ts · 第 1–14 行(共 14 行)

   1| // Content for the verify bundled skill.
   2| // Each .md file is inlined as a string at build time via Bun's text loader.
   3| 
   4| import cliMd from './verify/examples/cli.md'
   5| import serverMd from './verify/examples/server.md'
   6| import skillMd from './verify/SKILL.md'
   7| 
   8| export const SKILL_MD: string = skillMd
   9| 
  10| export const SKILL_FILES: Record<string, string> = {
  11|   'examples/cli.md': cliMd,
  12|   'examples/server.md': serverMd,
  13| }
  14| 

runSkillGenerator 与 dream/hunter

RUN_SKILL_GENERATOR feature 注册 runSkillGenerator,引导用户创建新 SKILL.md。

KAIROS_DREAM 注册 dream skill;REVIEW_ARTIFACT 注册 hunter——均属 ant-only 实验能力,外部 OSS build 不含。

pattern:if (feature('X')) { require('./y.js'); registerY() } 保证 tree-shaking 彻底移除 dead code。

源码引用: src/skills/bundled/index.ts · 第 35–46 行(共 80 行)

  35|   if (feature('KAIROS') || feature('KAIROS_DREAM')) {
  36|     /* eslint-disable @typescript-eslint/no-require-imports */
  37|     const { registerDreamSkill } = require('./dream.js')
  38|     /* eslint-enable @typescript-eslint/no-require-imports */
  39|     registerDreamSkill()
  40|   }
  41|   if (feature('REVIEW_ARTIFACT')) {
  42|     /* eslint-disable @typescript-eslint/no-require-imports */
  43|     const { registerHunterSkill } = require('./hunter.js')
  44|     /* eslint-enable @typescript-eslint/no-require-imports */
  45|     registerHunterSkill()
  46|   }

debug / simplify / batch 速览

debug skill 引导收集会话诊断信息;simplify 要求模型精简未提交变更;batch 批量处理相似任务。

三者均 userInvocable: true,prompt 为 TS 字符串常量,无外部 md 依赖。

loremIpsum 用于 UI/测试占位;skillify 把重复 workflow 转为 SKILL.md 结构。

注册模式相同:registerXSkill() { registerBundledSkill({ name, description, getPromptForCommand }) }。

源码引用: src/skills/bundled/debug.ts · 第 1–25 行(共 104 行)

   1| import { open, stat } from 'fs/promises'
   2| import { CLAUDE_CODE_GUIDE_AGENT_TYPE } from 'src/tools/AgentTool/built-in/claudeCodeGuideAgent.js'
   3| import { getSettingsFilePathForSource } from 'src/utils/settings/settings.js'
   4| import { enableDebugLogging, getDebugLogPath } from '../../utils/debug.js'
   5| import { errorMessage, isENOENT } from '../../utils/errors.js'
   6| import { formatFileSize } from '../../utils/format.js'
   7| import { registerBundledSkill } from '../bundledSkills.js'
   8| 
   9| const DEFAULT_DEBUG_LINES_READ = 20
  10| const TAIL_READ_BYTES = 64 * 1024
  11| 
  12| export function registerDebugSkill(): void {
  13|   registerBundledSkill({
  14|     name: 'debug',
  15|     description:
  16|       process.env.USER_TYPE === 'ant'
  17|         ? 'Debug your current Claude Code session by reading the session debug log. Includes all event logging'
  18|         : 'Enable debug logging for this session and help diagnose issues',
  19|     allowedTools: ['Read', 'Grep', 'Glob'],
  20|     argumentHint: '[issue description]',
  21|     // disableModelInvocation so that the user has to explicitly request it in
  22|     // interactive mode and so the description does not take up context.
  23|     disableModelInvocation: true,
  24|     userInvocable: true,
  25|     async getPromptForCommand(args) {

源码引用: src/skills/bundled/simplify.ts · 第 1–25 行(共 70 行)

   1| import { AGENT_TOOL_NAME } from '../../tools/AgentTool/constants.js'
   2| import { registerBundledSkill } from '../bundledSkills.js'
   3| 
   4| const SIMPLIFY_PROMPT = `# Simplify: Code Review and Cleanup
   5| 
   6| Review all changed files for reuse, quality, and efficiency. Fix any issues found.
   7| 
   8| ## Phase 1: Identify Changes
   9| 
  10| Run \`git diff\` (or \`git diff HEAD\` if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation.
  11| 
  12| ## Phase 2: Launch Three Review Agents in Parallel
  13| 
  14| Use the ${AGENT_TOOL_NAME} tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context.
  15| 
  16| ### Agent 1: Code Reuse Review
  17| 
  18| For each change:
  19| 
  20| 1. **Search for existing utilities and helpers** that could replace newly written code. Look for similar patterns elsewhere in the codebase — common locations are utility directories, shared modules, and files adjacent to the changed ones.
  21| 2. **Flag any new function that duplicates existing functionality.** Suggest the existing function to use instead.
  22| 3. **Flag any inline logic that could use an existing utility** — hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates.
  23| 
  24| ### Agent 2: Code Quality Review
  25| 

loop 与 scheduleRemoteAgents

AGENT_TRIGGERS feature 注册 loop skill:/loop 委托 isKairosCronEnabled() 决定可见性,与 cron tools 一致 per-invocation gate。

AGENT_TRIGGERS_REMOTE 注册 scheduleRemoteAgents,远程 agent 调度 onboarding。

两者用 require 延迟加载,外部 OSS build DCE 整个 block。initBundledSkills 注释说明 loop 无条件 register 但 isEnabled 控制显示。

源码引用: src/skills/bundled/index.ts · 第 47–63 行(共 80 行)

  47|   if (feature('AGENT_TRIGGERS')) {
  48|     /* eslint-disable @typescript-eslint/no-require-imports */
  49|     const { registerLoopSkill } = require('./loop.js')
  50|     /* eslint-enable @typescript-eslint/no-require-imports */
  51|     // /loop's isEnabled delegates to isKairosCronEnabled() — same lazy
  52|     // per-invocation pattern as the cron tools. Registered unconditionally;
  53|     // the skill's own isEnabled callback decides visibility.
  54|     registerLoopSkill()
  55|   }
  56|   if (feature('AGENT_TRIGGERS_REMOTE')) {
  57|     /* eslint-disable @typescript-eslint/no-require-imports */
  58|     const {
  59|       registerScheduleRemoteAgentsSkill,
  60|     } = require('./scheduleRemoteAgents.js')
  61|     /* eslint-enable @typescript-eslint/no-require-imports */
  62|     registerScheduleRemoteAgentsSkill()
  63|   }

源码引用: src/skills/bundled/loop.ts · 第 1–30 行(共 93 行)

   1| import {
   2|   CRON_CREATE_TOOL_NAME,
   3|   CRON_DELETE_TOOL_NAME,
   4|   DEFAULT_MAX_AGE_DAYS,
   5|   isKairosCronEnabled,
   6| } from '../../tools/ScheduleCronTool/prompt.js'
   7| import { registerBundledSkill } from '../bundledSkills.js'
   8| 
   9| const DEFAULT_INTERVAL = '10m'
  10| 
  11| const USAGE_MESSAGE = `Usage: /loop [interval] <prompt>
  12| 
  13| Run a prompt or slash command on a recurring interval.
  14| 
  15| Intervals: Ns, Nm, Nh, Nd (e.g. 5m, 30m, 2h, 1d). Minimum granularity is 1 minute.
  16| If no interval is specified, defaults to ${DEFAULT_INTERVAL}.
  17| 
  18| Examples:
  19|   /loop 5m /babysit-prs
  20|   /loop 30m check the deploy
  21|   /loop 1h /standup 1
  22|   /loop check the deploy          (defaults to ${DEFAULT_INTERVAL})
  23|   /loop check the deploy every 20m`
  24| 
  25| function buildPrompt(args: string): string {
  26|   return `# /loop — schedule a recurring prompt
  27| 
  28| Parse the input below into \`[interval] <prompt…>\` and schedule it with ${CRON_CREATE_TOOL_NAME}.
  29| 
  30| ## Parsing (in priority order)

claudeInChrome 与 updateConfig

shouldAutoEnableClaudeInChrome() 为 true 时 registerClaudeInChromeSkill——浏览器扩展联动 onboarding。

updateConfig 引导用户修改 settings.json 字段,是 bundled 中最常维护的「元 skill」之一。

keybindings 展示可定制快捷键,与 keybindings 模块文档交叉引用。

bundled skill 的 aliases 数组提供短名(如 /verify 别名)。

源码引用: src/skills/bundled/index.ts · 第 70–72 行(共 80 行)

  70|   if (shouldAutoEnableClaudeInChrome()) {
  71|     registerClaudeInChromeSkill()
  72|   }

源码引用: src/skills/bundled/claudeInChrome.ts · 第 1–30 行(共 35 行)

   1| import { BROWSER_TOOLS } from '@ant/claude-for-chrome-mcp'
   2| import { BASE_CHROME_PROMPT } from '../../utils/claudeInChrome/prompt.js'
   3| import { shouldAutoEnableClaudeInChrome } from '../../utils/claudeInChrome/setup.js'
   4| import { registerBundledSkill } from '../bundledSkills.js'
   5| 
   6| const CLAUDE_IN_CHROME_MCP_TOOLS = BROWSER_TOOLS.map(
   7|   tool => `mcp__claude-in-chrome__${tool.name}`,
   8| )
   9| 
  10| const SKILL_ACTIVATION_MESSAGE = `
  11| Now that this skill is invoked, you have access to Chrome browser automation tools. You can now use the mcp__claude-in-chrome__* tools to interact with web pages.
  12| 
  13| IMPORTANT: Start by calling mcp__claude-in-chrome__tabs_context_mcp to get information about the user's current browser tabs.
  14| `
  15| 
  16| export function registerClaudeInChromeSkill(): void {
  17|   registerBundledSkill({
  18|     name: 'claude-in-chrome',
  19|     description:
  20|       'Automates your Chrome browser to interact with web pages - clicking elements, filling forms, capturing screenshots, reading console logs, and navigating sites. Opens pages in new tabs within your existing Chrome session. Requires site-level permissions before executing (configured in the extension).',
  21|     whenToUse:
  22|       'When the user wants to interact with web pages, automate browser tasks, capture screenshots, read console logs, or perform any browser-based actions. Always invoke BEFORE attempting to use any mcp__claude-in-chrome__* tools.',
  23|     allowedTools: CLAUDE_IN_CHROME_MCP_TOOLS,
  24|     userInvocable: true,
  25|     isEnabled: () => shouldAutoEnableClaudeInChrome(),
  26|     async getPromptForCommand(args) {
  27|       let prompt = `${BASE_CHROME_PROMPT}\n${SKILL_ACTIVATION_MESSAGE}`
  28|       if (args) {
  29|         prompt += `\n## Task\n\n${args}`
  30|       }

其他 bundled skill 速览

Skill用途
updateConfig引导修改 settings
keybindings快捷键帮助
debug调试会话
skillify把流程转为 skill
simplify简化变更
batch批处理
stuck卡住时引导
loopKairos cron 循环(AGENT_TRIGGERS)
claudeInChrome浏览器集成 onboarding

均可通过 registerBundledSkill 的 aliases 提供短名。REPL useSkillsChange 不监听 bundled(仅 disk),bundled 变更需发版。

源码引用: src/skills/bundled/stuck.ts · 第 1–25 行(共 80 行)

   1| import { registerBundledSkill } from '../bundledSkills.js'
   2| 
   3| // Prompt text contains `ps` commands as instructions for Claude to run,
   4| // not commands this file executes.
   5| // eslint-disable-next-line custom-rules/no-direct-ps-commands
   6| const STUCK_PROMPT = `# /stuck — diagnose frozen/slow Claude Code sessions
   7| 
   8| The user thinks another Claude Code session on this machine is frozen, stuck, or very slow. Investigate and post a report to #claude-code-feedback.
   9| 
  10| ## What to look for
  11| 
  12| Scan for other Claude Code processes (excluding the current one — PID is in \`process.pid\` but for shell commands just exclude the PID you see running this prompt). Process names are typically \`claude\` (installed) or \`cli\` (native dev build).
  13| 
  14| Signs of a stuck session:
  15| - **High CPU (≥90%) sustained** — likely an infinite loop. Sample twice, 1-2s apart, to confirm it's not a transient spike.
  16| - **Process state \`D\` (uninterruptible sleep)** — often an I/O hang. The \`state\` column in \`ps\` output; first character matters (ignore modifiers like \`+\`, \`s\`, \`<\`).
  17| - **Process state \`T\` (stopped)** — user probably hit Ctrl+Z by accident.
  18| - **Process state \`Z\` (zombie)** — parent isn't reaping.
  19| - **Very high RSS (≥4GB)** — possible memory leak making the session sluggish.
  20| - **Stuck child process** — a hung \`git\`, \`node\`, or shell subprocess can freeze the parent. Check \`pgrep -lP <pid>\` for each session.
  21| 
  22| ## Investigation steps
  23| 
  24| 1. **List all Claude Code processes** (macOS/Linux):
  25|    \`\`\`

源码引用: src/skills/bundled/updateConfig.ts · 第 1–25 行(共 476 行)

   1| import { toJSONSchema } from 'zod/v4'
   2| import { SettingsSchema } from '../../utils/settings/types.js'
   3| import { jsonStringify } from '../../utils/slowOperations.js'
   4| import { registerBundledSkill } from '../bundledSkills.js'
   5| 
   6| /**
   7|  * Generate JSON Schema from the settings Zod schema.
   8|  * This keeps the skill prompt in sync with the actual types.
   9|  */
  10| function generateSettingsSchema(): string {
  11|   const jsonSchema = toJSONSchema(SettingsSchema(), { io: 'input' })
  12|   return jsonStringify(jsonSchema, null, 2)
  13| }
  14| 
  15| const SETTINGS_EXAMPLES_DOCS = `## Settings File Locations
  16| 
  17| Choose the appropriate file based on scope:
  18| 
  19| | File | Scope | Git | Use For |
  20| |------|-------|-----|---------|
  21| | \`~/.claude/settings.json\` | Global | N/A | Personal preferences for all projects |
  22| | \`.claude/settings.json\` | Project | Commit | Team-wide hooks, permissions, plugins |
  23| | \`.claude/settings.local.json\` | Project | Gitignore | Personal overrides for this project |
  24| 
  25| Settings load in order: user → project → local (later overrides earlier).

本章小结与延伸

bundled = 官方维护 skill。改 initBundledSkills 注册表即可增删;大资源用 files + lazy content module。feature gate 与 isEnabled 双轨控制外部 build 体积与运行时可见性。 继续学习:

  • skills-loading
  • skill-tool-integration
Prev
skills-loading · 磁盘加载与 bundled 注册表
Next
mcp-skills · MCP prompt 转 skill