Skip to content

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.

aider: a new backend (Aider 0.86.2) (#211)

ZixiaoL86505b5b1fb4
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 6872d52f..d6d47c68 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -177,7 +177,7 @@ export HOSTNAME=0.0.0.0
TOOLS="$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}"
+export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider}"
wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }
# The executable IS the definition of "installed" — an installer that exits 0 without producing
@@ -197,6 +197,7 @@ backend_bin() {
omp) echo "$TOOLS/bin/omp" ;;
goose) echo "$TOOLS/bin/goose" ;;
kimi) echo "$TOOLS/bin/kimi" ;;
+ aider) echo "$TOOLS/aider-venv/bin/aider" ;;
esac
}
@@ -240,6 +241,51 @@ install_opencode() {
# download has to go unverified: the digests are pinned HERE instead, computed from the v1.50.0
# release assets (each archive holds exactly ./goose). That is strictly stronger than the tag
# alone, which can be moved and whose asset can be re-uploaded.
+# Aider, Apache-2.0 (Aider-AI/aider), pinned to 0.86.2, plus the MCP bridge it needs.
+#
+# Its own venv, the dsh/hermes precedent: aider pins litellm and a large scientific stack, and must
+# not share the runner's interpreter. The version is pinned exactly and aider's own wheel pins every
+# dependency to a version, so the venv is the same one on every volume; there is no digest check
+# here, the release is trusted the way the other PyPI installs (dsh) are.
+#
+# NOTE the Python floor: aider 0.86.2 declares Requires-Python <3.13,>=3.10. On an interpreter
+# outside that range pip does not fail — it silently offers an OLDER aider (0.82.3 was the highest
+# on 3.9), and every behaviour runner/aider_driver.py was written against would be absent without a
+# single error. The explicit version pin below is what turns that into a hard failure.
+#
+# The official MCP SDK goes in beside it: upstream aider has no MCP client at all, so
+# runner/aider_mcp_bridge.py is what lets a declared MCP server be reached and, therefore, measured.
+# Installed in this venv rather than globally because no other backend uses it.
+AIDER_PIN="${HR_AIDER_VERSION:-0.86.2}"
+install_aider() {
+ am_py="${HR_AIDER_BASE_PYTHON:-python3}"
+ # The venv lives on the data volume, so a pin bump in the image must reach a volume that
+ # already has one (the dsh precedent): aider-ready names the version the venv was built for,
+ # and a mismatch rebuilds it. Sessions keep nothing in the venv.
+ rm -rf "$TOOLS/aider-venv"
+ "$am_py" -m venv "$TOOLS/aider-venv" || return 1
+ "$TOOLS/aider-venv/bin/pip" install -q --disable-pip-version-check \
+ "aider-chat==$AIDER_PIN" || return 1
+ # The driver imports aider in process; prove the pinned version is importable before declaring the
+ # install good, so a resolver that quietly picked another one fails HERE and not on a live turn.
+ "$TOOLS/aider-venv/bin/python" -c '
+import sys, aider
+want = sys.argv[1]
+if aider.__version__ != want:
+ sys.exit("aider %s installed, wanted %s" % (aider.__version__, want))
+' "$AIDER_PIN" || return 1
+ # aider's MCP client: the official MIT SDK, into the same venv. f/mcptools was the first choice
+ # and is not usable here — it is a Go program that publishes NO binaries on any release (checked
+ # through v0.7.1, every one has zero assets), so it would mean a Go toolchain in a python-slim
+ # image for one command.
+ "$TOOLS/aider-venv/bin/pip" install -q --disable-pip-version-check \
+ "mcp==${HR_MCP_SDK_VERSION:-2.2.0}" || return 1
+ # Written LAST, after both installs and the version check 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' "$AIDER_PIN" > "$TOOLS/aider-venv/bin/aider-ready" \
+ && chmod +x "$TOOLS/aider-venv/bin/aider-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
@@ -451,6 +497,16 @@ install_backends() {
try_install "Kimi Code CLI" install_kimi || true
fi
+ # The largest install of the set: ~735 MB and about ninety seconds on a fresh volume
+ # (tree-sitter-language-pack 351 MB, scipy 100, numpy 57). In the default list all the same,
+ # because the console offers every base the gateway's catalogue lists and a base that is listed
+ # but not installed fails on its first task; an operator who does not want it leaves it out of
+ # HR_BACKENDS, the same switch every backend has.
+ if wanted aider && [ "$("$TOOLS/aider-venv/bin/aider-ready" 2>/dev/null)" != "$AIDER_PIN" ]; then
+ echo "[harnessrouter] installing Aider $AIDER_PIN (Apache-2.0) — ~735 MB, this takes a minute…"
+ try_install "Aider" install_aider || true
+ fi
+
# The dsh venv lives on the data volume, so a pin bump in the image must reach a volume that
# already has a venv: dsh-ready names the version it was built for, and a mismatch rebuilds
# the venv (sessions live under ~/.dsh, not in it). The 0.1.0rc7 -> 0.1.2rc1 move is where
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.md
index fb34f77f..383ef6c5 100644
--- a/docs/self-hosting-guide.md
+++ b/docs/self-hosting-guide.md
@@ -333,16 +333,16 @@ problem, because it only offers you providers that work.
| Connection `provider` | Backends that can use it |
|---|---|
-| `anthropic` | Claude Code, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
-| `openai` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
-| `openrouter` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
-| `azure-foundry` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
-| `google` | Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, Kimi Code CLI |
+| `anthropic` | Claude Code, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider |
+| `openai` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider |
+| `openrouter` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider |
+| `azure-foundry` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider |
+| `google` | Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, Kimi Code CLI, Aider |
| `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 |
-| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
-| `llmtr` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
-| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
+| `tokenrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, Aider |
+| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider |
+| `llmtr` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider |
+| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, Aider |
</details>
@@ -650,10 +650,13 @@ Backends are installed into your data volume rather than baked into the image, s
want is a run-time setting:
```bash
-docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi ... # the default
+docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider ... # the default
docker run -e HR_BACKENDS=opencode ... # lean
```
+Aider is the largest of the set: its environment is about 735 MB and takes about ninety seconds to
+install on a fresh volume. Leave it out of `HR_BACKENDS` if you will not use it.
+
A backend that fails to install is not fatal: the others still work, and the console offers what
the gateway's catalogue lists, so an unavailable backend simply is not shown.
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index c6ad256b..e9f511a1 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -580,3 +580,453 @@ against it; the catalog carries no per-id window, so `KIMI_CONTEXT_WINDOW` holds
ids, exactly as `CODEX_CONTEXT_WINDOW` does for codex. Being wrong changes WHEN the agent compacts,
never whether it answers: too large lets a thread overflow the real window (the provider then
errors), too small compacts early and wastes tokens.
+
+## The aider backend (Aider 0.86.2) — behaviour measured before any column ran
+
+Everything in THIS section was measured against the pinned 0.86.2 — its source, and a stub that
+answers as a provider would, at no API cost — before a single paid turn. The google column has since
+run; its results and what they overturned are a section of their own below.
+`docs/support-matrix.md` is rendered from the results file and is untouched.
+
+**aider is driven IN PROCESS, and that is a correctness requirement rather than a preference.** It
+has no machine-readable output mode, and its stdout carries the model's prose and aider's own
+diagnostics on one channel. A stub was made to return model prose whose second line began
+`litellm.AuthenticationError:`; on stdout it was byte-identical to a real 401 on the same stream,
+same exit code 0, no colour under `--no-pretty`. No anchored regex separates those, so a
+text-parsing normaliser would report ordinary answers as provider failures. In process they are
+never mixed: failures reach `io.tool_error`, prose reaches `io.assistant_output`, and
+`coder.usage_report` is None exactly when no completion came back. `runner/aider_driver.py` uses
+aider's own entry point, `main(..., return_coder=True)` — the one its GUI uses (`gui.py:71`) and its
+tests cover. Upstream supports NO python API: its scripting page says the python scripting API "is
+not officially supported or documented, and could change in future releases without providing
+backwards compatibility". Hence the exact pin and the install-time symbol checks.
+
+**Upstream refuses shell commands under `--yes-always` by design, and HarnessRouter approves them
+through a policy gate.** State this plainly to anyone who knows aider, because they will assume the
+opposite. `confirm_ask` returns `"n"` for the one call site that sets `explicit_yes_required`
+(`handle_shell_commands`) — so out of the box a skill's bundled script can be read but never run.
+The driver wraps that single gate: it receives the exact command the model proposed, refuses it if
+the harness disabled the matching tool (with the policy as the reason, which is what the reader
+sees), and otherwise approves it to run in the workspace under the session's uid. The model chooses
+the command; the harness never injects one. Measured both ways: with `Shell` disabled the proposed
+command is refused and the file it would have written does not appear; with it enabled the script
+runs and its output is reported.
+
+**MCP reaches aider through a bridge, because aider has no MCP client at all** — zero source hits
+for MCP across the whole tree. The bridge (`runner/aider_mcp_bridge.py`) is built on the official MCP
+Python SDK (`mcp`, MIT), installed into aider's own venv, and exposed to the model as `hr-mcp`: the
+declared servers are listed by NAME in the context aider reads — so the model cannot invent an
+endpoint — and the gate recognises `hr-mcp call <server> <tool>` and records it under the MCP tool's
+own name. `mcp_called` is therefore measured from a command that actually ran.
+
+f/mcptools was the first choice and is not usable here: it is a Go program that publishes **no
+binaries on any release** (checked every release through v0.7.1 — all have zero assets), so it would
+have meant adding a Go toolchain to a `python:3.12-slim` image for one command. The official SDK is
+also the more defensible component — the protocol's own reference implementation rather than a third
+party's wrapper around it.
+
+Measured live against public servers, at no cost: `hr-mcp tools context7` lists both of its tools
+with their schemas (exit 0); a correct `call` returns the server's content (exit 0); a call with the
+wrong parameters relays the server's own validation error and **exits 1**, so the agent sees a failed
+command rather than an answer-shaped one; an unknown server name exits 2 and names the ones that
+exist. **deepwiki works through this bridge** — worth recording because goose cannot handshake with
+it, so aider's custom-harness row needs no `MCP_URL` override.
+
+Two field-name traps were found by running it rather than reading about it: the 2.2.0 SDK is
+snake_case (`input_schema`, `structured_content`, `is_error`), not the camelCase of older releases,
+and a wrong name raised inside anyio's TaskGroup and surfaced as the useless sentence "unhandled
+errors in a TaskGroup (1 sub-exception)". The bridge unwraps ExceptionGroups so an MCP failure
+reaches the agent as a real message.
+
+**The edit format is pinned to `diff`, and it is load-bearing.** Shell commands are extracted in
+`editblock_coder.get_edits()`; `wholefile`, `udiff` and `patch` never populate `shell_commands`, so
+a ```bash block is inert on those formats and a skill's script could not run at all.
+
+**Shell output is fed back through aider's own reflection path, and this is the measured
+experiment the backend was asked to run.** Stock aider stashes the output in `cur_messages` for the
+NEXT user message and sets no reflection (`base_coder.py:1609-1614`), unlike its lint and test
+paths — so within one turn the model never sees what its command printed, and cannot report a token
+the script produced. Setting `reflected_message` gives aider the same in-turn loop every other
+backend has. Measured against the stub: reflection on, two provider round trips and the answer
+carries the script's output; reflection off, one round trip and the answer is the ```bash block
+itself. One hazard found and fixed while measuring it: `init_before_message()` empties
+`shell_commands` once per TURN, not per reflection, so the first version re-ran every executed
+command on each pass — one command ran four times, four round trips instead of two, side effects
+repeated. The driver now clears the list after running it, pinned by a test.
+
+The cost ceiling is aider's own: `Coder.max_reflections` is 3, so a model that keeps proposing the
+same command after seeing its output costs at most three extra round trips and three executions,
+not an unbounded loop. Observed with a stub that answers identically every time.
+
+**Model ids are sent with an `openai/` prefix.** A bare id is resolved against aider's own
+`MODEL_ALIASES` (`models.py:87-111`), which rewrites 21 of them including `gemini-2.5-pro`, an id
+this catalog also serves. The prefix skips that table, so the id the picker offered is the id the
+provider is asked for. The same class of silent substitution that pruned the gemini catalog.
+
+**Streaming is off (`--no-stream`), and that is about billing honesty.** With streaming, aider
+reports `usage_present: false` and substitutes a **tiktoken estimate** through the same field names
+(587 against a true 595, measured live) because it never sends `stream_options`. Its own numbers are
+not used either way: result events carry `usage: {}` and `_relay_usage` will supply them.
+
+**Nothing of aider's lands in the workspace root.** Its chat and input histories are relocated under
+`.harness/aider/`, and the repo-map tags cache — `Path(root)/".aider.tags.cache.v4"`, with no CLI
+flag — is moved there by setting `RepoMap.TAGS_CACHE_DIR` in the driver, which only an in-process
+driver can do. Verified after a full turn: the workspace root held `.git`, `.harness` and the task's
+own files, nothing else. Auto-commits are off so aider never interleaves commits with the
+checkpoint repo's, and `--no-gitignore` stops it appending to the `.gitignore` the runner owns.
+
+**The install path is verified in a real image.** `docker build` of this tree,
+then a container with `HR_BACKENDS=aider`: the install completed, the container reported
+`backends available: aider`, and `aider.__version__` inside it is 0.86.2 with the MCP SDK importable
+beside it. **681 MB measured there** (`du -sh /data/agent-tools/aider-venv`) — a first estimate of
+735 MB came from a macOS venv — and the MCP bridge was run from inside the image against deepwiki,
+listing its tools with exit 0. The PR proposed keeping aider out of the default `HR_BACKENDS` for its size; the review put it in (2026-09-18), because the console offers every base the catalogue lists and a listed base that is not installed fails on its first task. Note the Python floor: 0.86.2
+declares `Requires-Python <3.13,>=3.10`, and on an interpreter outside that range pip does not fail
+— it silently offers an older aider (0.82.3 on 3.9) with none of the behaviour above. The installer
+asserts the imported version to turn that into a hard failure. Installing the MCP SDK into the same
+venv bumps `idna` past aider's own `idna==3.11` pin; aider was re-verified running end to end
+afterwards, so that pin is advisory here — but it is why the SDK goes in aider's venv and not the
+runner's, where the same class of bump breaks FastAPI outright.
+
+**Known limitation: no tool loop, so the custom-harness dimension's disabled tool is not aider's.**
+The request body's keys are exactly `['messages','model','temperature']` — no `tools`, no
+`functions`. aider's withholdable surface is the shell command and the URL scrape, which the gate
+really does refuse; but `custom-harness.mjs` disables the fixed id `WebSearch`, which matches
+nothing on this harness — so `disabled_tool_unused` would pass VACUOUSLY, as it already does for
+qwen, gemini and cline, whose catalogs carry no `WebSearch` either. The enforcement here is real and
+demonstrable; what is missing is a dimension that disables a tool the base under test actually
+lists.
+
+
+## aider × Google, the first paid column (2026-09-16)
+
+11 pairs, **51 ok / 4 FAIL**, every pair served by `integration:google` on every turn and every
+`served_model` matching the id the pair asked for. The two questions the column was run to answer
+both came back:
+
+**`--timeout` holds.** `gemini-2.5-flash-lite` had burned 27,360s in a single vercel scenario before
+the flag was pinned. Here the whole pair ran green, its slowest scenario 25.69s. No scenario in the
+column waited without a bound.
+
+**The artifact failure is not a gpt-5 phenomenon.** One turned up here too — but for a different
+reason than the gpt-5 family's, so the earlier `diff`-edit-format hypothesis explains neither.
+
+### Three symptoms, one cause: the reminder is glued to the user's message
+
+`base_coder.py:1322`. When `main_model.reminder == "user"` — the default (`models.py:125`), and what
+every id in this catalog resolves to — aider appends its whole `system_reminder` to the FINAL user
+message rather than sending it as its own turn. Reproduced against the real package: the matrix's
+39-character `Reply with exactly: M2-<id>` becomes a **3,080-character** user message whose last
+3,041 characters are SEARCH/REPLACE rules and shell-command examples. The instruction is 1.3% of
+what the model is handed, and it is at the top.
+
+Three of the four failures are that message, failing in three different ways:
+
+ * **FOLLOWUP, `gemini-3.5-flash` and `gemini-3-flash-preview`** — the model continues the tail
+ instead of obeying the head. The answer ends `...suggest the command to install them. Etc.`,
+ byte-identical to the end of the appended block. 31.8s and 37.9s against 7.6s for a healthy
+ followup, because it is reciting 3 KB.
+ * **ARTIFACT, `gemini-3.5-flash-lite`** — "Please add hello-aider.txt to the chat so I can propose
+ the edit", about a file that does not exist yet. The system prompt says `You can create new
+ files without asking!` and then, in the next sentence, that edits to files not in the chat
+ `*MUST*` be refused until the user adds them. The weaker model took the second sentence.
+ * **An unhandled crash, `gemini-3-flash-preview`** — `The turn failed: list index out of range`,
+ seen once in six re-runs. Asked to echo one word, the model emitted a headerless SEARCH/REPLACE
+ block whose only content was that same word. Fed to the real parser, aider reads the word as the
+ FILENAME: `[('M1-gemini-3-flash-preview', '', 'M1-gemini-3-flash-preview\n')]`. Then
+ `strip_quoted_wrapping` (`editblock_coder.py:349-354`) drops the one line because it endswith
+ the filename and immediately indexes `res[0]` on the now-empty list. **An upstream defect in
+ 0.86.2**, reproducible in three lines with no model and no network; this product only supplies
+ the conditions.
+
+`--no-suggest-shell-commands` would remove the shell half of that block, and is NOT taken: shell
+commands are how a skill's script runs at all, which is the custom-harness dimension.
+
+### The fourth failure was not repaired, and the A/B says so
+
+`RECYCLE gemini-3-flash-preview FAIL 399.14s`, reported as
+`Input tokens: ~45,356 of 0 -- possibly exhausted context window!`. The `0` is real and is a defect
+of ours — see `_write_model_metadata` — but it is a defect of REPORTING. Six re-runs of that one
+pair, three with the metadata file and three on the committed driver, put every recycle in the same
+band regardless: **19.9s / 209.0s with it, 210.8s / 222.8s / 229.2s without**, all passing. The
+399.1s failure is the tail of that distribution, not something the metadata fix cured. Recorded here
+because the first re-run passed at 19.9s and reading that one sample as a fix would have been wrong.
+
+`gemini-3-flash-preview` is the unstable id on this harness: across six full runs it produced one
+upstream crash, four followup failures, and recycles ranging over an order of magnitude.
+
+### aider's custom-harness row: the capability is real, the row never passed (2026-09-18)
+
+Measured on the vercel integration, nine runs of `custom-harness.mjs` with `BASES=aider`:
+
+```
+skill_reached 9/9 script_ran 2/9 mcp_called 2/9 row ok 0/9
+```
+
+The harness itself is stored correctly every time — `skill_stored`, `tool_disabled_stored` and
+`mcp_stored` are all true — and the MCP capability demonstrably WORKS. A harness declaring only the
+deepwiki server, asked to read a wiki structure, produced this record:
+
+```
+tools: ["Shell", "deepwiki.read_wiki_structure"]
+assistant:
+ ```bash
+ hr-mcp tools deepwiki
+ ```
+ ```bash
+ hr-mcp call deepwiki read_wiki_structure --params '{"repoName":"modelcontextprotocol/servers"}'
+ ```
+```
+
+The model listed the server's tools and then called one, against the real public server, through
+`runner/aider_mcp_bridge.py`. The block that tells it how is in the workspace's AGENTS.md on every
+turn, verified on disk under `## MCP servers` with the declared server named.
+
+**What fails is not the wiring but the choice, and both halves of this row turn on the same choice.**
+Every other backend gives a skill's script and an MCP tool their own call channel: the model emits a
+tool call and the runtime executes it. aider has no such channel at all — a "tool call" here is the
+model writing a ```bash block into its prose, which `editblock_coder.get_edits()` then extracts. So
+`script_ran` and `mcp_called` are not two independent measurements; they are one question asked
+twice: did the model choose to emit a fenced bash block this turn. Against a prompt built to make it
+emit SEARCH/REPLACE blocks — and with 3,041 characters of those rules appended to the user's own
+message (see the reminder finding above) — it chose to twice out of nine, and never twice in the
+same run.
+
+The first turn shows the pull plainly: asked for the skill's build stamp, the model usually reads the
+token out of `stamp.py` and answers with it instead of running the script. That answer is correct,
+and it is not what the row measures.
+
+Recorded as measured: the row is **FAIL**, and the reason is aider's, not the bridge's. Anyone
+re-running it should expect a different mix of the same two flips rather than a stable result.
+
+## aider × Vercel, the full column (2026-09-18)
+
+52 pairs, **235 ok / 21 FAIL**. Every pair `connection=integration:vercel` on every turn, no
+foreign connection anywhere. The log flags `SUBSTITUTED=` on 51 of 52 pairs and NONE of them is
+one: `run.mjs:177` compares the served id to the asked id as raw strings, and this channel stamps a
+vendor prefix (`openai/gpt-5.6-sol`, `nvidia/nemotron-3-super-120b-a12b`). Judged by the comparator
+that owns the question, `scripts/support-matrix/samemodel.py`, **0 of the 51 is a real
+substitution**. The google column flagged none because that channel stamps the bare id. Read the
+flag as raw pre-canonicalisation data, not as a finding.
+
+```
+first ok=51 FAIL=1
+followup ok=49 FAIL=2
+switch ok=51 FAIL=0
+artifact ok=47 FAIL=4
+recycle ok=37 FAIL=14 <- two thirds of every failure in the column
+```
+
+### The `--timeout` pin holds on the channel that produced the hangs
+
+The 3,621s / 6,040s / 16,071s / 27,360s scenarios were all measured HERE. The slowest scenario in
+this column is 477s (`gemini-3-flash-preview`'s recycle) and nothing waited without a bound.
+
+### The artifact failure is a small-model behaviour, not a gpt-5 one
+
+Four artifact failures: `gpt-5.4-mini`, `gemini-3.5-flash-lite`, `gemini-3.1-flash-lite`,
+`grok-4.20`. Three of the four are the mini/lite variant of a family whose full-size sibling passed,
+across three vendors and (with the google column's `gemini-3.5-flash-lite`) two providers. The gpt-5
+family passed 5 of 6. **The earlier hypothesis -- that this was the gpt-5 family meeting the `diff`
+edit format -- is dead.** What these models do is obey the system prompt's `*MUST* tell the user
+their full path names and ask them to *add the files to the chat*` for a file that does not exist
+yet, ignoring the sentence above it that says new files need no permission.
+
+### Recycle, by family
+
+```
+claude 8/8 deepseek 3/3 kimi 2/2 glm 2/2 step 1/1
+gemini 10/11 grok 4/5 qwen 4/5
+muse 2/4
+gpt-5 1/6
+nemotron 0/2 mistral 0/1 hunyuan 0/1
+```
+
+### aider puts a user message the user never sent at the head of every conversation
+
+`editblock_prompts.py:31`. aider teaches the SEARCH/REPLACE format by example, and with
+`examples_as_sys_msg` false -- the default (`models.py:126`), and what every id in this catalog
+resolves to, because aider's per-model overrides match legacy substrings (`gpt-4.1`, `3.5-sonnet`,
+`deepseek`+`v3`, `qwq`+`32b`) that no 2026 id contains -- those examples are injected as REAL
+`user`/`assistant` turns. The first user message in the model's context is therefore
+`Change get_factorial() to use math.factorial`.
+
+The recycle scenario asks what word was requested `in my very first message of this task`. In the
+column five models answered out of that synthetic turn: `math.factorial` (gpt-5.6-terra, gpt-5.6-luna),
+`Change` (gpt-5.4, muse-glimmer-30b), and qwen3.8-max quoting it back as a sentence. They are not
+wrong about what they were shown. This is not only a test artefact: any feature that asks a model
+about its own history inherits a turn attributed to a user who never wrote it.
+
+### Setting `examples_as_sys_msg` closes that trap and changes nothing (2026-09-18)
+
+aider supports the fix: `--model-settings-file` (`main.py:757`) with `examples_as_sys_msg: true`
+folds the examples into the system prompt under `# Example conversations:` instead of sending them
+as turns. Measured on the six ids that had failed recycle, one variable changed and every other
+ModelSettings field left at the default already in effect, against a CONTROL of the same six pairs
+on the same image in the same hour:
+
+```
+ control (as shipped) with examples_as_sys_msg
+ ok=25 FAIL=5 ok=25 FAIL=5
+```
+
+Identical. The mechanism is real -- under the setting NO answer cites the example text, while the
+control still produced `math.factorial` -- but closing it does not buy a single scenario: the models
+that stopped answering `math.factorial` answered `HELLO`, or `Ok`, or "the first message of this
+task did not ask me to reply with any specific word" instead. **Not taken.** Fitting the harness's
+prompt to this matrix without a measurement that supports it is the trade this repo does not make.
+
+### The column's recycle number is a single sample, and it is not stable
+
+The same six pairs re-run on the same image failed recycle three times, where the column failed them
+five times and voided a sixth. `gpt-5.2`'s `FIRST FAIL 171.62s -- The LLM did not conform to the
+edit format`, which voided its whole pair in the column, did not reproduce at all: both arms ran it
+4/5. Quote `recycle ok=37/51` as what this run measured, never as aider's rate.
+
+### The model's reasoning was being rendered as its answer (fixed)
+
+`grok-4.20` is the only id in the column whose provider returns a separate reasoning field, and its
+cards carried the chain of thought: `...(wait, no, that is not how it works) The instruction is to
+tell which files need changes and stop. So my response should be:... ► ANSWER hello-aider.txt`. That
+`► ANSWER` is aider's own terminal banner (`reasoning_tags.py:11`), reaching a browser transcript.
+The driver hooked `io.assistant_output`, which `base_coder.py:1882-1890` feeds the DISPLAY string --
+reasoning prepended to the answer -- rather than `partial_response_content`, which carries the answer
+alone. Fixed in `_install`; re-measured on a rebuilt image, the same cards now read
+`AIDER No files in the repo need to be changed for this request.` with no banner. **Both verdicts
+stayed FAIL**: the artifact row is judged on the file card, and the recall answer never contained
+the word either way. The leak reached the transcript only -- aider writes `partial_response_content`
+to the chat history (`base_coder.py:1828`), so no later turn was fed the reasoning.
+
+## aider, the review of PR #211 on hr-test (2026-09-18)
+
+Reviewed on a derived image of the PR branch merged with main, on the 0.18.4 base, with every
+built-in skill installed as a fresh volume installs them. What the review changed, each with the
+measurement that made it a defect, and then what the columns say on the image that carries the
+changes.
+
+**Every turn carried the whole skill library.** The PR passed every file of every installed
+skill bundle through `--read` on every turn: on hr-test that is 27 files and 264 KB for the three
+built-in bundles, two licences and a PNG among them, and `Reply with exactly: AIDER-SMOKE-OK` cost
+**45,030 input tokens**. The same turn on the review image costs 3,039. The agent doc alone
+reaches the model; a skill is read when a task calls for it, as on every base without a loader.
+
+**The agent doc is the system message.** `--read` delivered it as a USER message ("Here are some
+READ ONLY files, provided for your reference") ahead of the conversation, and aider's few-shot
+examples for the edit format went in as user/assistant turns ahead of that. So the first user
+message the model saw was never the user's: asked what the first message of the task asked for,
+the gpt-5 family answered `Change` (aider's `Change get_factorial()` example) and, once the
+examples were folded away, `reference` (the read-only preamble). The doc now rides aider's own
+`Model.system_prompt_prefix` hook, ahead of the system message aider composes, and the examples
+fold into that message through aider's own `examples_as_sys_msg`, set on the object because a
+settings-file entry replaces every other setting of the model with class defaults. The PR's A/B
+of that switch (above) was run with the history cap still in place, which is why it could not
+move a verdict: the first message was being summarised away regardless.
+
+**The conversation was summarised away after four short turns.** aider keeps at most
+`min(max(window/16, 1k), 8k)` tokens of chat history, and 1k for an id litellm has no record of,
+which is most of this catalog; past that it summarises the history with a model call on every
+turn. Measured in the console matrix: after first, follow-up, switch and artifact, the recycle
+question could not be answered on ids that had answered the follow-up one turn earlier. The
+driver passes `--max-chat-history-tokens` as half the window when the record says it, else
+96,000, which fits the catalog's smallest windows; the other bases keep the whole transcript the
+same way.
+
+**The model was never told how this workspace works.** aider's prompt tells it the USER adds
+files and may run the commands it suggests. Here the driver does both, and a model that was not
+told behaved as aider's prompt says: asked to use a skill it guessed the token instead of reading
+SKILL.md; asked for an MCP tool it wrote "I'm constrained here to only return SEARCH/REPLACE
+blocks"; asked for a streamable-HTTP tool it invented the result. The doc now carries a block
+that says what happens between messages, names each installed SKILL.md as a `cat` the model can
+run on any turn (aider's own file-mention route adds only files git already tracks, and on a
+session's first turn the skill files are not committed yet, measured), and forbids reporting
+output that was never received. Plugin matrix before: 1 of 4 columns (skills guessed, stdio
+refused, http invented). After, run twice: **4 of 4 both times**. `custom-harness.mjs`, which the
+PR ran nine times without a pass: **3 of 3**, `skill_reached`, `script_ran`, `mcp_called` all
+true each time.
+
+**The operator's step budget never reached the driver.** The builder accepted `max_turns` and
+`turn()` did not pass it; the test that claimed to pin the dispatch pinned the builder. Fixed and
+pinned on the dispatch.
+
+**Usage was empty on every kimi and aider turn.** Both normalisers wrote `usage: {}` on the
+promise that "the relay stamps it", and nothing in this tree did: the console showed no tokens for
+either base. The relay now reads the provider's usage off the bytes as they pass, the way it
+already reads the served model (OpenAI `prompt_tokens` netted to fresh input by the cached part,
+Anthropic's counters as they are, Gemini's `usageMetadata`, streamed or not), sums it over the
+turn's calls and stamps it on a result event that arrived empty. Measured after: aider
+`input 3,039 / output 9`, then `input 2,710 / cache_read 2,176` on the follow-up; kimi
+`input 7,487 / cache_read 13,312`.
+
+**`temperature` refused by a provider.** aider sends `temperature: 0` for every id its settings do
+not know; `claude-fable-5-1` on TokenRouter answered "`temperature` is deprecated for this model"
+and the turn died after 171 s of retries. No other base sets one; aider's own `use_temperature`
+switch leaves it out.
+
+**Edit markup rendered as the answer.** A file-writing task's reply card read
+`hello.py ```python <<<<<<< SEARCH ======= print("aider") >>>>>>> REPLACE ``` `. That is aider's
+wire format for an edit; the driver strips it from the text (the text event AND the result event,
+since the gateway stores the latter as the answer) and reports each edited file as an `Edit` card,
+as file edits render on every other base.
+
+**Two claims removed.** The catalog listed `Web Fetch` as a withholdable tool while the runner
+always ran aider with `--no-detect-urls`, so the switch withheld something that never happened;
+the web is reached through a shell command like everything else, under the one gate. And the
+install was opt-in "per the 300 MB line", but the console offers every base the gateway's
+catalogue lists, so on a default install Aider was a base that failed on its first task; it is in
+the default `HR_BACKENDS` (fresh volume: healthy after 147 s against 114 s without it, 687 MB),
+and an operator who does not want it leaves it out.
+
+**Smaller:** a failure reason no longer names aider's in-chat commands (`- Use /drop …`); the two
+bridge tests that imported the aider venv's SDK (mcp 2.x, httpx2) under the runner's 1.x
+environment, which is why the PR's runner job was red, stub those modules by name; aider's own
+app icon is in the harness list.
+
+**Verified unchanged:** the hard tool policy (Shell withheld: the model's `cat
+/proc/sys/kernel/random/boot_id` was refused at the gate with the policy as its result and no
+UUID in the answer; allowed: the UUID came back); cancel (a 60-function module task cancelled
+mid-flight: `runner_killed: true`, no driver process left, session `cancelled`); the console at
+1440 and 390 (settings page, task page with the edit card and the file card, no markup, no
+overflow, no page errors).
+
+**The columns on the review image (`pr211-a9e7a51`, hr-test, 2026-09-18).** Console scenario
+matrix, 50 ids × first / follow-up / switch / artifact / recycle, connections as the console
+routes them (TokenRouter for most, Vercel 6, Anthropic 2, Custom OpenAI 2, OpenRouter 1, Azure 1):
+
+```
+first 50/50 follow-up 47/50 switch 50/50 artifact 47/50 recycle 47/50 = 241/250
+```
+
+The nine: `claude-opus-5` three times, the provider's `finish_reason content_filter` on the
+scenario's own words (the same id tripped the same way in the kimi review); `gemini-3.5-flash` and
+`gemini-3.6-flash` on the follow-up, the reminder tail continued (upstream's, above);
+`gpt-5.2` and `llama-3.3-70b` on the recycle recall, answering with a later word; `gpt-5.4` and
+`gpt-5.4-mini` on the artifact after three literal-reply turns, answering `DONE` with no edit
+block (the same prompt on a fresh session writes the file; measured twice). Two of these were
+re-run three times and flipped both ways, so read them as what this run measured.
+
+A pattern worth knowing about the base itself: aider answers with ONE response per turn, and a
+reflection follows only when aider has something to feed back (a command's output, a file it
+added). "Create the file, then run wc on it and tell me the count" therefore often ends after
+the edit: the model writes the block, aider applies it, and no second pass happens unless the
+model also proposed the command in the same response. Every other base loops on tool calls.
+
+Conformance, run alone against an aider harness on gpt-5.4: 75/75 at full. A provider refusal
+(a custom connection with a bogus key): the task fails with "The API provider is not able to
+authenticate you. Check your API key." and nothing of aider's around it. Fresh volume on the final
+image: healthy after 150 s, 687 MB venv, `aider-ready` reads 0.86.2.
+
+**Richard's first manual task, and what it found (2026-09-19, `pr211-a30c77d`).** "improve the ppt
+style" on a one-slide deck, gemini-3.8-flash: the model named `hello.pptx`, aider added it to the
+chat, the UTF-8 read failed ("Use --encoding to set the unicode encoding"), the file was dropped
+and added again on the next mention, an error and a reflection each time. Twelve commands and
+fifteen minutes later the deck WAS restyled through officecli and `hello.md` edited, and the turn
+read FAILED with the decode error, because any error had failed a turn; and the transcript showed
+prose inside a code block, because each response's text was joined to the next without a break
+and a closing fence ran into the next sentence. Fixed on the branch: a binary file is refused at
+aider's own "Add file to the chat?" prompt (aider's ignore_mentions then holds it), and since
+nobody is at that prompt to say what to do instead, the answer goes back as a reflection and the
+turn goes on; the turn fails when an error was the LAST thing that happened; each response ends
+with a paragraph break and its shell blocks render as cards only. Re-run of the same two turns:
+the deck restyled in 53 s, DONE, five tool cards, no markup. The doc also says now that each line
+of a bash block runs on its own (a multi-line `python3 -c "…"` ran line by line) and that binary
+files are worked on with commands.
diff --git a/gateway/app.py b/gateway/app.py
index 96c2b5fd..fdd75361 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -1068,6 +1068,13 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {
("llmtr", "opencode"): "tokenrouter",
# kimi reaches every provider the same way qwen does — one OpenAI-compatible surface through
# the loopback relay — so these rows are qwen's, verbatim, with the backend renamed.
+ ("anthropic", "aider"): "anthropic", ("openai", "aider"): "openai",
+ ("azure-foundry", "aider"): "azure",
+ ("openrouter", "aider"): "openai-api",
+ ("tokenrouter", "aider"): "tokenrouter", ("vercel", "aider"): "tokenrouter",
+ ("llmtr", "aider"): "tokenrouter",
+ ("custom", "aider"): "openai-api",
+ ("google", "aider"): "openai-api",
("anthropic", "kimi"): "anthropic", ("openai", "kimi"): "openai",
("azure-foundry", "kimi"): "azure",
("openrouter", "kimi"): "openai-api",
@@ -1138,6 +1145,7 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {
("harnessrouter", "omp"): "tokenrouter", ("harnessrouter", "dsh"): "tokenrouter",
("harnessrouter", "opencode"): "tokenrouter", ("harnessrouter", "qwen"): "tokenrouter",
("harnessrouter", "kimi"): "tokenrouter",
+ ("harnessrouter", "aider"): "tokenrouter",
("harnessrouter", "cline"): "tokenrouter", ("harnessrouter", "gemini"): "google",
("harnessrouter", "goose"): "tokenrouter",
}
@@ -4603,7 +4611,7 @@ _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.
- "openai": {"hermes", "opencode", "pi", "dsh", "qwen", "cline", "omp", "goose", "kimi"},
+ "openai": {"hermes", "opencode", "pi", "dsh", "qwen", "cline", "omp", "goose", "kimi", "aider"},
"anthropic": {"claude", "opencode", "pi", "dsh", "omp"},
# The OpenAI Responses API: what codex speaks, and only codex among the agent CLIs here.
"responses": {"codex"},
@@ -6030,6 +6038,32 @@ _MODEL_CATALOG: dict[str, dict] = {
# its text turns answer but its first tool turn is refused on every channel (TokenRouter
# "404 This model is not supported in the v1/chat/completions endpoint", Azure "400 The
# requested operation is unsupported"). Same rule cline earned for it on 2026-08-30.
+ # aider: same relay reach as the others (litellm's openai provider through the loopback relay).
+ # Measured: the vercel column ran all 52 runnable ids (235 ok / 21 FAIL) and the google column
+ # 11 (51 ok / 4 FAIL); every pair was served by the connection under test and, judged by
+ # samemodel.py, as the id it asked for. Three of the ids those columns measured were the Gemini
+ # 2.5 family, retired from this catalog since (#196); `llama-3.3-70b` is the one listed id no
+ # column reached. docs/support-matrix-notes.md carries the failures and what each is.
+ #
+ # Ids are sent with an `openai/` prefix by the runner, which is load-bearing rather than
+ # cosmetic: a BARE id is resolved against aider's own MODEL_ALIASES table, which rewrites 20 of
+ # them to a DIFFERENT model on a DIFFERENT provider. No id this catalog serves is in that table
+ # today — `gemini-2.5-pro` was, and left with #196 — but the overlap is upstream's to change in
+ # any release, and the prefix skips the table entirely rather than tracking it.
+ "aider": {"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",
+ "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"]},
# kimi (Kimi Code CLI): the same relay reach as qwen and cline (OpenAI chat/completions through the
# loopback relay), so the list is qwen's, reordered to put the kimi family first as its home family.
#
@@ -6190,7 +6224,8 @@ RESPONSES_ONLY_MODELS = frozenset({"gpt-5.3-codex", "gpt-6-astra"})
# kimi speaks chat/completions only: the runner defines its model with provider type `openai`
# through the relay (Kimi Code CLI has an openai_responses type too, but it is not the one the runner
# sets), so a Responses-API-only id would be a picker row that fails on send.
-CHAT_ONLY_BACKENDS = ("qwen", "cline", "goose", "kimi")
+# aider speaks chat/completions through litellm's openai provider, so a Responses-API-only id
+CHAT_ONLY_BACKENDS = ("qwen", "cline", "goose", "kimi", "aider")
_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:
@@ -13309,6 +13344,32 @@ _BASE_CATALOG: dict[str, dict] = {
# as claude's permissions.deny and pi's -xt, not the instruction-only tier.
"tool_enforcement": "hard",
},
+ "aider": {
+ "label": "Aider", "backend": "aider", "status": "ready",
+ # aider composes its own system message from the edit format; the runner's driver puts
+ # these instructions and the harness's AGENTS.md ahead of it, in the same system message,
+ # through the Model's own system_prompt_prefix hook.
+ "system_prompt": ("You are Aider, an autonomous coding agent. You work on a real git "
+ "workspace, editing files and proposing shell commands to complete the "
+ "task end to end."),
+ # aider has no tool loop: the request body's keys are exactly ['messages','model'] — no
+ # `tools`, no `functions` (and no temperature, see the driver). Its tool SURFACE is the
+ # shell command the model proposes in a fenced block, which the driver's gate decides; that
+ # one is withholdable and is listed. "Edit" is aider's edit engine: it is what aider IS, it
+ # cannot be withheld, and it is therefore NOT listed — offering a switch that does nothing
+ # is the overstatement UHP §4.3 forbids. aider's URL scrape is off in this harness
+ # (--no-detect-urls, set by the runner), so a "Web Fetch" switch would be that same
+ # overstatement; the web is reached through a shell command like everything else, and the
+ # Shell switch withholds it. MCP tools reach the model through the `hr-mcp` bridge
+ # (runner/aider_mcp_bridge.py) and are gated by tool NAME in the same place; they are
+ # per-harness rather than catalog entries, so they are not listed here.
+ "tools": [("Shell", "Shell")],
+ # "hard", and measured rather than asserted: with Shell disabled the model's proposed
+ # command is refused at the gate and the file it would have written does not appear; with an
+ # MCP tool name disabled the `hr-mcp` call is refused by that tool's own name. Pinned by
+ # runner/tests/test_aider_driver.py.
+ "tool_enforcement": "hard",
+ },
"kimi": {
"label": "Kimi Code CLI", "backend": "kimi", "status": "ready",
"system_prompt": ("You are Kimi Code CLI, an autonomous coding agent. You work on a real git "
diff --git a/runner/aider_driver.py b/runner/aider_driver.py
new file mode 100644
index 00000000..fa43121e
--- /dev/null
+++ b/runner/aider_driver.py
@@ -0,0 +1,550 @@
+"""One Aider 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, aider is DRIVEN IN PROCESS
+through `aider.main.main(..., return_coder=True)`, which hands back the constructed Coder without
+running the interactive loop — rather than launched as a CLI whose printed text we would parse. That
+entry point is aider's own: its GUI calls it (`gui.py:71`) and its test suite covers it. It is NOT a
+supported API, and saying so would be a lie upstream has already contradicted — aider's scripting
+page states that "the python scripting API is not officially supported or documented, and could
+change in future releases without providing backwards compatibility". This is why the version is
+pinned EXACTLY and why install-time checks assert the symbols this driver reaches for.
+
+WHY THIS EXISTS AT ALL, measured on the pinned 0.86.2. Aider has no machine-readable output mode,
+and its stdout is ONE channel carrying both the model's prose and aider's own diagnostics. A stub
+was made to return model prose whose second line began `litellm.AuthenticationError:`; on stdout it
+was BYTE-IDENTICAL to a real 401 on the same stream, same exit code 0, no colour under --no-pretty.
+So no anchored regex can separate "the provider failed" from "the agent wrote about an error", and a
+text-parsing normaliser for this backend would invent failures on ordinary answers. In process the
+two are never mixed: a real failure reaches io.tool_error/io.tool_warning and leaves
+`coder.usage_report` None, while prose reaches io.assistant_output only.
+
+WHAT ELSE ONLY WORKS IN PROCESS:
+ * The shell intercept (see _Gate). Upstream's --yes-always deliberately auto-DECLINES every shell
+ command the model proposes, and in driver mode aider forces yes_always on itself
+ (main.py:546-547), so wrapping io.confirm_ask is the only way to let a skill's script run — and
+ the only place a per-harness tool policy can be applied to a command before it executes.
+ * Relocating the repo-map tags cache out of the workspace root (see main), which has no CLI flag
+ and would otherwise hand the user a `.aider.tags.cache.v4/` directory as a deliverable.
+
+The event protocol is dsh_driver's: one {"m": method, "p": payload} JSON object per line on stdout,
+normalised by _aider_to_claude in server.py.
+"""
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import pathlib
+import re
+import sys
+import time
+
+_T0 = time.time()
+
+# A SEARCH/REPLACE block as aider's editblock format writes it: the file name alone on the line
+# before the fence, the fence (with or without a language), the three markers. The markers'
+# lengths follow editblock_coder.py (5 to 9 characters). This is aider's wire format for an edit,
+# and the edit is reported as a card of its own; the prose around the block is the answer.
+_EDIT_BLOCK = re.compile(r"(?:^\S+\n)?```[^\n]*\n<{5,9} SEARCH\n.*?^>{5,9} REPLACE\n```\n?",
+ re.S | re.M)
+
+
+# `hr-mcp call <server> <tool>` wherever it stands in COMMAND position: at the start of the line
+# or after &&, ||, ;, |, ( or a backtick, by its bare name or a path ending in it. Not after a
+# plain space, so `echo hr-mcp call x y` stays the prose it is. Server and tool are one shell
+# word each.
+_HR_MCP_CALL = re.compile(r"(?:^|[\n;&|(`])\s*(?:\S*/)?hr-mcp\s+call\s+([^\s;&|)`'\"]+)\s+([^\s;&|)`'\"]+)",
+ re.M)
+
+
+# The fences editblock_coder.py:452 extracts shell commands from. Every such block becomes a
+# shell_decision card (approved or refused), so the prose does not repeat it.
+_SHELL_FENCES = ("```bash", "```sh", "```shell", "```cmd", "```batch", "```powershell", "```ps1",
+ "```zsh", "```fish", "```ksh", "```csh", "```tcsh")
+
+
+def _strip_shell_blocks(text: str) -> str:
+ """Drop the shell blocks the way aider reads them: a block opens on a shell fence and closes on
+ the next line that STARTS with a fence, whatever follows on that line (a model that writes
+ "```An improved style…" has closed the block and started a sentence; aider treats it so,
+ editblock_coder.py:478, and the sentence is kept here)."""
+ out, lines, i = [], (text or "").splitlines(), 0
+ while i < len(lines):
+ line = lines[i]
+ if line.strip() in _SHELL_FENCES or any(line.strip().startswith(f + " ") for f in _SHELL_FENCES):
+ i += 1
+ while i < len(lines) and not lines[i].strip().startswith("```"):
+ i += 1
+ if i < len(lines):
+ rest = lines[i].strip()[3:].strip()
+ if rest:
+ out.append(rest)
+ i += 1
+ continue
+ out.append(line)
+ i += 1
+ return "\n".join(out)
+
+
+def strip_edit_blocks(text: str) -> str:
+ return _strip_shell_blocks(_EDIT_BLOCK.sub("", text or "")).strip()
+
+
+def is_text_file(path: str, sniff: int = 65536) -> bool:
+ """Whether aider could read this file as text. aider adds a file the model names and reads it
+ as UTF-8; a binary one (a .pptx the model was asked to restyle, 2026-09-19 on hr-test) fails
+ with "Use --encoding to set the unicode encoding.", is dropped, and is added again on the next
+ mention, an error and a reflection each time. Refusing the add up front is what aider itself
+ does when the operator answers no: the name goes on ignore_mentions and is not asked again."""
+ try:
+ with open(path, "rb") as f:
+ head = f.read(sniff)
+ except OSError:
+ return False
+ if b"\x00" in head:
+ return False
+ try:
+ head.decode("utf-8")
+ except UnicodeDecodeError:
+ # a cut inside a multi-byte sequence at the sniff boundary is not a binary file
+ try:
+ head[:-4].decode("utf-8")
+ except UnicodeDecodeError:
+ return False
+ return True
+
+
+def _emit(method: str, payload) -> None:
+ sys.stdout.write(json.dumps({"m": method, "p": payload}, default=str) + "\n")
+ sys.stdout.flush()
+
+
+class _Gate:
+ """The policy gate on every shell command the model proposes.
+
+ It is NOT a blanket yes. It receives the exact command aider is about to run, checks it against
+ the harness's disabled-tool list, and refuses with the policy as the reason — which is what
+ makes `tool_enforcement` on this backend a gate that exists rather than a claim that passes
+ because the harness has no tools at all.
+
+ The model chooses the command; the harness never injects one. (`--message "/run <cmd>"` would be
+ US choosing it, and is deliberately not used anywhere in this backend.)
+
+ Two kinds of name are matched against the policy:
+ * `hr-mcp call <server> <tool>` — the MCP bridge's call form, so a disabled MCP tool is
+ refused by the tool's own name;
+ * the command's argv[0], so a disabled `Shell` withholds shell execution outright.
+ """
+
+ def __init__(self, disabled: list[str]) -> None:
+ self.disabled = {d.strip().lower() for d in (disabled or []) if d and d.strip()}
+ self.calls: list[dict] = []
+ # True while the last thing that happened was an error: set by tool_error, cleared by the
+ # next assistant output. What decides whether the turn failed (see main).
+ self.error_after_output = False
+
+ def mcp_calls_in(self, command: str) -> list[tuple[str, str]]:
+ """Every ('server', 'tool') an hr-mcp call in this command names, in order.
+
+ `hr-mcp call <server> <tool> [--params …]` is the form the runner documents to the model,
+ so recognising it is reading our own contract back; `hr-mcp tools <server>` is discovery,
+ not a call, and is deliberately not matched. The WHOLE command is scanned, not its first
+ words: with a tool disabled, gpt-5.4 proposed `hr-mcp tools probe && hr-mcp call probe
+ probe_sse` and a gate that read argv[0..3] saw a discovery and let the call through
+ (hr-test, 2026-09-18). The bridge refuses a disabled tool as well, by name, whatever the
+ shell around it looks like; this gate is what names the call in the turn record."""
+ return [(m.group(1), m.group(2)) for m in _HR_MCP_CALL.finditer(command)]
+
+ def decide(self, command: str) -> tuple[bool, str, str]:
+ """(approved, tool_name, reason). tool_name is what the turn record will call this."""
+ calls = self.mcp_calls_in(command)
+ if calls:
+ for server, tool in calls:
+ name = f"{server}.{tool}"
+ for d in (tool.lower(), name.lower()):
+ if d in self.disabled:
+ return False, name, f"the harness disabled the tool '{tool}'"
+ server, tool = calls[0]
+ return True, f"{server}.{tool}", ""
+ if "shell" in self.disabled or "bash" in self.disabled:
+ return False, "Shell", "the harness disabled shell commands"
+ return True, "Shell", ""
+
+
+def _install(coder, gate: _Gate) -> None:
+ """Replace the Coder's IO with one that reports on separate channels and gates confirmations."""
+ io = coder.io
+ orig_confirm = io.confirm_ask
+ orig_assistant = io.assistant_output
+ orig_error = io.tool_error
+ orig_warning = io.tool_warning
+
+ def assistant_output(message, pretty=None):
+ # WHAT ARRIVES HERE IS AIDER'S DISPLAY STRING, NOT THE MODEL'S ANSWER. For a reasoning
+ # model base_coder.py:1882-1890 prepends the chain of thought and rewrites its tags into
+ # terminal furniture (`► **THINKING**` ... `► **ANSWER**`, reasoning_tags.py:10-11) before
+ # handing it here. MEASURED on vercel|aider|grok-4.20 (2026-09-18, the column's only id
+ # whose provider returns a reasoning field): its cards carried the model deliberating --
+ # `...(wait, no, that's not how it works)... So my response should be: ► ANSWER ...` -- and
+ # were scored against text the model never addressed to the user.
+ #
+ # The answer is `partial_response_content`, set from the completion's own `content`
+ # (base_coder.py:1866) and never decorated; aider's own helper covers the other shape, a
+ # provider that inlines the tags in content instead of sending a separate field. The
+ # display string is the fallback only when there is no content, so a call site off the send
+ # path still reports something.
+ try:
+ from aider.reasoning_tags import remove_reasoning_content
+ body = remove_reasoning_content(coder.partial_response_content or "",
+ coder.reasoning_tag_name)
+ except Exception:
+ body = ""
+ gate.error_after_output = False
+ _emit("text", {"text": strip_edit_blocks(body or str(message))})
+ return orig_assistant(message, pretty)
+
+ def tool_error(message="", strip=True):
+ # A REAL failure lands here and nowhere else. This is the whole reason the driver exists:
+ # on stdout this text and the model's own prose are the same bytes.
+ gate.error_after_output = True
+ _emit("error", {"text": str(message)})
+ return orig_error(message, strip)
+
+ def tool_warning(message="", strip=True):
+ _emit("warning", {"text": str(message)})
+ return orig_warning(message, strip)
+
+ def confirm_ask(question, default="y", subject=None, explicit_yes_required=False,
+ group=None, allow_never=False):
+ # explicit_yes_required is set by exactly ONE call site in the whole 0.86.2 tree —
+ # handle_shell_commands (coders/base_coder.py) — so this branch is the shell gate and
+ # nothing else. Every other confirmation keeps aider's own --yes-always behaviour by
+ # falling through to the original.
+ if explicit_yes_required:
+ command = str(subject or question)
+ approved, name, reason = gate.decide(command)
+ gate.calls.append({"command": command, "tool": name, "approved": approved,
+ "reason": reason})
+ _emit("shell_decision", {"command": command, "tool": name,
+ "approved": approved, "reason": reason})
+ return approved
+ # A file the model named, which aider offers to add to the chat (base_coder.py:1773).
+ # Binary files are refused: aider reads a chat file as UTF-8 text, and a .pptx or an
+ # image fails that read every time it is mentioned. The model works on such files with
+ # commands, as the doc says.
+ if question == "Add file to the chat?" and subject:
+ path = str(subject) if os.path.isabs(str(subject)) else os.path.join(coder.root, str(subject))
+ if not is_text_file(path):
+ _emit("warning", {"text": f"{subject} is not a text file and stays out of the chat"})
+ # aider's prompt tells the model to ask the user for the file and stop; when the
+ # user says no, a person types what to do instead. Nobody is at that prompt here,
+ # so the answer goes back as a reflection and the turn goes on (measured: without
+ # it, "improve the ppt style" ended on "Please add this file to the chat").
+ note = (f"`{subject}` is a binary file: it cannot be added to the chat or edited "
+ "with a SEARCH/REPLACE block. Inspect and change it with shell commands in "
+ "a ```bash block (the installed skills cover documents, decks, "
+ "spreadsheets and PDFs), then report what you did.")
+ coder.reflected_message = ((coder.reflected_message + "\n\n") if coder.reflected_message else "") + note
+ return False
+ return orig_confirm(question, default=default, subject=subject,
+ explicit_yes_required=explicit_yes_required, group=group,
+ allow_never=allow_never)
+
+ io.assistant_output = assistant_output
+ io.tool_error = tool_error
+ io.tool_warning = tool_warning
+ io.confirm_ask = confirm_ask
+
+
+def _run_shell_commands_reporting(coder, gate: _Gate, reflect: bool = True):
+ """Wrap Coder.run_shell_commands so each approved command's OUTPUT is reported too.
+
+ aider runs the command itself and appends the output to the next message's context; it exposes
+ no per-command result hook, so the pairing here is: the gate records the call as aider asks, and
+ this wrapper reports what the whole batch produced. Without it the turn record would show a
+ tool_use with no tool_result."""
+ orig = coder.run_shell_commands
+
+ def wrapped():
+ before = len(gate.calls)
+ out = orig()
+ for call in gate.calls[before:]:
+ if call["approved"]:
+ _emit("shell_result", {"tool": call["tool"], "command": call["command"],
+ "output": str(out or "")})
+ # MUST clear, and this is not tidiness: init_before_message() empties shell_commands ONCE
+ # per turn, not once per reflection, and run_shell_commands iterates whatever is in it. With
+ # a reflection set below, the next pass would RE-RUN every command already executed —
+ # measured: one proposed command ran four times and the turn made four provider round trips
+ # instead of two, with the side effects repeated each time.
+ coder.shell_commands = []
+ if reflect and out:
+ # MEASURED, and the reason this is not the default everywhere: aider stashes shell
+ # output in cur_messages for the NEXT user message and sets no reflection of its own
+ # (base_coder.py:1609-1614), unlike lint and test results which DO set
+ # reflected_message. So within one turn the model never sees what its command printed —
+ # it cannot report a token the script produced, and every other backend here can.
+ # Setting the reflection gives aider the same in-turn loop, using aider's own mechanism
+ # and its own max_reflections bound rather than a loop of ours.
+ coder.reflected_message = str(out)
+ return out
+
+ coder.run_shell_commands = wrapped
+
+
+def _run_turn(coder, prompt: str) -> None:
+ """aider's own reflection loop (Coder.run_one), driven directly.
+
+ run_stream is run_one without the loop: it sends ONE message and stops. Reproducing the loop
+ here is what lets a reflection — aider's mechanism for "there is more to do before this turn
+ ends", used by its lint and test paths — carry a shell command's output back to the model in the
+ SAME turn. The bound is aider's own max_reflections, not one invented here."""
+ coder.io.user_input(prompt)
+ coder.init_before_message()
+ message = prompt
+ reflections = 0
+ reported: set = set()
+ while message:
+ coder.reflected_message = None
+ list(coder.send_message(message))
+ # aider_edited_files accumulates over the turn; what this pass added is reported now, so
+ # the cards sit beside the prose that produced them.
+ edited = sorted(set(coder.aider_edited_files or []) - reported)
+ if edited:
+ reported.update(edited)
+ _emit("edits", {"files": edited})
+ if not coder.reflected_message:
+ break
+ if reflections >= coder.max_reflections:
+ _emit("warning", {"text": f"stopped after {coder.max_reflections} reflections"})
+ break
+ reflections += 1
+ message = coder.reflected_message
+
+
+def _write_model_metadata(cwd: str, model: str) -> str | None:
+ """Give aider back the model record that the `openai/` prefix hides from it.
+
+ server.py prefixes every id with `openai/` on purpose, so aider resolves it through litellm's
+ openai provider verbatim instead of through aider's MODEL_ALIASES table, which rewrites 21 ids.
+ The cost went unmeasured until the google column: litellm's lookup for a prefixed name only
+ falls back to the bare id when that id's own `litellm_provider` IS openai (models.py:228-231).
+ So `openai/gpt-5.6-sol` keeps its full 66-key record while EVERY gemini, claude, grok and qwen
+ id resolves to an empty dict.
+
+ Empty info is not cosmetic. aider reads its limits off that record, so a turn runs with
+ max_input_tokens and max_output_tokens of 0 and REPORTS them: measured on
+ google|aider|gemini-3-flash-preview (2026-09-16), a truncated answer died with
+ `Input tokens: ~45,356 of 0 -- possibly exhausted context window!`, an accusation about a
+ 1,048,576-token model built entirely out of the absent record. base_coder.py:1492 reads
+ `supports_assistant_prefill` off the same dict to decide whether a `finish_reason: length` may
+ be continued by prefilling the assistant turn, and an empty dict always answers no.
+
+ The fix asks the info manager for the BARE id: the same lookup aider would have done without the
+ prefix, and no alias rewriting, because this queries the manager rather than constructing a
+ Model. Whatever litellm ships is what aider gets -- no limit is hardcoded here -- and an id
+ litellm does not know (claude-opus-4.8, grok-4.6, qwen3.8-max and kimi-k3 among them) writes
+ nothing and leaves the turn exactly as it behaves today.
+
+ WHAT THIS DOES NOT DO is change whether a turn passes, and the temptation to claim otherwise was
+ measured away. litellm records no `supports_assistant_prefill` for the gemini family either, so
+ the abandon-on-length path is identical with and without this file, and an A/B of that one pair
+ -- three runs each way, 2026-09-16 -- put every recycle in the same band whichever driver ran:
+ 19.9s / 209.0s with it, 210.8s / 222.8s / 229.2s without, and the original 399.1s failure is the
+ tail of that same distribution rather than a defect this repaired. This makes the limits real
+ and the failure legible. Nothing more.
+ """
+ bare = model.split("/", 1)[1] if model.startswith("openai/") else model
+ try:
+ from aider.models import model_info_manager
+ # get_model_info prints to stdout on a failed cache refresh (models.py:203) and stdout is
+ # this driver's NDJSON channel, so the lookup is fenced off it.
+ with contextlib.redirect_stdout(sys.stderr):
+ info = model_info_manager.get_model_info(bare)
+ except Exception:
+ info = None
+ if not info:
+ return None
+ path = pathlib.Path(cwd, ".harness", "aider", "model-metadata.json")
+ try:
+ path.write_text(json.dumps({model: dict(info)}, default=str))
+ except OSError:
+ return None
+ return str(path)
+
+
+def _history_budget(meta_path: str | None) -> int:
+ """How much of the conversation aider keeps verbatim before summarising it away.
+
+ aider caps it at min(max(window/16, 1024), 8192) tokens (models.py:346), and 1024 for an id
+ litellm has no record of, which is most of this catalog. Past that cap the restored history is
+ SUMMARISED by a model call on every turn, and the summary is lossy: measured in the console
+ matrix (hr-test, 2026-09-18), after four short turns the fifth could no longer say what the
+ first message asked for, on ids that answered the same question one turn earlier. The other
+ bases keep the whole transcript until the window is near full; aider gets the same here.
+ Half the window when the record says it, else HR_AIDER_HISTORY_TOKENS, 96,000, which fits the
+ 128k windows at the small end of the catalog with the map, the doc and a reply beside it."""
+ fallback = int(os.environ.get("HR_AIDER_HISTORY_TOKENS", "96000"))
+ if not meta_path:
+ return fallback
+ try:
+ record = next(iter(json.loads(pathlib.Path(meta_path).read_text()).values()))
+ window = int(record.get("max_input_tokens") or 0)
+ except (OSError, ValueError, StopIteration, AttributeError, TypeError):
+ return fallback
+ return max(window // 2, 8192) if window else fallback
+
+
+def main() -> int:
+ job = json.loads(sys.argv[1])
+ cwd = job.get("cwd") or os.getcwd()
+ os.chdir(cwd)
+
+ # The repo-map tags cache is `Path(root) / RepoMap.TAGS_CACHE_DIR` with no CLI flag, so the
+ # stock value drops a `.aider.tags.cache.v4/` directory in the workspace ROOT — which this
+ # product collects and hands back to the user as a produced file on every turn. Under .harness/
+ # it is excluded by _PRODUCED_EXCLUDE_PREFIX and still checkpointed. Set BEFORE any Coder is
+ # constructed, because RepoMap reads it in __init__.
+ from aider.repomap import RepoMap
+ RepoMap.TAGS_CACHE_DIR = ".harness/aider/tags.cache.v4"
+ pathlib.Path(cwd, ".harness", "aider").mkdir(parents=True, exist_ok=True)
+
+ from aider.main import main as aider_main
+
+ hist = pathlib.Path(cwd, ".harness", "aider")
+ # The harness's own files stay out of aider's repo map: .harness/ holds the skill bundles
+ # (their scripts would otherwise be summarised into every request), aider's own state and the
+ # MCP shim, none of which is the user's project. The map then describes the task's files
+ # alone, and an empty workspace gets no map at all.
+ ignore = hist / "aiderignore"
+ ignore.write_text(".harness/\nAGENTS.md\n.gitignore\n")
+ argv = [
+ "--aiderignore", str(ignore),
+ "--model", job["model"],
+ # The edit format decides whether a skill's script can run AT ALL: shell commands are
+ # extracted in editblock_coder.get_edits(), and wholefile/udiff/patch never populate
+ # shell_commands, so a ```bash block is inert on those formats. Pinned, not left to the
+ # per-model default.
+ "--edit-format", "diff",
+ "--yes-always",
+ "--no-pretty", "--no-fancy-input", "--no-stream",
+ "--no-check-update", "--no-show-release-notes", "--no-show-model-warnings",
+ "--no-analytics",
+ # WITHOUT THIS A TURN CAN HANG FOREVER. aider's --timeout defaults to None, so a provider
+ # that accepts the connection and never finishes the stream leaves the API call waiting with
+ # no bound; aider's own retry loop cannot help, because it only fires on an exception and is
+ # itself bounded (retry_delay doubles until it passes RETRY_TIMEOUT=60, ~63s in total).
+ # Measured in the support matrix's vercel column: single scenarios ran 3,621s, 6,040s,
+ # 16,071s and 27,360s — against 7-30s for the same scenarios on a healthy call — and only
+ # the runner's 6-hour MAX_TURN_SECONDS eventually killed them. Every other backend surfaced
+ # the same provider flakiness as a fast error ("Upstream stream ended before terminal
+ # chunk"); on aider it was an unbounded wait.
+ "--timeout", os.environ.get("HR_AIDER_TIMEOUT", "300"),
+ # The workspace is this product's checkpoint repo. aider committing into it would interleave
+ # its commits with the harness's own, so aider keeps the repo map and leaves committing to
+ # the harness. --no-gitignore stops it appending .aider* patterns to the .gitignore the
+ # runner writes and owns.
+ "--no-auto-commits", "--no-dirty-commits", "--no-gitignore",
+ "--chat-history-file", str(hist / "chat.history.md"),
+ "--input-history-file", str(hist / "input.history"),
+ # aider's ONLY continuation mechanism: it replays that file into the context. Passed on
+ # EVERY turn, not just a resume — on a first turn the file does not exist and aider starts
+ # fresh — and the file travels in the checkpoint, which is what lets a follow-up after a
+ # sandbox recycle still know what was said. Without it every aider turn is a new thread.
+ "--restore-chat-history",
+ ]
+ meta = _write_model_metadata(cwd, job["model"])
+ if meta:
+ argv += ["--model-metadata-file", meta]
+ argv += ["--max-chat-history-tokens", str(_history_budget(meta))]
+ # aider's URL scrape (a URL in the user's message is fetched into the chat after a
+ # confirmation) stays off: the web is reached through a shell command like everything else,
+ # under the one gate, and the catalog lists no separate Web Fetch tool for that reason.
+ argv += ["--no-detect-urls"]
+ coder = aider_main(argv, input=None, output=None, return_coder=True)
+ if not hasattr(coder, "run_stream"):
+ _emit("error", {"text": f"aider did not return a coder (exit {coder!r})"})
+ return 1
+
+ # THE HARNESS'S INSTRUCTIONS ARE SYSTEM-LEVEL, as on every other base. aider composes its own
+ # system message and its CLI offers no way in, but the Model object it built carries a
+ # `system_prompt_prefix` that format_chat_chunks puts ahead of that message (base_coder.py:1229,
+ # aider's own hook for "Formatting re-enabled." and "/no_think"). The agent doc goes there.
+ # The alternative, --read, sent the doc as a USER message ("Here are some READ ONLY files,
+ # provided for your reference") ahead of the conversation, so the model's first user message
+ # was aider's preamble: asked what the first message of the task said, gpt-5.4 answered
+ # "reference" (hr-test, 2026-09-18). With the doc in the system message the conversation holds
+ # the user's turns and nothing else before them (the repo map, when the workspace has files,
+ # is aider's own user-role message and stays).
+ prefix = []
+ for path in job.get("system_files") or []:
+ try:
+ prefix.append(pathlib.Path(path).read_text())
+ except OSError:
+ continue
+ if prefix:
+ coder.main_model.system_prompt_prefix = (
+ "\n\n".join(p.strip() for p in prefix if p.strip()) + "\n\n"
+ + (coder.main_model.system_prompt_prefix or ""))
+
+ # THE OPERATOR'S STEP BUDGET. aider has no CLI flag for it: its loop is Coder.max_reflections,
+ # a class attribute defaulting to 3, and the driver holds the object. Unlike kimi (1000 steps)
+ # and openhands (500 iterations) aider's default is already small, so this is about honouring a
+ # budget that was set rather than about bounding a runaway — but a budget the caller set and the
+ # backend ignores is the kind of quiet lie this repo treats as a defect.
+ budget = job.get("max_turns")
+ if budget:
+ coder.max_reflections = max(1, int(budget))
+
+ # THE CONVERSATION HOLDS ONLY WHAT THE USER SAID. aider's few-shot examples for the edit
+ # format are, by default for most ids, injected as REAL user/assistant turns ahead of the
+ # user's own, so the first user message the model sees is "Change get_factorial() to use
+ # math.factorial". Asked what the first message of the task asked for, the gpt-5 family
+ # answered "Change" (console matrix, hr-test 2026-09-18, once the history was kept intact).
+ # aider's own switch folds the examples into the system prompt instead (base_coder.py:1233);
+ # a per-model settings file would replace every other setting of the model with the class
+ # defaults, so the attribute is set on the object, which is what format_chat_chunks reads.
+ coder.main_model.examples_as_sys_msg = True
+ # NO TEMPERATURE. aider sends `temperature: 0` for every id its settings do not know, and a
+ # provider that has retired the field refuses the whole turn: claude-fable-5-1 on TokenRouter
+ # answered "`temperature` is deprecated for this model" and the turn died after 171 s of
+ # retries (console matrix, hr-test 2026-09-18). No other base sets a temperature; aider's own
+ # per-model switch leaves it out.
+ coder.main_model.use_temperature = False
+
+ disabled = job.get("tools_disabled") or []
+ gate = _Gate(disabled)
+ _install(coder, gate)
+ _run_shell_commands_reporting(coder, gate, reflect=bool(job.get("reflect_shell_output", True)))
+
+ _emit("init", {"model": coder.main_model.name, "edit_format": coder.edit_format})
+ try:
+ _run_turn(coder, job["prompt"])
+ except Exception as exc: # noqa: BLE001 — the turn's failure is the product here, not a crash
+ _emit("error", {"text": f"{type(exc).__name__}: {exc}"})
+ _emit("result", {"final": "", "ok": False, "edited": [], "reason": str(exc)[:500]})
+ return 1
+
+ # usage_report is None when no completion came back — the in-process failure signal that
+ # stdout cannot give. Otherwise the turn failed when an error was the LAST thing that
+ # happened: a provider refusal ends the turn on io.tool_error with nothing after it. An error
+ # the turn recovered from (a file it could not read, an edit block it retried) followed by
+ # more of the model's work is not a failed turn: measured 2026-09-19, a restyled .pptx and an
+ # edited hello.md were reported FAILED for a decode error twelve commands earlier.
+ failed = coder.usage_report is None or gate.error_after_output
+ _emit("result", {
+ # The result's text is what the gateway stores as the answer, so it is stripped of the
+ # edit markup exactly as the text events were; the edits were reported as cards.
+ "final": strip_edit_blocks(coder.partial_response_content or ""),
+ "ok": not failed,
+ "edited": sorted(coder.aider_edited_files or []),
+ "shell_calls": gate.calls,
+ "usage_report": coder.usage_report,
+ "seconds": round(time.time() - _T0, 2),
+ })
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/runner/aider_mcp_bridge.py b/runner/aider_mcp_bridge.py
new file mode 100644
index 00000000..9850e698
--- /dev/null
+++ b/runner/aider_mcp_bridge.py
@@ -0,0 +1,171 @@
+"""aider's MCP client, built on the official Model Context Protocol Python SDK.
+
+aider ships no MCP client of any kind — `grep -rniE "\\bmcp\\b"` over the whole 0.86.2 tree returns
+nothing. Rather than record the capability as missing, the harness brings one and lets the model
+reach it through the ONE tool surface aider has: a shell command it proposes in a fenced block.
+
+WHY NOT f/mcptools, which was the first choice: it is a Go program that publishes NO binaries on any
+release (checked every release through v0.7.1 — all have zero assets), so installing it would mean
+adding a Go toolchain to a python:3.12-slim image for one command. The official `mcp` SDK is MIT,
+pip-installable, and goes straight into the venv aider already needs. It is also the more defensible
+"well-known open source component": the protocol's own reference implementation rather than a third
+party's wrapper around it.
+
+Invoked as `hr-mcp`, a shim the turn builder writes into the workspace and puts on PATH:
+
+ hr-mcp tools <server>
+ hr-mcp call <server> <tool> --params '{"key": "value"}'
+
+Servers are named, not URL'd, so the model cannot invent an endpoint: the names and their targets
+come from the harness's own configuration, written beside this file as aider-mcp.json.
+"""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import pathlib
+import sys
+
+
+def _load(config: str) -> dict:
+ try:
+ data = json.loads(pathlib.Path(config).read_text())
+ except Exception as exc: # noqa: BLE001
+ print(f"hr-mcp: cannot read its server list ({exc})", file=sys.stderr)
+ raise SystemExit(2)
+ return data
+
+
+def _refused(config: dict, server: str, tool: str) -> str:
+ """The harness's tool policy, enforced HERE, where the call executes: the driver's gate names
+ the call in the turn record, but a gate that reads a shell command can be walked around by
+ the shell (a compound command did, hr-test 2026-09-18), and the bridge is the only road to the
+ server. The disabled names travel in the same file as the servers."""
+ disabled = {str(d).strip().lower() for d in (config.get("disabledTools") or []) if str(d).strip()}
+ for name in (tool.lower(), f"{server}.{tool}".lower()):
+ if name in disabled:
+ return f"hr-mcp: the harness disabled the tool '{tool}'"
+ return ""
+
+
+def _target(servers: dict, name: str):
+ """The SDK object that reaches this server, built from what the HARNESS declared.
+
+ The transport is never inferred. A URL handed to the SDK as a plain string is hard-wired to
+ streamable HTTP (`Client.__init__` -> `streamable_http_client(srv)`, client.py:393-394), and
+ that path takes no headers either — they are configured on an httpx client, not on the call. So
+ a declared SSE server would have been dialled with the wrong protocol and a declared header
+ would have been written to the config and never sent. Both are built explicitly here.
+ """
+ entry = servers.get(name)
+ if entry is None:
+ known = ", ".join(sorted(servers)) or "none are configured"
+ print(f"hr-mcp: no MCP server named {name!r} (known: {known})", file=sys.stderr)
+ raise SystemExit(2)
+ url = (entry.get("url") or "").strip()
+ if url:
+ headers = {str(k): str(v) for k, v in (entry.get("headers") or {}).items()}
+ if str(entry.get("transport") or "").lower() == "sse":
+ from mcp.client.sse import sse_client
+ return sse_client(url, headers=headers or None)
+ if headers:
+ import httpx2
+ from mcp.client.streamable_http import streamable_http_client
+ return streamable_http_client(url, http_client=httpx2.AsyncClient(headers=headers))
+ return url
+ cmd = entry.get("command")
+ if cmd:
+ from mcp import StdioServerParameters
+ return StdioServerParameters(command=cmd, args=[str(a) for a in (entry.get("args") or [])],
+ env=entry.get("env") or None)
+ print(f"hr-mcp: server {name!r} has neither a url nor a command", file=sys.stderr)
+ raise SystemExit(2)
+
+
+def _render(result) -> str:
+ """A CallToolResult as text the agent can read. Structured content wins when present, because a
+ tool that returns data should not be flattened into prose."""
+ # FIELD NAMES ARE snake_case IN THE 2.2.0 SDK — structured_content, is_error, input_schema —
+ # not the camelCase of older releases. Read off mcp.types.Tool/CallToolResult.model_fields
+ # against the pinned version, after the camelCase guess silently produced an AttributeError
+ # inside a TaskGroup and came out as an unreadable ExceptionGroup.
+ structured = getattr(result, "structured_content", None)
+ if structured:
+ return json.dumps(structured, indent=2, default=str)
+ parts = []
+ for block in (getattr(result, "content", None) or []):
+ text = getattr(block, "text", None)
+ parts.append(text if text is not None else json.dumps(
+ getattr(block, "model_dump", lambda: str(block))(), default=str))
+ return "\n".join(p for p in parts if p)
+
+
+async def _run(args) -> int:
+ # _target has already built the transport the harness declared; Client accepts a URL string,
+ # StdioServerParameters or a Transport, and only the string form is hard-wired to streamable
+ # HTTP. `mode` here is the protocol-handshake era, not the HTTP transport.
+ from mcp.client.client import Client
+
+ config = _load(args.config)
+ servers = config.get("mcpServers") or {}
+ if args.command == "call":
+ refused = _refused(config, args.server, args.tool)
+ if refused:
+ print(refused, file=sys.stderr)
+ return 1
+ target = _target(servers, args.server)
+ async with Client(target, raise_exceptions=False) as client:
+ if args.command == "tools":
+ listed = await client.list_tools()
+ for tool in listed.tools:
+ desc = (tool.description or "").strip().splitlines()
+ print(f"{tool.name}: {desc[0] if desc else ''}")
+ print(f" params: {json.dumps(tool.input_schema or {}, default=str)}")
+ return 0
+ result = await client.call_tool(args.tool, args.parsed_params)
+ print(_render(result))
+ # A tool that reports failure must exit non-zero, so the agent sees a failed command rather
+ # than an answer-shaped one.
+ return 1 if getattr(result, "is_error", False) else 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ p = argparse.ArgumentParser(prog="hr-mcp", description="Call MCP tools from the shell.")
+ p.add_argument("--config", default=".harness/aider-mcp.json")
+ sub = p.add_subparsers(dest="command", required=True)
+ t = sub.add_parser("tools", help="list a server's tools")
+ t.add_argument("server")
+ c = sub.add_parser("call", help="call one tool")
+ c.add_argument("server")
+ c.add_argument("tool")
+ c.add_argument("--params", default="")
+ args = p.parse_args(argv)
+ # Validate BEFORE anything is imported or connected: a malformed --params is the agent's
+ # mistake, and it should be told that in one line rather than shown whatever the import or the
+ # network failed with first.
+ args.parsed_params = {}
+ if args.command == "call":
+ try:
+ args.parsed_params = json.loads(args.params) if args.params else {}
+ except json.JSONDecodeError as exc:
+ print(f"hr-mcp: --params is not valid JSON ({exc})", file=sys.stderr)
+ return 2
+ if not isinstance(args.parsed_params, dict):
+ print("hr-mcp: --params must be a JSON object", file=sys.stderr)
+ return 2
+ try:
+ return asyncio.run(_run(args))
+ except SystemExit:
+ raise
+ except BaseException as exc: # noqa: BLE001 — the agent reads stderr; a traceback helps nobody
+ # anyio runs the transport in a TaskGroup, so a failure arrives wrapped in an ExceptionGroup
+ # whose own str() says only "unhandled errors in a TaskGroup (1 sub-exception)". Unwrap it,
+ # or every MCP failure reaches the agent as that same useless sentence.
+ for inner in getattr(exc, "exceptions", None) or [exc]:
+ print(f"hr-mcp: {type(inner).__name__}: {inner}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/runner/server.py b/runner/server.py
index 4e6f6d07..e89753e3 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -240,6 +240,26 @@ def _own_tree(root: str, uid: int, from_uids: set[int]) -> None:
continue
+def _aider_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:
+ """aider has no session id at all: its continuation is a chat-history FILE, and a missing one
+ resumes silently with no output difference whatsoever (measured on 0.86.2). So the question
+ "is the conversation there?" is "does the history hold at least one message?", asked with
+ aider's own parser rather than by eyeballing the markdown.
+
+ The driver relocates that file under .harness/ so it is neither a produced file nor a name the
+ user sees; the runner mints the session id, as it does for kimi."""
+ hist = pathlib.Path(cwd) / ".harness" / "aider" / "chat.history.md"
+ if not hist.is_file():
+ return False
+ try:
+ text = hist.read_text(errors="replace")
+ except OSError:
+ return False
+ # aider's own marker for a recorded exchange: split_chat_history_markdown keys on the "####"
+ # user-message heading. Matching it here is reading aider's format, not guessing at prose.
+ return any(line.startswith("####") for line in text.splitlines())
+
+
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."""
@@ -271,6 +291,7 @@ _SESSION_PRESENT = {
"opencode": _argv_session_present,
"goose": _goose_session_present,
"kimi": _argv_session_present,
+ "aider": _aider_session_present,
}
@@ -437,6 +458,7 @@ DSH_DEFAULT_MODEL = os.environ.get("DSH_DEFAULT_MODEL", "deepseek-v4-pro")
OMP_DEFAULT_MODEL = os.environ.get("OMP_DEFAULT_MODEL", "gpt-5.4")
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")
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.
@@ -858,7 +880,11 @@ def _write_skills(cwd: str, skills: list[dict], backend: str = "claude") -> list
rootrels = [".harness/skills"]
entryroot = ".harness/skills"
else:
- # dsh has no skill loader; the AGENTS.md block below is the only door
+ # dsh has no skill loader; the AGENTS.md block below is the only door.
+ # aider lands here on purpose too, and for a stronger reason: it has no skill loader AND no
+ # instruction-file discovery, so its turn builder passes every file under this directory to
+ # --read explicitly. Under .harness/ the bundle is excluded from produced files, so a skill
+ # is never handed back to the user as a deliverable of their own task.
rootrels = [".harness/skills"]
entryroot = ".harness/skills"
# cline lands in the else on purpose, with the evidence written down so nobody "fixes" it:
@@ -1185,8 +1211,10 @@ def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:
# 1.50.0 package), merging from the project root down to the work dir, and injects the
# content VERBATIM into the system prompt: verified live, inside a
# "<!-- 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.
"AGENTS.md" if backend in ("codex", "hermes", "pi", "dsh", "opencode", "cline", "omp",
- "goose", "kimi")
+ "goose", "kimi", "aider")
else "CLAUDE.md")
@@ -3141,6 +3169,77 @@ def _served_model_in(data: bytes) -> str:
_FINISH_RE = re.compile(rb'"finish_reason"\s*:\s*"([a-z_]{1,40})"')
+def _usage_fields(u) -> dict:
+ """One provider usage object, in the runner's contract: {input_tokens (FRESH input only),
+ output_tokens, cache_read_tokens, cache_write_tokens}, only the fields the object carries.
+
+ Three shapes pass the relay. OpenAI chat: prompt_tokens is GROSS (cache hits included) with the
+ cached part under prompt_tokens_details.cached_tokens, so it is netted here the way
+ _norm_token_usage nets codex's. Anthropic messages: input_tokens is already net, the cache
+ counters are their own fields. Gemini's usageMetadata: promptTokenCount is gross with
+ cachedContentTokenCount the cached part."""
+ if not isinstance(u, dict):
+ return {}
+
+ def n(v) -> int:
+ try:
+ return max(int(v or 0), 0)
+ except (TypeError, ValueError):
+ return 0
+
+ if "prompt_tokens" in u or "completion_tokens" in u:
+ det = u.get("prompt_tokens_details")
+ cached = n(det.get("cached_tokens")) if isinstance(det, dict) else 0
+ return {"input_tokens": max(n(u.get("prompt_tokens")) - cached, 0),
+ "output_tokens": n(u.get("completion_tokens")), "cache_read_tokens": cached}
+ if "input_tokens" in u or "output_tokens" in u:
+ out = {}
+ for src, dst in (("input_tokens", "input_tokens"), ("output_tokens", "output_tokens"),
+ ("cache_read_input_tokens", "cache_read_tokens"),
+ ("cache_creation_input_tokens", "cache_write_tokens")):
+ if u.get(src) is not None:
+ out[dst] = n(u[src])
+ return out
+ if "promptTokenCount" in u or "candidatesTokenCount" in u:
+ cached = n(u.get("cachedContentTokenCount"))
+ return {"input_tokens": max(n(u.get("promptTokenCount")) - cached, 0),
+ "output_tokens": n(u.get("candidatesTokenCount")), "cache_read_tokens": cached}
+ return {}
+
+
+def _usage_in_doc(doc) -> dict:
+ """The usage a response document or stream event carries, if any. Anthropic's stream puts the
+ input side on message_start (under message.usage) and the output side on message_delta, so a
+ call's usage is the union of what its events said, later values replacing earlier ones."""
+ if not isinstance(doc, dict):
+ return {}
+ for u in (doc.get("usage"), doc.get("usageMetadata"),
+ (doc.get("message") or {}).get("usage") if isinstance(doc.get("message"), dict) else None):
+ got = _usage_fields(u)
+ if got:
+ return got
+ return {}
+
+
+def _usage_in_sse_line(line: bytes) -> dict:
+ """One SSE line as it passes the relay → the usage it carries, {} for anything else."""
+ if not line.startswith(b"data:") or b"sage" not in line:
+ return {}
+ try:
+ return _usage_in_doc(json.loads(line[5:].strip()))
+ except ValueError:
+ return {}
+
+
+def _usage_add(flags: dict, call_usage: dict) -> None:
+ """Fold one call's usage into the route's running total: a turn is many provider calls."""
+ if not call_usage:
+ return
+ total = flags.setdefault("usage", {})
+ for k, v in call_usage.items():
+ total[k] = int(total.get(k, 0)) + int(v)
+
+
def _model_metadata_with_context_length(data: bytes) -> bytes:
"""A model listing (GET /models or /models/<id>) with the window also under `context_length`.
@@ -3201,6 +3300,24 @@ def _relay_served_model(env: dict) -> str:
return ""
+def _relay_usage(env: dict) -> dict:
+ """The tokens the provider reported on this turn's route, summed over its calls; {} when the
+ turn did not ride the relay or nothing carried usage. Found by the placeholder bearer, exactly
+ as _relay_served_model finds the served model, and subject to the same one-route invariant.
+
+ This is the usage of every backend whose own stream reports none (kimi, aider): the provider's
+ statement of what it counted, read off the bytes as they pass, rather than a number the CLI
+ estimated or nothing at all. A backend that reports its own usage keeps it; this only fills a
+ result event that arrived empty."""
+ for v in env.values():
+ if isinstance(v, str) and v.startswith("hr-relay-"):
+ route = _HERMES_RELAY["routes"].get(v)
+ if route:
+ u = (route[2] or {}).get("usage")
+ return dict(u) if isinstance(u, dict) and u else {}
+ return {}
+
+
class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
@@ -3355,6 +3472,7 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
pending = b""
carry = b"" # tail of the previous chunk, so a split "model":"…" is still seen
fcarry = b"" # tail of the previous chunk, for the finish_reason field
+ call_usage: dict = {} # what this call's events said about tokens, unioned
while True:
chunk = resp.read(4096)
if not chunk:
@@ -3373,14 +3491,20 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
if fr:
flags["last_finish"] = fr
fcarry = chunk[-64:]
- if sigs is not None:
- pending += chunk
- while b"\n" in pending:
- line, pending = pending.split(b"\n", 1)
- for cid, sig in _google_signatures_in_line(line.strip()):
+ # usage (and Google's tool-call signatures) live on whole SSE lines, so the
+ # stream is line-buffered as it passes; the bytes still go through untouched
+ pending += chunk
+ while b"\n" in pending:
+ line, pending = pending.split(b"\n", 1)
+ line = line.strip()
+ call_usage.update(_usage_in_sse_line(line))
+ if sigs is not None:
+ for cid, sig in _google_signatures_in_line(line):
sigs[cid] = sig
self.wfile.write(f"{len(chunk):x}\r\n".encode() + chunk + b"\r\n")
self.wfile.flush()
+ call_usage.update(_usage_in_sse_line(pending.strip()))
+ _usage_add(flags, call_usage)
self.wfile.write(b"0\r\n\r\n")
else:
data = resp.read()
@@ -3391,6 +3515,11 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
fr = _finish_reason_in(data[-65536:])
if fr:
flags["last_finish"] = fr
+ if body is not None and b"sage" in data:
+ try:
+ _usage_add(flags, _usage_in_doc(json.loads(data)))
+ except ValueError:
+ pass
if body is None and "/models" in tail.split("?", 1)[0]:
data = _model_metadata_with_context_length(data)
if sigs is not None and b"thought_signature" in data:
@@ -3941,6 +4070,178 @@ def _build_kimi(provider: str, auth: Auth, model: str, prompt: str, cwd: str, en
return cmd
+AIDER_PROVIDERS = {"anthropic", "openai", "azure", "openai-api", "tokenrouter"}
+AIDER_PYTHON = os.environ.get("HR_AIDER_PYTHON", "/data/agent-tools/aider-venv/bin/python")
+AIDER_DRIVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "aider_driver.py")
+# aider's MCP client, runner/aider_mcp_bridge.py, run by the aider venv's own interpreter. aider
+# ships none of its own — zero source hits across the whole 0.86.2 tree — so rather than record the
+# capability as missing, the harness brings one and lets the model reach it through the ONE tool
+# surface aider has: a shell command it proposes. The maintainer's 2026-09-13 decision: bridge the
+# capability, then measure the claim for real.
+AIDER_MCP_BRIDGE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "aider_mcp_bridge.py")
+
+
+def _aider_mcp_servers(mcp_servers: list[dict] | None) -> dict:
+ """The declared servers, keyed by the NAME the model will use. Named rather than URL'd so the
+ model cannot invent an endpoint: it says `hr-mcp call <name> …` and the mapping is ours.
+
+ THE DECLARED TRANSPORT TRAVELS, for the reason _kimi_mcp_config states: the harness's
+ declaration decides, never the url's spelling. It matters more here, because the bridge's SDK
+ does not guess at all — `Client(<str>)` is hard-wired to streamable HTTP (client.py:393-394) —
+ so an SSE server reached this backend as the wrong protocol and could not answer."""
+ out: dict = {}
+ for i, sv in enumerate(mcp_servers or []):
+ if not isinstance(sv, dict):
+ continue
+ name = _skill_dir_name(sv.get("name") or sv.get("id") or f"server{i}")
+ url = (sv.get("url") or "").strip()
+ if url:
+ entry: dict = {"url": url}
+ if str(sv.get("transport") or "").lower() == "sse":
+ entry["transport"] = "sse"
+ hdrs = sv.get("headers")
+ if isinstance(hdrs, dict) and hdrs:
+ entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}
+ elif sv.get("command"):
+ cmd = sv["command"]
+ argv = cmd if isinstance(cmd, list) else [str(cmd)]
+ entry = {"command": argv[0],
+ "args": [str(x) for x in argv[1:]] + [str(x) for x in (sv.get("args") or [])]}
+ envv = sv.get("env")
+ if isinstance(envv, dict) and envv:
+ entry["env"] = {str(k): str(v) for k, v in envv.items()}
+ else:
+ continue
+ out[name] = entry
+ return out
+
+
+def _aider_working_notes(cwd: str, servers: dict | None = None) -> str:
+ """How THIS workspace works, in the terms aider's own prompt uses.
+
+ aider's system prompt tells the model that the USER adds files to the chat and that the
+ user may run the shell commands it suggests. Here nobody sits at that keyboard: the driver
+ answers every confirmation, adds a file the model names, runs a command it proposes and hands
+ the output back in the same turn. Unless the model is told so it behaves as aider's prompt
+ says, measured 2026-09-18 on hr-test: asked to use a skill it guessed the token instead of
+ reading SKILL.md, asked to call an MCP tool it wrote "I'm constrained here to only return
+ SEARCH/REPLACE blocks", asked for a streamable-HTTP tool it invented the result. Reading goes
+ through the shell on purpose: aider's own file-mention route adds only files git already
+ tracks, and on a session's first turn the skill files are not committed yet (measured: the
+ model named the path exactly and the turn ended there). `cat` works on every turn. The paths
+ are workspace-relative; the skills block above keeps its absolute folders for composing
+ commands."""
+ skills = sorted(p.relative_to(cwd).as_posix()
+ for p in (pathlib.Path(cwd) / ".harness" / "skills").glob("*/SKILL.md"))
+ lines = ["\n## How this workspace works for you\n",
+ "You cannot open files or run anything yourself; the harness does both for you "
+ "between messages, without asking anyone.\n",
+ "- To run a command, put it in a ```bash fenced block and end your reply. It is "
+ "executed and its output is given back to you in the next message; then continue.",
+ "- To read a file that is not in the chat, run `cat <path>` that way."]
+ if skills:
+ lines.append(" Read a skill before using it:")
+ lines += [f" - `cat {rel}`" for rel in skills]
+ lines += ["- A skill's scripts run the same way (cd into the skill's folder first)"
+ + (", and so do MCP tool calls (`hr-mcp`, below)." if servers else "."),
+ "- Each line of a bash block runs as its own command. A program that needs more "
+ "than one line goes into a file first (a SEARCH/REPLACE block creates it), then "
+ "one line runs it.",
+ "- Binary files (documents, decks, spreadsheets, images, PDFs) cannot be added to "
+ "the chat or edited with SEARCH/REPLACE; inspect and change them with commands.",
+ "- Report only output you were actually given. Never write the result you expect "
+ "a command or a tool to produce; if you have not run it yet, run it first.\n"]
+ return "\n".join(lines)
+
+
+def _aider_mcp_block(servers: dict) -> str:
+ """The bridge, in the context aider reads, in the exact form the driver's gate recognises.
+
+ Listing the servers is all the runner can do from here: their tool NAMES are only knowable by
+ asking the server, which needs a live connection at turn time. So `hr-mcp tools <server>` is
+ part of the instruction — the model discovers the tools the way a person would — and
+ `hr-mcp call` is what the gate matches, so a call made this way is recorded under the MCP
+ tool's own name and the support matrix measures `mcp_called` from a command that actually ran
+ rather than from a capability we claimed."""
+ if not servers:
+ return ""
+ rows = []
+ for name, entry in servers.items():
+ if entry.get("url"):
+ rows.append(f"- `{name}` — streamable HTTP")
+ else:
+ rows.append(f"- `{name}` — stdio")
+ return ("\n## MCP servers\n\n"
+ "These MCP servers are available to you through the `hr-mcp` command. They are real "
+ "tools: use them when the task calls for one.\n\n"
+ + "\n".join(rows) + "\n\n"
+ "List a server's tools with `hr-mcp tools <server>`, and call one with\n\n"
+ "```bash\n"
+ "hr-mcp call <server> <tool> --params '{\"key\": \"value\"}'\n"
+ "```\n\n"
+ "Propose the command in a ```bash block as you would any other shell command.\n")
+
+
+def _build_aider(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,
+ mcp_servers: list[dict] | None = None, tools_disabled: list[str] | None = None,
+ skills_read: list[str] | None = None, max_turns: int | None = None) -> list[str]:
+ pr = provider or "openai-api"
+ if pr not in AIDER_PROVIDERS:
+ raise HTTPException(400, f"unknown aider provider '{pr}' (one of {sorted(AIDER_PROVIDERS)})")
+ if not auth.base_url:
+ raise HTTPException(400, "aider needs a base_url (none configured)")
+ if auth.api_key:
+ # Every aider turn rides the loopback relay, the qwen rationale unchanged. It matters twice
+ # over here: aider takes its credential only from the environment, and aider reports no
+ # served model of its own, so _relay_served_model is what makes matrix rule 2 enforceable.
+ relay_base, relay_tok = _hermes_relay_route(auth.base_url, auth.api_key)
+ auth = auth.model_copy(update={"base_url": relay_base, "api_key": relay_tok})
+ env["OPENAI_API_BASE"] = auth.base_url
+ env["OPENAI_API_KEY"] = auth.api_key or ""
+ env["HOME"] = str(pathlib.Path(cwd) / ".harness" / "home")
+ pathlib.Path(env["HOME"]).mkdir(parents=True, exist_ok=True)
+ # The MCP bridge, and the only reason aider can reach an MCP server at all. The shim is written
+ # per turn rather than installed once because it has to name the aider venv's interpreter and
+ # the bridge beside this file, both of which are known here and nowhere else.
+ servers = _aider_mcp_servers(mcp_servers)
+ bindir = pathlib.Path(cwd) / ".harness" / "bin"
+ bindir.mkdir(parents=True, exist_ok=True)
+ cfg = pathlib.Path(cwd) / ".harness" / "aider-mcp.json"
+ # The disabled names ride with the servers: the bridge refuses a disabled tool itself, where
+ # the call executes, so the policy holds whatever shell the model wraps the call in.
+ cfg.write_text(json.dumps({"mcpServers": servers,
+ "disabledTools": [str(t) for t in (tools_disabled or [])]}, indent=2))
+ shim = bindir / "hr-mcp"
+ shim.write_text("#!/bin/sh\nexec %s %s --config %s \"$@\"\n"
+ % (shlex.quote(AIDER_PYTHON), shlex.quote(AIDER_MCP_BRIDGE), shlex.quote(str(cfg))))
+ shim.chmod(0o755)
+ env["PATH"] = str(bindir) + os.pathsep + env.get("PATH", os.environ.get("PATH", ""))
+ # The notes and the MCP block are APPENDED to the agent doc the turn already wrote, which
+ # the driver puts into the system message. Without the block the bridge exists and the model is never told
+ # it does — the defect this call site is here to prevent, caught because the block was
+ # generated and never used.
+ doc = _agent_doc_path(cwd, "aider")
+ try:
+ doc.write_text((doc.read_text() if doc.exists() else "")
+ + _aider_working_notes(cwd, servers) + _aider_mcp_block(servers))
+ except OSError:
+ pass
+ # aider resolves a BARE id against its own MODEL_ALIASES table, which rewrites 21 of them —
+ # `gemini-2.5-pro` among them, an id this product's catalog also serves. An `openai/` prefix
+ # routes through litellm's openai provider verbatim and skips that table entirely, so the id the
+ # picker offered is the id the provider is asked for.
+ job = {"cwd": cwd, "model": f"openai/{model}", "prompt": prompt,
+ "tools_disabled": list(tools_disabled or []),
+ # the agent doc, which the driver puts into aider's system message
+ "system_files": list(skills_read or []),
+ # aider takes the budget as Coder.max_reflections, set in the driver: it has no CLI flag
+ # for it, and only an in-process driver holds the object.
+ "max_turns": max_turns}
+ return [AIDER_PYTHON, AIDER_DRIVER, json.dumps(job)]
+
+
+
+
# Path A only (Gemini API Key / Google AI Studio). Unlike qwen, upstream gemini-cli speaks NO
# OpenAI-compatible mode at all (that is a qwen-fork-only addition — see QWEN_PROVIDERS above),
# so there is no loopback-relay trick that lets any generic OpenAI/Anthropic-shaped integration
@@ -5159,6 +5460,128 @@ def _goose_eof(state: dict, rc: int) -> list[dict]:
_goose_to_claude.eof = _goose_eof # type: ignore[attr-defined]
+# aider has NO conversation id of ANY kind — its continuation is the chat-history FILE — so the
+# runner announces a synthetic one. Without it the gateway never records a conversation id, never
+# treats a later turn as a follow-up, and every turn is a fresh thread: measured as the support
+# matrix's recycle scenario failing on every aider row while first/follow-up/switch passed, because
+# those three never ask the agent to remember anything.
+_AIDER_SESSION_NAME = "harness"
+# aider's in-chat command advice in a failure message: the line, and the heading it sits under
+# when nothing else is left of that list.
+_AIDER_CHAT_ADVICE = re.compile(r"^[ \t]*-?[ \t]*Use /\w+[^\n]*\n?", re.M)
+
+
+# ── aider ────────────────────────────────────────────────────────────────────────
+# The turn process is runner/aider_driver.py inside the pinned aider venv: aider is driven IN
+# PROCESS through its own `main(..., return_coder=True)` entry point, and the driver re-emits what
+# it observes as NDJSON — the dsh_driver shape ({"m": method, "p": payload}).
+#
+# THIS IS NOT A STYLE CHOICE. aider has no machine-readable output mode, and its stdout is one
+# channel carrying the model's prose and aider's own diagnostics together. Measured on 0.86.2: a
+# stub returning model prose whose second line began `litellm.AuthenticationError:` was
+# BYTE-IDENTICAL on stdout to a real 401 on the same stream, same exit code 0, no colour under
+# --no-pretty. A text-parsing normaliser would therefore report real answers as provider failures,
+# which is worse than reporting nothing. In process the channels are separate at the source:
+# io.tool_error carries failures, io.assistant_output carries prose, and `coder.usage_report` is
+# None exactly when no completion came back.
+def _aider_to_claude(obj: dict, state: dict) -> list[dict]:
+ m = obj.get("m")
+ p = obj.get("p") if isinstance(obj.get("p"), dict) else {}
+ if not state.get("_aider_init"):
+ # _run_turn_bg records the conversation id ONLY from a system/init event, and that recorded
+ # id is what makes the next turn a follow-up rather than a new thread.
+ state["_aider_init"] = True
+ return ([{"type": "system", "subtype": "init", "session_id": _AIDER_SESSION_NAME,
+ "model": state.get("model")}]
+ + _aider_event(obj, state, m, p))
+ return _aider_event(obj, state, m, p)
+
+
+def _aider_event(obj: dict, state: dict, m, p) -> list[dict]:
+ if m == "text":
+ txt = str(p.get("text") or "")
+ if not txt.strip():
+ return []
+ state["final"] = txt
+ # One event per response, a whole response each, and the console joins consecutive
+ # text blocks as they come: without the blank line a closing fence ran into the next
+ # response's first sentence and the rest of the turn rendered inside a code block
+ # (2026-09-19). A paragraph break keeps each response its own markdown.
+ return [{"type": "assistant", "message": {"content": [{"type": "text", "text": txt.rstrip() + "\n\n"}]}}]
+ if m == "error":
+ # Reached io.tool_error, which the model's prose cannot reach. Recorded, NOT rendered: it is
+ # the turn's failure reason, not part of its answer. aider's advice about its own in-chat
+ # commands (`- Use /drop …`, `- Use /clear …`, base_coder.py show_exhausted_error) is cut,
+ # the same rule kimi's "To resume this session:" line earned: this product has no such
+ # commands, and a reason that names them sends the user looking for a prompt that is not
+ # there.
+ state["_aider_error"] = _AIDER_CHAT_ADVICE.sub("", str(p.get("text") or "")).strip()
+ return []
+ if m == "warning":
+ state.setdefault("_aider_warnings", []).append(str(p.get("text") or ""))
+ return []
+ if m == "shell_decision":
+ # A command the model proposed. An approved one renders as a call whose result arrives on
+ # the following shell_result; a REFUSED one is a complete pair here and now, because the
+ # policy is the whole of its result and nothing ran.
+ tuid = f"sh{len(state.setdefault('_aider_calls', []))}"
+ state["_aider_calls"].append(tuid)
+ call = {"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": tuid, "name": str(p.get("tool") or "Shell"),
+ "input": {"command": str(p.get("command") or "")}}]}}
+ if p.get("approved"):
+ state["_aider_last_call"] = tuid
+ return [call]
+ return [call, {"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": tuid, "is_error": True,
+ "content": str(p.get("reason") or "refused by the harness tool policy")}]}}]
+ if m == "shell_result":
+ tuid = state.get("_aider_last_call") or "sh0"
+ return [{"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": tuid, "is_error": False,
+ "content": str(p.get("output") or "")}]}}]
+ if m == "edits":
+ # Files aider's edit engine wrote this pass, one card each, the way every other base's
+ # file edits render. The SEARCH/REPLACE markup that produced them is aider's wire format,
+ # not the answer, and the driver strips it from the text.
+ out: list[dict] = []
+ for f in p.get("files") or []:
+ tuid = f"ed{len(state.setdefault('_aider_calls', []))}"
+ state["_aider_calls"].append(tuid)
+ out.append({"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": tuid, "name": "Edit", "input": {"file_path": str(f)}}]}})
+ out.append({"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": tuid, "is_error": False, "content": "edited"}]}})
+ return out
+ if m == "result":
+ err = state.get("_aider_error") or ""
+ ok = bool(p.get("ok")) and not err
+ final = str(p.get("final") or state.get("final") or "")
+ if ok:
+ state["final"] = final
+ # usage is {} deliberately: per the 2026-09-13 decision no harness PR builds its own usage
+ # pipeline. aider's own numbers would be the wrong ones anyway — with streaming it fills the
+ # real field names with a tiktoken ESTIMATE (587 against a true 595, measured), and it reads
+ # cache under names an OpenAI-shaped response never carries. _relay_usage stamps these rows.
+ return [{"type": "result", "subtype": "success" if ok else "error", "is_error": not ok,
+ "result": final if ok else (err or p.get("reason") or ""), "usage": {}}]
+ return []
+
+
+def _aider_eof(state: dict, rc: int) -> list[dict]:
+ """The driver emits its own result event, so this fires only when the process died before
+ reaching it — a crash, a kill, an import failure. The reason then comes from io.tool_error if
+ anything got that far, and otherwise from the errbuf tail _failure_reason prefers."""
+ err = state.get("_aider_error") or ""
+ if rc == 0 and not err:
+ return [{"type": "result", "subtype": "success", "is_error": False,
+ "result": state.get("final", ""), "usage": {}}]
+ return [{"type": "result", "subtype": "error", "is_error": True, "result": err, "usage": {}}]
+
+
+_aider_to_claude.eof = _aider_eof # type: ignore[attr-defined]
+
+
# ── kimi ─────────────────────────────────────────────────────────────────────────
@@ -5326,6 +5749,8 @@ BACKENDS = {
# normaliser and an eof rather than the passthrough qwen's claude-shaped stream can use.
"kimi": {"providers": sorted(KIMI_PROVIDERS), "default_model": KIMI_DEFAULT_MODEL,
"normalize": _kimi_to_claude},
+ "aider": {"providers": sorted(AIDER_PROVIDERS), "default_model": AIDER_DEFAULT_MODEL,
+ "normalize": _aider_to_claude},
}
@@ -5446,6 +5871,9 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m
served = _relay_served_model(env)
if served:
ev["model"] = served
+ if ev.get("type") == "result" and not ev.get("usage"):
+ # Same for the tokens: the CLI reported none, the relay counted the provider's.
+ ev["usage"] = _relay_usage(env)
with _turns_lock:
rec["events"].append(ev)
if ev.get("type") == "system" and ev.get("subtype") == "init" and ev.get("session_id"):
@@ -5473,6 +5901,8 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m
served = _relay_served_model(env)
if served:
ev["model"] = served
+ if ev.get("type") == "result" and not ev.get("usage"):
+ ev["usage"] = _relay_usage(env)
with _turns_lock:
rec["events"].append(ev)
if ev.get("type") == "result":
@@ -6531,6 +6961,27 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,
skills_dir=kimi_skills, tools_disabled=req.tools_disabled,
max_turns=req.max_turns)
+ elif backend == "aider":
+ model = model or AIDER_DEFAULT_MODEL
+ # aider has no skill loader and no instruction-file convention: the driver puts the agent
+ # doc into aider's system message (the Model's system_prompt_prefix, aider's own hook). The
+ # agent doc alone goes through it. Its
+ # skills block names each installed skill with its description and folder, and the model
+ # reaches a skill's files ON DEMAND through the one tool surface it has, a shell command
+ # (`cat <folder>/SKILL.md`), whose output the driver feeds back in the same turn, or by
+ # naming a tracked file, which aider adds to the chat itself. That is the door every base
+ # without a loader uses (dsh reads them with its file tools). The PR read EVERY file of every
+ # bundle on every turn: measured on hr-test 2026-09-18, the three built-in bundles are 27
+ # files and 264 KB, licences and a PNG among them, and "Reply with exactly: …" cost 45,030
+ # input tokens. A skill's content is loaded when a task calls for it, never as a tax on
+ # every turn.
+ aider_read: list[str] = []
+ doc = _agent_doc_path(cwd, backend)
+ if doc.exists():
+ aider_read.append(str(doc))
+ 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 == "gemini":
model = model or GEMINI_DEFAULT_MODEL
cmd = _build_gemini(req.provider, auth, model, req.prompt, cwd, env,
diff --git a/runner/tests/test_aider_driver.py b/runner/tests/test_aider_driver.py
new file mode 100644
index 00000000..54e9cff1
--- /dev/null
+++ b/runner/tests/test_aider_driver.py
@@ -0,0 +1,773 @@
+"""The aider backend (Aider-AI/aider, Apache-2.0, pinned to 0.86.2).
+
+aider is the only backend here driven IN PROCESS, and every test below pins one of the reasons why.
+The reason that decided it: on stdout, model prose beginning `litellm.AuthenticationError:` is
+BYTE-IDENTICAL to a real 401 — same stream, same exit code 0 — so a text-parsing normaliser would
+turn ordinary answers into provider failures. In process the channels are separate at the source.
+
+Source anchors (all 0.86.2):
+ return_coder / forced yes_always aider/main.py:451, 546-547
+ the ONE explicit_yes_required site aider/coders/base_coder.py handle_shell_commands
+ shell extraction, diff format only aider/coders/editblock_coder.py get_edits
+ shell output is not reflected aider/coders/base_coder.py:1609-1614
+ MODEL_ALIASES (21 rewrites) aider/models.py:87-111
+ TAGS_CACHE_DIR, no CLI flag aider/repomap.py:43
+"""
+import json
+import os
+import pathlib
+import sys
+import tempfile
+import types
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import aider_driver # noqa: E402
+from server import (Auth, BACKENDS, _AIDER_SESSION_NAME, _aider_eof, # noqa: E402
+ _aider_mcp_block,
+ _aider_to_claude, _agent_doc_path, _build_aider, _resume_lost)
+
+
+# ── the policy gate: what makes tool_enforcement "hard" true rather than asserted ──
+def test_an_ordinary_command_is_approved_and_named_shell():
+ g = aider_driver._Gate([])
+ assert g.decide("python3 stamp.py") == (True, "Shell", "")
+
+
+def test_disabling_shell_refuses_the_command_the_model_proposed():
+ g = aider_driver._Gate(["Shell"])
+ approved, tool, reason = g.decide("python3 stamp.py")
+ assert approved is False and tool == "Shell"
+ assert "disabled shell commands" in reason
+
+
+def test_an_mcp_call_is_named_for_the_tool_it_invokes():
+ """The bridge's call form. Naming the call after the MCP tool is what lets the support matrix
+ measure `mcp_called` from a command that actually ran — aider itself has no MCP client at all
+ (zero source hits across the 0.86.2 tree)."""
+ g = aider_driver._Gate([])
+ assert g.mcp_calls_in("hr-mcp call deepwiki read_wiki_structure --params {}") == \
+ [("deepwiki", "read_wiki_structure")]
+ approved, tool, _ = g.decide("hr-mcp call deepwiki read_wiki_structure --params {}")
+ assert approved is True and tool == "deepwiki.read_wiki_structure"
+
+
+def test_disabling_an_mcp_tool_refuses_it_by_its_own_name():
+ g = aider_driver._Gate(["read_wiki_structure"])
+ approved, tool, reason = g.decide("hr-mcp call deepwiki read_wiki_structure --params {}")
+ assert approved is False and tool == "deepwiki.read_wiki_structure"
+ assert "read_wiki_structure" in reason
+
+
+def test_a_disabled_tool_is_refused_wherever_the_call_stands_in_a_compound_command():
+ """gpt-5.4, with probe_sse disabled, proposed `hr-mcp tools probe && hr-mcp call probe
+ probe_sse` and a gate that read argv[0..3] saw a discovery and let the call through (hr-test,
+ 2026-09-18). The whole command is scanned; the bridge refuses the same name itself."""
+ g = aider_driver._Gate(["probe_sse"])
+ assert g.decide("hr-mcp tools probe && hr-mcp call probe probe_sse --params '{}'")[0] is False
+ assert g.decide("cd x; .harness/bin/hr-mcp call probe probe_sse")[0] is False
+ assert g.decide("echo | hr-mcp call probe probe_sse")[0] is False
+ ok, name, _ = g.decide("hr-mcp call probe other_tool")
+ assert ok and name == "probe.other_tool"
+ # the bridge's own refusal, by bare name and by server.tool
+ cfg = {"mcpServers": {"probe": {"url": "https://x/sse"}}, "disabledTools": ["probe_sse"]}
+ assert aider_mcp_bridge._refused(cfg, "probe", "probe_sse").startswith("hr-mcp: the harness disabled")
+ assert aider_mcp_bridge._refused({"disabledTools": ["probe.probe_sse"]}, "probe", "probe_sse")
+ assert aider_mcp_bridge._refused(cfg, "probe", "other") == ""
+ # and the runner writes the names beside the servers
+ _, d, _, _ = _build(tools_disabled=["probe_sse"], mcp_servers=[{"name": "probe", "url": "https://x/sse", "transport": "sse"}])
+ doc = json.loads(pathlib.Path(d, ".harness", "aider-mcp.json").read_text())
+ assert doc["disabledTools"] == ["probe_sse"] and "probe" in doc["mcpServers"]
+
+
+def test_a_command_that_merely_mentions_hr_mcp_is_not_an_mcp_call():
+ """`hr-mcp` in prose, or a bare `hr-mcp tools <server>` discovery call, is a shell command —
+ only the four-part `call` form names a tool, and treating anything else as one would invent an
+ MCP call in the turn record."""
+ g = aider_driver._Gate([])
+ assert g.mcp_calls_in("echo hr-mcp call x y") == []
+ assert g.mcp_calls_in("hr-mcp tools deepwiki") == []
+
+
+def test_an_unparseable_command_does_not_crash_the_gate():
+ g = aider_driver._Gate([])
+ assert g.mcp_calls_in('hr-mcp call "unclosed') == []
+ assert g.decide('hr-mcp call "unclosed')[1] == "Shell"
+
+
+# ── the normalizer ───────────────────────────────────────────────────────────────
+def _norm(events):
+ state: dict = {}
+ out = []
+ for e in events:
+ out += _aider_to_claude(e, state)
+ return [e for e in out if e.get("subtype") != "init"], state
+
+
+def test_a_failure_on_the_error_channel_is_not_rendered_as_the_answer():
+ """The whole point of the driver. io.tool_error is reachable only by aider itself; the model's
+ prose cannot reach it. The text becomes the turn's reason and never its result."""
+ out, state = _norm([
+ {"m": "text", "p": {"text": "Here is what I found about the error handling."}},
+ {"m": "error", "p": {"text": "litellm.AuthenticationError: Incorrect API key provided"}},
+ {"m": "result", "p": {"ok": False, "final": ""}},
+ ])
+ rendered = [e for e in out if e.get("type") == "assistant"]
+ assert len(rendered) == 1 # the prose rendered
+ res = out[-1]
+ assert res["is_error"] is True
+ assert "AuthenticationError" in res["result"]
+
+
+def test_aiders_advice_about_its_own_chat_commands_is_cut_from_the_reason():
+ """show_exhausted_error ends with `- Use /tokens …`, `- Use /drop …`, `- Use /clear …`: in-chat
+ commands this product never shows. Same rule kimi's resume hint earned."""
+ state: dict = {"_aider_init": True}
+ text = ("Model openai/gpt-5.4 has hit a token limit!\n\nInput tokens: ~300,000 of 272,000 "
+ "-- possibly exhausted context window!\n\nTo reduce input tokens:\n"
+ "- Use /tokens to see token usage.\n- Use /drop to remove unneeded files from the chat "
+ "session.\n- Use /clear to clear the chat history.\n- Break your code into smaller source files.\n")
+ _aider_to_claude({"m": "error", "p": {"text": text}}, state)
+ reason = state["_aider_error"]
+ assert "Use /" not in reason
+ assert "hit a token limit" in reason and "Break your code into smaller source files." in reason
+ ev = _aider_to_claude({"m": "result", "p": {"ok": False, "final": ""}}, state)[0]
+ assert ev["is_error"] and "Use /" not in ev["result"]
+
+
+def test_prose_that_merely_mentions_an_error_still_succeeds():
+ """The case an anchored stdout regex cannot get right, and the driver gets right for free."""
+ out, _ = _norm([
+ {"m": "text", "p": {"text": "litellm.AuthenticationError: is raised when the key is bad."}},
+ {"m": "result", "p": {"ok": True, "final": "litellm.AuthenticationError: is raised when the key is bad."}},
+ ])
+ assert out[-1]["is_error"] is False
+ assert out[-1]["subtype"] == "success"
+
+
+def test_an_approved_command_renders_as_a_call_and_its_real_result():
+ out, _ = _norm([
+ {"m": "shell_decision", "p": {"command": "python3 stamp.py", "tool": "Shell",
+ "approved": True, "reason": ""}},
+ {"m": "shell_result", "p": {"tool": "Shell", "command": "python3 stamp.py",
+ "output": "STAMP-OK"}},
+ ])
+ call = out[0]["message"]["content"][0]
+ res = out[1]["message"]["content"][0]
+ assert call["type"] == "tool_use" and call["name"] == "Shell"
+ assert call["input"] == {"command": "python3 stamp.py"}
+ assert res["type"] == "tool_result" and res["tool_use_id"] == call["id"]
+ assert res["is_error"] is False and res["content"] == "STAMP-OK"
+
+
+def test_a_refused_command_is_a_complete_pair_with_the_policy_as_its_result():
+ """Nothing ran, so the policy IS the result — and the reader sees the refusal rather than a
+ call that silently never finished."""
+ out, _ = _norm([{"m": "shell_decision", "p": {"command": "rm -rf /", "tool": "Shell",
+ "approved": False,
+ "reason": "the harness disabled shell commands"}}])
+ assert len(out) == 2
+ res = out[1]["message"]["content"][0]
+ assert res["is_error"] is True and "disabled shell commands" in res["content"]
+
+
+def test_usage_is_empty_rather_than_aiders_own_numbers():
+ """aider fills the real field names with a tiktoken ESTIMATE when streaming (587 against a true
+ 595, measured) and reads cache under names an OpenAI response never carries. Per the 2026-09-13
+ decision the relay supplies these, and no harness PR builds its own usage pipeline."""
+ out, _ = _norm([{"m": "result", "p": {"ok": True, "final": "done"}}])
+ assert out[0]["usage"] == {}
+
+
+def test_eof_only_speaks_when_the_driver_never_reached_its_result():
+ assert _aider_eof({"final": "x"}, 0)[0]["subtype"] == "success"
+ assert _aider_eof({"_aider_error": "boom"}, 1)[0]["result"] == "boom"
+
+
+def test_backend_is_registered_with_its_eof():
+ assert BACKENDS["aider"]["normalize"] is _aider_to_claude
+ assert getattr(BACKENDS["aider"]["normalize"], "eof", None) is _aider_eof
+
+
+# ── argv, environment and the bridge ─────────────────────────────────────────────
+def _build(**kw):
+ d = tempfile.mkdtemp()
+ env: dict = {}
+ cmd = _build_aider("openai-api", Auth(api_key="sk-t", base_url="https://up.example/v1"),
+ "gemini-2.5-pro", "do it", d, env, **kw)
+ return cmd, d, env, json.loads(cmd[-1])
+
+
+def test_the_model_id_is_prefixed_so_aiders_alias_table_cannot_rewrite_it():
+ """MODEL_ALIASES rewrites 21 BARE ids, `gemini-2.5-pro` among them — an id this catalog also
+ serves. The openai/ prefix routes through litellm verbatim and skips that table, which is the
+ same class of silent substitution that pruned the gemini catalog."""
+ _, _, _, job = _build()
+ assert job["model"] == "openai/gemini-2.5-pro"
+
+
+def test_the_real_key_never_reaches_aider():
+ _, _, env, _ = _build()
+ assert env["OPENAI_API_KEY"].startswith("hr-relay-")
+ assert env["OPENAI_API_BASE"] != "https://up.example/v1"
+
+
+def test_the_bridge_actually_reaches_the_model_and_is_runnable():
+ """The defect this pins: the block was generated by a function nobody called, so the bridge
+ existed and the model was never told it did — MCP was dead code that unit-testing the generator
+ in isolation could not see. Assert the whole chain instead: config written, shim on PATH and
+ executable, and the instructions appended to the doc the driver puts into the system message."""
+ d = tempfile.mkdtemp()
+ doc = pathlib.Path(d, "AGENTS.md")
+ doc.write_text("# harness contract\n")
+ env: dict = {}
+ _build_aider("openai-api", Auth(api_key="sk-t", base_url="https://up.example/v1"),
+ "gpt-5.4", "do it", d, env,
+ mcp_servers=[{"name": "deepwiki", "url": "https://mcp.deepwiki.com/mcp"}])
+ cfg = json.loads(pathlib.Path(d, ".harness", "aider-mcp.json").read_text())
+ assert cfg == {"mcpServers": {"deepwiki": {"url": "https://mcp.deepwiki.com/mcp"}}, "disabledTools": []}
+ shim = pathlib.Path(d, ".harness", "bin", "hr-mcp")
+ assert shim.is_file() and shim.stat().st_mode & 0o111 # executable
+ assert str(shim.parent) in env["PATH"].split(":")
+ text = doc.read_text()
+ assert "# harness contract" in text # appended, not overwritten
+ assert "hr-mcp call" in text and "deepwiki" in text
+ assert "```bash" in text # the only surface aider can propose a tool through
+
+
+def test_no_bridge_is_advertised_when_no_server_is_declared():
+ d = tempfile.mkdtemp()
+ doc = pathlib.Path(d, "AGENTS.md"); doc.write_text("# harness contract\n")
+ _build_aider("openai-api", Auth(api_key="sk-t", base_url="https://up.example/v1"),
+ "gpt-5.4", "do it", d, {}, mcp_servers=[])
+ text = doc.read_text()
+ assert text.startswith("# harness contract\n")
+ assert "hr-mcp" not in text and "## MCP servers" not in text
+ assert _aider_mcp_block({}) == ""
+
+
+def test_the_doc_tells_the_model_how_this_workspace_works_and_names_the_skills_by_relative_path():
+ """aider's own prompt says the USER adds files and may run the suggested commands; here the
+ driver does both, and a model that was not told behaved as aider's prompt says (guessed a
+ skill's token, declared itself unable to run a tool, invented a result). The block names each
+ SKILL.md as a `cat` the model can run on any turn; aider's own file-mention route adds only
+ files git already tracks, which a first turn's skill files are not."""
+ d = tempfile.mkdtemp()
+ sk = pathlib.Path(d, ".harness", "skills", "plugin-probe"); sk.mkdir(parents=True)
+ sk.joinpath("SKILL.md").write_text("---\nname: plugin-probe\n---\n")
+ doc = pathlib.Path(d, "AGENTS.md"); doc.write_text("# harness contract\n")
+ _build_aider("openai-api", Auth(api_key="sk-t", base_url="https://up.example/v1"),
+ "gpt-5.4", "do it", d, {}, mcp_servers=[])
+ text = doc.read_text()
+ assert "## How this workspace works for you" in text
+ assert "- `cat .harness/skills/plugin-probe/SKILL.md`" in text
+ assert "```bash" in text and "Report only output you were actually given" in text
+ # written fresh each turn on top of the doc the turn wrote: no growth across turns
+ doc.write_text("# harness contract\n")
+ _build_aider("openai-api", Auth(api_key="sk-t", base_url="https://up.example/v1"),
+ "gpt-5.4", "do it", d, {}, mcp_servers=[])
+ assert doc.read_text().count("## How this workspace works for you") == 1
+
+
+def test_edit_blocks_are_stripped_from_the_answer_and_the_edits_render_as_cards():
+ """The SEARCH/REPLACE markup is aider's wire format for an edit; the console showed it raw as
+ the reply ("hello.py ```python <<<<<<< SEARCH ======= print(...) >>>>>>> REPLACE ```",
+ hr-test 2026-09-18). The prose is the answer; each edited file is a card, as on every base."""
+ text = ("I will create the file.\n\nhello.py\n```python\n<<<<<<< SEARCH\n=======\n"
+ "print(\"aider\")\n>>>>>>> REPLACE\n```\n\nDONE-FILE")
+ assert aider_driver.strip_edit_blocks(text) == "I will create the file.\n\n\nDONE-FILE"
+ shell = "Run this:\n```bash\ncat SKILL.md\n```"
+ assert aider_driver.strip_edit_blocks(shell) == "Run this:" # the command renders as a card
+ # a fence the model closed and kept writing on ("```An improved…") closes the block for aider
+ # (editblock_coder.py:478) and the sentence is prose
+ assert aider_driver.strip_edit_blocks("```bash\nofficecli view a.pptx\n```An improved style.\nDone.") == "An improved style.\nDone."
+ state: dict = {"_aider_init": True}
+ evs = _aider_to_claude({"m": "edits", "p": {"files": ["hello.py", "b.txt"]}}, state)
+ calls = [c for e in evs for c in e["message"]["content"] if c["type"] == "tool_use"]
+ results = [c for e in evs for c in e["message"]["content"] if c["type"] == "tool_result"]
+ assert [c["name"] for c in calls] == ["Edit", "Edit"]
+ assert [c["input"]["file_path"] for c in calls] == ["hello.py", "b.txt"]
+ assert [r["tool_use_id"] for r in results] == [c["id"] for c in calls]
+ # the result event's text is what the gateway stores as the answer: stripped there too, or
+ # the markup comes back through the other door (measured: the text event was clean and the
+ # stored answer still carried the block)
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert '"final": strip_edit_blocks(coder.partial_response_content or "")' in src
+
+
+def test_agent_doc_is_written_as_agents_md_even_though_aider_reads_it_via_read():
+ assert _agent_doc_path("/ws", "aider").name == "AGENTS.md"
+
+
+# ── a lost conversation must not answer from an empty history ────────────────────
+def test_resume_lost_reads_the_history_file_because_there_is_no_session_id():
+ """aider has no session id at all, and a missing history file resumes silently with no output
+ difference whatsoever. The store question is "does the history hold a message?"."""
+ d = tempfile.mkdtemp()
+ assert _resume_lost("aider", ["aider"], "s1", d) == "s1"
+ hist = pathlib.Path(d, ".harness", "aider", "chat.history.md")
+ hist.parent.mkdir(parents=True)
+ hist.write_text("# aider chat started at 2026-09-13\n\n") # a file, but no exchange
+ assert _resume_lost("aider", ["aider"], "s1", d) == "s1"
+ hist.write_text("# aider chat started\n\n#### do the thing\n\nok\n")
+ assert _resume_lost("aider", ["aider"], "s1", d) is None
+
+
+# ── the in-turn loop the maintainer asked to be measured ─────────────────────────
+class _FakeCoder:
+ """Enough Coder to exercise the shell-reporting wrapper without aider installed."""
+ def __init__(self, output="STAMP-OK"):
+ self.shell_commands = ["python3 stamp.py"]
+ self.reflected_message = None
+ self.runs = 0
+ self._output = output
+
+ def run_shell_commands(self):
+ self.runs += 1
+ return "\n".join(f"Output from {c}\n{self._output}" for c in self.shell_commands)
+
+
+def test_shell_output_is_fed_back_so_the_model_sees_it_in_the_same_turn():
+ """aider stashes shell output for the NEXT user message and sets no reflection of its own
+ (base_coder.py:1609-1614), unlike its lint and test paths. Without this the model can never
+ report what its command printed, and every other backend here can. Measured against a stub with
+ the reflection on: two provider round trips and the answer carries the script's output; with it
+ off, one round trip and the answer is the ```bash block itself."""
+ c = _FakeCoder()
+ g = aider_driver._Gate([])
+ g.calls.append({"command": "python3 stamp.py", "tool": "Shell", "approved": True, "reason": ""})
+ aider_driver._run_shell_commands_reporting(c, g, reflect=True)
+ c.run_shell_commands()
+ assert c.reflected_message and "STAMP-OK" in c.reflected_message
+
+
+def test_a_reflection_does_not_re_run_the_command_it_reported():
+ """The bug this wrapper introduced and this test pins: init_before_message() empties
+ shell_commands once per TURN, not per reflection, so with a reflection set the next pass
+ re-ran every command already executed. Measured before the fix: one proposed command ran four
+ times and the turn made four round trips instead of two, side effects repeated each time."""
+ c = _FakeCoder()
+ g = aider_driver._Gate([])
+ aider_driver._run_shell_commands_reporting(c, g, reflect=True)
+ c.run_shell_commands()
+ assert c.shell_commands == [] # cleared, so a reflection cannot replay it
+ c.reflected_message = None # _run_turn clears this at the top of every pass
+ c.run_shell_commands() # the reflection's pass
+ # nothing left to run, so no output, so no second reflection: the loop ends after one.
+ assert c.runs == 2 and c.reflected_message is None
+
+
+def test_reflection_can_be_turned_off_and_then_aider_behaves_as_shipped():
+ c = _FakeCoder()
+ g = aider_driver._Gate([])
+ aider_driver._run_shell_commands_reporting(c, g, reflect=False)
+ c.run_shell_commands()
+ assert c.reflected_message is None
+
+
+# ── the MCP bridge itself ────────────────────────────────────────────────────────
+# These run without the `mcp` SDK installed: the SDK is imported inside _run, and everything below
+# is argument handling and the shapes the bridge puts in front of the agent. The live half — list,
+# call, a failing call and an unknown server, against public servers — was measured separately and
+# is recorded in docs/support-matrix-notes.md.
+import aider_mcp_bridge # noqa: E402
+
+
+def test_an_unknown_server_names_the_ones_that_exist():
+ """The agent reads stderr. "no such server" without the list is a dead end for it."""
+ cfg = pathlib.Path(tempfile.mkdtemp(), "m.json")
+ cfg.write_text(json.dumps({"mcpServers": {"deepwiki": {"url": "https://x/mcp"}}}))
+ servers = aider_mcp_bridge._load(str(cfg))
+ try:
+ aider_mcp_bridge._target(servers, "nope")
+ except SystemExit as e:
+ assert e.code == 2
+ else:
+ raise AssertionError("an unknown server must not be silently accepted")
+
+
+def test_a_url_server_resolves_to_its_url():
+ """No transport and no headers: the plain string, which the SDK dials as streamable HTTP."""
+ servers = {"deepwiki": {"url": "https://mcp.deepwiki.com/mcp"}}
+ assert aider_mcp_bridge._target(servers, "deepwiki") == "https://mcp.deepwiki.com/mcp"
+
+
+def _stub_mcp_sdk(monkeypatch):
+ """The bridge runs under the aider venv's SDK (mcp 2.x with httpx2), not the runner's (1.x, no
+ httpx2): the transports it builds do not import here. Stub the three modules by name so the
+ test checks the bridge's choice of transport, which is what the declaration bug was about."""
+ sse = types.ModuleType("mcp.client.sse")
+ sse.sse_client = lambda url, headers=None: ("sse", url, headers)
+ sh = types.ModuleType("mcp.client.streamable_http")
+ sh.streamable_http_client = lambda url, http_client=None: ("http", url, http_client)
+ hx = types.ModuleType("httpx2")
+ hx.AsyncClient = lambda headers=None: ("client", headers)
+ client = types.ModuleType("mcp.client")
+ pkg = types.ModuleType("mcp")
+ pkg.client = client
+ for name, mod in (("mcp", pkg), ("mcp.client", client), ("mcp.client.sse", sse),
+ ("mcp.client.streamable_http", sh), ("httpx2", hx)):
+ monkeypatch.setitem(sys.modules, name, mod)
+
+
+def test_the_declared_transport_decides_and_not_the_urls_spelling(monkeypatch):
+ _stub_mcp_sdk(monkeypatch)
+ """MEASURED DEFECT this pins: `Client.__init__` sends a plain URL string to
+ `streamable_http_client` unconditionally (mcp 2.2.0, client.py:393-394) — there is no inference
+ and no SSE path — so a harness that declared `transport: sse` had its server dialled with the
+ wrong protocol. Same rule the maintainer set for kimi: the declaration decides, never the url.
+ A string result here would be that defect returning."""
+ sse = aider_mcp_bridge._target(
+ {"events": {"url": "https://example.test/events", "transport": "sse"}}, "events")
+ assert sse == ("sse", "https://example.test/events", None)
+
+
+def test_declared_headers_reach_the_server_rather_than_the_config_file(monkeypatch):
+ """They were written into the config and never read: the streamable path takes headers on an
+ httpx client, not on the call, so a plain URL string dropped every one of them."""
+ _stub_mcp_sdk(monkeypatch)
+ with_hdrs = aider_mcp_bridge._target(
+ {"api": {"url": "https://example.test/mcp", "headers": {"X-K": "v"}}}, "api")
+ assert with_hdrs == ("http", "https://example.test/mcp", ("client", {"X-K": "v"}))
+
+
+def test_structured_content_wins_over_prose():
+ """A tool that returns data should not be flattened into text for the agent to re-parse.
+
+ NOTE the field name: the 2.2.0 SDK is snake_case (structured_content / is_error /
+ input_schema), not the camelCase of older releases. The camelCase guess raised inside a
+ TaskGroup and surfaced as an unreadable "unhandled errors in a TaskGroup" — measured."""
+ class R:
+ structured_content = {"answer": 42}
+ content = []
+ assert json.loads(aider_mcp_bridge._render(R())) == {"answer": 42}
+
+
+def test_text_blocks_are_joined_when_there_is_no_structured_content():
+ class Block:
+ def __init__(self, t): self.text = t
+ class R:
+ structured_content = None
+ content = [Block("one"), Block("two")]
+ assert aider_mcp_bridge._render(R()) == "one\ntwo"
+
+
+def test_bad_params_json_is_rejected_before_any_connection():
+ rc = aider_mcp_bridge.main(["--config", "/nonexistent", "call", "s", "t",
+ "--params", "{not json"])
+ assert rc == 2
+
+
+# ── conversation continuity: the bug the support matrix found ────────────────────
+def test_the_turn_announces_a_session_id_even_though_aider_has_none():
+ """MEASURED FAILURE this pins: aider has no conversation id of any kind, so the gateway never
+ recorded one, never treated a later turn as a follow-up, and every turn was a fresh thread. The
+ support matrix's recycle scenario failed on every aider row while first/follow-up/switch
+ passed — those three only check that a turn answers, never that it remembers."""
+ state: dict = {}
+ out = _aider_to_claude({"m": "text", "p": {"text": "hi"}}, state)
+ assert out[0]["type"] == "system" and out[0]["subtype"] == "init"
+ assert out[0]["session_id"] == _AIDER_SESSION_NAME
+ # once per turn, not once per event
+ again = _aider_to_claude({"m": "text", "p": {"text": "more"}}, state)
+ assert not [e for e in again if e.get("subtype") == "init"]
+
+
+def test_the_chat_history_is_restored_on_every_turn():
+ """aider's only continuation mechanism. It travels in the checkpoint under .harness/, which is
+ what lets a follow-up after a sandbox recycle still know what was said; on a first turn the file
+ does not exist and aider starts fresh."""
+ import json as _json
+ _, _, _, job = _build()
+ # the driver owns the argv; assert the flag it builds
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert '"--restore-chat-history"' in src
+ assert '"--chat-history-file", str(hist / "chat.history.md")' in src
+
+
+# ── the Plugins sub-protocol (UHP 2026-09-12) ────────────────────────────────────
+def test_a_plugins_stdio_server_reaches_the_bridge_as_command_and_args():
+ """_plugin_launchers bakes env, cwd and the ${PLUGIN_ROOT}/${PLUGIN_DATA} placeholders into one
+ launcher script, so every writer sees the same {name, command, args}. aider has no MCP client of
+ its own, so "the writer" here is the bridge's server table plus the shim the turn builds."""
+ d = tempfile.mkdtemp()
+ pathlib.Path(d, "AGENTS.md").write_text("# contract\n")
+ env: dict = {}
+ _build_aider("openai-api", Auth(api_key="sk-t", base_url="https://up.example/v1"),
+ "gpt-5.4", "do it", d, env, mcp_servers=[
+ {"name": "probe", "command": "/ws/.harness/plugin-data/demo/.launch-probe.sh",
+ "args": ["--x", "1"]},
+ {"name": "vault", "url": "https://mcp.example.invalid/mcp"}])
+ cfg = json.loads(pathlib.Path(d, ".harness", "aider-mcp.json").read_text())["mcpServers"]
+ assert cfg["probe"] == {"command": "/ws/.harness/plugin-data/demo/.launch-probe.sh",
+ "args": ["--x", "1"]}
+ assert cfg["vault"]["url"].startswith("https://")
+ # both kinds are advertised to the model, and a stdio one is named as such
+ doc = pathlib.Path(d, "AGENTS.md").read_text()
+ assert "`probe` — stdio" in doc and "`vault` — streamable HTTP" in doc
+
+
+def test_the_bridge_resolves_a_stdio_entry_to_stdio_server_parameters():
+ """The half a config file cannot show. Verified live against a real stdio MCP server too: the
+ bridge listed its tool and called it, exit 0.
+
+ Skipped where the SDK is absent: `mcp` lives in AIDER's venv, not the runner's — deliberately,
+ because installing it beside the runner bumps starlette past what FastAPI 0.115.6 accepts."""
+ import pytest
+ pytest.importorskip("mcp", reason="the MCP SDK lives in aider's own venv")
+ servers = {"probe": {"command": "/bin/echo", "args": ["a", "b"], "env": {"K": "V"}}}
+ target = aider_mcp_bridge._target(servers, "probe")
+ assert target.command == "/bin/echo"
+ assert target.args == ["a", "b"]
+ assert target.env == {"K": "V"}
+
+
+# The companion test that asserted membership of _STDIO_MCP_BACKENDS is gone with the set itself:
+# upstream (#185) stopped declaring any transport missing, because the runner now hands every client
+# one launcher shape and bridges SSE and streamable HTTP over stdio for the ones that cannot speak
+# them. Nothing about aider changed — the bridge already resolved a stdio entry — so what is left to
+# pin is the two tests above: the servers the turn writes, and the shape the bridge resolves them to.
+
+
+def test_the_driver_bounds_every_api_call():
+ """MEASURED FAILURE this pins: aider's --timeout defaults to None, so a provider that accepts
+ the connection and never finishes the stream leaves the call waiting forever. aider's own retry
+ loop cannot save it — that only fires on an exception, and is itself bounded at ~63s. In the
+ vercel column single scenarios ran 3,621s, 6,040s, 16,071s and 27,360s against 7-30s healthy,
+ and only the runner's 6-hour cap ended them."""
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert '"--timeout", os.environ.get("HR_AIDER_TIMEOUT", "300")' in src
+
+
+def test_the_operators_step_budget_reaches_the_driver():
+ """aider has no CLI flag for it — its loop is Coder.max_reflections, a class attribute — so the
+ budget travels in the job and the driver sets it on the object. Pinned here because the dispatch
+ passes it and a builder that did not accept it would TypeError on the first aider turn, which no
+ unit test exercises."""
+ _, _, _, job = _build(max_turns=7)
+ assert job["max_turns"] == 7
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert "coder.max_reflections = max(1, int(budget))" in src
+ # The dispatch is the link that was missing: the builder accepted the budget and turn() never
+ # handed it over, so every aider turn ran on aider's own default no matter what the harness
+ # said. Read off the source, since turn() needs a live workspace and a provider to run.
+ server_src = pathlib.Path(__file__).resolve().parents[1].joinpath("server.py").read_text()
+ dispatch = server_src[server_src.index('elif backend == "aider":'):]
+ dispatch = dispatch[:dispatch.index("elif backend ==", 10)]
+ assert "max_turns=req.max_turns" in dispatch
+
+
+def test_only_the_agent_doc_rides_read_and_skills_are_reached_on_demand():
+ """The PR passed every file of every installed skill bundle through --read on every turn:
+ 27 files and 264 KB for the three built-in bundles on hr-test, 45,030 input tokens for a
+ one-line answer. The agent doc's skills block names the folders; the model reads a skill when
+ a task calls for it, through the shell command the driver feeds back or a file mention aider
+ adds itself."""
+ server_src = pathlib.Path(__file__).resolve().parents[1].joinpath("server.py").read_text()
+ dispatch = server_src[server_src.index('elif backend == "aider":'):]
+ dispatch = dispatch[:dispatch.index("elif backend ==", 10)]
+ assert "rglob" not in dispatch and "skills_read=aider_read" in dispatch
+
+
+def _stub_aider_models(info):
+ """`from aider.models import model_info_manager` without aider installed."""
+ pkg = types.ModuleType("aider")
+ mod = types.ModuleType("aider.models")
+ mod.model_info_manager = types.SimpleNamespace(get_model_info=lambda name: info(name))
+ pkg.models = mod
+ return {"aider": pkg, "aider.models": mod}
+
+
+def test_the_prefixed_id_is_given_back_the_record_the_prefix_hides():
+ """MEASURED FAILURE this pins: litellm falls back from `openai/<id>` to the bare id ONLY when
+ that id's own litellm_provider is openai (models.py:228-231). `openai/gpt-5.6-sol` keeps its
+ 66-key record; every gemini, claude, grok and qwen id resolved to an EMPTY dict, and aider then
+ ran and REPORTED limits of 0 -- `Input tokens: ~45,356 of 0 -- possibly exhausted context
+ window!` about a 1,048,576-token model (google|aider|gemini-3-flash-preview, 2026-09-16).
+ The BARE id is what gets looked up, so aider's alias table is still never consulted."""
+ asked = []
+ stub = _stub_aider_models(lambda n: (asked.append(n), {"max_input_tokens": 1048576})[1])
+ with tempfile.TemporaryDirectory() as d:
+ pathlib.Path(d, ".harness", "aider").mkdir(parents=True)
+ saved = {k: sys.modules.get(k) for k in stub}
+ sys.modules.update(stub)
+ try:
+ out = aider_driver._write_model_metadata(d, "openai/gemini-3-flash-preview")
+ finally:
+ for k, v in saved.items():
+ sys.modules.pop(k, None) if v is None else sys.modules.__setitem__(k, v)
+ assert asked == ["gemini-3-flash-preview"]
+ written = json.loads(pathlib.Path(out).read_text())
+ # registered under the PREFIXED name: that is the key aider looks the running model up by
+ assert written == {"openai/gemini-3-flash-preview": {"max_input_tokens": 1048576}}
+
+
+def test_an_id_litellm_does_not_know_writes_nothing():
+ """claude-opus-4.8, grok-4.6, qwen3.8-max and kimi-k3 are absent from litellm's database even
+ bare, so there is nothing to hand over and the turn must run exactly as it does today."""
+ stub = _stub_aider_models(lambda n: {})
+ with tempfile.TemporaryDirectory() as d:
+ pathlib.Path(d, ".harness", "aider").mkdir(parents=True)
+ saved = {k: sys.modules.get(k) for k in stub}
+ sys.modules.update(stub)
+ try:
+ assert aider_driver._write_model_metadata(d, "openai/grok-4.6") is None
+ finally:
+ for k, v in saved.items():
+ sys.modules.pop(k, None) if v is None else sys.modules.__setitem__(k, v)
+ assert not pathlib.Path(d, ".harness", "aider", "model-metadata.json").exists()
+
+
+def test_the_record_is_handed_to_aider_on_the_command_line():
+ """A file written and never passed is the defect the MCP block already taught this backend."""
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert 'meta = _write_model_metadata(cwd, job["model"])' in src
+ assert 'argv += ["--model-metadata-file", meta]' in src
+
+
+def test_the_conversation_is_kept_verbatim_rather_than_summarised_at_aiders_cap():
+ """aider keeps at most 8k tokens of history (1k for an id litellm does not know) and
+ summarises the rest with a model call; after four short turns the fifth could not say what
+ the first asked (console matrix, hr-test 2026-09-18). Half the window when known, else a
+ budget that fits the catalog's smallest windows; and the flag reaches the command line."""
+ d = tempfile.mkdtemp()
+ meta = pathlib.Path(d, "meta.json")
+ meta.write_text(json.dumps({"openai/gpt-5.4": {"max_input_tokens": 400000}}))
+ assert aider_driver._history_budget(str(meta)) == 200000
+ meta.write_text(json.dumps({"openai/x": {"max_input_tokens": 8000}}))
+ assert aider_driver._history_budget(str(meta)) == 8192
+ assert aider_driver._history_budget(None) == 96000
+ meta.write_text("not json")
+ assert aider_driver._history_budget(str(meta)) == 96000
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert 'argv += ["--max-chat-history-tokens", str(_history_budget(meta))]' in src
+
+
+def test_the_agent_doc_is_the_system_message_and_the_conversation_holds_only_the_users_turns():
+ """--read sent the doc as a user message ("Here are some READ ONLY files, provided for your
+ reference") ahead of the conversation, and aider's few-shot examples were user/assistant turns
+ ahead of that: asked what the first message of the task said, gpt-5.4 answered "reference"
+ and, before, "Change" (hr-test, 2026-09-18). The doc rides aider's own system_prompt_prefix
+ hook and the examples fold into the system message; nothing of aider's precedes the user."""
+ _, _, _, job = _build(skills_read=["/w/AGENTS.md"])
+ assert job["system_files"] == ["/w/AGENTS.md"] and "read_files" not in job
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert '"--read"' not in src
+ assert "coder.main_model.system_prompt_prefix = (" in src
+ assert "coder.main_model.examples_as_sys_msg = True" in src
+
+
+def test_no_temperature_is_sent_since_a_provider_that_retired_the_field_refuses_the_turn():
+ """claude-fable-5-1 on TokenRouter: "`temperature` is deprecated for this model", turn dead
+ after 171 s of retries (console matrix, hr-test 2026-09-18). aider sends 0 for every id its
+ settings do not know; no other base sets one; aider's own switch leaves it out."""
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert "coder.main_model.use_temperature = False" in src
+
+
+def test_the_harness_own_files_stay_out_of_the_repo_map():
+ """.harness/ holds the skill bundles, aider's state and the MCP shim; summarised into the
+ repo map they rode every request as the user's project. The driver hands aider an ignore
+ file for them, so the map describes the task's files alone."""
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert 'ignore.write_text(".harness/\\nAGENTS.md\\n.gitignore\\n")' in src
+ assert '"--aiderignore", str(ignore),' in src
+
+
+def test_a_binary_file_the_model_names_is_refused_at_aiders_add_prompt():
+ """Asked to restyle hello.pptx (hr-test, 2026-09-19), the model named it, aider added it, the
+ UTF-8 read failed ("Use --encoding…"), the file was dropped and added again on the next
+ mention: an error and a reflection each time, twelve commands, fifteen minutes. A binary
+ file is refused at aider's own "Add file to the chat?" prompt, which puts it on
+ ignore_mentions; text files still go in."""
+ d = tempfile.mkdtemp()
+ pathlib.Path(d, "deck.pptx").write_bytes(b"PK\x03\x04\xf7\x00binary")
+ pathlib.Path(d, "notes.md").write_text("# notes\n")
+ assert aider_driver.is_text_file(os.path.join(d, "deck.pptx")) is False
+ assert aider_driver.is_text_file(os.path.join(d, "notes.md")) is True
+ asked = []
+ io = types.SimpleNamespace(confirm_ask=lambda q, default="y", subject=None, explicit_yes_required=False, group=None, allow_never=False: asked.append(subject) or True,
+ assistant_output=lambda m, p=None: None, tool_error=lambda m="", strip=True: None,
+ tool_warning=lambda m="", strip=True: None)
+ coder = types.SimpleNamespace(io=io, root=d, partial_response_content="", reasoning_tag_name="think",
+ reflected_message=None)
+ gate = aider_driver._Gate([])
+ aider_driver._install(coder, gate)
+ assert io.confirm_ask("Add file to the chat?", subject="deck.pptx") is False
+ assert io.confirm_ask("Add file to the chat?", subject="notes.md") is True
+ assert asked == ["notes.md"] # the binary never reached aider's prompt
+ # nobody is at aider's prompt to say what to do instead, so the turn is told and goes on
+ assert "`deck.pptx` is a binary file" in coder.reflected_message and "```bash" in coder.reflected_message
+
+
+def test_the_turn_fails_only_when_an_error_was_the_last_thing_that_happened():
+ """The restyled .pptx and the edited hello.md were reported FAILED for a decode error twelve
+ commands earlier. An error followed by more of the model's work is a recovered error; an
+ error with nothing after it (a provider refusal) is the failure."""
+ io = types.SimpleNamespace(confirm_ask=lambda *a, **k: True, assistant_output=lambda m, p=None: None,
+ tool_error=lambda m="", strip=True: None, tool_warning=lambda m="", strip=True: None)
+ coder = types.SimpleNamespace(io=io, root="/tmp", partial_response_content="", reasoning_tag_name="think",
+ reflected_message=None)
+ gate = aider_driver._Gate([])
+ aider_driver._install(coder, gate)
+ assert gate.error_after_output is False
+ io.tool_error("x: 'utf-8' codec can't decode"); assert gate.error_after_output is True
+ io.assistant_output("I restyled the deck."); assert gate.error_after_output is False
+ io.tool_error("litellm.AuthenticationError"); assert gate.error_after_output is True
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("aider_driver.py").read_text()
+ assert "failed = coder.usage_report is None or gate.error_after_output" in src
+
+
+def test_each_text_pass_ends_with_a_paragraph_break():
+ """The console joins consecutive text blocks as they come; a closing fence ran straight into
+ the next pass's first sentence and the rest of the turn rendered inside a code block."""
+ state: dict = {"_aider_init": True}
+ ev = _aider_to_claude({"m": "text", "p": {"text": "First pass.\n"}}, state)[0]
+ assert ev["message"]["content"][0]["text"] == "First pass.\n\n"
+
+
+def test_the_models_reasoning_is_not_rendered_as_its_answer():
+ """MEASURED FAILURE this pins (vercel|aider|grok-4.20, 2026-09-18): the transcript showed the
+ model's chain of thought -- "(wait, no, that's not how it works)... So my response should be:"
+ -- because io.assistant_output receives aider's DISPLAY string, which base_coder.py:1882-1890
+ builds by prepending the reasoning and rewriting its tags into `► **THINKING**`/`► **ANSWER**`
+ furniture. The answer is partial_response_content, which is never decorated."""
+ class _IO:
+ def __init__(self):
+ self.seen = []
+ def assistant_output(self, message, pretty=None): self.seen.append(message)
+ def confirm_ask(self, *a, **k): return True
+ def tool_error(self, *a, **k): pass
+ def tool_warning(self, *a, **k): pass
+ class _Coder:
+ def __init__(self):
+ self.io = _IO()
+ self.reasoning_tag_name = "thinking-content-7bbeb8e1441453ad999a0bbba8a46d4b"
+ self.partial_response_content = "M1-grok-4.20"
+ self.shell_commands = []
+ coder = _Coder()
+ emitted = []
+ real_emit = aider_driver._emit
+ aider_driver._emit = lambda m, p: emitted.append((m, p))
+ # the driver asks aider to strip, so aider is where the tag semantics stay; the suite runs
+ # without aider installed, so its helper stands in here
+ import re as _re
+ pkg = types.ModuleType("aider"); mod = types.ModuleType("aider.reasoning_tags")
+ mod.remove_reasoning_content = lambda res, tag: (
+ _re.sub(f"<{tag}>.*?</{tag}>", "", res, flags=_re.DOTALL).strip() if tag else res)
+ pkg.reasoning_tags = mod
+ saved = {k: sys.modules.get(k) for k in ("aider", "aider.reasoning_tags")}
+ sys.modules.update({"aider": pkg, "aider.reasoning_tags": mod})
+ try:
+ aider_driver._install(coder, aider_driver._Gate([]))
+ # what aider would hand it for a reasoning model
+ coder.io.assistant_output(
+ "--------------\n► **THINKING**\n\nwait, no, that is not how it works\n\n"
+ "------------\n► **ANSWER**\n\nM1-grok-4.20")
+ finally:
+ aider_driver._emit = real_emit
+ for k, v in saved.items():
+ sys.modules.pop(k, None) if v is None else sys.modules.__setitem__(k, v)
+ texts = [p["text"] for m, p in emitted if m == "text"]
+ assert texts == ["M1-grok-4.20"], texts
+ assert "THINKING" not in texts[0]
+
diff --git a/runner/tests/test_relay_usage.py b/runner/tests/test_relay_usage.py
new file mode 100644
index 00000000..16d0056d
--- /dev/null
+++ b/runner/tests/test_relay_usage.py
@@ -0,0 +1,129 @@
+"""The relay sees every provider answer, so it can count the tokens for a backend whose CLI
+reports none (kimi, aider): read off the bytes as they pass, summed over the turn's calls, stamped
+on a result event that arrived without usage. Same mechanism as the served model."""
+import json
+import pathlib
+import sys
+import threading
+import urllib.request
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import server as rs # noqa: E402
+
+
+def test_openai_usage_is_netted_to_fresh_input_like_codex_and_cline():
+ u = rs._usage_fields({"prompt_tokens": 6410, "completion_tokens": 20, "total_tokens": 6430,
+ "prompt_tokens_details": {"cached_tokens": 5632}})
+ assert u == {"input_tokens": 778, "output_tokens": 20, "cache_read_tokens": 5632}
+
+
+def test_anthropic_usage_is_already_net_and_keeps_both_cache_counters():
+ u = rs._usage_fields({"input_tokens": 12, "output_tokens": 7, "cache_read_input_tokens": 900,
+ "cache_creation_input_tokens": 300})
+ assert u == {"input_tokens": 12, "output_tokens": 7, "cache_read_tokens": 900,
+ "cache_write_tokens": 300}
+
+
+def test_gemini_usage_metadata_is_read_too():
+ u = rs._usage_in_doc({"usageMetadata": {"promptTokenCount": 100, "candidatesTokenCount": 9,
+ "cachedContentTokenCount": 40}})
+ assert u == {"input_tokens": 60, "output_tokens": 9, "cache_read_tokens": 40}
+ assert rs._usage_fields({"weird": 1}) == {} and rs._usage_fields(None) == {}
+
+
+def test_an_anthropic_stream_is_the_union_of_message_start_and_message_delta():
+ start = b'data: {"type":"message_start","message":{"id":"m","usage":{"input_tokens":25,"output_tokens":1,"cache_read_input_tokens":0}}}'
+ delta = b'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":15}}'
+ call: dict = {}
+ for line in (start, b'event: ping', delta, b'data: [DONE]'):
+ call.update(rs._usage_in_sse_line(line))
+ assert call == {"input_tokens": 25, "output_tokens": 15, "cache_read_tokens": 0}
+
+
+def test_an_openai_stream_reports_usage_only_on_its_last_chunk():
+ lines = [b'data: {"choices":[{"delta":{"content":"hi"}}],"usage":null}',
+ b'data: {"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":2}}',
+ b'data: [DONE]']
+ call: dict = {}
+ for line in lines:
+ call.update(rs._usage_in_sse_line(line))
+ assert call == {"input_tokens": 10, "output_tokens": 2, "cache_read_tokens": 0}
+
+
+def test_a_turn_is_many_calls_and_the_route_sums_them():
+ flags: dict = {}
+ rs._usage_add(flags, {"input_tokens": 10, "output_tokens": 2, "cache_read_tokens": 0})
+ rs._usage_add(flags, {})
+ rs._usage_add(flags, {"input_tokens": 3, "output_tokens": 5, "cache_read_tokens": 10})
+ assert flags["usage"] == {"input_tokens": 13, "output_tokens": 7, "cache_read_tokens": 10}
+ tok = "hr-relay-" + "u" * 32
+ rs._HERMES_RELAY["routes"][tok] = ("https://api.example/v1", "real", flags)
+ try:
+ assert rs._relay_usage({"HOME": "/x", "OPENAI_API_KEY": tok}) == flags["usage"]
+ assert rs._relay_usage({"OPENAI_API_KEY": "sk-direct"}) == {}
+ flags.clear()
+ assert rs._relay_usage({"OPENAI_API_KEY": tok}) == {}
+ finally:
+ rs._HERMES_RELAY["routes"].pop(tok, None)
+
+
+def _upstream(handler):
+ up = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ threading.Thread(target=up.serve_forever, daemon=True).start()
+ return up
+
+
+def test_usage_is_counted_off_a_json_answer_and_a_streamed_one_through_the_live_relay():
+ class Upstream(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"{}")
+ if body.get("stream"):
+ chunks = [b'data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"delta":{"content":"hi"},"finish_reason":null}],"usage":null}\n\n',
+ b'data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"completion_tokens":4,"prompt_tokens_details":{"cached_tokens":30}}}\n\n',
+ b'data: [DONE]\n\n']
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.end_headers()
+ for c in chunks:
+ self.wfile.write(c)
+ self.wfile.flush()
+ return
+ data = json.dumps({"id": "x", "object": "chat.completion", "model": "m",
+ "choices": [{"message": {"role": "assistant", "content": "hi"},
+ "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 100, "completion_tokens": 7,
+ "prompt_tokens_details": {"cached_tokens": 60}}}).encode()
+ self.send_response(200)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ up = _upstream(Upstream)
+ try:
+ base, tok = rs._hermes_relay_route(f"http://127.0.0.1:{up.server_address[1]}/v1", "sk-real")
+ env = {"OPENAI_API_KEY": tok}
+ for stream in (False, True):
+ body = json.dumps({"model": "m", "stream": stream,
+ "messages": [{"role": "user", "content": "hi"}]}).encode()
+ req = urllib.request.Request(base + "/chat/completions", data=body, method="POST",
+ headers={"authorization": f"Bearer {tok}",
+ "content-type": "application/json"})
+ urllib.request.urlopen(req, timeout=10).read()
+ # 100-60 fresh + 40-30 fresh; 7 + 4 out; 60 + 30 cached
+ assert rs._relay_usage(env) == {"input_tokens": 50, "output_tokens": 11, "cache_read_tokens": 90}
+ finally:
+ up.shutdown()
+ rs._HERMES_RELAY["routes"].pop(tok, None)
+
+
+def test_a_backend_that_reports_its_own_usage_keeps_it():
+ """The stamp fills an EMPTY usage only: a CLI's own count (codex, claude, goose) is the
+ record, and the relay's count would double nothing and replace nothing. Pinned on the source
+ of the run loop, which needs a live process to exercise."""
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("server.py").read_text()
+ assert src.count('if ev.get("type") == "result" and not ev.get("usage"):') == 2
diff --git a/scripts/support-matrix/README.md b/scripts/support-matrix/README.md
index 710581fb..77b1ae95 100644
--- a/scripts/support-matrix/README.md
+++ b/scripts/support-matrix/README.md
@@ -32,3 +32,16 @@ to some models, which is how a single failing pair is reproduced with tracing on
Rows that fail must carry the reproduced provider error text; a verified list is never inherited
from another instance, since each reaches providers by its own path. Retest a bare `incomplete`
before excluding a model.
+
+## The plugin matrix
+
+`plugins/run-matrix.py` proves the plugin path on every base, one base at a time: a harness is
+created with ONE Agent Plugins package (`plugins/fixture/`: a manifest, a skill whose token the
+model must repeat, a stdio MCP server that speaks the protocol by hand) and nothing on its
+direct lists, one real task runs per column (skill, stdio MCP, SSE MCP, streamable-HTTP MCP, the
+remote two against a public probe), and the answer is judged on the probe token alone.
+
+ python3 plugins/run-matrix.py --base-url https://your-instance/api/harness --api-key "$KEY" \
+ --bases aider --out plugin-results.json
+
+Kept in the repository since 2026-09-18 after the copy in a scratch folder was emptied mid-review.
diff --git a/scripts/support-matrix/custom-harness.mjs b/scripts/support-matrix/custom-harness.mjs
index 44017efb..92986b2f 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').split(','); // every built-in harness, all twelve
+const BASES = (process.env.BASES || 'codex,claude-code,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi,aider').split(','); // every built-in harness, all thirteen
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, so
diff --git a/scripts/support-matrix/plugins/fixture/bin/probe.py b/scripts/support-matrix/plugins/fixture/bin/probe.py
new file mode 100755
index 00000000..397e8c35
--- /dev/null
+++ b/scripts/support-matrix/plugins/fixture/bin/probe.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""A minimal MCP stdio server with one tool, plugin_probe(note) -> "PLUGIN_MCP_OK".
+
+Speaks the protocol by hand (JSON-RPC 2.0, one message per line) so it depends on nothing
+but python3, whatever SDK version the client brings."""
+import json
+import sys
+
+TOOL = {"name": "plugin_probe", "description": "The support matrix's probe tool. Returns a fixed token.",
+ "inputSchema": {"type": "object", "properties": {"note": {"type": "string"}}}}
+
+
+def reply(msg_id, result):
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg_id, "result": result}) + "\n")
+ sys.stdout.flush()
+
+
+for line in sys.stdin:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ msg = json.loads(line)
+ except ValueError:
+ continue
+ m, i = msg.get("method"), msg.get("id")
+ if m == "initialize":
+ reply(i, {"protocolVersion": msg.get("params", {}).get("protocolVersion", "2025-06-18"),
+ "capabilities": {"tools": {}}, "serverInfo": {"name": "probe", "version": "1.0.0"}})
+ elif m == "tools/list":
+ reply(i, {"tools": [TOOL]})
+ elif m == "tools/call":
+ reply(i, {"content": [{"type": "text", "text": "PLUGIN_MCP_OK"}], "isError": False})
+ elif m == "ping":
+ reply(i, {})
+ elif i is not None:
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": i,
+ "error": {"code": -32601, "message": f"unknown method {m}"}}) + "\n")
+ sys.stdout.flush()
diff --git a/scripts/support-matrix/plugins/fixture/mcp.json b/scripts/support-matrix/plugins/fixture/mcp.json
new file mode 100644
index 00000000..131adf47
--- /dev/null
+++ b/scripts/support-matrix/plugins/fixture/mcp.json
@@ -0,0 +1,6 @@
+{
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
+ "mcpServers": {
+ "probe": {"type": "stdio", "command": "python3", "args": ["${PLUGIN_ROOT}/bin/probe.py"]}
+ }
+}
diff --git a/scripts/support-matrix/plugins/fixture/plugin.json b/scripts/support-matrix/plugins/fixture/plugin.json
new file mode 100644
index 00000000..a49f1713
--- /dev/null
+++ b/scripts/support-matrix/plugins/fixture/plugin.json
@@ -0,0 +1,6 @@
+{
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
+ "name": "plugin-probe",
+ "version": "1.0.0",
+ "description": "A probe package for the support matrix: one skill and one stdio MCP server."
+}
diff --git a/scripts/support-matrix/plugins/fixture/skills/plugin-probe/SKILL.md b/scripts/support-matrix/plugins/fixture/skills/plugin-probe/SKILL.md
new file mode 100644
index 00000000..026ff536
--- /dev/null
+++ b/scripts/support-matrix/plugins/fixture/skills/plugin-probe/SKILL.md
@@ -0,0 +1,10 @@
+---
+name: plugin-probe
+description: A probe skill for the support matrix. Use it when asked to use the plugin-probe skill.
+---
+
+# plugin-probe
+
+When this skill is used, reply with exactly this single line and nothing else:
+
+PLUGIN_SKILL_OK
diff --git a/scripts/support-matrix/plugins/run-matrix.py b/scripts/support-matrix/plugins/run-matrix.py
new file mode 100755
index 00000000..7e343e02
--- /dev/null
+++ b/scripts/support-matrix/plugins/run-matrix.py
@@ -0,0 +1,217 @@
+#!/usr/bin/env python3
+"""Prove the plugin path on every harness base, directly. No workflow, no fan out.
+
+For each base it creates a harness carrying the fixture package, runs one real task, checks the
+answer for the probe token, and deletes the harness. Two modes:
+
+ skills the package carries only its Skill; every base must load it
+ mcp the package also declares a stdio MCP server; every base must call its tool (since
+ #180/#182 every base takes a stdio server; pi's adapter and dsh's client spawn it)
+ sse the package declares an SSE server (a public probe); codex, dsh and goose reach it
+ through the runner's bridge (#185), every other base natively
+ http the package declares a streamable-HTTP server (the same probe's /mcp end)
+
+An Agent Plugins 1.0.0 package is the unit in every column: the harness is created with ONE
+plugin and nothing on its direct mcpServers/skills lists, so what is proved is the plugin path.
+
+ python3 plugins/run-matrix.py --base-url https://20-98-237-6.sslip.io/api/harness --api-key "$KEY" \
+ --mode all --out matrix-results.json
+
+Add --bases codex,hermes to narrow it, --model to pin one, --keep to leave the harnesses behind.
+Runs one base at a time on purpose: hr-test is a single box and a hosted matrix is capped at 8.
+"""
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+import pathlib
+import sys
+import time
+import urllib.error
+import urllib.request
+
+HERE = pathlib.Path(__file__).parent
+FIXTURE = 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"]
+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.
+PROBE_URL = "https://mcp-probe.calmrock-23b12d3f.eastus2.azurecontainerapps.io"
+PROBE_ID = "ef8e44614954"
+SKILL_PROMPT = ("Use your plugin-probe skill and follow it exactly. Reply with the single line it "
+ "tells you to reply with, and nothing else.")
+# A client may expose an MCP tool under the bare name or as <server>_<tool> (pi does the latter),
+# so the prompt names the server too and both spellings; the answer is judged on the token alone.
+MCP_PROMPT = ("Call the MCP tool plugin_probe from the server named probe (it may appear to you as "
+ "plugin_probe or probe_plugin_probe) with note=matrix, then reply with the tool's output "
+ "text verbatim and nothing else. Do not answer from memory or from a skill; the tool "
+ "must actually be called.")
+REMOTE_PROMPT = ("Call the MCP tool {tool} from the server named probe (it may appear to you as {tool} "
+ "or probe_{tool}) with no arguments, then reply with the tool's output text verbatim and "
+ "nothing else. The tool must actually be called.")
+MODES = ["skills", "mcp", "sse", "http"]
+# Per column: the server entry the package's mcp.json carries (None = no server), the tool the task
+# calls, and the token that proves the whole chain answered.
+COLUMN = {
+ "skills": (None, None, "PLUGIN_SKILL_OK"),
+ "mcp": ("stdio", "plugin_probe", "PLUGIN_MCP_OK"),
+ "sse": ({"type": "sse", "url": f"{PROBE_URL}/sse"}, "probe_sse", f"PROBE-SSE-{PROBE_ID}"),
+ "http": ({"type": "streamable-http", "url": f"{PROBE_URL}/mcp"}, "probe_http", f"PROBE-HTTP-{PROBE_ID}"),
+}
+
+
+def package(mode: str) -> list[dict]:
+ server = COLUMN[mode][0]
+ files = []
+ for f in sorted(FIXTURE.rglob("*")):
+ if not f.is_file():
+ continue
+ rel = f.relative_to(FIXTURE).as_posix()
+ if rel == "mcp.json" and server is None:
+ continue
+ if rel.startswith("bin/") and server != "stdio":
+ continue
+ if rel == "mcp.json" and isinstance(server, dict):
+ # the remote columns: the fixture's stdio entry is replaced by a url server, the shape
+ # agent-plugins.org's mcp.schema 1.0.0 allows (type + url, optional headers)
+ files.append({"path": rel, "content": json.dumps({
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
+ "mcpServers": {"probe": server}}, indent=2)})
+ continue
+ raw = f.read_bytes()
+ try:
+ entry = {"path": rel, "content": raw.decode()}
+ except UnicodeDecodeError:
+ entry = {"path": rel, "content_b64": base64.b64encode(raw).decode()}
+ if rel.startswith("bin/"):
+ entry["executable"] = True
+ files.append(entry)
+ return files
+
+
+class Api:
+ def __init__(self, base_url: str, key: str, timeout: float):
+ self.base, self.key, self.timeout = base_url.rstrip("/"), key, timeout
+
+ def call(self, method: str, path: str, body=None, timeout=None):
+ data = json.dumps(body).encode() if body is not None else None
+ req = urllib.request.Request(self.base + path, data=data, method=method, headers={
+ "authorization": f"Bearer {self.key}", "accept": "application/json",
+ **({"content-type": "application/json"} if data else {})})
+ try:
+ with urllib.request.urlopen(req, timeout=timeout or self.timeout) as r:
+ return r.status, json.loads(r.read() or b"{}")
+ except urllib.error.HTTPError as e:
+ raw = e.read()
+ try:
+ return e.code, json.loads(raw or b"{}")
+ except Exception:
+ return e.code, {"raw": raw[:400].decode(errors="replace")}
+
+
+def text_of(resp: dict) -> str:
+ out = []
+ for item in resp.get("output") or []:
+ for c in item.get("content") or []:
+ if c.get("type") == "output_text":
+ out.append(c.get("text") or "")
+ return "\n".join(out)
+
+
+def run_one(api: Api, base: str, mode: str, model: str, keep: bool, task_timeout: float) -> dict:
+ row = {"base": base, "mode": mode, "harness": "", "outcome": "", "detail": ""}
+ body = {"name": f"plugin-matrix-{base}-{mode}", "base": base,
+ "plugins": [{"files": package(mode)}]}
+ if model:
+ body["default_model"] = model
+ status, created = api.call("POST", "/v1/harnesses", body)
+ if status != 200:
+ err = (created.get("error") or {})
+ if mode == "mcp" and base in NO_STDIO and err.get("code") == "unsupported_transport":
+ row["outcome"] = "refused as designed"
+ row["detail"] = f"422 {err.get('code')} detail={err.get('detail')}"
+ else:
+ row["outcome"] = "create failed"
+ row["detail"] = f"HTTP {status} {err.get('code') or created}"
+ return row
+ if mode == "mcp" and base in NO_STDIO:
+ row["outcome"] = "should have been refused"
+ row["detail"] = "the package declares a stdio server and this base cannot run one"
+ api.call("DELETE", f"/v1/harnesses/{created['id']}")
+ return row
+ row["harness"] = created["id"]
+ plug = (created.get("plugins") or [{}])[0]
+ row["detail"] = (f"derived skills={[s['name'] for s in plug.get('skills') or []]} "
+ f"servers={[s['name'] for s in plug.get('mcpServers') or []]} "
+ f"skipped={plug.get('skipped')}")
+ try:
+ _, tool, token = COLUMN[mode]
+ prompt = (SKILL_PROMPT if mode == "skills" else MCP_PROMPT if mode == "mcp"
+ else REMOTE_PROMPT.format(tool=tool))
+ status, resp = api.call("POST", "/v1/responses", {
+ "input": prompt, "metadata": {"harness_id": created["id"]}, "stream": False,
+ "max_step": 12}, timeout=task_timeout)
+ answer = text_of(resp) if status == 200 else ""
+ if status != 200:
+ row["outcome"], row["detail"] = "task failed", f"HTTP {status} {str(resp)[:200]}"
+ elif token in answer:
+ row["outcome"] = "pass"
+ row["detail"] = answer.strip().splitlines()[-1][:200]
+ else:
+ row["outcome"] = "no token"
+ row["detail"] = f"status={resp.get('status')} answer={answer.strip()[:200]!r}"
+ finally:
+ if not keep:
+ api.call("DELETE", f"/v1/harnesses/{created['id']}")
+ return row
+
+
+def main() -> int:
+ p = argparse.ArgumentParser()
+ p.add_argument("--base-url", required=True)
+ p.add_argument("--api-key", required=True)
+ p.add_argument("--bases", default="all")
+ p.add_argument("--mode", default="all", choices=MODES + ["all"])
+ p.add_argument("--model", default="")
+ p.add_argument("--task-timeout", type=float, default=420.0)
+ p.add_argument("--keep", action="store_true")
+ p.add_argument("--out", default="")
+ a = p.parse_args()
+
+ api = Api(a.base_url, a.api_key, 60.0)
+ status, disc = api.call("GET", "/v1/uhp")
+ if status != 200 or not (disc.get("capabilities") or {}).get("plugins"):
+ print(f"this server does not report the plugins capability (HTTP {status}): {disc}", file=sys.stderr)
+ return 2
+ print(f"server serves {disc.get('default_version')} · plugins {disc['capabilities']['plugins']} · "
+ f"schemas {disc.get('plugin_schemas')}\n")
+
+ bases = BASES if a.bases == "all" else [b.strip() for b in a.bases.split(",") if b.strip()]
+ modes = MODES if a.mode == "all" else [a.mode]
+ rows = []
+ for mode in modes:
+ for base in bases:
+ t0 = time.time()
+ row = run_one(api, base, mode, a.model, a.keep, a.task_timeout)
+ row["seconds"] = round(time.time() - t0, 1)
+ rows.append(row)
+ print(f"{mode:<7} {base:<12} {row['outcome']:<24} {row['seconds']:>6}s {row['detail'][:120]}")
+ print("\nsummary")
+ for mode in modes:
+ good = [r for r in rows if r["mode"] == mode and r["outcome"] in ("pass", "refused as designed")]
+ print(f" {mode}: {len(good)}/{len([r for r in rows if r['mode'] == mode])} as expected")
+ bad = [f"{r['mode']}/{r['base']}: {r['outcome']}" for r in rows
+ if r["outcome"] not in ("pass", "refused as designed")]
+ if bad:
+ print(" not as expected: " + "; ".join(bad))
+ if a.out:
+ pathlib.Path(a.out).write_text(json.dumps({"target": a.base_url, "rows": rows}, indent=2))
+ print(f"\nwrote {a.out}")
+ return 1 if bad else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ui/public/logos/aider.png b/ui/public/logos/aider.png
new file mode 100644
index 00000000..66f4a725
Binary files /dev/null and b/ui/public/logos/aider.png differ
diff --git a/ui/src/components/HarnessLogo.tsx b/ui/src/components/HarnessLogo.tsx
index abbfa57d..b0364087 100644
--- a/ui/src/components/HarnessLogo.tsx
+++ b/ui/src/components/HarnessLogo.tsx
@@ -17,6 +17,7 @@ const LOGO: Record<string, string> = {
omp: '/logos/omp.png',
goose: '/logos/goose.png', // the flying goose from goose-docs.ai (logo_light.png, cropped to the mark)
kimi: '/logos/kimi.png', // the official Kimi mark (the K app icon from kimi.ai/code), supplied by Richard 2026-09-17
+ aider: '/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)
};
export function HarnessLogo({ id, size = 26 }: { id: string; size?: number }) {
diff --git a/ui/src/components/HarnessSettings.tsx b/ui/src/components/HarnessSettings.tsx
index f0cc90c3..9a12269b 100644
--- a/ui/src/components/HarnessSettings.tsx
+++ b/ui/src/components/HarnessSettings.tsx
@@ -273,7 +273,7 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {
<section className="form-section">
<div><h3>Agent instructions</h3><p>Persistent role, conventions, constraints, and output contract loaded on every Task.</p></div>
<div className="field-stack">
- <div className="field"><label htmlFor="hsInstructions">{['codex', 'hermes', 'omp', 'pi', 'opencode', 'dsh', 'qwen', 'cline', 'goose', 'kimi'].includes(base?.id || draft?.base || '') ? 'AGENTS.md' : 'CLAUDE.md'}</label>
+ <div className="field"><label htmlFor="hsInstructions">{['codex', 'hermes', 'omp', 'pi', 'opencode', 'dsh', 'qwen', 'cline', 'goose', 'kimi', 'aider'].includes(base?.id || draft?.base || '') ? 'AGENTS.md' : 'CLAUDE.md'}</label>
<textarea id="hsInstructions" rows={7} disabled={readOnly}
value={oob ? oob.systemPrompt : (draft?.systemPrompt || '')}
onChange={(e) => upd({ systemPrompt: e.target.value })} />
diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.ts
index 148d2c6e..330fa50b 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" pill
status: 'ready' | 'soon';
- backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | null; // gateway backend; null = coming soon
+ backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | 'aider' | null; // gateway backend; null = coming soon
systemPrompt: 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)
@@ -139,6 +139,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', '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: 'kimi-k3', moreModels: 0,
systemPrompt: 'You are Kimi Code CLI, 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: 'aider', name: 'Aider', version: 'v0.86.2', backend: 'aider', status: 'ready',
+ // Placeholder only: the gateway's catalog wins once fetched. Two columns ran on this backend
+ // (vercel 52 ids, google 11); three of those ids were the Gemini 2.5 family, retired from the
+ // catalog since (#196). _MODEL_CATALOG["aider"] carries what they measured.
+ 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', '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 Aider, an autonomous coding agent. You work on a real git workspace, editing files and proposing shell commands to complete the task end to end.',
+ tools: [], skills: [] },
];
export const oobById = (id: string) => OOB.find((o) => o.id === id) || null;