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
Consolidate harness launcher setup and remove command parsing (#1684)
Ali Khokhar7d812e53a631
diff --git a/README.md b/README.mdindex 8185e785..bcf3f193 100644--- a/README.md+++ b/README.md@@ -342,6 +342,14 @@ Providers that do not support a selected control retain their own behavior.For terminal use, start `fcc-server`, then run `fcc-claude`, `fcc-codex`,`fcc-pi`, `fcc-opencode`, `fcc-cline`, `fcc-hermes`, `fcc-dsh`, `fcc-grok`,`fcc-muse`, or `fcc-aider`.+These wrappers configure the FCC connection and pass your commands and options+to the native harness. Interactive and headless use share the same setup.+Every wrapper launch requires FCC to be available, including help and version+requests. Launches that need a model catalog stop if it cannot be loaded.++Each Codex CLI launch uses its own temporary catalog. FCC also publishes the+stable catalog used by the Codex App and editor configurations below.+Use the guides below for editor integrations.<details>diff --git a/pyproject.toml b/pyproject.tomlindex d4557258..04f7894a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "5.22.6"+version = "5.22.7"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.pyindex 93c712d2..05c21caa 100644--- a/smoke/capabilities.py+++ b/smoke/capabilities.py@@ -540,10 +540,12 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("free_claude_code.cli.launchers.codex","Codex CLI binary and fcc provider env","Responses config, auth env, and native /model catalog injection",- "proxy preflight and catalog fail-open warning",+ "shared startup; required catalog failure stops launch; private catalog cleanup",("tests/cli/test_codex_model_catalog.py",- "tests/cli/test_entrypoints.py",+ "tests/cli/test_codex_launcher.py",+ "tests/cli/test_launcher_workflow.py",+ "tests/cli/test_launcher_resources.py",),(),),@@ -555,7 +557,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("Pi CLI binary, bundled extension, and FCC child-process environment","Anthropic Messages provider with an FCC-scoped live model catalog","proxy preflight, missing extension, or catalog failure exits without fallback",- ("tests/cli/test_entrypoints.py",),+ ("tests/cli/test_pi_launcher.py", "tests/cli/test_pi_extension.py"),("test_pi_cli_prompt_e2e",),),CapabilityContract(@@ -579,7 +581,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("free_claude_code.cli.launchers.aider","Aider 0.86.2+, live FCC Messages catalog, and private process files","Anthropic Messages route scoped to FCC for native Aider sessions",- "binary, proxy, route conflict, catalog, or private-file failure exits before inference",+ "binary, proxy, catalog, or private-file failure exits before inference",("tests/cli/test_aider_config.py","tests/cli/test_aider_launcher.py",@@ -594,7 +596,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("free_claude_code.cli.launchers.cline","Cline binary, live FCC model catalog, and protected child-process files","Responses provider scoped to FCC for attached local sessions",- "version, detached mode, proxy, or catalog failure exits without fallback",+ "version, proxy, catalog, or private-file failure exits before inference",("tests/cli/test_cline_launcher.py","tests/cli/test_model_catalog.py",@@ -639,8 +641,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("grok_cli_integration","free_claude_code.cli.launchers.grok","Grok Build 1.0.5+, live FCC Responses catalog, and child-only config",- "Responses route scoped to FCC for attached TUI, headless, and ACP sessions",- "version, route conflict, proxy, or catalog failure exits before inference",+ "Responses route scoped to FCC for native Grok sessions",+ "version, process config conflict, proxy, or catalog failure exits before inference",("tests/cli/test_grok_launcher.py","tests/cli/test_model_catalog.py",@@ -653,8 +655,8 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("muse_cli_integration","free_claude_code.cli.launchers.muse","Muse Code 0.2.1+, live FCC Responses catalog, and child-only route",- "Responses route scoped to FCC for attached TUI, exec, and resume sessions",- "version, route conflict, proxy, or catalog failure exits before inference",+ "Responses route scoped to FCC for native Muse sessions",+ "version, proxy, or catalog failure exits before inference",("tests/cli/test_muse_launcher.py","tests/api/test_model_listing.py",diff --git a/src/free_claude_code/cli/claude_env.py b/src/free_claude_code/cli/claude_env.pyindex 83b3a273..3c9e239f 100644--- a/src/free_claude_code/cli/claude_env.py+++ b/src/free_claude_code/cli/claude_env.py@@ -2,7 +2,7 @@from collections.abc import Mapping-from free_claude_code.cli.local_http import with_local_proxy_bypass+from free_claude_code.cli.environment import client_environmentCLAUDE_CODE_AUTO_COMPACT_WINDOW = "190000"CLAUDE_BINARY_NAME = "claude"@@ -17,20 +17,18 @@ def build_claude_proxy_env("""Return the canonical environment for Claude Code proxy sessions."""# Claude's aggregate traffic flag also suppresses gateway model discovery.- env = with_local_proxy_bypass(- {- key: value- for key, value in base_env.items()- if not key.startswith("ANTHROPIC_")- and key != "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"- },+ return client_environment(+ base_env,proxy_root_url=proxy_root_url,+ remove_prefixes=("ANTHROPIC_",),+ remove_keys=("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",),+ updates={+ "ANTHROPIC_BASE_URL": proxy_root_url,+ "ANTHROPIC_AUTH_TOKEN": auth_token,+ "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1",+ "CLAUDE_CODE_AUTO_COMPACT_WINDOW": CLAUDE_CODE_AUTO_COMPACT_WINDOW,+ "DISABLE_AUTOUPDATER": "1",+ "DISABLE_FEEDBACK_COMMAND": "1",+ "DISABLE_ERROR_REPORTING": "1",+ },)- env["ANTHROPIC_BASE_URL"] = proxy_root_url- env["ANTHROPIC_AUTH_TOKEN"] = auth_token- env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"- env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = CLAUDE_CODE_AUTO_COMPACT_WINDOW- env["DISABLE_AUTOUPDATER"] = "1"- env["DISABLE_FEEDBACK_COMMAND"] = "1"- env["DISABLE_ERROR_REPORTING"] = "1"- return envdiff --git a/src/free_claude_code/cli/environment.py b/src/free_claude_code/cli/environment.pynew file mode 100644index 00000000..31cc62e3--- /dev/null+++ b/src/free_claude_code/cli/environment.py@@ -0,0 +1,41 @@+"""Shared child-only environment setup for native clients."""++from collections.abc import Mapping, Sequence++from .local_http import with_local_proxy_bypass+++def client_environment(+ base_env: Mapping[str, str],+ *,+ proxy_root_url: str,+ remove_keys: Sequence[str] = (),+ remove_prefixes: tuple[str, ...] = (),+ updates: Mapping[str, str] | None = None,+ case_sensitive: bool = True,+) -> dict[str, str]:+ """Replace owned connection settings while preserving native user state."""++ keys = set(remove_keys if case_sensitive else map(str.casefold, remove_keys))+ prefixes = (+ remove_prefixes+ if case_sensitive+ else tuple(prefix.casefold() for prefix in remove_prefixes)+ )+ env = {+ key: value+ for key, value in base_env.items()+ if (name := key if case_sensitive else key.casefold()) not in keys+ and not name.startswith(prefixes)+ }+ if updates:+ env.update(updates)+ return with_local_proxy_bypass(env, proxy_root_url=proxy_root_url)+++def require_unset_environment(base_env: Mapping[str, str], keys: Sequence[str]) -> None:+ """Avoid replacing another owner's explicit process configuration."""++ for key in keys:+ if base_env.get(key, "").strip():+ raise ValueError(f"{key} is already set. Unset it before using FCC.")diff --git a/src/free_claude_code/cli/launchers/aider.py b/src/free_claude_code/cli/launchers/aider.pyindex 6b575b95..5ea15201 100644--- a/src/free_claude_code/cli/launchers/aider.py+++ b/src/free_claude_code/cli/launchers/aider.py@@ -1,328 +1,51 @@-"""Installed `fcc-aider` launcher for the official Aider CLI."""+"""Installed Aider launcher using native model settings for FCC routing."""-import json-import osimport secrets-import sys-import tempfile-from collections.abc import Iterator, Mapping, Sequence-from contextlib import ExitStack, contextmanager-from dataclasses import dataclass-from pathlib import Path-from typing import Never+from collections.abc import Sequence-from free_claude_code.cli.local_http import with_local_proxy_bypass-from free_claude_code.config.loader import get_settings-from free_claude_code.config.paths import aider_temp_dir_path-from free_claude_code.config.server_urls import local_proxy_root_url-from free_claude_code.core.json_types import JsonValue+from free_claude_code.cli.environment import client_environment-from .aider_config import (- AIDER_API_KEY_ENV_PREFIX,- AiderConfig,- build_aider_config,-)-from .common import preflight_proxy, resolve_client_binary, run_client_process-from .model_catalog import (- ClientModel,- client_models_from_response,- fetch_proxy_models_response,-)--_BINARY_NAME = "aider"-_DISPLAY_NAME = "Aider"-_INSTALL_HINT = "Install Aider from: https://aider.chat/docs/install.html"-_PASSTHROUGH_FLAGS = frozenset(- {- "-h",- "--help",- "--version",- "--just-check-update",- "--upgrade",- "--update",- "--install-main-branch",- "--shell-completions",- }-)-_ROUTE_FILE_OPTIONS = ("--model-settings-file", "--model-metadata-file")-_MODEL_OPTIONS = ("--model", "--weak-model", "--editor-model")-_SETTINGS_FILENAME = "model-settings.yml"-_METADATA_FILENAME = "model-metadata.json"-_AIDER_VALIDATION_KEY = "ANTHROPIC_API_KEY=fcc-local"---@dataclass(frozen=True, slots=True)-class AiderConfigFiles:- """Private file paths owned for the lifetime of one Aider launch."""-- directory: Path- settings_path: Path- metadata_path: Path+from .aider_config import AIDER_API_KEY_ENV_PREFIX, build_aider_config+from .resources import LaunchResources+from .runner import HarnessSpec, LaunchContext, PreparedLaunch, launch_harness-class _AiderConfigFilesError(RuntimeError):- """Failure while preparing launcher-owned Aider files."""---def launch(argv: Sequence[str] | None = None) -> None:- """Launch Aider with a process-local FCC Messages model catalog."""-- args = list(sys.argv[1:] if argv is None else argv)- binary_path = resolve_client_binary(- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,+def _configure(+ ctx: LaunchContext, args: list[str], files: LaunchResources+) -> PreparedLaunch:+ key_env = f"{AIDER_API_KEY_ENV_PREFIX}{secrets.token_hex(16).upper()}"+ config = build_aider_config(+ ctx.models,+ messages_url=f"{ctx.proxy_root_url.rstrip('/')}/v1/messages",+ api_key_env=key_env,+ )+ settings_path = files.write_json("model-settings.yml", config.settings)+ metadata_path = files.write_json("model-metadata.json", config.metadata)+ return PreparedLaunch(+ [ctx.binary_path, "--set-env", "ANTHROPIC_API_KEY=fcc-local", *args],+ client_environment(+ ctx.base_env,+ proxy_root_url=ctx.proxy_root_url,+ remove_prefixes=(AIDER_API_KEY_ENV_PREFIX,),+ case_sensitive=False,+ updates={+ key_env: ctx.auth_token,+ "AIDER_MODEL": ctx.models[0].wire_slug,+ "AIDER_MODEL_SETTINGS_FILE": str(settings_path),+ "AIDER_MODEL_METADATA_FILE": str(metadata_path),+ },+ ),)-- if is_aider_passthrough(args):- _run(binary_path, args, os.environ)- return-- reject_aider_route_file_overrides(args)- settings = get_settings()- auth_token = settings.proxy_auth_token.strip()- if not auth_token:- print("Free Claude Code proxy authentication token is empty.", file=sys.stderr)- raise SystemExit(1)-- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)-- try:- models = client_models_from_response(- fetch_proxy_models_response(- proxy_root_url,- auth_token,- view="messages",- )- )- api_key_env = new_aider_api_key_env_name()- config = build_aider_config(- models,- messages_url=f"{proxy_root_url.rstrip('/')}/v1/messages",- api_key_env=api_key_env,- )- except Exception as exc:- print(f"Could not prepare the Aider FCC model catalog: {exc}", file=sys.stderr)- raise SystemExit(1) from None-- try:- with temporary_aider_config_files(config) as files:- child_args = normalized_aider_arguments(- args,- models=models,- settings_path=files.settings_path,- metadata_path=files.metadata_path,- )- child_env = build_aider_launcher_env(- proxy_root_url=proxy_root_url,- api_key_env=api_key_env,- auth_token=auth_token,- base_env=os.environ,- )- _run(binary_path, child_args, child_env)- except _AiderConfigFilesError as exc:- print(f"Could not create temporary Aider configuration: {exc}", file=sys.stderr)- raise SystemExit(1) from None---def is_aider_passthrough(argv: Sequence[str]) -> bool:- """Return whether Aider can run without FCC-owned process configuration."""-- return any(argument in _PASSTHROUGH_FLAGS for argument in _before_separator(argv))---def reject_aider_route_file_overrides(argv: Sequence[str]) -> None:- """Reject command-line paths that would replace FCC's process overlay."""-- for argument in _before_separator(argv):- if argument in _ROUTE_FILE_OPTIONS or any(- argument.startswith(f"{option}=") for option in _ROUTE_FILE_OPTIONS- ):- print(- "fcc-aider owns the model settings and metadata files for its FCC "- "route. Use ordinary aider or Aider's normal home/project model "- "files for other route/catalog customization.",- file=sys.stderr,- )- raise SystemExit(2)---def normalized_aider_arguments(- argv: Sequence[str],- *,- models: tuple[ClientModel, ...],- settings_path: Path,- metadata_path: Path,-) -> list[str]:- """Replace Aider's three model roles with canonical FCC model names."""-- if not models:- raise ValueError("Aider requires at least one routable FCC model")-- before, separator_and_after = _split_separator(argv)- selected: dict[str, str] = {}- remaining: list[str] = []- index = 0- while index < len(before):- argument = before[index]- option = next(- (- candidate- for candidate in _MODEL_OPTIONS- if argument == candidate or argument.startswith(f"{candidate}=")- ),- None,- )- if option is None:- remaining.append(argument)- index += 1- continue- if option in selected:- _model_argument_error(f"{option} may be provided only once")-- if argument == option:- value_index = index + 1- if value_index >= len(before) or before[value_index].startswith("-"):- _model_argument_error(f"{option} requires one model value")- value = before[value_index]- index += 2- else:- value = argument.removeprefix(f"{option}=")- index += 1- if not value.strip():- _model_argument_error(f"{option} requires one model value")- selected[option] = value-- canonical_by_input: dict[str, str] = {}- for model in models:- canonical = f"anthropic/{model.wire_slug}"- canonical_by_input[model.wire_slug] = canonical- canonical_by_input[canonical] = canonical-- resolved: dict[str, str] = {}- for option, value in selected.items():- canonical = canonical_by_input.get(value)- if canonical is None:- _model_argument_error(- f"{option} model {value!r} is not in the current FCC model catalog"- )- resolved[option] = canonical-- main_model = resolved.get("--model", f"anthropic/{models[0].wire_slug}")- weak_model = resolved.get("--weak-model", main_model)- editor_model = resolved.get("--editor-model", main_model)- owned = [- "--model",- main_model,- "--weak-model",- weak_model,- "--editor-model",- editor_model,- "--model-settings-file",- str(settings_path),- "--model-metadata-file",- str(metadata_path),- "--set-env",- _AIDER_VALIDATION_KEY,- ]- return [*remaining, *owned, *separator_and_after]---def new_aider_api_key_env_name() -> str:- """Return one unguessable process-local environment variable name."""-- return f"{AIDER_API_KEY_ENV_PREFIX}{secrets.token_hex(16).upper()}"---def build_aider_launcher_env(- *,- proxy_root_url: str,- api_key_env: str,- auth_token: str,- base_env: Mapping[str, str],-) -> dict[str, str]:- """Build Aider's child-only environment while preserving native state."""-- prefix = AIDER_API_KEY_ENV_PREFIX.casefold()- clean_env = {- key: value- for key, value in base_env.items()- if not key.casefold().startswith(prefix)- }- env = with_local_proxy_bypass(clean_env, proxy_root_url=proxy_root_url)- env[api_key_env] = auth_token- return env---@contextmanager-def temporary_aider_config_files(- config: AiderConfig,-) -> Iterator[AiderConfigFiles]:- """Write one private Aider config pair and remove its launch directory."""-- with ExitStack() as stack:- try:- base_directory = aider_temp_dir_path()- base_directory.mkdir(parents=True, mode=0o700, exist_ok=True)- if os.name != "nt":- base_directory.chmod(0o700)- temp_directory = stack.enter_context(- tempfile.TemporaryDirectory(prefix="fcc-aider-", dir=base_directory)- )- directory = Path(temp_directory)- if os.name != "nt":- directory.chmod(0o700)- files = AiderConfigFiles(- directory=directory,- settings_path=directory / _SETTINGS_FILENAME,- metadata_path=directory / _METADATA_FILENAME,- )- _write_private_json(files.settings_path, config.settings)- _write_private_json(files.metadata_path, config.metadata)- except OSError as exc:- raise _AiderConfigFilesError(str(exc)) from exc- yield files---def _write_private_json(path: Path, payload: JsonValue) -> None:- descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)- with os.fdopen(descriptor, "w", encoding="utf-8") as output:- json.dump(payload, output, ensure_ascii=True, indent=2)- output.write("\n")---def _before_separator(argv: Sequence[str]) -> Sequence[str]:- try:- return argv[: argv.index("--")]- except ValueError:- return argv---def _split_separator(argv: Sequence[str]) -> tuple[list[str], list[str]]:- try:- index = argv.index("--")- except ValueError:- return list(argv), []- return list(argv[:index]), list(argv[index:])-def _model_argument_error(message: str) -> Never:- print(f"Invalid fcc-aider model option: {message}.", file=sys.stderr)- raise SystemExit(2)+SPEC = HarnessSpec(+ binary_name="aider",+ display_name="Aider",+ install_hint="Install Aider from: https://aider.chat/docs/install.html",+ configure=_configure,+ catalog_view="messages",+)-def _run(binary_path: str, args: Sequence[str], env: Mapping[str, str]) -> None:- run_client_process(- command=[binary_path, *args],- env=env,- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/aider_config.py b/src/free_claude_code/cli/launchers/aider_config.pyindex 9e6ea2b0..f737f944 100644--- a/src/free_claude_code/cli/launchers/aider_config.py+++ b/src/free_claude_code/cli/launchers/aider_config.py@@ -33,28 +33,28 @@ def build_aider_config(if _AIDER_API_KEY_ENV_PATTERN.fullmatch(api_key_env) is None:raise ValueError("invalid Aider proxy-auth environment variable name")- settings: list[JsonObject] = [- {- "name": "aider/extra_params",+ by_name = {model.wire_slug: model for model in models}+ for model in models:+ by_name.setdefault(f"anthropic/{model.wire_slug}", model)+ settings: list[JsonObject] = []+ metadata: JsonObject = {}+ for name, model in by_name.items():+ entry: JsonObject = {+ "name": name,+ "weak_model_name": name,+ "editor_model_name": name,"extra_params": {+ "model": f"anthropic/{model.wire_slug}","api_base": messages_url,"api_key": f"os.environ/{api_key_env}",},}- ]- settings.extend(- {- "name": f"anthropic/{model.wire_slug}",- "accepts_settings": (+ if model.supports_reasoning is not None:+ entry["accepts_settings"] = (["reasoning_effort"] if model.supports_reasoning else []- ),- }- for model in models- if model.supports_reasoning is not None- )- metadata: JsonObject = {- f"anthropic/{model.wire_slug}": _model_metadata(model) for model in models- }+ )+ settings.append(entry)+ metadata[name] = _model_metadata(model)return AiderConfig(settings=settings, metadata=metadata)diff --git a/src/free_claude_code/cli/launchers/claude.py b/src/free_claude_code/cli/launchers/claude.pyindex 75cff6f5..368c8666 100644--- a/src/free_claude_code/cli/launchers/claude.py+++ b/src/free_claude_code/cli/launchers/claude.py@@ -1,86 +1,33 @@-"""Installed `fcc-claude` launcher."""+"""Installed Claude launcher: native command handling with an FCC connection."""-import os-import sysfrom collections.abc import Sequence-from free_claude_code.cli.claude_env import (- CLAUDE_BINARY_NAME,- build_claude_proxy_env,-)-from free_claude_code.config.loader import get_settings-from free_claude_code.config.server_urls import local_proxy_root_url--from .common import preflight_proxy, resolve_client_binary, run_client_process--_DISPLAY_NAME = "Claude Code"-_INSTALL_HINT = "Install Claude Code with: npm install -g @anthropic-ai/claude-code"-_DEFAULT_PERMISSION_MODE_ARGS = ("--permission-mode", "default")-_PERMISSION_MODE_FLAG = "--permission-mode"-_BYPASS_PERMISSIONS_FLAG = "--dangerously-skip-permissions"-+from free_claude_code.cli.claude_env import CLAUDE_BINARY_NAME, build_claude_proxy_env-def launch(argv: Sequence[str] | None = None) -> None:- """Launch Claude Code with Free Claude Code proxy environment variables."""+from .resources import LaunchResources+from .runner import HarnessSpec, LaunchContext, PreparedLaunch, launch_harness- settings = get_settings()- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)- binary_name = claude_binary_name()- binary_path = resolve_client_binary(- binary_name=binary_name,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )- args = list(sys.argv[1:] if argv is None else argv)- run_client_process(- command=build_claude_launcher_command(binary_path=binary_path, argv=args),- env=build_claude_proxy_env(- proxy_root_url=proxy_root_url,- auth_token=settings.proxy_auth_token,- base_env=os.environ,+def _configure(+ ctx: LaunchContext, args: list[str], _files: LaunchResources+) -> PreparedLaunch:+ return PreparedLaunch(+ [ctx.binary_path, *args],+ build_claude_proxy_env(+ proxy_root_url=ctx.proxy_root_url,+ auth_token=ctx.auth_token,+ base_env=ctx.base_env,),- binary_name=binary_name,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,)-def claude_binary_name() -> str:- """Return the Claude Code binary name."""-- return CLAUDE_BINARY_NAME---def build_claude_launcher_command(- *, binary_path: str, argv: Sequence[str]-) -> list[str]:- """Start Claude outside auto mode unless the user selected a mode."""-- args = list(argv)- if not _has_explicit_permission_mode(args):- args[:0] = _DEFAULT_PERMISSION_MODE_ARGS-- return [binary_path, *args]---def _has_explicit_permission_mode(argv: Sequence[str]) -> bool:- """Return whether CLI arguments explicitly choose a permission mode."""+SPEC = HarnessSpec(+ binary_name=CLAUDE_BINARY_NAME,+ display_name="Claude Code",+ install_hint="Install Claude Code with: npm install -g @anthropic-ai/claude-code",+ configure=_configure,+)- for arg in argv:- if arg == "--":- break- if arg in (- _PERMISSION_MODE_FLAG,- _BYPASS_PERMISSIONS_FLAG,- ) or arg.startswith(f"{_PERMISSION_MODE_FLAG}="):- return True- return False+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/cline.py b/src/free_claude_code/cli/launchers/cline.pyindex 6ea98051..5bf5cf32 100644--- a/src/free_claude_code/cli/launchers/cline.py+++ b/src/free_claude_code/cli/launchers/cline.py@@ -1,370 +1,61 @@-"""Installed `fcc-cline` launcher for the stable Cline CLI."""+"""Installed Cline launcher with private native provider settings."""-import json-import osimport re-import subprocess-import sys-import tempfile-from collections.abc import Mapping, Sequence-from pathlib import Path-from typing import Never--from free_claude_code.cli.local_http import with_local_proxy_bypass-from free_claude_code.config.loader import get_settings-from free_claude_code.config.server_urls import local_proxy_root_url--from .cline_config import CLINE_PROVIDER_ID, ClineConfig, build_cline_config-from .common import preflight_proxy, resolve_client_binary, run_client_process-from .model_catalog import client_models_from_response, fetch_proxy_models_response--_BINARY_NAME = "cline"-_DISPLAY_NAME = "Cline CLI"-_INSTALL_HINT = (- "Install Cline from: https://docs.cline.bot/getting-started/installing-cline"+from collections.abc import Sequence++from free_claude_code.cli.environment import client_environment++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,)-_MINIMUM_VERSION = (3, 0, 55)-_VERSION_TIMEOUT_SECONDS = 5.0+_VERSION_PATTERN = re.compile(r"(?m)^\s*(?:cline(?:\s+version)?\s+|v)?"r"(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?\s*$")-_PASSTHROUGH_COMMANDS = frozenset(- {- "auth",- "config",- "history",- "h",- "plugin",- "skill",- "mcp",- "doctor",- "update",- "version",- }-)-_PASSTHROUGH_FLAGS = frozenset({"--help", "-h", "--version", "-V", "--update"})-_DETACHED_COMMANDS = frozenset(- {"connect", "schedule", "hub", "dashboard", "hook", "kanban"}-)-_DETACHED_FLAGS = frozenset({"--zen", "-z", "--kanban"})-_VALUE_OPTIONS = frozenset(- {- "--auto-approve",- "-c",- "--cwd",- "--thinking",- "--compaction",- "--id",- "-P",- "--provider",- "-k",- "--key",- "-m",- "--model",- "-s",- "--system",- "-t",- "--timeout",- "--config",- "--data-dir",- "--hooks-dir",- "--team-name",- }-)-_OPTIONAL_VALUE_OPTIONS = frozenset({"--retries"})-_BOOLEAN_OPTIONS = frozenset(- {- "-p",- "--plan",- "--json",- "-i",- "--tui",- "-z",- "--zen",- "--acp",- "--worktree",- "--update",- "--kanban",- "-v",- "--verbose",- "-a",- "--act",- "-y",- "--yolo",- "-h",- "--help",- "-V",- "--version",- }-)-def launch(argv: Sequence[str] | None = None) -> None:- """Launch one attached Cline process with an FCC-only default provider."""-- args = list(sys.argv[1:] if argv is None else argv)- binary_path = resolve_client_binary(- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,+def _configure(+ ctx: LaunchContext, args: list[str], files: LaunchResources+) -> PreparedLaunch:+ config = build_cline_config(+ ctx.models, proxy_root_url=ctx.proxy_root_url, auth_token=ctx.auth_token)-- if is_cline_passthrough(args):- _run(binary_path, args, os.environ)- return- if detached_cline_surface(args):- print(- "fcc-cline supports attached terminal sessions only. "- "Run this detached Cline surface with ordinary cline instead.",- file=sys.stderr,- )- raise SystemExit(2)- _reject_sandbox_override(args, os.environ)- _reject_routing_overrides(args)- require_compatible_cline(binary_path)-- settings = get_settings()- auth_token = settings.proxy_auth_token.strip()- if not auth_token:- print("Free Claude Code proxy authentication token is empty.", file=sys.stderr)- raise SystemExit(1)-- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)-- try:- models = client_models_from_response(- fetch_proxy_models_response(proxy_root_url, auth_token)- )- config = build_cline_config(- models,- proxy_root_url=proxy_root_url,- auth_token=auth_token,- )- except Exception as exc:- print(f"Could not prepare the Cline FCC model catalog: {exc}", file=sys.stderr)- raise SystemExit(1) from None-- _run_with_temporary_config(- binary_path=binary_path,- args=args,- config=config,- proxy_root_url=proxy_root_url,- )---def is_cline_passthrough(argv: Sequence[str]) -> bool:- """Return whether Cline can run without FCC-owned process configuration."""-- before_separator = _before_separator(argv)- if any(argument in _PASSTHROUGH_FLAGS for argument in before_separator):- return True- return first_root_positional(argv) in _PASSTHROUGH_COMMANDS---def detached_cline_surface(argv: Sequence[str]) -> bool:- """Return whether arguments request a process that outlives this launcher."""-- before_separator = _before_separator(argv)- if any(argument in _DETACHED_FLAGS for argument in before_separator):- return True- return first_root_positional(argv) in _DETACHED_COMMANDS---def first_root_positional(argv: Sequence[str]) -> str | None:- """Find Cline's first root positional without taking over CLI parsing."""-- index = 0- while index < len(argv):- argument = argv[index]- if argument == "--":- return None- if argument in _VALUE_OPTIONS:- index += 2- continue- if _is_joined_value_option(argument):- index += 1- continue- if argument in _OPTIONAL_VALUE_OPTIONS:- if index + 1 < len(argv) and not argv[index + 1].startswith("-"):- index += 2- else:- index += 1- continue- if argument.startswith("--retries=") or argument in _BOOLEAN_OPTIONS:- index += 1- continue- if argument.startswith("-"):- return None- return argument- return None---def require_compatible_cline(binary_path: str) -> None:- """Exit unless the installed Cline satisfies FCC's released contract."""-- version = cline_binary_version(binary_path)- if version is not None and version >= _MINIMUM_VERSION:- return-- minimum = ".".join(str(part) for part in _MINIMUM_VERSION)- print(- f"The Cline CLI at {binary_path} must be a stable release at least version {minimum}.",- file=sys.stderr,+ providers_path = files.write_json("settings/providers.json", config.providers)+ files.write_json("settings/models.json", config.models)+ return PreparedLaunch(+ [ctx.binary_path, "--provider", CLINE_PROVIDER_ID, *args],+ client_environment(+ ctx.base_env,+ proxy_root_url=ctx.proxy_root_url,+ updates={+ "CLINE_PROVIDER_SETTINGS_PATH": str(providers_path),+ "CLINE_SESSION_BACKEND_MODE": "local",+ },+ ),)- print("Upgrade it with: cline update", file=sys.stderr)- raise SystemExit(126)-def cline_binary_version(binary_path: str) -> tuple[int, int, int] | None:- """Read a stable semantic Cline version without invoking a shell."""-- try:- result = subprocess.run(- [binary_path, "--version"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- timeout=_VERSION_TIMEOUT_SECONDS,- )- except OSError, subprocess.TimeoutExpired:- return None- if result.returncode != 0:- return None-- match = _VERSION_PATTERN.search(result.stdout)- if match is None:- return None- return int(match.group(1)), int(match.group(2)), int(match.group(3))---def build_cline_launcher_env(- *,- proxy_root_url: str,- providers_path: Path,- base_env: Mapping[str, str],-) -> dict[str, str]:- """Build the child-only Cline environment while preserving native state."""-- env = with_local_proxy_bypass(base_env, proxy_root_url=proxy_root_url)- env["CLINE_PROVIDER_SETTINGS_PATH"] = str(providers_path)- env["CLINE_SESSION_BACKEND_MODE"] = "local"- return env---def _run_with_temporary_config(- *,- binary_path: str,- args: Sequence[str],- config: ClineConfig,- proxy_root_url: str,-) -> None:- try:- temp_config = tempfile.TemporaryDirectory(prefix="fcc-cline-")- except OSError as exc:- _temporary_config_error(exc)-- with temp_config as temp_directory:- settings_directory = Path(temp_directory, "settings")- providers_path = settings_directory / "providers.json"- models_path = settings_directory / "models.json"- try:- settings_directory.mkdir(mode=0o700)- _write_private_json(providers_path, config.providers)- _write_private_json(models_path, config.models)- except OSError as exc:- _temporary_config_error(exc)-- _run(- binary_path,- ["--provider", CLINE_PROVIDER_ID, *args],- build_cline_launcher_env(- proxy_root_url=proxy_root_url,- providers_path=providers_path,- base_env=os.environ,- ),- )---def _write_private_json(path: Path, payload: Mapping[str, object]) -> None:- descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)- with os.fdopen(descriptor, "w", encoding="utf-8") as output:- json.dump(payload, output, ensure_ascii=True, indent=2)- output.write("\n")---def _run(binary_path: str, args: Sequence[str], env: Mapping[str, str]) -> None:- run_client_process(- command=[binary_path, *args],- env=env,- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )---def _reject_routing_overrides(argv: Sequence[str]) -> None:- for argument in _before_separator(argv):- if (- argument in {"-P", "--provider", "-k", "--key"}- or argument.startswith(("--provider=", "--key="))- or (argument.startswith(("-P", "-k")) and len(argument) > 2)- ):- print(- "fcc-cline owns the Cline provider and API key. "- "Use ordinary cline for a different provider.",- file=sys.stderr,- )- raise SystemExit(2)---def _reject_sandbox_override(argv: Sequence[str], base_env: Mapping[str, str]) -> None:- has_data_dir = any(- argument == "--data-dir" or argument.startswith("--data-dir=")- for argument in _before_separator(argv)- )- sandbox_enabled = base_env.get("CLINE_SANDBOX", "").strip() == "1"- if not has_data_dir and not sandbox_enabled:- return-- print(- "fcc-cline cannot use Cline sandbox data overrides because Cline replaces "- "the ephemeral FCC provider file in that mode. Use ordinary cline for "- "--data-dir or CLINE_SANDBOX=1.",- file=sys.stderr,- )- raise SystemExit(2)---def _before_separator(argv: Sequence[str]) -> Sequence[str]:- try:- return argv[: argv.index("--")]- except ValueError:- return argv---def _is_joined_value_option(argument: str) -> bool:- if any(- argument.startswith(f"{option}=")- for option in _VALUE_OPTIONS- if option.startswith("--")- ):- return True- return any(- argument.startswith(option) and len(argument) > len(option)- for option in _VALUE_OPTIONS- if option.startswith("-") and not option.startswith("--")- )+SPEC = HarnessSpec(+ binary_name="cline",+ display_name="Cline CLI",+ install_hint="Install Cline from: https://docs.cline.bot/getting-started/installing-cline",+ configure=_configure,+ catalog_view="responses",+ compatibility_check=NativeCheck(+ ("--version",),+ lambda output: version_at_least(output, _VERSION_PATTERN, (3, 0, 55)),+ "FCC requires Cline 3.0.55 or newer.",+ ),+)-def _temporary_config_error(exc: OSError) -> Never:- print(f"Could not create temporary Cline configuration: {exc}", file=sys.stderr)- raise SystemExit(1) from None+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/codex.py b/src/free_claude_code/cli/launchers/codex.pyindex ecaaa6eb..d26b69b2 100644--- a/src/free_claude_code/cli/launchers/codex.py+++ b/src/free_claude_code/cli/launchers/codex.py@@ -1,35 +1,19 @@-"""Installed `fcc-codex` launcher."""+"""Installed Codex launcher and external-client credential handoff."""import json-import osimport sys-from collections.abc import Mapping, Sequence-from dataclasses import dataclass+from collections.abc import Sequence-from free_claude_code.cli.local_http import with_local_proxy_bypass+from free_claude_code.cli.environment import client_environmentfrom free_claude_code.config.loader import get_settings-from free_claude_code.config.paths import codex_model_catalog_path-from free_claude_code.config.server_urls import local_proxy_root_url-from free_claude_code.config.settings import Settings-from .codex_model_catalog import build_codex_model_catalog, write_codex_model_catalog-from .common import (- preflight_proxy,- resolve_client_binary,- run_client_process,-)-from .model_catalog import (- ClientModel,- catalog_wire_slug_for_ref,- client_models_from_response,- fetch_proxy_models_response,-)+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"-_DISPLAY_NAME = "Codex CLI"-_DEFAULT_BINARY = "codex"-_INSTALL_HINT = "Install Codex with: npm install -g @openai/codex"-# Preserve CODEX_HOME: it owns durable user configuration, not parent-task identity._STRIPPED_CODEX_ENV_KEYS = frozenset({"OPENAI_API_KEY",@@ -46,175 +30,65 @@ _STRIPPED_CODEX_ENV_KEYS = frozenset()-def launch(argv: Sequence[str] | None = None) -> None:- """Launch Codex CLI with Free Claude Code proxy configuration."""-- args = list(sys.argv[1:] if argv is None else argv)- settings = get_settings()- if args == [_PRINT_PROXY_AUTH_TOKEN_FLAG]:- print(settings.proxy_auth_token)- return-- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)-- binary_name = codex_binary_name()- binary_path = resolve_client_binary(- binary_name=binary_name,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )- catalog = codex_model_catalog_plan(proxy_root_url, settings)- run_client_process(- command=build_codex_launcher_command(- binary_path=binary_path,- argv=args,- settings=settings,- proxy_root_url=proxy_root_url,- catalog_config_args=catalog.config_args,- catalog_models=catalog.models,- ),- env=build_codex_launcher_env(- proxy_root_url=proxy_root_url,- base_env=os.environ,- ),- binary_name=binary_name,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )---@dataclass(frozen=True, slots=True)-class CodexModelCatalogPlan:- """The generated Codex catalog config args and the models it advertises."""-- config_args: tuple[str, ...] = ()- models: tuple[ClientModel, ...] = ()---def codex_binary_name() -> str:- """Return the Codex CLI binary name."""-- return _DEFAULT_BINARY---def build_codex_launcher_command(- *,- binary_path: str,- argv: Sequence[str],- settings: Settings,- proxy_root_url: str,- catalog_config_args: Sequence[str] = (),- catalog_models: Sequence[ClientModel] = (),-) -> list[str]:- """Return a Codex command with ephemeral FCC provider config."""-+def codex_config_args(*, api_url: str, model: str | None = None) -> list[str]:+ """Build native TOML overrides 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"] = modelreturn [- binary_path,- *catalog_config_args,- *codex_config_args(- api_url=_ensure_v1_url(proxy_root_url),- model=catalog_wire_slug_for_ref(- catalog_models, getattr(settings, "model", None)- ),- ),- *argv,+ arg+ for key, value in values.items()+ for arg in ("-c", f"{key}={json.dumps(value)}")]-def build_codex_launcher_env(- *,- proxy_root_url: str,- base_env: Mapping[str, str],-) -> dict[str, str]:- """Return a Codex environment that targets the local proxy provider."""-- env = with_local_proxy_bypass(- {- key: value- for key, value in base_env.items()- if key not in _STRIPPED_CODEX_ENV_KEYS and not key.startswith("OPENAI_")- },- proxy_root_url=proxy_root_url,+def _configure(+ ctx: LaunchContext, args: list[str], files: LaunchResources+) -> PreparedLaunch:+ catalog_path = files.write_json(+ "model-catalog.json", build_codex_model_catalog(ctx.models))- return env---def codex_model_catalog_plan(- proxy_root_url: str, settings: Settings-) -> CodexModelCatalogPlan:- """Prepare the generated Codex model catalog and the models it advertises."""-- try:- models_response = fetch_proxy_models_response(- proxy_root_url, settings.proxy_auth_token- )- models = client_models_from_response(models_response)- if not models:- print(- "Free Claude Code warning: Codex model catalog is empty; "- "launching without model picker catalog.",- file=sys.stderr,- )- return CodexModelCatalogPlan()- catalog_path = codex_model_catalog_path()- write_codex_model_catalog(- catalog_path, build_codex_model_catalog(models_response)- )- except Exception as exc:- print(- "Free Claude Code warning: could not prepare Codex model catalog "- f"({exc}); launching without model picker catalog.",- file=sys.stderr,- )- return CodexModelCatalogPlan()-- return CodexModelCatalogPlan(- config_args=tuple(build_model_catalog_config_args(str(catalog_path))),- models=models,+ configuration = codex_config_args(+ api_url=ctx.proxy_root_url,+ model=catalog_wire_slug_for_ref(ctx.models, ctx.settings.model),)---def build_model_catalog_config_args(catalog_path: str) -> list[str]:- """Return Codex config args for a generated model catalog."""-- return ["-c", _toml_assignment("model_catalog_json", catalog_path)]---def codex_config_args(*, api_url: str, model: str | None = None) -> list[str]:- """Return Codex `-c` assignments for the ephemeral FCC provider."""-- args = [- "-c",- _toml_assignment("model_provider", "fcc"),- "-c",- _toml_assignment("model_providers.fcc.name", "Free Claude Code"),- "-c",- _toml_assignment("model_providers.fcc.base_url", _ensure_v1_url(api_url)),- "-c",- _toml_assignment("model_providers.fcc.auth.command", "fcc-codex"),- "-c",- _toml_assignment(- "model_providers.fcc.auth.args", [_PRINT_PROXY_AUTH_TOKEN_FLAG]+ 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_",),),- "-c",- _toml_assignment("model_providers.fcc.wire_api", "responses"),- ]- if model:- args.extend(["-c", _toml_assignment("model", model)])- return args+ )-def _ensure_v1_url(url: str) -> str:- stripped = url.rstrip("/")- return stripped if stripped.endswith("/v1") else f"{stripped}/v1"+SPEC = HarnessSpec(+ binary_name="codex",+ display_name="Codex CLI",+ install_hint="Install Codex with: npm install -g @openai/codex",+ configure=_configure,+ catalog_view="responses",+)-def _toml_assignment(key: str, value: str | list[str]) -> str:- return f"{key}={json.dumps(value)}"+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]:+ print(get_settings().proxy_auth_token)+ return+ launch_harness(SPEC, args)diff --git a/src/free_claude_code/cli/launchers/codex_model_catalog.py b/src/free_claude_code/cli/launchers/codex_model_catalog.pyindex cb2d6028..f9d34cfb 100644--- a/src/free_claude_code/cli/launchers/codex_model_catalog.py+++ b/src/free_claude_code/cli/launchers/codex_model_catalog.py@@ -2,13 +2,13 @@import jsonimport uuid-from collections.abc import Mapping+from collections.abc import Mapping, Sequencefrom pathlib import Pathfrom free_claude_code.core.json_types import JsonObject, JsonValuefrom free_claude_code.core.model_capabilities import ModelInputModality-from .model_catalog import ClientModel, client_models_from_response+from .model_catalog import ClientModelSUPPORTED_REASONING_LEVELS: list[JsonObject] = [{"effort": "low", "description": "Fast responses with lighter reasoning"},@@ -30,15 +30,13 @@ CODEX_BASE_INSTRUCTIONS = ()-def build_codex_model_catalog(models_response: Mapping[str, JsonValue]) -> JsonObject:+def build_codex_model_catalog(models: Sequence[ClientModel]) -> JsonObject:"""Convert FCC `/v1/models` data into Codex `model_catalog_json` payload."""return {"models": [_codex_catalog_entry(model, priority=priority)- for priority, model in enumerate(- client_models_from_response(models_response)- )+ for priority, model in enumerate(models)]}diff --git a/src/free_claude_code/cli/launchers/dsh.py b/src/free_claude_code/cli/launchers/dsh.pyindex ff44219e..b93ca7f8 100644--- a/src/free_claude_code/cli/launchers/dsh.py+++ b/src/free_claude_code/cli/launchers/dsh.py@@ -1,358 +1,72 @@-"""Installed `fcc-dsh` launcher for attached DeepSeek Harness sessions."""+"""Installed DeepSeek Harness launcher with an FCC connection patch."""-import json-import osimport re-import subprocess-import sys-import tempfile-from collections.abc import Mapping, Sequence-from dataclasses import dataclass-from pathlib import Path-from typing import Never--from free_claude_code.cli.local_http import with_local_proxy_bypass-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.core.json_types import JsonValue--from .common import preflight_proxy, resolve_client_binary, run_client_process-from .dsh_config import (- DSH_API_KEY_ENV,- DSH_ENV_PREFIX,- build_dsh_launch_config,-)-from .model_catalog import (- ClientModel,- client_models_from_response,- fetch_proxy_models_response,+from collections.abc import Sequence++from free_claude_code.cli.environment import client_environment++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,)-_BINARY_NAME = "dsh"-_DISPLAY_NAME = "DeepSeek Harness"-_SUPPORTED_VERSION = "0.1.0-rc.8"-_INSTALL_COMMAND = f"npm install -g @deepseek-ai/dsh@{_SUPPORTED_VERSION}"-_INSTALL_HINT = (- f"Install the supported DeepSeek Harness release with: {_INSTALL_COMMAND}"-)-_VERSION_TIMEOUT_SECONDS = 5.0_VERSION_PATTERN = re.compile(r"(?im)^\s*(?:dsh\s+)?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?)\s*$")-_SUPPORTED_PROFILES = frozenset({"web", "headless"})-_ROOT_HELP_FLAGS = frozenset({"-h", "--help"})-_ROOT_VERSION_FLAGS = frozenset({"-V", "--version"})---@dataclass(frozen=True, slots=True)-class DshInvocation:- """One minimally classified DSH command line."""-- args: tuple[str, ...]- patch_index: int | None-- @property- def is_routed(self) -> bool:- return self.patch_index is not None---def launch(argv: Sequence[str] | None = None) -> None:- """Launch one attached DSH Web or headless process through FCC."""-- args = list(sys.argv[1:] if argv is None else argv)- binary_path = resolve_client_binary(- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )- invocation = classify_dsh_invocation(args)- if not invocation.is_routed:- _run(binary_path, invocation.args, os.environ)- return-- require_compatible_dsh(binary_path)- settings = get_settings()- auth_token = settings.proxy_auth_token.strip()- if not auth_token:- print("Free Claude Code proxy authentication token is empty.", file=sys.stderr)- raise SystemExit(1)- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)- try:- models = client_models_from_response(- fetch_proxy_models_response(proxy_root_url, auth_token)- )- except Exception as exc:- print(- f"Could not prepare the DeepSeek Harness FCC model catalog: {exc}",- file=sys.stderr,- )- raise SystemExit(1) from None-- _run_with_dsh_config(- binary_path=binary_path,- invocation=invocation,- models=models,- proxy_root_url=proxy_root_url,- auth_token=auth_token,- provider_progress_timeout=settings.provider_progress_timeout,+def _configure(+ ctx: LaunchContext, args: list[str], files: LaunchResources+) -> PreparedLaunch:+ settings_path = files.write_json("settings.yaml", {})+ credentials_path = files.write_json(".credentials.yaml", {})+ config = build_dsh_launch_config(+ ctx.models,+ proxy_root_url=ctx.proxy_root_url,+ settings_path=settings_path,+ credentials_path=credentials_path,+ provider_progress_timeout=ctx.settings.provider_progress_timeout,)---def classify_dsh_invocation(argv: Sequence[str]) -> DshInvocation:- """Classify only DSH's documented launcher prefix and supported profiles."""-- args = list(argv)+ patch_path = files.write_json("fcc.patch.yml", config)+ patch_args = ["--patch", str(patch_path)]if not args:- return DshInvocation(args=("web",), patch_index=1)- if args[0] == "plugin":- return DshInvocation(args=tuple(args), patch_index=None)- if args[0] == "web":- return _classify_web(args)- return _classify_profile(args)---def require_compatible_dsh(binary_path: str) -> None:- """Exit unless DSH exactly matches FCC's audited preview contract."""-- version = dsh_binary_version(binary_path)- if version == _SUPPORTED_VERSION:- return-- found = version or "an unrecognized version"- print(- f"fcc-dsh requires DeepSeek Harness {_SUPPORTED_VERSION}; found {found}.",- file=sys.stderr,- )- print(f"Install it with: {_INSTALL_COMMAND}", file=sys.stderr)- raise SystemExit(126)---def dsh_binary_version(binary_path: str) -> str | None:- """Read DSH's semantic preview version without invoking a shell."""-- try:- result = subprocess.run(- [binary_path, "--version"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- timeout=_VERSION_TIMEOUT_SECONDS,- )- except OSError, subprocess.TimeoutExpired:- return None- if result.returncode != 0:- return None-- match = _VERSION_PATTERN.search(result.stdout)- return match.group(1) if match is not None else None---def build_dsh_launcher_env(- *,- auth_token: str,- proxy_root_url: str,- base_env: Mapping[str, str],-) -> dict[str, str]:- """Build a child-only DSH environment while preserving native state."""-- filtered = {- key: value- for key, value in base_env.items()- if not key.startswith(DSH_ENV_PREFIX)- }- env = with_local_proxy_bypass(filtered, proxy_root_url=proxy_root_url)- env[DSH_API_KEY_ENV] = auth_token- env["DSH_TELEMETRY_DISABLED"] = "1"- return env---def _classify_web(args: list[str]) -> DshInvocation:- patch_index = len(args)- default_dump = False- index = 1- while index < len(args):- argument = args[index]- if argument == "--patch" or argument.startswith("--patch="):- _patch_override_error()- if argument == "--dump-default-config":- default_dump = True- index += 1- continue- if argument == "--dump-config":- index += 1- continue- patch_index = index- break-- if default_dump or (- patch_index < len(args) and args[patch_index] in _ROOT_HELP_FLAGS- ):- return DshInvocation(args=tuple(args), patch_index=None)- return DshInvocation(args=tuple(args), patch_index=patch_index)---def _classify_profile(args: list[str]) -> DshInvocation:- profile: str | None = None- patch_index = len(args)- default_dump = False- index = 0- while index < len(args):- argument = args[index]- if argument in _ROOT_VERSION_FLAGS:- return DshInvocation(args=tuple(args), patch_index=None)- if argument in _ROOT_HELP_FLAGS and profile is None:- return DshInvocation(args=tuple(args), patch_index=None)- if argument == "--profile":- if index + 1 >= len(args) or not args[index + 1]:- _profile_value_error()- profile = args[index + 1]- index += 2- continue- if argument.startswith("--profile="):- profile = argument.partition("=")[2]- if not profile:- _profile_value_error()- index += 1- continue- if argument == "--patch" or argument.startswith("--patch="):- _patch_override_error()- if argument == "--dump-default-config":- default_dump = True- index += 1- continue- if argument == "--dump-config":- index += 1- continue- patch_index = index- break-- if profile is not None and profile not in _SUPPORTED_PROFILES:- _unsupported_profile_error(profile)- if default_dump:- return DshInvocation(args=tuple(args), patch_index=None)- if profile is not None:- if patch_index < len(args) and args[patch_index] in _ROOT_HELP_FLAGS:- return DshInvocation(args=tuple(args), patch_index=None)- return DshInvocation(args=tuple(args), patch_index=patch_index)-- normalized = ["web", *args]- return DshInvocation(args=tuple(normalized), patch_index=1)---def _run_with_dsh_config(- *,- binary_path: str,- invocation: DshInvocation,- models: tuple[ClientModel, ...],- proxy_root_url: str,- auth_token: str,- provider_progress_timeout: float,-) -> None:- try:- temp_config = tempfile.TemporaryDirectory(prefix="fcc-dsh-")- except OSError as exc:- _temporary_config_error(exc)-- with temp_config as temp_directory:- directory = Path(temp_directory)- patch_path = directory / "fcc.patch.yml"- settings_path = directory / "settings.yaml"- credentials_path = directory / ".credentials.yaml"- try:- if os.name != "nt":- directory.chmod(0o700)- config = build_dsh_launch_config(- models,- proxy_root_url=proxy_root_url,- settings_path=settings_path,- credentials_path=credentials_path,- provider_progress_timeout=provider_progress_timeout,- )- _write_private_json(patch_path, config.patch)- _write_private_json(settings_path, {})- _write_private_json(credentials_path, {})- except ValueError as exc:- print(- f"Could not prepare DeepSeek Harness configuration: {exc}",- file=sys.stderr,- )- raise SystemExit(1) from None- except OSError as exc:- _temporary_config_error(exc)-- child_env = build_dsh_launcher_env(- auth_token=auth_token,- proxy_root_url=proxy_root_url,- base_env=os.environ,- )- _run(- binary_path,- _args_with_patch(invocation, patch_path),- child_env,- )---def _args_with_patch(invocation: DshInvocation, patch_path: Path) -> list[str]:- if invocation.patch_index is None:- raise ValueError("native DSH passthrough cannot receive an FCC patch")- args = list(invocation.args)- args[invocation.patch_index : invocation.patch_index] = ["--patch", str(patch_path)]- return args---def _write_private_json(path: Path, payload: JsonValue) -> None:- descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)- with os.fdopen(descriptor, "w", encoding="utf-8") as output:- json.dump(payload, output, ensure_ascii=True, indent=2)- output.write("\n")---def _run(binary_path: str, args: Sequence[str], env: Mapping[str, str]) -> None:- run_client_process(- command=[binary_path, *args],- env=env,- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )---def _profile_value_error() -> Never:- print("fcc-dsh requires a value after --profile.", file=sys.stderr)- raise SystemExit(2)---def _patch_override_error() -> Never:- print(- "fcc-dsh owns the final DeepSeek Harness patch. "- "Use ordinary dsh for custom profile patches.",- file=sys.stderr,+ command = [ctx.binary_path, "web", *patch_args]+ elif args[0] == "web":+ command = [ctx.binary_path, "web", *patch_args, *args[1:]]+ else:+ command = [ctx.binary_path, "--profile", "web", *patch_args, *args]+ return PreparedLaunch(+ command,+ client_environment(+ ctx.base_env,+ proxy_root_url=ctx.proxy_root_url,+ remove_prefixes=(DSH_ENV_PREFIX,),+ updates={DSH_API_KEY_ENV: ctx.auth_token, "DSH_TELEMETRY_DISABLED": "1"},+ ),)- raise SystemExit(2)-def _unsupported_profile_error(profile: str) -> Never:- print(- f"fcc-dsh supports only the web and headless profiles, not {profile!r}. "- "Use ordinary dsh for custom profiles.",- file=sys.stderr,- )- raise SystemExit(2)+SPEC = HarnessSpec(+ binary_name="dsh",+ display_name="DeepSeek Harness",+ install_hint="Install the supported DeepSeek Harness release with: npm install -g @deepseek-ai/[email protected]",+ configure=_configure,+ catalog_view="responses",+ compatibility_check=NativeCheck(+ ("--version",),+ lambda output: (+ bool(match := _VERSION_PATTERN.search(output))+ and match.group(1) == "0.1.0-rc.8"+ ),+ "FCC requires DeepSeek Harness 0.1.0-rc.8.",+ ),+)-def _temporary_config_error(exc: OSError) -> Never:- print(- f"Could not create temporary DeepSeek Harness configuration: {exc}",- file=sys.stderr,- )- raise SystemExit(1) from None+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/dsh_config.py b/src/free_claude_code/cli/launchers/dsh_config.pyindex fbde4b85..bcec26fa 100644--- a/src/free_claude_code/cli/launchers/dsh_config.py+++ b/src/free_claude_code/cli/launchers/dsh_config.py@@ -1,7 +1,6 @@"""Process-local DeepSeek Harness configuration for FCC model routing."""import math-from dataclasses import dataclass, fieldfrom pathlib import Pathfrom free_claude_code.core.json_types import JsonObject@@ -27,15 +26,6 @@ _REASONING_EFFORTS: JsonObject = {}-@dataclass(frozen=True, slots=True)-class DshLaunchConfig:- """Secret-free DSH patch for one attached FCC launch."""-- patch: tuple[JsonObject, ...] = field(repr=False)- selected_model: str- api_key_env: str = DSH_API_KEY_ENV--def build_dsh_launch_config(models: tuple[ClientModel, ...],*,@@ -43,7 +33,7 @@ def build_dsh_launch_config(settings_path: Path,credentials_path: Path,provider_progress_timeout: float,-) -> DshLaunchConfig:+) -> tuple[JsonObject, ...]:"""Translate FCC's catalog and timeout into an isolated DSH overlay."""if not models:@@ -61,7 +51,7 @@ def build_dsh_launch_config("retryPolicy": {"mode": "normal", "maxRetries": 0},"streamIdleTimeoutMs": stream_idle_timeout_ms,}- patch = (+ return (_configured_row("settings","@deepseek-ai/dsh-settings-file",@@ -89,7 +79,6 @@ def build_dsh_launch_config(),_disabled_row("tool-web", "@deepseek-ai/dsh-tool-web"),)- return DshLaunchConfig(patch=patch, selected_model=selected_model)def _stream_idle_timeout_ms(provider_progress_timeout: float) -> int:diff --git a/src/free_claude_code/cli/launchers/grok.py b/src/free_claude_code/cli/launchers/grok.pyindex 0a2e3358..d2724218 100644--- a/src/free_claude_code/cli/launchers/grok.py+++ b/src/free_claude_code/cli/launchers/grok.py@@ -1,128 +1,33 @@-"""Installed `fcc-grok` launcher for attached Grok Build sessions."""+"""Installed Grok Build launcher with native FCC connection settings."""import json-import osimport re-import subprocess-import sys-from collections.abc import Mapping, Sequence-from dataclasses import dataclass-from enum import StrEnum-from typing import Never+from collections.abc import Sequence-from free_claude_code.cli.local_http import with_local_proxy_bypass-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.core.json_types import JsonValue--from .common import (- preflight_proxy,- proxy_v1_url,- resolve_client_binary,- run_client_process,+from free_claude_code.cli.environment import (+ client_environment,+ require_unset_environment,)-from .model_catalog import (- ClientModel,- client_models_from_response,- fetch_proxy_models_response,++from .common import proxy_v1_url+from .resources import LaunchResources+from .runner import (+ HarnessSpec,+ LaunchContext,+ NativeCheck,+ PreparedLaunch,+ launch_harness,+ version_at_least,)-_BINARY_NAME = "grok"-_DISPLAY_NAME = "Grok Build"_INSTALL_HINT = ("Install Grok Build with `irm https://x.ai/cli/install.ps1 | iex` on Windows ""or `curl -fsSL https://x.ai/cli/install.sh | bash` on macOS/Linux.")-_MINIMUM_VERSION = (1, 0, 5)-_VERSION_TIMEOUT_SECONDS = 5.0_VERSION_PATTERN = re.compile(r"^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?"r"(?:\s+\([^\r\n]*\))?$")-_PASSTHROUGH_COMMANDS = frozenset(- {- "completions",- "disk-usage",- "doctor",- "du",- "export",- "login",- "logout",- "mcp",- "memory",- "plugin",- "sessions",- "setup",- "share",- "trace",- "update",- "v",- "version",- "worktree",- "wrap",- }-)-_CONFIGURED_COMMANDS = frozenset({"inspect", "models"})-_REJECTED_COMMANDS = frozenset({"dashboard", "leader", "workspace"})-_PASSTHROUGH_FLAGS = frozenset({"-h", "--help", "-v", "-V", "--version"})-_ROUTE_BYPASS_FLAGS = frozenset(- {- "--cli-chat-proxy-base-url",- "--force-login",- "--leader",- "--oauth",- "--xai-api-base-url",- }-)-_VALUE_OPTIONS = frozenset(- {- "--agent",- "--agent-profile",- "--agents",- "--allow",- "--allowedTools",- "--append-system-prompt",- "--background-wait-timeout",- "--cli-chat-proxy-base-url",- "--client-identifier",- "--compaction-detail",- "--compaction-mode",- "--cwd",- "--debug-file",- "--deny",- "--disallowed-tools",- "--disallowedTools",- "--effort",- "--hunk-tracker-mode",- "--installer",- "--json-schema",- "--leader-socket",- "--load",- "--max-turns",- "--model",- "--output-format",- "--permission-mode",- "--plugin-dir",- "--prompt-file",- "--prompt-json",- "--reasoning-effort",- "--ref",- "--rules",- "--sandbox",- "--session-id",- "--single",- "--storage-mode",- "--system-prompt",- "--system-prompt-override",- "--tools",- "--worktree-ref",- "--xai-api-base-url",- "-m",- "-p",- "-s",- }-)-_OPTIONAL_VALUE_OPTIONS = frozenset({"--resume", "--worktree", "-r", "-w"})_PROCESS_CONFIG_KEYS = ("GROK_CONFIG", "GROK_CONFIG_PATH")_ROUTING_ENV_KEYS = frozenset({@@ -140,361 +45,77 @@ _ROUTING_ENV_KEYS = frozenset()-class GrokInvocationMode(StrEnum):- """How `fcc-grok` treats one Grok Build invocation."""-- PASSTHROUGH = "passthrough"- CONFIGURED = "configured"- ROUTED = "routed"---@dataclass(frozen=True, slots=True)-class GrokInvocation:- """A minimal command classification without replacing Grok's parser."""-- mode: GrokInvocationMode- agent_index: int | None = None---def launch(argv: Sequence[str] | None = None) -> None:- """Launch one attached Grok Build process through FCC."""-- args = list(sys.argv[1:] if argv is None else argv)- binary_path = resolve_client_binary(- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )- invocation = classify_grok_invocation(args)- if invocation.mode is GrokInvocationMode.PASSTHROUGH:- _run(binary_path, args, os.environ)- return-- _reject_process_config_conflicts(os.environ)- _reject_routing_overrides(args)- require_compatible_grok(binary_path)-- settings = get_settings()- auth_token = settings.proxy_auth_token.strip()- if not auth_token:- print("Free Claude Code proxy authentication token is empty.", file=sys.stderr)- raise SystemExit(1)-- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)-- try:- models = client_models_from_response(- fetch_proxy_models_response(proxy_root_url, auth_token)- )- if not models:- raise ValueError("model catalog contains no routable models")- except Exception as exc:- print(- f"Could not prepare the Grok Build FCC model catalog: {exc}",- file=sys.stderr,- )- raise SystemExit(1) from None-+def _compatible_version(output: str) -> bool:try:- selected_model = _selected_model(args, models)- except ValueError as exc:- print(f"Invalid Grok Build model selection: {exc}", file=sys.stderr)- raise SystemExit(2) from None-- child_env = build_grok_launcher_env(- models=models,- selected_model=selected_model,- proxy_root_url=proxy_root_url,- auth_token=auth_token,- base_env=os.environ,- )-- command_args = (- _args_with_safety_flags(args, invocation)- if invocation.mode is GrokInvocationMode.ROUTED- else args- )- _run(binary_path, command_args, child_env)---def classify_grok_invocation(argv: Sequence[str]) -> GrokInvocation:- """Classify only the Grok surfaces whose lifecycle FCC can own."""-- before_separator = _before_separator(argv)- if any(argument in _PASSTHROUGH_FLAGS for argument in before_separator):- return GrokInvocation(GrokInvocationMode.PASSTHROUGH)-- positional_index = _first_positional_index(before_separator)- if positional_index is None:- return GrokInvocation(GrokInvocationMode.ROUTED)-- command = before_separator[positional_index]- if command in _PASSTHROUGH_COMMANDS:- return GrokInvocation(GrokInvocationMode.PASSTHROUGH)- if command in _CONFIGURED_COMMANDS:- return GrokInvocation(GrokInvocationMode.CONFIGURED)- if command in _REJECTED_COMMANDS:- _detached_surface_error(command)- if command != "agent":- return GrokInvocation(GrokInvocationMode.ROUTED)-- mode_index = _first_positional_index(before_separator, start=positional_index + 1)- mode = before_separator[mode_index] if mode_index is not None else None- if mode == "stdio":- return GrokInvocation(GrokInvocationMode.ROUTED, agent_index=positional_index)- _detached_surface_error(f"agent {mode}" if mode else "agent")---def require_compatible_grok(binary_path: str) -> None:- """Exit unless Grok Build satisfies FCC's custom-model contract."""-- version = grok_binary_version(binary_path)- if version is not None and version >= _MINIMUM_VERSION:- return-- minimum = ".".join(str(part) for part in _MINIMUM_VERSION)- print(- f"The Grok Build CLI at {binary_path} must be at least version {minimum}.",- file=sys.stderr,- )- print(_INSTALL_HINT, file=sys.stderr)- raise SystemExit(1)---def grok_binary_version(binary_path: str) -> tuple[int, int, int] | None:- """Read Grok Build's machine-readable version metadata."""-- try:- result = subprocess.run(- [binary_path, "version", "--json"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- timeout=_VERSION_TIMEOUT_SECONDS,- )- except OSError, subprocess.TimeoutExpired:- return None- if result.returncode != 0:- return None-- try:- payload: JsonValue = json.loads(result.stdout)+ payload = json.loads(output)except json.JSONDecodeError:- return None+ return Falseif not isinstance(payload, dict):- return None-- current_version = payload.get("currentVersion")- if not isinstance(current_version, str):- return None- match = _VERSION_PATTERN.fullmatch(current_version.strip())- if match is None:- return None- return int(match.group(1)), int(match.group(2)), int(match.group(3))---def build_grok_launcher_env(- *,- models: Sequence[ClientModel],- selected_model: str,- proxy_root_url: str,- auth_token: str,- base_env: Mapping[str, str],-) -> dict[str, str]:- """Build a child-only Grok route while preserving native Grok state."""-- filtered = {- key: value- for key, value in base_env.items()- if not key.startswith("FCC_GROK_") and key not in _ROUTING_ENV_KEYS- }- env = with_local_proxy_bypass(filtered, proxy_root_url=proxy_root_url)- v1_url = proxy_v1_url(proxy_root_url)- env["GROK_XAI_API_BASE_URL"] = v1_url- env["GROK_MODELS_BASE_URL"] = v1_url- env["GROK_MODELS_LIST_URL"] = f"{v1_url}/models?view=responses"- env["GROK_DEFAULT_MODEL"] = selected_model- env["GROK_IMAGE_DESCRIPTION_MODEL"] = selected_model- env["GROK_PROMPT_SUGGESTIONS_MODEL"] = selected_model- env["GROK_SESSION_SUMMARY_MODEL"] = selected_model- env["GROK_WEB_SEARCH_MODEL"] = selected_model- env["XAI_API_KEY"] = auth_token- env["GROK_CONFIG"] = json.dumps(- {- "models": {"allowed_models": [model.wire_slug for model in models]},- "shell_environment_policy": {"ignore_default_excludes": False},- },- ensure_ascii=True,- separators=(",", ":"),+ return False+ version = payload.get("currentVersion")+ return isinstance(version, str) and version_at_least(+ version.strip(), _VERSION_PATTERN, (1, 0, 5))- return env---def _selected_model(argv: Sequence[str], models: Sequence[ClientModel]) -> str:- supplied = _model_override(argv)- if supplied is None:- return models[0].wire_slug- available = {model.wire_slug for model in models}- if supplied not in available:- raise ValueError(f"model {supplied!r} is not in the current FCC catalog")- return supplied---def _model_override(argv: Sequence[str]) -> str | None:- selected: str | None = None- index = 0- while index < len(argv):- argument = argv[index]- if argument == "--":- break- if argument in {"-m", "--model"}:- if index + 1 >= len(argv) or not argv[index + 1]:- raise ValueError(f"{argument} requires a model value")- selected = _merge_model_override(selected, argv[index + 1])- index += 2- continue- if argument.startswith("--model="):- value = argument.partition("=")[2]- if not value:- raise ValueError("--model requires a model value")- selected = _merge_model_override(selected, value)- index += 1- continue- if argument.startswith("-m") and len(argument) > 2:- selected = _merge_model_override(selected, argument[2:])- index += 1- continue- if argument in _VALUE_OPTIONS:- index += 2- continue- if argument in _OPTIONAL_VALUE_OPTIONS:- if index + 1 < len(argv) and not argv[index + 1].startswith("-"):- index += 2- else:- index += 1- continue- index += 1- return selected---def _merge_model_override(current: str | None, candidate: str) -> str:- if current is not None and current != candidate:- raise ValueError("conflicting --model values are not supported")- return candidate--def _args_with_safety_flags(- argv: Sequence[str], invocation: GrokInvocation-) -> list[str]:- args = list(argv)- agent_index = invocation.agent_index- if "--disable-web-search" not in _before_separator(args):- args.insert(0, "--disable-web-search")- if agent_index is not None:- agent_index += 1- if agent_index is None:- if "--no-leader" not in _before_separator(args):- args.insert(0, "--no-leader")- return args-- if "--no-leader" not in _before_separator(args)[agent_index + 1 :]:- args.insert(agent_index + 1, "--no-leader")- return args---def _reject_process_config_conflicts(base_env: Mapping[str, str]) -> None:- for key in _PROCESS_CONFIG_KEYS:- if base_env.get(key, "").strip():- print(- f"{key} is already set. Unset it before running fcc-grok; "- "ordinary grok remains unchanged.",- file=sys.stderr,- )- raise SystemExit(2)---def _reject_routing_overrides(argv: Sequence[str]) -> None:- for argument in _before_separator(argv):- if argument in _ROUTE_BYPASS_FLAGS or any(- argument.startswith(f"{flag}=") for flag in _ROUTE_BYPASS_FLAGS- ):- print(- "fcc-grok owns the attached Grok Build route. "- "Use ordinary grok for xAI login, custom endpoints, or leader mode.",- file=sys.stderr,- )- raise SystemExit(2)---def _first_positional_index(argv: Sequence[str], *, start: int = 0) -> int | None:- index = start- while index < len(argv):- argument = argv[index]- if argument == "--":- return index + 1 if index + 1 < len(argv) else None- if argument in _VALUE_OPTIONS:- index += 2- continue- if _is_joined_value_option(argument):- index += 1- continue- if argument in _OPTIONAL_VALUE_OPTIONS:- if index + 1 < len(argv) and not argv[index + 1].startswith("-"):- index += 2- else:- index += 1- continue- if argument.startswith("-"):- index += 1- continue- return index- return None---def _is_joined_value_option(argument: str) -> bool:- if any(- argument.startswith(f"{option}=")- for option in _VALUE_OPTIONS | _OPTIONAL_VALUE_OPTIONS- if option.startswith("--")- ):- return True- return any(- argument.startswith(option) and len(argument) > len(option)- for option in _VALUE_OPTIONS | _OPTIONAL_VALUE_OPTIONS- if option.startswith("-") and not option.startswith("--")- )---def _before_separator(argv: Sequence[str]) -> Sequence[str]:- try:- return argv[: argv.index("--")]- except ValueError:- return argv---def _detached_surface_error(surface: str) -> Never:- print(- f"fcc-grok cannot own the lifecycle of Grok Build {surface!r}. "- "Use ordinary grok for detached, leader, workspace, or dashboard modes.",- file=sys.stderr,+def _configure(+ ctx: LaunchContext, args: list[str], _files: LaunchResources+) -> PreparedLaunch:+ require_unset_environment(ctx.base_env, _PROCESS_CONFIG_KEYS)+ v1_url = proxy_v1_url(ctx.proxy_root_url)+ default_model = ctx.models[0].wire_slug+ env = client_environment(+ ctx.base_env,+ proxy_root_url=ctx.proxy_root_url,+ remove_keys=tuple(_ROUTING_ENV_KEYS),+ remove_prefixes=("FCC_GROK_",),+ updates={+ "GROK_XAI_API_BASE_URL": v1_url,+ "GROK_MODELS_BASE_URL": v1_url,+ "GROK_MODELS_LIST_URL": f"{v1_url}/models?view=responses",+ "GROK_DEFAULT_MODEL": default_model,+ "GROK_IMAGE_DESCRIPTION_MODEL": default_model,+ "GROK_PROMPT_SUGGESTIONS_MODEL": default_model,+ "GROK_SESSION_SUMMARY_MODEL": default_model,+ "GROK_WEB_SEARCH_MODEL": default_model,+ "XAI_API_KEY": ctx.auth_token,+ "GROK_CONFIG": json.dumps(+ {+ "models": {+ "allowed_models": [model.wire_slug for model in ctx.models]+ },+ "shell_environment_policy": {"ignore_default_excludes": False},+ },+ separators=(",", ":"),+ ),+ },)- raise SystemExit(2)+ if args and args[0] == "agent":+ command = [+ ctx.binary_path,+ "--disable-web-search",+ "agent",+ "--no-leader",+ *args[1:],+ ]+ else:+ command = [ctx.binary_path, "--disable-web-search", "--no-leader", *args]+ return PreparedLaunch(command, env)+++SPEC = HarnessSpec(+ binary_name="grok",+ display_name="Grok Build",+ install_hint=_INSTALL_HINT,+ configure=_configure,+ catalog_view="responses",+ compatibility_check=NativeCheck(+ ("version", "--json"),+ _compatible_version,+ "FCC requires Grok Build 1.0.5 or newer.",+ ),+)-def _run(binary_path: str, args: Sequence[str], env: Mapping[str, str]) -> None:- run_client_process(- command=[binary_path, *args],- env=env,- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/hermes.py b/src/free_claude_code/cli/launchers/hermes.pyindex d75e1bf9..df6c1efe 100644--- a/src/free_claude_code/cli/launchers/hermes.py+++ b/src/free_claude_code/cli/launchers/hermes.py@@ -1,522 +1,88 @@-"""Installed `fcc-hermes` launcher for attached Hermes Agent sessions."""+"""Installed Hermes launcher with a native managed provider overlay."""import jsonimport osimport reimport secrets-import subprocess-import sys-import tempfile-from collections.abc import Mapping, Sequence+from collections.abc import Sequencefrom pathlib import Path-from typing import Never-from free_claude_code.cli.local_http import with_local_proxy_bypass-from free_claude_code.config.loader import get_settings-from free_claude_code.config.server_urls import local_proxy_root_url--from .common import preflight_proxy, resolve_client_binary, run_client_process-from .hermes_config import (- HERMES_KEY_ENV_PREFIX,- HermesManagedConfig,- build_hermes_managed_config,+from free_claude_code.cli.environment import (+ client_environment,+ require_unset_environment,)-from .model_catalog import client_models_from_response, fetch_proxy_models_response-_BINARY_NAME = "hermes"-_DISPLAY_NAME = "Hermes Agent"-_INSTALL_URL = "https://hermes-agent.nousresearch.com/docs/installation"-_INSTALL_HINT = f"Install Hermes Agent from: {_INSTALL_URL}"-_MINIMUM_VERSION = (0, 20, 4)-_VERSION_TIMEOUT_SECONDS = 5.0-_ACTIVATION_TIMEOUT_SECONDS = 15.0-_VERSION_PATTERN = re.compile(r"(?i)\b(?:Hermes Agent\s+)?v?(\d+)\.(\d+)\.(\d+)\b")-_PASSTHROUGH_FLAGS = frozenset({"-h", "--help", "-V", "--version"})-_DETACHED_COMMANDS = frozenset(- {- "acp",- "rl",- "gateway",- "cron",- "serve",- "dashboard",- "gui",- "desktop",- "proxy",- }-)-_GLOBAL_VALUE_OPTIONS = frozenset(- {- "-z",- "--oneshot",- "--usage-file",- "-m",- "--model",- "--provider",- "--reasoning",- "-t",- "--toolsets",- "-r",- "--resume",- "--in",- "-s",- "--skills",- "-p",- "--profile",- }+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,)-_GLOBAL_OPTIONAL_VALUE_OPTIONS = frozenset({"-c", "--continue"})-_GLOBAL_BOOLEAN_OPTIONS = frozenset(- {- "--no-restore-cwd",- "-w",- "--worktree",- "--accept-hooks",- "--yolo",- "--pass-session-id",- "--ignore-user-config",- "--ignore-rules",- "--safe-mode",- "--tui",- "--cli",- "--dev",- }-)---def launch(argv: Sequence[str] | None = None) -> None:- """Launch one attached Hermes process with an FCC-owned default route."""-- args = list(sys.argv[1:] if argv is None else argv)- binary_path = resolve_client_binary(- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )-- if is_hermes_passthrough(args):- _run(binary_path, args, os.environ)- return- if detached_hermes_surface(args):- print(- "fcc-hermes supports attached terminal sessions only. "- "Run this detached Hermes surface with ordinary hermes instead.",- file=sys.stderr,- )- raise SystemExit(2)-- profile_args = hermes_profile_args(args)- routed_args, selected_model = _without_routing_overrides(args)- _reject_managed_policy(os.environ)- require_compatible_hermes(binary_path)-- settings = get_settings()- auth_token = settings.proxy_auth_token.strip()- if not auth_token:- print("Free Claude Code proxy authentication token is empty.", file=sys.stderr)- raise SystemExit(1)-- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)-- try:- models = client_models_from_response(- fetch_proxy_models_response(proxy_root_url, auth_token)- )- managed = build_hermes_managed_config(- models,- proxy_root_url=proxy_root_url,- nonce=secrets.token_hex(8),- selected_model=selected_model,- )- except Exception as exc:- print(f"Could not prepare the Hermes FCC model catalog: {exc}", file=sys.stderr)- raise SystemExit(1) from None-- _run_with_managed_config(- binary_path=binary_path,- args=routed_args,- profile_args=profile_args,- managed=managed,- proxy_root_url=proxy_root_url,- auth_token=auth_token,- )---def is_hermes_passthrough(argv: Sequence[str]) -> bool:- """Return whether Hermes should run without FCC process configuration."""-- before_separator = _before_separator(argv)- if any(argument in _PASSTHROUGH_FLAGS for argument in before_separator):- return True- root = first_root_positional(argv)- return root not in {None, "chat"} and not detached_hermes_surface(argv)---def detached_hermes_surface(argv: Sequence[str]) -> bool:- """Return whether arguments request a process that can outlive the wrapper."""-- root = first_root_positional(argv)- if root in _DETACHED_COMMANDS:- return True- return root == "mcp" and _second_positional(argv) == "serve"---def first_root_positional(argv: Sequence[str]) -> str | None:- """Find Hermes's root command without copying its full argparse tree."""-- positionals = _root_positionals(argv, limit=1)- return positionals[0] if positionals else None---def hermes_profile_args(argv: Sequence[str]) -> tuple[str, ...]:- """Return the first explicit profile selector Hermes will consume."""-- before_separator = _before_separator(argv)- index = 0- while index < len(before_separator):- argument = before_separator[index]- if argument in {"-p", "--profile"}:- if index + 1 < len(before_separator):- return argument, before_separator[index + 1]- return ()- if argument.startswith("--profile="):- return (argument,)- index = _next_root_index(before_separator, index)- return ()---def require_compatible_hermes(binary_path: str) -> None:- """Exit unless the installed Hermes satisfies FCC's audited contract."""-- version = hermes_binary_version(binary_path)- if version is not None and version >= _MINIMUM_VERSION:- return-- minimum = ".".join(str(part) for part in _MINIMUM_VERSION)- print(- f"The Hermes Agent at {binary_path} must be at least version {minimum}.",- file=sys.stderr,- )- print(f"Upgrade it from: {_INSTALL_URL}", file=sys.stderr)- raise SystemExit(126)---def hermes_binary_version(binary_path: str) -> tuple[int, int, int] | None:- """Read a Hermes semantic version without invoking a shell."""-- try:- result = subprocess.run(- [binary_path, "--version"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- timeout=_VERSION_TIMEOUT_SECONDS,- )- except OSError, subprocess.TimeoutExpired:- return None- if result.returncode != 0:- return None-- match = _VERSION_PATTERN.search(result.stdout)- if match is None:- return None- return int(match.group(1)), int(match.group(2)), int(match.group(3))---def build_hermes_launcher_env(- *,- managed_directory: Path,- key_env: str,- auth_token: str,- proxy_root_url: str,- base_env: Mapping[str, str],-) -> dict[str, str]:- """Build a child-only Hermes environment while preserving native state."""-- filtered = {- key: value- for key, value in base_env.items()- if not key.startswith(HERMES_KEY_ENV_PREFIX)- and key- not in {- "HERMES_MANAGED_DIR",- "HERMES_INFERENCE_MODEL",- "HERMES_INFERENCE_PROVIDER",- }- }- env = with_local_proxy_bypass(filtered, proxy_root_url=proxy_root_url)- env["HERMES_MANAGED_DIR"] = str(managed_directory)- env[key_env] = auth_token- return env---def _run_with_managed_config(- *,- binary_path: str,- args: Sequence[str],- profile_args: Sequence[str],- managed: HermesManagedConfig,- proxy_root_url: str,- auth_token: str,-) -> None:- try:- temp_config = tempfile.TemporaryDirectory(prefix="fcc-hermes-")- except OSError as exc:- _temporary_config_error(exc)-- with temp_config as temp_directory:- managed_directory = Path(temp_directory)- config_path = managed_directory / "config.yaml"- try:- if os.name != "nt":- managed_directory.chmod(0o700)- _write_private_json(config_path, managed.config)- except OSError as exc:- _temporary_config_error(exc)-- child_env = build_hermes_launcher_env(- managed_directory=managed_directory,- key_env=managed.key_env,- auth_token=auth_token,- proxy_root_url=proxy_root_url,- base_env=os.environ,- )- _require_overlay_activation(- binary_path=binary_path,- profile_args=profile_args,- expected_provider=managed.provider_ref,- env=child_env,- )- _run(- binary_path,- [- "--provider",- managed.provider_ref,- "--model",- managed.selected_model,- *args,- ],- child_env,- )+_INSTALL_HINT = (+ "Install Hermes Agent from: https://hermes-agent.nousresearch.com/docs/installation"+)+_VERSION_PATTERN = re.compile(r"(?i)\b(?:Hermes Agent\s+)?v?(\d+)\.(\d+)\.(\d+)\b")-def _require_overlay_activation(- *,- binary_path: str,- profile_args: Sequence[str],- expected_provider: str,- env: Mapping[str, str],-) -> None:- command = [- binary_path,- *profile_args,- "config",- "get",- "model.provider",- "--json",- ]- try:- result = subprocess.run(- command,- check=False,- capture_output=True,- text=True,- timeout=_ACTIVATION_TIMEOUT_SECONDS,- env=dict(env),- )- except OSError, subprocess.TimeoutExpired:- _overlay_activation_error()- if result.returncode != 0:- _overlay_activation_error()- lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]- if not lines:- _overlay_activation_error()+def _overlay_loaded(output: str, expected_provider: str) -> bool:+ lines = output.strip().splitlines()try:- active_provider = json.loads(lines[-1])+ return bool(lines) and json.loads(lines[-1]) == expected_providerexcept json.JSONDecodeError:- _overlay_activation_error()- if active_provider != expected_provider:- _overlay_activation_error()---def _without_routing_overrides(argv: Sequence[str]) -> tuple[list[str], str | None]:- args = list(argv)- cleaned: list[str] = []- selected_model: str | None = None- index = 0- while index < len(args):- argument = args[index]- if argument == "--":- cleaned.extend(args[index:])- break- if argument == "--provider" or argument.startswith("--provider="):- _routing_override_error()- if argument in {"-m", "--model"}:- if index + 1 >= len(args) or args[index + 1] == "--":- _model_value_error()- if selected_model is not None:- _duplicate_model_error()- selected_model = args[index + 1]- index += 2- continue- if argument.startswith("--model="):- value = argument.partition("=")[2]- if not value:- _model_value_error()- if selected_model is not None:- _duplicate_model_error()- selected_model = value- index += 1- continue- if argument.startswith("-m") and len(argument) > 2:- if selected_model is not None:- _duplicate_model_error()- selected_model = argument[2:]- index += 1- continue- cleaned.append(argument)- index += 1- return cleaned, selected_model---def _reject_managed_policy(base_env: Mapping[str, str]) -> None:- if base_env.get("HERMES_MANAGED_DIR", "").strip() or _system_policy_exists():- print(- "fcc-hermes will not replace an existing Hermes managed policy. "- "Use ordinary hermes or remove the administrator-managed scope.",- file=sys.stderr,- )- raise SystemExit(2)---def _system_policy_exists() -> bool:- return os.name != "nt" and Path("/etc/hermes").exists()---def _root_positionals(argv: Sequence[str], *, limit: int) -> list[str]:- before_separator = _before_separator(argv)- positionals: list[str] = []- index = 0- while index < len(before_separator) and len(positionals) < limit:- argument = before_separator[index]- if argument in _GLOBAL_VALUE_OPTIONS:- index += 2- continue- if _is_joined_global_value(argument):- index += 1- continue- if argument in _GLOBAL_OPTIONAL_VALUE_OPTIONS:- if index + 1 < len(before_separator) and not before_separator[- index + 1- ].startswith("-"):- index += 2- else:- index += 1- continue- if argument in _GLOBAL_BOOLEAN_OPTIONS or argument in _PASSTHROUGH_FLAGS:- index += 1- continue- if argument.startswith("-"):- index += 1- continue- positionals.append(argument)- index += 1- return positionals-+ return False-def _second_positional(argv: Sequence[str]) -> str | None:- positionals = _root_positionals(argv, limit=2)- return positionals[1] if len(positionals) == 2 else None--def _next_root_index(argv: Sequence[str], index: int) -> int:- argument = argv[index]- if argument in _GLOBAL_VALUE_OPTIONS:- return min(index + 2, len(argv))- if (- argument in _GLOBAL_OPTIONAL_VALUE_OPTIONS- and index + 1 < len(argv)- and not argv[index + 1].startswith("-")- ):- return index + 2- return index + 1---def _is_joined_global_value(argument: str) -> bool:- if any(- argument.startswith(f"{option}=")- for option in _GLOBAL_VALUE_OPTIONS- if option.startswith("--")- ):- return True- return any(- argument.startswith(option) and len(argument) > len(option)- for option in _GLOBAL_VALUE_OPTIONS- if option.startswith("-") and not option.startswith("--")+def _configure(+ ctx: LaunchContext, args: list[str], files: LaunchResources+) -> PreparedLaunch:+ require_unset_environment(ctx.base_env, ("HERMES_MANAGED_DIR",))+ if os.name != "nt" and Path("/etc/hermes").exists():+ raise ValueError("An existing Hermes managed policy cannot be replaced by FCC.")+ managed = build_hermes_managed_config(+ ctx.models, proxy_root_url=ctx.proxy_root_url, nonce=secrets.token_hex(16))---def _before_separator(argv: Sequence[str]) -> Sequence[str]:- try:- return argv[: argv.index("--")]- except ValueError:- return argv---def _write_private_json(path: Path, payload: Mapping[str, object]) -> None:- descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)- with os.fdopen(descriptor, "w", encoding="utf-8") as output:- json.dump(payload, output, ensure_ascii=True, indent=2)- output.write("\n")---def _run(binary_path: str, args: Sequence[str], env: Mapping[str, str]) -> None:- run_client_process(- command=[binary_path, *args],- env=env,- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,+ path = files.write_json("config.yaml", managed.config)+ env = client_environment(+ ctx.base_env,+ proxy_root_url=ctx.proxy_root_url,+ remove_prefixes=(HERMES_KEY_ENV_PREFIX,),+ updates={+ "HERMES_MANAGED_DIR": str(path.parent),+ "HERMES_INFERENCE_PROVIDER": managed.provider_ref,+ "HERMES_INFERENCE_MODEL": managed.default_model,+ managed.key_env: ctx.auth_token,+ },)---def _routing_override_error() -> Never:- print(- "fcc-hermes owns the Hermes provider. "- "Use ordinary hermes for a different provider.",- file=sys.stderr,+ return PreparedLaunch(+ [ctx.binary_path, *args],+ env,+ NativeCheck(+ ("config", "get", "model.provider", "--json"),+ lambda output: _overlay_loaded(output, managed.provider_ref),+ "Could not activate the FCC Hermes managed provider.",+ timeout_seconds=15.0,+ ),)- raise SystemExit(2)---def _model_value_error() -> Never:- print("fcc-hermes requires a value after --model/-m.", file=sys.stderr)- raise SystemExit(2)--def _duplicate_model_error() -> Never:- print("fcc-hermes accepts only one --model/-m override.", file=sys.stderr)- raise SystemExit(2)--def _temporary_config_error(exc: OSError) -> Never:- print(f"Could not create temporary Hermes configuration: {exc}", file=sys.stderr)- raise SystemExit(1) from None+SPEC = HarnessSpec(+ binary_name="hermes",+ display_name="Hermes Agent",+ install_hint=_INSTALL_HINT,+ configure=_configure,+ catalog_view="responses",+ compatibility_check=NativeCheck(+ ("--version",),+ lambda output: version_at_least(output, _VERSION_PATTERN, (0, 20, 4)),+ "FCC requires Hermes 0.20.4 or newer.",+ ),+)-def _overlay_activation_error() -> Never:- print(- "Hermes did not honor the temporary Free Claude Code route. "- "Check the selected Hermes profile and managed-policy settings.",- file=sys.stderr,- )- raise SystemExit(1)+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/hermes_config.py b/src/free_claude_code/cli/launchers/hermes_config.pyindex e3e9704d..06c213e4 100644--- a/src/free_claude_code/cli/launchers/hermes_config.py+++ b/src/free_claude_code/cli/launchers/hermes_config.py@@ -38,10 +38,9 @@ class HermesManagedConfig:"""Secret-free managed overlay for one attached Hermes process."""config: JsonObject = field(repr=False)- provider_key: strprovider_ref: strkey_env: str- selected_model: str+ default_model: strdef build_hermes_managed_config(@@ -49,7 +48,6 @@ def build_hermes_managed_config(*,proxy_root_url: str,nonce: str,- selected_model: str | None = None,) -> HermesManagedConfig:"""Translate an FCC catalog into one invocation-specific Hermes overlay."""@@ -59,9 +57,7 @@ def build_hermes_managed_config(raise ValueError("Hermes configuration nonce must be alphanumeric")wire_slugs = tuple(model.wire_slug for model in models)- active_model = selected_model or wire_slugs[0]- if active_model not in wire_slugs:- raise ValueError(f"model is not in the FCC catalog: {active_model}")+ active_model = wire_slugs[0]provider_key = f"{HERMES_PROVIDER_PREFIX}{nonce.lower()}"provider_ref = f"custom:{provider_key}"@@ -105,10 +101,9 @@ def build_hermes_managed_config(config["model_overrides"] = {"custom": model_overrides}return HermesManagedConfig(config=config,- provider_key=provider_key,provider_ref=provider_ref,key_env=key_env,- selected_model=active_model,+ default_model=active_model,)diff --git a/src/free_claude_code/cli/launchers/muse.py b/src/free_claude_code/cli/launchers/muse.pyindex 4145c582..9b4d3ec6 100644--- a/src/free_claude_code/cli/launchers/muse.py+++ b/src/free_claude_code/cli/launchers/muse.py@@ -1,31 +1,21 @@-"""Installed `fcc-muse` launcher for attached Muse Code sessions."""+"""Installed Muse Code launcher with a native FCC connection."""-import osimport re-import subprocess-import sys-from collections.abc import Mapping, Sequence-from dataclasses import dataclass-from enum import StrEnum--from free_claude_code.cli.local_http import with_local_proxy_bypass-from free_claude_code.config.loader import get_settings-from free_claude_code.config.server_urls import local_proxy_root_url--from .common import (- preflight_proxy,- proxy_v1_url,- resolve_client_binary,- run_client_process,-)-from .model_catalog import (- ClientModel,- client_models_from_response,- fetch_proxy_models_response,+from collections.abc import Sequence++from free_claude_code.cli.environment import client_environment++from .common import proxy_v1_url+from .resources import LaunchResources+from .runner import (+ HarnessSpec,+ LaunchContext,+ NativeCheck,+ PreparedLaunch,+ launch_harness,+ version_at_least,)-_BINARY_NAME = "muse"-_DISPLAY_NAME = "Muse Code"_INSTALL_HINT = ("Install Muse Code on native Windows with "'`& ([scriptblock]::Create((irm "https://raw.githubusercontent.com/'@@ -33,354 +23,51 @@ _INSTALL_HINT = ("or on macOS/Linux/WSL with ""`curl -fsSL https://dev.meta.ai/install.sh | bash`.")-_MINIMUM_VERSION = (0, 2, 1)-_VERSION_TIMEOUT_SECONDS = 5.0_VERSION_PATTERN = re.compile(r"(?m)^\s*Muse Code\s+(\d+)\.(\d+)\.(\d+)"r"(?:\s+\([^\r\n]+\))?\s*$")-_PASSTHROUGH_COMMANDS = frozenset(- {- "auth",- "config",- "export",- "init",- "login",- "logout",- "sandbox",- "session-message",- "skills",- "trace",- }-)-_PASSTHROUGH_FLAGS = frozenset({"-h", "--help", "-V", "--version"})-_ROOT_VALUE_OPTIONS = frozenset(- {- "--agents",- "--provider",- "--preset",- "--model",- "--reasoning-effort",- "--base-url",- "--image",- "--workspace",- "--worktree-base",- "--worktree-existing",- "--approval-mode",- "--approval-judge",- "--echo-delay-ms",- "--sandbox-network",- }-)-_ROOT_OPTIONAL_VALUE_OPTIONS = frozenset({"-w", "--worktree"})-_WORKTREE_VALUES = frozenset({"off", "create", "existing"})-_ROOT_BOOLEAN_OPTIONS = frozenset(- {- "--parallel-tool-calls",- "--no-parallel-tool-calls",- "--subagent-worktree-isolation",- "--no-session-log",- "--yolo",- "--trust-workspace",- "--disable-approval",- "--disable-sandbox",- "--disable-write",- "--disable-shell",- "--enable-shell-tool",- }-)-_ROUTE_OVERRIDE_OPTIONS = frozenset({"--provider", "--base-url"})_ROUTING_ENV_KEYS = frozenset({"META_API_KEY", "MUSE_MODEL", "MUSE_CUSTOM_HEADERS", "MUSE_WWW_ROUTING"})-class MuseInvocationMode(StrEnum):- """How `fcc-muse` treats one Muse invocation."""-- PASSTHROUGH = "passthrough"- TUI = "tui"- EXEC = "exec"- RESUME = "resume"---@dataclass(frozen=True, slots=True)-class MuseInvocation:- """The minimal Muse command classification FCC needs for flag placement."""-- mode: MuseInvocationMode- command_index: int | None = None---def launch(argv: Sequence[str] | None = None) -> None:- """Launch one attached Muse Code process through FCC."""-- args = list(sys.argv[1:] if argv is None else argv)- binary_path = resolve_client_binary(- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )- invocation = classify_muse_invocation(args)- if invocation.mode is MuseInvocationMode.PASSTHROUGH:- _run(binary_path, args, os.environ)- return-- _reject_routing_overrides(args, invocation)- require_compatible_muse(binary_path)-- settings = get_settings()- auth_token = settings.proxy_auth_token.strip()- if not auth_token:- print("Free Claude Code proxy authentication token is empty.", file=sys.stderr)- raise SystemExit(1)-- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)-- try:- models = client_models_from_response(- fetch_proxy_models_response(proxy_root_url, auth_token)- )- if not models:- raise ValueError("model catalog contains no routable models")- except Exception as exc:- print(f"Could not prepare the Muse FCC model catalog: {exc}", file=sys.stderr)- raise SystemExit(1) from None-- try:- selected_model, cleaned_args = _select_and_remove_model(args, models)- except ValueError as exc:- print(f"Invalid Muse Code model selection: {exc}", file=sys.stderr)- raise SystemExit(2) from None-- child_env = build_muse_launcher_env(- proxy_root_url=proxy_root_url,- auth_token=auth_token,- base_env=os.environ,- )- command_args = _routed_args(- cleaned_args,- invocation.mode,- proxy_root_url=proxy_root_url,- selected_model=selected_model,- )- _run(binary_path, command_args, child_env)---def classify_muse_invocation(argv: Sequence[str]) -> MuseInvocation:- """Classify only Muse surfaces whose attached lifecycle FCC can own."""-- before_separator = _before_separator(argv)- if any(argument in _PASSTHROUGH_FLAGS for argument in before_separator):- return MuseInvocation(MuseInvocationMode.PASSTHROUGH)- if before_separator and before_separator[0] in _PASSTHROUGH_COMMANDS:- return MuseInvocation(MuseInvocationMode.PASSTHROUGH)- if before_separator and before_separator[0] == "exec":- return MuseInvocation(MuseInvocationMode.EXEC, command_index=0)-- positional_index = _first_root_positional_index(before_separator)- if positional_index is not None and before_separator[positional_index] == "resume":- return MuseInvocation(MuseInvocationMode.RESUME, command_index=positional_index)- return MuseInvocation(MuseInvocationMode.TUI)---def muse_binary_version(binary_path: str) -> tuple[int, int, int] | None:- """Read the released Muse semantic version without invoking a shell."""-- try:- result = subprocess.run(- [binary_path, "--version"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- timeout=_VERSION_TIMEOUT_SECONDS,- )- except OSError, subprocess.TimeoutExpired:- return None- if result.returncode != 0:- return None-- match = _VERSION_PATTERN.search(result.stdout)- if match is None:- return None- return int(match.group(1)), int(match.group(2)), int(match.group(3))---def require_compatible_muse(binary_path: str) -> None:- """Exit unless Muse satisfies FCC's released base-URL contract."""-- version = muse_binary_version(binary_path)- if version is not None and version >= _MINIMUM_VERSION:- return-- minimum = ".".join(str(part) for part in _MINIMUM_VERSION)- print(- f"The Muse Code CLI at {binary_path} must be at least version {minimum}.",- file=sys.stderr,+def _configure(+ ctx: LaunchContext, args: list[str], _files: LaunchResources+) -> PreparedLaunch:+ connection = ["--provider", "meta", "--base-url", proxy_v1_url(ctx.proxy_root_url)]+ if args and args[0] in {"exec", "resume"}:+ command = [ctx.binary_path, args[0], *connection, *args[1:]]+ else:+ command = [ctx.binary_path, *connection, *args]+ return PreparedLaunch(+ command,+ client_environment(+ ctx.base_env,+ proxy_root_url=ctx.proxy_root_url,+ remove_keys=tuple(_ROUTING_ENV_KEYS),+ remove_prefixes=("FCC_MUSE_",),+ updates={+ "META_API_KEY": ctx.auth_token,+ "MUSE_MODEL": ctx.models[0].wire_slug,+ },+ ),)- print(_INSTALL_HINT, file=sys.stderr)- raise SystemExit(1)---def build_muse_launcher_env(- *,- proxy_root_url: str,- auth_token: str,- base_env: Mapping[str, str],-) -> dict[str, str]:- """Build the child-only Muse route while preserving native Muse state."""-- filtered = {- key: value- for key, value in base_env.items()- if not key.startswith("FCC_MUSE_") and key not in _ROUTING_ENV_KEYS- }- env = with_local_proxy_bypass(filtered, proxy_root_url=proxy_root_url)- env["META_API_KEY"] = auth_token- return env--def _reject_routing_overrides(argv: Sequence[str], invocation: MuseInvocation) -> None:- for argument in _before_separator(argv):- if argument in _ROUTE_OVERRIDE_OPTIONS or any(- argument.startswith(f"{option}=") for option in _ROUTE_OVERRIDE_OPTIONS- ):- print(- "fcc-muse owns the attached Muse provider and base URL. "- "Use ordinary muse for a native Meta route.",- file=sys.stderr,- )- raise SystemExit(2)- if invocation.mode is MuseInvocationMode.EXEC and argument == "--api-key-stdin":- print(- "fcc-muse supplies the attached Muse credential. "- "Use ordinary muse exec with --api-key-stdin for a native route.",- file=sys.stderr,- )- raise SystemExit(2)--def _select_and_remove_model(- argv: Sequence[str], models: Sequence[ClientModel]-) -> tuple[str, list[str]]:- selected: str | None = None- cleaned: list[str] = []- index = 0- while index < len(argv):- argument = argv[index]- if argument == "--":- cleaned.extend(argv[index:])- break- if argument == "--model":- if index + 1 >= len(argv) or not argv[index + 1]:- raise ValueError("--model requires a model value")- if selected is not None:- raise ValueError("multiple --model values are not supported")- selected = argv[index + 1]- index += 2- continue- if argument.startswith("--model="):- value = argument.partition("=")[2]- if not value:- raise ValueError("--model requires a model value")- if selected is not None:- raise ValueError("multiple --model values are not supported")- selected = value- index += 1- continue- cleaned.append(argument)- index += 1-- chosen = selected or models[0].wire_slug- available = {model.wire_slug for model in models}- if chosen not in available:- raise ValueError(f"model {chosen!r} is not in the current FCC catalog")- return chosen, cleaned---def _routed_args(- argv: Sequence[str],- mode: MuseInvocationMode,- *,- proxy_root_url: str,- selected_model: str,-) -> list[str]:- route = [- "--provider",- "meta",- "--base-url",- proxy_v1_url(proxy_root_url),- "--model",- selected_model,- ]- args = list(argv)- if mode is MuseInvocationMode.EXEC:- return ["exec", *route, *args[1:]]- if mode is MuseInvocationMode.RESUME:- command_index = _first_root_positional_index(_before_separator(args))- if command_index is None or args[command_index] != "resume":- raise ValueError("Muse resume command could not be located")- return [*args[: command_index + 1], *route, *args[command_index + 1 :]]- return [*route, *args]---def _first_root_positional_index(argv: Sequence[str]) -> int | None:- index = 0- while index < len(argv):- argument = argv[index]- if argument == "--":- return index + 1 if index + 1 < len(argv) else None- if argument in _ROOT_VALUE_OPTIONS:- index += 2- continue- if _is_joined_root_value_option(argument):- index += 1- continue- if argument in _ROOT_OPTIONAL_VALUE_OPTIONS:- if index + 1 < len(argv) and argv[index + 1] in _WORKTREE_VALUES:- index += 2- else:- index += 1- continue- if argument in _ROOT_BOOLEAN_OPTIONS or argument in _PASSTHROUGH_FLAGS:- index += 1- continue- if argument.startswith("-"):- return None- return index- return None---def _is_joined_root_value_option(argument: str) -> bool:- if any(- argument.startswith(f"{option}=")- for option in _ROOT_VALUE_OPTIONS | _ROOT_OPTIONAL_VALUE_OPTIONS- if option.startswith("--")- ):- return True- return argument.startswith("-w") and len(argument) > 2---def _before_separator(argv: Sequence[str]) -> Sequence[str]:- try:- return argv[: argv.index("--")]- except ValueError:- return argv+SPEC = HarnessSpec(+ binary_name="muse",+ display_name="Muse Code",+ install_hint=_INSTALL_HINT,+ configure=_configure,+ catalog_view="responses",+ compatibility_check=NativeCheck(+ ("--version",),+ lambda output: version_at_least(output, _VERSION_PATTERN, (0, 2, 1)),+ "FCC requires Muse Code 0.2.1 or newer.",+ ),+)-def _run(binary_path: str, args: Sequence[str], env: Mapping[str, str]) -> None:- run_client_process(- command=[binary_path, *args],- env=env,- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/opencode.py b/src/free_claude_code/cli/launchers/opencode.pyindex 403ce352..e6bef18b 100644--- a/src/free_claude_code/cli/launchers/opencode.py+++ b/src/free_claude_code/cli/launchers/opencode.py@@ -1,229 +1,69 @@-"""Installed `fcc-opencode` launcher for stable OpenCode v1."""+"""Installed OpenCode launcher with process-local FCC configuration."""import json-import osimport re-import subprocess-import sys-import tempfile-from collections.abc import Mapping, Sequence-from pathlib import Path-from typing import Never+from collections.abc import Sequence-from free_claude_code.cli.local_http import with_local_proxy_bypass-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.core.json_types import JsonValue+from free_claude_code.cli.environment import (+ client_environment,+ require_unset_environment,+)-from .common import preflight_proxy, resolve_client_binary, run_client_process-from .model_catalog import client_models_from_response, fetch_proxy_models_response-from .opencode_config import OPENCODE_API_KEY_ENV, OpenCodeConfig, build_opencode_config+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,+)-_BINARY_NAME = "opencode"-_DISPLAY_NAME = "OpenCode CLI"-_INSTALL_HINT = "Install OpenCode from: https://opencode.ai/docs/"-_MINIMUM_VERSION = (1, 18, 18)-_VERSION_TIMEOUT_SECONDS = 5.0_VERSION_PATTERN = re.compile(r"(?m)^\s*(?:(?:opencode(?:\s+version)?\s+)|v)?"r"(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?\s*$")-_PASSTHROUGH_COMMANDS = frozenset({"auth", "upgrade", "uninstall", "completion"})-_PASSTHROUGH_FLAGS = frozenset({"--help", "-h", "--version", "-v"})_PROCESS_CONFIG_KEYS = ("OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT")-def launch(argv: Sequence[str] | None = None) -> None:- """Launch OpenCode with one child-scoped FCC provider and model catalog."""-- args = list(sys.argv[1:] if argv is None else argv)- binary_path = resolve_client_binary(- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )-- if is_opencode_passthrough(args):- run_client_process(- command=[binary_path, *args],- env=os.environ,- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )- return-- require_compatible_opencode(binary_path)- _reject_process_config_conflicts(os.environ)-- settings = get_settings()- auth_token = settings.proxy_auth_token.strip()- if not auth_token:- print(- "Free Claude Code proxy authentication token is empty.",- file=sys.stderr,- )- raise SystemExit(1)-- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)-- try:- models = client_models_from_response(- fetch_proxy_models_response(proxy_root_url, auth_token)- )- config = build_opencode_config(models, proxy_root_url=proxy_root_url)- except Exception as exc:- print(- f"Could not prepare the OpenCode FCC model catalog: {exc}",- file=sys.stderr,- )- raise SystemExit(1) from None-- _run_with_temporary_config(- binary_path=binary_path,- args=args,- config=config,- proxy_root_url=proxy_root_url,- auth_token=auth_token,- )---def is_opencode_passthrough(argv: Sequence[str]) -> bool:- """Return whether OpenCode should run without requiring a live FCC server."""-- return bool(argv) and (- argv[0] in _PASSTHROUGH_COMMANDS- or any(argument in _PASSTHROUGH_FLAGS for argument in argv)- )---def require_compatible_opencode(binary_path: str) -> None:- """Exit unless the installed OpenCode satisfies FCC's stable-v1 contract."""-- version = opencode_binary_version(binary_path)- if version is not None and version >= _MINIMUM_VERSION:- return-- minimum = ".".join(str(part) for part in _MINIMUM_VERSION)- print(- f"The OpenCode CLI at {binary_path} must be a stable release "- f"at least version {minimum}.",- file=sys.stderr,- )- print("Upgrade it with: opencode upgrade", file=sys.stderr)- raise SystemExit(126)---def opencode_binary_version(binary_path: str) -> tuple[int, int, int] | None:- """Read a semantic OpenCode version without invoking a shell."""-- try:- result = subprocess.run(- [binary_path, "--version"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- timeout=_VERSION_TIMEOUT_SECONDS,- )- except OSError, subprocess.TimeoutExpired:- return None- if result.returncode != 0:- return None-- match = _VERSION_PATTERN.search(result.stdout)- if match is None:- return None- return int(match.group(1)), int(match.group(2)), int(match.group(3))---def build_opencode_launcher_env(- *,- proxy_root_url: str,- auth_token: str,- config_path: Path,- overlay: Mapping[str, JsonValue],- base_env: Mapping[str, str],-) -> dict[str, str]:- """Build an isolated child environment without persisting FCC credentials."""-- env = with_local_proxy_bypass(- {- key: value- for key, value in base_env.items()- if not key.startswith("FCC_OPENCODE_") and key not in _PROCESS_CONFIG_KEYS- },- proxy_root_url=proxy_root_url,- )- env["OPENCODE_CONFIG"] = str(config_path)- env["OPENCODE_CONFIG_CONTENT"] = json.dumps(- overlay,- ensure_ascii=True,- separators=(",", ":"),+def _configure(+ ctx: LaunchContext, args: list[str], files: LaunchResources+) -> PreparedLaunch:+ require_unset_environment(ctx.base_env, _PROCESS_CONFIG_KEYS)+ config = build_opencode_config(ctx.models, proxy_root_url=ctx.proxy_root_url)+ path = files.write_json("opencode.json", config.file)+ return PreparedLaunch(+ [ctx.binary_path, *args],+ client_environment(+ ctx.base_env,+ proxy_root_url=ctx.proxy_root_url,+ remove_keys=_PROCESS_CONFIG_KEYS,+ remove_prefixes=("FCC_OPENCODE_",),+ updates={+ "OPENCODE_CONFIG": str(path),+ "OPENCODE_CONFIG_CONTENT": json.dumps(+ config.overlay, separators=(",", ":")+ ),+ OPENCODE_API_KEY_ENV: ctx.auth_token,+ },+ ),)- env[OPENCODE_API_KEY_ENV] = auth_token- return env---def _reject_process_config_conflicts(base_env: Mapping[str, str]) -> None:- for key in _PROCESS_CONFIG_KEYS:- if base_env.get(key, "").strip():- print(- f"{key} is already set. Unset it before running fcc-opencode; "- "ordinary opencode remains unchanged.",- file=sys.stderr,- )- raise SystemExit(1)--def _run_with_temporary_config(- *,- binary_path: str,- args: Sequence[str],- config: OpenCodeConfig,- proxy_root_url: str,- auth_token: str,-) -> None:- try:- temp_config = tempfile.TemporaryDirectory(prefix="fcc-opencode-")- except OSError as exc:- _temporary_config_error(exc)- with temp_config as temp_directory:- config_path = Path(temp_directory, "opencode.json")- try:- config_path.write_text(- json.dumps(config.file, ensure_ascii=True, indent=2) + "\n",- encoding="utf-8",- )- except OSError as exc:- _temporary_config_error(exc)-- run_client_process(- command=[binary_path, *args],- env=build_opencode_launcher_env(- proxy_root_url=proxy_root_url,- auth_token=auth_token,- config_path=config_path,- overlay=config.overlay,- base_env=os.environ,- ),- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=_INSTALL_HINT,- )+SPEC = HarnessSpec(+ binary_name="opencode",+ display_name="OpenCode CLI",+ install_hint="Install OpenCode from: https://opencode.ai/docs/",+ configure=_configure,+ catalog_view="responses",+ compatibility_check=NativeCheck(+ ("--version",),+ lambda output: version_at_least(output, _VERSION_PATTERN, (1, 18, 18)),+ "FCC requires OpenCode 1.18.18 or newer.",+ ),+)-def _temporary_config_error(exc: OSError) -> Never:- print(- f"Could not create temporary OpenCode configuration: {exc}",- file=sys.stderr,- )- raise SystemExit(1) from None+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/pi.py b/src/free_claude_code/cli/launchers/pi.pyindex 3f390586..b1ec6665 100644--- a/src/free_claude_code/cli/launchers/pi.py+++ b/src/free_claude_code/cli/launchers/pi.py@@ -1,168 +1,72 @@-"""Installed `fcc-pi` launcher."""+"""Installed Pi launcher using the bundled FCC provider extension."""-import os-import subprocessimport sys-from collections.abc import Mapping, Sequence+from collections.abc import Sequencefrom pathlib import Path-from free_claude_code.cli.local_http import with_local_proxy_bypass-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.cli.environment import client_environment-from .common import preflight_proxy, resolve_client_binary, run_client_process--_API_KEY_ENV = "FCC_PI_API_KEY"-_BASE_URL_ENV = "FCC_PI_BASE_URL"-_BINARY_NAME = "pi"-_DISPLAY_NAME = "Pi"-_HELP_TIMEOUT_SECONDS = 5.0-_MODEL_SCOPE = "free-claude-code/**"-_REQUIRED_HELP_MARKERS = ("--extension", "--models")-_PASSTHROUGH_COMMANDS = frozenset(- {"config", "install", "list", "remove", "uninstall", "update"}+from .resources import LaunchResources+from .runner import (+ HarnessSpec,+ LaunchContext,+ NativeCheck,+ PreparedLaunch,+ launch_harness,)-_PASSTHROUGH_FLAGS = frozenset({"--help", "-h", "--version", "-v"})-def launch(argv: Sequence[str] | None = None) -> None:- """Launch Pi with a process-local Free Claude Code provider."""+def pi_extension_path() -> Path:+ return Path(__file__).with_name("pi_extension.ts").resolve()- args = list(sys.argv[1:] if argv is None else argv)- install_hint = pi_install_hint()- binary_path = resolve_client_binary(- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=install_hint,- )- if not pi_binary_is_compatible(binary_path):- print(- f"The 'pi' command at {binary_path} is not a compatible Pi Coding Agent.",- file=sys.stderr,- )- print(install_hint, file=sys.stderr)- raise SystemExit(126)- if is_pi_passthrough(args):- run_client_process(- command=[binary_path, *args],- env=os.environ,- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=install_hint,- )- return+def pi_install_hint(platform: str | None = None) -> str:+ if (platform or sys.platform) == "win32":+ return 'Install Pi with: powershell -c "irm https://pi.dev/install.ps1 | iex"'+ return "Install Pi with: curl -fsSL https://pi.dev/install.sh | sh"- settings = get_settings()- proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- print(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",- file=sys.stderr,- )- print("Start it in another terminal with: fcc-server", file=sys.stderr)- raise SystemExit(1)+def _configure(+ ctx: LaunchContext, args: list[str], _files: LaunchResources+) -> PreparedLaunch:extension_path = pi_extension_path()if not extension_path.is_file():- print(- "Free Claude Code's bundled Pi extension is missing. Reinstall FCC.",- file=sys.stderr,+ raise ValueError(+ "Free Claude Code's bundled Pi extension is missing. Reinstall FCC.")- raise SystemExit(1)-- run_client_process(- command=build_pi_launcher_command(- binary_path=binary_path,- extension_path=extension_path,- argv=args,+ return PreparedLaunch(+ [+ ctx.binary_path,+ "-e",+ str(extension_path),+ "--models",+ "free-claude-code/**",+ *args,+ ],+ client_environment(+ ctx.base_env,+ proxy_root_url=ctx.proxy_root_url,+ remove_prefixes=("FCC_PI_",),+ updates={+ "FCC_PI_BASE_URL": ctx.proxy_root_url.rstrip("/"),+ "FCC_PI_API_KEY": ctx.auth_token,+ },),- env=build_pi_launcher_env(- proxy_root_url=proxy_root_url,- auth_token=settings.proxy_auth_token,- base_env=os.environ,- ),- binary_name=_BINARY_NAME,- display_name=_DISPLAY_NAME,- install_hint=install_hint,- )---def build_pi_launcher_command(- *,- binary_path: str,- extension_path: Path,- argv: Sequence[str],-) -> list[str]:- """Return a Pi session command with ephemeral FCC provider registration."""-- return [- binary_path,- "-e",- str(extension_path),- "--models",- _MODEL_SCOPE,- *argv,- ]---def build_pi_launcher_env(- *,- proxy_root_url: str,- auth_token: str,- base_env: Mapping[str, str],-) -> dict[str, str]:- """Return a Pi environment containing only FCC-owned proxy variables."""-- env = with_local_proxy_bypass(- {- key: value- for key, value in base_env.items()- if not key.startswith("FCC_PI_")- },- proxy_root_url=proxy_root_url,- )- env[_BASE_URL_ENV] = proxy_root_url.rstrip("/")- env[_API_KEY_ENV] = auth_token- return env---def is_pi_passthrough(argv: Sequence[str]) -> bool:- """Return whether Pi must receive argv unchanged as a non-session command."""-- return bool(argv) and (- argv[0] in _PASSTHROUGH_COMMANDS or argv[0] in _PASSTHROUGH_FLAGS)-def pi_extension_path() -> Path:- """Return the absolute installed path to the bundled Pi extension."""-- return Path(__file__).with_name("pi_extension.ts").resolve()---def pi_binary_is_compatible(binary_path: str) -> bool:- """Return whether an executable exposes the Pi features FCC requires."""-- try:- result = subprocess.run(- [binary_path, "--help"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- timeout=_HELP_TIMEOUT_SECONDS,- )- except OSError, subprocess.TimeoutExpired:- return False- return result.returncode == 0 and all(- marker in result.stdout for marker in _REQUIRED_HELP_MARKERS- )-+SPEC = HarnessSpec(+ binary_name="pi",+ display_name="Pi",+ install_hint=pi_install_hint(),+ configure=_configure,+ compatibility_check=NativeCheck(+ ("--help",),+ lambda output: all(marker in output for marker in ("--extension", "--models")),+ "The 'pi' command is not a compatible Pi Coding Agent.",+ ),+)-def pi_install_hint(platform: str | None = None) -> str:- """Return Pi's official installer command for the current platform."""- if (platform or sys.platform) == "win32":- return 'Install Pi with: powershell -c "irm https://pi.dev/install.ps1 | iex"'- return "Install Pi with: curl -fsSL https://pi.dev/install.sh | sh"+def launch(argv: Sequence[str] | None = None) -> None:+ launch_harness(SPEC, argv)diff --git a/src/free_claude_code/cli/launchers/resources.py b/src/free_claude_code/cli/launchers/resources.pynew file mode 100644index 00000000..fd3e4654--- /dev/null+++ b/src/free_claude_code/cli/launchers/resources.py@@ -0,0 +1,42 @@+"""Private native configuration owned by one launcher process lifetime."""++import json+import os+import tempfile+from contextlib import ExitStack+from pathlib import Path++from free_claude_code.config.paths import launcher_temp_dir_path+from free_claude_code.core.json_types import JsonValue+++class LaunchResources:+ """Lazily allocate files and register cleanup with the shared launch scope."""++ def __init__(self, stack: ExitStack) -> None:+ self._stack = stack+ self._directory: Path | None = None++ @property+ def directory(self) -> Path:+ if self._directory is None:+ base = launcher_temp_dir_path()+ base.mkdir(parents=True, mode=0o700, exist_ok=True)+ if os.name != "nt":+ base.chmod(0o700)+ directory = self._stack.enter_context(+ tempfile.TemporaryDirectory(prefix="fcc-", dir=base)+ )+ self._directory = Path(directory)+ return self._directory++ def write_json(self, filename: str, payload: JsonValue) -> Path:+ """Write JSON, also accepted by native YAML readers, without overwrites."""++ path = self.directory / filename+ path.parent.mkdir(parents=True, mode=0o700, exist_ok=True)+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(descriptor, "w", encoding="utf-8") as output:+ json.dump(payload, output, ensure_ascii=True, indent=2)+ output.write("\n")+ return pathdiff --git a/src/free_claude_code/cli/launchers/runner.py b/src/free_claude_code/cli/launchers/runner.pynew file mode 100644index 00000000..7e05d37e--- /dev/null+++ b/src/free_claude_code/cli/launchers/runner.py@@ -0,0 +1,171 @@+"""One setup, execution, and cleanup path for installed native harnesses."""++import os+import re+import subprocess+import sys+from collections.abc import Callable, Mapping, Sequence+from contextlib import ExitStack+from dataclasses import dataclass, field+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 (+ 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."""++ args: tuple[str, ...]+ accepts: Callable[[str], bool]+ failure_message: str+ timeout_seconds: float = 5.0+++@dataclass(frozen=True, slots=True)+class LaunchContext:+ binary_path: str+ settings: Settings = field(repr=False)+ proxy_root_url: str+ auth_token: str = field(repr=False)+ base_env: Mapping[str, str] = field(repr=False)+ models: tuple[ClientModel, ...]+++@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+ display_name: str+ install_hint: str+ configure: Callable[[LaunchContext, list[str], LaunchResources], PreparedLaunch]+ catalog_view: Literal["messages", "responses"] | None = None+ compatibility_check: NativeCheck | None = None+++class LaunchError(Exception):+ def __init__(self, message: str, exit_code: int = 1) -> None:+ super().__init__(message)+ self.exit_code = exit_code+++def version_at_least(+ output: str, pattern: re.Pattern[str], minimum: tuple[int, int, int]+) -> bool:+ match = pattern.search(output)+ return match is not None and tuple(map(int, match.groups())) >= minimum+++def _check_native(+ binary_path: str,+ check: NativeCheck,+ env: Mapping[str, str],+ *,+ exit_code: int,+ install_hint: str = "",+) -> None:+ try:+ result = subprocess.run(+ [binary_path, *check.args],+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=check.timeout_seconds,+ env=dict(env),+ )+ if result.returncode == 0 and check.accepts(result.stdout):+ return+ except OSError, subprocess.TimeoutExpired:+ pass+ message = check.failure_message+ if install_hint:+ message += f"\n{install_hint}"+ raise LaunchError(message, exit_code)+++def launch_harness(spec: HarnessSpec, argv: Sequence[str] | None = None) -> None:+ """Prepare the FCC connection and leave command semantics to the harness."""++ args = list(sys.argv[1:] if argv is None else argv)+ base_env = dict(os.environ)+ auth_token = base_env.get("ANTHROPIC_AUTH_TOKEN", "")+ stage = "load settings"+ try:+ binary_path = resolve_client_binary(+ binary_name=spec.binary_name,+ display_name=spec.display_name,+ install_hint=spec.install_hint,+ )+ if spec.compatibility_check:+ _check_native(+ binary_path,+ spec.compatibility_check,+ base_env,+ exit_code=126,+ install_hint=spec.install_hint,+ )+ settings = get_settings()+ auth_token = settings.proxy_auth_token.strip()+ if not auth_token:+ raise LaunchError("Free Claude Code proxy authentication token is empty.")+ proxy_root_url = local_proxy_root_url(settings)+ if error := preflight_proxy(proxy_root_url):+ raise LaunchError(+ f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}\n"+ "Start it in another terminal with: fcc-server"+ )+ models: tuple[ClientModel, ...] = ()+ if spec.catalog_view is not None:+ stage = "prepare model catalog"+ models = client_models_from_response(+ fetch_proxy_models_response(+ proxy_root_url, auth_token, view=spec.catalog_view+ )+ )+ if not models:+ raise ValueError("model catalog contains no routable models")+ context = LaunchContext(+ binary_path, settings, proxy_root_url, auth_token, base_env, models+ )+ with ExitStack() as stack:+ stage = "prepare configuration"+ prepared = spec.configure(context, args, LaunchResources(stack))+ if prepared.activation_check:+ _check_native(+ binary_path, prepared.activation_check, prepared.env, exit_code=1+ )+ stage = "start process"+ run_client_process(+ command=prepared.command,+ env=prepared.env,+ binary_name=spec.binary_name,+ display_name=spec.display_name,+ install_hint=spec.install_hint,+ )+ except (LaunchError, OSError, ValueError) as exc:+ message = (+ str(exc)+ if isinstance(exc, LaunchError)+ else f"Could not {stage} for {spec.display_name}: {exc}"+ )+ if auth_token:+ message = message.replace(auth_token, "[redacted]")+ print(message, file=sys.stderr)+ raise SystemExit(exc.exit_code if isinstance(exc, LaunchError) else 1) from Nonediff --git a/src/free_claude_code/config/paths.py b/src/free_claude_code/config/paths.pyindex b508b6ee..6021c1b8 100644--- a/src/free_claude_code/config/paths.py+++ b/src/free_claude_code/config/paths.py@@ -15,7 +15,7 @@ OPENAI_AUTH_FILENAME = "openai.json"OPENAI_AUTH_LOCK_FILENAME = "openai.lock"CONFIG_LOCK_FILENAME = "config.lock"FCC_TEMP_DIRNAME = "tmp"-AIDER_TEMP_DIRNAME = "aider"+LAUNCHER_TEMP_DIRNAME = "launchers"CHAT_STATE_DIRNAME = "chat"CHAT_DATABASE_FILENAME = "chat.db"CHAT_LOCK_FILENAME = "chat.lock"@@ -39,10 +39,10 @@ def config_lock_path() -> Path:return config_dir_path() / CONFIG_LOCK_FILENAME-def aider_temp_dir_path() -> Path:- """Return the base directory for managed per-launch Aider files."""+def launcher_temp_dir_path() -> Path:+ """Return the base directory for private native launcher configuration."""- return config_dir_path() / FCC_TEMP_DIRNAME / AIDER_TEMP_DIRNAME+ return config_dir_path() / FCC_TEMP_DIRNAME / LAUNCHER_TEMP_DIRNAMEdef chat_state_dir_path() -> Path:diff --git a/src/free_claude_code/runtime/codex_catalog.py b/src/free_claude_code/runtime/codex_catalog.pyindex 870a4913..2ff30612 100644--- a/src/free_claude_code/runtime/codex_catalog.py+++ b/src/free_claude_code/runtime/codex_catalog.py@@ -11,6 +11,7 @@ from free_claude_code.cli.launchers.codex_model_catalog import (build_codex_model_catalog,write_codex_model_catalog,)+from free_claude_code.cli.launchers.model_catalog import client_models_from_responsefrom free_claude_code.config.paths import codex_model_catalog_path@@ -44,7 +45,9 @@ class CodexModelCatalogPublisher:view=ModelCatalogView.RESPONSES,)catalog = build_codex_model_catalog(- models_response.model_dump(by_alias=True, exclude_none=True)+ client_models_from_response(+ models_response.model_dump(by_alias=True, exclude_none=True)+ ))models = catalog.get("models")if not isinstance(models, list) or not models:diff --git a/tests/cli/conftest.py b/tests/cli/conftest.pynew file mode 100644index 00000000..c84a0f8e--- /dev/null+++ b/tests/cli/conftest.py@@ -0,0 +1,121 @@+"""Launcher tests exercise public entrypoints without native processes or network."""++import io+import json+import subprocess+from collections.abc import Callable, Mapping+from dataclasses import dataclass, field+from pathlib import Path+from urllib.request import Request++import pytest++from free_claude_code.cli import local_http+from free_claude_code.core.json_types import JsonObject+++class JsonResponse(io.BytesIO):+ status = 200+++@dataclass+class LaunchCapture:+ requests: list[Request] = field(default_factory=list)+ probes: list[list[str]] = field(default_factory=list)+ commands: list[list[str]] = field(default_factory=list)+ environments: list[dict[str, str]] = field(default_factory=list)+ catalog: JsonObject = field(+ default_factory=lambda: {+ "data": [+ {+ "id": "nvidia_nim/catalog-model:variant",+ "provider_model_ref": "nvidia_nim/catalog-model:variant",+ "supportsReasoning": False,+ "inputModalities": ["text", "image"],+ "contextWindow": 32000,+ "maxCompletionTokens": 4096,+ }+ ],+ }+ )+ catalog_error: Exception | None = None+ health_error: Exception | None = None+ on_start: Callable[[list[str], Mapping[str, str]], None] | None = None+ exit_code: int = 23+ versions: dict[str, str] = field(+ default_factory=lambda: {+ "pi": "Pi Coding Agent --extension --models",+ "opencode": "1.18.18",+ "cline": "3.0.55",+ "hermes": "Hermes Agent 0.20.4",+ "dsh": "0.1.0-rc.8",+ "grok": '{"currentVersion":"1.0.5"}',+ "muse": "Muse Code 1.0.3 (1.0.3-R2198.1)",+ }+ )++ def open(self, request: Request, *, timeout: float) -> JsonResponse:+ self.requests.append(request)+ if request.full_url.endswith("/health"):+ if self.health_error:+ raise self.health_error+ return JsonResponse(b"{}")+ assert "/v1/models?view=" in request.full_url+ assert request.get_header("Authorization") == "Bearer launcher-test-token"+ if self.catalog_error:+ raise self.catalog_error+ return JsonResponse(json.dumps(self.catalog).encode())++ def probe(+ self, command: list[str], **kwargs: object+ ) -> subprocess.CompletedProcess[str]:+ self.probes.append(command)+ if command[1:] == ["config", "get", "model.provider", "--json"]:+ env = kwargs["env"]+ assert isinstance(env, Mapping)+ config = json.loads(+ (Path(env["HERMES_MANAGED_DIR"]) / "config.yaml").read_text()+ )+ return subprocess.CompletedProcess(+ command, 0, json.dumps(config["model"]["provider"]), ""+ )+ return subprocess.CompletedProcess(command, 0, self.versions[command[0]], "")++ def start(self, command: list[str], *, env: Mapping[str, str]) -> object:+ self.commands.append(command)+ self.environments.append(dict(env))+ if self.on_start:+ self.on_start(command, env)+ capture = self++ class Process:+ pid = 0++ def wait(self) -> int:+ return capture.exit_code++ return Process()+++def launch_capture(monkeypatch: pytest.MonkeyPatch) -> LaunchCapture:+ from free_claude_code.cli.launchers import common++ capture = LaunchCapture()+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "launcher-test-token")+ monkeypatch.setenv("HOST", "127.0.0.1")+ monkeypatch.setenv("PORT", "8182")+ monkeypatch.setenv("MODEL", "nvidia_nim/catalog-model:variant")+ for key in (+ "OPENCODE_CONFIG",+ "OPENCODE_CONFIG_CONTENT",+ "GROK_CONFIG",+ "GROK_CONFIG_FILE",+ "HERMES_MANAGED_DIR",+ ):+ monkeypatch.delenv(key, raising=False)+ monkeypatch.setattr(common.shutil, "which", lambda name: name)+ monkeypatch.setattr(local_http._DIRECT_OPENER, "open", capture.open)+ monkeypatch.setattr(subprocess, "run", capture.probe)+ monkeypatch.setattr(subprocess, "Popen", capture.start)+ return capturediff --git a/tests/cli/test_aider_config.py b/tests/cli/test_aider_config.pyindex ad86c571..e24612f5 100644--- a/tests/cli/test_aider_config.py+++ b/tests/cli/test_aider_config.py@@ -46,47 +46,43 @@ def test_aider_config_projects_messages_route_and_canonical_catalog() -> None:api_key_env="FCC_AIDER_PROXY_AUTH_A1B2C3",)- assert config.settings == [- {- "name": "aider/extra_params",- "extra_params": {- "api_base": "http://127.0.0.1:9191/v1/messages",- "api_key": "os.environ/FCC_AIDER_PROXY_AUTH_A1B2C3",- },- },- {- "name": "anthropic/nvidia_nim/vendor/model",- "accepts_settings": ["reasoning_effort"],- },- {- "name": "anthropic/ollama_cloud/qwen3-coder:480b",- "accepts_settings": [],- },- ]- assert list(config.metadata) == [- "anthropic/nvidia_nim/vendor/model",- "anthropic/ollama_cloud/qwen3-coder:480b",- "anthropic/future_provider/unknown-model",- ]- assert config.metadata == {- "anthropic/nvidia_nim/vendor/model": {+ expected_metadata = {+ "nvidia_nim/vendor/model": {"litellm_provider": "anthropic","mode": "chat","supports_vision": True,"max_input_tokens": 131072,"max_output_tokens": 8192,},- "anthropic/ollama_cloud/qwen3-coder:480b": {+ "ollama_cloud/qwen3-coder:480b": {"litellm_provider": "anthropic","mode": "chat","supports_vision": False,"max_output_tokens": 4096,},- "anthropic/future_provider/unknown-model": {+ "future_provider/unknown-model": {"litellm_provider": "anthropic","mode": "chat",},}+ entries = {entry["name"]: entry for entry in config.settings}+ assert len(entries) == len(config.metadata) == 6+ for wire_name, metadata in expected_metadata.items():+ for name in (wire_name, f"anthropic/{wire_name}"):+ assert config.metadata[name] == metadata+ entry = entries[name]+ assert entry["weak_model_name"] == name+ assert entry["editor_model_name"] == name+ assert entry["extra_params"] == {+ "model": f"anthropic/{wire_name}",+ "api_base": "http://127.0.0.1:9191/v1/messages",+ "api_key": "os.environ/FCC_AIDER_PROXY_AUTH_A1B2C3",+ }+ assert entries["nvidia_nim/vendor/model"]["accepts_settings"] == [+ "reasoning_effort"+ ]+ assert entries["ollama_cloud/qwen3-coder:480b"]["accepts_settings"] == []+ assert "accepts_settings" not in entries["future_provider/unknown-model"]serialized = json.dumps({"settings": config.settings, "metadata": config.metadata})assert json.loads(serialized) == {@@ -113,6 +109,25 @@ def test_aider_config_rejects_empty_catalog() -> None:)+def test_aider_catalog_ids_take_precedence_over_generated_transport_spellings() -> None:+ models = (+ ClientModel("provider/model", "provider/model", "First", None),+ ClientModel(+ "anthropic/provider/model", "anthropic/provider/model", "Second", None+ ),+ )+ config = build_aider_config(+ models,+ messages_url="http://localhost:8182/v1/messages",+ api_key_env="FCC_AIDER_PROXY_AUTH_COLLISION",+ )+ entries = {entry["name"]: entry for entry in config.settings}+ extra = entries["anthropic/provider/model"]["extra_params"]+ assert isinstance(extra, dict)+ assert extra["model"] == "anthropic/anthropic/provider/model"+ assert len(entries) == 3++@pytest.mark.parametrize("api_key_env",[diff --git a/tests/cli/test_aider_launcher.py b/tests/cli/test_aider_launcher.pyindex feaaddfa..82b7ea42 100644--- a/tests/cli/test_aider_launcher.py+++ b/tests/cli/test_aider_launcher.py@@ -1,656 +1,57 @@-"""Contracts for the installed `fcc-aider` launcher."""+"""Native Aider configuration replaces FCC argument rewriting."""import json-import os-from collections.abc import Mappingfrom pathlib import Path-from unittest.mock import patchimport 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.settings import Settings-from free_claude_code.core.json_types import JsonObject---def _settings(*, token: str = "proxy-token") -> Settings:- return Settings.model_construct(- host="0.0.0.0",- port=9191,- proxy_auth_enabled=False,- proxy_auth_token=token,- model="nvidia_nim/test-model",- )---def _models() -> tuple[ClientModel, ...]:- return (- ClientModel(- wire_slug="nvidia_nim/vendor/main-model",- provider_model_ref="nvidia_nim/vendor/main-model",- display_name="Main model",- supports_reasoning=True,- ),- ClientModel(- wire_slug="ollama_cloud/qwen3-coder:480b",- provider_model_ref="ollama_cloud/qwen3-coder:480b",- display_name="Colon model",- supports_reasoning=False,- ),- )---def _models_payload() -> JsonObject:- return {- "data": [- {- "id": model.wire_slug,- "provider_model_ref": model.provider_model_ref,- "display_name": model.display_name,- }- for model in _models()- ]- }--- "argv",- [- ["-h"],- ["--help"],- ["--version"],- ["--just-check-update"],- ["--upgrade"],- ["--update"],- ["--install-main-branch"],- ["--shell-completions", "bash"],- ],-)-def test_aider_maintenance_surfaces_are_native_passthrough(- argv: list[str],-) -> None:- from free_claude_code.cli.launchers import aider-- with (- patch.object(aider, "resolve_client_binary", return_value="resolved-aider"),- patch.object(aider, "get_settings") as get_settings,- patch.object(aider, "preflight_proxy") as preflight_proxy,- patch.object(aider, "fetch_proxy_models_response") as fetch_models,- patch.object(aider, "run_client_process") as run_client_process,- ):- aider.launch(argv)-- assert run_client_process.call_args.kwargs["command"] == [- "resolved-aider",- *argv,- ]- assert run_client_process.call_args.kwargs["env"] is os.environ- get_settings.assert_not_called()- preflight_proxy.assert_not_called()- fetch_models.assert_not_called()--- "argv",- [- [],- ["--list-models", "qwen"],- ["--gui"],- ["--browser"],- ["--copy-paste"],- ["--apply", "changes.diff"],- ["-m", "one-shot prompt"],- ["src/app.py"],- ["--", "--version"],- ],-)-def test_aider_attached_surfaces_are_not_passthrough(argv: list[str]) -> None:- from free_claude_code.cli.launchers.aider import is_aider_passthrough-- assert not is_aider_passthrough(argv)--- "argv",- [- ["--model-settings-file", "custom.yml"],- ["--model-settings-file=custom.yml"],- ["--model-metadata-file", "custom.json"],- ["--model-metadata-file=custom.json"],- ],-)-def test_aider_rejects_caller_owned_route_files(- argv: list[str], capsys: pytest.CaptureFixture[str]-) -> None:- from free_claude_code.cli.launchers import aider-- with pytest.raises(SystemExit) as exc_info:- aider.reject_aider_route_file_overrides(argv)-- assert exc_info.value.code == 2- assert "ordinary aider" in capsys.readouterr().err.lower()---def test_aider_route_file_flags_after_separator_remain_positional() -> None:- from free_claude_code.cli.launchers.aider import reject_aider_route_file_overrides-- reject_aider_route_file_overrides(- ["src/app.py", "--", "--model-settings-file", "fixture.yml"]- )---def test_aider_model_options_normalize_and_preserve_other_argument_order(- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.aider import normalized_aider_arguments-- result = normalized_aider_arguments(- [- "--verbose",- "--weak-model=ollama_cloud/qwen3-coder:480b",- "src/app.py",- "--model",- "anthropic/ollama_cloud/qwen3-coder:480b",- "--editor-model",- "nvidia_nim/vendor/main-model",- "--",- "--model",- "after-separator",- ],- models=_models(),- settings_path=tmp_path / "settings.yml",- metadata_path=tmp_path / "metadata.json",- )-- assert result == [- "--verbose",- "src/app.py",- "--model",- "anthropic/ollama_cloud/qwen3-coder:480b",- "--weak-model",- "anthropic/ollama_cloud/qwen3-coder:480b",- "--editor-model",- "anthropic/nvidia_nim/vendor/main-model",- "--model-settings-file",- str(tmp_path / "settings.yml"),- "--model-metadata-file",- str(tmp_path / "metadata.json"),- "--set-env",- "ANTHROPIC_API_KEY=fcc-local",- "--",- "--model",- "after-separator",- ]---def test_aider_default_weak_and_editor_follow_resolved_main(tmp_path: Path) -> None:- from free_claude_code.cli.launchers.aider import normalized_aider_arguments-- result = normalized_aider_arguments(- ["-m", "keep this one-shot", "--model", _models()[1].wire_slug],- models=_models(),- settings_path=tmp_path / "settings.yml",- metadata_path=tmp_path / "metadata.json",- )-- canonical = "anthropic/ollama_cloud/qwen3-coder:480b"- assert result[:2] == ["-m", "keep this one-shot"]- assert result[2:8] == [- "--model",- canonical,- "--weak-model",- canonical,- "--editor-model",- canonical,- ]---def test_aider_default_main_uses_first_catalog_entry(tmp_path: Path) -> None:- from free_claude_code.cli.launchers.aider import normalized_aider_arguments-- result = normalized_aider_arguments(- [],- models=_models(),- settings_path=tmp_path / "settings.yml",- metadata_path=tmp_path / "metadata.json",- )-- assert result[:6] == [+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch+++def test_aider_receives_native_files_and_a_private_credential_reference(+ launch_capture: LaunchCapture, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("fcc_aider_proxy_auth_stale", "stale-secret")+ monkeypatch.setenv("USER_SETTING", "preserved")+ key_names: list[str] = []++ def inspect(command, env):+ settings_path = Path(env["AIDER_MODEL_SETTINGS_FILE"])+ metadata_path = Path(env["AIDER_MODEL_METADATA_FILE"])+ settings = json.loads(settings_path.read_text())+ metadata = json.loads(metadata_path.read_text())+ assert settings_path.parent == metadata_path.parent+ assert env["AIDER_MODEL"] == "nvidia_nim/catalog-model:variant"+ assert env["USER_SETTING"] == "preserved"+ assert "fcc_aider_proxy_auth_stale" not in env+ (key_name,) = [key for key in env if key.startswith("FCC_AIDER_PROXY_AUTH_")]+ assert key_name.upper() == key_name+ assert env[key_name] == "launcher-test-token"+ key_names.append(key_name)+ bare = next(entry for entry in settings if entry["name"] == env["AIDER_MODEL"])+ assert bare["extra_params"] == {+ "model": "anthropic/nvidia_nim/catalog-model:variant",+ "api_base": "http://127.0.0.1:8182/v1/messages",+ "api_key": f"os.environ/{key_name}",+ }+ assert env["AIDER_MODEL"] in metadata+ assert "launcher-test-token" not in settings_path.read_text()+ assert "launcher-test-token" not in metadata_path.read_text()+ assert command[1:3] == ["--set-env", "ANTHROPIC_API_KEY=fcc-local"]++ launch_capture.on_start = inspect+ args = ["--model",- "anthropic/nvidia_nim/vendor/main-model",+ "native-selection","--weak-model",- "anthropic/nvidia_nim/vendor/main-model",+ "native-weak","--editor-model",- "anthropic/nvidia_nim/vendor/main-model",+ "native-editor",+ "--message",+ "hello",]--- "argv",- [- ["--model"],- ["--weak-model="],- ["--editor-model", "--verbose"],- ],-)-def test_aider_rejects_missing_model_values(- argv: list[str], tmp_path: Path, capsys: pytest.CaptureFixture[str]-) -> None:- from free_claude_code.cli.launchers.aider import normalized_aider_arguments-- with pytest.raises(SystemExit) as exc_info:- normalized_aider_arguments(- argv,- models=_models(),- settings_path=tmp_path / "settings.yml",- metadata_path=tmp_path / "metadata.json",- )-- assert exc_info.value.code == 2- assert "requires one model" in capsys.readouterr().err--- "argv",- [- ["--model", _models()[0].wire_slug, "--model=" + _models()[1].wire_slug],- [- "--weak-model",- _models()[0].wire_slug,- "--weak-model",- _models()[1].wire_slug,- ],- [- "--editor-model=" + _models()[0].wire_slug,- "--editor-model=" + _models()[1].wire_slug,- ],- ],-)-def test_aider_rejects_duplicate_model_options(- argv: list[str], tmp_path: Path, capsys: pytest.CaptureFixture[str]-) -> None:- from free_claude_code.cli.launchers.aider import normalized_aider_arguments-- with pytest.raises(SystemExit) as exc_info:- normalized_aider_arguments(- argv,- models=_models(),- settings_path=tmp_path / "settings.yml",- metadata_path=tmp_path / "metadata.json",- )-- assert exc_info.value.code == 2- assert "only once" in capsys.readouterr().err---def test_aider_rejects_unknown_initial_model(- tmp_path: Path, capsys: pytest.CaptureFixture[str]-) -> None:- from free_claude_code.cli.launchers.aider import normalized_aider_arguments-- with pytest.raises(SystemExit) as exc_info:- normalized_aider_arguments(- ["--model", "anthropic/not/in/catalog"],- models=_models(),- settings_path=tmp_path / "settings.yml",- metadata_path=tmp_path / "metadata.json",- )-- assert exc_info.value.code == 2- assert "not in the current FCC model catalog" in capsys.readouterr().err---def test_aider_child_env_scrubs_stale_keys_and_preserves_native_state() -> None:- from free_claude_code.cli.launchers.aider import build_aider_launcher_env-- env = build_aider_launcher_env(- proxy_root_url="http://127.0.0.1:9191",- api_key_env="FCC_AIDER_PROXY_AUTH_FRESH123",- auth_token="real-secret",- base_env={- "PATH": "keep",- "AIDER_CONFIG_FILE": "keep-user-config",- "HTTP_PROXY": "http://proxy.example",- "NO_PROXY": "example.com",- "fcc_aider_proxy_auth_old": "remove",- "FCC_AIDER_PROXY_AUTH_OTHER": "remove",- },- )-- assert env["PATH"] == "keep"- assert env["AIDER_CONFIG_FILE"] == "keep-user-config"- assert env["HTTP_PROXY"] == "http://proxy.example"- assert env["NO_PROXY"] == "example.com,127.0.0.1,localhost,::1"- assert env["no_proxy"] == env["NO_PROXY"]- assert env["FCC_AIDER_PROXY_AUTH_FRESH123"] == "real-secret"- assert "fcc_aider_proxy_auth_old" not in env- assert "FCC_AIDER_PROXY_AUTH_OTHER" not in env---def test_aider_launch_uses_messages_catalog_and_private_ephemeral_files(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers import aider-- monkeypatch.setenv("HOME", str(tmp_path))- monkeypatch.setenv("USERPROFILE", str(tmp_path))- monkeypatch.setenv("AIDER_CONFIG_FILE", "keep-native-state")- observed_directory: Path | None = None- observed_env_name: str | None = None-- def observe_process(- *,- command: list[str],- env: Mapping[str, str],- binary_name: str,- display_name: str,- install_hint: str,- ) -> None:- nonlocal observed_directory, observed_env_name- del binary_name, display_name, install_hint- settings_index = command.index("--model-settings-file") + 1- metadata_index = command.index("--model-metadata-file") + 1- settings_path = Path(command[settings_index])- metadata_path = Path(command[metadata_index])- observed_directory = settings_path.parent- assert metadata_path.parent == observed_directory- assert settings_path.name == "model-settings.yml"- assert metadata_path.name == "model-metadata.json"- settings_payload = json.loads(settings_path.read_text(encoding="utf-8"))- metadata_payload = json.loads(metadata_path.read_text(encoding="utf-8"))- env_reference = settings_payload[0]["extra_params"]["api_key"]- assert isinstance(env_reference, str)- observed_env_name = env_reference.removeprefix("os.environ/")- assert observed_env_name.startswith("FCC_AIDER_PROXY_AUTH_")- assert env[observed_env_name] == "proxy-token"- assert env["AIDER_CONFIG_FILE"] == "keep-native-state"- rendered = (- " ".join(command)- + json.dumps(settings_payload)- + json.dumps(metadata_payload)- )- assert "proxy-token" not in rendered- assert command[:3] == ["resolved-aider", "--verbose", "src/app.py"]- assert command[-2:] == ["--set-env", "ANTHROPIC_API_KEY=fcc-local"]-- with (- patch.object(aider, "resolve_client_binary", return_value="resolved-aider"),- patch.object(aider, "get_settings", return_value=_settings()),- patch.object(aider, "preflight_proxy", return_value=None),- patch.object(- aider,- "fetch_proxy_models_response",- return_value=_models_payload(),- ) as fetch_models,- patch.object(aider, "run_client_process", side_effect=observe_process),- ):- aider.launch(["--verbose", "src/app.py"])-- fetch_models.assert_called_once_with(- "http://127.0.0.1:9191",- "proxy-token",- view="messages",- )- assert observed_directory is not None- assert observed_env_name is not None- assert observed_directory.parent == tmp_path / ".fcc" / "tmp" / "aider"- assert not observed_directory.exists()--[email protected]("error", [SystemExit(7), KeyboardInterrupt()])-def test_aider_temp_files_cleanup_when_child_ends_abnormally(- error: BaseException,- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers import aider-- monkeypatch.setenv("HOME", str(tmp_path))- monkeypatch.setenv("USERPROFILE", str(tmp_path))- observed_directory: Path | None = None-- def fail_process(**kwargs: object) -> None:- nonlocal observed_directory- command = kwargs["command"]- assert isinstance(command, list)- settings_path = Path(command[command.index("--model-settings-file") + 1])- observed_directory = settings_path.parent- assert observed_directory.is_dir()- raise error-- with (- patch.object(aider, "resolve_client_binary", return_value="resolved-aider"),- patch.object(aider, "get_settings", return_value=_settings()),- patch.object(aider, "preflight_proxy", return_value=None),- patch.object(- aider,- "fetch_proxy_models_response",- return_value=_models_payload(),- ),- patch.object(aider, "run_client_process", side_effect=fail_process),- pytest.raises(type(error)),- ):- aider.launch([])-- assert observed_directory is not None- assert not observed_directory.exists()---def test_aider_temporary_preparations_are_unique(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.aider import temporary_aider_config_files-- monkeypatch.setenv("HOME", str(tmp_path))- monkeypatch.setenv("USERPROFILE", str(tmp_path))- first_config = build_aider_config(- _models(),- messages_url="http://127.0.0.1:9191/v1/messages",- api_key_env="FCC_AIDER_PROXY_AUTH_FIRST",- )- second_config = build_aider_config(- _models(),- messages_url="http://127.0.0.1:9191/v1/messages",- api_key_env="FCC_AIDER_PROXY_AUTH_SECOND",- )-- with (- temporary_aider_config_files(first_config) as first,- temporary_aider_config_files(second_config) as second,- ):- first_directory = first.directory- second_directory = second.directory- assert first_directory != second_directory- assert first_directory.is_dir()- assert second_directory.is_dir()-- assert not first_directory.exists()- assert not second_directory.exists()--- os.name == "nt", reason="POSIX file modes are not enforced on Windows"-)-def test_aider_managed_directories_and_files_are_owner_only(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.aider import temporary_aider_config_files-- monkeypatch.setenv("HOME", str(tmp_path))- monkeypatch.setenv("USERPROFILE", str(tmp_path))- base = tmp_path / ".fcc" / "tmp" / "aider"- base.mkdir(parents=True, mode=0o755)- base.chmod(0o755)- config = build_aider_config(- _models(),- messages_url="http://127.0.0.1:9191/v1/messages",- api_key_env="FCC_AIDER_PROXY_AUTH_MODES",- )-- with temporary_aider_config_files(config) as files:- assert base.stat().st_mode & 0o777 == 0o700- assert files.directory.stat().st_mode & 0o777 == 0o700- assert files.settings_path.stat().st_mode & 0o777 == 0o600- assert files.metadata_path.stat().st_mode & 0o777 == 0o600--- ("token", "preflight_error", "catalog", "expected"),- [- (" ", None, _models_payload(), "token is empty"),- ("proxy-token", "connection refused", _models_payload(), "fcc-server"),- ("proxy-token", None, {"data": []}, "at least one routable"),- ],-)-def test_aider_launch_fails_before_child_for_invalid_preparation(- token: str,- preflight_error: str | None,- catalog: JsonObject,- expected: str,- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import aider-- with (- patch.object(aider, "resolve_client_binary", return_value="resolved-aider"),- patch.object(aider, "get_settings", return_value=_settings(token=token)),- patch.object(aider, "preflight_proxy", return_value=preflight_error),- patch.object(- aider,- "fetch_proxy_models_response",- return_value=catalog,- ),- patch.object(aider, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- aider.launch([])-- assert exc_info.value.code == 1- assert expected in capsys.readouterr().err- run_client_process.assert_not_called()---def test_aider_catalog_failure_is_reported_once_without_secret(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import aider-- with (- patch.object(aider, "resolve_client_binary", return_value="resolved-aider"),- patch.object(aider, "get_settings", return_value=_settings()),- patch.object(aider, "preflight_proxy", return_value=None),- patch.object(- aider,- "fetch_proxy_models_response",- side_effect=ValueError("bad catalog"),- ),- patch.object(aider, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- aider.launch([])-- assert exc_info.value.code == 1- error = capsys.readouterr().err- assert error.count("bad catalog") == 1- assert "proxy-token" not in error- run_client_process.assert_not_called()---def test_aider_file_creation_error_does_not_launch_or_disclose_token(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import aider-- monkeypatch.setenv("HOME", str(tmp_path))- monkeypatch.setenv("USERPROFILE", str(tmp_path))- with (- patch.object(aider, "resolve_client_binary", return_value="resolved-aider"),- patch.object(aider, "get_settings", return_value=_settings()),- patch.object(aider, "preflight_proxy", return_value=None),- patch.object(- aider,- "fetch_proxy_models_response",- return_value=_models_payload(),- ),- patch.object(- aider.tempfile,- "TemporaryDirectory",- side_effect=OSError("storage unavailable"),- ),- patch.object(aider, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- aider.launch([])-- assert exc_info.value.code == 1- error = capsys.readouterr().err- assert "storage unavailable" in error- assert "proxy-token" not in error- run_client_process.assert_not_called()---def test_aider_missing_binary_uses_shared_resolution_contract() -> None:- from free_claude_code.cli.launchers import aider-- with (- patch.object(- aider,- "resolve_client_binary",- side_effect=SystemExit(127),- ) as resolve_client_binary,- patch.object(aider, "get_settings") as get_settings,- pytest.raises(SystemExit) as exc_info,- ):- aider.launch([])-- assert exc_info.value.code == 127- resolve_client_binary.assert_called_once_with(- binary_name="aider",- display_name="Aider",- install_hint="Install Aider from: https://aider.chat/docs/install.html",- )- get_settings.assert_not_called()---def test_aider_config_repr_never_contains_the_proxy_token() -> None:- config = build_aider_config(- _models(),- messages_url="http://127.0.0.1:9191/v1/messages",- api_key_env="FCC_AIDER_PROXY_AUTH_SAFE",- )-- assert "proxy-token" not in repr(config)- assert "127.0.0.1" not in repr(config)---def test_aider_random_credentials_are_uppercase_and_distinct() -> None:- from free_claude_code.cli.launchers.aider import new_aider_api_key_env_name-- with patch(- "free_claude_code.cli.launchers.aider.secrets.token_hex",- side_effect=["a1b2", "c3d4"],- ):- first = new_aider_api_key_env_name()- second = new_aider_api_key_env_name()-- assert first == "FCC_AIDER_PROXY_AUTH_A1B2"- assert second == "FCC_AIDER_PROXY_AUTH_C3D4"- assert first != second---def test_aider_temp_path_is_owned_by_fcc_home(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- from free_claude_code.config.paths import aider_temp_dir_path-- monkeypatch.setenv("HOME", str(tmp_path))- monkeypatch.setenv("USERPROFILE", str(tmp_path))-- assert aider_temp_dir_path() == tmp_path / ".fcc" / "tmp" / "aider"+ launch("aider", args)+ assert launch_capture.commands[0][-len(args) :] == args+ launch("aider", [])+ assert key_names[0] != key_names[1]diff --git a/tests/cli/test_claude_launcher.py b/tests/cli/test_claude_launcher.pyindex b3acb3a5..6956b719 100644--- a/tests/cli/test_claude_launcher.py+++ b/tests/cli/test_claude_launcher.py@@ -1,55 +1,29 @@-import pytest--from free_claude_code.cli.launchers.claude import build_claude_launcher_command---def test_claude_launcher_defaults_to_non_auto_permission_mode() -> None:- assert build_claude_launcher_command(- binary_path="claude", argv=["fix the tests"]- ) == ["claude", "--permission-mode", "default", "fix the tests"]+"""Claude owns permission options and prompt interpretation."""+import pytest- "argv",- [- ["--permission-mode", "auto", "fix the tests"],- ["--permission-mode=acceptEdits", "fix the tests"],- ["--dangerously-skip-permissions", "fix the tests"],- ],-)-def test_claude_launcher_preserves_explicit_permission_choice(- argv: list[str],-) -> None:- assert build_claude_launcher_command(binary_path="claude", argv=argv) == [- "claude",- *argv,- ]--[email protected]("argv", [["--permission-mode"], ["--permission-mode="]])-def test_claude_launcher_leaves_malformed_permission_options_to_claude(- argv: list[str],-) -> None:- assert build_claude_launcher_command(binary_path="claude", argv=argv) == [- "claude",- *argv,- ]+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch@pytest.mark.parametrize(- "argv",+ "args",[- ["explain --permission-mode auto"],+ [],+ ["--permission-mode", "auto", "fix tests"],+ ["--permission-mode=acceptEdits", "fix tests"],+ ["--dangerously-skip-permissions", "fix tests"],+ ["--permission-mode"],["--", "--permission-mode=auto"],- ["--", "--dangerously-skip-permissions"],+ ["explain --permission-mode auto"],],)-def test_claude_launcher_does_not_treat_prompt_text_as_a_permission_choice(- argv: list[str],+def test_claude_owns_permission_selection(+ args: list[str], launch_capture: LaunchCapture) -> None:- assert build_claude_launcher_command(binary_path="claude", argv=argv) == [- "claude",- "--permission-mode",- "default",- *argv,- ]+ launch("claude", args)+ assert launch_capture.commands == [["claude", *args]]+ env = launch_capture.environments[0]+ assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8182"+ assert env["ANTHROPIC_AUTH_TOKEN"] == "launcher-test-token"+ assert env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"diff --git a/tests/cli/test_cline_launcher.py b/tests/cli/test_cline_launcher.pyindex ba3f9a3c..af8939d1 100644--- a/tests/cli/test_cline_launcher.py+++ b/tests/cli/test_cline_launcher.py@@ -1,13 +1,8 @@"""Contract tests for the installed `fcc-cline` launcher."""import json-import os-import subprocess-from collections.abc import Mappingfrom datetime import UTC, datetimefrom pathlib import Path-from types import SimpleNamespace-from unittest.mock import patchimport pytest@@ -16,38 +11,9 @@ from free_claude_code.cli.launchers.cline_config import (build_cline_config,)from free_claude_code.cli.launchers.model_catalog import ClientModel-from free_claude_code.config.settings import Settings-from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.model_capabilities import ModelInputModality-def _settings(*, token: str = "proxy-token") -> Settings:- return Settings(- host="0.0.0.0",- port=9191,- proxy_auth_enabled=False,- proxy_auth_token=token,- model="nvidia_nim/test-model",- )---def _models_payload() -> JsonObject:- return {- "data": [- {- "id": "nvidia_nim/vendor/model",- "provider_model_ref": "nvidia_nim/vendor/model",- "display_name": "Nested model",- },- {- "id": "claude-3-freecc-no-thinking/open_router/plain-model",- "provider_model_ref": "open_router/plain-model",- "display_name": "No-thinking model",- },- ]- }--def test_cline_config_uses_responses_and_only_known_metadata() -> None:config = build_cline_config((@@ -164,434 +130,21 @@ def test_cline_config_rejects_empty_model_catalog() -> None:)- "argv",- [- ["--help"],- ["--verbose", "--version"],- ["auth", "login"],- ["--config", "elsewhere", "config"],- ["history"],- ["h"],- ["plugin", "list"],- ["skill", "list"],- ["mcp", "list"],- ["doctor"],- ["update"],- ["version"],- ],-)-def test_cline_management_commands_are_native_passthrough(argv: list[str]) -> None:- from free_claude_code.cli.launchers import cline-- assert cline.is_cline_passthrough(argv)- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "get_settings") as get_settings,- patch.object(cline, "require_compatible_cline") as require_version,- patch.object(cline, "run_client_process") as run_client_process,- ):- cline.launch(argv)-- assert run_client_process.call_args.kwargs["command"] == [- "resolved-cline",- *argv,- ]- get_settings.assert_not_called()- require_version.assert_not_called()--- "argv",- [- ["connect", "discord"],- ["--cwd", "workspace", "schedule", "list"],- ["hub", "start"],- ["dashboard"],- ["hook"],- ["kanban"],- ["--zen", "prompt"],- ["-z", "prompt"],- ["--kanban"],- ],-)-def test_cline_detached_surfaces_are_rejected_before_fcc_calls(- argv: list[str], capsys: pytest.CaptureFixture[str]-) -> None:- from free_claude_code.cli.launchers import cline-- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "get_settings") as get_settings,- patch.object(cline, "require_compatible_cline") as require_version,- patch.object(cline, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- cline.launch(argv)-- assert exc_info.value.code == 2- assert "attached terminal sessions only" in capsys.readouterr().err- get_settings.assert_not_called()- require_version.assert_not_called()- run_client_process.assert_not_called()--- "argv",- [- ["-P", "openrouter", "prompt"],- ["-Popenrouter", "prompt"],- ["--provider", "openrouter", "prompt"],- ["--provider=openrouter", "prompt"],- ["-k", "secret", "prompt"],- ["-ksecret", "prompt"],- ["--key", "secret", "prompt"],- ["--key=secret", "prompt"],- ],-)-def test_cline_rejects_caller_owned_routing(argv: list[str]) -> None:- from free_claude_code.cli.launchers import cline-- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "require_compatible_cline") as require_version,- pytest.raises(SystemExit) as exc_info,- ):- cline.launch(argv)-- assert exc_info.value.code == 2- require_version.assert_not_called()--- ("argv", "sandbox_env"),- [- (["--data-dir", "isolated", "prompt"], None),- (["--data-dir=isolated", "prompt"], None),- (["prompt"], "1"),- ],-)-def test_cline_rejects_sandbox_overrides_that_replace_ephemeral_credentials(- argv: list[str],- sandbox_env: str | None,- monkeypatch: pytest.MonkeyPatch,- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import cline-- if sandbox_env is None:- monkeypatch.delenv("CLINE_SANDBOX", raising=False)- else:- monkeypatch.setenv("CLINE_SANDBOX", sandbox_env)- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "require_compatible_cline") as require_version,- patch.object(cline, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- cline.launch(argv)-- assert exc_info.value.code == 2- assert "replaces the ephemeral FCC provider file" in capsys.readouterr().err- require_version.assert_not_called()- run_client_process.assert_not_called()--- ("argv", "expected"),- [- ([], None),- (["prompt"], "prompt"),- (["--cwd", "workspace", "prompt"], "prompt"),- (["--cwd=workspace", "prompt"], "prompt"),- (["-cworkspace", "prompt"], "prompt"),- (["--retries", "4", "prompt"], "prompt"),- (["--retries=4", "prompt"], "prompt"),- (["--verbose", "doctor"], "doctor"),- (["--unknown", "hub"], None),- (["--", "hub"], None),- ],-)-def test_cline_root_positional_scanner(argv: list[str], expected: str | None) -> None:- from free_claude_code.cli.launchers.cline import first_root_positional-- assert first_root_positional(argv) == expected--- ("output", "return_code", "expected"),- [- ("3.0.55\n", 0, (3, 0, 55)),- ("cline version 3.1.0\n", 0, (3, 1, 0)),- ("v3.1.0+release.1\n", 0, (3, 1, 0)),- ("3.1.0-beta.1\n", 0, None),- ("unexpected 3.1.0\n", 0, None),- ("3.1.0\n", 1, None),- ],-)-def test_cline_version_probe(- output: str,- return_code: int,- expected: tuple[int, int, int] | None,-) -> None:- from free_claude_code.cli.launchers import cline-- with patch.object(- cline.subprocess,- "run",- return_value=SimpleNamespace(stdout=output, returncode=return_code),- ):- assert cline.cline_binary_version("resolved-cline") == expected---def test_cline_version_probe_handles_timeout() -> None:- from free_claude_code.cli.launchers import cline-- with patch.object(- cline.subprocess,- "run",- side_effect=subprocess.TimeoutExpired("cline", 5),- ):- assert cline.cline_binary_version("resolved-cline") is None---def test_cline_rejects_incompatible_version_with_update_hint(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import cline-- with (- patch.object(cline, "cline_binary_version", return_value=(3, 0, 54)),- pytest.raises(SystemExit) as exc_info,- ):- cline.require_compatible_cline("resolved-cline")-- assert exc_info.value.code == 126- captured = capsys.readouterr()- assert "at least version 3.0.55" in captured.err- assert "cline update" in captured.err-+def test_cline_native_configuration_is_available_to_child(launch_capture) -> None:+ from tests.cli.test_launcher_workflow import launch-def test_cline_child_env_is_process_local_and_preserves_native_state(- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.cline import build_cline_launcher_env-- providers_path = tmp_path / "settings" / "providers.json"- env = build_cline_launcher_env(- proxy_root_url="http://127.0.0.1:9191",- providers_path=providers_path,- base_env={- "PATH": "keep",- "CLINE_PROVIDER_SETTINGS_PATH": "stale-provider-file",- "CLINE_SESSION_BACKEND_MODE": "hub",- "CLINE_DATA_DIR": "keep-user-state",- "CLINE_CONFIG_DIR": "keep-user-config",- "HTTP_PROXY": "http://proxy.example",- },- )-- assert env["PATH"] == "keep"- assert env["CLINE_PROVIDER_SETTINGS_PATH"] == str(providers_path)- assert env["CLINE_SESSION_BACKEND_MODE"] == "local"- assert env["CLINE_DATA_DIR"] == "keep-user-state"- assert env["CLINE_CONFIG_DIR"] == "keep-user-config"- assert env["HTTP_PROXY"] == "http://proxy.example"- assert env["NO_PROXY"] == "127.0.0.1,localhost,::1"- assert env["no_proxy"] == env["NO_PROXY"]---def test_cline_launch_uses_private_ephemeral_files_and_preserves_model_flag(- monkeypatch: pytest.MonkeyPatch,-) -> None:- from free_claude_code.cli.launchers import cline-- monkeypatch.setenv("CLINE_DATA_DIR", "keep-native-state")- observed_providers_path: Path | None = None- observed_models_path: Path | None = None-- def observe_process(- *,- command: list[str],- env: Mapping[str, str],- binary_name: str,- display_name: str,- install_hint: str,- ) -> None:- nonlocal observed_providers_path, observed_models_path- del binary_name, display_name, install_hint- assert command == [- "resolved-cline",- "--provider",- CLINE_PROVIDER_ID,- "--model",- "open_router/chosen/model",- "hello",- ]- observed_providers_path = Path(env["CLINE_PROVIDER_SETTINGS_PATH"])- observed_models_path = observed_providers_path.with_name("models.json")- providers = json.loads(observed_providers_path.read_text(encoding="utf-8"))- models = json.loads(observed_models_path.read_text(encoding="utf-8"))+ def inspect(command, env):+ providers_path = Path(env["CLINE_PROVIDER_SETTINGS_PATH"])+ providers = json.loads(providers_path.read_text())+ models = json.loads(providers_path.with_name("models.json").read_text())settings = providers["providers"][CLINE_PROVIDER_ID]["settings"]- assert settings["apiKey"] == "proxy-token"- assert settings["protocol"] == "openai-responses"- assert settings["baseUrl"] == "http://127.0.0.1:9191/v1"- assert (- "nvidia_nim/vendor/model"- in models["providers"][CLINE_PROVIDER_ID]["models"]- )+ assert settings["baseUrl"] == "http://127.0.0.1:8182/v1"+ assert settings["apiKey"] == "launcher-test-token"+ assert settings["model"] in models["providers"][CLINE_PROVIDER_ID]["models"]assert env["CLINE_SESSION_BACKEND_MODE"] == "local"- assert env["CLINE_DATA_DIR"] == "keep-native-state"-- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "require_compatible_cline"),- patch.object(cline, "get_settings", return_value=_settings()),- patch.object(cline, "preflight_proxy", return_value=None),- patch.object(- cline,- "fetch_proxy_models_response",- return_value=_models_payload(),- ) as fetch_models,- patch.object(cline, "run_client_process", side_effect=observe_process),- ):- cline.launch(["--model", "open_router/chosen/model", "hello"])-- fetch_models.assert_called_once_with("http://127.0.0.1:9191", "proxy-token")- assert observed_providers_path is not None- assert observed_models_path is not None- assert not observed_providers_path.exists()- assert not observed_models_path.exists()---def test_cline_fails_closed_when_proxy_is_unreachable(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import cline-- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "require_compatible_cline"),- patch.object(cline, "get_settings", return_value=_settings()),- patch.object(cline, "preflight_proxy", return_value="connection refused"),- patch.object(cline, "fetch_proxy_models_response") as fetch_models,- patch.object(cline, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- cline.launch(["hello"])-- assert exc_info.value.code == 1- assert "fcc-server" in capsys.readouterr().err- fetch_models.assert_not_called()- run_client_process.assert_not_called()---def test_cline_fails_closed_when_catalog_has_no_routable_models(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import cline-- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "require_compatible_cline"),- patch.object(cline, "get_settings", return_value=_settings()),- patch.object(cline, "preflight_proxy", return_value=None),- patch.object(- cline,- "fetch_proxy_models_response",- return_value={"data": [{"id": "claude-opus-4-20250514"}]},- ),- patch.object(cline, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- cline.launch(["hello"])-- assert exc_info.value.code == 1- assert "at least one routable FCC model" in capsys.readouterr().err- run_client_process.assert_not_called()---def test_cline_rejects_empty_proxy_token_before_network_calls(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import cline-- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "require_compatible_cline"),- patch.object(- cline,- "get_settings",- return_value=SimpleNamespace(- host="0.0.0.0",- port=9191,- proxy_auth_token=" ",- ),- ),- patch.object(cline, "preflight_proxy") as preflight_proxy,- patch.object(cline, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- cline.launch([])-- assert exc_info.value.code == 1- assert "token is empty" in capsys.readouterr().err- preflight_proxy.assert_not_called()- run_client_process.assert_not_called()---def test_cline_reports_temporary_config_creation_failure(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import cline-- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "require_compatible_cline"),- patch.object(cline, "get_settings", return_value=_settings()),- patch.object(cline, "preflight_proxy", return_value=None),- patch.object(- cline, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(- cline.tempfile,- "TemporaryDirectory",- side_effect=OSError("temporary directory unavailable"),- ),- patch.object(cline, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- cline.launch(["hello"])-- assert exc_info.value.code == 1- assert "temporary directory unavailable" in capsys.readouterr().err- run_client_process.assert_not_called()--- os.name == "nt", reason="POSIX file modes are not enforced on Windows"-)-def test_cline_provider_file_is_owner_only(monkeypatch: pytest.MonkeyPatch) -> None:- from free_claude_code.cli.launchers import cline-- observed_mode: int | None = None-- def observe_process(**kwargs: object) -> None:- nonlocal observed_mode- env = kwargs["env"]- assert isinstance(env, Mapping)- observed_mode = Path(env["CLINE_PROVIDER_SETTINGS_PATH"]).stat().st_mode & 0o777-- with (- patch.object(cline, "resolve_client_binary", return_value="resolved-cline"),- patch.object(cline, "require_compatible_cline"),- patch.object(cline, "get_settings", return_value=_settings()),- patch.object(cline, "preflight_proxy", return_value=None),- patch.object(- cline, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(cline, "run_client_process", side_effect=observe_process),- ):- cline.launch(["hello"])+ assert command[:3] == ["cline", "--provider", "openai-native"]- assert observed_mode == 0o600+ launch_capture.on_start = inspect+ args = ["--model", "native-selection", "--data-dir", "native-data-dir"]+ launch("cline", args)+ assert launch_capture.commands[0][-len(args) :] == argsdiff --git a/tests/cli/test_codex_launcher.py b/tests/cli/test_codex_launcher.pynew file mode 100644index 00000000..868a9a1e--- /dev/null+++ b/tests/cli/test_codex_launcher.py@@ -0,0 +1,63 @@+"""Codex's CLI catalog and external credential integration."""++import tomllib+from unittest.mock import patch++import pytest++from free_claude_code.cli.launchers import codex, runner+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch+++def test_external_credential_command_needs_no_native_launch(+ launch_capture: LaunchCapture, capsys: pytest.CaptureFixture[str]+) -> None:+ with patch.object(+ runner, "launch_harness", side_effect=AssertionError("must not launch")+ ):+ codex.launch(["--print-proxy-auth-token"])+ assert capsys.readouterr() == ("launcher-test-token\n", "")+ assert not launch_capture.commands+ assert not launch_capture.probes+ assert not launch_capture.requests+++def test_codex_selects_the_advertised_slug_from_opaque_catalog_data(+ launch_capture: LaunchCapture,+) -> None:+ launch_capture.catalog = {+ "data": [+ {+ "id": "arbitrary-wire-id",+ "provider_model_ref": "nvidia_nim/catalog-model:variant",+ "supportsReasoning": False,+ }+ ]+ }+ launch("codex", ["exec", "--model", "native-choice", "hello"])+ command = launch_capture.commands[0]+ config = tomllib.loads(+ "\n".join(command[i + 1] for i, arg in enumerate(command) if arg == "-c")+ )+ assert config["model"] == "arbitrary-wire-id"+ assert config["model_providers"]["fcc"]["wire_api"] == "responses"+ assert config["model_providers"]["fcc"]["base_url"] == "http://127.0.0.1:8182/v1"+ assert config["model_providers"]["fcc"]["auth"] == {+ "command": "fcc-codex",+ "args": ["--print-proxy-auth-token"],+ }+ assert command[-4:] == ["exec", "--model", "native-choice", "hello"]+++def test_codex_scrubs_parent_task_identity_and_preserves_native_home(+ launch_capture: LaunchCapture, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("CODEX_HOME", "native-codex-home")+ monkeypatch.setenv("CODEX_THREAD_ID", "parent-task")+ monkeypatch.setenv("OPENAI_SOMETHING", "old-route")+ launch("codex", [])+ env = launch_capture.environments[0]+ assert env["CODEX_HOME"] == "native-codex-home"+ assert "CODEX_THREAD_ID" not in env+ assert not any(key.startswith("OPENAI_") for key in env)diff --git a/tests/cli/test_codex_model_catalog.py b/tests/cli/test_codex_model_catalog.pyindex 65a8245d..c9d2e7ef 100644--- a/tests/cli/test_codex_model_catalog.py+++ b/tests/cli/test_codex_model_catalog.py@@ -13,6 +13,7 @@ from free_claude_code.cli.launchers.codex_model_catalog import (build_codex_model_catalog,write_codex_model_catalog,)+from free_claude_code.cli.launchers.model_catalog import client_models_from_responsedef _models_payload(*model_ids: str) -> dict[str, Any]:@@ -51,9 +52,11 @@ def _slugs(catalog: Mapping[str, Any]) -> list[str]:def test_codex_catalog_uses_direct_configured_and_cached_model_slugs() -> None:catalog = build_codex_model_catalog(- _models_payload(- "nvidia_nim/nvidia/nemotron-3-super",- "open_router/meta-llama/llama-3.3-70b",+ client_models_from_response(+ _models_payload(+ "nvidia_nim/nvidia/nemotron-3-super",+ "open_router/meta-llama/llama-3.3-70b",+ )))@@ -79,16 +82,18 @@ def test_codex_catalog_uses_direct_configured_and_cached_model_slugs() -> None:def test_codex_catalog_ignores_rows_without_direct_provider_identity() -> None:catalog = build_codex_model_catalog(- {- "data": [- {"id": "claude-opus-4-20250514"},- {- "id": "nvidia_nim/provider-model",- "provider_model_ref": "nvidia_nim/provider-model",- "display_name": "NIM",- },- ]- }+ 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"]@@ -96,9 +101,11 @@ def test_codex_catalog_ignores_rows_without_direct_provider_identity() -> None:def test_codex_catalog_deduplicates_direct_wire_ids() -> None:catalog = build_codex_model_catalog(- _models_payload(- "nvidia_nim/provider-model",- "nvidia_nim/provider-model",+ client_models_from_response(+ _models_payload(+ "nvidia_nim/provider-model",+ "nvidia_nim/provider-model",+ )))@@ -107,7 +114,9 @@ def test_codex_catalog_deduplicates_direct_wire_ids() -> None:def test_codex_catalog_preserves_no_thinking_only_entries_for_routing() -> None:catalog = build_codex_model_catalog(- _models_payload("claude-3-freecc-no-thinking/open_router/plain-model")+ 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"]@@ -115,11 +124,13 @@ def test_codex_catalog_preserves_no_thinking_only_entries_for_routing() -> None:def test_codex_catalog_ordering_and_priorities_are_deterministic() -> None:catalog = build_codex_model_catalog(- _models_payload(- "anthropic/gemini/models/gemini-test",- "nvidia_nim/nvidia/test",- "anthropic/gemini/models/gemini-test",- "open_router/provider/test",+ client_models_from_response(+ _models_payload(+ "anthropic/gemini/models/gemini-test",+ "nvidia_nim/nvidia/test",+ "anthropic/gemini/models/gemini-test",+ "open_router/provider/test",+ )))@@ -136,9 +147,11 @@ def test_codex_catalog_accepts_direct_provider_slugs_without_a_provider_registryNone):catalog = build_codex_model_catalog(- _models_payload(- "nvidia_nim/provider-model",- "future_provider/provider-model",+ client_models_from_response(+ _models_payload(+ "nvidia_nim/provider-model",+ "future_provider/provider-model",+ )))@@ -152,29 +165,31 @@ def test_codex_catalog_projects_known_capabilities_and_preserves_unknown_defaultNone):catalog = build_codex_model_catalog(- {- "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",- },- ]- }+ 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)@@ -213,7 +228,9 @@ def test_launcher_config_composes_with_persistent_codex_config(catalog_path = tmp_path / "codex-model-catalog.json"write_codex_model_catalog(catalog_path,- build_codex_model_catalog(_models_payload("nvidia_nim/test-model")),+ build_codex_model_catalog(+ client_models_from_response(_models_payload("nvidia_nim/test-model"))+ ),)codex_home = tmp_path / "codex-home"codex_home.mkdir()@@ -271,8 +288,12 @@ 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(_models_payload("nvidia_nim/first"))- second = build_codex_model_catalog(_models_payload("nvidia_nim/second"))+ 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 Trueassert write_codex_model_catalog(catalog_path, first) is False@@ -298,7 +319,9 @@ def test_catalog_writer_cleans_temporary_file_after_replace_failure(with pytest.raises(PermissionError, match="locked"):write_codex_model_catalog(catalog_path,- build_codex_model_catalog(_models_payload("nvidia_nim/replacement")),+ build_codex_model_catalog(+ client_models_from_response(_models_payload("nvidia_nim/replacement"))+ ),)assert catalog_path.read_text(encoding="utf-8") == "previous\n"diff --git a/tests/cli/test_dsh_config.py b/tests/cli/test_dsh_config.pyindex 62a7d943..09902c4b 100644--- a/tests/cli/test_dsh_config.py+++ b/tests/cli/test_dsh_config.py@@ -58,23 +58,20 @@ def test_dsh_config_pins_responses_models_retries_and_private_state(provider_progress_timeout=600.0,)- assert launch.selected_model == "nvidia_nim/vendor/model"- assert launch.api_key_env == "FCC_DSH_API_KEY"-- settings = _row_by_id(launch.patch, "settings")+ settings = _row_by_id(launch, "settings")assert settings == {"id": "settings","name": "@deepseek-ai/dsh-settings-file","config": {"path": str(settings_path), "watch": False},}- credentials = _row_by_id(launch.patch, "credentials")+ credentials = _row_by_id(launch, "credentials")assert credentials == {"id": "credentials","name": "@deepseek-ai/dsh-credentials-local","config": {"path": str(credentials_path), "watch": False},}- llm = _row_by_id(launch.patch, "llm-pi-ai")+ llm = _row_by_id(launch, "llm-pi-ai")provider = llm["config"]["providers"]["free-claude-code"]assert provider == {"displayName": "Free Claude Code",@@ -123,7 +120,7 @@ def test_dsh_config_pins_responses_models_retries_and_private_state("retryPolicy": {"mode": "normal", "maxRetries": 0},"streamIdleTimeoutMs": 660_000,}- assert _row_by_id(launch.patch, "agent-default-model") == {+ assert _row_by_id(launch, "agent-default-model") == {"id": "agent-default-model","name": "@deepseek-ai/dsh-agent-default-model","config": {@@ -137,13 +134,13 @@ def test_dsh_config_pins_responses_models_retries_and_private_state(("web-search-deepseek", "@deepseek-ai/dsh-web-search-deepseek"),("tool-web", "@deepseek-ai/dsh-tool-web"),):- assert _row_by_id(launch.patch, row_id) == {+ assert _row_by_id(launch, row_id) == {"id": row_id,"name": package,"disabled": True,}- serialized = json.dumps(launch.patch)+ serialized = json.dumps(launch)assert "proxy-token" not in serializedfor unsupported in ("compat", "headers", "telemetry"):assert unsupported not in serialized@@ -158,7 +155,7 @@ def test_dsh_config_rounds_fractional_progress_timeout_up() -> None:provider_progress_timeout=0.0001,)- provider = _row_by_id(launch.patch, "llm-pi-ai")["config"]["providers"][+ provider = _row_by_id(launch, "llm-pi-ai")["config"]["providers"]["free-claude-code"]assert provider["streamIdleTimeoutMs"] == 60_001diff --git a/tests/cli/test_dsh_launcher.py b/tests/cli/test_dsh_launcher.pyindex f54e4ae1..70efce9b 100644--- a/tests/cli/test_dsh_launcher.py+++ b/tests/cli/test_dsh_launcher.py@@ -1,438 +1,46 @@-"""Contract tests for the installed `fcc-dsh` launcher."""+"""DSH keeps its native profile grammar and receives one FCC patch."""import json-import os-import subprocessfrom pathlib import Path-from types import SimpleNamespace-from unittest.mock import patchimport pytest-from free_claude_code.cli.launchers.dsh import DshInvocation-from free_claude_code.cli.launchers.model_catalog import ClientModel-from free_claude_code.config.settings import Settings-from free_claude_code.core.json_types import JsonObject---def _settings(*, token: str = "proxy-token") -> Settings:- return Settings(- host="0.0.0.0",- port=9191,- proxy_auth_enabled=False,- proxy_auth_token=token,- model="nvidia_nim/test-model",- provider_progress_timeout=600,- )---def _models_payload() -> JsonObject:- return {- "data": [- {- "id": "nvidia_nim/vendor/model",- "provider_model_ref": "nvidia_nim/vendor/model",- "display_name": "Nested model",- },- {- "id": "claude-3-freecc-no-thinking/open_router/plain-model",- "provider_model_ref": "open_router/plain-model",- "display_name": "No-thinking model",- },- ]- }---def _models() -> tuple[ClientModel, ...]:- return (- ClientModel(- wire_slug="nvidia_nim/vendor/model",- provider_model_ref="nvidia_nim/vendor/model",- display_name="Nested model",- supports_reasoning=True,- ),- )+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch@pytest.mark.parametrize(- ("argv", "expected_args", "patch_index"),+ "args",[- ([], ("web",), 1),- (["--no-open"], ("web", "--no-open"), 1),- (["web"], ("web",), 1),- (["web", "--port", "3199"], ("web", "--port", "3199"), 1),- (- ["--profile", "web", "--no-open"],- ("--profile", "web", "--no-open"),- 2,- ),- (- ["--profile=headless", "write", "--patch", "as prompt"],- ("--profile=headless", "write", "--patch", "as prompt"),- 1,- ),- (- ["--profile", "headless", "hello"],- ("--profile", "headless", "hello"),- 2,- ),- (["--dump-config"], ("web", "--dump-config"), 1),- (- ["--profile", "web", "--dump-config"],- ("--profile", "web", "--dump-config"),- 3,- ),+ [],+ ["web", "--port", "8000"],+ ["--profile", "headless", "--prompt", "hello"],+ ["--profile", "future-native-profile", "--patch", "user.patch.yml"],+ ["--", "--help"],],)-def test_dsh_routed_surface_classification(- argv: list[str], expected_args: tuple[str, ...], patch_index: int+def test_dsh_attaches_patch_without_classifying_native_profiles(+ args: list[str], launch_capture: LaunchCapture) -> None:- from free_claude_code.cli.launchers.dsh import classify_dsh_invocation-- invocation = classify_dsh_invocation(argv)-- assert invocation.is_routed- assert invocation.args == expected_args- assert invocation.patch_index == patch_index--- "argv",- [- ["--help"],- ["-h"],- ["--version"],- ["-V"],- ["plugin", "--profile", "web", "list"],- ["web", "--help"],- ["--profile", "headless", "--help"],- ["--dump-default-config"],- ["web", "--dump-default-config"],- ["--profile", "web", "--dump-default-config"],- ],-)-def test_dsh_management_surfaces_are_native_passthrough(argv: list[str]) -> None:- from free_claude_code.cli.launchers.dsh import classify_dsh_invocation-- invocation = classify_dsh_invocation(argv)-- assert not invocation.is_routed- assert invocation.args == tuple(argv)--- "argv",- [- ["--patch", "custom.yml"],- ["--patch=custom.yml"],- ["web", "--patch", "custom.yml"],- ["--profile", "headless", "--patch=custom.yml", "task"],- ],-)-def test_dsh_caller_patch_is_rejected_before_launch(argv: list[str]) -> None:- from free_claude_code.cli.launchers.dsh import classify_dsh_invocation-- with pytest.raises(SystemExit) as exc_info:- classify_dsh_invocation(argv)-- assert exc_info.value.code == 2--- "argv",- [- ["--profile", "tui"],- ["--profile=custom", "task"],- ["--profile", ""],- ["--profile"],- ],-)-def test_dsh_unsupported_or_missing_profile_is_rejected(argv: list[str]) -> None:- from free_claude_code.cli.launchers.dsh import classify_dsh_invocation-- with pytest.raises(SystemExit) as exc_info:- classify_dsh_invocation(argv)-- assert exc_info.value.code == 2--- ("output", "return_code", "expected"),- [- ("0.1.0-rc.8\n", 0, "0.1.0-rc.8"),- ("dsh v0.1.0-rc.8\n", 0, "0.1.0-rc.8"),- ("0.1.0-rc.7\n", 0, "0.1.0-rc.7"),- ("0.1.0\n", 0, "0.1.0"),- ("not a version\n", 0, None),- ("0.1.0-rc.8\n", 1, None),- ],-)-def test_dsh_version_parsing(- output: str, return_code: int, expected: str | None-) -> None:- from free_claude_code.cli.launchers import dsh-- with patch.object(- dsh.subprocess,- "run",- return_value=SimpleNamespace(returncode=return_code, stdout=output),- ):- assert dsh.dsh_binary_version("resolved-dsh") == expected---def test_dsh_version_timeout_is_incompatible() -> None:- from free_claude_code.cli.launchers import dsh-- with patch.object(- dsh.subprocess,- "run",- side_effect=subprocess.TimeoutExpired("dsh", 5),- ):- assert dsh.dsh_binary_version("resolved-dsh") is None--[email protected]("version", ["0.1.0-rc.7", "0.1.0", "0.1.0-rc.9", None])-def test_dsh_requires_exact_audited_version_before_proxy(- version: str | None,- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import dsh-- with (- patch.object(dsh, "resolve_client_binary", return_value="resolved-dsh"),- patch.object(dsh, "dsh_binary_version", return_value=version),- patch.object(dsh, "get_settings") as get_settings,- pytest.raises(SystemExit) as exc_info,- ):- dsh.launch([])-- assert exc_info.value.code == 126- assert "0.1.0-rc.8" in capsys.readouterr().err- get_settings.assert_not_called()---def test_dsh_native_passthrough_needs_no_proxy() -> None:- from free_claude_code.cli.launchers import dsh-- with (- patch.object(dsh, "resolve_client_binary", return_value="resolved-dsh"),- patch.object(dsh, "get_settings") as get_settings,- patch.object(dsh, "require_compatible_dsh") as require_version,- patch.object(dsh, "run_client_process") as run_client_process,- ):- dsh.launch(["plugin", "--profile", "web", "list"])-- run_client_process.assert_called_once_with(- command=["resolved-dsh", "plugin", "--profile", "web", "list"],- env=os.environ,- binary_name="dsh",- display_name="DeepSeek Harness",- install_hint="Install the supported DeepSeek Harness release with: "- "npm install -g @deepseek-ai/[email protected]",- )- get_settings.assert_not_called()- require_version.assert_not_called()---def test_dsh_launch_prepares_authenticated_catalog_and_timeout() -> None:- from free_claude_code.cli.launchers import dsh-- with (- patch.object(dsh, "resolve_client_binary", return_value="resolved-dsh"),- patch.object(dsh, "require_compatible_dsh"),- patch.object(dsh, "get_settings", return_value=_settings()),- patch.object(dsh, "preflight_proxy", return_value=None),- patch.object(- dsh, "fetch_proxy_models_response", return_value=_models_payload()- ) as fetch_models,- patch.object(dsh, "_run_with_dsh_config") as run_configured,- ):- dsh.launch(["--profile", "headless", "hello", "world"])-- fetch_models.assert_called_once_with("http://127.0.0.1:9191", "proxy-token")- call = run_configured.call_args.kwargs- assert call["binary_path"] == "resolved-dsh"- assert call["invocation"] == DshInvocation(- args=("--profile", "headless", "hello", "world"), patch_index=2- )- assert [model.wire_slug for model in call["models"]] == [- "nvidia_nim/vendor/model",- "claude-3-freecc-no-thinking/open_router/plain-model",- ]- assert call["auth_token"] == "proxy-token"- assert call["provider_progress_timeout"] == 600---def test_dsh_proxy_failure_does_not_fetch_catalog(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import dsh-- with (- patch.object(dsh, "resolve_client_binary", return_value="resolved-dsh"),- patch.object(dsh, "require_compatible_dsh"),- patch.object(dsh, "get_settings", return_value=_settings()),- patch.object(dsh, "preflight_proxy", return_value="connection refused"),- patch.object(dsh, "fetch_proxy_models_response") as fetch_models,- pytest.raises(SystemExit) as exc_info,- ):- dsh.launch([])-- assert exc_info.value.code == 1- fetch_models.assert_not_called()- assert "fcc-server" in capsys.readouterr().err---def test_dsh_empty_proxy_token_fails_before_health_check() -> None:- from free_claude_code.cli.launchers import dsh-- with (- patch.object(dsh, "resolve_client_binary", return_value="resolved-dsh"),- patch.object(dsh, "require_compatible_dsh"),- patch.object(- dsh,- "get_settings",- return_value=SimpleNamespace(proxy_auth_token=" "),- ),- patch.object(dsh, "preflight_proxy") as preflight,- pytest.raises(SystemExit) as exc_info,- ):- dsh.launch([])-- assert exc_info.value.code == 1- preflight.assert_not_called()---def test_dsh_catalog_failure_never_starts_child(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import dsh-- with (- patch.object(dsh, "resolve_client_binary", return_value="resolved-dsh"),- patch.object(dsh, "require_compatible_dsh"),- patch.object(dsh, "get_settings", return_value=_settings()),- patch.object(dsh, "preflight_proxy", return_value=None),- patch.object(- dsh,- "fetch_proxy_models_response",- side_effect=RuntimeError("catalog unavailable"),- ),- patch.object(dsh, "_run_with_dsh_config") as run_configured,- pytest.raises(SystemExit) as exc_info,- ):- dsh.launch([])-- assert exc_info.value.code == 1- run_configured.assert_not_called()- assert "catalog unavailable" in capsys.readouterr().err---def test_dsh_child_environment_preserves_native_state_and_replaces_owned_keys() -> None:- from free_claude_code.cli.launchers.dsh import build_dsh_launcher_env-- env = build_dsh_launcher_env(- auth_token="proxy-token",- proxy_root_url="http://127.0.0.1:9191",- base_env={- "PATH": "keep",- "DSH_HOME": "native-home",- "DEEPSEEK_API_KEY": "native-key",- "FCC_DSH_API_KEY": "stale",- "FCC_DSH_OTHER": "stale",- "DSH_TELEMETRY_DISABLED": "0",- "NO_PROXY": "example.com",- },- )-- assert env["PATH"] == "keep"- assert env["DSH_HOME"] == "native-home"- assert env["DEEPSEEK_API_KEY"] == "native-key"- assert env["FCC_DSH_API_KEY"] == "proxy-token"- assert "FCC_DSH_OTHER" not in env- assert env["DSH_TELEMETRY_DISABLED"] == "1"- for key in ("NO_PROXY", "no_proxy"):- assert "example.com" in env[key]- assert "127.0.0.1" in env[key]---def test_dsh_private_config_lives_for_child_and_is_removed_after_exit(- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers import dsh-- observed_directory: Path | None = None-- def inspect_child(**kwargs: object) -> None:- nonlocal observed_directory- command = kwargs["command"]- env = kwargs["env"]- assert isinstance(command, list)- assert isinstance(env, dict)- patch_index = command.index("--patch") + 1- patch_path = Path(command[patch_index])- observed_directory = patch_path.parent- assert patch_path.is_file()- assert command[:4] == [- "resolved-dsh",- "--profile",- "headless",- "--patch",- ]- assert command[-1] == "hello"- patch_payload = json.loads(patch_path.read_text(encoding="utf-8"))- settings_path = patch_path.parent / "settings.yaml"- credentials_path = patch_path.parent / ".credentials.yaml"- assert json.loads(settings_path.read_text(encoding="utf-8")) == {}- assert json.loads(credentials_path.read_text(encoding="utf-8")) == {}- settings_row = next(row for row in patch_payload if row["id"] == "settings")- credentials_row = next(- row for row in patch_payload if row["id"] == "credentials"- )- assert settings_row["config"]["path"] == str(settings_path)- assert credentials_row["config"]["path"] == str(credentials_path)- assert "proxy-token" not in json.dumps(patch_payload)- assert env["FCC_DSH_API_KEY"] == "proxy-token"- raise SystemExit(23)-- invocation = DshInvocation(- args=("--profile", "headless", "hello"),- patch_index=2,- )- with (- patch.object(dsh.tempfile, "tempdir", str(tmp_path), create=True),- patch.object(dsh, "run_client_process", side_effect=inspect_child),- pytest.raises(SystemExit) as exc_info,- ):- dsh._run_with_dsh_config(- binary_path="resolved-dsh",- invocation=invocation,- models=_models(),- proxy_root_url="http://127.0.0.1:9191",- auth_token="proxy-token",- provider_progress_timeout=600,- )-- assert exc_info.value.code == 23- assert observed_directory is not None- assert not observed_directory.exists()---def test_dsh_empty_catalog_fails_before_child() -> None:- from free_claude_code.cli.launchers import dsh-- with (- patch.object(dsh, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- dsh._run_with_dsh_config(- binary_path="resolved-dsh",- invocation=DshInvocation(args=("web",), patch_index=1),- models=(),- proxy_root_url="http://127.0.0.1:9191",- auth_token="proxy-token",- provider_progress_timeout=600,- )-- assert exc_info.value.code == 1- run_client_process.assert_not_called()+ def inspect(command, env):+ path = Path(command[command.index("--patch") + 1])+ patch = json.loads(path.read_text())+ serialized = json.dumps(patch)+ assert "openai-responses" in serialized+ assert "http://127.0.0.1:8182/v1" in serialized+ assert "nvidia_nim/catalog-model:variant" in serialized+ assert json.loads((path.parent / "settings.yaml").read_text()) == {}+ assert json.loads((path.parent / ".credentials.yaml").read_text()) == {}+ assert env["FCC_DSH_API_KEY"] == "launcher-test-token"+ assert env["DSH_TELEMETRY_DISABLED"] == "1"+ assert "launcher-test-token" not in serialized++ launch_capture.on_start = inspect+ launch("dsh", args)+ command = launch_capture.commands[0]+ if not args or args[0] == "web":+ assert command[:3] == ["dsh", "web", "--patch"]+ assert command[4:] == args[1:]+ else:+ assert command[:4] == ["dsh", "--profile", "web", "--patch"]+ assert command[5:] == argsdiff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex e889749e..5642314b 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -8,8 +8,6 @@ from collections.abc import Callablefrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch-from urllib.error import URLError-from urllib.request import Requestimport pytest@@ -32,26 +30,6 @@ def _launcher_settings()-class _JsonResponse:- def __init__(self, payload: dict[str, object]) -> None:- self._payload = payload-- def __enter__(self) -> _JsonResponse:- return self-- def __exit__(self, *_args: object) -> None:- return None-- def read(self) -> bytes:- return json.dumps(self._payload).encode("utf-8")---def empty_proxy_bypass_env(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.delenv("NO_PROXY", raising=False)- monkeypatch.delenv("no_proxy", raising=False)--def test_cli_scripts_are_registered() -> None:pyproject = tomllib.loads((Path(__file__).resolve().parents[2] / "pyproject.toml").read_text(@@ -471,725 +449,3 @@ def test_claude_child_env_targets_current_proxy_config() -> None:assert "ANTHROPIC_API_URL" not in envassert "ANTHROPIC_API_KEY" not in envassert "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" not in env---def test_launch_claude_passes_args_and_child_env(- monkeypatch: pytest.MonkeyPatch,- empty_proxy_bypass_env: None,-) -> None:- from free_claude_code.cli.launchers.claude import launch-- monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com")- monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "old-token")- monkeypatch.setenv("KEEP_ME", "yes")- monkeypatch.delenv("DISABLE_TELEMETRY", raising=False)- settings = _launcher_settings(port=9191, token="proxy-token")-- with (- patch(- "free_claude_code.cli.launchers.claude.get_settings", return_value=settings- ),- patch(- "free_claude_code.cli.launchers.claude.preflight_proxy", return_value=None- ),- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-claude.cmd",- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- patch("free_claude_code.cli.launchers.common.register_pid") as register_pid,- patch("free_claude_code.cli.launchers.common.unregister_pid") as unregister_pid,- pytest.raises(SystemExit) as exc_info,- ):- process = popen.return_value- process.pid = 12345- process.wait.return_value = 7- launch(["--model", "sonnet"])-- assert exc_info.value.code == 7- popen.assert_called_once()- assert popen.call_args.args[0] == [- "resolved-claude.cmd",- "--permission-mode",- "default",- "--model",- "sonnet",- ]- child_env = popen.call_args.kwargs["env"]- assert child_env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:9191"- assert child_env["ANTHROPIC_AUTH_TOKEN"] == "proxy-token"- assert child_env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"- assert child_env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] == "190000"- assert child_env["DISABLE_AUTOUPDATER"] == "1"- assert child_env["DISABLE_FEEDBACK_COMMAND"] == "1"- assert child_env["DISABLE_ERROR_REPORTING"] == "1"- assert "DISABLE_TELEMETRY" not in child_env- assert child_env["NO_PROXY"] == "127.0.0.1,localhost,::1"- assert child_env["no_proxy"] == child_env["NO_PROXY"]- assert "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" not in child_env- assert child_env["KEEP_ME"] == "yes"- register_pid.assert_called_once_with(12345)- unregister_pid.assert_called_once_with(12345)---def test_launch_codex_passes_responses_config_and_child_env(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- empty_proxy_bypass_env: None,-) -> None:- from free_claude_code.cli.launchers.codex import launch-- monkeypatch.setenv("OPENAI_API_KEY", "official-key")- monkeypatch.setenv("OPENAI_BASE_URL", "https://api.openai.com/v1")- monkeypatch.setenv("CODEX_HOME", "keep-home")- monkeypatch.setenv("CODEX_INTERNAL_ORIGINATOR_OVERRIDE", "Codex Desktop")- monkeypatch.setenv("CODEX_PERMISSION_PROFILE", "danger-full-access")- monkeypatch.setenv("CODEX_SHELL", "1")- monkeypatch.setenv("CODEX_THREAD_ID", "parent-thread")- settings = _launcher_settings(port=9191, token="proxy-token")- catalog_path = tmp_path / "codex-model-catalog.json"- requests: list[Request] = []-- def fake_urlopen(request: Request, *, timeout: float) -> _JsonResponse:- requests.append(request)- assert timeout == 1.5- return _JsonResponse(- {- "data": [- {- "id": "nvidia_nim/provider-model",- "provider_model_ref": "nvidia_nim/provider-model",- "display_name": "NVIDIA model",- },- {- "id": "claude-opus-4-20250514",- "display_name": "Claude Opus 4",- },- ]- }- )-- with (- patch(- "free_claude_code.cli.launchers.codex.get_settings", return_value=settings- ),- patch(- "free_claude_code.cli.launchers.codex.preflight_proxy", return_value=None- ),- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-codex.cmd",- ),- patch(- "free_claude_code.cli.launchers.codex.codex_model_catalog_path",- return_value=catalog_path,- ),- patch(- "free_claude_code.cli.launchers.model_catalog.open_local_request",- side_effect=fake_urlopen,- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- patch("free_claude_code.cli.launchers.common.register_pid") as register_pid,- patch("free_claude_code.cli.launchers.common.unregister_pid") as unregister_pid,- pytest.raises(SystemExit) as exc_info,- ):- process = popen.return_value- process.pid = 12345- process.wait.return_value = 0- launch(["exec", "hello"])-- assert exc_info.value.code == 0- command = popen.call_args.args[0]- assert command[0] == "resolved-codex.cmd"- assert 'model_provider="fcc"' in command- assert 'model_providers.fcc.base_url="http://127.0.0.1:9191/v1"' in command- assert 'model_providers.fcc.auth.command="fcc-codex"' in command- assert 'model_providers.fcc.auth.args=["--print-proxy-auth-token"]' in command- assert 'model_providers.fcc.wire_api="responses"' in command- assert not any("model_providers.fcc.env_key" in arg for arg in command)- assert f"model_catalog_json={json.dumps(str(catalog_path))}" in command- assert command[-2:] == ["exec", "hello"]- assert len(requests) == 1- request = requests[0]- assert request.full_url == "http://127.0.0.1:9191/v1/models?view=responses"- headers = {key.lower(): value for key, value in request.header_items()}- assert headers["authorization"] == "Bearer proxy-token"- assert "x-api-key" not in headers- catalog = json.loads(catalog_path.read_text(encoding="utf-8"))- assert [model["slug"] for model in catalog["models"]] == [- "nvidia_nim/provider-model"- ]- child_env = popen.call_args.kwargs["env"]- assert "FCC_CODEX_API_KEY" not in child_env- assert child_env["CODEX_HOME"] == "keep-home"- assert child_env["NO_PROXY"] == "127.0.0.1,localhost,::1"- assert child_env["no_proxy"] == child_env["NO_PROXY"]- assert "CODEX_INTERNAL_ORIGINATOR_OVERRIDE" not in child_env- assert "CODEX_PERMISSION_PROFILE" not in child_env- assert "CODEX_SHELL" not in child_env- assert "CODEX_THREAD_ID" not in child_env- assert "OPENAI_API_KEY" not in child_env- assert "OPENAI_BASE_URL" not in child_env- register_pid.assert_called_once_with(12345)- unregister_pid.assert_called_once_with(12345)---def test_launch_codex_selects_the_slug_its_catalog_advertises(- tmp_path: Path,- empty_proxy_bypass_env: None,-) -> None:- """A non-thinking configured model is advertised under its no-thinking slug."""-- from free_claude_code.cli.launchers.codex import launch-- settings = _launcher_settings(port=9191, token="proxy-token")- catalog_path = tmp_path / "codex-model-catalog.json"- no_thinking_slug = "claude-3-freecc-no-thinking/nvidia_nim/test-model"-- def fake_urlopen(request: Request, *, timeout: float) -> _JsonResponse:- del request, timeout- return _JsonResponse(- {- "data": [- {- "id": no_thinking_slug,- "provider_model_ref": "nvidia_nim/test-model",- "display_name": "NVIDIA model (no thinking)",- }- ]- }- )-- with (- patch(- "free_claude_code.cli.launchers.codex.get_settings", return_value=settings- ),- patch(- "free_claude_code.cli.launchers.codex.preflight_proxy", return_value=None- ),- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-codex.cmd",- ),- patch(- "free_claude_code.cli.launchers.codex.codex_model_catalog_path",- return_value=catalog_path,- ),- patch(- "free_claude_code.cli.launchers.model_catalog.open_local_request",- side_effect=fake_urlopen,- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- patch("free_claude_code.cli.launchers.common.register_pid"),- patch("free_claude_code.cli.launchers.common.unregister_pid"),- pytest.raises(SystemExit),- ):- process = popen.return_value- process.pid = 12345- process.wait.return_value = 0- launch(["exec", "hello"])-- command = popen.call_args.args[0]- catalog = json.loads(catalog_path.read_text(encoding="utf-8"))- assert [model["slug"] for model in catalog["models"]] == [no_thinking_slug]- assert f"model={json.dumps(no_thinking_slug)}" in command- assert 'model="nvidia_nim/test-model"' not in command---def test_launch_codex_keeps_the_configured_ref_without_a_catalog(- tmp_path: Path,- empty_proxy_bypass_env: None,-) -> None:- """A failed catalog fetch must not change the model Codex is told to use."""-- from free_claude_code.cli.launchers.codex import launch-- settings = _launcher_settings(port=9191, token="proxy-token")-- with (- patch(- "free_claude_code.cli.launchers.codex.get_settings", return_value=settings- ),- patch(- "free_claude_code.cli.launchers.codex.preflight_proxy", return_value=None- ),- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-codex.cmd",- ),- patch(- "free_claude_code.cli.launchers.codex.codex_model_catalog_path",- return_value=tmp_path / "codex-model-catalog.json",- ),- patch(- "free_claude_code.cli.launchers.model_catalog.open_local_request",- side_effect=URLError("boom"),- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- patch("free_claude_code.cli.launchers.common.register_pid"),- patch("free_claude_code.cli.launchers.common.unregister_pid"),- pytest.raises(SystemExit),- ):- process = popen.return_value- process.pid = 12345- process.wait.return_value = 0- launch(["exec", "hello"])-- assert 'model="nvidia_nim/test-model"' in popen.call_args.args[0]---def test_codex_empty_catalog_keeps_the_configured_ref_without_catalog_config(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import codex-- settings = _launcher_settings(port=9191, token="proxy-token")- with (- patch.object(codex, "fetch_proxy_models_response", return_value={"data": []}),- patch.object(codex, "write_codex_model_catalog") as write_catalog,- ):- catalog = codex.codex_model_catalog_plan("http://127.0.0.1:9191", settings)-- command = codex.build_codex_launcher_command(- binary_path="resolved-codex.cmd",- argv=("exec", "hello"),- settings=settings,- proxy_root_url="http://127.0.0.1:9191",- catalog_config_args=catalog.config_args,- catalog_models=catalog.models,- )-- assert catalog == codex.CodexModelCatalogPlan()- assert not any("model_catalog_json=" in arg for arg in command)- assert 'model="nvidia_nim/test-model"' in command- write_catalog.assert_not_called()- assert "Codex model catalog is empty" in capsys.readouterr().err--- "failing_step", ("build_codex_model_catalog", "write_codex_model_catalog")-)-def test_codex_catalog_plan_fails_open_when_catalog_processing_fails(- failing_step: str,- capsys: pytest.CaptureFixture[str],- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers import codex-- settings = _launcher_settings(port=9191, token="proxy-token")- models_response = {- "data": [- {- "id": "nvidia_nim/test-model",- "provider_model_ref": "nvidia_nim/test-model",- "display_name": "NVIDIA model",- }- ]- }- with (- patch.object(- codex, "fetch_proxy_models_response", return_value=models_response- ),- patch.object(- codex,- "codex_model_catalog_path",- return_value=tmp_path / "codex-model-catalog.json",- ),- patch.object(codex, failing_step, side_effect=OSError("boom")),- ):- catalog = codex.codex_model_catalog_plan("http://127.0.0.1:9191", settings)-- assert catalog == codex.CodexModelCatalogPlan()- captured = capsys.readouterr()- assert "could not prepare Codex model catalog" in captured.err- assert "launching without model picker catalog" in captured.err---def test_codex_proxy_auth_command_prints_only_current_token(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import codex-- settings = _launcher_settings(token=" proxy-token ")- with (- patch.object(codex, "get_settings", return_value=settings) as get_settings,- patch.object(codex, "preflight_proxy") as preflight_proxy,- patch.object(codex, "resolve_client_binary") as resolve_client_binary,- patch(- "free_claude_code.cli.launchers.model_catalog.open_local_request"- ) as open_local_request,- patch.object(codex, "run_client_process") as run_client_process,- ):- codex.launch(["--print-proxy-auth-token"])-- assert capsys.readouterr() == ("proxy-token\n", "")- get_settings.assert_called_once_with()- preflight_proxy.assert_not_called()- resolve_client_binary.assert_not_called()- open_local_request.assert_not_called()- run_client_process.assert_not_called()---def test_launch_codex_catalog_failure_warns_and_continues(- capsys: pytest.CaptureFixture[str],- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.codex import launch-- settings = _launcher_settings(port=9191, token="proxy-token")-- with (- patch(- "free_claude_code.cli.launchers.codex.get_settings", return_value=settings- ),- patch(- "free_claude_code.cli.launchers.codex.preflight_proxy", return_value=None- ),- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-codex.cmd",- ),- patch(- "free_claude_code.cli.launchers.codex.codex_model_catalog_path",- return_value=tmp_path / "codex-model-catalog.json",- ),- patch(- "free_claude_code.cli.launchers.model_catalog.open_local_request",- side_effect=URLError("boom"),- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- patch("free_claude_code.cli.launchers.common.register_pid"),- patch("free_claude_code.cli.launchers.common.unregister_pid"),- pytest.raises(SystemExit) as exc_info,- ):- process = popen.return_value- process.pid = 12345- process.wait.return_value = 0- launch(["exec", "hello"])-- assert exc_info.value.code == 0- command = popen.call_args.args[0]- assert not any("model_catalog_json=" in arg for arg in command)- captured = capsys.readouterr()- assert "could not prepare Codex model catalog" in captured.err- assert "launching without model picker catalog" in captured.err---def test_pi_launcher_builds_scoped_session_command_and_proxy_env(- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.pi import (- build_pi_launcher_command,- build_pi_launcher_env,- )-- extension = tmp_path / "pi_extension.ts"- env = build_pi_launcher_env(- proxy_root_url="http://127.0.0.1:9191/",- auth_token="proxy-token",- base_env={- "PATH": "keep",- "ANTHROPIC_API_KEY": "native-pi-credential",- "FCC_PI_API_KEY": "stale-key",- "FCC_PI_BASE_URL": "https://stale.invalid",- },- )-- assert build_pi_launcher_command(- binary_path="resolved-pi.cmd",- extension_path=extension,- argv=["--print", "hello"],- ) == [- "resolved-pi.cmd",- "-e",- str(extension),- "--models",- "free-claude-code/**",- "--print",- "hello",- ]- assert env == {- "PATH": "keep",- "ANTHROPIC_API_KEY": "native-pi-credential",- "NO_PROXY": "127.0.0.1,localhost,::1",- "no_proxy": "127.0.0.1,localhost,::1",- "FCC_PI_BASE_URL": "http://127.0.0.1:9191",- "FCC_PI_API_KEY": "proxy-token",- }---def test_launch_pi_registers_bundled_extension_for_sessions(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- empty_proxy_bypass_env: None,-) -> None:- from free_claude_code.cli.launchers.pi import launch-- monkeypatch.setenv("KEEP_ME", "yes")- monkeypatch.setenv("FCC_PI_API_KEY", "stale-key")- extension = tmp_path / "pi_extension.ts"- extension.write_text("export default () => {};", encoding="utf-8")- settings = _launcher_settings(port=9191, token="proxy-token")-- with (- patch("free_claude_code.cli.launchers.pi.get_settings", return_value=settings),- patch("free_claude_code.cli.launchers.pi.preflight_proxy", return_value=None),- patch(- "free_claude_code.cli.launchers.pi.pi_extension_path",- return_value=extension,- ),- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-pi.cmd",- ),- patch(- "free_claude_code.cli.launchers.pi.pi_binary_is_compatible",- return_value=True,- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- patch("free_claude_code.cli.launchers.common.register_pid"),- patch("free_claude_code.cli.launchers.common.unregister_pid"),- pytest.raises(SystemExit) as exc_info,- ):- process = popen.return_value- process.pid = 12345- process.wait.return_value = 0- launch(["--print", "hello"])-- assert exc_info.value.code == 0- assert popen.call_args.args[0] == [- "resolved-pi.cmd",- "-e",- str(extension),- "--models",- "free-claude-code/**",- "--print",- "hello",- ]- child_env = popen.call_args.kwargs["env"]- assert child_env["FCC_PI_BASE_URL"] == "http://127.0.0.1:9191"- assert child_env["FCC_PI_API_KEY"] == "proxy-token"- assert child_env["NO_PROXY"] == "127.0.0.1,localhost,::1"- assert child_env["no_proxy"] == child_env["NO_PROXY"]- assert child_env["KEEP_ME"] == "yes"--- "argv",- [- ["--help"],- ["--version"],- ["config", "set", "theme", "dark"],- ["install", "npm:example"],- ["list"],- ["remove", "npm:example"],- ["uninstall", "npm:example"],- ["update"],- ],-)-def test_launch_pi_passes_management_commands_through_without_proxy(- argv: list[str],-) -> None:- from free_claude_code.cli.launchers.pi import launch-- with (- patch("free_claude_code.cli.launchers.pi.get_settings") as get_settings,- patch("free_claude_code.cli.launchers.pi.preflight_proxy") as preflight,- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-pi",- ),- patch(- "free_claude_code.cli.launchers.pi.pi_binary_is_compatible",- return_value=True,- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- patch("free_claude_code.cli.launchers.common.register_pid"),- patch("free_claude_code.cli.launchers.common.unregister_pid"),- pytest.raises(SystemExit) as exc_info,- ):- process = popen.return_value- process.pid = 12345- process.wait.return_value = 0- launch(argv)-- assert exc_info.value.code == 0- assert popen.call_args.args[0] == ["resolved-pi", *argv]- get_settings.assert_not_called()- preflight.assert_not_called()---def test_launch_pi_fails_closed_when_bundled_extension_is_missing(- capsys: pytest.CaptureFixture[str],- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.pi import launch-- settings = _launcher_settings(port=9191)- with (- patch("free_claude_code.cli.launchers.pi.get_settings", return_value=settings),- patch("free_claude_code.cli.launchers.pi.preflight_proxy", return_value=None),- patch(- "free_claude_code.cli.launchers.pi.pi_extension_path",- return_value=tmp_path / "missing.ts",- ),- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-pi",- ),- patch(- "free_claude_code.cli.launchers.pi.pi_binary_is_compatible",- return_value=True,- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- pytest.raises(SystemExit) as exc_info,- ):- launch([])-- assert exc_info.value.code == 1- popen.assert_not_called()- assert "bundled Pi extension is missing" in capsys.readouterr().err---def test_pi_install_hints_use_official_platform_installers() -> None:- from free_claude_code.cli.launchers.pi import pi_install_hint-- assert "https://pi.dev/install.ps1" in pi_install_hint("win32")- assert "https://pi.dev/install.sh" in pi_install_hint("darwin")--- ("help_output", "return_code", "expected"),- [- ("--extension <path>\n--models <patterns>\n", 0, True),- ("--models <patterns>\n", 0, False),- ("--extension <path>\n", 0, False),- ("--extension <path>\n--models <patterns>\n", 1, False),- ],-)-def test_pi_binary_compatibility_requires_both_launcher_capabilities(- help_output: str,- return_code: int,- expected: bool,-) -> None:- from free_claude_code.cli.launchers.pi import pi_binary_is_compatible-- with patch(- "free_claude_code.cli.launchers.pi.subprocess.run",- return_value=SimpleNamespace(returncode=return_code, stdout=help_output),- ):- assert pi_binary_is_compatible("resolved-pi") is expected---def test_launch_pi_rejects_unrelated_pi_binary(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers.pi import launch-- with (- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="unrelated-pi",- ),- patch(- "free_claude_code.cli.launchers.pi.pi_binary_is_compatible",- return_value=False,- ),- patch("free_claude_code.cli.launchers.pi.get_settings") as get_settings,- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- pytest.raises(SystemExit) as exc_info,- ):- launch([])-- assert exc_info.value.code == 126- get_settings.assert_not_called()- popen.assert_not_called()- captured = capsys.readouterr()- assert "not a compatible Pi Coding Agent" in captured.err- assert "https://pi.dev/install." in captured.err---def test_launch_claude_keyboard_interrupt_kills_child_tree() -> None:- from free_claude_code.cli.launchers.claude import launch-- settings = _launcher_settings(port=9191, token="proxy-token")-- with (- patch(- "free_claude_code.cli.launchers.claude.get_settings", return_value=settings- ),- patch(- "free_claude_code.cli.launchers.claude.preflight_proxy", return_value=None- ),- patch(- "free_claude_code.cli.launchers.common.shutil.which",- return_value="resolved-claude.cmd",- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- patch("free_claude_code.cli.launchers.common.register_pid"),- patch(- "free_claude_code.cli.launchers.common.kill_pid_tree_best_effort"- ) as kill_tree,- patch("free_claude_code.cli.launchers.common.unregister_pid") as unregister_pid,- pytest.raises(KeyboardInterrupt),- ):- process = popen.return_value- process.pid = 12345- process.wait.side_effect = [KeyboardInterrupt, 0]-- launch([])-- kill_tree.assert_called_once_with(12345)- unregister_pid.assert_called_once_with(12345)---def test_launch_claude_exits_when_command_cannot_be_resolved(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers.claude import launch-- settings = _launcher_settings()- with (- patch(- "free_claude_code.cli.launchers.claude.get_settings", return_value=settings- ),- patch(- "free_claude_code.cli.launchers.claude.preflight_proxy", return_value=None- ),- patch("free_claude_code.cli.launchers.common.shutil.which", return_value=None),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- pytest.raises(SystemExit) as exc_info,- ):- launch([])-- assert exc_info.value.code == 127- popen.assert_not_called()- captured = capsys.readouterr()- assert "Could not find Claude Code command: claude" in captured.err- assert "npm install -g @anthropic-ai/claude-code" in captured.err---def test_launch_claude_unreachable_proxy_exits_with_hint(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers.claude import launch-- settings = _launcher_settings(port=9393)- with (- patch(- "free_claude_code.cli.launchers.claude.get_settings", return_value=settings- ),- patch(- "free_claude_code.cli.launchers.claude.preflight_proxy",- return_value="connection refused",- ),- patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,- pytest.raises(SystemExit) as exc_info,- ):- launch([])-- assert exc_info.value.code == 1- popen.assert_not_called()- captured = capsys.readouterr()- assert "http://127.0.0.1:9393" in captured.err- assert "fcc-server" in captured.errdiff --git a/tests/cli/test_grok_launcher.py b/tests/cli/test_grok_launcher.pyindex 86de1daf..3be26c96 100644--- a/tests/cli/test_grok_launcher.py+++ b/tests/cli/test_grok_launcher.py@@ -1,481 +1,51 @@-"""Contract tests for the installed `fcc-grok` launcher."""+"""Grok's native configuration and connection-option placement."""import json-import subprocess-from types import SimpleNamespace-from unittest.mock import patchimport pytest-from free_claude_code.cli.launchers.model_catalog import ClientModel-from free_claude_code.config.settings import Settings-from free_claude_code.core.json_types import JsonObject---def _settings(*, token: str = "proxy-token") -> Settings:- return Settings(- host="0.0.0.0",- port=9191,- proxy_auth_enabled=False,- proxy_auth_token=token,- model="nvidia_nim/test-model",- )---def _models() -> tuple[ClientModel, ...]:- return (- ClientModel(- wire_slug="nvidia_nim/vendor/model",- provider_model_ref="nvidia_nim/vendor/model",- display_name="Nested model",- supports_reasoning=True,- ),- ClientModel(- wire_slug="claude-3-freecc-no-thinking/open_router/plain-model",- provider_model_ref="open_router/plain-model",- display_name="Plain model",- supports_reasoning=False,- ),- )---def _models_payload() -> JsonObject:- return {- "object": "list",- "data": [- {- "id": model.wire_slug,- "provider_model_ref": model.provider_model_ref,- "display_name": model.display_name,- }- for model in _models()- ],- }--- "argv",- [- [],- ["fix the bug"],- ["-p", "fix the bug"],- ["--single=fix the bug"],- ["--prompt-json", "[]"],- ["--prompt-file", "prompt.json"],- ["--cwd", "workspace", "agent", "--model", "nvidia_nim/model", "stdio"],- ],-)-def test_attached_grok_surfaces_are_routed(argv: list[str]) -> None:- from free_claude_code.cli.launchers.grok import (- GrokInvocationMode,- classify_grok_invocation,- )-- invocation = classify_grok_invocation(argv)-- assert invocation.mode is GrokInvocationMode.ROUTED- if "agent" in argv:- assert invocation.agent_index is not None--[email protected]("argv", [["models"], ["inspect"], ["inspect", "--json"]])-def test_catalog_surfaces_receive_fcc_configuration(argv: list[str]) -> None:- from free_claude_code.cli.launchers.grok import (- GrokInvocationMode,- classify_grok_invocation,- )-- assert classify_grok_invocation(argv).mode is GrokInvocationMode.CONFIGURED+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch@pytest.mark.parametrize(- "argv",- [- ["--help"],- ["--version"],- ["version", "--json"],- ["doctor"],- ["login", "--oauth"],- ["logout"],- ["mcp", "list"],- ["plugin", "list"],- ["memory", "status"],- ["sessions", "list"],- ["setup"],- ["share", "session"],- ["wrap", "git", "status"],- ["export", "session"],- ["trace", "list"],- ["update", "--check"],- ["completions", "powershell"],- ["worktree", "list"],- ["du"],- ["disk-usage"],- ],-)-def test_management_surfaces_are_native_passthrough(argv: list[str]) -> None:- from free_claude_code.cli.launchers.grok import (- GrokInvocationMode,- classify_grok_invocation,- )-- assert classify_grok_invocation(argv).mode is GrokInvocationMode.PASSTHROUGH--- "argv",- [- ["agent"],- ["agent", "headless"],- ["agent", "serve"],- ["agent", "leader"],- ["agent", "future-mode"],- ["leader", "list"],- ["workspace", "start"],- ["dashboard"],- ],-)-def test_detached_surfaces_are_rejected(argv: list[str]) -> None:- from free_claude_code.cli.launchers.grok import classify_grok_invocation-- with pytest.raises(SystemExit) as exc_info:- classify_grok_invocation(argv)-- assert exc_info.value.code == 2--- "argv",- [- ["--leader"],- ["--oauth"],- ["--force-login"],- ["--xai-api-base-url", "https://example.test"],- ["--xai-api-base-url=https://example.test"],- ["agent", "--cli-chat-proxy-base-url", "https://example.test", "stdio"],- ],-)-def test_route_bypass_flags_are_rejected_before_version_probe(argv: list[str]) -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "require_compatible_grok") as require_version,- pytest.raises(SystemExit) as exc_info,- ):- grok.launch(argv)-- assert exc_info.value.code == 2- require_version.assert_not_called()--- ("output", "return_code", "expected"),+ ("args", "expected"),[+ ([], ["grok", "--disable-web-search", "--no-leader"]),+ (+ ["-p", "hello"],+ ["grok", "--disable-web-search", "--no-leader", "-p", "hello"],+ ),(- '{"currentVersion":"1.0.5 (5115b46bc9)","channel":"stable"}',- 0,- (1, 0, 5),+ ["agent", "stdio"],+ ["grok", "--disable-web-search", "agent", "--no-leader", "stdio"],+ ),+ (+ ["--", "agent"],+ ["grok", "--disable-web-search", "--no-leader", "--", "agent"],),- ('{"channel":"stable","currentVersion":"1.2.3+build.1"}', 0, (1, 2, 3)),- ('{"currentVersion":"1.0.5","channel":"unknown"}', 0, (1, 0, 5)),- ('{"currentVersion":"1.2.3","channel":"alpha"}', 0, (1, 2, 3)),- ('{"currentVersion":"1.2.3-alpha.1","channel":"stable"}', 0, None),- ('{"currentVersion":123,"channel":"stable"}', 0, None),- ('{"currentVersion":"1.2.3","channel":"stable"}', 1, None),- ('{"currentVersion":"1.2.3\t(build)","channel":"stable"}', 0, None),- ("not-json", 0, None),- ("[]", 0, None),],)-def test_grok_version_probe(- output: str,- return_code: int,- expected: tuple[int, int, int] | None,-) -> None:- from free_claude_code.cli.launchers import grok-- with patch.object(- grok.subprocess,- "run",- return_value=SimpleNamespace(stdout=output, returncode=return_code),- ) as run:- assert grok.grok_binary_version("resolved-grok") == expected- run.assert_called_once_with(- ["resolved-grok", "version", "--json"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- timeout=5.0,- )---def test_grok_version_probe_handles_timeout() -> None:- from free_claude_code.cli.launchers import grok-- with patch.object(- grok.subprocess,- "run",- side_effect=subprocess.TimeoutExpired("grok", 5),- ):- assert grok.grok_binary_version("resolved-grok") is None--[email protected]("version", [(1, 0, 4), None])-def test_incompatible_grok_fails_before_settings(- version: tuple[int, int, int] | None,+def test_grok_connection_options_use_native_scopes(+ args, expected, launch_capture: LaunchCapture) -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "grok_binary_version", return_value=version),- patch.object(grok, "get_settings") as get_settings,- pytest.raises(SystemExit) as exc_info,- ):- grok.launch([])-- assert exc_info.value.code == 1- get_settings.assert_not_called()---def test_native_passthrough_needs_no_proxy_or_version() -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "get_settings") as get_settings,- patch.object(grok, "require_compatible_grok") as require_version,- patch.object(grok, "run_client_process") as run_client_process,- ):- grok.launch(["plugin", "list"])-- assert run_client_process.call_args.kwargs["command"] == [- "resolved-grok",- "plugin",- "list",- ]- get_settings.assert_not_called()- require_version.assert_not_called()---def test_routed_launch_uses_catalog_model_and_injects_safety_flags() -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "require_compatible_grok"),- patch.object(grok, "get_settings", return_value=_settings()),- patch.object(grok, "preflight_proxy", return_value=None),- patch.object(- grok, "fetch_proxy_models_response", return_value=_models_payload()- ) as fetch_models,- patch.object(grok, "run_client_process") as run_client_process,- ):- grok.launch(["--model", "nvidia_nim/vendor/model", "-p", "hello"])-- fetch_models.assert_called_once_with("http://127.0.0.1:9191", "proxy-token")- call = run_client_process.call_args.kwargs- assert call["command"] == [- "resolved-grok",- "--no-leader",- "--disable-web-search",- "--model",- "nvidia_nim/vendor/model",- "-p",- "hello",- ]- assert call["env"]["GROK_DEFAULT_MODEL"] == "nvidia_nim/vendor/model"---def test_agent_stdio_inserts_flags_in_their_parser_scopes() -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "require_compatible_grok"),- patch.object(grok, "get_settings", return_value=_settings()),- patch.object(grok, "preflight_proxy", return_value=None),- patch.object(- grok, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(grok, "run_client_process") as run_client_process,- ):- grok.launch(["--cwd", "agent", "agent", "--always-approve", "stdio"])-- assert run_client_process.call_args.kwargs["command"] == [- "resolved-grok",- "--disable-web-search",- "--cwd",- "agent",- "agent",- "--no-leader",- "--always-approve",- "stdio",- ]---def test_grok_environment_preserves_native_state_and_replaces_owned_route() -> None:- from free_claude_code.cli.launchers.grok import build_grok_launcher_env-- env = build_grok_launcher_env(- models=_models(),- selected_model="nvidia_nim/vendor/model",- proxy_root_url="http://127.0.0.1:9191",- auth_token="proxy-token",- base_env={- "PATH": "keep",- "GROK_HOME": "native-home",- "GROK_TELEMETRY": "native-value",- "FCC_GROK_STALE": "remove",- "GROK_XAI_API_BASE_URL": "https://api.x.ai/v1",- "GROK_MODELS_BASE_URL": "https://native.example/v1",- "GROK_MODELS_LIST_URL": "https://native.example/models",- "GROK_DEFAULT_MODEL": "native-model",- "GROK_IMAGE_DESCRIPTION_MODEL": "native-model",- "GROK_PROMPT_SUGGESTIONS_MODEL": "native-model",- "GROK_SESSION_SUMMARY_MODEL": "native-model",- "GROK_WEB_SEARCH_MODEL": "native-model",- "XAI_API_KEY": "native-key",- "GROK_CODE_XAI_API_KEY": "legacy-key",- "NO_PROXY": "example.com",- },- )-- assert env["PATH"] == "keep"- assert env["GROK_HOME"] == "native-home"- assert env["GROK_TELEMETRY"] == "native-value"- assert "FCC_GROK_STALE" not in env- assert env["GROK_XAI_API_BASE_URL"] == "http://127.0.0.1:9191/v1"- assert env["GROK_MODELS_BASE_URL"] == "http://127.0.0.1:9191/v1"+ launch("grok", args)+ assert launch_capture.commands == [expected]+ env = launch_capture.environments[0]+ assert env["GROK_XAI_API_BASE_URL"] == "http://127.0.0.1:8182/v1"assert (- env["GROK_MODELS_LIST_URL"] == "http://127.0.0.1:9191/v1/models?view=responses"+ env["GROK_MODELS_LIST_URL"] == "http://127.0.0.1:8182/v1/models?view=responses")- assert env["GROK_DEFAULT_MODEL"] == "nvidia_nim/vendor/model"- assert env["GROK_IMAGE_DESCRIPTION_MODEL"] == "nvidia_nim/vendor/model"- assert env["GROK_PROMPT_SUGGESTIONS_MODEL"] == "nvidia_nim/vendor/model"- assert env["GROK_SESSION_SUMMARY_MODEL"] == "nvidia_nim/vendor/model"- assert env["GROK_WEB_SEARCH_MODEL"] == "nvidia_nim/vendor/model"- assert env["XAI_API_KEY"] == "proxy-token"- assert "GROK_CODE_XAI_API_KEY" not in env- assert json.loads(env["GROK_CONFIG"]) == {- "models": {- "allowed_models": [- "nvidia_nim/vendor/model",- "claude-3-freecc-no-thinking/open_router/plain-model",- ]- },- "shell_environment_policy": {"ignore_default_excludes": False},- }- assert "proxy-token" not in env["GROK_CONFIG"]- for key in ("NO_PROXY", "no_proxy"):- assert "example.com" in env[key]- assert "127.0.0.1" in env[key]+ assert env["XAI_API_KEY"] == "launcher-test-token"+ assert json.loads(env["GROK_CONFIG"])["models"]["allowed_models"] == [+ "nvidia_nim/catalog-model:variant"+ ][email protected]("key", ["GROK_CONFIG", "GROK_CONFIG_PATH"])-def test_existing_process_overlay_is_rejected(- key: str, monkeypatch: pytest.MonkeyPatch[email protected]("key", ("GROK_CONFIG", "GROK_CONFIG_PATH"))+def test_existing_grok_process_config_is_not_replaced(+ key: str, launch_capture: LaunchCapture, monkeypatch: pytest.MonkeyPatch) -> None:- from free_claude_code.cli.launchers import grok-- monkeypatch.setenv(key, "owner-config")- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "require_compatible_grok") as require_version,- pytest.raises(SystemExit) as exc_info,- ):- grok.launch([])-- assert exc_info.value.code == 2- require_version.assert_not_called()--- "argv",- [- ["--model", "missing/model"],- ["--model=missing/model"],- ["-mmissing/model"],- ["--model"],- ["--model", "nvidia_nim/vendor/model", "-m", "open_router/other"],- ],-)-def test_invalid_model_override_never_starts_child(argv: list[str]) -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "require_compatible_grok"),- patch.object(grok, "get_settings", return_value=_settings()),- patch.object(grok, "preflight_proxy", return_value=None),- patch.object(- grok, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(grok, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- grok.launch(argv)-- assert exc_info.value.code == 2- run_client_process.assert_not_called()---def test_prompt_value_named_model_flag_is_not_parsed_as_an_override() -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "require_compatible_grok"),- patch.object(grok, "get_settings", return_value=_settings()),- patch.object(grok, "preflight_proxy", return_value=None),- patch.object(- grok, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(grok, "run_client_process") as run_client_process,- ):- grok.launch(["--single=--model"])-- assert (- run_client_process.call_args.kwargs["env"]["GROK_DEFAULT_MODEL"]- == "nvidia_nim/vendor/model"- )---def test_proxy_or_catalog_failure_never_starts_grok() -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "require_compatible_grok"),- patch.object(grok, "get_settings", return_value=_settings()),- patch.object(grok, "preflight_proxy", return_value="connection refused"),- patch.object(grok, "fetch_proxy_models_response") as fetch_models,- patch.object(grok, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- grok.launch([])-- assert exc_info.value.code == 1- fetch_models.assert_not_called()- run_client_process.assert_not_called()---def test_child_exit_code_is_mirrored_by_shared_process_owner() -> None:- from free_claude_code.cli.launchers import grok-- with (- patch.object(grok, "resolve_client_binary", return_value="resolved-grok"),- patch.object(grok, "require_compatible_grok"),- patch.object(grok, "get_settings", return_value=_settings()),- patch.object(grok, "preflight_proxy", return_value=None),- patch.object(- grok, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(grok, "run_client_process", side_effect=SystemExit(23)),- pytest.raises(SystemExit) as exc_info,- ):- grok.launch([])-- assert exc_info.value.code == 23+ monkeypatch.setenv(key, "user-owned-config")+ launch("grok", [], exit_code=1)+ assert not launch_capture.commandsdiff --git a/tests/cli/test_hermes_config.py b/tests/cli/test_hermes_config.pyindex 5189da86..2ad3cdfa 100644--- a/tests/cli/test_hermes_config.py+++ b/tests/cli/test_hermes_config.py@@ -43,16 +43,14 @@ def _models() -> tuple[ClientModel, ...]:def test_hermes_config_pins_responses_catalog_and_fallbacks() -> None:managed = build_hermes_managed_config(- _models(),+ (_models()[1], _models()[0], _models()[2]),proxy_root_url="http://127.0.0.1:9191/",nonce="a1b2c3",- selected_model="claude-3-freecc-no-thinking/open_router/plain-model",)- assert managed.provider_key == "fcc-a1b2c3"assert managed.provider_ref == "custom:fcc-a1b2c3"assert managed.key_env == "FCC_HERMES_A1B2C3"- assert managed.selected_model == (+ assert managed.default_model == ("claude-3-freecc-no-thinking/open_router/plain-model")assert managed.config["providers"] == {@@ -147,8 +145,7 @@ def test_hermes_config_uses_first_model_by_default() -> None:nonce="ABC123",)- assert managed.selected_model == "nvidia_nim/vendor/model"- assert managed.provider_key == "fcc-abc123"+ assert managed.default_model == "nvidia_nim/vendor/model"assert managed.key_env == "FCC_HERMES_ABC123"@@ -161,16 +158,6 @@ def test_hermes_config_rejects_empty_catalog() -> None:)-def test_hermes_config_rejects_unknown_model() -> None:- with pytest.raises(ValueError, match="not in the FCC catalog"):- build_hermes_managed_config(- _models(),- proxy_root_url="http://127.0.0.1:9191",- nonce="abc123",- selected_model="missing/model",- )--@pytest.mark.parametrize("nonce", ["", "not-valid", "spaces here"])def test_hermes_config_rejects_unsafe_nonce(nonce: str) -> None:with pytest.raises(ValueError, match="alphanumeric"):diff --git a/tests/cli/test_hermes_launcher.py b/tests/cli/test_hermes_launcher.pyindex e33ce0c5..2a3dcd6d 100644--- a/tests/cli/test_hermes_launcher.py+++ b/tests/cli/test_hermes_launcher.py@@ -1,610 +1,91 @@-"""Contract tests for the installed `fcc-hermes` launcher."""+"""Hermes's native managed overlay and activation check."""import json-import osimport subprocessfrom pathlib import Path-from types import SimpleNamespacefrom unittest.mock import patchimport 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.config.settings import Settings-from free_claude_code.core.json_types import JsonObject+from free_claude_code.config.paths import launcher_temp_dir_path+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch-def _settings(*, token: str = "proxy-token") -> Settings:- return Settings(- host="0.0.0.0",- port=9191,- proxy_auth_enabled=False,- proxy_auth_token=token,- model="nvidia_nim/test-model",- )---def _models_payload() -> JsonObject:- return {- "data": [- {- "id": "nvidia_nim/vendor/model",- "provider_model_ref": "nvidia_nim/vendor/model",- "display_name": "Nested model",- },- {- "id": "claude-3-freecc-no-thinking/open_router/plain-model",- "provider_model_ref": "open_router/plain-model",- "display_name": "No-thinking model",- },- ]- }---def _models() -> tuple[ClientModel, ...]:- return (- ClientModel(- wire_slug="nvidia_nim/vendor/model",- provider_model_ref="nvidia_nim/vendor/model",- display_name="Nested model",- supports_reasoning=True,- ),- )--- "argv",- [- [],- ["chat"],- ["-z", "hello"],- ["--oneshot=hello"],- ["--tui"],- ["--resume", "session-id"],- ["-c"],- ["-c", "session name"],- ["--profile", "coder", "chat", "--query", "hello"],- ],-)-def test_hermes_attached_surfaces_are_routed(argv: list[str]) -> None:- from free_claude_code.cli.launchers import hermes-- assert not hermes.is_hermes_passthrough(argv)- assert not hermes.detached_hermes_surface(argv)--- "argv",- [- ["--help"],- ["chat", "--help"],- ["--version"],- ["setup"],- ["auth", "list"],- ["update"],- ["config", "show"],- ["model"],- ["profile", "list"],- ["sessions", "list"],- ["plugin-command"],- ],-)-def test_hermes_management_surfaces_are_native_passthrough(argv: list[str]) -> None:- from free_claude_code.cli.launchers import hermes-- assert hermes.is_hermes_passthrough(argv)--- "argv",- [- ["acp"],- ["rl"],- ["gateway"],- ["cron"],- ["serve"],- ["dashboard"],- ["gui"],- ["desktop"],- ["proxy"],- ["mcp", "serve"],- ],-)-def test_hermes_detached_surfaces_are_rejected(argv: list[str]) -> None:- from free_claude_code.cli.launchers import hermes-- assert hermes.detached_hermes_surface(argv)- assert not hermes.is_hermes_passthrough(argv)--- ("argv", "expected"),- [- (["--profile", "coder", "chat"], ("--profile", "coder")),- (["chat", "-p", "coder"], ("-p", "coder")),- (["--profile=coder", "-z", "hello"], ("--profile=coder",)),- (["-m", "provider/model", "chat"], ()),- (["--", "--profile", "not-hermes"], ()),- ],-)-def test_hermes_profile_selector_matches_upstream_preparse(- argv: list[str], expected: tuple[str, ...]-) -> None:- from free_claude_code.cli.launchers.hermes import hermes_profile_args-- assert hermes_profile_args(argv) == expected--- ("output", "return_code", "expected"),- [- ("Hermes Agent v0.20.4 (2026-08-19)\n", 0, (0, 20, 4)),- ("0.21.0\n", 0, (0, 21, 0)),- ("Hermes Agent v0.20.3\n", 0, (0, 20, 3)),- ("not a version\n", 0, None),- ("Hermes Agent v0.20.4\n", 1, None),- ],-)-def test_hermes_version_parsing(- output: str, return_code: int, expected: tuple[int, int, int] | None-) -> None:- from free_claude_code.cli.launchers import hermes-- with patch.object(- hermes.subprocess,- "run",- return_value=SimpleNamespace(returncode=return_code, stdout=output),- ):- assert hermes.hermes_binary_version("resolved-hermes") == expected---def test_hermes_version_timeout_is_incompatible() -> None:- from free_claude_code.cli.launchers import hermes-- with patch.object(- hermes.subprocess, "run", side_effect=subprocess.TimeoutExpired("hermes", 5)- ):- assert hermes.hermes_binary_version("resolved-hermes") is None---def test_hermes_old_version_is_rejected_before_proxy(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "hermes_binary_version", return_value=(0, 20, 3)),- patch.object(hermes, "get_settings") as get_settings,- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch([])-- assert exc_info.value.code == 126- assert "at least version 0.20.4" in capsys.readouterr().err- get_settings.assert_not_called()---def test_hermes_management_passthrough_needs_no_proxy() -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "get_settings") as get_settings,- patch.object(hermes, "require_compatible_hermes") as require_version,- patch.object(hermes, "run_client_process") as run_client_process,- ):- hermes.launch(["config", "show"])-- run_client_process.assert_called_once_with(- command=["resolved-hermes", "config", "show"],- env=os.environ,- binary_name="hermes",- display_name="Hermes Agent",- install_hint="Install Hermes Agent from: "- "https://hermes-agent.nousresearch.com/docs/installation",- )- get_settings.assert_not_called()- require_version.assert_not_called()---def test_hermes_detached_surface_fails_before_proxy(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "get_settings") as get_settings,- patch.object(hermes, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch(["gateway"])-- assert exc_info.value.code == 2- assert "ordinary hermes" in capsys.readouterr().err- get_settings.assert_not_called()- run_client_process.assert_not_called()--- "argv",- [- ["--provider", "openrouter"],- ["--provider=openrouter"],- ["chat", "--provider", "openrouter"],- ],-)-def test_hermes_provider_override_is_rejected(argv: list[str]) -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "get_settings") as get_settings,- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch(argv)-- assert exc_info.value.code == 2- get_settings.assert_not_called()--[email protected]("argv", [["--model"], ["--model="], ["-m"]])-def test_hermes_missing_model_value_is_rejected(argv: list[str]) -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch(argv)-- assert exc_info.value.code == 2---def test_hermes_duplicate_model_override_is_rejected() -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch(["-m", "one/model", "chat", "--model=two/model"])-- assert exc_info.value.code == 2---def test_hermes_launch_prepares_validated_catalog_and_selected_model() -> None:- from free_claude_code.cli.launchers import hermes-- settings = _settings()- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "require_compatible_hermes"),- patch.object(hermes, "_system_policy_exists", return_value=False),- patch.object(hermes, "get_settings", return_value=settings),- patch.object(hermes, "preflight_proxy", return_value=None),- patch.object(- hermes, "fetch_proxy_models_response", return_value=_models_payload()- ) as fetch_models,- patch.object(hermes.secrets, "token_hex", return_value="a1b2c3"),- patch.object(hermes, "_run_with_managed_config") as run_managed,- ):- hermes.launch(- [- "--profile",- "coder",- "chat",- "--model",- "nvidia_nim/vendor/model",- "--query",- "hello",- ]- )-- fetch_models.assert_called_once_with("http://127.0.0.1:9191", "proxy-token")- call = run_managed.call_args.kwargs- assert call["binary_path"] == "resolved-hermes"- assert call["args"] == ["--profile", "coder", "chat", "--query", "hello"]- assert call["profile_args"] == ("--profile", "coder")- assert call["managed"].provider_ref == "custom:fcc-a1b2c3"- assert call["managed"].selected_model == "nvidia_nim/vendor/model"- assert call["auth_token"] == "proxy-token"---def test_hermes_unknown_model_fails_before_child(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "require_compatible_hermes"),- patch.object(hermes, "_system_policy_exists", return_value=False),- patch.object(hermes, "get_settings", return_value=_settings()),- patch.object(hermes, "preflight_proxy", return_value=None),- patch.object(- hermes, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(hermes, "_run_with_managed_config") as run_managed,- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch(["--model", "missing/model"])-- assert exc_info.value.code == 1- run_managed.assert_not_called()- assert "not in the FCC catalog" in capsys.readouterr().err---def test_hermes_proxy_failure_does_not_fetch_catalog(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "require_compatible_hermes"),- patch.object(hermes, "_system_policy_exists", return_value=False),- patch.object(hermes, "get_settings", return_value=_settings()),- patch.object(hermes, "preflight_proxy", return_value="connection refused"),- patch.object(hermes, "fetch_proxy_models_response") as fetch_models,- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch([])-- assert exc_info.value.code == 1- fetch_models.assert_not_called()- assert "fcc-server" in capsys.readouterr().err---def test_hermes_empty_proxy_token_fails_before_health_check(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "require_compatible_hermes"),- patch.object(hermes, "_system_policy_exists", return_value=False),- patch.object(- hermes,- "get_settings",- return_value=SimpleNamespace(proxy_auth_token=" "),- ),- patch.object(hermes, "preflight_proxy") as preflight,- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch([])-- assert exc_info.value.code == 1- preflight.assert_not_called()- assert "authentication token is empty" in capsys.readouterr().err---def test_hermes_catalog_failure_never_starts_child(- capsys: pytest.CaptureFixture[str],+def test_hermes_uses_native_defaults_and_keeps_user_commands(+ launch_capture: LaunchCapture,) -> None:- from free_claude_code.cli.launchers import hermes-- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "require_compatible_hermes"),- patch.object(hermes, "_system_policy_exists", return_value=False),- patch.object(hermes, "get_settings", return_value=_settings()),- patch.object(hermes, "preflight_proxy", return_value=None),- patch.object(- hermes,- "fetch_proxy_models_response",- side_effect=RuntimeError("catalog unavailable"),- ),- patch.object(hermes, "_run_with_managed_config") as run_managed,- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch([])-- assert exc_info.value.code == 1- run_managed.assert_not_called()- assert "catalog unavailable" in capsys.readouterr().err---def test_hermes_existing_managed_policy_is_not_shadowed(- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]-) -> None:- from free_claude_code.cli.launchers import hermes-- monkeypatch.setenv("HERMES_MANAGED_DIR", "administrator-policy")- with (- patch.object(hermes, "resolve_client_binary", return_value="resolved-hermes"),- patch.object(hermes, "get_settings") as get_settings,- pytest.raises(SystemExit) as exc_info,- ):- hermes.launch([])-- assert exc_info.value.code == 2- get_settings.assert_not_called()- assert "managed policy" in capsys.readouterr().err---def test_hermes_child_environment_preserves_native_state_and_replaces_owned_keys(- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.hermes import build_hermes_launcher_env-- env = build_hermes_launcher_env(- managed_directory=tmp_path,- key_env="FCC_HERMES_FRESH",- auth_token="proxy-token",- proxy_root_url="http://127.0.0.1:9191",- base_env={- "PATH": "keep",- "HERMES_HOME": "native-home",- "OPENROUTER_API_KEY": "native-key",- "FCC_HERMES_STALE": "stale",- "HERMES_MANAGED_DIR": "stale-policy",- "HERMES_INFERENCE_MODEL": "stale-model",- "HERMES_INFERENCE_PROVIDER": "stale-provider",- "NO_PROXY": "example.com",- },- )-- assert env["PATH"] == "keep"- assert env["HERMES_HOME"] == "native-home"- assert env["OPENROUTER_API_KEY"] == "native-key"- assert env["HERMES_MANAGED_DIR"] == str(tmp_path)- assert env["FCC_HERMES_FRESH"] == "proxy-token"- assert "FCC_HERMES_STALE" not in env- assert "HERMES_INFERENCE_MODEL" not in env- assert "HERMES_INFERENCE_PROVIDER" not in env- assert env["NO_PROXY"] == "example.com,127.0.0.1,localhost,::1"- assert env["no_proxy"] == env["NO_PROXY"]---def test_hermes_temporary_overlay_is_verified_and_removed(- monkeypatch: pytest.MonkeyPatch,-) -> None:- from free_claude_code.cli.launchers import hermes-- monkeypatch.setenv("HERMES_HOME", "native-home")- managed = build_hermes_managed_config(- _models(),- proxy_root_url="http://127.0.0.1:9191",- nonce="abc123",- )- observed_directory: Path | None = None-- def fake_run_process(**kwargs: object) -> None:- nonlocal observed_directory- command = kwargs["command"]- env = kwargs["env"]- assert isinstance(command, list)- assert isinstance(env, dict)- assert command == [- "resolved-hermes",- "--provider",- "custom:fcc-abc123",- "--model",- "nvidia_nim/vendor/model",- "--profile",- "coder",- "-z",- "hello",- ]- observed_directory = Path(env["HERMES_MANAGED_DIR"])- config_path = observed_directory / "config.yaml"- assert config_path.exists()- if os.name != "nt":- assert observed_directory.stat().st_mode & 0o777 == 0o700- assert config_path.stat().st_mode & 0o777 == 0o600- assert json.loads(config_path.read_text(encoding="utf-8")) == managed.config- assert "proxy-token" not in config_path.read_text(encoding="utf-8")- assert env["FCC_HERMES_ABC123"] == "proxy-token"- assert env["HERMES_HOME"] == "native-home"- raise SystemExit(0)-- with (- patch.object(- hermes.subprocess,- "run",- return_value=SimpleNamespace(- returncode=0,- stdout='"custom:fcc-abc123"\n',- stderr="",- ),- ) as probe,- patch.object(- hermes, "run_client_process", side_effect=fake_run_process- ) as run_process,- pytest.raises(SystemExit) as exc_info,- ):- hermes._run_with_managed_config(- binary_path="resolved-hermes",- args=["--profile", "coder", "-z", "hello"],- profile_args=["--profile", "coder"],- managed=managed,- proxy_root_url="http://127.0.0.1:9191",- auth_token="proxy-token",+ def inspect(command, env):+ config = json.loads(+ (Path(env["HERMES_MANAGED_DIR"]) / "config.yaml").read_text())-- assert exc_info.value.code == 0- probe.assert_called_once()- assert probe.call_args.args[0] == [- "resolved-hermes",+ provider = env["HERMES_INFERENCE_PROVIDER"]+ assert provider == config["model"]["provider"]+ assert env["HERMES_INFERENCE_MODEL"] == config["model"]["default"]+ (entry,) = config["providers"].values()+ assert entry["transport"] == "codex_responses"+ assert entry["api"] == "http://127.0.0.1:8182/v1"+ assert env[entry["key_env"]] == "launcher-test-token"+ assert all(aux["provider"] == provider for aux in config["auxiliary"].values())+ assert "launcher-test-token" not in json.dumps(config)++ launch_capture.on_start = inspect+ args = ["--profile",- "coder",+ "native-profile",+ "--model",+ "native-model",+ "--oneshot",+ "hello",+ ]+ launch("hermes", args)+ assert launch_capture.commands == [["hermes", *args]]+ assert launch_capture.probes[-1] == [+ "hermes","config","get","model.provider","--json",]- run_process.assert_called_once()- assert observed_directory is not None- assert not observed_directory.exists()- "probe_result",- [- SimpleNamespace(returncode=1, stdout="", stderr="failure"),- SimpleNamespace(returncode=0, stdout="not-json\n", stderr=""),- SimpleNamespace(returncode=0, stdout='"custom:other"\n', stderr=""),- ],-)-def test_hermes_overlay_activation_failure_never_starts_child(- probe_result: SimpleNamespace,[email protected]("output", ['"other-provider"', "{}", "", "not json"])+def test_hermes_failed_activation_cleans_configuration(+ output: str, launch_capture: LaunchCapture) -> None:- from free_claude_code.cli.launchers import hermes+ original = launch_capture.probe- managed = build_hermes_managed_config(- _models(),- proxy_root_url="http://127.0.0.1:9191",- nonce="abc123",- )- with (- patch.object(hermes.subprocess, "run", return_value=probe_result),- patch.object(hermes, "run_client_process") as run_process,- pytest.raises(SystemExit) as exc_info,- ):- hermes._run_with_managed_config(- binary_path="resolved-hermes",- args=[],- profile_args=[],- managed=managed,- proxy_root_url="http://127.0.0.1:9191",- auth_token="proxy-token",- )+ def probe(command, **kwargs):+ if "config" in command:+ return subprocess.CompletedProcess(command, 0, output, "")+ return original(command, **kwargs)- assert exc_info.value.code == 1- run_process.assert_not_called()+ with patch.object(subprocess, "run", side_effect=probe):+ launch("hermes", [], exit_code=1)+ assert not launch_capture.commands+ assert list(launcher_temp_dir_path().iterdir()) == []-def test_hermes_overlay_activation_timeout_never_starts_child() -> None:- from free_claude_code.cli.launchers import hermes+def test_existing_hermes_managed_policy_is_not_replaced(+ launch_capture: LaunchCapture, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("HERMES_MANAGED_DIR", "organization-policy")+ launch("hermes", [], exit_code=1)+ assert not launch_capture.commands- managed = build_hermes_managed_config(- _models(),- proxy_root_url="http://127.0.0.1:9191",- nonce="abc123",- )- with (- patch.object(- hermes.subprocess,- "run",- side_effect=subprocess.TimeoutExpired("hermes", 15),- ),- patch.object(hermes, "run_client_process") as run_process,- pytest.raises(SystemExit) as exc_info,- ):- hermes._run_with_managed_config(- binary_path="resolved-hermes",- args=[],- profile_args=[],- managed=managed,- proxy_root_url="http://127.0.0.1:9191",- auth_token="proxy-token",- )- assert exc_info.value.code == 1- run_process.assert_not_called()+def test_hermes_activation_timeout_stops_and_cleans(+ launch_capture: LaunchCapture,+) -> None:+ original = launch_capture.probe++ def probe(command, **kwargs):+ if "config" in command:+ assert kwargs["timeout"] == 15.0+ raise subprocess.TimeoutExpired(command, 15)+ return original(command, **kwargs)++ with patch.object(subprocess, "run", side_effect=probe):+ launch("hermes", [], exit_code=1)+ assert not launch_capture.commands+ assert list(launcher_temp_dir_path().iterdir()) == []diff --git a/tests/cli/test_launcher_checks.py b/tests/cli/test_launcher_checks.pynew file mode 100644index 00000000..e59963f8--- /dev/null+++ b/tests/cli/test_launcher_checks.py@@ -0,0 +1,130 @@+"""One bootstrap contract, with only native probe syntax varying by harness."""++import importlib+import subprocess+from unittest.mock import patch+from urllib.error import URLError++import pytest++from free_claude_code.cli.launchers import common, runner+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import HARNESSES, launch+++ ("name", "output", "compatible"),+ [+ ("opencode", "1.18.18", True),+ ("opencode", "opencode version 1.19.0+build", True),+ ("opencode", "1.18.17", False),+ ("opencode", "1.18.18-beta.1", False),+ ("cline", "cline 3.0.55", True),+ ("cline", "v3.1.0", True),+ ("cline", "3.0.54", False),+ ("cline", "3.1.0-beta", False),+ ("hermes", "Hermes Agent v0.20.4", True),+ ("hermes", "Hermes Agent 0.20.3", False),+ ("dsh", "dsh v0.1.0-rc.8", True),+ ("dsh", "0.1.0-rc.7", False),+ ("dsh", "0.1.0-rc.9", False),+ ("grok", '{"currentVersion":"1.0.5"}', True),+ ("grok", '{"currentVersion":"1.1.0+build (build info)"}', True),+ ("grok", '{"currentVersion":"1.0.4"}', False),+ ("grok", '{"currentVersion":"1.0.5-beta"}', False),+ ("grok", '{"currentVersion":3}', False),+ ("grok", "[]", False),+ ("muse", "Muse Code 0.2.1", True),+ ("muse", "Muse Code 1.0.3 (1.0.3-R2198.1)", True),+ ("muse", "Muse Code 0.2.0", False),+ ("pi", "--extension --models", True),+ ("pi", "--extension", False),+ ("pi", "--models", False),+ ],+)+def test_native_compatibility_precedes_fcc_setup(+ name: str, output: str, compatible: bool, launch_capture: LaunchCapture+) -> None:+ launch_capture.versions[name] = output+ launch(name, ["--help"], exit_code=23 if compatible else 126)+ assert bool(launch_capture.commands) is compatible+ assert bool(launch_capture.requests) is compatible+++ "name", ("pi", "opencode", "cline", "hermes", "dsh", "grok", "muse")+)+ "error", (OSError("cannot execute"), subprocess.TimeoutExpired("probe", 5))+)+def test_native_probe_failure_stops_before_fcc(+ name: str, error: Exception, launch_capture: LaunchCapture+) -> None:+ with patch.object(subprocess, "run", side_effect=error):+ launch(name, [], exit_code=126)+ assert not launch_capture.requests+ assert not launch_capture.commands++[email protected]("name", HARNESSES)+def test_missing_binary_does_not_read_settings(+ name: str, launch_capture: LaunchCapture, capsys: pytest.CaptureFixture[str]+) -> None:+ with (+ patch.object(common.shutil, "which", return_value=None),+ patch.object(runner, "get_settings") as settings,+ ):+ launch(name, [], exit_code=127)+ settings.assert_not_called()+ assert not launch_capture.requests+ assert "Install" in capsys.readouterr().err++[email protected]("name", HARNESSES)+def test_settings_are_loaded_once_for_a_launch(+ name: str, launch_capture: LaunchCapture+) -> None:+ with patch.object(runner, "get_settings", wraps=runner.get_settings) as settings:+ launch(name, [])+ settings.assert_called_once_with()+++def test_empty_token_stops_before_network(launch_capture: LaunchCapture) -> None:+ settings = runner.get_settings().model_copy(update={"proxy_auth_token": " "})+ with patch.object(runner, "get_settings", return_value=settings):+ launch("claude", [], exit_code=1)+ assert not launch_capture.requests+++ "name", tuple(name for name in HARNESSES if name not in {"claude", "pi"})+)+ "payload", ({}, {"data": []}, {"data": [{"id": "no provider reference"}]})+)+def test_unusable_catalog_prevents_every_catalog_dependent_child(+ name: str, payload, launch_capture: LaunchCapture+) -> None:+ launch_capture.catalog = payload+ launch(name, [], exit_code=1)+ assert not launch_capture.commands+++def test_setup_error_reports_once_and_redacts_token(+ launch_capture: LaunchCapture, capsys: pytest.CaptureFixture[str]+) -> None:+ launch_capture.catalog_error = URLError("rejected launcher-test-token")+ launch("codex", [], exit_code=1)+ output = capsys.readouterr()+ assert output.out == ""+ assert output.err.count("Could not prepare model catalog") == 1+ assert "launcher-test-token" not in output.err+ assert "rejected [redacted]" in output.err+++def test_programming_errors_are_not_disguised_as_setup_failures(+ launch_capture: LaunchCapture,+) -> None:+ launch_capture.catalog_error = AssertionError("programming error")+ with pytest.raises(AssertionError, match="programming error"):+ importlib.import_module("free_claude_code.cli.launchers.codex").launch([])diff --git a/tests/cli/test_launcher_environment.py b/tests/cli/test_launcher_environment.pynew file mode 100644index 00000000..7a6433b1--- /dev/null+++ b/tests/cli/test_launcher_environment.py@@ -0,0 +1,36 @@+"""Native state and process-local proxy settings survive shared launch setup."""++import os++import pytest++from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import HARNESSES, launch++[email protected]("name", HARNESSES)+def test_native_state_and_unrelated_environment_are_preserved(+ name: str, launch_capture: LaunchCapture, monkeypatch: pytest.MonkeyPatch+) -> None:+ inherited = {+ "CODEX_HOME": "native-codex-home",+ "DSH_HOME": "native-dsh-home",+ "GROK_HOME": "native-grok-home",+ "HERMES_HOME": "native-hermes-home",+ "MUSE_HOME": "native-muse-home",+ "FCC_UNRELATED": "keep",+ "HTTP_PROXY": "http://machine-proxy.invalid:8080",+ "NO_PROXY": "internal.example",+ }+ for key, value in inherited.items():+ monkeypatch.setenv(key, value)+ parent = dict(os.environ)+ launch(name, [])+ child = launch_capture.environments[0]+ for key, value in inherited.items():+ if key != "NO_PROXY":+ assert child[key] == value+ assert "internal.example" in child["NO_PROXY"].split(",")+ assert "127.0.0.1" in child["NO_PROXY"].split(",")+ assert child["NO_PROXY"] == child["no_proxy"]+ assert dict(os.environ) == parentdiff --git a/tests/cli/test_launcher_resources.py b/tests/cli/test_launcher_resources.pynew file mode 100644index 00000000..d3b16e48--- /dev/null+++ b/tests/cli/test_launcher_resources.py@@ -0,0 +1,142 @@+"""Observe configuration while children run and after launch scopes unwind."""++import importlib+import os+from pathlib import Path+from unittest.mock import Mock, patch++import pytest++from free_claude_code.cli.launchers import common, resources+from free_claude_code.config.paths import launcher_temp_dir_path+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch++FILE_HARNESSES = ("codex", "opencode", "cline", "hermes", "dsh", "aider")++[email protected]("name", FILE_HARNESSES)+def test_private_files_live_until_child_exit(+ name: str, launch_capture: LaunchCapture+) -> None:+ paths: list[Path] = []++ def inspect(command, env):+ paths.extend(+ path for path in launcher_temp_dir_path().rglob("*") if path.is_file()+ )+ assert paths+ if os.name != "nt":+ assert all(path.stat().st_mode & 0o777 == 0o600 for path in paths)+ assert all(path.parent.stat().st_mode & 0o777 == 0o700 for path in paths)++ launch_capture.on_start = inspect+ launch(name, [])+ assert all(not path.exists() for path in paths)+ assert list(launcher_temp_dir_path().iterdir()) == []++[email protected]("name", FILE_HARNESSES)+ "failure", (PermissionError("cannot start"), KeyboardInterrupt())+)+def test_cleanup_on_process_start_failure(+ name: str, failure: BaseException, launch_capture: LaunchCapture+) -> None:+ def fail_start(command, env):+ assert any(launcher_temp_dir_path().rglob("*"))+ raise failure++ launch_capture.on_start = fail_start+ if isinstance(failure, KeyboardInterrupt):+ with pytest.raises(KeyboardInterrupt):+ importlib.import_module(f"free_claude_code.cli.launchers.{name}").launch([])+ else:+ launch(name, [], exit_code=1)+ assert list(launcher_temp_dir_path().iterdir()) == []+++def test_cleanup_after_partial_configuration(launch_capture: LaunchCapture) -> None:+ original = resources.LaunchResources.write_json++ def fail_second(self, filename, payload):+ if filename == "settings/models.json":+ raise PermissionError("failed second write")+ return original(self, filename, payload)++ with patch.object(resources.LaunchResources, "write_json", fail_second):+ launch("cline", [], exit_code=1)+ assert not launch_capture.commands+ assert list(launcher_temp_dir_path().iterdir()) == []+++def test_cleanup_after_directory_creation_error(launch_capture: LaunchCapture) -> None:+ with patch.object(+ resources.tempfile,+ "TemporaryDirectory",+ side_effect=PermissionError("no directory"),+ ):+ launch("codex", [], exit_code=1)+ assert not launch_capture.commands+++def test_nested_launches_keep_independent_live_catalogs(+ launch_capture: LaunchCapture,+) -> None:+ outer: list[Path] = []++ def nested(command, env):+ outer.extend(launcher_temp_dir_path().glob("*/model-catalog.json"))+ assert len(outer) == 1++ def inspect_inner(inner_command, inner_env):+ paths = list(launcher_temp_dir_path().glob("*/model-catalog.json"))+ assert len(paths) == 2+ assert outer[0].is_file()++ launch_capture.on_start = inspect_inner+ launch("codex", [])+ assert outer[0].is_file()++ launch_capture.on_start = nested+ launch("codex", [])+ assert not outer[0].exists()+++def test_interrupt_kills_and_waits_for_registered_child_before_cleanup(+ launch_capture: LaunchCapture,+) -> None:+ process = Mock(pid=12345)+ process.wait.side_effect = (KeyboardInterrupt(), 0)+ events: list[str] = []++ def kill(pid):+ assert pid == 12345+ assert list(launcher_temp_dir_path().glob("*/model-catalog.json"))+ events.append("kill")++ with (+ patch.object(common.subprocess, "Popen", return_value=process),+ patch.object(+ common, "register_pid", side_effect=lambda pid: events.append("register")+ ),+ patch.object(common, "kill_pid_tree_best_effort", side_effect=kill),+ patch.object(+ common,+ "unregister_pid",+ side_effect=lambda pid: events.append("unregister"),+ ),+ pytest.raises(KeyboardInterrupt),+ ):+ importlib.import_module("free_claude_code.cli.launchers.codex").launch([])+ assert events == ["register", "kill", "unregister"]+ assert process.wait.call_count == 2+ assert list(launcher_temp_dir_path().iterdir()) == []++[email protected]("name", ("claude", "pi", "grok", "muse"))+def test_environment_only_harnesses_allocate_no_directory(+ name: str, launch_capture: LaunchCapture+) -> None:+ launch(name, [])+ assert not launcher_temp_dir_path().exists()diff --git a/tests/cli/test_launcher_workflow.py b/tests/cli/test_launcher_workflow.pynew file mode 100644index 00000000..aceec734--- /dev/null+++ b/tests/cli/test_launcher_workflow.py@@ -0,0 +1,141 @@+"""Regression tests for shared startup and native command ownership."""++import importlib+import json+import tomllib+from pathlib import Path+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 tests.cli.conftest import LaunchCapture++HARNESSES = (+ "claude",+ "codex",+ "pi",+ "opencode",+ "cline",+ "hermes",+ "dsh",+ "grok",+ "muse",+ "aider",+)+++def launch(name: str, args: list[str], exit_code: int = 23) -> None:+ module = importlib.import_module(f"free_claude_code.cli.launchers.{name}")+ with pytest.raises(SystemExit) as exc:+ module.launch(args)+ assert exc.value.code == exit_code++[email protected]("name", HARNESSES)+def test_help_receives_normal_fcc_setup(+ name: str, launch_capture: LaunchCapture+) -> None:+ launch(name, ["--help"])+ assert launch_capture.requests[0].full_url == "http://127.0.0.1:8182/health"+ assert launch_capture.commands[0][-1] == "--help"+ if name in {"claude", "pi"}:+ assert len(launch_capture.requests) == 1+ else:+ view = "messages" if name == "aider" else "responses"+ assert [request.full_url for request in launch_capture.requests] == [+ "http://127.0.0.1:8182/health",+ f"http://127.0.0.1:8182/v1/models?view={view}",+ ]++[email protected]("name", HARNESSES)+def test_help_does_not_bypass_failed_setup(+ name: str, launch_capture: LaunchCapture+) -> None:+ launch_capture.health_error = URLError("test server is stopped")+ launch(name, ["--help"], exit_code=1)+ assert not launch_capture.commands++[email protected]("name", HARNESSES)+def test_native_inputs_are_forwarded_without_fcc_model_or_command_policy(+ name: str, launch_capture: LaunchCapture+) -> None:+ args = [+ "--model",+ "future/model",+ "--model=another/model",+ "--future-option",+ "resume",+ "--",+ "--help",+ "--provider",+ "literal text",+ ]+ launch(name, args)+ assert launch_capture.commands[0][-len(args) :] == args+++ "failure", [URLError("catalog unavailable"), ValueError("invalid catalog"), None]+)+def test_codex_required_catalog_failure_stops_launch(+ failure: Exception | None, launch_capture: LaunchCapture+) -> None:+ launch_capture.catalog_error = failure+ launch_capture.catalog = {"data": []}+ launch("codex", [], exit_code=1)+ assert not launch_capture.commands+++def test_codex_cli_catalog_is_private_and_does_not_replace_external_catalog(+ launch_capture: LaunchCapture,+) -> None:+ stable = codex_model_catalog_path()+ stable.parent.mkdir(parents=True, exist_ok=True)+ stable.write_text('{"external":"unchanged"}')+ private_paths: list[Path] = []++ def inspect(command, env):+ settings = tomllib.loads(+ "\n".join(+ command[index + 1] for index, arg in enumerate(command) if arg == "-c"+ )+ )+ path = Path(settings["model_catalog_json"])+ assert path != stable+ assert (+ json.loads(path.read_text())["models"][0]["slug"]+ == "nvidia_nim/catalog-model:variant"+ )+ assert stable.read_text() == '{"external":"unchanged"}'+ private_paths.append(path)++ launch_capture.on_start = inspect+ launch("codex", [])+ launch("codex", [])+ assert private_paths[0] != private_paths[1]+ assert all(not path.exists() for path in private_paths)+++def test_aider_native_settings_resolve_bare_and_transport_names_without_rewriting_args() -> (+ None+):+ wire_name = "nvidia_nim/catalog-model:variant"+ config = build_aider_config(+ (ClientModel(wire_name, wire_name, "Model", False),),+ messages_url="http://localhost:8182/v1/messages",+ api_key_env="FCC_AIDER_PROXY_AUTH_TEST123",+ )+ entries = {entry["name"]: entry for entry in config.settings}+ for name in (wire_name, f"anthropic/{wire_name}"):+ entry = entries[name]+ extra_params = entry["extra_params"]+ assert isinstance(extra_params, dict)+ assert extra_params["model"] == f"anthropic/{wire_name}"+ assert entry["weak_model_name"] == name+ assert entry["editor_model_name"] == name+ assert name in config.metadatadiff --git a/tests/cli/test_muse_launcher.py b/tests/cli/test_muse_launcher.pyindex b7320e22..bb103493 100644--- a/tests/cli/test_muse_launcher.py+++ b/tests/cli/test_muse_launcher.py@@ -1,467 +1,38 @@-"""Contract tests for the installed `fcc-muse` launcher."""--import os-import subprocess-from types import SimpleNamespace-from unittest.mock import patch+"""Muse receives connection options in native parser scope."""import pytest-from free_claude_code.config.settings import Settings-from free_claude_code.core.json_types import JsonObject---def _settings(*, token: str = "proxy-token") -> Settings:- settings = Settings(- host="0.0.0.0",- port=9191,- proxy_auth_enabled=False,- proxy_auth_token=token or "placeholder-token",- model="nvidia_nim/test-model",- )- return settings.model_copy(update={"proxy_auth_token": token})---def _models_payload() -> JsonObject:- return {- "object": "list",- "data": [- {- "id": "nvidia_nim/vendor/model",- "provider_model_ref": "nvidia_nim/vendor/model",- "display_name": "Nested model",- },- {- "id": "claude-3-freecc-no-thinking/open_router/plain-model",- "provider_model_ref": "open_router/plain-model",- "display_name": "No-thinking model",- },- ],- }---def test_muse_install_hint_covers_native_windows_and_posix() -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(- muse, "resolve_client_binary", side_effect=SystemExit(1)- ) as resolve_client_binary,- pytest.raises(SystemExit),- ):- muse.launch([])-- install_hint = resolve_client_binary.call_args.kwargs["install_hint"]- assert "scripts/install-muse.ps1" in install_hint- assert "https://dev.meta.ai/install.sh" in install_hint--- ("argv", "str_mode", "command_index"),- [- ([], "tui", None),- (["fix the bug"], "tui", None),- (["--workspace", "repo", "fix the bug"], "tui", None),- (["exec", "--json", "fix the bug"], "exec", 0),- (["resume"], "resume", 0),- (["resume", "--last"], "resume", 0),- (["--workspace", "repo", "resume", "session-id"], "resume", 2),- (["-w", "resume", "--last"], "resume", 1),- (["--worktree", "existing", "resume"], "resume", 2),- (["--worktree=create", "resume"], "resume", 1),- (["--", "resume"], "tui", None),- ],-)-def test_muse_invocation_classification(- argv: list[str], str_mode: str, command_index: int | None-) -> None:- from free_claude_code.cli.launchers.muse import (- MuseInvocationMode,- classify_muse_invocation,- )-- invocation = classify_muse_invocation(argv)-- assert invocation.mode is MuseInvocationMode(str_mode)- assert invocation.command_index == command_index--- "argv",- [- ["--help"],- ["exec", "--help"],- ["resume", "--help"],- ["--version"],- ["auth", "status"],- ["login"],- ["logout"],- ["config", "validate"],- ["export", "session-id"],- ["trace", "session-id"],- ["skills", "list"],- ["sandbox", "status"],- ["session-message", "send"],- ["init"],- ],-)-def test_management_surfaces_are_native_passthrough(argv: list[str]) -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(muse, "resolve_client_binary", return_value="resolved-muse"),- patch.object(muse, "require_compatible_muse") as require_version,- patch.object(muse, "get_settings") as get_settings,- patch.object(muse, "run_client_process") as run_client_process,- ):- muse.launch(argv)-- assert run_client_process.call_args.kwargs["command"] == [- "resolved-muse",- *argv,- ]- assert run_client_process.call_args.kwargs["env"] is os.environ- require_version.assert_not_called()- get_settings.assert_not_called()--- "argv",- [- ["--provider", "meta", "prompt"],- ["--provider=meta", "prompt"],- ["--base-url", "https://example.test/v1", "prompt"],- ["--base-url=https://example.test/v1", "prompt"],- ["resume", "--provider", "meta"],- ["exec", "--api-key-stdin", "prompt"],- ],-)-def test_routed_invocations_reject_caller_owned_route(- argv: list[str], capsys: pytest.CaptureFixture[str]-) -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(muse, "resolve_client_binary", return_value="resolved-muse"),- patch.object(muse, "require_compatible_muse") as require_version,- pytest.raises(SystemExit) as exc_info,- ):- muse.launch(argv)-- assert exc_info.value.code == 2- assert "ordinary muse" in capsys.readouterr().err- require_version.assert_not_called()---def test_route_like_prompt_content_after_separator_is_not_rejected() -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(muse, "resolve_client_binary", return_value="resolved-muse"),- patch.object(muse, "require_compatible_muse"),- patch.object(muse, "get_settings", return_value=_settings()),- patch.object(muse, "preflight_proxy", return_value=None),- patch.object(- muse, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(muse, "run_client_process") as run_client_process,- ):- muse.launch(["exec", "--", "--provider", "native", "--model", "words"])-- assert run_client_process.call_args.kwargs["command"] == [- "resolved-muse",- "exec",- "--provider",- "meta",- "--base-url",- "http://127.0.0.1:9191/v1",- "--model",- "nvidia_nim/vendor/model",- "--",- "--provider",- "native",- "--model",- "words",- ]--- ("argv", "expected"),- [- (- ["fix the bug"],- [- "--provider",- "meta",- "--base-url",- "http://127.0.0.1:9191/v1",- "--model",- "nvidia_nim/vendor/model",- "fix the bug",- ],- ),- (- ["exec", "--json", "fix the bug"],- [- "exec",- "--provider",- "meta",- "--base-url",- "http://127.0.0.1:9191/v1",- "--model",- "nvidia_nim/vendor/model",- "--json",- "fix the bug",- ],- ),- (- ["resume", "--last"],- [- "resume",- "--provider",- "meta",- "--base-url",- "http://127.0.0.1:9191/v1",- "--model",- "nvidia_nim/vendor/model",- "--last",- ],- ),- (- ["--workspace", "repo", "resume", "session-id"],- [- "--workspace",- "repo",- "resume",- "--provider",- "meta",- "--base-url",- "http://127.0.0.1:9191/v1",- "--model",- "nvidia_nim/vendor/model",- "session-id",- ],- ),- ],-)-def test_routed_launch_places_flags_in_muse_grammar(- argv: list[str], expected: list[str]-) -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(muse, "resolve_client_binary", return_value="resolved-muse"),- patch.object(muse, "require_compatible_muse"),- patch.object(muse, "get_settings", return_value=_settings()),- patch.object(muse, "preflight_proxy", return_value=None),- patch.object(- muse, "fetch_proxy_models_response", return_value=_models_payload()- ) as fetch_models,- patch.object(muse, "run_client_process") as run_client_process,- ):- muse.launch(argv)-- assert run_client_process.call_args.kwargs["command"] == [- "resolved-muse",- *expected,- ]- fetch_models.assert_called_once_with("http://127.0.0.1:9191", "proxy-token")--- "model_args",- [- ["--model", "claude-3-freecc-no-thinking/open_router/plain-model"],- ["--model=claude-3-freecc-no-thinking/open_router/plain-model"],- ],-)-def test_explicit_model_is_validated_and_reinserted_once(- model_args: list[str],-) -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(muse, "resolve_client_binary", return_value="resolved-muse"),- patch.object(muse, "require_compatible_muse"),- patch.object(muse, "get_settings", return_value=_settings()),- patch.object(muse, "preflight_proxy", return_value=None),- patch.object(- muse, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(muse, "run_client_process") as run_client_process,- ):- muse.launch(["exec", *model_args, "prompt"])-- command = run_client_process.call_args.kwargs["command"]- assert command == [- "resolved-muse",- "exec",- "--provider",- "meta",- "--base-url",- "http://127.0.0.1:9191/v1",- "--model",- "claude-3-freecc-no-thinking/open_router/plain-model",- "prompt",- ]- assert command.count("--model") == 1--- ("argv", "message"),- [- (["exec", "--model"], "requires a model value"),- (["exec", "--model="], "requires a model value"),- (["exec", "--model", "missing/model", "prompt"], "not in the current"),- (- [- "exec",- "--model",- "nvidia_nim/vendor/model",- "--model=nvidia_nim/vendor/model",- ],- "multiple --model",- ),- ],-)-def test_invalid_model_selection_fails_closed(- argv: list[str], message: str, capsys: pytest.CaptureFixture[str]-) -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(muse, "resolve_client_binary", return_value="resolved-muse"),- patch.object(muse, "require_compatible_muse"),- patch.object(muse, "get_settings", return_value=_settings()),- patch.object(muse, "preflight_proxy", return_value=None),- patch.object(- muse, "fetch_proxy_models_response", return_value=_models_payload()- ),- patch.object(muse, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- muse.launch(argv)-- assert exc_info.value.code == 2- assert message in capsys.readouterr().err- run_client_process.assert_not_called()+from free_claude_code.cli.launchers.muse import SPEC+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch@pytest.mark.parametrize(- ("output", "return_code", "expected"),+ "args",[- ("Muse Code 0.2.1 (0.2.1-R1215.1)\n", 0, (0, 2, 1)),- ("Muse Code 1.4.2 (1.4.2-R99.3)\n", 0, (1, 4, 2)),- ("Muse Code 0.2.1\n", 0, (0, 2, 1)),- ("unexpected Muse Code 0.2.1\n", 0, None),- ("Muse Code 0.2.1 (0.2.1-R1215.1)\n", 1, None),+ [],+ ["exec", "--model", "native-model", "hello"],+ ["resume", "session-id", "--model=native-model"],+ ["--", "exec", "--model"],+ ["literal exec text"],],)-def test_muse_version_probe(- output: str,- return_code: int,- expected: tuple[int, int, int] | None,+def test_muse_connection_placement_keeps_native_model_options(+ args: list[str], launch_capture: LaunchCapture) -> None:- from free_claude_code.cli.launchers import muse-- with patch.object(- muse.subprocess,- "run",- return_value=SimpleNamespace(stdout=output, returncode=return_code),- ):- assert muse.muse_binary_version("resolved-muse") == expected---def test_muse_version_probe_handles_timeout() -> None:- from free_claude_code.cli.launchers import muse-- with patch.object(- muse.subprocess,- "run",- side_effect=subprocess.TimeoutExpired("muse", 5),- ):- assert muse.muse_binary_version("resolved-muse") is None--[email protected]("version", [(0, 2, 0), None])-def test_incompatible_muse_fails_before_settings(- version: tuple[int, int, int] | None,-) -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(muse, "resolve_client_binary", return_value="resolved-muse"),- patch.object(muse, "muse_binary_version", return_value=version),- patch.object(muse, "get_settings") as get_settings,- pytest.raises(SystemExit) as exc_info,- ):- muse.launch([])-- assert exc_info.value.code == 1- get_settings.assert_not_called()---def test_muse_child_environment_replaces_only_route_controls() -> None:- from free_claude_code.cli.launchers.muse import build_muse_launcher_env-- env = build_muse_launcher_env(- proxy_root_url="http://127.0.0.1:9191",- auth_token="proxy-token",- base_env={- "META_API_KEY": "native-token",- "MUSE_MODEL": "native-model",- "MUSE_CUSTOM_HEADERS": "Authorization: native",- "MUSE_WWW_ROUTING": "native",- "FCC_MUSE_OLD": "stale",- "MUSE_NO_AUTO_UPDATE": "1",- "HOME": "native-home",- "HTTPS_PROXY": "http://proxy.test:8080",- "NO_PROXY": "existing.test",- "no_proxy": "lower.test",- },+ launch("muse", args)+ connection = ["--provider", "meta", "--base-url", "http://127.0.0.1:8182/v1"]+ expected = (+ ["muse", args[0], *connection, *args[1:]]+ if args and args[0] in {"exec", "resume"}+ else ["muse", *connection, *args])+ assert launch_capture.commands == [expected]+ env = launch_capture.environments[0]+ assert env["META_API_KEY"] == "launcher-test-token"+ assert env["MUSE_MODEL"] == "nvidia_nim/catalog-model:variant"- assert env["META_API_KEY"] == "proxy-token"- assert "MUSE_MODEL" not in env- assert "MUSE_CUSTOM_HEADERS" not in env- assert "MUSE_WWW_ROUTING" not in env- assert "FCC_MUSE_OLD" not in env- assert env["MUSE_NO_AUTO_UPDATE"] == "1"- assert env["HOME"] == "native-home"- assert env["HTTPS_PROXY"] == "http://proxy.test:8080"- assert "127.0.0.1" in env["NO_PROXY"]- assert "127.0.0.1" in env["no_proxy"]--- ("token", "preflight_error", "catalog", "expected"),- [- ("", None, _models_payload(), "authentication token is empty"),- ("proxy-token", "connection refused", _models_payload(), "not reachable"),- ("proxy-token", None, {"object": "list", "data": []}, "no routable"),- ("proxy-token", None, {"unexpected": True}, "no routable"),- ],-)-def test_preflight_failures_never_start_muse(- token: str,- preflight_error: str | None,- catalog: JsonObject,- expected: str,- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import muse-- with (- patch.object(muse, "resolve_client_binary", return_value="resolved-muse"),- patch.object(muse, "require_compatible_muse"),- patch.object(muse, "get_settings", return_value=_settings(token=token)),- patch.object(muse, "preflight_proxy", return_value=preflight_error),- patch.object(muse, "fetch_proxy_models_response", return_value=catalog),- patch.object(muse, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- muse.launch(["prompt"])- assert exc_info.value.code == 1- assert expected in capsys.readouterr().err- run_client_process.assert_not_called()+def test_muse_install_hint_covers_windows_and_posix() -> None:+ assert "install-muse.ps1" in SPEC.install_hint+ assert "https://dev.meta.ai/install.sh" in SPEC.install_hintdiff --git a/tests/cli/test_opencode_launcher.py b/tests/cli/test_opencode_launcher.pyindex c0190f8f..c06dc232 100644--- a/tests/cli/test_opencode_launcher.py+++ b/tests/cli/test_opencode_launcher.py@@ -1,48 +1,15 @@"""OpenCode launcher contract tests."""import json-import subprocess-from collections.abc import Mappingfrom pathlib import Path-from types import SimpleNamespace-from unittest.mock import patchimport pytestfrom free_claude_code.cli.launchers.model_catalog import ClientModelfrom free_claude_code.cli.launchers.opencode_config import build_opencode_config-from free_claude_code.config.settings import Settings-from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.model_capabilities import ModelInputModality-def _settings() -> Settings:- return Settings(- host="0.0.0.0",- port=9191,- proxy_auth_enabled=False,- proxy_auth_token="proxy-token",- model="nvidia_nim/test-model",- )---def _models_payload() -> JsonObject:- return {- "data": [- {- "id": "nvidia_nim/vendor/model",- "provider_model_ref": "nvidia_nim/vendor/model",- "display_name": "Nested model",- },- {- "id": "claude-3-freecc-no-thinking/open_router/plain-model",- "provider_model_ref": "open_router/plain-model",- "display_name": "No-thinking model",- },- ]- }--def test_opencode_config_uses_responses_sdk_and_only_known_metadata() -> None:config = build_opencode_config((@@ -140,407 +107,28 @@ def test_opencode_config_rejects_empty_model_catalog() -> None:build_opencode_config((), proxy_root_url="http://127.0.0.1:9191")-def test_opencode_child_env_is_process_local_and_preserves_user_state(- tmp_path: Path,-) -> None:- from free_claude_code.cli.launchers.opencode import build_opencode_launcher_env-- config_path = tmp_path / "opencode.json"- env = build_opencode_launcher_env(- proxy_root_url="http://127.0.0.1:9191",- auth_token="proxy-token",- config_path=config_path,- overlay={"model": "free-claude-code/nvidia_nim/vendor/model"},- base_env={- "PATH": "keep",- "OPENCODE_CONFIG": "",- "OPENCODE_CONFIG_CONTENT": "",- "OPENCODE_CONFIG_DIR": "keep-user-state",- "FCC_OPENCODE_API_KEY": "stale-token",- "FCC_OPENCODE_OTHER": "stale-value",- "HTTP_PROXY": "http://proxy.example",- },- )-- assert env["PATH"] == "keep"- assert env["OPENCODE_CONFIG"] == str(config_path)- assert json.loads(env["OPENCODE_CONFIG_CONTENT"]) == {- "model": "free-claude-code/nvidia_nim/vendor/model"- }- assert env["OPENCODE_CONFIG_DIR"] == "keep-user-state"- assert env["FCC_OPENCODE_API_KEY"] == "proxy-token"- assert "FCC_OPENCODE_OTHER" not in env- assert env["HTTP_PROXY"] == "http://proxy.example"- assert env["NO_PROXY"] == "127.0.0.1,localhost,::1"- assert env["no_proxy"] == env["NO_PROXY"]--- ("output", "return_code", "expected"),- [- ("1.18.18\n", 0, (1, 18, 18)),- ("opencode version 1.19.0\n", 0, (1, 19, 0)),- ("v1.19.0+release.1\n", 0, (1, 19, 0)),- ("v2.0.0-beta.1\n", 0, None),- ("unexpected text 1.19.0\n", 0, None),- ("not-a-version\n", 0, None),- ("1.18.18\n", 1, None),- ],-)-def test_opencode_version_probe(- output: str,- return_code: int,- expected: tuple[int, int, int] | None,-) -> None:- from free_claude_code.cli.launchers.opencode import opencode_binary_version-- with patch(- "free_claude_code.cli.launchers.opencode.subprocess.run",- return_value=SimpleNamespace(stdout=output, returncode=return_code),- ):- assert opencode_binary_version("resolved-opencode") == expected---def test_opencode_version_probe_handles_timeout() -> None:- from free_claude_code.cli.launchers.opencode import opencode_binary_version-- with patch(- "free_claude_code.cli.launchers.opencode.subprocess.run",- side_effect=subprocess.TimeoutExpired("opencode", 5),- ):- assert opencode_binary_version("resolved-opencode") is None--- "argv",- [- ["--help"],- ["run", "--help"],- ["--version"],- ["auth", "login"],- ["upgrade"],- ["uninstall"],- ["completion", "bash"],- ],-)-def test_opencode_management_commands_pass_through_without_fcc(- argv: list[str],-) -> None:- from free_claude_code.cli.launchers import opencode-- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "get_settings") as get_settings,- patch.object(opencode, "preflight_proxy") as preflight_proxy,- patch.object(opencode, "run_client_process") as run_client_process,- ):- opencode.launch(argv)-- run_client_process.assert_called_once()- assert run_client_process.call_args.kwargs["command"] == [- "resolved-opencode",- *argv,- ]- get_settings.assert_not_called()- preflight_proxy.assert_not_called()--- "argv",- [[], ["models"], ["run", "hello"], ["serve"], ["web"], ["acp"]],-)-def test_opencode_inference_commands_are_never_raw_passthrough(- argv: list[str],-) -> None:- from free_claude_code.cli.launchers.opencode import is_opencode_passthrough-- assert not is_opencode_passthrough(argv)---def test_opencode_models_is_fcc_configured_and_temp_config_is_cleaned(- monkeypatch: pytest.MonkeyPatch,-) -> None:- from free_claude_code.cli.launchers import opencode-- monkeypatch.setenv("KEEP_ME", "yes")- observed_path: Path | None = None- observed_file: JsonObject | None = None- observed_env: dict[str, str] | None = None-- def observe_process(- *,- command: list[str],- env: Mapping[str, str],- binary_name: str,- display_name: str,- install_hint: str,- ) -> None:- nonlocal observed_path, observed_file, observed_env- del binary_name, display_name, install_hint- observed_path = Path(env["OPENCODE_CONFIG"])- payload = json.loads(observed_path.read_text(encoding="utf-8"))- assert isinstance(payload, dict)- observed_file = payload- observed_env = dict(env)- assert command == ["resolved-opencode", "models"]-- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "require_compatible_opencode"),- patch.object(opencode, "get_settings", return_value=_settings()),- patch.object(opencode, "preflight_proxy", return_value=None),- patch.object(- opencode,- "fetch_proxy_models_response",- return_value=_models_payload(),- ) as fetch_models,- patch.object(opencode, "run_client_process", side_effect=observe_process),- ):- opencode.launch(["models"])-- fetch_models.assert_called_once_with("http://127.0.0.1:9191", "proxy-token")- assert observed_path is not None- assert not observed_path.exists()- assert observed_file is not None- providers = observed_file["provider"]- assert isinstance(providers, dict)- assert "free-claude-code" in providers- assert observed_env is not None- assert observed_env["FCC_OPENCODE_API_KEY"] == "proxy-token"- assert observed_env["KEEP_ME"] == "yes"- assert "proxy-token" not in json.dumps(observed_file)- assert "proxy-token" not in observed_env["OPENCODE_CONFIG_CONTENT"]--[email protected]("key", ["OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT"])-def test_opencode_rejects_inherited_process_config_before_fcc_calls(- key: str,- monkeypatch: pytest.MonkeyPatch,- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import opencode-- monkeypatch.setenv(key, "user-config")- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "require_compatible_opencode"),- patch.object(opencode, "get_settings") as get_settings,- patch.object(opencode, "preflight_proxy") as preflight_proxy,- patch.object(opencode, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- opencode.launch([])-- assert exc_info.value.code == 1- assert key in capsys.readouterr().err- get_settings.assert_not_called()- preflight_proxy.assert_not_called()- run_client_process.assert_not_called()---def test_opencode_fails_closed_when_catalog_has_no_routable_models(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import opencode-- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "require_compatible_opencode"),- patch.object(opencode, "get_settings", return_value=_settings()),- patch.object(opencode, "preflight_proxy", return_value=None),- patch.object(- opencode,- "fetch_proxy_models_response",- return_value={"data": [{"id": "claude-opus-4-20250514"}]},- ),- patch.object(opencode, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- opencode.launch([])-- assert exc_info.value.code == 1- run_client_process.assert_not_called()- assert "at least one routable FCC model" in capsys.readouterr().err---def test_opencode_fails_closed_when_proxy_is_unreachable(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import opencode-- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "require_compatible_opencode"),- patch.object(opencode, "get_settings", return_value=_settings()),- patch.object(opencode, "preflight_proxy", return_value="connection refused"),- patch.object(opencode, "fetch_proxy_models_response") as fetch_models,- patch.object(opencode, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- opencode.launch(["run", "hello"])-- assert exc_info.value.code == 1- captured = capsys.readouterr()- assert "connection refused" in captured.err- assert "fcc-server" in captured.err- fetch_models.assert_not_called()- run_client_process.assert_not_called()---def test_opencode_fails_closed_when_catalog_fetch_fails(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import opencode-- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "require_compatible_opencode"),- patch.object(opencode, "get_settings", return_value=_settings()),- patch.object(opencode, "preflight_proxy", return_value=None),- patch.object(- opencode,- "fetch_proxy_models_response",- side_effect=OSError("catalog unavailable"),- ),- patch.object(opencode, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- opencode.launch(["run", "hello"])-- assert exc_info.value.code == 1- assert "catalog unavailable" in capsys.readouterr().err- run_client_process.assert_not_called()---def test_opencode_reports_temporary_config_creation_failure(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import opencode-- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "require_compatible_opencode"),- patch.object(opencode, "get_settings", return_value=_settings()),- patch.object(opencode, "preflight_proxy", return_value=None),- patch.object(- opencode,- "fetch_proxy_models_response",- return_value=_models_payload(),- ),- patch.object(- opencode.tempfile,- "TemporaryDirectory",- side_effect=OSError("temporary directory unavailable"),- ),- patch.object(opencode, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- opencode.launch(["run", "hello"])-- assert exc_info.value.code == 1- assert "temporary directory unavailable" in capsys.readouterr().err- run_client_process.assert_not_called()---def test_opencode_reports_temporary_config_write_failure(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import opencode-- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "require_compatible_opencode"),- patch.object(opencode, "get_settings", return_value=_settings()),- patch.object(opencode, "preflight_proxy", return_value=None),- patch.object(- opencode,- "fetch_proxy_models_response",- return_value=_models_payload(),- ),- patch.object(- opencode.Path,- "write_text",- side_effect=OSError("temporary file unavailable"),- ),- patch.object(opencode, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- opencode.launch(["run", "hello"])-- assert exc_info.value.code == 1- assert "temporary file unavailable" in capsys.readouterr().err- run_client_process.assert_not_called()---def test_opencode_rejects_empty_proxy_token_before_network_calls(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import opencode-- with (- patch.object(- opencode, "resolve_client_binary", return_value="resolved-opencode"- ),- patch.object(opencode, "require_compatible_opencode"),- patch.object(- opencode,- "get_settings",- return_value=SimpleNamespace(- host="0.0.0.0",- port=9191,- proxy_auth_token=" ",- ),- ),- patch.object(opencode, "preflight_proxy") as preflight_proxy,- patch.object(opencode, "run_client_process") as run_client_process,- pytest.raises(SystemExit) as exc_info,- ):- opencode.launch([])-- assert exc_info.value.code == 1- assert "token is empty" in capsys.readouterr().err- preflight_proxy.assert_not_called()- run_client_process.assert_not_called()---def test_opencode_rejects_incompatible_version_with_upgrade_hint(- capsys: pytest.CaptureFixture[str],-) -> None:- from free_claude_code.cli.launchers import opencode+def test_opencode_child_receives_private_catalog_and_overlay(launch_capture) -> None:+ from tests.cli.test_launcher_workflow import launch- with (- patch.object(opencode, "opencode_binary_version", return_value=(1, 18, 17)),- pytest.raises(SystemExit) as exc_info,- ):- opencode.require_compatible_opencode("resolved-opencode")+ def inspect(command, env):+ config = json.loads(Path(env["OPENCODE_CONFIG"]).read_text())+ overlay = json.loads(env["OPENCODE_CONFIG_CONTENT"])+ provider = config["provider"]["free-claude-code"]+ assert provider["options"]["baseURL"] == "http://127.0.0.1:8182/v1"+ assert "nvidia_nim/catalog-model:variant" in provider["models"]+ assert overlay["enabled_providers"] == ["free-claude-code"]+ assert env["FCC_OPENCODE_API_KEY"] == "launcher-test-token"- assert exc_info.value.code == 126- captured = capsys.readouterr()- assert "stable release at least version 1.18.18" in captured.err- assert "opencode upgrade" in captured.err+ launch_capture.on_start = inspect+ launch("opencode", ["models"])[email protected]("version", [(1, 18, 18), (1, 19, 0), (2, 0, 0)])-def test_opencode_accepts_stable_minimum_and_newer_versions(- version: tuple[int, int, int],[email protected]("key", ("OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT"))+def test_existing_opencode_process_configuration_is_not_replaced(+ key, launch_capture, monkeypatch) -> None:- from free_claude_code.cli.launchers import opencode+ from tests.cli.test_launcher_workflow import launch- with patch.object(opencode, "opencode_binary_version", return_value=version):- opencode.require_compatible_opencode("resolved-opencode")+ monkeypatch.setenv(key, "user-owned-config")+ launch("opencode", [], exit_code=1)+ assert not launch_capture.commandsdiff --git a/tests/cli/test_pi_launcher.py b/tests/cli/test_pi_launcher.pynew file mode 100644index 00000000..55d6767d--- /dev/null+++ b/tests/cli/test_pi_launcher.py@@ -0,0 +1,34 @@+"""Pi keeps its native extension and catalog ownership."""++from pathlib import Path+from unittest.mock import patch++from free_claude_code.cli.launchers import pi+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch+++def test_pi_registers_bundled_extension_without_a_python_catalog(+ launch_capture: LaunchCapture,+) -> None:+ launch("pi", ["--model", "native-selection", "--print", "hello"])+ command = launch_capture.commands[0]+ assert command[:2] == ["pi", "-e"]+ assert Path(command[2]) == pi.pi_extension_path()+ assert command[3:5] == ["--models", "free-claude-code/**"]+ assert launch_capture.environments[0]["FCC_PI_API_KEY"] == "launcher-test-token"+ assert launch_capture.environments[0]["FCC_PI_BASE_URL"] == "http://127.0.0.1:8182"+ assert len(launch_capture.requests) == 1+++def test_missing_bundled_extension_prevents_launch(+ launch_capture: LaunchCapture, tmp_path: Path+) -> None:+ with patch.object(pi, "pi_extension_path", return_value=tmp_path / "absent.ts"):+ launch("pi", [], exit_code=1)+ assert not launch_capture.commands+++def test_pi_install_hints_use_official_platform_installers() -> None:+ assert "https://pi.dev/install.ps1" in pi.pi_install_hint("win32")+ assert "https://pi.dev/install.sh" in pi.pi_install_hint("linux")diff --git a/uv.lock b/uv.lockindex d6cf4d96..22f27a55 100644--- a/uv.lock+++ b/uv.lock@@ -598,7 +598,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "5.22.6"+version = "5.22.7"source = { editable = "." }dependencies = [{ name = "aiohttp" },