Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Add Grok Build as an FCC coding agent (#1489)

Ali Khokhard4e76d9926ea
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 2a1b2102..c5a296c1 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -12,16 +12,17 @@ and how contributors should extend it.
Free Claude Code is a local proxy for agent clients. It accepts Anthropic
Messages traffic from Claude Code and Pi clients and OpenAI Responses traffic
-from Codex, OpenCode, Cline, Hermes, and DeepSeek Harness clients, routes the request to a
-configured upstream provider, and preserves the wire protocol expected by the
-caller.
+from Codex, OpenCode, Cline, Hermes, DeepSeek Harness, and Grok Build clients,
+routes the request to a configured upstream provider, and preserves the wire
+protocol expected by the caller.
There are three runtime surfaces:
- HTTP proxy: FastAPI routes expose Anthropic-compatible, Responses-compatible,
health, model-listing, stop, and admin endpoints.
- CLI launchers: wrapper entrypoints prepare Claude Code, Codex, Pi, OpenCode,
- Cline, Hermes, and DeepSeek Harness sessions so they target the local proxy.
+ Cline, Hermes, DeepSeek Harness, and Grok Build sessions so they target the
+ local proxy.
- Messaging bridge: optional Discord or Telegram adapters turn chat messages
into managed client CLI sessions.
@@ -34,6 +35,7 @@ flowchart LR
Cline[Cline CLI] --> ProxyAPI
Hermes[Hermes Agent] --> ProxyAPI
DSH[DeepSeek Harness] --> ProxyAPI
+ Grok[Grok Build] --> ProxyAPI
AdminUI[Local Admin UI] --> ProxyAPI
Bots[Discord or Telegram Bots] --> Messaging[Messaging Bridge]
Messaging --> ClientCLI[Managed Client CLI Sessions]
@@ -185,6 +187,9 @@ for real prompts against supported providers:
- `fcc-dsh`, DeepSeek Harness 0.1.0-rc.8, and the OpenAI Responses behavior it
relies on for attached Web and headless sessions, including an FCC-scoped
model catalog and process-local configuration.
+- `fcc-grok`, Grok Build 1.0.5 or newer, and the OpenAI Responses behavior it
+ relies on for attached terminal, headless, and ACP sessions, including an
+ FCC-scoped model catalog and process-local configuration.
- Configured Discord and Telegram messaging bridges, including command handling,
reply-based conversation branches, status updates, transcript rendering,
managed Claude/Codex task execution where configured, task stop/clear flows,
@@ -243,6 +248,7 @@ Console scripts are registered in [pyproject.toml](pyproject.toml):
- `fcc-cline` calls `free_claude_code.cli.launchers.cline:launch`.
- `fcc-hermes` calls `free_claude_code.cli.launchers.hermes:launch`.
- `fcc-dsh` calls `free_claude_code.cli.launchers.dsh:launch`.
+- `fcc-grok` calls `free_claude_code.cli.launchers.grok:launch`.
[scripts/install.sh](scripts/install.sh) and [scripts/install.ps1](scripts/install.ps1)
install or update the uv tool plus optional voice extras. On Windows the
@@ -251,7 +257,8 @@ per-user application bundle and desktop link. [scripts/uninstall.sh](scripts/uni
and [scripts/uninstall.ps1](scripts/uninstall.ps1) remove those exact desktop
artifacts, the FCC uv tool, and the managed `~/.fcc/` tree from
[config/paths.py](src/free_claude_code/config/paths.py); they do not remove
-uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes, DeepSeek Harness, or uv-managed Python runtimes. [scripts/ci.sh](scripts/ci.sh) and
+uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes, DeepSeek Harness, Grok
+Build, or uv-managed Python runtimes. [scripts/ci.sh](scripts/ci.sh) and
[scripts/ci.ps1](scripts/ci.ps1) mirror [.github/workflows/tests.yml](.github/workflows/tests.yml)
for local pre-push verification.
@@ -618,12 +625,14 @@ generation. Safe `model_fallback.started` and `model_fallback.selected` trace
events expose canonical route refs, candidate positions, failure kind, status,
wire API, and generation without prompt or raw upstream error content.
-`GET /v1/models` advertises:
+`GET /v1/models` owns one neutral inventory with three typed views:
-- configured provider model refs;
-- cached provider-discovered models;
-- no-thinking variants when appropriate;
-- built-in Claude model IDs for compatibility with Claude clients.
+- the default `claude` view preserves configured and cached provider models,
+ no-thinking variants, and built-in Claude compatibility IDs;
+- the `messages` view exposes one direct routable ID per model for
+ Messages-native clients; and
+- the `responses` view exposes those direct IDs plus Responses transport,
+ retry, reasoning, and timeout metadata for Responses-native clients.
Provider model discovery and optional thinking metadata live in the
application-level catalog owned by `ProviderRuntimeManager`.
@@ -646,7 +655,7 @@ translate reasoning. The catalog is not part of an individual provider
generation, so a hot replacement does not erase the last useful model list.
Discovery failures retain prior entries.
-Codex-specific model picker shaping stays out of this route.
+Codex-specific model picker shaping stays outside the neutral inventory.
[runtime/codex_catalog.py](src/free_claude_code/runtime/codex_catalog.py) is the
composition bridge: it asks this route's pure builder for the exact application
inventory, passes that response to the existing Codex adapter, and writes
@@ -1286,12 +1295,10 @@ client environment.
OpenAI authorization.
[cli/launchers/model_catalog.py](src/free_claude_code/cli/launchers/model_catalog.py)
-owns the client-neutral projection from FCC's `/v1/models` response to direct,
-nested `provider/model` routes. It removes Claude-only compatibility aliases,
-deduplicates normal and no-thinking forms deterministically, and is shared by
-Codex, OpenCode, Cline, Hermes, and DeepSeek Harness. Each launcher remains
-responsible for translating those neutral entries into its client's
-configuration format.
+consumes the direct Responses view, validates its nested `provider/model`
+references, and is shared by Codex, OpenCode, Cline, Hermes, DeepSeek Harness,
+and Grok Build. The API owns compatibility filtering and direct wire identity;
+each launcher owns only translation into its client's configuration format.
[cli/launchers/pi.py](src/free_claude_code/cli/launchers/pi.py) owns the installed
`fcc-pi` launcher and [cli/launchers/pi_extension.ts](src/free_claude_code/cli/launchers/pi_extension.ts)
@@ -1301,7 +1308,7 @@ is its bundled Pi adapter:
scope Pi to the ephemeral `free-claude-code/**` provider, whose model IDs
retain FCC's nested `provider/model` routing reference.
- The extension fetches FCC's `/v1/models` catalog before registration, projects
- only routable provider-model IDs, and registers an `anthropic-messages`
+ the direct Messages view, and registers an `anthropic-messages`
provider targeting the local proxy. Catalog failure is fail-closed so Pi never
silently falls back to a different provider.
- Catalog discovery and provider inference use HTTP bearer authorization. Pi's
@@ -1409,6 +1416,24 @@ own the installed `fcc-dsh` launcher for DeepSeek Harness 0.1.0-rc.8:
activity; `fcc-dsh` owns the configured model route, not a general plugin
sandbox.
+[cli/launchers/grok.py](src/free_claude_code/cli/launchers/grok.py) owns the
+installed `fcc-grok` launcher for stable Grok Build 1.0.5 or newer:
+
+- Attached TUI, headless, and `agent stdio` sessions require a reachable FCC
+ server, a canonical proxy token, and a non-empty direct Responses catalog.
+ Model overrides are validated before Grok starts; preparation is fail-closed.
+- A child-only environment points Grok's native Responses backend and model
+ picker at FCC, sets client retries to zero through catalog metadata, and
+ derives its idle timeout from FCC's provider-progress boundary. Native Grok
+ configuration, credentials, sessions, plugins, skills, and telemetry remain
+ Grok-owned and are never rewritten.
+- The wrapper prevents native leader or endpoint overrides for attached
+ sessions. Detached modes pass through or fail explicitly according to their
+ lifecycle, rather than outliving FCC's process-only route.
+- Grok's built-in web search and fetch are disabled because they use a distinct
+ Responses-side service contract FCC does not implement. Ordinary `grok`
+ remains unchanged.
+
[cli/managed/](src/free_claude_code/cli/managed/) owns managed Claude Code subprocesses used by
Discord and Telegram messaging. Managed task invocations extend the same proxy
environment only with non-interactive terminal settings, optional `--resume`,
@@ -1432,10 +1457,10 @@ reports a count-only failure, and leaves failures available for the next cleanup
attempt. Real-session registration is collision-safe and becomes durable tree
state only after the manager accepts it.
-Codex, Pi, OpenCode, Cline, Hermes, and DeepSeek Harness are supported through
-their installed launchers. FCC does not keep internal managed session runners
-for them because no user-facing messaging setting selects those clients for
-Discord or Telegram.
+Codex, Pi, OpenCode, Cline, Hermes, DeepSeek Harness, and Grok Build are
+supported through their installed launchers. FCC does not keep internal managed
+session runners for them because no user-facing messaging setting selects those
+clients for Discord or Telegram.
## Messaging Architecture
diff --git a/README.md b/README.md
index 072f66b3..1c07f9ff 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@
## What You Get
- **48 ToS-friendly providers. 1.3B+ free tokens every month.** Use free, paid, subscription, and local models from one searchable UI without putting your account at risk. FCC follows provider terms and removes integrations if they stop being allowed.
-- **7 coding agents. One model catalog.** Run [Claude Code](https://code.claude.com/docs/en/overview), [Codex](https://github.com/openai/codex), [Pi](https://github.com/earendil-works/pi), [OpenCode](https://github.com/anomalyco/opencode), [Cline](https://github.com/cline/cline), [Hermes](https://github.com/NousResearch/hermes-agent), or [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) with your FCC models.
+- **8 coding agents. One model catalog.** Run [Claude Code](https://code.claude.com/docs/en/overview), [Codex](https://github.com/openai/codex), [Pi](https://github.com/earendil-works/pi), [OpenCode](https://github.com/anomalyco/opencode), [Cline](https://github.com/cline/cline), [Hermes](https://github.com/NousResearch/hermes-agent), [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness), or [Grok Build](https://github.com/xai-org/grok-build) with your FCC models.
- **Keep coding through provider outages.** After retries are exhausted, FCC automatically tries your next configured model without making you restart the turn—across every client.
- **Up to 90% fewer terminal-output tokens.** Optional [RTK](https://github.com/rtk-ai/rtk) filters common command output, while five FCC optimizations handle quota probes, command-prefix detection, titles, suggestions, and filepaths without calling a provider.
- **Terminal, desktop, IDE, or phone.** Work through native launchers, [VS Code](https://code.visualstudio.com/), [Codex App](https://learn.chatgpt.com/docs/app), [JetBrains](https://www.jetbrains.com/), [Discord](https://discord.com/), or [Telegram](https://telegram.org/).
@@ -149,7 +149,13 @@ DeepSeek Harness headless:
fcc-dsh --profile headless "your task"
```
-All seven launchers use the current Admin UI settings. Use the agent's model picker to choose from the models FCC exposes. Normal CLI arguments still work, for example:
+Grok Build:
+
+```bash
+fcc-grok
+```
+
+All eight launchers use the current Admin UI settings. Use the agent's model picker to choose from the models FCC exposes. Normal CLI arguments still work, for example:
```bash
fcc-codex exec "hello"
@@ -161,6 +167,9 @@ another provider with Hermes `/model` intentionally leaves the FCC route.
`fcc-dsh` keeps DeepSeek Harness sessions and plugins while applying temporary
FCC provider settings. It currently supports the preview release `0.1.0-rc.8`
on Node.js `^22.19` or `>=24`.
+`fcc-grok` keeps Grok Build's sessions and plugins, while routing attached
+sessions through FCC. Web search and fetch stay disabled until FCC supports
+Grok Build's Responses-side web-tool contract.
<a id="model-picker"></a>
@@ -310,7 +319,7 @@ Open **Admin UI → Model Config → Reasoning** and select the behavior you wan
| Selection | Behavior |
| --- | --- |
-| **From client** (default) | Use the effort sent by Claude Code, Codex, Pi, OpenCode, Cline, Hermes, or DeepSeek Harness. If none is sent, keep the provider default. |
+| **From client** (default) | Use the effort sent by Claude Code, Codex, Pi, OpenCode, Cline, Hermes, DeepSeek Harness, or Grok Build. If none is sent, keep the provider default. |
| **Off** | Request reasoning to be disabled. |
| **Low**, **Medium**, **High**, **X-High**, or **Max** | Override the client with the selected reasoning level. |
| **Inherit** (Fable, Opus, Sonnet, and Haiku only) | Use the root Reasoning selection. |
@@ -324,7 +333,8 @@ Providers that do not support a selected control retain their own behavior.
## Connect Your Client
For terminal use, start `fcc-server`, then run `fcc-claude`, `fcc-codex`,
-`fcc-pi`, `fcc-opencode`, `fcc-cline`, `fcc-hermes`, or `fcc-dsh`. Use the guides below for editor integrations.
+`fcc-pi`, `fcc-opencode`, `fcc-cline`, `fcc-hermes`, `fcc-dsh`, or `fcc-grok`.
+Use the guides below for editor integrations.
<details>
<summary><strong>Claude Code in VS Code</strong></summary>
@@ -561,7 +571,7 @@ Stop every running FCC command before uninstalling.
**Keeps**
- uv and Python
-- Claude Code, Codex, Pi, OpenCode, Cline, Hermes, DeepSeek Harness, and RTK
+- Claude Code, Codex, Pi, OpenCode, Cline, Hermes, DeepSeek Harness, Grok Build, and RTK
- Shared PATH entries
macOS/Linux:
diff --git a/pyproject.toml b/pyproject.toml
index 40ed0742..d851fdb5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "5.10.0"
+version = "5.11.0"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
@@ -37,6 +37,7 @@ fcc-opencode = "free_claude_code.cli.launchers.opencode:launch"
fcc-cline = "free_claude_code.cli.launchers.cline:launch"
fcc-hermes = "free_claude_code.cli.launchers.hermes:launch"
fcc-dsh = "free_claude_code.cli.launchers.dsh:launch"
+fcc-grok = "free_claude_code.cli.launchers.grok:launch"
[project.gui-scripts]
fcc-desktop = "free_claude_code.cli.desktop_entrypoint:launch"
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 3b54d851..badf6b69 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -28,6 +28,8 @@ $HermesInstallUrl = "https://hermes-agent.nousresearch.com/install.ps1"
$MinHermesVersion = "0.20.4"
$DshVersion = "0.1.0-rc.8"
$DshPackage = "@deepseek-ai/dsh@$DshVersion"
+$GrokInstallUrl = "https://x.ai/cli/install.ps1"
+$MinGrokVersion = "1.0.5"
$RtkVersion = "0.44.2"
$RtkReleaseBaseUrl = "https://github.com/rtk-ai/rtk/releases/download/v$RtkVersion"
$RtkWindowsAssetName = "rtk-x86_64-pc-windows-msvc.zip"
@@ -40,6 +42,7 @@ $script:InstallOpenCode = $true
$script:InstallCline = $false
$script:InstallHermes = $true
$script:InstallDsh = $true
+$script:InstallGrok = $true
$script:PiAvailable = $false
$script:EnableRtk = $Rtk.IsPresent
$FccCommands = @(
@@ -53,6 +56,7 @@ $FccCommands = @(
"fcc-cline",
"fcc-hermes",
"fcc-dsh",
+ "fcc-grok",
"fcc-init",
"free-claude-code"
)
@@ -122,8 +126,11 @@ function Select-CodingAgents {
$script:InstallDsh = Read-YesNo `
-Prompt "Install or verify DeepSeek Harness for fcc-dsh?" `
-DefaultYes $script:InstallDsh
+ $script:InstallGrok = Read-YesNo `
+ -Prompt "Install or verify Grok Build for fcc-grok?" `
+ -DefaultYes $script:InstallGrok
- if ($script:InstallClaudeCode -or $script:InstallCodex -or $script:InstallPi -or $script:InstallOpenCode -or $script:InstallCline -or $script:InstallHermes -or $script:InstallDsh) {
+ if ($script:InstallClaudeCode -or $script:InstallCodex -or $script:InstallPi -or $script:InstallOpenCode -or $script:InstallCline -or $script:InstallHermes -or $script:InstallDsh -or $script:InstallGrok) {
break
}
Write-Host "Select at least one coding agent."
@@ -642,7 +649,7 @@ function Convert-SemanticVersionOutput {
if ([string]::IsNullOrWhiteSpace($Output)) {
return ""
}
- if ($Output -match '(?m)^\s*(?:(?:uv|opencode|cline|dsh|node)(?:\s+version)?\s+|Hermes Agent\s+v?|v)?(?<version>\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?)(?:\s+\([^\r\n]*\))?\s*$') {
+ if ($Output -match '(?m)^\s*(?:(?:uv|opencode|cline|dsh|grok|node)(?:\s+version)?\s+|Hermes Agent\s+v?|v)?(?<version>\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?)(?:\s+\([^\r\n]*\))?\s*$') {
return $Matches["version"]
}
return ""
@@ -932,6 +939,66 @@ function Ensure-Hermes {
Confirm-HermesApplication
}
+function Get-GrokVersion {
+ param([string] $GrokPath)
+
+ $output = Invoke-Utf8NativeCapture -FilePath $GrokPath -Arguments @("--version")
+ $version = Convert-SemanticVersionOutput $output
+ if ([string]::IsNullOrWhiteSpace($version)) {
+ throw "Grok Build is present, but 'grok --version' did not return a valid semantic version."
+ }
+ return $version
+}
+
+function Confirm-GrokApplication {
+ if ($DryRun) {
+ Write-Host "+ grok --version"
+ return
+ }
+
+ $command = Get-ApplicationCommand "grok"
+ if (-not $command) {
+ throw "Grok Build was installed, but 'grok' is not available on PATH."
+ }
+ $version = Get-GrokVersion $command.Source
+ if (-not (Test-SupportedStableVersion -Version $version -Minimum $MinGrokVersion)) {
+ throw "Stable Grok Build $MinGrokVersion or newer is required; found Grok Build $version after installation."
+ }
+ Write-Host "Verified Grok Build $version."
+}
+
+function Install-Grok {
+ Invoke-DownloadedPowerShellInstaller -Url $GrokInstallUrl -Name "Grok Build"
+ Add-KnownBinDirectories
+}
+
+function Ensure-Grok {
+ if ($DryRun) {
+ if (Get-ApplicationCommand "grok") {
+ Write-Host "+ grok --version"
+ Write-Host "A compatible Grok Build will be preserved; an older version will be upgraded with the official installer."
+ }
+ else {
+ Install-Grok
+ }
+ Confirm-GrokApplication
+ return
+ }
+
+ $command = Get-ApplicationCommand "grok"
+ if ($command) {
+ $version = Get-GrokVersion $command.Source
+ if (Test-SupportedStableVersion -Version $version -Minimum $MinGrokVersion) {
+ Write-Host "Grok Build $version already satisfies >=$MinGrokVersion; leaving it unchanged."
+ return
+ }
+ Write-Host "Grok Build $version does not satisfy stable >=$MinGrokVersion; upgrading it with the official installer."
+ }
+
+ Install-Grok
+ Confirm-GrokApplication
+}
+
function Get-DshVersion {
param([string] $DshPath)
@@ -1094,7 +1161,12 @@ function Ensure-SelectedCodingAgents {
Ensure-Dsh
}
- if ((-not $script:InstallClaudeCode) -and (-not $script:InstallCodex) -and (-not $script:PiAvailable) -and (-not $script:InstallOpenCode) -and (-not $script:InstallCline) -and (-not $script:InstallHermes) -and (-not $script:InstallDsh)) {
+ if ($script:InstallGrok) {
+ Write-Step "Ensuring Grok Build is installed"
+ Ensure-Grok
+ }
+
+ if ((-not $script:InstallClaudeCode) -and (-not $script:InstallCodex) -and (-not $script:PiAvailable) -and (-not $script:InstallOpenCode) -and (-not $script:InstallCline) -and (-not $script:InstallHermes) -and (-not $script:InstallDsh) -and (-not $script:InstallGrok)) {
throw "No selected coding agent was installed. Re-run the installer and choose at least one."
}
}
@@ -1249,7 +1321,7 @@ function Configure-AndConfirmFreeClaudeCode {
if ($DryRun) {
Write-Host "+ uv tool update-shell"
Write-Host "+ uv tool dir --bin"
- Write-Host "+ verify fcc-desktop, fcc-server, fcc-claude, fcc-codex, fcc-pi, fcc-opencode, fcc-cline, fcc-hermes, and fcc-dsh in the uv tool bin directory"
+ Write-Host "+ verify fcc-desktop, fcc-server, fcc-claude, fcc-codex, fcc-pi, fcc-opencode, fcc-cline, fcc-hermes, fcc-dsh, and fcc-grok in the uv tool bin directory"
Write-Host "+ fcc-server --version"
Export-FccDesktopIcon `
-DesktopCommand "<uv-tool-bin>\fcc-desktop.exe" `
@@ -1276,7 +1348,7 @@ function Configure-AndConfirmFreeClaudeCode {
[IO.Path]::AltDirectorySeparatorChar
)
$installedCommands = @{}
- foreach ($commandName in @("fcc-desktop", "fcc-server", "fcc-claude", "fcc-codex", "fcc-pi", "fcc-opencode", "fcc-cline", "fcc-hermes", "fcc-dsh")) {
+ foreach ($commandName in @("fcc-desktop", "fcc-server", "fcc-claude", "fcc-codex", "fcc-pi", "fcc-opencode", "fcc-cline", "fcc-hermes", "fcc-dsh", "fcc-grok")) {
$command = Get-ApplicationCommand $commandName
if (-not $command) {
throw "Free Claude Code installation did not create '$commandName'."
@@ -1447,4 +1519,10 @@ else {
else {
Write-Host "The fcc-dsh wrapper is ready after you install DeepSeek Harness $DshVersion."
}
+ if ($script:InstallGrok) {
+ Write-Host "Run Grok Build with: fcc-grok"
+ }
+ else {
+ Write-Host "The fcc-grok wrapper is ready after you install Grok Build $MinGrokVersion or newer."
+ }
}
diff --git a/scripts/install.sh b/scripts/install.sh
index 0578bfd9..e60ad117 100644
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -14,13 +14,15 @@ HERMES_INSTALL_URL="https://hermes-agent.nousresearch.com/install.sh"
MIN_HERMES_VERSION="0.20.4"
DSH_VERSION="0.1.0-rc.8"
DSH_PACKAGE="@deepseek-ai/dsh@$DSH_VERSION"
+GROK_INSTALL_URL="https://x.ai/cli/install.sh"
+MIN_GROK_VERSION="1.0.5"
RTK_VERSION="0.44.2"
RTK_RELEASE_BASE_URL="https://github.com/rtk-ai/rtk/releases/download/v$RTK_VERSION"
UV_INSTALL_URL="https://astral.sh/uv/install.sh"
FCC_MACOS_BUNDLE_ID="io.github.alishahryar1.free-claude-code"
FCC_MACOS_OWNER_FILE=".free-claude-code-owner"
# Include retired entry points so updates reject older FCC processes before replacement.
-FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh fcc-init free-claude-code"
+FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh fcc-grok fcc-init free-claude-code"
dry_run=0
voice_nim=0
@@ -33,6 +35,7 @@ install_opencode=1
install_cline=0
install_hermes=1
install_dsh=1
+install_grok=1
enable_rtk=0
torch_backend=""
temporary_file=""
@@ -156,7 +159,18 @@ choose_coding_agents() {
install_dsh=0
fi
- if [ "$install_claude" -eq 1 ] || [ "$install_codex" -eq 1 ] || [ "$install_pi" -eq 1 ] || [ "$install_opencode" -eq 1 ] || [ "$install_cline" -eq 1 ] || [ "$install_hermes" -eq 1 ] || [ "$install_dsh" -eq 1 ]; then
+ if [ "$install_grok" -eq 1 ]; then
+ grok_default=yes
+ else
+ grok_default=no
+ fi
+ if prompt_yes_no "Install or verify Grok Build for fcc-grok?" "$grok_default"; then
+ install_grok=1
+ else
+ install_grok=0
+ fi
+
+ if [ "$install_claude" -eq 1 ] || [ "$install_codex" -eq 1 ] || [ "$install_pi" -eq 1 ] || [ "$install_opencode" -eq 1 ] || [ "$install_cline" -eq 1 ] || [ "$install_hermes" -eq 1 ] || [ "$install_dsh" -eq 1 ] || [ "$install_grok" -eq 1 ]; then
break
fi
printf 'Select at least one coding agent.\n\n' >&4
@@ -959,6 +973,68 @@ ensure_dsh() {
verify_dsh_command
}
+current_grok_version() {
+ if output=$(grok --version 2>/dev/null); then
+ :
+ else
+ return 1
+ fi
+
+ version=$(printf '%s\n' "$output" | awk '
+ /^[[:space:]]*(grok[[:space:]]+|v)?[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?([[:space:]]+\([^\r\n]*\))?[[:space:]]*$/ &&
+ match($0, /[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?/) {
+ print substr($0, RSTART, RLENGTH)
+ exit
+ }
+ ')
+ [ -n "$version" ] || return 1
+ printf '%s\n' "$version"
+}
+
+verify_grok_command() {
+ if [ "$dry_run" -eq 1 ]; then
+ print_command grok --version
+ return 0
+ fi
+
+ command -v grok >/dev/null 2>&1 || fail "Grok Build was installed, but 'grok' is not available on PATH."
+ version=$(current_grok_version) || fail "Grok Build is present, but 'grok --version' did not return a valid semantic version."
+ if ! stable_version_is_supported "$version" "$MIN_GROK_VERSION"; then
+ fail "Stable Grok Build $MIN_GROK_VERSION or newer is required; found Grok Build $version after installation."
+ fi
+ printf 'Verified Grok Build %s.\n' "$version"
+}
+
+install_grok_build() {
+ download_and_run "$GROK_INSTALL_URL" bash "Grok Build"
+ add_known_bin_directories
+}
+
+ensure_grok() {
+ if [ "$dry_run" -eq 1 ]; then
+ if command -v grok >/dev/null 2>&1; then
+ print_command grok --version
+ printf 'A compatible Grok Build will be preserved; an older version will be upgraded with the official installer.\n'
+ else
+ install_grok_build
+ fi
+ verify_grok_command
+ return 0
+ fi
+
+ if command -v grok >/dev/null 2>&1; then
+ version=$(current_grok_version) || fail "Grok Build is present, but 'grok --version' did not return a valid semantic version."
+ if stable_version_is_supported "$version" "$MIN_GROK_VERSION"; then
+ printf 'Grok Build %s already satisfies >=%s; leaving it unchanged.\n' "$version" "$MIN_GROK_VERSION"
+ return 0
+ fi
+ printf 'Grok Build %s does not satisfy stable >=%s; upgrading it with the official installer.\n' "$version" "$MIN_GROK_VERSION"
+ fi
+
+ install_grok_build
+ verify_grok_command
+}
+
ensure_selected_coding_agents() {
if [ "$install_claude" -eq 1 ]; then
step "Ensuring Claude Code is installed"
@@ -995,7 +1071,12 @@ ensure_selected_coding_agents() {
ensure_dsh
fi
- if [ "$install_claude" -eq 0 ] && [ "$install_codex" -eq 0 ] && [ "$pi_available" -eq 0 ] && [ "$install_opencode" -eq 0 ] && [ "$install_cline" -eq 0 ] && [ "$install_hermes" -eq 0 ] && [ "$install_dsh" -eq 0 ]; then
+ if [ "$install_grok" -eq 1 ]; then
+ step "Ensuring Grok Build is installed"
+ ensure_grok
+ fi
+
+ if [ "$install_claude" -eq 0 ] && [ "$install_codex" -eq 0 ] && [ "$pi_available" -eq 0 ] && [ "$install_opencode" -eq 0 ] && [ "$install_cline" -eq 0 ] && [ "$install_hermes" -eq 0 ] && [ "$install_dsh" -eq 0 ] && [ "$install_grok" -eq 0 ]; then
fail "No selected coding agent was installed. Re-run the installer and choose at least one."
fi
}
@@ -1182,7 +1263,7 @@ configure_and_verify_free_claude_code() {
if [ "$dry_run" -eq 1 ]; then
print_command uv tool dir --bin
- printf '+ verify fcc-desktop, fcc-server, fcc-claude, fcc-codex, fcc-pi, fcc-opencode, fcc-cline, fcc-hermes, and fcc-dsh in the uv tool bin directory\n'
+ printf '+ verify fcc-desktop, fcc-server, fcc-claude, fcc-codex, fcc-pi, fcc-opencode, fcc-cline, fcc-hermes, fcc-dsh, and fcc-grok in the uv tool bin directory\n'
print_command fcc-server --version
return 0
fi
@@ -1200,7 +1281,7 @@ configure_and_verify_free_claude_code() {
export PATH
hash -r 2>/dev/null || true
- for command_name in fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh; do
+ for command_name in fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh fcc-grok; do
[ -x "$tool_bin/$command_name" ] || fail "Free Claude Code installation did not create $tool_bin/$command_name."
done
@@ -1323,7 +1404,7 @@ fi
step "Checking installation prerequisites"
require_command curl
-if [ "$install_claude" -eq 1 ] || [ "$install_opencode" -eq 1 ] || [ "$install_hermes" -eq 1 ]; then
+if [ "$install_claude" -eq 1 ] || [ "$install_opencode" -eq 1 ] || [ "$install_hermes" -eq 1 ] || [ "$install_grok" -eq 1 ]; then
require_command bash
fi
require_command sh
@@ -1390,4 +1471,9 @@ else
else
printf 'The fcc-dsh wrapper is ready after you install DeepSeek Harness %s.\n' "$DSH_VERSION"
fi
+ if [ "$install_grok" -eq 1 ]; then
+ printf 'Run Grok Build with: fcc-grok\n'
+ else
+ printf 'The fcc-grok wrapper is ready after you install Grok Build %s or newer.\n' "$MIN_GROK_VERSION"
+ fi
fi
diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1
index e5361aa1..0c4b4f57 100644
--- a/scripts/uninstall.ps1
+++ b/scripts/uninstall.ps1
@@ -21,6 +21,7 @@ $FccCommands = @(
"fcc-cline",
"fcc-hermes",
"fcc-dsh",
+ "fcc-grok",
"fcc-init",
"free-claude-code"
)
@@ -32,7 +33,7 @@ function Show-Usage {
Usage: uninstall.ps1 [options]
Removes the Free Claude Code uv tool and deletes ~/.fcc/ after removal is verified.
-Does not remove uv, Claude Code, Codex, Pi, OpenCode, the uv-managed Python runtime, or shared PATH entries.
+Does not remove uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes Agent, DeepSeek Harness, Grok Build, the uv-managed Python runtime, or shared PATH entries.
Options:
-DryRun Print commands without running them.
@@ -337,5 +338,5 @@ if ($DryRun) {
}
else {
Write-Host "Free Claude Code has been removed and verified."
- Write-Host "uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes Agent, DeepSeek Harness, the uv-managed Python runtime, and shared PATH entries were left installed."
+ Write-Host "uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes Agent, DeepSeek Harness, Grok Build, the uv-managed Python runtime, and shared PATH entries were left installed."
}
diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh
index 2a7aa5ac..b65de24b 100644
--- a/scripts/uninstall.sh
+++ b/scripts/uninstall.sh
@@ -6,7 +6,7 @@ FCC_HOME_DIRNAME=".fcc"
FCC_MACOS_BUNDLE_ID="io.github.alishahryar1.free-claude-code"
FCC_MACOS_OWNER_FILE=".free-claude-code-owner"
# Include retired entry points so older installations are fully stopped and removed.
-FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh fcc-init free-claude-code"
+FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh fcc-grok fcc-init free-claude-code"
dry_run=0
uv_tool_bin=""
@@ -16,7 +16,7 @@ show_usage() {
Usage: uninstall.sh [options]
Removes the Free Claude Code uv tool and deletes ~/.fcc/ after removal is verified.
-Does not remove uv, Claude Code, Codex, Pi, OpenCode, the uv-managed Python runtime, or shared PATH entries.
+Does not remove uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes Agent, DeepSeek Harness, Grok Build, the uv-managed Python runtime, or shared PATH entries.
Options:
--dry-run Print commands without running them.
@@ -298,5 +298,5 @@ if [ "$dry_run" -eq 1 ]; then
printf '\nDry run complete. No changes were made.\n'
else
printf '\nFree Claude Code has been removed and verified.\n'
- printf 'uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes Agent, DeepSeek Harness, the uv-managed Python runtime, and shared PATH entries were left installed.\n'
+ printf 'uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes Agent, DeepSeek Harness, Grok Build, the uv-managed Python runtime, and shared PATH entries were left installed.\n'
fi
diff --git a/smoke/README.md b/smoke/README.md
index 38e2274b..1c78b803 100644
--- a/smoke/README.md
+++ b/smoke/README.md
@@ -56,7 +56,7 @@ Default targets do not send real bot messages or load voice backends:
| `api` | messages, count_tokens full payload, errors, `/stop`, optimizations | configured provider only for streaming messages |
| `auth` | canonical bearer auth, conflicting legacy headers, invalid/missing auth | none; test sets an isolated token |
| `cli` | server entrypoint, Claude CLI adaptive thinking, automatic WebSearch, Auto-mode classifier, session cleanup | Claude CLI binary and provider only for real CLI; connected OpenAI account for Auto mode; `FCC_SMOKE_RUN_WEB_TOOLS=1` for WebSearch |
-| `clients` | VS Code and JetBrains protocol payloads; Pi, OpenCode, Cline, Hermes, and DeepSeek Harness CLI prompts | configured provider; installed Pi/OpenCode/Cline binaries; Hermes and DSH use a local fake upstream |
+| `clients` | VS Code and JetBrains protocol payloads; Pi, OpenCode, Cline, Hermes, DeepSeek Harness, and Grok Build CLI prompts | configured provider; installed Pi/OpenCode/Cline binaries; Hermes, DSH, and Grok use a local fake upstream |
| `config` | env precedence, removed-env migration, proxy/timeouts | none |
| `extensibility` | provider runtime and platform factory construction | none |
| `messaging` | fake Discord/Telegram full flow, literal clear scopes, trees, persistence, voice cancel | none |
diff --git a/smoke/capabilities.py b/smoke/capabilities.py
index eb026785..d432019b 100644
--- a/smoke/capabilities.py
+++ b/smoke/capabilities.py
@@ -599,6 +599,20 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"test_dsh_cli_web_startup_e2e",
),
),
+ CapabilityContract(
+ "cli",
+ "grok_cli_integration",
+ "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",
+ (
+ "tests/cli/test_grok_launcher.py",
+ "tests/cli/test_model_catalog.py",
+ ),
+ ("test_grok_cli_headless_e2e",),
+ ),
CapabilityContract(
"extensibility",
"provider_platform_abcs",
diff --git a/smoke/features.py b/smoke/features.py
index cb989167..2a4468d9 100644
--- a/smoke/features.py
+++ b/smoke/features.py
@@ -167,6 +167,19 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
("DeepSeek Harness 0.1.0-rc.8",),
"skip only when DSH is absent; the local fake upstream must pass",
),
+ FeatureCoverage(
+ "grok_cli_integration",
+ "Grok Build discovers FCC models and sends Responses through the proxy",
+ (
+ "tests/cli/test_grok_launcher.py",
+ "tests/cli/test_model_catalog.py",
+ ),
+ ("test_probe_and_models_routes",),
+ ("test_grok_cli_headless_e2e",),
+ ("clients",),
+ ("stable Grok Build 1.0.5+",),
+ "skip only when Grok Build is absent; the local fake upstream must pass",
+ ),
FeatureCoverage(
"provider_matrix",
"Every configured provider prefix can satisfy conversation scenarios",
diff --git a/smoke/product/test_client_product_live.py b/smoke/product/test_client_product_live.py
index 092f32f9..16f2b24b 100644
--- a/smoke/product/test_client_product_live.py
+++ b/smoke/product/test_client_product_live.py
@@ -578,6 +578,91 @@ def test_dsh_cli_web_startup_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> N
assert provider_requests == []
[email protected]_target("clients")
+def test_grok_cli_headless_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> None:
+ if not shutil.which("grok"):
+ pytest.skip("missing_env: Grok Build not found")
+ uv_bin = shutil.which("uv")
+ if not uv_bin:
+ pytest.skip("missing_env: uv not found")
+
+ model_id = "fcc-smoke-grok"
+ full_model = f"lmstudio/{model_id}"
+ marker = "FCC_SMOKE_GROK"
+ auth_token = smoke_config.settings.proxy_auth_token
+ credential_env_keys = _provider_credential_env_keys()
+
+ with (
+ _successful_openai_provider(model_id=model_id, marker=marker) as (
+ provider_base_url,
+ provider_requests,
+ ),
+ SmokeServerDriver(
+ smoke_config,
+ name="product-grok-cli-headless",
+ env_overrides=_local_provider_overrides(full_model, provider_base_url),
+ env_unset=credential_env_keys,
+ ).run() as server,
+ ):
+ isolated_home = tmp_path / "grok-home"
+ isolated_home.mkdir()
+ env = os.environ.copy()
+ for key in credential_env_keys:
+ env.pop(key, None)
+ for key in tuple(env):
+ if key.startswith("FCC_GROK_") or key.startswith("GROK_"):
+ env.pop(key)
+ env.pop("XAI_API_KEY", None)
+ env.update(
+ {
+ "HOST": "127.0.0.1",
+ "PORT": str(server.port),
+ "FCC_OPEN_BROWSER": "0",
+ "ANTHROPIC_AUTH_TOKEN": auth_token,
+ "HOME": str(isolated_home),
+ "USERPROFILE": str(isolated_home),
+ }
+ )
+ result = subprocess.run(
+ [
+ uv_bin,
+ "run",
+ "--project",
+ str(smoke_config.root),
+ "--no-sync",
+ "fcc-grok",
+ "--model",
+ full_model,
+ "--single",
+ f"Reply with exactly {marker}",
+ ],
+ cwd=tmp_path,
+ env=env,
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=smoke_config.timeout_s + 30,
+ )
+ server_log = server.log_path.read_text(encoding="utf-8", errors="replace")
+
+ combined = f"{result.stdout}\n{result.stderr}"
+ assert result.returncode == 0, result.stderr or result.stdout
+ assert marker in result.stdout
+ assert auth_token not in combined
+ assert "GET /v1/models?view=responses" in server_log
+ responses_count = server_log.count("POST /v1/responses")
+ assert responses_count >= 1
+ assert "POST /v1/chat/completions" not in server_log
+ assert responses_count == len(provider_requests)
+ assert {request["path"] for request in provider_requests} == {
+ "/v1/chat/completions"
+ }
+ for request in provider_requests:
+ provider_body = request["body"]
+ assert isinstance(provider_body, dict)
+ assert provider_body["model"] == model_id
+
+
@pytest.mark.smoke_target("cli")
def test_claude_cli_adaptive_thinking_e2e(
smoke_config: SmokeConfig, tmp_path: Path
diff --git a/src/free_claude_code/api/model_catalog.py b/src/free_claude_code/api/model_catalog.py
index f7d08f05..dd42c263 100644
--- a/src/free_claude_code/api/model_catalog.py
+++ b/src/free_claude_code/api/model_catalog.py
@@ -1,8 +1,11 @@
-"""Model-list response construction for Claude-compatible clients."""
+"""Model-list response construction for FCC clients."""
+import math
+from dataclasses import dataclass
+from enum import StrEnum
from typing import Literal
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from free_claude_code.application.ports import RequestRuntimePort
from free_claude_code.config.model_refs import configured_chat_model_refs
@@ -13,6 +16,16 @@ from free_claude_code.core.gateway_model_ids import (
)
DISCOVERED_MODEL_CREATED_AT = "1970-01-01T00:00:00Z"
+_INFERENCE_IDLE_TIMEOUT_MARGIN_SECONDS = 60
+_REASONING_EFFORTS = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
+
+
+class ModelCatalogView(StrEnum):
+ """Client-specific projections of the application model inventory."""
+
+ CLAUDE = "claude"
+ MESSAGES = "messages"
+ RESPONSES = "responses"
class ModelResponse(BaseModel):
@@ -23,6 +36,22 @@ class ModelResponse(BaseModel):
display_name: str
id: str
type: Literal["model"] = "model"
+ provider_model_ref: str | None = None
+ api_backend: Literal["responses"] | None = Field(
+ default=None, serialization_alias="apiBackend"
+ )
+ max_retries: Literal[0] | None = Field(
+ default=None, serialization_alias="maxRetries"
+ )
+ supports_reasoning_effort: bool | None = Field(
+ default=None, serialization_alias="supportsReasoningEffort"
+ )
+ reasoning_efforts: tuple[str, ...] | None = Field(
+ default=None, serialization_alias="reasoningEfforts"
+ )
+ inference_idle_timeout_seconds: int | None = Field(
+ default=None, serialization_alias="inferenceIdleTimeoutSecs"
+ )
class ModelsListResponse(BaseModel):
@@ -77,10 +106,28 @@ SUPPORTED_CLAUDE_MODELS = [
]
+@dataclass(frozen=True, slots=True)
+class _InventoryModel:
+ provider_model_ref: str
+ supports_thinking: bool | None
+
+
def build_models_list_response(
+ settings: Settings,
+ runtime: RequestRuntimePort,
+ *,
+ view: ModelCatalogView = ModelCatalogView.CLAUDE,
+) -> ModelsListResponse:
+ """Return the application model inventory in the requested client view."""
+ if view is ModelCatalogView.CLAUDE:
+ return _build_claude_models_response(settings, runtime)
+ return _build_direct_models_response(settings, runtime, view=view)
+
+
+def _build_claude_models_response(
settings: Settings, runtime: RequestRuntimePort
) -> ModelsListResponse:
- """Return configured, cached, and compatibility model ids."""
+ """Preserve the established Claude-compatible catalog exactly."""
models: list[ModelResponse] = []
seen: set[str] = set()
@@ -114,6 +161,98 @@ def build_models_list_response(
)
+def _build_direct_models_response(
+ settings: Settings,
+ runtime: RequestRuntimePort,
+ *,
+ view: ModelCatalogView,
+) -> ModelsListResponse:
+ models: list[ModelResponse] = []
+ timeout_seconds = (
+ _responses_inference_idle_timeout_seconds(settings.provider_progress_timeout)
+ if view is ModelCatalogView.RESPONSES
+ else None
+ )
+
+ for inventory_model in _collect_inventory(settings, runtime):
+ provider_model_ref = inventory_model.provider_model_ref
+ allows_reasoning = inventory_model.supports_thinking is not False
+ model_id = (
+ provider_model_ref
+ if allows_reasoning
+ else no_thinking_gateway_model_id(provider_model_ref)
+ )
+ models.append(
+ ModelResponse(
+ id=model_id,
+ display_name=(
+ provider_model_ref
+ if allows_reasoning
+ else f"{provider_model_ref} (no thinking)"
+ ),
+ created_at=DISCOVERED_MODEL_CREATED_AT,
+ provider_model_ref=provider_model_ref,
+ api_backend=(
+ "responses" if view is ModelCatalogView.RESPONSES else None
+ ),
+ max_retries=0 if view is ModelCatalogView.RESPONSES else None,
+ supports_reasoning_effort=(
+ allows_reasoning if view is ModelCatalogView.RESPONSES else None
+ ),
+ reasoning_efforts=(
+ _REASONING_EFFORTS
+ if view is ModelCatalogView.RESPONSES and allows_reasoning
+ else None
+ ),
+ inference_idle_timeout_seconds=timeout_seconds,
+ )
+ )
+
+ return ModelsListResponse(
+ data=models,
+ first_id=models[0].id if models else None,
+ has_more=False,
+ last_id=models[-1].id if models else None,
+ )
+
+
+def _collect_inventory(
+ settings: Settings, runtime: RequestRuntimePort
+) -> tuple[_InventoryModel, ...]:
+ inventory: list[_InventoryModel] = []
+ seen: set[str] = set()
+
+ for ref in configured_chat_model_refs(settings):
+ if ref.model_ref in seen:
+ continue
+ seen.add(ref.model_ref)
+ inventory.append(
+ _InventoryModel(
+ provider_model_ref=ref.model_ref,
+ supports_thinking=runtime.cached_model_supports_thinking(
+ ref.provider_id, ref.model_id
+ ),
+ )
+ )
+
+ for model_info in runtime.cached_prefixed_model_infos():
+ if model_info.model_id in seen:
+ continue
+ seen.add(model_info.model_id)
+ inventory.append(
+ _InventoryModel(
+ provider_model_ref=model_info.model_id,
+ supports_thinking=model_info.supports_thinking,
+ )
+ )
+
+ return tuple(inventory)
+
+
+def _responses_inference_idle_timeout_seconds(provider_progress_timeout: float) -> int:
+ return math.ceil(provider_progress_timeout) + _INFERENCE_IDLE_TIMEOUT_MARGIN_SECONDS
+
+
def _discovered_model_response(model_id: str, *, display_name: str) -> ModelResponse:
return ModelResponse(
id=model_id,
diff --git a/src/free_claude_code/api/routes.py b/src/free_claude_code/api/routes.py
index d88fbaba..3b152c76 100644
--- a/src/free_claude_code/api/routes.py
+++ b/src/free_claude_code/api/routes.py
@@ -22,7 +22,11 @@ from .dependencies import (
resolve_provider,
)
from .handlers import MessagesHandler, ResponsesHandler, TokenCountHandler
-from .model_catalog import ModelsListResponse, build_models_list_response
+from .model_catalog import (
+ ModelCatalogView,
+ ModelsListResponse,
+ build_models_list_response,
+)
from .ports import ApiServices
from .request_errors import ordinary_application_error_response
from .request_ids import get_request_id
@@ -186,15 +190,20 @@ async def probe_health():
return _probe_response("GET, HEAD, OPTIONS")
[email protected]("/v1/models", response_model=ModelsListResponse)
+ "/v1/models",
+ response_model=ModelsListResponse,
+ response_model_exclude_none=True,
+)
async def list_models(
+ view: ModelCatalogView = ModelCatalogView.CLAUDE,
services: ApiServices = Depends(get_services),
settings: Settings = Depends(get_settings),
_auth=Depends(require_proxy_auth),
):
"""List the model ids this proxy advertises to compatible clients."""
trace_event(stage="ingress", event="free_claude_code.api.models.list", source="api")
- return build_models_list_response(settings, services.requests)
+ return build_models_list_response(settings, services.requests, view=view)
@router.post("/stop")
diff --git a/src/free_claude_code/cli/launchers/grok.py b/src/free_claude_code/cli/launchers/grok.py
new file mode 100644
index 00000000..78f22138
--- /dev/null
+++ b/src/free_claude_code/cli/launchers/grok.py
@@ -0,0 +1,489 @@
+"""Installed `fcc-grok` launcher for attached Grok Build sessions."""
+
+import json
+import os
+import re
+import subprocess
+import sys
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from enum import StrEnum
+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,
+ proxy_v1_url,
+ resolve_client_binary,
+ run_client_process,
+)
+from .model_catalog import (
+ ClientModel,
+ client_models_from_response,
+ fetch_proxy_models_response,
+)
+
+_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"(?im)^\s*(?:grok\s+)?v?(\d+)\.(\d+)\.(\d+)(?:\s+\([^\r\n]*\))?\s*$"
+)
+_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(
+ {
+ "GROK_CODE_XAI_API_KEY",
+ "GROK_DEFAULT_MODEL",
+ "GROK_IMAGE_DESCRIPTION_MODEL",
+ "GROK_MODELS_BASE_URL",
+ "GROK_MODELS_LIST_URL",
+ "GROK_PROMPT_SUGGESTIONS_MODEL",
+ "GROK_SESSION_SUMMARY_MODEL",
+ "GROK_WEB_SEARCH_MODEL",
+ "GROK_XAI_API_BASE_URL",
+ "XAI_API_KEY",
+ }
+)
+
+
+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
+
+ 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 stable 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 a stable release at least "
+ f"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 a stable Grok Build 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_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 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,
+ )
+ raise SystemExit(2)
+
+
+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,
+ )
diff --git a/src/free_claude_code/cli/launchers/model_catalog.py b/src/free_claude_code/cli/launchers/model_catalog.py
index 8a1182a4..21ad4781 100644
--- a/src/free_claude_code/cli/launchers/model_catalog.py
+++ b/src/free_claude_code/cli/launchers/model_catalog.py
@@ -6,11 +6,6 @@ from dataclasses import dataclass
from urllib.request import Request
from free_claude_code.cli.local_http import open_local_request
-from free_claude_code.config.provider_catalog import SUPPORTED_PROVIDER_IDS
-from free_claude_code.core.gateway_model_ids import (
- GATEWAY_MODEL_ID_PREFIX,
- NO_THINKING_GATEWAY_MODEL_ID_PREFIX,
-)
from free_claude_code.core.json_types import JsonObject, JsonValue
from .common import PROXY_PREFLIGHT_TIMEOUT_SECONDS
@@ -31,21 +26,10 @@ def client_models_from_response(
) -> tuple[ClientModel, ...]:
"""Project an FCC `/v1/models` response into direct client model records."""
- candidates = _catalog_candidates(models_response)
- normal_provider_refs = {
- candidate.provider_model_ref
- for candidate in candidates
- if candidate.allows_reasoning
- }
models: list[ClientModel] = []
seen_slugs: set[str] = set()
- for candidate in candidates:
- if (
- not candidate.allows_reasoning
- and candidate.provider_model_ref in normal_provider_refs
- ):
- continue
+ for candidate in _catalog_candidates(models_response):
if candidate.wire_slug in seen_slugs:
continue
seen_slugs.add(candidate.wire_slug)
@@ -57,7 +41,7 @@ def client_models_from_response(
def fetch_proxy_models_response(proxy_root_url: str, auth_token: str) -> JsonObject:
"""Fetch the authenticated FCC-local `/v1/models` response directly."""
- url = f"{proxy_root_url.rstrip('/')}/v1/models"
+ url = f"{proxy_root_url.rstrip('/')}/v1/models?view=responses"
request = Request(
url,
headers={"Authorization": f"Bearer {auth_token}"},
@@ -84,58 +68,35 @@ def _catalog_candidates(
for item in data:
if not isinstance(item, Mapping):
continue
- model_id = _string_value(item.get("id"))
+ model_id = _nonempty_string(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,
+ provider_model_ref = _provider_model_ref(item.get("provider_model_ref"))
+ if provider_model_ref is None:
+ continue
+ candidates.append(
+ ClientModel(
+ wire_slug=model_id,
+ provider_model_ref=provider_model_ref,
+ display_name=_nonempty_string(item.get("display_name")) or model_id,
+ allows_reasoning=model_id == provider_model_ref,
+ )
)
- if candidate is not None:
- candidates.append(candidate)
return candidates
-def _candidate_from_model_id(model_id: str, *, display_name: str) -> ClientModel | None:
- prefix, separator, remainder = model_id.partition("/")
- if not separator:
+def _nonempty_string(value: object) -> str | None:
+ if not isinstance(value, str):
return None
+ stripped = value.strip()
+ return stripped or None
- if prefix == GATEWAY_MODEL_ID_PREFIX:
- if not _is_provider_model_ref(remainder):
- return None
- return ClientModel(
- wire_slug=remainder,
- provider_model_ref=remainder,
- display_name=display_name,
- allows_reasoning=True,
- )
-
- if prefix == NO_THINKING_GATEWAY_MODEL_ID_PREFIX:
- if not _is_provider_model_ref(remainder):
- return None
- return ClientModel(
- wire_slug=model_id,
- provider_model_ref=remainder,
- display_name=display_name,
- allows_reasoning=False,
- )
-
- if prefix in SUPPORTED_PROVIDER_IDS and remainder:
- return ClientModel(
- wire_slug=model_id,
- provider_model_ref=model_id,
- display_name=display_name,
- allows_reasoning=True,
- )
- return None
-
-
-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: object) -> str | None:
- return value if isinstance(value, str) else None
+def _provider_model_ref(value: object) -> str | None:
+ ref = _nonempty_string(value)
+ if ref is None:
+ return None
+ provider_id, separator, model_id = ref.partition("/")
+ if not separator or not provider_id or not model_id:
+ return None
+ return ref
diff --git a/src/free_claude_code/cli/launchers/pi_extension.ts b/src/free_claude_code/cli/launchers/pi_extension.ts
index 4fe3c4e7..e443a456 100644
--- a/src/free_claude_code/cli/launchers/pi_extension.ts
+++ b/src/free_claude_code/cli/launchers/pi_extension.ts
@@ -5,8 +5,6 @@ const BASE_URL_ENV = "FCC_PI_BASE_URL";
const CATALOG_TIMEOUT_MS = 3000;
const DEFAULT_CONTEXT_WINDOW = 128000;
const DEFAULT_MAX_TOKENS = 16384;
-const NORMAL_MODEL_PREFIX = "anthropic/";
-const NO_THINKING_MODEL_PREFIX = "claude-3-freecc-no-thinking/";
function requireEnvironment(name: string): string {
const value = process.env[name]?.trim();
@@ -35,32 +33,11 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
-function catalogModelIds(payload: unknown): string[] {
- if (!isRecord(payload) || payload.object !== "list" || !Array.isArray(payload.data)) {
- throw new Error("FCC model catalog returned an invalid response shape.");
- }
-
- const ids: string[] = [];
- for (const entry of payload.data) {
- if (!isRecord(entry) || typeof entry.id !== "string") continue;
- const id = entry.id.trim();
- if (id) ids.push(id);
- }
- return ids;
-}
-
-function providerModelRef(id: string, prefix: string): string | undefined {
- if (!id.startsWith(prefix)) return undefined;
- const parts = id.slice(prefix.length).split("/");
- if (parts.length < 2 || parts.some((part) => !part)) return undefined;
- return parts.join("/");
-}
-
-function modelDefinition(providerModel: string, reasoning: boolean): ProviderModelConfig {
+function modelDefinition(id: string, providerModel: string): ProviderModelConfig {
return {
- id: providerModel,
+ id,
name: providerModel,
- reasoning,
+ reasoning: id === providerModel,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: DEFAULT_CONTEXT_WINDOW,
@@ -69,29 +46,18 @@ function modelDefinition(providerModel: string, reasoning: boolean): ProviderMod
}
export function projectFccModels(payload: unknown): ProviderModelConfig[] {
- const ids = catalogModelIds(payload);
- const normalModels = new Set<string>();
- for (const id of ids) {
- const providerModel = providerModelRef(id, NORMAL_MODEL_PREFIX);
- if (providerModel) normalModels.add(providerModel);
+ if (!isRecord(payload) || payload.object !== "list" || !Array.isArray(payload.data)) {
+ throw new Error("FCC model catalog returned an invalid response shape.");
}
-
const models: ProviderModelConfig[] = [];
const seen = new Set<string>();
- for (const id of ids) {
- const normalModel = providerModelRef(id, NORMAL_MODEL_PREFIX);
- if (normalModel) {
- if (!seen.has(normalModel)) {
- seen.add(normalModel);
- models.push(modelDefinition(normalModel, true));
- }
- continue;
- }
-
- const noThinkingModel = providerModelRef(id, NO_THINKING_MODEL_PREFIX);
- if (!noThinkingModel || normalModels.has(noThinkingModel) || seen.has(noThinkingModel)) continue;
- seen.add(noThinkingModel);
- models.push(modelDefinition(noThinkingModel, false));
+ for (const entry of payload.data) {
+ if (!isRecord(entry) || typeof entry.id !== "string" || typeof entry.provider_model_ref !== "string") continue;
+ const id = entry.id.trim();
+ const providerModel = entry.provider_model_ref.trim();
+ if (!id || !providerModel.includes("/") || seen.has(id)) continue;
+ seen.add(id);
+ models.push(modelDefinition(id, providerModel));
}
if (models.length === 0) {
@@ -111,7 +77,7 @@ async function fetchFccModels(baseUrl: string, apiKey: string): Promise<Provider
try {
let response: Response;
try {
- response = await fetch(`${baseUrl}/v1/models`, {
+ response = await fetch(`${baseUrl}/v1/models?view=messages`, {
headers: { Authorization: `Bearer ${apiKey}` },
signal: controller.signal,
});
diff --git a/src/free_claude_code/config/settings.py b/src/free_claude_code/config/settings.py
index 41a4382c..7f2f814c 100644
--- a/src/free_claude_code/config/settings.py
+++ b/src/free_claude_code/config/settings.py
@@ -521,6 +521,9 @@ class Settings(BaseModel):
provider_progress_timeout: float = Field(
default=600.0,
gt=0,
+ # Responses metadata adds 60 seconds before encoding this as a u64.
+ # The next representable float below 2**64 leaves more than that margin.
+ lt=float(1 << 64),
allow_inf_nan=False,
validation_alias="PROVIDER_PROGRESS_TIMEOUT",
)
diff --git a/src/free_claude_code/core/openai_responses/streaming/assembler.py b/src/free_claude_code/core/openai_responses/streaming/assembler.py
index 1d26ac4c..557c774a 100644
--- a/src/free_claude_code/core/openai_responses/streaming/assembler.py
+++ b/src/free_claude_code/core/openai_responses/streaming/assembler.py
@@ -19,13 +19,13 @@ from ..ids import (
)
from ..models import OpenAIResponsesRequest
from ..tools import responses_tool_identity_from_anthropic_name
-from . import event_builders as events
from .blocks import ReasoningBlockState, TextBlockState, ToolBlockState
from .completion import ResponseBlockCompleter, reasoning_output_item, tool_item
from .error_mapping import (
openai_error_from_anthropic_error,
replay_unsafe_function_call_error,
)
+from .event_builders import ResponseEventBuilder
from .ledger import ResponsesOutputLedger
@@ -37,8 +37,10 @@ class ResponsesStreamAssembler:
self._response_id = new_response_id()
self._created_at = int(time.time())
self._ledger = ResponsesOutputLedger()
+ self._events = ResponseEventBuilder()
self._completer = ResponseBlockCompleter(
self._ledger,
+ events=self._events,
on_invalid_function_call=self._fail_invalid_function_call,
)
self._started = False
@@ -116,7 +118,7 @@ class ResponsesStreamAssembler:
chunks.extend(self._finish_incomplete_response())
return chunks
self.final_response = self.response_payload(status="completed")
- chunks.append(events.response_completed(self.final_response))
+ chunks.append(self._events.response_completed(self.final_response))
self.terminal = True
return chunks
@@ -140,7 +142,7 @@ class ResponsesStreamAssembler:
self._provisional_error = None
self.final_response = self.response_payload(status="failed", error=error)
self.terminal = True
- return [events.response_failed(self.final_response)]
+ return [self._events.response_failed(self.final_response)]
def _finish_incomplete_response(self) -> list[str]:
self.final_response = self.response_payload(
@@ -148,13 +150,15 @@ class ResponsesStreamAssembler:
incomplete_details={"reason": "max_output_tokens"},
)
self.terminal = True
- return [events.response_incomplete(self.final_response)]
+ return [self._events.response_incomplete(self.final_response)]
def _ensure_started(self) -> list[str]:
if self._started:
return []
self._started = True
- return [events.response_created(self.response_payload(status="in_progress"))]
+ return [
+ self._events.response_created(self.response_payload(status="in_progress"))
+ ]
def _handle_content_block_start(self, data: Mapping[str, Any]) -> list[str]:
block = data.get("content_block")
@@ -267,8 +271,8 @@ class ResponsesStreamAssembler:
}
chunks.extend(
[
- events.output_item_added(output_index, item),
- events.content_part_added(state.item_id, output_index),
+ self._events.output_item_added(output_index, item),
+ self._events.content_part_added(state.item_id, output_index),
]
)
return chunks, state
@@ -288,7 +292,7 @@ class ResponsesStreamAssembler:
)
self._ledger.set_active_block(state)
chunks.append(
- events.output_item_added(
+ self._events.output_item_added(
output_index,
reasoning_output_item(state, status="in_progress"),
)
@@ -319,7 +323,7 @@ class ResponsesStreamAssembler:
state.argument_parts.append(json.dumps(initial_input))
self._ledger.set_active_block(state)
chunks.append(
- events.output_item_added(
+ self._events.output_item_added(
state.output_index,
tool_item(state, status="in_progress"),
)
@@ -330,13 +334,15 @@ class ResponsesStreamAssembler:
if not text:
return []
state.text_parts.append(text)
- return [events.output_text_delta(state.item_id, state.output_index, text)]
+ return [self._events.output_text_delta(state.item_id, state.output_index, text)]
def _emit_reasoning_delta(self, state: ReasoningBlockState, text: str) -> list[str]:
if not text:
return []
state.text_parts.append(text)
- return [events.reasoning_text_delta(state.item_id, state.output_index, text)]
+ return [
+ self._events.reasoning_text_delta(state.item_id, state.output_index, text)
+ ]
def _complete_existing_block(self, index: int) -> list[str]:
existing = self._ledger.pop_active_block(index)
diff --git a/src/free_claude_code/core/openai_responses/streaming/completion.py b/src/free_claude_code/core/openai_responses/streaming/completion.py
index f118fa9e..adbc7d5d 100644
--- a/src/free_claude_code/core/openai_responses/streaming/completion.py
+++ b/src/free_claude_code/core/openai_responses/streaming/completion.py
@@ -8,8 +8,8 @@ from ..tools import (
custom_tool_input_text_from_arguments,
normalized_function_call_arguments,
)
-from . import event_builders as events
from .blocks import BlockState, ReasoningBlockState, TextBlockState, ToolBlockState
+from .event_builders import ResponseEventBuilder
from .ledger import ResponsesOutputLedger
InvalidFunctionCallHandler = Callable[
@@ -24,9 +24,11 @@ class ResponseBlockCompleter:
self,
ledger: ResponsesOutputLedger,
*,
+ events: ResponseEventBuilder,
on_invalid_function_call: InvalidFunctionCallHandler,
) -> None:
self._ledger = ledger
+ self._events = events
self._on_invalid_function_call = on_invalid_function_call
def complete_block(self, state: BlockState) -> list[str]:
@@ -41,9 +43,9 @@ class ResponseBlockCompleter:
item = message_item(state.item_id, text, "completed")
self._ledger.commit_output(state.output_index, item)
return [
- events.output_text_done(state.item_id, state.output_index, text),
- events.content_part_done(state.item_id, state.output_index, text),
- events.output_item_done(state.output_index, item),
+ self._events.output_text_done(state.item_id, state.output_index, text),
+ self._events.content_part_done(state.item_id, state.output_index, text),
+ self._events.output_item_done(state.output_index, item),
]
def _complete_reasoning_block(self, state: ReasoningBlockState) -> list[str]:
@@ -54,9 +56,11 @@ class ResponseBlockCompleter:
if text:
self._ledger.add_reasoning_text(text)
chunks.append(
- events.reasoning_text_done(state.item_id, state.output_index, text)
+ self._events.reasoning_text_done(
+ state.item_id, state.output_index, text
+ )
)
- chunks.append(events.output_item_done(state.output_index, item))
+ chunks.append(self._events.output_item_done(state.output_index, item))
return chunks
def _complete_tool_block(self, state: ToolBlockState) -> list[str]:
@@ -72,16 +76,16 @@ class ResponseBlockCompleter:
chunks: list[str] = []
if arguments:
chunks.append(
- events.function_call_arguments_delta(
+ self._events.function_call_arguments_delta(
state.item_id, state.output_index, arguments
)
)
chunks.extend(
[
- events.function_call_arguments_done(
+ self._events.function_call_arguments_done(
state.item_id, state.output_index, arguments
),
- events.output_item_done(state.output_index, item),
+ self._events.output_item_done(state.output_index, item),
]
)
return chunks
@@ -95,16 +99,16 @@ class ResponseBlockCompleter:
chunks: list[str] = []
if input_text:
chunks.append(
- events.custom_tool_call_input_delta(
+ self._events.custom_tool_call_input_delta(
state.item_id, state.output_index, input_text
)
)
chunks.extend(
[
- events.custom_tool_call_input_done(
+ self._events.custom_tool_call_input_done(
state.item_id, state.output_index, input_text
),
- events.output_item_done(state.output_index, item),
+ self._events.output_item_done(state.output_index, item),
]
)
return chunks
diff --git a/src/free_claude_code/core/openai_responses/streaming/event_builders.py b/src/free_claude_code/core/openai_responses/streaming/event_builders.py
index 5eb8b40a..bb324874 100644
--- a/src/free_claude_code/core/openai_responses/streaming/event_builders.py
+++ b/src/free_claude_code/core/openai_responses/streaming/event_builders.py
@@ -5,185 +5,181 @@ from typing import Any
from ..events import format_response_sse_event
-def response_created(response: dict[str, Any]) -> str:
- return format_response_sse_event(
- "response.created",
- {"type": "response.created", "response": response},
- )
-
-
-def response_completed(response: dict[str, Any]) -> str:
- return format_response_sse_event(
- "response.completed",
- {"type": "response.completed", "response": response},
- )
-
-
-def response_incomplete(response: dict[str, Any]) -> str:
- return format_response_sse_event(
- "response.incomplete",
- {"type": "response.incomplete", "response": response},
- )
-
-
-def response_failed(response: dict[str, Any]) -> str:
- return format_response_sse_event(
- "response.failed",
- {"type": "response.failed", "response": response},
- )
-
-
-def output_item_added(output_index: int, item: dict[str, Any]) -> str:
- return format_response_sse_event(
- "response.output_item.added",
- {
- "type": "response.output_item.added",
- "output_index": output_index,
- "item": item,
- },
- )
-
-
-def output_item_done(output_index: int, item: dict[str, Any]) -> str:
- return format_response_sse_event(
- "response.output_item.done",
- {
- "type": "response.output_item.done",
- "output_index": output_index,
- "item": item,
- },
- )
-
-
-def content_part_added(item_id: str, output_index: int) -> str:
- return format_response_sse_event(
- "response.content_part.added",
- {
- "type": "response.content_part.added",
- "item_id": item_id,
- "output_index": output_index,
- "content_index": 0,
- "part": {"type": "output_text", "text": "", "annotations": []},
- },
- )
-
-
-def output_text_delta(item_id: str, output_index: int, text: str) -> str:
- return format_response_sse_event(
- "response.output_text.delta",
- {
- "type": "response.output_text.delta",
- "item_id": item_id,
- "output_index": output_index,
- "content_index": 0,
- "delta": text,
- },
- )
-
-
-def output_text_done(item_id: str, output_index: int, text: str) -> str:
- return format_response_sse_event(
- "response.output_text.done",
- {
- "type": "response.output_text.done",
- "item_id": item_id,
- "output_index": output_index,
- "content_index": 0,
- "text": text,
- },
- )
-
-
-def content_part_done(item_id: str, output_index: int, text: str) -> str:
- return format_response_sse_event(
- "response.content_part.done",
- {
- "type": "response.content_part.done",
- "item_id": item_id,
- "output_index": output_index,
- "content_index": 0,
- "part": {"type": "output_text", "text": text, "annotations": []},
- },
- )
-
-
-def reasoning_text_delta(item_id: str, output_index: int, text: str) -> str:
- return format_response_sse_event(
- "response.reasoning_text.delta",
- {
- "type": "response.reasoning_text.delta",
- "item_id": item_id,
- "output_index": output_index,
- "content_index": 0,
- "delta": text,
- },
- )
-
-
-def reasoning_text_done(item_id: str, output_index: int, text: str) -> str:
- return format_response_sse_event(
- "response.reasoning_text.done",
- {
- "type": "response.reasoning_text.done",
- "item_id": item_id,
- "output_index": output_index,
- "content_index": 0,
- "text": text,
- },
- )
-
-
-def function_call_arguments_delta(
- item_id: str, output_index: int, arguments: str
-) -> str:
- return format_response_sse_event(
- "response.function_call_arguments.delta",
- {
- "type": "response.function_call_arguments.delta",
- "item_id": item_id,
- "output_index": output_index,
- "delta": arguments,
- },
- )
-
-
-def function_call_arguments_done(
- item_id: str, output_index: int, arguments: str
-) -> str:
- return format_response_sse_event(
- "response.function_call_arguments.done",
- {
- "type": "response.function_call_arguments.done",
- "item_id": item_id,
- "output_index": output_index,
- "arguments": arguments,
- },
- )
-
-
-def custom_tool_call_input_delta(
- item_id: str, output_index: int, input_text: str
-) -> str:
- return format_response_sse_event(
- "response.custom_tool_call_input.delta",
- {
- "type": "response.custom_tool_call_input.delta",
- "item_id": item_id,
- "output_index": output_index,
- "delta": input_text,
- },
- )
-
-
-def custom_tool_call_input_done(
- item_id: str, output_index: int, input_text: str
-) -> str:
- return format_response_sse_event(
- "response.custom_tool_call_input.done",
- {
- "type": "response.custom_tool_call_input.done",
- "item_id": item_id,
- "output_index": output_index,
- "input": input_text,
- },
- )
+class ResponseEventBuilder:
+ """Build one ordered Responses event stream."""
+
+ def __init__(self) -> None:
+ self._next_sequence_number = 0
+
+ def response_created(self, response: dict[str, Any]) -> str:
+ return self._format(
+ "response.created",
+ {"type": "response.created", "response": response},
+ )
+
+ def response_completed(self, response: dict[str, Any]) -> str:
+ return self._format(
+ "response.completed",
+ {"type": "response.completed", "response": response},
+ )
+
+ def response_incomplete(self, response: dict[str, Any]) -> str:
+ return self._format(
+ "response.incomplete",
+ {"type": "response.incomplete", "response": response},
+ )
+
+ def response_failed(self, response: dict[str, Any]) -> str:
+ return self._format(
+ "response.failed",
+ {"type": "response.failed", "response": response},
+ )
+
+ def output_item_added(self, output_index: int, item: dict[str, Any]) -> str:
+ return self._format(
+ "response.output_item.added",
+ {
+ "type": "response.output_item.added",
+ "output_index": output_index,
+ "item": item,
+ },
+ )
+
+ def output_item_done(self, output_index: int, item: dict[str, Any]) -> str:
+ return self._format(
+ "response.output_item.done",
+ {
+ "type": "response.output_item.done",
+ "output_index": output_index,
+ "item": item,
+ },
+ )
+
+ def content_part_added(self, item_id: str, output_index: int) -> str:
+ return self._format(
+ "response.content_part.added",
+ {
+ "type": "response.content_part.added",
+ "item_id": item_id,
+ "output_index": output_index,
+ "content_index": 0,
+ "part": {"type": "output_text", "text": "", "annotations": []},
+ },
+ )
+
+ def output_text_delta(self, item_id: str, output_index: int, text: str) -> str:
+ return self._format(
+ "response.output_text.delta",
+ {
+ "type": "response.output_text.delta",
+ "item_id": item_id,
+ "output_index": output_index,
+ "content_index": 0,
+ "delta": text,
+ },
+ )
+
+ def output_text_done(self, item_id: str, output_index: int, text: str) -> str:
+ return self._format(
+ "response.output_text.done",
+ {
+ "type": "response.output_text.done",
+ "item_id": item_id,
+ "output_index": output_index,
+ "content_index": 0,
+ "text": text,
+ },
+ )
+
+ def content_part_done(self, item_id: str, output_index: int, text: str) -> str:
+ return self._format(
+ "response.content_part.done",
+ {
+ "type": "response.content_part.done",
+ "item_id": item_id,
+ "output_index": output_index,
+ "content_index": 0,
+ "part": {"type": "output_text", "text": text, "annotations": []},
+ },
+ )
+
+ def reasoning_text_delta(self, item_id: str, output_index: int, text: str) -> str:
+ return self._format(
+ "response.reasoning_text.delta",
+ {
+ "type": "response.reasoning_text.delta",
+ "item_id": item_id,
+ "output_index": output_index,
+ "content_index": 0,
+ "delta": text,
+ },
+ )
+
+ def reasoning_text_done(self, item_id: str, output_index: int, text: str) -> str:
+ return self._format(
+ "response.reasoning_text.done",
+ {
+ "type": "response.reasoning_text.done",
+ "item_id": item_id,
+ "output_index": output_index,
+ "content_index": 0,
+ "text": text,
+ },
+ )
+
+ def function_call_arguments_delta(
+ self, item_id: str, output_index: int, arguments: str
+ ) -> str:
+ return self._format(
+ "response.function_call_arguments.delta",
+ {
+ "type": "response.function_call_arguments.delta",
+ "item_id": item_id,
+ "output_index": output_index,
+ "delta": arguments,
+ },
+ )
+
+ def function_call_arguments_done(
+ self, item_id: str, output_index: int, arguments: str
+ ) -> str:
+ return self._format(
+ "response.function_call_arguments.done",
+ {
+ "type": "response.function_call_arguments.done",
+ "item_id": item_id,
+ "output_index": output_index,
+ "arguments": arguments,
+ },
+ )
+
+ def custom_tool_call_input_delta(
+ self, item_id: str, output_index: int, input_text: str
+ ) -> str:
+ return self._format(
+ "response.custom_tool_call_input.delta",
+ {
+ "type": "response.custom_tool_call_input.delta",
+ "item_id": item_id,
+ "output_index": output_index,
+ "delta": input_text,
+ },
+ )
+
+ def custom_tool_call_input_done(
+ self, item_id: str, output_index: int, input_text: str
+ ) -> str:
+ return self._format(
+ "response.custom_tool_call_input.done",
+ {
+ "type": "response.custom_tool_call_input.done",
+ "item_id": item_id,
+ "output_index": output_index,
+ "input": input_text,
+ },
+ )
+
+ def _format(self, event_type: str, data: dict[str, Any]) -> str:
+ data["sequence_number"] = self._next_sequence_number
+ self._next_sequence_number += 1
+ return format_response_sse_event(event_type, data)
diff --git a/src/free_claude_code/core/openai_responses/streaming/ledger.py b/src/free_claude_code/core/openai_responses/streaming/ledger.py
index cab4a8d4..0eb82d4f 100644
--- a/src/free_claude_code/core/openai_responses/streaming/ledger.py
+++ b/src/free_claude_code/core/openai_responses/streaming/ledger.py
@@ -75,14 +75,17 @@ class ResponsesOutputLedger:
output_tokens = self._output_tokens or 0
usage: dict[str, Any] = {
"input_tokens": input_tokens,
+ "input_tokens_details": {
+ "cached_tokens": self._input_token_counts.get(
+ "cache_read_input_tokens", 0
+ )
+ },
"output_tokens": output_tokens,
+ "output_tokens_details": {
+ "reasoning_tokens": min(self._reasoning_tokens_estimate, output_tokens)
+ },
"total_tokens": input_tokens + output_tokens,
}
- capped_reasoning_tokens = min(self._reasoning_tokens_estimate, output_tokens)
- if capped_reasoning_tokens:
- usage["output_tokens_details"] = {
- "reasoning_tokens": capped_reasoning_tokens
- }
return usage
def safe_text_index(self, index: int | None) -> int:
diff --git a/src/free_claude_code/runtime/codex_catalog.py b/src/free_claude_code/runtime/codex_catalog.py
index 92b498b0..870a4913 100644
--- a/src/free_claude_code/runtime/codex_catalog.py
+++ b/src/free_claude_code/runtime/codex_catalog.py
@@ -2,7 +2,10 @@
from pathlib import Path
-from free_claude_code.api.model_catalog import build_models_list_response
+from free_claude_code.api.model_catalog import (
+ ModelCatalogView,
+ build_models_list_response,
+)
from free_claude_code.application.ports import RequestRuntimePort
from free_claude_code.cli.launchers.codex_model_catalog import (
build_codex_model_catalog,
@@ -38,8 +41,11 @@ class CodexModelCatalogPublisher:
models_response = build_models_list_response(
runtime.current_settings(),
runtime,
+ view=ModelCatalogView.RESPONSES,
+ )
+ catalog = build_codex_model_catalog(
+ models_response.model_dump(by_alias=True, exclude_none=True)
)
- catalog = build_codex_model_catalog(models_response.model_dump())
models = catalog.get("models")
if not isinstance(models, list) or not models:
raise ValueError("Codex model catalog contains no routable models.")
diff --git a/tests/api/test_model_listing.py b/tests/api/test_model_listing.py
index c250d912..e7a3a146 100644
--- a/tests/api/test_model_listing.py
+++ b/tests/api/test_model_listing.py
@@ -1,3 +1,5 @@
+import math
+
from fastapi.testclient import TestClient
from free_claude_code.application.model_metadata import ProviderModelInfo
@@ -74,6 +76,10 @@ def test_models_list_includes_configured_refs_cached_provider_models_and_aliases
assert data["first_id"] == ids[0]
assert data["last_id"] == ids[-1]
assert data["has_more"] is False
+ assert all(
+ "provider_model_ref" not in item and "apiBackend" not in item
+ for item in data["data"]
+ )
def test_models_list_uses_thinking_metadata_for_cached_models():
@@ -168,3 +174,86 @@ def test_models_list_works_with_empty_discovery_catalog():
"claude-3-freecc-no-thinking/open_router/anthropic/claude-opus",
]
assert "claude-sonnet-4-20250514" in ids
+
+
+def test_direct_model_views_exclude_claude_aliases_and_duplicate_variants():
+ app = create_test_app(_settings(model_opus=None, model_haiku=None))
+ manager = provider_manager_for_app(app)
+ manager.cache_model_infos(
+ "open_router",
+ {
+ ProviderModelInfo("reasoning-model", supports_thinking=True),
+ ProviderModelInfo("plain-model", supports_thinking=False),
+ },
+ )
+
+ messages = TestClient(app).get("/v1/models?view=messages").json()
+ responses = TestClient(app).get("/v1/models?view=responses").json()
+
+ assert [row["id"] for row in messages["data"]] == [
+ "deepseek/deepseek-chat",
+ "claude-3-freecc-no-thinking/open_router/plain-model",
+ "open_router/reasoning-model",
+ ]
+ assert "claude-sonnet-4-20250514" not in {row["id"] for row in messages["data"]}
+ assert all("apiBackend" not in row for row in messages["data"])
+ assert responses["data"][0] == {
+ "object": "model",
+ "created": 0,
+ "owned_by": "free-claude-code",
+ "created_at": "1970-01-01T00:00:00Z",
+ "display_name": "deepseek/deepseek-chat",
+ "id": "deepseek/deepseek-chat",
+ "type": "model",
+ "provider_model_ref": "deepseek/deepseek-chat",
+ "apiBackend": "responses",
+ "maxRetries": 0,
+ "supportsReasoningEffort": True,
+ "reasoningEfforts": [
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ ],
+ "inferenceIdleTimeoutSecs": 660,
+ }
+ plain = responses["data"][1]
+ assert plain["supportsReasoningEffort"] is False
+ assert "reasoningEfforts" not in plain
+
+
+def test_responses_model_view_rounds_timeout_up_before_margin():
+ app = create_test_app(
+ _settings().model_copy(update={"provider_progress_timeout": 1.1})
+ )
+
+ response = TestClient(app).get("/v1/models?view=responses")
+
+ assert response.status_code == 200
+ assert {row["inferenceIdleTimeoutSecs"] for row in response.json()["data"]} == {62}
+
+
+def test_responses_model_view_timeout_fits_unsigned_range():
+ largest_accepted_timeout = math.nextafter(float(1 << 64), 0.0)
+ app = create_test_app(
+ _settings().model_copy(
+ update={"provider_progress_timeout": largest_accepted_timeout}
+ )
+ )
+
+ response = TestClient(app).get("/v1/models?view=responses")
+
+ assert response.status_code == 200
+ assert all(
+ row["inferenceIdleTimeoutSecs"] <= (1 << 64) - 1
+ for row in response.json()["data"]
+ )
+
+
+def test_unknown_model_view_is_rejected():
+ response = TestClient(create_test_app(_settings())).get("/v1/models?view=other")
+
+ assert response.status_code == 422
diff --git a/tests/cli/test_cline_launcher.py b/tests/cli/test_cline_launcher.py
index 7272b472..50664ea1 100644
--- a/tests/cli/test_cline_launcher.py
+++ b/tests/cli/test_cline_launcher.py
@@ -34,11 +34,13 @@ def _models_payload() -> JsonObject:
return {
"data": [
{
- "id": "anthropic/nvidia_nim/vendor/model",
+ "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",
},
]
diff --git a/tests/cli/test_codex_model_catalog.py b/tests/cli/test_codex_model_catalog.py
index 30854aa7..723185b4 100644
--- a/tests/cli/test_codex_model_catalog.py
+++ b/tests/cli/test_codex_model_catalog.py
@@ -20,7 +20,10 @@ def _models_payload(*model_ids: str) -> dict[str, Any]:
"data": [
{
"id": model_id,
- "display_name": model_id.replace("anthropic/", ""),
+ "provider_model_ref": (
+ model_id.removeprefix("claude-3-freecc-no-thinking/")
+ ),
+ "display_name": model_id,
}
for model_id in model_ids
]
@@ -46,13 +49,11 @@ def _slugs(catalog: Mapping[str, Any]) -> list[str]:
return slugs
-def test_codex_catalog_converts_configured_and_cached_models_to_direct_slugs() -> None:
+def test_codex_catalog_uses_direct_configured_and_cached_model_slugs() -> None:
catalog = build_codex_model_catalog(
_models_payload(
- "anthropic/nvidia_nim/nvidia/nemotron-3-super",
- "claude-3-freecc-no-thinking/nvidia_nim/nvidia/nemotron-3-super",
- "anthropic/open_router/meta-llama/llama-3.3-70b",
- "claude-3-freecc-no-thinking/open_router/meta-llama/llama-3.3-70b",
+ "nvidia_nim/nvidia/nemotron-3-super",
+ "open_router/meta-llama/llama-3.3-70b",
)
)
@@ -76,23 +77,28 @@ def test_codex_catalog_converts_configured_and_cached_models_to_direct_slugs() -
} <= set(model)
-def test_codex_catalog_excludes_claude_compatibility_model_ids() -> None:
+def test_codex_catalog_ignores_rows_without_direct_provider_identity() -> None:
catalog = build_codex_model_catalog(
- _models_payload(
- "claude-opus-4-20250514",
- "claude-3-haiku-20240307",
- "anthropic/nvidia_nim/provider-model",
- )
+ {
+ "data": [
+ {"id": "claude-opus-4-20250514"},
+ {
+ "id": "nvidia_nim/provider-model",
+ "provider_model_ref": "nvidia_nim/provider-model",
+ "display_name": "NIM",
+ },
+ ]
+ }
)
assert _slugs(catalog) == ["nvidia_nim/provider-model"]
-def test_codex_catalog_skips_no_thinking_duplicate_when_normal_slug_exists() -> None:
+def test_codex_catalog_deduplicates_direct_wire_ids() -> None:
catalog = build_codex_model_catalog(
_models_payload(
- "claude-3-freecc-no-thinking/nvidia_nim/provider-model",
- "anthropic/nvidia_nim/provider-model",
+ "nvidia_nim/provider-model",
+ "nvidia_nim/provider-model",
)
)
@@ -111,32 +117,34 @@ def test_codex_catalog_ordering_and_priorities_are_deterministic() -> None:
catalog = build_codex_model_catalog(
_models_payload(
"anthropic/gemini/models/gemini-test",
- "anthropic/nvidia_nim/nvidia/test",
+ "nvidia_nim/nvidia/test",
"anthropic/gemini/models/gemini-test",
- "anthropic/open_router/provider/test",
+ "open_router/provider/test",
)
)
models = _catalog_models(catalog)
assert _slugs(catalog) == [
- "gemini/models/gemini-test",
+ "anthropic/gemini/models/gemini-test",
"nvidia_nim/nvidia/test",
"open_router/provider/test",
]
assert [model["priority"] for model in models] == [0, 1, 2]
-def test_codex_catalog_accepts_future_direct_provider_slugs() -> None:
+def test_codex_catalog_accepts_direct_provider_slugs_without_a_provider_registry() -> (
+ None
+):
catalog = build_codex_model_catalog(
_models_payload(
"nvidia_nim/provider-model",
- "anthropic/open_router/provider-model",
+ "future_provider/provider-model",
)
)
assert _slugs(catalog) == [
"nvidia_nim/provider-model",
- "open_router/provider-model",
+ "future_provider/provider-model",
]
@@ -150,7 +158,7 @@ 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("anthropic/nvidia_nim/test-model")),
+ build_codex_model_catalog(_models_payload("nvidia_nim/test-model")),
)
codex_home = tmp_path / "codex-home"
codex_home.mkdir()
@@ -208,8 +216,8 @@ 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("anthropic/nvidia_nim/first"))
- second = build_codex_model_catalog(_models_payload("anthropic/nvidia_nim/second"))
+ first = build_codex_model_catalog(_models_payload("nvidia_nim/first"))
+ second = build_codex_model_catalog(_models_payload("nvidia_nim/second"))
assert write_codex_model_catalog(catalog_path, first) is True
assert write_codex_model_catalog(catalog_path, first) is False
@@ -235,9 +243,7 @@ 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("anthropic/nvidia_nim/replacement")
- ),
+ build_codex_model_catalog(_models_payload("nvidia_nim/replacement")),
)
assert catalog_path.read_text(encoding="utf-8") == "previous\n"
diff --git a/tests/cli/test_dsh_launcher.py b/tests/cli/test_dsh_launcher.py
index 9e6140ef..8bd28f42 100644
--- a/tests/cli/test_dsh_launcher.py
+++ b/tests/cli/test_dsh_launcher.py
@@ -30,11 +30,13 @@ def _models_payload() -> JsonObject:
return {
"data": [
{
- "id": "anthropic/nvidia_nim/vendor/model",
+ "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",
},
]
diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.py
index d395e503..ecc8d1cd 100644
--- a/tests/cli/test_entrypoints.py
+++ b/tests/cli/test_entrypoints.py
@@ -68,6 +68,7 @@ def test_cli_scripts_are_registered() -> None:
"fcc-cline": "free_claude_code.cli.launchers.cline:launch",
"fcc-hermes": "free_claude_code.cli.launchers.hermes:launch",
"fcc-dsh": "free_claude_code.cli.launchers.dsh:launch",
+ "fcc-grok": "free_claude_code.cli.launchers.grok:launch",
}
assert pyproject["project"]["gui-scripts"] == {
"fcc-desktop": "free_claude_code.cli.desktop_entrypoint:launch",
@@ -404,13 +405,10 @@ def test_launch_codex_passes_responses_config_and_child_env(
{
"data": [
{
- "id": "anthropic/nvidia_nim/provider-model",
+ "id": "nvidia_nim/provider-model",
+ "provider_model_ref": "nvidia_nim/provider-model",
"display_name": "NVIDIA model",
},
- {
- "id": ("claude-3-freecc-no-thinking/nvidia_nim/provider-model"),
- "display_name": "NVIDIA model (no thinking)",
- },
{
"id": "claude-opus-4-20250514",
"display_name": "Claude Opus 4",
@@ -461,7 +459,7 @@ def test_launch_codex_passes_responses_config_and_child_env(
assert command[-2:] == ["exec", "hello"]
assert len(requests) == 1
request = requests[0]
- assert request.full_url == "http://127.0.0.1:9191/v1/models"
+ 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
diff --git a/tests/cli/test_grok_launcher.py b/tests/cli/test_grok_launcher.py
new file mode 100644
index 00000000..9e2951df
--- /dev/null
+++ b/tests/cli/test_grok_launcher.py
@@ -0,0 +1,465 @@
+"""Contract tests for the installed `fcc-grok` launcher."""
+
+import json
+import subprocess
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import 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",
+ allows_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",
+ allows_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
+
+
+ "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"),
+ [
+ ("1.0.5\n", 0, (1, 0, 5)),
+ ("grok 1.2.3\n", 0, (1, 2, 3)),
+ ("1.2.3 (abcdef)\n", 0, (1, 2, 3)),
+ ("1.2.3-alpha.1\n", 0, None),
+ ("unexpected 1.2.3\n", 0, None),
+ ("1.2.3\n", 1, 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),
+ ):
+ assert grok.grok_binary_version("resolved-grok") == expected
+
+
+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,
+) -> 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"
+ assert (
+ env["GROK_MODELS_LIST_URL"] == "http://127.0.0.1:9191/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]
+
+
[email protected]("key", ["GROK_CONFIG", "GROK_CONFIG_PATH"])
+def test_existing_process_overlay_is_rejected(
+ key: str, 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
diff --git a/tests/cli/test_hermes_launcher.py b/tests/cli/test_hermes_launcher.py
index c3b6138d..277c7028 100644
--- a/tests/cli/test_hermes_launcher.py
+++ b/tests/cli/test_hermes_launcher.py
@@ -31,11 +31,13 @@ def _models_payload() -> JsonObject:
return {
"data": [
{
- "id": "anthropic/nvidia_nim/vendor/model",
+ "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",
},
]
diff --git a/tests/cli/test_model_catalog.py b/tests/cli/test_model_catalog.py
index ce7e6612..89b438f0 100644
--- a/tests/cli/test_model_catalog.py
+++ b/tests/cli/test_model_catalog.py
@@ -10,24 +10,22 @@ from free_claude_code.cli.launchers.model_catalog import (
from free_claude_code.core.json_types import JsonObject
-def _models_payload(*model_ids: str) -> JsonObject:
- return {
- "data": [
- {
- "id": model_id,
- "display_name": f"Display {index}",
- }
- for index, model_id in enumerate(model_ids)
- ]
- }
-
-
def test_client_models_project_nested_direct_refs_in_source_order() -> None:
assert client_models_from_response(
- _models_payload(
- "anthropic/nvidia_nim/nvidia/nemotron-3-super",
- "open_router/meta-llama/llama-3.3-70b",
- )
+ {
+ "data": [
+ {
+ "id": "nvidia_nim/nvidia/nemotron-3-super",
+ "provider_model_ref": "nvidia_nim/nvidia/nemotron-3-super",
+ "display_name": "Display 0",
+ },
+ {
+ "id": "open_router/meta-llama/llama-3.3-70b",
+ "provider_model_ref": "open_router/meta-llama/llama-3.3-70b",
+ "display_name": "Display 1",
+ },
+ ]
+ }
) == (
ClientModel(
wire_slug="nvidia_nim/nvidia/nemotron-3-super",
@@ -44,20 +42,40 @@ def test_client_models_project_nested_direct_refs_in_source_order() -> None:
)
-def test_client_models_suppress_no_thinking_alias_when_normal_model_exists() -> None:
+def test_client_models_keep_no_thinking_direct_route() -> None:
models = client_models_from_response(
- _models_payload(
- "claude-3-freecc-no-thinking/nvidia_nim/provider-model",
- "anthropic/nvidia_nim/provider-model",
- )
+ {
+ "data": [
+ {
+ "id": "claude-3-freecc-no-thinking/nvidia_nim/provider-model",
+ "provider_model_ref": "nvidia_nim/provider-model",
+ "display_name": "Display 0",
+ }
+ ]
+ }
)
- assert [model.wire_slug for model in models] == ["nvidia_nim/provider-model"]
+ assert models == (
+ ClientModel(
+ wire_slug="claude-3-freecc-no-thinking/nvidia_nim/provider-model",
+ provider_model_ref="nvidia_nim/provider-model",
+ display_name="Display 0",
+ allows_reasoning=False,
+ ),
+ )
def test_client_models_keep_no_thinking_only_route() -> None:
assert client_models_from_response(
- _models_payload("claude-3-freecc-no-thinking/open_router/plain-model")
+ {
+ "data": [
+ {
+ "id": "claude-3-freecc-no-thinking/open_router/plain-model",
+ "provider_model_ref": "open_router/plain-model",
+ "display_name": "Display 0",
+ }
+ ]
+ }
) == (
ClientModel(
wire_slug="claude-3-freecc-no-thinking/open_router/plain-model",
@@ -72,7 +90,9 @@ def test_client_models_ignore_compatibility_unknown_and_malformed_entries() -> N
payload: JsonObject = {
"data": [
{"id": "claude-opus-4-20250514"},
- {"id": "anthropic/unknown/model"},
+ {"id": "unknown/model", "provider_model_ref": 123},
+ {"id": " ", "provider_model_ref": "open_router/model"},
+ {"id": "open_router/model", "provider_model_ref": "open_router/"},
{"id": 123},
"not-an-object",
]
@@ -84,11 +104,25 @@ def test_client_models_ignore_compatibility_unknown_and_malformed_entries() -> N
def test_client_models_deduplicate_wire_slugs_deterministically() -> None:
models = client_models_from_response(
- _models_payload(
- "anthropic/gemini/models/gemini-test",
- "gemini/models/gemini-test",
- "anthropic/open_router/provider/test",
- )
+ {
+ "data": [
+ {
+ "id": "gemini/models/gemini-test",
+ "provider_model_ref": "gemini/models/gemini-test",
+ "display_name": "Display 0",
+ },
+ {
+ "id": "gemini/models/gemini-test",
+ "provider_model_ref": "gemini/models/gemini-test",
+ "display_name": "Display 1",
+ },
+ {
+ "id": "open_router/provider/test",
+ "provider_model_ref": "open_router/provider/test",
+ "display_name": "Display 2",
+ },
+ ]
+ }
)
assert [model.wire_slug for model in models] == [
@@ -121,7 +155,7 @@ def test_fetch_proxy_models_uses_canonical_bearer_request() -> None:
assert response == {"data": []}
request = open_local_request.call_args.args[0]
- assert request.full_url == "http://127.0.0.1:9191/v1/models"
+ assert request.full_url == "http://127.0.0.1:9191/v1/models?view=responses"
assert request.get_method() == "GET"
assert request.get_header("Authorization") == "Bearer proxy-token"
diff --git a/tests/cli/test_opencode_launcher.py b/tests/cli/test_opencode_launcher.py
index 5db1ea13..56c57c14 100644
--- a/tests/cli/test_opencode_launcher.py
+++ b/tests/cli/test_opencode_launcher.py
@@ -29,11 +29,13 @@ def _models_payload() -> JsonObject:
return {
"data": [
{
- "id": "anthropic/nvidia_nim/vendor/model",
+ "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",
},
]
diff --git a/tests/config/test_config.py b/tests/config/test_config.py
index 83022886..11c71f84 100644
--- a/tests/config/test_config.py
+++ b/tests/config/test_config.py
@@ -108,14 +108,24 @@ def test_process_values_are_parsed_at_the_loader_boundary(
@pytest.mark.parametrize(
"value",
- [0.0, -1.0, float("inf"), float("-inf"), float("nan")],
+ [
+ 0.0,
+ -1.0,
+ float("inf"),
+ float("-inf"),
+ float("nan"),
+ float(1 << 64),
+ ],
)
-def test_provider_progress_timeout_must_be_finite_and_positive(value: float) -> None:
+def test_provider_progress_timeout_must_be_representable(value: float) -> None:
with pytest.raises(ValidationError):
Settings(provider_progress_timeout=value)
[email protected]("value", ["0", "-1", "inf", "-inf", "nan"])
+ "value",
+ ["0", "-1", "inf", "-inf", "nan", str(1 << 64)],
+)
def test_loader_rejects_invalid_provider_progress_timeout(value: str) -> None:
with pytest.raises(ValidationError):
compose_settings_snapshot({}, {"PROVIDER_PROGRESS_TIMEOUT": value})
diff --git a/tests/core/openai_responses/test_sse.py b/tests/core/openai_responses/test_sse.py
index 0459f57f..a4419512 100644
--- a/tests/core/openai_responses/test_sse.py
+++ b/tests/core/openai_responses/test_sse.py
@@ -173,6 +173,9 @@ async def test_anthropic_text_stream_converts_to_responses_sse() -> None:
events = parse_sse_text(text)
event_names = [event.event for event in events]
+ assert [event.data["sequence_number"] for event in events] == list(
+ range(len(events))
+ )
assert event_names[:3] == [
"response.created",
"response.output_item.added",
@@ -206,7 +209,9 @@ async def test_max_tokens_stop_reason_converts_to_response_incomplete() -> None:
assert incomplete["output"][0]["content"][0]["text"] == "partial output"
assert incomplete["usage"] == {
"input_tokens": 3,
+ "input_tokens_details": {"cached_tokens": 0},
"output_tokens": 4,
+ "output_tokens_details": {"reasoning_tokens": 0},
"total_tokens": 7,
}
@@ -587,7 +592,9 @@ async def test_split_usage_deltas_sum_latest_anthropic_input_categories() -> Non
assert response["usage"] == {
"input_tokens": 36,
+ "input_tokens_details": {"cached_tokens": 11},
"output_tokens": 7,
+ "output_tokens_details": {"reasoning_tokens": 0},
"total_tokens": 43,
}
assert "stop_reason" not in response
@@ -632,7 +639,9 @@ async def test_usage_ignores_invalid_anthropic_input_categories() -> None:
assert response["usage"] == {
"input_tokens": 35,
+ "input_tokens_details": {"cached_tokens": 10},
"output_tokens": 7,
+ "output_tokens_details": {"reasoning_tokens": 0},
"total_tokens": 42,
}
@@ -668,7 +677,7 @@ async def test_reasoning_usage_detail_is_capped_at_output_tokens() -> None:
@pytest.mark.asyncio
-async def test_reasoning_usage_detail_omits_zero_capped_count() -> None:
+async def test_reasoning_usage_detail_reports_zero_capped_count() -> None:
response = await _completed_response_from_sse(
_aiter(
_anthropic_reasoning_stream(
@@ -681,13 +690,15 @@ async def test_reasoning_usage_detail_omits_zero_capped_count() -> None:
assert response["usage"] == {
"input_tokens": 3,
+ "input_tokens_details": {"cached_tokens": 0},
"output_tokens": 0,
+ "output_tokens_details": {"reasoning_tokens": 0},
"total_tokens": 3,
}
@pytest.mark.asyncio
-async def test_text_only_usage_omits_reasoning_usage_detail() -> None:
+async def test_text_only_usage_reports_zero_reasoning_usage_detail() -> None:
response = await _completed_response_from_sse(
_aiter(_anthropic_text_stream("plain text only")),
{"model": "nvidia_nim/test-model", "stream": True},
@@ -695,7 +706,9 @@ async def test_text_only_usage_omits_reasoning_usage_detail() -> None:
assert response["usage"] == {
"input_tokens": 3,
+ "input_tokens_details": {"cached_tokens": 0},
"output_tokens": 4,
+ "output_tokens_details": {"reasoning_tokens": 0},
"total_tokens": 7,
}
diff --git a/tests/scripts/test_installers.py b/tests/scripts/test_installers.py
index 6dc2e8c9..82b45983 100644
--- a/tests/scripts/test_installers.py
+++ b/tests/scripts/test_installers.py
@@ -21,6 +21,7 @@ FCC_COMMANDS = (
"fcc-cline",
"fcc-hermes",
"fcc-dsh",
+ "fcc-grok",
"fcc-init",
"free-claude-code",
)
@@ -56,6 +57,7 @@ def _posix_command(name: str) -> str:
"cline": "3.0.55",
"hermes": "0.20.4",
"dsh": "0.1.0-rc.8",
+ "grok": "1.0.5",
"node": "22.19.0",
}.get(name, "1.0.0")
version_output = (
@@ -138,6 +140,7 @@ if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "install" ]; then
cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-cline"
cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-hermes"
cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-dsh"
+ cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-grok"
if [ "$FAIL_STEP" != "fcc-missing" ]; then
cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-codex"
fi
@@ -327,7 +330,7 @@ while [ "$#" -gt 0 ]; do
done
echo "download:$url" >> "$CALL_LOG"
case "$url:$FAIL_STEP" in
- *claude.ai*:claude-download|*chatgpt.com*:codex-download|*pi.dev*:pi-download|*opencode.ai*:opencode-download|*hermes-agent.nousresearch.com*:hermes-download|*rtk-ai*:rtk-download|*astral.sh*:uv-download)
+ *claude.ai*:claude-download|*chatgpt.com*:codex-download|*pi.dev*:pi-download|*opencode.ai*:opencode-download|*hermes-agent.nousresearch.com*:hermes-download|*x.ai*:grok-download|*rtk-ai*:rtk-download|*astral.sh*:uv-download)
exit 41
;;
esac
@@ -337,6 +340,7 @@ case "$url" in
*pi.dev*) source="$FAKE_FIXTURES/pi-installer.sh" ;;
*opencode.ai*) source="$FAKE_FIXTURES/opencode-installer.sh" ;;
*hermes-agent.nousresearch.com*) source="$FAKE_FIXTURES/hermes-installer.sh" ;;
+ *x.ai*) source="$FAKE_FIXTURES/grok-installer.sh" ;;
*rtk-ai*)
if [ "$FAIL_STEP" = "rtk-install" ]; then
printf 'invalid archive\n' > "$output"
@@ -404,6 +408,16 @@ echo "hermes-install:$*" >> "$CALL_LOG"
mkdir -p "$HOME/.local/bin"
cp "$FAKE_FIXTURES/hermes-command.sh" "$HOME/.local/bin/hermes"
chmod +x "$HOME/.local/bin/hermes"
+""",
+ )
+ _write_executable(
+ fixtures / "grok-installer.sh",
+ """#!/bin/sh
+echo "grok-install" >> "$CALL_LOG"
+[ "$FAIL_STEP" = "grok-install" ] && exit 27
+mkdir -p "$HOME/.local/bin"
+cp "$FAKE_FIXTURES/grok-command.sh" "$HOME/.local/bin/grok"
+chmod +x "$HOME/.local/bin/grok"
""",
)
_write_executable(
@@ -423,6 +437,7 @@ chmod +x "$HOME/.local/bin/uv"
_write_executable(fixtures / "cline-command.sh", _posix_command("cline"))
_write_executable(fixtures / "hermes-command.sh", _posix_command("hermes"))
_write_executable(fixtures / "dsh-command.sh", _posix_command("dsh"))
+ _write_executable(fixtures / "grok-command.sh", _posix_command("grok"))
rtk_command = _posix_rtk_command().encode()
with tarfile.open(
fixtures / "rtk-x86_64-unknown-linux-musl.tar.gz", "w:gz"
@@ -516,6 +531,7 @@ def test_install_sh_fresh_install_is_verified(posix_harness: PosixHarness) -> No
assert calls.index("npm:install -g @deepseek-ai/[email protected]") < calls.index(
"dsh:--version"
)
+ assert calls.index("grok-install") < calls.index("grok:--version")
assert calls.index("uv-install") < calls.index("uv:--version")
assert any(
call.startswith(
@@ -537,7 +553,7 @@ def test_install_sh_fresh_install_is_verified(posix_harness: PosixHarness) -> No
def test_install_sh_installs_selected_hermes_without_setup(
posix_harness: PosixHarness,
) -> None:
- result = posix_harness.run_interactive("n\nn\nn\nn\nn\ny\nn\nn\n")
+ result = posix_harness.run_interactive("n\nn\nn\nn\nn\ny\nn\nn\nn\n")
assert result.returncode == 0, result.stdout
calls = posix_harness.calls()
@@ -557,7 +573,7 @@ def test_install_sh_stops_when_selected_hermes_install_fails(
failure: str,
) -> None:
result = posix_harness.run_interactive(
- "n\nn\nn\nn\nn\ny\nn\nn\n", fail_step=failure
+ "n\nn\nn\nn\nn\ny\nn\nn\nn\n", fail_step=failure
)
assert result.returncode != 0
@@ -571,7 +587,7 @@ def test_install_sh_rejects_unsupported_hermes_platform_before_download(
posix_harness.env["FAKE_UNAME"] = "Darwin"
posix_harness.env["FAKE_UNAME_MACHINE"] = "x86_64"
- result = posix_harness.run_interactive("n\nn\nn\nn\nn\ny\nn\nn\n")
+ result = posix_harness.run_interactive("n\nn\nn\nn\nn\ny\nn\nn\nn\n")
assert result.returncode != 0
assert "does not provide a supported release for Darwin x86_64" in result.stdout
@@ -594,10 +610,52 @@ def test_install_sh_preserves_compatible_existing_hermes(
)
+def test_install_sh_preserves_compatible_existing_grok(
+ posix_harness: PosixHarness,
+) -> None:
+ posix_harness.add_client("grok")
+
+ result = posix_harness.run()
+
+ assert result.returncode == 0, result.stderr
+ assert "Grok Build 1.0.5 already satisfies >=1.0.5" in result.stdout
+ assert not any("x.ai/cli" in call for call in posix_harness.calls())
+
+
+def test_install_sh_upgrades_old_grok_with_official_installer(
+ posix_harness: PosixHarness,
+) -> None:
+ _write_executable(
+ posix_harness.bin_dir / "grok",
+ _posix_command("grok").replace("grok 1.0.5", "grok 1.0.4"),
+ )
+
+ result = posix_harness.run()
+
+ assert result.returncode == 0, result.stderr
+ assert "does not satisfy stable >=1.0.5" in result.stdout
+ assert "download:https://x.ai/cli/install.sh" in posix_harness.calls()
+ assert "grok-install" in posix_harness.calls()
+
+
[email protected]("failure", ["grok-download", "grok-install"])
+def test_install_sh_stops_when_grok_install_fails(
+ posix_harness: PosixHarness,
+ failure: str,
+) -> None:
+ result = posix_harness.run_interactive(
+ "n\nn\nn\nn\nn\nn\nn\ny\nn\n", fail_step=failure
+ )
+
+ assert result.returncode != 0
+ assert "Free Claude Code is installed and verified." not in result.stdout
+ assert not any(call.startswith("uv:") for call in posix_harness.calls())
+
+
def test_install_sh_installs_selected_dsh_at_exact_preview(
posix_harness: PosixHarness,
) -> None:
- result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\ny\nn\n")
+ result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\ny\nn\nn\n")
assert result.returncode == 0, result.stdout
calls = posix_harness.calls()
@@ -650,7 +708,7 @@ def test_install_sh_rejects_incompatible_node_for_selected_dsh(
_posix_command("node").replace("node 22.19.0", f"node {node_version}"),
)
- result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\ny\nn\n")
+ result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\ny\nn\nn\n")
assert result.returncode != 0
assert "Free Claude Code is installed and verified." not in result.stdout
@@ -676,7 +734,7 @@ def test_install_sh_stops_when_selected_dsh_install_fails(
posix_harness: PosixHarness,
) -> None:
result = posix_harness.run_interactive(
- "n\nn\nn\nn\nn\nn\ny\nn\n", fail_step="dsh-install"
+ "n\nn\nn\nn\nn\nn\ny\nn\nn\n", fail_step="dsh-install"
)
assert result.returncode != 0
@@ -770,7 +828,7 @@ def test_install_sh_preserves_existing_rtk_and_configures_only_selected_agent(
) -> None:
posix_harness.add_rtk()
- result = posix_harness.run_interactive("n\ny\nn\nn\nn\nn\nn\ny\n")
+ result = posix_harness.run_interactive("n\ny\nn\nn\nn\nn\nn\nn\ny\n")
assert result.returncode == 0, result.stdout
assert "verifying it without updating it" in result.stdout
@@ -818,7 +876,7 @@ def test_install_sh_reprompts_then_installs_only_selected_agent(
posix_harness: PosixHarness,
) -> None:
result = posix_harness.run_interactive(
- "n\nn\nn\nn\nn\nn\nn\nn\ny\nn\nn\nn\nn\nn\nn\n"
+ "n\nn\nn\nn\nn\nn\nn\nn\nn\ny\nn\nn\nn\nn\nn\nn\nn\n"
)
assert result.returncode == 0, result.stdout
@@ -839,7 +897,7 @@ def test_install_sh_rejects_uninstalled_only_selection(
posix_harness: PosixHarness,
) -> None:
result = posix_harness.run_interactive(
- "n\nn\ny\nn\nn\nn\nn\nn\n", fail_step="pi-skip"
+ "n\nn\ny\nn\nn\nn\nn\nn\nn\n", fail_step="pi-skip"
)
assert result.returncode != 0
@@ -942,6 +1000,7 @@ def test_install_sh_preserves_valid_existing_tools(
posix_harness.add_client("pi")
posix_harness.add_client("cline")
posix_harness.add_client("hermes")
+ posix_harness.add_client("grok")
posix_harness.add_uv(uv_version)
result = posix_harness.run()
@@ -1385,6 +1444,7 @@ def _batch_client(name: str) -> str:
"cline": "3.0.55",
"hermes": "0.20.4",
"dsh": "0.1.0-rc.8",
+ "grok": "1.0.5",
"node": "22.19.0",
}.get(name, "1.0.0")
version_output = (
@@ -1454,6 +1514,7 @@ copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-opencode.cmd" >nu
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-cline.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-hermes.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-dsh.cmd" >nul
+copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-grok.cmd" >nul
if not "%FAIL_STEP%"=="fcc-missing" copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-codex.cmd" >nul
exit /b 0
:update_shell
@@ -1585,6 +1646,7 @@ def powershell_harness(
_batch_client("hermes"), encoding="utf-8"
)
(fixtures / "dsh-command.cmd").write_text(_batch_client("dsh"), encoding="utf-8")
+ (fixtures / "grok-command.cmd").write_text(_batch_client("grok"), encoding="utf-8")
(fixtures / "rtk-command.cmd").write_text(_batch_rtk(), encoding="utf-8")
(fixtures / "uv-command.cmd").write_text(_batch_uv("0.11.28"), encoding="utf-8")
(fixtures / "fcc-command.cmd").write_text(
@@ -1643,6 +1705,15 @@ $bin = Join-Path $env:LOCALAPPDATA "hermes\hermes-agent\bin"
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "hermes-command.cmd") (Join-Path $bin "hermes.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "hermes-install:${NonInteractive}:${SkipSetup}"
+""",
+ encoding="utf-8",
+ )
+ (fixtures / "grok-installer.ps1").write_text(
+ r"""if ($env:FAIL_STEP -eq "grok-install") { exit 66 }
+$bin = Join-Path $env:USERPROFILE ".local\bin"
+New-Item -ItemType Directory -Force -Path $bin | Out-Null
+Copy-Item (Join-Path $env:FAKE_FIXTURES "grok-command.cmd") (Join-Path $bin "grok.cmd") -Force
+Add-Content -LiteralPath $env:CALL_LOG -Value "grok-install"
""",
encoding="utf-8",
)
@@ -1690,6 +1761,7 @@ function Invoke-RestMethod {
($env:FAIL_STEP -eq "pi-download" -and $Uri.Contains("pi.dev")) -or
($env:FAIL_STEP -eq "opencode-download" -and $Uri.Contains("anomalyco/opencode")) -or
($env:FAIL_STEP -eq "hermes-download" -and $Uri.Contains("hermes-agent.nousresearch.com")) -or
+ ($env:FAIL_STEP -eq "grok-download" -and $Uri.Contains("x.ai/cli")) -or
($env:FAIL_STEP -eq "rtk-download" -and $Uri.Contains("rtk-ai/rtk")) -or
($env:FAIL_STEP -eq "uv-download" -and $Uri.Contains("astral.sh"))
) {
@@ -1707,6 +1779,9 @@ function Invoke-RestMethod {
elseif ($Uri.Contains("hermes-agent.nousresearch.com")) {
$source = Join-Path $env:FAKE_FIXTURES "hermes-installer.ps1"
}
+ elseif ($Uri.Contains("x.ai/cli")) {
+ $source = Join-Path $env:FAKE_FIXTURES "grok-installer.ps1"
+ }
elseif ($Uri.Contains("opencode-windows-")) {
if ($env:FAIL_STEP -eq "opencode-archive") {
Set-Content -LiteralPath $OutFile -Value "not a zip"
@@ -1810,6 +1885,7 @@ def test_install_ps1_fresh_install_is_verified(
assert calls.index("npm:install -g @deepseek-ai/[email protected]") < calls.index(
"dsh:--version"
)
+ assert calls.index("grok-install") < calls.index("grok:--version")
assert not any("hermes:setup" in call for call in calls)
assert calls.index("uv-install") < calls.index("uv:--version")
assert any(
@@ -1866,6 +1942,46 @@ def test_install_ps1_preserves_compatible_existing_hermes(
)
+def test_install_ps1_preserves_compatible_existing_grok(
+ powershell_harness: PowerShellHarness,
+) -> None:
+ powershell_harness.add_client("grok")
+
+ result = powershell_harness.run()
+
+ assert result.returncode == 0, result.stderr
+ assert "Grok Build 1.0.5 already satisfies >=1.0.5" in result.stdout
+ assert not any("x.ai/cli" in call for call in powershell_harness.calls())
+
+
+def test_install_ps1_upgrades_old_grok_with_official_installer(
+ powershell_harness: PowerShellHarness,
+) -> None:
+ (powershell_harness.bin_dir / "grok.cmd").write_text(
+ _batch_client("grok").replace("grok 1.0.5", "grok 1.0.4"),
+ encoding="utf-8",
+ )
+
+ result = powershell_harness.run()
+
+ assert result.returncode == 0, result.stderr
+ assert "does not satisfy stable >=1.0.5" in result.stdout
+ assert "download:https://x.ai/cli/install.ps1" in powershell_harness.calls()
+ assert "grok-install" in powershell_harness.calls()
+
+
[email protected]("failure", ["grok-download", "grok-install"])
+def test_install_ps1_stops_when_grok_install_fails(
+ powershell_harness: PowerShellHarness,
+ failure: str,
+) -> None:
+ result = powershell_harness.run(fail_step=failure)
+
+ assert result.returncode != 0
+ assert "Free Claude Code is installed and verified." not in result.stdout
+ assert not any(call.startswith("uv:") for call in powershell_harness.calls())
+
+
def test_install_ps1_preserves_exact_dsh_preview(
powershell_harness: PowerShellHarness,
) -> None:
@@ -2220,6 +2336,7 @@ def test_install_ps1_preserves_valid_existing_tools(
powershell_harness.add_client("pi")
powershell_harness.add_client("cline")
powershell_harness.add_client("hermes")
+ powershell_harness.add_client("grok")
powershell_harness.add_uv(uv_version)
result = powershell_harness.run()
@@ -2524,6 +2641,8 @@ def test_installers_use_native_clients_and_single_python_selection() -> None:
assert "https://pi.dev/install.sh" in shell
assert "https://pi.dev/install.ps1" in powershell
+ assert "https://x.ai/cli/install.sh" in shell
+ assert "https://x.ai/cli/install.ps1" in powershell
def test_install_ps1_uses_x64_python_for_windows_arm_compatibility() -> None:
@@ -2575,8 +2694,8 @@ Invoke-DownloadedPowerShellInstaller `
("answers", "expected", "expected_messages"),
[
(
- ("", "", "", "", "", "", "", ""),
- "True,True,True,True,False,True,True,False",
+ ("", "", "", "", "", "", "", "", ""),
+ "True,True,True,True,False,True,True,True,False",
(),
),
(
@@ -2590,15 +2709,17 @@ Invoke-DownloadedPowerShellInstaller `
"n",
"n",
"n",
+ "n",
"y",
"n",
"n",
"n",
"n",
"n",
+ "n",
"y",
),
- "False,True,False,False,False,False,False,True",
+ "False,True,False,False,False,False,False,False,True",
("Please answer Y or N.", "Select at least one coding agent."),
),
],
@@ -2624,6 +2745,7 @@ $script:InstallOpenCode = $true
$script:InstallCline = $false
$script:InstallHermes = $true
$script:InstallDsh = $true
+$script:InstallGrok = $true
$script:EnableRtk = $false
function Read-Host {{
param([string] $Prompt)
@@ -2634,7 +2756,7 @@ function Read-Host {{
function Read-YesNo {{{read_yes_no}}}
function Select-CodingAgents {{{select_agents}}}
Select-CodingAgents
-Write-Output "selection:$($script:InstallClaudeCode),$($script:InstallCodex),$($script:InstallPi),$($script:InstallOpenCode),$($script:InstallCline),$($script:InstallHermes),$($script:InstallDsh),$($script:EnableRtk)"
+Write-Output "selection:$($script:InstallClaudeCode),$($script:InstallCodex),$($script:InstallPi),$($script:InstallOpenCode),$($script:InstallCline),$($script:InstallHermes),$($script:InstallDsh),$($script:InstallGrok),$($script:EnableRtk)"
"""
result = subprocess.run(
@@ -2663,6 +2785,7 @@ $script:InstallOpenCode = $false
$script:InstallCline = $false
$script:InstallHermes = $false
$script:InstallDsh = $false
+$script:InstallGrok = $false
$script:PiAvailable = $false
$script:Calls = @()
function Write-Step {{ param([string] $Message) }}
@@ -2673,6 +2796,7 @@ function Ensure-OpenCode {{ $script:Calls += "opencode" }}
function Ensure-Cline {{ $script:Calls += "cline" }}
function Ensure-Hermes {{ $script:Calls += "hermes" }}
function Ensure-Dsh {{ $script:Calls += "dsh" }}
+function Ensure-Grok {{ $script:Calls += "grok" }}
function Ensure-SelectedCodingAgents {{{body}}}
Ensure-SelectedCodingAgents
Write-Output "calls:$($script:Calls -join ',')"
@@ -2705,6 +2829,7 @@ $script:InstallOpenCode = $false
$script:InstallCline = $false
$script:InstallHermes = $false
$script:InstallDsh = $false
+$script:InstallGrok = $false
$script:PiAvailable = $false
$script:Calls = @()
function Write-Step {{ param([string] $Message) }}
@@ -2742,6 +2867,7 @@ $script:InstallOpenCode = $false
$script:InstallCline = $false
$script:InstallHermes = $false
$script:InstallDsh = $false
+$script:InstallGrok = $false
$script:PiAvailable = $false
function Write-Step {{ param([string] $Message) }}
function Ensure-ClaudeCode {{ }}
@@ -2751,6 +2877,7 @@ function Ensure-OpenCode {{ }}
function Ensure-Cline {{ }}
function Ensure-Hermes {{ }}
function Ensure-Dsh {{ }}
+function Ensure-Grok {{ }}
function Ensure-SelectedCodingAgents {{{body}}}
Ensure-SelectedCodingAgents
"""
diff --git a/tests/scripts/test_uninstallers.py b/tests/scripts/test_uninstallers.py
index be348cf6..25de29be 100644
--- a/tests/scripts/test_uninstallers.py
+++ b/tests/scripts/test_uninstallers.py
@@ -16,6 +16,7 @@ FCC_COMMANDS = (
"fcc-cline",
"fcc-hermes",
"fcc-dsh",
+ "fcc-grok",
"fcc-init",
"free-claude-code",
)
@@ -140,12 +141,16 @@ def posix_uninstall_harness(tmp_path: Path) -> PosixUninstallHarness:
_write_executable(bin_dir / "cline", "#!/bin/sh\nexit 0\n")
_write_executable(bin_dir / "hermes", "#!/bin/sh\nexit 0\n")
_write_executable(bin_dir / "dsh", "#!/bin/sh\nexit 0\n")
+ _write_executable(bin_dir / "grok", "#!/bin/sh\nexit 0\n")
hermes_state = home / ".hermes" / "sessions" / "state.json"
hermes_state.parent.mkdir(parents=True)
hermes_state.write_text('{"native": true}\n', encoding="utf-8")
dsh_state = home / ".dsh" / "sessions" / "state.json"
dsh_state.parent.mkdir(parents=True)
dsh_state.write_text('{"native": true}\n', encoding="utf-8")
+ grok_state = home / ".grok" / "sessions" / "state.json"
+ grok_state.parent.mkdir(parents=True)
+ grok_state.write_text('{"native": true}\n', encoding="utf-8")
_write_executable(
bin_dir / "pgrep",
"""#!/bin/sh
@@ -177,7 +182,7 @@ if [ "${1:-}" = "tool" ] && [ "${2:-}" = "uninstall" ]; then
echo 'Tool `free-claude-code` is not installed' >&2
exit 2
fi
- for name in fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh fcc-init free-claude-code; do
+ for name in fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh fcc-grok fcc-init free-claude-code; do
/bin/rm -f "$FAKE_TOOL_BIN/$name"
done
echo "Uninstalled free-claude-code"
@@ -250,12 +255,16 @@ def test_uninstall_sh_removes_and_verifies_only_fcc(
assert (posix_uninstall_harness.bin_dir / "cline").exists()
assert (posix_uninstall_harness.bin_dir / "hermes").exists()
assert (posix_uninstall_harness.bin_dir / "dsh").exists()
+ assert (posix_uninstall_harness.bin_dir / "grok").exists()
assert (
posix_uninstall_harness.home / ".hermes" / "sessions" / "state.json"
).read_text(encoding="utf-8") == '{"native": true}\n'
assert (
posix_uninstall_harness.home / ".dsh" / "sessions" / "state.json"
).read_text(encoding="utf-8") == '{"native": true}\n'
+ assert (
+ posix_uninstall_harness.home / ".grok" / "sessions" / "state.json"
+ ).read_text(encoding="utf-8") == '{"native": true}\n'
assert posix_uninstall_harness.calls() == [
"uv:tool dir --bin",
"uv:tool uninstall free-claude-code",
@@ -502,7 +511,16 @@ def powershell_uninstall_harness(
(tool_bin / f"{name}.cmd").write_text(
"@echo off\nexit /b 0\n", encoding="utf-8"
)
- for name in ("claude", "codex", "pi", "opencode", "cline", "hermes", "dsh"):
+ for name in (
+ "claude",
+ "codex",
+ "pi",
+ "opencode",
+ "cline",
+ "hermes",
+ "dsh",
+ "grok",
+ ):
(bin_dir / f"{name}.cmd").write_text("@echo off\nexit /b 0\n", encoding="utf-8")
hermes_state = local_app_data / "hermes" / "state.json"
hermes_state.parent.mkdir(parents=True)
@@ -510,6 +528,9 @@ def powershell_uninstall_harness(
dsh_state = home / ".dsh" / "sessions" / "state.json"
dsh_state.parent.mkdir(parents=True)
dsh_state.write_text('{"native": true}\n', encoding="utf-8")
+ grok_state = home / ".grok" / "sessions" / "state.json"
+ grok_state.parent.mkdir(parents=True)
+ grok_state.write_text('{"native": true}\n', encoding="utf-8")
uv_commands = " ".join(FCC_COMMANDS)
(bin_dir / "uv.cmd").write_text(
@@ -638,12 +659,16 @@ def test_uninstall_ps1_removes_and_verifies_only_fcc(
assert (powershell_uninstall_harness.bin_dir / "cline.cmd").exists()
assert (powershell_uninstall_harness.bin_dir / "hermes.cmd").exists()
assert (powershell_uninstall_harness.bin_dir / "dsh.cmd").exists()
+ assert (powershell_uninstall_harness.bin_dir / "grok.cmd").exists()
assert (
Path(powershell_uninstall_harness.env["LOCALAPPDATA"]) / "hermes" / "state.json"
).read_text(encoding="utf-8") == '{"native": true}\n'
assert (
powershell_uninstall_harness.home / ".dsh" / "sessions" / "state.json"
).read_text(encoding="utf-8") == '{"native": true}\n'
+ assert (
+ powershell_uninstall_harness.home / ".grok" / "sessions" / "state.json"
+ ).read_text(encoding="utf-8") == '{"native": true}\n'
assert powershell_uninstall_harness.calls() == [
"uv:tool dir --bin",
"uv:tool uninstall free-claude-code",
diff --git a/uv.lock b/uv.lock
index c570b35c..83f47c0f 100644
--- a/uv.lock
+++ b/uv.lock
@@ -607,7 +607,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "5.10.0"
+version = "5.11.0"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },