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

minor: Bundle RTK and Headroom and fix lock acquisition (#2042)

Ali Khokharbb6166ad6edd
diff --git a/README.md b/README.md
index 32343e24..03b5a1e1 100644
--- a/README.md
+++ b/README.md
@@ -64,7 +64,7 @@ Windows PowerShell:
& ([scriptblock]::Create((irm "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/install.ps1")))
```
-When prompted, choose at least one coding agent and optionally RTK. You can review the installers before running them: [install.sh](scripts/install.sh) and [install.ps1](scripts/install.ps1).
+When prompted, choose at least one coding agent and optionally enable [RTK](https://github.com/rtk-ai/rtk) + [Headroom](https://github.com/headroomlabs-ai/headroom) token optimization for supported agents. You can review the installers before running them: [install.sh](scripts/install.sh) and [install.ps1](scripts/install.ps1).
### 2. Start FCC
@@ -505,7 +505,7 @@ Stop every running FCC command before uninstalling.
**Keeps**
- uv and Python
-- Your coding agents and RTK
+- Your coding agents, RTK, and Headroom
macOS/Linux:
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 25e5e60d..456e5435 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -1,7 +1,7 @@
param(
[switch] $VoiceLocal,
[string] $TorchBackend = "",
- [switch] $Rtk,
+ [switch] $RtkHeadroom,
[switch] $DryRun,
[switch] $Help,
[Parameter(ValueFromRemainingArguments = $true)]
@@ -25,6 +25,7 @@ $DshPackage = "@deepseek-ai/dsh@latest"
$GrokInstallUrl = "https://x.ai/cli/install.ps1"
$MuseInstallUrl = "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/install-muse.ps1"
$RtkVersion = "0.44.2"
+$HeadroomPackage = "headroom-ai[mcp]==0.40.0"
$RtkReleaseBaseUrl = "https://github.com/rtk-ai/rtk/releases/download/v$RtkVersion"
$RtkWindowsAssetName = "rtk-x86_64-pc-windows-msvc.zip"
$RtkWindowsAssetSha256 = "3a1e114edce9080f8a10663e9c87488363a82f14a5ca8aab2ad416817f89d47c"
@@ -41,7 +42,7 @@ $script:InstallMuse = $true
$script:InstallAider = $true
$script:PiAvailable = $false
$script:MuseAvailable = $false
-$script:EnableRtk = $Rtk.IsPresent
+$script:EnableRtkHeadroom = $RtkHeadroom.IsPresent
$script:InstallLog = ""
$script:InstallLogWarning = $false
$script:InstallSteps = [ordered] @{}
@@ -52,6 +53,7 @@ $script:InstallStageNumber = 0
$script:InstallStageCount = 0
$script:FccVerified = $false
$script:DesktopReady = $false
+$script:HeadroomPath = ""
$FccCommands = @(
# Include retired entry points so updates reject older FCC processes before replacement.
"fcc-desktop",
@@ -81,7 +83,7 @@ Installs or updates Free Claude Code and lets you choose which coding agents to
Options:
-VoiceLocal Install local Whisper voice transcription support.
-TorchBackend VALUE Use a uv PyTorch backend, such as cu130. Requires local voice.
- -Rtk Install and configure RTK for the selected coding agents.
+ -RtkHeadroom Install and configure RTK + Headroom token optimization.
-DryRun Print commands without running them.
-Help Show this help text.
"@
@@ -153,7 +155,7 @@ function Get-InstallerRetryCommand {
$options = @()
if ($VoiceLocal) { $options += "-VoiceLocal" }
if ($TorchBackend) { $options += @("-TorchBackend", $TorchBackend) }
- if ($script:EnableRtk) { $options += "-Rtk" }
+ if ($script:EnableRtkHeadroom) { $options += "-RtkHeadroom" }
if ($script:InstallerPath -and (Test-Path -LiteralPath $script:InstallerPath -PathType Leaf)) {
return "& " + (Format-Command $script:InstallerPath $options)
}
@@ -318,16 +320,10 @@ function Select-CodingAgents {
Write-Host ""
}
- if (-not $script:EnableRtk) {
- if (Get-ApplicationCommand "rtk") {
- Write-Host "RTK already installed; will verify."
- $script:EnableRtk = $true
- }
- else {
- $script:EnableRtk = Read-YesNo `
- -Prompt "Enable RTK token optimization globally for the selected coding agents?" `
- -DefaultYes $false
- }
+ if (-not $script:EnableRtkHeadroom) {
+ $script:EnableRtkHeadroom = Read-YesNo `
+ -Prompt "Enable RTK + Headroom token optimization?" `
+ -DefaultYes $false
}
}
@@ -796,7 +792,7 @@ function Ensure-Rtk {
}
function Configure-RtkForSelectedAgents {
- if (-not $script:EnableRtk) {
+ if (-not $script:EnableRtkHeadroom) {
return
}
@@ -818,6 +814,55 @@ function Configure-RtkForSelectedAgents {
}
}
+function Ensure-Headroom {
+ $command = Get-ApplicationCommand "headroom"
+ if ($command) {
+ $script:HeadroomPath = $command.Source
+ Write-Host "Headroom already found on PATH; verifying it without updating it."
+ }
+ else {
+ Invoke-NativeCommand -FilePath "uv" -Arguments @("tool", "install", "--python", $PythonRequest, $HeadroomPackage)
+ if ($DryRun) {
+ $script:HeadroomPath = "<uv-tool-bin>\headroom.exe"
+ }
+ else {
+ $uvCommand = Get-ApplicationCommand "uv"
+ $toolBin = Add-UvToolBinDirectory -UvPath $uvCommand.Source
+ $command = Get-ApplicationCommand "headroom"
+ if (-not $command -or (Split-Path -Parent $command.Source) -ne $toolBin) {
+ throw "Headroom installation did not create its command in the uv tool bin directory."
+ }
+ $script:HeadroomPath = $command.Source
+ }
+ }
+ Invoke-NativeCommand -FilePath $script:HeadroomPath -Arguments @("--version")
+ Invoke-NativeCommand -FilePath $script:HeadroomPath -Arguments @("mcp", "install", "--help")
+}
+
+function Configure-HeadroomForSelectedAgents {
+ # Headroom 0.40.0's OpenCode registrar uses the pre-v2 schema.
+ Write-Host "Headroom setup supports Claude Code, Codex, and Grok. Other selected agents are skipped."
+ $agents = @()
+ if ($script:InstallClaudeCode) { $agents += "claude" }
+ if ($script:InstallCodex) { $agents += "codex" }
+ if ($script:InstallGrok) { $agents += "grok" }
+ if ($agents.Count -eq 0) {
+ Write-Host "Headroom registration skipped: no supported agents selected."
+ return
+ }
+ $previousPath = $env:PATH
+ try {
+ # Upstream resolves the server executable from PATH.
+ $env:PATH = (Split-Path -Parent $script:HeadroomPath) + [IO.Path]::PathSeparator + $env:PATH
+ foreach ($agent in $agents) {
+ Invoke-NativeCommand -FilePath $script:HeadroomPath -Arguments @("mcp", "install", "--agent", $agent)
+ }
+ }
+ finally {
+ $env:PATH = $previousPath
+ }
+}
+
function Ensure-ClaudeCode {
if (Get-ApplicationCommand "claude") {
$script:InstallStepOutcome = "Reused"
@@ -1897,14 +1942,18 @@ try {
foreach ($name in @("FCC package", "PATH configuration", "FCC verification", "Desktop integration")) {
$script:InstallSteps[$name] = "Not attempted"
}
- if ($script:EnableRtk) { $script:InstallSteps["RTK configuration"] = "Not attempted" }
+ if ($script:EnableRtkHeadroom) {
+ $script:InstallSteps["Headroom verification"] = "Not attempted"
+ $script:InstallSteps["RTK configuration"] = "Not attempted"
+ $script:InstallSteps["Headroom configuration"] = "Not attempted"
+ }
Write-Host "`nInstallation plan:"
Write-Host " Install or update Free Claude Code."
Write-Host " Verify or install: $($selectedAgents -join ', ')."
if ($VoiceLocal) { Write-Host " Include local voice support." }
if ($TorchBackend) { Write-Host " PyTorch backend: $TorchBackend" }
- if ($script:EnableRtk) { Write-Host " Configure RTK for the selected agents." }
+ if ($script:EnableRtkHeadroom) { Write-Host " Run RTK + Headroom setup for supported selected agents." }
Write-Host "Press Ctrl+C to cancel. You can rerun the installer afterward."
$script:InstallStageCount = $script:InstallSteps.Count - 1
@@ -1920,9 +1969,13 @@ try {
Configure-AndConfirmFreeClaudeCode
- if ($script:EnableRtk) {
+ if ($script:EnableRtkHeadroom) {
+ Start-InstallStep "Headroom verification"
+ Ensure-Headroom
Start-InstallStep "RTK configuration"
Configure-RtkForSelectedAgents
+ Start-InstallStep "Headroom configuration"
+ Configure-HeadroomForSelectedAgents
}
Complete-InstallStep
$installSucceeded = $true
diff --git a/scripts/install.sh b/scripts/install.sh
index 2f991af2..20c0c5b9 100644
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -13,6 +13,7 @@ DSH_PACKAGE="@deepseek-ai/dsh@latest"
GROK_INSTALL_URL="https://x.ai/cli/install.sh"
MUSE_INSTALL_URL="https://dev.meta.ai/install.sh"
RTK_VERSION="0.44.2"
+HEADROOM_PACKAGE="headroom-ai[mcp]==0.40.0"
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"
@@ -32,13 +33,14 @@ install_dsh=1
install_grok=1
install_muse=1
install_aider=1
-enable_rtk=0
+enable_rtk_headroom=0
torch_backend=""
temporary_file=""
temporary_binary=""
tool_bin=""
pi_available=0
rtk_path=""
+headroom_path=""
install_log=""
install_log_warning=0
install_report_started=0
@@ -66,7 +68,7 @@ Installs or updates Free Claude Code and lets you choose which coding agents to
Options:
--voice-local Install local Whisper voice transcription support.
--torch-backend VALUE Use a uv PyTorch backend, such as cu130. Requires local voice.
- --rtk Install and configure RTK for the selected coding agents.
+ --rtk-headroom Install and configure RTK + Headroom token optimization.
--dry-run Print commands without running them.
--help Show this help text.
USAGE
@@ -145,7 +147,7 @@ print_installer_retry() {
printf ' --torch-backend '
shell_quote "$torch_backend"
fi
- [ "$enable_rtk" -eq 0 ] || printf ' --rtk'
+ [ "$enable_rtk_headroom" -eq 0 ] || printf ' --rtk-headroom'
printf '\n'
}
@@ -328,12 +330,9 @@ choose_coding_agents() {
printf 'Select at least one coding agent.\n\n' >&4
done
- if [ "$enable_rtk" -eq 0 ]; then
- if command -v rtk >/dev/null 2>&1; then
- printf 'RTK already installed; will verify.\n' >&4
- enable_rtk=1
- elif prompt_yes_no "Enable RTK token optimization globally for the selected coding agents?" no; then
- enable_rtk=1
+ if [ "$enable_rtk_headroom" -eq 0 ]; then
+ if prompt_yes_no "Enable RTK + Headroom token optimization?" no; then
+ enable_rtk_headroom=1
fi
fi
@@ -769,7 +768,7 @@ ensure_rtk_claude_config_directory() {
}
configure_rtk_for_selected_agents() {
- [ "$enable_rtk" -eq 1 ] || return 0
+ [ "$enable_rtk_headroom" -eq 1 ] || return 0
step "Installing and configuring RTK token optimization"
ensure_rtk
@@ -789,6 +788,41 @@ configure_rtk_for_selected_agents() {
fi
}
+ensure_headroom() {
+ if command -v headroom >/dev/null 2>&1; then
+ headroom_path=$(command -v headroom)
+ printf 'Headroom already found on PATH; verifying it without updating it.\n'
+ else
+ run uv tool install --python "$PYTHON_VERSION" "$HEADROOM_PACKAGE"
+ if [ "$dry_run" -eq 1 ]; then
+ headroom_path="<uv-tool-bin>/headroom"
+ else
+ add_uv_tool_bin_directory
+ headroom_path="$tool_bin/headroom"
+ [ -x "$headroom_path" ] || fail "Headroom installation did not create $headroom_path."
+ fi
+ fi
+ run "$headroom_path" --version
+ run "$headroom_path" mcp install --help
+}
+
+configure_headroom_for_selected_agents() {
+ # Headroom 0.40.0's OpenCode registrar uses the pre-v2 schema.
+ printf 'Headroom setup supports Claude Code, Codex, and Grok. Other selected agents are skipped.\n'
+ set --
+ [ "$install_claude" -eq 0 ] || set -- "$@" claude
+ [ "$install_codex" -eq 0 ] || set -- "$@" codex
+ [ "$install_grok" -eq 0 ] || set -- "$@" grok
+ if [ "$#" -eq 0 ]; then
+ printf 'Headroom registration skipped: no supported agents selected.\n'
+ return 0
+ fi
+ for headroom_agent in "$@"; do
+ # Upstream resolves the server executable from PATH.
+ run env "PATH=$(dirname "$headroom_path"):$PATH" "$headroom_path" mcp install --agent "$headroom_agent"
+ done
+}
+
ensure_claude() {
if command -v claude >/dev/null 2>&1; then
install_step_outcome=Reused
@@ -1433,8 +1467,8 @@ parse_args() {
torch_backend=${1#*=}
[ -n "$torch_backend" ] || fail "--torch-backend requires a non-empty value."
;;
- --rtk)
- enable_rtk=1
+ --rtk-headroom)
+ enable_rtk_headroom=1
;;
--dry-run)
dry_run=1
@@ -1677,11 +1711,11 @@ done
printf '\n'
[ "$voice_local" -eq 0 ] || printf ' Include local voice support.\n'
[ -z "$torch_backend" ] || printf ' PyTorch backend: %s\n' "$torch_backend"
-[ "$enable_rtk" -eq 0 ] || printf ' Configure RTK for the selected agents.\n'
+[ "$enable_rtk_headroom" -eq 0 ] || printf ' Run RTK + Headroom setup for supported selected agents.\n'
printf 'Press Ctrl+C to cancel. You can rerun the installer afterward.\n'
pending_steps=$(printf 'uv\n%s\nFCC package\nPATH configuration\nFCC verification\n' "$pending_steps"
[ "$(uname -s)" != Darwin ] || printf 'Desktop integration\n'
- [ "$enable_rtk" -eq 0 ] || printf 'RTK configuration\n'
+ [ "$enable_rtk_headroom" -eq 0 ] || printf 'Headroom verification\nRTK configuration\nHeadroom configuration\n'
)
install_stage_count=$(printf '%s\n' "$pending_steps" | wc -l)
@@ -1692,7 +1726,7 @@ if [ "$install_claude" -eq 1 ] || [ "$install_opencode" -eq 1 ] || [ "$install_h
fi
require_command sh
require_command mktemp
-if [ "$enable_rtk" -eq 1 ] && ! command -v rtk >/dev/null 2>&1; then
+if [ "$enable_rtk_headroom" -eq 1 ] && ! command -v rtk >/dev/null 2>&1; then
require_command tar
if [ "$dry_run" -eq 0 ] &&
! command -v sha256sum >/dev/null 2>&1 &&
@@ -1711,7 +1745,7 @@ if [ "$dry_run" -eq 0 ]; then
fi
if [ "$install_hermes" -eq 1 ] && ! command -v hermes >/dev/null 2>&1; then confirm_hermes_platform; fi
if [ "$install_opencode" -eq 1 ]; then check_opencode_install; fi
- if [ "$enable_rtk" -eq 1 ] && ! command -v rtk >/dev/null 2>&1; then select_rtk_release; fi
+ if [ "$enable_rtk_headroom" -eq 1 ] && ! command -v rtk >/dev/null 2>&1; then select_rtk_release; fi
fi
start_install_step uv "Ensuring uv $MIN_UV_VERSION or newer is installed"
@@ -1729,9 +1763,13 @@ if [ "$(uname -s)" = "Darwin" ]; then
install_macos_desktop_app
desktop_ready=1
fi
-if [ "$enable_rtk" -eq 1 ]; then
+if [ "$enable_rtk_headroom" -eq 1 ]; then
+ start_install_step "Headroom verification"
+ ensure_headroom
start_install_step "RTK configuration"
configure_rtk_for_selected_agents
+ start_install_step "Headroom configuration"
+ configure_headroom_for_selected_agents
fi
complete_install_step
diff --git a/smoke/installers/test_installers.py b/smoke/installers/test_installers.py
index 9e1fe7dd..5988c49b 100644
--- a/smoke/installers/test_installers.py
+++ b/smoke/installers/test_installers.py
@@ -46,6 +46,146 @@ CODING_AGENTS = (
)
+def test_install_ps1_bundle_dry_run_includes_headroom(powershell_harness):
+ result = powershell_harness.run("-RtkHeadroom", "-DryRun")
+ assert result.returncode == 0, result.stderr
+ assert "headroom-ai[mcp]==0.40.0" in result.stdout
+ assert "mcp install --agent claude" in result.stdout
+ assert "_fcc-configure-headroom" not in result.stdout
+ assert not any("headroom-ai" in call for call in powershell_harness.calls())
+
+
+def test_install_sh_bundle_dry_run_includes_headroom(posix_harness):
+ result = posix_harness.run("--rtk-headroom", "--dry-run")
+ assert result.returncode == 0, result.stderr
+ assert "headroom-ai[mcp]==0.40.0" in result.stdout
+ assert "mcp install --agent claude" in result.stdout
+ assert "_fcc-configure-headroom" not in result.stdout
+ assert not any("headroom-ai" in call for call in posix_harness.calls())
+
+
+def _assert_headroom_bundle_workflow(harness, failure, reuse):
+ windows = isinstance(harness, PowerShellHarness)
+ for agent in CODING_AGENTS:
+ harness.add_client(agent)
+ harness.add_uv("0.12.13")
+ harness.add_rtk()
+ if reuse:
+ harness.add_client("headroom")
+ flag = "-RtkHeadroom" if windows else "--rtk-headroom"
+ result = harness.run(flag, fail_step=failure)
+ calls = harness.calls()
+ package = [call for call in calls if "headroom-ai[mcp]" in call]
+ setup = [call for call in calls if call.startswith("headroom:mcp install --agent")]
+ rtk = [call for call in calls if call.startswith("rtk:init")]
+ assert bool(package) is (not reuse)
+ if failure:
+ assert result.returncode != 0, result.stdout + result.stderr
+ stage = (
+ "Headroom configuration"
+ if failure == "headroom-configure"
+ else "Headroom verification"
+ )
+ assert f"Failed: {stage}" in result.stdout
+ assert flag in result.stdout.split("Retry:", 1)[1]
+ if failure in {"headroom-install", "headroom-check"}:
+ assert not rtk and not setup
+ else:
+ assert rtk and setup == [
+ "headroom:mcp install --agent claude",
+ "headroom:mcp install --agent codex",
+ ]
+ offset = len(calls)
+ result = harness.run(flag)
+ assert result.returncode == 0, result.stdout + result.stderr
+ calls = harness.calls()[offset:]
+ setup = [
+ call for call in calls if call.startswith("headroom:mcp install --agent")
+ ]
+ rtk = [call for call in calls if call.startswith("rtk:init")]
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert setup == [
+ f"headroom:mcp install --agent {agent}" for agent in ("claude", "codex", "grok")
+ ]
+ assert (
+ calls.index("headroom:--version") < calls.index(rtk[0]) < calls.index(setup[0])
+ )
+ assert not any("_fcc-configure-headroom" in call for call in calls)
+
+
+ ("failure", "reuse"),
+ [
+ ("", False),
+ ("", True),
+ ("headroom-install", False),
+ ("headroom-check", False),
+ ("headroom-configure", False),
+ ],
+)
+def test_install_ps1_headroom_bundle_workflow(powershell_harness, failure, reuse):
+ _assert_headroom_bundle_workflow(powershell_harness, failure, reuse)
+
+
+ ("failure", "reuse"),
+ [
+ ("", False),
+ ("", True),
+ ("headroom-install", False),
+ ("headroom-check", False),
+ ("headroom-configure", False),
+ ],
+)
+def test_install_sh_headroom_bundle_workflow(posix_harness, failure, reuse):
+ _assert_headroom_bundle_workflow(posix_harness, failure, reuse)
+
+
[email protected]("selected", ["claude", "codex", "grok", "unsupported"])
+def test_install_sh_headroom_native_selection(posix_harness, selected):
+ posix_harness.add_client("headroom")
+ flags = "\n".join(f"install_{name}=0" for name in ("claude", "codex", "grok"))
+ if selected != "unsupported":
+ flags += f"\ninstall_{selected}=1"
+ result = posix_harness.run_functions(
+ flags
+ + "\nheadroom_path=$(command -v headroom)\nconfigure_headroom_for_selected_agents"
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert posix_harness.calls() == (
+ []
+ if selected == "unsupported"
+ else [f"headroom:mcp install --agent {selected}"]
+ )
+ if selected == "unsupported":
+ assert "skip" in result.stdout.lower()
+
+
[email protected]("selected", ["claude", "codex", "grok", "unsupported"])
+def test_install_ps1_headroom_native_selection(powershell_harness, selected):
+ powershell_harness.add_client("headroom")
+ variables = {
+ "claude": "InstallClaudeCode",
+ "codex": "InstallCodex",
+ "grok": "InstallGrok",
+ }
+ flags = "\n".join(f"$script:{name} = $false" for name in variables.values())
+ if selected != "unsupported":
+ flags += f"\n$script:{variables[selected]} = $true"
+ result = powershell_harness.run_functions(
+ flags
+ + '\n$script:HeadroomPath = (Get-ApplicationCommand "headroom").Source\nConfigure-HeadroomForSelectedAgents'
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert powershell_harness.calls() == (
+ []
+ if selected == "unsupported"
+ else [f"headroom:mcp install --agent {selected}"]
+ )
+ if selected == "unsupported":
+ assert "skip" in result.stdout.lower()
+
+
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
@@ -112,6 +252,10 @@ if [ "{name}" = "opencode" ] && [ "${{FCC_RUNNING_PHASE:-}}" = "opencode-plugin"
: > "$FCC_PROCESS_MARKER.probed"
fi
fi
+if [ "{name}" = "headroom" ]; then
+ [ "$FAIL_STEP" != "headroom-check" ] || exit 79
+ if [ "$FAIL_STEP" = "headroom-configure" ] && [ "${{4:-}}" = "codex" ]; then exit 80; fi
+fi
if [ "$FAIL_STEP" = "{name}-verify" ]; then
exit 31
fi
@@ -167,6 +311,13 @@ if [ "${{1:-}}" = "--version" ]; then
fi
if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "install" ]; then
case " $* " in
+ *" headroom-ai[mcp]==0.40.0 "*)
+ [ "$FAIL_STEP" = "headroom-install" ] && exit 78
+ mkdir -p "$tool_bin"
+ cp "$FAKE_FIXTURES/headroom-command.sh" "$tool_bin/headroom"
+ chmod +x "$tool_bin/headroom"
+ exit 0
+ ;;
*" aider-chat@latest "*)
if [ "$FAIL_STEP" = "aider-install" ]; then
exit 29
@@ -588,6 +739,7 @@ chmod +x "$uv_bin/uv"
metadata.size = len(rtk_command)
archive.addfile(metadata, io.BytesIO(rtk_command))
_write_executable(fixtures / "uv-command.sh", _posix_uv_command("0.12.13"))
+ _write_executable(fixtures / "headroom-command.sh", _posix_command("headroom"))
_write_executable(
fixtures / "fcc-command.sh",
"""#!/bin/sh
@@ -675,18 +827,20 @@ def test_install_sh_auto_selects_installed_harnesses(
posix_harness.add_client(command)
result = posix_harness.run_interactive(
- "\n" if rtk is None else "", *(("--rtk",) if rtk else ())
+ "" if rtk else "\n", *(("--rtk-headroom",) if rtk else ())
)
assert result.returncode == 0, result.stdout
assert "Install or verify" not in result.stdout
assert "for fcc-" not in result.stdout
- assert ("Enable RTK token optimization" in result.stdout) is (rtk is None)
+ assert ("Enable RTK + Headroom token optimization" in result.stdout) is (
+ rtk is not True
+ )
for command in CODING_AGENTS:
assert f"{command}:--version" in posix_harness.calls()
- assert ("rtk:--version:telemetry=1" in posix_harness.calls()) is (rtk is not None)
+ assert ("rtk:--version:telemetry=1" in posix_harness.calls()) is (rtk is True)
assert ("rtk:init --global --codex:telemetry=1" in posix_harness.calls()) is (
- rtk is not None
+ rtk is True
)
@@ -700,7 +854,7 @@ def test_install_sh_asks_only_about_missing_harnesses(
posix_harness.add_rtk()
result = posix_harness.run_interactive(
- ("y\n" if install_codex else "\n") + "\n" * (7 if rtk else 8)
+ ("y\n" if install_codex else "\n") + "\n" * 8
)
assert result.returncode == 0, result.stdout
@@ -719,12 +873,8 @@ def test_install_sh_asks_only_about_missing_harnesses(
assert "opencode:--version" in calls
assert ("codex-install:1" in calls) is install_codex
assert not any(f"{command}:--version" in calls for command in CODING_AGENTS[4:])
- assert ("Enable RTK token optimization" in result.stdout) is not rtk
- assert ("rtk:init --global --codex:telemetry=1" in calls) is (rtk and install_codex)
- if rtk and install_codex:
- assert calls.index("codex:--version") < calls.index(
- "rtk:init --global --codex:telemetry=1"
- )
+ assert "Enable RTK + Headroom token optimization" in result.stdout
+ assert not any(call.startswith("rtk:init") for call in calls)
def test_install_sh_discovers_installed_npm_harnesses_before_questions(
@@ -1201,7 +1351,7 @@ def test_install_sh_stops_when_selected_dsh_install_fails(
def test_install_sh_installs_and_configures_rtk_for_selected_agents(
posix_harness: PosixHarness,
) -> None:
- result = posix_harness.run("--rtk")
+ result = posix_harness.run("--rtk-headroom")
assert result.returncode == 0, result.stderr
calls = posix_harness.calls()
@@ -1234,7 +1384,7 @@ def test_install_sh_prepares_custom_claude_config_directory_for_rtk(
custom_config = posix_harness.root / "custom-claude"
posix_harness.env["CLAUDE_CONFIG_DIR"] = str(custom_config)
- result = posix_harness.run("--rtk")
+ result = posix_harness.run("--rtk-headroom")
assert result.returncode == 0, result.stderr
assert custom_config.is_dir()
@@ -1259,7 +1409,7 @@ def test_install_sh_selects_pinned_rtk_release_for_platform(
posix_harness.env["FAKE_UNAME"] = system
posix_harness.env["FAKE_UNAME_MACHINE"] = machine
- result = posix_harness.run("--rtk", "--dry-run")
+ result = posix_harness.run("--rtk-headroom", "--dry-run")
assert result.returncode == 0, result.stderr
assert f"rtk-ai/rtk/releases/download/v0.44.2/{asset}" in result.stdout
@@ -1273,7 +1423,7 @@ def test_install_sh_rejects_unsupported_rtk_platform(
posix_harness.env["FAKE_UNAME"] = "FreeBSD"
posix_harness.env["FAKE_UNAME_MACHINE"] = "riscv64"
- result = posix_harness.run("--rtk", "--dry-run")
+ result = posix_harness.run("--rtk-headroom", "--dry-run")
assert result.returncode != 0
assert "does not provide a release for FreeBSD riscv64" in result.stderr
@@ -1300,7 +1450,7 @@ def test_install_sh_rejects_conflicting_rtk_command(
) -> None:
posix_harness.add_unrelated_rtk()
- result = posix_harness.run("--rtk")
+ result = posix_harness.run("--rtk-headroom")
assert result.returncode != 0
assert "not a compatible Rust Token Killer installation" in result.stderr
@@ -1323,7 +1473,7 @@ def test_install_sh_stops_when_rtk_setup_fails(
posix_harness: PosixHarness,
failure: str,
) -> None:
- result = posix_harness.run("--rtk", fail_step=failure)
+ result = posix_harness.run("--rtk-headroom", fail_step=failure)
assert result.returncode != 0
assert "Free Claude Code is installed and verified." in result.stdout
@@ -2051,6 +2201,8 @@ if "{name}"=="opencode" if "%FCC_RUNNING_PHASE%"=="opencode-plugin" (
type nul > "%FCC_PROCESS_MARKER%.probed"
)
)
+if "{name}"=="headroom" if "%FAIL_STEP%"=="headroom-check" exit /b 79
+if "{name}"=="headroom" if "%FAIL_STEP%"=="headroom-configure" if "%4"=="codex" exit /b 80
if "%FAIL_STEP%"=="{name}-verify" exit /b 51
{version_command}
if "%1"=="--help" (
@@ -2098,6 +2250,8 @@ echo uv {version}
exit /b 0
:install
if "%5"=="python3.12" goto install_aider
+if "%5"=="headroom-ai[mcp]==0.40.0" goto install_headroom
+if "%5"=="headroom-ai[mcp]" goto install_headroom
if "%FAIL_STEP%"=="fcc-install" exit /b 53
if not exist "%UV_BIN_DIR%" mkdir "%UV_BIN_DIR%"
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-server.cmd" >nul
@@ -2120,6 +2274,11 @@ if "%FAIL_STEP%"=="aider-install" exit /b 57
if not exist "%UV_BIN_DIR%" mkdir "%UV_BIN_DIR%"
copy /y "%FAKE_FIXTURES%\aider-command.cmd" "%UV_BIN_DIR%\aider.cmd" >nul
exit /b 0
+:install_headroom
+if "%FAIL_STEP%"=="headroom-install" exit /b 78
+if not exist "%UV_BIN_DIR%" mkdir "%UV_BIN_DIR%"
+copy /y "%FAKE_FIXTURES%\headroom-command.cmd" "%UV_BIN_DIR%\headroom.cmd" >nul
+exit /b 0
:update_shell
if "%FAIL_STEP%"=="path-update" exit /b 54
exit /b 0
@@ -2282,6 +2441,9 @@ def powershell_harness(
)
(fixtures / "rtk-command.cmd").write_text(_batch_rtk(), encoding="utf-8")
(fixtures / "uv-command.cmd").write_text(_batch_uv("0.12.13"), encoding="utf-8")
+ (fixtures / "headroom-command.cmd").write_text(
+ _batch_client("headroom"), encoding="utf-8"
+ )
(fixtures / "fcc-command.cmd").write_text(
"""@echo off
for %%I in ("%~f0") do set "FCC_NAME=%%~nI"
@@ -2673,21 +2835,21 @@ def test_install_ps1_auto_selects_installed_harnesses(
powershell_harness.add_client(command)
result = powershell_harness.run_interactive(
- [""] if rtk is None else [], *(("-Rtk",) if rtk else ())
+ [] if rtk else [""], *(("-RtkHeadroom",) if rtk else ())
)
assert result.returncode == 0, result.stderr
assert "Install or verify" not in result.stdout
assert "for fcc-" not in result.stdout
- assert ("Enable RTK token optimization" in result.stdout) is (rtk is None)
+ assert ("Enable RTK + Headroom token optimization" in result.stdout) is (
+ rtk is not True
+ )
for command in CODING_AGENTS:
assert f"{command}:--version" in powershell_harness.calls()
assert "muse-install:external" in powershell_harness.calls()
- assert ("rtk:--version:telemetry=1" in powershell_harness.calls()) is (
- rtk is not None
- )
+ assert ("rtk:--version:telemetry=1" in powershell_harness.calls()) is (rtk is True)
assert ("rtk:init --global --codex:telemetry=1" in powershell_harness.calls()) is (
- rtk is not None
+ rtk is True
)
@@ -2701,7 +2863,7 @@ def test_install_ps1_asks_only_about_missing_harnesses(
powershell_harness.add_rtk()
result = powershell_harness.run_interactive(
- ["y" if install_codex else ""] + [""] * (7 if rtk else 8)
+ ["y" if install_codex else ""] + [""] * 8
)
assert result.returncode == 0, result.stderr
@@ -2720,12 +2882,8 @@ def test_install_ps1_asks_only_about_missing_harnesses(
assert "opencode:--version" in calls
assert ("codex-install:1" in calls) is install_codex
assert not any(f"{command}:--version" in calls for command in CODING_AGENTS[4:])
- assert ("Enable RTK token optimization" in result.stdout) is not rtk
- assert ("rtk:init --global --codex:telemetry=1" in calls) is (rtk and install_codex)
- if rtk and install_codex:
- assert calls.index("codex:--version") < calls.index(
- "rtk:init --global --codex:telemetry=1"
- )
+ assert "Enable RTK + Headroom token optimization" in result.stdout
+ assert not any(call.startswith("rtk:init") for call in calls)
def test_install_ps1_discovers_installed_npm_harnesses_before_questions(
@@ -3609,7 +3767,7 @@ def test_install_ps1_preserves_existing_rtk_and_configures_selected_agents(
) -> None:
powershell_harness.add_rtk()
- result = powershell_harness.run("-Rtk")
+ result = powershell_harness.run("-RtkHeadroom")
assert result.returncode == 0, result.stderr
assert "verifying it without updating it" in result.stdout
@@ -3634,7 +3792,8 @@ def test_install_ps1_prepares_custom_claude_config_directory_for_rtk(
powershell_harness.env["CLAUDE_CONFIG_DIR"] = str(custom_config)
result = powershell_harness.run_functions(
- "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-RtkClaudeConfigDirectory", "-Rtk"
+ "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-RtkClaudeConfigDirectory",
+ "-RtkHeadroom",
)
assert result.returncode == 0, result.stderr
@@ -3649,7 +3808,7 @@ def test_install_ps1_rejects_conflicting_rtk_command(
powershell_harness.add_unrelated_rtk()
result = powershell_harness.run_functions(
- "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Rtk", "-Rtk"
+ "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Rtk", "-RtkHeadroom"
)
assert result.returncode != 0
@@ -3661,7 +3820,7 @@ def test_install_ps1_rejects_conflicting_rtk_command(
def test_install_ps1_rtk_dry_run_prints_install_and_agent_setup(
powershell_harness: PowerShellHarness,
) -> None:
- result = powershell_harness.run("-Rtk", "-DryRun")
+ result = powershell_harness.run("-RtkHeadroom", "-DryRun")
assert result.returncode == 0, result.stderr
assert powershell_harness.calls() == []
@@ -4375,7 +4534,7 @@ $script:InstallDsh = $true
$script:InstallGrok = $true
$script:InstallMuse = $true
$script:InstallAider = $true
-$script:EnableRtk = $false
+$script:EnableRtkHeadroom = $false
function Read-Host {{
param([string] $Prompt)
$answer = $script:Answers[$script:AnswerIndex]
@@ -4386,7 +4545,7 @@ function Read-YesNo {{{read_yes_no}}}
function Read-CodingAgentSelection {{{read_selection}}}
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:InstallGrok),$($script:InstallMuse),$($script:InstallAider),$($script:EnableRtk)"
+Write-Output "selection:$($script:InstallClaudeCode),$($script:InstallCodex),$($script:InstallPi),$($script:InstallOpenCode),$($script:InstallCline),$($script:InstallHermes),$($script:InstallDsh),$($script:InstallGrok),$($script:InstallMuse),$($script:InstallAider),$($script:EnableRtkHeadroom)"
"""
result = subprocess.run(
@@ -4448,7 +4607,7 @@ def test_install_ps1_configures_rtk_only_for_available_selected_agents(
body = _braced_body(text, "function Configure-RtkForSelectedAgents")
script = f"""Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
-$script:EnableRtk = $true
+$script:EnableRtkHeadroom = $true
$script:InstallClaudeCode = $false
$script:InstallCodex = $true
$script:InstallPi = $true
@@ -5119,9 +5278,9 @@ def _assert_installer_recovers_after_verification_failure(
harness.add_rtk()
home = Path(harness.env["USERPROFILE" if windows else "HOME"])
options = (
- ("-Rtk", "-VoiceLocal", "-TorchBackend", "cu130")
+ ("-RtkHeadroom", "-VoiceLocal", "-TorchBackend", "cu130")
if windows
- else ("--rtk", "--voice-local", "--torch-backend", "cu130")
+ else ("--rtk-headroom", "--voice-local", "--torch-backend", "cu130")
)
failed = harness.run(*options, fail_step="fcc-verify")
@@ -5280,9 +5439,9 @@ def test_install_ps1_retry_command_preserves_literal_options_and_path(
script = powershell_harness.root / "install ' & café.ps1"
output = powershell_harness.root / "retry-options.json"
script.write_text(
- "param([switch] $VoiceLocal, [string] $TorchBackend, [switch] $Rtk)\n"
+ "param([switch] $VoiceLocal, [string] $TorchBackend, [switch] $RtkHeadroom)\n"
"[IO.File]::WriteAllText($env:TEST_RETRY_OUTPUT, "
- "(ConvertTo-Json @($VoiceLocal.IsPresent, $TorchBackend, $Rtk.IsPresent)), [Text.Encoding]::UTF8)\n",
+ "(ConvertTo-Json @($VoiceLocal.IsPresent, $TorchBackend, $RtkHeadroom.IsPresent)), [Text.Encoding]::UTF8)\n",
encoding="utf-8-sig",
)
backend = "cu'130 $literal; &(literal)"
@@ -5295,7 +5454,7 @@ def test_install_ps1_retry_command_preserves_literal_options_and_path(
"-VoiceLocal",
"-TorchBackend",
backend,
- "-Rtk",
+ "-RtkHeadroom",
)
assert result.returncode == 0, result.stderr
assert json.loads(output.read_text(encoding="utf-8-sig")) == [True, backend, True]
@@ -5314,7 +5473,7 @@ def test_install_sh_retry_command_preserves_literal_options_and_path(
TEST_BACKEND=backend,
)
result = posix_harness.run_functions(
- "installer_path=$TEST_RETRY_PATH\nvoice_local=1\nenable_rtk=1\ntorch_backend=$TEST_BACKEND\n"
+ "installer_path=$TEST_RETRY_PATH\nvoice_local=1\nenable_rtk_headroom=1\ntorch_backend=$TEST_BACKEND\n"
'retry=$(print_installer_retry)\neval "${retry#Retry: }"'
)
assert result.returncode == 0, result.stderr
@@ -5322,7 +5481,7 @@ def test_install_sh_retry_command_preserves_literal_options_and_path(
"--voice-local",
"--torch-backend",
backend,
- "--rtk",
+ "--rtk-headroom",
]
@@ -5479,7 +5638,9 @@ def _assert_installer_keeps_launch_instructions_after_rtk_failure(
harness.add_client(command)
harness.add_uv("0.12.13")
harness.add_rtk()
- result = harness.run("-Rtk" if windows else "--rtk", fail_step="rtk-init-claude")
+ result = harness.run(
+ "-RtkHeadroom" if windows else "--rtk-headroom", fail_step="rtk-init-claude"
+ )
assert result.returncode != 0
assert "Free Claude Code is installed and verified." in result.stdout
assert "Run Claude Code with: fcc-claude" in result.stdout
diff --git a/src/free_claude_code/core/interprocess_lock.py b/src/free_claude_code/core/interprocess_lock.py
index 0edef57c..af8c7562 100644
--- a/src/free_claude_code/core/interprocess_lock.py
+++ b/src/free_claude_code/core/interprocess_lock.py
@@ -9,10 +9,7 @@ if os.name == "nt":
import msvcrt
def _try_lock(handle: BinaryIO) -> bool:
- if os.fstat(handle.fileno()).st_size == 0:
- handle.seek(0)
- handle.write(b"\0")
- handle.flush()
+ # Windows can lock beyond EOF, so no initialization write is needed.
handle.seek(0)
try:
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
@@ -60,14 +57,17 @@ class InterprocessFileLock:
raise ValueError("timeout must be non-negative")
self._path.parent.mkdir(parents=True, exist_ok=True)
handle = self._path.open("a+b")
- deadline = None if timeout is None else time.monotonic() + timeout
- while not _try_lock(handle):
- if not wait or (deadline is not None and time.monotonic() >= deadline):
+ try:
+ deadline = None if timeout is None else time.monotonic() + timeout
+ while not _try_lock(handle):
+ if not wait or (deadline is not None and time.monotonic() >= deadline):
+ return False
+ time.sleep(poll_interval)
+ self._handle = handle
+ return True
+ finally:
+ if self._handle is not handle:
handle.close()
- return False
- time.sleep(poll_interval)
- self._handle = handle
- return True
def release(self) -> None:
"""Release a held lock; repeated calls are harmless."""
diff --git a/tests/core/test_interprocess_lock.py b/tests/core/test_interprocess_lock.py
new file mode 100644
index 00000000..9052d1ef
--- /dev/null
+++ b/tests/core/test_interprocess_lock.py
@@ -0,0 +1,74 @@
+import os
+
+import pytest
+
+from free_claude_code.core import interprocess_lock
+
+
[email protected]("stage", ["acquire", "wait"])
[email protected]("error_type", [PermissionError, KeyboardInterrupt])
+def test_failed_acquisition_closes_handle_and_allows_retry(
+ tmp_path, monkeypatch, stage, error_type
+):
+ lock = interprocess_lock.InterprocessFileLock(tmp_path / "lock")
+ opened = []
+ failure = error_type("acquisition interrupted")
+
+ def try_lock(handle):
+ opened.append(handle)
+ if stage == "acquire":
+ raise failure
+ return False
+
+ def sleep(_):
+ raise failure
+
+ try:
+ with monkeypatch.context() as patch:
+ patch.setattr(interprocess_lock, "_try_lock", try_lock)
+ patch.setattr(interprocess_lock.time, "sleep", sleep)
+ with pytest.raises(error_type) as caught:
+ lock.acquire(wait=stage == "wait")
+ assert caught.value is failure
+ assert opened[0].closed
+ assert lock.acquire()
+ finally:
+ lock.release()
+ for handle in opened:
+ handle.close()
+
+
+def test_empty_file_locked_by_another_handle_is_normal_contention(
+ tmp_path, monkeypatch
+):
+ if os.name != "nt":
+ pytest.skip("Windows byte-range locking")
+
+ import msvcrt
+
+ path = tmp_path / "lock"
+ contender = interprocess_lock.InterprocessFileLock(path)
+ opened = []
+ try_lock = interprocess_lock._try_lock
+
+ def capture(handle):
+ opened.append(handle)
+ return try_lock(handle)
+
+ monkeypatch.setattr(interprocess_lock, "_try_lock", capture)
+ with path.open("a+b") as holder:
+ # Windows supports locks beyond EOF. Hold byte zero without writing it.
+ msvcrt.locking(holder.fileno(), msvcrt.LK_NBLCK, 1)
+ try:
+ assert contender.acquire() is False
+ assert opened[0].closed
+ finally:
+ msvcrt.locking(holder.fileno(), msvcrt.LK_UNLCK, 1)
+ contender.release()
+ for handle in opened:
+ handle.close()
+ try:
+ assert contender.acquire()
+ assert path.stat().st_size == 0
+ finally:
+ contender.release()