When the SDK serves as a server agent for multiple users, session confusion and concatenation issues arise due to different sessions for different users
When the SDK serves as a server agent for multiple users, session confusion and concatenation issues arise due to different sessions for different users
I looked into how session isolation works in the SDK and I believe the issue stems from the fact that the CLI subprocess determines session identity based on the working directory (cwd) and an auto-generated or reused session ID, with session files stored under ~/.claude/projects/<sanitized-cwd>/<session_id>.jsonl. When multiple users share the same server process, there are two vectors for session confusion:
-
Shared session ID via
--continueor--resume: If the SDK is used withcontinue_conversation=True, the CLI resumes the most recent session in thatcwd, which in a multi-user server means one user could resume another user's session. -
Shared
~/.claudedirectory: All CLI subprocess instances write to the same~/.claude/projects/tree. Without per-user isolation of the Claude home directory, session files from different users can collide if they share the samecwd.
Proposed fix (two layers):
Layer 1 - Per-user session directory isolation: Set the CLAUDE_CONFIG_DIR environment variable (or equivalent) to a unique per-user path before spawning the subprocess. This can be done in SubprocessCLITransport.connect() by injecting it into process_env. The SDK could accept a config_dir option in ClaudeAgentOptions, or the caller could pass it via the existing env dict:
options = ClaudeAgentOptions(
env={"CLAUDE_CONFIG_DIR": f"/tmp/claude-sessions/{user_id}"}
)
Layer 2 - Document the multi-tenant pattern: Even with directory isolation, ClaudeSDKClient instances should not be shared across users. Each user request should get its own ClaudeSDKClient with its own subprocess. The SDK docs should explicitly call out this pattern for server deployments.
If the CLI does not currently support CLAUDE_CONFIG_DIR, an alternative would be to set unique cwd values per user to force distinct session directories, though that is a less clean solution.
Would this approach work? Happy to submit a PR if so.
This appears to be a duplicate of #560, which covers the same underlying issue: ClaudeSDKClient does not isolate context across different session_id values in a single long-lived client. Both issues describe session confusion when the SDK is used as a server agent for multiple users.
Closing in favor of #560 — please follow that issue for updates.