modified
Show diff (145 lines)
--- a/sessions.md +++ b/sessions.md @@ -4,11 +4,7 @@ This 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. -## - -​ - -Choose an approach +## Choose an approach How 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>) (they don’t end the call). @@ -21,11 +17,7 @@ Try an alternative approach without losing the original| Fork the session. 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. -### - -​ - -Continue, resume, and fork +### Continue, resume, and fork Continue, 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). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session: @@ -34,19 +26,11 @@ **Fork** is different: it creates a new session that starts with a copy of the original’s history. The original stays unchanged. Use fork to try a different direction while keeping the option to go back. -## - -​ - -Automatic session management +## Automatic session management Both SDKs offer an interface that tracks session state for you across calls, so you don’t pass IDs around manually. Use these for multi-turn conversations within a single process. -### - -​ - -Python: `ClaudeSDKClient` +### Python: `ClaudeSDKClient` [`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. This 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: @@ -95,11 +79,7 @@ Each query prints the agent’s text response followed by a status line from the result message, such as `[done: success, cost: $0.0042]`. See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claudesdkclient>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function. -### - -​ - -TypeScript: `continue: true` +### TypeScript: `continue: true` The TypeScript SDK doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call: @@ -138,17 +118,9 @@ The experimental [V2 session API](</docs/en/agent-sdk/typescript-v2-preview>), 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. -## - -​ - -Use session options with `query()` - -### - -​ - -Capture the session ID +## Use session options with `query()` + +### Capture the session ID Resume 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`. @@ -211,11 +183,7 @@ When the query completes, the script prints the agent’s response followed by a line such as `Session ID: 5b3f2c1a-8d4e-4f6b-9a7c-2e1d0f9b8a6c`. In the next sections, you pass this ID to `resume`. -### - -​ - -Resume by ID +### Resume by ID Pass 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: @@ -267,7 +235,7 @@ You should see a response that builds on the earlier analysis instead of starting fresh. That confirms the agent resumed the session with its prior context intact. -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.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#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.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.You can resume from any working directory: +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.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#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`. 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.You can resume from any working directory: * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#where-the-session-picker-looks>) for the exact lookup order and how duplicate copies are handled. * **Same machine only** : the session file still needs to exist on the current machine. @@ -276,11 +244,7 @@ To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). -### - -​ - -Fork to explore alternatives +### Fork to explore alternatives Forking creates a new session that starts with a copy of the original’s history but diverges from that point. The fork gets its own session ID; the original’s ID and history stay unchanged. You end up with two independent sessions you can resume separately. @@ -384,11 +348,7 @@ You should see that `forkedId` differs from the original session ID. Resuming the original session still continues the JWT thread, which confirms the fork did not modify the original history. -## - -​ - -Resume across hosts +## Resume across hosts Session 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: @@ -398,11 +358,7 @@ Both 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. Both 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. -## - -​ - -Related resources +## Related resources * [How the agent loop works](</docs/en/agent-sdk/agent-loop>): Understand turns, messages, and context accumulation within a session * [File checkpointing](</docs/en/agent-sdk/file-checkpointing>): Snapshot and revert file changes the agent made within a session
modified
--- a/sessions.md +++ b/sessions.md @@ -269,7 +269,7 @@ 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.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#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.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.You can resume from any working directory: - * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) for the exact lookup order and how duplicate copies are handled. + * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#where-the-session-picker-looks>) for the exact lookup order and how duplicate copies are handled. * **Same machine only** : the session file still needs to exist on the current machine. 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. @@ -393,7 +393,7 @@ Session 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: * **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. - * **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`. Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) 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. + * **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`. Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#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. * **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. Both 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. Both 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.
modified
--- a/sessions.md +++ b/sessions.md @@ -267,7 +267,7 @@ You should see a response that builds on the earlier analysis instead of starting fresh. That confirms the agent resumed the session with its prior context intact. -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.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#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.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.You can resume from any working directory: +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.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#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.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.You can resume from any working directory: * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) for the exact lookup order and how duplicate copies are handled. * **Same machine only** : the session file still needs to exist on the current machine.
modified
--- a/sessions.md +++ b/sessions.md @@ -267,7 +267,7 @@ You should see a response that builds on the earlier analysis instead of starting fresh. That confirms the agent resumed the session with its prior context intact. -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. 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#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.You can resume from any working directory: +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.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#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.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.You can resume from any working directory: * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) for the exact lookup order and how duplicate copies are handled. * **Same machine only** : the session file still needs to exist on the current machine.
modified
--- a/sessions.md +++ b/sessions.md @@ -390,8 +390,9 @@ Resume across hosts -Session files are local to the machine that created them. To resume a session on a different host (CI workers, ephemeral containers, serverless), you have two options: - +Session 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: + + * **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. * **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`. Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) 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. * **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.
modified
--- a/sessions.md +++ b/sessions.md @@ -267,7 +267,7 @@ You should see a response that builds on the earlier analysis instead of starting fresh. That confirms the agent resumed the session with its prior context intact. -Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, or under `$CLAUDE_CONFIG_DIR/projects/<encoded-cwd>/*.jsonl` if you set the `CLAUDE_CONFIG_DIR` environment variable. `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-`, so `/Users/me/proj` becomes `-Users-me-proj`.You can resume from any working directory: +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. 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#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.You can resume from any working directory: * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) for the exact lookup order and how duplicate copies are handled. * **Same machine only** : the session file still needs to exist on the current machine.
modified
Show diff (587 lines)
--- a/sessions.md +++ b/sessions.md @@ -1,201 +1,409 @@ -A session is a saved conversation tied to a project directory. Claude Code stores it locally as you work, so you can resume where you left off, branch to try a different approach, or switch between tasks. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), [Claude Code on the web](</docs/en/claude-code-on-the-web>), and the [VS Code extension](</docs/en/vs-code#resume-past-conversations>) each maintain their own session history. This page covers the CLI. +A session is the conversation history the SDK accumulates while your agent works. It contains your prompt, every tool call the agent made, every tool result, and every response. The SDK writes it to disk automatically so you can return to it later. Returning to a session means the agent has full context from before: files it already read, analysis it already performed, decisions it already made. You can ask a follow-up question, recover from an interruption, or branch off to try a different approach. + +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>). + +This 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. ## ​ -Resume a session - -Sessions are saved continuously to local transcript files as you work, so you can return to one after exiting or running `/clear`. Use these entry points: - -Command| What it does +Choose an approach + +How 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>) (they don’t end the call). + +What you’re building| What to use ---|--- -`claude --continue`| Resumes the most recent session in the current directory -`claude --resume`| Opens the session picker -`claude --resume <name>`| Resumes the named session directly -`claude --from-pr <number>`| Opens the session picker filtered to sessions linked to that pull request -`/resume`| Switches to a different conversation from inside an active session - -Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) don’t appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. You can run `claude --resume <session-id>` from any directory: Claude Code looks for the ID in the current project directory and its git worktrees first, then in every other project on this machine, so it finds a session that started elsewhere or moved with [`/cd`](</docs/en/commands>). The cross-project search resolves the ID only when exactly one other project holds a transcript with messages for it, so a hand-copied duplicate makes Claude Code report not-found rather than resume an arbitrary copy. If no stored session matches the ID, Claude Code reports `No conversation found with session ID: <session-id>`. Before v2.1.223, the lookup stopped at the current project directory and its git worktrees, so you had to resume from the directory the session last worked in. - -### - -​ - -What a resumed session restores - -A resumed session restores the conversation along with the state saved in it: - - * Conversation history: the full history, including tool calls and results. - * Model: the session continues on the model it was using. The model isn’t restored when it has been retired or isn’t allowed by `availableModels`, when a `--model` flag or `ANTHROPIC_MODEL`-family environment variable picks one at launch, or on providers that use provider-specific deployment IDs, such as [Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry](</docs/en/third-party-integrations>); see [model configuration](</docs/en/model-config#setting-your-model>) for the resolution order. - * Agent: a session started with [`--agent`](</docs/en/sub-agents#invoke-subagents-explicitly>) or the `agent` setting continues as that agent, keeping its system prompt, tool restrictions, and model. Pass `--agent` when resuming to pick a different one. Claude Code looks for the agent in two places: the session’s original directory, provided you have [trusted that workspace](</docs/en/permissions#project-allow-rules-and-workspace-trust>), and then the directory you resume from, so a project-scoped agent still loads when you resume from another directory. If Claude Code doesn’t find the agent in either place, the session resumes with the default tools and system prompt and shows a [warning naming the agent](</docs/en/errors#session-agent-no-longer-available>). - * Permission mode: the mode the session was in. `plan` and `bypassPermissions` are never restored; [bypassing permissions](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) must be enabled again at launch, with one of its launch flags or `permissions.defaultMode: "bypassPermissions"` in [settings](</docs/en/settings#permission-settings>). `auto` is restored only when your account still meets the [auto mode requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Pass `--permission-mode` to override the restored mode. - * Active goal: a [goal](</docs/en/goal#resume-with-an-active-goal>) that was still active when the session ended carries over; its turn count, timer, and token-spend baseline reset. - * Scheduled tasks: [tasks that haven’t expired](</docs/en/scheduled-tasks#limitations>) are restored. Background Bash and monitor tasks aren’t. - -Not every configuration flag from the original launch is restored. If the session depended on `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, or directories added with `--add-dir`, pass them again when you resume; directories added mid-session with `/add-dir` aren’t restored either, though the session picker still uses them to locate the session. The standard settings files, such as `settings.json` and `settings.local.json`, are re-read at launch, so configuration that lives in them doesn’t need to be passed again. - -### - -​ - -Resume from a summary - -On a Pro or Max plan, when you resume a session that has been inactive for more than about an hour and is over 100,000 tokens, Claude Code restores the conversation and then opens a dialog before you send your first message. The session’s [prompt cache](</docs/en/prompt-caching#cache-lifetime>) has expired by then, so the next request processes the full history once no matter which of the dialog’s options you pick. The dialog offers three ways to continue the session. They differ in how much of the conversation each one carries forward into later requests, which is a tradeoff between keeping every detail and sending fewer tokens per request: - - * **Resume from summary** : runs [`/compact`](</docs/en/context-window#what-survives-compaction>) immediately. Claude Code sends one summarization request over the full history, then replaces the history with the summary, your most recent exchanges, and up to five recently read files. Later requests carry the summary instead of the full history. - * **Resume full session as-is** : loads the conversation unchanged. After you send your first message, Claude Code reprocesses and re-caches the full history, then re-reads it from the cache on later requests while the cache stays warm. - * **Don’t ask me again** : resumes the full session and stops showing the dialog on all future resumes. - -Resuming as-is keeps every detail of the conversation available, at a per-request cost that scales with the conversation’s size. Resuming from the summary costs less on each later request because it carries the summary instead of the full history, but whatever the summary leaves out is no longer in Claude’s context. See [why usage climbs in a long session](</docs/en/costs#why-usage-climbs-in-a-long-session>) for where that per-request cost comes from. - -### - -​ - -Where the session picker looks - -Claude Code stores sessions per project directory. By default the session picker shows: - - * Sessions from the current worktree, including [background sessions](</docs/en/agent-view>), which are marked `bg` in the list - * Sessions started elsewhere that added the current directory with `/add-dir` - -Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Sessions whose first prompt was a [`/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>) command don’t appear in the picker; running `/loop` later in a conversation doesn’t hide the session. Before v2.1.211, a `/loop` run early in a conversation hid the session from the picker permanently. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. When you select a session from another worktree of the same repository, Claude Code resumes it in place. When you select a session from an unrelated project, Claude Code copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: - -Command| Exact match| Ambiguous name ----|---|--- -`claude --resume <name>`| Resumes directly| Opens the session picker with the name pre-filled as a search term -`/resume <name>`| Resumes directly| Reports an error; run `/resume` with no argument to open the session picker +One-shot task: single prompt, no follow-up| Nothing extra. One `query()` call handles it. +Multi-turn chat in one process| `ClaudeSDKClient` (Python) or `continue: true` (TypeScript). The SDK tracks the session for you with no ID handling. +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. +Resume a specific past session (not the most recent)| Capture the session ID and pass it to `resume`. +Try an alternative approach without losing the original| Fork the session. +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. + +### + +​ + +Continue, resume, and fork + +Continue, 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). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session: + + * **Continue** finds the most recent session in the current directory. You don’t track anything. Works well when your app runs one conversation at a time. + * **Resume** takes a specific session ID. You track the ID. Required when you have multiple sessions (for example, one per user in a multi-user app) or want to return to one that isn’t the most recent. + +**Fork** is different: it creates a new session that starts with a copy of the original’s history. The original stays unchanged. Use fork to try a different direction while keeping the option to go back. ## ​ -Name your sessions - -Give sessions descriptive names so they’re findable in the session picker and resumable by name. This matters most when you’re working on several tasks in parallel. - -When| How to set the name ----|--- -At startup| `claude -n auth-refactor` -During a session| `/rename auth-refactor`. The name also appears on the prompt bar -From the session picker| Highlight a session and press `Ctrl+R` -On plan accept| Accepting a plan in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) names the session from the plan content unless you’ve already set one -From claude.ai or the Claude app| Rename a [Remote Control session](</docs/en/remote-control#connect-from-another-device>); Claude Code applies the same name in the CLI. Requires Claude Code v2.1.221 or later -From the desktop app| Rename a session in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>) - -Once you name a session through a CLI route or from claude.ai, return to it with `claude --resume <name>` or `/resume <name>`; a desktop-app session resumes in the app, which keeps its own session history. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. If you don’t name a session, Claude Code generates a session title for it: a short summary of your first prompt, written by a background request to the small/fast model, normally a Haiku-class model. Naming the session with `--name` or `/rename` replaces the generated title. You see the generated title in the session picker and in the statusline [`session_name`](</docs/en/statusline>) field when no name is set; like the default display name, it isn’t a resume handle. +Automatic session management + +Both SDKs offer an interface that tracks session state for you across calls, so you don’t pass IDs around manually. Use these for multi-turn conversations within a single process. + +### + +​ + +Python: `ClaudeSDKClient` + +[`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. This 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: + +Python + + import asyncio + from claude_agent_sdk import ( + ClaudeSDKClient, + ClaudeAgentOptions, + AssistantMessage, + ResultMessage, + TextBlock, + ) + + def print_response(message): + """Print only the human-readable parts of a message.""" + if isinstance(message, AssistantMessage): + for block in message.content: + if isinstance(block, TextBlock): + print(block.text) + elif isinstance(message, ResultMessage): + cost = ( + f"${message.total_cost_usd:.4f}" + if message.total_cost_usd is not None + else "N/A" + ) + print(f"[done: {message.subtype}, cost: {cost}]") + + async def main(): + options = ClaudeAgentOptions( + allowed_tools=["Read", "Edit", "Glob", "Grep"], + ) + + async with ClaudeSDKClient(options=options) as client: + # First query: client captures the session ID internally + await client.query("Analyze the auth module") + async for message in client.receive_response(): + print_response(message) + + # Second query: automatically continues the same session + await client.query("Now refactor it to use JWT") + async for message in client.receive_response(): + print_response(message) + + asyncio.run(main()) + +Each query prints the agent’s text response followed by a status line from the result message, such as `[done: success, cost: $0.0042]`. See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claudesdkclient>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function. + +### + +​ + +TypeScript: `continue: true` + +The TypeScript SDK doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call: + +TypeScript + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + // First query: creates a new session + try { + for await (const message of query({ + prompt: "Analyze the auth module", + options: { allowedTools: ["Read", "Glob", "Grep"] } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result, + // so the follow-up query below still runs. + console.error(`Session ended with an error: ${error}`); + } + + // Second query: continue: true resumes the most recent session + for await (const message of query({ + prompt: "Now refactor it to use JWT", + options: { + continue: true, + allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"] + } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + +The experimental [V2 session API](</docs/en/agent-sdk/typescript-v2-preview>), 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. ## ​ -Use the session picker - -Run `/resume` inside a session, or `claude --resume` with no arguments, to open the interactive session picker. Use these keyboard shortcuts to navigate, search, and widen the list: - -Shortcut| Action ----|--- -`↑` / `↓`| Navigate between sessions -`→` / `←`| Expand or collapse grouped sessions -`Enter`| Resume the highlighted session -`Space`| Preview the session content. `Ctrl+V` also works on terminals that don’t capture it as paste -`Ctrl+R`| Rename the highlighted session -`/` or any printable character other than `Space`| Enter search mode and filter sessions. Paste a GitHub, GitHub Enterprise, GitLab, or Bitbucket pull or merge request URL to find the session that created it -`Ctrl+A`| Show sessions from all projects on this machine. Press again to return to the current repository -`Ctrl+W`| Show sessions from all worktrees of the current repository. Press again to return to the current worktree. Only shown in multi-worktree repositories -`Ctrl+B`| Filter to sessions from the current git branch. Press again to show all branches -`Esc`| Exit the session picker or search mode - -Each row shows the session name if you set one, otherwise the AI-generated session title, conversation summary, or first prompt, along with time since last activity, git branch, and file size. Widen to all projects with `Ctrl+A` to also see each session’s project path. Sessions created with `/branch` or `--fork-session` get their own session IDs and appear as separate rows. When the picker finds more than one entry for the same session, it groups them under a single row. Press `→` to expand a group. If Claude Code can’t load the session you select from the `claude --resume` picker, it prints [`Failed to resume the conversation`](</docs/en/errors#failed-to-resume-the-conversation>) with a command to retry, then exits with code 1. From the `/resume` picker inside a session, Claude Code reports the failure and your current conversation keeps running. +Use session options with `query()` + +### + +​ + +Capture the session ID + +Resume 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`. + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + async def main(): + session_id = None + + try: + async for message in query( + prompt="Analyze the auth module and suggest improvements", + options=ClaudeAgentOptions( + allowed_tools=["Read", "Glob", "Grep"], + ), + ): + if isinstance(message, ResultMessage): + session_id = message.session_id + if message.subtype == "success": + print(message.result) + except Exception as error: + # A single-shot query() raises after yielding an error result. If the + # failure was an error result, the loop above already captured session_id; + # connection or process failures yield no result message, so session_id stays None. + print(f"Session ended with an error: {error}") + + print(f"Session ID: {session_id}") + return session_id + + session_id = asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + let sessionId: string | undefined; + + try { + for await (const message of query({ + prompt: "Analyze the auth module and suggest improvements", + options: { allowedTools: ["Read", "Glob", "Grep"] } + })) { + if (message.type === "result") { + sessionId = message.session_id; + if (message.subtype === "success") { + console.log(message.result); + } + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result. If the + // failure was an error result, the loop above already captured sessionId; + // connection or process failures yield no result message, so sessionId stays undefined. + console.error(`Session ended with an error: ${error}`); + } + + console.log(`Session ID: ${sessionId}`); + +When the query completes, the script prints the agent’s response followed by a line such as `Session ID: 5b3f2c1a-8d4e-4f6b-9a7c-2e1d0f9b8a6c`. In the next sections, you pass this ID to `resume`. + +### + +​ + +Resume by ID + +Pass 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: + + * **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files. + * **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#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. + * **Restart your process.** You captured the ID before shutdown and want to restore the conversation. + +This example resumes the session from Capture the session ID with a follow-up prompt. Because you’re resuming, the agent already has the prior analysis in context: + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + session_id = "..." # The ID you captured in the previous example + + async def main(): + # Earlier session analyzed the code; now build on that analysis + async for message in query( + prompt="Now implement the refactoring you suggested", + options=ClaudeAgentOptions( + resume=session_id, + allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"], + ), + ): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + + asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + const sessionId = "..."; // The ID you captured in the previous example + + // Earlier session analyzed the code; now build on that analysis + for await (const message of query({ + prompt: "Now implement the refactoring you suggested", + options: { + resume: sessionId, + allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"] + } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + +You should see a response that builds on the earlier analysis instead of starting fresh. That confirms the agent resumed the session with its prior context intact. + +Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, or under `$CLAUDE_CONFIG_DIR/projects/<encoded-cwd>/*.jsonl` if you set the `CLAUDE_CONFIG_DIR` environment variable. `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-`, so `/Users/me/proj` becomes `-Users-me-proj`.You can resume from any working directory: + + * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) for the exact lookup order and how duplicate copies are handled. + * **Same machine only** : the session file still needs to exist on the current machine. + +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. + +To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). + +### + +​ + +Fork to explore alternatives + +Forking creates a new session that starts with a copy of the original’s history but diverges from that point. The fork gets its own session ID; the original’s ID and history stay unchanged. You end up with two independent sessions you can resume separately. + +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>). + +This example builds on 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: + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + session_id = "..." # The ID you captured in the previous example + + async def main(): + # Fork: branch from session_id into a new session + forked_id = None + try: + async for message in query( + prompt="Instead of JWT, outline how OAuth2 would work for the auth module", + options=ClaudeAgentOptions( + resume=session_id, + fork_session=True, + max_turns=5, + ), + ): + if isinstance(message, ResultMessage): + forked_id = message.session_id # The fork's ID, distinct from session_id + if message.subtype == "success": + print(message.result) + except Exception as error: + # A single-shot query() raises after yielding an error result. If the + # failure was an error result, forked_id was already captured by the + # loop above; connection or process failures yield no result message. + print(f"Session ended with an error: {error}") + + print(f"Forked session: {forked_id}") + + # Original session is untouched; resuming it continues the JWT thread + try: + async for message in query( + prompt="Continue with the JWT approach", + options=ClaudeAgentOptions(resume=session_id), + ): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + except Exception as error: + # A single-shot query() raises after yielding an error result. + print(f"Session ended with an error: {error}") + + asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + const sessionId = "..."; // The ID you captured in the previous example + + // Fork: branch from sessionId into a new session + let forkedId: string | undefined; + + try { + for await (const message of query({ + prompt: "Instead of JWT, outline how OAuth2 would work for the auth module", + options: { + resume: sessionId, + forkSession: true, + maxTurns: 5 + } + })) { + if (message.type === "system" && message.subtype === "init") { + forkedId = message.session_id; // The fork's ID, distinct from sessionId + } + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result. If the + // failure was an error result, forkedId was already captured by the loop + // above; connection or process failures yield no result message. + console.error(`Session ended with an error: ${error}`); + } + + console.log(`Forked session: ${forkedId}`); + + // Original session is untouched; resuming it continues the JWT thread + try { + for await (const message of query({ + prompt: "Continue with the JWT approach", + options: { resume: sessionId } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result. + console.error(`Session ended with an error: ${error}`); + } + +You should see that `forkedId` differs from the original session ID. Resuming the original session still continues the JWT thread, which confirms the fork did not modify the original history. ## ​ -Branch a session - -Branching creates a copy of the conversation so far and switches you into it, leaving the original intact. Use it to try a different approach without losing the path you were on. From inside a session, run `/branch` with an optional name: - - /branch try-streaming-approach - -If you omit the name, Claude Code names the new branch after the first prompt in the conversation. As of v2.1.198 this also applies after [compaction](</docs/en/how-claude-code-works#when-context-fills-up>); earlier versions fell back to the literal name `Branched conversation` instead of looking past the compaction summary to the original first prompt. From the command line, combine `--continue` or `--resume` with `--fork-session`: - - claude --continue --fork-session - -The `/branch` confirmation prints two session IDs: the new branch you are now in and the original. The original is unchanged on disk and remains in the session picker; return to it with `/resume <original-name>` or by passing its ID to `/resume`. `/branch` copies the transcript and switches the running Claude Code process to write to it. That distinction determines what the branch inherits: - -State| After `/branch` ----|--- -Conversation history| Copied into the branch up to the point you ran `/branch` -”Allow for this session” permission grants| Carried over; the branch runs in the same process, so your existing grants still apply. If you fork into a separate process with `--fork-session`, the new process starts without them and you re-approve there -In-flight [background subagents](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) and [background Bash commands](</docs/en/interactive-mode#background-bash-commands>)| Keep running. Their output appears in the new branch you switched into, not in the original session - -If you resume the same session in two terminals without forking, messages from both interleave into one transcript. For checkpoint-based rewind within a single session, see [Checkpointing](</docs/en/checkpointing>). +Resume across hosts + +Session files are local to the machine that created them. To resume a session on a different host (CI workers, ephemeral containers, serverless), you have two options: + + * **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`. Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) 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. + * **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. + +Both 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. Both 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. ## ​ -Manage context within a session - -These commands control what’s in the context window without leaving the session: - - * **`/clear`** : start fresh with an empty context. Claude Code saves the previous conversation; resume it with `/resume`, or, in the same Claude Code process, from [the rewind menu’s previous-session entry](</docs/en/checkpointing#rewind-past-a-cleared-conversation>). You keep a name you set with `--name` or `/rename` in the new conversation, but not an AI-generated session title - * **`/compact [instructions]`** : replace history with a summary, optionally focused on what you specify - * **`/context`** : show what is currently consuming context - -For how compaction interacts with CLAUDE.md, skills, and rules, see the [context window guide](</docs/en/context-window>). For strategies on when to clear versus compact, see [Best practices](</docs/en/best-practices#manage-your-session>). - -## - -​ - -Export and locate session data - -Run `/export` to open a menu that lets you copy the current conversation to your clipboard or save it as a plain-text file, with messages and tool outputs rendered as readable text. Pass a filename to skip the menu and write directly to that file. - -### - -​ - -Access conversations from scripts - -`/export` produces a rendered transcript for a person to read. The interfaces below produce structured data for a script to parse: a JSON result from a run, the path to a session’s transcript file, or a live stream of events. Pick by what triggers the script: - - * **Run Claude once and capture the result** : invoke `claude -p` with [`--output-format json` or `stream-json`](</docs/en/headless#get-structured-output>) to capture the result, session ID, usage, and cost of a non-interactive run as structured JSON. - * **Ask an existing session a question** : pass a session ID to [`claude -p --resume`](</docs/en/headless#continue-conversations>) to send a follow-up prompt, such as a summary request, and capture the structured response. - * **React to session events** : read the `transcript_path` field that [hooks](</docs/en/hooks#common-input-fields>) and [status line commands](</docs/en/statusline#available-data>) receive as input. A `SessionEnd` hook can archive the transcript when a session ends. - * **Embed Claude in a TypeScript or Python app** : use the [Agent SDK](</docs/en/agent-sdk/overview>) to receive each message programmatically. - -The example below uses the second interface. It sends a follow-up prompt to an existing session and reads the answer with `jq`: - - claude -p --resume <session-id> --output-format json "summarize what we changed" | jq -r '.result' - -### - -​ - -Where transcripts are stored - -By default, transcripts are stored as JSONL at `~/.claude/projects/<project>/<session-id>.jsonl`, where `<project>` is your working directory path with non-alphanumeric characters replaced by `-`. Each line is a JSON object for a message, tool use, or metadata entry. The entry format is internal to Claude Code and changes between versions, so scripts that parse these files directly can break on any release. To build on session data, use `/export` or the script interfaces instead. The location, retention, and write behavior are configurable: - -To| Set| Where ----|---|--- -Move storage off `~/.claude`| [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>)| Environment variable -Change the 30-day retention| [`cleanupPeriodDays`](</docs/en/settings#available-settings>)| `settings.json` -Suppress transcript writes in all modes| [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>)| Environment variable -Suppress writes for one non-interactive run| [`--no-session-persistence`](</docs/en/cli-reference>)| CLI flag with `claude -p` - -## - -​ - -See also - -These pages cover related session and parallelism mechanics: - - * [Worktrees](</docs/en/worktrees>): run isolated parallel sessions on separate branches - * [Checkpointing](</docs/en/checkpointing>): rewind code and conversation to an earlier point - * [Context window](</docs/en/context-window>): what fills context and what survives compaction - * [Non-interactive mode](</docs/en/headless>): session behavior under `claude -p` +Related resources + + * [How the agent loop works](</docs/en/agent-sdk/agent-loop>): Understand turns, messages, and context accumulation within a session + * [File checkpointing](</docs/en/agent-sdk/file-checkpointing>): Snapshot and revert file changes the agent made within a session + * [Python `ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>): Full session option reference for Python + * [TypeScript `Options`](</docs/en/agent-sdk/typescript#options>): Full session option reference for TypeScript
modified
--- a/sessions.md +++ b/sessions.md @@ -16,7 +16,7 @@ `claude --from-pr <number>`| Opens the session picker filtered to sessions linked to that pull request `/resume`| Switches to a different conversation from inside an active session -Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) don’t appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. You can run `claude --resume <session-id>` from any directory: Claude Code looks for the ID in the current project directory and its git worktrees first, then in every other project on this machine, so it finds a session that started elsewhere or moved with [`/cd`](</docs/en/commands>). The cross-project search resolves the ID only when exactly one other project holds a transcript for it, so a hand-copied duplicate makes Claude Code report not-found rather than resume an arbitrary copy. If no stored session matches the ID, Claude Code reports `No conversation found with session ID: <session-id>`. Before v2.1.223, the lookup stopped at the current project directory and its git worktrees, so you had to resume from the directory the session last worked in. +Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) don’t appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. You can run `claude --resume <session-id>` from any directory: Claude Code looks for the ID in the current project directory and its git worktrees first, then in every other project on this machine, so it finds a session that started elsewhere or moved with [`/cd`](</docs/en/commands>). The cross-project search resolves the ID only when exactly one other project holds a transcript with messages for it, so a hand-copied duplicate makes Claude Code report not-found rather than resume an arbitrary copy. If no stored session matches the ID, Claude Code reports `No conversation found with session ID: <session-id>`. Before v2.1.223, the lookup stopped at the current project directory and its git worktrees, so you had to resume from the directory the session last worked in. ###
modified
--- a/sessions.md +++ b/sessions.md @@ -16,7 +16,7 @@ `claude --from-pr <number>`| Opens the session picker filtered to sessions linked to that pull request `/resume`| Switches to a different conversation from inside an active session -Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. Run this from the directory the session was started in: session ID lookup is scoped to the current project directory and its git worktrees, so a session created elsewhere reports `No conversation found with session ID: <session-id>`. +Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) don’t appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. You can run `claude --resume <session-id>` from any directory: Claude Code looks for the ID in the current project directory and its git worktrees first, then in every other project on this machine, so it finds a session that started elsewhere or moved with [`/cd`](</docs/en/commands>). The cross-project search resolves the ID only when exactly one other project holds a transcript for it, so a hand-copied duplicate makes Claude Code report not-found rather than resume an arbitrary copy. If no stored session matches the ID, Claude Code reports `No conversation found with session ID: <session-id>`. Before v2.1.223, the lookup stopped at the current project directory and its git worktrees, so you had to resume from the directory the session last worked in. ### @@ -82,7 +82,7 @@ From the session picker| Highlight a session and press `Ctrl+R` On plan accept| Accepting a plan in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) names the session from the plan content unless you’ve already set one From claude.ai or the Claude app| Rename a [Remote Control session](</docs/en/remote-control#connect-from-another-device>); Claude Code applies the same name in the CLI. Requires Claude Code v2.1.221 or later -From the desktop app| Rename a session in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>); that section covers where the name is visible from the CLI. Requires Claude Code v2.1.221 or later +From the desktop app| Rename a session in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>) Once you name a session through a CLI route or from claude.ai, return to it with `claude --resume <name>` or `/resume <name>`; a desktop-app session resumes in the app, which keeps its own session history. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. If you don’t name a session, Claude Code generates a session title for it: a short summary of your first prompt, written by a background request to the small/fast model, normally a Haiku-class model. Naming the session with `--name` or `/rename` replaces the generated title. You see the generated title in the session picker and in the statusline [`session_name`](</docs/en/statusline>) field when no name is set; like the default display name, it isn’t a resume handle.
modified
--- a/sessions.md +++ b/sessions.md @@ -82,9 +82,9 @@ From the session picker| Highlight a session and press `Ctrl+R` On plan accept| Accepting a plan in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) names the session from the plan content unless you’ve already set one From claude.ai or the Claude app| Rename a [Remote Control session](</docs/en/remote-control#connect-from-another-device>); Claude Code applies the same name in the CLI. Requires Claude Code v2.1.221 or later -From the desktop app| Rename a session in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>); Claude Code applies the same name in the CLI. Requires Claude Code v2.1.221 or later - -Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. If you don’t name a session, Claude Code generates a session title for it: a short summary of your first prompt, written by a background request to the small/fast model, normally a Haiku-class model. Naming the session with `--name` or `/rename` replaces the generated title. You see the generated title in the session picker and in the statusline [`session_name`](</docs/en/statusline>) field when no name is set; like the default display name, it isn’t a resume handle. +From the desktop app| Rename a session in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>); that section covers where the name is visible from the CLI. Requires Claude Code v2.1.221 or later + +Once you name a session through a CLI route or from claude.ai, return to it with `claude --resume <name>` or `/resume <name>`; a desktop-app session resumes in the app, which keeps its own session history. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. If you don’t name a session, Claude Code generates a session title for it: a short summary of your first prompt, written by a background request to the small/fast model, normally a Haiku-class model. Naming the session with `--name` or `/rename` replaces the generated title. You see the generated title in the session picker and in the statusline [`session_name`](</docs/en/statusline>) field when no name is set; like the default display name, it isn’t a resume handle. ##
modified
--- a/sessions.md +++ b/sessions.md @@ -81,6 +81,8 @@ During a session| `/rename auth-refactor`. The name also appears on the prompt bar From the session picker| Highlight a session and press `Ctrl+R` On plan accept| Accepting a plan in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) names the session from the plan content unless you’ve already set one +From claude.ai or the Claude app| Rename a [Remote Control session](</docs/en/remote-control#connect-from-another-device>); Claude Code applies the same name in the CLI. Requires Claude Code v2.1.221 or later +From the desktop app| Rename a session in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>); Claude Code applies the same name in the CLI. Requires Claude Code v2.1.221 or later Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. If you don’t name a session, Claude Code generates a session title for it: a short summary of your first prompt, written by a background request to the small/fast model, normally a Haiku-class model. Naming the session with `--name` or `/rename` replaces the generated title. You see the generated title in the session picker and in the statusline [`session_name`](</docs/en/statusline>) field when no name is set; like the default display name, it isn’t a resume handle.
modified
--- a/sessions.md +++ b/sessions.md @@ -60,7 +60,7 @@ * Sessions from the current worktree, including [background sessions](</docs/en/agent-view>), which are marked `bg` in the list * Sessions started elsewhere that added the current directory with `/add-dir` -Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Sessions whose first prompt was a [`/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>) command don’t appear in the picker; running `/loop` later in a conversation doesn’t hide the session. Before v2.1.211, a `/loop` run early in a conversation hid the session from the picker permanently. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: +Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Sessions whose first prompt was a [`/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>) command don’t appear in the picker; running `/loop` later in a conversation doesn’t hide the session. Before v2.1.211, a `/loop` run early in a conversation hid the session from the picker permanently. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. When you select a session from another worktree of the same repository, Claude Code resumes it in place. When you select a session from an unrelated project, Claude Code copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: Command| Exact match| Ambiguous name ---|---|---
modified
--- a/sessions.md +++ b/sessions.md @@ -34,6 +34,20 @@ * Scheduled tasks: [tasks that haven’t expired](</docs/en/scheduled-tasks#limitations>) are restored. Background Bash and monitor tasks aren’t. Not every configuration flag from the original launch is restored. If the session depended on `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, or directories added with `--add-dir`, pass them again when you resume; directories added mid-session with `/add-dir` aren’t restored either, though the session picker still uses them to locate the session. The standard settings files, such as `settings.json` and `settings.local.json`, are re-read at launch, so configuration that lives in them doesn’t need to be passed again. + +### + +​ + +Resume from a summary + +On a Pro or Max plan, when you resume a session that has been inactive for more than about an hour and is over 100,000 tokens, Claude Code restores the conversation and then opens a dialog before you send your first message. The session’s [prompt cache](</docs/en/prompt-caching#cache-lifetime>) has expired by then, so the next request processes the full history once no matter which of the dialog’s options you pick. The dialog offers three ways to continue the session. They differ in how much of the conversation each one carries forward into later requests, which is a tradeoff between keeping every detail and sending fewer tokens per request: + + * **Resume from summary** : runs [`/compact`](</docs/en/context-window#what-survives-compaction>) immediately. Claude Code sends one summarization request over the full history, then replaces the history with the summary, your most recent exchanges, and up to five recently read files. Later requests carry the summary instead of the full history. + * **Resume full session as-is** : loads the conversation unchanged. After you send your first message, Claude Code reprocesses and re-caches the full history, then re-reads it from the cache on later requests while the cache stays warm. + * **Don’t ask me again** : resumes the full session and stops showing the dialog on all future resumes. + +Resuming as-is keeps every detail of the conversation available, at a per-request cost that scales with the conversation’s size. Resuming from the summary costs less on each later request because it carries the summary instead of the full history, but whatever the summary leaves out is no longer in Claude’s context. See [why usage climbs in a long session](</docs/en/costs#why-usage-climbs-in-a-long-session>) for where that per-request cost comes from. ###
modified
--- a/sessions.md +++ b/sessions.md @@ -28,7 +28,7 @@ * Conversation history: the full history, including tool calls and results. * Model: the session continues on the model it was using. The model isn’t restored when it has been retired or isn’t allowed by `availableModels`, when a `--model` flag or `ANTHROPIC_MODEL`-family environment variable picks one at launch, or on providers that use provider-specific deployment IDs, such as [Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry](</docs/en/third-party-integrations>); see [model configuration](</docs/en/model-config#setting-your-model>) for the resolution order. - * Agent: a session started with [`--agent`](</docs/en/sub-agents#invoke-subagents-explicitly>) or the `agent` setting continues as that agent, keeping its system prompt, tool restrictions, and model. Pass `--agent` when resuming to pick a different one. If the agent no longer exists in the session’s original directory or the one you resume from, the session resumes with the default tools and system prompt and shows a [warning naming the agent](</docs/en/errors#session-agent-no-longer-available>). + * Agent: a session started with [`--agent`](</docs/en/sub-agents#invoke-subagents-explicitly>) or the `agent` setting continues as that agent, keeping its system prompt, tool restrictions, and model. Pass `--agent` when resuming to pick a different one. Claude Code looks for the agent in two places: the session’s original directory, provided you have [trusted that workspace](</docs/en/permissions#project-allow-rules-and-workspace-trust>), and then the directory you resume from, so a project-scoped agent still loads when you resume from another directory. If Claude Code doesn’t find the agent in either place, the session resumes with the default tools and system prompt and shows a [warning naming the agent](</docs/en/errors#session-agent-no-longer-available>). * Permission mode: the mode the session was in. `plan` and `bypassPermissions` are never restored; [bypassing permissions](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) must be enabled again at launch, with one of its launch flags or `permissions.defaultMode: "bypassPermissions"` in [settings](</docs/en/settings#permission-settings>). `auto` is restored only when your account still meets the [auto mode requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Pass `--permission-mode` to override the restored mode. * Active goal: a [goal](</docs/en/goal#resume-with-an-active-goal>) that was still active when the session ended carries over; its turn count, timer, and token-spend baseline reset. * Scheduled tasks: [tasks that haven’t expired](</docs/en/scheduled-tasks#limitations>) are restored. Background Bash and monitor tasks aren’t.
modified
--- a/sessions.md +++ b/sessions.md @@ -107,7 +107,15 @@ claude --continue --fork-session -The original session is unchanged and remains available in the session picker. The `/branch` confirmation prints two session IDs: the new branch you are now in and the original. To return to the original, pass its ID to `/resume`, use the session picker, or run `/resume <original-name>`. Permissions you approved with “allow for this session” do not carry over to the new branch. If you resume the same session in two terminals without forking, messages from both interleave into one transcript. For checkpoint-based rewind within a single session, see [Checkpointing](</docs/en/checkpointing>). +The `/branch` confirmation prints two session IDs: the new branch you are now in and the original. The original is unchanged on disk and remains in the session picker; return to it with `/resume <original-name>` or by passing its ID to `/resume`. `/branch` copies the transcript and switches the running Claude Code process to write to it. That distinction determines what the branch inherits: + +State| After `/branch` +---|--- +Conversation history| Copied into the branch up to the point you ran `/branch` +”Allow for this session” permission grants| Carried over; the branch runs in the same process, so your existing grants still apply. If you fork into a separate process with `--fork-session`, the new process starts without them and you re-approve there +In-flight [background subagents](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) and [background Bash commands](</docs/en/interactive-mode#background-bash-commands>)| Keep running. Their output appears in the new branch you switched into, not in the original session + +If you resume the same session in two terminals without forking, messages from both interleave into one transcript. For checkpoint-based rewind within a single session, see [Checkpointing](</docs/en/checkpointing>). ##
modified
--- a/sessions.md +++ b/sessions.md @@ -28,6 +28,7 @@ * Conversation history: the full history, including tool calls and results. * Model: the session continues on the model it was using. The model isn’t restored when it has been retired or isn’t allowed by `availableModels`, when a `--model` flag or `ANTHROPIC_MODEL`-family environment variable picks one at launch, or on providers that use provider-specific deployment IDs, such as [Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry](</docs/en/third-party-integrations>); see [model configuration](</docs/en/model-config#setting-your-model>) for the resolution order. + * Agent: a session started with [`--agent`](</docs/en/sub-agents#invoke-subagents-explicitly>) or the `agent` setting continues as that agent, keeping its system prompt, tool restrictions, and model. Pass `--agent` when resuming to pick a different one. If the agent no longer exists in the session’s original directory or the one you resume from, the session resumes with the default tools and system prompt and shows a [warning naming the agent](</docs/en/errors#session-agent-no-longer-available>). * Permission mode: the mode the session was in. `plan` and `bypassPermissions` are never restored; [bypassing permissions](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) must be enabled again at launch, with one of its launch flags or `permissions.defaultMode: "bypassPermissions"` in [settings](</docs/en/settings#permission-settings>). `auto` is restored only when your account still meets the [auto mode requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Pass `--permission-mode` to override the restored mode. * Active goal: a [goal](</docs/en/goal#resume-with-an-active-goal>) that was still active when the session ended carries over; its turn count, timer, and token-spend baseline reset. * Scheduled tasks: [tasks that haven’t expired](</docs/en/scheduled-tasks#limitations>) are restored. Background Bash and monitor tasks aren’t. @@ -40,7 +41,12 @@ Where the session picker looks -Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Sessions whose first prompt was a [`/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>) command don’t appear in the picker; running `/loop` later in a conversation doesn’t hide the session. Before v2.1.211, a `/loop` run early in a conversation hid the session from the picker permanently. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: +Claude Code stores sessions per project directory. By default the session picker shows: + + * Sessions from the current worktree, including [background sessions](</docs/en/agent-view>), which are marked `bg` in the list + * Sessions started elsewhere that added the current directory with `/add-dir` + +Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Sessions whose first prompt was a [`/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>) command don’t appear in the picker; running `/loop` later in a conversation doesn’t hide the session. Before v2.1.211, a `/loop` run early in a conversation hid the session from the picker permanently. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: Command| Exact match| Ambiguous name ---|---|--- @@ -85,7 +91,7 @@ `Ctrl+B`| Filter to sessions from the current git branch. Press again to show all branches `Esc`| Exit the session picker or search mode -Each row shows the session name if you set one, otherwise the AI-generated session title, conversation summary, or first prompt, along with time since last activity, git branch, and file size. Widen to all projects with `Ctrl+A` to also see each session’s project path. Sessions created with `/branch` or `--fork-session` get their own session IDs and appear as separate rows. When the picker finds more than one entry for the same session, it groups them under a single row. Press `→` to expand a group. +Each row shows the session name if you set one, otherwise the AI-generated session title, conversation summary, or first prompt, along with time since last activity, git branch, and file size. Widen to all projects with `Ctrl+A` to also see each session’s project path. Sessions created with `/branch` or `--fork-session` get their own session IDs and appear as separate rows. When the picker finds more than one entry for the same session, it groups them under a single row. Press `→` to expand a group. If Claude Code can’t load the session you select from the `claude --resume` picker, it prints [`Failed to resume the conversation`](</docs/en/errors#failed-to-resume-the-conversation>) with a command to retry, then exits with code 1. From the `/resume` picker inside a session, Claude Code reports the failure and your current conversation keeps running. ##
modified
--- a/sessions.md +++ b/sessions.md @@ -62,7 +62,7 @@ From the session picker| Highlight a session and press `Ctrl+R` On plan accept| Accepting a plan in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) names the session from the plan content unless you’ve already set one -Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. +Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. If you don’t name a session, Claude Code generates a session title for it: a short summary of your first prompt, written by a background request to the small/fast model, normally a Haiku-class model. Naming the session with `--name` or `/rename` replaces the generated title. You see the generated title in the session picker and in the statusline [`session_name`](</docs/en/statusline>) field when no name is set; like the default display name, it isn’t a resume handle. ## @@ -85,7 +85,7 @@ `Ctrl+B`| Filter to sessions from the current git branch. Press again to show all branches `Esc`| Exit the session picker or search mode -Each row shows the session name if set, otherwise the conversation summary or first prompt, along with time since last activity, message count, and git branch. Project path appears after you widen to all projects with `Ctrl+A`. Forked sessions created with `/branch`, `/rewind`, or `--fork-session` are grouped under their root session. Press `→` to expand a group. +Each row shows the session name if you set one, otherwise the AI-generated session title, conversation summary, or first prompt, along with time since last activity, git branch, and file size. Widen to all projects with `Ctrl+A` to also see each session’s project path. Sessions created with `/branch` or `--fork-session` get their own session IDs and appear as separate rows. When the picker finds more than one entry for the same session, it groups them under a single row. Press `→` to expand a group. ## @@ -111,7 +111,7 @@ These commands control what’s in the context window without leaving the session: - * **`/clear`** : start fresh with an empty context. The previous conversation is saved and resumable with `/resume`, or, in the same Claude Code process, from [the rewind menu’s previous-session entry](</docs/en/checkpointing#rewind-past-a-cleared-conversation>) + * **`/clear`** : start fresh with an empty context. Claude Code saves the previous conversation; resume it with `/resume`, or, in the same Claude Code process, from [the rewind menu’s previous-session entry](</docs/en/checkpointing#rewind-past-a-cleared-conversation>). You keep a name you set with `--name` or `/rename` in the new conversation, but not an AI-generated session title * **`/compact [instructions]`** : replace history with a summary, optionally focused on what you specify * **`/context`** : show what is currently consuming context
modified
--- a/sessions.md +++ b/sessions.md @@ -13,7 +13,7 @@ `claude --continue`| Resumes the most recent session in the current directory `claude --resume`| Opens the session picker `claude --resume <name>`| Resumes the named session directly -`claude --from-pr <number>`| Resumes the session linked to that pull request +`claude --from-pr <number>`| Opens the session picker filtered to sessions linked to that pull request `/resume`| Switches to a different conversation from inside an active session Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. Run this from the directory the session was started in: session ID lookup is scoped to the current project directory and its git worktrees, so a session created elsewhere reports `No conversation found with session ID: <session-id>`. @@ -22,9 +22,25 @@ ​ +What a resumed session restores + +A resumed session restores the conversation along with the state saved in it: + + * Conversation history: the full history, including tool calls and results. + * Model: the session continues on the model it was using. The model isn’t restored when it has been retired or isn’t allowed by `availableModels`, when a `--model` flag or `ANTHROPIC_MODEL`-family environment variable picks one at launch, or on providers that use provider-specific deployment IDs, such as [Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry](</docs/en/third-party-integrations>); see [model configuration](</docs/en/model-config#setting-your-model>) for the resolution order. + * Permission mode: the mode the session was in. `plan` and `bypassPermissions` are never restored; [bypassing permissions](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) must be enabled again at launch, with one of its launch flags or `permissions.defaultMode: "bypassPermissions"` in [settings](</docs/en/settings#permission-settings>). `auto` is restored only when your account still meets the [auto mode requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Pass `--permission-mode` to override the restored mode. + * Active goal: a [goal](</docs/en/goal#resume-with-an-active-goal>) that was still active when the session ended carries over; its turn count, timer, and token-spend baseline reset. + * Scheduled tasks: [tasks that haven’t expired](</docs/en/scheduled-tasks#limitations>) are restored. Background Bash and monitor tasks aren’t. + +Not every configuration flag from the original launch is restored. If the session depended on `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, or directories added with `--add-dir`, pass them again when you resume; directories added mid-session with `/add-dir` aren’t restored either, though the session picker still uses them to locate the session. The standard settings files, such as `settings.json` and `settings.local.json`, are re-read at launch, so configuration that lives in them doesn’t need to be passed again. + +### + +​ + Where the session picker looks -Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: +Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Sessions whose first prompt was a [`/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>) command don’t appear in the picker; running `/loop` later in a conversation doesn’t hide the session. Before v2.1.211, a `/loop` run early in a conversation hid the session from the picker permanently. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: Command| Exact match| Ambiguous name ---|---|---
modified
--- a/sessions.md +++ b/sessions.md @@ -95,7 +95,7 @@ These commands control what’s in the context window without leaving the session: - * **`/clear`** : start fresh with an empty context. The previous conversation is saved and resumable + * **`/clear`** : start fresh with an empty context. The previous conversation is saved and resumable with `/resume`, or, in the same Claude Code process, from [the rewind menu’s previous-session entry](</docs/en/checkpointing#rewind-past-a-cleared-conversation>) * **`/compact [instructions]`** : replace history with a summary, optionally focused on what you specify * **`/context`** : show what is currently consuming context
modified
--- a/sessions.md +++ b/sessions.md @@ -81,7 +81,7 @@ /branch try-streaming-approach -From the command line, combine `--continue` or `--resume` with `--fork-session`: +If you omit the name, Claude Code names the new branch after the first prompt in the conversation. As of v2.1.198 this also applies after [compaction](</docs/en/how-claude-code-works#when-context-fills-up>); earlier versions fell back to the literal name `Branched conversation` instead of looking past the compaction summary to the original first prompt. From the command line, combine `--continue` or `--resume` with `--fork-session`: claude --continue --fork-session
modified
--- a/sessions.md +++ b/sessions.md @@ -24,7 +24,7 @@ Where the session picker looks -Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: +Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: Command| Exact match| Ambiguous name ---|---|--- @@ -46,7 +46,7 @@ From the session picker| Highlight a session and press `Ctrl+R` On plan accept| Accepting a plan in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) names the session from the plan content unless you’ve already set one -Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. +Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. ## @@ -107,7 +107,7 @@ Export and locate session data -Run `/export` to copy the current conversation to your clipboard or save it as a plain-text file, with messages and tool outputs rendered as readable text. Pass a filename to write directly to that file. +Run `/export` to open a menu that lets you copy the current conversation to your clipboard or save it as a plain-text file, with messages and tool outputs rendered as readable text. Pass a filename to skip the menu and write directly to that file. ###
modified
--- a/sessions.md +++ b/sessions.md @@ -1,10 +1,4 @@ -A session is a saved conversation tied to a project directory. Claude Code stores it locally as you work, so you can resume where you left off, branch to try a different approach, or switch between tasks. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), [Claude Code on the web](</docs/en/claude-code-on-the-web>), and the [VS Code extension](</docs/en/vs-code#resume-past-conversations>) each maintain their own session history. This page covers the CLI: - - * Resume a previous conversation by flag, name, or PR - * Name sessions so you can find them later - * Browse sessions with the `/resume` picker - * Branch a conversation to try a different approach - * Export transcripts and find them on disk +A session is a saved conversation tied to a project directory. Claude Code stores it locally as you work, so you can resume where you left off, branch to try a different approach, or switch between tasks. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), [Claude Code on the web](</docs/en/claude-code-on-the-web>), and the [VS Code extension](</docs/en/vs-code#resume-past-conversations>) each maintain their own session history. This page covers the CLI. ## @@ -113,7 +107,39 @@ Export and locate session data -Run `/export` to copy the current conversation to your clipboard or save it as a plain-text file, with messages and tool outputs rendered as readable text. Pass a filename to write directly to that file. Transcripts are stored as JSONL at `~/.claude/projects/<project>/<session-id>.jsonl`, where `<project>` is derived from your working directory path. Each line is a JSON object for a message, tool use, or metadata entry. To store sessions somewhere other than `~/.claude`, set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>). These local files are removed after 30 days by default; change this with [`cleanupPeriodDays`](</docs/en/settings#available-settings>). To suppress transcript writes entirely, set [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>), or in non-interactive mode use `--no-session-persistence`. +Run `/export` to copy the current conversation to your clipboard or save it as a plain-text file, with messages and tool outputs rendered as readable text. Pass a filename to write directly to that file. + +### + +​ + +Access conversations from scripts + +`/export` produces a rendered transcript for a person to read. The interfaces below produce structured data for a script to parse: a JSON result from a run, the path to a session’s transcript file, or a live stream of events. Pick by what triggers the script: + + * **Run Claude once and capture the result** : invoke `claude -p` with [`--output-format json` or `stream-json`](</docs/en/headless#get-structured-output>) to capture the result, session ID, usage, and cost of a non-interactive run as structured JSON. + * **Ask an existing session a question** : pass a session ID to [`claude -p --resume`](</docs/en/headless#continue-conversations>) to send a follow-up prompt, such as a summary request, and capture the structured response. + * **React to session events** : read the `transcript_path` field that [hooks](</docs/en/hooks#common-input-fields>) and [status line commands](</docs/en/statusline#available-data>) receive as input. A `SessionEnd` hook can archive the transcript when a session ends. + * **Embed Claude in a TypeScript or Python app** : use the [Agent SDK](</docs/en/agent-sdk/overview>) to receive each message programmatically. + +The example below uses the second interface. It sends a follow-up prompt to an existing session and reads the answer with `jq`: + + claude -p --resume <session-id> --output-format json "summarize what we changed" | jq -r '.result' + +### + +​ + +Where transcripts are stored + +By default, transcripts are stored as JSONL at `~/.claude/projects/<project>/<session-id>.jsonl`, where `<project>` is your working directory path with non-alphanumeric characters replaced by `-`. Each line is a JSON object for a message, tool use, or metadata entry. The entry format is internal to Claude Code and changes between versions, so scripts that parse these files directly can break on any release. To build on session data, use `/export` or the script interfaces instead. The location, retention, and write behavior are configurable: + +To| Set| Where +---|---|--- +Move storage off `~/.claude`| [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>)| Environment variable +Change the 30-day retention| [`cleanupPeriodDays`](</docs/en/settings#available-settings>)| `settings.json` +Suppress transcript writes in all modes| [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>)| Environment variable +Suppress writes for one non-interactive run| [`--no-session-persistence`](</docs/en/cli-reference>)| CLI flag with `claude -p` ##
modified
--- a/sessions.md +++ b/sessions.md @@ -22,7 +22,7 @@ `claude --from-pr <number>`| Resumes the session linked to that pull request `/resume`| Switches to a different conversation from inside an active session -Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. +Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. Run this from the directory the session was started in: session ID lookup is scoped to the current project directory and its git worktrees, so a session created elsewhere reports `No conversation found with session ID: <session-id>`. ###
modified
--- a/sessions.md +++ b/sessions.md @@ -30,7 +30,7 @@ Where the session picker looks -Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: +Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: Command| Exact match| Ambiguous name ---|---|---
modified
--- a/sessions.md +++ b/sessions.md @@ -1,9 +1,3 @@ -> ## Documentation Index -> -> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt> -> -> Use this file to discover all available pages before exploring further. - A session is a saved conversation tied to a project directory. Claude Code stores it locally as you work, so you can resume where you left off, branch to try a different approach, or switch between tasks. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), [Claude Code on the web](</docs/en/claude-code-on-the-web>), and the [VS Code extension](</docs/en/vs-code#resume-past-conversations>) each maintain their own session history. This page covers the CLI: * Resume a previous conversation by flag, name, or PR
modified
Show diff (359 lines)
--- a/sessions.md +++ b/sessions.md @@ -4,273 +4,132 @@ > > Use this file to discover all available pages before exploring further. -A session is the conversation history the SDK accumulates while your agent works. It contains your prompt, every tool call the agent made, every tool result, and every response. The SDK writes it to disk automatically so you can return to it later. Returning to a session means the agent has full context from before: files it already read, analysis it already performed, decisions it already made. You can ask a follow-up question, recover from an interruption, or branch off to try a different approach. +A session is a saved conversation tied to a project directory. Claude Code stores it locally as you work, so you can resume where you left off, branch to try a different approach, or switch between tasks. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), [Claude Code on the web](</docs/en/claude-code-on-the-web>), and the [VS Code extension](</docs/en/vs-code#resume-past-conversations>) each maintain their own session history. This page covers the CLI: -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>). - -This 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. + * Resume a previous conversation by flag, name, or PR + * Name sessions so you can find them later + * Browse sessions with the `/resume` picker + * Branch a conversation to try a different approach + * Export transcripts and find them on disk ## ​ -Choose an approach +Resume a session -How 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>) (they don’t end the call). +Sessions are saved continuously to local transcript files as you work, so you can return to one after exiting or running `/clear`. Use these entry points: -What you’re building| What to use +Command| What it does ---|--- -One-shot task: single prompt, no follow-up| Nothing extra. One `query()` call handles it. -Multi-turn chat in one process| `ClaudeSDKClient` (Python) or `continue: true` (TypeScript). The SDK tracks the session for you with no ID handling. -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. -Resume a specific past session (not the most recent)| Capture the session ID and pass it to `resume`. -Try an alternative approach without losing the original| Fork the session. -Stateless task, don’t want anything written to disk (TypeScript only)| Set [`persistSession: false`](</docs/en/agent-sdk/typescript#options>). The session exists only in memory for the duration of the call. Python always persists to disk. +`claude --continue`| Resumes the most recent session in the current directory +`claude --resume`| Opens the session picker +`claude --resume <name>`| Resumes the named session directly +`claude --from-pr <number>`| Resumes the session linked to that pull request +`/resume`| Switches to a different conversation from inside an active session + +Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. ### ​ -Continue, resume, and fork +Where the session picker looks -Continue, 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). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session: +Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: - * **Continue** finds the most recent session in the current directory. You don’t track anything. Works well when your app runs one conversation at a time. - * **Resume** takes a specific session ID. You track the ID. Required when you have multiple sessions (for example, one per user in a multi-user app) or want to return to one that isn’t the most recent. - -**Fork** is different: it creates a new session that starts with a copy of the original’s history. The original stays unchanged. Use fork to try a different direction while keeping the option to go back. +Command| Exact match| Ambiguous name +---|---|--- +`claude --resume <name>`| Resumes directly| Opens the session picker with the name pre-filled as a search term +`/resume <name>`| Resumes directly| Reports an error; run `/resume` with no argument to open the session picker ## ​ -Automatic session management +Name your sessions -Both SDKs offer an interface that tracks session state for you across calls, so you don’t pass IDs around manually. Use these for multi-turn conversations within a single process. +Give sessions descriptive names so they’re findable in the session picker and resumable by name. This matters most when you’re working on several tasks in parallel. -### +When| How to set the name +---|--- +At startup| `claude -n auth-refactor` +During a session| `/rename auth-refactor`. The name also appears on the prompt bar +From the session picker| Highlight a session and press `Ctrl+R` +On plan accept| Accepting a plan in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) names the session from the plan content unless you’ve already set one -​ - -Python: `ClaudeSDKClient` - -[`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. The client is typically used as an async context manager. This 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: - -Python - - import asyncio - from claude_agent_sdk import ( - ClaudeSDKClient, - ClaudeAgentOptions, - AssistantMessage, - ResultMessage, - TextBlock, - ) - - def print_response(message): - """Print only the human-readable parts of a message.""" - if isinstance(message, AssistantMessage): - for block in message.content: - if isinstance(block, TextBlock): - print(block.text) - elif isinstance(message, ResultMessage): - cost = ( - f"${message.total_cost_usd:.4f}" - if message.total_cost_usd is not None - else "N/A" - ) - print(f"[done: {message.subtype}, cost: {cost}]") - - async def main(): - options = ClaudeAgentOptions( - allowed_tools=["Read", "Edit", "Glob", "Grep"], - ) - - async with ClaudeSDKClient(options=options) as client: - # First query: client captures the session ID internally - await client.query("Analyze the auth module") - async for message in client.receive_response(): - print_response(message) - - # Second query: automatically continues the same session - await client.query("Now refactor it to use JWT") - async for message in client.receive_response(): - print_response(message) - - asyncio.run(main()) - -See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claudesdkclient>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function. - -### - -​ - -TypeScript: `continue: true` - -The TypeScript SDK doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call: - -TypeScript - - import { query } from "@anthropic-ai/claude-agent-sdk"; - - // First query: creates a new session - for await (const message of query({ - prompt: "Analyze the auth module", - options: { allowedTools: ["Read", "Glob", "Grep"] } - })) { - if (message.type === "result" && message.subtype === "success") { - console.log(message.result); - } - } - - // Second query: continue: true resumes the most recent session - for await (const message of query({ - prompt: "Now refactor it to use JWT", - options: { - continue: true, - allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"] - } - })) { - if (message.type === "result" && message.subtype === "success") { - console.log(message.result); - } - } - -The experimental [V2 session API](</docs/en/agent-sdk/typescript-v2-preview>), 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. +Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. ## ​ -Use session options with `query()` +Use the session picker -### +Run `/resume` inside a session, or `claude --resume` with no arguments, to open the interactive session picker. Use these keyboard shortcuts to navigate, search, and widen the list: -​ +Shortcut| Action +---|--- +`↑` / `↓`| Navigate between sessions +`→` / `←`| Expand or collapse grouped sessions +`Enter`| Resume the highlighted session +`Space`| Preview the session content. `Ctrl+V` also works on terminals that don’t capture it as paste +`Ctrl+R`| Rename the highlighted session +`/` or any printable character other than `Space`| Enter search mode and filter sessions. Paste a GitHub, GitHub Enterprise, GitLab, or Bitbucket pull or merge request URL to find the session that created it +`Ctrl+A`| Show sessions from all projects on this machine. Press again to return to the current repository +`Ctrl+W`| Show sessions from all worktrees of the current repository. Press again to return to the current worktree. Only shown in multi-worktree repositories +`Ctrl+B`| Filter to sessions from the current git branch. Press again to show all branches +`Esc`| Exit the session picker or search mode -Capture the session ID - -Resume 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`. - -Python - -TypeScript - - import asyncio - from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage - - async def main(): - session_id = None - - async for message in query( - prompt="Analyze the auth module and suggest improvements", - options=ClaudeAgentOptions( - allowed_tools=["Read", "Glob", "Grep"], - ), - ): - if isinstance(message, ResultMessage): - session_id = message.session_id - if message.subtype == "success": - print(message.result) - - print(f"Session ID: {session_id}") - return session_id - - session_id = asyncio.run(main()) - -### - -​ - -Resume by ID - -Pass 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: - - * **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files. - * **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#handle-the-result>)); resume with a higher limit. - * **Restart your process.** You captured the ID before shutdown and want to restore the conversation. - -This example resumes the session from Capture the session ID with a follow-up prompt. Because you’re resuming, the agent already has the prior analysis in context: - -Python - -TypeScript - - # Earlier session analyzed the code; now build on that analysis - async for message in query( - prompt="Now implement the refactoring you suggested", - options=ClaudeAgentOptions( - resume=session_id, - allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"], - ), - ): - if isinstance(message, ResultMessage) and message.subtype == "success": - print(message.result) - -If a `resume` call returns a fresh session instead of the expected history, the most common cause is a mismatched `cwd`. Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, where `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-` (so `/Users/me/proj` becomes `-Users-me-proj`). If your resume call runs from a different directory, the SDK looks in the wrong place. The session file also needs to exist on the current machine. - -To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). - -### - -​ - -Fork to explore alternatives - -Forking creates a new session that starts with a copy of the original’s history but diverges from that point. The fork gets its own session ID; the original’s ID and history stay unchanged. You end up with two independent sessions you can resume separately. - -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>). - -This example builds on 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: - -Python - -TypeScript - - # Fork: branch from session_id into a new session - forked_id = None - async for message in query( - prompt="Instead of JWT, implement OAuth2 for the auth module", - options=ClaudeAgentOptions( - resume=session_id, - fork_session=True, - ), - ): - if isinstance(message, ResultMessage): - forked_id = message.session_id # The fork's ID, distinct from session_id - if message.subtype == "success": - print(message.result) - - print(f"Forked session: {forked_id}") - - # Original session is untouched; resuming it continues the JWT thread - async for message in query( - prompt="Continue with the JWT approach", - options=ClaudeAgentOptions(resume=session_id), - ): - if isinstance(message, ResultMessage) and message.subtype == "success": - print(message.result) +Each row shows the session name if set, otherwise the conversation summary or first prompt, along with time since last activity, message count, and git branch. Project path appears after you widen to all projects with `Ctrl+A`. Forked sessions created with `/branch`, `/rewind`, or `--fork-session` are grouped under their root session. Press `→` to expand a group. ## ​ -Resume across hosts +Branch a session -Session files are local to the machine that created them. To resume a session on a different host (CI workers, ephemeral containers, serverless), you have two options: +Branching creates a copy of the conversation so far and switches you into it, leaving the original intact. Use it to try a different approach without losing the path you were on. From inside a session, run `/branch` with an optional name: - * **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it to the same path on the new host before calling `resume`. The `cwd` must match. - * **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. + /branch try-streaming-approach -Both 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. Both 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. +From the command line, combine `--continue` or `--resume` with `--fork-session`: + + claude --continue --fork-session + +The original session is unchanged and remains available in the session picker. The `/branch` confirmation prints two session IDs: the new branch you are now in and the original. To return to the original, pass its ID to `/resume`, use the session picker, or run `/resume <original-name>`. Permissions you approved with “allow for this session” do not carry over to the new branch. If you resume the same session in two terminals without forking, messages from both interleave into one transcript. For checkpoint-based rewind within a single session, see [Checkpointing](</docs/en/checkpointing>). ## ​ -Related resources +Manage context within a session - * [How the agent loop works](</docs/en/agent-sdk/agent-loop>): Understand turns, messages, and context accumulation within a session - * [File checkpointing](</docs/en/agent-sdk/file-checkpointing>): Track and revert file changes across sessions - * [Python `ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>): Full session option reference for Python - * [TypeScript `Options`](</docs/en/agent-sdk/typescript#options>): Full session option reference for TypeScript +These commands control what’s in the context window without leaving the session: + + * **`/clear`** : start fresh with an empty context. The previous conversation is saved and resumable + * **`/compact [instructions]`** : replace history with a summary, optionally focused on what you specify + * **`/context`** : show what is currently consuming context + +For how compaction interacts with CLAUDE.md, skills, and rules, see the [context window guide](</docs/en/context-window>). For strategies on when to clear versus compact, see [Best practices](</docs/en/best-practices#manage-your-session>). + +## + +​ + +Export and locate session data + +Run `/export` to copy the current conversation to your clipboard or save it as a plain-text file, with messages and tool outputs rendered as readable text. Pass a filename to write directly to that file. Transcripts are stored as JSONL at `~/.claude/projects/<project>/<session-id>.jsonl`, where `<project>` is derived from your working directory path. Each line is a JSON object for a message, tool use, or metadata entry. To store sessions somewhere other than `~/.claude`, set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>). These local files are removed after 30 days by default; change this with [`cleanupPeriodDays`](</docs/en/settings#available-settings>). To suppress transcript writes entirely, set [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>), or in non-interactive mode use `--no-session-persistence`. + +## + +​ + +See also + +These pages cover related session and parallelism mechanics: + + * [Worktrees](</docs/en/worktrees>): run isolated parallel sessions on separate branches + * [Checkpointing](</docs/en/checkpointing>): rewind code and conversation to an earlier point + * [Context window](</docs/en/context-window>): what fills context and what survives compaction + * [Non-interactive mode](</docs/en/headless>): session behavior under `claude -p`
modified
--- a/sessions.md +++ b/sessions.md @@ -54,7 +54,7 @@ Python: `ClaudeSDKClient` -[`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. The client must be used as an async context manager. This 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: +[`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. The client is typically used as an async context manager. This 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: Python @@ -107,7 +107,7 @@ TypeScript: `continue: true` -The stable TypeScript SDK (the `query()` function used throughout these docs, sometimes called V1) doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call: +The TypeScript SDK doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call: TypeScript @@ -136,7 +136,7 @@ } } -The experimental [V2 session API](</docs/en/agent-sdk/typescript-v2-preview>), which provided `createSession()` with a `send` / `stream` pattern, is deprecated. Use the V1 `query()` function and the session options described on this page instead. +The experimental [V2 session API](</docs/en/agent-sdk/typescript-v2-preview>), 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. ##
modified
--- a/sessions.md +++ b/sessions.md @@ -136,7 +136,7 @@ } } -There’s also a [V2 preview](</docs/en/agent-sdk/typescript-v2-preview>) of the TypeScript SDK that provides `createSession()` with a `send` / `stream` pattern, closer to Python’s `ClaudeSDKClient` in feel. V2 is unstable and its APIs may change; the rest of this documentation uses the stable V1 `query()` function. +The experimental [V2 session API](</docs/en/agent-sdk/typescript-v2-preview>), which provided `createSession()` with a `send` / `stream` pattern, is deprecated. Use the V1 `query()` function and the session options described on this page instead. ##
modified
--- a/sessions.md +++ b/sessions.md @@ -33,7 +33,7 @@ Continue, resume, and fork -Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claude-agent-options>) in Python, [`Options`](</docs/en/agent-sdk/typescript#options>) in TypeScript). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session: +Continue, 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). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session: * **Continue** finds the most recent session in the current directory. You don’t track anything. Works well when your app runs one conversation at a time. * **Resume** takes a specific session ID. You track the ID. Required when you have multiple sessions (for example, one per user in a multi-user app) or want to return to one that isn’t the most recent. @@ -54,7 +54,7 @@ Python: `ClaudeSDKClient` -[`ClaudeSDKClient`](</docs/en/agent-sdk/python#claude-sdk-client>) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](</docs/en/agent-sdk/python#claude-sdk-client>) to iterate over the messages for the current query. The client must be used as an async context manager. This 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: +[`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. The client must be used as an async context manager. This 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: Python @@ -99,7 +99,7 @@ asyncio.run(main()) -See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claude-sdk-client>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function. +See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claudesdkclient>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function. ### @@ -150,7 +150,7 @@ Capture the session ID -Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](</docs/en/agent-sdk/python#result-message>) in Python, [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdk-result-message>) 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`. +Resume 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`. Python @@ -262,7 +262,7 @@ * **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it to the same path on the new host before calling `resume`. The `cwd` must match. * **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. -Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](</docs/en/agent-sdk/typescript#list-sessions>) and [`getSessionMessages()`](</docs/en/agent-sdk/typescript#get-session-messages>) 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. Both 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#get-session-info>), [`renameSession()`](</docs/en/agent-sdk/typescript#rename-session>), and [`tagSession()`](</docs/en/agent-sdk/typescript#tag-session>) in TypeScript. Use them to organize sessions by tag or give them human-readable titles. +Both 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. Both 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. ## @@ -272,5 +272,5 @@ * [How the agent loop works](</docs/en/agent-sdk/agent-loop>): Understand turns, messages, and context accumulation within a session * [File checkpointing](</docs/en/agent-sdk/file-checkpointing>): Track and revert file changes across sessions - * [Python `ClaudeAgentOptions`](</docs/en/agent-sdk/python#claude-agent-options>): Full session option reference for Python + * [Python `ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>): Full session option reference for Python * [TypeScript `Options`](</docs/en/agent-sdk/typescript#options>): Full session option reference for TypeScript
modified
--- a/sessions.md +++ b/sessions.md @@ -1,3 +1,9 @@ +> ## Documentation Index +> +> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt> +> +> Use this file to discover all available pages before exploring further. + A session is the conversation history the SDK accumulates while your agent works. It contains your prompt, every tool call the agent made, every tool result, and every response. The SDK writes it to disk automatically so you can return to it later. Returning to a session means the agent has full context from before: files it already read, analysis it already performed, decisions it already made. You can ask a follow-up question, recover from an interruption, or branch off to try a different approach. 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>).
modified
--- a/sessions.md +++ b/sessions.md @@ -203,6 +203,8 @@ If a `resume` call returns a fresh session instead of the expected history, the most common cause is a mismatched `cwd`. Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, where `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-` (so `/Users/me/proj` becomes `-Users-me-proj`). If your resume call runs from a different directory, the SDK looks in the wrong place. The session file also needs to exist on the current machine. +To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). + ### ​
added
Show diff (271 lines)
--- a/sessions.md +++ b/sessions.md @@ -0,0 +1,268 @@ +A session is the conversation history the SDK accumulates while your agent works. It contains your prompt, every tool call the agent made, every tool result, and every response. The SDK writes it to disk automatically so you can return to it later. Returning to a session means the agent has full context from before: files it already read, analysis it already performed, decisions it already made. You can ask a follow-up question, recover from an interruption, or branch off to try a different approach. + +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>). + +This 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. + +## + +​ + +Choose an approach + +How 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>) (they don’t end the call). + +What you’re building| What to use +---|--- +One-shot task: single prompt, no follow-up| Nothing extra. One `query()` call handles it. +Multi-turn chat in one process| `ClaudeSDKClient` (Python) or `continue: true` (TypeScript). The SDK tracks the session for you with no ID handling. +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. +Resume a specific past session (not the most recent)| Capture the session ID and pass it to `resume`. +Try an alternative approach without losing the original| Fork the session. +Stateless task, don’t want anything written to disk (TypeScript only)| Set [`persistSession: false`](</docs/en/agent-sdk/typescript#options>). The session exists only in memory for the duration of the call. Python always persists to disk. + +### + +​ + +Continue, resume, and fork + +Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claude-agent-options>) in Python, [`Options`](</docs/en/agent-sdk/typescript#options>) in TypeScript). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session: + + * **Continue** finds the most recent session in the current directory. You don’t track anything. Works well when your app runs one conversation at a time. + * **Resume** takes a specific session ID. You track the ID. Required when you have multiple sessions (for example, one per user in a multi-user app) or want to return to one that isn’t the most recent. + +**Fork** is different: it creates a new session that starts with a copy of the original’s history. The original stays unchanged. Use fork to try a different direction while keeping the option to go back. + +## + +​ + +Automatic session management + +Both SDKs offer an interface that tracks session state for you across calls, so you don’t pass IDs around manually. Use these for multi-turn conversations within a single process. + +### + +​ + +Python: `ClaudeSDKClient` + +[`ClaudeSDKClient`](</docs/en/agent-sdk/python#claude-sdk-client>) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](</docs/en/agent-sdk/python#claude-sdk-client>) to iterate over the messages for the current query. The client must be used as an async context manager. This 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: + +Python + + import asyncio + from claude_agent_sdk import ( + ClaudeSDKClient, + ClaudeAgentOptions, + AssistantMessage, + ResultMessage, + TextBlock, + ) + + def print_response(message): + """Print only the human-readable parts of a message.""" + if isinstance(message, AssistantMessage): + for block in message.content: + if isinstance(block, TextBlock): + print(block.text) + elif isinstance(message, ResultMessage): + cost = ( + f"${message.total_cost_usd:.4f}" + if message.total_cost_usd is not None + else "N/A" + ) + print(f"[done: {message.subtype}, cost: {cost}]") + + async def main(): + options = ClaudeAgentOptions( + allowed_tools=["Read", "Edit", "Glob", "Grep"], + ) + + async with ClaudeSDKClient(options=options) as client: + # First query: client captures the session ID internally + await client.query("Analyze the auth module") + async for message in client.receive_response(): + print_response(message) + + # Second query: automatically continues the same session + await client.query("Now refactor it to use JWT") + async for message in client.receive_response(): + print_response(message) + + asyncio.run(main()) + +See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claude-sdk-client>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function. + +### + +​ + +TypeScript: `continue: true` + +The stable TypeScript SDK (the `query()` function used throughout these docs, sometimes called V1) doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call: + +TypeScript + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + // First query: creates a new session + for await (const message of query({ + prompt: "Analyze the auth module", + options: { allowedTools: ["Read", "Glob", "Grep"] } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + + // Second query: continue: true resumes the most recent session + for await (const message of query({ + prompt: "Now refactor it to use JWT", + options: { + continue: true, + allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"] + } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + +There’s also a [V2 preview](</docs/en/agent-sdk/typescript-v2-preview>) of the TypeScript SDK that provides `createSession()` with a `send` / `stream` pattern, closer to Python’s `ClaudeSDKClient` in feel. V2 is unstable and its APIs may change; the rest of this documentation uses the stable V1 `query()` function. + +## + +​ + +Use session options with `query()` + +### + +​ + +Capture the session ID + +Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](</docs/en/agent-sdk/python#result-message>) in Python, [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdk-result-message>) 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`. + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + async def main(): + session_id = None + + async for message in query( + prompt="Analyze the auth module and suggest improvements", + options=ClaudeAgentOptions( + allowed_tools=["Read", "Glob", "Grep"], + ), + ): + if isinstance(message, ResultMessage): + session_id = message.session_id + if message.subtype == "success": + print(message.result) + + print(f"Session ID: {session_id}") + return session_id + + session_id = asyncio.run(main()) + +### + +​ + +Resume by ID + +Pass 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: + + * **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files. + * **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#handle-the-result>)); resume with a higher limit. + * **Restart your process.** You captured the ID before shutdown and want to restore the conversation. + +This example resumes the session from Capture the session ID with a follow-up prompt. Because you’re resuming, the agent already has the prior analysis in context: + +Python + +TypeScript + + # Earlier session analyzed the code; now build on that analysis + async for message in query( + prompt="Now implement the refactoring you suggested", + options=ClaudeAgentOptions( + resume=session_id, + allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"], + ), + ): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + +If a `resume` call returns a fresh session instead of the expected history, the most common cause is a mismatched `cwd`. Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, where `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-` (so `/Users/me/proj` becomes `-Users-me-proj`). If your resume call runs from a different directory, the SDK looks in the wrong place. The session file also needs to exist on the current machine. + +### + +​ + +Fork to explore alternatives + +Forking creates a new session that starts with a copy of the original’s history but diverges from that point. The fork gets its own session ID; the original’s ID and history stay unchanged. You end up with two independent sessions you can resume separately. + +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>). + +This example builds on 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: + +Python + +TypeScript + + # Fork: branch from session_id into a new session + forked_id = None + async for message in query( + prompt="Instead of JWT, implement OAuth2 for the auth module", + options=ClaudeAgentOptions( + resume=session_id, + fork_session=True, + ), + ): + if isinstance(message, ResultMessage): + forked_id = message.session_id # The fork's ID, distinct from session_id + if message.subtype == "success": + print(message.result) + + print(f"Forked session: {forked_id}") + + # Original session is untouched; resuming it continues the JWT thread + async for message in query( + prompt="Continue with the JWT approach", + options=ClaudeAgentOptions(resume=session_id), + ): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + +## + +​ + +Resume across hosts + +Session files are local to the machine that created them. To resume a session on a different host (CI workers, ephemeral containers, serverless), you have two options: + + * **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it to the same path on the new host before calling `resume`. The `cwd` must match. + * **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. + +Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](</docs/en/agent-sdk/typescript#list-sessions>) and [`getSessionMessages()`](</docs/en/agent-sdk/typescript#get-session-messages>) 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. Both 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#get-session-info>), [`renameSession()`](</docs/en/agent-sdk/typescript#rename-session>), and [`tagSession()`](</docs/en/agent-sdk/typescript#tag-session>) in TypeScript. Use them to organize sessions by tag or give them human-readable titles. + +## + +​ + +Related resources + + * [How the agent loop works](</docs/en/agent-sdk/agent-loop>): Understand turns, messages, and context accumulation within a session + * [File checkpointing](</docs/en/agent-sdk/file-checkpointing>): Track and revert file changes across sessions + * [Python `ClaudeAgentOptions`](</docs/en/agent-sdk/python#claude-agent-options>): Full session option reference for Python + * [TypeScript `Options`](</docs/en/agent-sdk/typescript#options>): Full session option reference for TypeScript