HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
cheetahclaws: a new backend, CheetahClaws 3.5.88 driven in process
master5d56b965544afb
diff --git a/NOTICE b/NOTICEindex c51fa432..8d981409 100644--- a/NOTICE+++ b/NOTICE@@ -39,6 +39,11 @@ run, by you, under their own licenses:@anthropic-ai/claude-code Anthropic's own terms ("SEE LICENSE IN README.md")@openai/codex Apache-2.0hermes-agent MIT (License-Expression declared by the publisher since 0.19.0)+ cheetahclaws Apache-2.0 — "CheetahClaws, Copyright 2026 SAIL Lab at UC Berkeley"+ (SAIL-Research-Lab/cheetahclaws; its NOTICE ships in the wheel). The+ console's CheetahClaws mark, ui/public/logos/cheetahclaws.png, is that+ project's app icon (cheetahclaws/web/static/favicon.png), included+ unmodified under the same license.Claude Code is distributed under Anthropic's terms and may not be redistributed inside apublic image; hermes-agent's publisher declared no license before 0.19.0. Installing thediff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 2d5d3d17..35939183 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -179,7 +179,7 @@ export HOSTNAME=0.0.0.0TOOLS="$DATA_DIR/agent-tools"export PATH="$TOOLS/bin:$PATH"export NODE_PATH="$TOOLS/lib/node_modules"-export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider,openhands,systemone}"+export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider,openhands,systemone,cheetahclaws}"wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }# The executable IS the definition of "installed" — an installer that exits 0 without producing@@ -202,6 +202,7 @@ backend_bin() {aider) echo "$TOOLS/aider-venv/bin/aider" ;;openhands) echo "$TOOLS/openhands-venv/bin/python" ;;systemone) echo "$TOOLS/systemone-venv/bin/python" ;;+ cheetahclaws) echo "$TOOLS/cheetahclaws-venv/bin/cheetahclaws-ready" ;;esac}@@ -290,6 +291,70 @@ if aider.__version__ != want:&& chmod +x "$TOOLS/aider-venv/bin/aider-ready"}+# CheetahClaws, Apache-2.0 (SAIL-Research-Lab/cheetahclaws, PyPI `cheetahclaws`), pinned to 3.5.88.+#+# Its own venv, the aider/openhands precedent: runner/cheetahclaws_driver.py drives the CLI's agent+# loop IN PROCESS, so this venv's interpreter is what the runner starts, and the package's own+# dependency tree (anthropic, openai, httpx, rich, pyte, prompt_toolkit) stays off the runner's.+# The BARE package: its `files` extra brings pymupdf, which is AGPL-3.0, and `browser` brings+# playwright with a Chromium of its own; the driver withholds the four tools those extras serve+# (WebBrowse, ReadPDF, ReadSpreadsheet, ReadImage) for as long as they are absent.+#+# VERIFIED, not only pinned. PyPI publishes the wheel's sha256, so the wheel is downloaded on its+# own, compared against the digest pinned here (computed from the 3.5.88 release's+# cheetahclaws-3.5.88-py3-none-any.whl, and equal to the one PyPI lists), and installed from that+# file; an index entry can be replaced, a digest cannot. An operator who overrides the version+# supplies HR_CHEETAHCLAWS_SHA256 for it, or is told the wheel is unverified (install_backends).+# The import check then asserts the symbols the driver reaches for, so an upstream refactor fails+# the install here rather than the first live turn.+CHEETAHCLAWS_PIN="${HR_CHEETAHCLAWS_VERSION:-3.5.88}"+if [ "$CHEETAHCLAWS_PIN" = "3.5.88" ]; then+ CHEETAHCLAWS_SHA256="${HR_CHEETAHCLAWS_SHA256:-6e9b46c0e2d125f700cc0b609464efe1a3fe0914cbd0ecad8e405a1c0fc4f9c0}"+else+ CHEETAHCLAWS_SHA256="${HR_CHEETAHCLAWS_SHA256:-}"+fi+install_cheetahclaws() {+ cc_py="${HR_CHEETAHCLAWS_BASE_PYTHON:-python3}"+ rm -rf "$TOOLS/cheetahclaws-venv"+ "$cc_py" -m venv "$TOOLS/cheetahclaws-venv" || return 1+ cc_tmp="$(mktemp -d)"+ "$TOOLS/cheetahclaws-venv/bin/pip" download -q --disable-pip-version-check --no-deps \+ --only-binary=:all: -d "$cc_tmp" "cheetahclaws==$CHEETAHCLAWS_PIN" || { rm -rf "$cc_tmp"; return 1; }+ cc_whl="$cc_tmp/cheetahclaws-$CHEETAHCLAWS_PIN-py3-none-any.whl"+ [ -f "$cc_whl" ] || { echo "cheetahclaws $CHEETAHCLAWS_PIN: no wheel was downloaded"; rm -rf "$cc_tmp"; return 1; }+ if [ -n "$CHEETAHCLAWS_SHA256" ]; then+ cc_have="$(sha256sum "$cc_whl" | awk '{print $1}')"+ if [ "$CHEETAHCLAWS_SHA256" != "$cc_have" ]; then+ echo "cheetahclaws $CHEETAHCLAWS_PIN: wheel digest mismatch (want $CHEETAHCLAWS_SHA256, have $cc_have)"+ rm -rf "$cc_tmp"; return 1+ fi+ fi+ "$TOOLS/cheetahclaws-venv/bin/pip" install -q --disable-pip-version-check "$cc_whl" \+ || { rm -rf "$cc_tmp"; return 1; }+ rm -rf "$cc_tmp"+ "$TOOLS/cheetahclaws-venv/bin/python" -c '+import sys, importlib.metadata as md+want = sys.argv[1]+have = md.version("cheetahclaws")+if have != want:+ sys.exit("cheetahclaws %s installed, wanted %s" % (have, want))+# every name runner/cheetahclaws_driver.py imports, from the modules it imports them from+from cheetahclaws.agent import AgentState, run, TextChunk, ThinkingChunk, ToolStart, ToolEnd, TurnDone, PermissionRequest # noqa: F401+from cheetahclaws.commands.session import autosave_session, _migrate_session # noqa: F401+from cheetahclaws.config import load_config, MR_SESSION_DIR # noqa: F401+from cheetahclaws.context import build_system_prompt # noqa: F401+from cheetahclaws.mcp_client.tools import initialize_mcp # noqa: F401+from cheetahclaws.tool_registry import get_all_tools # noqa: F401+import cheetahclaws.commands.session as s+if not hasattr(s, "_autosave_sid"):+ sys.exit("cheetahclaws %s: commands.session has no _autosave_sid" % have)+' "$CHEETAHCLAWS_PIN" || return 1+ # Written LAST, after the install and the checks proved the venv good: the marker is what the+ # boot compares against the pin, so a half-built venv is rebuilt rather than trusted.+ printf '#!/bin/sh\necho %s\n' "$CHEETAHCLAWS_PIN" > "$TOOLS/cheetahclaws-venv/bin/cheetahclaws-ready" \+ && chmod +x "$TOOLS/cheetahclaws-venv/bin/cheetahclaws-ready"+}+# Kimi Code CLI, MIT (MoonshotAI/kimi-code), pinned to 2.0.0.## THIS IS THE SUCCESSOR, NOT Kimi CLI. 0.18.0 shipped MoonshotAI/kimi-cli 1.50.0, the Python@@ -665,6 +730,21 @@ install_backends() {chromium_libs || echo "[harnessrouter] WARNING: Chromium's system libraries could not be installed; the System One base's browser environments will not start until they are (retried on the next start)"fi+ # In the default set, for the reason aider is: the console offers every base the gateway's+ # catalogue lists, and a listed base that is not installed fails on its first task. ~90 MB.+ # The marker names the version the venv was built for, so a pin bump rebuilds it on a volume+ # that already has one; the session lives in the workspace, not in the venv.+ if wanted cheetahclaws && [ "$("$(backend_bin cheetahclaws)" 2>/dev/null)" != "$CHEETAHCLAWS_PIN" ]; then+ echo "[harnessrouter] installing CheetahClaws $CHEETAHCLAWS_PIN (Apache-2.0)…"+ if [ -z "$CHEETAHCLAWS_SHA256" ]; then+ # Said HERE, outside try_install, which keeps an installer's output only when it fails.+ echo "[harnessrouter] WARN: HR_CHEETAHCLAWS_VERSION=$CHEETAHCLAWS_PIN overrides the pinned 3.5.88, and no"+ echo "[harnessrouter] HR_CHEETAHCLAWS_SHA256 was given — this cheetahclaws wheel is UNVERIFIED."+ fi+ try_install "CheetahClaws" install_cheetahclaws || true+ fi+ [ -x "$TOOLS/cheetahclaws-venv/bin/python" ] && export HR_CHEETAHCLAWS_PYTHON="$TOOLS/cheetahclaws-venv/bin/python"+if wanted kimi && [ "$("$(backend_bin kimi)" --version 2>/dev/null | head -n 1)" != "$KIMI_PIN" ]; thenecho "[harnessrouter] installing Kimi Code CLI $KIMI_PIN (MIT, version-pinned)…"try_install "Kimi Code CLI" install_kimi || truediff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.mdindex c31d8708..1d07157f 100644--- a/docs/self-hosting-guide.md+++ b/docs/self-hosting-guide.md@@ -337,16 +337,16 @@ offers you providers that work.|---|---|| `anthropic` | Claude Code, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands || `openai` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands |-| `openrouter` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands, System One |+| `openrouter` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands, System One, CheetahClaws || `azure-foundry` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands || `google` | Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, Kimi Code CLI, Aider, OpenHands || `typesafe` | System One (Jev on TypeSafe's own API: `jev-latest`, `jev-preview`) || `bedrock` | Claude Code, Hermes |-| `tokenrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands |-| `harnessrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands, System One (the open-weight models `laya`, `openthai-systemone` and `system-one-phase2`, served by the hosted service and billed to the key's credits) |-| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands |+| `tokenrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands, CheetahClaws |+| `harnessrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands, CheetahClaws, System One (the open-weight models `laya`, `openthai-systemone` and `system-one-phase2`, served by the hosted service and billed to the key's credits) |+| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands, CheetahClaws || `llmtr` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands |-| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands |+| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider, OpenHands, CheetahClaws (OpenAI format) |</details>@@ -654,7 +654,7 @@ Backends are installed into your data volume rather than baked into the image, swant is a run-time setting:```bash-docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider,openhands,systemone ... # the default+docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider,openhands,systemone,cheetahclaws ... # the defaultdocker run -e HR_BACKENDS=opencode ... # lean```diff --git a/gateway/app.py b/gateway/app.pyindex 87e8f6a1..72a1b79a 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -1176,6 +1176,12 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {("llmtr", "openhands"): "tokenrouter",("custom", "openhands"): "openai-api",("google", "openhands"): "openai-api",+ # cheetahclaws speaks ONE wire protocol: its `custom/<model>` client is OpenAI Chat Completions+ # aimed at the loopback relay (CUSTOM_BASE_URL, 3.5.88), so it is wired to the chat-completions+ # connections and to nothing it would have to translate for.+ ("openrouter", "cheetahclaws"): "openai-api",+ ("tokenrouter", "cheetahclaws"): "tokenrouter", ("vercel", "cheetahclaws"): "tokenrouter",+ ("custom", "cheetahclaws"): "openai-api",("anthropic", "qwen"): "anthropic", ("openai", "qwen"): "openai",("azure-foundry", "qwen"): "azure",("openrouter", "qwen"): "openai-api",@@ -1241,6 +1247,7 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {("harnessrouter", "kimi"): "tokenrouter",("harnessrouter", "aider"): "tokenrouter",("harnessrouter", "openhands"): "tokenrouter",+ ("harnessrouter", "cheetahclaws"): "tokenrouter",("harnessrouter", "cline"): "tokenrouter", ("harnessrouter", "gemini"): "google",("harnessrouter", "goose"): "tokenrouter",# The hosted service serves the open-weight System One models (laya, openthai-systemone,@@ -4838,8 +4845,9 @@ _CUSTOM_FORMAT_BACKENDS = {# OPENAI_BASE_PATH through the relay). Its own anthropic provider takes ANTHROPIC_HOST with no# base-path counterpart and is unprobed, so a custom ANTHROPIC endpoint stays off this set# until it is — the picker greys out what the router cannot actually run.+ # cheetahclaws: OpenAI Chat Completions only (its `custom/` client), so the openai set alone."openai": {"hermes", "opencode", "pi", "dsh", "qwen", "cline", "omp", "goose", "kimi", "aider",- "openhands"},+ "openhands", "cheetahclaws"},"anthropic": {"claude", "opencode", "pi", "dsh", "omp"},# The OpenAI Responses API: what codex speaks, and only codex among the agent CLIs here."responses": {"codex"},@@ -6405,6 +6413,26 @@ _MODEL_CATALOG: dict[str, dict] = {"qwen3.8-flash", "qwen3.8-27b", "qwen3.7-max", "qwen3.7-plus", "glm-5.3","glm-5.3-flash", "mistral-medium-3.5", "step-3.7-flash", "hunyuan-4-preview","nemotron-3.5-lightning", "nemotron-3-super"]},+ # cheetahclaws: the same relay reach as kimi and openhands (OpenAI chat/completions through the+ # loopback relay), so the list is theirs. OFFERED, NOT YET MEASURED on these connections: the+ # PR that added the base ran its column on a custom OpenAI-format connection only, and the+ # hosted provider columns decide which of these ids stay. The id reaches the provider verbatim+ # (the runner sends `custom/<id>`, and providers.py strips the prefix before the request).+ "cheetahclaws": {"default": "gpt-5.4",+ "models": [+ "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5", "gpt-5.4",+ "gpt-5.4-mini", "gpt-5.2", "claude-fable-5-1", "claude-fable-5", "claude-opus-5.5",+ "claude-opus-5", "claude-sonnet-5", "claude-opus-4.8", "claude-opus-4.7",+ "claude-sonnet-4.6", "claude-haiku-4.5", "gemini-3.8-flash", "gemini-3.7-flash",+ "gemini-3.6-flash", "gemini-3.5-flash", "gemini-3.5-flash-lite",+ "gemini-3.1-pro-preview", "gemini-3.1-flash-lite", "gemini-3-flash-preview",+ "grok-4.6", "grok-4.5", "grok-4.3", "grok-4.20", "grok-build-0.1",+ "muse-spark-1.3", "muse-spark-1.2", "muse-spark-1.1", "muse-glimmer-30b",+ "llama-3.3-70b", "deepseek-v4.1-flash", "deepseek-v4-pro", "deepseek-v4-flash",+ "kimi-k3", "kimi-k2.7-code", "qwen3.8-max", "qwen3.8-flash", "qwen3.8-27b",+ "qwen3.7-max", "qwen3.7-plus", "glm-5.3", "glm-5.3-flash", "mistral-medium-3.5",+ "step-3.7-flash", "hunyuan-4-preview", "nemotron-3.5-lightning",+ "nemotron-3-super"]},"qwen": {"default": "qwen3.7-max","models": ["qwen3.7-max", "qwen3.8-max","gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5",@@ -6552,7 +6580,8 @@ RESPONSES_ONLY_MODELS = frozenset({"gpt-5.3-codex", "gpt-6-astra"})# sets), so a Responses-API-only id would be a picker row that fails on send.# aider and openhands speak chat/completions through litellm's openai provider (the id is sent# `openai/<id>`), so a Responses-API-only id would be a picker row that fails on send.-CHAT_ONLY_BACKENDS = ("qwen", "cline", "goose", "kimi", "aider", "openhands")+# cheetahclaws speaks chat/completions only (its `custom/` provider is OpenAI Chat Completions).+CHAT_ONLY_BACKENDS = ("qwen", "cline", "goose", "kimi", "aider", "openhands", "cheetahclaws")_BARE_MODELS = {"", "claude", "codex", "anthropic", "bedrock", "openai", "hermes", "pi", "dsh", "deepseek", "omp"}# Models whose serving CHANNEL refuses image input outright. Measured, not assumed — probed# 2026-08-19 on the TokenRouter connection with a data-URI image in a user message:@@ -13883,6 +13912,43 @@ _BASE_CATALOG: dict[str, dict] = {# of every backend here that has a shell."tool_enforcement": "hard",},+ "cheetahclaws": {+ "label": "CheetahClaws", "backend": "cheetahclaws", "status": "ready",+ # NOT a system prompt of its own: the CLI composes its system prompt itself+ # (context.build_system_prompt) and reads the harness's instructions from CLAUDE.md in the+ # workspace — CLAUDE.md only; it has no AGENTS.md discovery at all.+ "system_prompt": ("You are CheetahClaws, an autonomous coding agent. You work on a real git "+ "workspace with shell and file access, reading and editing files and "+ "running commands to complete the task end to end."),+ # The `tools` array a live 3.5.88 turn SENT ITS PROVIDER, captured at a stub (the CLI's+ # "full" profile), by the names the model sees; test_catalog_cheetahclaws_tools.py pins+ # these ids equal to the runner's CHEETAHCLAWS_TOOLS. Not offered, because the driver+ # withholds them on every turn and a switch for them would change nothing: AskUserQuestion+ # (it blocks on a terminal nobody is at), ReadEmail and SendEmail (no mailbox is ever+ # configured), and WebBrowse, ReadPDF, ReadSpreadsheet and ReadImage, whose optional extras+ # the pinned bare install does not carry (pymupdf, which `files` would bring, is AGPL-3.0).+ "tools": [("Bash", "Shell"), ("Read", "File Read"), ("Write", "File Write"), ("Edit", "Edit"),+ ("Glob", "Glob"), ("Grep", "Search"), ("WebFetch", "Web Fetch"),+ ("WebSearch", "Web Search"), ("NotebookEdit", "Notebook Edit"),+ ("GetDiagnostics", "Diagnostics"), ("SummarizeLargeFile", "Large File Summary"),+ ("Skill", "Skill"), ("SkillList", "Skill List"), ("Agent", "Subagent"),+ ("CheckAgentResult", "Subagent Result"), ("ListAgentTasks", "Subagent Tasks"),+ ("ListAgentTypes", "Subagent Types"), ("SendMessage", "Subagent Message"),+ ("TaskCreate", "Task Create"), ("TaskGet", "Task Get"), ("TaskList", "Task List"),+ ("TaskUpdate", "Task Update"), ("MemorySave", "Memory Save"), ("MemoryList", "Memory List"),+ ("MemorySearch", "Memory Search"), ("MemoryVerify", "Memory Verify"),+ ("MemoryDelete", "Memory Delete"), ("Research", "Research"),+ ("EnterPlanMode", "Enter Plan"), ("ExitPlanMode", "Exit Plan"),+ ("SleepTimer", "Sleep Timer")],+ # "hard", and measured: the driver sets the CLI's own `disabled_tools`, which removes the+ # tool from the schema sent to the provider (tool_registry.get_tool_schemas) AND refuses a+ # call to it at execution (agent.py: a name outside the turn's active set is an error, not a+ # permission question). Pinned against a stub in runner/tests/test_cheetahclaws_backend.py+ # (Bash and Write disabled: absent from the provider's `tools`). An MCP tool is withheld the+ # same way, by its bare or server.tool name. The honest limit every shell-bearing base has:+ # disabling Write alone does not stop a file being written through Bash.+ "tool_enforcement": "hard",+ },"systemone": {"label": "System One", "backend": "systemone", "status": "ready",# Delivered as the loop's task instructions on every step, beside the environment's own.diff --git a/gateway/tests/test_catalog_cheetahclaws_tools.py b/gateway/tests/test_catalog_cheetahclaws_tools.pynew file mode 100644index 00000000..44b9018f--- /dev/null+++ b/gateway/tests/test_catalog_cheetahclaws_tools.py@@ -0,0 +1,51 @@+"""The console must never offer a CheetahClaws tool toggle the runner cannot enforce.++The driver withholds a disabled tool through the CLI's own `disabled_tools`, which matches registry+NAMES exactly: a catalog id outside the runner's CHEETAHCLAWS_TOOLS would be a toggle that is+reported as off and changes nothing, the overstatement UHP section 4.3 forbids and the reason this+backend may claim `tool_enforcement: "hard"`. CHEETAHCLAWS_TOOLS is the `tools` array of a live+3.5.88 request captured at a stub; this test holds the catalog to it.+"""+import os+import pathlib+import sys++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "runner"))+os.environ.setdefault("HR_BACKING", "local")+import app as A # noqa: E402+from server import BACKENDS, CHEETAHCLAWS_TOOLS # noqa: E402+++def test_every_advertised_tool_can_actually_be_withheld():+ advertised = {tid for tid, _label in A._BASE_CATALOG["cheetahclaws"]["tools"]}+ assert advertised == set(CHEETAHCLAWS_TOOLS), (+ f"only in catalog: {advertised - set(CHEETAHCLAWS_TOOLS)}, "+ f"only in the runner: {set(CHEETAHCLAWS_TOOLS) - advertised}")+++def test_a_tool_the_driver_always_withholds_is_not_offered():+ import cheetahclaws_driver as drv+ offered = {tid for tid, _ in A._BASE_CATALOG["cheetahclaws"]["tools"]}+ assert not offered & set(drv.ALWAYS_WITHHELD)+ assert not offered & set(drv.OPTIONAL_TOOLS)+++def test_cheetahclaws_is_registered_as_a_chat_completions_base():+ base = A._BASE_CATALOG["cheetahclaws"]+ assert base["backend"] == "cheetahclaws" and base["tool_enforcement"] == "hard"+ assert "cheetahclaws" in A.CHAT_ONLY_BACKENDS+ assert "cheetahclaws" in A._CUSTOM_FORMAT_BACKENDS["openai"]+ assert "cheetahclaws" not in A._CUSTOM_FORMAT_BACKENDS["anthropic"]+ assert "cheetahclaws" not in A._CUSTOM_FORMAT_BACKENDS["responses"]+ assert "cheetahclaws" in BACKENDS+++def test_it_is_wired_to_the_chat_completions_connections_only():+ wired = {prov: runner for (prov, backend), runner in A._INTEGRATION_WIRING.items()+ if backend == "cheetahclaws"}+ # the hosted HarnessRouter API is TokenRouter-shaped and is wired wherever TokenRouter is+ # (test_harnessrouter_provider.py)+ assert wired == {"openrouter": "openai-api", "tokenrouter": "tokenrouter",+ "vercel": "tokenrouter", "custom": "openai-api", "harnessrouter": "tokenrouter"}+ assert set(wired.values()) <= set(BACKENDS["cheetahclaws"]["providers"])diff --git a/runner/cheetahclaws_driver.py b/runner/cheetahclaws_driver.pynew file mode 100644index 00000000..923742c2--- /dev/null+++ b/runner/cheetahclaws_driver.py@@ -0,0 +1,362 @@+"""One CheetahClaws turn, as a runner subprocess.++Spawned per turn by server.py (the same one-process-per-turn contract as every other backend: the+runner reads NDJSON off stdout, cancel is a process-group kill). Inside, CheetahClaws's own agent+loop is DRIVEN IN PROCESS — `cheetahclaws.agent.run`, the generator its REPL and its headless+bridge runner (`cli._start_headless_bridges`) both consume — rather than launched as+`cheetahclaws -p` whose printed text we would parse. Everything that loop yields is re-emitted the+moment it is yielded, as one {"m": method, "p": payload} line (the dsh_driver shape), normalised by+_cheetahclaws_to_claude in server.py. The version is pinned EXACTLY (docker/entrypoint.sh) because+the loop is the package's internal API rather than a documented one.++WHY NOT THE CLI, measured on the pinned 3.5.88:+ * No event stream. `-p` prints the final answer and ANSI tool cards, and the session file is the+ only structured record. That file is rewritten ONCE PER USER TURN — `autosave_session` runs+ after `run_query` returns (cli.py, "Silent autosave"), never between messages — so tailing it+ gives a silent turn and then everything at once, the stream S-09 measures as not progressive.+ * A provider failure is prose on stdout and exit 0. `cheetahclaws -p` against a dead endpoint, a+ bad key and a 429 printed `[Failed — APIConnectionError: …]`, `[Failed — AuthenticationError:+ Error code: 401 …]` and `[Failed — RateLimitError: Error code: 429 …]` and exited 0 each time.+ In process the verdict is structural instead: the loop appends an assistant message only when a+ completion came back, so a turn whose history ends on the user's message (or a tool result) had+ its last provider call fail, whatever the text said. The printed sentence is kept as the reason.+ * No resume flag. `-p` always starts from an empty AgentState; continuing is the REPL's `/resume`,+ which loads session_latest.json into the state. The driver does the same load (the CLI's own+ `_migrate_session`) before the turn and writes the file back after it with the CLI's own+ `autosave_session`, so the file the CLI would have written is the file on disk.+ * MCP connects in a background thread started at import (mcp_client/tools.py), so a `-p` turn can+ make its first model call before any MCP tool is registered. The driver waits for it.+"""+from __future__ import annotations++import contextlib+import json+import os+import pathlib+import re+import sys+import time+import uuid++_T0 = time.time()+# The NDJSON channel. Everything CheetahClaws prints goes to stderr instead (see main), so a stray+# print from a tool can never land inside, or between, the lines the runner parses.+_OUT = sys.stdout++# The notices the agent loop yields as TextChunks of its own, outside the provider stream (agent.py+# on 3.5.88: the retry ladder, the final failure, an open circuit breaker, compaction, the read-only+# dedup and the two loop guards). They are the CLI talking, not the model, so they are reported as+# notices rather than as answer text. Each is yielded as ONE chunk that starts with "\n[".+_NOTICE = re.compile(r"^\n\[(?:Retry \d+/\d+ after \d+s — |Failed — |Circuit breaker OPEN |"+ r"Context too long — |Context overflow — |NIM rate-limited |deduped |"+ r"Loop guard\] )")+# The one a failed provider call ends on: `[Failed — <ExceptionType>: <message>.<hint>]`.+FAILED_RE = re.compile(r"^\s*\[Failed — (?P<body>.+)\]\s*$", re.S)+# A sentence that sends the reader to the CLI's own slash commands ("Hint: Check your API key:+# /config …", "Try /clear and rephrase …"). The person reading the turn record has no such prompt:+# the rule kimi's "To resume this session" line and aider's "Use /drop" advice already follow. The+# sentences around it are the reason and stay.+_SLASH_CMD = re.compile(r"(?:^|\s)/[a-z][\w-]*\b")+LOOP_GUARD = "[Loop guard]"++# Withheld on every turn, because none of them can do its job here. AskUserQuestion blocks on the+# terminal's stdin (tools/interaction.py, ask_input_interactive) and nobody is at it: a question+# goes into the answer instead, where the person reads it. ReadEmail and SendEmail need a mailbox+# the CLI reads from its own config (email_address, email_password, email_*_host), which this+# product never sets; offered, they are a tool that fails on every call.+ALWAYS_WITHHELD = ("AskUserQuestion", "ReadEmail", "SendEmail")+# Tools whose module is an OPTIONAL extra of the package, withheld while it is not installed in the+# venv. The pinned install is the bare package (docker/entrypoint.sh): the `files` extra brings+# pymupdf, which is AGPL-3.0, and `browser` brings playwright with a browser of its own. A tool the+# model is offered and cannot run is the overstatement UHP 4.3 forbids; an operator who installs+# an extra into the venv gets its tool back without a code change.+OPTIONAL_TOOLS = {"WebBrowse": "playwright", "ReadPDF": "fitz", "ReadSpreadsheet": "openpyxl",+ "ReadImage": "PIL"}+++def unavailable_tools() -> list[str]:+ import importlib.util+ return sorted(t for t, mod in OPTIONAL_TOOLS.items() if importlib.util.find_spec(mod) is None)+++def _emit(method: str, payload) -> None:+ _OUT.write(json.dumps({"m": method, "p": payload}, default=str) + "\n")+ _OUT.flush()+++def is_notice(text: str) -> bool:+ return bool(_NOTICE.match(text or ""))+++def failure_reason(notice: str) -> str:+ """The sentence a failed call is reported with: the CLI's own words, minus the brackets and+ minus a hint that names a slash command."""+ text = (notice or "").strip()+ m = FAILED_RE.match(text)+ if m:+ text = "Failed — " + m.group("body").strip()+ elif text.startswith(LOOP_GUARD):+ text = "Loop guard: " + text[len(LOOP_GUARD):].strip()+ elif text.startswith("[") and text.endswith("]"):+ text = text[1:-1].strip()+ sentences = re.split(r"(?<=[.!?)])\s+", text)+ return " ".join(s for s in sentences if not _SLASH_CMD.search(s)).strip()+++def disabled_names(requested, registered) -> list[str]:+ """The registry names to withhold for a harness's disabled list.++ A built-in is named as the CLI names it (`Bash`, `Write`). An MCP tool is registered as+ `mcp__<server>__<tool>` and the harness names it by its bare tool name or `<server>.<tool>`, the+ two forms the aider bridge and the openhands filter already accept; both are matched here, so a+ disabled MCP tool is withheld by the same mechanism as a built-in rather than merely described."""+ want = ({str(x).strip() for x in (requested or []) if str(x).strip()}+ | set(ALWAYS_WITHHELD) | set(unavailable_tools()))+ out = set()+ for name in registered or []:+ if name in want:+ out.add(name)+ continue+ if name.startswith("mcp__"):+ parts = name.split("__", 2)+ if len(parts) == 3 and (parts[2] in want or f"{parts[1]}.{parts[2]}" in want):+ out.add(name)+ # Names that match nothing registered are passed through as well: the loop ignores them, and a+ # tool that registers late (an MCP server that connected after this call) is still covered.+ return sorted(out | want)+++def session_file(home: pathlib.Path) -> pathlib.Path:+ """Where the CLI autosaves: config.MR_SESSION_DIR / session_latest.json (3.5.88)."""+ return home / ".cheetahclaws" / "sessions" / "mr_sessions" / "session_latest.json"+++def load_session(path: pathlib.Path, session_id: str) -> dict | None:+ """The saved conversation when it is the one asked for, else None."""+ if not session_id:+ return None+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ if not isinstance(data, dict) or data.get("session_id") != session_id:+ return None+ if not isinstance(data.get("messages"), list) or not data["messages"]:+ return None+ return data+++class Pairing:+ """Gives each ToolStart/ToolEnd the id of the tool call it belongs to.++ The loop's ToolStart and ToolEnd carry a name and no id, and the ends of a batch arrive after+ all of its starts (parallel calls first, then sequential ones, agent.py). The assistant message+ the loop appended just before (its TurnDone) holds the batch's calls with their real ids, in+ the order the starts follow, so a start takes the first unclaimed call of its name and an end+ takes the first unfinished start of its name. The ids are then the ones in the session file."""++ def __init__(self) -> None:+ self.pending: list[dict] = []+ self.started: list[dict] = []+ self.n = 0++ def batch(self, assistant_msg: dict | None) -> None:+ calls = (assistant_msg or {}).get("tool_calls") or []+ self.pending = [dict(c) for c in calls if isinstance(c, dict)]++ def start(self, name: str, inputs) -> str:+ for i, c in enumerate(self.pending):+ if c.get("name") == name:+ call = self.pending.pop(i)+ tid = str(call.get("id") or "")+ break+ else:+ tid = ""+ if not tid:+ self.n += 1+ tid = f"cc{self.n}"+ self.started.append({"id": tid, "name": name})+ return tid++ def end(self, name: str) -> str:+ for i, c in enumerate(self.started):+ if c["name"] == name:+ return self.started.pop(i)["id"]+ self.n += 1+ return f"cc{self.n}"+++def verdict(messages: list, start: int, notices: list[str], budget_hit: bool) -> dict:+ """How the turn ended, read off the history the loop left behind.++ `start` is the index of the user message this turn appended. The loop appends an assistant+ message only for a completion that came back, and its own loop guards append one of their own+ whose text is the guard's notice; anything else that ends the loop (a failed provider call, an+ open circuit breaker) leaves the history ending on the user's message or on a tool result."""+ last = messages[-1] if len(messages) > start else None+ role = (last or {}).get("role")+ content = (last or {}).get("content")+ text = content if isinstance(content, str) else ""+ if budget_hit:+ return {"ok": False, "subtype": "error_max_turns", "final": text if role == "assistant" else "",+ "reason": "the operator's step budget was reached"}+ if role == "assistant" and not text.startswith(LOOP_GUARD):+ return {"ok": True, "subtype": "success", "final": text, "reason": ""}+ if role == "assistant":+ # The loop guard stopped a model that kept repeating itself: the CLI's sentence, not an+ # answer. The turn did not finish its task.+ return {"ok": False, "subtype": "error", "final": "", "reason": failure_reason(text)}+ failed = [n for n in notices if FAILED_RE.match(n.strip())]+ reason = failure_reason(failed[-1] if failed else (notices[-1] if notices else ""))+ return {"ok": False, "subtype": "error", "final": "",+ "reason": reason or "the turn ended without a completion from the provider"}+++def main() -> int:+ job = json.loads(sys.argv[1])+ cwd = job.get("cwd") or os.getcwd()+ os.chdir(cwd)+ home = pathlib.Path(os.environ.get("HOME") or pathlib.Path.home())+ # Nobody is at the terminal. Anything that reads stdin gets end-of-file at once instead of+ # waiting on a pipe the runner never writes.+ sys.stdin = open(os.devnull, encoding="utf-8")+ logs = home / ".cheetahclaws" / "logs"+ logs.mkdir(parents=True, exist_ok=True)++ with contextlib.redirect_stdout(sys.stderr):+ from cheetahclaws.config import load_config+ from cheetahclaws.bootstrap import bootstrap+ from cheetahclaws import runtime+ from cheetahclaws.agent import (AgentState, run, TextChunk, ThinkingChunk, ToolStart,+ ToolEnd, TurnDone, PermissionRequest)+ from cheetahclaws.commands import session as cc_session+ from cheetahclaws.context import build_system_prompt++ config = load_config()+ config.update({+ "model": job["model"],+ # The harness is the permission layer: its disabled tools are withheld from the schema+ # below, and nobody is at a prompt to approve anything else.+ "permission_mode": "accept-all",+ # CheetahClaws writes its structured log (one JSON object per line) to stderr unless+ # it has a file, and the runner merges stderr into the NDJSON stream it parses.+ "log_file": str(logs / "cheetahclaws.jsonl"),+ "quiet": True,+ })+ bootstrap(config)++ # MCP: connect every configured server and register its tools BEFORE the tool list is+ # taken, instead of racing the background connect the import started.+ # A server that does not connect is left out and the turn runs without it, silently in the+ # CLI; here it becomes the runner's mcp_unavailable event, which the gateway renders as a+ # note on the reply (the kimi precedent).+ down: list[dict] = []+ try:+ from cheetahclaws.mcp_client.tools import initialize_mcp+ for server, error in (initialize_mcp() or {}).items():+ if error:+ down.append({"name": str(server), "reason": str(error)[:200]})+ except Exception as exc: # noqa: BLE001 — a broken MCP stack must not stop the turn+ down.append({"name": "mcp", "reason": f"{type(exc).__name__}: {exc}"[:200]})+ from cheetahclaws.tool_registry import get_all_tools+ config["disabled_tools"] = disabled_names(job.get("tools_disabled"),+ [t.name for t in get_all_tools()])++ state = AgentState()+ path = session_file(home)+ saved = load_session(path, str(job.get("session_id") or ""))+ if saved is not None:+ saved = cc_session._migrate_session(saved)+ state.messages = saved.get("messages", [])+ state.turn_count = saved.get("turn_count", 0)+ state.total_input_tokens = saved.get("total_input_tokens", 0)+ state.total_output_tokens = saved.get("total_output_tokens", 0)+ sid = saved["session_id"]+ else:+ sid = uuid.uuid4().hex[:8]+ config["_session_id"] = sid+ runtime.get_session_ctx(sid).agent_state = state+ # autosave_session keeps one id per PROCESS (a module global minted on first use); a turn+ # is one process, so without this every turn would save the conversation under a new id+ # and the next turn could not ask for it.+ cc_session._autosave_sid = sid++ system_prompt = build_system_prompt(config)+ doc = pathlib.Path(cwd, "CLAUDE.md")+ if doc.is_file() and f"[Project CLAUDE.md: {doc}]" not in system_prompt:+ # get_claude_md drops the WHOLE file when a line matches one of its prompt-injection+ # patterns (context.py, _THREAT_PATTERNS) and says so only on stderr. The harness's+ # instructions then never reach the model; the record says so.+ _emit("warning", {"text": "CheetahClaws excluded CLAUDE.md from the system prompt "+ "(its prompt-injection scan matched), so the harness "+ "instructions did not reach the model"})++ _emit("__hr_init", {"session_id": sid, "resumed": saved is not None,+ "messages": len(state.messages)})+ if down:+ _emit("mcp_unavailable", {"servers": down})++ budget = int(job.get("max_turns") or 0)+ calls = {"n": 0}+ pairing = Pairing()+ notices: list[str] = []+ start = len(state.messages)+ try:+ with contextlib.redirect_stdout(sys.stderr):+ events = run(job["prompt"], state, config, system_prompt,+ cancel_check=lambda: bool(budget) and calls["n"] >= budget)+ for ev in events:+ if isinstance(ev, TextChunk):+ if is_notice(ev.text):+ notices.append(ev.text.strip())+ _emit("notice", {"text": ev.text.strip()})+ elif ev.text:+ _emit("text", {"text": ev.text})+ elif isinstance(ev, ThinkingChunk):+ if ev.text:+ _emit("thinking", {"text": ev.text})+ elif isinstance(ev, TurnDone):+ calls["n"] += 1+ pairing.batch(state.messages[-1] if state.messages else None)+ elif isinstance(ev, ToolStart):+ tid = pairing.start(ev.name, ev.inputs)+ _emit("tool_start", {"id": tid, "name": ev.name, "input": ev.inputs or {}})+ elif isinstance(ev, ToolEnd):+ tid = pairing.end(ev.name)+ _emit("tool_end", {"id": tid, "name": ev.name, "result": str(ev.result or ""),+ "permitted": bool(ev.permitted)})+ elif isinstance(ev, PermissionRequest):+ # accept-all never asks; if a future version does, the harness answers as the+ # permission mode it set. Withheld tools never reach this point.+ ev.granted = True+ elif type(ev).__name__ == "QuotaPause":+ notices.append(f"[Budget reached — {getattr(ev, 'reason', '')}]")+ except Exception as exc: # noqa: BLE001 — the turn's failure is the product here, not a crash+ _save(cc_session, state, config)+ _emit("__hr_result", {"ok": False, "subtype": "error", "final": "", "session_id": sid,+ "reason": f"{type(exc).__name__}: {exc}"[:500],+ "seconds": round(time.time() - _T0, 2)})+ return 1++ budget_hit = bool(budget) and calls["n"] >= budget and (+ not state.messages or state.messages[-1].get("role") != "assistant"+ or bool(state.messages[-1].get("tool_calls")))+ out = verdict(state.messages, start, notices, budget_hit)+ _save(cc_session, state, config)+ _emit("__hr_result", {**out, "session_id": sid, "calls": calls["n"],+ "seconds": round(time.time() - _T0, 2)})+ return 0+++def _save(cc_session, state, config) -> None:+ """The CLI's own per-turn autosave: session_latest.json under the redirected HOME, which+ travels in the checkpoint."""+ with contextlib.redirect_stdout(sys.stderr):+ try:+ cc_session.autosave_session(state, config)+ except Exception: # noqa: BLE001 — autosave is best-effort in the CLI too+ pass+++if __name__ == "__main__":+ sys.exit(main())diff --git a/runner/server.py b/runner/server.pyindex 750e1c23..e4e83f15 100644--- a/runner/server.py+++ b/runner/server.py@@ -260,6 +260,26 @@ def _aider_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:return any(line.startswith("####") for line in text.splitlines())+def _cheetahclaws_home(cwd: str) -> pathlib.Path:+ """~/.cheetahclaws under the redirected HOME (turn() points HOME at .harness/home)."""+ return pathlib.Path(cwd) / ".harness" / "home" / ".cheetahclaws"+++def _cheetahclaws_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:+ """CheetahClaws has no resume flag: `-p` always starts from an empty state, and continuing is+ the REPL's /resume, which loads the autosaved session_latest.json. So this asks that file, read+ the way /resume reads it: the session is there when the file names this id and holds a message.+ The file is one per HOME, and HOME is redirected into the session's workspace, so "latest" is+ this session's own; it travels in the checkpoint with the rest of the home."""+ path = _cheetahclaws_home(cwd) / "sessions" / "mr_sessions" / "session_latest.json"+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return False+ return (isinstance(data, dict) and data.get("session_id") == session_id+ and isinstance(data.get("messages"), list) and bool(data["messages"]))++def _argv_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:"""The builder looked the session up and said so in argv: claude's --resume, opencode's--session and kimi's -r carry the id only when it was found in this workspace."""@@ -306,6 +326,7 @@ _SESSION_PRESENT = {"kimi": _argv_session_present,"aider": _aider_session_present,"openhands": _openhands_session_present,+ "cheetahclaws": _cheetahclaws_session_present,}@@ -500,7 +521,16 @@ CHECKPOINT_EXCLUDE = ["./tmp", "./.gcp-sa.json", "./.codex", "./.credentials.jso# the model is defined from the environment (see _build_kimi)."./.harness/home/.kimi-code/logs","./.harness/home/.kimi-code/cache",- "./.harness/home/.kimi-code/updates"]+ "./.harness/home/.kimi-code/updates",+ # CheetahClaws: sessions/ is what the next turn resumes from and it travels.+ # Its task tracker is written to the WORKSPACE (<cwd>/.cheetahclaws/+ # tasks.json, task/store.py) and is scratch; its mcp.json can carry an MCP+ # server's auth headers (the standing of claude's .mcp.json); its log is+ # the one place it prints what went wrong in full. The provider key is+ # never at rest: the CLI is handed the relay's placeholder in its env.+ "./.cheetahclaws/tasks.json",+ "./.harness/home/.cheetahclaws/mcp.json",+ "./.harness/home/.cheetahclaws/logs"]_GIT_ENV = {"GIT_AUTHOR_NAME": "harness", "GIT_AUTHOR_EMAIL": "[email protected]","GIT_COMMITTER_NAME": "harness", "GIT_COMMITTER_EMAIL": "[email protected]"}CLAUDE_DEFAULT_MODEL = os.environ.get("CLAUDE_DEFAULT_MODEL", "claude-sonnet-4.6")@@ -519,6 +549,7 @@ GOOSE_DEFAULT_MODEL = os.environ.get("GOOSE_DEFAULT_MODEL", "gpt-5.4")KIMI_DEFAULT_MODEL = os.environ.get("KIMI_DEFAULT_MODEL", "kimi-k3")AIDER_DEFAULT_MODEL = os.environ.get("AIDER_DEFAULT_MODEL", "gpt-5.4")OPENHANDS_DEFAULT_MODEL = os.environ.get("OPENHANDS_DEFAULT_MODEL", "gpt-5.4")+CHEETAHCLAWS_DEFAULT_MODEL = os.environ.get("CHEETAHCLAWS_DEFAULT_MODEL", "gpt-5.4")CODEX_REASONING_EFFORT = os.environ.get("CODEX_REASONING_EFFORT", "medium")# The window Codex plans compaction against. Its own catalog says 272k for every gpt-5.x; a larger# number here made it compact late and let a long thread overflow the real window first.@@ -616,6 +647,7 @@ def _git_ensure(ws: str) -> None:".harness/home/.hermes/.env", ".harness/home/.hermes/auth.json",".harness/home/.pi/agent/auth.json", ".harness/home/.pi/agent/models.json",".harness/goose/config/secrets.yaml",+ ".cheetahclaws/tasks.json","# harness: the CLI home is checkpointed by tar, not by this repo (see _git_ensure)",".harness/home/","",@@ -692,6 +724,9 @@ def _git_shed_cli_home_history(ws: str) -> None:# ── input/output file plumbing (OpenAI Responses input_file blocks + container files) ──# Paths never reported as agent-produced output (internal state / scratch / secrets / vcs)._PRODUCED_EXCLUDE_PREFIX = (".harness/", "tmp/", ".codex/", ".git/", ".claude/", ".pi/",+ # cheetahclaws: its project-level skills folder (written by+ # _write_skills) and its task tracker, both CLI state+ ".cheetahclaws/","node_modules/", ".venv/", "venv/", "__pycache__/", ".cache/", ".next/")_PRODUCED_EXCLUDE_NAMES = {".gitignore", ".gcp-sa.json", ".credentials.json"}# Dependency / install / build-cache noise the agent pulls in (apt debs, npm/py deps, byte-compiled@@ -766,9 +801,11 @@ def _mcp_name(s: str) -> str:return n or "mcp"-def _write_mcp_config_claude(cwd: str, servers: list[dict]) -> str | None:+def _write_mcp_config_claude(cwd: str, servers: list[dict],+ dest: pathlib.Path | None = None) -> str | None:"""Write a Claude Code .mcp.json for the enabled MCP servers. Returns its path- (passed via --mcp-config), or None if there are none.+ (passed via --mcp-config), or None if there are none. `dest` puts the same document where+ another CLI that reads this format looks for it (cheetahclaws: ~/.cheetahclaws/mcp.json).Both remote (http/sse, keyed on `url`) and local (stdio, keyed on `command`) serversare supported — stdio is the CLI's own default transport (`claude mcp add` defaults to@@ -799,7 +836,7 @@ def _write_mcp_config_claude(cwd: str, servers: list[dict]) -> str | None:entries[name] = entryif not entries:return None- path = pathlib.Path(cwd) / HARNESS_STATE / "mcp.json"+ path = dest or pathlib.Path(cwd) / HARNESS_STATE / "mcp.json"path.parent.mkdir(parents=True, exist_ok=True)path.write_text(json.dumps({"mcpServers": entries}, indent=2))return str(path)@@ -923,6 +960,16 @@ def _write_skills(cwd: str, skills: list[dict], backend: str = "claude") -> list# frontmatter does not match its directory name.rootrels = [".harness/goose/config/skills"]entryroot = ".harness/goose/config/skills"+ elif backend == "cheetahclaws":+ # <cwd>/.cheetahclaws/skills — the PROJECT-level root of the CLI's loader+ # (skill/loader.py _get_skill_paths: project first, then ~/.cheetahclaws/skills, then the+ # built-ins, deduplicated in that order), so a harness skill wins over a built-in of the+ # same name. It is in the workspace, and `.cheetahclaws/` is in _PRODUCED_EXCLUDE_PREFIX+ # for that reason: the bundle is never handed back as a deliverable. The loader reads+ # `SKILL.md` or `skill.md` with the Claude Code frontmatter, and the agent reaches a skill+ # through its own `Skill` and `SkillList` tools.+ rootrels = [".cheetahclaws/skills"]+ entryroot = ".cheetahclaws/skills"elif backend == "kimi":# --skills-dir "Overrides default discovery" (repeatable), so like opencode the loader# adapts to us and there is no per-CLI home directory to guess. Verified on 1.50.0: a skill@@ -1273,6 +1320,10 @@ def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:# "<!-- From: .../AGENTS.md -->" fence, with a behavioural instruction in it obeyed.# aider has no instruction-file convention of its own (no AGENTS.md discovery, no# CLAUDE.md): the file is written here and the driver puts it into aider's system message.+ # cheetahclaws reads CLAUDE.md and ONLY CLAUDE.md (context.py get_claude_md: the first one+ # walking up from the cwd, plus ~/.claude/CLAUDE.md; no source hit for AGENTS.md in+ # 3.5.88), so it takes the CLAUDE.md branch below, and an AGENTS.md in the workspace is+ # never loaded whether or not a CLAUDE.md is there."AGENTS.md" if backend in ("codex", "hermes", "pi", "dsh", "opencode", "cline", "omp","goose", "kimi", "aider", "openhands")else "CLAUDE.md")@@ -2946,6 +2997,26 @@ def _drop_stream_options(body: bytes) -> bytes:return body+def _request_stream_usage(body: bytes) -> bytes:+ """Ask for the usage chunk on a streamed chat-completions body that does not ask for it.++ OpenAI-shaped endpoints report usage on a stream only when the request carries+ `stream_options: {"include_usage": true}`, and a client that leaves it out gets a turn the+ relay cannot count. CheetahClaws's `custom/` client is one (3.5.88, stream_openai_compat sends+ model, messages, stream, tools, tool_choice and max_tokens, nothing else), and its session file+ carries no usage the runner can use. Set only on the routes that ask for it, and only when the+ body streams and names no stream_options of its own; a provider that refuses the field meets+ the relay's existing one-time retry without it (_drop_stream_options), which then sticks."""+ try:+ obj = json.loads(body)+ if isinstance(obj, dict) and obj.get("stream") is True and "stream_options" not in obj:+ obj["stream_options"] = {"include_usage": True}+ return json.dumps(obj, separators=(",", ":")).encode()+ except Exception: # noqa: BLE001 — a body we cannot parse is a body we must not alter+ pass+ return body++def _rename_max_tokens(body: bytes) -> bytes:"""max_tokens -> max_completion_tokens in one chat-completions body.@@ -3464,6 +3535,8 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):_body_model = ""if body is not None and self.path.endswith("/chat/completions"):body = _normalize_openai_chat_body(body)+ if flags.get("stream_usage"):+ body = _request_stream_usage(body)if flags.get("rename_max_tokens"):body = _rename_max_tokens(body)if flags.get("stringify_tool_content"):@@ -3793,12 +3866,14 @@ def _gemini_relay_route(host_root: str, api_key: str, model: str = "", native_moreturn f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok-def _hermes_relay_route(base_url: str, api_key: str, drop_fields: tuple[str, ...] = ()) -> tuple[str, str]:+def _hermes_relay_route(base_url: str, api_key: str, drop_fields: tuple[str, ...] = (),+ stream_usage: bool = False) -> tuple[str, str]:"""Register one turn's upstream; → (relay base_url, placeholder bearer for the CLI).`drop_fields` names top-level request fields this route's client sends on its own initiative andthe harness never asked for; they are removed before the provider sees them (the same list the- relay grows by itself when a provider names an unknown field)."""+ relay grows by itself when a provider names an unknown field). `stream_usage` asks the provider+ for a streamed call's usage when the client does not (_request_stream_usage)."""with _HERMES_RELAY["lock"]:if _HERMES_RELAY["server"] is None:srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _HermesRelayHandler)@@ -3812,7 +3887,8 @@ def _hermes_relay_route(base_url: str, api_key: str, drop_fields: tuple[str, ...# matrix; Anthropic's OpenAI-compatible surface lives under /v1). Bedrock keeps its host# (its own path is built in _bedrock_anthropic)._HERMES_RELAY["routes"][tok] = (_relay_base_with_version(base_url), api_key,- {"rename_max_tokens": False, "drop_fields": tuple(drop_fields)})+ {"rename_max_tokens": False, "drop_fields": tuple(drop_fields),+ "stream_usage": bool(stream_usage)})return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok@@ -4351,6 +4427,81 @@ def _build_aider(provider: str, auth: Auth, model: str, prompt: str, cwd: str, ereturn [AIDER_PYTHON, AIDER_DRIVER, json.dumps(job)]+# ── cheetahclaws ────────────────────────────────────────────────────────────────+# CheetahClaws (SAIL-Research-Lab/cheetahclaws, PyPI `cheetahclaws`, Apache-2.0), pinned to 3.5.88.+# The turn process is runner/cheetahclaws_driver.py inside the pinned venv: the CLI's own agent loop+# is driven IN PROCESS and every event it yields is re-emitted as it happens (the aider shape, for+# the reasons the driver's docstring measures: `-p` has no event stream, the session file is+# written once per turn, a provider failure is prose with exit 0, and there is no resume flag).+#+# ONE provider type, measured: `custom/<model>` is CheetahClaws's OpenAI Chat Completions client+# (providers.py, stream_openai_compat) aimed at CUSTOM_BASE_URL with CUSTOM_API_KEY, which is+# exactly what the loopback relay fronts. So the runner providers are the chat-completions ones;+# no Anthropic Messages or Responses path is offered, because the CLI is not asked to speak one.+CHEETAHCLAWS_PROVIDERS = {"openai-api", "tokenrouter"}+CHEETAHCLAWS_PYTHON = os.environ.get("HR_CHEETAHCLAWS_PYTHON",+ "/data/agent-tools/cheetahclaws-venv/bin/python")+CHEETAHCLAWS_DRIVER = os.path.join(os.path.dirname(os.path.abspath(__file__)),+ "cheetahclaws_driver.py")+# The `tools` array a live 3.5.88 turn sent its provider, captured at a stub (the CLI's default+# "full" profile, bare package), minus what the driver withholds on every turn in this image:+# AskUserQuestion, ReadEmail and SendEmail (cheetahclaws_driver.ALWAYS_WITHHELD) and the four tools+# of optional extras that are not installed (OPTIONAL_TOOLS: WebBrowse, ReadPDF, ReadSpreadsheet,+# ReadImage). These are the names `disabled_tools` matches, exactly and case-sensitively; the+# gateway's catalog is pinned equal to this tuple (gateway/tests/test_catalog_cheetahclaws_tools.py),+# so a toggle the console shows always withholds a tool the model was actually offered.+CHEETAHCLAWS_TOOLS = ("Agent", "Bash", "CheckAgentResult", "Edit", "EnterPlanMode", "ExitPlanMode",+ "GetDiagnostics", "Glob", "Grep", "ListAgentTasks", "ListAgentTypes",+ "MemoryDelete", "MemoryList", "MemorySave", "MemorySearch", "MemoryVerify",+ "NotebookEdit", "Read", "Research", "SendMessage", "Skill", "SkillList",+ "SleepTimer", "SummarizeLargeFile", "TaskCreate", "TaskGet", "TaskList",+ "TaskUpdate", "WebFetch", "WebSearch", "Write")+++def _build_cheetahclaws(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,+ resume_session_id: str | None = None,+ mcp_servers: list[dict] | None = None,+ tools_disabled: list[str] | None = None,+ max_turns: int | None = None) -> list[str]:+ pr = provider or "openai-api"+ if pr not in CHEETAHCLAWS_PROVIDERS:+ raise HTTPException(400, f"unknown cheetahclaws provider '{pr}' "+ f"(one of {sorted(CHEETAHCLAWS_PROVIDERS)})")+ if not auth.base_url:+ raise HTTPException(400, "cheetahclaws needs a base_url (none configured)")+ if auth.api_key:+ # Every turn rides the loopback relay: the CLI is handed the relay's address and a+ # per-turn placeholder, never the key, and the relay's taps supply what the CLI does not+ # report — the served model (matrix rule 2) and fresh / cached / output tokens. The session+ # file carries neither: its totals are the GROSS prompt tokens with no cache split, and it+ # names no model.+ relay_base, relay_tok = _hermes_relay_route(auth.base_url, auth.api_key, stream_usage=True)+ auth = auth.model_copy(update={"base_url": relay_base, "api_key": relay_tok})+ # The two names providers.py reads for `custom/`. custom_base_url in config.json would win+ # over the variable, and the driver writes no config.json, so the variable is what applies.+ env["CUSTOM_BASE_URL"] = auth.base_url+ env["CUSTOM_API_KEY"] = auth.api_key or ""+ home = _cheetahclaws_home(cwd)+ home.mkdir(parents=True, exist_ok=True)+ # MCP in the Claude Code `mcpServers` shape the CLI reads (mcp_client/config.py) at its+ # user-level path, rewritten every turn so a server the harness no longer names is gone. The+ # project-level <cwd>/.mcp.json is the user's own file and is left alone.+ mcp = home / "mcp.json"+ if not _write_mcp_config_claude(cwd, mcp_servers or [], dest=mcp):+ mcp.write_text(json.dumps({"mcpServers": {}}))+ have = _cheetahclaws_session_present(cwd, [], resume_session_id) if resume_session_id else False+ job = {"cwd": cwd, "model": f"custom/{model}", "prompt": prompt,+ # the session to continue, only when its file is here (see _resume_lost)+ "session_id": resume_session_id if have else "",+ # withheld from the tool schema by the CLI's own `disabled_tools` (the driver expands+ # an MCP tool's bare or server.tool name to its mcp__server__tool registry name)+ "tools_disabled": list(tools_disabled or []),+ # the loop has no step limit of its own; the driver stops it through run()'s+ # cancel_check once this many model calls have been made+ "max_turns": max_turns}+ return [CHEETAHCLAWS_PYTHON, CHEETAHCLAWS_DRIVER, json.dumps(job)]++# Path A only (Gemini API Key / Google AI Studio). Unlike qwen, upstream gemini-cli speaks NO@@ -5707,6 +5858,90 @@ def _aider_eof(state: dict, rc: int) -> list[dict]:_aider_to_claude.eof = _aider_eof # type: ignore[attr-defined]+# ── cheetahclaws ───────────────────────────────────────────────────────────────+# One driver line → claude stream-json. The driver emits `__hr_init` first (the session id it+# loaded or minted), then the loop's events AS THEY ARE YIELDED — `text` is a streamed delta, so the+# console renders the answer while it is written — and `__hr_result` last, carrying the driver's+# verdict. The verdict is structural (see cheetahclaws_driver.verdict): nothing here reads prose to+# decide whether the turn failed. The CLI's own notices (`[Retry 1/3 …]`, `[Failed — …]`) arrive as+# `notice` and are never rendered as the answer; the last `[Failed — …]` is the failure's reason.+_CHEETAHCLAWS_ERR_RE = re.compile(r"^\s*\[?Failed — ")+++def _cheetahclaws_to_claude(obj: dict, state: dict) -> list[dict]:+ m = obj.get("m")+ p = obj.get("p") if isinstance(obj.get("p"), dict) else {}+ if m == "__hr_init":+ state["_cc_init"] = True+ return [{"type": "system", "subtype": "init", "session_id": str(p.get("session_id") or ""),+ "model": state.get("model")}]+ if m == "text":+ txt = str(p.get("text") or "")+ if not txt:+ return []+ state["_cc_text"] = state.get("_cc_text", "") + txt+ return [{"type": "assistant", "message": {"content": [{"type": "text", "text": txt}]}}]+ if m == "thinking":+ txt = str(p.get("text") or "")+ return [{"type": "assistant", "message": {"content": [{"type": "thinking", "thinking": txt}]}}] if txt else []+ if m == "tool_start":+ # A new call ends the text before it: the next text is a new paragraph, not a run-on of+ # the sentence that announced the call.+ if state.get("_cc_text") and not state["_cc_text"].endswith("\n"):+ state["_cc_text"] += "\n\n"+ return [{"type": "assistant", "message": {"content": [+ {"type": "tool_use", "id": str(p.get("id") or ""), "name": str(p.get("name") or ""),+ "input": p.get("input") if isinstance(p.get("input"), dict) else {}}]}}]+ if m == "tool_end":+ result = str(p.get("result") or "")+ # The loop's own rule for an errored tool result (agent.py, its loop guard): a denial, or a+ # result that opens with "error"/"denied".+ head = result.lstrip()[:24].lower()+ err = (not p.get("permitted", True)) or head.startswith("error") or head.startswith("denied")+ return [{"type": "user", "message": {"content": [+ {"type": "tool_result", "tool_use_id": str(p.get("id") or ""), "is_error": err,+ "content": result}]}}]+ if m == "notice":+ state.setdefault("_cc_notices", []).append(str(p.get("text") or ""))+ return []+ if m == "mcp_unavailable":+ # The CLI leaves a server that did not connect out of the turn and says nothing; the+ # gateway renders this as a note on the reply, as it does for kimi.+ servers = [s for s in (p.get("servers") or []) if isinstance(s, dict) and s.get("name")]+ return [{"type": "system", "subtype": "mcp_unavailable", "servers": servers}] if servers else []+ if m == "warning":+ state.setdefault("_cc_warnings", []).append(str(p.get("text") or ""))+ return []+ if m == "__hr_result":+ ok = bool(p.get("ok"))+ sub = str(p.get("subtype") or ("success" if ok else "error"))+ final = str(p.get("final") or "")+ if ok or sub == "error_max_turns":+ state["final"] = final+ # usage is {} on purpose: the relay's taps count what the provider reported (fresh, cached+ # and output tokens) and _run_turn_bg stamps them; the CLI's own totals are gross prompt+ # tokens with no cache split.+ return [{"type": "result", "subtype": sub, "is_error": not ok and sub != "error_max_turns",+ "result": final if (ok or final) else str(p.get("reason") or ""),+ "usage": {}}]+ return []+++def _cheetahclaws_eof(state: dict, rc: int) -> list[dict]:+ """The driver emits its own result, so this fires only when it died before reaching it (an+ import failure, a kill). The reason is the last `[Failed — …]` notice if one got that far, and+ otherwise the errbuf tail _failure_reason prefers."""+ failed = [n for n in state.get("_cc_notices") or [] if _CHEETAHCLAWS_ERR_RE.match(n)]+ err = failed[-1].strip().strip("[]") if failed else ""+ if rc == 0 and not err and state.get("_cc_text"):+ return [{"type": "result", "subtype": "success", "is_error": False,+ "result": state.get("_cc_text", ""), "usage": {}}]+ return [{"type": "result", "subtype": "error", "is_error": True, "result": err, "usage": {}}]+++_cheetahclaws_to_claude.eof = _cheetahclaws_eof # type: ignore[attr-defined]++# ── kimi ─────────────────────────────────────────────────────────────────────────@@ -6139,6 +6374,11 @@ BACKENDS = {"openhands": {"providers": sorted(OPENHANDS_PROVIDERS),"default_model": OPENHANDS_DEFAULT_MODEL,"normalize": _openhands_to_claude},+ # The driver emits its own NDJSON (see _cheetahclaws_to_claude), with an eof for a driver that+ # died before its result.+ "cheetahclaws": {"providers": sorted(CHEETAHCLAWS_PROVIDERS),+ "default_model": CHEETAHCLAWS_DEFAULT_MODEL,+ "normalize": _cheetahclaws_to_claude},# The System One driver emits claude's stream-json itself (system/init, assistant tool_use and# thinking blocks, user tool_result, result with usage and a `reason`), so its normaliser is the# passthrough, as qwen's is.@@ -7444,6 +7684,15 @@ def turn(req: TurnReq, identifier: str = "") -> dict:cmd = _build_aider(req.provider, auth, model, req.prompt, cwd, env,mcp_servers=req.mcp_servers, tools_disabled=req.tools_disabled,skills_read=aider_read, max_turns=req.max_turns)+ elif backend == "cheetahclaws":+ model = model or CHEETAHCLAWS_DEFAULT_MODEL+ # Skills are already in <cwd>/.cheetahclaws/skills (_write_skills) and the agent doc in+ # CLAUDE.md, both where the CLI's own loaders look; the builder adds the model, the relay,+ # MCP and the tool policy.+ cmd = _build_cheetahclaws(req.provider, auth, model, req.prompt, cwd, env,+ resume_session_id=req.resume_session_id,+ mcp_servers=req.mcp_servers,+ tools_disabled=req.tools_disabled, max_turns=req.max_turns)elif backend == "openhands":model = model or OPENHANDS_DEFAULT_MODELcmd = _build_openhands(req.provider, auth, model, req.prompt, cwd, env,diff --git a/runner/tests/fixtures/cheetahclaws/session_latest.json b/runner/tests/fixtures/cheetahclaws/session_latest.jsonnew file mode 100644index 00000000..b5dea0a4--- /dev/null+++ b/runner/tests/fixtures/cheetahclaws/session_latest.json@@ -0,0 +1,39 @@+{+ "_version": 1,+ "session_id": "426953bd",+ "title": "Run echo PROBE-OUT and tell me what it printed.",+ "saved_at": "2026-09-24 13:45:49",+ "messages": [+ {+ "role": "user",+ "content": "Run echo PROBE-OUT and tell me what it printed."+ },+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_1",+ "name": "Bash",+ "input": {+ "command": "echo PROBE-OUT"+ }+ }+ ]+ },+ {+ "role": "tool",+ "tool_call_id": "call_1",+ "name": "Bash",+ "content": "PROBE-OUT"+ },+ {+ "role": "assistant",+ "content": "Hello from the stub.",+ "tool_calls": []+ }+ ],+ "turn_count": 2,+ "total_input_tokens": 240,+ "total_output_tokens": 14+}\ No newline at end of filediff --git a/runner/tests/fixtures/cheetahclaws/turn-401.ndjson b/runner/tests/fixtures/cheetahclaws/turn-401.ndjsonnew file mode 100644index 00000000..0e6950c5--- /dev/null+++ b/runner/tests/fixtures/cheetahclaws/turn-401.ndjson@@ -0,0 +1,3 @@+{"m": "__hr_init", "p": {"session_id": "afacd074", "resumed": false, "messages": 0}}+{"m": "notice", "p": {"text": "[Failed \u2014 AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-bad. You can find your API key at https://pla.... Hint: Check your API key: /config or set the appropriate env var (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.)]"}}+{"m": "__hr_result", "p": {"ok": false, "subtype": "error", "final": "", "reason": "Failed \u2014 AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-bad. You can find your API key at https://pla....", "session_id": "afacd074", "calls": 0, "seconds": 0.87}}diff --git a/runner/tests/fixtures/cheetahclaws/turn-429.ndjson b/runner/tests/fixtures/cheetahclaws/turn-429.ndjsonnew file mode 100644index 00000000..173ae624--- /dev/null+++ b/runner/tests/fixtures/cheetahclaws/turn-429.ndjson@@ -0,0 +1,6 @@+{"m": "__hr_init", "p": {"session_id": "cf22ccb4", "resumed": false, "messages": 0}}+{"m": "notice", "p": {"text": "[Retry 1/3 after 6s \u2014 rate_limit: Error code: 429 - {'error': {'message': 'Rate limit reached for requests', 'type': 'requests', 'param': None, 'code':...]"}}+{"m": "notice", "p": {"text": "[Retry 2/3 after 12s \u2014 rate_limit: Error code: 429 - {'error': {'message': 'Rate limit reached for requests', 'type': 'requests', 'param': None, 'code':...]"}}+{"m": "notice", "p": {"text": "[Retry 3/3 after 24s \u2014 rate_limit: Error code: 429 - {'error': {'message': 'Rate limit reached for requests', 'type': 'requests', 'param': None, 'code':...]"}}+{"m": "notice", "p": {"text": "[Failed \u2014 RateLimitError: Error code: 429 - {'error': {'message': 'Rate limit reached for requests', 'type': 'requests', 'param': None, 'code':.... Hint: Rate limited by the API. Will retry with backoff.]"}}+{"m": "__hr_result", "p": {"ok": false, "subtype": "error", "final": "", "reason": "Failed \u2014 RateLimitError: Error code: 429 - {'error': {'message': 'Rate limit reached for requests', 'type': 'requests', 'param': None, 'code':.... Hint: Rate limited by the API. Will retry with backoff.", "session_id": "cf22ccb4", "calls": 0, "seconds": 48.17}}diff --git a/runner/tests/fixtures/cheetahclaws/turn-tool.ndjson b/runner/tests/fixtures/cheetahclaws/turn-tool.ndjsonnew file mode 100644index 00000000..807c41d5--- /dev/null+++ b/runner/tests/fixtures/cheetahclaws/turn-tool.ndjson@@ -0,0 +1,7 @@+{"m": "__hr_init", "p": {"session_id": "426953bd", "resumed": false, "messages": 0}}+{"m": "tool_start", "p": {"id": "call_1", "name": "Bash", "input": {"command": "echo PROBE-OUT"}}}+{"m": "tool_end", "p": {"id": "call_1", "name": "Bash", "result": "PROBE-OUT", "permitted": true}}+{"m": "text", "p": {"text": "Hello "}}+{"m": "text", "p": {"text": "from "}}+{"m": "text", "p": {"text": "the stub."}}+{"m": "__hr_result", "p": {"ok": true, "subtype": "success", "final": "Hello from the stub.", "reason": "", "session_id": "426953bd", "calls": 2, "seconds": 0.93}}diff --git a/runner/tests/fixtures/cheetahclaws/turn-unreachable.ndjson b/runner/tests/fixtures/cheetahclaws/turn-unreachable.ndjsonnew file mode 100644index 00000000..9427eeba--- /dev/null+++ b/runner/tests/fixtures/cheetahclaws/turn-unreachable.ndjson@@ -0,0 +1,6 @@+{"m": "__hr_init", "p": {"session_id": "4f0ded51", "resumed": false, "messages": 0}}+{"m": "notice", "p": {"text": "[Retry 1/3 after 2s \u2014 connection: Connection error.]"}}+{"m": "notice", "p": {"text": "[Retry 2/3 after 4s \u2014 connection: Connection error.]"}}+{"m": "notice", "p": {"text": "[Retry 3/3 after 8s \u2014 connection: Connection error.]"}}+{"m": "notice", "p": {"text": "[Failed \u2014 APIConnectionError: Connection error.. Hint: Network error \u2014 check your internet connection or the API endpoint URL.]"}}+{"m": "__hr_result", "p": {"ok": false, "subtype": "error", "final": "", "reason": "Failed \u2014 APIConnectionError: Connection error.. Hint: Network error \u2014 check your internet connection or the API endpoint URL.", "session_id": "4f0ded51", "calls": 0, "seconds": 61.03}}diff --git a/runner/tests/test_cheetahclaws_backend.py b/runner/tests/test_cheetahclaws_backend.pynew file mode 100644index 00000000..3a3d8b66--- /dev/null+++ b/runner/tests/test_cheetahclaws_backend.py@@ -0,0 +1,480 @@+"""The cheetahclaws backend (SAIL-Research-Lab/cheetahclaws, PyPI `cheetahclaws`, Apache-2.0, 3.5.88).++What these pin, each measured on the pinned version before it was written down:++ the provider failures `cheetahclaws -p` prints and still exits 0 on — an unreachable endpoint, a bad+ key and a 429 — end the turn FAILED with the CLI's own sentence as the reason; the verdict is+ the history's shape (no assistant message came back), never a match on prose+ the CLI's retry/failure notices are not rendered as the answer+ the live stream: every event is re-emitted as the loop yields it (text deltas, tool calls with the+ ids the session file carries)+ resume: the session is the CLI's own session_latest.json under the redirected HOME, loaded before+ the turn and written back after it; a follow-up whose file is gone is reported by _resume_lost+ a disabled tool is withheld from the tool schema the provider receives (`hard`), MCP tools by their+ bare or server.tool name, and AskUserQuestion always (nobody is at the terminal)+ the CLI reads CLAUDE.md only; skills go to the project-level .cheetahclaws/skills; the task tracker+ and that folder are CLI state, never produced files, and the tracker is never checkpointed+ the real key never reaches the CLI: it gets the loopback relay's address and a placeholder++Recorded fixtures (fixtures/cheetahclaws/) are the driver's own output against a stub endpoint on+3.5.88; the tests that run the driver itself skip where the package is not installed.+"""+import http.server+import json+import os+import pathlib+import subprocess+import sys+import tempfile+import threading++import pytest++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import cheetahclaws_driver as drv # noqa: E402+import server # noqa: E402+from server import (Auth, BACKENDS, CHECKPOINT_EXCLUDE, _PRODUCED_EXCLUDE_PREFIX, # noqa: E402+ _agent_doc_path, _build_cheetahclaws, _cheetahclaws_eof,+ _cheetahclaws_to_claude, _resume_lost, _write_skills)++FX = pathlib.Path(__file__).parent / "fixtures" / "cheetahclaws"+++def _lines(name: str) -> list[dict]:+ return [json.loads(x) for x in (FX / name).read_text(encoding="utf-8").splitlines() if x.strip()]+++def _normalise(lines: list[dict]) -> tuple[list[dict], dict]:+ state = {"model": "m", "final": ""}+ out: list[dict] = []+ for obj in lines:+ out += _cheetahclaws_to_claude(obj, state)+ return out, state+++def _result(events: list[dict]) -> dict:+ return [e for e in events if e.get("type") == "result"][-1]+++# ── provider failure: checklist item 6, measured on 3.5.88 ──[email protected]("fixture, prefix", [+ ("turn-unreachable.ndjson", "Failed — APIConnectionError: Connection error."),+ ("turn-401.ndjson", "Failed — AuthenticationError: Error code: 401"),+ ("turn-429.ndjson", "Failed — RateLimitError: Error code: 429"),+])+def test_a_provider_failure_fails_the_turn_with_the_clis_own_sentence(fixture, prefix):+ events, state = _normalise(_lines(fixture))+ res = _result(events)+ assert res["subtype"] == "error" and res["is_error"] is True+ assert res["result"].startswith(prefix)+ assert server._status_from_result(res, 0) == "failed" # the CLI exits 0 on every one of these+ # the retry ladder and the failure are notices, not the answer+ assert not [e for e in events if e.get("type") == "assistant"]+ assert state["final"] == ""+++def test_the_pinned_failure_texts_are_recognised_as_the_clis_notices():+ """Verbatim from `cheetahclaws -p` against a stub (3.5.88, exit 0 each time)."""+ for text in ("\n[Failed — APIConnectionError: Connection error.. Hint: Network error — check your "+ "internet connection or the API endpoint URL.]\n",+ "\n[Failed — AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect "+ "API key provided: sk-bad. You can find your API key at https://pla.... Hint: Check your "+ "API key: /config or set the appropriate env var (ANTHROPIC_API_KEY, OPENAI_API_KEY, "+ "etc.)]\n",+ "\n[Retry 1/3 after 6s — rate_limit: Error code: 429 - {'error': {'message': 'Rate "+ "limit reached for requests', 'type': 'requests', 'param': None, 'code':...]\n",+ "\n[Loop guard] Same tool call repeated 3 times — stopping to prevent a runaway loop.\n"):+ assert drv.is_notice(text), text+ assert not drv.is_notice("Hello from the model")+ assert not drv.is_notice("[Failed — this is the model quoting a log line]") # no leading newline+++def test_a_hint_that_names_the_clis_slash_commands_is_cut_from_the_reason():+ r = drv.failure_reason("[Failed — AuthenticationError: Error code: 401 - {...}. Hint: Check your "+ "API key: /config or set the appropriate env var (OPENAI_API_KEY, etc.)]")+ assert r == "Failed — AuthenticationError: Error code: 401 - {...}."+ r = drv.failure_reason("[Failed — APIConnectionError: Connection error.. Hint: Network error — "+ "check your internet connection or the API endpoint URL.]")+ assert r.endswith("check your internet connection or the API endpoint URL.")+++def test_the_verdict_is_the_historys_shape_not_the_text():+ user = {"role": "user", "content": "hi"}+ # a model that WRITES a failure line is still an answer+ said = [user, {"role": "assistant", "content": "[Failed — AuthenticationError: quoted]"}]+ assert drv.verdict(said, 0, [], False)["ok"] is True+ # a call that never came back leaves the history on the user's message+ v = drv.verdict([user], 0, ["[Failed — APIConnectionError: Connection error.. Hint: x]"], False)+ assert v["ok"] is False and v["reason"].startswith("Failed — APIConnectionError")+ # or on a tool result, when the call after a tool failed+ tool = [user, {"role": "assistant", "content": "", "tool_calls": [{"id": "1", "name": "Bash", "input": {}}]},+ {"role": "tool", "tool_call_id": "1", "content": "x"}]+ assert drv.verdict(tool, 0, [], False)["ok"] is False+ # the loop guard's own message is the CLI stopping the model, not an answer+ lg = [user, {"role": "assistant", "content": "[Loop guard] Same tool call repeated 3 times — stopping."}]+ v = drv.verdict(lg, 0, [], False)+ assert v["ok"] is False and v["reason"].startswith("Loop guard")+ # a resumed history's earlier answer is not this turn's answer+ resumed = [{"role": "user", "content": "a"}, {"role": "assistant", "content": "old answer"}, user]+ assert drv.verdict(resumed, 2, [], False)["ok"] is False+++def test_the_step_budget_ends_the_turn_as_max_turns():+ events, _ = _normalise([{"m": "__hr_init", "p": {"session_id": "s"}},+ {"m": "__hr_result", "p": {"ok": False, "subtype": "error_max_turns", "final": "",+ "reason": "the operator's step budget was reached"}}])+ res = _result(events)+ assert res["subtype"] == "error_max_turns" and res["is_error"] is False+ assert server._status_from_result(res, 0) == "max_turns"+++# ── the live stream ──+def test_the_recorded_turn_streams_calls_and_text_as_they_happen():+ events, state = _normalise(_lines("turn-tool.ndjson"))+ kinds = [(e["type"], (e.get("message") or {}).get("content", [{}])[0].get("type")) for e in events]+ assert kinds[0] == ("system", None) and events[0]["session_id"] == "426953bd"+ assert ("assistant", "tool_use") in kinds and ("user", "tool_result") in kinds+ use = next(e for e in events if e["type"] == "assistant" and e["message"]["content"][0]["type"] == "tool_use")+ res_ev = next(e for e in events if e["type"] == "user")+ # the id is the tool call's own, the one session_latest.json carries+ assert use["message"]["content"][0]["id"] == "call_1" == res_ev["message"]["content"][0]["tool_use_id"]+ assert use["message"]["content"][0]["name"] == "Bash"+ assert res_ev["message"]["content"][0]["content"] == "PROBE-OUT"+ texts = [e["message"]["content"][0]["text"] for e in events+ if e["type"] == "assistant" and e["message"]["content"][0]["type"] == "text"]+ assert texts == ["Hello ", "from ", "the stub."] # three deltas, not one block at the end+ res = _result(events)+ assert res["subtype"] == "success" and res["result"] == "Hello from the stub." and res["usage"] == {}+ assert state["final"] == "Hello from the stub."+++def test_a_refused_or_errored_tool_result_is_marked_as_an_error():+ out = _cheetahclaws_to_claude({"m": "tool_end", "p": {"id": "1", "name": "Bash", "result": "Denied: x",+ "permitted": False}}, {})+ assert out[0]["message"]["content"][0]["is_error"] is True+ out = _cheetahclaws_to_claude({"m": "tool_end", "p": {"id": "1", "name": "Read",+ "result": "Error: no such file", "permitted": True}}, {})+ assert out[0]["message"]["content"][0]["is_error"] is True+++def test_tool_ids_are_paired_to_the_batch_the_model_asked_for():+ p = drv.Pairing()+ p.batch({"role": "assistant", "tool_calls": [{"id": "a", "name": "Read", "input": {}},+ {"id": "b", "name": "Read", "input": {}},+ {"id": "c", "name": "Bash", "input": {}}]})+ assert [p.start("Read", {}), p.start("Read", {}), p.start("Bash", {})] == ["a", "b", "c"]+ assert [p.end("Read"), p.end("Read"), p.end("Bash")] == ["a", "b", "c"]+ assert p.start("Write", {}).startswith("cc") # a start with no call gets its own id+++def test_eof_speaks_only_when_the_driver_died_before_its_result():+ st = {"_cc_notices": ["[Failed — APIConnectionError: Connection error.. Hint: x]"]}+ ev = _cheetahclaws_eof(st, 1)+ assert ev[0]["is_error"] is True and ev[0]["result"].startswith("Failed — APIConnectionError")+ assert _cheetahclaws_eof({}, 137)[0]["is_error"] is True+ assert _cheetahclaws_to_claude.eof is _cheetahclaws_eof+++# ── registration and the builder ──+def test_backend_is_registered():+ spec = BACKENDS["cheetahclaws"]+ assert spec["normalize"] is _cheetahclaws_to_claude+ assert set(spec["providers"]) == {"openai-api", "tokenrouter"}+ assert "cheetahclaws" in server._SESSION_PRESENT+++def _build(**kw):+ d = tempfile.mkdtemp()+ env: dict = {}+ args = dict(provider="openai-api", auth=Auth(api_key="sk-real-key", base_url="https://api.example/v1"),+ model="some-model", prompt="hi", cwd=d, env=env)+ args.update(kw)+ cmd = _build_cheetahclaws(**args)+ return cmd, d, env, json.loads(cmd[2])+++def test_the_real_key_never_reaches_the_cli():+ cmd, _, env, job = _build()+ assert env["CUSTOM_API_KEY"].startswith("hr-relay-") and env["CUSTOM_BASE_URL"].startswith("http://127.0.0.1:")+ assert "sk-real-key" not in json.dumps(env) and "sk-real-key" not in " ".join(cmd)+ assert cmd[0] == server.CHEETAHCLAWS_PYTHON and cmd[1].endswith("cheetahclaws_driver.py")+ assert job["model"] == "custom/some-model" # the CLI's OpenAI-chat client, whatever the id+++def test_an_unknown_provider_and_a_missing_base_url_are_refused():+ with pytest.raises(Exception, match="unknown cheetahclaws provider"):+ _build(provider="anthropic")+ with pytest.raises(Exception, match="needs a base_url"):+ _build(auth=Auth(api_key="k"))+++def test_mcp_servers_are_written_where_the_cli_reads_them_and_cleared_when_gone():+ _, d, _, _ = _build(mcp_servers=[{"name": "probe", "url": "https://x/sse", "transport": "sse", "auth": "tok"},+ {"name": "local", "command": "python3", "args": ["s.py"]}])+ doc = json.loads(pathlib.Path(d, ".harness", "home", ".cheetahclaws", "mcp.json").read_text())+ assert doc["mcpServers"]["probe"] == {"type": "sse", "url": "https://x/sse",+ "headers": {"Authorization": "Bearer tok"}}+ assert doc["mcpServers"]["local"]["type"] == "stdio"+ # the next turn names none: the file is emptied, so a disabled server is not connected+ _build_cheetahclaws("openai-api", Auth(api_key="k", base_url="https://api.example/v1"), "m", "hi", d, {})+ doc = json.loads(pathlib.Path(d, ".harness", "home", ".cheetahclaws", "mcp.json").read_text())+ assert doc == {"mcpServers": {}}+++def test_the_policy_and_the_budget_reach_the_driver():+ _, _, _, job = _build(tools_disabled=["Bash", "probe_sse"], max_turns=9)+ assert job["tools_disabled"] == ["Bash", "probe_sse"] and job["max_turns"] == 9+++def test_disabled_names_withhold_mcp_tools_by_either_name_and_the_question_tool_always():+ reg = ["Bash", "Read", "AskUserQuestion", "mcp__probe__probe_sse", "mcp__probe__other", "mcp__db__query"]+ got = drv.disabled_names(["Bash", "probe_sse", "db.query"], reg)+ assert {"Bash", "mcp__probe__probe_sse", "mcp__db__query", "AskUserQuestion"} <= set(got)+ assert "mcp__probe__other" not in got and "Read" not in got+ assert "AskUserQuestion" in drv.disabled_names([], reg)+ assert {"ReadEmail", "SendEmail"} <= set(drv.disabled_names([], reg))+++def test_a_tool_whose_optional_extra_is_not_installed_is_withheld(monkeypatch):+ import importlib.util+ real = importlib.util.find_spec+ monkeypatch.setattr(importlib.util, "find_spec", lambda name, *a: None if name == "fitz" else real(name, *a))+ assert "ReadPDF" in drv.unavailable_tools() and "ReadPDF" in drv.disabled_names([], ["ReadPDF"])+ monkeypatch.setattr(importlib.util, "find_spec", lambda name, *a: object())+ assert drv.unavailable_tools() == []+++# ── resume: checklist item 5 ──+def _seed_session(d: str) -> str:+ path = pathlib.Path(d, ".harness", "home", ".cheetahclaws", "sessions", "mr_sessions")+ path.mkdir(parents=True, exist_ok=True)+ (path / "session_latest.json").write_text((FX / "session_latest.json").read_text(encoding="utf-8"))+ return json.loads((FX / "session_latest.json").read_text(encoding="utf-8"))["session_id"]+++def test_a_follow_up_resumes_from_the_recorded_session_file():+ d = tempfile.mkdtemp()+ sid = _seed_session(d)+ cmd, _, _, job = _build(cwd=d, resume_session_id=sid)+ assert job["session_id"] == sid+ assert _resume_lost("cheetahclaws", cmd, sid, d) is None+++def test_a_follow_up_whose_session_is_gone_is_reported_lost():+ d = tempfile.mkdtemp()+ cmd, _, _, job = _build(cwd=d, resume_session_id="deadbeef")+ assert job["session_id"] == "" # the driver starts a new conversation+ assert _resume_lost("cheetahclaws", cmd, "deadbeef", d) == "deadbeef"+ # a file that holds ANOTHER conversation is not this one+ _seed_session(d)+ assert _resume_lost("cheetahclaws", cmd, "deadbeef", d) == "deadbeef"+ # a first turn asks for nothing and loses nothing+ assert _resume_lost("cheetahclaws", cmd, None, d) is None+++def test_the_driver_loads_only_the_session_it_was_asked_for():+ d = tempfile.mkdtemp()+ sid = _seed_session(d)+ path = drv.session_file(pathlib.Path(d, ".harness", "home"))+ assert drv.load_session(path, sid)["messages"][-1]["content"] == "Hello from the stub."+ assert drv.load_session(path, "other") is None and drv.load_session(path, "") is None+++# ── hygiene: checklist items 3, 4 and 7 ──+def test_the_instruction_file_is_claude_md():+ assert _agent_doc_path("/w", "cheetahclaws").name == "CLAUDE.md"+++def test_skills_land_in_the_project_level_folder_the_loader_reads_first():+ d = tempfile.mkdtemp()+ got = _write_skills(d, [{"name": "probe-skill", "files": [{"path": "SKILL.md", "content": "---\nname: probe-skill\n"+ "description: d\n---\nbody"}]}],+ "cheetahclaws")+ assert pathlib.Path(d, ".cheetahclaws", "skills", "probe-skill", "SKILL.md").is_file()+ assert got[0]["entry"] == ".cheetahclaws/skills/probe-skill/SKILL.md"+++def test_the_clis_workspace_state_is_never_a_produced_file_and_the_tracker_never_travels():+ assert any(".cheetahclaws/skills/x/SKILL.md".startswith(p) for p in _PRODUCED_EXCLUDE_PREFIX)+ assert any(".cheetahclaws/tasks.json".startswith(p) for p in _PRODUCED_EXCLUDE_PREFIX)+ assert "./.cheetahclaws/tasks.json" in CHECKPOINT_EXCLUDE+ assert "./.harness/home/.cheetahclaws/mcp.json" in CHECKPOINT_EXCLUDE+++# ── the driver itself, against a stub endpoint (needs the pinned package) ──+class _Stub(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"+ requests: list = []+ mode = "ok"++ def log_message(self, *a):+ pass++ def _send(self, code, body, ctype="application/json"):+ data = body if isinstance(body, bytes) else json.dumps(body).encode()+ self.send_response(code)+ self.send_header("content-type", ctype)+ self.send_header("content-length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def do_GET(self):+ self._send(200, {"object": "list", "data": [{"id": "stub-model", "object": "model"}]})++ def do_POST(self):+ req = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}")+ type(self).requests.append(req)+ if type(self).mode == "401":+ return self._send(401, {"error": {"message": "Incorrect API key provided", "type": "invalid_request_error",+ "code": "invalid_api_key"}})+ base = {"id": "c", "object": "chat.completion.chunk", "model": "stub-model", "created": 0}+ if type(self).mode == "call_bash" and not any(m.get("role") == "tool" for m in req.get("messages", [])):+ # the model asks for a tool the harness withheld, the way a model that saw it in an+ # earlier turn's history would+ call = {"index": 0, "id": "call_x", "type": "function",+ "function": {"name": "Bash", "arguments": json.dumps({"command": "echo pwned > PWNED.txt"})}}+ chunks = [{**base, "choices": [{"index": 0, "delta": {"tool_calls": [call]}, "finish_reason": None}]},+ {**base, "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]}]+ body = b"".join(b"data: " + json.dumps(c).encode() + b"\n\n" for c in chunks) + b"data: [DONE]\n\n"+ return self._send(200, body, "text/event-stream")+ chunks = [{**base, "choices": [{"index": 0, "delta": {"content": p}, "finish_reason": None}]}+ for p in ("PONG-", "1")]+ chunks.append({**base, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]})+ body = b"".join(b"data: " + json.dumps(c).encode() + b"\n\n" for c in chunks) + b"data: [DONE]\n\n"+ self._send(200, body, "text/event-stream")+++def stub():+ pytest.importorskip("cheetahclaws", reason="the pinned CheetahClaws lives in its own venv, not here")+ _Stub.requests = []+ _Stub.mode = "ok"+ srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Stub)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ yield srv+ srv.shutdown()+++def _run_driver(ws: str, port: int, prompt: str, **job) -> list[dict]:+ home = pathlib.Path(ws, ".harness", "home")+ home.mkdir(parents=True, exist_ok=True)+ env = {**os.environ, "HOME": str(home), "USERPROFILE": str(home),+ "CUSTOM_BASE_URL": f"http://127.0.0.1:{port}/v1", "CUSTOM_API_KEY": "hr-relay-placeholder"}+ out = subprocess.run([sys.executable, drv.__file__,+ json.dumps({"cwd": ws, "model": "custom/stub-model", "prompt": prompt, **job})],+ cwd=ws, env=env, capture_output=True, text=True, timeout=120)+ assert out.returncode == 0, out.stderr[-2000:]+ return [json.loads(x) for x in out.stdout.splitlines() if x.strip()]+++def test_the_driver_streams_a_turn_and_resumes_it_on_the_next(stub):+ ws = tempfile.mkdtemp()+ first = _run_driver(ws, stub.server_address[1], "say PONG-1")+ assert first[0]["m"] == "__hr_init" and first[0]["p"]["resumed"] is False+ assert [x["p"]["text"] for x in first if x["m"] == "text"] == ["PONG-", "1"]+ assert first[-1]["m"] == "__hr_result" and first[-1]["p"]["ok"] is True and first[-1]["p"]["final"] == "PONG-1"+ sid = first[0]["p"]["session_id"]+ second = _run_driver(ws, stub.server_address[1], "what did you say?", session_id=sid)+ assert second[0]["p"] == {"session_id": sid, "resumed": True, "messages": 2}+ sent = _Stub.requests[-1]["messages"]+ assert [m["content"] for m in sent if m["role"] == "user"][-2:] == ["say PONG-1", "what did you say?"]+++def test_the_driver_fails_a_turn_the_provider_refused(stub):+ _Stub.mode = "401"+ lines = _run_driver(tempfile.mkdtemp(), stub.server_address[1], "hi")+ res = lines[-1]["p"]+ assert res["ok"] is False and res["reason"].startswith("Failed — AuthenticationError: Error code: 401")+ assert "/config" not in res["reason"]+ assert not [x for x in lines if x["m"] == "text"]+++def test_a_disabled_tool_is_not_in_the_schema_the_provider_receives(stub):+ _run_driver(tempfile.mkdtemp(), stub.server_address[1], "hi", tools_disabled=["Bash", "Write"])+ offered = {t["function"]["name"] for t in _Stub.requests[-1].get("tools") or []}+ assert offered and "Read" in offered+ assert not {"Bash", "Write", "AskUserQuestion"} & offered+++def test_a_call_to_a_withheld_tool_is_refused_at_execution_too(stub):+ _Stub.mode = "call_bash"+ ws = tempfile.mkdtemp()+ lines = _run_driver(ws, stub.server_address[1], "hi", tools_disabled=["Bash"])+ end = next(x["p"] for x in lines if x["m"] == "tool_end")+ assert end["name"] == "Bash" and end["result"].startswith("Error: tool 'Bash' is not enabled")+ assert not pathlib.Path(ws, "PWNED.txt").exists()+++def test_the_harness_instructions_reach_the_system_prompt_from_claude_md(stub):+ ws = tempfile.mkdtemp()+ pathlib.Path(ws, "CLAUDE.md").write_text("Always answer in the voice of PROBE-DOC-7.\n")+ pathlib.Path(ws, "AGENTS.md").write_text("Always answer in the voice of PROBE-AGENTS-9.\n")+ _run_driver(ws, stub.server_address[1], "hi")+ system = next(m["content"] for m in _Stub.requests[-1]["messages"] if m["role"] == "system")+ assert "PROBE-DOC-7" in system and "PROBE-AGENTS-9" not in system+++# ── served model and usage: checklist item 5 ──+def test_the_relay_asks_for_stream_usage_on_this_route_only_and_counts_it():+ """The CLI's `custom/` client streams without stream_options (3.5.88), and an OpenAI-shaped+ provider then sends no usage at all, so the relay would have nothing to count. This route asks+ for it; a route that did not ask sends the body as the client wrote it."""+ import urllib.request+ seen: list = []++ class Upstream(http.server.BaseHTTPRequestHandler):+ def log_message(self, *a):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}")+ seen.append(body)+ usage = ({"prompt_tokens": 40, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 30}}+ if (body.get("stream_options") or {}).get("include_usage") else None)+ chunks = [{"id": "c", "object": "chat.completion.chunk", "model": "served-x",+ "choices": [{"delta": {"content": "hi"}, "finish_reason": "stop"}]}]+ if usage:+ chunks.append({"id": "c", "object": "chat.completion.chunk", "model": "served-x",+ "choices": [], "usage": usage})+ data = b"".join(b"data: " + json.dumps(c).encode() + b"\n\n" for c in chunks) + b"data: [DONE]\n\n"+ self.send_response(200)+ self.send_header("content-type", "text/event-stream")+ self.end_headers()+ self.wfile.write(data)++ up = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Upstream)+ threading.Thread(target=up.serve_forever, daemon=True).start()+ env: dict = {}+ other = None+ try:+ _build_cheetahclaws("openai-api", Auth(api_key="sk-real", base_url=f"http://127.0.0.1:{up.server_address[1]}/v1"),+ "m", "hi", tempfile.mkdtemp(), env)+ base, tok = env["CUSTOM_BASE_URL"], env["CUSTOM_API_KEY"]+ other = server._hermes_relay_route(f"http://127.0.0.1:{up.server_address[1]}/v1", "sk-real")[1]+ for bearer in (tok, other):+ body = json.dumps({"model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]}).encode()+ req = urllib.request.Request(base + "/chat/completions", data=body, method="POST",+ headers={"authorization": f"Bearer {bearer}", "content-type": "application/json"})+ urllib.request.urlopen(req, timeout=10).read()+ assert seen[0]["stream_options"] == {"include_usage": True}+ assert "stream_options" not in seen[1]+ assert server._relay_usage(env) == {"input_tokens": 10, "output_tokens": 4, "cache_read_tokens": 30}+ assert server._relay_served_model(env) == "served-x"+ finally:+ up.shutdown()+ server._HERMES_RELAY["routes"].pop(env.get("CUSTOM_API_KEY"), None)+ server._HERMES_RELAY["routes"].pop(other, None)+++def test_a_body_that_already_asks_or_does_not_stream_is_left_alone():+ same = json.dumps({"stream": True, "stream_options": {"include_usage": False}}).encode()+ assert server._request_stream_usage(same) == same+ plain = json.dumps({"stream": False}).encode()+ assert server._request_stream_usage(plain) == plain+ assert server._request_stream_usage(b"not json") == b"not json"+++def test_an_mcp_server_that_did_not_connect_becomes_a_note_on_the_reply():+ out = _cheetahclaws_to_claude({"m": "mcp_unavailable", "p": {"servers": [{"name": "dead", "reason": "refused"}]}}, {})+ assert out == [{"type": "system", "subtype": "mcp_unavailable", "servers": [{"name": "dead", "reason": "refused"}]}]+ assert _cheetahclaws_to_claude({"m": "mcp_unavailable", "p": {"servers": []}}, {}) == []diff --git a/scripts/support-matrix/custom-harness.mjs b/scripts/support-matrix/custom-harness.mjsindex a15a4642..40602f3c 100644--- a/scripts/support-matrix/custom-harness.mjs+++ b/scripts/support-matrix/custom-harness.mjs@@ -14,7 +14,7 @@ import { chromium } from 'playwright';import crypto from 'node:crypto';const BASE = process.env.BASE;-const BASES = (process.env.BASES || 'codex,claude-code,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider,openhands').split(','); // every built-in harness, all fourteen+const BASES = (process.env.BASES || 'codex,claude-code,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider,openhands,cheetahclaws').split(','); // every built-in chat harness, all fifteen (systemone runs decision models only)const RESULTS = process.env.RESULTS || 'results-custom.json';// A harness's other kind of tool is an MCP server. A self-contained instance hosts only the// database and media servers, one needing a database and the other costing real money per call, sodiff --git a/scripts/support-matrix/plugins/run-matrix.py b/scripts/support-matrix/plugins/run-matrix.pyindex 1b39d00a..15d746f4 100755--- a/scripts/support-matrix/plugins/run-matrix.py+++ b/scripts/support-matrix/plugins/run-matrix.py@@ -35,7 +35,7 @@ HERE = pathlib.Path(__file__).parentFIXTURE = HERE / "fixture"# Every base the catalog serves. Since #180/#182 every one of them takes a stdio server (pi's# adapter and dsh's client spawn it themselves), so no base is expected to refuse any column.-BASES = ["claude-code", "codex", "hermes", "goose", "gemini", "qwen", "opencode", "cline", "omp", "pi", "dsh", "kimi", "aider", "openhands"]+BASES = ["claude-code", "codex", "hermes", "goose", "gemini", "qwen", "opencode", "cline", "omp", "pi", "dsh", "kimi", "aider", "openhands", "cheetahclaws"]NO_STDIO: set[str] = set()# The public probe the remote columns call: its SSE end answers PROBE-SSE-<id>, its streamable-HTTP# end PROBE-HTTP-<id>. Both are the same fixed server, so a wrong answer is the base, not the probe.diff --git a/ui/public/logos/cheetahclaws.png b/ui/public/logos/cheetahclaws.pngnew file mode 100644index 00000000..2df7e52cBinary files /dev/null and b/ui/public/logos/cheetahclaws.png differdiff --git a/ui/src/components/HarnessLogo.tsx b/ui/src/components/HarnessLogo.tsxindex 1c3257fb..6d166d74 100644--- a/ui/src/components/HarnessLogo.tsx+++ b/ui/src/components/HarnessLogo.tsx@@ -19,6 +19,7 @@ const LOGO: Record<string, string> = {kimi: '/logos/kimi.png', // the official Kimi mark (the K app icon from kimi.ai/code), supplied by Richard 2026-09-17aider: '/logos/aider.png', // aider's own app icon (aider.chat/assets/icons/apple-touch-icon.png, from the Apache-2.0 repo's website assets)openhands: '/logos/openhands.png', // OpenHands' own app icon (public/apple-touch-icon.png in the MIT OpenHands/OpenHands repository)+ cheetahclaws: '/logos/cheetahclaws.png', // CheetahClaws' own app icon (cheetahclaws/web/static/favicon.png in the Apache-2.0 SAIL-Research-Lab/cheetahclaws repository, shipped in the 3.5.88 wheel)systemone: '/logos/systemone.png', // the System One Harness's own mark (the project has no vendor logo; Jev is TypeSafe's model, not the harness)};diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.tsindex d3d8b72e..6fa7223a 100644--- a/ui/src/lib/harness.ts+++ b/ui/src/lib/harness.ts@@ -20,7 +20,7 @@ export interface OobHarness {defaultModel?: string; // the backend default, NOT necessarily models[0]moreModels?: number; // "+N" pillstatus: 'ready' | 'soon';- backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | 'aider' | 'openhands' | 'systemone' | null; // gateway backend; null = coming soon+ backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | 'aider' | 'openhands' | 'systemone' | 'cheetahclaws' | null; // gateway backend; null = coming soonsystemPrompt: string; // the harness's built-in system prompt (shown read-only)tools: string[]; // built-in tools (read-only)skills: string[]; // built-in skills (read-only)@@ -157,6 +157,13 @@ export const OOB: OobHarness[] = [models: ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-3.3-70b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning', 'nemotron-3-super'], defaultModel: 'gpt-5.4', moreModels: 0,systemPrompt: 'You are OpenHands, an autonomous coding agent. You work on a real git workspace with shell and file access, reading and editing files and running commands to complete the task end to end.',tools: [], skills: [] },+ { id: 'cheetahclaws', name: 'CheetahClaws', version: 'v3.5.88', backend: 'cheetahclaws', status: 'ready',+ // Placeholder only, like every list above: the gateway's catalog wins once fetched. The list is+ // the other chat-completions bases' (same relay reach); _MODEL_CATALOG["cheetahclaws"] says what+ // has and has not been measured on it.+ models: ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-3.3-70b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning', 'nemotron-3-super'], defaultModel: 'gpt-5.4', moreModels: 0,+ systemPrompt: 'You are CheetahClaws, an autonomous coding agent. You work on a real git workspace with shell and file access, reading and editing files and running commands to complete the task end to end.',+ tools: [], skills: [] },{ id: 'systemone', name: 'System One', version: 'v0.4.0', backend: 'systemone', status: 'ready',// Placeholder only: the gateway's catalog wins once fetched. Jev, a decision model, under the// ids its two providers serve: jev-latest on both (the default), jev-preview on TypeSafe's own