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 Pi as a first-class FCC client (#1088)
Ali Khokhar2fe2ba82d24e
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex acf3690f..c540b872 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -11,15 +11,15 @@ and how contributors should extend it.## System OverviewFree Claude Code is a local proxy for agent clients. It accepts Anthropic-Messages traffic from Claude Code clients and OpenAI Responses traffic from Codex-clients, routes the request to a configured upstream provider, and preserves the-wire protocol expected by the caller.+Messages traffic from Claude Code and Pi clients and OpenAI Responses traffic+from Codex 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 and Codex environments+- CLI launchers: wrapper entrypoints prepare Claude Code, Codex, and Pi sessionsso they target the local proxy.- Messaging bridge: optional Discord or Telegram adapters turn chat messagesinto managed client CLI sessions.@@ -28,6 +28,7 @@ There are three runtime surfaces:flowchart LRClaudeCode[Claude Code CLI and Extensions] --> ProxyAPI[FastAPI Proxy]Codex[Codex CLI and Extensions] --> ProxyAPI+ Pi[Pi Coding Agent] --> ProxyAPIAdminUI[Local Admin UI] --> ProxyAPIBots[Discord or Telegram Bots] --> Messaging[Messaging Bridge]Messaging --> ClientCLI[Managed Client CLI Sessions]@@ -123,8 +124,8 @@ of the FCC release version. It reads installed distribution metadata forFastAPI/OpenAPI, FCC-owned CLI `--version` output, and the outbound web-toolsuser agent. A source-only checkout without installed metadata reports theexplicit `0+unknown` fallback; runtime code never parses `pyproject.toml` or-duplicates a release literal. Claude and Codex launcher arguments remain-transparent to their wrapped clients.+duplicates a release literal. Client launcher arguments remain transparent to+their wrapped clients except for FCC-owned ephemeral provider configuration.The main ownership rule is that Anthropic and Responses protocol schemas andshared protocol behavior belong in [src/free_claude_code/core/](src/free_claude_code/core/), while request routing and@@ -156,6 +157,9 @@ for real prompts against supported providers:Codex relies on, including native/interleaved reasoning, function and customtool calls, generated `/model` catalog support, Responses stream lifecycleevents, and Responses-to-Anthropic conversion at the adapter boundary.+- `fcc-pi`, Pi, and the Anthropic-compatible proxy behavior Pi relies on,+ including an FCC-scoped model catalog, streaming text and reasoning, and tool+ use/results.- 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,@@ -208,12 +212,13 @@ Console scripts are registered in [pyproject.toml](pyproject.toml):- `fcc-init` calls `free_claude_code.cli.entrypoints:init`.- `fcc-claude` calls `free_claude_code.cli.launchers.claude:launch`.- `fcc-codex` calls `free_claude_code.cli.launchers.codex:launch`.+- `fcc-pi` calls `free_claude_code.cli.launchers.pi:launch`.[scripts/install.sh](scripts/install.sh) and [scripts/install.ps1](scripts/install.ps1)install or update the uv tool plus optional voice extras. [scripts/uninstall.sh](scripts/uninstall.sh)and [scripts/uninstall.ps1](scripts/uninstall.ps1) remove only the FCC uv tool and alwaysdelete the managed `~/.fcc/` tree from [config/paths.py](src/free_claude_code/config/paths.py); they do not remove-uv, Claude Code, Codex, or uv-managed Python runtimes. [scripts/ci.sh](scripts/ci.sh) and+uv, Claude Code, Codex, Pi, 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.@@ -777,13 +782,18 @@ otherwise the Messages handler rejects them before provider execution.## CLI Launchers And Managed Claude+[cli/proxy_auth.py](src/free_claude_code/cli/proxy_auth.py) owns the neutral+proxy-auth token policy shared by client launchers. A blank configured token+becomes the local-only `fcc-no-auth` sentinel so clients cross their login gates+while FCC continues to run without API authentication.+[cli/claude_env.py](src/free_claude_code/cli/claude_env.py) owns the canonicalClaude Code proxy environment used by every FCC-launched Claude process. Itstrips inherited `ANTHROPIC_*` variables, sets `ANTHROPIC_BASE_URL`, enablesgateway model discovery, configures the auto-compact window, disablesnonessential Anthropic traffic, and always sets `ANTHROPIC_AUTH_TOKEN`. Blank-proxy auth becomes the local-only `fcc-no-auth` sentinel so Claude Code reaches-the proxy instead of stopping at its login gate.+proxy auth uses the shared local-only sentinel so Claude Code reaches the proxy+instead of stopping at its login gate.[cli/launchers/claude.py](src/free_claude_code/cli/launchers/claude.py) owns the installed`fcc-claude` launcher:@@ -805,6 +815,21 @@ the proxy instead of stopping at its login gate.fail-open: launch continues with a warning if the catalog cannot be prepared.- It stores the proxy auth token in `FCC_CODEX_API_KEY` for Codex to read.+[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)+is its bundled Pi adapter:++- Session commands load the extension from its absolute installed path and+ scope Pi to the ephemeral `free-claude-code/*` provider.+- The extension fetches FCC's `/v1/models` catalog before registration, projects+ only routable provider-model IDs, 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.+- FCC connection values live only in child-process `FCC_PI_*` variables. Native+ Pi credentials and persistent configuration remain untouched.+- Pi package-management, configuration, help, and version commands pass through+ unchanged because they do not create an FCC-backed session.+[cli/managed/](src/free_claude_code/cli/managed/) owns managed Claude Code subprocesses used byDiscord and Telegram messaging. Managed task invocations extend the same proxyenvironment only with non-interactive terminal settings, optional `--resume`,@@ -828,9 +853,9 @@ reports a count-only failure, and leaves failures available for the next cleanupattempt. Real-session registration is collision-safe and becomes durable treestate only after the manager accepts it.-Codex is supported through `fcc-codex` and Codex extensions. FCC does not keep an-internal managed-Codex session runner because no user-facing messaging setting-selects Codex for Discord or Telegram.+Codex and Pi are supported through their installed launchers. FCC does not keep+internal managed session runners for them because no user-facing messaging+setting selects either client for Discord or Telegram.## Messaging Architecturediff --git a/README.md b/README.mdindex 97064879..16b05b4d 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@# 🤖 Free Claude Code-Use Claude Code CLI, Codex CLI, their VS Code extensions, JetBrains ACP, or chat bots through your own provider-backed proxy.+Use Claude Code, Codex, Pi, editor extensions, or chat bots through your own provider-backed proxy.[](https://opensource.org/licenses/MIT)[](https://www.python.org/downloads/)@@ -12,7 +12,7 @@ Use Claude Code CLI, Codex CLI, their VS Code extensions, JetBrains ACP, or chat[](https://github.com/astral-sh/ruff)[](https://github.com/Delgan/loguru)-Run Claude Code or Codex with free, paid, or local models. Choose and validate providers from one local Admin UI.+Run your coding agents with free, paid, or local models. Choose and validate providers from one local Admin UI.[Quick Start](#quick-start) · [Providers](#choose-a-provider) · [Clients](#connect-your-client) · [Integrations](#optional-integrations) · [Manage](#manage-your-installation)@@ -54,9 +54,9 @@ Run Claude Code or Codex with free, paid, or local models. Choose and validate p## What You Get-- Launch Claude Code with `fcc-claude` or Codex with `fcc-codex`.+- Launch Claude Code with `fcc-claude`, Codex with `fcc-codex`, or Pi with `fcc-pi`.- Switch among 24 cloud and local providers from the Admin UI.-- Use the native Claude Code and Codex `/model` pickers.+- Use each coding agent's native model picker.- Route Opus, Sonnet, Haiku, and fallback traffic to different models.- Keep streaming, tool use, and reasoning support across compatible models.- Connect Claude Code and Codex in VS Code or Claude Code through JetBrains ACP.@@ -128,12 +128,20 @@ Codex:fcc-codex```-Both launchers use the current Admin UI settings. Type `/model` inside either agent to choose from the models FCC exposes. Normal CLI arguments still work, for example:+Pi:++```bash+fcc-pi+```++All three 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:```bashfcc-codex exec "hello"```+`fcc-pi` registers FCC only for that Pi process; your existing Pi settings, sessions, credentials, and extensions remain unchanged.+## Choose A ProviderEnter the listed setting in the Admin UI, set `MODEL` to a provider-prefixed model ID, then click **Validate** and **Apply**. Provider names link to their key, model, or setup pages.@@ -204,7 +212,7 @@ For example, route Opus to `nvidia_nim/moonshotai/kimi-k2.6`, Sonnet to `open_ro## Connect Your Client-For terminal use, start `fcc-server`, then prefer `fcc-claude` or `fcc-codex`. Use the guides below for editor integrations.+For terminal use, start `fcc-server`, then run `fcc-claude`, `fcc-codex`, or `fcc-pi`. Use the guides below for editor integrations.<details><summary><strong>Claude Code in VS Code</strong></summary>@@ -398,7 +406,7 @@ Re-run the matching command from [Install Or Update](#install).### Uninstall-Stop every running FCC command first. The uninstaller removes the FCC uv tool, verifies every FCC command is gone, and then deletes `~/.fcc/`. It leaves uv, Python, Claude Code, Codex, and shared PATH entries intact.+Stop every running FCC command first. The uninstaller removes the FCC uv tool, verifies every FCC command is gone, and then deletes `~/.fcc/`. It leaves uv, Python, Claude Code, Codex, Pi, and shared PATH entries intact.macOS/Linux:diff --git a/pyproject.toml b/pyproject.tomlindex d6b4515c..6af07403 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,8 +4,8 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "3.5.19"-description = "Local proxy connecting Claude Code and Codex to OpenAI-compatible AI providers"+version = "3.6.0"+description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"dependencies = [@@ -31,6 +31,7 @@ free-claude-code = "free_claude_code.cli.entrypoints:serve"fcc-init = "free_claude_code.cli.entrypoints:init"fcc-claude = "free_claude_code.cli.launchers.claude:launch"fcc-codex = "free_claude_code.cli.launchers.codex:launch"+fcc-pi = "free_claude_code.cli.launchers.pi:launch"[project.optional-dependencies]voice = [diff --git a/scripts/install.ps1 b/scripts/install.ps1index b66000e2..6f73b1bb 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -18,13 +18,14 @@ $PythonVersion = "3.14.0"$MinUvVersion = "0.11.0"$ClaudeInstallUrl = "https://claude.ai/install.ps1"$CodexInstallUrl = "https://chatgpt.com/codex/install.ps1"+$PiInstallUrl = "https://pi.dev/install.ps1"$UvInstallUrl = "https://astral.sh/uv/install.ps1"function Show-Usage {@"Usage: install.ps1 [options]-Installs Claude Code and Codex if missing, ensures a compatible uv, and installs or updates Free Claude Code.+Installs Claude Code, Codex, and Pi if missing, ensures a compatible uv, and installs or updates Free Claude Code.Options:-VoiceNim Install NVIDIA NIM voice transcription support.@@ -158,6 +159,30 @@ function Add-KnownBinDirectories {}if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {Add-PathEntry (Join-Path $env:LOCALAPPDATA "Programs\OpenAI\Codex\bin")+ Add-PathEntry (Join-Path $env:LOCALAPPDATA "pi-node\current")+ }+ if (-not [string]::IsNullOrWhiteSpace($env:APPDATA)) {+ Add-PathEntry (Join-Path $env:APPDATA "npm")+ }+}++function Add-PiBinDirectories {+ if ($DryRun) {+ return+ }++ Add-KnownBinDirectories+ $npm = Get-ApplicationCommand "npm"+ if (-not $npm) {+ return+ }++ $prefix = (& $npm.Source prefix -g 2>$null | Out-String).Trim()+ if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($prefix)) {+ $prefix = (& $npm.Source config get prefix 2>$null | Out-String).Trim()+ }+ if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($prefix)) {+ Add-PathEntry $prefix}}@@ -231,6 +256,39 @@ function Confirm-Application {Invoke-NativeCommand -FilePath $command.Source -Arguments @("--version")}+function Test-PiApplication {+ param($Command)++ try {+ $helpOutput = (& $Command.Source --help 2>$null | Out-String)+ }+ catch {+ return $false+ }+ return (+ $LASTEXITCODE -eq 0 -and+ $helpOutput.Contains("--extension") -and+ $helpOutput.Contains("--models")+ )+}++function Confirm-PiApplication {+ if ($DryRun) {+ Write-Host "+ pi --help (verify --extension and --models support)"+ Write-Host "+ pi --version"+ return+ }++ $command = Get-ApplicationCommand "pi"+ if (-not $command) {+ throw "Pi was installed, but 'pi' is not available on PATH."+ }+ if (-not (Test-PiApplication $command)) {+ throw "The 'pi' command at '$($command.Source)' is not a compatible Pi Coding Agent."+ }+ Invoke-NativeCommand -FilePath $command.Source -Arguments @("--version")+}+function Ensure-ClaudeCode {if (Get-ApplicationCommand "claude") {Write-Host "Claude Code already found on PATH; verifying it."@@ -255,6 +313,22 @@ function Ensure-Codex {Confirm-Application -CommandName "codex" -DisplayName "Codex"}+function Ensure-Pi {+ $existingPi = Get-ApplicationCommand "pi"+ if ($existingPi -and ($DryRun -or (Test-PiApplication $existingPi))) {+ Write-Host "Pi already found on PATH; verifying it."+ }+ else {+ if ($existingPi) {+ Write-Host "The existing 'pi' command at '$($existingPi.Source)' is not Pi Coding Agent; installing Pi."+ }+ Invoke-DownloadedPowerShellInstaller -Url $PiInstallUrl -Name "Pi"+ Add-PiBinDirectories+ }++ Confirm-PiApplication+}+function Convert-UvVersionOutput {param([string] $Output)@@ -398,7 +472,7 @@ function Configure-AndConfirmFreeClaudeCode {if ($DryRun) {Write-Host "+ uv tool update-shell"Write-Host "+ uv tool dir --bin"- Write-Host "+ verify fcc-server, fcc-claude, and fcc-codex in the uv tool bin directory"+ Write-Host "+ verify fcc-server, fcc-claude, fcc-codex, and fcc-pi in the uv tool bin directory"Write-Host "+ fcc-server --version"return}@@ -419,7 +493,7 @@ function Configure-AndConfirmFreeClaudeCode {[IO.Path]::AltDirectorySeparatorChar)$installedCommands = @{}- foreach ($commandName in @("fcc-server", "fcc-claude", "fcc-codex")) {+ foreach ($commandName in @("fcc-server", "fcc-claude", "fcc-codex", "fcc-pi")) {$command = Get-ApplicationCommand $commandNameif (-not $command) {throw "Free Claude Code installation did not create '$commandName'."@@ -459,6 +533,9 @@ Ensure-ClaudeCodeWrite-Step "Ensuring Codex is installed"Ensure-Codex+Write-Step "Ensuring Pi is installed"+Ensure-Pi+Write-Step "Ensuring uv $MinUvVersion or newer is installed"Ensure-Uv@@ -476,4 +553,5 @@ else {Write-Host "Free Claude Code is installed and verified. Start the proxy with: fcc-server"Write-Host "Run Claude Code with: fcc-claude"Write-Host "Run Codex with: fcc-codex"+ Write-Host "Run Pi with: fcc-pi"}diff --git a/scripts/install.sh b/scripts/install.shindex 49dbf502..1196f1b9 100644--- a/scripts/install.sh+++ b/scripts/install.sh@@ -6,6 +6,7 @@ PYTHON_VERSION="3.14.0"MIN_UV_VERSION="0.11.0"CLAUDE_INSTALL_URL="https://claude.ai/install.sh"CODEX_INSTALL_URL="https://chatgpt.com/codex/install.sh"+PI_INSTALL_URL="https://pi.dev/install.sh"UV_INSTALL_URL="https://astral.sh/uv/install.sh"dry_run=0@@ -19,7 +20,7 @@ show_usage() {cat <<'USAGE'Usage: install.sh [options]-Installs Claude Code and Codex if missing, ensures a compatible uv, and installs or updates Free Claude Code.+Installs Claude Code, Codex, and Pi if missing, ensures a compatible uv, and installs or updates Free Claude Code.Options:--voice-nim Install NVIDIA NIM voice transcription support.@@ -102,12 +103,26 @@ add_known_bin_directories() {if [ -n "${HOME:-}" ]; thenadd_path_entry "$HOME/.local/bin"add_path_entry "$HOME/.cargo/bin"+ add_path_entry "${XDG_DATA_HOME:-$HOME/.local/share}/pi-node/current/bin"fiexport PATHhash -r 2>/dev/null || true}+add_pi_bin_directories() {+ [ "$dry_run" -eq 0 ] || return 0+ add_known_bin_directories+ if command -v npm >/dev/null 2>&1; then+ pi_npm_prefix=$(npm prefix -g 2>/dev/null || npm config get prefix 2>/dev/null || true)+ if [ -n "$pi_npm_prefix" ]; then+ add_path_entry "$pi_npm_prefix/bin"+ export PATH+ hash -r 2>/dev/null || true+ fi+ fi+}+require_command() {if [ "$dry_run" -eq 0 ] && ! command -v "$1" >/dev/null 2>&1; thenfail "$1 is required. Install it first, then rerun this installer."@@ -184,6 +199,31 @@ verify_command() {run "$command_path" --version}+pi_command_is_compatible() {+ pi_command_path=$(command -v pi 2>/dev/null) || return 1+ pi_help=$("$pi_command_path" --help 2>/dev/null) || return 1+ case "$pi_help" in+ *--extension*) ;;+ *) return 1 ;;+ esac+ case "$pi_help" in+ *--models*) return 0 ;;+ *) return 1 ;;+ esac+}++verify_pi_command() {+ if [ "$dry_run" -eq 1 ]; then+ printf '+ pi --help (verify --extension and --models support)\n'+ print_command pi --version+ return 0+ fi++ pi_command_path=$(command -v pi 2>/dev/null) || fail "Pi was installed, but 'pi' is not available on PATH."+ pi_command_is_compatible || fail "The 'pi' command at $pi_command_path is not a compatible Pi Coding Agent."+ run "$pi_command_path" --version+}+ensure_claude() {if command -v claude >/dev/null 2>&1; thenprintf 'Claude Code already found on PATH; verifying it.\n'@@ -206,6 +246,22 @@ ensure_codex() {verify_command codex "Codex"}+ensure_pi() {+ if [ "$dry_run" -eq 1 ] && command -v pi >/dev/null 2>&1; then+ printf 'Pi already found on PATH; verifying it.\n'+ elif pi_command_is_compatible; then+ printf 'Pi already found on PATH; verifying it.\n'+ else+ if existing_pi_path=$(command -v pi 2>/dev/null); then+ printf "The existing 'pi' command at %s is not Pi Coding Agent; installing Pi.\n" "$existing_pi_path"+ fi+ download_and_run "$PI_INSTALL_URL" sh "Pi"+ add_pi_bin_directories+ fi++ verify_pi_command+}+current_uv_version() {if output=$(uv --version); then:@@ -380,7 +436,7 @@ configure_and_verify_free_claude_code() {if [ "$dry_run" -eq 1 ]; thenprint_command uv tool dir --bin- printf '+ verify fcc-server, fcc-claude, and fcc-codex in the uv tool bin directory\n'+ printf '+ verify fcc-server, fcc-claude, fcc-codex, and fcc-pi in the uv tool bin directory\n'print_command fcc-server --versionreturn 0fi@@ -398,7 +454,7 @@ configure_and_verify_free_claude_code() {export PATHhash -r 2>/dev/null || true- for command_name in fcc-server fcc-claude fcc-codex; do+ for command_name in fcc-server fcc-claude fcc-codex fcc-pi; do[ -x "$tool_bin/$command_name" ] || fail "Free Claude Code installation did not create $tool_bin/$command_name."done@@ -421,6 +477,9 @@ ensure_claudestep "Ensuring Codex is installed"ensure_codex+step "Ensuring Pi is installed"+ensure_pi+step "Ensuring uv $MIN_UV_VERSION or newer is installed"ensure_uv@@ -436,4 +495,5 @@ elseprintf '\nFree Claude Code is installed and verified. Start the proxy with: fcc-server\n'printf 'Run Claude Code with: fcc-claude\n'printf 'Run Codex with: fcc-codex\n'+ printf 'Run Pi with: fcc-pi\n'fidiff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1index af012dee..06d0c877 100644--- a/scripts/uninstall.ps1+++ b/scripts/uninstall.ps1@@ -14,6 +14,7 @@ $FccCommands = @("fcc-server","fcc-claude","fcc-codex",+ "fcc-pi","fcc-init","free-claude-code")@@ -25,7 +26,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, the uv-managed Python runtime, or shared PATH entries.+Does not remove uv, Claude Code, Codex, Pi, the uv-managed Python runtime, or shared PATH entries.Options:-DryRun Print commands without running them.@@ -266,5 +267,5 @@ if ($DryRun) {}else {Write-Host "Free Claude Code has been removed and verified."- Write-Host "uv, Claude Code, Codex, the uv-managed Python runtime, and shared PATH entries were left installed."+ Write-Host "uv, Claude Code, Codex, Pi, the uv-managed Python runtime, and shared PATH entries were left installed."}diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex 974a080d..a9b9b54f 100644--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -3,7 +3,7 @@ set -euPACKAGE_NAME="free-claude-code"FCC_HOME_DIRNAME=".fcc"-FCC_COMMANDS="fcc-server fcc-claude fcc-codex fcc-init free-claude-code"+FCC_COMMANDS="fcc-server fcc-claude fcc-codex fcc-pi fcc-init free-claude-code"dry_run=0uv_tool_bin=""@@ -13,7 +13,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, the uv-managed Python runtime, or shared PATH entries.+Does not remove uv, Claude Code, Codex, Pi, the uv-managed Python runtime, or shared PATH entries.Options:--dry-run Print commands without running them.@@ -239,5 +239,5 @@ if [ "$dry_run" -eq 1 ]; thenprintf '\nDry run complete. No changes were made.\n'elseprintf '\nFree Claude Code has been removed and verified.\n'- printf 'uv, Claude Code, Codex, the uv-managed Python runtime, and shared PATH entries were left installed.\n'+ printf 'uv, Claude Code, Codex, Pi, the uv-managed Python runtime, and shared PATH entries were left installed.\n'fidiff --git a/smoke/capabilities.py b/smoke/capabilities.pyindex 9193da98..8001d9f6 100644--- a/smoke/capabilities.py+++ b/smoke/capabilities.py@@ -489,6 +489,17 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (),(),),+ CapabilityContract(+ "cli",+ "pi_cli_integration",+ "pi_cli_integration",+ "free_claude_code.cli.launchers.pi",+ "Pi CLI binary, bundled extension, and FCC child-process environment",+ "Anthropic Messages provider with an FCC-scoped live model catalog",+ "proxy preflight, missing extension, or catalog failure exits without fallback",+ ("tests/cli/test_entrypoints.py",),+ ("test_pi_cli_prompt_e2e",),+ ),CapabilityContract("extensibility","provider_platform_abcs",diff --git a/smoke/features.py b/smoke/features.pyindex dff65b85..73588056 100644--- a/smoke/features.py+++ b/smoke/features.py@@ -34,6 +34,7 @@ README_FEATURES: tuple[str, ...] = ("zero_cost_provider_access","drop_in_claude_code_replacement","drop_in_codex_replacement",+ "pi_cli_integration","provider_matrix","per_model_mapping","thinking_token_support",@@ -98,6 +99,17 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (("configured provider credentials or local provider endpoint",),"missing providers are missing_env unless FCC_ALLOW_NO_PROVIDER_SMOKE=1",),+ FeatureCoverage(+ "pi_cli_integration",+ "Pi discovers FCC models and sends Anthropic Messages through the proxy",+ "readme",+ ("tests/cli/test_entrypoints.py",),+ ("test_probe_and_models_routes",),+ ("test_pi_cli_prompt_e2e",),+ ("clients",),+ ("Pi CLI", "configured provider credentials or local provider endpoint"),+ "skip only when Pi is absent; configured providers 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.pyindex 5600b8c0..fec8f664 100644--- a/smoke/product/test_client_product_live.py+++ b/smoke/product/test_client_product_live.py@@ -1,5 +1,7 @@import json+import osimport shutil+import subprocessimport threadingfrom collections.abc import Iteratorfrom contextlib import contextmanager@@ -60,6 +62,62 @@ def test_jetbrains_protocol_e2e(smoke_config: SmokeConfig) -> None:assert_product_stream(first.events)[email protected]_target("clients")+def test_pi_cli_prompt_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> None:+ if not shutil.which("pi"):+ pytest.skip("missing_env: Pi CLI not found")+ uv_bin = shutil.which("uv")+ if not uv_bin:+ pytest.skip("missing_env: uv not found")+ provider_model = ProviderMatrixDriver(smoke_config).first_model()+ auth_token = "fcc-pi-smoke-token"++ with SmokeServerDriver(+ smoke_config,+ name="product-pi-cli",+ env_overrides={+ "MODEL": provider_model.full_model,+ "ANTHROPIC_AUTH_TOKEN": auth_token,+ "MESSAGING_PLATFORM": "none",+ },+ ).run() as server:+ env = os.environ.copy()+ env.update(+ {+ "HOST": "127.0.0.1",+ "PORT": str(server.port),+ "FCC_OPEN_BROWSER": "0",+ "ANTHROPIC_AUTH_TOKEN": auth_token,+ "PI_CODING_AGENT_DIR": str(tmp_path / "pi-agent"),+ }+ )+ result = subprocess.run(+ [+ uv_bin,+ "run",+ "--project",+ str(smoke_config.root),+ "--no-sync",+ "fcc-pi",+ "--no-session",+ "--no-approve",+ "--print",+ "Reply with exactly FCC_SMOKE_PI",+ ],+ cwd=tmp_path,+ env=env,+ check=False,+ capture_output=True,+ text=True,+ timeout=smoke_config.timeout_s + 15,+ )+ server_log = server.log_path.read_text(encoding="utf-8", errors="replace")++ assert result.returncode == 0, result.stderr or result.stdout+ assert "FCC_SMOKE_PI" in result.stdout+ assert "POST /v1/messages" in server_log++@pytest.mark.smoke_target("cli")def test_claude_cli_adaptive_thinking_e2e(smoke_config: SmokeConfig, tmp_path: Pathdiff --git a/src/free_claude_code/cli/claude_env.py b/src/free_claude_code/cli/claude_env.pyindex bf6122a3..42c942b3 100644--- a/src/free_claude_code/cli/claude_env.py+++ b/src/free_claude_code/cli/claude_env.py@@ -2,10 +2,11 @@from collections.abc import Mapping+from free_claude_code.cli.proxy_auth import proxy_auth_token+CLAUDE_CODE_AUTO_COMPACT_WINDOW = "190000"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1"CLAUDE_BINARY_NAME = "claude"-CLAUDE_NO_AUTH_SENTINEL = "fcc-no-auth"def build_claude_proxy_env(@@ -22,16 +23,10 @@ def build_claude_proxy_env(if not key.startswith("ANTHROPIC_")}env["ANTHROPIC_BASE_URL"] = proxy_root_url- env["ANTHROPIC_AUTH_TOKEN"] = claude_auth_token(auth_token)+ env["ANTHROPIC_AUTH_TOKEN"] = proxy_auth_token(auth_token)env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = CLAUDE_CODE_AUTO_COMPACT_WINDOWenv["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"] = (CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC)return env---def claude_auth_token(auth_token: str) -> str:- """Return the Claude Code auth marker for proxy-auth or no-auth sessions."""-- return auth_token.strip() or CLAUDE_NO_AUTH_SENTINELdiff --git a/src/free_claude_code/cli/launchers/codex.py b/src/free_claude_code/cli/launchers/codex.pyindex 9914e855..3d195d4b 100644--- a/src/free_claude_code/cli/launchers/codex.py+++ b/src/free_claude_code/cli/launchers/codex.py@@ -6,6 +6,7 @@ import sysfrom collections.abc import Mapping, Sequencefrom urllib.request import Request, urlopen+from free_claude_code.cli.proxy_auth import proxy_auth_tokenfrom free_claude_code.config.paths import codex_model_catalog_pathfrom free_claude_code.config.server_urls import local_proxy_root_urlfrom free_claude_code.config.settings import Settings, get_settings@@ -118,7 +119,7 @@ def build_codex_launcher_env(for key, value in base_env.items()if key not in _STRIPPED_CODEX_ENV_KEYS and not key.startswith("OPENAI_")}- env[_CODEX_AUTH_ENV_KEY] = auth_token.strip() or "fcc-no-auth"+ env[_CODEX_AUTH_ENV_KEY] = proxy_auth_token(auth_token)return envdiff --git a/src/free_claude_code/cli/launchers/pi.py b/src/free_claude_code/cli/launchers/pi.pynew file mode 100644index 00000000..3596ac78--- /dev/null+++ b/src/free_claude_code/cli/launchers/pi.py@@ -0,0 +1,163 @@+"""Installed `fcc-pi` launcher."""++import os+import subprocess+import sys+from collections.abc import Mapping, Sequence+from pathlib import Path++from free_claude_code.cli.proxy_auth import proxy_auth_token+from free_claude_code.config.server_urls import local_proxy_root_url+from free_claude_code.config.settings import get_settings++from .common import preflight_proxy, resolve_client_binary, run_client_process++_API_KEY_ENV = "FCC_PI_API_KEY"+_BASE_URL_ENV = "FCC_PI_BASE_URL"+_BINARY_NAME = "pi"+_DISPLAY_NAME = "Pi"+_HELP_TIMEOUT_SECONDS = 5.0+_MODEL_SCOPE = "free-claude-code/*"+_REQUIRED_HELP_MARKERS = ("--extension", "--models")+_PASSTHROUGH_COMMANDS = frozenset(+ {"config", "install", "list", "remove", "uninstall", "update"}+)+_PASSTHROUGH_FLAGS = frozenset({"--help", "-h", "--version", "-v"})+++def launch(argv: Sequence[str] | None = None) -> None:+ """Launch Pi with a process-local Free Claude Code provider."""++ args = list(sys.argv[1:] if argv is None else argv)+ install_hint = pi_install_hint()+ binary_path = resolve_client_binary(+ binary_name=_BINARY_NAME,+ display_name=_DISPLAY_NAME,+ install_hint=install_hint,+ )+ if not pi_binary_is_compatible(binary_path):+ print(+ f"The 'pi' command at {binary_path} is not a compatible Pi Coding Agent.",+ file=sys.stderr,+ )+ print(install_hint, file=sys.stderr)+ raise SystemExit(126)++ if is_pi_passthrough(args):+ run_client_process(+ command=[binary_path, *args],+ env=os.environ,+ binary_name=_BINARY_NAME,+ display_name=_DISPLAY_NAME,+ install_hint=install_hint,+ )+ return++ settings = get_settings()+ proxy_root_url = local_proxy_root_url(settings)+ if error := preflight_proxy(proxy_root_url):+ print(+ f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",+ file=sys.stderr,+ )+ print("Start it in another terminal with: fcc-server", file=sys.stderr)+ raise SystemExit(1)++ extension_path = pi_extension_path()+ if not extension_path.is_file():+ print(+ "Free Claude Code's bundled Pi extension is missing. Reinstall FCC.",+ file=sys.stderr,+ )+ raise SystemExit(1)++ run_client_process(+ command=build_pi_launcher_command(+ binary_path=binary_path,+ extension_path=extension_path,+ argv=args,+ ),+ env=build_pi_launcher_env(+ proxy_root_url=proxy_root_url,+ auth_token=settings.anthropic_auth_token,+ base_env=os.environ,+ ),+ binary_name=_BINARY_NAME,+ display_name=_DISPLAY_NAME,+ install_hint=install_hint,+ )+++def build_pi_launcher_command(+ *,+ binary_path: str,+ extension_path: Path,+ argv: Sequence[str],+) -> list[str]:+ """Return a Pi session command with ephemeral FCC provider registration."""++ return [+ binary_path,+ "-e",+ str(extension_path),+ "--models",+ _MODEL_SCOPE,+ *argv,+ ]+++def build_pi_launcher_env(+ *,+ proxy_root_url: str,+ auth_token: str,+ base_env: Mapping[str, str],+) -> dict[str, str]:+ """Return a Pi environment containing only FCC-owned proxy variables."""++ env = {+ key: value for key, value in base_env.items() if not key.startswith("FCC_PI_")+ }+ env[_BASE_URL_ENV] = proxy_root_url.rstrip("/")+ env[_API_KEY_ENV] = proxy_auth_token(auth_token)+ return env+++def is_pi_passthrough(argv: Sequence[str]) -> bool:+ """Return whether Pi must receive argv unchanged as a non-session command."""++ return bool(argv) and (+ argv[0] in _PASSTHROUGH_COMMANDS or argv[0] in _PASSTHROUGH_FLAGS+ )+++def pi_extension_path() -> Path:+ """Return the absolute installed path to the bundled Pi extension."""++ return Path(__file__).with_name("pi_extension.ts").resolve()+++def pi_binary_is_compatible(binary_path: str) -> bool:+ """Return whether an executable exposes the Pi features FCC requires."""++ try:+ result = subprocess.run(+ [binary_path, "--help"],+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=_HELP_TIMEOUT_SECONDS,+ )+ except OSError, subprocess.TimeoutExpired:+ return False+ return result.returncode == 0 and all(+ marker in result.stdout for marker in _REQUIRED_HELP_MARKERS+ )+++def pi_install_hint(platform: str | None = None) -> str:+ """Return Pi's official installer command for the current platform."""++ if (platform or sys.platform) == "win32":+ return 'Install Pi with: powershell -c "irm https://pi.dev/install.ps1 | iex"'+ return "Install Pi with: curl -fsSL https://pi.dev/install.sh | sh"diff --git a/src/free_claude_code/cli/launchers/pi_extension.ts b/src/free_claude_code/cli/launchers/pi_extension.tsnew file mode 100644index 00000000..f738a711--- /dev/null+++ b/src/free_claude_code/cli/launchers/pi_extension.ts@@ -0,0 +1,157 @@+import type { ExtensionAPI, ProviderModelConfig } from "@earendil-works/pi-coding-agent";++const API_KEY_ENV = "FCC_PI_API_KEY";+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();+ if (!value) {+ throw new Error(`Missing required ${name} environment variable.`);+ }+ return value;+}++function normalizeBaseUrl(value: string): string {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ throw new Error(`${BASE_URL_ENV} is not a valid URL.`);+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") {+ throw new Error(`${BASE_URL_ENV} must use http or https.`);+ }+ url.search = "";+ url.hash = "";+ return url.toString().replace(/\/+$/, "");+}++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 {+ return {+ id: providerModel,+ name: providerModel,+ reasoning,+ input: ["text"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: DEFAULT_CONTEXT_WINDOW,+ maxTokens: DEFAULT_MAX_TOKENS,+ };+}++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);+ }++ 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));+ }++ if (models.length === 0) {+ throw new Error("FCC model catalog contains no routable provider models.");+ }+ return models;+}++function requestIdSuffix(response: Response): string {+ const requestId = response.headers.get("request-id") ?? response.headers.get("x-request-id");+ return requestId ? ` (request ${requestId})` : "";+}++async function fetchFccModels(baseUrl: string, apiKey: string): Promise<ProviderModelConfig[]> {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), CATALOG_TIMEOUT_MS);+ try {+ let response: Response;+ try {+ response = await fetch(`${baseUrl}/v1/models`, {+ headers: { "X-API-Key": apiKey },+ signal: controller.signal,+ });+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ throw new Error(`FCC model catalog timed out after ${CATALOG_TIMEOUT_MS}ms.`);+ }+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(`Could not reach the FCC model catalog: ${message}`);+ }++ if (!response.ok) {+ throw new Error(`FCC model catalog returned HTTP ${response.status}${requestIdSuffix(response)}.`);+ }++ let payload: unknown;+ try {+ payload = await response.json();+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ throw new Error(`FCC model catalog timed out after ${CATALOG_TIMEOUT_MS}ms.`);+ }+ throw new Error(`FCC model catalog returned invalid JSON${requestIdSuffix(response)}.`);+ }+ return projectFccModels(payload);+ } finally {+ clearTimeout(timeout);+ }+}++export default async function freeClaudeCode(pi: ExtensionAPI): Promise<void> {+ const baseUrl = normalizeBaseUrl(requireEnvironment(BASE_URL_ENV));+ const apiKey = requireEnvironment(API_KEY_ENV);+ const models = await fetchFccModels(baseUrl, apiKey);++ pi.registerProvider("free-claude-code", {+ name: "Free Claude Code",+ baseUrl,+ apiKey: `$${API_KEY_ENV}`,+ api: "anthropic-messages",+ models,+ });+}diff --git a/src/free_claude_code/cli/proxy_auth.py b/src/free_claude_code/cli/proxy_auth.pynew file mode 100644index 00000000..7264ab7a--- /dev/null+++ b/src/free_claude_code/cli/proxy_auth.py@@ -0,0 +1,9 @@+"""Shared proxy-auth policy for FCC client launchers."""++PROXY_NO_AUTH_SENTINEL = "fcc-no-auth"+++def proxy_auth_token(auth_token: str) -> str:+ """Return the configured proxy token or the no-auth client marker."""++ return auth_token.strip() or PROXY_NO_AUTH_SENTINELdiff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex 36744126..8789e35e 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -177,6 +177,7 @@ def test_cli_scripts_are_registered() -> None:assert scripts["free-claude-code"] == "free_claude_code.cli.entrypoints:serve"assert scripts["fcc-claude"] == "free_claude_code.cli.launchers.claude:launch"assert scripts["fcc-codex"] == "free_claude_code.cli.launchers.codex:launch"+ assert scripts["fcc-pi"] == "free_claude_code.cli.launchers.pi:launch"@pytest.mark.parametrize("entrypoint_name", ["serve", "init"])@@ -674,6 +675,247 @@ def test_launch_codex_catalog_failure_warns_and_continues(assert "launching without model picker catalog" in captured.err+def test_pi_launcher_builds_scoped_session_command_and_proxy_env(+ tmp_path: Path,+) -> None:+ from free_claude_code.cli.launchers.pi import (+ build_pi_launcher_command,+ build_pi_launcher_env,+ )++ extension = tmp_path / "pi_extension.ts"+ env = build_pi_launcher_env(+ proxy_root_url="http://127.0.0.1:9191/",+ auth_token=" proxy-token ",+ base_env={+ "PATH": "keep",+ "ANTHROPIC_API_KEY": "native-pi-credential",+ "FCC_PI_API_KEY": "stale-key",+ "FCC_PI_BASE_URL": "https://stale.invalid",+ },+ )++ assert build_pi_launcher_command(+ binary_path="resolved-pi.cmd",+ extension_path=extension,+ argv=["--print", "hello"],+ ) == [+ "resolved-pi.cmd",+ "-e",+ str(extension),+ "--models",+ "free-claude-code/*",+ "--print",+ "hello",+ ]+ assert env == {+ "PATH": "keep",+ "ANTHROPIC_API_KEY": "native-pi-credential",+ "FCC_PI_BASE_URL": "http://127.0.0.1:9191",+ "FCC_PI_API_KEY": "proxy-token",+ }+++def test_pi_launcher_uses_no_auth_sentinel_for_blank_token() -> None:+ from free_claude_code.cli.launchers.pi import build_pi_launcher_env++ env = build_pi_launcher_env(+ proxy_root_url="http://127.0.0.1:8082",+ auth_token="",+ base_env={},+ )++ assert env["FCC_PI_API_KEY"] == "fcc-no-auth"+++def test_launch_pi_registers_bundled_extension_for_sessions(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from free_claude_code.cli.launchers.pi import launch++ monkeypatch.setenv("KEEP_ME", "yes")+ monkeypatch.setenv("FCC_PI_API_KEY", "stale-key")+ extension = tmp_path / "pi_extension.ts"+ extension.write_text("export default () => {};", encoding="utf-8")+ settings = _launcher_settings(port=9191, token="proxy-token")++ with (+ patch("free_claude_code.cli.launchers.pi.get_settings", return_value=settings),+ patch("free_claude_code.cli.launchers.pi.preflight_proxy", return_value=None),+ patch(+ "free_claude_code.cli.launchers.pi.pi_extension_path",+ return_value=extension,+ ),+ patch(+ "free_claude_code.cli.launchers.common.shutil.which",+ return_value="resolved-pi.cmd",+ ),+ patch(+ "free_claude_code.cli.launchers.pi.pi_binary_is_compatible",+ return_value=True,+ ),+ patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,+ patch("free_claude_code.cli.launchers.common.register_pid"),+ patch("free_claude_code.cli.launchers.common.unregister_pid"),+ pytest.raises(SystemExit) as exc_info,+ ):+ process = popen.return_value+ process.pid = 12345+ process.wait.return_value = 0+ launch(["--print", "hello"])++ assert exc_info.value.code == 0+ assert popen.call_args.args[0] == [+ "resolved-pi.cmd",+ "-e",+ str(extension),+ "--models",+ "free-claude-code/*",+ "--print",+ "hello",+ ]+ child_env = popen.call_args.kwargs["env"]+ assert child_env["FCC_PI_BASE_URL"] == "http://127.0.0.1:9191"+ assert child_env["FCC_PI_API_KEY"] == "proxy-token"+ assert child_env["KEEP_ME"] == "yes"+++ "argv",+ [+ ["--help"],+ ["--version"],+ ["config", "set", "theme", "dark"],+ ["install", "npm:example"],+ ["list"],+ ["remove", "npm:example"],+ ["uninstall", "npm:example"],+ ["update"],+ ],+)+def test_launch_pi_passes_management_commands_through_without_proxy(+ argv: list[str],+) -> None:+ from free_claude_code.cli.launchers.pi import launch++ with (+ patch("free_claude_code.cli.launchers.pi.get_settings") as get_settings,+ patch("free_claude_code.cli.launchers.pi.preflight_proxy") as preflight,+ patch(+ "free_claude_code.cli.launchers.common.shutil.which",+ return_value="resolved-pi",+ ),+ patch(+ "free_claude_code.cli.launchers.pi.pi_binary_is_compatible",+ return_value=True,+ ),+ patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,+ patch("free_claude_code.cli.launchers.common.register_pid"),+ patch("free_claude_code.cli.launchers.common.unregister_pid"),+ pytest.raises(SystemExit) as exc_info,+ ):+ process = popen.return_value+ process.pid = 12345+ process.wait.return_value = 0+ launch(argv)++ assert exc_info.value.code == 0+ assert popen.call_args.args[0] == ["resolved-pi", *argv]+ get_settings.assert_not_called()+ preflight.assert_not_called()+++def test_launch_pi_fails_closed_when_bundled_extension_is_missing(+ capsys: pytest.CaptureFixture[str],+ tmp_path: Path,+) -> None:+ from free_claude_code.cli.launchers.pi import launch++ settings = _launcher_settings(port=9191)+ with (+ patch("free_claude_code.cli.launchers.pi.get_settings", return_value=settings),+ patch("free_claude_code.cli.launchers.pi.preflight_proxy", return_value=None),+ patch(+ "free_claude_code.cli.launchers.pi.pi_extension_path",+ return_value=tmp_path / "missing.ts",+ ),+ patch(+ "free_claude_code.cli.launchers.common.shutil.which",+ return_value="resolved-pi",+ ),+ patch(+ "free_claude_code.cli.launchers.pi.pi_binary_is_compatible",+ return_value=True,+ ),+ patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,+ pytest.raises(SystemExit) as exc_info,+ ):+ launch([])++ assert exc_info.value.code == 1+ popen.assert_not_called()+ assert "bundled Pi extension is missing" in capsys.readouterr().err+++def test_pi_install_hints_use_official_platform_installers() -> None:+ from free_claude_code.cli.launchers.pi import pi_install_hint++ assert "https://pi.dev/install.ps1" in pi_install_hint("win32")+ assert "https://pi.dev/install.sh" in pi_install_hint("darwin")+++ ("help_output", "return_code", "expected"),+ [+ ("--extension <path>\n--models <patterns>\n", 0, True),+ ("--models <patterns>\n", 0, False),+ ("--extension <path>\n", 0, False),+ ("--extension <path>\n--models <patterns>\n", 1, False),+ ],+)+def test_pi_binary_compatibility_requires_both_launcher_capabilities(+ help_output: str,+ return_code: int,+ expected: bool,+) -> None:+ from free_claude_code.cli.launchers.pi import pi_binary_is_compatible++ with patch(+ "free_claude_code.cli.launchers.pi.subprocess.run",+ return_value=SimpleNamespace(returncode=return_code, stdout=help_output),+ ):+ assert pi_binary_is_compatible("resolved-pi") is expected+++def test_launch_pi_rejects_unrelated_pi_binary(+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers.pi import launch++ with (+ patch(+ "free_claude_code.cli.launchers.common.shutil.which",+ return_value="unrelated-pi",+ ),+ patch(+ "free_claude_code.cli.launchers.pi.pi_binary_is_compatible",+ return_value=False,+ ),+ patch("free_claude_code.cli.launchers.pi.get_settings") as get_settings,+ patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,+ pytest.raises(SystemExit) as exc_info,+ ):+ launch([])++ assert exc_info.value.code == 126+ get_settings.assert_not_called()+ popen.assert_not_called()+ captured = capsys.readouterr()+ assert "not a compatible Pi Coding Agent" in captured.err+ assert "https://pi.dev/install." in captured.err++def test_launch_claude_keyboard_interrupt_kills_child_tree() -> None:from free_claude_code.cli.launchers.claude import launchdiff --git a/tests/scripts/test_installers.py b/tests/scripts/test_installers.pyindex e714daf4..b4030a97 100644--- a/tests/scripts/test_installers.py+++ b/tests/scripts/test_installers.py@@ -32,6 +32,12 @@ def _braced_body(text: str, declaration: str) -> str:def _posix_command(name: str) -> str:+ help_output = (+ ' echo " --extension, -e <path> Load an extension"\n'+ ' echo " --models <patterns> Scope models"'+ if name == "pi"+ else " :"+ )return f"""#!/bin/shecho "{name}:$*" >> "$CALL_LOG"if [ "$FAIL_STEP" = "{name}-verify" ]; then@@ -40,6 +46,24 @@ fiif [ "${{1:-}}" = "--version" ]; thenecho "{name} 1.0.0"fi+if [ "${{1:-}}" = "--help" ]; then+{help_output}+fi+"""+++def _posix_npm_command() -> str:+ return """#!/bin/sh+echo "npm:$*" >> "$CALL_LOG"+if [ "${1:-}" = "prefix" ] && [ "${2:-}" = "-g" ]; then+ printf '%s\n' "$FAKE_NPM_PREFIX"+ exit 0+fi+if [ "${1:-}" = "config" ] && [ "${2:-}" = "get" ] && [ "${3:-}" = "prefix" ]; then+ printf '%s\n' "$FAKE_NPM_PREFIX"+ exit 0+fi+exit 71"""@@ -60,6 +84,7 @@ if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "install" ]; thenmkdir -p "$FAKE_TOOL_BIN"cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-server"cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-claude"+ cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-pi"if [ "$FAIL_STEP" != "fcc-missing" ]; thencp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-codex"fi@@ -92,6 +117,14 @@ class PosixHarness:def add_client(self, name: str) -> None:_write_executable(self.bin_dir / name, _posix_command(name))+ def add_unrelated_pi(self) -> None:+ _write_executable(self.bin_dir / "pi", _posix_command("unrelated-pi"))++ def add_npm_prefix(self, prefix: Path) -> None:+ prefix.mkdir(parents=True)+ self.env["FAKE_NPM_PREFIX"] = str(prefix)+ _write_executable(self.bin_dir / "npm", _posix_npm_command())+def add_uv(self, version: str) -> None:_write_executable(self.bin_dir / "uv", _posix_uv_command(version))@@ -143,13 +176,14 @@ while [ "$#" -gt 0 ]; dodoneecho "download:$url" >> "$CALL_LOG"case "$url:$FAIL_STEP" in- *claude.ai*:claude-download|*chatgpt.com*:codex-download|*astral.sh*:uv-download)+ *claude.ai*:claude-download|*chatgpt.com*:codex-download|*pi.dev*:pi-download|*astral.sh*:uv-download)exit 41;;esaccase "$url" in*claude.ai*) source="$FAKE_FIXTURES/claude-installer.sh" ;;*chatgpt.com*) source="$FAKE_FIXTURES/codex-installer.sh" ;;+ *pi.dev*) source="$FAKE_FIXTURES/pi-installer.sh" ;;*astral.sh*) source="$FAKE_FIXTURES/uv-installer.sh" ;;*) exit 42 ;;esac@@ -174,6 +208,21 @@ echo "codex-install:$CODEX_NON_INTERACTIVE" >> "$CALL_LOG"mkdir -p "$HOME/.local/bin"cp "$FAKE_FIXTURES/codex-command.sh" "$HOME/.local/bin/codex"chmod +x "$HOME/.local/bin/codex"+""",+ )+ _write_executable(+ fixtures / "pi-installer.sh",+ """#!/bin/sh+echo "pi-install" >> "$CALL_LOG"+[ "$FAIL_STEP" = "pi-install" ] && exit 24+if [ -n "${FAKE_NPM_PREFIX:-}" ]; then+ pi_bin="$FAKE_NPM_PREFIX/bin"+else+ pi_bin="$HOME/.local/bin"+fi+mkdir -p "$pi_bin"+cp "$FAKE_FIXTURES/pi-command.sh" "$pi_bin/pi"+chmod +x "$pi_bin/pi"""",)_write_executable(@@ -188,6 +237,7 @@ chmod +x "$HOME/.local/bin/uv")_write_executable(fixtures / "claude-command.sh", _posix_command("claude"))_write_executable(fixtures / "codex-command.sh", _posix_command("codex"))+ _write_executable(fixtures / "pi-command.sh", _posix_command("pi"))_write_executable(fixtures / "uv-command.sh", _posix_uv_command("0.11.28"))_write_executable(fixtures / "fcc-command.sh",@@ -226,6 +276,7 @@ def test_install_sh_fresh_install_is_verified(posix_harness: PosixHarness) -> Nocalls = posix_harness.calls()assert calls.index("claude-install") < calls.index("claude:--version")assert calls.index("codex-install:1") < calls.index("codex:--version")+ assert calls.index("pi-install") < calls.index("pi:--version")assert calls.index("uv-install") < calls.index("uv:--version")assert any(call.startswith(@@ -248,6 +299,7 @@ def test_install_sh_preserves_valid_existing_tools() -> None:posix_harness.add_client("claude")posix_harness.add_client("codex")+ posix_harness.add_client("pi")posix_harness.add_uv("0.11.7")result = posix_harness.run()@@ -257,9 +309,42 @@ def test_install_sh_preserves_valid_existing_tools(assert "leaving it unchanged" in result.stdout+def test_install_sh_replaces_unrelated_pi_command(+ posix_harness: PosixHarness,+) -> None:+ posix_harness.add_client("claude")+ posix_harness.add_client("codex")+ posix_harness.add_unrelated_pi()+ posix_harness.add_uv("0.11.7")++ result = posix_harness.run()++ assert result.returncode == 0, result.stderr+ assert "is not Pi Coding Agent; installing Pi" in result.stdout+ assert "pi-install" in posix_harness.calls()+++def test_install_sh_discovers_custom_pi_npm_prefix(+ posix_harness: PosixHarness,+) -> None:+ posix_harness.add_client("claude")+ posix_harness.add_client("codex")+ posix_harness.add_npm_prefix(posix_harness.root / "custom-npm")+ posix_harness.add_uv("0.11.7")++ result = posix_harness.run()++ assert result.returncode == 0, result.stderr+ calls = posix_harness.calls()+ assert "npm:prefix -g" in calls+ assert "pi:--help" in calls+ assert "pi:--version" in calls++def test_install_sh_replaces_obsolete_uv(posix_harness: PosixHarness) -> None:posix_harness.add_client("claude")posix_harness.add_client("codex")+ posix_harness.add_client("pi")posix_harness.add_uv("0.5.9")result = posix_harness.run()@@ -278,6 +363,9 @@ def test_install_sh_replaces_obsolete_uv(posix_harness: PosixHarness) -> None:"codex-download","codex-install","codex-verify",+ "pi-download",+ "pi-install",+ "pi-verify","uv-download","uv-install","uv-verify",@@ -301,7 +389,10 @@ def test_install_sh_stops_without_success_on_each_failure("claude-verify": "chatgpt.com","codex-download": "codex-install","codex-install": "codex:--version",- "codex-verify": "astral.sh",+ "codex-verify": "pi.dev",+ "pi-download": "pi-install",+ "pi-install": "pi:--version",+ "pi-verify": "astral.sh","uv-download": "uv-install","uv-install": "uv:--version","uv-verify": "uv:tool install",@@ -340,6 +431,7 @@ def test_install_sh_rejects_unparseable_existing_uv() -> None:posix_harness.add_client("claude")posix_harness.add_client("codex")+ posix_harness.add_client("pi")posix_harness.add_uv("not-a-version")result = posix_harness.run()@@ -377,14 +469,32 @@ def _powershells() -> tuple[str, ...]:def _batch_client(name: str) -> str:+ help_output = (+ "echo --extension, -e ^<path^> Load an extension\n"+ "echo --models ^<patterns^> Scope models"+ if name == "pi"+ else "rem no product help"+ )return f"""@echo offecho {name}:%*>>"%CALL_LOG%"if "%FAIL_STEP%"=="{name}-verify" exit /b 51if "%1"=="--version" echo {name} 1.0.0+if "%1"=="--help" (+{help_output}+)exit /b 0"""+def _batch_npm() -> str:+ return r"""@echo off+echo npm:%*>>"%CALL_LOG%"+if "%1"=="prefix" if "%2"=="-g" echo %FAKE_NPM_PREFIX%& exit /b 0+if "%1"=="config" if "%2"=="get" if "%3"=="prefix" echo %FAKE_NPM_PREFIX%& exit /b 0+exit /b 71+"""++def _batch_uv(version: str) -> str:return rf"""@echo offecho uv:%*>>"%CALL_LOG%"@@ -402,6 +512,7 @@ if "%FAIL_STEP%"=="fcc-install" exit /b 53if not exist "%FAKE_TOOL_BIN%" mkdir "%FAKE_TOOL_BIN%"copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-server.cmd" >nulcopy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-claude.cmd" >nul+copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-pi.cmd" >nulif not "%FAIL_STEP%"=="fcc-missing" copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-codex.cmd" >nulexit /b 0:update_shell@@ -427,6 +538,14 @@ class PowerShellHarness:def add_client(self, name: str) -> None:_write_executable(self.bin_dir / f"{name}.cmd", _batch_client(name))+ def add_unrelated_pi(self) -> None:+ _write_executable(self.bin_dir / "pi.cmd", _batch_client("unrelated-pi"))++ def add_npm_prefix(self, prefix: Path) -> None:+ prefix.mkdir(parents=True)+ self.env["FAKE_NPM_PREFIX"] = str(prefix)+ _write_executable(self.bin_dir / "npm.cmd", _batch_npm())+def add_uv(self, version: str) -> None:_write_executable(self.bin_dir / "uv.cmd", _batch_uv(version))@@ -471,8 +590,9 @@ def powershell_harness(tool_bin = tmp_path / "tool-bin"home = tmp_path / "home"local_app_data = tmp_path / "local-app-data"+ app_data = tmp_path / "app-data"log = tmp_path / "calls.log"- for path in (bin_dir, fixtures, tool_bin, home, local_app_data):+ for path in (bin_dir, fixtures, tool_bin, home, local_app_data, app_data):path.mkdir(parents=True)(fixtures / "claude-command.cmd").write_text(@@ -481,6 +601,7 @@ def powershell_harness((fixtures / "codex-command.cmd").write_text(_batch_client("codex"), encoding="utf-8")+ (fixtures / "pi-command.cmd").write_text(_batch_client("pi"), encoding="utf-8")(fixtures / "uv-command.cmd").write_text(_batch_uv("0.11.28"), encoding="utf-8")(fixtures / "fcc-command.cmd").write_text("""@echo off@@ -507,6 +628,15 @@ $bin = Join-Path $env:LOCALAPPDATA "Programs\OpenAI\Codex\bin"New-Item -ItemType Directory -Force -Path $bin | Out-NullCopy-Item (Join-Path $env:FAKE_FIXTURES "codex-command.cmd") (Join-Path $bin "codex.cmd") -ForceAdd-Content -LiteralPath $env:CALL_LOG -Value "codex-install:$env:CODEX_NON_INTERACTIVE"+""",+ encoding="utf-8",+ )+ (fixtures / "pi-installer.ps1").write_text(+ r"""if ($env:FAIL_STEP -eq "pi-install") { exit 64 }+$bin = if ($env:FAKE_NPM_PREFIX) { $env:FAKE_NPM_PREFIX } else { Join-Path $env:APPDATA "npm" }+New-Item -ItemType Directory -Force -Path $bin | Out-Null+Copy-Item (Join-Path $env:FAKE_FIXTURES "pi-command.cmd") (Join-Path $bin "pi.cmd") -Force+Add-Content -LiteralPath $env:CALL_LOG -Value "pi-install"""",encoding="utf-8",)@@ -532,6 +662,7 @@ function Invoke-RestMethod {if (($env:FAIL_STEP -eq "claude-download" -and $Uri.Contains("claude.ai")) -or($env:FAIL_STEP -eq "codex-download" -and $Uri.Contains("chatgpt.com")) -or+ ($env:FAIL_STEP -eq "pi-download" -and $Uri.Contains("pi.dev")) -or($env:FAIL_STEP -eq "uv-download" -and $Uri.Contains("astral.sh"))) {throw "simulated download failure"@@ -542,6 +673,9 @@ function Invoke-RestMethod {elseif ($Uri.Contains("chatgpt.com")) {$source = Join-Path $env:FAKE_FIXTURES "codex-installer.ps1"}+ elseif ($Uri.Contains("pi.dev")) {+ $source = Join-Path $env:FAKE_FIXTURES "pi-installer.ps1"+ }elseif ($Uri.Contains("astral.sh")) {$source = Join-Path $env:FAKE_FIXTURES "uv-installer.ps1"}@@ -566,6 +700,7 @@ $installer = [scriptblock]::Create([IO.File]::ReadAllText($env:FCC_INSTALLER))"PATHEXT": ".COM;.EXE;.BAT;.CMD","USERPROFILE": str(home),"LOCALAPPDATA": str(local_app_data),+ "APPDATA": str(app_data),"CALL_LOG": str(log),"FAKE_FIXTURES": str(fixtures),"FAKE_TOOL_BIN": str(tool_bin),@@ -588,6 +723,7 @@ def test_install_ps1_fresh_install_is_verified(calls = powershell_harness.calls()assert calls.index("claude-install") < calls.index("claude:--version")assert calls.index("codex-install:1") < calls.index("codex:--version")+ assert calls.index("pi-install") < calls.index("pi:--version")assert calls.index("uv-install") < calls.index("uv:--version")assert any(call.startswith(@@ -610,6 +746,7 @@ def test_install_ps1_preserves_valid_existing_tools() -> None:powershell_harness.add_client("claude")powershell_harness.add_client("codex")+ powershell_harness.add_client("pi")powershell_harness.add_uv("0.11.7")result = powershell_harness.run()@@ -619,11 +756,44 @@ def test_install_ps1_preserves_valid_existing_tools(assert "leaving it unchanged" in result.stdout+def test_install_ps1_replaces_unrelated_pi_command(+ powershell_harness: PowerShellHarness,+) -> None:+ powershell_harness.add_client("claude")+ powershell_harness.add_client("codex")+ powershell_harness.add_unrelated_pi()+ powershell_harness.add_uv("0.11.7")++ result = powershell_harness.run()++ assert result.returncode == 0, result.stderr+ assert "is not Pi Coding Agent; installing Pi" in result.stdout+ assert "pi-install" in powershell_harness.calls()+++def test_install_ps1_discovers_custom_pi_npm_prefix(+ powershell_harness: PowerShellHarness,+) -> None:+ powershell_harness.add_client("claude")+ powershell_harness.add_client("codex")+ powershell_harness.add_npm_prefix(powershell_harness.root / "custom-npm")+ powershell_harness.add_uv("0.11.7")++ result = powershell_harness.run()++ assert result.returncode == 0, result.stderr+ calls = powershell_harness.calls()+ assert "npm:prefix -g" in calls+ assert "pi:--help" in calls+ assert "pi:--version" in calls++def test_install_ps1_replaces_obsolete_uv(powershell_harness: PowerShellHarness,) -> None:powershell_harness.add_client("claude")powershell_harness.add_client("codex")+ powershell_harness.add_client("pi")powershell_harness.add_uv("0.5.9")result = powershell_harness.run()@@ -642,6 +812,9 @@ def test_install_ps1_replaces_obsolete_uv("codex-download","codex-install","codex-verify",+ "pi-download",+ "pi-install",+ "pi-verify","uv-download","uv-install","uv-verify",@@ -665,7 +838,10 @@ def test_install_ps1_stops_without_success_on_each_failure("claude-verify": "chatgpt.com","codex-download": "codex-install","codex-install": "codex:--version",- "codex-verify": "astral.sh",+ "codex-verify": "pi.dev",+ "pi-download": "pi-install",+ "pi-install": "pi:--version",+ "pi-verify": "astral.sh","uv-download": "uv-install","uv-install": "uv:--version","uv-verify": "uv:tool install",@@ -718,6 +894,7 @@ def test_install_ps1_rejects_unparseable_existing_uv() -> None:powershell_harness.add_client("claude")powershell_harness.add_client("codex")+ powershell_harness.add_client("pi")powershell_harness.add_uv("not-a-version")result = powershell_harness.run()@@ -747,6 +924,7 @@ def test_installers_use_native_clients_and_single_python_selection() -> None:for text in (shell, powershell):assert "@anthropic-ai/claude-code" not in textassert "@openai/codex" not in text+ assert "@earendil-works/pi-coding-agent" not in textassert "git+" not in textassert "git --version" not in textassert (@@ -758,6 +936,9 @@ def test_installers_use_native_clients_and_single_python_selection() -> None:assert "tool update-shell" in textassert "--python" in text+ assert "https://pi.dev/install.sh" in shell+ assert "https://pi.dev/install.ps1" in powershell+def test_readme_install_section_has_no_manual_git_prerequisite() -> None:readme = (_repo_root() / "README.md").read_text(encoding="utf-8")diff --git a/tests/scripts/test_uninstallers.py b/tests/scripts/test_uninstallers.pyindex e4d542f0..ebe2287c 100644--- a/tests/scripts/test_uninstallers.py+++ b/tests/scripts/test_uninstallers.py@@ -10,6 +10,7 @@ FCC_COMMANDS = ("fcc-server","fcc-claude","fcc-codex",+ "fcc-pi","fcc-init","free-claude-code",)@@ -84,6 +85,7 @@ def posix_uninstall_harness(tmp_path: Path) -> PosixUninstallHarness:_write_executable(bin_dir / "claude", "#!/bin/sh\nexit 0\n")_write_executable(bin_dir / "codex", "#!/bin/sh\nexit 0\n")+ _write_executable(bin_dir / "pi", "#!/bin/sh\nexit 0\n")_write_executable(bin_dir / "uv","""#!/bin/sh@@ -105,7 +107,7 @@ if [ "${1:-}" = "tool" ] && [ "${2:-}" = "uninstall" ]; thenecho 'Tool `free-claude-code` is not installed' >&2exit 2fi- for name in fcc-server fcc-claude fcc-codex fcc-init free-claude-code; do+ for name in fcc-server fcc-claude fcc-codex fcc-pi fcc-init free-claude-code; do/bin/rm -f "$FAKE_TOOL_BIN/$name"doneecho "Uninstalled free-claude-code"@@ -154,6 +156,7 @@ def test_uninstall_sh_removes_and_verifies_only_fcc(assert (posix_uninstall_harness.bin_dir / "uv").exists()assert (posix_uninstall_harness.bin_dir / "claude").exists()assert (posix_uninstall_harness.bin_dir / "codex").exists()+ assert (posix_uninstall_harness.bin_dir / "pi").exists()assert posix_uninstall_harness.calls() == ["uv:tool dir --bin","uv:tool uninstall free-claude-code",@@ -308,7 +311,7 @@ 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"):+ for name in ("claude", "codex", "pi"):(bin_dir / f"{name}.cmd").write_text("@echo off\nexit /b 0\n", encoding="utf-8")uv_commands = " ".join(FCC_COMMANDS)@@ -398,6 +401,7 @@ def test_uninstall_ps1_removes_and_verifies_only_fcc(assert (powershell_uninstall_harness.bin_dir / "uv.cmd").exists()assert (powershell_uninstall_harness.bin_dir / "claude.cmd").exists()assert (powershell_uninstall_harness.bin_dir / "codex.cmd").exists()+ assert (powershell_uninstall_harness.bin_dir / "pi.cmd").exists()assert powershell_uninstall_harness.calls() == ["uv:tool dir --bin","uv:tool uninstall free-claude-code",diff --git a/uv.lock b/uv.lockindex 9dce648a..abf8d093 100644--- a/uv.lock+++ b/uv.lock@@ -561,7 +561,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "3.5.19"+version = "3.6.0"source = { editable = "." }dependencies = [{ name = "aiohttp" },