Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/claude_agent_sdk/_internal/transport/subprocess_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import platform
import re
import shutil
import unicodedata
from collections.abc import AsyncIterable, AsyncIterator
from contextlib import suppress
from pathlib import Path
Expand All @@ -21,6 +22,7 @@
from ..._errors import CLIJSONDecodeError as SDKJSONDecodeError
from ..._version import __version__
from ...types import ClaudeAgentOptions, SystemPromptFile, SystemPromptPreset
from ..sessions import _canonicalize_path, _sanitize_path
from . import Transport

logger = logging.getLogger(__name__)
Expand All @@ -29,6 +31,20 @@
MINIMUM_CLAUDE_CODE_VERSION = "2.0.0"


def _get_claude_config_dir_for_env(process_env: dict[str, str]) -> Path:
"""Resolve the CLI config directory for a child process environment."""
if config_dir := process_env.get("CLAUDE_CONFIG_DIR"):
return Path(unicodedata.normalize("NFC", config_dir))

if home_dir := process_env.get("HOME"):
return Path(unicodedata.normalize("NFC", home_dir)) / ".claude"

if user_profile := process_env.get("USERPROFILE"):
return Path(unicodedata.normalize("NFC", user_profile)) / ".claude"

return Path.home() / ".claude"
Comment thread
anthony-maio marked this conversation as resolved.


class SubprocessCLITransport(Transport):
"""Subprocess transport using Claude Code CLI."""

Expand Down Expand Up @@ -331,6 +347,20 @@ def _build_command(self) -> list[str]:

return cmd

def _ensure_project_log_dir(self, process_env: dict[str, str]) -> None:
"""Pre-create the CLI project log directory for the child process."""
try:
cwd = self._cwd or str(Path.cwd())
except OSError:
return

project_dir = (
_get_claude_config_dir_for_env(process_env)
/ "projects"
/ _sanitize_path(_canonicalize_path(cwd))
)
project_dir.mkdir(parents=True, exist_ok=True)

async def connect(self) -> None:
"""Start subprocess."""
if self._process:
Expand Down Expand Up @@ -358,6 +388,8 @@ async def connect(self) -> None:
if self._cwd:
process_env["PWD"] = self._cwd

self._ensure_project_log_dir(process_env)

# Pipe stderr if we have a callback OR debug mode is enabled
should_pipe_stderr = (
self._options.stderr is not None
Expand Down
119 changes: 119 additions & 0 deletions tests/test_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import os
import uuid
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch

import anyio
Expand Down Expand Up @@ -565,6 +566,124 @@ async def _test():

anyio.run(_test)

def test_connect_creates_project_log_dir_for_home_override(self, tmp_path):
"""Test that connect pre-creates the CLI project log directory."""

async def _test():
from claude_agent_sdk._internal.sessions import (
_canonicalize_path,
_sanitize_path,
)

home_dir = tmp_path / "agent-home"
home_dir.mkdir()
cwd = tmp_path / "tmp-myapp-agents" / "agent-123" / "workspace"
cwd.mkdir(parents=True)

mock_version_process = MagicMock()
mock_version_process.stdout = MagicMock()
mock_version_process.stdout.receive = AsyncMock(
return_value=b"2.0.0 (Claude Code)"
)
mock_version_process.terminate = MagicMock()
mock_version_process.wait = AsyncMock()

mock_process = MagicMock()
mock_process.stdout = MagicMock()
mock_stdin = MagicMock()
mock_stdin.aclose = AsyncMock()
mock_process.stdin = mock_stdin
mock_process.returncode = None

with patch(
"anyio.open_process", new_callable=AsyncMock
) as mock_open_process:
mock_open_process.side_effect = [mock_version_process, mock_process]

transport = SubprocessCLITransport(
prompt="test",
options=make_options(
cwd=str(cwd),
env={"HOME": str(home_dir)},
),
)

await transport.connect()

expected_dir = (
home_dir
/ ".claude"
/ "projects"
/ _sanitize_path(_canonicalize_path(str(cwd)))
)
assert expected_dir.is_dir()
Comment thread
anthony-maio marked this conversation as resolved.

anyio.run(_test)

def test_connect_prefers_claude_config_dir_for_project_logs(self, tmp_path):
"""Test that CLAUDE_CONFIG_DIR controls the pre-created log directory."""

async def _test():
from claude_agent_sdk._internal.sessions import (
_canonicalize_path,
_sanitize_path,
)

config_dir = tmp_path / "custom-config"
cwd = tmp_path / "workspace"
cwd.mkdir(parents=True)

mock_version_process = MagicMock()
mock_version_process.stdout = MagicMock()
mock_version_process.stdout.receive = AsyncMock(
return_value=b"2.0.0 (Claude Code)"
)
mock_version_process.terminate = MagicMock()
mock_version_process.wait = AsyncMock()

mock_process = MagicMock()
mock_process.stdout = MagicMock()
mock_stdin = MagicMock()
mock_stdin.aclose = AsyncMock()
mock_process.stdin = mock_stdin
mock_process.returncode = None

with patch(
"anyio.open_process", new_callable=AsyncMock
) as mock_open_process:
mock_open_process.side_effect = [mock_version_process, mock_process]

transport = SubprocessCLITransport(
prompt="test",
options=make_options(
cwd=str(cwd),
env={"CLAUDE_CONFIG_DIR": str(config_dir)},
),
)

await transport.connect()

expected_dir = (
config_dir / "projects" / _sanitize_path(_canonicalize_path(str(cwd)))
)
assert expected_dir.is_dir()
Comment thread
anthony-maio marked this conversation as resolved.

anyio.run(_test)

def test_claude_config_dir_env_paths_are_normalized(self):
"""Config dir resolution normalizes env paths to NFC."""
import unicodedata

from claude_agent_sdk._internal.transport.subprocess_cli import (
_get_claude_config_dir_for_env,
)

decomposed = unicodedata.normalize("NFD", "C:/tmp/cafe\u0301")

resolved = _get_claude_config_dir_for_env({"CLAUDE_CONFIG_DIR": decomposed})

assert resolved == Path(unicodedata.normalize("NFC", decomposed))

def test_build_command_with_sandbox_only(self):
"""Test building CLI command with sandbox settings (no existing settings)."""
import json
Expand Down