1197 words Slides

17.6 Session Management

Course: Claude Code - Enterprise Development

Section: Claude Agent SDK

Video Length: 3-4 minutes

Presenter: Daniel Treasure


Opening Hook

"Agents that run once and disappear are useful, but agents that maintain state across interactions are powerful. Sessions let you create persistent agent workflows: start a task, pause it, come back later, and resume exactly where you left off."


Key Talking Points

What to say:

  • "Sessions store conversation history and state so agents can maintain context."
  • "Perfect for: long-running workflows, multi-step tasks, users returning to in-progress work."
  • "Create sessions programmatically, list them, resume them, manage lifecycle."
  • "Sessions are isolated: one session per workflow, no interference."

What to show on screen:

  • Creating a new session
  • Running agent task within session
  • Pausing/resuming session
  • Viewing session history
  • Cleaning up inactive sessions

Demo Plan

[00:00 - 00:45] Session Basics 1. Explain: sessions are like persistent chat histories 2. Show: session creation with metadata (project, user, task) 3. Show: agent using session to maintain context 4. Explain: when to use sessions vs. stateless agents

[00:45 - 01:45] Creating & Using Sessions 1. Create session: session = agent.create_session(...) 2. Run task: agent.run(task, session_id=session.id) 3. Show: agent responds with session history included 4. Show: next task using same session_id 5. Demonstrate: agent references previous context

[01:45 - 02:45] Resume Long-Running Workflows 1. Scenario: multi-day code migration task 2. Day 1: agent analyzes codebase, creates plan 3. Pause and save session 4. Day 2: resume session, agent continues from plan 5. Show: agent has full history, no replication of work 6. Complete: migration finished

[02:45 - 03:45] Session Management 1. List sessions: active, completed, archived 2. Get session details: history, metadata, tokens used 3. Update session: add notes, change status 4. Delete session: cleanup archived/test sessions 5. Explain: when to prune sessions (storage/cost)


Code Examples & Commands

Python Session Management:

from claude_code import Agent, Session
import asyncio

async def session_workflow():
    agent = Agent(model="claude-sonnet-4-5-20250929")

    # Create a new session
    session = agent.create_session(
        metadata={
            "project": "migration-v2",
            "user": "alice@company.com",
            "description": "Python 2 to 3 migration"
        }
    )

    print(f"Created session: {session.id}")

    # Day 1: Initial analysis
    result1 = await agent.run(
        "Analyze our Python codebase and create a migration plan for Python 2 to Python 3",
        session_id=session.id
    )
    print(f"Day 1 Output:\n{result1.output}\n")

    # (Session persists; can pause here)

    # Day 2: Continue from where we left off
    result2 = await agent.run(
        "Based on the plan you created, start with the utils module. What changes are needed?",
        session_id=session.id
    )
    print(f"Day 2 Output:\n{result2.output}\n")

    # Day 3: Verify
    result3 = await agent.run(
        "Are there any remaining Python 2 syntax patterns we haven't addressed?",
        session_id=session.id
    )
    print(f"Day 3 Output:\n{result3.output}\n")

asyncio.run(session_workflow())

Managing Multiple Sessions:

from claude_code import Agent
from datetime import datetime

async def manage_sessions():
    agent = Agent(model="claude-sonnet-4-5-20250929")

    # Create multiple sessions for different tasks
    sessions = {}
    tasks = {
        "feature-auth": "Implement OAuth2 authentication",
        "bug-memory-leak": "Debug memory leak in worker process",
        "docs-api": "Write API documentation"
    }

    for task_name, task_desc in tasks.items():
        session = agent.create_session(
            metadata={
                "task": task_name,
                "created_at": datetime.now().isoformat(),
                "priority": "high" if task_name == "bug-memory-leak" else "normal"
            }
        )
        sessions[task_name] = session.id
        print(f"Created session for {task_name}: {session.id}")

    # Work on a task
    result = await agent.run(
        "Create an outline for the API documentation",
        session_id=sessions["docs-api"]
    )

    # List all sessions
    all_sessions = agent.list_sessions(limit=10)
    print(f"\nActive sessions: {len(all_sessions)}")
    for s in all_sessions:
        print(f"  - {s.id}: {s.metadata.get('task', 'Unknown')}")

    # Cleanup completed sessions
    completed = [s for s in all_sessions if s.status == "completed"]
    for s in completed:
        agent.delete_session(s.id)
        print(f"Deleted completed session: {s.id}")

asyncio.run(manage_sessions())

Session with Metadata & Callbacks:

import asyncio
from claude_code import Agent

async def advanced_session():
    agent = Agent(
        model="claude-sonnet-4-5-20250929",
        permission_callback=lambda action, resource, details: True  # Allow all for demo
    )

    # Create session with rich metadata
    session = agent.create_session(
        metadata={
            "workflow": "code-review-pr",
            "pr_id": "gh-1234",
            "author": "bob@company.com",
            "target_branch": "main",
            "start_time": datetime.now().isoformat(),
            "max_iterations": 5
        }
    )

    print(f"Started code review workflow: {session.id}\n")

    # Step 1: Read PR
    result1 = await agent.run(
        "Read the PR description and changes from gh-1234",
        session_id=session.id
    )

    # Step 2: Review
    result2 = await agent.run(
        "Review the code for security, performance, and style. Flag any issues.",
        session_id=session.id
    )

    # Step 3: Approve or request changes
    result3 = await agent.run(
        "Based on your review, should this PR be approved or require changes?",
        session_id=session.id
    )

    # Get session history
    final_session = agent.get_session(session.id)
    print(f"\nSession Stats:")
    print(f"  Duration: {final_session.duration_seconds}s")
    print(f"  Messages: {final_session.message_count}")
    print(f"  Tokens: {final_session.token_count}")

asyncio.run(advanced_session())

TypeScript Session Management:

import Anthropic from "@anthropic-ai/sdk";

interface SessionMetadata {
  project: string;
  user: string;
  description: string;
  createdAt: string;
}

async function sessionWorkflow(): Promise<void> {
  const client = new Anthropic();

  // Create session (implementation depends on SDK)
  const sessionId = "session-abc123";

  console.log(`Started session: ${sessionId}\n`);

  // Step 1
  const response1 = await client.messages.create({
    model: "claude-sonnet-4-5-20250929",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: "Analyze this codebase and create a refactoring plan",
      },
    ],
    // SDK would include session_id parameter here
  });

  console.log("Step 1 Complete\n");

  // Step 2 (use same session)
  const response2 = await client.messages.create({
    model: "claude-sonnet-4-5-20250929",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: "Now implement the first phase of the refactoring",
      },
    ],
    // SDK would include session_id parameter here
  });

  console.log("Step 2 Complete");
}

sessionWorkflow().catch(console.error);

Gotchas & Tips

Gotcha 1: Session Limits - Session history grows with each interaction - Very long sessions can hit token limits - Solution: Archive old sessions, start new ones for new phases

Gotcha 2: Stale Context - If session pauses for a week, context may become irrelevant - Solution: Summarize progress before long pause, refresh context on resume

Gotcha 3: Concurrent Sessions - Multiple agents writing to same session simultaneously can corrupt state - Solution: Lock sessions for exclusive access, or use different sessions

Gotcha 4: Storage & Cost - Sessions consume storage (conversation history) - Long sessions use more tokens - Solution: Regularly prune old sessions, archive completed ones

Tip 1: Metadata is Key - Use rich metadata: project, user, phase, iteration - Makes sessions searchable and manageable

Tip 2: Session Snapshots - Periodically snapshot session state (save to database) - Useful for debugging or auditing

Tip 3: Graceful Resumption - When resuming after pause, summarize what's been done - Example: "We completed phases 1 and 2. Ready for phase 3?"

Tip 4: Multi-Agent Sessions - Can have multiple agents reference same session for coordination - Useful for collaborative workflows


Lead-out

"Sessions are the backbone of long-running workflows. Next: custom tools. You can teach agents to use functions specific to your domain—not just built-in tools like Read and Bash."


Reference URLs

  • Claude Code Session API: [check official docs]
  • Session Management Best Practices: [would be in official docs]

Prep Reading

  • Understand session lifecycle: create, use, pause, resume, delete (5 min)
  • Design a long-running workflow you'd like to automate (5 min)

Notes for Daniel

  • Multi-day workflow: Session example spans days—emphasize continuity and resumption as key values.
  • Real use cases: Data pipelines, code migrations, customer support workflows, research projects.
  • Storage consideration: Mention that sessions persist in a backend (likely with retention policies).
  • Isolation: Each session is independent—no data leakage between sessions.