Learning resourcesReviewed · Anthropic

Claude Agent SDK: Work with sessions

This Claude Agent SDK guide is for Python and TypeScript developers building agents that remember earlier work, but saved conversations do not restore changed files. It explains automatic continuation, resuming a particular conversation, branching into a new conversation, and transferring session history between hosts.

Researched 23 Nov 2026

In short.

This session-management guide helps Python and TypeScript developers build Claude agents that return to earlier conversations, but retaining a conversation does not undo file edits. It explains when to use automatic continuation, explicit session IDs or conversation forks, including recovery after process restarts and some limit errors. Its practical constraints include local transcript availability, working-directory requirements for session stores, and differences between SDK and bundled CLI versions. Installation, authentication, actual operating costs and runtime reliability are not established by this page, and no example was executed.

Researched and written by an AI model and checked by a second AI model. How it works

Coverage comprises the complete selected page at [https://code.claude.com/docs/en/agent-sdk/sessions.md], including its examples, storage guidance, persistence distinctions and API version notices. The documentation-index invitation and all linked pages are outside scope. No code was executed, and no session continuation, recovery, fork, storage adapter or cross-host transfer was tested. Licensing, pricing, installation prerequisites and production behavior remain unknown where the page does not establish them.

The overview

Identity

Work with sessions is a documentation guide for session management in the Claude Agent SDK. The source is [https://code.claude.com/docs/en/agent-sdk/sessions.md]. Its examples use the Python package claude_agent_sdk and the TypeScript package @anthropic-ai/claude-agent-sdk.

The resource teaches one SDK feature rather than providing a standalone application. Its focus is preserving and returning to agent conversation history across prompts, processes and hosts.

Assessment

The guide is useful when an application needs follow-up prompts to share earlier analysis or decisions. It distinguishes an ongoing conversation from the multiple turns an agent can already take inside one query() call, so a one-shot task needs no additional session handling. Permission prompts and AskUserQuestion can also be handled within that call.

Its strongest practical contribution is mapping application needs to specific interfaces: automatic continuation for one conversation, resume for a chosen history, and fork for an alternative direction. It does not establish production reliability, performance or recovery success through measured results.

Users

The intended readers are developers building ongoing agent chats, applications that recover after restarts, or tools that explore different approaches from the same prior analysis. Developers serving several users receive a specific reason to track session IDs: automatic continuation chooses the most recent session in a directory rather than a particular user's conversation.

Beginners get an application-oriented choice table and paired language examples. Following those examples still requires familiarity with asynchronous Python or TypeScript, message iteration and exception handling; the page does not teach those foundations.

Capabilities

The page documents continuing the latest conversation, capturing a session ID, resuming that specific session, and forking its history into a new session. It also describes resuming after error_max_turns or error_max_budget_usd by supplying a higher limit.

For session organization, it identifies listSessions() and getSessionMessages() in TypeScript, with list_sessions() and get_session_messages() in Python. It also names APIs for obtaining session information, renaming sessions and tagging them. These functions can support session pickers, transcript viewers and cleanup logic, but their full signatures and implementation details are outside this page.

Using it

Requirements

The examples assume an available Python or TypeScript SDK environment. The page does not establish installation commands, supported language runtime versions, authentication steps, model availability or account requirements.

Resuming a persisted conversation requires access to its transcript. By default, that file remains on the machine that created it. Cross-host continuation therefore requires shared session storage or transferring the transcript. For a sessionStore or session_store adapter, the page says the lookup key derives from the working directory, so the resumed run needs a cwd matching the original run.

Mechanism

A session records prompts, tool calls, tool results and responses, and the SDK normally writes this conversation history to disk automatically. Continue selects the most recent session in the current directory; resume selects a specific session ID. Both append to an existing history. Fork creates a new session with a copy of the earlier history and leaves the original conversation unchanged.

The documented default transcript location is ~/.claude/projects/<encoded-cwd>/<session-id>.jsonl. CLAUDE_CONFIG_DIR changes the configuration root. Directory encoding replaces non-alphanumeric characters with hyphens; names exceeding 200 characters are truncated and receive a hash.

Setup

For Python conversations within one process, use ClaudeSDKClient as an asynchronous context manager, send prompts with client.query(), and consume each response with client.receive_response(). For automatic continuation through query(), the documented options are continue_conversation=True in Python and continue: true in TypeScript.

For explicit resumption, capture session_id from a result message and pass it as resume on a later query. The page says result messages carry the ID for both success and error outcomes. A single-shot query() raises after yielding an error result, so exception handling matters; connection or process failures may yield no result and leave the ID unavailable. Initialization messages also expose the ID directly in TypeScript and inside SystemMessage.data in Python.

Example

One example first asks the agent to analyze an authentication module, then asks it to refactor the module to use JWT. The Python version sends both prompts through one ClaudeSDKClient instance. The TypeScript version makes two query() calls and sets continue: true on the second. The intended behavior is that the second prompt can use the first conversation's analysis.

A separate example branches from that analysis to explore OAuth2 using resume with fork_session=True in Python or forkSession: true in TypeScript. It captures the fork's new ID and then resumes the original ID to continue the JWT discussion. These are documentation examples; no execution results were obtained.

Assessment & evidence

Limitations

Sessions preserve conversation history, not a filesystem snapshot. A fork can edit files that remain visible to other sessions in the same directory. The page points to file checkpointing for snapshotting and reverting file changes, but that linked guide is outside the available evidence.

Automatic continuation selects the latest directory session, making explicit IDs the documented choice when several conversations coexist. Cross-directory lookup still requires the transcript to exist locally unless storage or transfer is arranged. The page does not establish behavior for concurrent writers, transcript corruption, storage failures or access isolation between users.

For avoiding persistence, TypeScript offers persistSession: false, which the page describes as keeping the session in memory for the call. Python instead uses CLAUDE_CODE_SKIP_PROMPT_HISTORY through the env option to suppress transcript writes. The page does not establish that these controls have identical effects on every kind of stored data.

Reasoning

The interface choice follows how precisely an application needs to identify a conversation. Automatic continuation avoids ID bookkeeping when there is one conversation to continue. Explicit resume makes the target conversation unambiguous across restarts or multiple users. Fork preserves an earlier conversational direction while allowing another one to develop.

The distinction between history and files is central to deciding whether the feature fits. A session can preserve what the agent previously discussed or observed without preserving the earlier state of the working files. Conversation branching therefore needs a separate file-state strategy when experiments must be reversible.

Alternatives

For a one-shot task, the guide recommends one query() call without additional session management. Within one process, Python's ClaudeSDKClient offers automatic continuity; TypeScript uses continue: true on subsequent calls.

For work that moves between hosts, the page offers a session store adapter, transcript-file transfer, or a fresh session supplied with application state such as decisions, analysis output and file diffs. It describes explicit application state as often more robust than moving transcript files, but provides no comparative measurements. Competing SDKs and other session systems are not assessed.

Evidence

The evidence is the complete documentation page at [https://code.claude.com/docs/en/agent-sdk/sessions.md], captured on 2026-11-23 at 18:27:51.950 UTC. It contains explanatory prose, an application choice table, Python and TypeScript examples, storage notes and version-specific notices.

The examples support an explanation of the documented interfaces and intended behavior. They do not establish successful execution, performance, reliability or actual spending. Linked API references, session-storage documentation, file-checkpointing instructions and other related pages were outside the selected scope.

Access & freshness

Costs

Actual operating costs are unknown. The page supplies no pricing schedule, representative workload measurements or comparison of fresh, resumed and forked conversations.

The Python example prints ResultMessage.total_cost_usd when available and N/A otherwise. Its sample $0.0042 status line is illustrative output, not a measured result or a price estimate. The error_max_budget_usd recovery example describes raising a run limit; it does not establish the cost of completing the task.

Rights

The supplied page does not state a license for the documentation or its code examples, or provide redistribution permissions. SDK licensing, service terms, ownership terms for generated material and rights affecting stored transcripts are not established here. Public availability of the page does not resolve those questions.

Freshness

The capture date identifies the available documentation snapshot, not its publication date or the latest SDK release. The page states that the experimental TypeScript V2 createSession() API was removed in Agent SDK 0.3.142 and directs readers to query() session options.

It also states that cross-directory session lookup was more restricted before Claude Code v2.1.223, so behavior depends on the bundled CLI version. Using CLAUDE_CODE_PROJECT_DIR_NAME alongside CLAUDE_CONFIG_DIR requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later. Compatibility with any particular installation remains unassessed.

Actions

Choose automatic continuation for a single conversation, explicit IDs for independently addressable conversations, or forks for alternative conversational paths. Capture IDs even from error results and handle failures that produce no result. For cross-host work, choose shared storage, transcript transfer or explicit application state, and account for the session store's working-directory requirement.

Before adoption, confirm the installed SDK and bundled CLI versions, obtain the missing installation and authentication instructions, and establish costs and transcript handling requirements. Validate a follow-up, restart recovery and fork behavior in the intended environment. Check file changes separately when an experiment must be reversible.

Evidence for this report

selected-page.txtselected · checked 2026-11-23