free-claude-code/cli/entrypoints.py
Ali Khokhar 85b601884d
Some checks are pending
CI / Ban suppressions and legacy annotations (push) Waiting to run
CI / pytest (push) Waiting to run
CI / ruff-check (push) Waiting to run
CI / ruff-format (push) Waiting to run
CI / ty (push) Waiting to run
Remove legacy future annotation imports (#982)
## Problem

Python 3.14 provides native lazy annotations, but the codebase still
relied on legacy future annotation imports. Those imports also made
type-only import cycles easier to hide instead of fixing ownership
boundaries.

## Changes

| Before | After |
| --- | --- |
| Python files used `from __future__ import annotations`. | Python files
rely on Python 3.14 native lazy annotations. |
| Some runtime modules used `TYPE_CHECKING` or local imports for
required dependencies. | Runtime modules use top-level owner-module
imports with explicit boundaries. |
| Local and GitHub guardrails only rejected type ignore suppressions. |
Local and GitHub guardrails reject type ignore suppressions and legacy
future annotation imports. |
| Agent docs only documented the no-type-ignore rule. | Agent docs
document the Python 3.14 annotation and import-boundary rules. |

<!-- greptile_comment -->

<details open><summary><h3>Greptile Summary</h3></summary>

This PR moves the codebase to Python 3.14 native lazy annotations. The
main changes are:

- Removed legacy `from __future__ import annotations` imports across
Python modules.
- Promoted selected runtime dependencies from `TYPE_CHECKING` or local
imports to explicit owner-module imports.
- Added local, GitHub, and contract-test guardrails to reject legacy
future annotation imports.
- Updated agent docs with the annotation and import-boundary rules.
- Bumped the package patch version for production-file changes.
</details>

<h3>Confidence Score: 5/5</h3>

Safe to merge with low risk.

The changes are mostly mechanical annotation cleanup with matching CI
and contract-test guardrails. Reviewed import-boundary updates did not
show a confirmed runtime cycle or dependency break.

No files require special attention.

<details><summary><h3><a href="https://www.greptile.com/trex"><img
alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="20" align="absmiddle"></a> T-Rex Logs</h3></summary>

**What T-Rex did**
- Performed an end-to-end validation of the guardrail contract suite: an
environment check confirmed uv availability, a guardrail pytest run used
CPython 3.14.0 with 5 passing contract tests, 3 focused CI-script tests
passed, and the direct CI suppressions guardrail command (including the
legacy future-annotations grep) also passed.

<a
href="https://app.greptile.com/trex/runs/13303335/artifacts"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifactsDark.svg?v=4"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"><img
alt="View all artifacts"
src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"></picture></a>

<sub><a href="https://www.greptile.com/trex"><img alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="14" align="absmiddle"></a> Ran code and verified through
T-Rex</sub>
</details>

<details open><summary><h3>Important Files Changed</h3></summary>

| Filename | Overview |
|----------|----------|
| api/runtime.py | Moves messaging, CLI manager, session, limiter, and
tree dependencies from local/type-checking imports to explicit top-level
owner-module imports. |
| messaging/platforms/telegram.py | Removes future annotations and
promotes Telegram SDK type imports into the existing availability guard.
|
| messaging/platforms/telegram_inbound.py | Removes future annotations
and imports Telegram SDK types at module scope for inbound
normalization. |
| tests/contracts/test_import_boundaries.py | Adds an AST contract that
rejects legacy future annotation imports across Python files. |
| scripts/ci.sh | Extends the local suppression check to reject legacy
future annotation imports alongside type-ignore suppressions. |
| scripts/ci.ps1 | Mirrors the local PowerShell CI suppression check for
legacy future annotations. |
| .github/workflows/tests.yml | Renames and broadens the GitHub
guardrail job to reject both type suppressions and legacy future
annotations. |
| pyproject.toml | Bumps the patch version for production-file changes.
|

</details>

<details open><summary><h3>Sequence Diagram</h3></summary>

<a href="#gh-light-mode-only">

```mermaid
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant Dev as Developer/CI
participant Guard as Suppression guard
participant AST as Import-boundary contract test
participant Py as Python modules

Dev->>Guard: Run local/GitHub suppression check
Guard->>Py: "Scan *.py for type ignores and future annotations"
Guard-->>Dev: Fail if legacy annotation import remains
Dev->>AST: Run pytest contract tests
AST->>Py: Parse imports with ast
AST-->>Dev: Assert no future annotations/import-boundary violations
Py-->>Dev: Use Python 3.14 native lazy annotations
```

</a>
<a href="#gh-dark-mode-only">

```mermaid
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant Dev as Developer/CI
participant Guard as Suppression guard
participant AST as Import-boundary contract test
participant Py as Python modules

Dev->>Guard: Run local/GitHub suppression check
Guard->>Py: "Scan *.py for type ignores and future annotations"
Guard-->>Dev: Fail if legacy annotation import remains
Dev->>AST: Run pytest contract tests
AST->>Py: Parse imports with ast
AST-->>Dev: Assert no future annotations/import-boundary violations
Py-->>Dev: Use Python 3.14 native lazy annotations
```

</a>
</details>

<sub>Reviews (2): Last reviewed commit: ["Remove legacy future
annotations
import"](6e6cda69da)
| [Re-trigger
Greptile](https://app.greptile.com/api/retrigger?id=41875785)</sub>

<!-- /greptile_comment -->
2026-07-04 21:41:51 -07:00

148 lines
4.5 KiB
Python

"""CLI entry points for the installed package."""
import os
import shutil
import threading
import time
import webbrowser
from pathlib import Path
import uvicorn
from api.admin_urls import local_admin_url, local_proxy_root_url
from api.app import GracefulLifespanApp, create_app
from cli.launchers.common import preflight_proxy
from cli.process_registry import (
kill_all_best_effort,
)
from config.env_template import load_env_template
from config.paths import (
config_dir_path,
legacy_env_paths,
managed_env_path,
)
from config.settings import Settings, get_settings
SERVER_GRACEFUL_SHUTDOWN_SECONDS = 5
def serve() -> None:
"""Start the FastAPI server (registered as `fcc-server` script)."""
opened_admin_browser = False
try:
try:
while True:
_migrate_legacy_env_if_missing()
settings = get_settings()
if not _run_supervised_server(
settings, open_admin_browser=not opened_admin_browser
):
return
opened_admin_browser = True
get_settings.cache_clear()
except KeyboardInterrupt:
return
finally:
kill_all_best_effort()
def _admin_browser_open_enabled() -> bool:
"""Whether to open /admin when the server becomes reachable (FCC_OPEN_BROWSER)."""
raw = os.environ.get("FCC_OPEN_BROWSER", "true").strip().lower()
return raw not in {"", "0", "false", "no"}
def _schedule_open_admin_browser(settings: Settings) -> None:
"""After /health succeeds, open the admin UI in the default browser (daemon thread)."""
if not _admin_browser_open_enabled():
return
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 one uvicorn server instance; return whether admin requested restart."""
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
app = create_app(lifespan_enabled=False)
app.state.admin_restart_callback = request_restart
asgi_app = GracefulLifespanApp(app)
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
def init() -> None:
"""Scaffold config at ~/.fcc/.env (registered as `fcc-init`)."""
config_dir = config_dir_path()
env_file = managed_env_path()
migrated_from = _migrate_legacy_env_if_missing()
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