free-claude-code/cli/launchers/codex_model_catalog.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

184 lines
5.8 KiB
Python

"""Build Codex model catalogs from the FCC model-list route."""
import json
import uuid
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from api.gateway_model_ids import (
GATEWAY_MODEL_ID_PREFIX,
NO_THINKING_GATEWAY_MODEL_ID_PREFIX,
)
from config.provider_ids import SUPPORTED_PROVIDER_IDS
SUPPORTED_REASONING_LEVELS = [
{"effort": "low", "description": "Fast responses with lighter reasoning"},
{
"effort": "medium",
"description": "Balances speed and reasoning depth for everyday tasks",
},
{"effort": "high", "description": "Greater reasoning depth for complex problems"},
{
"effort": "xhigh",
"description": "Extra high reasoning depth for complex problems",
},
]
CODEX_BASE_INSTRUCTIONS = (
"You are Codex, a coding agent. Help the user understand, modify, test, "
"and review code in their workspace. Follow the user's instructions, use "
"tools when needed, and communicate concise progress and verification."
)
@dataclass(frozen=True, slots=True)
class _CatalogCandidate:
slug: str
provider_model_ref: str
display_name: str
force_no_thinking: bool
def build_codex_model_catalog(models_response: Mapping[str, Any]) -> dict[str, Any]:
"""Convert FCC `/v1/models` data into Codex `model_catalog_json` payload."""
candidates = list(_catalog_candidates(models_response))
normal_provider_refs = {
candidate.provider_model_ref
for candidate in candidates
if not candidate.force_no_thinking
}
models: list[dict[str, Any]] = []
seen_slugs: set[str] = set()
for candidate in candidates:
if (
candidate.force_no_thinking
and candidate.provider_model_ref in normal_provider_refs
):
continue
if candidate.slug in seen_slugs:
continue
seen_slugs.add(candidate.slug)
models.append(_codex_catalog_entry(candidate, priority=len(models)))
return {"models": models}
def write_codex_model_catalog(catalog_path: Path, catalog: Mapping[str, Any]) -> None:
"""Atomically write a Codex model catalog JSON file."""
catalog_path.parent.mkdir(parents=True, exist_ok=True)
temp_path = catalog_path.with_name(f".{catalog_path.name}.{uuid.uuid4().hex}.tmp")
temp_path.write_text(
json.dumps(catalog, ensure_ascii=True, indent=2) + "\n",
encoding="utf-8",
)
temp_path.replace(catalog_path)
def _catalog_candidates(
models_response: Mapping[str, Any],
) -> list[_CatalogCandidate]:
data = models_response.get("data")
if not isinstance(data, list):
return []
candidates: list[_CatalogCandidate] = []
for item in data:
if not isinstance(item, Mapping):
continue
model_id = _string_value(item.get("id"))
if model_id is None:
continue
candidate = _candidate_from_model_id(
model_id,
display_name=_string_value(item.get("display_name")) or model_id,
)
if candidate is not None:
candidates.append(candidate)
return candidates
def _candidate_from_model_id(
model_id: str, *, display_name: str
) -> _CatalogCandidate | None:
prefix, separator, remainder = model_id.partition("/")
if not separator:
return None
if prefix == GATEWAY_MODEL_ID_PREFIX:
if not _is_provider_model_ref(remainder):
return None
return _CatalogCandidate(
slug=remainder,
provider_model_ref=remainder,
display_name=display_name,
force_no_thinking=False,
)
if prefix == NO_THINKING_GATEWAY_MODEL_ID_PREFIX:
if not _is_provider_model_ref(remainder):
return None
return _CatalogCandidate(
slug=model_id,
provider_model_ref=remainder,
display_name=display_name,
force_no_thinking=True,
)
if prefix in SUPPORTED_PROVIDER_IDS and remainder:
return _CatalogCandidate(
slug=model_id,
provider_model_ref=model_id,
display_name=display_name,
force_no_thinking=False,
)
return None
def _codex_catalog_entry(
candidate: _CatalogCandidate, *, priority: int
) -> dict[str, Any]:
return {
"slug": candidate.slug,
"display_name": candidate.display_name,
"description": "Free Claude Code provider model",
"default_reasoning_level": "medium",
"supported_reasoning_levels": SUPPORTED_REASONING_LEVELS,
"shell_type": "shell_command",
"visibility": "list",
"supported_in_api": True,
"priority": priority,
"additional_speed_tiers": [],
"service_tiers": [],
"base_instructions": CODEX_BASE_INSTRUCTIONS,
"supports_reasoning_summaries": True,
"default_reasoning_summary": "none",
"support_verbosity": True,
"default_verbosity": "low",
"apply_patch_tool_type": "freeform",
"web_search_tool_type": "text_and_image",
"truncation_policy": {"mode": "tokens", "limit": 10000},
"supports_parallel_tool_calls": True,
"supports_image_detail_original": True,
"context_window": 200000,
"max_context_window": 200000,
"effective_context_window_percent": 95,
"experimental_supported_tools": [],
"input_modalities": ["text"],
"supports_search_tool": True,
"use_responses_lite": False,
}
def _is_provider_model_ref(value: str) -> bool:
provider_id, separator, provider_model = value.partition("/")
return bool(separator and provider_model and provider_id in SUPPORTED_PROVIDER_IDS)
def _string_value(value: Any) -> str | None:
return value if isinstance(value, str) else None