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
Make version commands bypass server startup imports (#1135)
Ali Khokhar56b0a21c0a3d
diff --git a/pyproject.toml b/pyproject.tomlindex 2eed690c..dfdc3600 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "4.7.0"+version = "4.7.1"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/src/free_claude_code/cli/commands.py b/src/free_claude_code/cli/commands.pynew file mode 100644index 00000000..a4c77dfc--- /dev/null+++ b/src/free_claude_code/cli/commands.py@@ -0,0 +1,153 @@+"""Implementations for installed Free Claude Code commands."""++import os+import shutil+import sys+import threading+import time+import webbrowser+from pathlib import Path++import uvicorn++from free_claude_code.cli.launchers.common import preflight_proxy+from free_claude_code.cli.process_registry import kill_all_best_effort+from free_claude_code.config.env_migrations import (+ explicit_env_file_huggingface_warning,+ migrate_owned_env_files,+)+from free_claude_code.config.env_template import load_env_template+from free_claude_code.config.paths import (+ config_dir_path,+ legacy_env_paths,+ managed_env_path,+)+from free_claude_code.config.server_urls import local_admin_url, local_proxy_root_url+from free_claude_code.config.settings import Settings, get_settings+from free_claude_code.runtime.bootstrap import build_asgi_app++SERVER_GRACEFUL_SHUTDOWN_SECONDS = 5+++def serve() -> None:+ """Start and supervise the FastAPI server."""+ opened_admin_browser = False+ try:+ try:+ while True:+ _migrate_legacy_env_if_missing()+ _migrate_config_env_keys()+ settings = get_settings()+ should_open_admin = (+ settings.open_admin_browser and not opened_admin_browser+ )+ if not _run_supervised_server(+ settings, open_admin_browser=should_open_admin+ ):+ return+ opened_admin_browser = opened_admin_browser or should_open_admin+ get_settings.cache_clear()+ except KeyboardInterrupt:+ return+ finally:+ kill_all_best_effort()+++def _schedule_open_admin_browser(settings: Settings) -> None:+ """After /health succeeds, open the admin UI in the default browser (daemon thread)."""++ admin_url = local_admin_url(settings)+ proxy_root_url = local_proxy_root_url(settings)++ def open_when_ready() -> None:+ deadline = time.monotonic() + 30.0+ while time.monotonic() < deadline:+ if preflight_proxy(proxy_root_url) is None:+ webbrowser.open(admin_url)+ return+ time.sleep(0.15)++ threading.Thread(+ target=open_when_ready, name="fcc-open-admin-browser", daemon=True+ ).start()+++def _run_supervised_server(settings: Settings, *, open_admin_browser: bool) -> bool:+ """Run once; restart only after the old ownership graph fully closes."""++ restart_requested = False+ server_holder: dict[str, uvicorn.Server] = {}++ def request_restart() -> None:+ nonlocal restart_requested+ restart_requested = True+ if server := server_holder.get("server"):+ server.should_exit = True++ asgi_app = build_asgi_app(settings, restart_callback=request_restart)+ config = uvicorn.Config(+ asgi_app,+ host=settings.host,+ port=settings.port,+ log_level="debug",+ timeout_graceful_shutdown=SERVER_GRACEFUL_SHUTDOWN_SECONDS,+ )+ server = uvicorn.Server(config)+ server_holder["server"] = server+ if open_admin_browser:+ _schedule_open_admin_browser(settings)+ server.run()+ return restart_requested and asgi_app.runtime.is_closed+++def init() -> None:+ """Scaffold config at ~/.fcc/.env."""+ config_dir = config_dir_path()+ env_file = managed_env_path()++ migrated_from = _migrate_legacy_env_if_missing()+ _migrate_config_env_keys()+ if migrated_from is not None:+ print(f"Config migrated from {migrated_from} to {env_file}")+ print(+ "Edit it to set your API keys and model preferences, then run: fcc-server"+ )+ return++ if env_file.exists():+ print(f"Config already exists at {env_file}")+ print("Delete it first if you want to reset to defaults.")+ return++ config_dir.mkdir(parents=True, exist_ok=True)+ template = load_env_template()+ env_file.write_text(template, encoding="utf-8")+ print(f"Config created at {env_file}")+ print("Edit it to set your API keys and model preferences, then run: fcc-server")+++def _migrate_legacy_env_if_missing() -> Path | None:+ """Copy a legacy user env into the managed config path when absent."""++ env_file = managed_env_path()+ if env_file.exists():+ return None++ # TODO: Remove after the ~/.fcc/.env migration has had a release cycle.+ for legacy_env in legacy_env_paths():+ if not legacy_env.is_file():+ continue+ env_file.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(legacy_env, env_file)+ return legacy_env++ return None+++def _migrate_config_env_keys() -> tuple[Path, ...]:+ """Apply dotenv key migrations before Settings loads config."""++ migrated = migrate_owned_env_files()+ if warning := explicit_env_file_huggingface_warning(os.environ):+ print(warning, file=sys.stderr)+ return migrateddiff --git a/src/free_claude_code/cli/entrypoints.py b/src/free_claude_code/cli/entrypoints.pyindex 7f45c05b..f0db25ab 100644--- a/src/free_claude_code/cli/entrypoints.py+++ b/src/free_claude_code/cli/entrypoints.py@@ -1,137 +1,31 @@-"""CLI entry points for the installed package."""+"""Lightweight entry points for installed Free Claude Code commands."""-import os-import shutilimport sys-import threading-import time-import webbrowserfrom collections.abc import Sequence-from pathlib import Path-import uvicorn--from free_claude_code.cli.launchers.common import preflight_proxy-from free_claude_code.cli.process_registry import (- kill_all_best_effort,-)-from free_claude_code.config.env_migrations import (- explicit_env_file_huggingface_warning,- migrate_owned_env_files,-)-from free_claude_code.config.env_template import load_env_template-from free_claude_code.config.paths import (- config_dir_path,- legacy_env_paths,- managed_env_path,-)-from free_claude_code.config.server_urls import local_admin_url, local_proxy_root_url-from free_claude_code.config.settings import Settings, get_settingsfrom free_claude_code.core.version import package_version-from free_claude_code.runtime.bootstrap import build_asgi_app--SERVER_GRACEFUL_SHUTDOWN_SECONDS = 5def serve(argv: Sequence[str] | None = None) -> None:- """Start the FastAPI server (registered as `fcc-server` script)."""+ """Start the FastAPI server (registered as ``fcc-server``)."""if _print_version_if_requested(argv):return- opened_admin_browser = False- try:- try:- while True:- _migrate_legacy_env_if_missing()- _migrate_config_env_keys()- settings = get_settings()- should_open_admin = (- settings.open_admin_browser and not opened_admin_browser- )- if not _run_supervised_server(- settings, open_admin_browser=should_open_admin- ):- return- opened_admin_browser = opened_admin_browser or should_open_admin- get_settings.cache_clear()- except KeyboardInterrupt:- return- finally:- kill_all_best_effort()---def _schedule_open_admin_browser(settings: Settings) -> None:- """After /health succeeds, open the admin UI in the default browser (daemon thread)."""-- admin_url = local_admin_url(settings)- proxy_root_url = local_proxy_root_url(settings)-- def open_when_ready() -> None:- deadline = time.monotonic() + 30.0- while time.monotonic() < deadline:- if preflight_proxy(proxy_root_url) is None:- webbrowser.open(admin_url)- return- time.sleep(0.15)- threading.Thread(- target=open_when_ready, name="fcc-open-admin-browser", daemon=True- ).start()+ # Keep the server composition root off metadata-only command paths.+ from free_claude_code.cli.commands import serve as run_server--def _run_supervised_server(settings: Settings, *, open_admin_browser: bool) -> bool:- """Run once; restart only after the old ownership graph fully closes."""-- restart_requested = False- server_holder: dict[str, uvicorn.Server] = {}-- def request_restart() -> None:- nonlocal restart_requested- restart_requested = True- if server := server_holder.get("server"):- server.should_exit = True-- asgi_app = build_asgi_app(settings, restart_callback=request_restart)- config = uvicorn.Config(- asgi_app,- host=settings.host,- port=settings.port,- log_level="debug",- timeout_graceful_shutdown=SERVER_GRACEFUL_SHUTDOWN_SECONDS,- )- server = uvicorn.Server(config)- server_holder["server"] = server- if open_admin_browser:- _schedule_open_admin_browser(settings)- server.run()- return restart_requested and asgi_app.runtime.is_closed+ run_server()def init(argv: Sequence[str] | None = None) -> None:- """Scaffold config at ~/.fcc/.env (registered as `fcc-init`)."""+ """Scaffold config at ~/.fcc/.env (registered as ``fcc-init``)."""if _print_version_if_requested(argv):return- config_dir = config_dir_path()- env_file = managed_env_path()- migrated_from = _migrate_legacy_env_if_missing()- _migrate_config_env_keys()- if migrated_from is not None:- print(f"Config migrated from {migrated_from} to {env_file}")- print(- "Edit it to set your API keys and model preferences, then run: fcc-server"- )- return+ # Config initialization shares command infrastructure with the server.+ from free_claude_code.cli.commands import init as initialize_config- if env_file.exists():- print(f"Config already exists at {env_file}")- print("Delete it first if you want to reset to defaults.")- return-- config_dir.mkdir(parents=True, exist_ok=True)- template = load_env_template()- env_file.write_text(template, encoding="utf-8")- print(f"Config created at {env_file}")- print("Edit it to set your API keys and model preferences, then run: fcc-server")+ initialize_config()def _print_version_if_requested(argv: Sequence[str] | None) -> bool:@@ -140,30 +34,3 @@ def _print_version_if_requested(argv: Sequence[str] | None) -> bool:return Falseprint(f"free-claude-code {package_version()}")return True---def _migrate_legacy_env_if_missing() -> Path | None:- """Copy a legacy user env into the managed config path when absent."""-- env_file = managed_env_path()- if env_file.exists():- return None-- # TODO: Remove after the ~/.fcc/.env migration has had a release cycle.- for legacy_env in legacy_env_paths():- if not legacy_env.is_file():- continue- env_file.parent.mkdir(parents=True, exist_ok=True)- shutil.copyfile(legacy_env, env_file)- return legacy_env-- return None---def _migrate_config_env_keys() -> tuple[Path, ...]:- """Apply dotenv key migrations before Settings loads config."""-- migrated = migrate_owned_env_files()- if warning := explicit_env_file_huggingface_warning(os.environ):- print(warning, file=sys.stderr)- return migrateddiff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex ac2e844c..34a8d9ec 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -1,6 +1,8 @@-"""Tests for cli/entrypoints.py — fcc-init scaffolding logic."""+"""Tests for installed CLI entrypoints, commands, and launchers."""import json+import subprocess+import sysimport tomllibfrom collections.abc import Callablefrom pathlib import Path@@ -31,7 +33,7 @@ def _launcher_settings(def _run_init(tmp_home: Path) -> tuple[str, Path]:"""Run init() with home directory redirected to tmp_home. Returns (printed output, env_file path)."""- from free_claude_code.cli.entrypoints import init+ from free_claude_code.cli.commands import initenv_file = tmp_home / ".fcc" / ".env"printed: list[str] = []@@ -109,7 +111,7 @@ def test_legacy_env_migration_does_not_overwrite_managed_env(tmp_path: Path,) -> None:"""Legacy migration never overwrites an existing ~/.fcc/.env."""- from free_claude_code.cli.entrypoints import _migrate_legacy_env_if_missing+ from free_claude_code.cli.commands import _migrate_legacy_env_if_missingmanaged_env = tmp_path / ".fcc" / ".env"managed_env.parent.mkdir(parents=True)@@ -194,38 +196,55 @@ def test_fcc_owned_entrypoints_report_version_without_side_effects() -> None:from free_claude_code.cli import entrypoints- with (- patch.object(entrypoints, "package_version", return_value="9.8.7"),- patch.object(entrypoints, "_migrate_legacy_env_if_missing") as migrate_legacy,- patch.object(entrypoints, "_migrate_config_env_keys") as migrate_keys,- patch.object(entrypoints, "get_settings") as get_settings,- patch.object(- entrypoints, "_run_supervised_server", return_value=False- ) as run_server,- patch.object(entrypoints, "kill_all_best_effort") as kill_all,- patch.object(entrypoints, "config_dir_path") as config_dir,- patch.object(entrypoints, "managed_env_path") as managed_env,- patch.object(entrypoints, "load_env_template") as load_template,- ):+ with patch.object(entrypoints, "package_version", return_value="9.8.7"):getattr(entrypoints, entrypoint_name)(argv)assert capsys.readouterr() == ("free-claude-code 9.8.7\n", "")- for side_effect in {- migrate_legacy,- migrate_keys,- get_settings,- run_server,- kill_all,- config_dir,- managed_env,- load_template,- }:- side_effect.assert_not_called()++[email protected]("entrypoint_name", ["serve", "init"])+def test_version_entrypoints_do_not_import_command_runtime(+ entrypoint_name: str,+) -> None:+ script = "\n".join(+ (+ "import json",+ "import sys",+ f"from free_claude_code.cli.entrypoints import {entrypoint_name}",+ f"{entrypoint_name}(['--version'])",+ "forbidden = ('uvicorn', 'fastapi', 'openai', "+ "'free_claude_code.cli.commands', "+ "'free_claude_code.runtime.bootstrap')",+ "print(json.dumps([name for name in forbidden if name in sys.modules]))",+ )+ )++ completed = subprocess.run(+ [sys.executable, "-c", script],+ capture_output=True,+ check=False,+ text=True,+ )++ assert completed.returncode == 0, completed.stderr+ assert json.loads(completed.stdout.splitlines()[-1]) == []++[email protected]("entrypoint_name", ["serve", "init"])+def test_non_version_entrypoints_delegate_to_command_implementation(+ entrypoint_name: str,+) -> None:+ from free_claude_code.cli import commands, entrypoints++ with patch.object(commands, entrypoint_name) as command:+ getattr(entrypoints, entrypoint_name)(())++ command.assert_called_once_with()def test_schedule_open_admin_browser_opens_when_health_ready() -> None:"""Opening /admin runs after /health preflight succeeds."""- from free_claude_code.cli import entrypoints+ from free_claude_code.cli import commandsfrom free_claude_code.config.server_urls import local_admin_urlsettings = _launcher_settings(port=31337)@@ -240,41 +259,41 @@ def test_schedule_open_admin_browser_opens_when_health_ready() -> None:self._target()with (- patch.object(entrypoints.threading, "Thread", ImmediateThread),- patch.object(entrypoints, "preflight_proxy", return_value=None),+ patch.object(commands.threading, "Thread", ImmediateThread),+ patch.object(commands, "preflight_proxy", return_value=None),patch.object(- entrypoints.webbrowser,+ commands.webbrowser,"open",side_effect=lambda url: opened_urls.append(url),),- patch.object(entrypoints.time, "sleep"),+ patch.object(commands.time, "sleep"),):- entrypoints._schedule_open_admin_browser(settings)+ commands._schedule_open_admin_browser(settings)assert opened_urls == [local_admin_url(settings)]def test_serve_skips_admin_browser_when_setting_is_disabled() -> None:- from free_claude_code.cli import entrypoints+ from free_claude_code.cli import commandssettings = _launcher_settings(open_admin_browser=False)get_settings = MagicMock(return_value=settings)get_settings.cache_clear = MagicMock()with (- patch.object(entrypoints, "get_settings", get_settings),+ patch.object(commands, "get_settings", get_settings),patch.object(- entrypoints, "_run_supervised_server", return_value=False+ commands, "_run_supervised_server", return_value=False) as run_server,- patch.object(entrypoints, "kill_all_best_effort"),+ patch.object(commands, "kill_all_best_effort"),):- entrypoints.serve()+ commands.serve()run_server.assert_called_once_with(settings, open_admin_browser=False)def test_serve_supervisor_restarts_when_app_requests_restart() -> None:- from free_claude_code.cli import entrypoints+ from free_claude_code.cli import commandssettings = _launcher_settings()get_settings = MagicMock(side_effect=[settings, settings])@@ -306,16 +325,14 @@ def test_serve_supervisor_restarts_when_app_requests_restart() -> None:return SimpleNamespace(app=app, kwargs=kwargs)with (- patch.object(entrypoints, "get_settings", get_settings),- patch.object(entrypoints.uvicorn, "Config", side_effect=fake_config),- patch.object(entrypoints.uvicorn, "Server", side_effect=FakeServer),- patch.object(entrypoints, "build_asgi_app", side_effect=build_asgi_app),- patch.object(- entrypoints, "_schedule_open_admin_browser"- ) as schedule_open_admin,- patch.object(entrypoints, "kill_all_best_effort") as kill_all,+ patch.object(commands, "get_settings", get_settings),+ patch.object(commands.uvicorn, "Config", side_effect=fake_config),+ patch.object(commands.uvicorn, "Server", side_effect=FakeServer),+ patch.object(commands, "build_asgi_app", side_effect=build_asgi_app),+ patch.object(commands, "_schedule_open_admin_browser") as schedule_open_admin,+ patch.object(commands, "kill_all_best_effort") as kill_all,):- entrypoints.serve()+ commands.serve()assert len(servers) == 2schedule_open_admin.assert_called_once_with(settings)@@ -324,7 +341,7 @@ def test_serve_supervisor_restarts_when_app_requests_restart() -> None:def test_serve_supervisor_refuses_restart_after_incomplete_shutdown() -> None:- from free_claude_code.cli import entrypoints+ from free_claude_code.cli import commandssettings = _launcher_settings()get_settings = MagicMock(return_value=settings)@@ -350,14 +367,14 @@ def test_serve_supervisor_refuses_restart_after_incomplete_shutdown() -> None:return SimpleNamespace(app=app, kwargs=kwargs)with (- patch.object(entrypoints, "get_settings", get_settings),- patch.object(entrypoints.uvicorn, "Config", side_effect=fake_config),- patch.object(entrypoints.uvicorn, "Server", side_effect=FakeServer),- patch.object(entrypoints, "build_asgi_app", side_effect=build_asgi_app),- patch.object(entrypoints, "_schedule_open_admin_browser"),- patch.object(entrypoints, "kill_all_best_effort") as kill_all,+ patch.object(commands, "get_settings", get_settings),+ patch.object(commands.uvicorn, "Config", side_effect=fake_config),+ patch.object(commands.uvicorn, "Server", side_effect=FakeServer),+ patch.object(commands, "build_asgi_app", side_effect=build_asgi_app),+ patch.object(commands, "_schedule_open_admin_browser"),+ patch.object(commands, "kill_all_best_effort") as kill_all,):- entrypoints.serve()+ commands.serve()assert len(servers) == 1get_settings.cache_clear.assert_not_called()@@ -365,7 +382,7 @@ def test_serve_supervisor_refuses_restart_after_incomplete_shutdown() -> None:def test_serve_migrates_legacy_env_before_loading_settings(tmp_path: Path) -> None:- from free_claude_code.cli import entrypoints+ from free_claude_code.cli import commandslegacy_env = tmp_path / "free-claude-code" / ".env"legacy_env.parent.mkdir(parents=True)@@ -376,11 +393,11 @@ def test_serve_migrates_legacy_env_before_loading_settings(tmp_path: Path) -> Nowith (patch("pathlib.Path.home", return_value=tmp_path),- patch.object(entrypoints, "get_settings", get_settings),- patch.object(entrypoints, "_run_supervised_server", return_value=False),- patch.object(entrypoints, "kill_all_best_effort"),+ patch.object(commands, "get_settings", get_settings),+ patch.object(commands, "_run_supervised_server", return_value=False),+ patch.object(commands, "kill_all_best_effort"),):- entrypoints.serve()+ commands.serve()assert (tmp_path / ".fcc" / ".env").read_text("utf-8") == ("MODEL=deepseek/deepseek-chat\n"@@ -392,7 +409,7 @@ def test_serve_migrates_hf_token_before_loading_settings(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:- from free_claude_code.cli import entrypoints+ from free_claude_code.cli import commandsrepo = tmp_path / "repo"repo.mkdir()@@ -404,12 +421,12 @@ def test_serve_migrates_hf_token_before_loading_settings(with (patch("pathlib.Path.home", return_value=tmp_path),- patch.object(entrypoints, "get_settings", get_settings),- patch.object(entrypoints, "_run_supervised_server", return_value=False),- patch.object(entrypoints, "kill_all_best_effort"),- patch.object(entrypoints, "explicit_env_file_huggingface_warning"),+ patch.object(commands, "get_settings", get_settings),+ patch.object(commands, "_run_supervised_server", return_value=False),+ patch.object(commands, "kill_all_best_effort"),+ patch.object(commands, "explicit_env_file_huggingface_warning"),):- entrypoints.serve()+ commands.serve()assert (repo / ".env").read_text(encoding="utf-8") == ("HUGGINGFACE_API_KEY=legacy-hf\n"@@ -421,13 +438,13 @@ def test_config_env_key_migration_warns_for_explicit_env_file(tmp_path: Path,capsys: pytest.CaptureFixture[str],) -> None:- from free_claude_code.cli import entrypoints+ from free_claude_code.cli import commandsexplicit = tmp_path / "custom.env"explicit.write_text("HF_TOKEN=legacy-hf\n", encoding="utf-8")- with patch.dict(entrypoints.os.environ, {"FCC_ENV_FILE": str(explicit)}):- migrated = entrypoints._migrate_config_env_keys()+ with patch.dict(commands.os.environ, {"FCC_ENV_FILE": str(explicit)}):+ migrated = commands._migrate_config_env_keys()assert migrated == ()assert "HF_TOKEN" in capsys.readouterr().err@@ -435,22 +452,22 @@ def test_config_env_key_migration_warns_for_explicit_env_file(def test_serve_handles_keyboard_interrupt_without_traceback() -> None:- from free_claude_code.cli import entrypoints+ from free_claude_code.cli import commandssettings = _launcher_settings()get_settings = MagicMock(return_value=settings)get_settings.cache_clear = MagicMock()with (- patch.object(entrypoints, "get_settings", get_settings),+ patch.object(commands, "get_settings", get_settings),patch.object(- entrypoints,+ commands,"_run_supervised_server",side_effect=KeyboardInterrupt,),- patch.object(entrypoints, "kill_all_best_effort") as kill_all,+ patch.object(commands, "kill_all_best_effort") as kill_all,):- entrypoints.serve()+ commands.serve()get_settings.cache_clear.assert_not_called()kill_all.assert_called_once()diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.pyindex 11f859cd..ce904329 100644--- a/tests/contracts/test_import_boundaries.py+++ b/tests/contracts/test_import_boundaries.py@@ -31,11 +31,11 @@ ALLOWED_PACKAGE_DEPENDENCIES: dict[str, set[str]] = {IMPORT_EXCEPTIONS: dict[tuple[str, str], str] = {(- "free_claude_code.cli.entrypoints",+ "free_claude_code.cli.commands","free_claude_code.runtime.bootstrap",): (- "Owner: installed server entrypoint. "- "Reason: the executable delegates construction to the process composition root."+ "Owner: installed server command. "+ "Reason: the command delegates construction to the process composition root."),}diff --git a/uv.lock b/uv.lockindex bf1c792b..3c185806 100644--- a/uv.lock+++ b/uv.lock@@ -561,7 +561,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "4.7.0"+version = "4.7.1"source = { editable = "." }dependencies = [{ name = "aiohttp" },