Work with sessions
기준일: 2026-07-26
공식 기준: Work with sessions
Work with sessions 문서는 Claude Code 공식 문서(agent-sdk/sessions)를 한국어로 정리한 가이드입니다. How sessions persist agent conversation history, and when to use continue, resume, and fork to return to a prior run. 명령·설정 키·코드 예시는 공식 문서를 그대로 보존하며, 해석과 절차 안내는 한국어로 제공합니다. 최종 동작은 설치 버전과 공식 원문을 확인하세요.
핵심 요약
How sessions persist agent conversation history, and when to use continue, resume, and fork to return to a prior run.
한국어 가이드 범위: agent-sdk/sessions 경로의 설정·명령·제약·예시를 학습용으로 재구성합니다.
문서 구성
공식 문서의 주요 섹션은 다음과 같습니다.
- Work with sessions
- Choose an approach
- Continue, resume, and fork
- Automatic session management
- Python: ClaudeSDKClient
- TypeScript: continue: true
- Use session options with query()
- Capture the session ID
- Resume by ID
- Fork to explore alternatives
- Resume across hosts
- Related resources
상세 내용
Work with sessions
How sessions persist agent conversation history, and when to use continue, resume, and fork to return to a prior run.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
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 (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. 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 in Python, Options in TypeScript).
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
주요 항목:
- 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 (예를 들어, one per user in a multi-user app) or want to return to one that isn't the most recent.
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 handles session IDs internally. Each call to client.query() automatically continues the same session. Call client.receive_response() 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.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
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.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Use session options with query()
이 섹션의 세부 항목은 공식 문서 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 in Python, 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.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
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_turnsorerror_max_budget_usd(see Handle the result); resume with a higher limit. In a single-shotquery()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.
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.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
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>.jsonlfrom the first run and restore it to the same path on the new host before callingresume. Thecwdmust 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.
Related resources
주요 항목:
- How the agent loop works: Understand turns, messages, and context accumulation within a session
- File checkpointing: Snapshot and revert file changes the agent made within a session
- Python
ClaudeAgentOptions: Full session option reference for Python - TypeScript
Options: Full session option reference for TypeScript
실습 체크리스트
- 공식 문서와 로컬/SDK 버전을 대조합니다.
- 관련 CLI·SDK 옵션은 공식 페이지와
--help로 교차 확인합니다. - Agent SDK 예시는 TypeScript/Python 패키지 최신 API를 우선합니다.
- 권한·호스팅·보안 설정 변경 후 통합 테스트를 실행합니다.
자주 쓰는 명령·설정 예시
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:
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
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`.
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](#capture-the-session-id) with a follow-up prompt. Because you're resuming, the agent already has the prior analysis in context:
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.
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`, or under `$CLAUDE_CONFIG_DIR/projects/<encoded-cwd>/*.jsonl` if you set the `CLAUDE_CONFIG_DIR` environment variable, 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](#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:
관련 링크
- 공식 원문: agent-sdk/sessions
- 문서 홈
이 가이드는 공식 문서를 한국어 학습용으로 재구성한 것입니다. 옵션 기본값·API 이름은 설치 버전에 따라 달라질 수 있습니다.