Claude Code Source Study 标志

Claude Code Source Study

组织
reason-machines
claude-code-source-study

Deep dive into Claude Code source code to learn production-grade AI agent architecture patterns

概览

发布者reason-machines
代码仓库trending-skills
技能名称claude-code-source-study
星标数
89
复刻数
16
附带文件
仅含指令
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 reason-machines 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Claude Code Source Study AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/reason-machines/trending-skills/tree/main/skills/claude-code-source-study
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/reason-machines/trending-skills.git /tmp/trending-skills
mkdir -p .claude/skills
cp -r /tmp/trending-skills/skills/claude-code-source-study .claude/skills/claude-code-source-study
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Claude Code Source Study,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Claude Code Source Study。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Claude Code Source Study 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Claude Code Source Study

Skill by ara.so — Daily 2026 Skills collection.

A 25-article deep-dive into Claude Code's ~1900-file source code, covering System Prompt engineering, multi-agent orchestration, tool systems, permission security, and terminal UI. Learn production-grade AI agent patterns from Anthropic's real CLI product.

What This Project Is

This is a Chinese-language source code analysis series that dissects Claude Code (Anthropic's AI CLI coding assistant) module by module — with exact file references, line numbers, and code snippets. Each article extracts reusable design patterns for building your own AI agent applications.

Tech stack covered: Bun + TypeScript + Ink (React for terminals) + Anthropic API

Repository Structure

claude-code-source-study/
├── docs/
│   ├── 00-目录与阅读指引.md      # Index and reading guide
│   ├── 01-项目全景.md             # Project overview
│   ├── 02-启动优化.md             # Startup optimization
│   ├── 03-状态管理.md             # State management
│   ├── 04-System-Prompt-工程.md  # System prompt engineering
│   ├── 05-对话循环.md             # Conversation loop
│   ├── 06-上下文管理.md           # Context management
│   ├── 07-Prompt-Cache.md        # Prompt caching
│   ├── 08-Thinking-与推理控制.md  # Thinking & reasoning
│   ├── 09-工具系统设计.md          # Tool system design
│   ├── 10-BashTool-深度剖析.md    # BashTool deep dive
│   ├── 11-命令系统.md             # Command system
│   ├── 12-Agent-系统.md           # Agent system
│   ├── 13-内置Agent设计模式.md    # Built-in agent patterns
│   ├── 14-任务系统.md             # Task system
│   ├── 15-MCP-协议实现.md         # MCP protocol
│   ├── 16-权限系统.md             # Permission system
│   ├── 17-Settings-系统.md       # Settings system
│   ├── 18-Hooks系统.md            # Hooks system
│   ├── 19-Feature-Flag与编译期优化.md
│   ├── 20-API调用与错误恢复.md    # API retry/recovery
│   ├── 21-Ink框架深度定制.md      # Ink UI customization
│   ├── 22-设计系统.md             # Design system
│   ├── 23-Memory系统.md           # Memory system
│   ├── 24-Skill-Plugin开发实战.md # Plugin development
│   └── 25-架构模式总结.md         # Architecture patterns summary
└── README.md

Reading Routes

⚡ Quick Route (7 articles) — Global understanding

01 → 02 → 03 → 05 → 09 → 12 → 25

🤖 AI Engineering Route (9 articles) — Deep AI core

01 → 03 → 04 → 05 → 06 → 08 → 09 → 12 → 13

📚 Complete Route (25 articles)

Read docs/01 through docs/25 in order.

Key Patterns Extracted from Claude Code

1. Tool Builder Pattern (buildTool())

Claude Code registers tools using a builder with three-layer conditional registration:

typescript
// Pattern extracted from docs/09-工具系统设计.md
const buildTool = <TInput, TOutput>(config: {
  name: string
  description: string
  inputSchema: ZodSchema<TInput>
  handler: (input: TInput, context: ToolContext) => Promise<TOutput>
  isEnabled?: (context: AppContext) => boolean
  requiresPermission?: PermissionLevel
}) => config

// Registration with conditions
const tools = [
  buildTool({ name: 'bash', ... }),
  buildTool({ name: 'read_file', ... }),
  buildTool({ name: 'write_file', ... }),
].filter(tool => tool.isEnabled?.(ctx) ?? true)

2. AsyncGenerator Conversation Loop (docs/05)

typescript
// Pattern: state-machine conversation loop using AsyncGenerator
async function* conversationLoop(
  messages: Message[],
  tools: Tool[]
): AsyncGenerator<StreamEvent> {
  while (true) {
    const stream = await anthropic.messages.stream({
      model: 'claude-opus-4-5',
      messages,
      tools,
      system: buildSystemPrompt(),
    })

    for await (const event of stream) {
      yield event
    }

    const response = await stream.finalMessage()

    if (response.stop_reason === 'end_turn') break

    if (response.stop_reason === 'tool_use') {
      const toolResults = await executeTools(response.content)
      messages.push({ role: 'assistant', content: response.content })
      messages.push({ role: 'user', content: toolResults })
      // loop continues
    }
  }
}

3. 35-Line Minimal Store (React ↔ Non-React Bridge) (docs/03)

typescript
// Pattern: tiny reactive store bridging React and imperative code
type Listener<T> = (state: T) => void

function createStore<T>(initialState: T) {
  let state = initialState
  const listeners = new Set<Listener<T>>()

  return {
    getState: () => state,
    setState: (updater: Partial<T> | ((s: T) => T)) => {
      state = typeof updater === 'function'
        ? updater(state)
        : { ...state, ...updater }
      listeners.forEach(l => l(state))
    },
    subscribe: (listener: Listener<T>) => {
      listeners.add(listener)
      return () => listeners.delete(listener)
    },
    // React hook integration
    useStore: () => {
      const [s, setS] = React.useState(state)
      React.useEffect(() => subscribe(setS), [])
      return s
    }
  }
}

4. System Prompt Segmented Construction (docs/04)

typescript
// Pattern: build system prompt in segments with cache boundaries
function buildSystemPrompt(context: AppContext): SystemPrompt {
  return [
    // Static segment — cache this (never changes)
    { type: 'text', text: CORE_INSTRUCTIONS, cache_control: { type: 'ephemeral' } },

    // Semi-static segment — cache per project
    { type: 'text', text: buildProjectContext(context.project), cache_control: { type: 'ephemeral' } },

    // Dynamic segment — never cache (changes each turn)
    { type: 'text', text: buildDynamicContext(context.session) },
  ]
}

5. Context Auto-Compact with Token Budget (docs/06)

typescript
// Pattern: token budget management with auto-compact
const TOKEN_BUDGET = {
  MAX_CONTEXT: 200_000,
  COMPACT_THRESHOLD: 0.85,  // compact at 85% full
  SUMMARY_RESERVE: 2_000,
}

async function maybeCompact(messages: Message[]): Promise<Message[]> {
  const tokenCount = await countTokens(messages)

  if (tokenCount < TOKEN_BUDGET.MAX_CONTEXT * TOKEN_BUDGET.COMPACT_THRESHOLD) {
    return messages
  }

  // Summarize older messages, keep recent ones verbatim
  const keepRecent = messages.slice(-20)
  const toSummarize = messages.slice(0, -20)

  const summary = await summarize(toSummarize)
  return [
    { role: 'user', content: `Previous conversation summary:\n${summary}` },
    { role: 'assistant', content: 'Understood.' },
    ...keepRecent,
  ]
}

6. Permission 7-Step Decision Pipeline (docs/16)

typescript
// Pattern: layered permission evaluation
type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'auto' | 'strict' | 'custom'

async function evaluatePermission(
  action: ToolAction,
  context: PermissionContext
): Promise<PermissionResult> {
  // Step 1: Check bypass mode
  if (context.mode === 'bypassPermissions') return { allowed: true }

  // Step 2: Check if action is always-safe
  if (isAlwaysSafe(action)) return { allowed: true }

  // Step 3: Check allowlist
  if (isAllowlisted(action, context.allowlist)) return { allowed: true }

  // Step 4: Check blocklist
  if (isBlocklisted(action, context.blocklist)) return { allowed: false, reason: 'blocklisted' }

  // Step 5: Check auto-approve rules
  if (matchesAutoApprove(action, context.rules)) return { allowed: true }

  // Step 6: Check session memory
  if (context.sessionMemory.has(actionKey(action))) return { allowed: true }

  // Step 7: Ask user
  const decision = await promptUser(action)
  if (decision.remember) context.sessionMemory.add(actionKey(action))
  return { allowed: decision.approved }
}

7. Multi-Agent Context Isolation (docs/12)

typescript
// Pattern: sub-agent with isolated context
async function spawnSubAgent(task: AgentTask, parentContext: AgentContext) {
  const subContext: AgentContext = {
    // Isolated: sub-agent gets its own conversation
    messages: [],
    sessionId: generateId(),

    // Inherited: shares tools and permissions from parent
    tools: parentContext.tools,
    permissionMode: parentContext.permissionMode,

    // Scoped: limited working directory
    cwd: task.workingDir ?? parentContext.cwd,

    // Budget: prevent runaway sub-agents
    maxTurns: task.maxTurns ?? 10,
    tokenBudget: task.tokenBudget ?? 50_000,
  }

  return conversationLoop(
    [{ role: 'user', content: task.prompt }],
    subContext.tools,
    subContext
  )
}

8. withRetry for API Overload (docs/20)

typescript
// Pattern: exponential backoff with overload handling
async function withRetry<T>(
  fn: () => Promise<T>,
  options = { maxAttempts: 3, baseDelay: 1000 }
): Promise<T> {
  for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
    try {
      return await fn()
    } catch (err) {
      if (attempt === options.maxAttempts) throw err

      // Handle Anthropic 529 overloaded
      if (isOverloadError(err)) {
        const delay = options.baseDelay * Math.pow(2, attempt - 1)
        await sleep(delay + Math.random() * 1000) // jitter
        continue
      }

      // Don't retry non-retriable errors
      if (isAuthError(err) || isInvalidRequestError(err)) throw err

      throw err
    }
  }
  throw new Error('unreachable')
}

Applying These Patterns to Your Own Agent

Minimal Agent Scaffold

typescript
import Anthropic from '@anthropic-ai/sdk'

const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY })

// 1. Define tools using builder pattern
const tools = [
  buildTool({
    name: 'read_file',
    description: 'Read a file from disk',
    inputSchema: z.object({ path: z.string() }),
    handler: async ({ path }) => fs.readFile(path, 'utf-8'),
  }),
]

// 2. Build system prompt with cache segments
const systemPrompt = buildSystemPrompt({ static: CORE_RULES, dynamic: '' })

// 3. Run conversation loop
for await (const event of conversationLoop(
  [{ role: 'user', content: userInput }],
  tools
)) {
  if (event.type === 'text') process.stdout.write(event.text)
}

Thinking / Extended Reasoning Config (docs/08)

typescript
// Control reasoning effort per request
type ThinkingConfig =
  | { type: 'disabled' }
  | { type: 'enabled'; budget_tokens: number }

// "ultrathink" = maximum budget
const EFFORT_LEVELS = {
  low:        { type: 'enabled', budget_tokens: 1_000 },
  medium:     { type: 'enabled', budget_tokens: 5_000 },
  high:       { type: 'enabled', budget_tokens: 10_000 },
  ultrathink: { type: 'enabled', budget_tokens: 32_000 },
} satisfies Record<string, ThinkingConfig>

const response = await anthropic.messages.create({
  model: 'claude-opus-4-5',
  thinking: EFFORT_LEVELS.ultrathink,
  messages,
})

Troubleshooting

ProblemSolution
Article links 404Clone the repo — all articles are in docs/ locally
Code examples reference internal modulesThey're illustrative patterns extracted from analysis, not runnable as-is
Need the actual Claude Code sourceSee Anthropic's published CLI source
Want to contribute an articleOpen a PR to docs/ following the existing article format

Start Here

bash
git clone https://github.com/luyao618/Claude-Code-Source-Study
cd Claude-Code-Source-Study

# Quick route: global understanding (7 articles)
open docs/01-项目全景.md

# AI engineering deep dive (9 articles)  
open docs/04-System-Prompt-工程.md

# Architecture patterns summary (read last)
open docs/25-架构模式总结.md

常见问题

Claude Code Source Study AI 技能有什么作用?

Deep dive into Claude Code source code to learn production-grade AI agent architecture patterns

为什么在 TypingMind 中使用 Claude Code Source Study?

因为您只需安装一次,就能搭配任何模型使用。Claude Code Source Study 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Claude Code Source Study?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/reason-machines/trending-skills/tree/main/skills/claude-code-source-study。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Claude Code Source Study?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Claude Code Source Study 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Claude Code Source Study 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Claude Code Source Study AI 技能免费吗?

该技能源自 reason-machines 在 GitHub 上发布的项目。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇