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

Separate shared harness setup from CLI execution (#1790)

Ali Khokharfcf0ffc0725c
diff --git a/e2e/conftest.py b/e2e/conftest.py
index 4553e425..7a543534 100644
--- a/e2e/conftest.py
+++ b/e2e/conftest.py
@@ -16,7 +16,6 @@ from e2e.code_support import CodeControl
from free_claude_code.api.app import create_app
from free_claude_code.api.ports import ApiServices
from free_claude_code.application.model_metadata import ProviderModelInfo
-from free_claude_code.cli import codex_integration, vscode
from free_claude_code.config import env_migrations, paths
from free_claude_code.config.env_migrations import recognized_env_keys
from free_claude_code.config.loader import (
@@ -27,6 +26,7 @@ from free_claude_code.config.loader import (
from free_claude_code.core.anthropic.models import MessagesRequest
from free_claude_code.core.openai_responses import OpenAIResponsesRequest
from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy
+from free_claude_code.harnesses import claude_integration, codex_integration
from free_claude_code.providers.base import BaseProvider, ProviderConfig
from free_claude_code.providers.runtime import ProviderRuntime
from free_claude_code.runtime.application import ApplicationRuntime
@@ -132,9 +132,13 @@ def admin_base_url(
monkeypatch.setattr(
codex_integration, "config_path", lambda: tmp_path / ".codex" / "config.toml"
)
- monkeypatch.setattr(vscode, "claude_state_path", lambda: tmp_path / ".claude.json")
monkeypatch.setattr(
- vscode, "settings_path", lambda: tmp_path / "vscode" / "settings.json"
+ claude_integration, "claude_state_path", lambda: tmp_path / ".claude.json"
+ )
+ monkeypatch.setattr(
+ claude_integration,
+ "settings_path",
+ lambda: tmp_path / "vscode" / "settings.json",
)
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
diff --git a/e2e/test_admin_integrations.py b/e2e/test_admin_integrations.py
index c43d2997..aa3215b1 100644
--- a/e2e/test_admin_integrations.py
+++ b/e2e/test_admin_integrations.py
@@ -5,7 +5,7 @@ from itertools import pairwise
import pytest
from playwright.sync_api import expect
-from free_claude_code.cli import vscode
+from free_claude_code.harnesses import claude_integration
@pytest.mark.parametrize(
@@ -294,7 +294,7 @@ def test_connect_disconnect_and_modal_dismissal(page, admin_base_url, tmp_path):
def test_manual_setup_and_revisit_read_the_file(page, admin_base_url, tmp_path):
path = tmp_path / "vscode" / "settings.json"
status = page.request.get(f"{admin_base_url}/admin/api/status").json()
- vscode.configure(
+ claude_integration.configure(
path,
tmp_path / ".claude.json",
f"http://localhost:{status['port']}/",
diff --git a/pyproject.toml b/pyproject.toml
index 8eb61bd8..746e4621 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "6.2.23"
+version = "6.2.24"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/smoke/capabilities.py b/smoke/capabilities.py
index ee64a264..af2d657f 100644
--- a/smoke/capabilities.py
+++ b/smoke/capabilities.py
@@ -96,6 +96,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"tests/providers/test_openai_chat_stream_output.py",
"tests/cli/test_entrypoints.py",
"tests/cli/test_codex_model_catalog.py",
+ "tests/harnesses/test_codex_model_catalog.py",
+ "tests/runtime/test_codex_catalog.py",
),
(
"test_probe_and_models_routes",
@@ -562,6 +564,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"shared startup; required catalog failure stops launch; private catalog cleanup",
(
"tests/cli/test_codex_model_catalog.py",
+ "tests/harnesses/test_codex_model_catalog.py",
+ "tests/runtime/test_codex_catalog.py",
"tests/cli/test_codex_launcher.py",
"tests/cli/test_launcher_workflow.py",
"tests/cli/test_launcher_resources.py",
@@ -589,7 +593,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"version, proxy, config conflict, or catalog failure exits without fallback",
(
"tests/cli/test_opencode_launcher.py",
- "tests/cli/test_model_catalog.py",
+ "tests/harnesses/test_model_catalog.py",
+ "tests/cli/test_catalog_http.py",
),
("test_opencode_cli_prompt_e2e",),
),
@@ -604,7 +609,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
(
"tests/cli/test_aider_config.py",
"tests/cli/test_aider_launcher.py",
- "tests/cli/test_model_catalog.py",
+ "tests/harnesses/test_model_catalog.py",
+ "tests/cli/test_catalog_http.py",
),
("test_aider_cli_prompt_e2e",),
),
@@ -618,7 +624,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"version, proxy, catalog, or private-file failure exits before inference",
(
"tests/cli/test_cline_launcher.py",
- "tests/cli/test_model_catalog.py",
+ "tests/harnesses/test_model_catalog.py",
+ "tests/cli/test_catalog_http.py",
),
("test_cline_cli_prompt_e2e",),
),
@@ -664,7 +671,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"version, process config conflict, proxy, or catalog failure exits before inference",
(
"tests/cli/test_grok_launcher.py",
- "tests/cli/test_model_catalog.py",
+ "tests/harnesses/test_model_catalog.py",
+ "tests/cli/test_catalog_http.py",
),
("test_grok_cli_headless_e2e",),
),
diff --git a/smoke/features.py b/smoke/features.py
index 561dcfe8..a03515ae 100644
--- a/smoke/features.py
+++ b/smoke/features.py
@@ -110,6 +110,8 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
"tests/api/test_openai_responses.py",
"tests/cli/test_entrypoints.py",
"tests/cli/test_codex_model_catalog.py",
+ "tests/harnesses/test_codex_model_catalog.py",
+ "tests/runtime/test_codex_catalog.py",
"tests/core/openai_responses/test_native.py",
"tests/providers/test_openai_chat_stream_output.py",
),
@@ -134,7 +136,8 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
"OpenCode discovers FCC models and sends Responses through the proxy",
(
"tests/cli/test_opencode_launcher.py",
- "tests/cli/test_model_catalog.py",
+ "tests/harnesses/test_model_catalog.py",
+ "tests/cli/test_catalog_http.py",
),
("test_probe_and_models_routes",),
("test_opencode_cli_prompt_e2e",),
@@ -151,7 +154,8 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
(
"tests/cli/test_aider_config.py",
"tests/cli/test_aider_launcher.py",
- "tests/cli/test_model_catalog.py",
+ "tests/harnesses/test_model_catalog.py",
+ "tests/cli/test_catalog_http.py",
),
("test_probe_and_models_routes",),
("test_aider_cli_prompt_e2e",),
@@ -167,7 +171,8 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
"Cline discovers FCC models and sends Responses through the proxy",
(
"tests/cli/test_cline_launcher.py",
- "tests/cli/test_model_catalog.py",
+ "tests/harnesses/test_model_catalog.py",
+ "tests/cli/test_catalog_http.py",
),
("test_probe_and_models_routes",),
("test_cline_cli_prompt_e2e",),
@@ -213,7 +218,8 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
"Grok Build discovers FCC models and sends Responses through the proxy",
(
"tests/cli/test_grok_launcher.py",
- "tests/cli/test_model_catalog.py",
+ "tests/harnesses/test_model_catalog.py",
+ "tests/cli/test_catalog_http.py",
),
("test_probe_and_models_routes",),
("test_grok_cli_headless_e2e",),
diff --git a/smoke/lib/claude_cli_matrix.py b/smoke/lib/claude_cli_matrix.py
index 7b90362b..452a58bd 100644
--- a/smoke/lib/claude_cli_matrix.py
+++ b/smoke/lib/claude_cli_matrix.py
@@ -10,7 +10,7 @@ from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
-from free_claude_code.cli.claude_env import build_claude_proxy_env
+from free_claude_code.harnesses.claude import build_claude_proxy_env
from smoke.lib.child_process import run_captured_text
from smoke.lib.config import ProviderModel, SmokeConfig, redacted
from smoke.lib.outcomes import is_upstream_unavailable_text
diff --git a/smoke/lib/e2e.py b/smoke/lib/e2e.py
index 780a473d..9b731dc6 100644
--- a/smoke/lib/e2e.py
+++ b/smoke/lib/e2e.py
@@ -16,7 +16,6 @@ from typing import Any
import httpx
import pytest
-from free_claude_code.cli.claude_env import build_claude_proxy_env
from free_claude_code.config.provider_catalog import SUPPORTED_PROVIDER_IDS
from free_claude_code.core.anthropic.stream_contracts import (
SSEEvent,
@@ -26,6 +25,7 @@ from free_claude_code.core.anthropic.stream_contracts import (
parse_sse_lines,
text_content,
)
+from free_claude_code.harnesses.claude import build_claude_proxy_env
from free_claude_code.messaging.models import IncomingMessage, MessageScope
from free_claude_code.messaging.session import SessionStore
from free_claude_code.messaging.voice import VoiceCancellationResult
diff --git a/smoke/prereq/test_cli_prereq_live.py b/smoke/prereq/test_cli_prereq_live.py
index 3f6d0d4e..93ff47d5 100644
--- a/smoke/prereq/test_cli_prereq_live.py
+++ b/smoke/prereq/test_cli_prereq_live.py
@@ -4,7 +4,7 @@ from pathlib import Path
import pytest
-from free_claude_code.cli.claude_env import build_claude_proxy_env
+from free_claude_code.harnesses.claude import build_claude_proxy_env
from smoke.lib.child_process import (
cmd_fcc_server,
run_captured_text,
diff --git a/src/free_claude_code/cli/launchers/aider.py b/src/free_claude_code/cli/launchers/aider.py
index 8a872ed2..8cfdbdda 100644
--- a/src/free_claude_code/cli/launchers/aider.py
+++ b/src/free_claude_code/cli/launchers/aider.py
@@ -2,11 +2,12 @@
from collections.abc import Sequence
-from free_claude_code.cli.environment import client_environment
+from free_claude_code.harnesses.environment import client_environment
+from free_claude_code.harnesses.launch import PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
from .aider_config import AIDER_API_KEY_ENV_PREFIX, build_aider_config
-from .resources import LaunchResources
-from .runner import HarnessSpec, LaunchContext, PreparedLaunch, launch_harness
+from .runner import HarnessSpec, LaunchContext, launch_harness
def _configure(
diff --git a/src/free_claude_code/cli/launchers/aider_config.py b/src/free_claude_code/cli/launchers/aider_config.py
index 561686b4..eab6ca61 100644
--- a/src/free_claude_code/cli/launchers/aider_config.py
+++ b/src/free_claude_code/cli/launchers/aider_config.py
@@ -5,8 +5,7 @@ from dataclasses import dataclass, field
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.model_capabilities import ModelInputModality
-
-from .model_catalog import ClientModel
+from free_claude_code.harnesses.model_catalog import ClientModel
AIDER_API_KEY_ENV_PREFIX = "FCC_AIDER_PROXY_AUTH_"
_AIDER_API_KEY_ENV_PATTERN = re.compile(rf"{AIDER_API_KEY_ENV_PREFIX}[A-Z0-9]+")
diff --git a/src/free_claude_code/cli/launchers/catalog_http.py b/src/free_claude_code/cli/launchers/catalog_http.py
new file mode 100644
index 00000000..873672b6
--- /dev/null
+++ b/src/free_claude_code/cli/launchers/catalog_http.py
@@ -0,0 +1,33 @@
+"""Authenticated local catalog acquisition for terminal launchers."""
+
+import json
+from typing import Literal
+from urllib.request import Request
+
+from free_claude_code.cli.local_http import open_local_request
+from free_claude_code.core.json_types import JsonObject, JsonValue
+
+from .common import PROXY_PREFLIGHT_TIMEOUT_SECONDS
+
+
+def fetch_proxy_models_response(
+ proxy_root_url: str,
+ auth_token: str,
+ view: Literal["messages", "responses"] = "responses",
+) -> JsonObject:
+ """Fetch the authenticated FCC-local `/v1/models` response directly."""
+
+ url = f"{proxy_root_url.rstrip('/')}/v1/models?view={view}"
+ request = Request(
+ url,
+ headers={"Authorization": f"Bearer {auth_token}"},
+ method="GET",
+ )
+ with open_local_request(
+ request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS
+ ) as response:
+ payload: JsonValue = 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/src/free_claude_code/cli/launchers/claude.py b/src/free_claude_code/cli/launchers/claude.py
index 368c8666..70d7a5e7 100644
--- a/src/free_claude_code/cli/launchers/claude.py
+++ b/src/free_claude_code/cli/launchers/claude.py
@@ -2,10 +2,11 @@
from collections.abc import Sequence
-from free_claude_code.cli.claude_env import CLAUDE_BINARY_NAME, build_claude_proxy_env
+from free_claude_code.harnesses.claude import CLAUDE_BINARY_NAME, build_claude_proxy_env
+from free_claude_code.harnesses.launch import PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
-from .resources import LaunchResources
-from .runner import HarnessSpec, LaunchContext, PreparedLaunch, launch_harness
+from .runner import HarnessSpec, LaunchContext, launch_harness
def _configure(
diff --git a/src/free_claude_code/cli/launchers/cline.py b/src/free_claude_code/cli/launchers/cline.py
index e74da90d..b50528c0 100644
--- a/src/free_claude_code/cli/launchers/cline.py
+++ b/src/free_claude_code/cli/launchers/cline.py
@@ -3,18 +3,12 @@
import re
from collections.abc import Sequence
-from free_claude_code.cli.environment import client_environment
+from free_claude_code.harnesses.environment import client_environment
+from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
from .cline_config import CLINE_PROVIDER_ID, build_cline_config
-from .resources import LaunchResources
-from .runner import (
- HarnessSpec,
- LaunchContext,
- NativeCheck,
- PreparedLaunch,
- launch_harness,
- version_at_least,
-)
+from .runner import HarnessSpec, LaunchContext, launch_harness, version_at_least
_VERSION_PATTERN = re.compile(
r"(?m)^\s*(?:cline(?:\s+version)?\s+|v)?"
diff --git a/src/free_claude_code/cli/launchers/cline_config.py b/src/free_claude_code/cli/launchers/cline_config.py
index deba4ba3..cc1b317f 100644
--- a/src/free_claude_code/cli/launchers/cline_config.py
+++ b/src/free_claude_code/cli/launchers/cline_config.py
@@ -3,11 +3,10 @@
from dataclasses import dataclass, field
from datetime import UTC, datetime
+from free_claude_code.config.server_urls import proxy_v1_url
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.model_capabilities import ModelInputModality
-
-from .common import proxy_v1_url
-from .model_catalog import ClientModel
+from free_claude_code.harnesses.model_catalog import ClientModel
# Cline's released session gateway only instantiates built-in providers. FCC
# replaces this process-local Responses provider's endpoint and catalog instead
diff --git a/src/free_claude_code/cli/launchers/codex.py b/src/free_claude_code/cli/launchers/codex.py
index 819293ff..50da51e0 100644
--- a/src/free_claude_code/cli/launchers/codex.py
+++ b/src/free_claude_code/cli/launchers/codex.py
@@ -1,102 +1,46 @@
"""Installed Codex launcher and external-client credential handoff."""
-import json
import sys
from collections.abc import Sequence
-from free_claude_code.cli.environment import client_environment
from free_claude_code.config.loader import get_settings
-
-from .codex_model_catalog import build_codex_model_catalog
-from .common import proxy_v1_url
-from .model_catalog import catalog_wire_slug_for_ref
-from .resources import LaunchResources
-from .runner import HarnessSpec, LaunchContext, PreparedLaunch, launch_harness
-
-_PRINT_PROXY_AUTH_TOKEN_FLAG = "--print-proxy-auth-token"
-_STRIPPED_CODEX_ENV_KEYS = frozenset(
- {
- "OPENAI_API_KEY",
- "OPENAI_BASE_URL",
- "OPENAI_API_BASE",
- "OPENAI_ORG_ID",
- "OPENAI_ORGANIZATION",
- "CODEX_API_KEY",
- "CODEX_INTERNAL_ORIGINATOR_OVERRIDE",
- "CODEX_PERMISSION_PROFILE",
- "CODEX_SHELL",
- "CODEX_THREAD_ID",
- }
+from free_claude_code.harnesses.codex import (
+ CODEX_INSTALL_HINT,
+ PRINT_PROXY_AUTH_TOKEN_FLAG,
+ prepare_codex_launch,
)
+from free_claude_code.harnesses.launch import PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
-
-def codex_config_values(
- *, api_url: str, model: str | None = None
-) -> dict[str, str | list[str]]:
- """Shared configuration for the FCC Responses provider."""
-
- values: dict[str, str | list[str]] = {
- "model_provider": "fcc",
- "model_providers.fcc.name": "Free Claude Code",
- "model_providers.fcc.base_url": proxy_v1_url(api_url),
- "model_providers.fcc.auth.command": "fcc-codex",
- "model_providers.fcc.auth.args": [_PRINT_PROXY_AUTH_TOKEN_FLAG],
- "model_providers.fcc.wire_api": "responses",
- }
- if model:
- values["model"] = model
- return values
+from .runner import HarnessSpec, LaunchContext, launch_harness
-def codex_config_args(*, api_url: str, model: str | None = None) -> list[str]:
- """Build native TOML overrides for the FCC Responses provider."""
- values = codex_config_values(api_url=api_url, model=model)
- return [
- arg
- for key, value in values.items()
- for arg in ("-c", f"{key}={json.dumps(value)}")
- ]
-
-
-def prepare_codex_launch(
+def _configure(
ctx: LaunchContext, args: list[str], files: LaunchResources
) -> PreparedLaunch:
- catalog_path = files.write_json(
- "model-catalog.json", build_codex_model_catalog(ctx.models)
- )
- configuration = codex_config_args(
- api_url=ctx.proxy_root_url,
- model=catalog_wire_slug_for_ref(ctx.models, ctx.settings.model),
- )
- return PreparedLaunch(
- [
- ctx.binary_path,
- *configuration,
- "-c",
- f"model_catalog_json={json.dumps(str(catalog_path))}",
- *args,
- ],
- client_environment(
- ctx.base_env,
- proxy_root_url=ctx.proxy_root_url,
- remove_keys=tuple(_STRIPPED_CODEX_ENV_KEYS),
- remove_prefixes=("OPENAI_",),
- ),
+ return prepare_codex_launch(
+ binary_path=ctx.binary_path,
+ proxy_root_url=ctx.proxy_root_url,
+ model=ctx.settings.model,
+ models=ctx.models,
+ base_env=ctx.base_env,
+ args=args,
+ files=files,
)
SPEC = HarnessSpec(
binary_name="codex",
display_name="Codex CLI",
- install_hint="Install Codex with: npm install -g @openai/codex",
- configure=prepare_codex_launch,
+ install_hint=CODEX_INSTALL_HINT,
+ configure=_configure,
catalog_view="responses",
)
def launch(argv: Sequence[str] | None = None) -> None:
args = list(sys.argv[1:] if argv is None else argv)
- if args == [_PRINT_PROXY_AUTH_TOKEN_FLAG]:
+ if args == [PRINT_PROXY_AUTH_TOKEN_FLAG]:
print(get_settings().proxy_auth_token)
return
launch_harness(SPEC, args)
diff --git a/src/free_claude_code/cli/launchers/common.py b/src/free_claude_code/cli/launchers/common.py
index a2886454..6ff8e9a7 100644
--- a/src/free_claude_code/cli/launchers/common.py
+++ b/src/free_claude_code/cli/launchers/common.py
@@ -18,13 +18,6 @@ PROXY_PREFLIGHT_PATH = "/health"
PROXY_PREFLIGHT_TIMEOUT_SECONDS = 1.5
-def proxy_v1_url(proxy_root_url: str) -> str:
- """Return the canonical local proxy API root for client launchers."""
-
- stripped = proxy_root_url.rstrip("/")
- return stripped if stripped.endswith("/v1") else f"{stripped}/v1"
-
-
def preflight_proxy(proxy_root_url: str) -> str | None:
"""Return an error message when the local proxy health check is unreachable."""
diff --git a/src/free_claude_code/cli/launchers/dsh.py b/src/free_claude_code/cli/launchers/dsh.py
index b93ca7f8..5c1f499e 100644
--- a/src/free_claude_code/cli/launchers/dsh.py
+++ b/src/free_claude_code/cli/launchers/dsh.py
@@ -3,17 +3,12 @@
import re
from collections.abc import Sequence
-from free_claude_code.cli.environment import client_environment
+from free_claude_code.harnesses.environment import client_environment
+from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
from .dsh_config import DSH_API_KEY_ENV, DSH_ENV_PREFIX, build_dsh_launch_config
-from .resources import LaunchResources
-from .runner import (
- HarnessSpec,
- LaunchContext,
- NativeCheck,
- PreparedLaunch,
- launch_harness,
-)
+from .runner import HarnessSpec, LaunchContext, launch_harness
_VERSION_PATTERN = re.compile(
r"(?im)^\s*(?:dsh\s+)?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?)\s*$"
diff --git a/src/free_claude_code/cli/launchers/dsh_config.py b/src/free_claude_code/cli/launchers/dsh_config.py
index bcec26fa..3b03d303 100644
--- a/src/free_claude_code/cli/launchers/dsh_config.py
+++ b/src/free_claude_code/cli/launchers/dsh_config.py
@@ -3,11 +3,10 @@
import math
from pathlib import Path
+from free_claude_code.config.server_urls import proxy_v1_url
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.model_capabilities import ModelInputModality
-
-from .common import proxy_v1_url
-from .model_catalog import ClientModel
+from free_claude_code.harnesses.model_catalog import ClientModel
DSH_API_KEY_ENV = "FCC_DSH_API_KEY"
DSH_ENV_PREFIX = "FCC_DSH_"
diff --git a/src/free_claude_code/cli/launchers/grok.py b/src/free_claude_code/cli/launchers/grok.py
index d2724218..df19c5a0 100644
--- a/src/free_claude_code/cli/launchers/grok.py
+++ b/src/free_claude_code/cli/launchers/grok.py
@@ -4,21 +4,15 @@ import json
import re
from collections.abc import Sequence
-from free_claude_code.cli.environment import (
+from free_claude_code.config.server_urls import proxy_v1_url
+from free_claude_code.harnesses.environment import (
client_environment,
require_unset_environment,
)
+from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
-from .common import proxy_v1_url
-from .resources import LaunchResources
-from .runner import (
- HarnessSpec,
- LaunchContext,
- NativeCheck,
- PreparedLaunch,
- launch_harness,
- version_at_least,
-)
+from .runner import HarnessSpec, LaunchContext, launch_harness, version_at_least
_INSTALL_HINT = (
"Install Grok Build with `irm https://x.ai/cli/install.ps1 | iex` on Windows "
diff --git a/src/free_claude_code/cli/launchers/hermes.py b/src/free_claude_code/cli/launchers/hermes.py
index 9dffa210..650ab6c3 100644
--- a/src/free_claude_code/cli/launchers/hermes.py
+++ b/src/free_claude_code/cli/launchers/hermes.py
@@ -6,21 +6,15 @@ import re
from collections.abc import Sequence
from pathlib import Path
-from free_claude_code.cli.environment import (
+from free_claude_code.harnesses.environment import (
client_environment,
require_unset_environment,
)
+from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
from .hermes_config import HERMES_KEY_ENV_PREFIX, build_hermes_managed_config
-from .resources import LaunchResources
-from .runner import (
- HarnessSpec,
- LaunchContext,
- NativeCheck,
- PreparedLaunch,
- launch_harness,
- version_at_least,
-)
+from .runner import HarnessSpec, LaunchContext, launch_harness, version_at_least
_INSTALL_HINT = (
"Install Hermes Agent from: https://hermes-agent.nousresearch.com/docs/installation"
diff --git a/src/free_claude_code/cli/launchers/hermes_config.py b/src/free_claude_code/cli/launchers/hermes_config.py
index 706bca66..9150db5f 100644
--- a/src/free_claude_code/cli/launchers/hermes_config.py
+++ b/src/free_claude_code/cli/launchers/hermes_config.py
@@ -2,11 +2,10 @@
from dataclasses import dataclass, field
+from free_claude_code.config.server_urls import proxy_v1_url
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.model_capabilities import ModelInputModality
-
-from .common import proxy_v1_url
-from .model_catalog import ClientModel
+from free_claude_code.harnesses.model_catalog import ClientModel
HERMES_PROVIDER_PREFIX = "fcc-"
HERMES_KEY_ENV_PREFIX = "FCC_HERMES_"
diff --git a/src/free_claude_code/cli/launchers/muse.py b/src/free_claude_code/cli/launchers/muse.py
index 9b4d3ec6..d5a9f957 100644
--- a/src/free_claude_code/cli/launchers/muse.py
+++ b/src/free_claude_code/cli/launchers/muse.py
@@ -3,18 +3,12 @@
import re
from collections.abc import Sequence
-from free_claude_code.cli.environment import client_environment
+from free_claude_code.config.server_urls import proxy_v1_url
+from free_claude_code.harnesses.environment import client_environment
+from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
-from .common import proxy_v1_url
-from .resources import LaunchResources
-from .runner import (
- HarnessSpec,
- LaunchContext,
- NativeCheck,
- PreparedLaunch,
- launch_harness,
- version_at_least,
-)
+from .runner import HarnessSpec, LaunchContext, launch_harness, version_at_least
_INSTALL_HINT = (
"Install Muse Code on native Windows with "
diff --git a/src/free_claude_code/cli/launchers/opencode.py b/src/free_claude_code/cli/launchers/opencode.py
index e6bef18b..f62841f3 100644
--- a/src/free_claude_code/cli/launchers/opencode.py
+++ b/src/free_claude_code/cli/launchers/opencode.py
@@ -4,21 +4,15 @@ import json
import re
from collections.abc import Sequence
-from free_claude_code.cli.environment import (
+from free_claude_code.harnesses.environment import (
client_environment,
require_unset_environment,
)
+from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
from .opencode_config import OPENCODE_API_KEY_ENV, build_opencode_config
-from .resources import LaunchResources
-from .runner import (
- HarnessSpec,
- LaunchContext,
- NativeCheck,
- PreparedLaunch,
- launch_harness,
- version_at_least,
-)
+from .runner import HarnessSpec, LaunchContext, launch_harness, version_at_least
_VERSION_PATTERN = re.compile(
r"(?m)^\s*(?:(?:opencode(?:\s+version)?\s+)|v)?"
diff --git a/src/free_claude_code/cli/launchers/opencode_config.py b/src/free_claude_code/cli/launchers/opencode_config.py
index cf933805..c7cddcb1 100644
--- a/src/free_claude_code/cli/launchers/opencode_config.py
+++ b/src/free_claude_code/cli/launchers/opencode_config.py
@@ -2,11 +2,10 @@
from dataclasses import dataclass
+from free_claude_code.config.server_urls import proxy_v1_url
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.model_capabilities import ModelInputModality
-
-from .common import proxy_v1_url
-from .model_catalog import ClientModel
+from free_claude_code.harnesses.model_catalog import ClientModel
OPENCODE_API_KEY_ENV = "FCC_OPENCODE_API_KEY"
OPENCODE_PROVIDER_ID = "free-claude-code"
diff --git a/src/free_claude_code/cli/launchers/pi.py b/src/free_claude_code/cli/launchers/pi.py
index d7e3d8eb..698c2788 100644
--- a/src/free_claude_code/cli/launchers/pi.py
+++ b/src/free_claude_code/cli/launchers/pi.py
@@ -5,17 +5,11 @@ import sys
from collections.abc import Sequence
from pathlib import Path
-from free_claude_code.cli.environment import client_environment
+from free_claude_code.harnesses.environment import client_environment
+from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
+from free_claude_code.harnesses.resources import LaunchResources
-from .resources import LaunchResources
-from .runner import (
- HarnessSpec,
- LaunchContext,
- NativeCheck,
- PreparedLaunch,
- launch_harness,
- version_at_least,
-)
+from .runner import HarnessSpec, LaunchContext, launch_harness, version_at_least
_VERSION_PATTERN = re.compile(r"(?m)^\s*(\d+)\.(\d+)\.(\d+)\s*$")
diff --git a/src/free_claude_code/cli/launchers/runner.py b/src/free_claude_code/cli/launchers/runner.py
index b633d2da..8f4b175a 100644
--- a/src/free_claude_code/cli/launchers/runner.py
+++ b/src/free_claude_code/cli/launchers/runner.py
@@ -13,24 +13,15 @@ from typing import Literal
from free_claude_code.config.loader import get_settings
from free_claude_code.config.server_urls import local_proxy_root_url
from free_claude_code.config.settings import Settings
-
-from .common import preflight_proxy, resolve_client_binary, run_client_process
-from .model_catalog import (
+from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
+from free_claude_code.harnesses.model_catalog import (
ClientModel,
client_models_from_response,
- fetch_proxy_models_response,
)
-from .resources import LaunchResources
-
-
-@dataclass(frozen=True, slots=True)
-class NativeCheck:
- """A fixed native probe; its adapter owns output interpretation."""
+from free_claude_code.harnesses.resources import LaunchResources
- args: tuple[str, ...]
- accepts: Callable[[str], bool]
- failure_message: str
- timeout_seconds: float = 5.0
+from .catalog_http import fetch_proxy_models_response
+from .common import preflight_proxy, resolve_client_binary, run_client_process
@dataclass(frozen=True, slots=True)
@@ -44,13 +35,6 @@ class LaunchContext:
launch_id: str = field(default_factory=lambda: secrets.token_hex(16))
-@dataclass(frozen=True, slots=True)
-class PreparedLaunch:
- command: list[str] = field(repr=False)
- env: Mapping[str, str] = field(repr=False)
- activation_check: NativeCheck | None = None
-
-
@dataclass(frozen=True, slots=True)
class HarnessSpec:
binary_name: str
diff --git a/src/free_claude_code/cli/local_http.py b/src/free_claude_code/cli/local_http.py
index ed8eb0ac..b1f42a07 100644
--- a/src/free_claude_code/cli/local_http.py
+++ b/src/free_claude_code/cli/local_http.py
@@ -1,51 +1,12 @@
-"""Direct HTTP and child-environment policy for FCC-local traffic."""
+"""Direct HTTP transport for FCC-local traffic."""
-from collections.abc import Mapping
from http.client import HTTPResponse
-from urllib.parse import urlsplit
from urllib.request import ProxyHandler, Request, build_opener
_DIRECT_OPENER = build_opener(ProxyHandler({}))
-_LOOPBACK_BYPASS_HOSTS = ("127.0.0.1", "localhost", "::1")
-_NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
def open_local_request(request: Request, *, timeout: float) -> HTTPResponse:
"""Open an FCC-local request without consulting machine proxy settings."""
return _DIRECT_OPENER.open(request, timeout=timeout)
-
-
-def with_local_proxy_bypass(
- base_env: Mapping[str, str],
- *,
- proxy_root_url: str,
-) -> dict[str, str]:
- """Copy an environment and keep its FCC-local destination off proxies."""
-
- host = urlsplit(proxy_root_url).hostname
- if host is None:
- raise ValueError("Local proxy root URL must include a host.")
-
- env = dict(base_env)
- entries: list[str] = []
- seen: set[str] = set()
- for key in _NO_PROXY_KEYS:
- for raw_entry in base_env.get(key, "").split(","):
- _append_unique(entries, seen, raw_entry)
- for local_host in (*_LOOPBACK_BYPASS_HOSTS, host):
- _append_unique(entries, seen, local_host)
-
- value = ",".join(entries)
- for key in _NO_PROXY_KEYS:
- env[key] = value
- return env
-
-
-def _append_unique(entries: list[str], seen: set[str], raw_entry: str) -> None:
- entry = raw_entry.strip()
- normalized = entry.casefold()
- if not entry or normalized in seen:
- return
- entries.append(entry)
- seen.add(normalized)
diff --git a/src/free_claude_code/cli/managed/claude.py b/src/free_claude_code/cli/managed/claude.py
index 749fe92c..4fd25bc2 100644
--- a/src/free_claude_code/cli/managed/claude.py
+++ b/src/free_claude_code/cli/managed/claude.py
@@ -6,11 +6,11 @@ from dataclasses import dataclass, field
from loguru import logger
-from free_claude_code.cli.claude_env import (
+from free_claude_code.core.json_types import JsonObject, JsonValue
+from free_claude_code.harnesses.claude import (
CLAUDE_BINARY_NAME,
build_claude_proxy_env,
)
-from free_claude_code.core.json_types import JsonObject, JsonValue
MANAGED_CLAUDE_MODEL_TIER = "fable"
diff --git a/src/free_claude_code/cli/managed/manager.py b/src/free_claude_code/cli/managed/manager.py
index 34cf9f46..8ecb73a5 100644
--- a/src/free_claude_code/cli/managed/manager.py
+++ b/src/free_claude_code/cli/managed/manager.py
@@ -5,7 +5,7 @@ import uuid
from loguru import logger
-from free_claude_code.cli.claude_env import CLAUDE_BINARY_NAME
+from free_claude_code.harnesses.claude import CLAUDE_BINARY_NAME
from .session import ManagedClaudeSession
diff --git a/src/free_claude_code/config/server_urls.py b/src/free_claude_code/config/server_urls.py
index d58e0234..5b088293 100644
--- a/src/free_claude_code/config/server_urls.py
+++ b/src/free_claude_code/config/server_urls.py
@@ -46,3 +46,10 @@ def same_proxy_url(value: object, expected: str) -> bool:
return normalized(value) == normalized(expected)
except ValueError:
return False
+
+
+def proxy_v1_url(proxy_root_url: str) -> str:
+ """Return the canonical local proxy API root for client launchers."""
+
+ stripped = proxy_root_url.rstrip("/")
+ return stripped if stripped.endswith("/v1") else f"{stripped}/v1"
diff --git a/src/free_claude_code/harnesses/__init__.py b/src/free_claude_code/harnesses/__init__.py
new file mode 100644
index 00000000..cc7020fc
--- /dev/null
+++ b/src/free_claude_code/harnesses/__init__.py
@@ -0,0 +1 @@
+"""Shared native-client setup; callers own acquisition and process execution."""
diff --git a/src/free_claude_code/cli/claude_env.py b/src/free_claude_code/harnesses/claude.py
similarity index 94%
rename from src/free_claude_code/cli/claude_env.py
rename to src/free_claude_code/harnesses/claude.py
index c1f638cb..50558e13 100644
--- a/src/free_claude_code/cli/claude_env.py
+++ b/src/free_claude_code/harnesses/claude.py
@@ -2,7 +2,7 @@
from collections.abc import Mapping
-from free_claude_code.cli.environment import client_environment
+from free_claude_code.harnesses.environment import client_environment
CLAUDE_CODE_AUTO_COMPACT_WINDOW = "190000"
CLAUDE_BINARY_NAME = "claude"
diff --git a/src/free_claude_code/cli/vscode.py b/src/free_claude_code/harnesses/claude_integration.py
similarity index 97%
rename from src/free_claude_code/cli/vscode.py
rename to src/free_claude_code/harnesses/claude_integration.py
index 3f2fe20b..ae886075 100644
--- a/src/free_claude_code/cli/vscode.py
+++ b/src/free_claude_code/harnesses/claude_integration.py
@@ -8,10 +8,10 @@ from typing import cast
import json5
-from free_claude_code.cli.claude_env import claude_proxy_values
-from free_claude_code.cli.config_file import atomic_write_text
from free_claude_code.config.server_urls import same_proxy_url
from free_claude_code.core.json_types import JsonObject
+from free_claude_code.harnesses.claude import claude_proxy_values
+from free_claude_code.harnesses.config_file import atomic_write_text
_ENV = "claudeCode.environmentVariables"
_LOGIN = "claudeCode.disableLoginPrompt"
diff --git a/src/free_claude_code/harnesses/codex.py b/src/free_claude_code/harnesses/codex.py
new file mode 100644
index 00000000..d76f8952
--- /dev/null
+++ b/src/free_claude_code/harnesses/codex.py
@@ -0,0 +1,91 @@
+"""Shared Codex provider configuration and native launch preparation."""
+
+import json
+from collections.abc import Mapping, Sequence
+
+from free_claude_code.config.server_urls import proxy_v1_url
+from free_claude_code.harnesses.environment import client_environment
+
+from .codex_model_catalog import build_codex_model_catalog
+from .launch import PreparedLaunch
+from .model_catalog import ClientModel, catalog_wire_slug_for_ref
+from .resources import LaunchResources
+
+PRINT_PROXY_AUTH_TOKEN_FLAG = "--print-proxy-auth-token"
+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_INTERNAL_ORIGINATOR_OVERRIDE",
+ "CODEX_PERMISSION_PROFILE",
+ "CODEX_SHELL",
+ "CODEX_THREAD_ID",
+ }
+)
+
+
+def codex_config_values(
+ *, api_url: str, model: str | None = None
+) -> dict[str, str | list[str]]:
+ """Shared configuration for the FCC Responses provider."""
+
+ values: dict[str, str | list[str]] = {
+ "model_provider": "fcc",
+ "model_providers.fcc.name": "Free Claude Code",
+ "model_providers.fcc.base_url": proxy_v1_url(api_url),
+ "model_providers.fcc.auth.command": "fcc-codex",
+ "model_providers.fcc.auth.args": [PRINT_PROXY_AUTH_TOKEN_FLAG],
+ "model_providers.fcc.wire_api": "responses",
+ }
+ if model:
+ values["model"] = model
+ return values
+
+
+def codex_config_args(*, api_url: str, model: str | None = None) -> list[str]:
+ """Build native TOML overrides for the FCC Responses provider."""
+ values = codex_config_values(api_url=api_url, model=model)
+ return [
+ arg
+ for key, value in values.items()
+ for arg in ("-c", f"{key}={json.dumps(value)}")
+ ]
+
+
+def prepare_codex_launch(
+ *,
+ binary_path: str,
+ proxy_root_url: str,
+ model: str,
+ models: Sequence[ClientModel],
+ base_env: Mapping[str, str],
+ args: Sequence[str],
+ files: LaunchResources,
+) -> PreparedLaunch:
+ catalog_path = files.write_json(
+ "model-catalog.json", build_codex_model_catalog(models)
+ )
+ configuration = codex_config_args(
+ api_url=proxy_root_url,
+ model=catalog_wire_slug_for_ref(models, model),
+ )
+ return PreparedLaunch(
+ [
+ binary_path,
+ *configuration,
+ "-c",
+ f"model_catalog_json={json.dumps(str(catalog_path))}",
+ *args,
+ ],
+ client_environment(
+ base_env,
+ proxy_root_url=proxy_root_url,
+ remove_keys=tuple(_STRIPPED_CODEX_ENV_KEYS),
+ remove_prefixes=("OPENAI_",),
+ ),
+ )
diff --git a/src/free_claude_code/cli/codex_integration.py b/src/free_claude_code/harnesses/codex_integration.py
similarity index 92%
rename from src/free_claude_code/cli/codex_integration.py
rename to src/free_claude_code/harnesses/codex_integration.py
index cf75d974..631ba2b3 100644
--- a/src/free_claude_code/cli/codex_integration.py
+++ b/src/free_claude_code/harnesses/codex_integration.py
@@ -9,11 +9,13 @@ from tomlkit.exceptions import ParseError
from tomlkit.items import InlineTable, Table
from tomlkit.toml_document import TOMLDocument
-from free_claude_code.cli.config_file import atomic_write_text
-from free_claude_code.cli.launchers.codex import codex_config_values
-from free_claude_code.cli.launchers.common import proxy_v1_url
-from free_claude_code.config.server_urls import same_proxy_url
+from free_claude_code.config.server_urls import proxy_v1_url, same_proxy_url
from free_claude_code.core.json_types import JsonObject
+from free_claude_code.harnesses.codex import (
+ PRINT_PROXY_AUTH_TOKEN_FLAG,
+ codex_config_values,
+)
+from free_claude_code.harnesses.config_file import atomic_write_text
def config_path() -> Path:
@@ -74,7 +76,7 @@ def _connected(document: TOMLDocument, catalog_path: Path, proxy_root_url: str)
and same_proxy_url(provider.get("base_url"), proxy_v1_url(proxy_root_url))
and provider.get("wire_api") == "responses"
and auth.get("command") == "fcc-codex"
- and auth.get("args") == ["--print-proxy-auth-token"]
+ and auth.get("args") == [PRINT_PROXY_AUTH_TOKEN_FLAG]
)
diff --git a/src/free_claude_code/cli/launchers/codex_model_catalog.py b/src/free_claude_code/harnesses/codex_model_catalog.py
similarity index 79%
rename from src/free_claude_code/cli/launchers/codex_model_catalog.py
rename to src/free_claude_code/harnesses/codex_model_catalog.py
index 4bf7663b..482ae005 100644
--- a/src/free_claude_code/cli/launchers/codex_model_catalog.py
+++ b/src/free_claude_code/harnesses/codex_model_catalog.py
@@ -1,11 +1,8 @@
"""Build Codex model catalogs from the FCC model-list route."""
-import json
-import uuid
-from collections.abc import Mapping, Sequence
-from pathlib import Path
+from collections.abc import Sequence
-from free_claude_code.core.json_types import JsonObject, JsonValue
+from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.model_capabilities import ModelInputModality
from .model_catalog import ClientModel
@@ -43,28 +40,6 @@ def build_codex_model_catalog(models: Sequence[ClientModel]) -> JsonObject:
}
-def write_codex_model_catalog(
- catalog_path: Path, catalog: Mapping[str, JsonValue]
-) -> bool:
- """Atomically write changed Codex model catalog JSON."""
-
- content = (json.dumps(catalog, ensure_ascii=True, indent=2) + "\n").encode()
- try:
- if catalog_path.read_bytes() == content:
- return False
- except FileNotFoundError:
- pass
-
- catalog_path.parent.mkdir(parents=True, exist_ok=True)
- temp_path = catalog_path.with_name(f".{catalog_path.name}.{uuid.uuid4().hex}.tmp")
- try:
- temp_path.write_bytes(content)
- temp_path.replace(catalog_path)
- finally:
- temp_path.unlink(missing_ok=True)
- return True
-
-
def _codex_catalog_entry(candidate: ClientModel, *, priority: int) -> JsonObject:
supports_reasoning = candidate.supports_reasoning is not False
input_modalities = candidate.input_modalities or frozenset(
diff --git a/src/free_claude_code/cli/config_file.py b/src/free_claude_code/harnesses/config_file.py
similarity index 100%
rename from src/free_claude_code/cli/config_file.py
rename to src/free_claude_code/harnesses/config_file.py
diff --git a/src/free_claude_code/cli/environment.py b/src/free_claude_code/harnesses/environment.py
similarity index 53%
rename from src/free_claude_code/cli/environment.py
rename to src/free_claude_code/harnesses/environment.py
index 31cc62e3..13de82c7 100644
--- a/src/free_claude_code/cli/environment.py
+++ b/src/free_claude_code/harnesses/environment.py
@@ -1,8 +1,10 @@
"""Shared child-only environment setup for native clients."""
from collections.abc import Mapping, Sequence
+from urllib.parse import urlsplit
-from .local_http import with_local_proxy_bypass
+_LOOPBACK_BYPASS_HOSTS = ("127.0.0.1", "localhost", "::1")
+_NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
def client_environment(
@@ -39,3 +41,38 @@ def require_unset_environment(base_env: Mapping[str, str], keys: Sequence[str])
for key in keys:
if base_env.get(key, "").strip():
raise ValueError(f"{key} is already set. Unset it before using FCC.")
+
+
+def with_local_proxy_bypass(
+ base_env: Mapping[str, str],
+ *,
+ proxy_root_url: str,
+) -> dict[str, str]:
+ """Copy an environment and keep its FCC-local destination off proxies."""
+
+ host = urlsplit(proxy_root_url).hostname
+ if host is None:
+ raise ValueError("Local proxy root URL must include a host.")
+
+ env = dict(base_env)
+ entries: list[str] = []
+ seen: set[str] = set()
+ for key in _NO_PROXY_KEYS:
+ for raw_entry in base_env.get(key, "").split(","):
+ _append_unique(entries, seen, raw_entry)
+ for local_host in (*_LOOPBACK_BYPASS_HOSTS, host):
+ _append_unique(entries, seen, local_host)
+
+ value = ",".join(entries)
+ for key in _NO_PROXY_KEYS:
+ env[key] = value
+ return env
+
+
+def _append_unique(entries: list[str], seen: set[str], raw_entry: str) -> None:
+ entry = raw_entry.strip()
+ normalized = entry.casefold()
+ if not entry or normalized in seen:
+ return
+ entries.append(entry)
+ seen.add(normalized)
diff --git a/src/free_claude_code/harnesses/launch.py b/src/free_claude_code/harnesses/launch.py
new file mode 100644
index 00000000..23bf4b56
--- /dev/null
+++ b/src/free_claude_code/harnesses/launch.py
@@ -0,0 +1,21 @@
+"""Native launch descriptions; execution belongs to each caller."""
+
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass, field
+
+
+@dataclass(frozen=True, slots=True)
+class NativeCheck:
+ """A fixed native probe; its adapter owns output interpretation."""
+
+ args: tuple[str, ...]
+ accepts: Callable[[str], bool]
+ failure_message: str
+ timeout_seconds: float = 5.0
+
+
+@dataclass(frozen=True, slots=True)
+class PreparedLaunch:
+ command: list[str] = field(repr=False)
+ env: Mapping[str, str] = field(repr=False)
+ activation_check: NativeCheck | None = None
diff --git a/src/free_claude_code/cli/launchers/model_catalog.py b/src/free_claude_code/harnesses/model_catalog.py
similarity index 78%
rename from src/free_claude_code/cli/launchers/model_catalog.py
rename to src/free_claude_code/harnesses/model_catalog.py
index 7ccf71a0..8be1168c 100644
--- a/src/free_claude_code/cli/launchers/model_catalog.py
+++ b/src/free_claude_code/harnesses/model_catalog.py
@@ -1,17 +1,11 @@
-"""Shared FCC model-catalog projection for installed client launchers."""
+"""Shared FCC model-catalog projection for native clients."""
-import json
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
-from typing import Literal
-from urllib.request import Request
-from free_claude_code.cli.local_http import open_local_request
-from free_claude_code.core.json_types import JsonObject, JsonValue
+from free_claude_code.core.json_types import JsonValue
from free_claude_code.core.model_capabilities import ModelInputModality
-from .common import PROXY_PREFLIGHT_TIMEOUT_SECONDS
-
@dataclass(frozen=True, slots=True)
class ClientModel:
@@ -63,29 +57,6 @@ def catalog_wire_slug_for_ref(
return provider_model_ref
-def fetch_proxy_models_response(
- proxy_root_url: str,
- auth_token: str,
- view: Literal["messages", "responses"] = "responses",
-) -> JsonObject:
- """Fetch the authenticated FCC-local `/v1/models` response directly."""
-
- url = f"{proxy_root_url.rstrip('/')}/v1/models?view={view}"
- request = Request(
- url,
- headers={"Authorization": f"Bearer {auth_token}"},
- method="GET",
- )
- with open_local_request(
- request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS
- ) as response:
- payload: JsonValue = 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 _catalog_candidates(
models_response: Mapping[str, JsonValue],
) -> list[ClientModel]:
diff --git a/src/free_claude_code/cli/launchers/resources.py b/src/free_claude_code/harnesses/resources.py
similarity index 100%
rename from src/free_claude_code/cli/launchers/resources.py
rename to src/free_claude_code/harnesses/resources.py
diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.py
index b6933900..6d3c2117 100644
--- a/src/free_claude_code/runtime/application.py
+++ b/src/free_claude_code/runtime/application.py
@@ -27,7 +27,6 @@ from free_claude_code.application.errors import (
)
from free_claude_code.application.model_metadata import ProviderModelRefreshResult
from free_claude_code.application.ports import StopResult
-from free_claude_code.cli import codex_integration, vscode
from free_claude_code.config.admin.persistence import (
PreparedAdminUpdate,
)
@@ -42,6 +41,7 @@ from free_claude_code.config.paths import (
from free_claude_code.config.server_urls import local_admin_url, local_proxy_root_url
from free_claude_code.config.settings import Settings
from free_claude_code.core.json_types import JsonObject
+from free_claude_code.harnesses import claude_integration, codex_integration
from free_claude_code.messaging.platforms import factory as messaging_platform_factory
from free_claude_code.messaging.platforms.factory import MessagingPlatformOptions
from free_claude_code.messaging.platforms.ports import (
@@ -374,9 +374,9 @@ class ApplicationRuntime:
return await _await_owned_task(
asyncio.create_task(
to_thread.run_sync(
- vscode.configure,
- vscode.settings_path(),
- vscode.claude_state_path(),
+ claude_integration.configure,
+ claude_integration.settings_path(),
+ claude_integration.claude_state_path(),
local_proxy_root_url(settings),
settings.proxy_auth_token,
connected,
diff --git a/src/free_claude_code/runtime/codex_app_server.py b/src/free_claude_code/runtime/codex_app_server.py
index bc578447..4747cca8 100644
--- a/src/free_claude_code/runtime/codex_app_server.py
+++ b/src/free_claude_code/runtime/codex_app_server.py
@@ -10,7 +10,7 @@ import subprocess
import uuid
from collections.abc import Mapping
from contextlib import ExitStack, suppress
-from dataclasses import dataclass, replace
+from dataclasses import dataclass, field, replace
from free_claude_code.application.code_sessions.models import (
CodeCatalog,
@@ -25,15 +25,15 @@ from free_claude_code.application.code_sessions.models import (
)
from free_claude_code.application.code_sessions.ports import EventSink, HarnessSelection
from free_claude_code.application.ports import RequestRuntimePort
-from free_claude_code.cli.launchers.codex import SPEC, prepare_codex_launch
-from free_claude_code.cli.launchers.codex_model_catalog import build_codex_model_catalog
-from free_claude_code.cli.launchers.resources import LaunchResources
-from free_claude_code.cli.launchers.runner import LaunchContext
from free_claude_code.cli.process_registry import register_pid, unregister_pid
from free_claude_code.config.model_refs import split_provider_model_ref
from free_claude_code.config.server_urls import local_proxy_root_url
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.version import package_version
+from free_claude_code.harnesses.codex import CODEX_INSTALL_HINT, prepare_codex_launch
+from free_claude_code.harnesses.codex_model_catalog import build_codex_model_catalog
+from free_claude_code.harnesses.model_catalog import ClientModel
+from free_claude_code.harnesses.resources import LaunchResources
from .codex_catalog import current_codex_models
from .codex_protocol import (
@@ -575,7 +575,10 @@ class CodexAppServer:
@dataclass(frozen=True, slots=True)
class _CodexSelection:
- context: LaunchContext
+ binary_path: str
+ proxy_root_url: str
+ base_env: Mapping[str, str] = field(repr=False)
+ models: tuple[ClientModel, ...]
model: str
configuration_key: str
fingerprints: dict[str, str]
@@ -586,15 +589,19 @@ class _CodexSelection:
resources = ExitStack()
try:
prepared = prepare_codex_launch(
- self.context,
- [
+ binary_path=self.binary_path,
+ proxy_root_url=self.proxy_root_url,
+ model=self.model,
+ models=self.models,
+ base_env=self.base_env,
+ args=[
"-c",
"features.default_mode_request_user_input=true",
"-c",
"tools.experimental_request_user_input.enabled=true",
"app-server",
],
- LaunchResources(resources),
+ files=LaunchResources(resources),
)
connection = CodexAppServer(
prepared.command,
@@ -602,13 +609,12 @@ class _CodexSelection:
cwd,
sink,
model_slugs={
- model.provider_model_ref: model.wire_slug
- for model in self.context.models
+ model.provider_model_ref: model.wire_slug for model in self.models
},
fingerprints=self.fingerprints,
reasoning={
model.provider_model_ref: model.supports_reasoning is not False
- for model in self.context.models
+ for model in self.models
},
resources=resources,
)
@@ -632,7 +638,7 @@ class CodexHarnessFactory:
def availability(self) -> tuple[bool, str | None]:
if self._binary or shutil.which("codex"):
return True, None
- return False, "Codex is not installed. " + SPEC.install_hint
+ return False, "Codex is not installed. " + CODEX_INSTALL_HINT
def catalog(self) -> CodeCatalog:
settings = self._runtime.current_settings()
@@ -655,7 +661,7 @@ class CodexHarnessFactory:
) -> _CodexSelection:
binary = self._binary or shutil.which("codex")
if binary is None:
- raise CodeUnavailableError("Codex is not installed. " + SPEC.install_hint)
+ raise CodeUnavailableError("Codex is not installed. " + CODEX_INSTALL_HINT)
settings = self._runtime.current_settings()
models = current_codex_models(self._runtime, settings)
selected = next(
@@ -693,16 +699,16 @@ class CodexHarnessFactory:
model.provider_model_ref: _fingerprint(entries[model.wire_slug])
for model in models
}
- context = LaunchContext(
- binary,
- settings.model_copy(update={"model": model}),
- local_proxy_root_url(settings),
- settings.proxy_auth_token,
- dict(self._env if self._env is not None else os.environ),
- models,
- )
return _CodexSelection(
- context, model, fingerprints[model], fingerprints, effort, mode
+ binary_path=binary,
+ proxy_root_url=local_proxy_root_url(settings),
+ base_env=dict(self._env if self._env is not None else os.environ),
+ models=models,
+ model=model,
+ configuration_key=fingerprints[model],
+ fingerprints=fingerprints,
+ reasoning_effort=effort,
+ mode=mode,
)
async def open_history(self, cwd: str, sink: EventSink) -> CodexAppServer:
@@ -710,7 +716,7 @@ class CodexHarnessFactory:
if binary is None:
raise CodeUnavailableError(
"Codex is needed to remove its native conversation. "
- + SPEC.install_hint
+ + CODEX_INSTALL_HINT
)
connection = CodexAppServer(
[binary, "app-server"],
diff --git a/src/free_claude_code/runtime/codex_catalog.py b/src/free_claude_code/runtime/codex_catalog.py
index 1da9354d..0c628440 100644
--- a/src/free_claude_code/runtime/codex_catalog.py
+++ b/src/free_claude_code/runtime/codex_catalog.py
@@ -1,5 +1,8 @@
"""Publish the application model inventory for Codex clients."""
+import json
+import uuid
+from collections.abc import Mapping
from pathlib import Path
from free_claude_code.api.model_catalog import (
@@ -7,16 +10,16 @@ from free_claude_code.api.model_catalog import (
build_models_list_response,
)
from free_claude_code.application.ports import RequestRuntimePort
-from free_claude_code.cli.launchers.codex_model_catalog import (
+from free_claude_code.config.paths import codex_model_catalog_path
+from free_claude_code.config.settings import Settings
+from free_claude_code.core.json_types import JsonValue
+from free_claude_code.harnesses.codex_model_catalog import (
build_codex_model_catalog,
- write_codex_model_catalog,
)
-from free_claude_code.cli.launchers.model_catalog import (
+from free_claude_code.harnesses.model_catalog import (
ClientModel,
client_models_from_response,
)
-from free_claude_code.config.paths import codex_model_catalog_path
-from free_claude_code.config.settings import Settings
def current_codex_models(
@@ -65,3 +68,25 @@ class CodexModelCatalogPublisher:
def _resolved_catalog_path(self) -> Path:
return self._catalog_path or codex_model_catalog_path()
+
+
+def write_codex_model_catalog(
+ catalog_path: Path, catalog: Mapping[str, JsonValue]
+) -> bool:
+ """Atomically write changed Codex model catalog JSON."""
+
+ content = (json.dumps(catalog, ensure_ascii=True, indent=2) + "\n").encode()
+ try:
+ if catalog_path.read_bytes() == content:
+ return False
+ except FileNotFoundError:
+ pass
+
+ catalog_path.parent.mkdir(parents=True, exist_ok=True)
+ temp_path = catalog_path.with_name(f".{catalog_path.name}.{uuid.uuid4().hex}.tmp")
+ try:
+ temp_path.write_bytes(content)
+ temp_path.replace(catalog_path)
+ finally:
+ temp_path.unlink(missing_ok=True)
+ return True
diff --git a/tests/api/test_codex_integration_routes.py b/tests/api/test_codex_integration_routes.py
index be9ba62f..531a20a7 100644
--- a/tests/api/test_codex_integration_routes.py
+++ b/tests/api/test_codex_integration_routes.py
@@ -3,9 +3,9 @@ import tomllib
import pytest
from fastapi.testclient import TestClient
-from free_claude_code.cli import codex_integration
from free_claude_code.config.paths import codex_model_catalog_path
from free_claude_code.config.settings import Settings
+from free_claude_code.harnesses import codex_integration
from tests.api.support import create_test_app, runtime_for_app
ROOT = "/admin/api/integrations/codex"
diff --git a/tests/api/test_vscode_integration.py b/tests/api/test_vscode_integration.py
index a1770262..5d50f613 100644
--- a/tests/api/test_vscode_integration.py
+++ b/tests/api/test_vscode_integration.py
@@ -3,8 +3,8 @@ import json
import pytest
from fastapi.testclient import TestClient
-from free_claude_code.cli import vscode
from free_claude_code.config.settings import Settings
+from free_claude_code.harnesses import claude_integration
from tests.api.support import create_test_app, runtime_for_app
ROOT = "/admin/api/integrations/claude-vscode"
@@ -13,8 +13,10 @@ ROOT = "/admin/api/integrations/claude-vscode"
@pytest.fixture
def integration(tmp_path, monkeypatch):
path = tmp_path / "settings.json"
- monkeypatch.setattr(vscode, "settings_path", lambda: path)
- monkeypatch.setattr(vscode, "claude_state_path", lambda: tmp_path / ".claude.json")
+ monkeypatch.setattr(claude_integration, "settings_path", lambda: path)
+ monkeypatch.setattr(
+ claude_integration, "claude_state_path", lambda: tmp_path / ".claude.json"
+ )
app = create_test_app(
Settings(host="0.0.0.0", port=4321, proxy_auth_token="integration-secret")
)
@@ -121,7 +123,7 @@ def test_io_failure_returns_safe_error(integration, monkeypatch):
def fail(*args):
raise PermissionError("integration-secret")
- monkeypatch.setattr(vscode, "configure", fail)
+ monkeypatch.setattr(claude_integration, "configure", fail)
response = client.post(f"{ROOT}/connect")
assert response.status_code == 503
assert "integration-secret" not in response.text
diff --git a/tests/cli/test_aider_config.py b/tests/cli/test_aider_config.py
index 70c55668..4dae3bec 100644
--- a/tests/cli/test_aider_config.py
+++ b/tests/cli/test_aider_config.py
@@ -5,8 +5,8 @@ import json
import pytest
from free_claude_code.cli.launchers.aider_config import build_aider_config
-from free_claude_code.cli.launchers.model_catalog import ClientModel
from free_claude_code.core.model_capabilities import ModelInputModality
+from free_claude_code.harnesses.model_catalog import ClientModel
def _models() -> tuple[ClientModel, ...]:
diff --git a/tests/cli/test_catalog_http.py b/tests/cli/test_catalog_http.py
new file mode 100644
index 00000000..af454a5f
--- /dev/null
+++ b/tests/cli/test_catalog_http.py
@@ -0,0 +1,62 @@
+from unittest.mock import patch
+
+import pytest
+
+from free_claude_code.cli.launchers.catalog_http import fetch_proxy_models_response
+
+
+class _ModelsResponse:
+ def __init__(self, body: bytes) -> None:
+ self._body = body
+
+ def __enter__(self) -> _ModelsResponse:
+ return self
+
+ def __exit__(self, *exc_info: object) -> None:
+ del exc_info
+
+ def read(self) -> bytes:
+ return self._body
+
+
+def test_fetch_proxy_models_uses_canonical_bearer_request() -> None:
+ with patch(
+ "free_claude_code.cli.launchers.catalog_http.open_local_request",
+ return_value=_ModelsResponse(b'{"data": []}'),
+ ) as open_local_request:
+ response = fetch_proxy_models_response("http://127.0.0.1:9191/", "proxy-token")
+
+ assert response == {"data": []}
+ request = open_local_request.call_args.args[0]
+ assert request.full_url == "http://127.0.0.1:9191/v1/models?view=responses"
+ assert request.get_method() == "GET"
+ assert request.get_header("Authorization") == "Bearer proxy-token"
+
+
+def test_fetch_proxy_models_can_request_messages_view() -> None:
+ with patch(
+ "free_claude_code.cli.launchers.catalog_http.open_local_request",
+ return_value=_ModelsResponse(b'{"data": []}'),
+ ) as open_local_request:
+ response = fetch_proxy_models_response(
+ "http://127.0.0.1:9191/",
+ "proxy-token",
+ view="messages",
+ )
+
+ assert response == {"data": []}
+ request = open_local_request.call_args.args[0]
+ assert request.full_url == "http://127.0.0.1:9191/v1/models?view=messages"
+ assert request.get_method() == "GET"
+ assert request.get_header("Authorization") == "Bearer proxy-token"
+
+
+def test_fetch_proxy_models_rejects_non_object_json() -> None:
+ with (
+ patch(
+ "free_claude_code.cli.launchers.catalog_http.open_local_request",
+ return_value=_ModelsResponse(b"[]"),
+ ),
+ pytest.raises(ValueError, match="JSON object"),
+ ):
+ fetch_proxy_models_response("http://127.0.0.1:9191", "proxy-token")
diff --git a/tests/cli/test_cline_launcher.py b/tests/cli/test_cline_launcher.py
index fe6c749c..a4c678de 100644
--- a/tests/cli/test_cline_launcher.py
+++ b/tests/cli/test_cline_launcher.py
@@ -10,8 +10,8 @@ from free_claude_code.cli.launchers.cline_config import (
CLINE_PROVIDER_ID,
build_cline_config,
)
-from free_claude_code.cli.launchers.model_catalog import ClientModel
from free_claude_code.core.model_capabilities import ModelInputModality
+from free_claude_code.harnesses.model_catalog import ClientModel
def test_cline_config_uses_responses_and_only_known_metadata() -> None:
diff --git a/tests/cli/test_codex_model_catalog.py b/tests/cli/test_codex_model_catalog.py
index c9d2e7ef..48684862 100644
--- a/tests/cli/test_codex_model_catalog.py
+++ b/tests/cli/test_codex_model_catalog.py
@@ -2,220 +2,17 @@ import json
import os
import shutil
import subprocess
-from collections.abc import Mapping
from pathlib import Path
-from typing import Any, cast
import pytest
-from free_claude_code.cli.launchers.codex import codex_config_args
-from free_claude_code.cli.launchers.codex_model_catalog import (
+from free_claude_code.harnesses.codex import codex_config_args
+from free_claude_code.harnesses.codex_model_catalog import (
build_codex_model_catalog,
- write_codex_model_catalog,
)
-from free_claude_code.cli.launchers.model_catalog import client_models_from_response
-
-
-def _models_payload(*model_ids: str) -> dict[str, Any]:
- return {
- "data": [
- {
- "id": model_id,
- "provider_model_ref": (
- model_id.removeprefix("claude-3-freecc-no-thinking/")
- ),
- "display_name": model_id,
- }
- for model_id in model_ids
- ]
- }
-
-
-def _catalog_models(catalog: Mapping[str, Any]) -> list[Mapping[str, Any]]:
- models = catalog["models"]
- assert isinstance(models, list)
- catalog_models: list[Mapping[str, Any]] = []
- for model in models:
- assert isinstance(model, Mapping)
- catalog_models.append(cast(Mapping[str, Any], model))
- return catalog_models
-
-
-def _slugs(catalog: Mapping[str, Any]) -> list[str]:
- slugs: list[str] = []
- for model in _catalog_models(catalog):
- slug = model["slug"]
- assert isinstance(slug, str)
- slugs.append(slug)
- return slugs
-
-
-def test_codex_catalog_uses_direct_configured_and_cached_model_slugs() -> None:
- catalog = build_codex_model_catalog(
- client_models_from_response(
- _models_payload(
- "nvidia_nim/nvidia/nemotron-3-super",
- "open_router/meta-llama/llama-3.3-70b",
- )
- )
- )
-
- assert _slugs(catalog) == [
- "nvidia_nim/nvidia/nemotron-3-super",
- "open_router/meta-llama/llama-3.3-70b",
- ]
- model = _catalog_models(catalog)[0]
- assert {
- "slug",
- "display_name",
- "description",
- "default_reasoning_level",
- "supported_reasoning_levels",
- "shell_type",
- "visibility",
- "supported_in_api",
- "priority",
- "additional_speed_tiers",
- "service_tiers",
- } <= set(model)
-
-
-def test_codex_catalog_ignores_rows_without_direct_provider_identity() -> None:
- catalog = build_codex_model_catalog(
- client_models_from_response(
- {
- "data": [
- {"id": "claude-opus-4-20250514"},
- {
- "id": "nvidia_nim/provider-model",
- "provider_model_ref": "nvidia_nim/provider-model",
- "display_name": "NIM",
- },
- ]
- }
- )
- )
-
- assert _slugs(catalog) == ["nvidia_nim/provider-model"]
-
-
-def test_codex_catalog_deduplicates_direct_wire_ids() -> None:
- catalog = build_codex_model_catalog(
- client_models_from_response(
- _models_payload(
- "nvidia_nim/provider-model",
- "nvidia_nim/provider-model",
- )
- )
- )
-
- assert _slugs(catalog) == ["nvidia_nim/provider-model"]
-
-
-def test_codex_catalog_preserves_no_thinking_only_entries_for_routing() -> None:
- catalog = build_codex_model_catalog(
- client_models_from_response(
- _models_payload("claude-3-freecc-no-thinking/open_router/plain-model")
- )
- )
-
- assert _slugs(catalog) == ["claude-3-freecc-no-thinking/open_router/plain-model"]
-
-
-def test_codex_catalog_ordering_and_priorities_are_deterministic() -> None:
- catalog = build_codex_model_catalog(
- client_models_from_response(
- _models_payload(
- "anthropic/gemini/models/gemini-test",
- "nvidia_nim/nvidia/test",
- "anthropic/gemini/models/gemini-test",
- "open_router/provider/test",
- )
- )
- )
-
- models = _catalog_models(catalog)
- assert _slugs(catalog) == [
- "anthropic/gemini/models/gemini-test",
- "nvidia_nim/nvidia/test",
- "open_router/provider/test",
- ]
- assert [model["priority"] for model in models] == [0, 1, 2]
-
-
-def test_codex_catalog_accepts_direct_provider_slugs_without_a_provider_registry() -> (
- None
-):
- catalog = build_codex_model_catalog(
- client_models_from_response(
- _models_payload(
- "nvidia_nim/provider-model",
- "future_provider/provider-model",
- )
- )
- )
-
- assert _slugs(catalog) == [
- "nvidia_nim/provider-model",
- "future_provider/provider-model",
- ]
-
-
-def test_codex_catalog_projects_known_capabilities_and_preserves_unknown_defaults() -> (
- None
-):
- catalog = build_codex_model_catalog(
- client_models_from_response(
- {
- "data": [
- {
- "id": "provider/vision-reasoning",
- "provider_model_ref": "provider/vision-reasoning",
- "supportsReasoning": True,
- "inputModalities": ["text", "image"],
- "contextWindow": 131072,
- "maxCompletionTokens": 8192,
- },
- {
- "id": "claude-3-freecc-no-thinking/provider/text-only",
- "provider_model_ref": "provider/text-only",
- "supportsReasoning": False,
- "inputModalities": ["text"],
- "maxCompletionTokens": 4096,
- },
- {
- "id": "provider/unknown",
- "provider_model_ref": "provider/unknown",
- },
- ]
- }
- )
- )
-
- vision, text_only, unknown = _catalog_models(catalog)
- assert vision["input_modalities"] == ["text", "image"]
- assert vision["default_reasoning_level"] == "medium"
- assert vision["supported_reasoning_levels"]
- assert vision["supports_reasoning_summaries"] is True
- assert vision["default_reasoning_summary"] == "none"
- assert vision["context_window"] == 131072
- assert vision["max_context_window"] == 131072
-
- assert text_only["input_modalities"] == ["text"]
- assert "default_reasoning_level" not in text_only
- assert text_only["supported_reasoning_levels"] == []
- assert text_only["supports_reasoning_summaries"] is False
- assert "default_reasoning_summary" not in text_only
- assert text_only["context_window"] == 200000
- assert text_only["max_context_window"] == 200000
-
- assert unknown["input_modalities"] == ["text"]
- assert unknown["default_reasoning_level"] == "medium"
- assert unknown["supported_reasoning_levels"]
- assert unknown["supports_reasoning_summaries"] is True
- assert unknown["default_reasoning_summary"] == "none"
- assert unknown["context_window"] == 200000
- assert unknown["max_context_window"] == 200000
+from free_claude_code.harnesses.model_catalog import client_models_from_response
+from free_claude_code.runtime.codex_catalog import write_codex_model_catalog
+from tests.harnesses.test_codex_model_catalog import _models_payload
def test_launcher_config_composes_with_persistent_codex_config(
@@ -282,47 +79,3 @@ def test_launcher_config_composes_with_persistent_codex_config(
assert result.returncode == 0, result.stderr
assert "nvidia_nim/test-model" in result.stdout
-
-
-def test_catalog_writer_skips_identical_content_and_replaces_changes(
- tmp_path: Path,
-) -> None:
- catalog_path = tmp_path / "codex-model-catalog.json"
- first = build_codex_model_catalog(
- client_models_from_response(_models_payload("nvidia_nim/first"))
- )
- second = build_codex_model_catalog(
- client_models_from_response(_models_payload("nvidia_nim/second"))
- )
-
- assert write_codex_model_catalog(catalog_path, first) is True
- assert write_codex_model_catalog(catalog_path, first) is False
- assert list(tmp_path.glob(".codex-model-catalog.json.*.tmp")) == []
-
- assert write_codex_model_catalog(catalog_path, second) is True
- assert json.loads(catalog_path.read_text(encoding="utf-8")) == second
- assert list(tmp_path.glob(".codex-model-catalog.json.*.tmp")) == []
-
-
-def test_catalog_writer_cleans_temporary_file_after_replace_failure(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- catalog_path = tmp_path / "codex-model-catalog.json"
- catalog_path.write_text("previous\n", encoding="utf-8")
-
- def fail_replace(_source: Path, _destination: Path) -> Path:
- raise PermissionError("destination is locked")
-
- monkeypatch.setattr(Path, "replace", fail_replace)
-
- with pytest.raises(PermissionError, match="locked"):
- write_codex_model_catalog(
- catalog_path,
- build_codex_model_catalog(
- client_models_from_response(_models_payload("nvidia_nim/replacement"))
- ),
- )
-
- assert catalog_path.read_text(encoding="utf-8") == "previous\n"
- assert list(tmp_path.glob(".codex-model-catalog.json.*.tmp")) == []
diff --git a/tests/cli/test_dsh_config.py b/tests/cli/test_dsh_config.py
index 09902c4b..5fe27ba2 100644
--- a/tests/cli/test_dsh_config.py
+++ b/tests/cli/test_dsh_config.py
@@ -7,8 +7,8 @@ from pathlib import Path
import pytest
from free_claude_code.cli.launchers.dsh_config import build_dsh_launch_config
-from free_claude_code.cli.launchers.model_catalog import ClientModel
from free_claude_code.core.model_capabilities import ModelInputModality
+from free_claude_code.harnesses.model_catalog import ClientModel
def _models() -> tuple[ClientModel, ...]:
diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.py
index 5642314b..d293e1dc 100644
--- a/tests/cli/test_entrypoints.py
+++ b/tests/cli/test_entrypoints.py
@@ -415,7 +415,7 @@ def test_serve_handles_keyboard_interrupt_without_traceback() -> None:
def test_claude_child_env_targets_current_proxy_config() -> None:
- from free_claude_code.cli.claude_env import build_claude_proxy_env
+ from free_claude_code.harnesses.claude import build_claude_proxy_env
env = build_claude_proxy_env(
proxy_root_url="http://127.0.0.1:9090",
diff --git a/tests/cli/test_hermes_config.py b/tests/cli/test_hermes_config.py
index a38e7d59..f93023f7 100644
--- a/tests/cli/test_hermes_config.py
+++ b/tests/cli/test_hermes_config.py
@@ -7,8 +7,8 @@ import pytest
from free_claude_code.cli.launchers.hermes_config import (
build_hermes_managed_config,
)
-from free_claude_code.cli.launchers.model_catalog import ClientModel
from free_claude_code.core.model_capabilities import ModelInputModality
+from free_claude_code.harnesses.model_catalog import ClientModel
def _models() -> tuple[ClientModel, ...]:
diff --git a/tests/cli/test_launcher_resources.py b/tests/cli/test_launcher_resources.py
index d3b16e48..cf6f753f 100644
--- a/tests/cli/test_launcher_resources.py
+++ b/tests/cli/test_launcher_resources.py
@@ -7,8 +7,9 @@ from unittest.mock import Mock, patch
import pytest
-from free_claude_code.cli.launchers import common, resources
+from free_claude_code.cli.launchers import common
from free_claude_code.config.paths import launcher_temp_dir_path
+from free_claude_code.harnesses import resources
from tests.cli.conftest import LaunchCapture
from tests.cli.test_launcher_workflow import launch
diff --git a/tests/cli/test_launcher_workflow.py b/tests/cli/test_launcher_workflow.py
index 9d6c66ec..87feaa8d 100644
--- a/tests/cli/test_launcher_workflow.py
+++ b/tests/cli/test_launcher_workflow.py
@@ -9,8 +9,8 @@ from urllib.error import URLError
import pytest
from free_claude_code.cli.launchers.aider_config import build_aider_config
-from free_claude_code.cli.launchers.model_catalog import ClientModel
from free_claude_code.config.paths import codex_model_catalog_path
+from free_claude_code.harnesses.model_catalog import ClientModel
from tests.cli.conftest import LaunchCapture
HARNESSES = (
diff --git a/tests/cli/test_local_http.py b/tests/cli/test_local_http.py
index 58a3d76a..139f44c2 100644
--- a/tests/cli/test_local_http.py
+++ b/tests/cli/test_local_http.py
@@ -8,7 +8,6 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from free_claude_code.cli.launchers.common import preflight_proxy
-from free_claude_code.cli.local_http import with_local_proxy_bypass
@contextmanager
@@ -49,36 +48,3 @@ def test_proxy_preflight_connects_directly_when_http_proxy_is_configured(
assert fcc_hits == ["/health"]
assert forward_proxy_hits == []
-
-
-def test_child_proxy_bypass_preserves_existing_proxy_policy() -> None:
- base_env = {
- "HTTP_PROXY": "http://proxy.example:3128",
- "NO_PROXY": "example.com, localhost",
- "no_proxy": "10.0.0.0/8,EXAMPLE.COM",
- "KEEP_ME": "yes",
- }
-
- env = with_local_proxy_bypass(
- base_env,
- proxy_root_url="http://fcc.internal:8082",
- )
-
- assert env["HTTP_PROXY"] == "http://proxy.example:3128"
- assert env["KEEP_ME"] == "yes"
- assert env["NO_PROXY"] == (
- "example.com,localhost,10.0.0.0/8,127.0.0.1,::1,fcc.internal"
- )
- assert env["no_proxy"] == env["NO_PROXY"]
- assert base_env["NO_PROXY"] == "example.com, localhost"
- assert base_env["no_proxy"] == "10.0.0.0/8,EXAMPLE.COM"
-
-
-def test_child_proxy_bypass_uses_all_loopback_spellings_without_duplicates() -> None:
- env = with_local_proxy_bypass(
- {"NO_PROXY": "127.0.0.1"},
- proxy_root_url="http://127.0.0.1:8082",
- )
-
- assert env["NO_PROXY"] == "127.0.0.1,localhost,::1"
- assert env["no_proxy"] == env["NO_PROXY"]
diff --git a/tests/cli/test_managed_claude.py b/tests/cli/test_managed_claude.py
index 059e587c..3041dcee 100644
--- a/tests/cli/test_managed_claude.py
+++ b/tests/cli/test_managed_claude.py
@@ -1,6 +1,5 @@
import os
-from free_claude_code.cli.claude_env import build_claude_proxy_env
from free_claude_code.cli.managed.claude import (
MANAGED_CLAUDE_MODEL_TIER,
ManagedClaudeConfig,
@@ -12,6 +11,7 @@ from free_claude_code.cli.managed.claude import (
parse_managed_claude_stdout_line,
)
from free_claude_code.cli.managed.diagnostics import classify_managed_claude_stderr
+from free_claude_code.harnesses.claude import build_claude_proxy_env
def _config(**overrides: object) -> ManagedClaudeConfig:
diff --git a/tests/cli/test_opencode_launcher.py b/tests/cli/test_opencode_launcher.py
index c06dc232..1e1b2d54 100644
--- a/tests/cli/test_opencode_launcher.py
+++ b/tests/cli/test_opencode_launcher.py
@@ -5,9 +5,9 @@ from pathlib import Path
import pytest
-from free_claude_code.cli.launchers.model_catalog import ClientModel
from free_claude_code.cli.launchers.opencode_config import build_opencode_config
from free_claude_code.core.model_capabilities import ModelInputModality
+from free_claude_code.harnesses.model_catalog import ClientModel
def test_opencode_config_uses_responses_sdk_and_only_known_metadata() -> None:
diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.py
index ca0aea7b..3aac1097 100644
--- a/tests/contracts/test_import_boundaries.py
+++ b/tests/contracts/test_import_boundaries.py
@@ -17,13 +17,15 @@ ALLOWED_PACKAGE_DEPENDENCIES: dict[str, set[str]] = {
"messaging": {"core"},
"providers": {"application", "config", "core"},
"api": {"application", "config", "core"},
- "cli": {"config", "core"},
+ "harnesses": {"config", "core"},
+ "cli": {"config", "core", "harnesses"},
"runtime": {
"api",
"application",
"cli",
"config",
"core",
+ "harnesses",
"messaging",
"providers",
},
@@ -139,6 +141,39 @@ def test_api_configuration_access_goes_through_runtime() -> None:
)
+def test_shared_harness_setup_has_no_terminal_owner() -> None:
+ former_paths = {
+ "cli/environment.py",
+ "cli/claude_env.py",
+ "cli/vscode.py",
+ "cli/codex_integration.py",
+ "cli/config_file.py",
+ "cli/launchers/resources.py",
+ "cli/launchers/model_catalog.py",
+ "cli/launchers/codex_model_catalog.py",
+ }
+ former_modules = {
+ f"{_PACKAGE_NAME}.{path.removesuffix('.py').replace('/', '.')}"
+ for path in former_paths
+ }
+ callers = {
+ f"{_PACKAGE_NAME}.runtime.codex_app_server",
+ f"{_PACKAGE_NAME}.runtime.codex_catalog",
+ }
+ records = _scan_imports(_PACKAGE_ROOT, known_modules=former_modules)
+ offenders = [
+ record.describe()
+ for record in records
+ if record.imported in former_modules
+ or (
+ record.importer in callers
+ and record.imported.startswith(f"{_PACKAGE_NAME}.cli.launchers")
+ )
+ ]
+ remaining = sorted(path for path in former_paths if (_PACKAGE_ROOT / path).exists())
+ assert not offenders and not remaining, "\n".join(offenders + remaining)
+
+
def test_package_dependencies_follow_declarative_policy() -> None:
modules = _module_paths(_PACKAGE_ROOT)
records = _scan_imports(_PACKAGE_ROOT)
@@ -247,7 +282,6 @@ def test_cli_local_http_transport_has_one_owner() -> None:
cli_root = _PACKAGE_ROOT / "cli"
owner = cli_root / "local_http.py"
owned_urllib_names = {"ProxyHandler", "build_opener", "urlopen"}
- owned_environment_keys = {"NO_PROXY", "no_proxy"}
offenders: list[str] = []
for path in cli_root.rglob("*.py"):
@@ -262,9 +296,23 @@ def test_cli_local_http_transport_has_one_owner() -> None:
for alias in node.names
if alias.name in owned_urllib_names
)
- if isinstance(node, ast.Constant) and node.value in owned_environment_keys:
- offenders.append(f"{relative_path}:{node.lineno}: {node.value}")
+ assert sorted(offenders) == []
+
+def test_child_proxy_environment_has_one_owner() -> None:
+ owner = _PACKAGE_ROOT / "harnesses" / "environment.py"
+ offenders: list[str] = []
+ for root in (_PACKAGE_ROOT / "cli", _PACKAGE_ROOT / "harnesses"):
+ for path in root.rglob("*.py"):
+ if path == owner:
+ continue
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ offenders.extend(
+ f"{path.relative_to(_REPO_ROOT).as_posix()}:{node.lineno}: {node.value}"
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Constant)
+ and node.value in {"NO_PROXY", "no_proxy"}
+ )
assert sorted(offenders) == []
@@ -636,9 +684,11 @@ def _module_name(package_root: Path, path: Path) -> str:
return ".".join((package_root.name, *module_parts))
-def _scan_imports(package_root: Path) -> list[ImportRecord]:
+def _scan_imports(
+ package_root: Path, *, known_modules: set[str] | None = None
+) -> list[ImportRecord]:
module_paths = _module_paths(package_root)
- modules = set(module_paths)
+ modules = set(module_paths) | (known_modules or set())
records: list[ImportRecord] = []
for importer, path in sorted(module_paths.items()):
visitor = _ImportVisitor(
diff --git a/tests/harnesses/__init__.py b/tests/harnesses/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/cli/test_vscode.py b/tests/harnesses/test_claude_integration.py
similarity index 96%
rename from tests/cli/test_vscode.py
rename to tests/harnesses/test_claude_integration.py
index b9640ab0..d8b3338c 100644
--- a/tests/cli/test_vscode.py
+++ b/tests/harnesses/test_claude_integration.py
@@ -3,7 +3,7 @@ from pathlib import Path
import pytest
-from free_claude_code.cli import vscode
+from free_claude_code.harnesses import claude_integration
URL = "http://127.0.0.1:8000"
TOKEN = "test-integration-token"
@@ -12,7 +12,9 @@ LOGIN = "claudeCode.disableLoginPrompt"
def operate(path, connected=None):
- result = vscode.configure(path, path.parent / ".claude.json", URL, TOKEN, connected)
+ result = claude_integration.configure(
+ path, path.parent / ".claude.json", URL, TOKEN, connected
+ )
return {"connected": result["connected"]}
@@ -330,17 +332,17 @@ def test_failed_replace_preserves_original_and_removes_tempfile(
],
)
def test_standard_global_path(tmp_path, monkeypatch, platform, suffix):
- monkeypatch.setattr(vscode.sys, "platform", platform)
+ monkeypatch.setattr(claude_integration.sys, "platform", platform)
monkeypatch.setattr(Path, "home", lambda: tmp_path)
monkeypatch.delenv("APPDATA", raising=False)
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
- assert vscode.settings_path() == tmp_path / suffix
+ assert claude_integration.settings_path() == tmp_path / suffix
@pytest.mark.parametrize(
"platform,variable", [("win32", "APPDATA"), ("linux", "XDG_CONFIG_HOME")]
)
def test_config_root_override(tmp_path, monkeypatch, platform, variable):
- monkeypatch.setattr(vscode.sys, "platform", platform)
+ monkeypatch.setattr(claude_integration.sys, "platform", platform)
monkeypatch.setenv(variable, str(tmp_path))
- assert vscode.settings_path() == tmp_path / "Code/User/settings.json"
+ assert claude_integration.settings_path() == tmp_path / "Code/User/settings.json"
diff --git a/tests/cli/test_codex_integration.py b/tests/harnesses/test_codex_integration.py
similarity index 99%
rename from tests/cli/test_codex_integration.py
rename to tests/harnesses/test_codex_integration.py
index 4da93998..3c25210b 100644
--- a/tests/cli/test_codex_integration.py
+++ b/tests/harnesses/test_codex_integration.py
@@ -3,7 +3,7 @@ from pathlib import Path
import pytest
-from free_claude_code.cli import codex_integration
+from free_claude_code.harnesses import codex_integration
URL = "http://127.0.0.1:8082"
diff --git a/tests/harnesses/test_codex_model_catalog.py b/tests/harnesses/test_codex_model_catalog.py
new file mode 100644
index 00000000..cf3a85df
--- /dev/null
+++ b/tests/harnesses/test_codex_model_catalog.py
@@ -0,0 +1,209 @@
+from collections.abc import Mapping
+from typing import Any, cast
+
+from free_claude_code.harnesses.codex_model_catalog import (
+ build_codex_model_catalog,
+)
+from free_claude_code.harnesses.model_catalog import client_models_from_response
+
+
+def _models_payload(*model_ids: str) -> dict[str, Any]:
+ return {
+ "data": [
+ {
+ "id": model_id,
+ "provider_model_ref": (
+ model_id.removeprefix("claude-3-freecc-no-thinking/")
+ ),
+ "display_name": model_id,
+ }
+ for model_id in model_ids
+ ]
+ }
+
+
+def _catalog_models(catalog: Mapping[str, Any]) -> list[Mapping[str, Any]]:
+ models = catalog["models"]
+ assert isinstance(models, list)
+ catalog_models: list[Mapping[str, Any]] = []
+ for model in models:
+ assert isinstance(model, Mapping)
+ catalog_models.append(cast(Mapping[str, Any], model))
+ return catalog_models
+
+
+def _slugs(catalog: Mapping[str, Any]) -> list[str]:
+ slugs: list[str] = []
+ for model in _catalog_models(catalog):
+ slug = model["slug"]
+ assert isinstance(slug, str)
+ slugs.append(slug)
+ return slugs
+
+
+def test_codex_catalog_uses_direct_configured_and_cached_model_slugs() -> None:
+ catalog = build_codex_model_catalog(
+ client_models_from_response(
+ _models_payload(
+ "nvidia_nim/nvidia/nemotron-3-super",
+ "open_router/meta-llama/llama-3.3-70b",
+ )
+ )
+ )
+
+ assert _slugs(catalog) == [
+ "nvidia_nim/nvidia/nemotron-3-super",
+ "open_router/meta-llama/llama-3.3-70b",
+ ]
+ model = _catalog_models(catalog)[0]
+ assert {
+ "slug",
+ "display_name",
+ "description",
+ "default_reasoning_level",
+ "supported_reasoning_levels",
+ "shell_type",
+ "visibility",
+ "supported_in_api",
+ "priority",
+ "additional_speed_tiers",
+ "service_tiers",
+ } <= set(model)
+
+
+def test_codex_catalog_ignores_rows_without_direct_provider_identity() -> None:
+ catalog = build_codex_model_catalog(
+ client_models_from_response(
+ {
+ "data": [
+ {"id": "claude-opus-4-20250514"},
+ {
+ "id": "nvidia_nim/provider-model",
+ "provider_model_ref": "nvidia_nim/provider-model",
+ "display_name": "NIM",
+ },
+ ]
+ }
+ )
+ )
+
+ assert _slugs(catalog) == ["nvidia_nim/provider-model"]
+
+
+def test_codex_catalog_deduplicates_direct_wire_ids() -> None:
+ catalog = build_codex_model_catalog(
+ client_models_from_response(
+ _models_payload(
+ "nvidia_nim/provider-model",
+ "nvidia_nim/provider-model",
+ )
+ )
+ )
+
+ assert _slugs(catalog) == ["nvidia_nim/provider-model"]
+
+
+def test_codex_catalog_preserves_no_thinking_only_entries_for_routing() -> None:
+ catalog = build_codex_model_catalog(
+ client_models_from_response(
+ _models_payload("claude-3-freecc-no-thinking/open_router/plain-model")
+ )
+ )
+
+ assert _slugs(catalog) == ["claude-3-freecc-no-thinking/open_router/plain-model"]
+
+
+def test_codex_catalog_ordering_and_priorities_are_deterministic() -> None:
+ catalog = build_codex_model_catalog(
+ client_models_from_response(
+ _models_payload(
+ "anthropic/gemini/models/gemini-test",
+ "nvidia_nim/nvidia/test",
+ "anthropic/gemini/models/gemini-test",
+ "open_router/provider/test",
+ )
+ )
+ )
+
+ models = _catalog_models(catalog)
+ assert _slugs(catalog) == [
+ "anthropic/gemini/models/gemini-test",
+ "nvidia_nim/nvidia/test",
+ "open_router/provider/test",
+ ]
+ assert [model["priority"] for model in models] == [0, 1, 2]
+
+
+def test_codex_catalog_accepts_direct_provider_slugs_without_a_provider_registry() -> (
+ None
+):
+ catalog = build_codex_model_catalog(
+ client_models_from_response(
+ _models_payload(
+ "nvidia_nim/provider-model",
+ "future_provider/provider-model",
+ )
+ )
+ )
+
+ assert _slugs(catalog) == [
+ "nvidia_nim/provider-model",
+ "future_provider/provider-model",
+ ]
+
+
+def test_codex_catalog_projects_known_capabilities_and_preserves_unknown_defaults() -> (
+ None
+):
+ catalog = build_codex_model_catalog(
+ client_models_from_response(
+ {
+ "data": [
+ {
+ "id": "provider/vision-reasoning",
+ "provider_model_ref": "provider/vision-reasoning",
+ "supportsReasoning": True,
+ "inputModalities": ["text", "image"],
+ "contextWindow": 131072,
+ "maxCompletionTokens": 8192,
+ },
+ {
+ "id": "claude-3-freecc-no-thinking/provider/text-only",
+ "provider_model_ref": "provider/text-only",
+ "supportsReasoning": False,
+ "inputModalities": ["text"],
+ "maxCompletionTokens": 4096,
+ },
+ {
+ "id": "provider/unknown",
+ "provider_model_ref": "provider/unknown",
+ },
+ ]
+ }
+ )
+ )
+
+ vision, text_only, unknown = _catalog_models(catalog)
+ assert vision["input_modalities"] == ["text", "image"]
+ assert vision["default_reasoning_level"] == "medium"
+ assert vision["supported_reasoning_levels"]
+ assert vision["supports_reasoning_summaries"] is True
+ assert vision["default_reasoning_summary"] == "none"
+ assert vision["context_window"] == 131072
+ assert vision["max_context_window"] == 131072
+
+ assert text_only["input_modalities"] == ["text"]
+ assert "default_reasoning_level" not in text_only
+ assert text_only["supported_reasoning_levels"] == []
+ assert text_only["supports_reasoning_summaries"] is False
+ assert "default_reasoning_summary" not in text_only
+ assert text_only["context_window"] == 200000
+ assert text_only["max_context_window"] == 200000
+
+ assert unknown["input_modalities"] == ["text"]
+ assert unknown["default_reasoning_level"] == "medium"
+ assert unknown["supported_reasoning_levels"]
+ assert unknown["supports_reasoning_summaries"] is True
+ assert unknown["default_reasoning_summary"] == "none"
+ assert unknown["context_window"] == 200000
+ assert unknown["max_context_window"] == 200000
diff --git a/tests/harnesses/test_environment.py b/tests/harnesses/test_environment.py
new file mode 100644
index 00000000..fe7dc5ac
--- /dev/null
+++ b/tests/harnesses/test_environment.py
@@ -0,0 +1,34 @@
+from free_claude_code.harnesses.environment import with_local_proxy_bypass
+
+
+def test_child_proxy_bypass_preserves_existing_proxy_policy() -> None:
+ base_env = {
+ "HTTP_PROXY": "http://proxy.example:3128",
+ "NO_PROXY": "example.com, localhost",
+ "no_proxy": "10.0.0.0/8,EXAMPLE.COM",
+ "KEEP_ME": "yes",
+ }
+
+ env = with_local_proxy_bypass(
+ base_env,
+ proxy_root_url="http://fcc.internal:8082",
+ )
+
+ assert env["HTTP_PROXY"] == "http://proxy.example:3128"
+ assert env["KEEP_ME"] == "yes"
+ assert env["NO_PROXY"] == (
+ "example.com,localhost,10.0.0.0/8,127.0.0.1,::1,fcc.internal"
+ )
+ assert env["no_proxy"] == env["NO_PROXY"]
+ assert base_env["NO_PROXY"] == "example.com, localhost"
+ assert base_env["no_proxy"] == "10.0.0.0/8,EXAMPLE.COM"
+
+
+def test_child_proxy_bypass_uses_all_loopback_spellings_without_duplicates() -> None:
+ env = with_local_proxy_bypass(
+ {"NO_PROXY": "127.0.0.1"},
+ proxy_root_url="http://127.0.0.1:8082",
+ )
+
+ assert env["NO_PROXY"] == "127.0.0.1,localhost,::1"
+ assert env["no_proxy"] == env["NO_PROXY"]
diff --git a/tests/cli/test_model_catalog.py b/tests/harnesses/test_model_catalog.py
similarity index 78%
rename from tests/cli/test_model_catalog.py
rename to tests/harnesses/test_model_catalog.py
index 2bf23e58..c9d34f6a 100644
--- a/tests/cli/test_model_catalog.py
+++ b/tests/harnesses/test_model_catalog.py
@@ -1,15 +1,10 @@
-from unittest.mock import patch
-
-import pytest
-
-from free_claude_code.cli.launchers.model_catalog import (
+from free_claude_code.core.json_types import JsonObject
+from free_claude_code.core.model_capabilities import ModelInputModality
+from free_claude_code.harnesses.model_catalog import (
ClientModel,
catalog_wire_slug_for_ref,
client_models_from_response,
- fetch_proxy_models_response,
)
-from free_claude_code.core.json_types import JsonObject
-from free_claude_code.core.model_capabilities import ModelInputModality
def test_client_models_project_nested_direct_refs_in_source_order() -> None:
@@ -188,63 +183,6 @@ def test_client_models_deduplicate_wire_slugs_deterministically() -> None:
assert models[0].display_name == "Display 0"
-class _ModelsResponse:
- def __init__(self, body: bytes) -> None:
- self._body = body
-
- def __enter__(self) -> _ModelsResponse:
- return self
-
- def __exit__(self, *exc_info: object) -> None:
- del exc_info
-
- def read(self) -> bytes:
- return self._body
-
-
-def test_fetch_proxy_models_uses_canonical_bearer_request() -> None:
- with patch(
- "free_claude_code.cli.launchers.model_catalog.open_local_request",
- return_value=_ModelsResponse(b'{"data": []}'),
- ) as open_local_request:
- response = fetch_proxy_models_response("http://127.0.0.1:9191/", "proxy-token")
-
- assert response == {"data": []}
- request = open_local_request.call_args.args[0]
- assert request.full_url == "http://127.0.0.1:9191/v1/models?view=responses"
- assert request.get_method() == "GET"
- assert request.get_header("Authorization") == "Bearer proxy-token"
-
-
-def test_fetch_proxy_models_can_request_messages_view() -> None:
- with patch(
- "free_claude_code.cli.launchers.model_catalog.open_local_request",
- return_value=_ModelsResponse(b'{"data": []}'),
- ) as open_local_request:
- response = fetch_proxy_models_response(
- "http://127.0.0.1:9191/",
- "proxy-token",
- view="messages",
- )
-
- assert response == {"data": []}
- request = open_local_request.call_args.args[0]
- assert request.full_url == "http://127.0.0.1:9191/v1/models?view=messages"
- assert request.get_method() == "GET"
- assert request.get_header("Authorization") == "Bearer proxy-token"
-
-
-def test_fetch_proxy_models_rejects_non_object_json() -> None:
- with (
- patch(
- "free_claude_code.cli.launchers.model_catalog.open_local_request",
- return_value=_ModelsResponse(b"[]"),
- ),
- pytest.raises(ValueError, match="JSON object"),
- ):
- fetch_proxy_models_response("http://127.0.0.1:9191", "proxy-token")
-
-
def _client_model(wire_slug: str, provider_model_ref: str) -> ClientModel:
return ClientModel(
wire_slug=wire_slug,
diff --git a/tests/runtime/codex_fake_process.py b/tests/runtime/codex_fake_process.py
index 524becbe..67f6bad9 100644
--- a/tests/runtime/codex_fake_process.py
+++ b/tests/runtime/codex_fake_process.py
@@ -28,7 +28,12 @@ for line in sys.stdin.buffer:
method = request.get("method")
request_id = request.get("id")
if method == "initialize":
- emit({"id": request_id, "result": {"userAgent": "codex/0.153.0"}})
+ if mode == "factory-wait":
+ continue
+ if mode == "factory-fail":
+ emit({"id": request_id, "error": {"message": "Initialization rejected"}})
+ else:
+ emit({"id": request_id, "result": {"userAgent": "codex/0.153.0"}})
elif method == "initialized":
pass
elif method in {"thread/start", "thread/resume"}:
@@ -195,6 +200,11 @@ for line in sys.stdin.buffer:
else:
emit({"id": request_id, "result": {}})
+if mode.startswith("factory-"):
+ # The catalog must still be readable when the native process exits.
+ catalog = json.loads(Path(sys.argv[2]).read_text()) if sys.argv[2] else None
+ Path(sys.argv[3]).write_text(json.dumps(catalog))
+
if mode == "child-warning-on-close":
emit(
{
diff --git a/tests/runtime/test_codex_app_server.py b/tests/runtime/test_codex_app_server.py
index 3ad5275a..5dc3d065 100644
--- a/tests/runtime/test_codex_app_server.py
+++ b/tests/runtime/test_codex_app_server.py
@@ -1,19 +1,200 @@
import asyncio
+import json
import os
import sys
+import tomllib
import uuid
+from dataclasses import dataclass, field
from pathlib import Path
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
from free_claude_code.application.code_sessions import CodeService
-from free_claude_code.application.code_sessions.models import CodeUnavailableError
+from free_claude_code.application.code_sessions.models import (
+ CodeConflictError,
+ CodeUnavailableError,
+)
+from free_claude_code.application.model_metadata import ProviderModelInfo
+from free_claude_code.application.ports import RequestRuntimePort
+from free_claude_code.config.paths import launcher_temp_dir_path
+from free_claude_code.config.settings import Settings
+from free_claude_code.core.gateway_model_ids import no_thinking_gateway_model_id
from free_claude_code.runtime.code_sessions_sqlite import SQLiteCodeStore
-from free_claude_code.runtime.codex_app_server import CodexAppServer
+from free_claude_code.runtime.codex_app_server import (
+ CodexAppServer,
+ CodexHarnessFactory,
+)
from tests.code_sessions_support import FakeHarness
+@dataclass
+class FactoryPeer:
+ mode: str = "factory-ready"
+ command: tuple[str, ...] = ()
+ env: dict[str, str] = field(default_factory=dict, repr=False)
+ catalog: Path | None = None
+ process: asyncio.subprocess.Process | None = None
+
+
+def factory_peer(tmp_path, monkeypatch):
+ peer = FactoryPeer()
+ spawn = asyncio.create_subprocess_exec
+
+ async def start(*command, **kwargs):
+ if command[0] != "test-codex":
+ return await spawn(*command, **kwargs)
+ peer.command, peer.env = command, dict(kwargs["env"])
+ config = tomllib.loads(
+ "\n".join(command[i + 1] for i, arg in enumerate(command) if arg == "-c")
+ )
+ path = config.get("model_catalog_json")
+ peer.catalog = Path(path) if path else None
+ peer.process = await spawn(
+ sys.executable,
+ str(Path(__file__).with_name("codex_fake_process.py")),
+ peer.mode,
+ path or "",
+ str(tmp_path / "catalog-at-exit.json"),
+ **kwargs,
+ )
+ return peer.process
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", start)
+ return peer
+
+
+def factory_runtime():
+ runtime = MagicMock(spec=RequestRuntimePort)
+ runtime.current_settings.return_value = Settings(
+ model="nvidia_nim/default", port=8182, proxy_auth_token="factory-token"
+ )
+ runtime.cached_model_info.return_value = None
+ runtime.cached_prefixed_model_infos.return_value = (
+ ProviderModelInfo(
+ "open_router/selected", supports_thinking=False, context_window_tokens=32000
+ ),
+ )
+ runtime.acquire.side_effect = AssertionError("Setup must not acquire a provider")
+ return runtime
+
+
+async def test_factory_open_preserves_setup_and_catalog_until_process_exit(
+ tmp_path, factory_peer, factory_runtime
+):
+ env = dict(os.environ) | {
+ "CODEX_HOME": str(tmp_path / "codex-home"),
+ "CODEX_THREAD_ID": "parent-thread",
+ "OPENAI_API_KEY": "parent-token",
+ "OPENAI_CUSTOM": "parent-route",
+ "KEEP_ME": "yes",
+ }
+ before = dict(env)
+ factory = CodexHarnessFactory(factory_runtime, binary="test-codex", env=env)
+ selection = factory.prepare("open_router/selected", None, "config")
+ native = await selection.open(str(tmp_path), AsyncMock())
+ try:
+ config = tomllib.loads(
+ "\n".join(
+ factory_peer.command[i + 1]
+ for i, arg in enumerate(factory_peer.command)
+ if arg == "-c"
+ )
+ )
+ assert config["model"] == no_thinking_gateway_model_id(selection.model)
+ assert config["model_providers"]["fcc"] == {
+ "name": "Free Claude Code",
+ "base_url": "http://127.0.0.1:8182/v1",
+ "auth": {"command": "fcc-codex", "args": ["--print-proxy-auth-token"]},
+ "wire_api": "responses",
+ }
+ assert factory_peer.command[-5:] == (
+ "-c",
+ "features.default_mode_request_user_input=true",
+ "-c",
+ "tools.experimental_request_user_input.enabled=true",
+ "app-server",
+ )
+ assert factory_peer.env["CODEX_HOME"] == env["CODEX_HOME"]
+ assert factory_peer.env["KEEP_ME"] == "yes"
+ assert "CODEX_THREAD_ID" not in factory_peer.env
+ assert not any(key.startswith("OPENAI_") for key in factory_peer.env)
+ assert "127.0.0.1" in factory_peer.env["NO_PROXY"].split(",")
+ assert env == before
+ assert factory_peer.catalog is not None
+ catalog = json.loads(factory_peer.catalog.read_text())
+ assert any(model["slug"] == config["model"] for model in catalog["models"])
+ assert "factory-token" not in factory_peer.catalog.read_text()
+ assert native.process.returncode is None
+ finally:
+ await native.close()
+ assert native.process.returncode == 0
+ assert json.loads((tmp_path / "catalog-at-exit.json").read_text()) == catalog
+ assert not factory_peer.catalog.parent.exists()
+
+
[email protected]("failure", ["reject", "cancel"])
+async def test_factory_initialization_failure_reaps_before_catalog_cleanup(
+ tmp_path, monkeypatch, factory_peer, factory_runtime, failure
+):
+ factory_peer.mode = "factory-fail" if failure == "reject" else "factory-wait"
+ initialized = asyncio.Event()
+ write = CodexAppServer._write
+
+ async def observe_write(native, message):
+ await write(native, message)
+ if message.get("method") == "initialize":
+ initialized.set()
+
+ monkeypatch.setattr(CodexAppServer, "_write", observe_write)
+ factory = CodexHarnessFactory(factory_runtime, binary="test-codex")
+ selection = factory.prepare("open_router/selected", None, "config")
+ opening = asyncio.create_task(selection.open(str(tmp_path), AsyncMock()))
+ try:
+ await asyncio.wait_for(initialized.wait(), 3)
+ if failure == "cancel":
+ opening.cancel()
+ error = asyncio.CancelledError if failure == "cancel" else CodeConflictError
+ with pytest.raises(error):
+ await asyncio.wait_for(opening, 8)
+ finally:
+ if not opening.done():
+ opening.cancel()
+ await asyncio.gather(opening, return_exceptions=True)
+ assert factory_peer.process.returncode == 0
+ assert json.loads((tmp_path / "catalog-at-exit.json").read_text())["models"]
+ assert not factory_peer.catalog.parent.exists()
+
+
+async def test_history_open_needs_no_fcc_setup_or_inventory(tmp_path, factory_peer):
+ runtime = MagicMock(spec=RequestRuntimePort)
+ for name in (
+ "current_settings",
+ "cached_model_info",
+ "cached_prefixed_model_infos",
+ ):
+ getattr(runtime, name).side_effect = AssertionError(
+ "History needs no inventory"
+ )
+ env = dict(os.environ) | {"CODEX_THREAD_ID": "parent", "OPENAI_API_KEY": "keep"}
+ factory = CodexHarnessFactory(runtime, binary="test-codex", env=env)
+ native = await factory.open_history(str(tmp_path), AsyncMock())
+ try:
+ assert factory_peer.command == ("test-codex", "app-server")
+ assert factory_peer.env == env
+ assert factory_peer.catalog is None
+ assert not launcher_temp_dir_path().exists()
+ finally:
+ await native.close()
+ assert native.process.returncode == 0
+ assert json.loads((tmp_path / "catalog-at-exit.json").read_text()) is None
+
+
@pytest.mark.asyncio
async def test_child_warning_during_shutdown_allows_connection_replacement(
tmp_path, monkeypatch
diff --git a/tests/runtime/test_codex_catalog.py b/tests/runtime/test_codex_catalog.py
index 1c522506..da31d777 100644
--- a/tests/runtime/test_codex_catalog.py
+++ b/tests/runtime/test_codex_catalog.py
@@ -11,8 +11,14 @@ from free_claude_code.application.ports import (
RequestRuntimePort,
)
from free_claude_code.config.settings import Settings
+from free_claude_code.harnesses.codex_model_catalog import build_codex_model_catalog
+from free_claude_code.harnesses.model_catalog import client_models_from_response
from free_claude_code.runtime.codex_app_server import CodexHarnessFactory
-from free_claude_code.runtime.codex_catalog import CodexModelCatalogPublisher
+from free_claude_code.runtime.codex_catalog import (
+ CodexModelCatalogPublisher,
+ write_codex_model_catalog,
+)
+from tests.harnesses.test_codex_model_catalog import _models_payload
class FakeRequestRuntime(RequestRuntimePort):
@@ -118,7 +124,6 @@ def test_code_picker_and_native_selection_use_the_same_advertised_efforts():
assert model.reasoning_efforts == ("off", "low", "medium", "high", "xhigh", "max")
selected = factory.prepare(model.id, None, "config")
assert selected.model == model.id
- assert selected.context.settings.model == model.id
assert selected.reasoning_effort == model.default_reasoning_effort == "medium"
for effort in model.reasoning_efforts:
assert factory.prepare(model.id, effort, "config").reasoning_effort == effort
@@ -144,3 +149,47 @@ def test_non_reasoning_model_off_selection_is_available():
assert model.reasoning_efforts == ("off",)
assert model.default_reasoning_effort == "off"
assert factory.prepare(model.id, "off", "config").reasoning_effort == "off"
+
+
+def test_catalog_writer_skips_identical_content_and_replaces_changes(
+ tmp_path: Path,
+) -> None:
+ catalog_path = tmp_path / "codex-model-catalog.json"
+ first = build_codex_model_catalog(
+ client_models_from_response(_models_payload("nvidia_nim/first"))
+ )
+ second = build_codex_model_catalog(
+ client_models_from_response(_models_payload("nvidia_nim/second"))
+ )
+
+ assert write_codex_model_catalog(catalog_path, first) is True
+ assert write_codex_model_catalog(catalog_path, first) is False
+ assert list(tmp_path.glob(".codex-model-catalog.json.*.tmp")) == []
+
+ assert write_codex_model_catalog(catalog_path, second) is True
+ assert json.loads(catalog_path.read_text(encoding="utf-8")) == second
+ assert list(tmp_path.glob(".codex-model-catalog.json.*.tmp")) == []
+
+
+def test_catalog_writer_cleans_temporary_file_after_replace_failure(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ catalog_path = tmp_path / "codex-model-catalog.json"
+ catalog_path.write_text("previous\n", encoding="utf-8")
+
+ def fail_replace(_source: Path, _destination: Path) -> Path:
+ raise PermissionError("destination is locked")
+
+ monkeypatch.setattr(Path, "replace", fail_replace)
+
+ with pytest.raises(PermissionError, match="locked"):
+ write_codex_model_catalog(
+ catalog_path,
+ build_codex_model_catalog(
+ client_models_from_response(_models_payload("nvidia_nim/replacement"))
+ ),
+ )
+
+ assert catalog_path.read_text(encoding="utf-8") == "previous\n"
+ assert list(tmp_path.glob(".codex-model-catalog.json.*.tmp")) == []
diff --git a/uv.lock b/uv.lock
index ce14aca9..e5696ada 100644
--- a/uv.lock
+++ b/uv.lock
@@ -598,7 +598,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "6.2.23"
+version = "6.2.24"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },