Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Refactor CLI surfaces around launchers and managed Claude (#861)

Ali Khokhar6bee3104fe5f
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 91063df0..bf15601f 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -128,8 +128,8 @@ Console scripts are registered in [pyproject.toml](pyproject.toml):
- `fcc-server` and `free-claude-code` call `cli.entrypoints:serve`.
- `fcc-init` calls `cli.entrypoints:init`.
-- `fcc-claude` calls `cli.entrypoints:launch_claude`.
-- `fcc-codex` calls `cli.entrypoints:launch_codex`.
+- `fcc-claude` calls `cli.launchers.claude:launch`.
+- `fcc-codex` calls `cli.launchers.codex:launch`.
[scripts/install.sh](scripts/install.sh) and [scripts/install.ps1](scripts/install.ps1)
install or update the uv tool plus optional voice extras. [scripts/uninstall.sh](scripts/uninstall.sh)
@@ -442,25 +442,19 @@ conversion. Forced `web_search` or `web_fetch` requests are handled locally when
`ENABLE_WEB_SERVER_TOOLS` is true; otherwise OpenAI-chat upstreams reject them
and native Anthropic Messages transports may receive them.
-## CLI Launchers And Client Adapter Boundary
+## CLI Launchers And Managed Claude
-[cli/adapters/base.py](cli/adapters/base.py) defines `ClientCliAdapter`, the
-boundary for building subprocess commands, building launcher environments,
-parsing stdout lines, and extracting persistent session IDs.
-
-[cli/adapters/claude.py](cli/adapters/claude.py) implements the Claude Code
-adapter:
+[cli/launchers/claude.py](cli/launchers/claude.py) owns the installed
+`fcc-claude` launcher:
- `fcc-claude` strips inherited `ANTHROPIC_*` variables, sets
`ANTHROPIC_BASE_URL`, enables gateway model discovery, configures the
auto-compact window, and always sets `ANTHROPIC_AUTH_TOKEN`. Blank proxy auth
becomes the local-only `fcc-no-auth` sentinel so Claude Code reaches the proxy
instead of stopping at its login gate.
-- Managed task invocations set `ANTHROPIC_API_URL`, `ANTHROPIC_BASE_URL`,
- gateway model discovery, non-interactive terminal settings, optional
- `--resume`, optional `--fork-session`, and `--output-format stream-json`.
-[cli/adapters/codex.py](cli/adapters/codex.py) implements the Codex adapter:
+[cli/launchers/codex.py](cli/launchers/codex.py) owns the installed
+`fcc-codex` launcher:
- `fcc-codex` strips official OpenAI and Codex credential variables.
- It creates an ephemeral `fcc` model provider with `wire_api = "responses"` and
@@ -470,15 +464,18 @@ adapter:
native `/model` picker lists FCC provider slugs. Catalog generation is
fail-open: launch continues with a warning if the catalog cannot be prepared.
- It stores the proxy auth token in `FCC_CODEX_API_KEY` for Codex to read.
-- Managed task invocations use Codex JSON output and map Responses events into
- the messaging parser event shape.
-- Codex `response.reasoning_text.delta` events are converted into the shared
- Anthropic-style `thinking_delta` parser shape; summary reasoning events remain
- raw unless a future feature selects them as the proxy wire shape.
-[cli/manager.py](cli/manager.py) coordinates multiple `CLISession` instances so
-separate conversations can run in separate client CLI processes while replies
-reuse or fork existing sessions.
+[cli/managed/](cli/managed/) owns managed Claude Code subprocesses used by
+Discord and Telegram messaging. Managed task invocations set
+`ANTHROPIC_API_URL`, `ANTHROPIC_BASE_URL`, gateway model discovery,
+non-interactive terminal settings, optional `--resume`, optional
+`--fork-session`, and `--output-format stream-json`. The managed session parser
+extracts persistent Claude session IDs and yields Claude stream-json events to
+the messaging event parser.
+
+Codex is supported through `fcc-codex` and Codex extensions. FCC does not keep an
+internal managed-Codex session runner because no user-facing messaging setting
+selects Codex for Discord or Telegram.
## Messaging Architecture
@@ -536,8 +533,8 @@ sequenceDiagram
participant Intake as MessagingTurnIntake
participant Queue as TreeQueueManager
participant Runner as MessagingNodeRunner
- participant Manager as CLISessionManager
- participant CLI as ClientCLI
+ participant Manager as ManagedClaudeSessionManager
+ participant CLI as ClaudeCode
participant Proxy as LocalProxy
Platform->>Workflow: IncomingMessage
@@ -621,16 +618,18 @@ when maintainers want branch-level assurance.
updated in place.
5. Add tests under [tests/api/](tests/api/) or [tests/config/](tests/config/).
-### Add A Client Adapter
+### Add Or Change A Client Surface
-1. Implement the `ClientCliAdapter` protocol from
- [cli/adapters/base.py](cli/adapters/base.py).
-2. Register selection behavior in [cli/adapters/registry.py](cli/adapters/registry.py).
-3. Ensure launcher env construction strips conflicting upstream credentials.
-4. Ensure managed task parsing emits the event shapes expected by
+1. For an installed wrapper, add or update a launcher under
+ [cli/launchers/](cli/launchers/) and keep credential stripping local to that
+ client.
+2. For messaging-managed execution, update [cli/managed/](cli/managed/) only
+ when Discord or Telegram should actually run a different managed client.
+3. Ensure managed task parsing emits the event shapes expected by
[messaging/event_parser.py](messaging/event_parser.py) and
[messaging/node_event_pipeline.py](messaging/node_event_pipeline.py).
-5. Add CLI adapter and session-manager tests under [tests/cli/](tests/cli/).
+4. Add launcher, managed-session, and customer-flow tests under
+ [tests/cli/](tests/cli/) and [tests/messaging/](tests/messaging/).
### Add A Messaging Platform
diff --git a/api/runtime.py b/api/runtime.py
index 3bb197a1..d8df1283 100644
--- a/api/runtime.py
+++ b/api/runtime.py
@@ -17,7 +17,7 @@ from providers.exceptions import ServiceUnavailableError
from providers.registry import ProviderRegistry
if TYPE_CHECKING:
- from cli.manager import CLISessionManager
+ from cli.managed import ManagedClaudeSessionManager
from messaging.platforms.base import MessagingPlatform
from messaging.session import SessionStore
from messaging.workflow import MessagingWorkflow
@@ -90,7 +90,7 @@ class AppRuntime:
_provider_registry: ProviderRegistry | None = field(default=None, init=False)
messaging_platform: MessagingPlatform | None = None
messaging_workflow: MessagingWorkflow | None = None
- cli_manager: CLISessionManager | None = None
+ cli_manager: ManagedClaudeSessionManager | None = None
@classmethod
def for_app(
@@ -224,7 +224,7 @@ class AppRuntime:
)
async def _start_messaging_workflow(self) -> None:
- from cli.manager import CLISessionManager
+ from cli.managed import ManagedClaudeSessionManager
from messaging.session import SessionStore
from messaging.workflow import MessagingWorkflow
@@ -244,7 +244,7 @@ class AppRuntime:
os.path.join(self.settings.claude_workspace, "plans")
)
plans_directory = os.path.relpath(plans_dir_abs, workspace)
- self.cli_manager = CLISessionManager(
+ self.cli_manager = ManagedClaudeSessionManager(
workspace_path=workspace,
api_url=api_url,
allowed_dirs=allowed_dirs,
diff --git a/cli/__init__.py b/cli/__init__.py
index 2df9787d..aeec27b2 100644
--- a/cli/__init__.py
+++ b/cli/__init__.py
@@ -1,6 +1,5 @@
-"""CLI integration for Claude Code."""
+"""CLI integration for installed launchers and managed Claude Code."""
-from .manager import CLISessionManager
-from .session import CLISession
+from .managed import ManagedClaudeSession, ManagedClaudeSessionManager
-__all__ = ["CLISession", "CLISessionManager"]
+__all__ = ["ManagedClaudeSession", "ManagedClaudeSessionManager"]
diff --git a/cli/adapters/__init__.py b/cli/adapters/__init__.py
deleted file mode 100644
index 0777e59b..00000000
--- a/cli/adapters/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""Client CLI adapter implementations."""
-
-from .claude import CLAUDE_CLI_ADAPTER, ClaudeCliAdapter
-from .codex import CODEX_CLI_ADAPTER, CodexCliAdapter
-from .registry import DEFAULT_CLIENT_CLI_ID, get_client_cli_adapter
-
-__all__ = [
- "CLAUDE_CLI_ADAPTER",
- "CODEX_CLI_ADAPTER",
- "DEFAULT_CLIENT_CLI_ID",
- "ClaudeCliAdapter",
- "CodexCliAdapter",
- "get_client_cli_adapter",
-]
diff --git a/cli/adapters/base.py b/cli/adapters/base.py
deleted file mode 100644
index b6452dec..00000000
--- a/cli/adapters/base.py
+++ /dev/null
@@ -1,92 +0,0 @@
-"""Shared contracts for client CLI subprocess adapters."""
-
-from __future__ import annotations
-
-from collections.abc import Iterable, Mapping
-from dataclasses import dataclass, field
-from typing import Any, Protocol
-
-
-@dataclass(frozen=True, slots=True)
-class CliTaskRequest:
- """A single prompt execution request for a managed client CLI process."""
-
- prompt: str
- session_id: str | None = None
- fork_session: bool = False
-
-
-@dataclass(frozen=True, slots=True)
-class CliInvocation:
- """Concrete subprocess invocation assembled by a client CLI adapter."""
-
- argv: tuple[str, ...]
- env: dict[str, str]
- cwd: str
- trace_metadata: dict[str, Any] = field(default_factory=dict)
-
-
-@dataclass(slots=True)
-class CliParseState:
- """Mutable line-parser state for a single client CLI process run."""
-
- log_raw_cli_diagnostics: bool = False
- session_id_extracted: bool = False
- responses_seen_output_keys: set[str] = field(default_factory=set)
- responses_current_output_scope: str | None = None
- responses_next_implicit_output_scope: int = 0
-
-
-class ClientCliAdapter(Protocol):
- """Adapter boundary for client CLI command/env construction and output parsing."""
-
- id: str
- display_name: str
- default_binary: str
- install_hint: str
- trace_stage: str
- process_launch_event: str
- trace_source: str
-
- def build_task_invocation(
- self,
- *,
- config: Any,
- request: CliTaskRequest,
- base_env: Mapping[str, str],
- ) -> CliInvocation:
- """Build the subprocess invocation for a managed task run."""
- ...
-
- def parse_stdout_line(self, line: str, state: CliParseState) -> Iterable[Any]:
- """Parse one stdout line into parser-ready internal CLI events."""
- ...
-
- def extract_session_id(self, event: Any) -> str | None:
- """Extract a persistent client CLI session id from a parsed event."""
- ...
-
- def get_launcher_binary_name(self, settings: Any) -> str:
- """Return the configured executable name for a wrapper entrypoint."""
- ...
-
- def build_launcher_command(
- self,
- *,
- binary_path: str,
- argv: Iterable[str],
- settings: Any,
- proxy_root_url: str,
- ) -> list[str]:
- """Build the wrapper subprocess command for a client CLI launch."""
- ...
-
- def build_launcher_env(
- self,
- *,
- proxy_root_url: str,
- auth_token: str,
- base_env: Mapping[str, str],
- ) -> dict[str, str]:
- """Build environment variables for a wrapper-launched client CLI."""
- ...
diff --git a/cli/adapters/claude.py b/cli/adapters/claude.py
deleted file mode 100644
index 213a59d5..00000000
--- a/cli/adapters/claude.py
+++ /dev/null
@@ -1,234 +0,0 @@
-"""Claude Code client CLI adapter."""
-
-from __future__ import annotations
-
-import json
-from collections.abc import Iterable, Mapping
-from typing import Any
-
-from loguru import logger
-
-from .base import CliInvocation, CliParseState, CliTaskRequest
-
-_AUTO_COMPACT_WINDOW = "190000"
-_NO_AUTH_SENTINEL = "fcc-no-auth"
-
-
-class ClaudeCliAdapter:
- """Client CLI adapter for Claude Code."""
-
- id = "claude"
- display_name = "Claude Code"
- default_binary = "claude"
- install_hint = "Install Claude Code with: npm install -g @anthropic-ai/claude-code"
- trace_stage = "claude_cli"
- process_launch_event = "claude_cli.process.launch"
- trace_source = "claude_cli"
-
- def build_task_invocation(
- self,
- *,
- config: Any,
- request: CliTaskRequest,
- base_env: Mapping[str, str],
- ) -> CliInvocation:
- """Build a Claude Code stream-json subprocess invocation."""
-
- env = self._task_env(
- api_url=config.api_url,
- auth_token=config.auth_token,
- base_env=base_env,
- )
- cmd = self._task_command(
- claude_bin=config.claude_bin,
- prompt=request.prompt,
- session_id=request.session_id,
- fork_session=request.fork_session,
- allowed_dirs=config.allowed_dirs,
- plans_directory=config.plans_directory,
- )
-
- resume_session_id = (
- request.session_id
- if request.session_id and not request.session_id.startswith("pending_")
- else None
- )
- return CliInvocation(
- argv=tuple(cmd),
- env=env,
- cwd=config.workspace_path,
- trace_metadata={
- "client_cli_id": self.id,
- "resume_session_id": resume_session_id,
- "fork_session": request.fork_session,
- "prompt": request.prompt,
- "cwd": config.workspace_path,
- "claude_binary": config.claude_bin,
- "cli_argv": cmd,
- },
- )
-
- def parse_stdout_line(self, line: str, state: CliParseState) -> Iterable[Any]:
- """Parse one Claude Code JSONL line into existing parser-ready events."""
-
- try:
- event = json.loads(line)
- except json.JSONDecodeError:
- if state.log_raw_cli_diagnostics:
- logger.debug("Non-JSON output: {}", line)
- else:
- logger.debug("Non-JSON CLI line: char_len={}", len(line))
- yield {"type": "raw", "content": line}
- return
-
- if not state.session_id_extracted:
- extracted_id = self.extract_session_id(event)
- if extracted_id:
- state.session_id_extracted = True
- logger.info(f"Extracted session ID: {extracted_id}")
- yield {"type": "session_info", "session_id": extracted_id}
-
- yield event
-
- def extract_session_id(self, event: Any) -> str | None:
- """Extract a Claude Code session ID from supported event shapes."""
-
- if not isinstance(event, dict):
- return None
-
- if session_id := _string_value(event.get("session_id")):
- return session_id
- if session_id := _string_value(event.get("sessionId")):
- return session_id
-
- for key in ["init", "system", "result", "metadata"]:
- nested = event.get(key)
- if not isinstance(nested, dict):
- continue
- if session_id := _string_value(nested.get("session_id")):
- return session_id
- if session_id := _string_value(nested.get("sessionId")):
- return session_id
-
- conv = event.get("conversation")
- if isinstance(conv, dict):
- return _string_value(conv.get("id"))
-
- return None
-
- def get_launcher_binary_name(self, settings: Any) -> str:
- """Return the configured Claude Code binary name."""
-
- configured = getattr(settings, "claude_cli_bin", "")
- return configured or self.default_binary
-
- def build_launcher_command(
- self,
- *,
- binary_path: str,
- argv: Iterable[str],
- settings: Any,
- proxy_root_url: str,
- ) -> list[str]:
- """Return the Claude wrapper command without changing user arguments."""
-
- return [binary_path, *argv]
-
- def build_launcher_env(
- self,
- *,
- proxy_root_url: str,
- auth_token: str,
- base_env: Mapping[str, str],
- ) -> dict[str, str]:
- """Return a Claude Code environment that targets the local proxy."""
-
- env = {
- key: value
- for key, value in base_env.items()
- if not key.startswith("ANTHROPIC_")
- }
- env["ANTHROPIC_BASE_URL"] = proxy_root_url
- env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"
- env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = _AUTO_COMPACT_WINDOW
- env["ANTHROPIC_AUTH_TOKEN"] = _claude_auth_token(auth_token)
- return env
-
- def _task_env(
- self,
- *,
- api_url: str,
- auth_token: str,
- base_env: Mapping[str, str],
- ) -> dict[str, str]:
- env = dict(base_env)
- env["ANTHROPIC_API_URL"] = api_url
- if api_url.endswith("/v1"):
- env["ANTHROPIC_BASE_URL"] = api_url[:-3]
- else:
- env["ANTHROPIC_BASE_URL"] = api_url
- env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"
- env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = _AUTO_COMPACT_WINDOW
- env.pop("ANTHROPIC_API_KEY", None)
- env["ANTHROPIC_AUTH_TOKEN"] = _claude_auth_token(auth_token)
-
- env["TERM"] = "dumb"
- env["PYTHONIOENCODING"] = "utf-8"
- return env
-
- def _task_command(
- self,
- *,
- claude_bin: str,
- prompt: str,
- session_id: str | None,
- fork_session: bool,
- allowed_dirs: list[str],
- plans_directory: str | None,
- ) -> list[str]:
- if session_id and not session_id.startswith("pending_"):
- cmd = [
- claude_bin,
- "--resume",
- session_id,
- ]
- if fork_session:
- cmd.append("--fork-session")
- cmd += [
- "-p",
- prompt,
- "--output-format",
- "stream-json",
- "--dangerously-skip-permissions",
- "--verbose",
- ]
- else:
- cmd = [
- claude_bin,
- "-p",
- prompt,
- "--output-format",
- "stream-json",
- "--dangerously-skip-permissions",
- "--verbose",
- ]
-
- for directory in allowed_dirs:
- cmd.extend(["--add-dir", directory])
-
- if plans_directory is not None:
- settings_json = json.dumps({"plansDirectory": plans_directory})
- cmd.extend(["--settings", settings_json])
-
- return cmd
-
-
-def _string_value(value: Any) -> str | None:
- return value if isinstance(value, str) else None
-
-
-def _claude_auth_token(auth_token: str) -> str:
- return auth_token.strip() or _NO_AUTH_SENTINEL
-
-
-CLAUDE_CLI_ADAPTER = ClaudeCliAdapter()
diff --git a/cli/adapters/codex.py b/cli/adapters/codex.py
deleted file mode 100644
index d123357a..00000000
--- a/cli/adapters/codex.py
+++ /dev/null
@@ -1,525 +0,0 @@
-"""Codex CLI adapter."""
-
-from __future__ import annotations
-
-import json
-from collections.abc import Iterable, Mapping
-from typing import Any, cast
-
-from loguru import logger
-
-from .base import CliInvocation, CliParseState, CliTaskRequest
-
-_CODEX_AUTH_ENV_KEY = "FCC_CODEX_API_KEY"
-_STRIPPED_CODEX_ENV_KEYS = frozenset(
- {
- "OPENAI_API_KEY",
- "OPENAI_BASE_URL",
- "OPENAI_API_BASE",
- "OPENAI_ORG_ID",
- "OPENAI_ORGANIZATION",
- "CODEX_API_KEY",
- _CODEX_AUTH_ENV_KEY,
- }
-)
-
-
-class CodexCliAdapter:
- """Client CLI adapter for OpenAI Codex CLI."""
-
- id = "codex"
- display_name = "Codex CLI"
- default_binary = "codex"
- install_hint = "Install Codex with: npm install -g @openai/codex"
- trace_stage = "codex_cli"
- process_launch_event = "codex_cli.process.launch"
- trace_source = "codex_cli"
-
- def build_task_invocation(
- self,
- *,
- config: Any,
- request: CliTaskRequest,
- base_env: Mapping[str, str],
- ) -> CliInvocation:
- """Build a Codex JSONL subprocess invocation for managed messaging."""
-
- env = self._task_env(
- api_url=config.api_url,
- auth_token=config.auth_token,
- base_env=base_env,
- )
- codex_bin = getattr(config, "codex_bin", None) or self.default_binary
- cmd = self._task_command(
- codex_bin=codex_bin,
- prompt=request.prompt,
- session_id=request.session_id,
- fork_session=request.fork_session,
- api_url=config.api_url,
- allowed_dirs=config.allowed_dirs,
- workspace_path=config.workspace_path,
- )
- resume_session_id = (
- request.session_id
- if request.session_id
- and not request.session_id.startswith("pending_")
- and not request.fork_session
- else None
- )
- return CliInvocation(
- argv=tuple(cmd),
- env=env,
- cwd=config.workspace_path,
- trace_metadata={
- "client_cli_id": self.id,
- "resume_session_id": resume_session_id,
- "fork_session": request.fork_session,
- "prompt": request.prompt,
- "cwd": config.workspace_path,
- "codex_binary": codex_bin,
- "cli_argv": cmd,
- },
- )
-
- def parse_stdout_line(self, line: str, state: CliParseState) -> Iterable[Any]:
- """Parse one Codex JSONL line into existing parser-ready events."""
-
- try:
- event = json.loads(line)
- except json.JSONDecodeError:
- if state.log_raw_cli_diagnostics:
- logger.debug("Non-JSON Codex output: {}", line)
- else:
- logger.debug("Non-JSON Codex CLI line: char_len={}", len(line))
- yield {"type": "raw", "content": line}
- return
-
- if not state.session_id_extracted:
- extracted_id = self.extract_session_id(event)
- if extracted_id:
- state.session_id_extracted = True
- logger.info("Extracted Codex session ID: {}", extracted_id)
- yield {"type": "session_info", "session_id": extracted_id}
-
- mapped = list(_codex_event_to_parser_events(event, state))
- if mapped:
- yield from mapped
- return
- if event.get("type") in {"response.output_item.done", "response.completed"}:
- return
-
- yield {"type": "raw", "content": line}
-
- def extract_session_id(self, event: Any) -> str | None:
- """Extract a Codex session or thread id from supported event shapes."""
-
- if not isinstance(event, dict):
- return None
- for key in ("session_id", "sessionId", "thread_id", "threadId"):
- if session_id := _string_value(event.get(key)):
- return session_id
- for key in ("thread", "session", "conversation", "metadata"):
- nested = event.get(key)
- if not isinstance(nested, dict):
- continue
- for nested_key in ("id", "session_id", "thread_id", "conversation_id"):
- if session_id := _string_value(nested.get(nested_key)):
- return session_id
- return None
-
- def get_launcher_binary_name(self, settings: Any) -> str:
- """Return the configured Codex binary name."""
-
- configured = getattr(settings, "codex_cli_bin", "")
- return configured or self.default_binary
-
- def build_launcher_command(
- self,
- *,
- binary_path: str,
- argv: Iterable[str],
- settings: Any,
- proxy_root_url: str,
- ) -> list[str]:
- """Return a Codex command with ephemeral FCC provider config."""
-
- return [
- binary_path,
- *self._codex_config_args(
- api_url=_ensure_v1_url(proxy_root_url),
- model=getattr(settings, "model", None),
- ),
- *argv,
- ]
-
- def build_launcher_env(
- self,
- *,
- proxy_root_url: str,
- auth_token: str,
- base_env: Mapping[str, str],
- ) -> dict[str, str]:
- """Return a Codex environment that targets the local proxy provider."""
-
- env = _base_codex_env(base_env)
- env[_CODEX_AUTH_ENV_KEY] = auth_token.strip() or "fcc-no-auth"
- return env
-
- def build_model_catalog_config_args(self, catalog_path: str) -> list[str]:
- """Return Codex config args for a generated model catalog."""
-
- return ["-c", _toml_assignment("model_catalog_json", catalog_path)]
-
- def _task_env(
- self,
- *,
- api_url: str,
- auth_token: str,
- base_env: Mapping[str, str],
- ) -> dict[str, str]:
- env = _base_codex_env(base_env)
- env[_CODEX_AUTH_ENV_KEY] = auth_token.strip() or "fcc-no-auth"
- env["TERM"] = "dumb"
- env["PYTHONIOENCODING"] = "utf-8"
- return env
-
- def _task_command(
- self,
- *,
- codex_bin: str,
- prompt: str,
- session_id: str | None,
- fork_session: bool,
- api_url: str,
- allowed_dirs: list[str],
- workspace_path: str,
- ) -> list[str]:
- common_args = [
- "--json",
- "--skip-git-repo-check",
- "--dangerously-bypass-approvals-and-sandbox",
- *self._codex_config_args(api_url=api_url),
- ]
- if session_id and not session_id.startswith("pending_") and not fork_session:
- return [
- codex_bin,
- "exec",
- "resume",
- *common_args,
- session_id,
- prompt,
- ]
-
- cmd = [
- codex_bin,
- "exec",
- *common_args,
- "-C",
- workspace_path,
- ]
- for directory in allowed_dirs:
- cmd.extend(["--add-dir", directory])
- cmd.append(prompt)
- return cmd
-
- def _codex_config_args(
- self, *, api_url: str, model: str | None = None
- ) -> list[str]:
- args = [
- "-c",
- _toml_assignment("model_provider", "fcc"),
- "-c",
- _toml_assignment("model_providers.fcc.name", "Free Claude Code"),
- "-c",
- _toml_assignment("model_providers.fcc.base_url", _ensure_v1_url(api_url)),
- "-c",
- _toml_assignment("model_providers.fcc.env_key", _CODEX_AUTH_ENV_KEY),
- "-c",
- _toml_assignment("model_providers.fcc.wire_api", "responses"),
- ]
- if model:
- args.extend(["-c", _toml_assignment("model", model)])
- return args
-
-
-def _codex_event_to_parser_events(
- event: dict[str, Any], state: CliParseState
-) -> Iterable[dict[str, Any]]:
- event_type = event.get("type")
- if event_type in {"error", "turn.failed"}:
- yield {"type": "error", "error": {"message": _event_message(event)}}
- return
- if event_type == "response.failed":
- _finish_response_scope(state)
- yield {"type": "error", "error": {"message": _event_message(event)}}
- return
- if event_type == "response.output_text.delta":
- _mark_streamed_message_item_seen(event, state)
- yield {
- "type": "content_block_delta",
- "index": 0,
- "delta": {"type": "text_delta", "text": str(event.get("delta", ""))},
- }
- return
- if event_type == "response.reasoning_text.delta":
- yield {
- "type": "content_block_delta",
- "index": _event_output_index(event),
- "delta": {
- "type": "thinking_delta",
- "thinking": str(event.get("delta", "")),
- },
- }
- return
- if event_type in {"agent_message", "assistant_message"}:
- text = _event_message(event)
- if text:
- yield {
- "type": "assistant",
- "message": {"content": [{"type": "text", "text": text}]},
- }
- return
- if event_type == "response.output_item.done":
- item = event.get("item")
- if isinstance(item, dict) and _mark_response_item_unseen(
- item,
- state,
- response_scope=_response_scope(event, state),
- output_index=_optional_event_output_index(event),
- ):
- yield from _responses_item_to_parser_events(item)
- return
- if event_type == "response.completed":
- response = event.get("response")
- output = response.get("output") if isinstance(response, dict) else None
- response_scope = _response_scope(event, state)
- if isinstance(output, list):
- for output_index, item in enumerate(output):
- if not isinstance(item, dict):
- continue
- item_mapping = cast(Mapping[str, Any], item)
- if _mark_response_item_unseen(
- item_mapping,
- state,
- response_scope=response_scope,
- output_index=output_index,
- ):
- yield from _responses_item_to_parser_events(item_mapping)
- _finish_response_scope(state)
- return
-
-
-def _responses_item_to_parser_events(
- item: Mapping[str, Any],
-) -> Iterable[dict[str, Any]]:
- item_type = item.get("type")
- if item_type == "message":
- text_parts: list[str] = []
- content = item.get("content")
- if isinstance(content, list):
- text_parts.extend(
- str(part.get("text", ""))
- for part in content
- if isinstance(part, dict) and part.get("type") == "output_text"
- )
- text = "".join(text_parts)
- if text:
- yield {
- "type": "assistant",
- "message": {"content": [{"type": "text", "text": text}]},
- }
- return
- if item_type == "function_call":
- yield {
- "type": "assistant",
- "message": {
- "content": [
- {
- "type": "tool_use",
- "id": str(item.get("call_id", item.get("id", ""))),
- "name": str(item.get("name", "")),
- "input": _safe_json_object(item.get("arguments")),
- }
- ]
- },
- }
- return
- if item_type == "custom_tool_call":
- yield {
- "type": "assistant",
- "message": {
- "content": [
- {
- "type": "tool_use",
- "id": str(item.get("call_id", item.get("id", ""))),
- "name": str(item.get("name", "")),
- "input": {"input": _custom_tool_input_text(item.get("input"))},
- }
- ]
- },
- }
-
-
-def _event_message(event: Mapping[str, Any]) -> str:
- for key in ("message", "text", "content", "error"):
- value = event.get(key)
- if isinstance(value, str):
- return value
- if isinstance(value, dict) and isinstance(value.get("message"), str):
- return str(value["message"])
- response = event.get("response")
- if isinstance(response, dict):
- error = response.get("error")
- if isinstance(error, dict) and isinstance(error.get("message"), str):
- return str(error["message"])
- return ""
-
-
-def _event_output_index(event: Mapping[str, Any]) -> int:
- value = event.get("output_index")
- return value if isinstance(value, int) else 0
-
-
-def _optional_event_output_index(event: Mapping[str, Any]) -> int | None:
- value = event.get("output_index")
- return value if isinstance(value, int) else None
-
-
-def _mark_response_item_unseen(
- item: Mapping[str, Any],
- state: CliParseState,
- *,
- response_scope: str | None = None,
- output_index: int | None = None,
-) -> bool:
- item_key = _response_item_key(
- item,
- response_scope=response_scope,
- output_index=output_index,
- )
- if item_key is None:
- return True
- if item_key in state.responses_seen_output_keys:
- return False
- state.responses_seen_output_keys.add(item_key)
- return True
-
-
-def _mark_streamed_message_item_seen(
- event: Mapping[str, Any], state: CliParseState
-) -> None:
- item_id = event.get("item_id")
- if isinstance(item_id, str) and item_id:
- state.responses_seen_output_keys.add(f"message:{item_id}")
- output_index = _optional_event_output_index(event)
- if output_index is not None:
- state.responses_seen_output_keys.add(
- _response_output_index_key(
- "message",
- _response_scope(event, state),
- output_index,
- )
- )
-
-
-def _response_item_key(
- item: Mapping[str, Any],
- *,
- response_scope: str | None = None,
- output_index: int | None = None,
-) -> str | None:
- item_type = item.get("type")
- if (
- item_type == "message"
- and response_scope is not None
- and output_index is not None
- ):
- return _response_output_index_key(item_type, response_scope, output_index)
- for key in ("id", "call_id"):
- value = item.get(key)
- if isinstance(value, str) and value:
- return f"{item_type}:{value}"
- return None
-
-
-def _response_scope(event: Mapping[str, Any], state: CliParseState) -> str:
- if state.responses_current_output_scope is not None:
- return state.responses_current_output_scope
- response_id = _event_response_id(event)
- if response_id is not None:
- scope = f"response:{response_id}"
- else:
- scope = f"implicit:{state.responses_next_implicit_output_scope}"
- state.responses_next_implicit_output_scope += 1
- state.responses_current_output_scope = scope
- return scope
-
-
-def _finish_response_scope(state: CliParseState) -> None:
- state.responses_current_output_scope = None
-
-
-def _event_response_id(event: Mapping[str, Any]) -> str | None:
- for key in ("response_id", "responseId"):
- value = event.get(key)
- if isinstance(value, str) and value:
- return value
- response = event.get("response")
- if isinstance(response, dict):
- value = response.get("id")
- if isinstance(value, str) and value:
- return value
- return None
-
-
-def _response_output_index_key(
- item_type: object, response_scope: str, output_index: int
-) -> str:
- return f"{item_type}_output_index:{response_scope}:{output_index}"
-
-
-def _safe_json_object(value: Any) -> dict[str, Any]:
- if isinstance(value, dict):
- return value
- if not isinstance(value, str) or not value:
- return {}
- try:
- parsed = json.loads(value)
- except json.JSONDecodeError:
- return {}
- return parsed if isinstance(parsed, dict) else {}
-
-
-def _custom_tool_input_text(value: Any) -> str:
- if value is None:
- return ""
- if isinstance(value, str):
- return value
- try:
- return json.dumps(value)
- except TypeError:
- return str(value)
-
-
-def _base_codex_env(base_env: Mapping[str, str]) -> dict[str, str]:
- return {
- key: value
- for key, value in base_env.items()
- if key not in _STRIPPED_CODEX_ENV_KEYS and not key.startswith("OPENAI_")
- }
-
-
-def _ensure_v1_url(url: str) -> str:
- stripped = url.rstrip("/")
- return stripped if stripped.endswith("/v1") else f"{stripped}/v1"
-
-
-def _toml_assignment(key: str, value: str) -> str:
- return f"{key}={json.dumps(value)}"
-
-
-def _string_value(value: Any) -> str | None:
- return value if isinstance(value, str) else None
-
-
-CODEX_CLI_ADAPTER = CodexCliAdapter()
diff --git a/cli/adapters/registry.py b/cli/adapters/registry.py
deleted file mode 100644
index 10bfb3c0..00000000
--- a/cli/adapters/registry.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""Internal client CLI adapter registry."""
-
-from __future__ import annotations
-
-from .base import ClientCliAdapter
-from .claude import CLAUDE_CLI_ADAPTER
-from .codex import CODEX_CLI_ADAPTER
-
-DEFAULT_CLIENT_CLI_ID = "claude"
-
-_ADAPTERS: dict[str, ClientCliAdapter] = {
- CLAUDE_CLI_ADAPTER.id: CLAUDE_CLI_ADAPTER,
- CODEX_CLI_ADAPTER.id: CODEX_CLI_ADAPTER,
-}
-
-
-def get_client_cli_adapter(
- client_cli_id: str = DEFAULT_CLIENT_CLI_ID,
-) -> ClientCliAdapter:
- """Return a registered client CLI adapter by id."""
-
- try:
- return _ADAPTERS[client_cli_id]
- except KeyError as exc:
- raise ValueError(f"Unknown client CLI adapter: {client_cli_id}") from exc
diff --git a/cli/claude_env.py b/cli/claude_env.py
new file mode 100644
index 00000000..f942c0c8
--- /dev/null
+++ b/cli/claude_env.py
@@ -0,0 +1,12 @@
+"""Shared Claude Code environment policy for FCC client surfaces."""
+
+from __future__ import annotations
+
+CLAUDE_CODE_AUTO_COMPACT_WINDOW = "190000"
+CLAUDE_NO_AUTH_SENTINEL = "fcc-no-auth"
+
+
+def claude_auth_token(auth_token: str) -> str:
+ """Return the Claude Code auth marker for proxy-auth or no-auth sessions."""
+
+ return auth_token.strip() or CLAUDE_NO_AUTH_SENTINEL
diff --git a/cli/entrypoints.py b/cli/entrypoints.py
index dbbf1ddf..29d16a44 100644
--- a/cli/entrypoints.py
+++ b/cli/entrypoints.py
@@ -2,46 +2,28 @@
from __future__ import annotations
-import json
import os
import shutil
-import subprocess
-import sys
import threading
import time
import webbrowser
-from collections.abc import Mapping, Sequence
from pathlib import Path
-from urllib.error import HTTPError, URLError
-from urllib.request import Request, urlopen
import uvicorn
from api.admin_urls import local_admin_url, local_proxy_root_url
from api.app import GracefulLifespanApp, create_app
-from cli.adapters.base import ClientCliAdapter
-from cli.adapters.claude import CLAUDE_CLI_ADAPTER
-from cli.adapters.codex import CODEX_CLI_ADAPTER
-from cli.codex_model_catalog import (
- build_codex_model_catalog,
- write_codex_model_catalog,
-)
+from cli.launchers.common import preflight_proxy
from cli.process_registry import (
kill_all_best_effort,
- kill_pid_tree_best_effort,
- register_pid,
- unregister_pid,
)
from config.paths import (
- codex_model_catalog_path,
config_dir_path,
legacy_env_paths,
managed_env_path,
)
from config.settings import Settings, get_settings
-PROXY_PREFLIGHT_PATH = "/health"
-PROXY_PREFLIGHT_TIMEOUT_SECONDS = 1.5
SERVER_GRACEFUL_SHUTDOWN_SECONDS = 5
@@ -99,7 +81,7 @@ def _schedule_open_admin_browser(settings: Settings) -> None:
def open_when_ready() -> None:
deadline = time.monotonic() + 30.0
while time.monotonic() < deadline:
- if _preflight_proxy(proxy_root_url) is None:
+ if preflight_proxy(proxy_root_url) is None:
webbrowser.open(admin_url)
return
time.sleep(0.15)
@@ -180,161 +162,3 @@ def _migrate_legacy_env_if_missing() -> Path | None:
return legacy_env
return None
-
-
-def _claude_child_env(
- settings: Settings, base_env: Mapping[str, str]
-) -> dict[str, str]:
- """Return a Claude Code environment that targets this proxy."""
-
- return CLAUDE_CLI_ADAPTER.build_launcher_env(
- proxy_root_url=local_proxy_root_url(settings),
- auth_token=settings.anthropic_auth_token,
- base_env=base_env,
- )
-
-
-def _preflight_proxy(proxy_root_url: str) -> str | None:
- """Return an error message when the local proxy health check is unreachable."""
-
- url = f"{proxy_root_url.rstrip('/')}{PROXY_PREFLIGHT_PATH}"
- request = Request(url, method="GET")
- try:
- with urlopen(request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS) as response:
- status_code = response.getcode()
- except HTTPError as exc:
- return f"returned HTTP {exc.code}"
- except URLError as exc:
- return str(exc.reason)
- except OSError as exc:
- return str(exc)
-
- if not 200 <= status_code < 300:
- return f"returned HTTP {status_code}"
- return None
-
-
-def launch_claude(argv: Sequence[str] | None = None) -> None:
- """Launch Claude Code with Free Claude Code proxy environment variables."""
-
- _launch_client_cli(CLAUDE_CLI_ADAPTER, argv)
-
-
-def launch_codex(argv: Sequence[str] | None = None) -> None:
- """Launch Codex CLI with Free Claude Code proxy configuration."""
-
- _launch_client_cli(CODEX_CLI_ADAPTER, argv)
-
-
-def _launch_client_cli(
- adapter: ClientCliAdapter, argv: Sequence[str] | None = None
-) -> None:
- """Launch a client CLI with Free Claude Code proxy environment variables."""
-
- settings = get_settings()
- proxy_root_url = local_proxy_root_url(settings)
- if error := _preflight_proxy(proxy_root_url):
- print(
- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",
- file=sys.stderr,
- )
- print("Start it in another terminal with: fcc-server", file=sys.stderr)
- raise SystemExit(1)
-
- args = list(sys.argv[1:] if argv is None else argv)
- binary_name = adapter.get_launcher_binary_name(settings)
- client_command = shutil.which(binary_name)
- if client_command is None:
- print(
- f"Could not find {adapter.display_name} command: {binary_name}",
- file=sys.stderr,
- )
- print(adapter.install_hint, file=sys.stderr)
- raise SystemExit(127)
-
- command = adapter.build_launcher_command(
- binary_path=client_command,
- argv=args,
- settings=settings,
- proxy_root_url=proxy_root_url,
- )
- catalog_args = _codex_model_catalog_config_args(adapter, proxy_root_url, settings)
- if catalog_args:
- command = [command[0], *catalog_args, *command[1:]]
- env = adapter.build_launcher_env(
- proxy_root_url=proxy_root_url,
- auth_token=settings.anthropic_auth_token,
- base_env=os.environ,
- )
- process: subprocess.Popen[bytes] | None = None
- try:
- process = subprocess.Popen(command, env=env)
- if process.pid:
- register_pid(process.pid)
- return_code = process.wait()
- except FileNotFoundError:
- print(
- f"Could not find {adapter.display_name} command: {binary_name}",
- file=sys.stderr,
- )
- print(adapter.install_hint, file=sys.stderr)
- raise SystemExit(127) from None
- except KeyboardInterrupt:
- if process is not None and process.pid:
- kill_pid_tree_best_effort(process.pid)
- process.wait()
- raise
- finally:
- if process is not None and process.pid:
- unregister_pid(process.pid)
-
- raise SystemExit(return_code)
-
-
-def _codex_model_catalog_config_args(
- adapter: ClientCliAdapter, proxy_root_url: str, settings: Settings
-) -> list[str]:
- if adapter.id != CODEX_CLI_ADAPTER.id:
- return []
-
- try:
- models_response = _fetch_proxy_models_response(
- proxy_root_url, settings.anthropic_auth_token
- )
- catalog = build_codex_model_catalog(models_response)
- models = catalog.get("models")
- if not isinstance(models, list) or not models:
- print(
- "Free Claude Code warning: Codex model catalog is empty; "
- "launching without model picker catalog.",
- file=sys.stderr,
- )
- return []
- catalog_path = codex_model_catalog_path()
- write_codex_model_catalog(catalog_path, catalog)
- except Exception as exc:
- print(
- "Free Claude Code warning: could not prepare Codex model catalog "
- f"({exc}); launching without model picker catalog.",
- file=sys.stderr,
- )
- return []
-
- return CODEX_CLI_ADAPTER.build_model_catalog_config_args(str(catalog_path))
-
-
-def _fetch_proxy_models_response(
- proxy_root_url: str, auth_token: str
-) -> dict[str, object]:
- url = f"{proxy_root_url.rstrip('/')}/v1/models"
- headers: dict[str, str] = {}
- if token := auth_token.strip():
- headers["X-API-Key"] = token
-
- request = Request(url, headers=headers, method="GET")
- with urlopen(request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS) as response:
- payload = json.loads(response.read().decode("utf-8"))
-
- if not isinstance(payload, dict):
- raise ValueError("model list response was not a JSON object")
- return payload
diff --git a/cli/launchers/__init__.py b/cli/launchers/__init__.py
new file mode 100644
index 00000000..a78dba72
--- /dev/null
+++ b/cli/launchers/__init__.py
@@ -0,0 +1 @@
+"""Installed FCC client CLI launchers."""
diff --git a/cli/launchers/claude.py b/cli/launchers/claude.py
new file mode 100644
index 00000000..33943f14
--- /dev/null
+++ b/cli/launchers/claude.py
@@ -0,0 +1,84 @@
+"""Installed `fcc-claude` launcher."""
+
+from __future__ import annotations
+
+import os
+import sys
+from collections.abc import Mapping, Sequence
+
+from api.admin_urls import local_proxy_root_url
+from cli.claude_env import CLAUDE_CODE_AUTO_COMPACT_WINDOW, claude_auth_token
+from config.settings import Settings, get_settings
+
+from .common import preflight_proxy, resolve_client_binary, run_client_process
+
+_DISPLAY_NAME = "Claude Code"
+_DEFAULT_BINARY = "claude"
+_INSTALL_HINT = "Install Claude Code with: npm install -g @anthropic-ai/claude-code"
+
+
+def launch(argv: Sequence[str] | None = None) -> None:
+ """Launch Claude Code with Free Claude Code proxy environment variables."""
+
+ settings = get_settings()
+ proxy_root_url = local_proxy_root_url(settings)
+ if error := preflight_proxy(proxy_root_url):
+ print(
+ f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",
+ file=sys.stderr,
+ )
+ print("Start it in another terminal with: fcc-server", file=sys.stderr)
+ raise SystemExit(1)
+
+ binary_name = claude_binary_name(settings)
+ binary_path = resolve_client_binary(
+ binary_name=binary_name,
+ display_name=_DISPLAY_NAME,
+ install_hint=_INSTALL_HINT,
+ )
+ args = list(sys.argv[1:] if argv is None else argv)
+ run_client_process(
+ command=build_claude_launcher_command(binary_path=binary_path, argv=args),
+ env=build_claude_launcher_env(
+ proxy_root_url=proxy_root_url,
+ auth_token=settings.anthropic_auth_token,
+ base_env=os.environ,
+ ),
+ binary_name=binary_name,
+ display_name=_DISPLAY_NAME,
+ install_hint=_INSTALL_HINT,
+ )
+
+
+def claude_binary_name(settings: Settings) -> str:
+ """Return the configured Claude Code binary name."""
+
+ return settings.claude_cli_bin or _DEFAULT_BINARY
+
+
+def build_claude_launcher_command(
+ *, binary_path: str, argv: Sequence[str]
+) -> list[str]:
+ """Return the Claude wrapper command without changing user arguments."""
+
+ return [binary_path, *argv]
+
+
+def build_claude_launcher_env(
+ *,
+ proxy_root_url: str,
+ auth_token: str,
+ base_env: Mapping[str, str],
+) -> dict[str, str]:
+ """Return a Claude Code environment that targets the local proxy."""
+
+ env = {
+ key: value
+ for key, value in base_env.items()
+ if not key.startswith("ANTHROPIC_")
+ }
+ env["ANTHROPIC_BASE_URL"] = proxy_root_url
+ env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"
+ env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = CLAUDE_CODE_AUTO_COMPACT_WINDOW
+ env["ANTHROPIC_AUTH_TOKEN"] = claude_auth_token(auth_token)
+ return env
diff --git a/cli/launchers/codex.py b/cli/launchers/codex.py
new file mode 100644
index 00000000..ed8c5ef4
--- /dev/null
+++ b/cli/launchers/codex.py
@@ -0,0 +1,204 @@
+"""Installed `fcc-codex` launcher."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from collections.abc import Mapping, Sequence
+from urllib.request import Request, urlopen
+
+from api.admin_urls import local_proxy_root_url
+from config.paths import codex_model_catalog_path
+from config.settings import Settings, get_settings
+
+from .codex_model_catalog import build_codex_model_catalog, write_codex_model_catalog
+from .common import (
+ PROXY_PREFLIGHT_TIMEOUT_SECONDS,
+ preflight_proxy,
+ resolve_client_binary,
+ run_client_process,
+)
+
+_CODEX_AUTH_ENV_KEY = "FCC_CODEX_API_KEY"
+_DISPLAY_NAME = "Codex CLI"
+_DEFAULT_BINARY = "codex"
+_INSTALL_HINT = "Install Codex with: npm install -g @openai/codex"
+_STRIPPED_CODEX_ENV_KEYS = frozenset(
+ {
+ "OPENAI_API_KEY",
+ "OPENAI_BASE_URL",
+ "OPENAI_API_BASE",
+ "OPENAI_ORG_ID",
+ "OPENAI_ORGANIZATION",
+ "CODEX_API_KEY",
+ _CODEX_AUTH_ENV_KEY,
+ }
+)
+
+
+def launch(argv: Sequence[str] | None = None) -> None:
+ """Launch Codex CLI with Free Claude Code proxy configuration."""
+
+ settings = get_settings()
+ proxy_root_url = local_proxy_root_url(settings)
+ if error := preflight_proxy(proxy_root_url):
+ print(
+ f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",
+ file=sys.stderr,
+ )
+ print("Start it in another terminal with: fcc-server", file=sys.stderr)
+ raise SystemExit(1)
+
+ binary_name = codex_binary_name(settings)
+ binary_path = resolve_client_binary(
+ binary_name=binary_name,
+ display_name=_DISPLAY_NAME,
+ install_hint=_INSTALL_HINT,
+ )
+ catalog_args = codex_model_catalog_config_args(proxy_root_url, settings)
+ args = list(sys.argv[1:] if argv is None else argv)
+ run_client_process(
+ command=build_codex_launcher_command(
+ binary_path=binary_path,
+ argv=args,
+ settings=settings,
+ proxy_root_url=proxy_root_url,
+ catalog_config_args=catalog_args,
+ ),
+ env=build_codex_launcher_env(
+ auth_token=settings.anthropic_auth_token,
+ base_env=os.environ,
+ ),
+ binary_name=binary_name,
+ display_name=_DISPLAY_NAME,
+ install_hint=_INSTALL_HINT,
+ )
+
+
+def codex_binary_name(settings: Settings) -> str:
+ """Return the configured Codex binary name."""
+
+ return settings.codex_cli_bin or _DEFAULT_BINARY
+
+
+def build_codex_launcher_command(
+ *,
+ binary_path: str,
+ argv: Sequence[str],
+ settings: Settings,
+ proxy_root_url: str,
+ catalog_config_args: Sequence[str] = (),
+) -> list[str]:
+ """Return a Codex command with ephemeral FCC provider config."""
+
+ return [
+ binary_path,
+ *catalog_config_args,
+ *codex_config_args(
+ api_url=_ensure_v1_url(proxy_root_url),
+ model=getattr(settings, "model", None),
+ ),
+ *argv,
+ ]
+
+
+def build_codex_launcher_env(
+ *,
+ auth_token: str,
+ base_env: Mapping[str, str],
+) -> dict[str, str]:
+ """Return a Codex environment that targets the local proxy provider."""
+
+ env = {
+ key: value
+ for key, value in base_env.items()
+ if key not in _STRIPPED_CODEX_ENV_KEYS and not key.startswith("OPENAI_")
+ }
+ env[_CODEX_AUTH_ENV_KEY] = auth_token.strip() or "fcc-no-auth"
+ return env
+
+
+def codex_model_catalog_config_args(
+ proxy_root_url: str, settings: Settings
+) -> list[str]:
+ """Prepare the generated Codex model catalog and return its config args."""
+
+ try:
+ models_response = fetch_proxy_models_response(
+ proxy_root_url, settings.anthropic_auth_token
+ )
+ catalog = build_codex_model_catalog(models_response)
+ models = catalog.get("models")
+ if not isinstance(models, list) or not models:
+ print(
+ "Free Claude Code warning: Codex model catalog is empty; "
+ "launching without model picker catalog.",
+ file=sys.stderr,
+ )
+ return []
+ catalog_path = codex_model_catalog_path()
+ write_codex_model_catalog(catalog_path, catalog)
+ except Exception as exc:
+ print(
+ "Free Claude Code warning: could not prepare Codex model catalog "
+ f"({exc}); launching without model picker catalog.",
+ file=sys.stderr,
+ )
+ return []
+
+ return build_model_catalog_config_args(str(catalog_path))
+
+
+def fetch_proxy_models_response(
+ proxy_root_url: str, auth_token: str
+) -> dict[str, object]:
+ """Fetch the local proxy `/v1/models` response for Codex catalog generation."""
+
+ url = f"{proxy_root_url.rstrip('/')}/v1/models"
+ headers: dict[str, str] = {}
+ if token := auth_token.strip():
+ headers["X-API-Key"] = token
+
+ request = Request(url, headers=headers, method="GET")
+ with urlopen(request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS) as response:
+ payload = json.loads(response.read().decode("utf-8"))
+
+ if not isinstance(payload, dict):
+ raise ValueError("model list response was not a JSON object")
+ return payload
+
+
+def build_model_catalog_config_args(catalog_path: str) -> list[str]:
+ """Return Codex config args for a generated model catalog."""
+
+ return ["-c", _toml_assignment("model_catalog_json", catalog_path)]
+
+
+def codex_config_args(*, api_url: str, model: str | None = None) -> list[str]:
+ """Return Codex `-c` assignments for the ephemeral FCC provider."""
+
+ args = [
+ "-c",
+ _toml_assignment("model_provider", "fcc"),
+ "-c",
+ _toml_assignment("model_providers.fcc.name", "Free Claude Code"),
+ "-c",
+ _toml_assignment("model_providers.fcc.base_url", _ensure_v1_url(api_url)),
+ "-c",
+ _toml_assignment("model_providers.fcc.env_key", _CODEX_AUTH_ENV_KEY),
+ "-c",
+ _toml_assignment("model_providers.fcc.wire_api", "responses"),
+ ]
+ if model:
+ args.extend(["-c", _toml_assignment("model", model)])
+ return args
+
+
+def _ensure_v1_url(url: str) -> str:
+ stripped = url.rstrip("/")
+ return stripped if stripped.endswith("/v1") else f"{stripped}/v1"
+
+
+def _toml_assignment(key: str, value: str) -> str:
+ return f"{key}={json.dumps(value)}"
diff --git a/cli/codex_model_catalog.py b/cli/launchers/codex_model_catalog.py
similarity index 100%
rename from cli/codex_model_catalog.py
rename to cli/launchers/codex_model_catalog.py
diff --git a/cli/launchers/common.py b/cli/launchers/common.py
new file mode 100644
index 00000000..d65441a1
--- /dev/null
+++ b/cli/launchers/common.py
@@ -0,0 +1,93 @@
+"""Shared process helpers for installed client CLI launchers."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import sys
+from collections.abc import Mapping
+from urllib.error import HTTPError, URLError
+from urllib.request import Request, urlopen
+
+from cli.process_registry import (
+ kill_pid_tree_best_effort,
+ register_pid,
+ unregister_pid,
+)
+
+PROXY_PREFLIGHT_PATH = "/health"
+PROXY_PREFLIGHT_TIMEOUT_SECONDS = 1.5
+
+
+def preflight_proxy(proxy_root_url: str) -> str | None:
+ """Return an error message when the local proxy health check is unreachable."""
+
+ url = f"{proxy_root_url.rstrip('/')}{PROXY_PREFLIGHT_PATH}"
+ request = Request(url, method="GET")
+ try:
+ with urlopen(request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS) as response:
+ status_code = response.getcode()
+ except HTTPError as exc:
+ return f"returned HTTP {exc.code}"
+ except URLError as exc:
+ return str(exc.reason)
+ except OSError as exc:
+ return str(exc)
+
+ if not 200 <= status_code < 300:
+ return f"returned HTTP {status_code}"
+ return None
+
+
+def resolve_client_binary(
+ *,
+ binary_name: str,
+ display_name: str,
+ install_hint: str,
+) -> str:
+ """Resolve an installed client binary or exit with a user-facing hint."""
+
+ client_command = shutil.which(binary_name)
+ if client_command is None:
+ print(
+ f"Could not find {display_name} command: {binary_name}",
+ file=sys.stderr,
+ )
+ print(install_hint, file=sys.stderr)
+ raise SystemExit(127)
+ return client_command
+
+
+def run_client_process(
+ *,
+ command: list[str],
+ env: Mapping[str, str],
+ binary_name: str,
+ display_name: str,
+ install_hint: str,
+) -> None:
+ """Run a client CLI command and mirror its exit code."""
+
+ process: subprocess.Popen[bytes] | None = None
+ try:
+ process = subprocess.Popen(command, env=dict(env))
+ if process.pid:
+ register_pid(process.pid)
+ return_code = process.wait()
+ except FileNotFoundError:
+ print(
+ f"Could not find {display_name} command: {binary_name}",
+ file=sys.stderr,
+ )
+ print(install_hint, file=sys.stderr)
+ raise SystemExit(127) from None
+ except KeyboardInterrupt:
+ if process is not None and process.pid:
+ kill_pid_tree_best_effort(process.pid)
+ process.wait()
+ raise
+ finally:
+ if process is not None and process.pid:
+ unregister_pid(process.pid)
+
+ raise SystemExit(return_code)
diff --git a/cli/managed/__init__.py b/cli/managed/__init__.py
new file mode 100644
index 00000000..92c7911c
--- /dev/null
+++ b/cli/managed/__init__.py
@@ -0,0 +1,6 @@
+"""Managed Claude Code sessions used by messaging."""
+
+from .manager import ManagedClaudeSessionManager
+from .session import ManagedClaudeSession
+
+__all__ = ["ManagedClaudeSession", "ManagedClaudeSessionManager"]
diff --git a/cli/managed/claude.py b/cli/managed/claude.py
new file mode 100644
index 00000000..69445291
--- /dev/null
+++ b/cli/managed/claude.py
@@ -0,0 +1,215 @@
+"""Managed Claude Code task command, environment, and stdout parsing."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass, field
+from typing import Any
+
+from loguru import logger
+
+from cli.claude_env import CLAUDE_CODE_AUTO_COMPACT_WINDOW, claude_auth_token
+
+
+@dataclass(frozen=True, slots=True)
+class ManagedClaudeTaskRequest:
+ """One prompt execution request for a managed Claude Code subprocess."""
+
+ prompt: str
+ session_id: str | None = None
+ fork_session: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class ManagedClaudeInvocation:
+ """Concrete subprocess invocation assembled for a managed Claude task."""
+
+ argv: tuple[str, ...]
+ env: dict[str, str]
+ cwd: str
+ trace_metadata: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True, slots=True)
+class ManagedClaudeConfig:
+ """Configuration for a managed Claude Code subprocess."""
+
+ workspace_path: str
+ api_url: str
+ allowed_dirs: list[str] = field(default_factory=list)
+ plans_directory: str | None = None
+ claude_bin: str = "claude"
+ auth_token: str = ""
+
+
+@dataclass(slots=True)
+class ManagedClaudeParseState:
+ """Mutable stdout parser state for one managed Claude Code task run."""
+
+ log_raw_cli_diagnostics: bool = False
+ session_id_extracted: bool = False
+
+
+def build_managed_claude_invocation(
+ *,
+ config: ManagedClaudeConfig,
+ request: ManagedClaudeTaskRequest,
+ base_env: Mapping[str, str],
+) -> ManagedClaudeInvocation:
+ """Build a Claude Code stream-json subprocess invocation."""
+
+ cmd = build_managed_claude_command(
+ claude_bin=config.claude_bin,
+ prompt=request.prompt,
+ session_id=request.session_id,
+ fork_session=request.fork_session,
+ allowed_dirs=config.allowed_dirs,
+ plans_directory=config.plans_directory,
+ )
+ resume_session_id = (
+ request.session_id
+ if request.session_id and not request.session_id.startswith("pending_")
+ else None
+ )
+ return ManagedClaudeInvocation(
+ argv=tuple(cmd),
+ env=build_managed_claude_env(
+ api_url=config.api_url,
+ auth_token=config.auth_token,
+ base_env=base_env,
+ ),
+ cwd=config.workspace_path,
+ trace_metadata={
+ "client_cli_id": "claude",
+ "resume_session_id": resume_session_id,
+ "fork_session": request.fork_session,
+ "prompt": request.prompt,
+ "cwd": config.workspace_path,
+ "claude_binary": config.claude_bin,
+ "cli_argv": cmd,
+ },
+ )
+
+
+def build_managed_claude_env(
+ *,
+ api_url: str,
+ auth_token: str,
+ base_env: Mapping[str, str],
+) -> dict[str, str]:
+ """Return a Claude Code task environment that targets the local proxy."""
+
+ env = dict(base_env)
+ env["ANTHROPIC_API_URL"] = api_url
+ env["ANTHROPIC_BASE_URL"] = api_url[:-3] if api_url.endswith("/v1") else api_url
+ env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"
+ env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = CLAUDE_CODE_AUTO_COMPACT_WINDOW
+ env.pop("ANTHROPIC_API_KEY", None)
+ env["ANTHROPIC_AUTH_TOKEN"] = claude_auth_token(auth_token)
+ env["TERM"] = "dumb"
+ env["PYTHONIOENCODING"] = "utf-8"
+ return env
+
+
+def build_managed_claude_command(
+ *,
+ claude_bin: str,
+ prompt: str,
+ session_id: str | None,
+ fork_session: bool,
+ allowed_dirs: list[str],
+ plans_directory: str | None,
+) -> list[str]:
+ """Return the Claude Code stream-json command for a managed task."""
+
+ if session_id and not session_id.startswith("pending_"):
+ cmd = [
+ claude_bin,
+ "--resume",
+ session_id,
+ ]
+ if fork_session:
+ cmd.append("--fork-session")
+ cmd += [
+ "-p",
+ prompt,
+ "--output-format",
+ "stream-json",
+ "--dangerously-skip-permissions",
+ "--verbose",
+ ]
+ else:
+ cmd = [
+ claude_bin,
+ "-p",
+ prompt,
+ "--output-format",
+ "stream-json",
+ "--dangerously-skip-permissions",
+ "--verbose",
+ ]
+
+ for directory in allowed_dirs:
+ cmd.extend(["--add-dir", directory])
+
+ if plans_directory is not None:
+ cmd.extend(["--settings", json.dumps({"plansDirectory": plans_directory})])
+
+ return cmd
+
+
+def parse_managed_claude_stdout_line(
+ line: str, state: ManagedClaudeParseState
+) -> Iterable[Any]:
+ """Parse one Claude Code stream-json stdout line."""
+
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ if state.log_raw_cli_diagnostics:
+ logger.debug("Non-JSON output: {}", line)
+ else:
+ logger.debug("Non-JSON CLI line: char_len={}", len(line))
+ yield {"type": "raw", "content": line}
+ return
+
+ if not state.session_id_extracted:
+ extracted_id = extract_managed_claude_session_id(event)
+ if extracted_id:
+ state.session_id_extracted = True
+ logger.info("Extracted session ID: {}", extracted_id)
+ yield {"type": "session_info", "session_id": extracted_id}
+
+ yield event
+
+
+def extract_managed_claude_session_id(event: Any) -> str | None:
+ """Extract a Claude Code session ID from supported stream-json event shapes."""
+
+ if not isinstance(event, dict):
+ return None
+
+ if session_id := _string_value(event.get("session_id")):
+ return session_id
+ if session_id := _string_value(event.get("sessionId")):
+ return session_id
+
+ for key in ("init", "system", "result", "metadata"):
+ nested = event.get(key)
+ if not isinstance(nested, dict):
+ continue
+ if session_id := _string_value(nested.get("session_id")):
+ return session_id
+ if session_id := _string_value(nested.get("sessionId")):
+ return session_id
+
+ conversation = event.get("conversation")
+ if isinstance(conversation, dict):
+ return _string_value(conversation.get("id"))
+
+ return None
+
+
+def _string_value(value: Any) -> str | None:
+ return value if isinstance(value, str) else None
diff --git a/cli/manager.py b/cli/managed/manager.py
similarity index 82%
rename from cli/manager.py
rename to cli/managed/manager.py
index 7f080f0b..b006ee40 100644
--- a/cli/manager.py
+++ b/cli/managed/manager.py
@@ -1,27 +1,19 @@
-"""
-CLI Session Manager for Multi-Instance Claude CLI Support
-
-Manages a pool of CLISession instances, each handling one conversation.
-This enables true parallel processing where multiple conversations run
-simultaneously in separate CLI processes.
-"""
+"""Managed Claude Code session pool for messaging."""
import asyncio
import uuid
from loguru import logger
-from .adapters.base import ClientCliAdapter
-from .adapters.registry import get_client_cli_adapter
-from .session import CLISession
+from .session import ManagedClaudeSession
-class CLISessionManager:
+class ManagedClaudeSessionManager:
"""
- Manages multiple CLISession instances for parallel conversation processing.
+ Manages multiple Claude Code sessions for parallel conversation processing.
- Each new conversation gets its own CLISession with its own subprocess.
- Replies to existing conversations reuse the same CLISession instance.
+ Each new conversation gets its own subprocess. Replies to existing
+ conversations reuse the same session instance.
"""
def __init__(
@@ -33,7 +25,6 @@ class CLISessionManager:
claude_bin: str = "claude",
auth_token: str = "",
*,
- client_cli_adapter: ClientCliAdapter | None = None,
log_raw_cli_diagnostics: bool = False,
log_messaging_error_details: bool = False,
):
@@ -52,24 +43,23 @@ class CLISessionManager:
self.plans_directory = plans_directory
self.claude_bin = claude_bin
self.auth_token = auth_token
- self._client_cli_adapter = client_cli_adapter or get_client_cli_adapter()
self._log_raw_cli_diagnostics = log_raw_cli_diagnostics
self._log_messaging_error_details = log_messaging_error_details
- self._sessions: dict[str, CLISession] = {}
- self._pending_sessions: dict[str, CLISession] = {}
+ self._sessions: dict[str, ManagedClaudeSession] = {}
+ self._pending_sessions: dict[str, ManagedClaudeSession] = {}
self._temp_to_real: dict[str, str] = {}
self._real_to_temp: dict[str, str] = {}
self._lock = asyncio.Lock()
async def get_or_create_session(
self, session_id: str | None = None
- ) -> tuple[CLISession, str, bool]:
+ ) -> tuple[ManagedClaudeSession, str, bool]:
"""
Get an existing session or create a new one.
Returns:
- Tuple of (CLISession instance, session_id, is_new_session)
+ Tuple of (session instance, session_id, is_new_session)
"""
async with self._lock:
if session_id:
@@ -82,14 +72,13 @@ class CLISessionManager:
temp_id = session_id if session_id else f"pending_{uuid.uuid4().hex[:8]}"
- new_session = CLISession(
+ new_session = ManagedClaudeSession(
workspace_path=self.workspace,
api_url=self.api_url,
allowed_dirs=self.allowed_dirs,
plans_directory=self.plans_directory,
claude_bin=self.claude_bin,
auth_token=self.auth_token,
- client_cli_adapter=self._client_cli_adapter,
log_raw_cli_diagnostics=self._log_raw_cli_diagnostics,
)
self._pending_sessions[temp_id] = new_session
diff --git a/cli/session.py b/cli/managed/session.py
similarity index 85%
rename from cli/session.py
rename to cli/managed/session.py
index 19801fd3..d7c335bf 100644
--- a/cli/session.py
+++ b/cli/managed/session.py
@@ -1,37 +1,28 @@
-"""Claude Code CLI session management."""
+"""Managed Claude Code subprocess session."""
import asyncio
import os
from collections.abc import AsyncGenerator
-from dataclasses import dataclass, field
-from typing import Any
from loguru import logger
+from cli.process_registry import kill_pid_tree_best_effort, register_pid, unregister_pid
from core.trace import trace_event
-from .adapters.base import ClientCliAdapter, CliParseState, CliTaskRequest
-from .adapters.registry import get_client_cli_adapter
-from .process_registry import kill_pid_tree_best_effort, register_pid, unregister_pid
+from .claude import (
+ ManagedClaudeConfig,
+ ManagedClaudeParseState,
+ ManagedClaudeTaskRequest,
+ build_managed_claude_invocation,
+ parse_managed_claude_stdout_line,
+)
# Cap stderr capture so a runaway child cannot exhaust memory; pipe is still drained.
_MAX_STDERR_CAPTURE_BYTES = 256 * 1024
-@dataclass(frozen=True, slots=True)
-class ClaudeCliConfig:
- """Configuration for a managed Claude CLI subprocess."""
-
- workspace_path: str
- api_url: str
- allowed_dirs: list[str] = field(default_factory=list)
- plans_directory: str | None = None
- claude_bin: str = "claude"
- auth_token: str = ""
-
-
-class CLISession:
- """Manages a single persistent Claude Code CLI subprocess."""
+class ManagedClaudeSession:
+ """Manages a single persistent Claude Code subprocess."""
def __init__(
self,
@@ -42,10 +33,9 @@ class CLISession:
claude_bin: str = "claude",
auth_token: str = "",
*,
- client_cli_adapter: ClientCliAdapter | None = None,
log_raw_cli_diagnostics: bool = False,
):
- self.config = ClaudeCliConfig(
+ self.config = ManagedClaudeConfig(
workspace_path=os.path.normpath(os.path.abspath(workspace_path)),
api_url=api_url,
allowed_dirs=[os.path.normpath(d) for d in (allowed_dirs or [])],
@@ -59,7 +49,6 @@ class CLISession:
self.plans_directory = self.config.plans_directory
self.claude_bin = self.config.claude_bin
self.auth_token = self.config.auth_token
- self._client_cli_adapter = client_cli_adapter or get_client_cli_adapter()
self._log_raw_cli_diagnostics = log_raw_cli_diagnostics
self.process: asyncio.subprocess.Process | None = None
self.current_session_id: str | None = None
@@ -114,9 +103,9 @@ class CLISession:
"""
async with self._cli_lock:
self._is_busy = True
- invocation = self._client_cli_adapter.build_task_invocation(
+ invocation = build_managed_claude_invocation(
config=self.config,
- request=CliTaskRequest(
+ request=ManagedClaudeTaskRequest(
prompt=prompt,
session_id=session_id,
fork_session=fork_session,
@@ -125,9 +114,9 @@ class CLISession:
)
trace_event(
- stage=self._client_cli_adapter.trace_stage,
- event=self._client_cli_adapter.process_launch_event,
- source=self._client_cli_adapter.trace_source,
+ stage="claude_cli",
+ event="claude_cli.process.launch",
+ source="claude_cli",
**invocation.trace_metadata,
)
@@ -146,7 +135,7 @@ class CLISession:
yield {"type": "exit", "code": 1}
return
- parse_state = CliParseState(
+ parse_state = ManagedClaudeParseState(
log_raw_cli_diagnostics=self._log_raw_cli_diagnostics
)
buffer = bytearray()
@@ -231,20 +220,16 @@ class CLISession:
unregister_pid(self.process.pid)
async def _handle_line_gen(
- self, line_str: str, parse_state: CliParseState
+ self, line_str: str, parse_state: ManagedClaudeParseState
) -> AsyncGenerator[dict]:
"""Process a single line and yield events."""
- for event in self._client_cli_adapter.parse_stdout_line(line_str, parse_state):
+ for event in parse_managed_claude_stdout_line(line_str, parse_state):
if isinstance(event, dict) and event.get("type") == "session_info":
session_id = event.get("session_id")
if isinstance(session_id, str):
self.current_session_id = session_id
yield event
- def _extract_session_id(self, event: Any) -> str | None:
- """Extract session ID from CLI event."""
- return self._client_cli_adapter.extract_session_id(event)
-
async def stop(self):
"""Stop the CLI process."""
if self.process and self.process.returncode is None:
diff --git a/messaging/__init__.py b/messaging/__init__.py
index 919a4996..16a04e77 100644
--- a/messaging/__init__.py
+++ b/messaging/__init__.py
@@ -2,20 +2,24 @@
from .event_parser import parse_cli_event
from .models import IncomingMessage
-from .platforms.base import CLISession, MessagingPlatform, SessionManagerInterface
+from .platforms.base import (
+ ManagedClaudeSessionManagerProtocol,
+ ManagedClaudeSessionProtocol,
+ MessagingPlatform,
+)
from .session import SessionStore
from .trees import MessageNode, MessageState, MessageTree, TreeQueueManager
from .workflow import MessagingWorkflow
__all__ = [
- "CLISession",
"IncomingMessage",
+ "ManagedClaudeSessionManagerProtocol",
+ "ManagedClaudeSessionProtocol",
"MessageNode",
"MessageState",
"MessageTree",
"MessagingPlatform",
"MessagingWorkflow",
- "SessionManagerInterface",
"SessionStore",
"TreeQueueManager",
"parse_cli_event",
diff --git a/messaging/command_context.py b/messaging/command_context.py
index 65d37bcd..f690c9cf 100644
--- a/messaging/command_context.py
+++ b/messaging/command_context.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Protocol
-from .platforms.base import MessagingPlatform, SessionManagerInterface
+from .platforms.base import ManagedClaudeSessionManagerProtocol, MessagingPlatform
from .session import SessionStore
from .transcript import RenderCtx
from .trees import MessageNode, MessageTree, TreeQueueManager
@@ -14,7 +14,7 @@ class MessagingCommandContext(Protocol):
"""Operations commands need from the messaging workflow."""
platform: MessagingPlatform
- cli_manager: SessionManagerInterface
+ cli_manager: ManagedClaudeSessionManagerProtocol
session_store: SessionStore
@property
diff --git a/messaging/node_event_pipeline.py b/messaging/node_event_pipeline.py
index 0e6680c6..684a0ae5 100644
--- a/messaging/node_event_pipeline.py
+++ b/messaging/node_event_pipeline.py
@@ -10,7 +10,7 @@ from loguru import logger
from core.trace import trace_event
from .cli_event_constants import TRANSCRIPT_EVENT_TYPES, get_status_for_event
-from .platforms.base import SessionManagerInterface
+from .platforms.base import ManagedClaudeSessionManagerProtocol
from .safe_diagnostics import text_len_hint
from .session import SessionStore
from .transcript import TranscriptBuffer
@@ -24,7 +24,7 @@ async def handle_session_info_event(
captured_session_id: str | None,
temp_session_id: str | None,
*,
- cli_manager: SessionManagerInterface,
+ cli_manager: ManagedClaudeSessionManagerProtocol,
session_store: SessionStore,
) -> tuple[str | None, str | None]:
"""Handle session_info event; return updated (captured_session_id, temp_session_id)."""
diff --git a/messaging/node_runner.py b/messaging/node_runner.py
index d0b06d6c..0212943b 100644
--- a/messaging/node_runner.py
+++ b/messaging/node_runner.py
@@ -12,7 +12,7 @@ from core.trace import trace_event
from .event_parser import parse_cli_event
from .node_event_pipeline import handle_session_info_event, process_parsed_cli_event
-from .platforms.base import MessagingPlatform, SessionManagerInterface
+from .platforms.base import ManagedClaudeSessionManagerProtocol, MessagingPlatform
from .safe_diagnostics import format_exception_for_log
from .session import SessionStore
from .transcript import RenderCtx, TranscriptBuffer
@@ -27,7 +27,7 @@ class MessagingNodeRunner:
self,
*,
platform: MessagingPlatform,
- cli_manager: SessionManagerInterface,
+ cli_manager: ManagedClaudeSessionManagerProtocol,
session_store: SessionStore,
get_tree_queue: Callable[[], TreeQueueManager],
format_status: Callable[[str, str, str | None], str],
diff --git a/messaging/platforms/__init__.py b/messaging/platforms/__init__.py
index 88261a7a..0e91f59c 100644
--- a/messaging/platforms/__init__.py
+++ b/messaging/platforms/__init__.py
@@ -1,11 +1,15 @@
"""Messaging platform adapters (Telegram, Discord, etc.)."""
-from .base import CLISession, MessagingPlatform, SessionManagerInterface
+from .base import (
+ ManagedClaudeSessionManagerProtocol,
+ ManagedClaudeSessionProtocol,
+ MessagingPlatform,
+)
from .factory import create_messaging_platform
__all__ = [
- "CLISession",
+ "ManagedClaudeSessionManagerProtocol",
+ "ManagedClaudeSessionProtocol",
"MessagingPlatform",
- "SessionManagerInterface",
"create_messaging_platform",
]
diff --git a/messaging/platforms/base.py b/messaging/platforms/base.py
index 60beffa6..522aebf8 100644
--- a/messaging/platforms/base.py
+++ b/messaging/platforms/base.py
@@ -12,8 +12,8 @@ from ..models import IncomingMessage
@runtime_checkable
-class CLISession(Protocol):
- """Protocol for CLI session - avoid circular import from cli package."""
+class ManagedClaudeSessionProtocol(Protocol):
+ """Protocol for managed Claude sessions - avoid circular imports."""
def start_task(
self, prompt: str, session_id: str | None = None, fork_session: bool = False
@@ -24,16 +24,14 @@ class CLISession(Protocol):
@runtime_checkable
-class SessionManagerInterface(Protocol):
+class ManagedClaudeSessionManagerProtocol(Protocol):
"""
- Protocol for session managers to avoid tight coupling with cli package.
-
- Implementations: CLISessionManager
+ Protocol for managed Claude session managers to avoid tight coupling.
"""
async def get_or_create_session(
self, session_id: str | None = None
- ) -> tuple[CLISession, str, bool]:
+ ) -> tuple[ManagedClaudeSessionProtocol, str, bool]:
"""
Get an existing session or create a new one.
diff --git a/messaging/workflow.py b/messaging/workflow.py
index beec6f8d..7e4a30f7 100644
--- a/messaging/workflow.py
+++ b/messaging/workflow.py
@@ -8,7 +8,7 @@ from core.trace import trace_event
from .models import IncomingMessage
from .node_runner import MessagingNodeRunner
-from .platforms.base import MessagingPlatform, SessionManagerInterface
+from .platforms.base import ManagedClaudeSessionManagerProtocol, MessagingPlatform
from .rendering.profiles import build_rendering_profile
from .safe_diagnostics import format_exception_for_log
from .session import SessionStore
@@ -28,7 +28,7 @@ class MessagingWorkflow:
def __init__(
self,
platform: MessagingPlatform,
- cli_manager: SessionManagerInterface,
+ cli_manager: ManagedClaudeSessionManagerProtocol,
session_store: SessionStore,
*,
debug_platform_edits: bool = False,
diff --git a/pyproject.toml b/pyproject.toml
index dc53ce46..54fd3b55 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "2.3.10"
+version = "2.3.11"
description = "Middleware between Claude Code CLI (Anthropic API) and NVIDIA NIM"
readme = "README.md"
requires-python = ">=3.14.0"
@@ -29,8 +29,8 @@ dependencies = [
fcc-server = "cli.entrypoints:serve"
free-claude-code = "cli.entrypoints:serve"
fcc-init = "cli.entrypoints:init"
-fcc-claude = "cli.entrypoints:launch_claude"
-fcc-codex = "cli.entrypoints:launch_codex"
+fcc-claude = "cli.launchers.claude:launch"
+fcc-codex = "cli.launchers.codex:launch"
[project.optional-dependencies]
voice = [
diff --git a/smoke/capabilities.py b/smoke/capabilities.py
index e13a6eea..a0aa99a8 100644
--- a/smoke/capabilities.py
+++ b/smoke/capabilities.py
@@ -69,7 +69,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
(
"tests/api/test_openai_responses.py",
"tests/core/openai_responses/test_sse.py",
- "tests/cli/test_adapters.py",
+ "tests/cli/test_entrypoints.py",
+ "tests/cli/test_codex_model_catalog.py",
),
(
"test_probe_and_models_routes",
@@ -424,7 +425,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"cli",
"claude_cli_drop_in",
"claude_cli_drop_in",
- "cli.session.CLISession",
+ "cli.managed.session.ManagedClaudeSession",
"Claude CLI binary and proxy env",
"stream-json events and session id mapping",
"stderr/error event and process cleanup",
@@ -439,12 +440,12 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"cli",
"codex_cli_drop_in",
"drop_in_codex_replacement",
- "cli.adapters.codex.CodexCliAdapter",
+ "cli.launchers.codex",
"Codex CLI binary and fcc provider env",
- "Responses config and JSONL event mapping",
- "stderr/error event and process cleanup",
+ "Responses config, auth env, and native /model catalog injection",
+ "proxy preflight and catalog fail-open warning",
(
- "tests/cli/test_adapters.py",
+ "tests/cli/test_codex_model_catalog.py",
"tests/cli/test_entrypoints.py",
),
(),
diff --git a/smoke/features.py b/smoke/features.py
index b11e4f32..e9247f48 100644
--- a/smoke/features.py
+++ b/smoke/features.py
@@ -93,7 +93,8 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
"readme",
(
"tests/api/test_openai_responses.py",
- "tests/cli/test_adapters.py",
+ "tests/cli/test_entrypoints.py",
+ "tests/cli/test_codex_model_catalog.py",
"tests/core/openai_responses/test_sse.py",
),
("test_probe_and_models_routes",),
diff --git a/smoke/product/test_cli_package_product_live.py b/smoke/product/test_cli_package_product_live.py
index be307588..8a6cd238 100644
--- a/smoke/product/test_cli_package_product_live.py
+++ b/smoke/product/test_cli_package_product_live.py
@@ -8,8 +8,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from cli.manager import CLISessionManager
-from cli.session import CLISession
+from cli.managed.manager import ManagedClaudeSessionManager
+from cli.managed.session import ManagedClaudeSession
from smoke.lib.child_process import cmd_fcc_init
from smoke.lib.config import SmokeConfig
@@ -37,7 +37,7 @@ def test_entrypoint_init_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> None:
@pytest.mark.asyncio
async def test_cli_session_resume_fork_e2e(tmp_path: Path) -> None:
- session = CLISession(str(tmp_path), "http://127.0.0.1:8082/v1")
+ session = ManagedClaudeSession(str(tmp_path), "http://127.0.0.1:8082/v1")
process = AsyncMock()
process.stdout.read.side_effect = [b""]
process.stderr.read.return_value = b""
@@ -62,7 +62,7 @@ async def test_cli_session_resume_fork_e2e(tmp_path: Path) -> None:
@pytest.mark.asyncio
async def test_cli_process_cleanup_e2e(tmp_path: Path) -> None:
- manager = CLISessionManager(
+ manager = ManagedClaudeSessionManager(
workspace_path=str(tmp_path),
api_url="http://127.0.0.1:8082/v1",
)
@@ -84,14 +84,14 @@ async def test_cli_process_cleanup_e2e(tmp_path: Path) -> None:
@pytest.mark.asyncio
async def test_cli_session_stop_kills_child_e2e(tmp_path: Path) -> None:
- session = CLISession(str(tmp_path), "http://127.0.0.1:8082/v1")
+ session = ManagedClaudeSession(str(tmp_path), "http://127.0.0.1:8082/v1")
process = MagicMock()
process.pid = 123456
process.returncode = None
process.wait = AsyncMock(side_effect=[asyncio.TimeoutError, 0])
session.process = process
- with patch("cli.session.kill_pid_tree_best_effort") as kill_tree:
+ with patch("cli.managed.session.kill_pid_tree_best_effort") as kill_tree:
stopped = await session.stop()
assert stopped is True
diff --git a/tests/api/test_app_lifespan_and_errors.py b/tests/api/test_app_lifespan_and_errors.py
index c88a79fd..d201cad0 100644
--- a/tests/api/test_app_lifespan_and_errors.py
+++ b/tests/api/test_app_lifespan_and_errors.py
@@ -313,7 +313,7 @@ def test_app_lifespan_sets_state_and_cleans_up(tmp_path, messaging_enabled):
return_value=fake_platform if messaging_enabled else None,
) as create_platform,
patch("messaging.session.SessionStore", return_value=session_store),
- patch("cli.manager.CLISessionManager", return_value=cli_manager),
+ patch("cli.managed.ManagedClaudeSessionManager", return_value=cli_manager),
patch(
"messaging.trees.TreeQueueManager.from_dict",
return_value=fake_queue,
@@ -383,7 +383,7 @@ def test_app_lifespan_cleanup_continues_if_platform_stop_raises(tmp_path):
return_value=fake_platform,
),
patch("messaging.session.SessionStore", return_value=session_store),
- patch("cli.manager.CLISessionManager", return_value=cli_manager),
+ patch("cli.managed.ManagedClaudeSessionManager", return_value=cli_manager),
TestClient(app),
):
pass
@@ -560,7 +560,7 @@ def test_app_lifespan_platform_start_exception_cleanup_still_runs(tmp_path):
return_value=fake_platform,
),
patch("messaging.session.SessionStore", return_value=session_store),
- patch("cli.manager.CLISessionManager", return_value=cli_manager),
+ patch("cli.managed.ManagedClaudeSessionManager", return_value=cli_manager),
TestClient(app),
):
pass
@@ -611,7 +611,7 @@ def test_app_lifespan_flush_pending_save_exception_warning_only(tmp_path):
return_value=fake_platform,
),
patch("messaging.session.SessionStore", return_value=session_store),
- patch("cli.manager.CLISessionManager", return_value=cli_manager),
+ patch("cli.managed.ManagedClaudeSessionManager", return_value=cli_manager),
TestClient(app),
):
pass
diff --git a/tests/cli/test_adapters.py b/tests/cli/test_adapters.py
deleted file mode 100644
index a5f8b316..00000000
--- a/tests/cli/test_adapters.py
+++ /dev/null
@@ -1,879 +0,0 @@
-from __future__ import annotations
-
-import json
-from types import SimpleNamespace
-
-from cli.adapters.base import CliParseState, CliTaskRequest
-from cli.adapters.claude import CLAUDE_CLI_ADAPTER
-from cli.adapters.codex import CODEX_CLI_ADAPTER
-from cli.adapters.registry import DEFAULT_CLIENT_CLI_ID, get_client_cli_adapter
-
-
-def _config(**overrides: object) -> SimpleNamespace:
- values: dict[str, object] = {
- "workspace_path": "/workspace",
- "api_url": "http://127.0.0.1:8082/v1",
- "allowed_dirs": [],
- "plans_directory": None,
- "claude_bin": "claude-test",
- "auth_token": "",
- }
- values.update(overrides)
- return SimpleNamespace(**values)
-
-
-def test_registry_returns_default_claude_adapter() -> None:
- assert DEFAULT_CLIENT_CLI_ID == "claude"
- assert get_client_cli_adapter() is CLAUDE_CLI_ADAPTER
- assert get_client_cli_adapter("claude") is CLAUDE_CLI_ADAPTER
- assert get_client_cli_adapter("codex") is CODEX_CLI_ADAPTER
-
-
-def test_claude_adapter_builds_new_task_command_and_env() -> None:
- invocation = CLAUDE_CLI_ADAPTER.build_task_invocation(
- config=_config(auth_token="proxy-token"),
- request=CliTaskRequest(prompt="hello"),
- base_env={
- "KEEP_ME": "yes",
- "ANTHROPIC_API_KEY": "official-key",
- "ANTHROPIC_AUTH_TOKEN": "stale-token",
- },
- )
-
- assert invocation.argv == (
- "claude-test",
- "-p",
- "hello",
- "--output-format",
- "stream-json",
- "--dangerously-skip-permissions",
- "--verbose",
- )
- assert invocation.env["KEEP_ME"] == "yes"
- assert invocation.env["ANTHROPIC_API_URL"] == "http://127.0.0.1:8082/v1"
- assert invocation.env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8082"
- assert invocation.env["ANTHROPIC_AUTH_TOKEN"] == "proxy-token"
- assert invocation.env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
- assert invocation.env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] == "190000"
- assert "ANTHROPIC_API_KEY" not in invocation.env
- assert invocation.trace_metadata["client_cli_id"] == "claude"
-
-
-def test_claude_adapter_builds_resume_fork_command() -> None:
- invocation = CLAUDE_CLI_ADAPTER.build_task_invocation(
- config=_config(),
- request=CliTaskRequest(
- prompt="continue",
- session_id="sess_123",
- fork_session=True,
- ),
- base_env={},
- )
-
- assert invocation.argv[:4] == (
- "claude-test",
- "--resume",
- "sess_123",
- "--fork-session",
- )
- assert "-p" in invocation.argv
- assert "continue" in invocation.argv
- assert invocation.trace_metadata["resume_session_id"] == "sess_123"
- assert invocation.trace_metadata["fork_session"] is True
-
-
-def test_claude_adapter_does_not_resume_pending_session() -> None:
- invocation = CLAUDE_CLI_ADAPTER.build_task_invocation(
- config=_config(),
- request=CliTaskRequest(prompt="new", session_id="pending_123"),
- base_env={},
- )
-
- assert "--resume" not in invocation.argv
- assert invocation.trace_metadata["resume_session_id"] is None
-
-
-def test_claude_adapter_adds_allowed_dirs_and_plans_directory() -> None:
- invocation = CLAUDE_CLI_ADAPTER.build_task_invocation(
- config=_config(
- allowed_dirs=["/dir1", "/dir2"],
- plans_directory="./agent_workspace/plans",
- ),
- request=CliTaskRequest(prompt="hello"),
- base_env={},
- )
-
- assert invocation.argv.count("--add-dir") == 2
- assert "/dir1" in invocation.argv
- assert "/dir2" in invocation.argv
- settings_idx = invocation.argv.index("--settings")
- settings = json.loads(invocation.argv[settings_idx + 1])
- assert settings["plansDirectory"] == "./agent_workspace/plans"
-
-
-def test_claude_adapter_launcher_env_targets_proxy() -> None:
- env = CLAUDE_CLI_ADAPTER.build_launcher_env(
- proxy_root_url="http://127.0.0.1:9191",
- auth_token=" proxy-token ",
- base_env={
- "PATH": "keep",
- "ANTHROPIC_BASE_URL": "https://api.anthropic.com",
- "ANTHROPIC_API_KEY": "official-key",
- "ANTHROPIC_AUTH_TOKEN": "stale-token",
- },
- )
-
- assert env["PATH"] == "keep"
- assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:9191"
- assert env["ANTHROPIC_AUTH_TOKEN"] == "proxy-token"
- assert env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
- assert env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] == "190000"
- assert "ANTHROPIC_API_KEY" not in env
-
-
-def test_claude_adapter_uses_sentinel_auth_when_proxy_auth_blank() -> None:
- invocation = CLAUDE_CLI_ADAPTER.build_task_invocation(
- config=_config(auth_token=""),
- request=CliTaskRequest(prompt="hello"),
- base_env={
- "ANTHROPIC_API_KEY": "official-key",
- "ANTHROPIC_AUTH_TOKEN": "stale-token",
- },
- )
-
- assert invocation.env["ANTHROPIC_AUTH_TOKEN"] == "fcc-no-auth"
- assert "ANTHROPIC_API_KEY" not in invocation.env
-
- env = CLAUDE_CLI_ADAPTER.build_launcher_env(
- proxy_root_url="http://127.0.0.1:9191",
- auth_token="",
- base_env={
- "ANTHROPIC_API_KEY": "official-key",
- "ANTHROPIC_AUTH_TOKEN": "stale-token",
- },
- )
-
- assert env["ANTHROPIC_AUTH_TOKEN"] == "fcc-no-auth"
- assert "ANTHROPIC_API_KEY" not in env
-
-
-def test_claude_adapter_launcher_command_preserves_args() -> None:
- command = CLAUDE_CLI_ADAPTER.build_launcher_command(
- binary_path="claude.cmd",
- argv=["--model", "sonnet"],
- settings=_config(),
- proxy_root_url="http://127.0.0.1:8082",
- )
-
- assert command == ["claude.cmd", "--model", "sonnet"]
-
-
-def test_claude_adapter_extracts_supported_session_id_shapes() -> None:
- assert CLAUDE_CLI_ADAPTER.extract_session_id({"session_id": "direct"}) == "direct"
- assert CLAUDE_CLI_ADAPTER.extract_session_id({"sessionId": "camel"}) == "camel"
- assert (
- CLAUDE_CLI_ADAPTER.extract_session_id({"init": {"session_id": "nested"}})
- == "nested"
- )
- assert (
- CLAUDE_CLI_ADAPTER.extract_session_id({"result": {"sessionId": "result"}})
- == "result"
- )
- assert (
- CLAUDE_CLI_ADAPTER.extract_session_id({"conversation": {"id": "conv"}})
- == "conv"
- )
- assert CLAUDE_CLI_ADAPTER.extract_session_id({"type": "message"}) is None
- assert CLAUDE_CLI_ADAPTER.extract_session_id("not a dict") is None
-
-
-def test_claude_adapter_invalid_stdout_json_becomes_raw_event() -> None:
- events = list(
- CLAUDE_CLI_ADAPTER.parse_stdout_line(
- "Not valid json",
- CliParseState(log_raw_cli_diagnostics=False),
- )
- )
-
- assert events == [{"type": "raw", "content": "Not valid json"}]
-
-
-def test_claude_adapter_synthesizes_session_info_once() -> None:
- state = CliParseState()
-
- first_events = list(
- CLAUDE_CLI_ADAPTER.parse_stdout_line('{"session_id": "sess_1"}', state)
- )
- second_events = list(
- CLAUDE_CLI_ADAPTER.parse_stdout_line('{"session_id": "sess_2"}', state)
- )
-
- assert first_events == [
- {"type": "session_info", "session_id": "sess_1"},
- {"session_id": "sess_1"},
- ]
- assert second_events == [{"session_id": "sess_2"}]
-
-
-def test_codex_adapter_builds_new_task_command_and_env() -> None:
- invocation = CODEX_CLI_ADAPTER.build_task_invocation(
- config=_config(auth_token="proxy-token"),
- request=CliTaskRequest(prompt="hello"),
- base_env={
- "KEEP_ME": "yes",
- "OPENAI_API_KEY": "official-key",
- "OPENAI_BASE_URL": "https://api.openai.com/v1",
- "CODEX_API_KEY": "stale-token",
- "CODEX_HOME": "/tmp/codex",
- },
- )
-
- assert invocation.argv[:3] == ("codex", "exec", "--json")
- assert "--dangerously-bypass-approvals-and-sandbox" in invocation.argv
- assert "-C" in invocation.argv
- assert "/workspace" in invocation.argv
- assert invocation.argv[-1] == "hello"
- assert 'model_provider="fcc"' in invocation.argv
- assert 'model_providers.fcc.wire_api="responses"' in invocation.argv
- assert invocation.env["KEEP_ME"] == "yes"
- assert invocation.env["CODEX_HOME"] == "/tmp/codex"
- assert invocation.env["FCC_CODEX_API_KEY"] == "proxy-token"
- assert "OPENAI_API_KEY" not in invocation.env
- assert "OPENAI_BASE_URL" not in invocation.env
- assert "CODEX_API_KEY" not in invocation.env
- assert invocation.trace_metadata["client_cli_id"] == "codex"
- assert invocation.trace_metadata["codex_binary"] == "codex"
- assert "claude_binary" not in invocation.trace_metadata
- assert CODEX_CLI_ADAPTER.trace_stage == "codex_cli"
- assert CODEX_CLI_ADAPTER.process_launch_event == "codex_cli.process.launch"
- assert CODEX_CLI_ADAPTER.trace_source == "codex_cli"
-
-
-def test_codex_adapter_uses_explicit_codex_binary_when_provided() -> None:
- invocation = CODEX_CLI_ADAPTER.build_task_invocation(
- config=_config(codex_bin="codex-test"),
- request=CliTaskRequest(prompt="hello"),
- base_env={},
- )
-
- assert invocation.argv[:3] == ("codex-test", "exec", "--json")
- assert invocation.trace_metadata["codex_binary"] == "codex-test"
-
-
-def test_codex_adapter_builds_resume_command() -> None:
- invocation = CODEX_CLI_ADAPTER.build_task_invocation(
- config=_config(),
- request=CliTaskRequest(prompt="continue", session_id="sess_123"),
- base_env={},
- )
-
- assert invocation.argv[:4] == ("codex", "exec", "resume", "--json")
- assert "sess_123" in invocation.argv
- assert invocation.argv[-1] == "continue"
- assert invocation.trace_metadata["resume_session_id"] == "sess_123"
-
-
-def test_codex_adapter_fork_starts_new_session() -> None:
- invocation = CODEX_CLI_ADAPTER.build_task_invocation(
- config=_config(),
- request=CliTaskRequest(
- prompt="fork",
- session_id="sess_123",
- fork_session=True,
- ),
- base_env={},
- )
-
- assert "resume" not in invocation.argv
- assert invocation.trace_metadata["resume_session_id"] is None
- assert invocation.trace_metadata["fork_session"] is True
-
-
-def test_codex_adapter_launcher_command_targets_responses_provider() -> None:
- command = CODEX_CLI_ADAPTER.build_launcher_command(
- binary_path="codex.cmd",
- argv=["exec", "hello"],
- settings=_config(model="nvidia_nim/test-model"),
- proxy_root_url="http://127.0.0.1:8082",
- )
-
- assert command[:2] == ["codex.cmd", "-c"]
- assert 'model_provider="fcc"' in command
- assert 'model_providers.fcc.base_url="http://127.0.0.1:8082/v1"' in command
- assert 'model_providers.fcc.env_key="FCC_CODEX_API_KEY"' in command
- assert 'model_providers.fcc.wire_api="responses"' in command
- assert 'model="nvidia_nim/test-model"' in command
- assert command[-2:] == ["exec", "hello"]
-
-
-def test_codex_adapter_launcher_env_strips_openai_credentials() -> None:
- env = CODEX_CLI_ADAPTER.build_launcher_env(
- proxy_root_url="http://127.0.0.1:9191",
- auth_token=" proxy-token ",
- base_env={
- "PATH": "keep",
- "CODEX_HOME": "/tmp/codex",
- "OPENAI_API_KEY": "official-key",
- "OPENAI_BASE_URL": "https://api.openai.com/v1",
- "CODEX_API_KEY": "stale",
- "FCC_CODEX_API_KEY": "old",
- },
- )
-
- assert env["PATH"] == "keep"
- assert env["CODEX_HOME"] == "/tmp/codex"
- assert env["FCC_CODEX_API_KEY"] == "proxy-token"
- assert "OPENAI_API_KEY" not in env
- assert "OPENAI_BASE_URL" not in env
- assert "CODEX_API_KEY" not in env
-
-
-def test_codex_adapter_parses_response_text_delta() -> None:
- events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- '{"type":"response.output_text.delta","delta":"hi","thread_id":"t1"}',
- CliParseState(),
- )
- )
-
- assert events == [
- {"type": "session_info", "session_id": "t1"},
- {
- "type": "content_block_delta",
- "index": 0,
- "delta": {"type": "text_delta", "text": "hi"},
- },
- ]
-
-
-def test_codex_adapter_marks_streamed_message_items_seen() -> None:
- state = CliParseState()
- item = {
- "type": "message",
- "id": "msg1",
- "content": [{"type": "output_text", "text": "hi"}],
- }
-
- delta_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.output_text.delta",
- "item_id": "msg1",
- "output_index": 0,
- "delta": "hi",
- }
- ),
- state,
- )
- )
- item_done_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps({"type": "response.output_item.done", "item": item}),
- state,
- )
- )
- completed_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [item]},
- }
- ),
- state,
- )
- )
-
- assert delta_events == [
- {
- "type": "content_block_delta",
- "index": 0,
- "delta": {"type": "text_delta", "text": "hi"},
- }
- ]
- assert item_done_events == []
- assert completed_events == []
-
-
-def test_codex_adapter_dedupes_output_index_only_message_done() -> None:
- state = CliParseState()
- item = {
- "type": "message",
- "content": [{"type": "output_text", "text": "hi"}],
- }
-
- delta_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.output_text.delta",
- "output_index": 0,
- "delta": "hi",
- }
- ),
- state,
- )
- )
- item_done_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.output_item.done",
- "output_index": 0,
- "item": item,
- }
- ),
- state,
- )
- )
-
- assert delta_events == [
- {
- "type": "content_block_delta",
- "index": 0,
- "delta": {"type": "text_delta", "text": "hi"},
- }
- ]
- assert item_done_events == []
-
-
-def test_codex_adapter_prefers_streamed_output_index_for_final_message_id() -> None:
- state = CliParseState()
- item = {
- "type": "message",
- "id": "msg_1",
- "content": [{"type": "output_text", "text": "hi"}],
- }
-
- delta_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.output_text.delta",
- "output_index": 0,
- "delta": "hi",
- }
- ),
- state,
- )
- )
- item_done_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.output_item.done",
- "output_index": 0,
- "item": item,
- }
- ),
- state,
- )
- )
- completed_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [item]},
- }
- ),
- state,
- )
- )
-
- assert delta_events == [
- {
- "type": "content_block_delta",
- "index": 0,
- "delta": {"type": "text_delta", "text": "hi"},
- }
- ]
- assert item_done_events == []
- assert completed_events == []
-
-
-def test_codex_adapter_dedupes_output_index_only_completed_message() -> None:
- state = CliParseState()
- item = {
- "type": "message",
- "content": [{"type": "output_text", "text": "hi"}],
- }
-
- delta_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.output_text.delta",
- "output_index": 0,
- "delta": "hi",
- }
- ),
- state,
- )
- )
- completed_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [item]},
- }
- ),
- state,
- )
- )
-
- assert delta_events == [
- {
- "type": "content_block_delta",
- "index": 0,
- "delta": {"type": "text_delta", "text": "hi"},
- }
- ]
- assert completed_events == []
-
-
-def test_codex_adapter_output_index_dedupe_scope_advances_after_terminal() -> None:
- state = CliParseState()
- streamed_item = {
- "type": "message",
- "content": [{"type": "output_text", "text": "first"}],
- }
- fallback_item = {
- "type": "message",
- "content": [{"type": "output_text", "text": "second"}],
- }
-
- list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.output_text.delta",
- "output_index": 0,
- "delta": "first",
- }
- ),
- state,
- )
- )
- first_completed_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [streamed_item]},
- }
- ),
- state,
- )
- )
- second_completed_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [fallback_item]},
- }
- ),
- state,
- )
- )
-
- assert first_completed_events == []
- assert second_completed_events == [
- {
- "type": "assistant",
- "message": {"content": [{"type": "text", "text": "second"}]},
- }
- ]
-
-
-def test_codex_adapter_output_index_dedupe_scope_advances_after_failed_response() -> (
- None
-):
- state = CliParseState()
- fallback_item = {
- "type": "message",
- "content": [{"type": "output_text", "text": "second"}],
- }
-
- list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.output_text.delta",
- "output_index": 0,
- "delta": "first",
- }
- ),
- state,
- )
- )
- failed_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.failed",
- "response": {
- "error": {
- "message": "upstream failed",
- },
- },
- }
- ),
- state,
- )
- )
- completed_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [fallback_item]},
- }
- ),
- state,
- )
- )
-
- assert failed_events == [{"type": "error", "error": {"message": "upstream failed"}}]
- assert completed_events == [
- {
- "type": "assistant",
- "message": {"content": [{"type": "text", "text": "second"}]},
- }
- ]
-
-
-def test_codex_adapter_parses_response_reasoning_text_delta() -> None:
- events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- (
- '{"type":"response.reasoning_text.delta","delta":"think",'
- '"output_index":2,"thread_id":"t1"}'
- ),
- CliParseState(),
- )
- )
-
- assert events == [
- {"type": "session_info", "session_id": "t1"},
- {
- "type": "content_block_delta",
- "index": 2,
- "delta": {"type": "thinking_delta", "thinking": "think"},
- },
- ]
-
-
-def test_codex_adapter_parses_completed_function_call_item() -> None:
- line = json.dumps(
- {
- "type": "response.output_item.done",
- "item": {
- "type": "function_call",
- "call_id": "call_1",
- "name": "echo",
- "arguments": '{"value":"FCC"}',
- },
- }
- )
-
- events = list(CODEX_CLI_ADAPTER.parse_stdout_line(line, CliParseState()))
-
- assert events == [
- {
- "type": "assistant",
- "message": {
- "content": [
- {
- "type": "tool_use",
- "id": "call_1",
- "name": "echo",
- "input": {"value": "FCC"},
- }
- ]
- },
- }
- ]
-
-
-def test_codex_adapter_parses_completed_custom_tool_call_item() -> None:
- line = json.dumps(
- {
- "type": "response.output_item.done",
- "item": {
- "type": "custom_tool_call",
- "call_id": "call_1",
- "name": "apply_patch",
- "input": "*** Begin Patch",
- },
- }
- )
-
- events = list(CODEX_CLI_ADAPTER.parse_stdout_line(line, CliParseState()))
-
- assert events == [
- {
- "type": "assistant",
- "message": {
- "content": [
- {
- "type": "tool_use",
- "id": "call_1",
- "name": "apply_patch",
- "input": {"input": "*** Begin Patch"},
- }
- ]
- },
- }
- ]
-
-
-def test_codex_adapter_dedupes_output_item_done_against_completed_output() -> None:
- state = CliParseState()
- item = {
- "type": "custom_tool_call",
- "id": "ctc_1",
- "call_id": "call_1",
- "name": "apply_patch",
- "input": "*** Begin Patch",
- }
-
- item_done_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps({"type": "response.output_item.done", "item": item}),
- state,
- )
- )
- completed_events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [item]},
- }
- ),
- state,
- )
- )
-
- assert item_done_events == [
- {
- "type": "assistant",
- "message": {
- "content": [
- {
- "type": "tool_use",
- "id": "call_1",
- "name": "apply_patch",
- "input": {"input": "*** Begin Patch"},
- }
- ]
- },
- }
- ]
- assert completed_events == []
-
-
-def test_codex_adapter_completed_output_is_fallback_for_unseen_message_item() -> None:
- item = {
- "type": "message",
- "id": "msg1",
- "content": [{"type": "output_text", "text": "hi"}],
- }
-
- events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [item]},
- }
- ),
- CliParseState(),
- )
- )
-
- assert events == [
- {
- "type": "assistant",
- "message": {"content": [{"type": "text", "text": "hi"}]},
- }
- ]
-
-
-def test_codex_adapter_completed_output_is_fallback_for_unseen_tool_item() -> None:
- item = {
- "type": "function_call",
- "id": "fc_1",
- "call_id": "call_1",
- "name": "echo",
- "arguments": '{"value":"FCC"}',
- }
-
- events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- json.dumps(
- {
- "type": "response.completed",
- "response": {"output": [item]},
- }
- ),
- CliParseState(),
- )
- )
-
- assert events == [
- {
- "type": "assistant",
- "message": {
- "content": [
- {
- "type": "tool_use",
- "id": "call_1",
- "name": "echo",
- "input": {"value": "FCC"},
- }
- ]
- },
- }
- ]
-
-
-def test_codex_adapter_reasoning_summary_delta_remains_raw() -> None:
- events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- (
- '{"type":"response.reasoning_summary_text.delta",'
- '"delta":"summary","thread_id":"t1"}'
- ),
- CliParseState(),
- )
- )
-
- assert events == [
- {"type": "session_info", "session_id": "t1"},
- {
- "type": "raw",
- "content": (
- '{"type":"response.reasoning_summary_text.delta",'
- '"delta":"summary","thread_id":"t1"}'
- ),
- },
- ]
-
-
-def test_codex_adapter_unknown_json_becomes_raw_event() -> None:
- events = list(
- CODEX_CLI_ADAPTER.parse_stdout_line(
- '{"type":"thread.started","thread_id":"t1"}',
- CliParseState(),
- )
- )
-
- assert events == [
- {"type": "session_info", "session_id": "t1"},
- {"type": "raw", "content": '{"type":"thread.started","thread_id":"t1"}'},
- ]
diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py
index 03ab929c..591b8bf9 100644
--- a/tests/cli/test_cli.py
+++ b/tests/cli/test_cli.py
@@ -3,8 +3,7 @@
import asyncio
import json
import os
-from collections.abc import Iterable, Mapping
-from typing import Any, cast
+from typing import cast
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -147,14 +146,14 @@ class TestCLIParser:
# --- CLI Session Tests ---
-class TestCLISession:
- """Test CLISession."""
+class TestManagedClaudeSession:
+ """Test ManagedClaudeSession."""
def test_session_init(self):
- """Test CLISession initialization."""
- from cli.session import CLISession
+ """Test ManagedClaudeSession initialization."""
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession(
+ session = ManagedClaudeSession(
workspace_path="/tmp/test",
api_url="http://localhost:8082/v1",
allowed_dirs=["/home/user/projects"],
@@ -165,42 +164,40 @@ class TestCLISession:
def test_session_extract_session_id(self):
"""Test session ID extraction from various event formats."""
- from cli.session import CLISession
-
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ from cli.managed.claude import extract_managed_claude_session_id
# Direct session_id field
- assert session._extract_session_id({"session_id": "abc123"}) == "abc123"
- assert session._extract_session_id({"sessionId": "abc123"}) == "abc123"
+ assert extract_managed_claude_session_id({"session_id": "abc123"}) == "abc123"
+ assert extract_managed_claude_session_id({"sessionId": "abc123"}) == "abc123"
# Nested in init
assert (
- session._extract_session_id({"init": {"session_id": "nested123"}})
+ extract_managed_claude_session_id({"init": {"session_id": "nested123"}})
== "nested123"
)
# Nested in result
assert (
- session._extract_session_id({"result": {"session_id": "res123"}})
+ extract_managed_claude_session_id({"result": {"session_id": "res123"}})
== "res123"
)
# Conversation id
assert (
- session._extract_session_id({"conversation": {"id": "conv123"}})
+ extract_managed_claude_session_id({"conversation": {"id": "conv123"}})
== "conv123"
)
# No session ID
- assert session._extract_session_id({"type": "message"}) is None
- assert session._extract_session_id("not a dict") is None
+ assert extract_managed_claude_session_id({"type": "message"}) is None
+ assert extract_managed_claude_session_id("not a dict") is None
@pytest.mark.asyncio
async def test_start_task_basic_flow(self):
"""Test start_task running a basic command flow."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
# Mock subprocess
mock_process = AsyncMock()
@@ -242,9 +239,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_with_session_resume(self):
"""Test resuming an existing session."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = AsyncMock()
mock_process.stdout.read.side_effect = [
@@ -269,9 +266,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_with_session_resume_and_fork(self):
"""Test resuming an existing session and forking."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = AsyncMock()
mock_process.stdout.read.side_effect = [b""] # Immediate EOF
@@ -296,9 +293,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_process_failure_with_stderr(self):
"""Test process exit with error code and stderr output."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = AsyncMock()
mock_process.stdout.read.side_effect = [b""] # No stdout
@@ -324,9 +321,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_stderr_while_stdout_streams(self):
"""Stderr is drained concurrently so stdout streaming is not blocked."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = AsyncMock()
mock_process.stdout.read.side_effect = [
@@ -353,7 +350,7 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_drain_stderr_bounded_retains_cap_but_drains_to_eof(self):
"""Oversized stderr is fully drained so the pipe cannot deadlock; capture is bounded."""
- from cli.session import _MAX_STDERR_CAPTURE_BYTES, CLISession
+ from cli.managed.session import _MAX_STDERR_CAPTURE_BYTES, ManagedClaudeSession
total_len = _MAX_STDERR_CAPTURE_BYTES + 100_000
remaining: dict[str, int] = {"n": total_len}
@@ -370,7 +367,7 @@ class TestCLISession:
class _FakeProcess:
stderr = _FakeStderr()
- out = await CLISession._drain_stderr_bounded(
+ out = await ManagedClaudeSession._drain_stderr_bounded(
cast(asyncio.subprocess.Process, _FakeProcess())
)
assert len(out) == _MAX_STDERR_CAPTURE_BYTES
@@ -380,9 +377,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_stop_session(self):
"""Test stopping the session process."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = MagicMock()
mock_process.returncode = None # Running
@@ -391,7 +388,7 @@ class TestCLISession:
session.process = mock_process
- with patch("cli.session.kill_pid_tree_best_effort") as kill_tree:
+ with patch("cli.managed.session.kill_pid_tree_best_effort") as kill_tree:
stopped = await session.stop()
assert stopped is True
@@ -401,9 +398,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_stop_session_timeout_force_kill(self):
"""Test force kill if terminate times out."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = MagicMock()
mock_process.returncode = None
@@ -419,7 +416,7 @@ class TestCLISession:
session.process = mock_process
- with patch("cli.session.kill_pid_tree_best_effort") as kill_tree:
+ with patch("cli.managed.session.kill_pid_tree_best_effort") as kill_tree:
stopped = await session.stop()
assert stopped is True
@@ -429,9 +426,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_split_buffer(self):
"""Test handling of JSON split across chunks."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = AsyncMock()
# Split json: {"type": "mess... age"}
@@ -458,9 +455,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_remnant_buffer(self):
"""Test handling of buffer remnant at EOF (no newline at end)."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = AsyncMock()
mock_process.stdout.read.side_effect = [
@@ -485,10 +482,10 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_non_v1_url(self):
"""Test start_task with a non-v1 URL."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
# URL not ending in /v1
- session = CLISession("/tmp", "http://localhost:8082")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082")
mock_process = AsyncMock()
mock_process.stdout.read.side_effect = [b""]
@@ -510,9 +507,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_sets_proxy_auth_token(self):
"""Test start_task forwards configured proxy auth to Claude Code."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession(
+ session = ManagedClaudeSession(
"/tmp", "http://localhost:8082/v1", auth_token="proxy-token"
)
@@ -540,9 +537,11 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_uses_sentinel_when_proxy_auth_blank(self):
"""Test start_task does not leak inherited Claude auth into proxy calls."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1", auth_token="")
+ session = ManagedClaudeSession(
+ "/tmp", "http://localhost:8082/v1", auth_token=""
+ )
mock_process = AsyncMock()
mock_process.stdout.read.side_effect = [b""]
@@ -565,9 +564,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_allowed_dirs(self):
"""Test start_task includes allowed dirs in command."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession(
+ session = ManagedClaudeSession(
"/tmp", "http://localhost:8082/v1", allowed_dirs=["/dir1", "/dir2"]
)
@@ -591,9 +590,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_plans_directory(self):
"""Test start_task includes --settings plansDirectory when plans_directory set."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession(
+ session = ManagedClaudeSession(
"/tmp",
"http://localhost:8082/v1",
plans_directory="./agent_workspace/plans",
@@ -621,9 +620,9 @@ class TestCLISession:
@pytest.mark.asyncio
async def test_start_task_json_error(self):
"""Test handling of non-JSON output from CLI."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = AsyncMock()
mock_process.stdout.read.side_effect = [b"Not valid json\n", b""]
@@ -640,123 +639,12 @@ class TestCLISession:
assert len(events) == 1
assert events[0]["content"] == "Not valid json"
- @pytest.mark.asyncio
- async def test_start_task_uses_injected_client_cli_adapter(self, tmp_path):
- """CLISession delegates argv/env/line parsing to the injected adapter."""
- from cli.adapters.base import CliInvocation, CliParseState, CliTaskRequest
- from cli.session import CLISession
-
- class FakeClientCliAdapter:
- id = "fake"
- display_name = "Fake CLI"
- default_binary = "fake"
- install_hint = "Install Fake CLI"
- trace_stage = "claude_cli"
- process_launch_event = "claude_cli.process.launch"
- trace_source = "claude_cli"
-
- def __init__(self) -> None:
- self.request: CliTaskRequest | None = None
-
- def build_task_invocation(
- self,
- *,
- config: Any,
- request: CliTaskRequest,
- base_env: Mapping[str, str],
- ) -> CliInvocation:
- self.request = request
- return CliInvocation(
- argv=("fake-cli", "--prompt", request.prompt),
- env={"FAKE_ENV": base_env.get("KEEP_ME", "")},
- cwd=config.workspace_path,
- trace_metadata={"client_cli_id": self.id},
- )
-
- def parse_stdout_line(
- self, line: str, state: CliParseState
- ) -> Iterable[dict[str, Any]]:
- if not state.session_id_extracted:
- state.session_id_extracted = True
- yield {"type": "session_info", "session_id": "fake_session"}
- yield {"type": "message", "content": line}
-
- def extract_session_id(self, event: Any) -> str | None:
- if isinstance(event, dict):
- value = event.get("session_id")
- return value if isinstance(value, str) else None
- return None
-
- def get_launcher_binary_name(self, settings: Any) -> str:
- return self.default_binary
-
- def build_launcher_command(
- self,
- *,
- binary_path: str,
- argv: Iterable[str],
- settings: Any,
- proxy_root_url: str,
- ) -> list[str]:
- return [binary_path, *argv]
-
- def build_launcher_env(
- self,
- *,
- proxy_root_url: str,
- auth_token: str,
- base_env: Mapping[str, str],
- ) -> dict[str, str]:
- return dict(base_env)
-
- adapter = FakeClientCliAdapter()
- session = CLISession(
- str(tmp_path),
- "http://localhost:8082/v1",
- client_cli_adapter=adapter,
- )
-
- mock_process = AsyncMock()
- mock_process.stdout.read.side_effect = [b"hello\n", b""]
- mock_process.stderr.read.return_value = b""
- mock_process.wait.return_value = 0
- mock_process.returncode = 0
-
- with (
- patch.dict(os.environ, {"KEEP_ME": "yes"}, clear=False),
- patch(
- "asyncio.create_subprocess_exec", new_callable=AsyncMock
- ) as mock_exec,
- ):
- mock_exec.return_value = mock_process
- events = [
- e
- async for e in session.start_task(
- "adapter prompt",
- session_id="sess_fake",
- fork_session=True,
- )
- ]
-
- assert adapter.request == CliTaskRequest(
- prompt="adapter prompt",
- session_id="sess_fake",
- fork_session=True,
- )
- assert mock_exec.call_args.args == ("fake-cli", "--prompt", "adapter prompt")
- assert mock_exec.call_args.kwargs["env"] == {"FAKE_ENV": "yes"}
- assert session.current_session_id == "fake_session"
- assert events[:2] == [
- {"type": "session_info", "session_id": "fake_session"},
- {"type": "message", "content": "hello"},
- ]
-
@pytest.mark.asyncio
async def test_stop_exception(self):
"""Test exception handling during stop."""
- from cli.session import CLISession
+ from cli.managed.session import ManagedClaudeSession
- session = CLISession("/tmp", "http://localhost:8082/v1")
+ session = ManagedClaudeSession("/tmp", "http://localhost:8082/v1")
mock_process = MagicMock()
mock_process.returncode = None
@@ -764,22 +652,22 @@ class TestCLISession:
session.process = mock_process
with patch(
- "cli.session.kill_pid_tree_best_effort",
+ "cli.managed.session.kill_pid_tree_best_effort",
side_effect=RuntimeError("Permission denied"),
):
stopped = await session.stop()
assert stopped is False
-class TestCLISessionManager:
- """Test CLISessionManager."""
+class TestManagedClaudeSessionManager:
+ """Test ManagedClaudeSessionManager."""
@pytest.mark.asyncio
async def test_manager_create_session(self):
"""Test creating a new session."""
- from cli.manager import CLISessionManager
+ from cli.managed.manager import ManagedClaudeSessionManager
- manager = CLISessionManager(
+ manager = ManagedClaudeSessionManager(
workspace_path="/tmp/test",
api_url="http://localhost:8082/v1",
)
@@ -792,9 +680,9 @@ class TestCLISessionManager:
@pytest.mark.asyncio
async def test_manager_reuse_session(self):
"""Test reusing an existing session."""
- from cli.manager import CLISessionManager
+ from cli.managed.manager import ManagedClaudeSessionManager
- manager = CLISessionManager(
+ manager = ManagedClaudeSessionManager(
workspace_path="/tmp/test",
api_url="http://localhost:8082/v1",
)
@@ -811,9 +699,9 @@ class TestCLISessionManager:
@pytest.mark.asyncio
async def test_manager_stats(self):
"""Test manager stats."""
- from cli.manager import CLISessionManager
+ from cli.managed.manager import ManagedClaudeSessionManager
- manager = CLISessionManager(
+ manager = ManagedClaudeSessionManager(
workspace_path="/tmp/test",
api_url="http://localhost:8082/v1",
)
diff --git a/tests/cli/test_cli_manager_edge_cases.py b/tests/cli/test_cli_manager_edge_cases.py
index e0f4a8ab..c1a15b79 100644
--- a/tests/cli/test_cli_manager_edge_cases.py
+++ b/tests/cli/test_cli_manager_edge_cases.py
@@ -3,23 +3,17 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-def _fake_client_cli_adapter():
- adapter = MagicMock()
- adapter.id = "fake"
- return adapter
-
-
@pytest.mark.asyncio
async def test_register_real_session_id_moves_pending_to_active_and_maps():
- from cli.manager import CLISessionManager
+ from cli.managed.manager import ManagedClaudeSessionManager
- with patch("cli.manager.CLISession") as mock_session_cls:
+ with patch("cli.managed.manager.ManagedClaudeSession") as mock_session_cls:
mock_session = MagicMock()
mock_session.is_busy = False
mock_session.stop = AsyncMock(return_value=True)
mock_session_cls.return_value = mock_session
- manager = CLISessionManager(
+ manager = ManagedClaudeSessionManager(
workspace_path="/tmp", api_url="http://x/v1", auth_token="proxy-token"
)
session, temp_id, is_new = await manager.get_or_create_session()
@@ -40,24 +34,26 @@ async def test_register_real_session_id_moves_pending_to_active_and_maps():
@pytest.mark.asyncio
async def test_register_real_session_id_missing_temp_id_returns_false():
- from cli.manager import CLISessionManager
+ from cli.managed.manager import ManagedClaudeSessionManager
- manager = CLISessionManager(workspace_path="/tmp", api_url="http://x/v1")
+ manager = ManagedClaudeSessionManager(workspace_path="/tmp", api_url="http://x/v1")
ok = await manager.register_real_session_id("missing", "real_1")
assert ok is False
@pytest.mark.asyncio
async def test_remove_session_pending_stops_and_returns_true():
- from cli.manager import CLISessionManager
+ from cli.managed.manager import ManagedClaudeSessionManager
- with patch("cli.manager.CLISession") as mock_session_cls:
+ with patch("cli.managed.manager.ManagedClaudeSession") as mock_session_cls:
mock_session = MagicMock()
mock_session.is_busy = False
mock_session.stop = AsyncMock(return_value=True)
mock_session_cls.return_value = mock_session
- manager = CLISessionManager(workspace_path="/tmp", api_url="http://x/v1")
+ manager = ManagedClaudeSessionManager(
+ workspace_path="/tmp", api_url="http://x/v1"
+ )
_, temp_id, _ = await manager.get_or_create_session()
removed = await manager.remove_session(temp_id)
@@ -67,15 +63,17 @@ async def test_remove_session_pending_stops_and_returns_true():
@pytest.mark.asyncio
async def test_remove_session_active_removes_temp_mapping():
- from cli.manager import CLISessionManager
+ from cli.managed.manager import ManagedClaudeSessionManager
- with patch("cli.manager.CLISession") as mock_session_cls:
+ with patch("cli.managed.manager.ManagedClaudeSession") as mock_session_cls:
mock_session = MagicMock()
mock_session.is_busy = False
mock_session.stop = AsyncMock(return_value=True)
mock_session_cls.return_value = mock_session
- manager = CLISessionManager(workspace_path="/tmp", api_url="http://x/v1")
+ manager = ManagedClaudeSessionManager(
+ workspace_path="/tmp", api_url="http://x/v1"
+ )
_, temp_id, _ = await manager.get_or_create_session()
await manager.register_real_session_id(temp_id, "real_1")
@@ -90,9 +88,9 @@ async def test_remove_session_active_removes_temp_mapping():
@pytest.mark.asyncio
async def test_stop_all_handles_stop_exceptions():
- from cli.manager import CLISessionManager
+ from cli.managed.manager import ManagedClaudeSessionManager
- manager = CLISessionManager(workspace_path="/tmp", api_url="http://x/v1")
+ manager = ManagedClaudeSessionManager(workspace_path="/tmp", api_url="http://x/v1")
s1 = MagicMock()
s1.stop = AsyncMock(side_effect=RuntimeError("boom"))
@@ -110,23 +108,3 @@ async def test_stop_all_handles_stop_exceptions():
s2.stop.assert_awaited_once()
assert manager.get_stats()["active_sessions"] == 0
assert manager.get_stats()["pending_sessions"] == 0
-
-
-async def test_get_or_create_session_passes_client_cli_adapter():
- from cli.manager import CLISessionManager
-
- adapter = _fake_client_cli_adapter()
- with patch("cli.manager.CLISession") as mock_session_cls:
- mock_session = MagicMock()
- mock_session.is_busy = False
- mock_session_cls.return_value = mock_session
-
- manager = CLISessionManager(
- workspace_path="/tmp",
- api_url="http://x/v1",
- client_cli_adapter=adapter,
- )
- await manager.get_or_create_session()
-
- assert mock_session_cls.call_args.kwargs["client_cli_adapter"] is adapter
diff --git a/tests/cli/test_cli_ownership.py b/tests/cli/test_cli_ownership.py
index 3c837244..ba6ef96b 100644
--- a/tests/cli/test_cli_ownership.py
+++ b/tests/cli/test_cli_ownership.py
@@ -2,11 +2,11 @@ from __future__ import annotations
from pathlib import Path
-from cli.session import CLISession
+from cli.managed.session import ManagedClaudeSession
def test_cli_session_owns_typed_runner_config(tmp_path: Path) -> None:
- session = CLISession(
+ session = ManagedClaudeSession(
workspace_path=str(tmp_path),
api_url="http://127.0.0.1:8082/v1",
allowed_dirs=[str(tmp_path)],
diff --git a/tests/cli/test_codex_model_catalog.py b/tests/cli/test_codex_model_catalog.py
index 391a60ed..fec6b6a3 100644
--- a/tests/cli/test_codex_model_catalog.py
+++ b/tests/cli/test_codex_model_catalog.py
@@ -9,7 +9,7 @@ from typing import Any, cast
import pytest
-from cli.codex_model_catalog import (
+from cli.launchers.codex_model_catalog import (
build_codex_model_catalog,
write_codex_model_catalog,
)
diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.py
index 7f27d90e..a473bf6f 100644
--- a/tests/cli/test_entrypoints.py
+++ b/tests/cli/test_entrypoints.py
@@ -174,8 +174,8 @@ def test_cli_scripts_are_registered() -> None:
scripts = pyproject["project"]["scripts"]
assert scripts["fcc-server"] == "cli.entrypoints:serve"
assert scripts["free-claude-code"] == "cli.entrypoints:serve"
- assert scripts["fcc-claude"] == "cli.entrypoints:launch_claude"
- assert scripts["fcc-codex"] == "cli.entrypoints:launch_codex"
+ assert scripts["fcc-claude"] == "cli.launchers.claude:launch"
+ assert scripts["fcc-codex"] == "cli.launchers.codex:launch"
def test_schedule_open_admin_browser_opens_when_health_ready(
@@ -199,7 +199,7 @@ def test_schedule_open_admin_browser_opens_when_health_ready(
with (
patch.object(entrypoints.threading, "Thread", ImmediateThread),
- patch.object(entrypoints, "_preflight_proxy", return_value=None),
+ patch.object(entrypoints, "preflight_proxy", return_value=None),
patch.object(
entrypoints.webbrowser,
"open",
@@ -309,11 +309,12 @@ def test_serve_handles_keyboard_interrupt_without_traceback() -> None:
def test_claude_child_env_targets_current_proxy_config() -> None:
- from cli.entrypoints import _claude_child_env
+ from cli.launchers.claude import build_claude_launcher_env
- env = _claude_child_env(
- _launcher_settings(port=9090, token=" proxy-token "),
- {
+ env = build_claude_launcher_env(
+ proxy_root_url="http://127.0.0.1:9090",
+ auth_token=" proxy-token ",
+ base_env={
"PATH": "keep",
"ANTHROPIC_BASE_URL": "https://api.anthropic.com",
"ANTHROPIC_AUTH_TOKEN": "old-token",
@@ -330,11 +331,12 @@ def test_claude_child_env_targets_current_proxy_config() -> None:
def test_claude_child_env_uses_sentinel_for_blank_configured_auth_token() -> None:
- from cli.entrypoints import _claude_child_env
+ from cli.launchers.claude import build_claude_launcher_env
- env = _claude_child_env(
- _launcher_settings(token=""),
- {
+ env = build_claude_launcher_env(
+ proxy_root_url="http://127.0.0.1:8082",
+ auth_token="",
+ base_env={
"ANTHROPIC_AUTH_TOKEN": "inherited-token",
"ANTHROPIC_API_KEY": "official-key",
},
@@ -347,7 +349,7 @@ def test_claude_child_env_uses_sentinel_for_blank_configured_auth_token() -> Non
def test_launch_claude_passes_args_and_child_env(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- from cli.entrypoints import launch_claude
+ from cli.launchers.claude import launch
monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com")
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "old-token")
@@ -355,19 +357,18 @@ def test_launch_claude_passes_args_and_child_env(
settings = _launcher_settings(port=9191, token="proxy-token")
with (
- patch("cli.entrypoints.get_settings", return_value=settings),
- patch("cli.entrypoints._preflight_proxy", return_value=None),
- patch("cli.entrypoints.shutil.which", return_value="resolved-claude.cmd"),
- patch("cli.entrypoints.urlopen") as urlopen,
- patch("cli.entrypoints.subprocess.Popen") as popen,
- patch("cli.entrypoints.register_pid") as register_pid,
- patch("cli.entrypoints.unregister_pid") as unregister_pid,
+ patch("cli.launchers.claude.get_settings", return_value=settings),
+ patch("cli.launchers.claude.preflight_proxy", return_value=None),
+ patch("cli.launchers.common.shutil.which", return_value="resolved-claude.cmd"),
+ patch("cli.launchers.common.subprocess.Popen") as popen,
+ patch("cli.launchers.common.register_pid") as register_pid,
+ patch("cli.launchers.common.unregister_pid") as unregister_pid,
pytest.raises(SystemExit) as exc_info,
):
process = popen.return_value
process.pid = 12345
process.wait.return_value = 7
- launch_claude(["--model", "sonnet"])
+ launch(["--model", "sonnet"])
assert exc_info.value.code == 7
popen.assert_called_once()
@@ -380,14 +381,13 @@ def test_launch_claude_passes_args_and_child_env(
assert child_env["KEEP_ME"] == "yes"
register_pid.assert_called_once_with(12345)
unregister_pid.assert_called_once_with(12345)
- urlopen.assert_not_called()
def test_launch_codex_passes_responses_config_and_child_env(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
- from cli.entrypoints import launch_codex
+ from cli.launchers.codex import launch
monkeypatch.setenv("OPENAI_API_KEY", "official-key")
monkeypatch.setenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
@@ -419,20 +419,22 @@ def test_launch_codex_passes_responses_config_and_child_env(
)
with (
- patch("cli.entrypoints.get_settings", return_value=settings),
- patch("cli.entrypoints._preflight_proxy", return_value=None),
- patch("cli.entrypoints.shutil.which", return_value="resolved-codex.cmd"),
- patch("cli.entrypoints.codex_model_catalog_path", return_value=catalog_path),
- patch("cli.entrypoints.urlopen", side_effect=fake_urlopen),
- patch("cli.entrypoints.subprocess.Popen") as popen,
- patch("cli.entrypoints.register_pid") as register_pid,
- patch("cli.entrypoints.unregister_pid") as unregister_pid,
+ patch("cli.launchers.codex.get_settings", return_value=settings),
+ patch("cli.launchers.codex.preflight_proxy", return_value=None),
+ patch("cli.launchers.common.shutil.which", return_value="resolved-codex.cmd"),
+ patch(
+ "cli.launchers.codex.codex_model_catalog_path", return_value=catalog_path
+ ),
+ patch("cli.launchers.codex.urlopen", side_effect=fake_urlopen),
+ patch("cli.launchers.common.subprocess.Popen") as popen,
+ patch("cli.launchers.common.register_pid") as register_pid,
+ patch("cli.launchers.common.unregister_pid") as unregister_pid,
pytest.raises(SystemExit) as exc_info,
):
process = popen.return_value
process.pid = 12345
process.wait.return_value = 0
- launch_codex(["exec", "hello"])
+ launch(["exec", "hello"])
assert exc_info.value.code == 0
command = popen.call_args.args[0]
@@ -464,28 +466,28 @@ def test_launch_codex_catalog_failure_warns_and_continues(
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
- from cli.entrypoints import launch_codex
+ from cli.launchers.codex import launch
settings = _launcher_settings(port=9191, token="proxy-token")
with (
- patch("cli.entrypoints.get_settings", return_value=settings),
- patch("cli.entrypoints._preflight_proxy", return_value=None),
- patch("cli.entrypoints.shutil.which", return_value="resolved-codex.cmd"),
+ patch("cli.launchers.codex.get_settings", return_value=settings),
+ patch("cli.launchers.codex.preflight_proxy", return_value=None),
+ patch("cli.launchers.common.shutil.which", return_value="resolved-codex.cmd"),
patch(
- "cli.entrypoints.codex_model_catalog_path",
+ "cli.launchers.codex.codex_model_catalog_path",
return_value=tmp_path / "codex-model-catalog.json",
),
- patch("cli.entrypoints.urlopen", side_effect=URLError("boom")),
- patch("cli.entrypoints.subprocess.Popen") as popen,
- patch("cli.entrypoints.register_pid"),
- patch("cli.entrypoints.unregister_pid"),
+ patch("cli.launchers.codex.urlopen", side_effect=URLError("boom")),
+ patch("cli.launchers.common.subprocess.Popen") as popen,
+ patch("cli.launchers.common.register_pid"),
+ patch("cli.launchers.common.unregister_pid"),
pytest.raises(SystemExit) as exc_info,
):
process = popen.return_value
process.pid = 12345
process.wait.return_value = 0
- launch_codex(["exec", "hello"])
+ launch(["exec", "hello"])
assert exc_info.value.code == 0
command = popen.call_args.args[0]
@@ -496,25 +498,25 @@ def test_launch_codex_catalog_failure_warns_and_continues(
def test_launch_claude_keyboard_interrupt_kills_child_tree() -> None:
- from cli.entrypoints import launch_claude
+ from cli.launchers.claude import launch
settings = _launcher_settings(port=9191, token="proxy-token")
with (
- patch("cli.entrypoints.get_settings", return_value=settings),
- patch("cli.entrypoints._preflight_proxy", return_value=None),
- patch("cli.entrypoints.shutil.which", return_value="resolved-claude.cmd"),
- patch("cli.entrypoints.subprocess.Popen") as popen,
- patch("cli.entrypoints.register_pid"),
- patch("cli.entrypoints.kill_pid_tree_best_effort") as kill_tree,
- patch("cli.entrypoints.unregister_pid") as unregister_pid,
+ patch("cli.launchers.claude.get_settings", return_value=settings),
+ patch("cli.launchers.claude.preflight_proxy", return_value=None),
+ patch("cli.launchers.common.shutil.which", return_value="resolved-claude.cmd"),
+ patch("cli.launchers.common.subprocess.Popen") as popen,
+ patch("cli.launchers.common.register_pid"),
+ patch("cli.launchers.common.kill_pid_tree_best_effort") as kill_tree,
+ patch("cli.launchers.common.unregister_pid") as unregister_pid,
pytest.raises(KeyboardInterrupt),
):
process = popen.return_value
process.pid = 12345
process.wait.side_effect = [KeyboardInterrupt, 0]
- launch_claude([])
+ launch([])
kill_tree.assert_called_once_with(12345)
unregister_pid.assert_called_once_with(12345)
@@ -523,17 +525,17 @@ def test_launch_claude_keyboard_interrupt_kills_child_tree() -> None:
def test_launch_claude_exits_when_command_cannot_be_resolved(
capsys: pytest.CaptureFixture[str],
) -> None:
- from cli.entrypoints import launch_claude
+ from cli.launchers.claude import launch
settings = _launcher_settings()
with (
- patch("cli.entrypoints.get_settings", return_value=settings),
- patch("cli.entrypoints._preflight_proxy", return_value=None),
- patch("cli.entrypoints.shutil.which", return_value=None),
- patch("cli.entrypoints.subprocess.Popen") as popen,
+ patch("cli.launchers.claude.get_settings", return_value=settings),
+ patch("cli.launchers.claude.preflight_proxy", return_value=None),
+ patch("cli.launchers.common.shutil.which", return_value=None),
+ patch("cli.launchers.common.subprocess.Popen") as popen,
pytest.raises(SystemExit) as exc_info,
):
- launch_claude([])
+ launch([])
assert exc_info.value.code == 127
popen.assert_not_called()
@@ -545,19 +547,21 @@ def test_launch_claude_exits_when_command_cannot_be_resolved(
def test_launch_claude_unreachable_proxy_exits_with_hint(
capsys: pytest.CaptureFixture[str],
) -> None:
- from cli.entrypoints import launch_claude
+ from cli.launchers.claude import launch
settings = _launcher_settings(port=9393)
with (
- patch("cli.entrypoints.get_settings", return_value=settings),
- patch("cli.entrypoints._preflight_proxy", return_value="connection refused"),
- patch("cli.entrypoints.subprocess.run") as run,
+ patch("cli.launchers.claude.get_settings", return_value=settings),
+ patch(
+ "cli.launchers.claude.preflight_proxy", return_value="connection refused"
+ ),
+ patch("cli.launchers.common.subprocess.Popen") as popen,
pytest.raises(SystemExit) as exc_info,
):
- launch_claude([])
+ launch([])
assert exc_info.value.code == 1
- run.assert_not_called()
+ popen.assert_not_called()
captured = capsys.readouterr()
assert "http://127.0.0.1:9393" in captured.err
assert "fcc-server" in captured.err
diff --git a/tests/cli/test_managed_claude.py b/tests/cli/test_managed_claude.py
new file mode 100644
index 00000000..f638d2c0
--- /dev/null
+++ b/tests/cli/test_managed_claude.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import os
+
+from cli.managed.claude import (
+ ManagedClaudeConfig,
+ ManagedClaudeParseState,
+ ManagedClaudeTaskRequest,
+ build_managed_claude_env,
+ build_managed_claude_invocation,
+ extract_managed_claude_session_id,
+ parse_managed_claude_stdout_line,
+)
+
+
+def _config(**overrides: object) -> ManagedClaudeConfig:
+ workspace_path = overrides.get("workspace_path", os.path.normpath("/tmp/workspace"))
+ api_url = overrides.get("api_url", "http://localhost:8082/v1")
+ raw_allowed_dirs = overrides.get("allowed_dirs")
+ allowed_dirs: list[str] = []
+ if raw_allowed_dirs is not None:
+ assert isinstance(raw_allowed_dirs, list)
+ for directory in raw_allowed_dirs:
+ assert isinstance(directory, str)
+ allowed_dirs.append(directory)
+ plans_directory = overrides.get("plans_directory")
+ claude_bin = overrides.get("claude_bin", "claude")
+ auth_token = overrides.get("auth_token", "proxy-token")
+
+ assert isinstance(workspace_path, str)
+ assert isinstance(api_url, str)
+ assert plans_directory is None or isinstance(plans_directory, str)
+ assert isinstance(claude_bin, str)
+ assert isinstance(auth_token, str)
+ return ManagedClaudeConfig(
+ workspace_path=workspace_path,
+ api_url=api_url,
+ allowed_dirs=allowed_dirs,
+ plans_directory=plans_directory,
+ claude_bin=claude_bin,
+ auth_token=auth_token,
+ )
+
+
+def test_managed_claude_builds_new_task_command_and_env() -> None:
+ invocation = build_managed_claude_invocation(
+ config=_config(
+ allowed_dirs=[os.path.normpath("/tmp/extra")],
+ plans_directory=".plans",
+ ),
+ request=ManagedClaudeTaskRequest(prompt="hello"),
+ base_env={"PATH": "keep", "ANTHROPIC_API_KEY": "official"},
+ )
+
+ assert invocation.argv[:2] == ("claude", "-p")
+ assert "hello" in invocation.argv
+ assert "--output-format" in invocation.argv
+ assert "stream-json" in invocation.argv
+ assert "--add-dir" in invocation.argv
+ assert os.path.normpath("/tmp/extra") in invocation.argv
+ assert "--settings" in invocation.argv
+ assert invocation.env["PATH"] == "keep"
+ assert invocation.env["ANTHROPIC_API_URL"] == "http://localhost:8082/v1"
+ assert invocation.env["ANTHROPIC_BASE_URL"] == "http://localhost:8082"
+ assert invocation.env["ANTHROPIC_AUTH_TOKEN"] == "proxy-token"
+ assert "ANTHROPIC_API_KEY" not in invocation.env
+ assert invocation.trace_metadata["client_cli_id"] == "claude"
+ assert invocation.trace_metadata["claude_binary"] == "claude"
+
+
+def test_managed_claude_builds_resume_and_fork_commands() -> None:
+ resume = build_managed_claude_invocation(
+ config=_config(),
+ request=ManagedClaudeTaskRequest(prompt="again", session_id="sess_1"),
+ base_env={},
+ )
+ fork = build_managed_claude_invocation(
+ config=_config(),
+ request=ManagedClaudeTaskRequest(
+ prompt="branch", session_id="sess_1", fork_session=True
+ ),
+ base_env={},
+ )
+
+ assert resume.argv[:3] == ("claude", "--resume", "sess_1")
+ assert "--fork-session" not in resume.argv
+ assert fork.argv[:3] == ("claude", "--resume", "sess_1")
+ assert "--fork-session" in fork.argv
+
+
+def test_managed_claude_env_uses_sentinel_when_proxy_auth_blank() -> None:
+ env = build_managed_claude_env(
+ api_url="http://localhost:8082/v1",
+ auth_token="",
+ base_env={"ANTHROPIC_AUTH_TOKEN": "stale"},
+ )
+
+ assert env["ANTHROPIC_AUTH_TOKEN"] == "fcc-no-auth"
+
+
+def test_managed_claude_extracts_session_ids() -> None:
+ assert extract_managed_claude_session_id({"session_id": "direct"}) == "direct"
+ assert extract_managed_claude_session_id({"sessionId": "camel"}) == "camel"
+ assert (
+ extract_managed_claude_session_id({"init": {"session_id": "nested"}})
+ == "nested"
+ )
+ assert (
+ extract_managed_claude_session_id({"result": {"sessionId": "result"}})
+ == "result"
+ )
+ assert extract_managed_claude_session_id({"conversation": {"id": "conv"}}) == "conv"
+ assert extract_managed_claude_session_id({"type": "message"}) is None
+ assert extract_managed_claude_session_id("not a dict") is None
+
+
+def test_managed_claude_parser_emits_session_info_once() -> None:
+ state = ManagedClaudeParseState()
+
+ first = list(parse_managed_claude_stdout_line('{"session_id": "sess_1"}', state))
+ second = list(parse_managed_claude_stdout_line('{"session_id": "sess_2"}', state))
+
+ assert first == [
+ {"type": "session_info", "session_id": "sess_1"},
+ {"session_id": "sess_1"},
+ ]
+ assert second == [{"session_id": "sess_2"}]
+
+
+def test_managed_claude_parser_returns_raw_for_non_json() -> None:
+ events = list(
+ parse_managed_claude_stdout_line(
+ "not json", ManagedClaudeParseState(log_raw_cli_diagnostics=False)
+ )
+ )
+
+ assert events == [{"type": "raw", "content": "not json"}]
diff --git a/tests/conftest.py b/tests/conftest.py
index 463b557e..57fdc922 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -85,9 +85,9 @@ def llamacpp_provider(provider_config):
@pytest.fixture
def mock_cli_session():
- from messaging.platforms.base import CLISession
+ from messaging.platforms.base import ManagedClaudeSessionProtocol
- session = MagicMock(spec=CLISession)
+ session = MagicMock(spec=ManagedClaudeSessionProtocol)
session.start_task = MagicMock() # This will return an async generator
session.is_busy = False
return session
@@ -95,9 +95,9 @@ def mock_cli_session():
@pytest.fixture
def mock_cli_manager():
- from messaging.platforms.base import SessionManagerInterface
+ from messaging.platforms.base import ManagedClaudeSessionManagerProtocol
- manager = MagicMock(spec=SessionManagerInterface)
+ manager = MagicMock(spec=ManagedClaudeSessionManagerProtocol)
manager.get_or_create_session = AsyncMock()
manager.register_real_session_id = AsyncMock(return_value=True)
manager.stop_all = AsyncMock()
diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.py
index 5eaf7092..8427d76d 100644
--- a/tests/contracts/test_import_boundaries.py
+++ b/tests/contracts/test_import_boundaries.py
@@ -258,6 +258,65 @@ def test_messaging_platforms_use_shared_outbox_and_voice_flow() -> None:
assert "NamedTemporaryFile" not in text
+def test_cli_surfaces_are_explicit_launchers_and_managed_claude() -> None:
+ repo_root = Path(__file__).resolve().parents[2]
+ cli_root = repo_root / "cli"
+
+ assert not (cli_root / "adapters" / "__init__.py").exists()
+ assert not any((cli_root / "adapters").glob("*.py"))
+ assert not (cli_root / "session.py").exists()
+ assert not (cli_root / "manager.py").exists()
+ assert not (cli_root / "codex_model_catalog.py").exists()
+
+ for path in {
+ cli_root / "claude_env.py",
+ cli_root / "launchers" / "claude.py",
+ cli_root / "launchers" / "codex.py",
+ cli_root / "launchers" / "codex_model_catalog.py",
+ cli_root / "managed" / "claude.py",
+ cli_root / "managed" / "session.py",
+ cli_root / "managed" / "manager.py",
+ }:
+ assert path.exists()
+
+ entrypoints_text = (cli_root / "entrypoints.py").read_text(encoding="utf-8")
+ assert "launch_claude" not in entrypoints_text
+ assert "launch_codex" not in entrypoints_text
+ assert "codex_model_catalog" not in entrypoints_text
+ assert "_preflight" + "_proxy" not in entrypoints_text
+ assert _text_occurrences(repo_root, "_preflight" + "_proxy") == []
+
+ claude_env_text = (cli_root / "claude_env.py").read_text(encoding="utf-8")
+ assert 'CLAUDE_CODE_AUTO_COMPACT_WINDOW = "190000"' in claude_env_text
+ assert 'CLAUDE_NO_AUTH_SENTINEL = "fcc-no-auth"' in claude_env_text
+ for path in {
+ cli_root / "launchers" / "claude.py",
+ cli_root / "managed" / "claude.py",
+ }:
+ text = path.read_text(encoding="utf-8")
+ assert '"190000"' not in text
+ assert '"fcc-no-auth"' not in text
+
+ messaging_base_text = (repo_root / "messaging" / "platforms" / "base.py").read_text(
+ encoding="utf-8"
+ )
+ assert "class ManagedClaudeSessionProtocol(Protocol)" in messaging_base_text
+ assert "class ManagedClaudeSession(Protocol)" not in messaging_base_text
+ assert "class ManagedClaudeSessionManagerProtocol(Protocol)" in messaging_base_text
+ assert "class SessionManagerInterface(Protocol)" not in messaging_base_text
+ for path in {
+ repo_root / "messaging" / "__init__.py",
+ repo_root / "messaging" / "platforms" / "__init__.py",
+ }:
+ text = path.read_text(encoding="utf-8")
+ assert '"ManagedClaudeSession"' not in text
+ assert "SessionManagerInterface" not in text
+
+ pyproject_text = (repo_root / "pyproject.toml").read_text(encoding="utf-8")
+ assert 'fcc-claude = "cli.launchers.claude:launch"' in pyproject_text
+ assert 'fcc-codex = "cli.launchers.codex:launch"' in pyproject_text
+
+
def _imports_matching(
roots: list[Path], *, forbidden_prefixes: tuple[str, ...]
) -> list[str]:
diff --git a/uv.lock b/uv.lock
index 84a6b6c1..da30f5a1 100644
--- a/uv.lock
+++ b/uv.lock
@@ -561,7 +561,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "2.3.10"
+version = "2.3.11"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },