modified
--- a/hosting.md +++ b/hosting.md @@ -219,6 +219,7 @@ * Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](</docs/en/memory#auto-memory>) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for the other inputs that load unconditionally. * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. When each config directory serves one working directory and you don’t pass a [`SessionStore`](</docs/en/agent-sdk/session-storage>), you can also set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) in `env` to keep the transcript paths under it short. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later. * Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call. + * If you pass a `SessionStore`, give each tenant its own storage location, such as a separate key prefix in your adapter. * Apply per-tenant egress rules at your proxy, such as distinct outbound IPs, credentials, or domain allowlists, so a compromised tenant cannot exfiltrate data via another tenant’s outbound policy. The example below applies the settings, auto memory, config directory, and working directory options together. Construct `tenantDir` and `configDir` so each tenant gets a path no other tenant can read. In TypeScript, `env` replaces the subprocess environment, so spread `...process.env` to keep inherited variables like `PATH` and `ANTHROPIC_API_KEY`. In Python, `env` is merged on top of the inherited environment.
modified
--- a/hosting.md +++ b/hosting.md @@ -2,7 +2,7 @@ ## The subprocess model -Every hosting decision on this page follows from how the SDK runs the agent. When your code calls `query()`, the SDK spawns a separate `claude` CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk. One agent session maps to one subprocess. Running N concurrent sessions means N subprocesses, each with its own process tree and transcript file. By default they all inherit your application’s working directory. When sessions need separate filesystems, pass a distinct `cwd` in the options of each session’s `query()` call: +Every hosting decision on this page follows from how the SDK runs the agent. When your code calls `query()`, the SDK spawns a separate `claude` CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk. One agent session maps to one subprocess. Running N concurrent sessions takes N subprocesses, each with its own process tree and transcript file. By default they all inherit your application’s working directory. When sessions need separate working directories, pass a distinct `cwd` in the options of each session’s `query()` call: TypeScript
modified
Show diff (258 lines)
--- a/hosting.md +++ b/hosting.md @@ -1,10 +1,6 @@ The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you don’t need to run the agent loop itself on your own infrastructure, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead. Anthropic hosts the agent loop, and your application sends events and receives streamed results through the client SDKs or the REST API. Tool execution runs in an Anthropic-managed cloud sandbox or a [self-hosted sandbox](<https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes>) on your own infrastructure. -## - -​ - -The subprocess model +## The subprocess model Every hosting decision on this page follows from how the SDK runs the agent. When your code calls `query()`, the SDK spawns a separate `claude` CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk. One agent session maps to one subprocess. Running N concurrent sessions means N subprocesses, each with its own process tree and transcript file. By default they all inherit your application’s working directory. When sessions need separate filesystems, pass a distinct `cwd` in the options of each session’s `query()` call: @@ -36,11 +32,7 @@ The TypeScript examples on this page use top-level `await`, so save them as `.mts` files or set `"type": "module"` in `package.json`. -### - -​ - -State that lives on local disk +### State that lives on local disk Three kinds of agent state live on the container’s filesystem by default. None of them survive a container restart, a scale-down, or a move to a different node. @@ -52,19 +44,11 @@ To persist transcripts across hosts, configure a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). Memory files and other working-directory artifacts need their own storage strategy, such as a mounted volume or an object-store sync. For how sessions, resumption, and forking work at the API level, see [Sessions](</docs/en/agent-sdk/sessions>). -## - -​ - -Choose a session pattern +## Choose a session pattern These four patterns cover session lifecycle: how long a container lives relative to the sessions it serves. For where the container runs, the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb>) has [deployable code](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>) for local Docker, Modal, and Kubernetes. Choose a session pattern here and a deployment target from the cookbook. -### - -​ - -Ephemeral sessions +### Ephemeral sessions Create a container for each user task and destroy it when the task completes. Best for one-off tasks. The user may still interact with the AI while the task is completing, but once completed the container is destroyed. Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation. The container runs a one-shot entrypoint that reads the task from the `TASK_PROMPT` environment variable, calls the SDK, and exits. @@ -95,11 +79,7 @@ The script prints each message as it arrives, including a result message whose `subtype` is `success` when the task completes within the turn limit. If the task hits the 20-turn limit instead, the result message’s `subtype` is `error_max_turns` and the `query()` call raises an error after yielding it, so wrap the loop in a try block if the container needs to exit cleanly. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error subtypes. -### - -​ - -Long-running sessions +### Long-running sessions Run persistent container instances, often hosting multiple SDK processes per container, to serve ongoing work. Best for agents that take autonomous action, serve content, or handle high-volume message streams. Example workloads include an email agent that triages and responds to incoming mail, a site builder that hosts a per-user editable site through container ports, and a chat bot that handles continuous traffic from a platform like Slack. The container exposes an HTTP or WebSocket endpoint and maps each active session to a long-lived query and the subprocess behind it. The calls that keep sessions open and warm differ between the SDKs: @@ -108,11 +88,7 @@ Size the container so it can hold the maximum number of concurrent sessions in memory. -### - -​ - -Hybrid sessions +### Hybrid sessions Ephemeral containers that hydrate from a [`SessionStore`](</docs/en/agent-sdk/session-storage>) on startup and persist updates back. Best for sessions that span many interactions but sit idle between them. The container spins down during idle periods and spins back up when the user returns. Example workloads include a personal project manager with intermittent check-ins, deep research that pauses and resumes over hours, and a customer support agent that loads ticket history across interactions. Tune your provider’s idle timeout to how frequently you expect users to return. Shutting a container down without a `SessionStore` configured loses the transcript with it, so the store is required for this pattern, not optional. The pattern hinges on resuming a session by ID with a shared store attached: @@ -152,25 +128,13 @@ asyncio.run(main()) -### - -​ - -Multi-agent container +### Multi-agent container Run multiple SDK subprocesses inside one container. Best for agents that must collaborate closely, for example multi-agent simulations where the agents interact with each other in a shared environment. Give each agent its own working directory so they do not overwrite each other’s files, and isolate settings loading so per-agent `CLAUDE.md` files do not leak across agents. See Multi-tenant isolation for the specific options. -## - -​ - -Provision the container - -### - -​ - -Container-based sandboxing +## Provision the container + +### Container-based sandboxing Run the SDK inside a sandboxed container for process isolation, resource limits, network control, and an ephemeral filesystem. Questions to answer when choosing a provider: @@ -182,11 +146,7 @@ For self-hosted options such as Docker, gVisor, and Firecracker, and detailed isolation configuration, see [Isolation Technologies](</docs/en/agent-sdk/secure-deployment#isolation-technologies>). -### - -​ - -Runtime dependencies +### Runtime dependencies The container needs your SDK’s language runtime: @@ -195,35 +155,19 @@ The bundled binary is pinned to the SDK package version, so updating the SDK is how you update the CLI. The SDK follows semver: take patch releases continuously and review the [TypeScript](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md>) or [Python](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md>) changelog before taking a minor. -### - -​ - -Resources +### Resources 1 GiB RAM, 5 GiB disk, and 1 CPU per agent is a reasonable starting point for a freshly started instance. Memory usage grows with session length and tool activity, so size for the session lengths and concurrency you actually need rather than the idle baseline. See Scaling and concurrency for how to work out agents per host. -### - -​ - -Network +### Network The SDK needs outbound HTTPS to `api.anthropic.com`, or to your provider’s regional endpoint when running on Amazon Bedrock or Google Cloud’s Agent Platform. If your agents use [MCP servers](</docs/en/agent-sdk/mcp>) or external tools, they need outbound access to those endpoints as well. For production, route outbound traffic through an egress proxy that enforces domain allowlists, injects credentials, and logs requests. See [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) for the full pattern. For inbound traffic, expose an HTTP or WebSocket port on the container. Your application handles client requests on that port and calls the SDK internally; the subprocess itself does not listen on the network. -## - -​ - -Handle production concerns +## Handle production concerns Work through these decisions before shipping a self-hosted agent. -### - -​ - -Session and state persistence +### Session and state persistence Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). See [Reference implementations](</docs/en/agent-sdk/session-storage#reference-implementations>) for example adapters for an object store, a key-value store, and a database, and a conformance suite for your own. Three things to know about how `SessionStore` behaves: @@ -231,11 +175,7 @@ * **Mirror, not replacement** : the subprocess writes to local disk first, and the SDK forwards a copy of each batch to the store. A fresh session’s local transcript outlives the run; a run resumed from the store deletes its local copy at the end, so the store holds the only durable copy. See [Dual-write architecture](</docs/en/agent-sdk/session-storage#dual-write-architecture>). * **`mirror_error` messages**: when the SDK can’t deliver a batch to the store, it drops the batch, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. See [Mirror writes are best-effort](</docs/en/agent-sdk/session-storage#mirror-writes-are-best-effort>) for the retry and timeout behavior. -### - -​ - -Observability +### Observability Agent SDK agents are long-lived processes that spawn tool calls across many API round-trips. Without telemetry you cannot see which tools ran, how long they took, or where a session stalled. The SDK inherits OpenTelemetry configuration from the environment. Set the OTEL environment variables at the container or orchestrator level so every `query()` call exports spans, metrics, and log events to your collector. The example below enables OTLP export for all three signals. `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` is required only for traces; omit it if you export metrics and logs alone. @@ -251,11 +191,7 @@ Prompt text and tool inputs are not included in exports by default. See [Control sensitive data in exports](</docs/en/agent-sdk/observability#control-sensitive-data-in-exports>) for the opt-in flags, and [Observability](</docs/en/agent-sdk/observability>) for the full signal catalog. -### - -​ - -Auth and secrets +### Auth and secrets Three auth concerns matter at hosting time: @@ -263,11 +199,7 @@ * **Inbound** : put authentication at a gateway in front of the agent container. The agent should receive pre-authenticated requests and should not be the component that validates user tokens. * **Outbound tools** : keep tool credentials out of the agent environment. Route outbound calls through a proxy that injects API keys after the request leaves the container. The agent makes the call; the proxy adds the credential. -### - -​ - -Scaling and concurrency +### Scaling and concurrency Each session runs in its own subprocess, so concurrency on a host is bounded by how many subprocesses its RAM can hold. Size each host with this formula: @@ -275,19 +207,11 @@ Measure the per-session ceiling by running a representative session to your target length under your expected tool load and recording peak RSS. The 1 GiB starting point in Resources is a floor, not the ceiling. Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts. -### - -​ - -Cost +### Cost Anthropic token cost typically dominates container infrastructure cost by an order of magnitude or more. A minimally provisioned container runs roughly $0.05 per hour, while a single long agent session can spend dollars in tokens. See [Cost tracking](</docs/en/agent-sdk/cost-tracking>) for per-session token accounting. -### - -​ - -Multi-tenant isolation +### Multi-tenant isolation Default SDK behavior reads settings and `CLAUDE.md` memory files from the filesystem. In a shared container that serves multiple tenants, those files can leak one tenant’s context into another tenant’s session. To isolate tenants inside a shared container: @@ -347,11 +271,7 @@ asyncio.run(main()) -## - -​ - -Known limitations +## Known limitations Plan around these in your deployment design. @@ -362,11 +282,7 @@ Large parallel-subagent fanouts can hit rate limits| Break work into smaller batches rather than issuing one wide dispatch. No per-subagent wall-clock deadline| Cap each [subagent](</docs/en/agent-sdk/subagents>) with `maxTurns` in its `AgentDefinition`. `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a subagent stops producing output; it isn’t a total-runtime deadline. -## - -​ - -Troubleshoot deployment failures +## Troubleshoot deployment failures Use this section when an agent that works on your machine fails in a deployed service. Each item below names a failure and links the entry that covers it: @@ -374,11 +290,7 @@ * **CLI present in the image but won’t launch** : Claude Code can’t start from a binary that doesn’t match the container’s architecture or libc, or from a file that lost its execute permission in the image build. See [Failed to start Claude Code](</docs/en/agent-sdk/troubleshooting#cliconnectionerror-failed-to-start-claude-code>). * **Claude Code process exits mid-run** : the error your application receives depends on the SDK language and on whether the CLI reported an error result first. The entries under [CLI process exit](</docs/en/agent-sdk/troubleshooting#cli-process-exit>) cover each message. -## - -​ - -Next steps +## Next steps * [Hosting cookbook](<https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb>): notebook walkthrough with [deployable code](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>) for Docker, Modal, and Kubernetes. * [Session storage](</docs/en/agent-sdk/session-storage>): persist transcripts across hosts with a `SessionStore` adapter.
modified
--- a/hosting.md +++ b/hosting.md @@ -190,7 +190,7 @@ The container needs your SDK’s language runtime: - * Python 3.10+ for the Python SDK, or Node.js 18+ for the TypeScript SDK + * Python 3.10+ for the Python SDK, or Node.js 18.14+ for the TypeScript SDK * Both the TypeScript and Python SDKs bundle a native Claude Code binary for most installs, and the spawned CLI needs no separate Node.js install. See the [quickstart’s install note](</docs/en/agent-sdk/quickstart>) for the installs that need a separate native Claude Code install. The bundled binary is pinned to the SDK package version, so updating the SDK is how you update the CLI. The SDK follows semver: take patch releases continuously and review the [TypeScript](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md>) or [Python](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md>) changelog before taking a minor. @@ -357,7 +357,7 @@ Limitation| What to do ---|--- -No top-level session timeout| A session does not time out on its own. Set `maxTurns` in TypeScript or `max_turns` in Python to bound how many tool-use round trips the agent takes before stopping. +No top-level session timeout| A session doesn’t time out on its own. Set `maxTurns` in TypeScript or `max_turns` in Python to bound how many [turns](</docs/en/agent-sdk/agent-loop#turns-and-messages>) the agent takes before stopping. Memory growth over long sessions| Cap session length or recycle subprocesses periodically. See Scaling and concurrency. Large parallel-subagent fanouts can hit rate limits| Break work into smaller batches rather than issuing one wide dispatch. No per-subagent wall-clock deadline| Cap each [subagent](</docs/en/agent-sdk/subagents>) with `maxTurns` in its `AgentDefinition`. `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a subagent stops producing output; it isn’t a total-runtime deadline.
modified
--- a/hosting.md +++ b/hosting.md @@ -293,7 +293,7 @@ * Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python to skip user, project, and local settings. * Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](</docs/en/memory#auto-memory>) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for the other inputs that load unconditionally. - * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. When each config directory serves one working directory and you don’t share a [`SessionStore`](</docs/en/agent-sdk/session-storage>) across tenants, you can also set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) in `env` to keep the transcript paths under it short. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later. + * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. When each config directory serves one working directory and you don’t pass a [`SessionStore`](</docs/en/agent-sdk/session-storage>), you can also set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) in `env` to keep the transcript paths under it short. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later. * Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call. * Apply per-tenant egress rules at your proxy, such as distinct outbound IPs, credentials, or domain allowlists, so a compromised tenant cannot exfiltrate data via another tenant’s outbound policy.
modified
--- a/hosting.md +++ b/hosting.md @@ -101,7 +101,12 @@ Long-running sessions -Run persistent container instances, often hosting multiple SDK processes per container, to serve ongoing work. Best for agents that take autonomous action, serve content, or handle high-volume message streams. Example workloads include an email agent that triages and responds to incoming mail, a site builder that hosts a per-user editable site through container ports, and a chat bot that handles continuous traffic from a platform like Slack. The container exposes an HTTP or WebSocket endpoint and maps each active session to a long-lived query and the subprocess behind it. In TypeScript, use [`streamInput()`](</docs/en/agent-sdk/typescript#query-object>) to add turns to an active session and [`startup()`](</docs/en/agent-sdk/typescript#startup>) to pre-warm subprocesses ahead of incoming traffic. In Python, use [`ClaudeSDKClient`](</docs/en/agent-sdk/python#claudesdkclient>) to hold a session open across turns. Size the container so it can hold the maximum number of concurrent sessions in memory. +Run persistent container instances, often hosting multiple SDK processes per container, to serve ongoing work. Best for agents that take autonomous action, serve content, or handle high-volume message streams. Example workloads include an email agent that triages and responds to incoming mail, a site builder that hosts a per-user editable site through container ports, and a chat bot that handles continuous traffic from a platform like Slack. The container exposes an HTTP or WebSocket endpoint and maps each active session to a long-lived query and the subprocess behind it. The calls that keep sessions open and warm differ between the SDKs: + + * **TypeScript** : use [`streamInput()`](</docs/en/agent-sdk/typescript#query-object>) to add turns to an active session. Call [`startup()`](</docs/en/agent-sdk/typescript#startup>) to pre-warm subprocesses ahead of incoming traffic. If you don’t know a session’s working directory until its first request arrives, pre-warm with [`prewarm()`](</docs/en/agent-sdk/typescript#prewarm>) instead. + * **Python** : use [`ClaudeSDKClient`](</docs/en/agent-sdk/python#claudesdkclient>) to hold a session open across turns. + +Size the container so it can hold the maximum number of concurrent sessions in memory. ###
modified
--- a/hosting.md +++ b/hosting.md @@ -1,4 +1,4 @@ -The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. +The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you don’t need to run the agent loop itself on your own infrastructure, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead. Anthropic hosts the agent loop, and your application sends events and receives streamed results through the client SDKs or the REST API. Tool execution runs in an Anthropic-managed cloud sandbox or a [self-hosted sandbox](<https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes>) on your own infrastructure. ##
modified
--- a/hosting.md +++ b/hosting.md @@ -119,7 +119,7 @@ declare const userInput: string; declare const sessionId: string; // looked up from your database by user - declare const sessionStore: SessionStore; // S3, Redis, Postgres, or your own adapter + declare const sessionStore: SessionStore; // an object store, key-value store, database, or your own adapter for await (const message of query({ prompt: userInput, @@ -133,7 +133,7 @@ user_input: str = ... session_id: str = ... # looked up from your database by user - session_store: SessionStore = ... # S3, Redis, Postgres, or your own adapter + session_store: SessionStore = ... # an object store, key-value store, database, or your own adapter async def main(): async for message in query( @@ -220,7 +220,7 @@ Session and state persistence -Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). See [Reference implementations](</docs/en/agent-sdk/session-storage#reference-implementations>) for S3, Redis, and Postgres adapters and a conformance suite for your own. Three things to know about how `SessionStore` behaves: +Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). See [Reference implementations](</docs/en/agent-sdk/session-storage#reference-implementations>) for example adapters for an object store, a key-value store, and a database, and a conformance suite for your own. Three things to know about how `SessionStore` behaves: * **Transcripts only** : `SessionStore` mirrors transcripts, not `CLAUDE.md` memory files or other working-directory artifacts. Mount a shared volume or sync those separately. * **Mirror, not replacement** : the subprocess writes to local disk first, and the SDK forwards a copy of each batch to the store. A fresh session’s local transcript outlives the run; a run resumed from the store deletes its local copy at the end, so the store holds the only durable copy. See [Dual-write architecture](</docs/en/agent-sdk/session-storage#dual-write-architecture>).
modified
--- a/hosting.md +++ b/hosting.md @@ -355,7 +355,7 @@ No top-level session timeout| A session does not time out on its own. Set `maxTurns` in TypeScript or `max_turns` in Python to bound how many tool-use round trips the agent takes before stopping. Memory growth over long sessions| Cap session length or recycle subprocesses periodically. See Scaling and concurrency. Large parallel-subagent fanouts can hit rate limits| Break work into smaller batches rather than issuing one wide dispatch. -No per-subagent wall-clock deadline| Cap each [subagent](</docs/en/agent-sdk/subagents>) with `maxTurns` in its `AgentDefinition`. For background subagents only, `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a `run_in_background` subagent stops producing output; it is not a total-runtime deadline. +No per-subagent wall-clock deadline| Cap each [subagent](</docs/en/agent-sdk/subagents>) with `maxTurns` in its `AgentDefinition`. `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a subagent stops producing output; it isn’t a total-runtime deadline. ##
modified
--- a/hosting.md +++ b/hosting.md @@ -6,15 +6,35 @@ The subprocess model -Every hosting decision on this page follows from how the SDK runs the agent. When your code calls `query()`, the SDK spawns a separate `claude` CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk. One agent session maps to one subprocess. Running N concurrent sessions means N subprocesses, each with its own process tree and transcript file. By default they all inherit your application’s working directory, so pass `cwd` on each `query()` call when sessions need separate filesystems: +Every hosting decision on this page follows from how the SDK runs the agent. When your code calls `query()`, the SDK spawns a separate `claude` CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk. One agent session maps to one subprocess. Running N concurrent sessions means N subprocesses, each with its own process tree and transcript file. By default they all inherit your application’s working directory. When sessions need separate filesystems, pass a distinct `cwd` in the options of each session’s `query()` call: TypeScript Python - query({ prompt, options: { cwd: "/work/session-a" } }) - - query(prompt=prompt, options=ClaudeAgentOptions(cwd="/work/session-a")) + import { query } from "@anthropic-ai/claude-agent-sdk"; + + for await (const message of query({ + prompt: "Summarize the files in this directory", + options: { cwd: "/work/session-a" }, + })) { + console.log(message); + } + + import asyncio + + from claude_agent_sdk import ClaudeAgentOptions, query + + async def main(): + async for message in query( + prompt="Summarize the files in this directory", + options=ClaudeAgentOptions(cwd="/work/session-a"), + ): + print(message) + + asyncio.run(main()) + +The TypeScript examples on this page use top-level `await`, so save them as `.mts` files or set `"type": "module"` in `package.json`. ### @@ -46,7 +66,7 @@ Ephemeral sessions -Create a container for each user task and destroy it when the task completes. Best for one-off tasks. The user may still interact with the AI while the task is completing, but once completed the container is destroyed. Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation. The container runs a one-shot entrypoint that calls the SDK and exits. In TypeScript, save the file as `entrypoint.mts` or set `"type": "module"` in `package.json` so top-level `await` is available. +Create a container for each user task and destroy it when the task completes. Best for one-off tasks. The user may still interact with the AI while the task is completing, but once completed the container is destroyed. Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation. The container runs a one-shot entrypoint that reads the task from the `TASK_PROMPT` environment variable, calls the SDK, and exits. TypeScript @@ -72,6 +92,8 @@ print(message) asyncio.run(main()) + +The script prints each message as it arrives, including a result message whose `subtype` is `success` when the task completes within the turn limit. If the task hits the 20-turn limit instead, the result message’s `subtype` is `error_max_turns` and the `query()` call raises an error after yielding it, so wrap the loop in a try block if the container needs to exit cleanly. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error subtypes. ### @@ -330,7 +352,7 @@ Limitation| What to do ---|--- -No top-level session timeout| A session does not time out on its own. Set `maxTurns` in `Options` to bound how many tool-use round trips the agent takes before stopping. +No top-level session timeout| A session does not time out on its own. Set `maxTurns` in TypeScript or `max_turns` in Python to bound how many tool-use round trips the agent takes before stopping. Memory growth over long sessions| Cap session length or recycle subprocesses periodically. See Scaling and concurrency. Large parallel-subagent fanouts can hit rate limits| Break work into smaller batches rather than issuing one wide dispatch. No per-subagent wall-clock deadline| Cap each [subagent](</docs/en/agent-sdk/subagents>) with `maxTurns` in its `AgentDefinition`. For background subagents only, `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a `run_in_background` subagent stops producing output; it is not a total-runtime deadline.
modified
--- a/hosting.md +++ b/hosting.md @@ -1,6 +1,4 @@ The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. - -For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). ## @@ -127,8 +125,6 @@ asyncio.run(main()) -See [Session storage](</docs/en/agent-sdk/session-storage>) for the full `SessionStore` interface and reference adapters. - ### ​ @@ -268,7 +264,7 @@ Default SDK behavior reads settings and `CLAUDE.md` memory files from the filesystem. In a shared container that serves multiple tenants, those files can leak one tenant’s context into another tenant’s session. To isolate tenants inside a shared container: - * Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python so no filesystem settings load. + * Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python to skip user, project, and local settings. * Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](</docs/en/memory#auto-memory>) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for the other inputs that load unconditionally. * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. When each config directory serves one working directory and you don’t share a [`SessionStore`](</docs/en/agent-sdk/session-storage>) across tenants, you can also set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) in `env` to keep the transcript paths under it short. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later. * Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call. @@ -324,8 +320,6 @@ asyncio.run(main()) -For per-tenant network controls, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). - ## ​ @@ -345,6 +339,18 @@ ​ +Troubleshoot deployment failures + +Use this section when an agent that works on your machine fails in a deployed service. Each item below names a failure and links the entry that covers it: + + * **CLI not found at service start** : in Python, a container or service manager runs your application with a different `PATH` than your shell, so an install that works locally isn’t visible to the process. In TypeScript, the image build skipped the SDK’s optional dependencies, or `pathToClaudeCodeExecutable` points at a file that doesn’t exist in the image. See [Claude Code not found](</docs/en/agent-sdk/troubleshooting#clinotfounderror-claude-code-not-found>). + * **CLI present in the image but won’t launch** : Claude Code can’t start from a binary that doesn’t match the container’s architecture or libc, or from a file that lost its execute permission in the image build. See [Failed to start Claude Code](</docs/en/agent-sdk/troubleshooting#cliconnectionerror-failed-to-start-claude-code>). + * **Claude Code process exits mid-run** : the error your application receives depends on the SDK language and on whether the CLI reported an error result first. The entries under [CLI process exit](</docs/en/agent-sdk/troubleshooting#cli-process-exit>) cover each message. + +## + +​ + Next steps * [Hosting cookbook](<https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb>): notebook walkthrough with [deployable code](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>) for Docker, Modal, and Kubernetes.
modified
--- a/hosting.md +++ b/hosting.md @@ -149,22 +149,13 @@ Container-based sandboxing -Run the SDK inside a sandboxed container for process isolation, resource limits, network control, and an ephemeral filesystem. Several providers specialize in sandboxed container environments that fit the Agent SDK’s model. Questions to answer when choosing a provider: +Run the SDK inside a sandboxed container for process isolation, resource limits, network control, and an ephemeral filesystem. Questions to answer when choosing a provider: * **Who runs the sandbox** : a sandbox-as-a-service provider operates the infrastructure for you, while self-hosted options give you software to run on your own. * **Cold-start latency** : how long from “create a sandbox” to “ready to accept the first request.” Ephemeral patterns need sub-second starts. Long-running patterns tolerate more. * **Persistent storage** : whether the provider offers durable volumes or only ephemeral disk. The hybrid pattern needs durable storage somewhere, whether in the sandbox or alongside it. * **Pricing model** : per-second, per-request, or flat hourly billing. Per-second pricing suits bursty ephemeral workloads. Hourly suits long-running sessions. * **Networking** : support for custom egress rules, outbound proxies, and private VPC peering for regulated environments. - -Providers to evaluate: - - * [Modal Sandbox](<https://modal.com/docs/guide/sandbox>), with a [demo implementation](<https://modal.com/docs/examples/claude-slack-gif-creator>) - * [Cloudflare Sandboxes](<https://github.com/cloudflare/sandbox-sdk>) - * [Daytona](<https://www.daytona.io/>) - * [E2B](<https://e2b.dev/>) - * [Fly Machines](<https://fly.io/docs/machines/>) - * [Vercel Sandbox](<https://vercel.com/docs/functions/sandbox>) For self-hosted options such as Docker, gVisor, and Firecracker, and detailed isolation configuration, see [Isolation Technologies](</docs/en/agent-sdk/secure-deployment#isolation-technologies>).
modified
--- a/hosting.md +++ b/hosting.md @@ -279,7 +279,7 @@ * Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python so no filesystem settings load. * Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](</docs/en/memory#auto-memory>) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for the other inputs that load unconditionally. - * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. When each config directory serves one working directory, you can also set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) in `env` to keep the transcript paths under it short. Requires TypeScript Agent SDK v0.3.234 or later. + * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. When each config directory serves one working directory and you don’t share a [`SessionStore`](</docs/en/agent-sdk/session-storage>) across tenants, you can also set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) in `env` to keep the transcript paths under it short. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later. * Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call. * Apply per-tenant egress rules at your proxy, such as distinct outbound IPs, credentials, or domain allowlists, so a compromised tenant cannot exfiltrate data via another tenant’s outbound policy.
modified
--- a/hosting.md +++ b/hosting.md @@ -279,11 +279,11 @@ * Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python so no filesystem settings load. * Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](</docs/en/memory#auto-memory>) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for the other inputs that load unconditionally. - * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. + * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. When each config directory serves one working directory, you can also set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) in `env` to keep the transcript paths under it short. Requires TypeScript Agent SDK v0.3.234 or later. * Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call. * Apply per-tenant egress rules at your proxy, such as distinct outbound IPs, credentials, or domain allowlists, so a compromised tenant cannot exfiltrate data via another tenant’s outbound policy. -The example below applies the four SDK-level options together. Construct `tenantDir` and `configDir` so each tenant gets a path no other tenant can read. In TypeScript, `env` replaces the subprocess environment, so spread `...process.env` to keep inherited variables like `PATH` and `ANTHROPIC_API_KEY`. In Python, `env` is merged on top of the inherited environment. +The example below applies the settings, auto memory, config directory, and working directory options together. Construct `tenantDir` and `configDir` so each tenant gets a path no other tenant can read. In TypeScript, `env` replaces the subprocess environment, so spread `...process.env` to keep inherited variables like `PATH` and `ANTHROPIC_API_KEY`. In Python, `env` is merged on top of the inherited environment. TypeScript
modified
--- a/hosting.md +++ b/hosting.md @@ -214,7 +214,7 @@ Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). See [Reference implementations](</docs/en/agent-sdk/session-storage#reference-implementations>) for S3, Redis, and Postgres adapters and a conformance suite for your own. Three things to know about how `SessionStore` behaves: * **Transcripts only** : `SessionStore` mirrors transcripts, not `CLAUDE.md` memory files or other working-directory artifacts. Mount a shared volume or sync those separately. - * **Mirror, not replacement** : the subprocess writes to local disk first, and the store receives a copy of each batch. Local writes remain authoritative. + * **Mirror, not replacement** : the subprocess writes to local disk first, and the SDK forwards a copy of each batch to the store. A fresh session’s local transcript outlives the run; a run resumed from the store deletes its local copy at the end, so the store holds the only durable copy. See [Dual-write architecture](</docs/en/agent-sdk/session-storage#dual-write-architecture>). * **`mirror_error` messages**: when the SDK can’t deliver a batch to the store, it drops the batch, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. See [Mirror writes are best-effort](</docs/en/agent-sdk/session-storage#mirror-writes-are-best-effort>) for the retry and timeout behavior. ###
modified
--- a/hosting.md +++ b/hosting.md @@ -1,4 +1,4 @@ -The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure: understand the subprocess model, choose a session pattern, provision the container, and handle production concerns like persistence, observability, auth, and multi-tenant isolation. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. +The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). @@ -215,7 +215,7 @@ * **Transcripts only** : `SessionStore` mirrors transcripts, not `CLAUDE.md` memory files or other working-directory artifacts. Mount a shared volume or sync those separately. * **Mirror, not replacement** : the subprocess writes to local disk first, and the store receives a copy of each batch. Local writes remain authoritative. - * **`mirror_error` messages**: a batch the store rejects is sent up to three times in total, with a short backoff before each retry; a timed-out call isn’t retried. If the batch still fails, the SDK drops it, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. + * **`mirror_error` messages**: when the SDK can’t deliver a batch to the store, it drops the batch, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. See [Mirror writes are best-effort](</docs/en/agent-sdk/session-storage#mirror-writes-are-best-effort>) for the retry and timeout behavior. ### @@ -259,7 +259,7 @@ agents per host = (host RAM - overhead) / (per-session RAM ceiling) -Measure the per-session ceiling by running a representative session to your target length under your expected tool load and recording peak RSS. The 1 GiB starting point in Resources is a floor, not the ceiling. Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts. Large fanouts of concurrent [subagents](</docs/en/agent-sdk/subagents>) from a single session can hit API rate limits. Break the work into smaller batches rather than issuing one wide dispatch. +Measure the per-session ceiling by running a representative session to your target length under your expected tool load and recording peak RSS. The 1 GiB starting point in Resources is a floor, not the ceiling. Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts. ###
modified
--- a/hosting.md +++ b/hosting.md @@ -174,10 +174,10 @@ Runtime dependencies -The container needs only your SDK’s language runtime: +The container needs your SDK’s language runtime: * Python 3.10+ for the Python SDK, or Node.js 18+ for the TypeScript SDK - * Both SDK packages bundle a native Claude Code binary for the host platform, so no separate Claude Code or Node.js install is needed for the spawned CLI + * Both the TypeScript and Python SDKs bundle a native Claude Code binary for most installs, and the spawned CLI needs no separate Node.js install. See the [quickstart’s install note](</docs/en/agent-sdk/quickstart>) for the installs that need a separate native Claude Code install. The bundled binary is pinned to the SDK package version, so updating the SDK is how you update the CLI. The SDK follows semver: take patch releases continuously and review the [TypeScript](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md>) or [Python](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md>) changelog before taking a minor.
modified
--- a/hosting.md +++ b/hosting.md @@ -48,7 +48,11 @@ Ephemeral sessions -Create a container for each user task and destroy it when the task completes. Best for one-off tasks. The user may still interact with the AI while the task is completing, but once completed the container is destroyed. Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation. The container runs a one-shot entrypoint that calls the SDK and exits. The example below shows a minimal TypeScript version. Save it as `entrypoint.mts` or set `"type": "module"` in `package.json` so top-level `await` is available. +Create a container for each user task and destroy it when the task completes. Best for one-off tasks. The user may still interact with the AI while the task is completing, but once completed the container is destroyed. Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation. The container runs a one-shot entrypoint that calls the SDK and exits. In TypeScript, save the file as `entrypoint.mts` or set `"type": "module"` in `package.json` so top-level `await` is available. + +TypeScript + +Python import { query } from "@anthropic-ai/claude-agent-sdk"; @@ -56,6 +60,20 @@ for await (const message of query({ prompt, options: { maxTurns: 20 } })) { console.log(message); } + + import asyncio + import os + + from claude_agent_sdk import ClaudeAgentOptions, query + + async def main(): + async for message in query( + prompt=os.environ["TASK_PROMPT"], + options=ClaudeAgentOptions(max_turns=20), + ): + print(message) + + asyncio.run(main()) ### @@ -227,7 +245,7 @@ Three auth concerns matter at hosting time: - * **Anthropic API** : the subprocess reads `ANTHROPIC_API_KEY` from its environment. Supply it from your secret manager, or set `ANTHROPIC_BASE_URL` to route model calls through a proxy that injects the key outside the container. See [Credential management](</docs/en/agent-sdk/secure-deployment#credential-management>) for the proxy pattern and the [SDK overview](</docs/en/agent-sdk/overview#get-started>) for supported authentication methods. + * **Anthropic API** : the subprocess reads `ANTHROPIC_API_KEY` from its environment. Supply it from your secret manager, or set `ANTHROPIC_BASE_URL` to route model calls through a proxy that injects the key outside the container. See [Credential management](</docs/en/agent-sdk/secure-deployment#credential-management>) for the proxy pattern and [Setup in the SDK quickstart](</docs/en/agent-sdk/quickstart#setup>) for supported authentication methods. * **Inbound** : put authentication at a gateway in front of the agent container. The agent should receive pre-authenticated requests and should not be the component that validates user tokens. * **Outbound tools** : keep tool credentials out of the agent environment. Route outbound calls through a proxy that injects API keys after the request leaves the container. The agent makes the call; the proxy adds the credential.
modified
--- a/hosting.md +++ b/hosting.md @@ -90,16 +90,24 @@ // ... } - from claude_agent_sdk import query, ClaudeAgentOptions - - async for message in query( - prompt=user_input, - options=ClaudeAgentOptions( - resume=session_id, # looked up from your database by user - session_store=session_store, # S3, Redis, Postgres, or your own adapter - ), - ): - ... + from claude_agent_sdk import query, ClaudeAgentOptions, SessionStore + import asyncio + + user_input: str = ... + session_id: str = ... # looked up from your database by user + session_store: SessionStore = ... # S3, Redis, Postgres, or your own adapter + + async def main(): + async for message in query( + prompt=user_input, + options=ClaudeAgentOptions( + resume=session_id, + session_store=session_store, + ), + ): + ... + + asyncio.run(main()) See [Session storage](</docs/en/agent-sdk/session-storage>) for the full `SessionStore` interface and reference adapters. @@ -285,19 +293,27 @@ } from claude_agent_sdk import query, ClaudeAgentOptions - - async for message in query( - prompt=prompt, - options=ClaudeAgentOptions( - cwd=tenant_dir, - setting_sources=[], - env={ - "CLAUDE_CONFIG_DIR": config_dir, - "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1", - }, - ), - ): - ... + import asyncio + + prompt: str = ... + tenant_dir: str = ... + config_dir: str = ... + + async def main(): + async for message in query( + prompt=prompt, + options=ClaudeAgentOptions( + cwd=tenant_dir, + setting_sources=[], + env={ + "CLAUDE_CONFIG_DIR": config_dir, + "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1", + }, + ), + ): + ... + + asyncio.run(main()) For per-tenant network controls, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>).
modified
--- a/hosting.md +++ b/hosting.md @@ -15,6 +15,8 @@ Python query({ prompt, options: { cwd: "/work/session-a" } }) + + query(prompt=prompt, options=ClaudeAgentOptions(cwd="/work/session-a")) ### @@ -87,6 +89,17 @@ })) { // ... } + + from claude_agent_sdk import query, ClaudeAgentOptions + + async for message in query( + prompt=user_input, + options=ClaudeAgentOptions( + resume=session_id, # looked up from your database by user + session_store=session_store, # S3, Redis, Postgres, or your own adapter + ), + ): + ... See [Session storage](</docs/en/agent-sdk/session-storage>) for the full `SessionStore` interface and reference adapters. @@ -271,6 +284,21 @@ // ... } + from claude_agent_sdk import query, ClaudeAgentOptions + + async for message in query( + prompt=prompt, + options=ClaudeAgentOptions( + cwd=tenant_dir, + setting_sources=[], + env={ + "CLAUDE_CONFIG_DIR": config_dir, + "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1", + }, + ), + ): + ... + For per-tenant network controls, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). ##
modified
--- a/hosting.md +++ b/hosting.md @@ -156,7 +156,7 @@ Network -The SDK needs outbound HTTPS to `api.anthropic.com`, or to your provider’s regional endpoint when running on Bedrock or Vertex. If your agents use [MCP servers](</docs/en/agent-sdk/mcp>) or external tools, they need outbound access to those endpoints as well. For production, route outbound traffic through an egress proxy that enforces domain allowlists, injects credentials, and logs requests. See [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) for the full pattern. For inbound traffic, expose an HTTP or WebSocket port on the container. Your application handles client requests on that port and calls the SDK internally; the subprocess itself does not listen on the network. +The SDK needs outbound HTTPS to `api.anthropic.com`, or to your provider’s regional endpoint when running on Amazon Bedrock or Google Cloud’s Agent Platform. If your agents use [MCP servers](</docs/en/agent-sdk/mcp>) or external tools, they need outbound access to those endpoints as well. For production, route outbound traffic through an egress proxy that enforces domain allowlists, injects credentials, and logs requests. See [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) for the full pattern. For inbound traffic, expose an HTTP or WebSocket port on the container. Your application handles client requests on that port and calls the SDK internally; the subprocess itself does not listen on the network. ##
modified
--- a/hosting.md +++ b/hosting.md @@ -176,7 +176,7 @@ * **Transcripts only** : `SessionStore` mirrors transcripts, not `CLAUDE.md` memory files or other working-directory artifacts. Mount a shared volume or sync those separately. * **Mirror, not replacement** : the subprocess writes to local disk first, and the store receives a copy of each batch. Local writes remain authoritative. - * **`mirror_error` messages**: if the store rejects or times out, the SDK emits a `{ type: "system", subtype: "mirror_error" }` message and continues the query without retry. Alert on these if store durability matters. + * **`mirror_error` messages**: a batch the store rejects is sent up to three times in total, with a short backoff before each retry; a timed-out call isn’t retried. If the batch still fails, the SDK drops it, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. ###
modified
--- a/hosting.md +++ b/hosting.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. - The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure: understand the subprocess model, choose a session pattern, provision the container, and handle production concerns like persistence, observability, auth, and multi-tenant isolation. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>).
modified
Show diff (490 lines)
--- a/hosting.md +++ b/hosting.md @@ -4,186 +4,304 @@ > > Use this file to discover all available pages before exploring further. -The Claude Agent SDK differs from traditional stateless LLM APIs in that it maintains conversational state and executes commands in a persistent environment. This guide covers the architecture, hosting considerations, and best practices for deploying SDK-based agents in production. - -For security hardening beyond basic sandboxing (including network controls, credential management, and isolation options), see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). - -## - -​ - -Hosting Requirements - -### - -​ - -Container-Based Sandboxing - -For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems. The SDK also supports [programmatic sandbox configuration](</docs/en/agent-sdk/typescript#sandboxsettings>) for command execution. - -### - -​ - -System Requirements - -Each SDK instance requires: - - * **Runtime dependencies** - * Python 3.10+ for the Python SDK, or Node.js 18+ for the TypeScript SDK - * Both SDK packages bundle a native Claude Code binary for the host platform, so no separate Claude Code or Node.js install is needed for the spawned CLI - * **Resource allocation** - * Recommended: 1GiB RAM, 5GiB of disk, and 1 CPU (vary this based on your task as needed) - * **Network access** - * Outbound HTTPS to `api.anthropic.com` - * Optional: Access to MCP servers or external tools - -## - -​ - -Understanding the SDK Architecture - -Unlike stateless API calls, the Claude Agent SDK operates as a **long-running process** that: - - * **Executes commands** in a persistent shell environment - * **Manages file operations** within a working directory - * **Handles tool execution** with context from previous interactions - -## - -​ - -Sandbox Provider Options - -Several providers specialize in secure container environments for AI code execution: - - * **[Modal Sandbox](<https://modal.com/docs/guide/sandbox>)** \- [demo implementation](<https://modal.com/docs/examples/claude-slack-gif-creator>) - * **[Cloudflare Sandboxes](<https://github.com/cloudflare/sandbox-sdk>)** - * **[Daytona](<https://www.daytona.io/>)** - * **[E2B](<https://e2b.dev/>)** - * **[Fly Machines](<https://fly.io/docs/machines/>)** - * **[Vercel Sandbox](<https://vercel.com/docs/functions/sandbox>)** - -For self-hosted options (Docker, gVisor, Firecracker) and detailed isolation configuration, see [Isolation Technologies](</docs/en/agent-sdk/secure-deployment#isolation-technologies>). - -## - -​ - -Production Deployment Patterns - -### - -​ - -Pattern 1: Ephemeral Sessions - -Create a new container for each user task, then destroy it when complete. Best for one-off tasks, the user may still interact with the AI while the task is completing, but once completed the container is destroyed. **Examples:** - - * Bug Investigation & Fix: Debug and resolve a specific issue with relevant context - * Invoice Processing: Extract and structure data from receipts/invoices for accounting systems - * Translation Tasks: Translate documents or content batches between languages - * Image/Video Processing: Apply transformations, optimizations, or extract metadata from media files - -### - -​ - -Pattern 2: Long-Running Sessions - -Maintain persistent container instances for long running tasks. Often times running _multiple_ Claude Agent processes inside of the container based on demand. Best for proactive agents that take action without the users input, agents that serve content or agents that process high amounts of messages. **Examples:** - - * Email Agent: Monitors incoming emails and autonomously triages, responds, or takes actions based on content - * Site Builder: Hosts custom websites per user with live editing capabilities served through container ports - * High-Frequency Chat Bots: Handles continuous message streams from platforms like Slack where rapid response times are critical - -### - -​ - -Pattern 3: Hybrid Sessions - -Ephemeral containers that are hydrated with history and state, possibly from a database or from the SDK’s session resumption features. Best for containers with intermittent interaction from the user that kicks off work and spins down when the work is completed but can be continued. **Examples:** - - * Personal Project Manager: Helps manage ongoing projects with intermittent check-ins, maintains context of tasks, decisions, and progress - * Deep Research: Conducts multi-hour research tasks, saves findings and resumes investigation when user returns - * Customer Support Agent: Handles support tickets that span multiple interactions, loads ticket history and customer context - -### - -​ - -Pattern 4: Single Containers - -Run multiple Claude Agent SDK processes in one global container. Best for agents that must collaborate closely together. This is likely the least popular pattern because you will have to prevent agents from overwriting each other. **Examples:** - - * **Simulations** : Agents that interact with each other in simulations such as video games. - -## - -​ - -FAQ - -### - -​ - -How do I communicate with my sandboxes? - -When hosting in containers, expose ports to communicate with your SDK instances. Your application can expose HTTP/WebSocket endpoints for external clients while the SDK runs internally within the container. - -### - -​ - -What is the cost of hosting a container? - -The dominant cost of serving agents is the tokens; containers vary based on what you provision, but a minimum cost is roughly 5 cents per hour running. - -### - -​ - -When should I shut down idle containers vs. keeping them warm? - -This is likely provider dependent, different sandbox providers will let you set different criteria for idle timeouts after which a sandbox might spin down. You will want to tune this timeout based on how frequent you think user response might be. - -### - -​ - -How often should I update the Claude Code CLI? - -The Claude Code CLI is versioned with semver, so any breaking changes will be versioned. - -### - -​ - -How do I monitor container health and agent performance? - -Since containers are just servers the same logging infrastructure you use for the backend will work for containers. - -### - -​ - -How long can an agent session run before timing out? - -An agent session will not timeout, but consider setting a ‘maxTurns’ property to prevent Claude from getting stuck in a loop. - -## - -​ - -Next Steps - - * [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) \- Network controls, credential management, and isolation hardening - * [TypeScript SDK - Sandbox Settings](</docs/en/agent-sdk/typescript#sandboxsettings>) \- Configure sandbox programmatically - * [Sessions Guide](</docs/en/agent-sdk/sessions>) \- Learn about session management - * [Permissions](</docs/en/agent-sdk/permissions>) \- Configure tool permissions - * [Cost Tracking](</docs/en/agent-sdk/cost-tracking>) \- Monitor API usage - * [MCP Integration](</docs/en/agent-sdk/mcp>) \- Extend with custom tools +The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure: understand the subprocess model, choose a session pattern, provision the container, and handle production concerns like persistence, observability, auth, and multi-tenant isolation. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. + +For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). + +## + +​ + +The subprocess model + +Every hosting decision on this page follows from how the SDK runs the agent. When your code calls `query()`, the SDK spawns a separate `claude` CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk. One agent session maps to one subprocess. Running N concurrent sessions means N subprocesses, each with its own process tree and transcript file. By default they all inherit your application’s working directory, so pass `cwd` on each `query()` call when sessions need separate filesystems: + +TypeScript + +Python + + query({ prompt, options: { cwd: "/work/session-a" } }) + +### + +​ + +State that lives on local disk + +Three kinds of agent state live on the container’s filesystem by default. None of them survive a container restart, a scale-down, or a move to a different node. + +State| Default location +---|--- +Session transcripts| `~/.claude/projects/`, or the `projects/` directory under `CLAUDE_CONFIG_DIR` if set +`CLAUDE.md` memory files| `~/.claude/CLAUDE.md` for the user tier and the session’s working directory for the project tier +Working-directory artifacts| The session’s working directory + +To persist transcripts across hosts, configure a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). Memory files and other working-directory artifacts need their own storage strategy, such as a mounted volume or an object-store sync. For how sessions, resumption, and forking work at the API level, see [Sessions](</docs/en/agent-sdk/sessions>). + +## + +​ + +Choose a session pattern + +These four patterns cover session lifecycle: how long a container lives relative to the sessions it serves. For where the container runs, the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb>) has [deployable code](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>) for local Docker, Modal, and Kubernetes. Choose a session pattern here and a deployment target from the cookbook. + +### + +​ + +Ephemeral sessions + +Create a container for each user task and destroy it when the task completes. Best for one-off tasks. The user may still interact with the AI while the task is completing, but once completed the container is destroyed. Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation. The container runs a one-shot entrypoint that calls the SDK and exits. The example below shows a minimal TypeScript version. Save it as `entrypoint.mts` or set `"type": "module"` in `package.json` so top-level `await` is available. + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + const prompt = process.env.TASK_PROMPT!; + for await (const message of query({ prompt, options: { maxTurns: 20 } })) { + console.log(message); + } + +### + +​ + +Long-running sessions + +Run persistent container instances, often hosting multiple SDK processes per container, to serve ongoing work. Best for agents that take autonomous action, serve content, or handle high-volume message streams. Example workloads include an email agent that triages and responds to incoming mail, a site builder that hosts a per-user editable site through container ports, and a chat bot that handles continuous traffic from a platform like Slack. The container exposes an HTTP or WebSocket endpoint and maps each active session to a long-lived query and the subprocess behind it. In TypeScript, use [`streamInput()`](</docs/en/agent-sdk/typescript#query-object>) to add turns to an active session and [`startup()`](</docs/en/agent-sdk/typescript#startup>) to pre-warm subprocesses ahead of incoming traffic. In Python, use [`ClaudeSDKClient`](</docs/en/agent-sdk/python#claudesdkclient>) to hold a session open across turns. Size the container so it can hold the maximum number of concurrent sessions in memory. + +### + +​ + +Hybrid sessions + +Ephemeral containers that hydrate from a [`SessionStore`](</docs/en/agent-sdk/session-storage>) on startup and persist updates back. Best for sessions that span many interactions but sit idle between them. The container spins down during idle periods and spins back up when the user returns. Example workloads include a personal project manager with intermittent check-ins, deep research that pauses and resumes over hours, and a customer support agent that loads ticket history across interactions. Tune your provider’s idle timeout to how frequently you expect users to return. Shutting a container down without a `SessionStore` configured loses the transcript with it, so the store is required for this pattern, not optional. The pattern hinges on resuming a session by ID with a shared store attached: + +TypeScript + +Python + + import { query, type SessionStore } from "@anthropic-ai/claude-agent-sdk"; + + declare const userInput: string; + declare const sessionId: string; // looked up from your database by user + declare const sessionStore: SessionStore; // S3, Redis, Postgres, or your own adapter + + for await (const message of query({ + prompt: userInput, + options: { resume: sessionId, sessionStore }, + })) { + // ... + } + +See [Session storage](</docs/en/agent-sdk/session-storage>) for the full `SessionStore` interface and reference adapters. + +### + +​ + +Multi-agent container + +Run multiple SDK subprocesses inside one container. Best for agents that must collaborate closely, for example multi-agent simulations where the agents interact with each other in a shared environment. Give each agent its own working directory so they do not overwrite each other’s files, and isolate settings loading so per-agent `CLAUDE.md` files do not leak across agents. See Multi-tenant isolation for the specific options. + +## + +​ + +Provision the container + +### + +​ + +Container-based sandboxing + +Run the SDK inside a sandboxed container for process isolation, resource limits, network control, and an ephemeral filesystem. Several providers specialize in sandboxed container environments that fit the Agent SDK’s model. Questions to answer when choosing a provider: + + * **Who runs the sandbox** : a sandbox-as-a-service provider operates the infrastructure for you, while self-hosted options give you software to run on your own. + * **Cold-start latency** : how long from “create a sandbox” to “ready to accept the first request.” Ephemeral patterns need sub-second starts. Long-running patterns tolerate more. + * **Persistent storage** : whether the provider offers durable volumes or only ephemeral disk. The hybrid pattern needs durable storage somewhere, whether in the sandbox or alongside it. + * **Pricing model** : per-second, per-request, or flat hourly billing. Per-second pricing suits bursty ephemeral workloads. Hourly suits long-running sessions. + * **Networking** : support for custom egress rules, outbound proxies, and private VPC peering for regulated environments. + +Providers to evaluate: + + * [Modal Sandbox](<https://modal.com/docs/guide/sandbox>), with a [demo implementation](<https://modal.com/docs/examples/claude-slack-gif-creator>) + * [Cloudflare Sandboxes](<https://github.com/cloudflare/sandbox-sdk>) + * [Daytona](<https://www.daytona.io/>) + * [E2B](<https://e2b.dev/>) + * [Fly Machines](<https://fly.io/docs/machines/>) + * [Vercel Sandbox](<https://vercel.com/docs/functions/sandbox>) + +For self-hosted options such as Docker, gVisor, and Firecracker, and detailed isolation configuration, see [Isolation Technologies](</docs/en/agent-sdk/secure-deployment#isolation-technologies>). + +### + +​ + +Runtime dependencies + +The container needs only your SDK’s language runtime: + + * Python 3.10+ for the Python SDK, or Node.js 18+ for the TypeScript SDK + * Both SDK packages bundle a native Claude Code binary for the host platform, so no separate Claude Code or Node.js install is needed for the spawned CLI + +The bundled binary is pinned to the SDK package version, so updating the SDK is how you update the CLI. The SDK follows semver: take patch releases continuously and review the [TypeScript](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md>) or [Python](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md>) changelog before taking a minor. + +### + +​ + +Resources + +1 GiB RAM, 5 GiB disk, and 1 CPU per agent is a reasonable starting point for a freshly started instance. Memory usage grows with session length and tool activity, so size for the session lengths and concurrency you actually need rather than the idle baseline. See Scaling and concurrency for how to work out agents per host. + +### + +​ + +Network + +The SDK needs outbound HTTPS to `api.anthropic.com`, or to your provider’s regional endpoint when running on Bedrock or Vertex. If your agents use [MCP servers](</docs/en/agent-sdk/mcp>) or external tools, they need outbound access to those endpoints as well. For production, route outbound traffic through an egress proxy that enforces domain allowlists, injects credentials, and logs requests. See [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) for the full pattern. For inbound traffic, expose an HTTP or WebSocket port on the container. Your application handles client requests on that port and calls the SDK internally; the subprocess itself does not listen on the network. + +## + +​ + +Handle production concerns + +Work through these decisions before shipping a self-hosted agent. + +### + +​ + +Session and state persistence + +Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). See [Reference implementations](</docs/en/agent-sdk/session-storage#reference-implementations>) for S3, Redis, and Postgres adapters and a conformance suite for your own. Three things to know about how `SessionStore` behaves: + + * **Transcripts only** : `SessionStore` mirrors transcripts, not `CLAUDE.md` memory files or other working-directory artifacts. Mount a shared volume or sync those separately. + * **Mirror, not replacement** : the subprocess writes to local disk first, and the store receives a copy of each batch. Local writes remain authoritative. + * **`mirror_error` messages**: if the store rejects or times out, the SDK emits a `{ type: "system", subtype: "mirror_error" }` message and continues the query without retry. Alert on these if store durability matters. + +### + +​ + +Observability + +Agent SDK agents are long-lived processes that spawn tool calls across many API round-trips. Without telemetry you cannot see which tools ran, how long they took, or where a session stalled. The SDK inherits OpenTelemetry configuration from the environment. Set the OTEL environment variables at the container or orchestrator level so every `query()` call exports spans, metrics, and log events to your collector. The example below enables OTLP export for all three signals. `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` is required only for traces; omit it if you export metrics and logs alone. + +.env + + CLAUDE_CODE_ENABLE_TELEMETRY=1 + CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1 + OTEL_TRACES_EXPORTER=otlp + OTEL_METRICS_EXPORTER=otlp + OTEL_LOGS_EXPORTER=otlp + OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf + OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.example.com:4318 + +Prompt text and tool inputs are not included in exports by default. See [Control sensitive data in exports](</docs/en/agent-sdk/observability#control-sensitive-data-in-exports>) for the opt-in flags, and [Observability](</docs/en/agent-sdk/observability>) for the full signal catalog. + +### + +​ + +Auth and secrets + +Three auth concerns matter at hosting time: + + * **Anthropic API** : the subprocess reads `ANTHROPIC_API_KEY` from its environment. Supply it from your secret manager, or set `ANTHROPIC_BASE_URL` to route model calls through a proxy that injects the key outside the container. See [Credential management](</docs/en/agent-sdk/secure-deployment#credential-management>) for the proxy pattern and the [SDK overview](</docs/en/agent-sdk/overview#get-started>) for supported authentication methods. + * **Inbound** : put authentication at a gateway in front of the agent container. The agent should receive pre-authenticated requests and should not be the component that validates user tokens. + * **Outbound tools** : keep tool credentials out of the agent environment. Route outbound calls through a proxy that injects API keys after the request leaves the container. The agent makes the call; the proxy adds the credential. + +### + +​ + +Scaling and concurrency + +Each session runs in its own subprocess, so concurrency on a host is bounded by how many subprocesses its RAM can hold. Size each host with this formula: + + agents per host = (host RAM - overhead) / (per-session RAM ceiling) + +Measure the per-session ceiling by running a representative session to your target length under your expected tool load and recording peak RSS. The 1 GiB starting point in Resources is a floor, not the ceiling. Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts. Large fanouts of concurrent [subagents](</docs/en/agent-sdk/subagents>) from a single session can hit API rate limits. Break the work into smaller batches rather than issuing one wide dispatch. + +### + +​ + +Cost + +Anthropic token cost typically dominates container infrastructure cost by an order of magnitude or more. A minimally provisioned container runs roughly $0.05 per hour, while a single long agent session can spend dollars in tokens. See [Cost tracking](</docs/en/agent-sdk/cost-tracking>) for per-session token accounting. + +### + +​ + +Multi-tenant isolation + +Default SDK behavior reads settings and `CLAUDE.md` memory files from the filesystem. In a shared container that serves multiple tenants, those files can leak one tenant’s context into another tenant’s session. To isolate tenants inside a shared container: + + * Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python so no filesystem settings load. + * Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](</docs/en/memory#auto-memory>) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for the other inputs that load unconditionally. + * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. + * Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call. + * Apply per-tenant egress rules at your proxy, such as distinct outbound IPs, credentials, or domain allowlists, so a compromised tenant cannot exfiltrate data via another tenant’s outbound policy. + +The example below applies the four SDK-level options together. Construct `tenantDir` and `configDir` so each tenant gets a path no other tenant can read. In TypeScript, `env` replaces the subprocess environment, so spread `...process.env` to keep inherited variables like `PATH` and `ANTHROPIC_API_KEY`. In Python, `env` is merged on top of the inherited environment. + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + declare const prompt: string; + declare const tenantDir: string; + declare const configDir: string; + + for await (const message of query({ + prompt, + options: { + cwd: tenantDir, + settingSources: [], + env: { + ...process.env, + CLAUDE_CONFIG_DIR: configDir, + CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", + }, + }, + })) { + // ... + } + +For per-tenant network controls, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). + +## + +​ + +Known limitations + +Plan around these in your deployment design. + +Limitation| What to do +---|--- +No top-level session timeout| A session does not time out on its own. Set `maxTurns` in `Options` to bound how many tool-use round trips the agent takes before stopping. +Memory growth over long sessions| Cap session length or recycle subprocesses periodically. See Scaling and concurrency. +Large parallel-subagent fanouts can hit rate limits| Break work into smaller batches rather than issuing one wide dispatch. +No per-subagent wall-clock deadline| Cap each [subagent](</docs/en/agent-sdk/subagents>) with `maxTurns` in its `AgentDefinition`. For background subagents only, `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a `run_in_background` subagent stops producing output; it is not a total-runtime deadline. + +## + +​ + +Next steps + + * [Hosting cookbook](<https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb>): notebook walkthrough with [deployable code](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>) for Docker, Modal, and Kubernetes. + * [Session storage](</docs/en/agent-sdk/session-storage>): persist transcripts across hosts with a `SessionStore` adapter. + * [Observability](</docs/en/agent-sdk/observability>): export OTEL traces, metrics, and logs to your collector. + * [Secure deployment](</docs/en/agent-sdk/secure-deployment>): network controls, credential management, and isolation hardening. + * [Cost tracking](</docs/en/agent-sdk/cost-tracking>): per-session token and cost accounting.
modified
--- a/hosting.md +++ b/hosting.md @@ -20,7 +20,7 @@ Container-Based Sandboxing -For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems. The SDK also supports [programmatic sandbox configuration](</docs/en/agent-sdk/typescript#sandbox-settings>) for command execution. +For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems. The SDK also supports [programmatic sandbox configuration](</docs/en/agent-sdk/typescript#sandboxsettings>) for command execution. ### @@ -182,7 +182,7 @@ Next Steps * [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) \- Network controls, credential management, and isolation hardening - * [TypeScript SDK - Sandbox Settings](</docs/en/agent-sdk/typescript#sandbox-settings>) \- Configure sandbox programmatically + * [TypeScript SDK - Sandbox Settings](</docs/en/agent-sdk/typescript#sandboxsettings>) \- Configure sandbox programmatically * [Sessions Guide](</docs/en/agent-sdk/sessions>) \- Learn about session management * [Permissions](</docs/en/agent-sdk/permissions>) \- Configure tool permissions * [Cost Tracking](</docs/en/agent-sdk/cost-tracking>) \- Monitor API usage
modified
--- a/hosting.md +++ b/hosting.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. + The Claude Agent SDK differs from traditional stateless LLM APIs in that it maintains conversational state and executes commands in a persistent environment. This guide covers the architecture, hosting considerations, and best practices for deploying SDK-based agents in production. For security hardening beyond basic sandboxing (including network controls, credential management, and isolation options), see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>).
modified
--- a/hosting.md +++ b/hosting.md @@ -25,8 +25,8 @@ Each SDK instance requires: * **Runtime dependencies** - * Python 3.10+ (for Python SDK) or Node.js 18+ (for TypeScript SDK) - * Node.js (required by the bundled Claude Code CLI that the SDK spawns; both SDK packages include it, so no separate install is needed) + * Python 3.10+ for the Python SDK, or Node.js 18+ for the TypeScript SDK + * Both SDK packages bundle a native Claude Code binary for the host platform, so no separate Claude Code or Node.js install is needed for the spawned CLI * **Resource allocation** * Recommended: 1GiB RAM, 5GiB of disk, and 1 CPU (vary this based on your task as needed) * **Network access**
added
Show diff (186 lines)
--- a/hosting.md +++ b/hosting.md @@ -0,0 +1,183 @@ +The Claude Agent SDK differs from traditional stateless LLM APIs in that it maintains conversational state and executes commands in a persistent environment. This guide covers the architecture, hosting considerations, and best practices for deploying SDK-based agents in production. + +For security hardening beyond basic sandboxing (including network controls, credential management, and isolation options), see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). + +## + +​ + +Hosting Requirements + +### + +​ + +Container-Based Sandboxing + +For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems. The SDK also supports [programmatic sandbox configuration](</docs/en/agent-sdk/typescript#sandbox-settings>) for command execution. + +### + +​ + +System Requirements + +Each SDK instance requires: + + * **Runtime dependencies** + * Python 3.10+ (for Python SDK) or Node.js 18+ (for TypeScript SDK) + * Node.js (required by the bundled Claude Code CLI that the SDK spawns; both SDK packages include it, so no separate install is needed) + * **Resource allocation** + * Recommended: 1GiB RAM, 5GiB of disk, and 1 CPU (vary this based on your task as needed) + * **Network access** + * Outbound HTTPS to `api.anthropic.com` + * Optional: Access to MCP servers or external tools + +## + +​ + +Understanding the SDK Architecture + +Unlike stateless API calls, the Claude Agent SDK operates as a **long-running process** that: + + * **Executes commands** in a persistent shell environment + * **Manages file operations** within a working directory + * **Handles tool execution** with context from previous interactions + +## + +​ + +Sandbox Provider Options + +Several providers specialize in secure container environments for AI code execution: + + * **[Modal Sandbox](<https://modal.com/docs/guide/sandbox>)** \- [demo implementation](<https://modal.com/docs/examples/claude-slack-gif-creator>) + * **[Cloudflare Sandboxes](<https://github.com/cloudflare/sandbox-sdk>)** + * **[Daytona](<https://www.daytona.io/>)** + * **[E2B](<https://e2b.dev/>)** + * **[Fly Machines](<https://fly.io/docs/machines/>)** + * **[Vercel Sandbox](<https://vercel.com/docs/functions/sandbox>)** + +For self-hosted options (Docker, gVisor, Firecracker) and detailed isolation configuration, see [Isolation Technologies](</docs/en/agent-sdk/secure-deployment#isolation-technologies>). + +## + +​ + +Production Deployment Patterns + +### + +​ + +Pattern 1: Ephemeral Sessions + +Create a new container for each user task, then destroy it when complete. Best for one-off tasks, the user may still interact with the AI while the task is completing, but once completed the container is destroyed. **Examples:** + + * Bug Investigation & Fix: Debug and resolve a specific issue with relevant context + * Invoice Processing: Extract and structure data from receipts/invoices for accounting systems + * Translation Tasks: Translate documents or content batches between languages + * Image/Video Processing: Apply transformations, optimizations, or extract metadata from media files + +### + +​ + +Pattern 2: Long-Running Sessions + +Maintain persistent container instances for long running tasks. Often times running _multiple_ Claude Agent processes inside of the container based on demand. Best for proactive agents that take action without the users input, agents that serve content or agents that process high amounts of messages. **Examples:** + + * Email Agent: Monitors incoming emails and autonomously triages, responds, or takes actions based on content + * Site Builder: Hosts custom websites per user with live editing capabilities served through container ports + * High-Frequency Chat Bots: Handles continuous message streams from platforms like Slack where rapid response times are critical + +### + +​ + +Pattern 3: Hybrid Sessions + +Ephemeral containers that are hydrated with history and state, possibly from a database or from the SDK’s session resumption features. Best for containers with intermittent interaction from the user that kicks off work and spins down when the work is completed but can be continued. **Examples:** + + * Personal Project Manager: Helps manage ongoing projects with intermittent check-ins, maintains context of tasks, decisions, and progress + * Deep Research: Conducts multi-hour research tasks, saves findings and resumes investigation when user returns + * Customer Support Agent: Handles support tickets that span multiple interactions, loads ticket history and customer context + +### + +​ + +Pattern 4: Single Containers + +Run multiple Claude Agent SDK processes in one global container. Best for agents that must collaborate closely together. This is likely the least popular pattern because you will have to prevent agents from overwriting each other. **Examples:** + + * **Simulations** : Agents that interact with each other in simulations such as video games. + +## + +​ + +FAQ + +### + +​ + +How do I communicate with my sandboxes? + +When hosting in containers, expose ports to communicate with your SDK instances. Your application can expose HTTP/WebSocket endpoints for external clients while the SDK runs internally within the container. + +### + +​ + +What is the cost of hosting a container? + +The dominant cost of serving agents is the tokens; containers vary based on what you provision, but a minimum cost is roughly 5 cents per hour running. + +### + +​ + +When should I shut down idle containers vs. keeping them warm? + +This is likely provider dependent, different sandbox providers will let you set different criteria for idle timeouts after which a sandbox might spin down. You will want to tune this timeout based on how frequent you think user response might be. + +### + +​ + +How often should I update the Claude Code CLI? + +The Claude Code CLI is versioned with semver, so any breaking changes will be versioned. + +### + +​ + +How do I monitor container health and agent performance? + +Since containers are just servers the same logging infrastructure you use for the backend will work for containers. + +### + +​ + +How long can an agent session run before timing out? + +An agent session will not timeout, but consider setting a ‘maxTurns’ property to prevent Claude from getting stuck in a loop. + +## + +​ + +Next Steps + + * [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) \- Network controls, credential management, and isolation hardening + * [TypeScript SDK - Sandbox Settings](</docs/en/agent-sdk/typescript#sandbox-settings>) \- Configure sandbox programmatically + * [Sessions Guide](</docs/en/agent-sdk/sessions>) \- Learn about session management + * [Permissions](</docs/en/agent-sdk/permissions>) \- Configure tool permissions + * [Cost Tracking](</docs/en/agent-sdk/cost-tracking>) \- Monitor API usage + * [MCP Integration](</docs/en/agent-sdk/mcp>) \- Extend with custom tools