Work with sessions changedagent-sdk/sessions
Upstream edited this page at 10 Oct 2026 18:00 UTC, give or take a minute or two: the time comes from Anthropic’s own sitemap rather than from a commit. This site recorded the change at 23 Oct 2026 19:07 UTC.
Upstream edited
Recorded here
Lines+24added
Lines−24removed
From line
8
where the diff opens
First seen
14 Aug 2026
this site's first read of the page
Recorded edits8to this page, all time
The whole hunk
from line 8, old and new numbered
/
from line 8
88
99> [!NOTE]
1010>
11> Sessions persist the **conversation**, not the filesystem. To snapshot and revert file changes the agent made, use [file checkpointing](/docs/en/agent-sdk/file-checkpointing.md).
11> Sessions persist the **conversation**, not the filesystem. To snapshot and revert file changes the agent made, use [file checkpointing](https://code.claude.com/docs/en/agent-sdk/file-checkpointing.md).
1212
1313This guide covers how to pick the right approach for your app, the SDK interfaces that track sessions automatically, how to capture session IDs and use `resume` and `fork` manually, and what to know about resuming sessions across hosts.
1414
1515## Choose an approach
1616
17How much session handling you need depends on your application's shape. Session management comes into play when you send multiple prompts that should share context. Within a single `query()` call, the agent already takes as many turns as it needs, and permission prompts and `AskUserQuestion` are [handled in-loop](/docs/en/agent-sdk/user-input.md) (they don't end the call).
17How much session handling you need depends on your application's shape. Session management comes into play when you send multiple prompts that should share context. Within a single `query()` call, the agent already takes as many turns as it needs, and permission prompts and `AskUserQuestion` are [handled in-loop](https://code.claude.com/docs/en/agent-sdk/user-input.md) (they don't end the call).
1818
1919| What you're building | What to use |
2020| :- | :- |
from line 23
2323| Pick up where you left off after a process restart | `continue_conversation=True` (Python) / `continue: true` (TypeScript). Resumes the most recent session in the directory, no ID needed. |
2424| Resume a specific past session (not the most recent) | Capture the session ID and pass it to `resume`. |
2525| Try an alternative approach without losing the original | Fork the session. |
26| Stateless task, don't want anything written to disk | Set [`persistSession: false`](/docs/en/agent-sdk/typescript#options) (TypeScript only). The session exists only in memory for the duration of the call. In Python, set [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/docs/en/env-vars) in the `env` option to suppress transcript writes instead. |
26| Stateless task, don't want anything written to disk | Set [`persistSession: false`](https://code.claude.com/docs/en/agent-sdk/typescript#options) (TypeScript only). The session exists only in memory for the duration of the call. In Python, set [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](https://code.claude.com/docs/en/env-vars) in the `env` option to suppress transcript writes instead. |
2727
2828### Continue, resume, and fork
2929
30Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](/docs/en/agent-sdk/python#claudeagentoptions) in Python, [`Options`](/docs/en/agent-sdk/typescript#options) in TypeScript).
30Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](https://code.claude.com/docs/en/agent-sdk/python#claudeagentoptions) in Python, [`Options`](https://code.claude.com/docs/en/agent-sdk/typescript#options) in TypeScript).
3131
3232**Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session:
3333
from line 42
4242
4343### Python: `ClaudeSDKClient`
4444
45[`ClaudeSDKClient`](/docs/en/agent-sdk/python#claudesdkclient) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](/docs/en/agent-sdk/python#claudesdkclient) to iterate over the messages for the current query. Use the client as an async context manager so connection setup and teardown are handled for you, or call `connect()` and `disconnect()` manually.
45[`ClaudeSDKClient`](https://code.claude.com/docs/en/agent-sdk/python#claudesdkclient) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](https://code.claude.com/docs/en/agent-sdk/python#claudesdkclient) to iterate over the messages for the current query. Use the client as an async context manager so connection setup and teardown are handled for you, or call `connect()` and `disconnect()` manually.
4646
4747This example runs two queries against the same `client`. The first asks the agent to analyze a module; the second asks it to refactor that module. Because both calls go through the same client instance, the second query has full context from the first without any explicit `resume` or session ID:
4848
from line 94
9494
9595Each query prints the agent's text response followed by a status line from the result message, such as `[done: success, cost: $0.0042]`.
9696
97See the [Python SDK reference](/docs/en/agent-sdk/python.md#choosing-between-query-and-claudesdkclient) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function.
97See the [Python SDK reference](https://code.claude.com/docs/en/agent-sdk/python.md#choosing-between-query-and-claudesdkclient) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function.
9898
9999### TypeScript: `continue: true`
100100
from line 137
137137
138138> [!NOTE]
139139>
140> The experimental [V2 session API](/docs/en/agent-sdk/typescript-v2-preview.md), which provided `createSession()` with a `send` / `stream` pattern, was removed in TypeScript Agent SDK 0.3.142. Use the `query()` function and the session options described on this page instead.
140> The experimental [V2 session API](https://code.claude.com/docs/en/agent-sdk/typescript-v2-preview.md), which provided `createSession()` with a `send` / `stream` pattern, was removed in TypeScript Agent SDK 0.3.142. Use the `query()` function and the session options described on this page instead.
141141
142142## Use session options with `query()`
143143
144144### Capture the session ID
145145
146Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](/docs/en/agent-sdk/python#resultmessage) in Python, [`SDKResultMessage`](/docs/en/agent-sdk/typescript#sdkresultmessage) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it's nested inside `SystemMessage.data`.
146Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](https://code.claude.com/docs/en/agent-sdk/python#resultmessage) in Python, [`SDKResultMessage`](https://code.claude.com/docs/en/agent-sdk/typescript#sdkresultmessage) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it's nested inside `SystemMessage.data`.
147147
148148```python Python theme={null}
149149import asyncio
from line 211
211211Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume:
212212
213213* **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files.
214* **Recover from a limit.** The first run ended with `error_max_turns` or `error_max_budget_usd` (see [Handle the result](/docs/en/agent-sdk/agent-loop.md#handle-the-result)); resume with a higher limit. In a single-shot `query()` call the SDK raises after yielding that error result, so catch the error before resuming.
214* **Recover from a limit.** The first run ended with `error_max_turns` or `error_max_budget_usd` (see [Handle the result](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#handle-the-result)); resume with a higher limit. In a single-shot `query()` call the SDK raises after yielding that error result, so catch the error before resuming.
215215* **Restart your process.** You captured the ID before shutdown and want to restore the conversation.
216216
217217This example resumes the session from [Capture the session ID](#capture-the-session-id) with a follow-up prompt. Because you're resuming, the agent already has the prior analysis in context:
from line 264
264264>
265265> Claude Code stores sessions under `~/.claude/projects/<encoded-cwd>/*.jsonl`. If you set the `CLAUDE_CONFIG_DIR` environment variable, look under `$CLAUDE_CONFIG_DIR/projects/` instead.
266266>
267> To find your session's directory, replace every non-alphanumeric character in the absolute working directory with `-`: `/Users/me/proj` becomes `-Users-me-proj`. For a working directory whose converted name exceeds 200 characters, Claude Code [truncates the name and appends a hash](/docs/en/sessions.md#where-transcripts-are-stored), so match the first 200 characters of the converted name when you list `projects/`.
267> To find your session's directory, replace every non-alphanumeric character in the absolute working directory with `-`: `/Users/me/proj` becomes `-Users-me-proj`. For a working directory whose converted name exceeds 200 characters, Claude Code [truncates the name and appends a hash](https://code.claude.com/docs/en/sessions.md#where-transcripts-are-stored), so match the first 200 characters of the converted name when you list `projects/`.
268268>
269> If you set [`CLAUDE_CODE_PROJECT_DIR_NAME`](/docs/en/sessions#name-the-project-directory-yourself) beside `CLAUDE_CONFIG_DIR`, look under that name in `projects/` instead. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later.
269> If you set [`CLAUDE_CODE_PROJECT_DIR_NAME`](https://code.claude.com/docs/en/sessions#name-the-project-directory-yourself) beside `CLAUDE_CONFIG_DIR`, look under that name in `projects/` instead. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later.
270270>
271271> You can resume from any working directory:
272272>
273> * **Cross-directory lookup**: Claude Code searches beyond the current project directory to find the ID; see [Resume a session](/docs/en/sessions.md#where-the-session-picker-looks) for the exact lookup order and how duplicate copies are handled.
273> * **Cross-directory lookup**: Claude Code searches beyond the current project directory to find the ID; see [Resume a session](https://code.claude.com/docs/en/sessions.md#where-the-session-picker-looks) for the exact lookup order and how duplicate copies are handled.
274274> * **Same machine only**: the session file still needs to exist on the current machine.
275275>
276276> Before v2.1.223, the lookup was scoped to the current project directory and its git worktrees; SDK versions that bundle an older CLI still behave this way.
277277
278To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](/docs/en/agent-sdk/session-storage).
278To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](https://code.claude.com/docs/en/agent-sdk/session-storage).
279279
280280### Fork to explore alternatives
281281
from line 283
283283
284284> [!NOTE]
285285>
286> Forking branches the conversation history, not the filesystem. If a forked agent edits files, those changes are real and visible to any session working in the same directory. To branch and revert file changes, use [file checkpointing](/docs/en/agent-sdk/file-checkpointing.md).
286> Forking branches the conversation history, not the filesystem. If a forked agent edits files, those changes are real and visible to any session working in the same directory. To branch and revert file changes, use [file checkpointing](https://code.claude.com/docs/en/agent-sdk/file-checkpointing.md).
287287
288288This example builds on [Capture the session ID](#capture-the-session-id): you've already analyzed an auth module in `session_id` and want to explore OAuth2 without losing the JWT-focused thread. The first block forks the session and captures the fork's ID (`forked_id`); the second block resumes the original `session_id` to continue down the JWT path. You now have two session IDs pointing at two separate histories:
289289
from line 389
389389
390390Session files are local to the machine that created them. To resume a session on a different host (CI workers, ephemeral containers, serverless), pick the approach that fits:
391391
392* **Pass a session store.** Attach a [`sessionStore` / `session_store` adapter](/docs/en/agent-sdk/session-storage) so the SDK mirrors transcripts to your own backend and another host can resume them. The store lookup key derives from the working directory, so resume from a `cwd` matching the original run's.
392* **Pass a session store.** Attach a [`sessionStore` / `session_store` adapter](https://code.claude.com/docs/en/agent-sdk/session-storage) so the SDK mirrors transcripts to your own backend and another host can resume them. The store lookup key derives from the working directory, so resume from a `cwd` matching the original run's.
393393
394394* **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it inside any directory under `~/.claude/projects/` on the new host before calling `resume`.
395395
396 Claude Code searches beyond the current project directory to find the ID; see [Resume a session](/docs/en/sessions.md#where-the-session-picker-looks) for the exact lookup order and how duplicate copies are handled. Before v2.1.223, the lookup was scoped to the current project directory and its git worktrees; SDK versions that bundle an older CLI still behave this way.
396 Claude Code searches beyond the current project directory to find the ID; see [Resume a session](https://code.claude.com/docs/en/sessions.md#where-the-session-picker-looks) for the exact lookup order and how duplicate copies are handled. Before v2.1.223, the lookup was scoped to the current project directory and its git worktrees; SDK versions that bundle an older CLI still behave this way.
397397
398398* **Don't rely on session resume.** Capture the results you need (analysis output, decisions, file diffs) as application state and pass them into a fresh session's prompt. This is often more robust than shipping transcript files around.
399399
400Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](/docs/en/agent-sdk/typescript#listsessions) and [`getSessionMessages()`](/docs/en/agent-sdk/typescript#getsessionmessages) in TypeScript, [`list_sessions()`](/docs/en/agent-sdk/python#list_sessions) and [`get_session_messages()`](/docs/en/agent-sdk/python#get_session_messages) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers.
400Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](https://code.claude.com/docs/en/agent-sdk/typescript#listsessions) and [`getSessionMessages()`](https://code.claude.com/docs/en/agent-sdk/typescript#getsessionmessages) in TypeScript, [`list_sessions()`](https://code.claude.com/docs/en/agent-sdk/python#list_sessions) and [`get_session_messages()`](https://code.claude.com/docs/en/agent-sdk/python#get_session_messages) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers.
401401
402Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](/docs/en/agent-sdk/python#get_session_info), [`rename_session()`](/docs/en/agent-sdk/python#rename_session), and [`tag_session()`](/docs/en/agent-sdk/python#tag_session) in Python, and [`getSessionInfo()`](/docs/en/agent-sdk/typescript#getsessioninfo), [`renameSession()`](/docs/en/agent-sdk/typescript#renamesession), and [`tagSession()`](/docs/en/agent-sdk/typescript#tagsession) in TypeScript. Use them to organize sessions by tag or give them human-readable titles.
402Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](https://code.claude.com/docs/en/agent-sdk/python#get_session_info), [`rename_session()`](https://code.claude.com/docs/en/agent-sdk/python#rename_session), and [`tag_session()`](https://code.claude.com/docs/en/agent-sdk/python#tag_session) in Python, and [`getSessionInfo()`](https://code.claude.com/docs/en/agent-sdk/typescript#getsessioninfo), [`renameSession()`](https://code.claude.com/docs/en/agent-sdk/typescript#renamesession), and [`tagSession()`](https://code.claude.com/docs/en/agent-sdk/typescript#tagsession) in TypeScript. Use them to organize sessions by tag or give them human-readable titles.
403403
404404## Related resources
405405
406* [How the agent loop works](/docs/en/agent-sdk/agent-loop.md): Understand turns, messages, and context accumulation within a session
407* [File checkpointing](/docs/en/agent-sdk/file-checkpointing.md): Snapshot and revert file changes the agent made within a session
408* [Python `ClaudeAgentOptions`](/docs/en/agent-sdk/python#claudeagentoptions): Full session option reference for Python
409* [TypeScript `Options`](/docs/en/agent-sdk/typescript#options): Full session option reference for TypeScript
406* [How the agent loop works](https://code.claude.com/docs/en/agent-sdk/agent-loop.md): Understand turns, messages, and context accumulation within a session
407* [File checkpointing](https://code.claude.com/docs/en/agent-sdk/file-checkpointing.md): Snapshot and revert file changes the agent made within a session
408* [Python `ClaudeAgentOptions`](https://code.claude.com/docs/en/agent-sdk/python#claudeagentoptions): Full session option reference for Python
409* [TypeScript `Options`](https://code.claude.com/docs/en/agent-sdk/typescript#options): Full session option reference for TypeScript
410410
No line in this hunk matches that.