Loading...
    • Developer Guide
    • API Reference
    • MCP
    • Resources
    • Release Notes
    Search...
    ⌘K
    First steps
    Intro to ClaudeQuickstart
    Models & pricing
    Models overviewChoosing a modelWhat's new in Claude 4.5Migrating to Claude 4.5Model deprecationsPricing
    Build with Claude
    Features overviewUsing the Messages APIContext windowsPrompting best practices
    Capabilities
    Prompt cachingContext editingExtended thinkingEffortStreaming MessagesBatch processingCitationsMultilingual supportToken countingEmbeddingsVisionPDF supportFiles APISearch resultsStructured outputs
    Tools
    OverviewHow to implement tool useFine-grained tool streamingBash toolCode execution toolProgrammatic tool callingComputer use toolText editor toolWeb fetch toolWeb search toolMemory toolTool search tool
    Agent Skills
    OverviewQuickstartBest practicesUsing Skills with the API
    Agent SDK
    OverviewQuickstartTypeScript SDKTypeScript V2 (preview)Python SDKMigration Guide
    Streaming InputHandling PermissionsControl execution with hooksSession ManagementFile checkpointingStructured outputs in the SDKHosting the Agent SDKSecurely deploying AI agentsModifying system promptsMCP in the SDKCustom ToolsSubagents in the SDKSlash Commands in the SDKAgent Skills in the SDKTracking Costs and UsageTodo ListsPlugins in the SDK
    MCP in the API
    MCP connectorRemote MCP servers
    Claude on 3rd-party platforms
    Amazon BedrockMicrosoft FoundryVertex AI
    Prompt engineering
    OverviewPrompt generatorUse prompt templatesPrompt improverBe clear and directUse examples (multishot prompting)Let Claude think (CoT)Use XML tagsGive Claude a role (system prompts)Prefill Claude's responseChain complex promptsLong context tipsExtended thinking tips
    Test & evaluate
    Define success criteriaDevelop test casesUsing the Evaluation ToolReducing latency
    Strengthen guardrails
    Reduce hallucinationsIncrease output consistencyMitigate jailbreaksStreaming refusalsReduce prompt leakKeep Claude in character
    Administration and monitoring
    Admin API overviewUsage and Cost APIClaude Code Analytics API
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    Guides

    Session Management

    Understanding how the Claude Agent SDK handles sessions and session resumption

    Session Management

    The Claude Agent SDK provides session management capabilities for handling conversation state and resumption. Sessions allow you to continue conversations across multiple interactions while maintaining full context.

    How Sessions Work

    When you start a new query, the SDK automatically creates a session and returns a session ID in the initial system message. You can capture this ID to resume the session later.

    Getting the Session ID

    import { query } from "@anthropic-ai/claude-agent-sdk"
    
    let sessionId: string | undefined
    
    const response = query({
      prompt: "Help me build a web application",
      options: {
        model: "claude-sonnet-4-5"
      }
    })
    
    for await (const message of response) {
      // The first message is a system init message with the session ID
      if (message.type === 'system' && message.subtype === 'init') {
        sessionId = message.session_id
        console.log(`Session started with ID: ${sessionId}`)
        // You can save this ID for later resumption
      }
    
      // Process other messages...
      console.log(message)
    }
    
    // Later, you can use the saved sessionId to resume
    if (sessionId) {
      const resumedResponse = query({
        prompt: "Continue where we left off",
        options: {
          resume: sessionId
        }
      })
    }

    Resuming Sessions

    The SDK supports resuming sessions from previous conversation states, enabling continuous development workflows. Use the resume option with a session ID to continue a previous conversation.

    The SDK automatically handles loading the conversation history and context when you resume a session, allowing Claude to continue exactly where it left off.

    To track and revert file changes across sessions, see File Checkpointing.

    Forking Sessions

    When resuming a session, you can choose to either continue the original session or fork it into a new branch. By default, resuming continues the original session. Use the forkSession option (TypeScript) or fork_session option (Python) to create a new session ID that starts from the resumed state.

    When to Fork a Session

    Forking is useful when you want to:

    • Explore different approaches from the same starting point
    • Create multiple conversation branches without modifying the original
    • Test changes without affecting the original session history
    • Maintain separate conversation paths for different experiments

    Forking vs Continuing

    BehaviorforkSession: false (default)forkSession: true
    Session IDSame as originalNew session ID generated
    HistoryAppends to original sessionCreates new branch from resume point
    Original SessionModifiedPreserved unchanged
    Use CaseContinue linear conversationBranch to explore alternatives

    Example: Forking a Session

    • How Sessions Work
    • Getting the Session ID
    • Resuming Sessions
    • Forking Sessions
    • When to Fork a Session
    • Forking vs Continuing
    • Example: Forking a Session
    import { query } from "@anthropic-ai/claude-agent-sdk"
    
    // Resume a previous session using its ID
    const response = query({
      prompt: "Continue implementing the authentication system from where we left off",
      options: {
        resume: "session-xyz", // Session ID from previous conversation
        model: "claude-sonnet-4-5",
        allowedTools: ["Read", "Edit", "Write", "Glob", "Grep", "Bash"]
      }
    })
    
    // The conversation continues with full context from the previous session
    for await (const message of response) {
      console.log(message)
    }
    import { query } from "@anthropic-ai/claude-agent-sdk"
    
    // First, capture the session ID
    let sessionId: string | undefined
    
    const response = query({
      prompt: "Help me design a REST API",
      options: { model: "claude-sonnet-4-5" }
    })
    
    for await (const message of response) {
      if (message.type === 'system' && message.subtype === 'init') {
        sessionId = message.session_id
        console.log(`Original session: ${sessionId}`)
      }
    }
    
    // Fork the session to try a different approach
    const forkedResponse = query({
      prompt: "Now let's redesign this as a GraphQL API instead",
      options: {
        resume: sessionId,
        forkSession: true,  // Creates a new session ID
        model: "claude-sonnet-4-5"
      }
    })
    
    for await (const message of forkedResponse) {
      if (message.type === 'system' && message.subtype === 'init') {
        console.log(`Forked session: ${message.session_id}`)
        // This will be a different session ID
      }
    }
    
    // The original session remains unchanged and can still be resumed
    const originalContinued = query({
      prompt: "Add authentication to the REST API",
      options: {
        resume: sessionId,
        forkSession: false,  // Continue original session (default)
        model: "claude-sonnet-4-5"
      }
    })