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.

Five harnesses, four offered, and all seven dimensions measured on them (#448)

ZixiaoLa07b098c4a09
diff --git a/.dockerignore b/.dockerignore
index 15877698..300ecb6e 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -24,3 +24,8 @@ __pycache__/
docs/
*.md
!README.md
+
+# The same environment store, for the same reason: .gitignore keeps it out of a commit, but the
+# build copies the working tree, so a local run's leftovers would be baked in at /app/runner/.
+# Its *.md rule above saves only the two README.md; leak.txt and the two symlinks would travel.
+runner/henv*/
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 2ad393fa..00cd4fdf 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -162,12 +162,18 @@ jobs:
docker rm -f smoke 2>/dev/null || true
docker volume rm smoke-data 2>/dev/null || true
docker run -d --name smoke -v smoke-data:/data -e HR_SECRET_KEY=ci-smoke "$REF"
- for i in $(seq 1 60); do
+ # A fresh volume installs every default base before it prints this line. Five minutes was
+ # enough for twenty bases and no longer is: from the four added in #448 on, amd64 was still
+ # installing when the wait ended, and the gate then blamed the first base it checked
+ # ("claude did not install"), three candidates running. Twelve minutes, and a timeout says
+ # so rather than naming a base.
+ for i in $(seq 1 144); do
docker logs smoke 2>&1 | grep -q "backends available" && break
sleep 5
done
docker logs smoke 2>&1 | tail -30
LINE=$(docker logs smoke 2>&1 | grep "backends available" | tail -1 || true)
+ [ -n "$LINE" ] || { echo "::error::the installs did not finish within 12 minutes on ${{ matrix.arch }}"; exit 1; }
echo "$LINE"
for b in claude codex hermes pi dsh; do
echo "$LINE" | grep -q "$b" || { echo "::error::$b did not install on ${{ matrix.arch }}"; exit 1; }
diff --git a/.gitignore b/.gitignore
index b4818953..ce317929 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,16 @@ protocol/site/dist/
protocol/site/dist/
*.egg-info/
+
+# An environment store a test run left behind. runner/tests/test_environments.py's `store` fixture
+# points ENV_ROOT at a tmp_path, but the git-import test writes its clone target relative to the
+# CWD, so running the suite from inside runner/ leaves `runner/henv<id>/` there — reproduced on an
+# unmodified main. Six of those files were committed by a `git add -A` in this branch's merge, and
+# two of them are symlinks into /tmp/pytest-of-root/... The id is a short [a-z0-9_-] token
+# (environments._ID_SAFE), so the prefix is the stable part.
+runner/henv*/
+
+# The matrix driver's own lockfile. package.json is tracked and the README asks the operator to
+# `npm install` next to run.mjs, so the lock has never been in the tree — and a `git add -A` after
+# installing playwright committed it twice in this branch before this rule existed.
+scripts/support-matrix/package-lock.json
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 18723470..6803229a 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -204,7 +204,15 @@ 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,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,agentzero,systemone,cheetahclaws}"
+# Four of the five added in this batch are in the DEFAULT set rather than opt-in, for the reason
+# agentzero's PR settled: the console lists every base in the catalog, so a base the operator
+# did not opt into is a row that fails on its first turn with no explanation. Disk is the
+# trade — jcode is a ~127 MB static Rust binary and the two Python bases bring their own venvs —
+# and an operator who wants them out sets HR_BACKENDS.
+#
+# gajae is NOT among them, and the gateway offers no gajae base either: its CLI cannot run under
+# this product's write-wall. gateway/app.py carries the measurement, above _MODEL_CATALOG["mimo"].
+export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,agentzero,systemone,cheetahclaws,mimo,jcode,opensquilla,nanobot}"
wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }
# The executable IS the definition of "installed" — an installer that exits 0 without producing
@@ -232,6 +240,11 @@ backend_bin() {
systemone) echo "$TOOLS/systemone-venv/bin/python" ;;
cheetahclaws) echo "$TOOLS/cheetahclaws-venv/bin/cheetahclaws-ready" ;;
agentzero) echo "$TOOLS/agentzero-venv/bin/agentzero-ready" ;;
+ mimo) echo "$TOOLS/bin/mimo" ;;
+ gajae) echo "$TOOLS/bin/gjc" ;;
+ jcode) echo "$TOOLS/bin/jcode" ;;
+ opensquilla) echo "$TOOLS/opensquilla-venv/bin/opensquilla" ;;
+ nanobot) echo "$TOOLS/nanobot-venv/bin/nanobot" ;;
esac
}
@@ -880,6 +893,178 @@ install_omp() {
mkdir -p "$TOOLS/bin" && install -m 755 "$omp_tmp/omp" "$TOOLS/bin/omp"; rm -rf "$omp_tmp"
}
+# ── this batch's five ─────────────────────────────────────────────────────────────────────────
+# Each is pinned EXACTLY to the release its runner code was measured against (the flags, the event
+# schema, the resume mechanism, the tool ids and the config shape were all read out of THAT
+# version), and each download is verified rather than trusted to a tag: three of the five publish
+# checksums upstream, so those are fetched and compared (install_omp's pattern); the two PyPI-ish
+# ones are pinned by version and proven by an import of the symbol the runner actually uses.
+
+# MiMo Code (MIT, XiaomiMiMo/MiMo-Code) ships on npm as @mimo-ai/cli with the binary `mimo`.
+# 0.1.15 is the release _build_mimo was measured against. The npm registry serves an integrity
+# digest with every tarball and npm verifies it, which is why this one is an npm install rather
+# than a release-asset fetch with a digest of our own.
+install_mimo() {
+ npm install -g --prefix "$TOOLS" --no-audit --no-fund "@mimo-ai/cli@${HR_MIMO_VERSION:-0.1.15}" || return 1
+ # MiMo performs a ONE-TIME SQLite migration and fetches an npm tree of ai-sdk packages on its
+ # first run. Measured: the first turn on a fresh home took over nine minutes and printed nothing
+ # before it was killed; the second, warm, answered in about twenty seconds. A turn is not where
+ # that cost belongs, so a throwaway home is warmed here, at install, and then removed.
+ mimo_warm="$(mktemp -d)"
+ mimo_got="$(HOME="$mimo_warm" "$TOOLS/bin/mimo" --version 2>/dev/null | head -n 1)"
+ rm -rf "$mimo_warm"
+ # The warm-up doubles as the proof: an npm install can land a tree with no working entry point.
+ if [ "$mimo_got" != "${HR_MIMO_VERSION:-0.1.15}" ]; then
+ echo "mimo installed but reports '${mimo_got:-nothing}', wanted ${HR_MIMO_VERSION:-0.1.15}"; return 1
+ fi
+}
+
+# Gajae-Code (MIT, Yeachan-Heo/gajae-code) publishes standalone prebuilt binaries per target on
+# GitHub releases WITH a checksum file beside them (gajae-release-binaries.sha256), so the bytes are
+# compared against upstream's own list rather than against a digest we computed. NOT the npm
+# package `gajae-code`: its bin shim is `#!/usr/bin/env bun`, and bun is not in this image.
+# NOT INSTALLED TODAY: `wanted gajae` is false unless an operator names it, and the gateway offers
+# no gajae base, so this runs for nobody. Kept against the day the write-wall decision is revisited
+# — the integration itself works; see the note in gateway/app.py above _MODEL_CATALOG["mimo"].
+install_gajae() {
+ case "$(uname -m)" in
+ x86_64) gj_arch="x64" ;;
+ aarch64|arm64) gj_arch="arm64" ;;
+ *) echo "unsupported architecture $(uname -m) for gajae"; return 1 ;;
+ esac
+ gj_ver="${HR_GAJAE_VERSION:-0.18.5}"; gj_ver="${gj_ver#v}"
+ gj_base="https://github.com/Yeachan-Heo/gajae-code/releases/download/v${gj_ver}"
+ gj_tmp="$(mktemp -d)"
+ curl -fsSL "$gj_base/gjc-linux-$gj_arch" -o "$gj_tmp/gjc" || { rm -rf "$gj_tmp"; return 1; }
+ curl -fsSL "$gj_base/gajae-release-binaries.sha256" -o "$gj_tmp/SHA256SUMS" || { rm -rf "$gj_tmp"; return 1; }
+ gj_want="$(grep " gjc-linux-$gj_arch\$" "$gj_tmp/SHA256SUMS" | awk '{print $1}')"
+ gj_have="$(sha256sum "$gj_tmp/gjc" | awk '{print $1}')"
+ if [ -z "$gj_want" ] || [ "$gj_want" != "$gj_have" ]; then
+ echo "gajae $gj_ver: checksum mismatch for gjc-linux-$gj_arch (want ${gj_want:-none}, have $gj_have)"
+ rm -rf "$gj_tmp"; return 1
+ fi
+ mkdir -p "$TOOLS/bin" && install -m 755 "$gj_tmp/gjc" "$TOOLS/bin/gjc"; rm -rf "$gj_tmp"
+ # The same proof jcode's install owes, for the same reason.
+ gj_got="$("$TOOLS/bin/gjc" --version 2>/dev/null | head -n 1)"
+ if [ "$gj_got" != "gjc/$gj_ver" ]; then
+ echo "gajae installed but reports '${gj_got:-nothing}', wanted gjc/$gj_ver"; rm -f "$TOOLS/bin/gjc"; return 1
+ fi
+}
+
+# jcode (MIT, 1jehuang/jcode) publishes one prebuilt archive per target with a SHA256SUMS file, so
+# it is fetched and compared the same way. v0.90.0 is the release _build_jcode and _jcode_to_claude
+# were measured against — the NDJSON event names, the per-request `tokens` accounting, the resume
+# error text and the tool ids all came out of this build.
+install_jcode() {
+ case "$(uname -m)" in
+ x86_64) jc_arch="x86_64" ;;
+ aarch64|arm64) jc_arch="aarch64" ;;
+ *) echo "unsupported architecture $(uname -m) for jcode"; return 1 ;;
+ esac
+ jc_ver="${HR_JCODE_VERSION:-0.90.0}"; jc_ver="${jc_ver#v}"
+ jc_base="https://github.com/1jehuang/jcode/releases/download/v${jc_ver}"
+ jc_tmp="$(mktemp -d)"
+ curl -fsSL "$jc_base/jcode-linux-$jc_arch.tar.gz" -o "$jc_tmp/jcode.tar.gz" || { rm -rf "$jc_tmp"; return 1; }
+ curl -fsSL "$jc_base/SHA256SUMS" -o "$jc_tmp/SHA256SUMS" || { rm -rf "$jc_tmp"; return 1; }
+ jc_want="$(grep " jcode-linux-$jc_arch.tar.gz\$" "$jc_tmp/SHA256SUMS" | awk '{print $1}')"
+ jc_have="$(sha256sum "$jc_tmp/jcode.tar.gz" | awk '{print $1}')"
+ if [ -z "$jc_want" ] || [ "$jc_want" != "$jc_have" ]; then
+ echo "jcode $jc_ver: checksum mismatch for jcode-linux-$jc_arch.tar.gz (want ${jc_want:-none}, have $jc_have)"
+ rm -rf "$jc_tmp"; return 1
+ fi
+ tar -xzf "$jc_tmp/jcode.tar.gz" -C "$jc_tmp" || { rm -rf "$jc_tmp"; return 1; }
+ # THE LINUX ARCHIVE IS A PAIR, NOT A BINARY: `jcode-linux-<arch>` is a 505-byte sh launcher that
+ # puts its own directory on LD_LIBRARY_PATH and execs `jcode-linux-<arch>.bin` beside it. The
+ # macOS archive is a single binary with no launcher, so a probe on a developer's Mac shows one
+ # layout and the image gets the other — installing "the file called jcode*" picked the launcher,
+ # left its .bin behind, and produced an executable that is on PATH and dies on its first turn.
+ # Both layouts are handled, the pair is kept together in its own directory, and `bin/jcode` is a
+ # symlink (the launcher resolves `readlink -f` itself, which is what makes that safe).
+ jc_dir="$TOOLS/jcode"
+ rm -rf "$jc_dir"; mkdir -p "$jc_dir" "$TOOLS/bin"
+ if [ -f "$jc_tmp/jcode-linux-$jc_arch.bin" ]; then
+ install -m 755 "$jc_tmp/jcode-linux-$jc_arch" "$jc_tmp/jcode-linux-$jc_arch.bin" "$jc_dir/" \
+ || { rm -rf "$jc_tmp" "$jc_dir"; return 1; }
+ ln -sf "$jc_dir/jcode-linux-$jc_arch" "$TOOLS/bin/jcode"
+ elif [ -f "$jc_tmp/jcode-linux-$jc_arch" ]; then
+ install -m 755 "$jc_tmp/jcode-linux-$jc_arch" "$TOOLS/bin/jcode" \
+ || { rm -rf "$jc_tmp" "$jc_dir"; return 1; }
+ else
+ echo "release archive held neither jcode-linux-$jc_arch nor its .bin"; rm -rf "$jc_tmp" "$jc_dir"; return 1
+ fi
+ rm -rf "$jc_tmp"
+ # PROVE IT RUNS, and that it is the version that was pinned. An installer that exits 0 without a
+ # working executable is how a base reaches the console and fails on its first task with nothing to
+ # read — which is exactly what the launcher-without-its-.bin produced.
+ jc_got="$("$TOOLS/bin/jcode" --version 2>/dev/null | awk '{print $2}')"
+ if [ "$jc_got" != "v$jc_ver" ]; then
+ echo "jcode installed but reports '${jc_got:-nothing}', wanted v$jc_ver"; rm -rf "$jc_dir" "$TOOLS/bin/jcode"; return 1
+ fi
+}
+
+# OpenSquilla (Apache-2.0, TokenRhythm/opensquilla). Its own venv, the aider/openhands precedent:
+# it pins a large dependency set and must not share the runner's interpreter.
+#
+# THE WHEEL COMES FROM THE GITHUB RELEASE, NOT FROM PyPI. PyPI's `opensquilla` is stale at 0.3.0
+# while upstream ships 0.5.6, and 0.5.6 is the release the runner's code was measured against — the
+# agent CLI's flags, the v1 progress-event envelope, the transcript shape and the config keys. The
+# release publishes SHA256SUMS beside the wheel, so the bytes are compared against it.
+install_opensquilla() {
+ sq_ver="${HR_OPENSQUILLA_VERSION:-0.5.6}"; sq_ver="${sq_ver#v}"
+ sq_base="https://github.com/TokenRhythm/opensquilla/releases/download/v${sq_ver}"
+ sq_whl="opensquilla-${sq_ver}-py3-none-any.whl"
+ sq_tmp="$(mktemp -d)"
+ curl -fsSL "$sq_base/$sq_whl" -o "$sq_tmp/$sq_whl" || { rm -rf "$sq_tmp"; return 1; }
+ curl -fsSL "$sq_base/SHA256SUMS" -o "$sq_tmp/SHA256SUMS" || { rm -rf "$sq_tmp"; return 1; }
+ sq_want="$(grep " $sq_whl\$" "$sq_tmp/SHA256SUMS" | awk '{print $1}')"
+ sq_have="$(sha256sum "$sq_tmp/$sq_whl" | awk '{print $1}')"
+ if [ -z "$sq_want" ] || [ "$sq_want" != "$sq_have" ]; then
+ echo "opensquilla $sq_ver: checksum mismatch for $sq_whl (want ${sq_want:-none}, have $sq_have)"
+ rm -rf "$sq_tmp"; return 1
+ fi
+ "${HR_OPENSQUILLA_BASE_PYTHON:-python3}" -m venv "$TOOLS/opensquilla-venv" \
+ || { rm -rf "$sq_tmp" "$TOOLS/opensquilla-venv"; return 1; }
+ "$TOOLS/opensquilla-venv/bin/pip" install -q --disable-pip-version-check "$sq_tmp/$sq_whl" \
+ || { rm -rf "$sq_tmp" "$TOOLS/opensquilla-venv"; return 1; }
+ rm -rf "$sq_tmp"
+ # A failed install leaves NO venv behind, and the version is PROVEN rather than assumed: the
+ # wheel's name could be anything, and a base that reports installed and dies on its first turn is
+ # the failure mode every installer here is written to avoid.
+ "$TOOLS/opensquilla-venv/bin/python" -c '
+import sys, importlib.metadata as md
+have = md.version("opensquilla")
+if have != sys.argv[1]:
+ sys.exit("opensquilla %s installed, wanted %s" % (have, sys.argv[1]))
+import opensquilla.cli.main # noqa: F401 - the module `opensquilla agent` boots from
+' "$sq_ver" || { rm -rf "$TOOLS/opensquilla-venv"; return 1; }
+}
+
+# nanobot (MIT, HKUDS/nanobot) from PyPI as nanobot-ai, pinned to the release the driver was written
+# against. Its own venv, for opensquilla's reason.
+install_nanobot() {
+ nb_ver="${HR_NANOBOT_VERSION:-0.3.5}"; nb_ver="${nb_ver#v}"
+ "${HR_NANOBOT_BASE_PYTHON:-python3}" -m venv "$TOOLS/nanobot-venv" \
+ || { rm -rf "$TOOLS/nanobot-venv"; return 1; }
+ "$TOOLS/nanobot-venv/bin/pip" install -q --disable-pip-version-check "nanobot-ai==$nb_ver" \
+ || { rm -rf "$TOOLS/nanobot-venv"; return 1; }
+ # Prove the SDK SURFACE the driver uses, not just that the package imports: the driver depends on
+ # Nanobot.from_config and on seven STREAM_EVENT_* constants, and a release that renamed one of
+ # them would otherwise fail at the first live turn with an ImportError the user would see as a
+ # dead base. The version is asserted beside them.
+ "$TOOLS/nanobot-venv/bin/python" -c '
+import sys, importlib.metadata as md
+have = md.version("nanobot-ai")
+if have != sys.argv[1]:
+ sys.exit("nanobot-ai %s installed, wanted %s" % (have, sys.argv[1]))
+import nanobot
+for name in ("Nanobot", "STREAM_EVENT_TEXT_DELTA", "STREAM_EVENT_REASONING_DELTA",
+ "STREAM_EVENT_TOOL_STARTED", "STREAM_EVENT_TOOL_COMPLETED",
+ "STREAM_EVENT_TOOL_FAILED", "STREAM_EVENT_RUN_COMPLETED", "STREAM_EVENT_RUN_FAILED"):
+ if not hasattr(nanobot, name):
+ sys.exit("nanobot-ai %s does not export %s, which runner/nanobot_driver.py needs" % (have, name))
+' "$nb_ver" || { rm -rf "$TOOLS/nanobot-venv"; return 1; }
+}
+
# Run an install and, if it fails, SAY WHY.
#
# This was `>/dev/null 2>&1 || true`, and the silence cost a day of someone's life: a root-owned
@@ -1077,6 +1262,48 @@ install_backends() {
try_install "Grok Build" install_grok || true
fi
+ # ── this batch's five ───────────────────────────────────────────────────────────────────────
+ # Each is checked by the version its own binary REPORTS, not merely by the executable existing,
+ # so a pin bump in the image reaches a data volume that already carries the previous build. That
+ # is the dsh lesson applied up front: the venv and the binaries outlive the image.
+ MIMO_PIN="${HR_MIMO_VERSION:-0.1.15}"
+ if wanted mimo && [ "$("$(backend_bin mimo)" --version 2>/dev/null | head -n 1)" != "$MIMO_PIN" ]; then
+ echo "[harnessrouter] installing MiMo Code $MIMO_PIN (MIT, version-pinned)…"
+ try_install "MiMo Code" install_mimo || true
+ fi
+
+ GAJAE_PIN="${HR_GAJAE_VERSION:-0.18.5}"
+ # `gjc --version` prints `gjc/<version>`, so the pin is compared against that spelling.
+ if wanted gajae && [ "$("$(backend_bin gajae)" --version 2>/dev/null | head -n 1)" != "gjc/$GAJAE_PIN" ]; then
+ echo "[harnessrouter] installing Gajae-Code $GAJAE_PIN (MIT, version-pinned)…"
+ try_install "Gajae-Code" install_gajae || true
+ fi
+
+ JCODE_PIN="${HR_JCODE_VERSION:-0.90.0}"
+ # `jcode --version` prints `jcode v<version> (<commit>)`; the version field is what is pinned.
+ if wanted jcode && [ "$("$(backend_bin jcode)" --version 2>/dev/null | awk '{print $2}')" != "v$JCODE_PIN" ]; then
+ echo "[harnessrouter] installing jcode $JCODE_PIN (MIT, version-pinned) — ~127 MB…"
+ try_install "jcode" install_jcode || true
+ fi
+
+ OPENSQUILLA_PIN="${HR_OPENSQUILLA_VERSION:-0.5.6}"
+ if wanted opensquilla && [ "$("$TOOLS/opensquilla-venv/bin/python" -c 'import importlib.metadata as m;print(m.version("opensquilla"))' 2>/dev/null)" != "$OPENSQUILLA_PIN" ]; then
+ rm -rf "$TOOLS/opensquilla-venv"
+ echo "[harnessrouter] installing OpenSquilla $OPENSQUILLA_PIN (Apache-2.0, version-pinned)…"
+ try_install "OpenSquilla" install_opensquilla || true
+ fi
+
+ NANOBOT_PIN="${HR_NANOBOT_VERSION:-0.3.5}"
+ if wanted nanobot && [ "$("$TOOLS/nanobot-venv/bin/python" -c 'import importlib.metadata as m;print(m.version("nanobot-ai"))' 2>/dev/null)" != "$NANOBOT_PIN" ]; then
+ rm -rf "$TOOLS/nanobot-venv"
+ echo "[harnessrouter] installing nanobot $NANOBOT_PIN (MIT, version-pinned)…"
+ try_install "nanobot" install_nanobot || true
+ fi
+ [ -x "$TOOLS/nanobot-venv/bin/python" ] && export HR_NANOBOT_PYTHON="$TOOLS/nanobot-venv/bin/python"
+ # Both venv bases are reached by PATH from the runner, so the interpreter and the console script
+ # are named explicitly — $TOOLS/bin is what PATH carries, and neither of these lives there.
+ [ -x "$TOOLS/opensquilla-venv/bin/opensquilla" ] && export HR_OPENSQUILLA_BIN="$TOOLS/opensquilla-venv/bin/opensquilla"
+
# 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
diff --git a/docs/harness-verification.md b/docs/harness-verification.md
index caa214a5..96bd14a1 100644
--- a/docs/harness-verification.md
+++ b/docs/harness-verification.md
@@ -84,7 +84,7 @@ A row passes only if all five hold, each read from what the server stored:
| The tool policy was stored | the disabled tool comes back too |
| The bundle reached the agent | the answer carries a token that exists ONLY inside the script |
| The script actually ran | the file the script writes is among the turn's produced files |
-| The tool policy took effect | no disabled tool appears among the turn's tool calls |
+| The tool policy took effect | no disabled tool appears among the turn's tool calls. The tool it disables is THAT BASE'S OWN, from `custom-harness.mjs`'s `DISABLED_TOOL` table: a tool id matching nothing in a runtime is dropped on the way through and disables nothing, so a single fixed id made this claim vacuously true on eleven of the twenty bases. A base with no tool the task can spare (aider, whose catalog is one Shell) says the policy is not testable there rather than passing |
| The MCP server was stored, and called | it comes back on a read, and a second turn's tool calls name it. A call is named by its tool name, except omp, which dispatches MCP as a `write` to `xd://mcp__<server>_<tool>`: there the call's arguments name it |
The token is generated per run and never appears in `SKILL.md` or the prompt, so an answer carrying
@@ -204,8 +204,11 @@ and need no edit — they were hand-written lists once, and each silently missed
lists with its mark and models.
13. `ui/src/components/HarnessLogo.tsx`: its brand mark, if there is one. A mapping to a file that
does not exist renders a broken image — worse than the generic glyph it falls back to.
-14. `ui/src/components/HarnessSettings.tsx`: the instruction-file label, which must agree with
- `_agent_doc_path` or the settings page names a file the runner does not write.
+14. `ui/src/lib/harness.ts`'s `instructionFileLabel` (which `HarnessSettings.tsx` calls): the
+ instruction-file label, which must agree with `_agent_doc_path` or the settings page names a
+ file the runner does not write. It had drifted — qwen and gemini were labelled `AGENTS.md`
+ while the runner wrote `QWEN.md` and `GEMINI.md` — so it is now one map held to the runner's
+ function by `gateway/tests/test_instruction_file_label.py`.
**Install and measurement:**
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.md
index 5374ab86..d7e71833 100644
--- a/docs/self-hosting-guide.md
+++ b/docs/self-hosting-guide.md
@@ -366,11 +366,11 @@ offers you providers that work.
| `google` | Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Gemini CLI, Cline, Oh My Pi, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero |
| `typesafe` | System One (Jev on TypeSafe's own API: `jev-latest`, `jev-preview`) |
| `bedrock` | Claude Code, Hermes |
-| `tokenrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, CheetahClaws |
-| `harnessrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, CheetahClaws, System One (the open-weight models `laya`, `openthai-systemone` and `system-one-phase2`, served by the hosted service and billed to the key's credits) |
-| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, CheetahClaws |
-| `llmtr` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero |
-| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, CheetahClaws (OpenAI format) |
+| `tokenrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, CheetahClaws, MiMo Code, jcode, OpenSquilla, nanobot |
+| `harnessrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, CheetahClaws, MiMo Code, jcode, OpenSquilla, nanobot, System One (the open-weight models `laya`, `openthai-systemone` and `system-one-phase2`, served by the hosted service and billed to the key's credits) |
+| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, CheetahClaws, MiMo Code, jcode, OpenSquilla, nanobot |
+| `llmtr` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, MiMo Code, jcode, OpenSquilla, nanobot |
+| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Kilo Code, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI, MiniMax Code, Grok Build, Aider, OpenHands, Agent Zero, MiMo Code, jcode, OpenSquilla, nanobot, CheetahClaws (OpenAI format) |
</details>
@@ -952,7 +952,7 @@ 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,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,agentzero,systemone,cheetahclaws ... # the default
+docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,agentzero,systemone,cheetahclaws,mimo,jcode,opensquilla,nanobot ... # the default
docker run -e HR_BACKENDS=opencode ... # lean
```
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index 3c4ba32b..47c17c8c 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -638,6 +638,11 @@ wrong. Two suggestions, both the maintainer's call: let the dimension name the t
(a base that has no `WebSearch` could disable one it has), and make the script write something the
agent cannot predict from reading it.
+**The first of those two was done on 2026-10-03** (see "The disabled tool is the base's own"
+below): `custom-harness.mjs` now carries a per-base `DISABLED_TOOL` table, held to the gateway's
+`_BASE_CATALOG` by a test. The second — a script whose output the agent cannot predict from reading
+it — is still open.
+
**Known open question: `max_context_size`.** kimi requires one per model and plans compaction
against it; the catalog carries no per-id window, so `KIMI_CONTEXT_WINDOW` holds one value for all
ids, exactly as `CODEX_CONTEXT_WINDOW` does for codex. Being wrong changes WHEN the agent compacts,
@@ -754,12 +759,16 @@ 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
+really does refuse; but `custom-harness.mjs` disabled the fixed id `WebSearch`, which matches
+nothing on this harness — so `disabled_tool_unused` passed VACUOUSLY, as it also did for qwen,
+gemini and cline, whose catalogs carry no `WebSearch` either. The enforcement here is real and
+demonstrable; what was missing was a dimension that disables a tool the base under test actually
lists.
+**Fixed 2026-10-03** (see "The disabled tool is the base's own" below). aider is the one base the
+table marks `null`: its catalog is a single tool, Shell, and the stamp task needs it, so the
+dimension says it cannot test the policy there instead of passing.
+
## aider × Google, the first paid column (2026-09-16)
@@ -3162,3 +3171,503 @@ On both candidate starts the log has one line, "Hermes: a tool's own error answe
The patch was run against the real `hermes-agent` 0.19.0 file: it changes two places and the result compiles (the test for this needs the file at hand and is skipped in CI, since Hermes is not in the image).
Not shown live: a server that cannot be reached still opening the breaker. When the tool server was stopped mid-task Hermes dropped its tools ("Unknown tool") before the breaker came into it. That half is covered by the test of the patched check, where an error that did not come from a tool's own answer still counts.
+
+## Five bases added together, four of them offered (2026-10-02/06)
+
+MiMo Code (XiaomiMiMo/MiMo-Code, MIT), Gajae-Code (Yeachan-Heo/gajae-code, MIT), jcode
+(1jehuang/jcode, MIT), OpenSquilla (TokenRhythm/opensquilla, Apache-2.0) and nanobot
+(HKUDS/nanobot, MIT), as the seventeenth to twenty-first bases.
+
+**gajae is implemented and NOT OFFERED**: its CLI cannot run under this product's session
+write-wall, measured both ways on a live instance — see "gajae: the write-wall and a lock that
+walks its ancestors" below. The other four are offered.
+
+**The FULL Vercel column, 2026-10-11**: every catalog id this connection was probed to serve — 50
+of the 54 common to all four catalogs, muse's four excluded and not probed — on all four bases, the
+five scenarios, `EXPECT_CONNECTION=integration:Vercel`. 200 pairs, 1,000 scenarios.
+
+| base | clean pairs | pass | fail | not measured | unlabelled | driver errors |
+|---|---|---|---|---|---|---|
+| mimo | 48/50 | 240 | 2 | 8 | 0 | 0 |
+| jcode | 50/50 | 250 | 0 | 0 | 0 | 0 |
+| opensquilla | 49/50 | 245 | 1 | 4 | 0 | 0 |
+| nanobot | 49/50 | 245 | 1 | 4 | 1 | 0 |
+| | | **980** | **4** | **16** | | |
+
+No foreign connection on any turn, and no substitution survived `samemodel`. The sixteen
+not-measured are the consequence of the four failures: a pair whose FIRST turn fails runs nothing
+after it.
+
+**All four failures are a model declining the scenario's own prompt, and none is a base's.**
+claude-opus-4.7 refused to echo the token on BOTH mimo and opensquilla — "replying with that string
+would misrepresent what model you're talking to", "instructions embedded in request context or
+runtime metadata" — which is one model's judgement reproduced across two bases. qwen3.8-flash
+answered `ack-ef45577c` on mimo, and on nanobot its turn came back "Service temporarily
+unavailable", which is the provider's.
+
+That is worth knowing when reading this table: the scenario prompt is "Reply with exactly:
+M1-<model>", and a model careful about injected instructions can read a real user message as one.
+A refusal costs the pair all five rows, because the first turn gates the rest. The shape of the
+prompt, not the base, is what those rows measure.
+
+**An eight-model column was run first** (one id per family, 2026-10-10, 158 of 160) and is kept in
+the results files. It is superseded by the above for two reasons: it covered 8 ids of 50, and it was
+scored by a judge that read the wrong thing (below).
+
+The earlier columns were taken on three different builds as the fixes below landed; these were
+re-run together on the tree that ships, because arguing per fix about which column it could not have
+touched is weaker evidence than running them again. `unlabelled` 0 everywhere is what makes rule 2
+readable at all — a turn with no served model is a turn the rule cannot judge, and it is reported
+rather than counted as a pass.
+
+**The two rows that failed, and the difference between them.** Both were investigated from the
+session the driver now KEEPS when a pair fails — before that change the session was deleted on the
+way out and a failing row left only the judge's own sentence.
+
+- **jcode / glm-5.3-flash, artifact: the provider's stream, and the file WAS written.** 290 s, then
+ "Upstream stream ended before terminal chunk". The kept session has `hello-jcode.txt` on disk and
+ in the full file listing, so the work happened; the turn was marked failed and its own produced
+ list was empty, so no card was rendered for it. Re-run: 5/5, so the truncation was the provider's
+ and not repeatable. Counted as a pass in the table above only because the re-run passed — the
+ original row and the re-run are both in the results files.
+- **nanobot / kimi-k3, artifact: repeatable, and not the base's write path.** Failed twice in a row
+ with `tools=0` — the model answered DONE having called nothing, and nothing was on disk anywhere
+ in the session. But a FRESH single turn of the same task on the same pair calls `write_file` and
+ produces the file, and so do both controls (nanobot with gpt-5.4, opensquilla with kimi-k3). What
+ differs is position: the artifact scenario is the FOURTH turn, after three "reply with exactly
+ M1-…" exchanges and a switch away to gpt-5.4 and back, and this model carries that pattern on and
+ answers in text. A model behaviour in a context, repeatable in that scenario, with the base's
+ write path demonstrably working for that exact pair. **The row is left at 7/8 rather than retried
+ until it passes.**
+
+Everything below is behaviour measured against the pinned build on a developer machine — flags,
+event schema, failure reporting, resume, usage accounting, tool policy — through a real provider one
+turn at a time. It says each base works; the column above is what says each MODEL it offers does.
+
+### What each one is, and what it shares
+
+| base | pinned | lineage | normaliser | turn process |
+|---|---|---|---|---|
+| mimo | @mimo-ai/cli 0.1.15 | an **opencode fork** (its repo root package.json is still `"name": "opencode"`) | `_opencode_to_claude`, unchanged | `mimo run --format json` |
+| gajae | gjc 0.18.5 | **pi's lineage** (docs/porting-from-pi-mono.md; its deps still carry `pi-ai`) | `_gajae_to_claude`, which delegates to `_pi_to_claude` | `gjc -p --mode json` |
+| jcode | v0.90.0 | its own (Rust) | `_jcode_to_claude`, its own | `jcode … run --ndjson` |
+| opensquilla | 0.5.6 | openclaw/hermes lineage (it migrates `~/.openclaw` and `~/.hermes`; its transcript is the pi message shape) | `_opensquilla_to_claude`, its own | `opensquilla agent --json --event-stream-stderr` |
+| nanobot | nanobot-ai 0.3.5 | its own (a personal-agent runtime, not a coding CLI) | the claude passthrough | `runner/nanobot_driver.py`, in process through its SDK |
+
+### The defects each one's defaults would have caused, and what was done
+
+- **opensquilla routes the model away from you by default.** `[squilla_router] enabled = true` ships
+ on, and the router "scores each turn … then routes it across four tiers to the cheapest capable
+ model". That is matrix rule 2 violated by configuration, not by accident. The builder writes
+ `enabled = false`, and if a `router_decision` event arrives anyway the turn FAILS naming the model
+ it ran instead — the rule pi already enforces for a CLI that substitutes.
+- **opensquilla assumes a generic endpoint holds 8192 tokens.** The first live probe died with
+ `provider_request_too_large` — "The fixed system instructions exceed the provider request budget"
+ — on a three-sentence prompt, because its own system block is ~14k characters and its tool schemas
+ ~29k. The builder declares `context_window` per model.
+- **opensquilla's `--session-db-path` defaults to `:memory:`**, i.e. no continuity between turns at
+ all. It is named explicitly, inside `.harness/`, so the conversation is checkpointed.
+- **jcode replaces itself mid-measurement.** Auto-update is on by default; `--no-update` is passed
+ on every turn. (`--auto-update` takes no value — `--auto-update=false` is a clap usage error.)
+ Its anonymous telemetry is also on by default and prints to stderr: `JCODE_NO_TELEMETRY=1`.
+- **jcode's own `done.usage` is not the turn's usage.** `NdjsonRunState.usage` is ASSIGNED on every
+ `TokenUsage` event rather than accumulated, so it holds the LAST request's numbers: a measured
+ two-request turn reported input 10,748 while its two `tokens` events summed to 21,357. The
+ normaliser accumulates the events and ignores `done.usage`. Its `input` is also GROSS — jcode's
+ own OpenAI client says "input_tokens is the total, including both cache-read and cache-write
+ subsets" — so BOTH caches are netted out, where `_norm_token_usage` nets only the read.
+- **jcode has no remote MCP client at all.** "jcode currently supports stdio (command-based)
+ servers only; HTTP/SSE entries are recognized and skipped with a log line." Without the runner's
+ bridge every remote server a harness declares is dropped in silence, so jcode is in
+ `_BRIDGED_TRANSPORTS` for both transports. opensquilla takes stdio and SSE but not streamable
+ HTTP, so it is bridged for `http`.
+- **jcode's `--model` is its session's INITIAL model, and a resumed turn ignores the one it is
+ given.** Its own help says so ("Interactive sessions can switch providers with /model") and
+ `jcode run` has no model flag of its own, so on `--resume` the model stored with the session wins.
+ Measured on 2026-10-07 with mimo as a flat-layout control in the same run: two turns in one
+ session, haiku then gemini — jcode served `anthropic/claude-haiku-4.5` twice, mimo served each as
+ asked. The family tour served ALL TWELVE of jcode's families with `openai/gpt-5.4` and scored it
+ 12 of 12, and the EIGHT-MODEL column had the same evidence and passed it too: every jcode pair's
+ `served` list held ONE entry where every mimo pair's held two. Both judges now read the served
+ model (`run.mjs` fails a switch row unless the turn naming the partner was served by it;
+ `family-tour.mjs` requires the family's own model), and `_jcode_session_model` points the session
+ store at this turn's model before `--resume` reads it. After: that eight-model column went to 8 of
+ 8 pairs with two served entries each, and the full 50-id column (above) is 50 of 50.
+
+ **What that does not fix, and will not be fixed from here: a turn after a KILLED turn stays on the
+ killed turn's model.** Reproduced deterministically with the same control — A on gpt-5.4 served
+ gpt-5.4, B on haiku killed mid-flight by a 10 s cap, C asked for gemini and was served HAIKU,
+ with the runner's own log line showing it had pointed the store at gemini first. Three places
+ jcode records the model were tried and measured and NONE of them changes it: the session file's
+ top-level `model` (which does fix the normal path, and is what ships), `env_snapshots[].model`
+ (the tour's file carried four consecutive entries naming the cancelled turn's model, which is
+ what made it look like the answer), and the `turns` table of `model-usage-v1.sqlite3`, which the
+ session file's own `model_usage_turn_id` points into. jcode's log has a `model` step inside
+ `restore_session` that assigns it; the binary is stripped, so the mechanism stops being reachable.
+ The alternative — refusing to resume a killed session when the model changed, and saying so with
+ the existing `resume_lost` notice — trades the conversation for the model, and the decision was to
+ keep the conversation and write the limit down here. A turn whose model matters after an
+ interruption should be started as a new session.
+
+- **A jcode turn leaves almost nothing to diagnose with.** Its NDJSON carries `id` and `name` for a
+ tool call and never the INPUT (`tool_done` carries `output`), so the record's tool arguments are
+ `{}` — and a turn that is cancelled loses its served model and its tool list from the record
+ altogether. The 279-tool-call runaway below was readable only from the gateway's event trace.
+
+- **Two of twelve families ran away on jcode and the deck was already correct.** Measured
+ 2026-10-07, grok-4.3 on the tour's "make the code line monospace" edit: 193 `bash` + 86 `todo`
+ calls, 68 tool-result rounds, ten minutes, no final answer. The trace shows it had ALREADY made
+ the change (Courier New present, sizes present, schema valid) and kept re-reading the slide XML,
+ the font list, the sizes and the file's sha256, rewriting one completed todo seventeen times.
+ deepseek, kimi, glm and mistral then also failed to settle inside the cap — the first three
+ families, before any model switch had real effect, finished in 27-33 s. jcode has no step or
+ iteration flag of any kind, so nothing bounds this but the turn's wall clock
+ (`MAX_TURN_SECONDS`, six hours by default); the operator's step budget — the gateway's `max_step`,
+ which reaches the runner as `max_turns` — is forwarded by nine of twenty builders and is a no-op
+ on the other eleven, this one included.
+
+- **nanobot's CLI seeds the workspace and makes a second git repository in it.** `nanobot agent -m`
+ calls `sync_workspace_templates()`, which creates AGENTS.md, SOUL.md, USER.md, HEARTBEAT.md,
+ memory/MEMORY.md, memory/history.jsonl, prompts/README.md and skills/ and then `GitStore.init()`s
+ the workspace — measured, all eight on a bare directory. Its SDK path calls neither (only
+ `.nanobot/workspace-id` appears), which is one of the reasons this base is driven in process.
+- **nanobot refuses a session store that sits inside the agent's workspace**, and that rules out
+ the arrangement every other base here uses. `JsonlSessionStore.__init__` raises "session storage
+ must be outside the agent workspace" when the sessions root is the workspace or under it — a
+ sound rule, since the agent has file tools over its workspace and must not be able to rewrite its
+ own conversation. The conversation still has to ride the checkpoint, which is a tar of the
+ session directory, so the sessions root has to be inside the session and outside the workspace:
+ the only shape that satisfies both is config (and therefore sessions) in `.harness/nanobot/` with
+ the agent's workspace one level down, at `<session>/workspace`. Its AGENTS.md and skills live
+ there too, and the driver chdirs into it, so a shell that writes a relative path cannot land a
+ level above what the model was told it has — Agent Zero's artifact failures were exactly that.
+
+ The nesting STAYS; what changed is that it no longer reaches the user, because a session's file
+ root and the agent's cwd being different directories broke three things. Measured on a live
+ instance with a flat-layout base as the control in the same run:
+ 1. a file written through `PUT /v1/sessions/{sid}/files` landed at the session root and the
+ agent answered "there is no notes.txt in the working directory", while the control read it.
+ That route is how an app owns state the agent also edits (the slides kit's deck.json), and
+ caller attachments land the same way. Both run before a backend is built, so neither can know
+ a base nests: `_adopt_into` moves root-level files into the agent's workspace at the start of
+ every turn, keeping back only what `/produced` already excludes.
+ 2. deliverables came back as `workspace/<name>`, a directory the user never typed.
+ `_produced_visible` strips it where the cards and their download both resolve, and GET /file
+ tries the agent's directory then the session root.
+ 3. the CHECKPOINT readers — share page, full file listing, download-all zip, and the kit route
+ that resolves a file by path — showed 30 files under that prefix, machinery included. The
+ runner writes `.harness/agent-subdir` and `.git/info/exclude` into the checkpoint and the
+ gateway reads them back (`_ws_rules`/`_ws_view`), so one source serves both sides rather than
+ a second exclusion list in the gateway.
+ An earlier version of this file called the prefix unfixable. That was read off the constraint
+ rather than measured, and only the constraint on the session store was real.
+ **Found by running the runner's real argv against the real package**, not by any test: the
+ driver's own fake could not have seen it, which is the whole of why that end-to-end was run.
+- **nanobot's usage is gross too.** A measured two-request turn: `input_tokens` 11,107 with
+ `cache_read_tokens` 5,503, while the requests reported 5,506 and 5,601 — the cached read is a
+ SUBSET. The driver nets it.
+- **gajae auto-enables `/v1/models` discovery on a custom provider.** Against Vercel it listed 376
+ upstream models under our provider name. It is marked optional, so an endpoint without a models
+ list degrades to the static entry, and the builder names the model fully qualified so a fuzzy
+ `--model` cannot land on a discovered id. Its signed model-preset registry — an HTTPS fetch that
+ can rewrite which model a preset names — is turned off.
+- **jcode's Linux release is a PAIR, and its macOS release is not.** `jcode-linux-<arch>.tar.gz`
+ holds a 505-byte `sh` launcher plus `jcode-linux-<arch>.bin`; the launcher puts its own directory
+ on `LD_LIBRARY_PATH` and execs the `.bin` beside it. The macOS archive holds a single binary and
+ no launcher — so a probe on a developer's Mac shows one layout and the image gets the other.
+ Installing "the file called jcode*" took the launcher, left its `.bin` behind, and produced an
+ executable that is on PATH, satisfies `backend_bin`, and dies on its first turn. Found by running
+ the installer function against the real Linux asset, which is now part of what is done before a
+ base is called installed: `install_mimo`, `install_gajae` and `install_jcode` each run the binary
+ and compare the version it REPORTS, and remove what they put down when it does not match.
+- **mimo's first run on a fresh volume is a one-time SQLite migration.** Measured: over nine
+ minutes with no output before it was killed, about twenty seconds warm. The installer warms a
+ throwaway home so a turn never pays it.
+
+### Failure reporting, per base (checklist item 8: check, do not assume)
+
+| base | how a provider failure arrives | exit |
+|---|---|---|
+| mimo | opencode's `error` event | 1 |
+| gajae | assistant `message_end` with `stopReason:"error"`, `errorStatus`, `errorMessage` — pi's contract exactly; ONE attempt on a 401, no retry storm. Also an `agent_failed` event pi has no branch for, which is why gajae carries its own wrapper | 1 |
+| jcode | a real `error` event naming the endpoint, the model, the auth variable's NAME (never its value), the status and the provider's body | 1 |
+| opensquilla | an `_event` of kind `error`, and `errors[]` on the final object | 1 |
+| nanobot | `run.failed`, or a `run.completed` whose RunResult carries an `error` or a non-completed `stop_reason` | driver's |
+
+### Tool enforcement, measured
+
+`hard` on four, and each was proven by asking the model for its own tool list with one tool
+withheld: gajae's `--tools` allowlist (write absent), jcode's `--disabled-tools` (write absent),
+mimo's `permission.<key>: "deny"` (opencode's, inherited), nanobot's session policy (write_file
+absent — and the model then wrote the file with `exec`, which is the honest limit every
+shell-bearing base has). `instruction` on opensquilla, because `--permissions` picks a posture and
+there is no deny list anywhere on its agent CLI; the disabled set reaches the model through
+AGENTS.md instead, as it does for codex, hermes, dsh and gemini.
+
+nanobot's policy is set on the SESSION rather than on the tool registry on purpose: the loop
+applies it per turn to the registry it is about to use, which by then also holds the MCP provider's
+tools. A registry filtered when the driver started would withhold the built-ins and let every MCP
+tool through — openhands' half-policy defect. The driver refuses to run the turn if the policy did
+not take.
+
+### End to end, with the runner's own argv and the runner's own relay (2026-10-02/03)
+
+Not the probe commands typed by hand: `_build_<base>` was called with a live connection, the
+loopback relay was started in the same process, the argv it returned was run against the pinned
+binary, and the bytes that came back were fed to the shipped normaliser. The task was the same on
+each: write a file and reply with exactly DONE.
+
+| base | file written | result | usage read off the record |
+|---|---|---|---|
+| gajae | `e2e.txt` = kiwi | success, `DONE`, served model `openai/gpt-6-luna` | 6 fresh in / 37 out, 11,105 cache read, 11,157 cache write |
+| jcode | `e2e.txt` = kiwi | success, `DONE` | 6 fresh in / 66 out, 10,592 cache read, 10,741 cache write |
+| opensquilla | `e2e.txt` = kiwi | success, `DONE` (from the transcript, not the concatenated `text`) | 6 fresh in / 189 out, 8,281 cache read, 8,408 cache write |
+| nanobot | `workspace/e2e.txt` = kiwi | success, `DONE` | 5,596 fresh in / 31 out, 5,505 cache read |
+| mimo | `e2e.txt` = kiwi | success, `DONE` | 12 fresh in / 406 out, 43,991 cache read, 15,155 cache write |
+
+mimo's end-to-end on a FRESH home timed out at 300 s inside its one-time SQLite migration; on a warm
+home the same argv answered normally, which is the row above. That cost is a property of a fresh
+data volume, not of a turn, and it is exactly why `install_mimo` warms a throwaway home at install.
+
+The relay is the one that matters for rule 2: all five reached the provider through it with the
+placeholder bearer in the environment, so `_relay_served_model` has its input on every one of them.
+gajae also names the served model itself, on every assistant message.
+
+### The Google column, and what a DIRECT provider showed that the aggregator hid (2026-10-11)
+
+Google's own OpenAI-compatible surface (`https://generativelanguage.googleapis.com/v1beta/openai`),
+as the instance's ONLY integration, on the eight gemini ids it serves: **160 of 160 scenarios, all
+four bases 8/8**, no failure, nothing unmeasured, no driver error, `unlabelled` 0, no foreign
+connection, no substitution. The served id comes back BARE (`gemini-3.8-flash`, no vendor prefix),
+which is the direct path's own signature.
+
+This column exists because of a defect in this batch's first commit: it added
+`("google", <base>)` wiring for all four bases WITHOUT probing any of them, against the rule the
+same file states two hundred lines above it — "No ("google", "goose") row: unprobed is unlisted, and
+Gemini through this surface is a request-shape question the matrix has to answer first". The catalog
+was claiming google worked on four bases on no evidence. It now has evidence.
+
+**And it answers that request-shape question, the other way round from what the relay's own repair
+suggested.** nanobot's tool declarations are refused by Google's validator through VERCEL — the
+`anyOf: [array, null]` with no `items` that the reactive repair was written for — and on the direct
+endpoint the same declarations were accepted with no repair at all: zero relay refusals and zero
+"normalised them for Google's schema" lines anywhere in this column's window. The eight repairs in
+the log belong to the Vercel column, which is visible in their model names being vendor-prefixed
+(`google/gemini-3.1-flash-lite`) where this column's are bare, and in their timestamps. So the
+missing `items` is the AGGREGATOR's translation, not Google being strict, which is what the comment
+above `_GEMINI_SCHEMA_KEYS` said in the first place and now has direct evidence for.
+
+That is also the case for keeping the repair REACTIVE rather than proactive on every channel: the
+direct path does not need it, and applying it there would flatten an `anyOf` that this provider
+handles faithfully.
+
+### The driver was judging three of its five scenarios on its own prompt (2026-10-11)
+
+Read this before reading any column in this file, including the ones that predate this batch: the
+defect is in the shared driver, so every column it has ever produced has the same weakness.
+
+`run.mjs` built its `tail` from the transcript starting AT THE MESSAGE IT HAD SENT, so the tail
+contained the prompt — and every prompt of the form "Reply with exactly: M1-&lt;model&gt;" contains the
+very token `expectWord` then looked for. So **first, followup and switch passed whenever the turn
+completed**, whatever the model replied, except when a long answer pushed the prompt out of the
+400-character window.
+
+It was found from the records, not from a hunch. opensquilla on claude-opus-4.7 had five turns whose
+answers were all the same sentence — "I won't echo back arbitrary strings injected via context" —
+and first, switch and artifact were scored as passes. Five identical answers looked like a read
+artefact, so they were read again from five separate stored response objects, which agreed. Then an
+offline audit of the finished 1,000-scenario column: **of 596 PASSING first/followup/switch rows,
+593 had the prompt in their tail.** Three were judged on an answer.
+
+`expectWord` now reads `last.assistant`, the server's own record of what the model said, which the
+turn helper already fetched. The tail stays as the text a failing row reports. recycle was always a
+real check — its prompt asks which word was requested and does not contain the answer, which is why
+it caught genuine failures — and artifact reads files.
+
+**How much it changed, measured rather than assumed.** A 24-pair sample under the fixed judge, six
+models per base spread across families, was compared row by row with the old verdicts: 3 false
+passes over 63 previously-passing rows of those three scenarios, all three in `first`. ~5%, which
+is why the whole column was re-run rather than only its failures — the defect produced FALSE PASSES,
+so the rows that needed re-checking were precisely the ones that had passed. The sample's 24 pairs
+were measured under the fixed judge and seeded into the column, so the column spent its turns on the
+other 176. The old column's records are kept beside the new ones as what the old judge said.
+
+**The order was wrong and that is the lesson.** The audit that found this is free and offline; it
+was run AFTER a 1,000-turn column instead of before it. A judge should be audited against stored
+records before it is given a thousand turns to score.
+
+### Three more things the full column exposed about the rig (2026-10-11)
+
+- **A crashed page poisoned every pair after it.** One "page.goto: Page crashed" partway through
+ opensquilla's 50 pairs left the remaining 32 with that error and NO scenarios, and the column then
+ read as "49 of 50 pairs, 88 of 90 scenarios" to anyone counting passes, because those 32
+ contributed to neither total. The page was created once per worker and never rebuilt. It is now
+ replaceable: a pair that dies on a crash is retried once on a fresh, logged-in page and goes back
+ on a queue. A browser that is gone still ends the worker, checked first so recovery is not
+ attempted on a dead browser. The re-run finished with zero driver errors.
+- **A re-run inherited the previous attempt's record.** `const rec = res[k] || {…}` meant the resume
+ of those 32 pairs filled scenarios into records still carrying the crash's `error` and `at`, so a
+ measured pair still looked errored — and a reader scored 32 measured pairs as "not measured"
+ because of it. The record is built fresh on every run; "has an error" and "has scenarios" can no
+ longer both be true.
+- **The recycle row reported the driver's own patience as the base's failure.** The route refuses
+ while a turn is settling and the driver retried the 409 for 30 s; mimo on gpt-5.6-luna had an
+ artifact turn still `running` at 478 s, so its recycle row read "recycle refused: HTTP 409 a turn
+ is running". It now waits for the session's record to reach a terminal state, up to 300 s, and
+ says so when it never does.
+
+### What every dimension measured, and what is still not measured
+
+All four offered bases have now been through all four dimensions on the Vercel connection. gajae is
+not offered and is in none of them (see the write-wall section below).
+
+| dimension | mimo | jcode | opensquilla | nanobot |
+|---|---|---|---|---|
+| five scenarios × ALL 50 served ids (Vercel) | 48/50 | 50/50 | 49/50 | 49/50 |
+| five scenarios × 8 gemini ids (Google, direct) | 8/8 | 8/8 | 8/8 | 8/8 |
+| custom-harness (own skill, own script, tool policy, MCP) | ok | ok | ok | ok |
+| plugin: skills / mcp / sse / http | 4/4 | 4/4 | 4/4 | 4/4 |
+| browser (one task in plain words, through the plugin) | ok | ok | ok | ok |
+| environments (pip, npm and apt from the layer, no install) | 3/3 | 3/3 | 3/3 | 3/3 |
+| family tour, 12 families in one conversation | 12/12 | 3/12 | 11/12 | 11/12 |
+
+Both of those were re-run with all four bases on ONE build after the two nanobot fixes they
+exposed, rather than left as "three bases before the fix and nanobot after it": the fixes are
+nanobot-only by construction, but that is an argument where a 16-turn re-run is a measurement.
+
+The browser column needs a browser, and this instance had none when it first ran: all four bases
+failed on "navigate: not configured", which says nothing about any base. The runs above use the
+operator's-own-browser configuration — `HR_BROWSER_CDP_URL` against a headless Chromium in the
+container — and NOT the browser-use vendor key; the two are different paths and a row proved on one
+is not proof for the other. The environments column ran on one layer carrying tabulate (pip),
+qrcode (npm) and jq (apt), and every row used them with zero install commands in the trace.
+
+Rule 2 is not merely answerable on these bases now, it was READ: `unlabelled` is 0 on all 32 pairs,
+so every turn carried a served model off the relay, and no substitution survived `samemodel`.
+
+- **The two tours that show 11 of 12 failed the same family, grok-4.3, inside the same few minutes**,
+ and the reason was the provider's: nanobot's row carried "The model is currently at capacity due to
+ high demand" and opensquilla's carried its own fallback sentence for a terminal event with no
+ message. Both pass grok on a retry — on a fresh session AND on the same long conversation that had
+ failed — so the rows stay as measured with the retries recorded beside them.
+- **jcode's 3 of 12 is the limit written up above**: its fourth family ran away and was killed at the
+ tour's cap, and every family after it stayed on the killed turn's model.
+- Still not measured: any connection other than Vercel and Google. The tour's families were PROBED first,
+ one short turn each, because a family this connection cannot serve would fail a tour for a reason
+ that says nothing about the base: twelve of thirteen answered. llama-3.3-70b was refused by this
+ instance with "no provider configured for backend 'mimo'" — this org holds one integration, which
+ is not a statement about what Vercel serves — so the tour covered twelve. muse is deliberately absent from these runs and no muse credential was used.
+ **"Five ids Vercel does not serve at all" earlier in this file is out of date for ALL FIVE.** That
+ passage is a 2026-09-16 measurement; the full column of 2026-10-11 ran every one of them and each
+ answered and passed 5 of 5 — `claude-fable-5-1` as `anthropic/claude-fable-5.1`,
+ `gemini-3-flash-preview` as `google/gemini-3-flash`, `grok-4.20` as `spacexai/grok-4.20-reasoning`,
+ `hunyuan-4-preview` as `tencent/hy4-preview`, `nemotron-3-super` as
+ `nvidia/nemotron-3-super-120b-a12b`. Every one of those is the provider renaming the model and
+ `samemodel` resolves all five, which is why this column reports no substitution. A provider's
+ coverage is a dated measurement and not a property of the id.
+
+## The disabled tool is the base's own, and the label on the instructions box is the runner's (2026-10-03)
+
+Three things the batch of five exposed, each a surface that read as working and was not.
+
+### The custom-harness dimension was disabling a tool eleven bases do not have
+
+`custom-harness.mjs` built every harness with `disabled_tools: ['WebSearch']` and judged the claim
+with `!tools.some((t) => /websearch/i.test(t))`. A tool id that matches nothing in a runtime is
+dropped on the way through and disables nothing, so on a base with no tool of that exact name
+`disabled_tool_unused` was VACUOUSLY true — a row passing a check that was not running, the same
+shape as the openhands column that reported 40/40 on a substitution check with no input.
+
+Eleven of the twenty bases were in that state: aider, codex, goose, openhands, pi and qwen/gemini/
+cline (the ones the 2026-09-19 and 2026-09-28 notes had already named), plus the five added on
+2026-10-02, whose ids are `web_search` / `websearch` — which the old regex would not have matched
+even where the tool existed.
+
+Now there is a per-base `DISABLED_TOOL` table, each entry read off that base's own `_BASE_CATALOG`
+entry and each a tool the stamp task does not need (nothing switches off a shell, a read or a
+write — that would fail the task rather than test the policy):
+
+| base | tool | base | tool |
+|---|---|---|---|
+| claude-code | `WebSearch` | kimi | `FetchURL` |
+| codex | `git` | cheetahclaws | `WebSearch` |
+| hermes | `web_search` | openhands | `Todo` |
+| pi | `edit` | mimo | `websearch` |
+| dsh | `web_search` | gajae | `web_search` |
+| opencode | `websearch` | jcode | `websearch` |
+| qwen | `web_fetch` | opensquilla | `web_search` |
+| gemini | `google_web_search` | nanobot | `web_search` |
+| cline | `fetch_web_content` | goose | `read_image` |
+| omp | `web_search` | **aider** | **null — not testable** |
+
+aider's catalog is one tool, Shell, and the task needs it, so its row reports that the policy is
+not testable on that base rather than passing. A vacuous pass is worse than an honest gap.
+
+The judge now compares whole names ignoring case and separators (`web_search`, `websearch` and
+`WebSearch` are one name; `search` does not match `search_sessions`), the row records WHICH tool it
+switched off, and `gateway/tests/test_matrix_disabled_tool.py` holds the table to `_BASE_CATALOG`
+so the next base whose ids drift fails there rather than quietly going vacuous.
+
+### The settings page named a file the runner does not write
+
+Registration point 14 requires the console's instruction-file label to agree with
+`_agent_doc_path`. Nothing checked it and it had drifted: the page labelled the box `AGENTS.md` for
+qwen and gemini while the runner writes `QWEN.md` and `GEMINI.md`. The instructions still reached
+the agent; the name on the box was wrong, which on this repo's terms is a defect rather than a nit.
+The label now comes from one exported map (`instructionFileLabel`), and
+`gateway/tests/test_instruction_file_label.py` holds it to `_agent_doc_path` for every base.
+
+### A CLI could say something about a turn and have it reach nobody
+
+The gateway's translator renders exactly two `system` subtypes and drops every other in silence, so
+a runner emitting a third was writing to a surface that did not exist. OpenSquilla reports
+"Provider context limit reached; compacting older context before retrying" as a progress event, and
+a person reading a turn that took minutes and lost its earlier context had no way to learn why.
+`system/notice` is now rendered as a note on the reply, beside `resume_lost` and `mcp_unavailable`;
+the runner bounds it and de-duplicates it (that warning repeats once per retry).
+
+## gajae: the write-wall and a lock that walks its ancestors (2026-10-03, decided 2026-10-06)
+
+Every gajae turn through the product died before its first model call:
+
+ [Uncaught Exception] Error: Failed to snapshot staged file lock: io_error.
+
+**The cause, with evidence at each link.**
+
+1. gjc's native lock helper `open_parent_no_follow` (`crates/pi-natives/src/path_identity.rs`)
+ hardens the lock against symlink swaps by refusing to trust path resolution: it walks from `/`
+ down to the path it is locking and opens EVERY ancestor with
+ `O_RDONLY|O_DIRECTORY|O_NOFOLLOW`. On a directory that needs **read**, not traverse.
+2. `docker/entrypoint.sh` sets `/data` and `/data/workspaces` to `751` — its own comment:
+ "traversable by sessions, neither listable nor writable".
+3. Measured in the container: as a session uid, `open("/data", O_RDONLY|O_DIRECTORY)` is EACCES;
+ as the product user, which owns it, it succeeds.
+4. The addon maps EACCES to `io_error`, `acquireFileLock` throws, nothing catches it.
+5. **Positive control**: the same binary, the same uid, the same flags, in a directory whose only
+ ancestor is `/` (0755) — no crash, and the run reaches the provider.
+6. **Narrowing**: cwd left under `/data` (unreadable ancestors) with only the agent dir and the
+ session dir moved to a readable path — works. So it is specifically the directories gjc locks,
+ both of which the runner names (`GJC_CODING_AGENT_DIR`, `--session-dir`).
+7. **Both directions of the switch, on a real turn through the API**: at `751` the turn failed with
+ that error; at `755` it completed in 4.6 s answering correctly with
+ `served_model = openai/gpt-5.4`; back at `751` it failed again. The modes were restored.
+
+Neither side is wrong. gjc assumes it may be running where an attacker can write and verifies every
+ancestor itself; this product makes those ancestors unwritable so nobody can, and in doing so makes
+them unreadable, which is what gjc's verification needs.
+
+**Decision (the user's, 2026-10-06): do not weaken the wall.** gajae is removed from everything
+that offers, routes or installs it — `_MODEL_CATALOG`, `_BASE_CATALOG`, `_INTEGRATION_WIRING`,
+`_CUSTOM_FORMAT_BACKENDS`, the console's `OOB` and logo map, the default `HR_BACKENDS`, and both
+measurement dimensions' base lists. The runner's implementation stays (`_build_gajae`,
+`_gajae_to_claude`, 13 tests and two captured fixtures) because the base works and the blocker is a
+product decision; `gateway/tests/test_gajae_not_offered.py` pins every one of those surfaces so a
+half-restore — listed but not routable, or routable but not installed — cannot pass unnoticed.
+
+**What it would take to offer it.** Relax `/data` and `/data/workspaces` to `755`, then restore the
+catalog entries, the wiring rows and the `_CUSTOM_FORMAT_BACKENDS` membership. What that gives up is
+"neither listable", not "nor writable": a session uid could then enumerate other session ids and
+environment names. It could not read them — `control.db` and `graph.db` are `0600` and `blobs/` is
+`0700`, and a session uid already has traverse, so file contents are governed by each file's own
+mode either way. The half that stops a session renaming or replacing another session's directory
+(which needs write on the parent, not on the target) is untouched by that change.
diff --git a/gateway/app.py b/gateway/app.py
index 2720c5d3..9dfebab2 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -1434,6 +1434,41 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {
# system-one-phase2) on its own GPU behind TypeSafe's wire, so a HarnessRouter key drives the
# systemone base too: decisions at <base>/systemone, billed to the key's credits (2026-09-24).
("harnessrouter", "systemone"): "typesafe",
+ # ── this batch ────────────────────────────────────────────────────────────────────────────
+ # mimo is an opencode FORK that kept opencode's provider model (an ai-sdk package name plus a
+ # baseURL), so it reaches what opencode reaches and is wired row for row with it. No new
+ # provider entry anywhere: these are wiring rows pointing at providers that already exist,
+ # which is checklist item 1 — a second _PROVIDER_CATALOG key of the same name would silently
+ # overwrite the first on a rebase.
+ ("anthropic", "mimo"): "anthropic", ("openai", "mimo"): "openai",
+ ("azure-foundry", "mimo"): "azure",
+ ("openrouter", "mimo"): "openai-api",
+ ("tokenrouter", "mimo"): "tokenrouter", ("vercel", "mimo"): "tokenrouter",
+ ("llmtr", "mimo"): "tokenrouter", ("custom", "mimo"): "tokenrouter",
+ ("google", "mimo"): "openai-api", ("harnessrouter", "mimo"): "tokenrouter",
+ # jcode, opensquilla and nanobot each speak ONE OpenAI shape, chat/completions, through the
+ # loopback relay, which is exactly cline's and goose's reach, so they are wired as those are.
+ # jcode and opensquilla also have an Anthropic-Messages provider, used only for a connection
+ # that IS Anthropic — a claude id on an aggregator stays on the relay so its served model
+ # remains readable (see _build_jcode).
+ ("anthropic", "jcode"): "anthropic", ("openai", "jcode"): "openai",
+ ("azure-foundry", "jcode"): "azure",
+ ("openrouter", "jcode"): "openai-api",
+ ("tokenrouter", "jcode"): "tokenrouter", ("vercel", "jcode"): "tokenrouter",
+ ("llmtr", "jcode"): "tokenrouter", ("custom", "jcode"): "openai-api",
+ ("google", "jcode"): "openai-api", ("harnessrouter", "jcode"): "tokenrouter",
+ ("anthropic", "opensquilla"): "anthropic", ("openai", "opensquilla"): "openai",
+ ("azure-foundry", "opensquilla"): "azure",
+ ("openrouter", "opensquilla"): "openai-api",
+ ("tokenrouter", "opensquilla"): "tokenrouter", ("vercel", "opensquilla"): "tokenrouter",
+ ("llmtr", "opensquilla"): "tokenrouter", ("custom", "opensquilla"): "openai-api",
+ ("google", "opensquilla"): "openai-api", ("harnessrouter", "opensquilla"): "tokenrouter",
+ ("anthropic", "nanobot"): "anthropic", ("openai", "nanobot"): "openai",
+ ("azure-foundry", "nanobot"): "azure",
+ ("openrouter", "nanobot"): "openai-api",
+ ("tokenrouter", "nanobot"): "tokenrouter", ("vercel", "nanobot"): "tokenrouter",
+ ("llmtr", "nanobot"): "tokenrouter", ("custom", "nanobot"): "openai-api",
+ ("google", "nanobot"): "openai-api", ("harnessrouter", "nanobot"): "tokenrouter",
}
@@ -1719,6 +1754,15 @@ async def _sandbox(path: str, sid: str, method: str = "POST", body: dict | None
headers=_pool_headers(), **kw)
+class _SandboxRefused(RuntimeError):
+ """The runner answered with its own verdict (a 4xx other than 429): `status` and the reason it
+ gave (`detail`), so a turn it refused to start says why rather than reading as a connection
+ that never ran."""
+ def __init__(self, message: str, status: int, detail: str):
+ super().__init__(message)
+ self.status, self.detail = status, detail
+
+
async def _sandbox_json(path: str, sid: str, method: str = "POST", body: dict | None = None,
params: dict | None = None, *, attempts: int = 28, base: float = 0.75) -> dict:
"""Call the sandbox and parse JSON, retrying transient failures with exponential backoff.
@@ -1740,8 +1784,15 @@ async def _sandbox_json(path: str, sid: str, method: str = "POST", body: dict |
return r.json()
last = f"HTTP {r.status_code}, {len(raw)}B body"
if 400 <= r.status_code < 500 and r.status_code != 429: # the server's verdict: waiting cannot change it
- last = f"HTTP {r.status_code}: {raw[:300].decode('utf-8', 'replace')}"
- break
+ text = raw[:2000].decode("utf-8", "replace")
+ try:
+ detail = str((json.loads(text) or {}).get("detail") or text)
+ except ValueError:
+ detail = text
+ raise _SandboxRefused(f"sandbox {path} failed after {i + 1} of {attempts} tries "
+ f"(HTTP {r.status_code}: {text[:300]})", r.status_code, detail[:600])
+ except _SandboxRefused:
+ raise # a verdict, not a transient: never retried
except Exception as e: # noqa: BLE001
last = f"{type(e).__name__}: {str(e)[:120]}"
if i < attempts - 1:
@@ -5400,10 +5451,17 @@ _CUSTOM_FORMAT_BACKENDS = {
# Anthropic endpoint cannot cache at all, which cost a benchmark 6 to 8 times the Claude Code
# price for the same task on goose and OpenHands.
# cheetahclaws: OpenAI Chat Completions only (its `custom/` client), so the openai set alone.
- "openai": {"hermes", "opencode", "kilo", "pi", "dsh", "qwen", "cline", "omp", "goose", "kimi",
- "aider", "openhands", "minimax", "cheetahclaws", "grok", "agentzero"},
+ # This batch: the four offered bases all drive a custom OpenAI endpoint. mimo also takes a
+ # custom ANTHROPIC endpoint (through @ai-sdk/anthropic), which is why it is in both sets;
+ # jcode's and opensquilla's Messages providers exist but are reserved for a connection that IS
+ # Anthropic, so a custom integration declaring the anthropic format would be offered a path the
+ # runner does not take for it — unlisted rather than nearly true.
# kilo passes api_format to the same ai-sdk package choice opencode makes (_opencode_npm).
- "anthropic": {"claude", "opencode", "kilo", "pi", "dsh", "omp", "goose", "hermes", "openhands"},
+ "openai": {"hermes", "opencode", "kilo", "pi", "dsh", "qwen", "cline", "omp", "goose", "kimi",
+ "aider", "openhands", "minimax", "cheetahclaws", "grok", "agentzero",
+ "mimo", "jcode", "opensquilla", "nanobot"},
+ "anthropic": {"claude", "opencode", "kilo", "pi", "dsh", "omp", "goose", "hermes", "openhands",
+ "mimo"},
# The OpenAI Responses API: what codex speaks, and only codex among the agent CLIs here.
"responses": {"codex"},
}
@@ -5971,6 +6029,20 @@ def _blocks_from_canonical(ev: dict) -> list[tuple[str, object]]:
# learn the context was dropped, so it is a short, honest note at the top of the reply.
out.append(("text", "_Note: the earlier conversation could not be restored. This reply "
"continues as a new session, without that context._\n\n"))
+ elif t == "system" and ev.get("subtype") == "notice":
+ # A sentence the CLI itself said about how the turn went — not its answer, and not a
+ # failure. OpenSquilla reports "Provider context limit reached; compacting older context
+ # before retrying" this way, and a person reading a turn that took three minutes and lost
+ # its earlier context has no other way to learn why. The runner decides what is worth
+ # saying; this is the one place it can be said, because an unrecognised system subtype is
+ # dropped here in silence, and a runner that emits one is writing to a surface that does
+ # not exist (which is how this event was nearly shipped unrendered).
+ #
+ # Bounded and de-duplicated by the runner, prefixed like the other two notes, and rendered
+ # as the reply's own text rather than as an answer the model gave.
+ text = str(ev.get("text") or "").strip()
+ if text:
+ out.append(("text", f"\n\n_Note: {text[:500]}_\n"))
elif t == "system" and ev.get("subtype") == "mcp_unavailable":
# A CLI that runs the turn without an MCP server it could not reach, and says nothing (Kimi
# Code CLI does exactly that), leaves a person wondering why the agent never used their
@@ -7278,6 +7350,42 @@ _MODEL_CATALOG["omp"]["models"] = list(_MODEL_CATALOG["pi"]["models"]) # pi's
# substitution would be the provider's, and the relay's served model shows it.
_MODEL_CATALOG["kilo"] = {"default": "gpt-5.4", "models": list(_MODEL_CATALOG["opencode"]["models"])}
_MODEL_CATALOG["agentzero"]["models"] = list(_MODEL_CATALOG["openhands"]["models"]) # see its entry
+# This batch's five, each taking the list of the base whose WIRE REACH it shares, and each OFFERED
+# BUT NOT YET MEASURED — no support-matrix column has run on any of them. The precedent for saying
+# so at the ids rather than under a heading that claims measurement is the cheetahclaws entry, and
+# the reason is checklist item 13: a comment that outlives what it describes is a defect here.
+#
+# mimo is an opencode FORK that kept opencode's provider model — the config names an ai-sdk package
+# and a baseURL, so it reaches what opencode reaches, Responses ids included.
+_MODEL_CATALOG["mimo"] = {"default": "gpt-5.4", "models": list(_MODEL_CATALOG["opencode"]["models"])}
+# ── gajae (Gajae-Code) is implemented and NOT offered ─────────────────────────────────────────
+# It has no entry here, none in _BASE_CATALOG, and no wiring row, so this server neither lists it,
+# routes it (_SUPPORTED_BASES and _HID_PREFIX_RE are derived from _BASE_CATALOG) nor runs it. The
+# runner's implementation stays in place — _build_gajae, _gajae_to_claude, their tests and their
+# captured fixtures — because the base WORKS; what stops it is this product's own write-wall, and
+# that is a decision to revisit rather than a defect to fix.
+#
+# MEASURED (2026-10-03, on a real instance, both directions of the switch):
+# gjc's native lock helper walks from / down to the path it is locking and opens EVERY ancestor
+# with O_RDONLY|O_DIRECTORY|O_NOFOLLOW (pi-natives, open_parent_no_follow), which needs READ on
+# each ancestor rather than traverse. docker/entrypoint.sh sets /data and /data/workspaces to
+# 751 — "traversable by sessions, neither listable nor writable" — so a session uid gets EACCES,
+# the addon reports io_error, and the turn dies before its first model call.
+# With those two directories at 755 a real turn completed in 4.6 s; put back to 751 it failed
+# again with the same error. Both sides are defending the same thing from opposite ends: gjc
+# refuses to trust path resolution for a lock, and this product makes the ancestors unreadable.
+#
+# To offer it: relax those two modes (which gives up "neither listable", not "nor writable"), then
+# restore this entry, the _BASE_CATALOG entry, the _INTEGRATION_WIRING rows and the
+# _CUSTOM_FORMAT_BACKENDS membership. gateway/tests/test_gajae_not_offered.py pins the current
+# state so a half-restore cannot pass unnoticed. docs/support-matrix-notes.md has the full record.
+# jcode, opensquilla and nanobot each speak ONE OpenAI shape — chat/completions — through the
+# loopback relay, which is kimi's reach exactly, so they take kimi's list and are in
+# CHAT_ONLY_BACKENDS below. (jcode and opensquilla also have an Anthropic-Messages provider, used
+# only for a connection that IS Anthropic; the runner keeps a claude id on an aggregator on the
+# relay so its served model stays readable — see _build_jcode.)
+for _b in ("jcode", "opensquilla", "nanobot"):
+ _MODEL_CATALOG[_b] = {"default": "gpt-5.4", "models": list(_MODEL_CATALOG["kimi"]["models"])}
# systemone: Jev's ids across its two providers. `jev-latest` is served by both (TypeSafe's own API,
# and OpenRouter's rolling alias of the same model) and is the default, so a harness made on either
# connection runs; `jev-preview` is TypeSafe's alone and `jev-1.13` OpenRouter's alone (jev-1.13
@@ -7328,12 +7436,18 @@ RESPONSES_ONLY_MODELS = frozenset({"gpt-5.3-codex", "gpt-6-astra"})
# minimax: the runner defines its endpoint with api `openai-completions` (MiniMax Code also has an
# openai-responses api, but it is not the one the runner sets), the kimi case exactly.
# cheetahclaws speaks chat/completions only (its `custom/` provider is OpenAI Chat Completions).
+# jcode's openai-compatible provider posts to /chat/completions (its own error names the endpoint),
+# opensquilla's generic `custom` provider is its Chat Completions adapter, and nanobot's `custom`
+# provider is the same — its `apiType` field, the one that would select a Responses surface, is
+# refused on any provider but `openai` ("providers.<name>.api_type is only supported for
+# providers.openai", which rejects the whole config). So a Responses-API-only id on any of the three
+# would be a picker row that fails on send.
# grok: the runner's one custom model is `api_backend = "chat_completions"` (Grok Build can speak the
# Responses and Messages APIs too, but that is not the model the runner defines).
# agentzero too: its model is litellm's openai provider (Agent Zero's `other`, a0_api_mode chat).
CHAT_ONLY_BACKENDS = ("qwen", "cline", "goose", "kimi", "aider", "openhands", "minimax",
- "cheetahclaws", "grok",
- "agentzero")
+ "cheetahclaws", "grok", "agentzero",
+ "jcode", "opensquilla", "nanobot")
_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:
@@ -8068,6 +8182,13 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
break
try:
started = await _sandbox_json("/turn", sid, body=body) # retries cold-start / transient empties
+ except _SandboxRefused as e:
+ # The runner refused to start this turn and said why (jcode on an Anthropic connection
+ # with a model its catalog does not list, 2026-10-12): that is the reason the person
+ # needs, so it carries a status like a connection that ran. Without one, the turn read
+ # "No connection on this account serves claude-sonnet-5.5-direct".
+ rec["tried"].append({"connection": name, "tenant": src, "status": e.status, "error": e.detail})
+ continue
except Exception as e: # noqa: BLE001
rec["tried"].append({"connection": name, "tenant": src, "error": str(e)[:200]})
continue
@@ -10168,6 +10289,63 @@ def _ws_visible(path: str) -> bool:
return not any(path.startswith(p) or f"/{p}" in path for p in _WS_HIDE_PREFIXES)
+# The checkpoint tarball is the session DIRECTORY, which is not always the directory the agent
+# works in: nanobot's loader refuses a session store inside the agent's workspace, so that base
+# keeps its store at the session root and works one level down (_NANOBOT_WS in the runner). Reading
+# the tar straight through therefore showed a nanobot session as 30 files under a `workspace/`
+# prefix the user never typed — its three built-in skill bundles and its instruction file among
+# them — on the share page, in the full files listing, in the download-all zip, and to the kit
+# route that resolves an app's own file BY PATH (a kit asking for deck.json would not have found
+# it). The runner already writes both facts INTO the checkpoint, so this reads them back rather
+# than keeping a second list in the gateway: `.harness/agent-subdir` names the agent's directory
+# and `.git/info/exclude` carries the base's own machinery patterns (git status honours the same
+# file, which is what keeps the produced-files list clean).
+_WS_SUBDIR_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
+
+
+def _ws_rules(tf) -> tuple[str, tuple[str, ...]]:
+ def _member(name: str) -> str:
+ for n in (f"./{name}", name):
+ try:
+ m = tf.getmember(n)
+ except KeyError:
+ continue
+ if m.isreg() and m.size <= 64 * 1024:
+ f = tf.extractfile(m)
+ if f is not None:
+ return f.read().decode(errors="replace")
+ return ""
+ # ONE plain directory name, checked before any stripping: "/etc" stripped of its slashes
+ # would have read as the name "etc", and a value this does not recognise must mean "no subdir"
+ # rather than some other directory.
+ sub = _member(".harness/agent-subdir").strip()
+ if not _WS_SUBDIR_RE.fullmatch(sub):
+ sub = ""
+ pats = tuple(l.strip() for l in _member(".git/info/exclude").splitlines()
+ if l.strip() and not l.startswith("#"))
+ return sub, pats
+
+
+def _ws_view(path: str, sub: str, pats: tuple[str, ...]) -> str | None:
+ """The tar member's path as the USER sees it, or None when it is not the user's file.
+
+ The base's own exclude patterns are matched against the path as GIT sees it — relative to the
+ session directory — because that is the file git reads them from; the prefix comes off after."""
+ for q in pats:
+ if path == q or (q.endswith("/") and path.startswith(q)):
+ return None
+ if sub:
+ if not path.startswith(f"{sub}/"):
+ return None # outside the agent's directory is the runner's own state
+ path = path[len(sub) + 1:]
+ return path if _ws_visible(path) else None
+
+
+def _ws_member(path: str, sub: str) -> str:
+ """The inverse: where that user path lives inside the tar."""
+ return f"{sub}/{path}" if sub else path
+
+
def _wf_id(path: str) -> str:
return "wf_" + base64.urlsafe_b64encode(path.encode()).decode().rstrip("=")
@@ -10268,11 +10446,13 @@ async def _ws_files(sid: str) -> dict[str, bytes] | None:
out: dict[str, bytes] = {}
total = 0
with tf:
+ sub, pats = _ws_rules(tf)
for m in tf.getmembers():
if not m.isreg():
continue
path = m.name[2:] if m.name.startswith("./") else m.name
- if not _ws_visible(path):
+ path = _ws_view(path, sub, pats)
+ if path is None:
continue
if m.size > _WS_FILE_CAP or total + m.size > _WS_TOTAL_CAP:
continue # oversized: served via the single-member fallback
@@ -10412,7 +10592,9 @@ async def _container_file_bytes(container_id: str, file_id: str) -> tuple[bytes,
if tf is None:
return None
with tf:
- for name in (f"./{path}", path):
+ sub, _pats = _ws_rules(tf)
+ member = _ws_member(path, sub)
+ for name in (f"./{member}", member):
try:
m = tf.getmember(name)
except KeyError:
@@ -10481,11 +10663,13 @@ async def session_workspace_files(sid: str, request: Request, changed: bool = Fa
cfile_by_name = await _cfile_by_name(sid)
files = []
with tf:
+ sub, pats = _ws_rules(tf)
for m in tf.getmembers():
if not m.isreg():
continue
path = m.name[2:] if m.name.startswith("./") else m.name
- if not _ws_visible(path):
+ path = _ws_view(path, sub, pats)
+ if path is None:
continue
fid = cfile_by_name.get(path) or _wf_id(path)
files.append({"object": "file", "id": fid, "container_id": sid,
@@ -10583,11 +10767,13 @@ async def session_files_archive(sid: str, request: Request, changed: bool = Fals
# turn relays, and health probes keep flowing).
n, tot = 0, 0
with tf:
+ sub, pats = _ws_rules(tf)
for m in tf.getmembers():
if not m.isreg():
continue
path = m.name[2:] if m.name.startswith("./") else m.name
- if not _ws_visible(path) or path.lstrip("/") in seen:
+ path = _ws_view(path, sub, pats)
+ if path is None or path.lstrip("/") in seen:
continue
tot += m.size
if tot > _ARCHIVE_MAX_BYTES:
@@ -16750,6 +16936,98 @@ _BASE_CATALOG: dict[str, dict] = {
("spawn_agent", "Subagent")],
"tool_enforcement": "instruction",
},
+ "mimo": {
+ "label": "MiMo Code", "backend": "mimo", "status": "ready",
+ "system_prompt": ("You are MiMo Code, an autonomous coding agent. You work on a real git "
+ "workspace with shell and file access, reading and editing files and "
+ "running commands to complete the task end to end."),
+ # The PERMISSION keys the fork kept from opencode (config/permission.ts), because those are
+ # the names that can actually be denied — a key outside this set is accepted by the
+ # record-with-rest schema and then matches no tool, which is a switch the console shows and
+ # that disables nothing.
+ "tools": [("bash", "Shell"), ("read", "File Read"), ("edit", "Edit"), ("glob", "Glob"),
+ ("grep", "Search"), ("list", "List"), ("webfetch", "Web Fetch"),
+ ("websearch", "Web Search"), ("todowrite", "Todo"), ("task", "Subagent"),
+ ("question", "Question"), ("lsp", "LSP"), ("skill", "Skill"),
+ ("external_directory", "External Directory")],
+ # "hard" for opencode's reason, which the fork did not change: a `permission.<key>: "deny"`
+ # removes the tool rather than discouraging it. The honest limit every shell-bearing base
+ # has: denying `edit` does not stop a file being written through `bash`.
+ "tool_enforcement": "hard",
+ },
+ "jcode": {
+ "label": "jcode", "backend": "jcode", "status": "ready",
+ "system_prompt": ("You are jcode, 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."),
+ # Measured on the pinned v0.90.0 by asking the model for its own tool list, which is the
+ # list the schema was built from; pinned equal to the runner's ALL_JCODE_TOOLS.
+ # macos_computer_use is listed because the build registers it — on Linux it has nothing to
+ # drive, which is a property of the host, not of the catalog.
+ "tools": [("bash", "Shell"), ("read", "File Read"), ("write", "File Write"),
+ ("edit", "Edit"), ("replace", "Replace"), ("apply_patch", "Apply Patch"),
+ ("ls", "List"), ("agentgrep", "Search"), ("open", "Open"),
+ ("webfetch", "Web Fetch"), ("websearch", "Web Search"), ("browser", "Browser"),
+ ("todo", "Todo"), ("memory", "Memory"), ("batch", "Batch"), ("bg", "Background"),
+ ("swarm", "Swarm"), ("applet", "Applet"), ("panel", "Panel"),
+ ("side_panel", "Side Panel"), ("schedule", "Schedule"),
+ ("skill_manage", "Skill Manage"), ("jcode_docs", "Docs"),
+ ("conversation_search", "Conversation Search"),
+ ("session_search", "Session Search"), ("compile_remote", "Remote Compile"),
+ ("integration_tools", "Integrations"), ("gmail", "Gmail"),
+ ("maintainer_feedback", "Maintainer Feedback"),
+ ("macos_computer_use", "Computer Use"), ("mcp", "MCP"),
+ ("mcp_call", "MCP Call"), ("mcp_search", "MCP Search"), ("invalid", "Invalid")],
+ # "hard", and measured: --disabled-tools runs after the tool profile, and with `write`
+ # disabled the model's own list came back without it. Writing has four doors here (write,
+ # edit, replace, apply_patch) and egress several, so disabling one is not disabling a
+ # capability — the same honest limit every shell-bearing base carries.
+ "tool_enforcement": "hard",
+ },
+ "opensquilla": {
+ "label": "OpenSquilla", "backend": "opensquilla", "status": "ready",
+ "system_prompt": ("You are OpenSquilla, an autonomous agent. You work on a real git "
+ "workspace with shell and file access, reading and editing files and "
+ "running commands to complete the task end to end."),
+ # The tool names its own turns record (measured: write_file, read_file). Its agent CLI has
+ # NO per-tool deny list — `--permissions` chooses a posture (restricted / bypass / full) —
+ # so this list is deliberately short: it names what a turn was seen to call rather than
+ # advertising a switch for every tool in the runtime when none of them can be withheld.
+ "tools": [("exec", "Shell"), ("read_file", "File Read"), ("write_file", "File Write"),
+ ("edit_file", "Edit"), ("list_dir", "List"), ("grep", "Search"),
+ ("web_search", "Web Search"), ("web_fetch", "Web Fetch")],
+ # "instruction", and for a stated reason rather than for lack of looking: there is no deny
+ # list on `opensquilla agent`, so the disabled set reaches the model as a line in AGENTS.md
+ # (runner/server.py adds this base to the set that gets that instruction). UHP §4.3 forbids
+ # overstating this as much as understating it.
+ "tool_enforcement": "instruction",
+ },
+ "nanobot": {
+ "label": "nanobot", "backend": "nanobot", "status": "ready",
+ "system_prompt": ("You are nanobot, an autonomous agent. You work on a real git workspace "
+ "with shell and file access, reading and editing files and running "
+ "commands to complete the task end to end."),
+ # The 22 tools its loop registers, read off its own start-up line on 0.3.5 and pinned equal
+ # to the runner's ALL_NANOBOT_TOOLS.
+ "tools": [("exec", "Shell"), ("exec_session", "Shell Session"),
+ ("list_exec_sessions", "Shell Sessions"), ("run_cli_app", "CLI App"),
+ ("read_file", "File Read"), ("write_file", "File Write"),
+ ("edit_file", "Edit"), ("apply_patch", "Apply Patch"),
+ ("find_files", "Find"), ("grep", "Search"), ("list_dir", "List"),
+ ("web_fetch", "Web Fetch"), ("web_search", "Web Search"),
+ ("message", "Message"), ("my", "Self"), ("spawn", "Subagent"),
+ ("create_goal", "Goal Create"), ("update_goal", "Goal Update"),
+ ("list_sessions", "Sessions"), ("read_session", "Session Read"),
+ ("search_sessions", "Session Search"),
+ ("send_session_message", "Session Message")],
+ # "hard", and measured at the door that covers BOTH tool sources: the driver sets the
+ # SESSION's disabled_tools, which the loop applies to the registry it is about to use —
+ # after the MCP provider has registered its own tools into it. A registry filtered at
+ # construction would have withheld the built-ins and let every MCP tool through. Measured:
+ # with write_file withheld the model wrote the file with `exec` instead, which is the honest
+ # limit — withholding a tool withholds that tool, not the capability.
+ "tool_enforcement": "hard",
+ },
}
# Bases this server can execute. Derived from the catalog above so the two cannot disagree —
diff --git a/gateway/tests/test_catalog_batch3_tools.py b/gateway/tests/test_catalog_batch3_tools.py
new file mode 100644
index 00000000..030a239e
--- /dev/null
+++ b/gateway/tests/test_catalog_batch3_tools.py
@@ -0,0 +1,103 @@
+"""The console must never offer a toggle the runner cannot enforce, on any of this batch's bases.
+
+A tool id in the catalog that matches nothing in the runtime is dropped on the way through and
+disables nothing while the console reports it as off — the overstatement UHP section 4.3 forbids,
+and the whole of what `tool_enforcement: "hard"` claims. These tests hold each catalog to the
+runner's own measured list, which is also where the measurement is recorded:
+
+ jcode ALL_JCODE_TOOLS — the model's own account of its tools on v0.90.0, with
+ --disabled-tools write proving the switch is enforcement
+ nanobot ALL_NANOBOT_TOOLS — the 22 its loop logs at start-up on 0.3.5
+
+mimo and opensquilla are checked differently and for stated reasons, below. gajae is checked by
+test_gajae_not_offered.py instead: it is implemented but deliberately not offered.
+"""
+import os
+import pathlib
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "runner"))
+os.environ.setdefault("HR_BACKING", "local")
+import app as A # noqa: E402
+from server import (ALL_GAJAE_TOOLS, ALL_JCODE_TOOLS, ALL_NANOBOT_TOOLS, # noqa: E402
+ BACKENDS, _opencode_denies)
+
+
+def _offered(base: str) -> set:
+ return {tid for tid, _label in A._BASE_CATALOG[base]["tools"]}
+
+
+def test_jcode_offers_only_tools_the_deny_list_can_withhold():
+ offered = _offered("jcode")
+ assert offered == ALL_JCODE_TOOLS, (
+ f"only in catalog: {offered - ALL_JCODE_TOOLS}, only in the runner: {ALL_JCODE_TOOLS - offered}")
+
+
+def test_nanobot_offers_exactly_the_tools_its_loop_registers():
+ offered = _offered("nanobot")
+ assert offered == set(ALL_NANOBOT_TOOLS), (
+ f"only in catalog: {offered - set(ALL_NANOBOT_TOOLS)}, "
+ f"only in the runner: {set(ALL_NANOBOT_TOOLS) - offered}")
+
+
+def test_mimo_offers_only_permission_keys_the_config_actually_denies():
+ # Its switch is opencode's `permission.<key>: "deny"`, and the runner drops a key outside the
+ # set opencode understands rather than writing one that matches no tool. So the test is not a
+ # list comparison but the real question: does every id the console shows produce a deny?
+ for tid in sorted(_offered("mimo")):
+ assert _opencode_denies([tid]) == {tid: "deny"}, tid
+
+
+def test_opensquilla_does_not_claim_an_enforcement_it_has_not_got():
+ # Its agent CLI has no per-tool deny list — `--permissions` picks a posture — so the disabled
+ # set reaches the model as an instruction in AGENTS.md, and the catalog must say so. UHP 4.3
+ # forbids understating this as much as overstating it.
+ assert A._BASE_CATALOG["opensquilla"]["tool_enforcement"] == "instruction"
+
+
+def test_the_four_with_a_real_switch_claim_hard():
+ for base in ("mimo", "jcode", "nanobot"):
+ assert A._BASE_CATALOG[base]["tool_enforcement"] == "hard", base
+
+
+def test_every_base_in_the_catalog_is_one_the_runner_can_execute():
+ for base in ("mimo", "jcode", "opensquilla", "nanobot"):
+ assert base in A._BASE_CATALOG
+ assert A._BASE_CATALOG[base]["backend"] in BACKENDS
+ assert base in A._MODEL_CATALOG and A._MODEL_CATALOG[base]["models"]
+ # Every id the picker offers has to be drivable by at least one wiring row, or the base is
+ # a row in the console that cannot be connected to anything.
+ assert any(b == base for _p, b in A._INTEGRATION_WIRING), base
+
+
+# ── the notice surface ────────────────────────────────────────────────────────────────────────
+# An unrecognised `system` subtype is dropped here in silence, so a runner that emits one is
+# writing to a surface that does not exist. `notice` is the third subtype this translator knows,
+# and it exists because opensquilla says things about a turn that are neither its answer nor a
+# failure — "Provider context limit reached; compacting older context before retrying" — and a
+# person reading a turn that took minutes and lost its earlier context has no other way to learn why.
+
+def test_a_cli_notice_is_rendered_as_a_note_on_the_reply():
+ out = A._blocks_from_canonical({"type": "system", "subtype": "notice",
+ "text": "Provider context limit reached; compacting."})
+ assert len(out) == 1
+ kind, text = out[0]
+ assert kind == "text"
+ assert "Provider context limit reached; compacting." in text
+ assert text.strip().startswith("_Note:")
+
+
+def test_an_empty_notice_renders_nothing():
+ assert A._blocks_from_canonical({"type": "system", "subtype": "notice", "text": ""}) == []
+ assert A._blocks_from_canonical({"type": "system", "subtype": "notice", "text": " "}) == []
+
+
+def test_a_notice_is_bounded():
+ out = A._blocks_from_canonical({"type": "system", "subtype": "notice", "text": "x" * 5000})
+ assert len(out[0][1]) < 600
+
+
+def test_a_subtype_nobody_renders_still_produces_nothing():
+ # The reason the runner may not invent one: this is silent, not an error.
+ assert A._blocks_from_canonical({"type": "system", "subtype": "made_up", "text": "hi"}) == []
diff --git a/gateway/tests/test_gajae_not_offered.py b/gateway/tests/test_gajae_not_offered.py
new file mode 100644
index 00000000..ee5c2b33
--- /dev/null
+++ b/gateway/tests/test_gajae_not_offered.py
@@ -0,0 +1,84 @@
+"""gajae is implemented and deliberately NOT offered — this pins that state at every surface.
+
+Gajae-Code works: it was measured end to end through the product on 2026-10-03, and the runner
+still carries `_build_gajae`, `_gajae_to_claude`, their tests and their captured fixtures. What
+stops it is this product's own write-wall, not a defect in either side:
+
+ gjc's native lock helper walks from / down to the path it is locking and opens EVERY ancestor
+ with O_RDONLY|O_DIRECTORY|O_NOFOLLOW, which needs READ on each ancestor rather than traverse.
+ docker/entrypoint.sh sets /data and /data/workspaces to 751 — "traversable by sessions, neither
+ listable nor writable" — so a session uid gets EACCES, the addon reports io_error, and the turn
+ dies before its first model call. Both sides defend the same thing from opposite ends: gjc
+ refuses to trust path resolution for a lock; the product makes the ancestors unreadable.
+
+ Measured BOTH WAYS on a live instance: at 751 a real turn failed with that error; at 755 the same
+ turn completed in 4.6 s answering correctly; back at 751 it failed again.
+
+A half-restore is the risk this file exists for — a base that is listed but not routable, or
+routable but not installed, fails on a user's first turn with nothing to read. So the rule is all
+or nothing: either every surface offers it or none does, and today it is none.
+"""
+import os
+import pathlib
+import re
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "runner"))
+os.environ.setdefault("HR_BACKING", "local")
+import app as A # noqa: E402
+
+ROOT = pathlib.Path(__file__).resolve().parents[2]
+
+
+def test_the_gateway_neither_lists_nor_routes_it():
+ assert "gajae" not in A._BASE_CATALOG
+ assert "gajae" not in A._MODEL_CATALOG
+ # _SUPPORTED_BASES and the per-harness URL matcher are DERIVED from _BASE_CATALOG, so this
+ # follows — asserted anyway, because routing a base nothing can serve is the worst shape.
+ assert "gajae" not in A._SUPPORTED_BASES
+ assert not A._HID_PREFIX_RE.match("/gajae/v1/responses")
+ assert not any(b == "gajae" for _p, b in A._INTEGRATION_WIRING)
+ assert not any("gajae" in bs for bs in A._CUSTOM_FORMAT_BACKENDS.values())
+
+
+def test_the_console_does_not_offer_it():
+ ts = (ROOT / "ui" / "src" / "lib" / "harness.ts").read_text()
+ assert "id: 'gajae'" not in ts
+ assert "'gajae'" not in ts # also out of the backend union and the label map
+ logo = (ROOT / "ui" / "src" / "components" / "HarnessLogo.tsx").read_text()
+ assert "gajae" not in logo
+ # and the mark it would have used is gone rather than left to rot in the tree
+ assert not (ROOT / "ui" / "public" / "logos" / "gajae.png").exists()
+
+
+def test_nothing_installs_it_by_default():
+ sh = (ROOT / "docker" / "entrypoint.sh").read_text()
+ default = re.search(r'HR_BACKENDS="\$\{HR_BACKENDS:-([^}]+)\}"', sh).group(1)
+ assert "gajae" not in default.split(",")
+
+
+def test_no_measurement_dimension_claims_to_cover_it():
+ # A base in a dimension's list that the server cannot serve produces a column of failures that
+ # say nothing about the base.
+ mjs = (ROOT / "scripts" / "support-matrix" / "custom-harness.mjs").read_text()
+ assert "gajae" not in mjs
+ plugins = (ROOT / "scripts" / "support-matrix" / "plugins" / "run-matrix.py").read_text()
+ assert "gajae" not in plugins
+
+
+def test_the_runner_implementation_is_still_there_and_still_works():
+ # Kept on purpose: the base works, and the thing that blocks it is a decision about file modes.
+ # If someone deletes this code, this test is where they are asked to mean it.
+ from server import ALL_GAJAE_TOOLS, _build_gajae, _gajae_to_claude # noqa: F401
+ assert len(ALL_GAJAE_TOOLS) > 30
+ assert (ROOT / "runner" / "tests" / "fixtures" / "batch3" / "gajae-write-file.ndjson").is_file()
+
+
+def test_the_reason_is_written_down_where_someone_would_look():
+ # Not folklore: the measurement lives in the code that would have to change and in the notes.
+ gw = (ROOT / "gateway" / "app.py").read_text()
+ assert "gajae (Gajae-Code) is implemented and NOT offered" in gw
+ assert "O_RDONLY|O_DIRECTORY|O_NOFOLLOW" in gw
+ notes = (ROOT / "docs" / "support-matrix-notes.md").read_text()
+ assert "write-wall" in notes and "open_parent_no_follow" in notes
diff --git a/gateway/tests/test_instruction_file_label.py b/gateway/tests/test_instruction_file_label.py
new file mode 100644
index 00000000..5659a9a7
--- /dev/null
+++ b/gateway/tests/test_instruction_file_label.py
@@ -0,0 +1,73 @@
+"""The settings page must name the file the runner actually writes.
+
+Registration point 14 of docs/harness-verification.md: "the instruction-file label, which must agree
+with `_agent_doc_path` or the settings page names a file the runner does not write". Nothing checked
+it, and it had drifted — the page labelled the box "AGENTS.md" for qwen and gemini while the runner
+wrote QWEN.md and GEMINI.md, so a person editing those instructions was editing a box named for a
+file their agent never read. (The text still reached the agent; the NAME on the box was a lie, which
+on this repo's own terms is a defect rather than a nit.)
+
+The console now derives the label from one map, `instructionFileLabel` in ui/src/lib/harness.ts,
+and this test holds that map to `_agent_doc_path` for every base the console lists.
+"""
+import os
+import pathlib
+import re
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "runner"))
+os.environ.setdefault("HR_BACKING", "local")
+import app as A # noqa: E402
+from server import _agent_doc_path # noqa: E402
+
+UI = pathlib.Path(__file__).resolve().parents[2] / "ui" / "src"
+HARNESS_TS = UI / "lib" / "harness.ts"
+SETTINGS_TSX = UI / "components" / "HarnessSettings.tsx"
+
+# The one base that reads no workspace: its instructions travel in the job, so there is no file to
+# name and the page says so instead of inventing one.
+NO_FILE = {"systemone"}
+
+
+def _label_map() -> dict:
+ src = HARNESS_TS.read_text()
+ special = dict(re.findall(r"^\s*([A-Za-z0-9_-]+):\s*'([^']+)',",
+ re.search(r"INSTRUCTION_FILE: Record<string, string> = \{(.*?)\n\};",
+ src, re.S).group(1), re.M))
+ agents = re.findall(r"'([a-z0-9-]+)'",
+ re.search(r"const AGENTS_MD_BASES = \[(.*?)\n\];", src, re.S).group(1))
+ out = {}
+ for base in A._BASE_CATALOG:
+ out[base] = special.get(base) or ("AGENTS.md" if base in agents else "CLAUDE.md")
+ return out
+
+
+def test_every_label_is_the_file_the_runner_writes():
+ for base, label in _label_map().items():
+ if base in NO_FILE:
+ assert label == "Instructions", base
+ continue
+ backend = A._BASE_CATALOG[base]["backend"]
+ want = _agent_doc_path("/w", backend).name
+ assert label == want, (
+ f"{base}: the settings page calls the box {label!r} and the runner writes {want!r}")
+
+
+def test_the_page_does_not_carry_a_second_copy_of_the_list():
+ # Two lists meant two places to edit and only one of them got edited, which is how this drifted.
+ src = SETTINGS_TSX.read_text()
+ assert "instructionFileLabel(" in src
+ assert "AGENTS.md" not in src and "CLAUDE.md" not in src
+
+
+def test_the_bases_this_batch_added_are_covered():
+ labels = _label_map()
+ for base in ("mimo", "jcode", "opensquilla", "nanobot"):
+ assert labels[base] == "AGENTS.md", base
+
+
+def test_the_two_that_were_mislabelled_now_say_their_own_name():
+ labels = _label_map()
+ assert labels["qwen"] == "QWEN.md"
+ assert labels["gemini"] == "GEMINI.md"
diff --git a/gateway/tests/test_matrix_disabled_tool.py b/gateway/tests/test_matrix_disabled_tool.py
new file mode 100644
index 00000000..5ab4b335
--- /dev/null
+++ b/gateway/tests/test_matrix_disabled_tool.py
@@ -0,0 +1,109 @@
+"""The custom-harness dimension must switch off a tool the base ACTUALLY HAS, and never one the
+fixture needs.
+
+A tool id that matches nothing in a runtime is dropped on the way through and disables nothing, so
+`disabled_tool_unused` is then vacuously true: the row passes a check that is not running. That is
+what a single hardcoded `WebSearch` did on eleven of the twenty bases.
+
+`custom-harness.mjs` no longer carries a per-base table of what to withhold — it DERIVES the choice
+from the base's own published tool list (`pickDisabled`), excluding what the fixture needs
+(`NEEDED_ID`) and preferring a short list of spare tools, and records the claim as unmeasurable when
+a base publishes nothing else. That is better than a table because there is no list to drift, and it
+moves the risk somewhere else: a base whose EXECUTION, FILE, SKILL or MCP tool is not matched by
+`NEEDED_ID` would have that tool withheld, and the fixture would fail for a reason that is the
+dimension's. This test is where that is caught, for every base the gateway offers.
+"""
+import os
+import pathlib
+import re
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as A # noqa: E402
+
+MJS = pathlib.Path(__file__).resolve().parents[2] / "scripts" / "support-matrix" / "custom-harness.mjs"
+SRC = MJS.read_text()
+
+
+def _regex(name: str) -> re.Pattern:
+ """A JS regex literal from the driver, as a Python pattern (both are PCRE-ish for this shape)."""
+ body = re.search(rf"const {name} = /\^?(.*?)\$?/i;", SRC).group(1)
+ return re.compile(rf"^(?:{body})$", re.I)
+
+
+NEEDED = _regex("NEEDED_ID")
+PREFERRED = _regex("PREFERRED")
+# What the fixture does: run its skill's script, read and write files, load the skill, call MCP. A
+# tool of any of those kinds must never be the one withheld.
+FIXTURE_KINDS = ("exec", "file", "skill", "mcp")
+
+
+def _bases_in_dimension() -> list:
+ """The ids the driver runs, as the gateway spells them — which is the same spelling."""
+ return re.search(r"const BASES = \(process\.env\.BASES \|\| '([^']+)'\)", SRC).group(1).split(",")
+
+
+# The driver's own exclusion: a System One model chooses among offered actions and runs no shell, so
+# the fixture's script has nothing to run on it.
+EXCLUDED = {"systemone"}
+
+
+def _tool_ids(spec: dict) -> list:
+ """A base's tool IDS. The catalog stores (id, label) pairs, and reading the pair as a string is
+ how the first version of this test decided no base's tools were covered by NEEDED_ID."""
+ out = []
+ for t in (spec.get("tools") or []):
+ out.append(str(t[0]) if isinstance(t, (tuple, list)) and t else str(t))
+ return out
+
+
+def test_every_base_the_gateway_offers_is_in_the_dimension():
+ missing = [b for b in A._BASE_CATALOG if b not in _bases_in_dimension() and b not in EXCLUDED]
+ assert not missing, f"the dimension would never measure {missing}"
+
+
+def test_this_batchs_four_bases_are_there():
+ for b in ("mimo", "jcode", "opensquilla", "nanobot"):
+ assert b in _bases_in_dimension(), b
+
+
+def test_gajae_is_not(the_dimension=None):
+ # it is implemented and not offered; a base the server cannot serve produces a column of
+ # failures that say nothing about it (see test_gajae_not_offered.py)
+ assert "gajae" not in _bases_in_dimension()
+
+
+def test_the_tools_this_batchs_bases_run_the_fixture_WITH_are_never_withheld():
+ """Named, not inferred. The first version of this test tried to re-derive "what the fixture
+ needs" with a regex over every base's tools and flagged `web_search`, `todowrite` and
+ `board_read` — the spare tools the dimension is SUPPOSED to withhold. Re-deriving the driver's
+ own judgement is how a test drifts; what is knowable here is the id each of these four bases
+ uses to run a script and to write a file, so those are listed."""
+ needs = {
+ "mimo": ("bash", "edit"), # opencode's names, kept in the fork
+ "jcode": ("bash", "write"),
+ "opensquilla": ("exec", "write_file"),
+ "nanobot": ("exec", "write_file"),
+ }
+ for base, ids in needs.items():
+ published = _tool_ids(A._BASE_CATALOG[base])
+ for tool in ids:
+ assert tool in published, f"{base} no longer publishes {tool}; this list is stale"
+ assert NEEDED.match(tool), (
+ f"NEEDED_ID does not cover {base}:{tool}, so pickDisabled could withhold the tool "
+ f"the fixture runs with and the row would fail for the dimension's reason")
+
+
+def test_a_preferred_tool_is_never_also_one_the_fixture_needs():
+ # the two lists must not overlap, or the preference would pick something the task uses
+ for spec in A._BASE_CATALOG.values():
+ for t in _tool_ids(spec):
+ assert not (PREFERRED.match(t) and NEEDED.match(t)), t
+
+
+def test_a_base_with_nothing_to_spare_records_it_as_unmeasurable():
+ # the mechanism, pinned at the source: null rather than a pass, and the row says so
+ assert "pickDisabled" in SRC
+ assert "rec.disabled_tool_unused === null" in SRC, "a null must not be read as a pass"
+ assert "disabled_tool_unused: null" in SRC or "? !toolNames.some" in SRC
diff --git a/gateway/tests/test_nested_workspace_view.py b/gateway/tests/test_nested_workspace_view.py
new file mode 100644
index 00000000..b820a505
--- /dev/null
+++ b/gateway/tests/test_nested_workspace_view.py
@@ -0,0 +1,111 @@
+"""The checkpoint tarball is the session directory; it is not always the directory the agent works in.
+
+nanobot's loader refuses a session store inside the agent's workspace, so that one base keeps its
+store at the session root and works one level down. Read straight through, a nanobot session showed
+as 30 files under a `workspace/` prefix the user never typed — its three built-in skill bundles and
+its instruction file among them. MEASURED on a live instance before the fix; the four surfaces that
+read the checkpoint are the share page, the full files listing, the download-all zip and the kit
+route that resolves an app's own file BY PATH (a kit asking for deck.json would not have found it).
+
+The two facts needed to read it as the agent's directory are already written INTO the checkpoint by
+the runner, which is why they are read back rather than restated here: `.harness/agent-subdir` names
+the directory, and `.git/info/exclude` carries the base's machinery patterns — the same file
+`git status` honours, which is what keeps the produced-files list clean. One source, two readers.
+"""
+import io
+import os
+import pathlib
+import sys
+import tarfile
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as A # noqa: E402
+
+EXCLUDE = ("# written by the harness runner: nanobot's own machinery, never the task's output\n"
+ "workspace/.nanobot/\nworkspace/skills/\nworkspace/memory/\nworkspace/AGENTS.md\n")
+
+
+def _tar(names: dict) -> tarfile.TarFile:
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w") as t:
+ for name, data in names.items():
+ b = data.encode()
+ ti = tarfile.TarInfo(name)
+ ti.size = len(b)
+ t.addfile(ti, io.BytesIO(b))
+ buf.seek(0)
+ return tarfile.open(fileobj=buf, mode="r")
+
+
+# exactly the shape a real nanobot checkpoint has (verified against a live instance's workspace.tgz)
+NESTED = {
+ "./.harness/agent-subdir": "workspace",
+ "./.git/info/exclude": EXCLUDE,
+ "./.harness/home/.nanobot/cli-apps/x": "state",
+ "./workspace/AGENTS.md": "instructions",
+ "./workspace/.nanobot/workspace-id": "id",
+ "./workspace/skills/imagegen/SKILL.md": "skill",
+ "./workspace/report.md": "the deliverable",
+}
+FLAT = {
+ "./.git/info/exclude": "",
+ "./.harness/home/x": "state",
+ "./AGENTS.md": "instructions",
+ "./report.md": "the deliverable",
+}
+
+
+def _view(members: dict) -> set:
+ tf = _tar(members)
+ with tf:
+ sub, pats = A._ws_rules(tf)
+ out = set()
+ for m in tf.getmembers():
+ p = m.name[2:] if m.name.startswith("./") else m.name
+ v = A._ws_view(p, sub, pats)
+ if v is not None:
+ out.add(v)
+ return out
+
+
+def test_a_nested_session_shows_the_agents_directory_and_nothing_else():
+ assert _view(NESTED) == {"report.md"}
+
+
+def test_a_flat_session_is_untouched():
+ # every other base: the session dir IS the agent's, and the generic families still hide
+ assert _view(FLAT) == {"report.md"}
+
+
+def test_the_rules_come_from_the_checkpoint_not_from_this_process():
+ tf = _tar(NESTED)
+ with tf:
+ sub, pats = A._ws_rules(tf)
+ assert sub == "workspace"
+ assert "workspace/skills/" in pats and "workspace/AGENTS.md" in pats
+ assert not any(p.startswith("#") for p in pats), "comments are not patterns"
+
+
+def test_a_marker_that_is_not_one_plain_directory_name_is_ignored():
+ # a traversal or an absolute path in the marker must not move the view
+ for bad in ("../../etc", "/etc", ".ssh", "a/b"):
+ tf = _tar({**NESTED, "./.harness/agent-subdir": bad})
+ with tf:
+ sub, _p = A._ws_rules(tf)
+ assert sub == "", bad
+
+
+def test_a_path_maps_back_into_the_tar_so_the_download_still_resolves():
+ # the listing hands out ids derived from the VISIBLE path; the reader has to find the member
+ assert A._ws_member("report.md", "workspace") == "workspace/report.md"
+ assert A._ws_member("report.md", "") == "report.md"
+ assert A._wf_path(A._wf_id("report.md")) == "report.md"
+
+
+def test_the_machinery_patterns_are_matched_the_way_git_reads_them():
+ # relative to the session dir, which is where the file lives — not to the agent's directory
+ sub, pats = "workspace", ("workspace/skills/", "workspace/AGENTS.md")
+ assert A._ws_view("workspace/skills/a/b.md", sub, pats) is None
+ assert A._ws_view("workspace/AGENTS.md", sub, pats) is None
+ assert A._ws_view("workspace/skills.md", sub, pats) == "skills.md"
diff --git a/gateway/tests/test_sandbox_retry.py b/gateway/tests/test_sandbox_retry.py
index 1e3ff92a..8466825a 100644
--- a/gateway/tests/test_sandbox_retry.py
+++ b/gateway/tests/test_sandbox_retry.py
@@ -77,3 +77,15 @@ def test_a_runner_that_never_comes_up_is_reported_with_the_tries_made(monkeypatc
out, calls, sleeps = _drive(monkeypatch, [_Resp(503, b"")], attempts=4)
assert isinstance(out, RuntimeError) and len(calls) == 4 and len(sleeps) == 3
assert "failed after 4 of 4 tries" in str(out) and "HTTP 503" in str(out)
+
+
+def test_a_runner_refusal_at_turn_start_keeps_its_status_and_its_reason(monkeypatch):
+ """The runner refused to start a turn and said why (jcode on an Anthropic connection with a
+ model its catalog does not list): the reason is what the person reads, not "No connection on
+ this account serves <model>", which is what a refusal with no status read as (2026-10-12)."""
+ why = "jcode cannot run claude-sonnet-5-5 on an Anthropic connection: its Anthropic provider runs only the models it lists"
+ out, calls, sleeps = _drive(monkeypatch, [_Resp(400, ('{"detail":"%s"}' % why).encode())])
+ assert isinstance(out, gw._SandboxRefused) and out.status == 400 and out.detail == why
+ rec = {"model": "claude-sonnet-5.5-direct",
+ "tried": [{"connection": "Anthropic", "status": out.status, "error": out.detail}]}
+ assert gw._turn_failure_message(rec) == f"The turn failed: {why}"
diff --git a/runner/nanobot_driver.py b/runner/nanobot_driver.py
new file mode 100644
index 00000000..da5f0480
--- /dev/null
+++ b/runner/nanobot_driver.py
@@ -0,0 +1,231 @@
+"""One nanobot turn, as a runner subprocess.
+
+Spawned per turn by server.py (the same one-process-per-turn contract every backend has: the runner
+reads NDJSON off stdout, cancel is a process-group kill). Inside, nanobot's own agent loop is
+DRIVEN IN PROCESS through its published Python SDK — `Nanobot.from_config(...).stream(...)`, the
+surface its docs/python-sdk.md documents — and the events it yields are re-emitted as CLAUDE'S
+stream-json, which is why this backend's normaliser in server.py is the passthrough (the
+systemone_driver precedent).
+
+WHY THE SDK AND NOT `nanobot agent -m`, measured on the pinned 0.3.5:
+
+ * The CLI prints prose. One-shot `-m` writes the final answer and a tool line to the terminal;
+ there is no JSON stream, no usage, no tool ids, so a turn record built from it could not show
+ what the agent did or what it cost.
+ * The CLI SEEDS THE WORKSPACE. Its path calls `sync_workspace_templates()`, which creates
+ AGENTS.md, SOUL.md, USER.md, HEARTBEAT.md, memory/MEMORY.md, memory/history.jsonl,
+ prompts/README.md and skills/ and then `GitStore.init()`s a git repository in the workspace.
+ Measured on a bare directory: all eight appeared. Every one of them would be handed to the user
+ as a file their task produced, and the git repo is a second one in the directory the runner's
+ checkpoint already keeps a repo in. The SDK path calls NEITHER (grepped: the function is reached
+ only from cli/, gateway_runtime and webui) — only `.nanobot/workspace-id` is created.
+ * An AGENTS.md written by the runner would have been one of those eight. The runner writes the
+ workspace contract there before the turn starts, and `sync_workspace_templates` only creates
+ files that are missing, so the contract would have survived — but only by luck of ordering.
+
+WHAT THIS DRIVER OWES THE TURN, and where each answer comes from:
+
+ * the served model and the token split — the relay's taps. nanobot reports usage itself and this
+ driver passes it on, netted (see `_usage`); the model it names is the one it was ASKED for, so
+ rule 2 is the relay's to answer, which is why the key reaches it through the ENVIRONMENT.
+ * continuity — `session_key`. nanobot keeps sessions beside its CONFIG file
+ (`get_data_dir()` is `get_config_path().parent`), so server.py puts the config under
+ .harness/nanobot/ and the conversation is checkpointed and excluded from produced files for
+ free. Verified across two separate processes with the same key.
+ * the tool policy — the SESSION's policy, not the registry. The loop filters tools per turn from
+ `session.policy.disabled_tools` AFTER the MCP provider has registered its own tools, so this is
+ the one door that covers both tool sources (the openhands lesson: built-in and MCP tools load on
+ different code paths, and a filter in front of only one of them is half a policy).
+ * a failure that reads as a failure — `run.failed`, and a `run.completed` whose RunResult carries
+ an `error` or a non-completed `stop_reason`. Both end the turn as an error with the reason.
+"""
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import json
+import os
+import sys
+import time
+
+# The NDJSON channel. nanobot logs through loguru, whose default sink is stderr, and the level is
+# raised below — but a stray print from a tool must still be unable to land inside the lines the
+# runner parses, so stdout is captured here and nothing else is allowed to write to it.
+_OUT = sys.stdout
+
+
+def _emit(ev: dict) -> None:
+ _OUT.write(json.dumps(ev, default=str) + "\n")
+ _OUT.flush()
+
+
+def _text(t: str) -> None:
+ if t:
+ _emit({"type": "assistant", "message": {"content": [{"type": "text", "text": t}]}})
+
+
+def _usage(u: object) -> dict:
+ """nanobot's LLMUsage, netted to this product's contract.
+
+ `input_tokens` is GROSS: one measured turn reported input_tokens 11107 with
+ cache_read_tokens 5503, and its two requests reported 5506 and 5601 — the cached read is a
+ SUBSET of the input, not a sibling of it. Billing charges fresh input at the input rate and the
+ cached subset at the cache-read rate, so a gross number here is the ~10x overcharge
+ _norm_token_usage's own comment describes. `cache_write_tokens` is None on an endpoint that
+ reports no write, which is why every field is read defensively rather than assumed present."""
+ if u is None:
+ return {}
+ get = (lambda k: getattr(u, k, None)) if not isinstance(u, dict) else (lambda k: u.get(k))
+
+ def n(k: str) -> int:
+ v = get(k)
+ return int(v) if isinstance(v, (int, float)) and v > 0 else 0
+
+ read, write = n("cache_read_tokens"), n("cache_write_tokens")
+ out = {"input_tokens": max(n("input_tokens") - read - write, 0),
+ "output_tokens": n("output_tokens")}
+ if read:
+ out["cache_read_tokens"] = read
+ if write:
+ out["cache_write_tokens"] = write
+ return {k: v for k, v in out.items() if v}
+
+
+def _quiet() -> None:
+ """Raise nanobot's own log level so the runner's bounded stderr tail holds the turn's real
+ failure rather than 40 lines of DEBUG. The tail is what the gateway shows when a turn fails, and
+ it keeps 80 lines: on the first probe every one of them was `Stage <x> completed in 0.2ms`."""
+ try:
+ from loguru import logger
+ logger.remove()
+ logger.add(sys.stderr, level=os.environ.get("HR_NANOBOT_LOG_LEVEL", "WARNING"))
+ except Exception: # noqa: BLE001 — logging is not worth failing a turn over
+ pass
+
+
+async def _run(job: dict) -> int:
+ from nanobot import ( # imported here so _quiet() runs before nanobot configures logging
+ STREAM_EVENT_REASONING_DELTA,
+ STREAM_EVENT_RUN_COMPLETED,
+ STREAM_EVENT_RUN_FAILED,
+ STREAM_EVENT_TEXT_DELTA,
+ STREAM_EVENT_TOOL_COMPLETED,
+ STREAM_EVENT_TOOL_FAILED,
+ STREAM_EVENT_TOOL_STARTED,
+ Nanobot,
+ )
+
+ session_key = str(job.get("session_key") or "harness")
+ prompt = str(job.get("prompt") or "")
+ disabled = sorted({str(x).split(" (")[0].strip() for x in (job.get("tools_disabled") or []) if x})
+ started = time.time()
+ final = ""
+ result_sent = False
+
+ # The process cwd is the SESSION directory, and nanobot's workspace is a directory inside it
+ # (runner/server.py, _NANOBOT_WS, with the reason). Its file tools resolve a relative path
+ # against the configured workspace, but its shell does not have to, and a tool that writes
+ # `report.md` must not land one level above the workspace the model was told it has. Agent
+ # Zero's artifact failures were exactly this — the driver left the cwd at the framework's base,
+ # so a model that passed a relative path wrote outside what the user collects — so the two are
+ # made to agree here rather than left to the tool.
+ os.chdir(job["workspace"])
+ async with Nanobot.from_config(config_path=job["config_path"],
+ workspace=job["workspace"]) as bot:
+ _emit({"type": "system", "subtype": "init", "session_id": session_key,
+ "model": str(job.get("model") or "")})
+ if disabled:
+ # The session's policy, deliberately, and NOT a filtered ToolRegistry built here: the
+ # loop re-reads `session.policy.disabled_tools` on every turn and applies it to the
+ # registry it is about to use, which by then also holds the MCP provider's tools. A
+ # registry filtered at construction would withhold the built-ins and let every MCP tool
+ # through — the exact half-policy openhands shipped. `get_or_create` returns the cached
+ # object the loop will itself fetch, so mutating it here is the same session.
+ sess = bot._loop.sessions.get_or_create(session_key) # noqa: SLF001
+ sess.policy = dataclasses.replace(sess.policy, disabled_tools=frozenset(disabled))
+ # And CHECK that it took. A tool policy that quietly fails to apply is the worst shape
+ # of this defect: the console reports the tool as off, the model is offered it anyway,
+ # and nothing anywhere says so. The policy object is upstream's, pinned by the
+ # entrypoint, so this can only fire if a release changed its type — and then the turn
+ # fails with the reason instead of running with the policy missing.
+ if frozenset(disabled) - set(getattr(sess.policy, "disabled_tools", ()) or ()):
+ raise RuntimeError(
+ "nanobot's session policy did not take the disabled tools "
+ f"({', '.join(disabled)}); refusing to run the turn with the tool policy missing")
+
+ async for ev in bot.stream(prompt, session_key=session_key):
+ t = ev.type
+ if t == STREAM_EVENT_TEXT_DELTA:
+ final += ev.delta or ""
+ _text(ev.delta or "")
+ elif t == STREAM_EVENT_REASONING_DELTA:
+ if ev.delta:
+ _emit({"type": "assistant", "message": {"content": [
+ {"type": "thinking", "thinking": ev.delta}]}})
+ elif t == STREAM_EVENT_TOOL_STARTED:
+ _emit({"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": str(ev.tool_call_id or "tool"),
+ "name": str(ev.name or "tool"),
+ "input": ev.arguments if isinstance(ev.arguments, dict) else {}}]}})
+ elif t in (STREAM_EVENT_TOOL_COMPLETED, STREAM_EVENT_TOOL_FAILED):
+ failed = t == STREAM_EVENT_TOOL_FAILED
+ meta = ev.metadata if isinstance(ev.metadata, dict) else {}
+ body = str(meta.get("detail") or meta.get("result") or ev.error or "")
+ _emit({"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": str(ev.tool_call_id or "tool"),
+ "is_error": failed, "content": body[:8000]}]}})
+ elif t == STREAM_EVENT_RUN_FAILED:
+ _emit({"type": "result", "subtype": "error", "is_error": True,
+ "result": str(ev.error or "nanobot run failed")[:1000],
+ "usage": _usage(ev.usage)})
+ result_sent = True
+ elif t == STREAM_EVENT_RUN_COMPLETED:
+ res = ev.result
+ # The RunResult's `content` is the FINAL answer on its own (measured: "DONE", not
+ # the whole turn's prose), so it is authoritative over what the deltas assembled.
+ answer = str(getattr(res, "content", "") or final)
+ err = str(getattr(res, "error", "") or "")
+ stop = str(getattr(res, "stop_reason", "") or "")
+ ok = not err and stop in ("", "completed", "stop", "end_turn")
+ ev_out = {"type": "result",
+ "subtype": "success" if ok else "error", "is_error": not ok,
+ "result": answer if ok else (err or answer),
+ "usage": _usage(getattr(res, "usage", None))}
+ if not ok and stop and not err:
+ # A stop reason that is not completion is the reason, and it is reported as
+ # one rather than silently passed off as an answer.
+ ev_out["reason"] = stop
+ _emit(ev_out)
+ result_sent = True
+ if not result_sent:
+ # The stream ended without either terminal event. That is not a success: say so, and leave
+ # the text empty so the runner's stderr tail is the reason rather than a sentence invented
+ # here (the same rule _kimi_eof follows).
+ _emit({"type": "result", "subtype": "error", "is_error": True, "result": "", "usage": {}})
+ return 1
+ return 0
+
+
+def main() -> int:
+ _quiet()
+ try:
+ job = json.loads(sys.argv[1])
+ except Exception as e: # noqa: BLE001
+ print(f"nanobot driver: bad job: {e}", file=sys.stderr)
+ return 2
+ try:
+ return asyncio.run(_run(job))
+ except KeyboardInterrupt:
+ return 130
+ except Exception as e: # noqa: BLE001
+ # The exception text is the only reason anybody will have, so it goes to stderr (which the
+ # runner collects into the turn's failure reason) AND the turn is failed explicitly, so a
+ # crashed driver never reads as a turn that completed with no answer.
+ print(f"nanobot driver: {type(e).__name__}: {e}", file=sys.stderr)
+ _emit({"type": "result", "subtype": "error", "is_error": True,
+ "result": f"{type(e).__name__}: {e}"[:1000], "usage": {}})
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/runner/server.py b/runner/server.py
index a5d7eaac..d8b97a06 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -359,6 +359,43 @@ def _agentzero_session_present(cwd: str, cmd: list[str], session_id: str) -> boo
return False
agents = doc.get("agents") if isinstance(doc, dict) else None
return bool(agents) and bool((agents[0] or {}).get("history"))
+def _opensquilla_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:
+ """Ask opensquilla's session database whether this key is in it.
+
+ It cannot be read off argv: --session-id names a FRESH session as well as continuing one (the
+ goose shape), so its presence says nothing. The store is the SQLite file the driver passes as
+ --session-db-path — a path, not a guess, because the default is `:memory:` and without an
+ explicit file there is no continuity at all. The id is a distinctive token, so the test is the
+ same shape as opencode's: the bytes of the database and of its write-ahead log, which can still
+ hold a session the previous turn wrote."""
+ base = pathlib.Path(cwd) / ".harness" / "opensquilla"
+ needle = session_id.encode()
+ for name in ("sessions.sqlite", "sessions.sqlite-wal"):
+ f = base / name
+ try:
+ if f.is_file() and needle in f.read_bytes():
+ return True
+ except OSError:
+ continue
+ return False
+
+
+def _nanobot_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:
+ """Ask nanobot's session store for the file that IS this conversation.
+
+ Not a search of bytes: nanobot names the file deterministically, so the predicate can be the
+ CLI's own. Sessions live beside the CONFIG file (get_data_dir() is get_config_path().parent),
+ under sessions/<workspace-id>/<urlsafe-b64(session_key) without padding>.jsonl. The workspace
+ id is a hash this process does not compute, so the one directory level is globbed and the
+ file name is the exact one nanobot would open."""
+ base = pathlib.Path(cwd) / ".harness" / "nanobot" / "sessions"
+ if not base.is_dir() or not session_id:
+ return False
+ name = base64.urlsafe_b64encode(session_id.encode()).decode().rstrip("=") + ".jsonl"
+ try:
+ return any((d / name).is_file() for d in base.iterdir() if d.is_dir())
+ except OSError:
+ return False
_SESSION_PRESENT = {
@@ -378,6 +415,15 @@ _SESSION_PRESENT = {
"openhands": _openhands_session_present,
"cheetahclaws": _cheetahclaws_session_present,
"agentzero": _agentzero_session_present,
+ # This batch: three builders perform the lookup themselves and carry the id in argv only when
+ # they found it (mimo's -s, gajae's -r, jcode's --resume all exit without running the model on
+ # an id their store does not hold), so argv IS the builder's conclusion. The two driver-backed
+ # bases pass the key on every turn and must ask their store.
+ "mimo": _argv_session_present,
+ "gajae": _argv_session_present,
+ "jcode": _argv_session_present,
+ "opensquilla": _opensquilla_session_present,
+ "nanobot": _nanobot_session_present,
}
@@ -397,6 +443,39 @@ def _resume_lost(backend: str, cmd: list[str], resume_session_id: str | None,
return None if probe(cwd, cmd, resume_session_id) else resume_session_id
+def _git_exclude(ws: str, patterns: list[str], why: str) -> None:
+ """Hide a backend's OWN machinery from the produced-files list, through git's own door.
+
+ `/produced` is `git status --porcelain -uall` over the session directory, so anything a CLI
+ writes into the directory the user collects is handed back as the task's deliverable. Every
+ backend but two keeps its machinery under `.harness/`, which _PRODUCED_EXCLUDE_PREFIX already
+ drops. nanobot cannot (its SkillsLoader reads `<workspace>/skills` and nothing else) and
+ opensquilla cannot (`ensure_agent_workspace` seeds SOUL.md, IDENTITY.md, USER.md and MEMORY.md
+ into its workspace unconditionally — `seed_templates` has no caller that passes False and no
+ setting reads it).
+
+ `.git/info/exclude` and NOT a .gitignore: it is per-repository, it is not a file in the
+ agent's workspace (so the agent cannot read, edit or be confused by it, and it is not itself a
+ produced file), and _git_ensure rewrites only the tracked root .gitignore, so this survives
+ every turn. It travels with the session because the checkpoint is a tar of the directory —
+ which also means these files still reach the next turn: what is hidden is the DELIVERABLES
+ list, not the session.
+
+ It excludes UNTRACKED files only, which is the case that matters: these are written on the
+ first turn, and after the first collection they are committed to the checkpoint ref and stop
+ appearing in the diff anyway."""
+ if not patterns:
+ return
+ try:
+ _git_ensure(ws) # idempotent; a fresh session may have no repo yet
+ info = pathlib.Path(ws, ".git", "info")
+ info.mkdir(parents=True, exist_ok=True)
+ (info / "exclude").write_text(
+ "\n".join([f"# written by the harness runner: {why}", *patterns, ""]))
+ except Exception: # noqa: BLE001 — a missing exclude costs noise in a list, never the turn
+ pass
+
+
def _isolate_session(ws: str) -> None:
"""Make the session directory the one place its uid can write, and make everything in it
that uid's. Allocation happens once, under a lock, from the owners of the directories that
@@ -654,6 +733,36 @@ CHECKPOINT_EXCLUDE = [*(f"./{c}" for c in _REBUILT_CACHES),
# named in kilo.json, and only the relay's placeholder at that), but a
# `kilo auth login` inside a task would, and it must not travel.
"./.harness/home/.local/share/kilo/auth.json",
+ # MiMo Code is opencode's fork and carries the same snapshot repo under its
+ # own name. _opencode_config turns snapshots off for it too; this keeps a
+ # workspace hydrated from before that from dragging one through every
+ # later checkpoint.
+ "./.harness/home/.local/share/mimocode/snapshot",
+ # gajae reads models.yml's apiKey as an env var NAME, so the file holds no
+ # credential today — but pi's models.json did until it didn't, and auth.json
+ # is written by `gjc /login`, which a task could run.
+ "./.harness/home/.gjc/agent/auth.json",
+ "./.harness/home/.gjc/agent/models.yml",
+ "./.harness/home/.gjc/agent/.env",
+ # jcode keeps provider credentials under its own home and in the per-provider
+ # env files its `provider add --api-key-stdin` writes. The runner puts the
+ # relay's per-turn placeholder in the ENVIRONMENT and writes neither, but
+ # `jcode login` / `jcode provider add` inside a task would.
+ "./.harness/home/.jcode/auth.json",
+ "./.harness/home/.jcode/credentials.json",
+ "./.harness/home/.config/jcode",
+ # opensquilla stores provider keys in its profile .env and its onboarding
+ # writes api_key straight into config.toml. The driver passes the relay
+ # placeholder in the environment instead, but `opensquilla onboard` or
+ # `configure provider` inside a task writes both.
+ "./.harness/opensquilla/.env",
+ "./.harness/opensquilla/secrets.toml",
+ # nanobot's config.json carries providers.<n>.api_key literally — it has no
+ # env-name indirection — so the file the driver writes per turn holds the
+ # turn's relay placeholder and must never ride a checkpoint tarball. Its
+ # SESSIONS live in the same directory and MUST travel, so the exclusion is
+ # the file, not the directory.
+ "./.harness/nanobot/config.json",
# Dependency/scratch dirs (any depth): re-creatable by the agent, and they
# dominate checkpoint size — a node project checkpointed 200MB+ and paid
# that again on every hydrate. The agent reinstalls when it needs them.
@@ -731,6 +840,14 @@ AIDER_DEFAULT_MODEL = os.environ.get("AIDER_DEFAULT_MODEL", "gpt-5.4")
OPENHANDS_DEFAULT_MODEL = os.environ.get("OPENHANDS_DEFAULT_MODEL", "gpt-5.4")
CHEETAHCLAWS_DEFAULT_MODEL = os.environ.get("CHEETAHCLAWS_DEFAULT_MODEL", "gpt-5.4")
AGENTZERO_DEFAULT_MODEL = os.environ.get("AGENTZERO_DEFAULT_MODEL", "gpt-5.4")
+# MiMo Code is an opencode fork (its repo root package.json is still literally "opencode"), so it
+# shares opencode's default for the same reason: multi-family through one connection.
+MIMO_DEFAULT_MODEL = os.environ.get("MIMO_DEFAULT_MODEL", "gpt-5.4")
+# Gajae-Code is pi's lineage (docs/porting-from-pi-mono.md), so it shares pi's default too.
+GAJAE_DEFAULT_MODEL = os.environ.get("GAJAE_DEFAULT_MODEL", "gpt-5.4")
+JCODE_DEFAULT_MODEL = os.environ.get("JCODE_DEFAULT_MODEL", "gpt-5.4")
+OPENSQUILLA_DEFAULT_MODEL = os.environ.get("OPENSQUILLA_DEFAULT_MODEL", "gpt-5.4")
+NANOBOT_DEFAULT_MODEL = os.environ.get("NANOBOT_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.
@@ -836,6 +953,13 @@ def _git_ensure(ws: str) -> None:
".cheetahclaws/tasks.json",
".harness/agentzero/base/usr/.env", ".harness/agentzero/base/usr/secrets.env",
*_PER_TURN_CONFIG,
+ # this batch — the same files CHECKPOINT_EXCLUDE drops from the tarball
+ ".harness/home/.gjc/agent/auth.json", ".harness/home/.gjc/agent/models.yml",
+ ".harness/home/.gjc/agent/.env",
+ ".harness/home/.jcode/auth.json", ".harness/home/.jcode/credentials.json",
+ ".harness/home/.config/jcode/",
+ ".harness/opensquilla/.env", ".harness/opensquilla/secrets.toml",
+ ".harness/nanobot/config.json",
"# harness: the CLI home is checkpointed by tar, not by this repo (see _git_ensure)",
".harness/home/",
# Agent Zero's whole base, for the #193 reason: its chat.json stores the full rendered
@@ -950,6 +1074,69 @@ def _safe_join(cwd: str, rel: str) -> pathlib.Path | None:
return p
+# nanobot is the one base whose agent workspace is a SUBDIRECTORY of the session (_NANOBOT_WS):
+# its own loader refuses a session store inside the workspace, so the session dir holds the store
+# and the agent works one level down. That makes the session's file root and the agent's cwd two
+# different directories, and everything the USER exchanges with the session goes through the
+# session root: attachments, an app's PUT (the slides kit's deck.json), the produced-files list and
+# its downloads. MEASURED on a live instance: a file written through PUT /v1/sessions/{sid}/files
+# landed at the session root and the agent answered "there is no secret.txt in the working
+# directory" — while the same test on a flat-layout base read it back. The marker is what lets the
+# file routes, which know only an identifier, find the directory the agent actually looks in.
+_AGENT_SUBDIR_MARKER = pathlib.Path(".harness", "agent-subdir")
+
+
+def _agent_subdir_set(ws: str, sub: str) -> None:
+ try:
+ m = pathlib.Path(ws) / _AGENT_SUBDIR_MARKER
+ m.parent.mkdir(parents=True, exist_ok=True)
+ m.write_text(sub)
+ except Exception: # noqa: BLE001 — without the marker _visible_root is the session dir, so the
+ pass # produced list keeps the workspace/ prefix and GET /file finds the file by
+ # its fallback: the turn still works, it just reads as it did before.
+
+
+def _visible_root(ws: str) -> str:
+ """The directory whose contents are the USER's files. The session dir for every base but one."""
+ try:
+ sub = (pathlib.Path(ws) / _AGENT_SUBDIR_MARKER).read_text().strip()
+ except OSError:
+ return ws
+ # _safe_join VALIDATES (it rejects an escape), but it also resolves symlinks, and on a mac
+ # /var is one — a resolved root does not share a prefix with the ws it came from, so the
+ # relpath below became "../../.." and nothing was stripped. The returned path is therefore
+ # built from ws as the caller spelled it.
+ if not sub or _safe_join(ws, sub) is None:
+ return ws
+ d = os.path.join(ws, sub)
+ return d if os.path.isdir(d) else ws
+
+
+def _adopt_into(ws: str, sub: str) -> None:
+ """Move user files sitting at the session root into the agent's workspace.
+
+ The write paths that run BEFORE a backend is built — a caller's attachments, and an app's PUT on
+ a session that has not had a turn yet — have no way to know a base nests its workspace, so they
+ land at the root. Rather than teach each of them, the one base that nests adopts them here, at
+ the start of every turn, which is exactly when the agent is about to look. Only the runner's own
+ entries stay behind; nothing else at the root belongs to anyone but the session."""
+ root = pathlib.Path(ws)
+ # DERIVED from the same lists /produced excludes, so "the runner's own entries" means one thing
+ # in both places: a name added to those lists is also a name this leaves at the root.
+ keep = ({".git", ".gitignore", sub} | _PRODUCED_EXCLUDE_NAMES | _NOISE_SEG
+ | {q.rstrip("/") for q in _PRODUCED_EXCLUDE_PREFIX})
+ for child in root.iterdir():
+ if child.name in keep:
+ continue
+ dest = root / sub / child.name
+ if dest.exists():
+ continue
+ try:
+ os.replace(child, dest)
+ except OSError:
+ pass
+
+
def _write_input_files(cwd: str, files: list[dict] | None) -> list[str]:
"""Write caller-attached input files (base64) into the workspace so the agent can read them."""
written: list[str] = []
@@ -1209,6 +1396,43 @@ def _write_skills(cwd: str, skills: list[dict], backend: str = "claude") -> list
# produced files and carried in the checkpoint.
rootrels = [".harness/agentzero/base/usr/skills"]
entryroot = ".harness/agentzero/base/usr/skills"
+ elif backend == "mimo":
+ # MiMo Code is opencode's fork and kept its `skills:{paths}` key, so the loader adapts to
+ # us here too — one directory, named in mimo.json.
+ rootrels = [".harness/skills"]
+ entryroot = ".harness/skills"
+ elif backend == "gajae":
+ # ~/.gjc/agent/skills/<name>/SKILL.md, the CANONICAL user location in gjc's own discovery
+ # table (docs/skills.md), with the agent dir redirected by GJC_CODING_AGENT_DIR into
+ # .harness/home/.gjc/agent (see _build_gajae). User-global for pi's reason: gjc gates
+ # project-local files behind a trust decision, and the user root loads unconditionally.
+ rootrels = [".harness/home/.gjc/agent/skills"]
+ entryroot = ".harness/home/.gjc/agent/skills"
+ elif backend == "jcode":
+ # ~/.jcode/skills/<name>/SKILL.md — jcode's GLOBAL skills root (tool/skill.rs names it
+ # first), and $HOME is already <cwd>/.harness/home, so this is both inside a loader path
+ # and inside the excluded, checkpointed tree. NOT ./.jcode/skills or ./.claude/skills,
+ # which jcode also reads: those sit in the workspace, where a skill bundle would be
+ # handed back to the user as a deliverable on every turn (goose's lesson).
+ rootrels = [".harness/home/.jcode/skills"]
+ entryroot = ".harness/home/.jcode/skills"
+ elif backend == "opensquilla":
+ # $OPENSQUILLA_STATE_DIR/skills/<name>/SKILL.md — its "managed" root (skills/__init__.py
+ # names the five sources; managed is the writable one), and the driver points the state
+ # dir at .harness/opensquilla, so this is under .harness/ like goose's.
+ rootrels = [".harness/opensquilla/skills"]
+ entryroot = ".harness/opensquilla/skills"
+ elif backend == "nanobot":
+ # <workspace>/skills/<name>/SKILL.md. This is the ONE path nanobot's loader reads for a
+ # skill that is not bundled with the package: SkillsLoader fixes `workspace_skills =
+ # workspace / "skills"` in its constructor and takes no override, and the workspace has to
+ # be the session directory or the agent's files land outside what the user collects.
+ # So unlike every other backend above, this bundle IS in the workspace and IS reported
+ # among produced files. Excluding "skills/" globally would hide a user's own folder of
+ # that name on twenty other bases, which is worse; a skill that never loads is worse
+ # still. Written down here rather than quietly: see the PR body's follow-up.
+ rootrels = [f"{_NANOBOT_WS}/skills"]
+ entryroot = f"{_NANOBOT_WS}/skills"
else:
# 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
@@ -1402,11 +1626,49 @@ _ENV_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
# arrive, `search_tool` answers "No MCP tools are available in this session", and the turn runs
# without them. Its streamable-HTTP client is fine (verified against a local server and the public
# deepwiki one, tools discovered and called), so only SSE is bridged.
+# jcode takes BOTH, because it has no remote MCP client at all: its README states "jcode
+# currently supports stdio (command-based) servers only; HTTP/SSE entries are recognized and
+# skipped with a log line" — so without the bridge every remote server a harness declares is
+# dropped in silence and the agent simply never has those tools.
_BRIDGED_TRANSPORTS = {"codex": ("sse",), "dsh": ("sse",), "goose": ("sse",), "grok": ("sse",),
- "cheetahclaws": ("http",)}
+ "cheetahclaws": ("http",), "jcode": ("http", "sse"),
+ # opensquilla's MCPServerEntry takes transport "stdio" | "sse" only, so a
+ # streamable-HTTP server has no client here either.
+ "opensquilla": ("http",)}
_MCP_BRIDGE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mcp_bridge.py")
+# A backend whose MCP client reaches a remote server fine but REFUSES one on a loopback or private
+# address. nanobot runs `validate_url_target` over every server url and drops the ones it does not
+# like with a log line of its own, so the server is simply absent from the model's tools and nothing
+# reaches the turn record as a refusal. MEASURED by the browser column (2026-10-10): the `plugs`
+# server, which is how every base gets the browser tools, is injected at
+# http://127.0.0.1:8080/v1/mcp/plugs — nanobot was the one base of four that made NO browser call,
+# twice, and said "I don't currently have the browser toolset available in this session" while its
+# config held the server correctly at tools.mcpServers.plugs.
+#
+# The bridge is the fix rather than nanobot's own `tools.ssrf_whitelist`: that list is applied
+# GLOBALLY by its config loader, so whitelisting the loopback range to let the product's own server
+# through would also let the AGENT's fetch tools reach anything on loopback — the exact thing that
+# guard is there to stop. Bridged, there is no url for nanobot to validate: the runner speaks to the
+# server and the agent sees a stdio command. Its own remote client keeps handling PUBLIC servers,
+# which is measured (the deepwiki server over streamable HTTP and SSE, both columns).
+_BRIDGE_LOOPBACK_BACKENDS = {"nanobot"}
+_LOOPBACK_HOSTS = ("localhost", "127.", "::1", "0.0.0.0", "169.254.", "10.", "192.168.")
+
+
+def _mcp_url_is_loopback(url: str) -> bool:
+ """Whether this server's url names a loopback, link-local or private host."""
+ host = urllib.parse.urlsplit(url).hostname or ""
+ host = host.strip("[]").lower()
+ if host.startswith("172."):
+ try: # 172.16.0.0/12, and no other 172.
+ return 16 <= int(host.split(".")[1]) <= 31
+ except (IndexError, ValueError):
+ return False
+ return host == "localhost" or host.endswith(".localhost") or host.startswith(_LOOPBACK_HOSTS)
+
+
def _sse_bridges(cwd: str, servers: list[dict] | None, backend: str) -> list[dict]:
"""Each remote server whose transport this backend's client cannot reach becomes a stdio
launcher that runs the bridge with the url, the transport and the headers in its environment
@@ -1414,14 +1676,15 @@ def _sse_bridges(cwd: str, servers: list[dict] | None, backend: str) -> list[dic
without a transport is streamable HTTP, as everywhere else in this file. Other servers and
backends pass untouched."""
bridged = _BRIDGED_TRANSPORTS.get(backend)
- if not bridged:
+ loopback_only = backend in _BRIDGE_LOOPBACK_BACKENDS
+ if not bridged and not loopback_only:
return list(servers or [])
out: list[dict] = []
for s in servers or []:
s = s or {}
url = str(s.get("url") or "").strip()
transport = str(s.get("transport") or "http").lower()
- if not url or transport not in bridged:
+ if not url or not (transport in (bridged or ()) or (loopback_only and _mcp_url_is_loopback(url))):
out.append(s)
continue
name = _mcp_name(str(s.get("name") or s.get("id") or "mcp"))
@@ -1543,6 +1806,10 @@ def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:
Getting this wrong is silent: the file is written either way, and a backend that does not read
the name we chose simply never sees the harness's instructions."""
+ if backend == "nanobot":
+ # The one base whose agent workspace is a subdirectory of the session (see _NANOBOT_WS):
+ # the file has to be where THAT workspace is, or it is written and never read.
+ return pathlib.Path(cwd) / _NANOBOT_WS / "AGENTS.md"
if backend == "qwen":
return pathlib.Path(cwd) / "QWEN.md" # qwen-code's own context file (bundle default)
if backend == "gemini":
@@ -1574,8 +1841,22 @@ def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:
# grok loads AGENTS.md (and CLAUDE.md, AGENT.md …) at every level from the repo root down to
# the cwd, once the folder is trusted; _build_grok sets GROK_FOLDER_TRUST=0. Verified on
# 1.0.41: a token written in AGENTS.md was in the model request.
+ # The five added in this batch all read AGENTS.md from the project root, each verified
+ # against the pinned build rather than the docs:
+ # mimo — opencode's instruction-context loader, unchanged in the fork
+ # gajae — discovery/agents-md.ts, "Discovers standalone AGENTS.md files by walking
+ # up from cwd", plus ~/.gjc/agent/AGENTS.md (system-prompt.ts)
+ # jcode — jcode-base/src/prompt.rs load_agents_md_files_from_dirs, which labels it
+ # "Project Instructions (AGENTS.md)"; no CLAUDE.md branch, despite the
+ # repo shipping one of its own
+ # opensquilla — its clean-room flag is literally --stateless-keep-project-rules,
+ # "keep AGENTS.md project rules only"
+ # nanobot — its own workspace template set writes AGENTS.md, so that is the name its
+ # context builder reads
"AGENTS.md" if backend in ("codex", "hermes", "pi", "dsh", "opencode", "cline", "omp",
- "goose", "kimi", "aider", "openhands", "kilo", "grok", "agentzero")
+ "goose", "kimi", "aider", "openhands", "kilo", "grok",
+ "agentzero",
+ "mimo", "gajae", "jcode", "opensquilla", "nanobot")
else "CLAUDE.md")
@@ -3166,6 +3447,218 @@ def _build_omp(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env
return cmd
+# ── gajae-code (Yeachan-Heo/gajae-code, binary `gjc`) ─────────────────────────────────────────
+# Pi's lineage, ported to its own tree (docs/porting-from-pi-mono.md; its npm dependency set still
+# carries `pi-ai`, and `$pickenv("GJC_TIMING", "PI_TIMING")` reads pi's env names as fallbacks).
+# Measured on the pinned 0.18.5 binary (2026-10-02), `gjc -p --mode json` emits pi's event stream
+# with pi's field names — session{id} / message_update{assistantMessageEvent} / message_end{message}
+# / tool_execution_start{toolCallId,toolName,args} / tool_execution_end{toolCallId,result,isError} /
+# agent_end — and every assistant message_end carries `model` and
+# `usage:{input,output,cacheRead,cacheWrite}`. So it reads through _pi_to_claude, as omp does,
+# rather than carrying a copy of it; _gajae_to_claude adds only the one event pi has no branch for.
+#
+# WHAT IS NOT PI:
+# * no --approve / --auto-approve flag exists, and none is needed: print mode runs tools
+# unattended (measured — it wrote a file with nothing attached to approve).
+# * the tool switch is an ALLOWLIST (--tools a,b,c) like omp's, not pi's --exclude-tools.
+# * resume is `-r <id>` against a session DIRECTORY (--session-dir), and a missing id exits
+# without running the model, printing plain text `Session "<id>" not found.` — so the lookup
+# happens here and -r is added only when the file is present.
+# * the agent dir is GJC_CODING_AGENT_DIR and the custom-provider file is models.yml.
+GAJAE_PROVIDERS = {"anthropic", "openai", "azure", "openrouter", "tokenrouter", "openai-api"}
+
+# gjc reads `providers.<n>.apiKey` as the NAME of an environment variable, so the credential is
+# named in models.yml and never written into it (the same discipline as opencode's `{env:VAR}`).
+_GAJAE_KEY_ENV = "HR_GAJAE_KEY"
+
+# Every tool id gjc 0.18.5 registers, read off tools/descriptors.ts's `names` table plus the three
+# hidden ones, and not off `--help`, whose list is stale (it advertises a `notebook` tool this build
+# does not have). An unknown name on --tools is a WARNING and is dropped (cli/args.ts filters
+# against BUILTIN_TOOLS before the agent sees it), so unlike omp a drifted list cannot kill a turn —
+# it can only make the allowlist narrower than intended, which is why the list is pinned by a test.
+# `computer` is macOS-arm64 only and is therefore never present in the image.
+ALL_GAJAE_TOOLS = {
+ "read", "bash", "edit", "ast_grep", "ast_edit", "render_mermaid", "ask", "debug", "bisect",
+ "eval", "python", "calc", "ssh", "github", "find", "search", "lsp", "browser", "checkpoint",
+ "rewind", "task", "subagent", "job", "monitor", "cron", "recipe", "irc", "todo_write",
+ "web_search", "search_tool_bm25", "skill_discovery", "telegram_send", "write", "skill", "goal",
+ "move_session",
+}
+
+
+def _gajae_has_session(session_dir: pathlib.Path, session_id: str) -> bool:
+ """Is this session in this workspace's session directory?
+
+ gjc names its files `<ISO timestamp>_<id>.jsonl` (measured), so the id is matched inside the
+ name rather than as the whole of it. Without this check `-r` on an id the directory does not
+ hold exits before the first event and prints only prose, which would read to the runner as a
+ turn that produced nothing."""
+ if not session_id or not session_dir.is_dir():
+ return False
+ try:
+ return any(p.is_file() for p in session_dir.rglob(f"*{session_id}*.jsonl"))
+ except OSError:
+ return False
+
+
+def _gajae_write_mcp(hdir: pathlib.Path, servers: list[dict] | None) -> str:
+ """Write the file `gjc --mcp-config` takes ("Tools-only MCP config file (absolute path)") and
+ return its path, or "" when there is nothing to write.
+
+ Standard mcpServers schema. The file goes under .harness/ rather than into the agent dir
+ because --mcp-config names it explicitly, and --no-mcp is passed beside it so the CONVENTIONAL
+ locations (the agent dir's mcp.json and the project's .gjc/mcp.json) are not also loaded: the
+ project one is a file in the workspace, which a task could write and the next turn would
+ execute — the hole pi closes with --no-extensions and opencode with --pure."""
+ entries: dict = {}
+ for i, sv in enumerate(servers or []):
+ if not isinstance(sv, dict):
+ continue
+ name = _mcp_name(sv.get("name") or sv.get("id") or f"server{i}")
+ url = (sv.get("url") or "").strip()
+ if url:
+ entry: dict = {"type": "sse" if str(sv.get("transport") or "").lower() == "sse" else "http",
+ "url": url}
+ if _mcp_headers(sv):
+ entry["headers"] = _mcp_headers(sv)
+ elif sv.get("command"):
+ entry = {"type": "stdio", "command": str(sv["command"]),
+ "args": [str(a) for a in (sv.get("args") or [])]}
+ else:
+ continue
+ entries[name] = entry
+ if not entries:
+ return ""
+ hdir.mkdir(parents=True, exist_ok=True)
+ path = hdir / "gajae-mcp.json"
+ path.write_text(json.dumps({"mcpServers": entries}, indent=2))
+ return str(path)
+
+
+def _gajae_to_claude(obj: dict, state: dict) -> list[dict]:
+ """gjc's `--mode json` stream is pi's, so this delegates to _pi_to_claude for every event pi
+ knows and handles only the one it does not.
+
+ `agent_failed` is gjc's own: print-mode.ts writes `{"type":"agent_failed","error":<diagnostic>}`
+ when the run's terminal disposition is a failure that no assistant message_end already reported
+ (an empty turn among them). Without a branch for it that turn reads as a completed turn whose
+ answer is whatever text came before — the failure-reported-as-prose shape _CLAUDE_ERR_RE and
+ _GOOSE_ERR_RE exist for. The error becomes the turn's reason and is NOT rendered as the answer.
+ pi and omp may emit the same event (it is in their shared AgentEvent union); this is NOT added
+ to _pi_to_claude because it has not been measured on either of those builds, and a normaliser
+ changed on an unmeasured assumption is how the last three of these went wrong."""
+ if obj.get("type") == "agent_failed":
+ err = obj.get("error")
+ if isinstance(err, dict):
+ text = str(err.get("message") or err.get("code") or "gajae agent failed")
+ else:
+ text = str(err or "gajae agent failed")
+ state["_pi_error"] = text[:500]
+ return []
+ return _pi_to_claude(obj, state)
+
+
+def _build_gajae(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,
+ resume_session_id: str | None = None, mcp_servers: list[dict] | None = None,
+ tools_disabled: list[str] | None = None, vision: bool = True) -> list[str]:
+ pr = provider or "anthropic"
+ if pr not in GAJAE_PROVIDERS:
+ raise HTTPException(400, f"unknown gajae provider '{pr}' (one of {sorted(GAJAE_PROVIDERS)})")
+ home = pathlib.Path(env.get("HOME") or cwd)
+ agent_dir = home / ".gjc" / "agent"
+ agent_dir.mkdir(parents=True, exist_ok=True)
+ env["GJC_CODING_AGENT_DIR"] = str(agent_dir)
+ # The signed model-preset registry is an HTTPS fetch at start-up that can rewrite which model a
+ # preset names. The harness names one model explicitly and must get that model, so the registry
+ # is off: a catalog fetched at run time is exactly the substitution surface matrix rule 2 is
+ # about, and the sandbox should not reach out for it either.
+ env["GJC_MODEL_PRESET_REGISTRY_DISABLED"] = "1"
+
+ use_custom = bool(auth.base_url) or pr in ("azure", "openai-api", "tokenrouter")
+ if use_custom:
+ if not auth.base_url:
+ raise HTTPException(400, f"gajae provider '{pr}' needs a base_url (none configured)")
+ if auth.api_format == "anthropic":
+ api = "anthropic-messages"
+ elif auth.api_format == "openai":
+ api = "openai-completions"
+ elif pr == "anthropic" or (pr == "tokenrouter" and _PI_CLAUDE_MODEL.search(model or "")):
+ api = "anthropic-messages"
+ elif pr == "azure" or _HERMES_RESPONSES_API_MODEL.search(model or ""):
+ api = "openai-responses"
+ else:
+ api = "openai-completions"
+ if api in ("openai-completions", "openai-responses") and auth.api_key and not auth.api_format:
+ # The relay, for pi's reasons, plus one of its own: the key would otherwise be written
+ # literally into models.yml, which lives under the checkpointed workspace.
+ 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})
+ # gjc resolves `apiKey` as the NAME of an environment variable (resolveApiKeyConfig), so the
+ # credential is named here and read from the environment — hermes's `key_env` discipline,
+ # and the reason models.yml can be in the workspace at all. It is still excluded from the
+ # checkpoint beside pi's and omp's, because a future build reading it as a literal must not
+ # turn this file into a leak.
+ env[_GAJAE_KEY_ENV] = auth.api_key or ""
+ base = (auth.base_url or "").rstrip("/")
+ if api == "anthropic-messages":
+ base = base.removesuffix("/v1")
+ elif not auth.api_format and not base.endswith("/v1"):
+ base += "/v1"
+ (agent_dir / "models.yml").write_text(json.dumps({"providers": {"hr": {
+ "baseUrl": base, "api": api, "apiKey": _GAJAE_KEY_ENV,
+ "models": [{"id": model, "name": model, "reasoning": False,
+ "input": ["text", "image"] if vision else ["text"],
+ "contextWindow": 200000, "maxTokens": 32000}],
+ }}}, indent=2))
+ pname = "hr"
+ else:
+ pname = pr
+ if pr == "anthropic" and auth.api_key:
+ env["ANTHROPIC_API_KEY"] = auth.api_key
+ elif pr == "openai" and auth.api_key:
+ env["OPENAI_API_KEY"] = auth.api_key
+
+ session_dir = pathlib.Path(cwd, ".harness", "gajae-sessions")
+ session_dir.mkdir(parents=True, exist_ok=True)
+ cmd = ["gjc", "-p", "--mode", "json",
+ # --model takes a FUZZY pattern. The id is given fully qualified so the exact entry
+ # wins: a custom provider also gets auto-enabled /v1/models discovery (model-registry.ts
+ # ~2976 adds `discovery:{type:"openai-models-list"}` to any custom OpenAI-family
+ # provider, optional so a relay that answers 404 degrades to the static model), and a
+ # bare family name among 300 discovered ids is a substitution waiting to happen.
+ "--model", f"{pname}/{model}" if pname == "hr" else model,
+ # Session storage AND lookup, inside .harness/ so the transcript is checkpointed and
+ # never handed back as a produced file.
+ "--session-dir", str(session_dir),
+ # Rules discovery stays ON: AGENTS.md is how the workspace contract reaches the model.
+ # What is off is everything that executes or fetches something the workspace could have
+ # planted — see --no-mcp below and the preset registry above.
+ "--no-mcp",
+ # Title generation is a second model call per turn for a string nothing here reads.
+ "--no-title",
+ # No LSP server to talk to in the sandbox, and it is a per-turn start-up cost.
+ "--no-lsp"]
+ mcp_path = _gajae_write_mcp(pathlib.Path(cwd, ".harness"), mcp_servers)
+ if mcp_path:
+ cmd += ["--mcp-config", mcp_path]
+ if resume_session_id and _gajae_has_session(session_dir, resume_session_id):
+ cmd += ["-r", resume_session_id]
+ elif resume_session_id:
+ print(f"[resume] gajae: session {resume_session_id} not in this workspace — starting fresh",
+ flush=True)
+ if tools_disabled:
+ disabled = {x.split(" (")[0].strip().lower() for x in tools_disabled if x and x.strip()}
+ enabled = [t for t in sorted(ALL_GAJAE_TOOLS) if t not in disabled]
+ if len(enabled) == len(ALL_GAJAE_TOOLS):
+ pass # named nothing this runtime has: an allowlist that removes nothing is not sent
+ elif not enabled:
+ cmd += ["--no-tools"]
+ else:
+ cmd += [f"--tools={','.join(enabled)}"]
+ cmd.append(prompt)
+ return cmd
+
+
# ── hermes (NousResearch hermes-agent CLI) ──────────────────────────────────────────
# One-shot turns run `hermes -z` (auto-approves, prints ONLY the final text on stdout, writes a
# JSON usage report via --usage-file); follow-up turns run `hermes chat -q -r <sid>` because the
@@ -3710,6 +4203,34 @@ def _request_stream_usage(body: bytes) -> bytes:
return body
+_OPENAI_STREAM_HOSTS = ("api.openai.com", ".openai.azure.com", ".cognitiveservices.azure.com")
+
+
+def _without_stream_obfuscation(body: bytes, base: str) -> bytes:
+ """Ask OpenAI or Azure for a stream without its `obfuscation` padding, on a body that already
+ asks for the usage chunk.
+
+ OpenAI pads every streamed chunk with an `obfuscation` field, the usage trailer included, and
+ opensquilla 0.5.6 accepts after `finish_reason` only a chunk whose keys it knows: a turn that had
+ already answered failed with "The model provider returned an invalid response" (invalid_stream_
+ order) on every OpenAI and Azure model the review instance has (gpt-5.5, gpt-5.4-mini, gpt-5.2,
+ 2026-10-12), while the same models through an aggregator that drops the field passed. Only that
+ route asks for this; the padding stays on every other client's stream. A provider that refuses
+ the field meets the relay's one-time retry without stream_options."""
+ host = (urllib.parse.urlsplit(base).hostname or "").lower()
+ if not (host == _OPENAI_STREAM_HOSTS[0] or host.endswith(_OPENAI_STREAM_HOSTS[1:])):
+ return body
+ try:
+ obj = json.loads(body)
+ so = obj.get("stream_options") if isinstance(obj, dict) else None
+ if obj.get("stream") is True and isinstance(so, dict) and "include_obfuscation" not in so:
+ obj["stream_options"] = {**so, "include_obfuscation": False}
+ return json.dumps(obj, separators=(",", ":")).encode()
+ except Exception: # noqa: BLE001 — a body we cannot parse is a body we must not alter
+ pass
+ return body
+
+
def _rename_max_tokens(body: bytes) -> bytes:
"""max_tokens -> max_completion_tokens in one chat-completions body.
@@ -3819,6 +4340,23 @@ def _google_unknown_field(refused: bytes) -> str:
return m.group(1) if m else ""
+_DEPRECATED_FIELD_RE = re.compile(r"`([A-Za-z_][A-Za-z0-9_]*)` is deprecated for this model")
+
+
+def _refused_top_level_field(refused: bytes) -> str:
+ """A top-level request field a provider refused by name, or "": Google's unknown field, or a
+ field Anthropic's OpenAI-compatible surface calls deprecated for the model ("`temperature` is
+ deprecated for this model.": nanobot on claude-sonnet-5.5 through a direct Anthropic connection,
+ 2026-10-12, every turn). A deprecated field is one the model no longer takes, so dropping it
+ changes nothing the model would have used."""
+ name = _google_unknown_field(refused)
+ if name:
+ return name
+ text = refused.decode("utf-8", "replace") if isinstance(refused, (bytes, bytearray)) else str(refused)
+ m = _DEPRECATED_FIELD_RE.search(text)
+ return m.group(1) if m else ""
+
+
# Gemini 3 requires each replayed tool call's thought signature: Google's OpenAI-compatible endpoint
# streams it on every function call (tool_calls[].extra_content.google.thought_signature) and refuses
# the next request without it, 400 "Function call is missing a thought_signature in functionCall
@@ -3840,6 +4378,19 @@ _STRICT_GEMINI_HOSTS = tuple(h for h in (
urllib.parse.urlsplit(os.environ.get("HR_HOSTED_BASE", "https://api.harnessrouter.ai")).netloc) if h)
+# A channel+model whose validator has already refused this process's tool declarations. Each turn
+# gets its OWN relay route, so a flag on the route is forgotten at the next turn and every turn pays
+# one refused round trip (measured: four turns, four refusals). This remembers it for the runner's
+# life instead, keyed by the upstream host and the model, which is as wide as the evidence goes — a
+# different model on the same channel may well be served by something that does not validate this
+# way, and the normalisation flattens anyOf, so it is not applied on a guess.
+_GEMINI_SCHEMA_SEEN: set[tuple[str, str]] = set()
+
+
+def _gemini_schema_key(base: str, model: str) -> tuple[str, str]:
+ return (urllib.parse.urlsplit(base).netloc, str(model or "").lower())
+
+
def _gemini_channel(base: str) -> bool:
"""Whether `base` is a provider that serves Google's native API under its own root."""
return any(h in base for h in _STRICT_GEMINI_HOSTS)
@@ -3848,11 +4399,14 @@ def _gemini_channel(base: str) -> bool:
# description, nullable, enum, properties, required, items, min/max, anyOf and a few more) and
# refuses anything else: "Unknown name \"$schema\" at 'tools[0].function_declarations[0].parameters'",
# "Unknown name \"exclusiveMinimum\"", "schema didn't specify the schema type field". Google's own
-# OpenAI-compatible endpoint, OpenRouter and Vercel normalise a harness's JSON-schema declarations
-# before they reach it; TokenRouter's Gemini channels forward them as sent, so the first turn of a
+# OpenAI-compatible endpoint, OpenRouter and Vercel normalise MOST of a harness's JSON-schema
+# declarations — but not all: measured on Vercel 2026-10-07, an optional array parameter
+# (`anyOf: [array, null]`, no `items`) reached Google as sent and was refused, which is why the retry
+# loop applies this on ANY channel once that channel's validator has named the problem.
+# TokenRouter's Gemini channels forward them as sent from the start, so the first turn of a
# task on opencode ($schema) and cline (exclusiveMinimum, a property without type) failed on the
# ids those channels serve natively, gemini-3.8-flash for one (measured 2026-09-06, the platform
-# column). Until TokenRouter normalises them itself, this relay does, for that channel only.
+# column). Until TokenRouter normalises them itself, this relay does, proactively for it.
_GEMINI_SCHEMA_KEYS = {"type", "format", "title", "description", "nullable", "enum", "maxItems", "minItems",
"properties", "required", "minProperties", "maxProperties", "minLength", "maxLength",
"pattern", "example", "anyOf", "propertyOrdering", "default", "items", "minimum", "maximum"}
@@ -4488,6 +5042,8 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
body = _with_free_form_objects(body) # before the Gemini normaliser below, which has its own rules
if flags.get("stream_usage"):
body = _request_stream_usage(body)
+ if flags.get("plain_stream"):
+ body = _without_stream_obfuscation(body, base)
if flags.get("rename_max_tokens"):
body = _rename_max_tokens(body)
if flags.get("stringify_tool_content"):
@@ -4516,10 +5072,14 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
if google and body is not None and self.path.endswith("/chat/completions"):
body = _google_with_signatures(body, flags.setdefault("google_sigs", {}))
headers["content-length"] = str(len(body))
- if ((_gemini_channel(base) or flags.get("gemini_schemas")) and "gemini" in str(_body_model).lower()
+ if ((((_gemini_channel(base) or flags.get("gemini_schemas"))
+ and "gemini" in str(_body_model).lower())
+ or _gemini_schema_key(base, _body_model) in _GEMINI_SCHEMA_SEEN)
and body is not None and self.path.endswith("/chat/completions")):
# TokenRouter's Gemini channels hand a harness's JSON-schema tool declarations to Google's
- # validator as sent; the broker does the same normalisation for brokered traffic
+ # validator as sent; the broker does the same normalisation for brokered traffic. The flag
+ # carries the same repair on a channel this did not expect to need it, once that channel's
+ # own validator has named the problem (below).
body = _with_gemini_schemas(body)
headers["content-length"] = str(len(body))
if body is not None:
@@ -4655,14 +5215,18 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
body = flat
headers["content-length"] = str(len(body))
continue
- if e.code in (400, 422):
- # The provider's own words, kept here for every provider: a harness shows a
- # refusal as "400 (no body)" (Gemini CLI) or cuts it to a few dozen characters
- # (CheetahClaws), and a matrix row that fails must carry the reproduced text
- # (docs/harness-verification.md). A llama-3.3-70b turn on a compacted history
- # was refused as "malformed" on 2026-09-27 with the reason cut off.
- print(f"[relay] {'google' if google else 'provider'} refused {tail} model={_body_model} "
- f"status={e.code}: {data[:300]!r}", flush=True)
+ # The provider's own words, kept here for EVERY provider and every status: a
+ # harness shows a refusal as "400 (no body)" (Gemini CLI) or cuts it to a few
+ # dozen characters (CheetahClaws), and a matrix row that fails must carry the
+ # reproduced text (docs/harness-verification.md). A llama-3.3-70b turn on a
+ # compacted history was refused as "malformed" on 2026-09-27 with the reason cut
+ # off. This was 400 and 422 only, which is why a repeatable grok failure on
+ # opensquilla (2026-10-10) left nothing to read: its own code falls back to "The
+ # model provider request failed." when the terminal event carries no message, so
+ # the provider's status and body were the only account of it that existed, and
+ # at 429 or 503 this did not print them.
+ print(f"[relay] {'google' if google else 'provider'} refused {tail} model={_body_model} "
+ f"status={e.code}: {data[:300]!r}", flush=True)
if (attempt < 2 and e.code == 400 and b"thought_signature" in data
and not flags.get("thought_signature") and body is not None):
# a Gemini 3 endpoint this relay did not recognise as Google names the need itself
@@ -4671,7 +5235,30 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
body = _google_with_signatures(body, flags.setdefault("google_sigs", {}))
headers["content-length"] = str(len(body))
continue
- unknown = _google_unknown_field(data) if e.code == 400 else ""
+ if (attempt < 2 and e.code == 400 and b"function_declarations" in data
+ and not flags.get("gemini_schemas") and body is not None
+ and self.path.endswith("/chat/completions")):
+ # Google's validator refused OUR tool declarations through a channel this relay
+ # did not think needed normalising. MEASURED on Vercel (2026-10-07, the batch-3
+ # nanobot column): "function_declarations[14].parameters.properties[args].items:
+ # field predicate failed: $type == Type.ARRAY" and "…any_of[0].items: missing
+ # field" — an optional array parameter, passed through to Google as sent. The
+ # comment above _GEMINI_SCHEMA_KEYS said Vercel normalises these before they
+ # reach Google; for this shape it does not, and one of eight models was dead on
+ # its FIRST turn with nothing in the harness's own log to read.
+ # Reactive rather than proactive on purpose: the normaliser flattens anyOf, which
+ # loses information a channel that handles it faithfully would have kept. It is
+ # applied only after that channel has refused, and then for the rest of the route.
+ fixed = _with_gemini_schemas(body)
+ if fixed != body:
+ flags["gemini_schemas"] = True
+ _GEMINI_SCHEMA_SEEN.add(_gemini_schema_key(base, _body_model))
+ body = fixed
+ headers["content-length"] = str(len(body))
+ print("[relay] provider's validator refused the harness's tool declarations; "
+ "normalised them for Google's schema and sent again", flush=True)
+ continue
+ unknown = _refused_top_level_field(data) if e.code == 400 else ""
dropped = _drop_top_level_field(body, unknown) if (unknown and body is not None) else None
if attempt < 2 and dropped is not None and dropped != body:
# Google's OpenAI-compatible endpoint refuses any field it does not know (pi and
@@ -4742,6 +5329,7 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
self.send_header("transfer-encoding", "chunked")
self.end_headers()
pending = b""
+ line_state: dict = {} # what the per-line rewrite has seen of this stream so far
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
@@ -4818,11 +5406,11 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
pending += chunk
# a route that rewrites usage forwards whole lines (as rewritten) instead of the
# raw read, so a rewrite never straddles two reads
- out_lines = [] if flags.get("usage_no_nulls") else None
+ out_lines = [] if (flags.get("usage_no_nulls") or flags.get("plain_stream")) else None
while b"\n" in pending:
line, pending = pending.split(b"\n", 1)
if out_lines is not None:
- out_lines.append(_usage_without_nulls(line) + b"\n")
+ out_lines.append(_rewrite_stream_line(line, flags, line_state) + b"\n")
line = line.strip()
if line and not line.startswith(b":"):
last_event = time.monotonic() # an event's line; a comment is not one
@@ -4848,8 +5436,8 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
call_usage.update(_usage_in_sse_line(pending.strip()))
seen_thinking = _thinking_in_sse_line(pending.strip())
_stream_fold(flags, call_usage, seen_thinking if seen_thinking is not None else call_thinking, folded)
- if flags.get("usage_no_nulls") and pending:
- tail_bytes = _usage_without_nulls(pending) # a last line with no newline after it
+ if (flags.get("usage_no_nulls") or flags.get("plain_stream")) and pending:
+ tail_bytes = _rewrite_stream_line(pending, flags, line_state) # a last line with no newline after it
self.wfile.write(f"{len(tail_bytes):x}\r\n".encode() + tail_bytes + b"\r\n")
self.wfile.write(b"0\r\n\r\n")
else:
@@ -5071,6 +5659,50 @@ HR_RELAY_UPSTREAM_TIMEOUT_S = _relay_upstream_timeout()
_USAGE_NULL_COUNT = re.compile(rb'("[a-z_]*_tokens"\s*:\s*)null')
+_TRAILER_KEYS = ("id", "object", "created", "model", "system_fingerprint", "service_tier", "usage")
+
+
+def _plain_trailer_line(line: bytes, state: dict) -> bytes:
+ """One SSE line for a client that accepts nothing after a finished choice but a bare usage
+ chunk (opensquilla 0.5.6: any other key, or any choice, there fails a turn that has already
+ answered). Every provider ends differently, measured 2026-10-12: OpenAI pads the usage trailer
+ with `obfuscation`, Azure adds `latency_checkpoint` and `routing`, OpenRouter repeats a no-op
+ choice with a `provider` key. Once a choice has finished, each later chunk is rewritten to the
+ keys of OpenAI's own trailer with no choice, or dropped when it carries no usage. Nothing after
+ a finished choice is an answer, and the usage is kept (the relay counts it from the line as it
+ came)."""
+ raw = line.strip()
+ if not raw.startswith(b"data:"):
+ return line
+ payload = raw[5:].strip()
+ if not payload.startswith(b"{"):
+ return line
+ try:
+ obj = json.loads(payload)
+ except ValueError:
+ return line
+ if not isinstance(obj, dict):
+ return line
+ if state.get("finished"):
+ if not isinstance(obj.get("usage"), dict):
+ return b"" # an empty line: nothing for the client to read
+ kept = {k: obj[k] for k in _TRAILER_KEYS if k in obj and obj[k] is not None}
+ kept["choices"] = []
+ return b"data: " + json.dumps(kept, separators=(",", ":")).encode()
+ choices = obj.get("choices")
+ if isinstance(choices, list) and any(isinstance(c, dict) and c.get("finish_reason") for c in choices):
+ state["finished"] = True
+ return line
+
+
+def _rewrite_stream_line(line: bytes, flags: dict, state: dict) -> bytes:
+ if flags.get("usage_no_nulls"):
+ line = _usage_without_nulls(line)
+ if flags.get("plain_stream"):
+ line = _plain_trailer_line(line, state)
+ return line
+
+
def _usage_without_nulls(line: bytes) -> bytes:
"""One answer line (an SSE event or a whole body) with every null token count inside its usage
written as 0. Moonshot's kimi-k3 through TokenRouter ends a stream with
@@ -5115,7 +5747,7 @@ def _gemini_relay_route(host_root: str, api_key: str, model: str = "", native_mo
def _hermes_relay_route(base_url: str, api_key: str, drop_fields: tuple[str, ...] = (),
stream_usage: bool = False, gemini_schemas: bool = False,
usage_no_nulls: bool = False, exact_base: bool = False,
- aux: bool = False) -> tuple[str, str]:
+ aux: bool = False, plain_stream: bool = False) -> tuple[str, str]:
"""Register one turn's upstream; → (relay base_url, placeholder bearer for the CLI).
`drop_fields` names top-level request fields this route's client sends on its own initiative and
@@ -5144,7 +5776,8 @@ def _hermes_relay_route(base_url: str, api_key: str, drop_fields: tuple[str, ...
upstream = (base_url or "").rstrip("/") if exact_base else _relay_base_with_version(base_url)
flags = {"rename_max_tokens": False, "drop_fields": tuple(drop_fields),
"stream_usage": bool(stream_usage), "gemini_schemas": bool(gemini_schemas),
- "usage_no_nulls": bool(usage_no_nulls), **({} if aux else _turn_effort())}
+ "usage_no_nulls": bool(usage_no_nulls), "plain_stream": bool(plain_stream),
+ **({} if aux else _turn_effort())}
_HERMES_RELAY["routes"][tok] = (upstream, api_key, flags if aux else _turn_route(flags))
return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok
@@ -6734,10 +7367,17 @@ def _opencode_npm(auth: Auth, model: str, pr: str) -> str:
def _opencode_config(auth: Auth, model: str, cwd: str, mcp_servers: list[dict] | None,
skills_dir: str | None, tools_disabled: list[str] | None = None,
- pr: str = "") -> str:
- """Write <cwd>/opencode.json and return the provider-qualified model id for --model."""
+ pr: str = "", backend: str = "opencode", key_env: str = "",
+ npm: str = "") -> str:
+ """Write <cwd>/.harness/<backend>.json and return the provider-qualified model id for --model.
+
+ `backend`/`key_env` exist for MiMo Code, which is an opencode FORK and reads the same config
+ schema (measured on @mimo-ai/cli 0.1.15: provider.<n>.{npm,options,models}, mcp, permission,
+ skills:{paths,urls}, snapshot — its own Effect schema, same keys) from its own env var. The
+ file name differs so two backends in one workspace cannot overwrite each other's config."""
+ key_env = key_env or _OPENCODE_KEY_ENV
if not auth.base_url:
- raise HTTPException(400, "opencode needs a base_url (none configured)")
+ raise HTTPException(400, f"{backend} needs a base_url (none configured)")
# Which ai-sdk package serves this turn. A turn runs exactly ONE model, so this is decided per
# turn at provider level rather than per model entry — opencode resolves
# `model.provider?.npm ?? provider.npm ?? "@ai-sdk/openai-compatible"`, so the provider-level
@@ -6748,7 +7388,10 @@ def _opencode_config(auth: Auth, model: str, cwd: str, mcp_servers: list[dict] |
# chat/completions, and sending it to the openai-compatible package fails at the first call.
# When api_format is set (custom integration), the user's explicit choice wins over any
# model-family heuristic — the endpoint is the one they told us to reach.
- npm = _opencode_npm(auth, model, pr)
+ # `npm` lets a caller decide the package itself: mimo does, because opencode's choice sends
+ # an aggregator's claude id down the Messages shape and off the relay, where nothing can
+ # read the served model back (see _mimo_npm).
+ npm = npm or _opencode_npm(auth, model, pr)
# Every ai-sdk package appends its own resource to baseURL (@ai-sdk/anthropic "/messages",
# @ai-sdk/openai "/responses", openai-compatible "/chat/completions") and expects the "/v1"
# to be there already, the way pi's openai clients do (see _pi_models_json). A connection
@@ -6765,7 +7408,7 @@ def _opencode_config(auth: Auth, model: str, cwd: str, mcp_servers: list[dict] |
"provider": {
"hr": {
"npm": npm,
- "options": {"baseURL": base, "apiKey": "{env:%s}" % _OPENCODE_KEY_ENV},
+ "options": {"baseURL": base, "apiKey": "{env:%s}" % key_env},
"models": {model: {}},
}
},
@@ -6793,13 +7436,17 @@ def _opencode_config(auth: Auth, model: str, cwd: str, mcp_servers: list[dict] |
# and reaches the provider); the env var is set in _build_opencode below.
hdir = pathlib.Path(cwd, ".harness")
hdir.mkdir(exist_ok=True)
- (hdir / "opencode.json").write_text(json.dumps(cfg, indent=2))
+ (hdir / f"{backend}.json").write_text(json.dumps(cfg, indent=2))
return f"hr/{model}"
-def _opencode_has_session(env: dict, session_id: str) -> bool:
+def _opencode_has_session(env: dict, session_id: str, share: str = "opencode") -> bool:
"""Is this opencode session actually in this workspace's database?
+ `share` names the directory under $HOME/.local/share and the database inside it, because MiMo
+ Code keeps the same SQLite store under its own name (measured: $HOME/.local/share/mimocode/
+ mimocode.db plus -wal, the same two files this reads for opencode).
+
opencode stores conversations in SQLite rather than one file per session, so there is no path
to stat the way claude's .jsonl or codex's rollout allows. The id is a distinctive token, so
the check is whether the database bytes contain it — the same shape of evidence as globbing
@@ -6810,9 +7457,9 @@ def _opencode_has_session(env: dict, session_id: str) -> bool:
home = pathlib.Path(env.get("HOME") or "")
if not home or not session_id:
return False
- base = home / ".local" / "share" / "opencode"
+ base = home / ".local" / "share" / share
needle = session_id.encode()
- for name in ("opencode.db", "opencode.db-wal"):
+ for name in (f"{share}.db", f"{share}.db-wal"):
f = base / name
try:
if f.exists() and needle in f.read_bytes():
@@ -6879,6 +7526,96 @@ def _build_opencode(provider: str, auth: Auth, model: str, prompt: str, cwd: str
return cmd
+# ── MiMo Code (XiaomiMiMo/MiMo-Code, npm @mimo-ai/cli, binary `mimo`) ────────────────────────
+# An opencode FORK, and openly so: the repo root package.json is still literally `"name":
+# "opencode"`. Measured on 0.1.15 (2026-10-02), it shares with opencode the thing that matters
+# most here — the `run --format json` event stream, line for line: {type, timestamp, sessionID,
+# part:{…}} with step_start / text / tool_use / step_finish / error, and step-finish's
+# tokens:{total,input,output,reasoning,cache:{read,write}} in opencode's cache-exclusive
+# convention. So it shares _opencode_to_claude and _opencode_usage_add rather than carrying a
+# copy, exactly as omp shares pi's normaliser.
+#
+# What differs is only spelling, and each difference is a place a shared helper is parameterised
+# rather than forked:
+# --auto -> --dangerously-skip-permissions (alias --yolo)
+# --session <id> -> -s <id>
+# OPENCODE_CONFIG -> MIMOCODE_CONFIG
+# ~/.local/share/opencode/opencode.db -> ~/.local/share/mimocode/mimocode.db
+# Its provider list is opencode's, for the same reason: the config takes an ai-sdk package name
+# and a baseURL, so the wire formats it can speak are the ones _opencode_npm chooses between.
+MIMO_PROVIDERS = set(OPENCODE_PROVIDERS)
+_MIMO_KEY_ENV = "HR_MIMO_KEY"
+
+
+def _mimo_npm(auth: Auth, model: str, pr: str) -> str:
+ """Which ai-sdk package serves this mimo turn — opencode's choice, with ONE difference.
+
+ opencode sends a claude id on an AGGREGATOR through @ai-sdk/anthropic, i.e. the Messages shape.
+ When this was measured that turn left the relay, and mimo names no served model of its own, so
+ every claude row on an aggregator recorded NO served_model and matrix rule 2 could not be
+ evaluated on it. (Every keyed mimo turn rides the relay now, the Messages shape included.)
+
+ MEASURED WITH A CONTROL on the Vercel column (2026-10-06): mimo's claude-haiku-4.5 pair came
+ back `unlabelled=4`, no served model on any of its four turns, while all seven of its other
+ models were labelled; jcode's claude-haiku-4.5 pair, which already keeps an aggregator's claude
+ on chat/completions, recorded `anthropic/claude-haiku-4.5`. Five scenarios "passed" on a rule
+ whose input was empty — the shape openhands' 40/40 had.
+
+ So the Messages shape is taken only when the CONNECTION is Anthropic (or a custom integration
+ declared anthropic-format). An aggregator serves a claude id over chat/completions perfectly
+ well, and that keeps the row measurable. This is kilo's finding applied where it was missed.
+ _opencode_npm itself is left alone: opencode's own columns were measured with it."""
+ if auth.api_format:
+ return _opencode_npm(auth, model, pr)
+ if pr == "anthropic":
+ return "@ai-sdk/anthropic"
+ if pr == "azure" or _HERMES_RESPONSES_API_MODEL.search(model or ""):
+ return "@ai-sdk/openai" # /v1/responses
+ return "@ai-sdk/openai-compatible" # /v1/chat/completions, and therefore the relay
+
+
+def _build_mimo(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,
+ resume_session_id: str | None = None, mcp_servers: list[dict] | None = None,
+ skills_dir: str | None = None, tools_disabled: list[str] | None = None) -> list[str]:
+ pr = provider or "openai-api"
+ if pr not in MIMO_PROVIDERS:
+ raise HTTPException(400, f"unknown mimo provider '{pr}' (one of {sorted(MIMO_PROVIDERS)})")
+ npm = _mimo_npm(auth, model, pr)
+ if auth.base_url and auth.api_key:
+ # EVERY keyed turn rides the relay, the Messages shape included, as opencode's do: the relay
+ # reads x-api-key and sends Anthropic the key that way (#352). The real key never reaches
+ # the CLI's environment, where the agent's shell can read it. The package is chosen before
+ # the swap, from the connection's own shape.
+ 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})
+ if auth.api_key:
+ env[_MIMO_KEY_ENV] = auth.api_key
+ qualified = _opencode_config(auth, model, cwd, mcp_servers, skills_dir, tools_disabled, pr,
+ backend="mimo", key_env=_MIMO_KEY_ENV, npm=npm)
+ env["MIMOCODE_CONFIG"] = os.path.join(cwd, ".harness", "mimo.json")
+ cmd = ["mimo", "run", "--format", "json", "--model", qualified,
+ # The sandbox is the trust boundary and nobody is attached to answer a prompt — the
+ # same grant claude gets with --dangerously-skip-permissions and pi with --approve.
+ # Measured: without it the turn stops at the first write.
+ "--dangerously-skip-permissions",
+ # Plugins off, for the hole --pure closes on opencode: project config is a file IN the
+ # workspace, so without this a task could write plugin origins into it and have the
+ # NEXT turn execute them.
+ "--pure",
+ # Reasoning parts are emitted only behind this flag, as in opencode's run.ts.
+ "--thinking"]
+ if resume_session_id and _opencode_has_session(env, resume_session_id, share="mimocode"):
+ cmd += ["-s", resume_session_id]
+ elif resume_session_id:
+ # opencode's guard, unchanged: naming a session this database does not hold exits 1 before
+ # the first event, and since every later turn passes the same dead id the conversation
+ # would be wedged for good rather than for one turn.
+ print(f"[resume] mimo: session {resume_session_id} not in this workspace — starting fresh",
+ flush=True)
+ cmd += ["--", prompt] if prompt.startswith("-") else [prompt]
+ return cmd
+
+
def _opencode_usage_add(state: dict, tk: dict | None) -> None:
"""step-finish carries Session.getUsage()'s `tokens`:
{total, input, output, reasoning, cache:{read,write}}. `input` is ALREADY cache-exclusive
@@ -8413,6 +9150,986 @@ def _minimax_eof(state: dict, rc: int) -> list[dict]:
_minimax_to_claude.eof = _minimax_eof # type: ignore[attr-defined]
+# ── jcode (1jehuang/jcode, Rust, binary `jcode`) ──────────────────────────────────────────────
+# Its own event schema, not a fork of anyone's. Measured on the pinned release v0.90.0
+# (`jcode v0.90.0 (a7f005e8c)`): `jcode … run --ndjson <message>` writes one JSON object per line
+# from src/cli/commands.rs's emit_ndjson_event —
+# start{session_id,provider,model} connection_type{connection} connection_phase{phase}
+# status_detail{detail} text_delta{text} text_replace{text} tool_start{id,name}
+# tool_input{delta} tool_exec{id,name} tool_done{id,name,output,error}
+# tokens{input,output,cache_read_input,cache_creation_input} message_end{stop_reason}
+# session{session_id} upstream_provider{provider} compaction{…}
+# done{text,usage,model,provider,session_id,…} error{message,…}
+JCODE_PROVIDERS = {"anthropic", "openai", "azure", "openrouter", "tokenrouter", "openai-api"}
+
+# The env names jcode's `openai-compatible` provider reads for a custom endpoint (README, verified
+# live against a gateway). They go in the ENVIRONMENT and not into config.toml on purpose: that is
+# also what makes _relay_served_model work, since it finds the relay route by the placeholder
+# bearer among the turn's env values, and a credential that rides only argv or a file leaves rule 2
+# unevaluable — the defect that let openhands report 40/40 on a check that was not running.
+_JCODE_BASE_ENV = "JCODE_OPENAI_COMPAT_API_BASE"
+_JCODE_KEY_ENV = "OPENAI_COMPAT_API_KEY"
+
+# Every tool id jcode 0.90.0 exposes, measured by asking the model for its own list with
+# --disabled-tools write (write absent, the rest present, which is also the proof that the switch
+# is enforcement and not instruction). Four of these write files (write, edit, replace,
+# apply_patch) and several reach the network (webfetch, websearch, gmail, compile_remote,
+# maintainer_feedback, schedule) — disabling one door is not disabling the capability.
+ALL_JCODE_TOOLS = {
+ "agentgrep", "applet", "apply_patch", "bash", "batch", "bg", "browser", "compile_remote",
+ "conversation_search", "edit", "gmail", "integration_tools", "invalid", "jcode_docs", "ls",
+ "memory", "mcp", "mcp_call", "mcp_search", "maintainer_feedback", "macos_computer_use", "open",
+ "panel", "read", "replace", "schedule", "session_search", "side_panel", "skill_manage",
+ "swarm", "todo", "webfetch", "websearch", "write",
+}
+
+
+def _jcode_usage_add(state: dict, ev: dict) -> None:
+ """Accumulate ONE `tokens` event into the turn total, netting the cache out of the input.
+
+ TWO measured facts, both of which a naive reading gets wrong:
+
+ 1. `done.usage` is NOT the turn's usage. NdjsonRunState.usage is ASSIGNED on every TokenUsage
+ event rather than accumulated (src/cli/commands.rs), so it holds the LAST request's numbers.
+ A two-request turn reported input 10748 while its two `tokens` events summed to 21357. So
+ the total is built here and `done.usage` is ignored.
+ 2. `input` is GROSS. jcode's OpenAI client states it outright — "OpenAI input_tokens is the
+ total, including both cache-read and cache-write subsets" (jcode-provider-openai/src/
+ stream.rs), and jcode-compaction-core repeats the contract — so BOTH cache counters are
+ subtracted to reach this product's fresh-only input. _norm_token_usage subtracts only the
+ read, which would leave the write billed twice."""
+ tot = state.setdefault("_jc_usage", {"input_tokens": 0, "output_tokens": 0,
+ "cache_read_tokens": 0, "cache_write_tokens": 0})
+
+ def _n(key: str) -> int:
+ v = ev.get(key)
+ return int(v) if isinstance(v, (int, float)) and v > 0 else 0
+
+ read, write, inp = _n("cache_read_input"), _n("cache_creation_input"), _n("input")
+ tot["cache_read_tokens"] += read
+ tot["cache_write_tokens"] += write
+ tot["input_tokens"] += max(inp - read - write, 0)
+ tot["output_tokens"] += _n("output")
+
+
+def _jcode_usage(state: dict) -> dict:
+ return {k: v for k, v in (state.get("_jc_usage") or {}).items() if v}
+
+
+def _jcode_to_claude(obj: dict, state: dict) -> list[dict]:
+ """Map ONE `jcode run --ndjson` line to zero+ canonical claude stream-json events.
+
+ Text streams from text_delta; `text_replace` is jcode's revision event and replaces what was
+ streamed, so it is not re-emitted (the user already has the old text on screen — the same
+ decision _pi_to_claude makes for a non-prefix revision) but it does become the candidate final.
+ `tool_input` carries argument deltas for a call whose tool_use was already emitted at
+ tool_start, so it is dropped rather than painted twice."""
+ t = obj.get("type")
+ if t == "start":
+ state["_jc_session"] = obj.get("session_id") or ""
+ return [{"type": "system", "subtype": "init",
+ "session_id": obj.get("session_id"), "model": state.get("model")}]
+ if t == "session":
+ state["_jc_session"] = obj.get("session_id") or state.get("_jc_session") or ""
+ return []
+ if t == "text_delta":
+ txt = obj.get("text") or ""
+ if not txt:
+ return []
+ state["_jc_text"] = state.get("_jc_text", "") + txt
+ state["final"] = state["_jc_text"]
+ return [{"type": "assistant", "message": {"content": [{"type": "text", "text": txt}]}}]
+ if t == "text_replace":
+ txt = obj.get("text") or ""
+ state["_jc_text"] = txt
+ state["final"] = txt
+ return []
+ if t == "tool_start":
+ return [{"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": obj.get("id") or "tool",
+ "name": obj.get("name") or "tool", "input": {}}]}}]
+ if t == "tool_done":
+ err = obj.get("error")
+ content = str(obj.get("output") or err or "")
+ return [{"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": obj.get("id") or "tool",
+ "is_error": bool(err), "content": content[:8000]}]}}]
+ if t == "tokens":
+ _jcode_usage_add(state, obj)
+ return []
+ if t == "message_end":
+ # One assistant message ended; the next may follow in the same turn (a tool round trip).
+ # `final` is the LAST message's text, so the buffer resets rather than accumulating a
+ # mid-run aside into the answer.
+ state["_jc_text"] = ""
+ return []
+ if t == "error":
+ # A REAL error event, which is more than several of these CLIs have: the message names the
+ # endpoint, the model, the auth variable's NAME (never its value), the status and the
+ # provider's own body. No `done` follows it, and the process exits 1.
+ state["_jc_error"] = str(obj.get("message") or "jcode run failed")[:1000]
+ return [{"type": "result", "subtype": "error", "is_error": True,
+ "result": state["_jc_error"], "usage": _jcode_usage(state)}]
+ if t == "done":
+ # `done.text` is the whole final answer, authoritative over what the deltas assembled.
+ final = obj.get("text")
+ if isinstance(final, str) and final:
+ state["final"] = final
+ return [{"type": "result", "subtype": "success", "is_error": False,
+ "result": state.get("final", ""), "usage": _jcode_usage(state),
+ # The CLI echoes the REQUESTED id here, never what the provider answered, so this
+ # is deliberately NOT set as the served model: the relay's tap is the only honest
+ # source for rule 2 on this backend, and the run loop fills it in when absent.
+ }]
+ return []
+
+
+def _jcode_eof(state: dict, rc: int) -> list[dict]:
+ """The stream ended with neither `done` nor `error`: killed, cancelled, or a crash before the
+ emitter ran. The exit code decides, and a failure returns an EMPTY result so the run loop's
+ collected stderr tail — which carries jcode's own `Error: …` block — is the reason rather than
+ a placeholder written here."""
+ if state.get("_jc_error"):
+ return []
+ usage = _jcode_usage(state)
+ if rc == 0:
+ return [{"type": "result", "subtype": "success", "is_error": False,
+ "result": state.get("final", ""), "usage": usage}]
+ return [{"type": "result", "subtype": "error", "is_error": True, "result": "", "usage": usage}]
+
+
+_jcode_to_claude.eof = _jcode_eof # type: ignore[attr-defined]
+
+
+# ── opensquilla (TokenRhythm/opensquilla, `opensquilla agent`) ─────────────────────────────────
+# Measured on the pinned 0.5.6 release wheel (2026-10-02). It needs no driver process: with
+# `--json --event-stream-stderr` the progress events and the one final object both arrive on the
+# merged stream the run loop already reads, and the per-message detail arrives in the transcript
+# file, which the eof handler reads.
+#
+# THREE THINGS ITS DEFAULTS DO THAT A HARNESS MUST UNDO, each measured rather than inferred:
+# 1. `[squilla_router] enabled = true` by DEFAULT. Its router scores every turn and routes it
+# across four tiers "to the cheapest capable model" — model substitution as a feature. The
+# builder writes `enabled = false`, or matrix rule 2 is violated by configuration.
+# 2. A `custom` endpoint is assumed to hold 8192 tokens. The first probe died with
+# `provider_request_too_large` ("The fixed system instructions exceed the provider request
+# budget") on a prompt of three sentences, because its own system block and tool schemas are
+# ~43k characters. The builder declares the window per model.
+# 3. `--session-db-path` defaults to `:memory:`, i.e. no continuity between turns at all.
+#
+# WHAT THE PROGRESS STREAM DOES NOT CARRY, by its own documented design: "The stream does not
+# expose reasoning text, answer text, tool arguments, tool results". `text_delta` really does
+# arrive with no text. So the live half of this backend's stream is the TOOL CALLS and the notices,
+# and the answer text plus each tool's result come out of the transcript at the end. Tool
+# ARGUMENTS are the one thing nothing surfaces: the progress stream omits them and the transcript
+# — which does carry them — is written once, after the run (cli/agent_cmd.py `_write_jsonl`), by
+# which time the call has already been reported. Said here rather than left to be discovered.
+OPENSQUILLA_PROVIDERS = {"anthropic", "openai", "azure", "openrouter", "tokenrouter", "openai-api"}
+
+# Its own name for the key of the generic OpenAI-compatible provider (`custom`), and of the generic
+# Messages one. The driver puts the relay's per-turn placeholder here, in the ENVIRONMENT, which is
+# also what lets _relay_served_model and _relay_usage find the route.
+_OPENSQUILLA_KEY_ENV = "CUSTOM_LLM_API_KEY"
+_OPENSQUILLA_ANTHROPIC_KEY_ENV = "CUSTOM_ANTHROPIC_API_KEY"
+# Its own venv (the aider/openhands precedent: it pins a large dependency set), so the executable is
+# named by path rather than looked up on PATH — $TOOLS/bin is what PATH carries, and this lives
+# beside its interpreter.
+OPENSQUILLA_BIN = os.environ.get("HR_OPENSQUILLA_BIN",
+ "/data/agent-tools/opensquilla-venv/bin/opensquilla")
+
+
+# The chat-routing directives OpenSquilla's models embed for its channel adapters:
+# `[[reply_to_current]]`, `[[reply_to: <target>]]`, and the one-bracket spelling a model that
+# dropped a pair still means. The project strips them in the channel layer AND in both of its
+# terminal renderers — "terminal surfaces render the raw stream, so without this filter the tag
+# leaks into the transcript as literal text" — but `opensquilla agent --json` strips neither, so
+# without this the tag is part of the answer. Measured on the first live turn: asked to reply with
+# exactly READY, the record said "[[reply_to_current]]\nREADY", which is a scenario that recalls an
+# exact word failing for a reason that has nothing to do with the model. The pattern and what goes
+# with it (trailing spaces and one newline) are the project's own, from
+# cli/tui/backend/directives.py.
+_SQ_DIRECTIVE = re.compile(
+ r"(?:\[\[\s*(?:reply_to_current|reply_to\s*:\s*[^\]\n]*)\s*\]\]"
+ r"|(?<!\[)\[\s*(?:reply_to_current|reply_to\s*:\s*[^\]\n]*)\s*\](?!\]))[ \t]*\r?\n?")
+
+
+def _opensquilla_text(s: str) -> str:
+ """One assistant text block, with the channel-routing directives taken out."""
+ return _SQ_DIRECTIVE.sub("", s or "").strip()
+
+
+def _opensquilla_paths(cwd: str) -> tuple[pathlib.Path, pathlib.Path, pathlib.Path]:
+ """(state dir, transcript, usage file) — all under .harness/, so all checkpointed and none of
+ them reported to the user as something their task produced."""
+ base = pathlib.Path(cwd, ".harness", "opensquilla")
+ return base, base / "transcript.jsonl", base / "usage.json"
+
+
+def _opensquilla_usage(u: dict | None) -> dict:
+ """Its usage block, netted to this product's contract.
+
+ `input_tokens` is GROSS: on one measured turn cached_tokens 16,764 plus cache_write_tokens
+ 8,570 summed to within nine tokens of input_tokens 25,343. cache_write_tokens is only in
+ `model_usage_breakdown`, not at the top level, so it is read from there."""
+ if not isinstance(u, dict):
+ return {}
+ def _n(d: dict, *keys: str) -> int:
+ for k in keys:
+ v = d.get(k)
+ if isinstance(v, (int, float)) and v > 0:
+ return int(v)
+ return 0
+ write = 0
+ for row in (u.get("model_usage_breakdown") or []):
+ if isinstance(row, dict):
+ write += _n(row, "cache_write_tokens")
+ read = _n(u, "cached_tokens", "cache_read_tokens")
+ out = {"input_tokens": max(_n(u, "input_tokens") - read - write, 0),
+ # reasoning_tokens is a SUBSET of output_tokens here (the usage file reports
+ # output 346 with reasoning 143 inside it), so it is not added again.
+ "output_tokens": _n(u, "output_tokens")}
+ if read:
+ out["cache_read_tokens"] = read
+ if write:
+ out["cache_write_tokens"] = write
+ return {k: v for k, v in out.items() if v}
+
+
+def _opensquilla_transcript(state: dict) -> list[dict]:
+ """Replay the transcript as canonical events: the assistant's text, and one tool_result per
+ call with the content the progress stream withheld.
+
+ Read BEFORE anything is torn down — it is read here, at eof, from a file the CLI has already
+ finished writing and closed, which is the ordering openhands' log-tail fallback got wrong
+ (it read after signalling the writer and recorded `SIGTERM … shutting down` as the reason).
+ The shape is pi's, because this project is openclaw/hermes lineage: {type:"message",
+ message:{role, content:[{type:"text"|"toolCall"|…}], usage:{input,output,cacheRead,cacheWrite}}}.
+ """
+ cwd = state.get("cwd") or ""
+ if not cwd:
+ return []
+ _, transcript, _ = _opensquilla_paths(cwd)
+ try:
+ lines = transcript.read_text(errors="replace").splitlines()
+ except OSError:
+ return []
+ out: list[dict] = []
+ final = ""
+ for raw in lines:
+ raw = raw.strip()
+ if not raw.startswith("{"):
+ continue
+ try:
+ msg = (json.loads(raw) or {}).get("message") or {}
+ except Exception: # noqa: BLE001 — one unparseable line in a transcript the CLI is still
+ continue # appending to is a line, not a turn: skip it and read the rest.
+ role = msg.get("role")
+ content = msg.get("content") if isinstance(msg.get("content"), list) else []
+ if role == "assistant":
+ text = _opensquilla_text("\n".join(c.get("text") or "" for c in content
+ if isinstance(c, dict) and c.get("type") == "text"))
+ if text.strip():
+ # `final` is the LAST assistant text, which is why the final answer is taken from
+ # here and NOT from the stdout object's `text`: that field concatenates the whole
+ # turn's assistant output, so a turn asked to "reply with exactly DONE" answered
+ # "I'll create probe.txt … and verify it.DONE" while the transcript's last
+ # assistant message was exactly "DONE".
+ final = text
+ out.append({"type": "assistant", "message": {"content": [{"type": "text", "text": text}]}})
+ elif role == "toolResult":
+ body = "\n".join(c.get("text") or "" for c in content
+ if isinstance(c, dict) and c.get("type") == "text")
+ out.append({"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": msg.get("toolCallId") or "tool",
+ "is_error": bool(msg.get("isError")), "content": body[:8000]}]}})
+ if final:
+ state["final"] = final
+ return out
+
+
+def _opensquilla_to_claude(obj: dict, state: dict) -> list[dict]:
+ """Map ONE line of the merged stream to zero+ canonical claude events.
+
+ Two kinds of object arrive on it: the v1 progress events, each stamped `"_event": true`, and
+ the single final result object `--json` writes to stdout at the end. Only `_event: true` may be
+ read as an event — the project says so, because ordinary diagnostics share the stream — and
+ everything else that parses as JSON and carries a `status` is the final object."""
+ if obj.get("_event") is True:
+ kind = obj.get("kind")
+ if kind == "tool_use_start":
+ return [{"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": obj.get("tool_use_id") or "tool",
+ "name": obj.get("tool_name") or "tool",
+ # The progress stream carries no arguments, by design. An empty object is the
+ # honest rendering: a card with no arguments, rather than invented ones.
+ "input": {}}]}}]
+ if kind == "router_decision":
+ # The router is turned OFF by the config this builder writes, so this event should
+ # never arrive. If it does, the turn ran on a model nobody asked for: recorded so the
+ # record says which, and the eof handler fails the turn on it rather than reporting a
+ # pass for a substitution.
+ picked = str(obj.get("model") or "")
+ if picked:
+ state.setdefault("_sq_routed", []).append(picked)
+ return []
+ if kind == "error":
+ state["_sq_error"] = str(obj.get("message") or "opensquilla error")[:1000]
+ return []
+ if kind == "warning":
+ # Something the CLI said about how the turn is going, which is neither its answer nor a
+ # failure: "Provider context limit reached; compacting older context before retrying" is
+ # the one measured here. A person reading a turn that took minutes and lost its earlier
+ # context has no other way to learn why, so it becomes a `system/notice` — a subtype the
+ # gateway renders as a note on the reply (it renders resume_lost and mcp_unavailable the
+ # same way, and drops any subtype it does not know, so emitting one it did not render
+ # would be writing to a surface that does not exist).
+ #
+ # De-duplicated HERE rather than in the gateway: its compaction warning repeats once per
+ # retry, and three identical notes on one reply is noise, not information.
+ text = str(obj.get("message") or "").strip()[:300]
+ seen = state.setdefault("_sq_notices", [])
+ if not text or text in seen:
+ return []
+ seen.append(text)
+ return [{"type": "system", "subtype": "notice", "text": text}]
+ return []
+ if isinstance(obj.get("status"), str) and "session_key" in obj:
+ state["_sq_final"] = obj
+ return [{"type": "system", "subtype": "init",
+ "session_id": obj.get("session_key"), "model": state.get("model")}]
+ return []
+
+
+def _opensquilla_eof(state: dict, rc: int) -> list[dict]:
+ """Everything the user reads comes out here: the transcript's messages, then the result.
+
+ The final object is the status of record — not the exit code, which is 1 for both a provider
+ failure and a usage error — and its `errors[]` carries the reason the agent reported."""
+ evs = _opensquilla_transcript(state)
+ final_obj = state.get("_sq_final") or {}
+ usage = _opensquilla_usage(final_obj.get("usage") if isinstance(final_obj, dict) else None)
+ errs = [str((e or {}).get("message") or "") for e in (final_obj.get("errors") or [])
+ if isinstance(e, dict)]
+ why = state.get("_sq_error") or "; ".join(x for x in errs if x)
+ routed = sorted(set(state.get("_sq_routed") or []))
+ requested = str(state.get("model") or "")
+ other = [m for m in routed if requested and not _same_model(requested, m)]
+ if other and not why:
+ why = f"its router ran {', '.join(other)} instead of {requested}"
+ ok = (str(final_obj.get("status") or "") == "ok") and not why
+ if not final_obj and rc != 0 and not why:
+ # Neither the final object nor an error event arrived: killed, cancelled, or dead before
+ # the emitter. The run loop's stderr tail is the reason; an empty result lets it through.
+ return evs + [{"type": "result", "subtype": "error", "is_error": True,
+ "result": "", "usage": usage}]
+ return evs + [{"type": "result", "subtype": "success" if ok else "error", "is_error": not ok,
+ "result": (state.get("final", "") if ok else (why or state.get("final", ""))),
+ "usage": usage}]
+
+
+_opensquilla_to_claude.eof = _opensquilla_eof # type: ignore[attr-defined]
+
+
+def _opensquilla_config(auth: Auth, model: str, state_dir: pathlib.Path, anthropic: bool,
+ mcp_servers: list[dict] | None) -> None:
+ """Write <state dir>/config.toml: one provider, one model, the router off.
+
+ TOML is written by hand rather than through a library because the runner has no TOML writer and
+ the values are ours: a model id (quoted, and the only place a caller-supplied string lands
+ here), a URL and three booleans."""
+ def q(v: str) -> str:
+ return '"' + str(v).replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+ pname = "custom_anthropic" if anthropic else "custom"
+ base = (auth.base_url or "").rstrip("/")
+ lines = [
+ "# written per turn by the harness runner — do not edit, it is overwritten",
+ "[llm]",
+ f"provider = {q(pname)}",
+ f"model = {q(model)}",
+ f"base_url = {q(base)}",
+ "",
+ # Declared because the generic endpoints fall back to 8192 tokens, which its own system
+ # prompt and tool schemas do not fit in (see the comment on this backend above).
+ f"[models.{pname}.{q(model)}]",
+ "context_window = 200000",
+ "max_output_tokens = 32000",
+ "supports_tools = true",
+ "",
+ "[squilla_router]",
+ "# OFF: it routes a turn to another tier's model, and this harness promises the model asked for.",
+ "enabled = false",
+ "auto_thinking = false",
+ "",
+ "[auth]",
+ "# Nothing is listening on a gateway port here; the one process is the agent turn.",
+ 'mode = "none"',
+ "",
+ "[memory]",
+ "# \"state\", not the default \"workspace\": the memory tools then read and write their",
+ "# markdown under the state dir (tools/builtin/memory_tools.py branches on exactly this)",
+ "# instead of under the directory the user collects, so memory the agent accumulates is not",
+ "# handed back as the task's output. It does NOT stop the four bootstrap seeds below —",
+ "# ensure_agent_workspace writes those whatever this says; _git_exclude is what covers them.",
+ 'source = "state"',
+ "",
+ ]
+ entries = []
+ for i, sv in enumerate(mcp_servers or []):
+ if not isinstance(sv, dict):
+ continue
+ name = _mcp_name(sv.get("name") or sv.get("id") or f"server{i}")
+ url = (sv.get("url") or "").strip()
+ transport = str(sv.get("transport") or "").lower()
+ if sv.get("command"):
+ cmd = sv["command"]
+ argv = cmd if isinstance(cmd, list) else [str(cmd)]
+ args = [str(a) for a in argv[1:]] + [str(a) for a in (sv.get("args") or [])]
+ entries.append((name, "stdio", str(argv[0]), args, ""))
+ elif url and transport == "sse":
+ entries.append((name, "sse", "", [], url))
+ # A streamable-HTTP server never reaches here: opensquilla's MCPServerEntry takes
+ # transport "stdio" | "sse" only, so _BRIDGED_TRANSPORTS turns http into a stdio launcher
+ # before this runs. One that still carries a bare url has no transport this CLI can speak
+ # and is dropped rather than written as a line it will refuse.
+ if entries:
+ lines += ["[mcp]", "enabled = true", ""]
+ for name, transport, command, args, url in entries:
+ lines += ["[[mcp.servers]]", f"name = {q(name)}", f"transport = {q(transport)}"]
+ if command:
+ lines += [f"command = {q(command)}",
+ "args = [" + ", ".join(q(a) for a in args) + "]"]
+ if url:
+ lines += [f"url = {q(url)}"]
+ lines += [""]
+ state_dir.mkdir(parents=True, exist_ok=True)
+ (state_dir / "config.toml").write_text("\n".join(lines))
+
+
+def _build_opensquilla(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,
+ resume_session_id: str | None = None, mcp_servers: list[dict] | None = None,
+ tools_disabled: list[str] | None = None,
+ max_turns: int | None = None) -> list[str]:
+ pr = provider or "openai-api"
+ if pr not in OPENSQUILLA_PROVIDERS:
+ raise HTTPException(400, f"unknown opensquilla provider '{pr}' "
+ f"(one of {sorted(OPENSQUILLA_PROVIDERS)})")
+ if not auth.base_url:
+ raise HTTPException(400, f"opensquilla provider '{pr}' needs a base_url (none configured)")
+ # Its `custom_anthropic` provider only for a connection that IS Anthropic, as jcode's above.
+ anthropic = auth.api_format == "anthropic" or (not auth.api_format and pr == "anthropic")
+ if auth.api_key:
+ # EVERY keyed turn rides the relay, as jcode's: the real key never reaches the CLI's
+ # environment, where the agent's shell can read it, and the relay is the only tap that can
+ # say which model answered. The Messages provider gets the relay's origin, which works
+ # whichever of /v1/messages or /messages it joins on.
+ relay_base, relay_tok = _hermes_relay_route(auth.base_url, auth.api_key, plain_stream=True)
+ auth = auth.model_copy(update={"base_url": _relay_origin(relay_base) if anthropic else relay_base,
+ "api_key": relay_tok})
+ state_dir, transcript, usage_path = _opensquilla_paths(cwd)
+ _opensquilla_config(auth, model, state_dir, anthropic, mcp_servers)
+ env[_OPENSQUILLA_ANTHROPIC_KEY_ENV if anthropic else _OPENSQUILLA_KEY_ENV] = auth.api_key or ""
+ # Both roots, per its own warning about parallel subprocesses: a write-capable agent holds a
+ # profile-wide writer lease, so two turns sharing a state dir conflict instead of queueing.
+ # One session has one workspace, and turns within a session are serialised above the runner, so
+ # the session's own directory is the profile — and the session DATABASE is named explicitly
+ # below, which is what keeps continuity while the profile stays per session.
+ env["OPENSQUILLA_STATE_DIR"] = str(state_dir)
+ env["OPENSQUILLA_GATEWAY_STATE_DIR"] = str(state_dir / "gateway")
+ # The four files `ensure_agent_workspace` seeds into the workspace, unconditionally — it takes a
+ # `seed_templates` flag that no caller passes and no setting reads, so there is nothing to turn
+ # off. MEASURED on the Vercel column (2026-10-06): a turn that wrote NOTHING handed back
+ # SOUL.md, IDENTITY.md, USER.md and MEMORY.md, their cards stayed in the transcript, and by the
+ # artifact turn rule 3 — the rendered cards must BE the turn's stored files — saw five cards
+ # against a record of one. All eight models, identically.
+ _git_exclude(cwd, ["SOUL.md", "IDENTITY.md", "USER.md", "MEMORY.md", "memory/"],
+ "the files opensquilla seeds into every workspace, never the task's output")
+ for stale in (transcript, usage_path):
+ try:
+ stale.unlink()
+ except OSError:
+ pass
+ cmd = [OPENSQUILLA_BIN, "agent", "-m", prompt,
+ "--json", "--event-stream-stderr",
+ "--workspace", cwd,
+ # The sandbox is the trust boundary and nobody is attached to approve anything — the
+ # grant claude gets with --dangerously-skip-permissions. Deliberately NOT
+ # --workspace-lockdown: writes outside the workspace are invisible to the user but they
+ # are also how a task installs a package, and the wall here is the sandbox, not a flag.
+ "--permissions", "bypass",
+ "--transcript-path", str(transcript),
+ "--usage-path", str(usage_path),
+ # Continuity. The default is `:memory:`, i.e. none at all; this file is under .harness/
+ # and therefore travels in the checkpoint. The key is the harness's session id.
+ "--session-db-path", str(state_dir / "sessions.sqlite"),
+ # A provider that answers the same 503 every time should not cost minutes before the
+ # reason reaches the user. Two attempts, which is openhands' lesson applied up front
+ # rather than after a 212-second failure.
+ "--max-provider-retries", "2"]
+ if resume_session_id:
+ cmd += ["--session-id", resume_session_id]
+ if max_turns:
+ cmd += ["--max-iterations", str(int(max_turns))]
+ if tools_disabled:
+ # NOT a per-tool switch: `--permissions` chooses a posture (restricted / bypass / full) and
+ # there is no deny list on the CLI, so the disabled set travels as a standing instruction in
+ # the agent doc instead — the same honest downgrade codex, hermes, dsh and gemini get, and
+ # the reason this base's tool_enforcement is "soft" in the gateway's catalog.
+ pass
+ return cmd
+
+
+# ── nanobot (HKUDS/nanobot, PyPI nanobot-ai) ──────────────────────────────────────────────────
+# Not a coding CLI: a self-hosted personal-agent runtime with a WebUI, chat channels, memory and
+# an agent loop. It is driven IN PROCESS through its published Python SDK by
+# runner/nanobot_driver.py, which emits claude's stream-json directly — so this backend's
+# normaliser is the passthrough, as systemone's is. The driver's docstring holds the measured
+# reasons the SDK is the surface and `nanobot agent -m` is not (no event stream, and its CLI path
+# seeds eight files and a second git repository into the workspace).
+NANOBOT_PROVIDERS = {"anthropic", "openai", "azure", "openrouter", "tokenrouter", "openai-api"}
+NANOBOT_PYTHON = os.environ.get("HR_NANOBOT_PYTHON", "/data/agent-tools/nanobot-venv/bin/python")
+# nanobot's agent workspace is a SUBDIRECTORY of the session, and this is the one base where that is
+# true. Its session store refuses to live inside the workspace the agent has file tools over —
+# JsonlSessionStore raises "session storage must be outside the agent workspace" when the sessions
+# root is the workspace or under it — which is a sound rule (the agent must not be able to rewrite
+# its own conversation) and it rules out the arrangement every other base uses here. The
+# conversation still has to travel in the checkpoint, and the checkpoint is a tar of the session
+# directory, so the sessions root has to be under the session directory and NOT under the
+# workspace: the only shape that satisfies both is config (and sessions) in .harness/nanobot/ with
+# the workspace one level down. Found by running the real argv against the real package; a test
+# over the driver's own fake could not have seen it.
+_NANOBOT_WS = "workspace"
+NANOBOT_DRIVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "nanobot_driver.py")
+# The variable config.json names and the driver's process holds. It is also what makes rule 2
+# answerable on this backend: _relay_served_model finds the relay route by the placeholder bearer
+# among the turn's ENV values, and a credential that lives only in a file leaves it unevaluable.
+_NANOBOT_KEY_ENV = "HR_NANOBOT_RELAY_KEY"
+
+# Every tool the loop registers on 0.3.5, read off its own start-up line ("Registered 22 tools: …").
+# Writing has three doors (write_file, edit_file, apply_patch), shell has three (exec, exec_session,
+# run_cli_app), egress two (web_fetch, web_search), and `spawn` is a subagent that inherits the
+# session's policy — measured: with write_file withheld the model wrote the file with `exec`
+# instead, which is what "disabling a tool withholds EXECUTION of that tool, not the capability"
+# means in practice and why the console says request rather than guarantee for the capability.
+ALL_NANOBOT_TOOLS = (
+ "apply_patch", "create_goal", "edit_file", "exec", "exec_session", "find_files", "grep",
+ "list_dir", "list_exec_sessions", "list_sessions", "message", "my", "read_file",
+ "read_session", "run_cli_app", "search_sessions", "send_session_message", "spawn",
+ "update_goal", "web_fetch", "web_search", "write_file",
+)
+
+
+# The variables `environments.apply_env` puts on a turn so the layer's interpreter and packages are
+# the ones the agent runs. nanobot's shell tool does NOT inherit them: its own `_build_env` says
+# "Build a minimal environment for subprocess execution. On Unix, only HOME/LANG/TERM are passed by
+# default." MEASURED by the environments column (2026-10-10): three of four bases used the layer's
+# pip, npm and apt packages without installing anything, and nanobot failed all three with
+# ModuleNotFoundError — the layer reached the driver process and stopped there. Its exec tool takes
+# an allow-list and a PATH prepend, so the layer is handed to it by name.
+_ENV_LAYER_KEYS = ("PROJECT_ROOT", "HR_ENVIRONMENT", "PYTHONPATH", "VIRTUAL_ENV", "NODE_PATH",
+ "LD_LIBRARY_PATH")
+
+
+def _nanobot_exec_env(env: dict, caller_keys: list[str] | tuple = ()) -> dict:
+ """nanobot's `tools.exec` entries that carry the environment layer and the harness's own
+ variables into its shell, or {}.
+
+ The harness's variables are named here as well: every other base's shell inherits them, and
+ nanobot's passes only what it is told to. MEASURED by the custom-harness dimension (2026-10-12):
+ the skill's script ran on nanobot and wrote its stamp without the harness's STAMP_NONCE, where
+ the three other bases carried it. Names only: the values stay in the driver's environment."""
+ link = str(env.get("HR_ENVIRONMENT") or "").strip()
+ keys = [k for k in _ENV_LAYER_KEYS if link and env.get(k)]
+ keys += [k for k in caller_keys if env.get(k) is not None and k not in keys]
+ # the layer's own PATH entries, taken as the ones under its directory rather than by
+ # reconstructing what apply_env decided to add
+ prepend = [x for x in str(env.get("PATH") or "").split(":") if x.startswith(link + "/")] if link else []
+ out: dict = {}
+ if keys:
+ out["allowedEnvKeys"] = keys
+ if prepend:
+ out["pathPrepend"] = ":".join(prepend)
+ return out
+
+
+def _nanobot_config(auth: Auth, model: str, cfg_dir: pathlib.Path, workspace: str,
+ mcp_servers: list[dict] | None, max_turns: int | None,
+ env: dict | None = None, caller_keys: list[str] | tuple = ()) -> pathlib.Path:
+ """Write <cwd>/.harness/nanobot/config.json and return its path.
+
+ The DIRECTORY is the point, not just the file: nanobot derives its data dir from the config
+ file's parent (`get_data_dir()` is `get_config_path().parent`), so the conversation store lands
+ at .harness/nanobot/sessions/<workspace id>/<key>.jsonl — inside the checkpointed tree and
+ outside the produced-files list, with nothing to configure. Verified by continuing a session
+ from a second process.
+
+ The api key is NAMED, not written: nanobot resolves `${VAR}` references anywhere in the config
+ before use (config/loader.py resolve_config_env_vars, which raises if the variable is unset
+ rather than silently sending an empty key), so the credential stays in the environment — the
+ same discipline opencode's `{env:VAR}` and gjc's apiKey-as-env-name give. The file is in
+ CHECKPOINT_EXCLUDE and .gitignore anyway, because a future build that stopped resolving
+ references must not turn this file into a leak."""
+ base = (auth.base_url or "").rstrip("/")
+ defaults: dict = {
+ "provider": "custom",
+ "model": model,
+ "workspace": workspace,
+ # Its own default is 200k, stated again here so a model with a smaller real window is the
+ # gateway's decision rather than a silent inherited constant.
+ "contextWindowTokens": 200000,
+ "maxTokens": 32000,
+ # EMPTY, and it must stay empty: a fallback model is a substitution, and this product
+ # promises the model that was asked for (matrix rule 2).
+ "fallbackModels": [],
+ }
+ if max_turns:
+ defaults["maxToolIterations"] = int(max_turns)
+ cfg: dict = {
+ # `apiType` is NOT sent: its validator refuses it on any provider but `openai`
+ # ("providers.<name>.api_type is only supported for providers.openai") and the refusal
+ # rejects the WHOLE config, so the turn dies on a field that was only ever decoration.
+ "providers": {"custom": {"apiKey": "${%s}" % _NANOBOT_KEY_ENV, "apiBase": base}},
+ "agents": {"defaults": defaults},
+ }
+ tools: dict = {}
+ mcp = _nanobot_mcp(mcp_servers)
+ if mcp:
+ tools["mcpServers"] = mcp
+ ex = _nanobot_exec_env(env or {}, caller_keys)
+ if ex:
+ tools["exec"] = ex
+ if tools:
+ cfg["tools"] = tools
+ cfg_dir.mkdir(parents=True, exist_ok=True)
+ path = cfg_dir / "config.json"
+ path.write_text(json.dumps(cfg, indent=2))
+ return path
+
+
+def _nanobot_mcp(servers: list[dict] | None) -> dict:
+ """nanobot's `tools.mcpServers` map: a name to {command,args,env} for stdio or {url,headers}
+ for a remote one. The transport is INFERRED by nanobot from the url — a path ending in /sse is
+ sse, anything else streamable HTTP (agent/tools/mcp.py connect_mcp_servers) — so no `type` is
+ sent and nanobot is in neither half of _BRIDGED_TRANSPORTS.
+
+ The KEY PATH is the whole of what was wrong here. This wrote a top-level `mcp: {servers: …}`,
+ which nanobot's Config forbids outright: its top level is agents/api/channels/gateway/
+ model_presets/providers/tools/transcription with extra="forbid", so every turn on a harness
+ carrying ANY MCP server died before the first model call with "Invalid configuration … mcp:
+ Unknown setting." Measured by the custom-harness dimension on 2026-10-07; nothing else could
+ have seen it, because no test exercised this function's output against nanobot's own schema and
+ the five routing scenarios never attach a server."""
+ out: dict = {}
+ for i, sv in enumerate(servers or []):
+ if not isinstance(sv, dict):
+ continue
+ name = _mcp_name(sv.get("name") or sv.get("id") or f"server{i}")
+ url = (sv.get("url") or "").strip()
+ if sv.get("command"):
+ cmd = sv["command"]
+ argv = cmd if isinstance(cmd, list) else [str(cmd)]
+ entry: dict = {"command": str(argv[0]),
+ "args": [str(a) for a in argv[1:]] + [str(a) for a 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()}
+ elif url:
+ entry = {"url": url}
+ if _mcp_headers(sv):
+ entry["headers"] = _mcp_headers(sv)
+ else:
+ continue
+ out[name] = entry
+ return out
+
+
+def _build_nanobot(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,
+ resume_session_id: str | None = None, mcp_servers: list[dict] | None = None,
+ tools_disabled: list[str] | None = None,
+ max_turns: int | None = None, caller_keys: list[str] | tuple = ()) -> list[str]:
+ pr = provider or "openai-api"
+ if pr not in NANOBOT_PROVIDERS:
+ raise HTTPException(400, f"unknown nanobot provider '{pr}' (one of {sorted(NANOBOT_PROVIDERS)})")
+ if not auth.base_url:
+ raise HTTPException(400, f"nanobot provider '{pr}' needs a base_url (none configured)")
+ if auth.base_url and auth.api_key:
+ # Every keyed turn rides the loopback relay, a custom endpoint included, so the real key
+ # never reaches the driver's environment. nanobot's `custom` provider speaks chat/completions
+ # and names only the model it was asked for, so the relay is also the only honest source of
+ # the served model: it reads the id off the provider's own answer. The credential therefore
+ # has to be reachable in the ENVIRONMENT as well, which it is — _relay_served_model finds
+ # the route by the placeholder bearer among env values, and the openhands defect was exactly
+ # a backend whose token rode somewhere else.
+ 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[_NANOBOT_KEY_ENV] = auth.api_key or ""
+ cfg_dir = pathlib.Path(cwd, ".harness", "nanobot")
+ work = pathlib.Path(cwd, _NANOBOT_WS)
+ work.mkdir(parents=True, exist_ok=True)
+ # the session's file root is one level up from the agent's cwd; see _visible_root
+ _agent_subdir_set(cwd, _NANOBOT_WS)
+ _adopt_into(cwd, _NANOBOT_WS)
+ # nanobot's own machinery inside the agent's workspace. MEASURED on the Vercel column
+ # (2026-10-06): without this a turn that wrote NOTHING handed the user 25 files — the three
+ # built-in skill bundles, the instruction file and nanobot's workspace id — and all eight
+ # nanobot pairs FAILED their first scenario, because the file cards pushed the answer out of
+ # the transcript the judge reads. Re-measured after: the same turn produces 0.
+ _git_exclude(cwd, [f"{_NANOBOT_WS}/.nanobot/", f"{_NANOBOT_WS}/skills/",
+ f"{_NANOBOT_WS}/memory/", f"{_NANOBOT_WS}/AGENTS.md"],
+ "nanobot's own machinery, never the task's output")
+ cfg_path = _nanobot_config(auth, model, cfg_dir, str(work), mcp_servers, max_turns, env, caller_keys)
+ # The session key IS the harness's session id when there is one. The driver always passes a key,
+ # so _nanobot_session_present asks the store rather than reading argv.
+ job = {"config_path": str(cfg_path), "workspace": str(work), "model": model, "prompt": prompt,
+ "session_key": resume_session_id or ("hr-" + uuid.uuid4().hex[:12]),
+ "tools_disabled": list(tools_disabled or [])}
+ return [NANOBOT_PYTHON, NANOBOT_DRIVER, json.dumps(job)]
+
+
+
+def _jcode_has_session(env: dict, session_id: str) -> bool:
+ """Is this conversation in this workspace's session store?
+
+ `$HOME/.jcode/sessions/<id>.json`, and $HOME is already inside the checkpointed workspace, so
+ the file travels with the session. Measured: `--resume` on an id the store does not hold prints
+ `Error: No session found matching '<id>'` and runs nothing, which would reach the runner as a
+ turn that failed for no stated reason."""
+ home = env.get("HOME") or ""
+ if not home or not session_id:
+ return False
+ return (pathlib.Path(home) / ".jcode" / "sessions" / f"{session_id}.json").is_file()
+
+
+_JCODE_ANTHROPIC_LISTED: list[str] | None = None
+
+
+def _jcode_anthropic_listed() -> list[str]:
+ """The Claude ids jcode's Anthropic provider runs, from the binary itself (`jcode model list`, a
+ static catalog: 125 ms with no reachable endpoint), read once per runner process."""
+ global _JCODE_ANTHROPIC_LISTED
+ if _JCODE_ANTHROPIC_LISTED is None:
+ try:
+ with tempfile.TemporaryDirectory(prefix="hr-jcode-models-") as home:
+ r = subprocess.run(["jcode", "model", "list", "--provider", "anthropic-api"], capture_output=True,
+ text=True, timeout=30, env={**_child_env(), "HOME": home, "JCODE_NO_TELEMETRY": "1",
+ "ANTHROPIC_AUTH_TOKEN": "placeholder",
+ "ANTHROPIC_BASE_URL": "http://127.0.0.1:9"})
+ _JCODE_ANTHROPIC_LISTED = [ln.strip() for ln in r.stdout.splitlines() if ln.strip().startswith("claude")]
+ except (OSError, subprocess.TimeoutExpired):
+ _JCODE_ANTHROPIC_LISTED = []
+ return _JCODE_ANTHROPIC_LISTED
+
+
+def _jcode_anthropic_model(model: str) -> str:
+ """The id jcode's Anthropic provider is handed for this model, or a refusal.
+
+ jcode runs ONLY the Claude ids its own catalog lists on that provider, and anything else it
+ replaces with its default, claude-opus-5-5, saying so only in its own log ("Model
+ claude-haiku-4-5-20251001 not supported by Anthropic provider"). Measured on the review instance
+ (2026-10-12): a turn asked for claude-haiku-4.5 through a direct Anthropic connection, the
+ connection's wire id was the dated claude-haiku-4-5-20251001, and Opus answered and was billed.
+ A dated id whose undated name jcode lists is the same model under jcode's name; any other id is
+ refused here rather than answered by a different model."""
+ listed = _jcode_anthropic_listed()
+ if not listed or model in listed:
+ return model # nothing to check against: the turn runs as asked
+ bare = re.sub(r"-\d{8}$", "", model)
+ if bare in listed:
+ return bare
+ raise HTTPException(400, f"jcode cannot run {model} on an Anthropic connection: its Anthropic provider "
+ f"runs only the models it lists ({', '.join(x for x in listed if '[' not in x)}) and "
+ f"would answer with {listed[0]} instead. Serve this model to jcode through an "
+ f"OpenAI-compatible connection, or use another base.")
+
+
+# The provider key jcode writes into a session for each --provider this runner passes it, read from
+# its own session files (2026-10-12): a turn on the Messages path stores `claude-api`, an
+# OpenAI-compatible one `openai-compatible`.
+_JCODE_PROVIDER_KEY = {"anthropic-api": "claude-api", "openai-compatible": "openai-compatible"}
+
+
+def _jcode_session_model(env: dict, session_id: str, model: str, provider_key: str = "") -> str:
+ """Point a resumed jcode session at the model THIS turn asked for; → what it held before.
+
+ jcode's `--model` and `--provider` are documented as the INITIAL ones ("Interactive sessions can
+ switch providers with /model"), and `jcode run` has no model flag of its own, so on `--resume`
+ the model stored with the session wins and the one the person just picked is ignored in silence.
+
+ MEASURED, with a flat control in the same run (2026-10-07): two turns in one session, haiku then
+ gemini — jcode served `anthropic/claude-haiku-4.5` twice, mimo served each model as asked. The
+ family tour is what exposed it, serving all TWELVE families with openai/gpt-5.4; the five-scenario
+ column had the same evidence and passed anyway, because its switch target is the subset's first
+ id and every jcode pair's `served` list simply had one entry where every mimo pair's had two.
+ Serving a model other than the one that was asked for is the failure this product's rule 2 exists
+ to catch, so the store is corrected rather than the switch being refused.
+
+ The file is jcode's own (`$HOME/.jcode/sessions/<id>.json`, inside the checkpointed home) and the
+ field is the one it writes there itself. Written beside and renamed, keeping the session uid, so a
+ crash cannot leave a half-written session file where jcode expects JSON."""
+ if not model:
+ return ""
+ path = (pathlib.Path(env.get("HOME") or "") / ".jcode" / "sessions" / f"{session_id}.json")
+ try:
+ doc = json.loads(path.read_text())
+ except Exception: # noqa: BLE001 — no store, unreadable, not JSON: the turn runs as it would have
+ return ""
+ if not isinstance(doc, dict):
+ return ""
+ was = str(doc.get("model") or "")
+ # The top-level field, and ONLY it. jcode also keeps the model in `env_snapshots[]` and in
+ # `model-usage-v1.sqlite3`; both were tried and NEITHER changed the one case this does not fix
+ # (below), so neither is in the tree — an intervention into another program's private state
+ # needs a measurement behind it, and these have none.
+ # WHAT THIS DOES NOT FIX, measured 2026-10-10 with a flat-layout control running the same
+ # script: A on gpt-5.4 served gpt-5.4; B on haiku KILLED mid-flight by a 10s cap; C asked for
+ # gemini and was served HAIKU — the killed turn's model — with this function's own log line
+ # showing it had pointed the store at gemini first. jcode's log has a `model` step inside
+ # `restore_session` that assigns it, and the source is not the session file, not
+ # `env_snapshots[]` and not `model-usage-v1.sqlite3` (all three tried and measured). The binary
+ # is stripped, so the mechanism stops being reachable from here. The normal path IS fixed and
+ # measured; a turn after a KILLED turn stays on the killed turn's model until someone with the
+ # source can say why. mimo, the control, is right on both paths.
+ # The PROVIDER KEY goes with the model. jcode joins the stored key onto the model when it
+ # restores the session, so after a turn on the Messages path (`claude-api`) a turn on an
+ # OpenAI-compatible connection asked its provider for `claude-api:openai/gpt-6.1-sol` and got a
+ # 404 (the five-scenario column's switch row, 2026-10-12); the other way round reaches no base
+ # url at all.
+ held_key = str(doc.get("provider_key") or "")
+ if was == model and (not provider_key or held_key == provider_key):
+ return ""
+ doc["model"] = model
+ if provider_key:
+ doc["provider_key"] = provider_key
+ tmp = path.with_suffix(".hr-tmp")
+ try:
+ tmp.write_text(json.dumps(doc))
+ st = path.stat()
+ os.chmod(tmp, st.st_mode & 0o7777)
+ os.chown(tmp, st.st_uid, st.st_gid)
+ os.replace(tmp, path)
+ except Exception: # noqa: BLE001 — the store is jcode's, not ours: if it cannot be rewritten the
+ try: # turn runs on the model the session already held, which is the behaviour
+ tmp.unlink() # before this function existed, and the temp file goes rather than staying
+ except OSError: # beside a file jcode will read.
+ pass
+ return ""
+ return was
+
+
+def _jcode_write_mcp(home: pathlib.Path, servers: list[dict] | None) -> bool:
+ """Write $HOME/.jcode/mcp.json, jcode's global MCP config. Returns whether anything was written.
+
+ STDIO ONLY, and that is jcode's own limit, stated in its README: "jcode currently supports
+ stdio (command-based) servers only; HTTP/SSE entries are recognized and skipped with a log
+ line." A remote server would therefore be dropped in silence, so jcode is in
+ _BRIDGED_TRANSPORTS for both http and sse and every remote entry arrives here as the bridge's
+ stdio launcher. Anything still carrying a bare url at this point has no transport this runtime
+ can reach and is skipped rather than written as a line the CLI will ignore."""
+ entries: dict = {}
+ for i, sv in enumerate(servers or []):
+ if not isinstance(sv, dict):
+ continue
+ name = _mcp_name(sv.get("name") or sv.get("id") or f"server{i}")
+ cmd = sv.get("command")
+ if not cmd:
+ continue
+ argv = cmd if isinstance(cmd, list) else [str(cmd)]
+ entry: dict = {"command": str(argv[0]),
+ "args": [str(a) for a in argv[1:]] + [str(a) for a 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()}
+ entries[name] = entry
+ if not entries:
+ return False
+ d = home / ".jcode"
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "mcp.json").write_text(json.dumps({"mcpServers": entries}, indent=2))
+ return True
+
+
+def _build_jcode(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,
+ resume_session_id: str | None = None, mcp_servers: list[dict] | None = None,
+ tools_disabled: list[str] | None = None) -> list[str]:
+ pr = provider or "openai-api"
+ if pr not in JCODE_PROVIDERS:
+ raise HTTPException(400, f"unknown jcode provider '{pr}' (one of {sorted(JCODE_PROVIDERS)})")
+ if not auth.base_url:
+ raise HTTPException(400, f"jcode provider '{pr}' needs a base_url (none configured)")
+ home = pathlib.Path(env.get("HOME") or cwd)
+ # The Messages path is taken ONLY for a connection that IS Anthropic (or one a custom
+ # integration declared as anthropic-format). Deliberately NOT for a claude id on an aggregator,
+ # which is where pi and opencode send one: jcode names only the model it was ASKED for, and an
+ # aggregator's Messages surface does not always say which model served, so a claude row there
+ # could record no served model and rule 2 would be unevaluable on it. An aggregator serves a claude id over
+ # chat/completions perfectly well, so those rows stay on the relay and stay measurable. This is
+ # the kilo finding, applied before it could become a column.
+ anthropic = auth.api_format == "anthropic" or (not auth.api_format and pr == "anthropic")
+ if auth.api_key:
+ # EVERY keyed turn rides the loopback relay, the Messages path and a custom endpoint
+ # included, as opencode's do. The real key never reaches the CLI's environment, where the
+ # agent's shell can read it; the relay reads the placeholder from a bearer or x-api-key
+ # and sends Anthropic the key the way it takes it (#352). It also decides whether rule 2
+ # can be evaluated at all: jcode names only the model it was ASKED for, so the served
+ # model comes from the relay reading the provider's own answer.
+ 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})
+ base = (auth.base_url or "").rstrip("/")
+ if anthropic:
+ # jcode's Messages path: ANTHROPIC_BASE_URL overrides the endpoint and ANTHROPIC_AUTH_TOKEN
+ # is sent as a bearer (README). The relay's ORIGIN: whether the client joins /v1/messages
+ # or /messages onto it, the relay strips one /v1 and joins the rest onto the connection's
+ # own base, as for hermes's Anthropic SDK (_relay_origin).
+ env["ANTHROPIC_BASE_URL"] = _relay_origin(base) if auth.api_key else base
+ model = _jcode_anthropic_model(model)
+ if auth.api_key:
+ env["ANTHROPIC_AUTH_TOKEN"] = auth.api_key
+ prov = "anthropic-api"
+ else:
+ if not auth.api_format and not base.endswith("/v1"):
+ base += "/v1"
+ env[_JCODE_BASE_ENV] = base
+ if auth.api_key:
+ env[_JCODE_KEY_ENV] = auth.api_key
+ prov = "openai-compatible"
+ # Anonymous telemetry (install count, version, OS, session activity, tool counts, crash
+ # reasons) is ON by default and prints a notice to stderr on every run. A sandbox running
+ # someone else's task does not phone home.
+ env["JCODE_NO_TELEMETRY"] = "1"
+ cmd = ["jcode",
+ # MANDATORY. Auto-update defaults to true, so without this the binary replaces itself
+ # mid-measurement — the exact failure checklist item 25 was written for. `--auto-update`
+ # takes no value (`--auto-update=false` is a clap usage error), so this is the off switch.
+ "--no-update",
+ # Suppress the status chatter so the stream the runner reads is the NDJSON and nothing else.
+ "--quiet",
+ "--provider", prov, "--model", model]
+ if resume_session_id and _jcode_has_session(env, resume_session_id):
+ # before --resume, not after: the model this turn asked for has to be in the store jcode is
+ # about to read, because its own --model is only the session's INITIAL one.
+ was = _jcode_session_model(env, resume_session_id, model, _JCODE_PROVIDER_KEY.get(prov, ""))
+ if was:
+ print(f"[jcode] session {resume_session_id} held model {was}; this turn asked for "
+ f"{model}, so the store was pointed at it", flush=True)
+ cmd += ["--resume", resume_session_id]
+ elif resume_session_id:
+ print(f"[resume] jcode: session {resume_session_id} not in this workspace — starting fresh",
+ flush=True)
+ if tools_disabled:
+ # A real per-tool switch, applied AFTER the tool profile, so it is enforcement rather than
+ # instruction: the model's own list came back without the disabled name. Names outside this
+ # runtime's set are dropped, so a label from another backend narrows nothing.
+ names = sorted({x.split(" (")[0].strip().lower() for x in tools_disabled if x and x.strip()}
+ & ALL_JCODE_TOOLS)
+ if names:
+ cmd += ["--disabled-tools", ",".join(names)]
+ if not _jcode_write_mcp(home, mcp_servers) and mcp_servers:
+ print("[jcode] every configured MCP server was remote and could not be bridged — "
+ "this turn runs without them", flush=True)
+ cmd += ["run", "--ndjson"]
+ cmd += ["--", prompt] if prompt.startswith("-") else [prompt]
+ return cmd
+
# Registry — providers/default_model/normalize per backend. The cmd build + run loop is dispatched
@@ -8799,6 +10516,28 @@ BACKENDS = {
"systemone": {"providers": sorted(SYSTEMONE_PROVIDERS),
"default_model": SYSTEMONE_DEFAULT_MODEL,
"normalize": _claude_passthrough},
+ # MiMo Code is an opencode FORK whose `run --format json` stream is opencode's line for line
+ # (measured on 0.1.15), so it shares opencode's normaliser rather than carrying a copy — the
+ # same relationship omp has to pi.
+ "mimo": {"providers": sorted(MIMO_PROVIDERS), "default_model": MIMO_DEFAULT_MODEL,
+ "normalize": _opencode_to_claude},
+ # Gajae-Code speaks pi's `--mode json` events with pi's field names, so _gajae_to_claude
+ # delegates to pi's and adds only the one event pi has no branch for (agent_failed).
+ "gajae": {"providers": sorted(GAJAE_PROVIDERS), "default_model": GAJAE_DEFAULT_MODEL,
+ "normalize": _gajae_to_claude},
+ # jcode's NDJSON is its OWN schema (src/cli/commands.rs emit_ndjson_event), including a `tokens`
+ # event the turn has to ACCUMULATE because its own `done.usage` holds only the last request's.
+ "jcode": {"providers": sorted(JCODE_PROVIDERS), "default_model": JCODE_DEFAULT_MODEL,
+ "normalize": _jcode_to_claude},
+ # opensquilla puts content-free progress events on stderr and one result object on stdout; the
+ # normaliser reads both off the merged stream and its eof replays the transcript the CLI writes.
+ "opensquilla": {"providers": sorted(OPENSQUILLA_PROVIDERS),
+ "default_model": OPENSQUILLA_DEFAULT_MODEL,
+ "normalize": _opensquilla_to_claude},
+ # The nanobot driver emits claude's stream-json itself (see nanobot_driver.py), so its
+ # normaliser is the passthrough, as systemone's is.
+ "nanobot": {"providers": sorted(NANOBOT_PROVIDERS), "default_model": NANOBOT_DEFAULT_MODEL,
+ "normalize": _claude_passthrough},
}
@@ -9982,6 +11721,25 @@ def _produced_list(ws: str) -> list[dict]:
return [{"path": k, "status": v, "mtime": _mtime(k)} for k, v in seen.items()]
+def _produced_visible(ws: str) -> list[dict]:
+ """_produced_list, with every path named the way the AGENT names it.
+
+ git runs on the session dir, which is one level above the agent's workspace on the one base that
+ nests (see _visible_root). A card reading "workspace/report.md" names a directory the user never
+ typed and no other base shows, so the prefix comes off here — the one place the cards and their
+ download both resolve through. A path OUTSIDE the visible root (an app's PUT that no turn has
+ adopted yet) is left alone, and GET /file resolves either shape."""
+ out = _produced_list(ws)
+ root = _visible_root(ws)
+ if root == ws:
+ return out
+ pre = os.path.relpath(root, ws) + "/"
+ for f in out:
+ if f["path"].startswith(pre):
+ f["path"] = f["path"][len(pre):]
+ return out
+
+
def _produced_ack(ws: str) -> str:
"""Advance the cursor: commit the current state and point the ref at it. Called by the gateway
ONLY after it has captured the listed files, which is the one thing that makes 'collected'
@@ -9998,8 +11756,7 @@ def _produced_ack(ws: str) -> str:
def produced(identifier: str = "") -> dict:
"""Files changed since the last acknowledged collection — surviving checkpoints, crashes and
cancels in between. Excludes internal state / scratch / secrets / vcs."""
- ws = _ws(identifier)
- out = _produced_list(ws)
+ out = _produced_visible(_ws(identifier))
return {"files": out, "count": len(out)}
@@ -10012,7 +11769,12 @@ def produced_ack(identifier: str = "") -> dict:
@app.get("/file")
def get_file(path: str, identifier: str = "") -> Response:
"""Raw bytes of a workspace file (for downloading turn-produced container files)."""
- dest = _safe_join(_ws(identifier), path)
+ ws = _ws(identifier)
+ # the visible root first, because that is how /produced named it; the session root second, so a
+ # path written before the agent's workspace existed still downloads.
+ dest = _safe_join(_visible_root(ws), path)
+ if dest is None or not dest.is_file():
+ dest = _safe_join(ws, path)
if dest is None or not dest.is_file():
raise HTTPException(404, "file not found")
media = mimetypes.guess_type(str(dest))[0] or "application/octet-stream"
@@ -10177,7 +11939,11 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
# silently dropped wherever it can't be a hard block, so it goes in this set rather than
# being left out of it — the same class of gap this comment already names for hermes.
agent_doc = req.agent_doc or ""
- if backend in ("codex", "hermes", "dsh", "gemini") and req.tools_disabled:
+ # opensquilla is in this set for the same reason gemini is: `--permissions` picks a posture
+ # (restricted / bypass / full) and there is no per-tool deny list anywhere on its agent CLI, so
+ # UHP §4.3 requires the disabled set be conveyed as a standing instruction rather than silently
+ # dropped. nanobot, mimo, gajae and jcode are NOT here — each has a real switch.
+ if backend in ("codex", "hermes", "dsh", "gemini", "opensquilla") and req.tools_disabled:
_off = ", ".join(t for t in req.tools_disabled if t)
if _off:
agent_doc = ((agent_doc + "\n\n") if agent_doc.strip() else "") + \
@@ -10380,6 +12146,40 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
cmd = _build_kilo(req.provider, auth, model, req.prompt, cwd, env,
resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,
skills_dir=skills_dir, tools_disabled=req.tools_disabled)
+ elif backend == "mimo":
+ model = model or MIMO_DEFAULT_MODEL
+ # Same door as opencode's: the `skills` key takes arbitrary paths, so the directory
+ # _write_skills has already produced is named in mimo.json.
+ skills_dir = os.path.join(cwd, ".harness", "skills") if installed_skills else None
+ cmd = _build_mimo(req.provider, auth, model, req.prompt, cwd, env,
+ resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,
+ skills_dir=skills_dir, tools_disabled=req.tools_disabled)
+ elif backend == "gajae":
+ model = model or GAJAE_DEFAULT_MODEL
+ # Skills are already under .harness/home/.gjc/agent/skills, gjc's own user-global root, so
+ # there is nothing to name on the command line (pi's and omp's arrangement).
+ cmd = _build_gajae(req.provider, auth, model, req.prompt, cwd, env,
+ resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,
+ tools_disabled=req.tools_disabled, vision=bool(req.vision))
+ elif backend == "jcode":
+ model = model or JCODE_DEFAULT_MODEL
+ cmd = _build_jcode(req.provider, auth, model, req.prompt, cwd, env,
+ resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,
+ tools_disabled=req.tools_disabled)
+ elif backend == "opensquilla":
+ model = model or OPENSQUILLA_DEFAULT_MODEL
+ cmd = _build_opensquilla(req.provider, auth, model, req.prompt, cwd, env,
+ resume_session_id=req.resume_session_id,
+ mcp_servers=req.mcp_servers,
+ tools_disabled=req.tools_disabled, max_turns=req.max_turns)
+ elif backend == "nanobot":
+ model = model or NANOBOT_DEFAULT_MODEL
+ cmd = _build_nanobot(req.provider, auth, model, req.prompt, cwd, env,
+ resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,
+ tools_disabled=req.tools_disabled, max_turns=req.max_turns,
+ # the harness's own variables and the platform's HR_ ones a turn carries
+ caller_keys=[*_caller_env(req.env),
+ *(k for k in (req.env or {}) if isinstance(k, str) and k.startswith("HR_"))])
else:
mcp_config = _write_mcp_config_claude(cwd, req.mcp_servers)
# Only a package that is ALSO a Claude Code plugin gets --plugin-dir; an Agent Plugins
diff --git a/runner/tests/fixtures/batch3/gajae-provider-401.ndjson b/runner/tests/fixtures/batch3/gajae-provider-401.ndjson
new file mode 100644
index 00000000..a14e115c
--- /dev/null
+++ b/runner/tests/fixtures/batch3/gajae-provider-401.ndjson
@@ -0,0 +1,5 @@
+{"type": "session", "id": "01a0fec9-6aed-743b-9fe0-986e29fae356"}
+{"type": "message_end", "message": {"role": "custom", "content": "<system-reminder>…trimmed for the fixture…</system-reminder>"}}
+{"type": "message_end", "message": {"role": "user", "content": [{"type": "text", "text": "Reply with exactly OK."}]}}
+{"type": "message_end", "message": {"role": "assistant", "content": [], "model": "openai/gpt-6-luna", "usage": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 0, "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}}, "stopReason": "error", "errorStatus": 401, "errorMessage": "401 Authentication failed. Create an API key and set in AI_GATEWAY_API_KEY environment variable: https://example/keys failed. Create an API key and set in AI_GATEWAY_API_KEY environment variable: https://example/keys (type=authentication_error)"}}
+{"type": "agent_end"}
diff --git a/runner/tests/fixtures/batch3/gajae-write-file.ndjson b/runner/tests/fixtures/batch3/gajae-write-file.ndjson
new file mode 100644
index 00000000..5152573a
--- /dev/null
+++ b/runner/tests/fixtures/batch3/gajae-write-file.ndjson
@@ -0,0 +1,11 @@
+{"type": "session", "id": "01a0fec9-049a-7124-a699-190b3038105c"}
+{"type": "message_end", "message": {"role": "custom", "content": "<system-reminder>…trimmed for the fixture…</system-reminder>"}}
+{"type": "message_end", "message": {"role": "user", "content": [{"type": "text", "text": "Write the single word banana into a new file probe.txt using your write tool, then reply with exactly DONE."}]}}
+{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "toolCall", "id": "call_Jno1EHG9x1xHNYKQ1zD6EUlZ", "name": "write", "arguments": {"_i": "Creating requested probe file", "path": "probe.txt", "content": "banana"}, "intent": "Creating requested probe file"}], "model": "openai/gpt-6-luna", "usage": {"input": 11127, "output": 30, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 11157, "cost": {"input": 0.0011127, "output": 1.4999999999999999e-05, "cacheRead": 0, "cacheWrite": 0, "total": 0.0011277000000000001}}, "stopReason": "toolUse"}}
+{"type": "tool_execution_start", "toolCallId": "call_Jno1EHG9x1xHNYKQ1zD6EUlZ", "toolName": "write", "args": {"path": "probe.txt", "content": "banana"}}
+{"type": "tool_execution_end", "toolCallId": "call_Jno1EHG9x1xHNYKQ1zD6EUlZ", "result": {"content": [{"type": "text", "text": "Successfully wrote 6 bytes to probe.txt"}], "details": {}}, "isError": false}
+{"type": "message_end", "message": {"role": "toolResult", "content": [{"type": "text", "text": "Successfully wrote 6 bytes to probe.txt"}]}}
+{"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "contentIndex": 0, "delta": "DONE"}}
+{"type": "message_update", "assistantMessageEvent": {"type": "text_end", "contentIndex": 0}}
+{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "DONE"}], "model": "openai/gpt-6-luna", "usage": {"input": 51, "output": 5, "cacheRead": 11124, "cacheWrite": 0, "totalTokens": 11180, "cost": {"input": 5.1e-06, "output": 2.4999999999999998e-06, "cacheRead": 0.00011124, "cacheWrite": 0, "total": 0.00011884}}, "stopReason": "stop"}}
+{"type": "agent_end"}
diff --git a/runner/tests/fixtures/batch3/jcode-provider-401.ndjson b/runner/tests/fixtures/batch3/jcode-provider-401.ndjson
new file mode 100644
index 00000000..1d79c90e
--- /dev/null
+++ b/runner/tests/fixtures/batch3/jcode-provider-401.ndjson
@@ -0,0 +1,4 @@
+{"model": "openai/gpt-6-luna", "provider": "openrouter", "session_id": "session_dog_1790981247328_eb623c91ec44a141", "type": "start"}
+{"connection": "https/sse", "type": "connection_type"}
+{"phase": "sending request", "type": "connection_phase"}
+{"message": "OpenAI-compatible chat request failed\n endpoint: https://ai-gateway.vercel.sh/v1/chat/completions\n model: openai/gpt-6-luna\n auth: OPENAI_COMPAT_API_KEY\n status: 401 Unauthorized\n response: {\"error\":{\"message\":\"Authentication failed. Create an API key and set in AI_GATEWAY_API_KEY environment variable: https://example/keys check network connectivity, DNS/TLS, that the base URL includes the API version (usually /v1), and that the model exists on the provider.", "model": "openai/gpt-6-luna", "provider": "openrouter", "session_id": "session_dog_1790981247328_eb623c91ec44a141", "type": "error"}
diff --git a/runner/tests/fixtures/batch3/jcode-write-file.ndjson b/runner/tests/fixtures/batch3/jcode-write-file.ndjson
new file mode 100644
index 00000000..cdf7aaf9
--- /dev/null
+++ b/runner/tests/fixtures/batch3/jcode-write-file.ndjson
@@ -0,0 +1,16 @@
+{"model": "openai/gpt-6-luna", "provider": "openrouter", "session_id": "session_sloth_1790981189870_91a9d9ad23dfe74a", "type": "start"}
+{"connection": "https/sse", "type": "connection_type"}
+{"phase": "sending request", "type": "connection_phase"}
+{"phase": "waiting for response", "type": "connection_phase"}
+{"id": "call_DKi1n58dmH4fXDBtF8sbZWGU", "name": "write", "type": "tool_start"}
+{"id": "call_DKi1n58dmH4fXDBtF8sbZWGU", "name": "write", "type": "tool_exec"}
+{"stop_reason": "tool_calls", "type": "message_end"}
+{"cache_creation_input": 175, "cache_read_input": 10431, "input": 10609, "output": 63, "type": "tokens"}
+{"error": null, "id": "call_DKi1n58dmH4fXDBtF8sbZWGU", "name": "write", "output": "Created probe.txt (1 lines):\n1+ banana\n\nFile diff:\n```diff\n--- /dev/null\n+++ b/probe.txt\n@@ -0,0 +1 @@\n+banana\n\\ No newline at end of file\n```\n", "type": "tool_done"}
+{"connection": "https/sse", "type": "connection_type"}
+{"phase": "sending request", "type": "connection_phase"}
+{"phase": "waiting for response", "type": "connection_phase"}
+{"text": "DONE", "type": "text_delta"}
+{"stop_reason": "stop", "type": "message_end"}
+{"cache_creation_input": 139, "cache_read_input": 10606, "input": 10748, "output": 5, "type": "tokens"}
+{"connection_phase": "waiting for response", "connection_type": "https/sse", "model": "openai/gpt-6-luna", "provider": "openrouter", "session_id": "session_sloth_1790981189870_91a9d9ad23dfe74a", "status_detail": null, "text": "DONE", "type": "done", "upstream_provider": null, "usage": {"cache_creation_input_tokens": 139, "cache_read_input_tokens": 10606, "input_tokens": 10748, "output_tokens": 5}}
diff --git a/runner/tests/fixtures/batch3/mimo-first-turn.ndjson b/runner/tests/fixtures/batch3/mimo-first-turn.ndjson
new file mode 100644
index 00000000..c184ae8a
--- /dev/null
+++ b/runner/tests/fixtures/batch3/mimo-first-turn.ndjson
@@ -0,0 +1,3 @@
+{"type": "step_start", "timestamp": 1790981943890, "sessionID": "ses_ffe5f01285330ffeQ7Q0ZNlKxc", "part": {"id": "prt_g001a0fed7b251001oTQC67Bwz", "messageID": "msg_g001a0fed7ae7f001yobQXinFb", "sessionID": "ses_ffe5f01285330ffeQ7Q0ZNlKxc", "type": "step-start"}}
+{"type": "text", "timestamp": 1790981944654, "sessionID": "ses_ffe5f01285330ffeQ7Q0ZNlKxc", "part": {"id": "prt_g001a0fed7b37a001G5akEnPJg", "messageID": "msg_g001a0fed7ae7f001yobQXinFb", "sessionID": "ses_ffe5f01285330ffeQ7Q0ZNlKxc", "type": "text", "text": "OK", "time": {"start": 1790981944186, "end": 1790981944649}}}
+{"type": "step_finish", "timestamp": 1790981944655, "sessionID": "ses_ffe5f01285330ffeQ7Q0ZNlKxc", "part": {"id": "prt_g001a0fed7b54d001rpR7kVL2u", "reason": "stop", "messageID": "msg_g001a0fed7ae7f001yobQXinFb", "sessionID": "ses_ffe5f01285330ffeQ7Q0ZNlKxc", "type": "step-finish", "tokens": {"total": 14450, "input": 14413, "output": 7, "reasoning": 30, "cache": {"write": 0, "read": 0}}, "cost": 0}}
diff --git a/runner/tests/test_batch3_backends.py b/runner/tests/test_batch3_backends.py
new file mode 100644
index 00000000..b79ba355
--- /dev/null
+++ b/runner/tests/test_batch3_backends.py
@@ -0,0 +1,1137 @@
+"""The five bases added together: mimo, gajae, jcode, opensquilla, nanobot.
+
+Everything asserted here was MEASURED against the pinned build named beside it, on 2026-10-02, not
+read off documentation. Each test pins one thing that would otherwise fail SILENTLY — the class of
+defect the last three harness PRs were taken over for:
+
+ * a shared helper reused for a fork whose spelling differs by one flag (mimo)
+ * a normaliser that treats a provider failure as an answer (gajae's agent_failed)
+ * usage read from the field the CLI offers rather than the one that is true (jcode's done.usage,
+ which holds only the LAST request's numbers)
+ * a default that substitutes the model (opensquilla's router) or that cannot fit the prompt
+ (its 8k assumption for a generic endpoint)
+ * a tool policy applied at one tool source and not the other (nanobot's session policy)
+
+Pinned builds: @mimo-ai/cli 0.1.15 · gjc 0.18.5 · jcode v0.90.0 · opensquilla 0.5.6 · nanobot-ai 0.3.5
+"""
+import json
+import pathlib
+import sys
+import tempfile
+
+import pytest
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+from server import (ALL_GAJAE_TOOLS, ALL_JCODE_TOOLS, ALL_NANOBOT_TOOLS, # noqa: E402
+ Auth, BACKENDS, CHECKPOINT_EXCLUDE, _agent_doc_path, _build_gajae,
+ _build_jcode, _build_mimo, _build_nanobot, _build_opensquilla,
+ _BRIDGED_TRANSPORTS, _gajae_to_claude, _jcode_eof, _jcode_to_claude,
+ _opencode_to_claude, _opensquilla_eof, _opensquilla_to_claude,
+ _opensquilla_transcript,
+ _jcode_session_model, _mcp_url_is_loopback, _opensquilla_usage,
+ _produced_visible, _resume_lost, _sse_bridges,
+ _visible_root,
+ _write_input_files, _write_skills)
+
+UP = "https://up.example/v1"
+
+
+def _ws():
+ d = tempfile.mkdtemp()
+ (pathlib.Path(d) / ".harness" / "home").mkdir(parents=True)
+ return d
+
+
+def _norm(fn, lines, model="gpt-5.4", cwd=""):
+ state: dict = {"model": model, "final": "", "cwd": cwd}
+ out = []
+ for ln in lines:
+ out += fn(ln, state)
+ return out, state
+
+
+# ── registration: the five places a missing row fails silently ────────────────────────────────
+
+def test_every_base_is_registered():
+ # gajae is in BACKENDS (the runner can execute it) but NOT in the gateway's catalogs, so the
+ # product never asks it to — gateway/tests/test_gajae_not_offered.py pins that and says why.
+ for b in ("mimo", "gajae", "jcode", "opensquilla", "nanobot"):
+ assert b in BACKENDS, b
+ assert BACKENDS[b]["providers"], b
+ assert BACKENDS[b]["default_model"], b
+ assert BACKENDS[b]["normalize"] is not None, b
+
+
+def test_all_five_read_agents_md():
+ # Measured per CLI (see _agent_doc_path's comment). Getting this wrong writes the file and the
+ # agent never sees it, so the workspace contract never arrives and nothing says so.
+ for b in ("mimo", "gajae", "jcode", "opensquilla", "nanobot"):
+ assert _agent_doc_path("/w", b).name == "AGENTS.md", b
+
+
+def test_skills_land_where_each_loader_looks():
+ want = {
+ "mimo": ".harness/skills", # named in mimo.json's skills.paths
+ "gajae": ".harness/home/.gjc/agent/skills", # gjc's canonical user root
+ "jcode": ".harness/home/.jcode/skills", # jcode's global root
+ "opensquilla": ".harness/opensquilla/skills", # its managed root = $OPENSQUILLA_STATE_DIR/skills
+ "nanobot": "workspace/skills", # the ONE path its loader reads, inside
+ # the nested workspace (see _NANOBOT_WS)
+ }
+ for backend, rel in want.items():
+ d = _ws()
+ _write_skills(d, [{"name": "demo", "content": "# demo"}], backend=backend)
+ assert (pathlib.Path(d) / rel / "demo" / "SKILL.md").is_file(), backend
+
+
+# ── mimo: an opencode fork, and every difference is a parameter rather than a copy ────────────
+
+def test_mimo_argv_is_opencodes_with_its_own_spellings():
+ d, env = _ws(), {}
+ cmd = _build_mimo("openai-api", Auth(api_key="sk-t", base_url=UP), "gpt-5.4", "do it", d, env)
+ assert cmd[0] == "mimo" and cmd[1] == "run"
+ assert "--format" in cmd and cmd[cmd.index("--format") + 1] == "json"
+ # Nothing runs unattended without this: measured, the turn stops at the first write.
+ assert "--dangerously-skip-permissions" in cmd
+ assert "--pure" in cmd and "--thinking" in cmd
+ # NOT opencode's --auto / --session: the fork renamed both.
+ assert "--auto" not in cmd
+ assert cmd[-1] == "do it"
+ # Its own config env var and file name, so two backends in one workspace cannot collide.
+ assert env["MIMOCODE_CONFIG"].endswith("/.harness/mimo.json")
+ assert (pathlib.Path(d) / ".harness" / "mimo.json").is_file()
+ assert not (pathlib.Path(d) / ".harness" / "opencode.json").exists()
+
+
+def test_mimo_config_is_the_opencode_schema_with_the_key_named_not_written():
+ d, env = _ws(), {}
+ # deepseek-v4-pro rather than a gpt-5.x id: the fork kept _opencode_npm's per-model split, and
+ # a gpt-5.x id would correctly pick @ai-sdk/openai (the Responses package) instead.
+ _build_mimo("openai-api", Auth(api_key="sk-secret", base_url=UP), "deepseek-v4-pro", "hi", d, env,
+ tools_disabled=["bash (Shell)"])
+ cfg = json.loads((pathlib.Path(d) / ".harness" / "mimo.json").read_text())
+ assert cfg["provider"]["hr"]["npm"] == "@ai-sdk/openai-compatible"
+ assert cfg["provider"]["hr"]["options"]["apiKey"] == "{env:HR_MIMO_KEY}"
+ # The real key never reaches the CLI at all: every OpenAI-shape turn rides the loopback relay,
+ # so what the config names and what the environment carries is a per-turn PLACEHOLDER.
+ assert "sk-secret" not in json.dumps(cfg)
+ assert env["HR_MIMO_KEY"].startswith("hr-relay-") and env["HR_MIMO_KEY"] != "sk-secret"
+ assert cfg["permission"] == {"bash": "deny"}
+ # opencode's snapshot repo is a git repo of the workspace under $HOME; left on it reached
+ # 699 MB in twenty turns (#193). The fork inherited it, so it is turned off here too.
+ assert cfg["snapshot"] is False
+
+
+def test_mimo_shares_opencodes_normaliser():
+ # The stream is opencode's line for line, measured: {type,timestamp,sessionID,part}.
+ assert BACKENDS["mimo"]["normalize"] is _opencode_to_claude
+ evs, state = _norm(_opencode_to_claude, [
+ {"type": "step_start", "sessionID": "ses_x", "part": {"type": "step-start"}},
+ {"type": "text", "sessionID": "ses_x", "part": {"type": "text", "text": "OK"}},
+ {"type": "step_finish", "sessionID": "ses_x",
+ "part": {"type": "step-finish", "reason": "stop",
+ "tokens": {"total": 14450, "input": 14413, "output": 7, "reasoning": 30,
+ "cache": {"write": 0, "read": 0}}}},
+ ])
+ assert evs[0]["type"] == "system" and evs[0]["session_id"] == "ses_x"
+ assert state["final"] == "OK"
+
+
+def test_mimo_resume_is_not_claimed_for_a_session_this_workspace_does_not_hold():
+ # Its SQLite store is opencode's under another name, $HOME/.local/share/mimocode/mimocode.db.
+ # Naming a session it does not hold exits 1 before the first event, which would wedge every
+ # later turn in the conversation rather than one.
+ d = _ws()
+ env = {"HOME": str(pathlib.Path(d) / ".harness" / "home")}
+ cmd = _build_mimo("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ resume_session_id="ses_gone")
+ assert "-s" not in cmd
+ assert _resume_lost("mimo", cmd, "ses_gone", d) == "ses_gone"
+ db = pathlib.Path(env["HOME"]) / ".local" / "share" / "mimocode"
+ db.mkdir(parents=True, exist_ok=True)
+ (db / "mimocode.db").write_bytes(b"...ses_here...")
+ cmd = _build_mimo("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ resume_session_id="ses_here")
+ assert cmd[cmd.index("-s") + 1] == "ses_here"
+ assert _resume_lost("mimo", cmd, "ses_here", d) is None
+
+
+# ── gajae: pi's stream, pi's normaliser, and the one event pi has no branch for ────────────────
+
+def test_gajae_argv():
+ d, env = _ws(), {"HOME": str(pathlib.Path(_ws()) / "h")}
+ cmd = _build_gajae("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "do it", d, env)
+ assert cmd[0] == "gjc" and "-p" in cmd
+ assert cmd[cmd.index("--mode") + 1] == "json"
+ # Fully qualified, because --model is a FUZZY pattern and a custom provider also gets
+ # auto-enabled /v1/models discovery: a bare family name among hundreds of discovered ids is a
+ # substitution waiting to happen.
+ assert cmd[cmd.index("--model") + 1] == "hr/gpt-5.4"
+ # Session storage AND lookup inside .harness/, so the transcript is checkpointed and is never
+ # handed back as a produced file.
+ assert cmd[cmd.index("--session-dir") + 1].endswith("/.harness/gajae-sessions")
+ # The conventional MCP autoload includes a file IN the workspace (.gjc/mcp.json) that a task
+ # could write and the next turn would execute — pi's --no-extensions hole, closed the same way.
+ assert "--no-mcp" in cmd
+ assert cmd[-1] == "do it"
+ # A signed model-preset registry fetched at start-up can rewrite which model a preset names.
+ assert env["GJC_MODEL_PRESET_REGISTRY_DISABLED"] == "1"
+
+
+def test_gajae_models_yml_names_the_key_rather_than_holding_it():
+ d = _ws()
+ env = {"HOME": str(pathlib.Path(d) / ".harness" / "home")}
+ # deepseek-v4-pro, not a gpt-5.x id: pi's own api split sends the gpt-5 line to
+ # openai-responses, which is correct and is asserted separately below.
+ _build_gajae("openai-api", Auth(api_key="sk-secret", base_url=UP), "deepseek-v4-pro", "hi", d, env)
+ mv = pathlib.Path(env["HOME"], ".gjc", "agent", "models.yml").read_text()
+ assert "sk-secret" not in mv
+ assert json.loads(mv)["providers"]["hr"]["apiKey"] == "HR_GAJAE_KEY"
+ assert json.loads(mv)["providers"]["hr"]["api"] == "openai-completions"
+ # What the variable holds is the relay's per-turn placeholder, never the provider key: the
+ # file is in the checkpointed workspace, and the real key stays in the runner process.
+ assert env["HR_GAJAE_KEY"].startswith("hr-relay-") and env["HR_GAJAE_KEY"] != "sk-secret"
+ # The gpt-5 line goes to the Responses api instead — pi's split, inherited.
+ d2 = _ws(); env2 = {"HOME": str(pathlib.Path(d2) / ".harness" / "home")}
+ _build_gajae("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d2, env2)
+ mv2 = json.loads(pathlib.Path(env2["HOME"], ".gjc", "agent", "models.yml").read_text())
+ assert mv2["providers"]["hr"]["api"] == "openai-responses"
+ # Excluded from the checkpoint anyway: a future build reading apiKey as a literal must not turn
+ # this file into a leak.
+ assert "./.harness/home/.gjc/agent/models.yml" in CHECKPOINT_EXCLUDE
+
+
+def test_gajae_tool_allowlist_is_the_full_set_minus_the_disabled_one():
+ d = _ws()
+ env = {"HOME": str(pathlib.Path(d) / ".harness" / "home")}
+ cmd = _build_gajae("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ tools_disabled=["write (File Write)"])
+ allow = next(a for a in cmd if a.startswith("--tools="))[len("--tools="):].split(",")
+ assert "write" not in allow
+ assert set(allow) == ALL_GAJAE_TOOLS - {"write"}
+ # A disable list naming nothing this runtime has is not a constraint, so nothing is sent — an
+ # allowlist that removes nothing would only risk narrowing the set by accident.
+ cmd = _build_gajae("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ tools_disabled=["WebSearch"])
+ assert not any(a.startswith("--tools") for a in cmd)
+
+
+def test_gajae_provider_failure_is_a_failed_turn_not_an_answer():
+ # MEASURED against the pinned binary with a bad key: the turn ends on an assistant message_end
+ # with stopReason "error" and the provider's sentence in errorMessage, and the CLI exits 1.
+ evs, state = _norm(_gajae_to_claude, [
+ {"type": "session", "id": "01a0", "version": 5},
+ {"type": "message_end", "message": {
+ "role": "assistant", "content": [], "model": "gpt-5.4", "stopReason": "error",
+ "errorStatus": 401, "errorMessage": "401 Authentication failed.",
+ "usage": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}}},
+ {"type": "agent_end", "messages": []},
+ ])
+ res = evs[-1]
+ assert res["type"] == "result" and res["is_error"] is True
+ assert "401 Authentication failed." in res["result"]
+
+
+def test_gajae_agent_failed_is_the_reason_and_never_the_answer():
+ # print-mode.ts writes this when the terminal disposition is a failure no message_end reported.
+ # pi's normaliser has no branch for it, so without this one the turn would complete with
+ # whatever text came before as its answer.
+ evs, state = _norm(_gajae_to_claude, [
+ {"type": "session", "id": "01a0"},
+ {"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "delta": "let me look"}},
+ {"type": "agent_failed", "error": {"code": "empty_turn", "message": "the model returned nothing"}},
+ {"type": "agent_end", "messages": []},
+ ])
+ res = evs[-1]
+ assert res["is_error"] is True
+ assert res["result"] == "the model returned nothing"
+
+
+def test_gajae_answer_that_merely_mentions_an_error_still_passes():
+ # The anchored-match rule: a coding agent writes about errors constantly, and an unanchored
+ # match turns real answers into failures (the goose lesson). Nothing here sets the error state.
+ evs, _ = _norm(_gajae_to_claude, [
+ {"type": "session", "id": "01a0"},
+ {"type": "message_end", "message": {
+ "role": "assistant", "model": "gpt-5.4", "stopReason": "stop",
+ "content": [{"type": "text", "text": "I fixed the error in parse(): it threw on empty input."}],
+ "usage": {"input": 10, "output": 5}}},
+ {"type": "agent_end", "messages": []},
+ ])
+ assert evs[-1]["is_error"] is False
+ assert "I fixed the error" in evs[-1]["result"]
+
+
+def test_gajae_resume_only_when_the_session_file_is_here():
+ d = _ws()
+ env = {"HOME": str(pathlib.Path(d) / ".harness" / "home")}
+ cmd = _build_gajae("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ resume_session_id="01a0-gone")
+ assert "-r" not in cmd and _resume_lost("gajae", cmd, "01a0-gone", d) == "01a0-gone"
+ sd = pathlib.Path(d, ".harness", "gajae-sessions")
+ sd.mkdir(parents=True, exist_ok=True)
+ (sd / "2026-10-02T22-43-45-033Z_01a0-here.jsonl").write_text("{}")
+ cmd = _build_gajae("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ resume_session_id="01a0-here")
+ assert cmd[cmd.index("-r") + 1] == "01a0-here"
+ assert _resume_lost("gajae", cmd, "01a0-here", d) is None
+
+
+# ── jcode: its own schema, and two measured facts a naive reading gets wrong ───────────────────
+
+def test_jcode_argv_pins_the_version_under_the_measurement():
+ d, env = _ws(), {"HOME": str(pathlib.Path(_ws()) / "h")}
+ cmd = _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "do it", d, env)
+ assert cmd[0] == "jcode"
+ # MANDATORY: auto-update defaults to true, so without this the binary replaces itself midway
+ # through a measurement — the Muse Code failure, written into the argv.
+ assert "--no-update" in cmd
+ assert cmd[cmd.index("--provider") + 1] == "openai-compatible"
+ assert cmd[cmd.index("--model") + 1] == "gpt-5.4"
+ assert cmd[-3:] == ["run", "--ndjson", "do it"]
+ # The relay token rides the ENVIRONMENT, which is what _relay_served_model keys off: a backend
+ # whose credential rides argv or a file leaves matrix rule 2 unevaluable (the openhands defect).
+ assert env["JCODE_OPENAI_COMPAT_API_BASE"].startswith("http")
+ assert env["OPENAI_COMPAT_API_KEY"]
+ # Telemetry is on by default and prints a notice on every run.
+ assert env["JCODE_NO_TELEMETRY"] == "1"
+
+
+def test_jcode_disabled_tools_are_filtered_to_names_this_runtime_has():
+ d, env = _ws(), {"HOME": str(pathlib.Path(_ws()) / "h")}
+ cmd = _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ tools_disabled=["write (File Write)", "NotATool"])
+ assert cmd[cmd.index("--disabled-tools") + 1] == "write"
+ assert "write" in ALL_JCODE_TOOLS and "notatool" not in ALL_JCODE_TOOLS
+
+
+def test_jcode_usage_is_summed_across_requests_and_netted_of_both_caches():
+ # The two facts: `done.usage` holds only the LAST request's numbers (NdjsonRunState.usage is
+ # assigned, never accumulated), and `input` is GROSS — jcode's own OpenAI client says
+ # "input_tokens is the total, including both cache-read and cache-write subsets".
+ # Measured turn: tokens(10609/63, read 10431, write 175) then tokens(10748/5, read 10606,
+ # write 139), with done.usage reporting only the second.
+ evs, state = _norm(_jcode_to_claude, [
+ {"type": "start", "session_id": "session_sloth_1", "model": "gpt-5.4"},
+ {"type": "tokens", "input": 10609, "output": 63, "cache_read_input": 10431,
+ "cache_creation_input": 175},
+ {"type": "tokens", "input": 10748, "output": 5, "cache_read_input": 10606,
+ "cache_creation_input": 139},
+ {"type": "text_delta", "text": "DONE"},
+ {"type": "done", "text": "DONE", "model": "gpt-5.4", "session_id": "session_sloth_1",
+ "usage": {"input_tokens": 10748, "output_tokens": 5,
+ "cache_read_input_tokens": 10606, "cache_creation_input_tokens": 139}},
+ ])
+ res = evs[-1]
+ assert res["type"] == "result" and res["is_error"] is False and res["result"] == "DONE"
+ u = res["usage"]
+ assert u["cache_read_tokens"] == 10431 + 10606
+ assert u["cache_write_tokens"] == 175 + 139
+ assert u["input_tokens"] == (10609 - 10431 - 175) + (10748 - 10606 - 139)
+ assert u["output_tokens"] == 68
+ # Not the number the CLI offers, which would under-report the turn by more than half.
+ assert u["input_tokens"] != 10748
+
+
+def test_jcode_error_event_fails_the_turn_and_keeps_the_reason():
+ evs, _ = _norm(_jcode_to_claude, [
+ {"type": "start", "session_id": "s", "model": "gpt-5.4"},
+ {"type": "error", "message": "OpenAI-compatible chat request failed\n status: 401 Unauthorized"},
+ ])
+ assert evs[-1]["is_error"] is True and "401 Unauthorized" in evs[-1]["result"]
+
+
+def test_jcode_eof_fails_a_stream_that_ended_with_neither_terminal_event():
+ # Killed, cancelled, or dead before the emitter. An EMPTY result lets the run loop's stderr tail
+ # be the reason instead of a sentence invented here.
+ out = _jcode_eof({"model": "gpt-5.4", "final": "half an answer"}, 1)
+ assert out[0]["is_error"] is True and out[0]["result"] == ""
+ out = _jcode_eof({"model": "gpt-5.4", "final": "an answer"}, 0)
+ assert out[0]["is_error"] is False and out[0]["result"] == "an answer"
+
+
+def test_jcode_bridges_remote_mcp_because_it_has_no_client_for_one():
+ # "jcode currently supports stdio (command-based) servers only; HTTP/SSE entries are recognized
+ # and skipped with a log line" — so without the bridge every remote server a harness declares is
+ # dropped in silence and the agent simply never has those tools.
+ assert set(_BRIDGED_TRANSPORTS["jcode"]) == {"http", "sse"}
+ d, env = _ws(), {"HOME": str(pathlib.Path(_ws()) / "h")}
+ pathlib.Path(env["HOME"]).mkdir(parents=True, exist_ok=True)
+ _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ mcp_servers=[{"name": "deepwiki", "command": "/bin/sh", "args": ["/l.sh"]}])
+ cfg = json.loads((pathlib.Path(env["HOME"]) / ".jcode" / "mcp.json").read_text())
+ assert cfg["mcpServers"]["deepwiki"]["command"] == "/bin/sh"
+
+
+# ── opensquilla: three defaults a harness must undo ────────────────────────────────────────────
+
+def test_opensquilla_config_turns_the_router_off_and_declares_the_window():
+ d, env = _ws(), {}
+ _build_opensquilla("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ cfg = pathlib.Path(d, ".harness", "opensquilla", "config.toml").read_text()
+ # Its router scores each turn and routes it across four tiers to the cheapest capable model,
+ # i.e. substitutes the model by design, and it is ON by default.
+ assert "[squilla_router]" in cfg and "enabled = false" in cfg
+ # A generic endpoint is assumed to hold 8192 tokens, and its own system block plus tool schemas
+ # are ~43k characters: the first probe died with provider_request_too_large on three sentences.
+ assert '[models.custom."gpt-5.4"]' in cfg
+ assert "context_window = 200000" in cfg
+ assert 'provider = "custom"' in cfg
+
+
+def test_opensquilla_argv_bounds_retries_and_keeps_a_session_db():
+ d, env = _ws(), {}
+ cmd = _build_opensquilla("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ resume_session_id="sess-1", max_turns=12)
+ assert cmd[1] == "agent" and cmd[cmd.index("-m") + 1] == "hi"
+ assert "--json" in cmd and "--event-stream-stderr" in cmd
+ assert cmd[cmd.index("--permissions") + 1] == "bypass"
+ # The default is `:memory:` — without an explicit file there is NO continuity between turns.
+ assert cmd[cmd.index("--session-db-path") + 1].endswith("/.harness/opensquilla/sessions.sqlite")
+ assert cmd[cmd.index("--session-id") + 1] == "sess-1"
+ assert cmd[cmd.index("--max-iterations") + 1] == "12"
+ # A provider answering the same 503 every time should not cost minutes before the reason lands.
+ assert cmd[cmd.index("--max-provider-retries") + 1] == "2"
+ assert env["OPENSQUILLA_STATE_DIR"].endswith("/.harness/opensquilla")
+ # The relay's per-turn placeholder, not the provider key — and in the ENVIRONMENT, which is
+ # where _relay_served_model looks for the route.
+ assert env["CUSTOM_LLM_API_KEY"].startswith("hr-relay-")
+
+
+def test_opensquilla_final_answer_comes_from_the_transcript_not_from_text():
+ # MEASURED: asked to "reply with exactly DONE", its stdout object's `text` was
+ # "I'll create `probe.txt` with the requested content and verify it.DONE" — the whole turn's
+ # assistant output concatenated — while the transcript's LAST assistant message was "DONE".
+ d = _ws()
+ base = pathlib.Path(d, ".harness", "opensquilla")
+ base.mkdir(parents=True)
+ (base / "transcript.jsonl").write_text("\n".join(json.dumps(x) for x in [
+ {"type": "message", "message": {"role": "user", "content": [{"type": "text", "text": "go"}]}},
+ {"type": "message", "message": {"role": "assistant", "content": [
+ {"type": "text", "text": "I’ll create probe.txt and verify it."},
+ {"type": "toolCall", "name": "write_file", "id": "call_1", "arguments": {}}]}},
+ {"type": "message", "message": {"role": "toolResult", "toolCallId": "call_1",
+ "toolName": "write_file", "isError": False,
+ "content": [{"type": "text", "text": "Written 6 bytes"}]}},
+ {"type": "message", "message": {"role": "assistant",
+ "content": [{"type": "text", "text": "DONE"}]}},
+ ]))
+ final_obj = {"status": "ok", "session_key": "s1", "text": "I’ll create probe.txt and verify it.DONE",
+ "usage": {"input_tokens": 25343, "output_tokens": 346, "cached_tokens": 16764,
+ "model_usage_breakdown": [{"cache_write_tokens": 8570}]}}
+ evs, state = _norm(_opensquilla_to_claude, [
+ {"_event": True, "schema_version": 1, "kind": "tool_use_start",
+ "tool_use_id": "call_1", "tool_name": "write_file"},
+ {"_event": True, "schema_version": 1, "kind": "tool_result",
+ "tool_use_id": "call_1", "tool_name": "write_file", "is_error": False},
+ final_obj,
+ ], cwd=d)
+ tail = _opensquilla_eof(state, 0)
+ res = tail[-1]
+ assert res["is_error"] is False
+ assert res["result"] == "DONE"
+ # the tool result's CONTENT, which the progress stream withholds by design, comes back here
+ assert any(e.get("type") == "user" and "Written 6 bytes" in json.dumps(e) for e in tail)
+ # usage netted: cached and cache_write are both SUBSETS of input_tokens (measured: 16764 + 8570
+ # is within nine tokens of 25343).
+ assert res["usage"]["input_tokens"] == 25343 - 16764 - 8570
+ assert res["usage"]["cache_read_tokens"] == 16764
+ assert res["usage"]["cache_write_tokens"] == 8570
+
+
+def test_opensquilla_a_routed_model_fails_the_turn():
+ # The router is off by configuration. If one of its decisions still arrives, the turn ran on a
+ # model nobody asked for, and a substitution is a finding — never a pass.
+ state = {"model": "gpt-5.4", "final": "an answer", "cwd": _ws()}
+ _opensquilla_to_claude({"_event": True, "kind": "router_decision", "tier": "c1",
+ "model": "deepseek-v4-flash", "source": "router"}, state)
+ _opensquilla_to_claude({"status": "ok", "session_key": "s", "usage": {}}, state)
+ res = _opensquilla_eof(state, 0)[-1]
+ assert res["is_error"] is True
+ assert "deepseek-v4-flash" in res["result"] and "gpt-5.4" in res["result"]
+
+
+def test_opensquilla_only_event_objects_are_read_as_events():
+ # Its own warning: stderr also carries ordinary diagnostics, so only `_event: true` counts.
+ state = {"model": "gpt-5.4", "final": "", "cwd": _ws()}
+ assert _opensquilla_to_claude({"kind": "tool_use_start", "tool_name": "rm_rf"}, state) == []
+ assert "_sq_final" not in state
+
+
+def test_opensquilla_usage_of_nothing_is_nothing():
+ assert _opensquilla_usage(None) == {}
+ assert _opensquilla_usage({"input_tokens": 0, "output_tokens": 0}) == {}
+
+
+# ── nanobot: the driver's contract with the runner ─────────────────────────────────────────────
+
+def test_nanobot_job_puts_the_session_store_inside_the_checkpointed_tree():
+ d, env = _ws(), {}
+ cmd = _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ resume_session_id="hr-1")
+ assert cmd[1].endswith("nanobot_driver.py")
+ job = json.loads(cmd[2])
+ assert job["session_key"] == "hr-1"
+ # Sessions live beside the CONFIG file (get_data_dir() is get_config_path().parent), so the
+ # config goes in .harness/: checkpointed, and out of the produced-files list.
+ assert job["config_path"].endswith("/.harness/nanobot/config.json")
+ # And the agent's workspace is a directory INSIDE the session rather than the session itself,
+ # because nanobot refuses a session store that sits inside the workspace the agent can write
+ # ("session storage must be outside the agent workspace"). Measured against the real package:
+ # with workspace == the session directory every turn dies before the first model call.
+ assert job["workspace"] == str(pathlib.Path(d) / "workspace")
+ assert pathlib.Path(job["workspace"]).is_dir()
+ sessions = pathlib.Path(job["config_path"]).parent / "sessions"
+ assert not sessions.resolve().is_relative_to(pathlib.Path(job["workspace"]).resolve())
+ # …and still inside the session directory, which is what the checkpoint tars.
+ assert sessions.resolve().is_relative_to(pathlib.Path(d).resolve())
+ # The instruction file and the skills follow the workspace, or they are written and never read.
+ assert _agent_doc_path(d, "nanobot") == pathlib.Path(d) / "workspace" / "AGENTS.md"
+
+
+def test_nanobot_config_names_the_key_and_offers_no_fallback_model():
+ d, env = _ws(), {}
+ _build_nanobot("openai-api", Auth(api_key="sk-secret", base_url=UP), "gpt-5.4", "hi", d, env)
+ cfg = json.loads(pathlib.Path(d, ".harness", "nanobot", "config.json").read_text())
+ assert cfg["providers"]["custom"]["apiKey"] == "${HR_NANOBOT_RELAY_KEY}"
+ assert "sk-secret" not in json.dumps(cfg)
+ assert env["HR_NANOBOT_RELAY_KEY"].startswith("hr-relay-")
+ assert env["HR_NANOBOT_RELAY_KEY"] != "sk-secret"
+ # A fallback model is a substitution, and this product promises the model that was asked for.
+ assert cfg["agents"]["defaults"]["fallbackModels"] == []
+ # `apiType` is REFUSED on any provider but `openai` and the refusal rejects the WHOLE config,
+ # so sending it would kill every turn over a field that was only ever decoration.
+ assert "apiType" not in cfg["providers"]["custom"]
+ # The config holds the relay placeholder today and must never ride a checkpoint tarball even if
+ # a future build stops resolving ${VAR}. The sessions beside it MUST travel, so the exclusion
+ # names the file, not the directory.
+ assert "./.harness/nanobot/config.json" in CHECKPOINT_EXCLUDE
+ assert not any(x.rstrip("/").endswith(".harness/nanobot") for x in CHECKPOINT_EXCLUDE)
+
+
+def test_nanobot_session_lookup_uses_the_name_nanobot_itself_would_open():
+ import base64 as _b64
+ d = _ws()
+ cmd = _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, {},
+ resume_session_id="hr:one")
+ assert _resume_lost("nanobot", cmd, "hr:one", d) == "hr:one"
+ ws_dir = pathlib.Path(d, ".harness", "nanobot", "sessions", "deadbeef")
+ ws_dir.mkdir(parents=True)
+ name = _b64.urlsafe_b64encode(b"hr:one").decode().rstrip("=") + ".jsonl"
+ (ws_dir / name).write_text("{}")
+ assert _resume_lost("nanobot", cmd, "hr:one", d) is None
+
+
+def test_nanobot_tool_list_is_the_one_its_loop_registers():
+ # 22, read off its own start-up line on 0.3.5. Writing has three doors and shell three, which is
+ # why withholding one tool is not withholding a capability.
+ assert len(ALL_NANOBOT_TOOLS) == 22
+ for n in ("write_file", "edit_file", "apply_patch", "exec", "exec_session", "run_cli_app"):
+ assert n in ALL_NANOBOT_TOOLS
+
+
+# ── the real bytes ─────────────────────────────────────────────────────────────────────────────
+# Everything above this line is a hand-written event, and a test written from the implementation
+# can only prove the implementation is self-consistent. These replay CAPTURED streams — the actual
+# stdout of the pinned binaries on 2026-10-02, against a live provider, trimmed and path-scrubbed
+# but otherwise unaltered — through the shipped normaliser.
+
+FIX = pathlib.Path(__file__).resolve().parent / "fixtures" / "batch3"
+
+
+def _replay(fn, name, model, eof=None, rc=0):
+ state = {"model": model, "final": "", "cwd": ""}
+ evs = []
+ for ln in (FIX / name).read_text().splitlines():
+ if ln.strip().startswith("{"):
+ evs += fn(json.loads(ln), state)
+ res = next((e for e in evs if e.get("type") == "result"), None)
+ if res is None and eof is not None:
+ tail = eof(state, rc)
+ evs += tail
+ res = next((e for e in tail if e.get("type") == "result"), None)
+ return evs, res
+
+
+def test_real_gajae_turn_that_wrote_a_file():
+ evs, res = _replay(_gajae_to_claude, "gajae-write-file.ndjson", "openai/gpt-6-luna")
+ assert evs[0]["type"] == "system" and evs[0]["subtype"] == "init"
+ assert any(e.get("type") == "assistant" and "tool_use" in json.dumps(e) for e in evs)
+ assert any(e.get("type") == "user" and "Successfully wrote" in json.dumps(e) for e in evs)
+ assert res["is_error"] is False and res["result"] == "DONE"
+ # The served model comes off the CLI's own assistant messages, so rule 2 is answerable here
+ # without the relay as well as with it.
+ assert res["model"] == "openai/gpt-6-luna"
+ assert res["usage"]["input_tokens"] > 0 and res["usage"]["output_tokens"] > 0
+
+
+def test_real_gajae_turn_that_the_provider_refused():
+ evs, res = _replay(_gajae_to_claude, "gajae-provider-401.ndjson", "openai/gpt-6-luna")
+ assert res["is_error"] is True
+ assert res["result"].startswith("401 Authentication failed")
+ # and the failure is NOT rendered as the assistant's answer. Pinned by the event TYPES rather
+ # than by "no assistant event": the second form also passes on an empty list, and a normaliser
+ # that emitted nothing at all would then look correct here.
+ assert [e.get("type") for e in evs] == ["system", "result"]
+
+
+def test_real_jcode_turn_sums_the_usage_its_own_done_event_under_reports():
+ evs, res = _replay(_jcode_to_claude, "jcode-write-file.ndjson", "openai/gpt-6-luna",
+ eof=_jcode_eof)
+ assert res["is_error"] is False and res["result"] == "DONE"
+ assert any("tool_use" in json.dumps(e) for e in evs)
+ assert any("Created probe.txt" in json.dumps(e) for e in evs)
+ u = res["usage"]
+ # The capture's own `done.usage` says input_tokens 10748; the two `tokens` events say 10609 and
+ # 10748, and both are gross. This is the turn, not the last request.
+ assert u["cache_read_tokens"] == 21037
+ assert u["cache_write_tokens"] == 314
+ assert u["output_tokens"] == 68
+
+
+def test_real_jcode_turn_that_the_provider_refused():
+ _evs, res = _replay(_jcode_to_claude, "jcode-provider-401.ndjson", "openai/gpt-6-luna",
+ eof=_jcode_eof, rc=1)
+ assert res["is_error"] is True
+ assert "401 Unauthorized" in res["result"]
+ # The message names the auth variable by NAME and never carries its value.
+ assert "OPENAI_COMPAT_API_KEY" in res["result"] and "sk-" not in res["result"]
+
+
+def test_real_mimo_turn_through_opencodes_normaliser_unchanged():
+ from server import _opencode_eof
+ evs, res = _replay(_opencode_to_claude, "mimo-first-turn.ndjson", "openai/gpt-6-luna",
+ eof=_opencode_eof)
+ assert evs[0]["subtype"] == "init"
+ assert res["is_error"] is False and res["result"] == "OK"
+ # step-finish's tokens, read by opencode's own accumulator: `input` is already cache-exclusive
+ # in this fork as in opencode, and reasoning is added back into output.
+ assert res["usage"]["input_tokens"] == 14413
+ assert res["usage"]["output_tokens"] == 37
+
+
+def test_opensquilla_warning_becomes_a_notice_the_gateway_renders_and_repeats_once():
+ # Its compaction warning repeats once per retry; three identical notes on one reply is noise,
+ # so the de-duplication happens here rather than in the gateway.
+ state = {"model": "gpt-5.4", "final": "", "cwd": _ws()}
+ w = {"_event": True, "schema_version": 1, "kind": "warning", "code": "***",
+ "message": "Provider context limit reached; compacting older context before retrying."}
+ first = _opensquilla_to_claude(dict(w), state)
+ again = _opensquilla_to_claude(dict(w), state)
+ assert len(first) == 1 and first[0]["subtype"] == "notice"
+ assert first[0]["text"].startswith("Provider context limit reached")
+ assert again == []
+ # a DIFFERENT warning is still said
+ other = _opensquilla_to_claude({**w, "message": "Search provider is not configured."}, state)
+ assert len(other) == 1 and other[0]["subtype"] == "notice"
+ # and an empty one is not
+ assert _opensquilla_to_claude({**w, "message": ""}, state) == []
+
+
+def test_opensquilla_channel_routing_directives_are_not_part_of_the_answer():
+ # MEASURED on the first live turn through the product: asked to reply with exactly READY, the
+ # record said "[[reply_to_current]]\nREADY". The directive is for OpenSquilla's channel
+ # adapters; the project strips it in the channel layer and in BOTH of its terminal renderers,
+ # but `opensquilla agent --json` strips neither. Left in, every scenario that recalls an exact
+ # word fails for a reason that has nothing to do with the model.
+ from server import _opensquilla_text
+ assert _opensquilla_text("[[reply_to_current]]\nREADY") == "READY"
+ assert _opensquilla_text("[reply_to: ops]\nhi there") == "hi there" # the one-bracket spelling
+ assert _opensquilla_text("READY [[reply_to_current]]") == "READY"
+ assert _opensquilla_text("READY") == "READY"
+ # and nothing else in double brackets is touched
+ assert _opensquilla_text("see [[notes]] here") == "see [[notes]] here"
+
+
+def test_opensquilla_transcript_answer_has_the_directive_removed():
+ d = _ws()
+ base = pathlib.Path(d, ".harness", "opensquilla"); base.mkdir(parents=True)
+ (base / "transcript.jsonl").write_text(json.dumps(
+ {"type": "message", "message": {"role": "assistant",
+ "content": [{"type": "text", "text": "[[reply_to_current]]\nDONE"}]}}))
+ state = {"model": "gpt-5.4", "final": "", "cwd": d}
+ evs = _opensquilla_transcript(state)
+ assert state["final"] == "DONE"
+ assert "reply_to_current" not in json.dumps(evs)
+
+
+def test_mimo_keeps_an_aggregators_claude_id_on_the_relay_so_rule_2_stays_answerable():
+ # MEASURED WITH A CONTROL on the Vercel column (2026-10-06): mimo's claude-haiku-4.5 pair came
+ # back unlabelled=4 — no served model on any of its four turns — while its seven other models
+ # were labelled, and jcode's claude pair, which already keeps aggregator claude on
+ # chat/completions, recorded anthropic/claude-haiku-4.5. Five scenarios "passed" on a rule with
+ # no input. A Messages turn cannot ride the relay, and mimo names no served model itself.
+ from server import _mimo_npm, _opencode_npm
+ a = Auth(api_key="k", base_url=UP)
+ # opencode's own choice is deliberately left alone; mimo's differs exactly here
+ assert _opencode_npm(a, "claude-haiku-4.5", "tokenrouter") == "@ai-sdk/anthropic"
+ assert _mimo_npm(a, "claude-haiku-4.5", "tokenrouter") == "@ai-sdk/openai-compatible"
+ # a connection that IS Anthropic still speaks Messages, through the relay like every keyed turn
+ assert _mimo_npm(a, "claude-haiku-4.5", "anthropic") == "@ai-sdk/anthropic"
+ # and nothing else moved
+ assert _mimo_npm(a, "gpt-5.4", "tokenrouter") == "@ai-sdk/openai"
+ assert _mimo_npm(a, "deepseek-v4-flash", "tokenrouter") == "@ai-sdk/openai-compatible"
+
+ # end to end: the claude row now rides the relay with a placeholder, which is what
+ # _relay_served_model reads the served model off
+ d, env = _ws(), {}
+ _build_mimo("tokenrouter", Auth(api_key="sk-secret", base_url=UP), "claude-haiku-4.5", "hi", d, env)
+ cfg = json.loads((pathlib.Path(d) / ".harness" / "mimo.json").read_text())
+ assert cfg["provider"]["hr"]["npm"] == "@ai-sdk/openai-compatible"
+ assert cfg["provider"]["hr"]["options"]["baseURL"].startswith("http://127.0.0.1:")
+ assert env["HR_MIMO_KEY"].startswith("hr-relay-")
+
+
+def test_nanobot_hides_its_own_machinery_from_the_produced_files_list():
+ # MEASURED on the Vercel column (2026-10-06): without this, a turn that wrote NOTHING handed the
+ # user 25 files — the three built-in skill bundles, the instruction file and nanobot's own
+ # workspace id — and all eight nanobot pairs FAILED their first scenario, because the file cards
+ # pushed the answer out of the transcript the judge reads. Re-measured after the fix: 0 files.
+ d, env = _ws(), {}
+ _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ ex = pathlib.Path(d, ".git", "info", "exclude")
+ assert ex.is_file(), "/produced is git status, so git's own exclude is the door"
+ lines = {l.strip() for l in ex.read_text().splitlines() if l.strip() and not l.startswith("#")}
+ assert {"workspace/.nanobot/", "workspace/skills/", "workspace/memory/",
+ "workspace/AGENTS.md"} <= lines
+ # NOT a .gitignore: this is not a file in the agent's workspace, so the agent cannot read or
+ # edit it and it is never itself a produced file; and _git_ensure rewrites only the root
+ # .gitignore, so this survives every turn.
+ assert not (pathlib.Path(d) / "workspace" / ".gitignore").exists()
+
+
+def test_opensquilla_hides_the_files_it_seeds_into_every_workspace():
+ # `ensure_agent_workspace` writes SOUL.md, IDENTITY.md, USER.md and MEMORY.md into the agent's
+ # workspace unconditionally — its `seed_templates` flag has no caller that passes False and no
+ # setting reads it, so there is nothing to turn off. Measured: a turn that wrote nothing handed
+ # those four back, and the stale cards then failed rule 3 on the artifact scenario for all
+ # eight models (five cards against a record of one).
+ d, env = _ws(), {}
+ _build_opensquilla("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ lines = {l.strip() for l in pathlib.Path(d, ".git", "info", "exclude").read_text().splitlines()
+ if l.strip() and not l.startswith("#")}
+ assert {"SOUL.md", "IDENTITY.md", "USER.md", "MEMORY.md", "memory/"} <= lines
+
+
+def test_opensquilla_memory_source_is_state_and_the_comment_says_what_it_actually_does():
+ # It keeps the memory the agent ACCUMULATES out of the collected workspace (memory_tools.py
+ # branches on exactly this value). It does NOT stop the bootstrap seeds — an earlier version of
+ # this change claimed it did, and the column showed otherwise.
+ d, env = _ws(), {}
+ _build_opensquilla("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ cfg = pathlib.Path(d, ".harness", "opensquilla", "config.toml").read_text()
+ assert 'source = "state"' in cfg
+ assert "does NOT stop the four bootstrap seeds" in cfg
+ assert env["OPENSQUILLA_STATE_DIR"].endswith("/.harness/opensquilla")
+
+
+# ── nanobot's nested workspace must not reach the user ───────────────────────────────────
+# Found by running the product, not by reading it: a file written through
+# PUT /v1/sessions/{sid}/files landed at the session root and the agent answered "there is no
+# secret.txt in the working directory", while the same test on a flat-layout base read it back.
+# The session's file root and the agent's cwd are two different directories for this one base.
+
+def _nano(d, prompt="hi"):
+ _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", prompt, d, {})
+
+
+def test_the_visible_root_is_the_session_dir_for_a_flat_base():
+ d, env = _ws(), {}
+ _build_mimo("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ assert _visible_root(d) == d
+ assert {f["path"] for f in _produced_visible(d)} == {f["path"] for f in
+ __import__("server")._produced_list(d)}
+
+
+def test_the_visible_root_is_the_agent_workspace_for_nanobot():
+ d = _ws()
+ _nano(d)
+ assert _visible_root(d) == str(pathlib.Path(d, "workspace"))
+
+
+def test_a_file_the_user_wrote_before_the_first_turn_reaches_the_agent():
+ # the PUT route and attachments both land at the session root; they run before any backend is
+ # built, so they cannot know a base nests. The turn adopts them.
+ d = _ws()
+ pathlib.Path(d, "deck.json").write_text('{"slides": 1}')
+ _write_input_files(d, [{"filename": "notes.txt", "content_b64": "aGVsbG8="}])
+ _nano(d)
+ assert pathlib.Path(d, "workspace", "deck.json").read_text() == '{"slides": 1}'
+ assert pathlib.Path(d, "workspace", "notes.txt").read_bytes() == b"hello"
+ assert not pathlib.Path(d, "deck.json").exists()
+
+
+def test_adoption_leaves_the_runners_own_entries_at_the_root():
+ d = _ws()
+ _nano(d) # makes .harness/nanobot and workspace/
+ pathlib.Path(d, "tmp").mkdir(exist_ok=True)
+ _nano(d)
+ for name in (".harness", "tmp", ".git", "workspace"):
+ assert pathlib.Path(d, name).exists(), name
+ assert not pathlib.Path(d, "workspace", name).exists(), name
+
+
+def test_adoption_never_overwrites_what_the_agent_already_has():
+ d = _ws()
+ _nano(d)
+ pathlib.Path(d, "workspace", "report.md").write_text("the agent's")
+ pathlib.Path(d, "report.md").write_text("the uploader's")
+ _nano(d)
+ assert pathlib.Path(d, "workspace", "report.md").read_text() == "the agent's"
+
+
+def test_a_produced_file_is_named_the_way_the_agent_named_it():
+ # a card reading "workspace/report.md" names a directory the user never typed and no other base
+ # shows. The prefix comes off where the cards and their download both resolve.
+ d = _ws()
+ _nano(d)
+ pathlib.Path(d, "workspace", "report.md").write_text("done")
+ import server
+ assert {f["path"] for f in server._produced_list(d)} == {"workspace/report.md"}, (
+ "the raw shape: git runs on the session dir")
+ assert {f["path"] for f in _produced_visible(d)} == {"report.md"}
+
+
+# ── nanobot's MCP config ────────────────────────────────────────────────────────────────
+# Found by the custom-harness dimension on 2026-10-07, and it could not have been found anywhere
+# else: nothing exercised this function's OUTPUT against nanobot's own schema, and the five routing
+# scenarios never attach a server. Every turn on a harness carrying ANY MCP server died before the
+# first model call — including the turn that was only supposed to report a build stamp, because the
+# config is invalid as a whole.
+
+def _nano_cfg(servers):
+ d, env = _ws(), {}
+ _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ mcp_servers=servers)
+ return json.loads(pathlib.Path(d, ".harness", "nanobot", "config.json").read_text())
+
+
+# nanobot.config.Config's top level, read off the installed package (0.3.5), with extra="forbid":
+# anything else is "Unknown setting." and the whole config is rejected.
+NANOBOT_TOP = {"agents", "api", "channels", "gateway", "model_presets", "providers", "tools",
+ "transcription"}
+
+
+def test_the_config_uses_only_keys_nanobots_own_schema_declares():
+ cfg = _nano_cfg([{"name": "deepwiki", "url": "https://mcp.deepwiki.com/mcp"}])
+ assert set(cfg) <= NANOBOT_TOP, f"extra='forbid' rejects the whole file: {set(cfg) - NANOBOT_TOP}"
+ assert "mcp" not in cfg, "this was the defect: a top-level mcp key, which nanobot forbids"
+
+
+def test_a_remote_server_lands_at_tools_mcpServers_with_no_type():
+ # the transport is nanobot's own inference: a url path ending in /sse is sse, anything else
+ # streamable HTTP (agent/tools/mcp.py), which is why nanobot is in neither half of
+ # _BRIDGED_TRANSPORTS and why no type is sent.
+ cfg = _nano_cfg([{"name": "deepwiki", "url": "https://mcp.deepwiki.com/mcp"}])
+ sv = cfg["tools"]["mcpServers"]["deepwiki"]
+ assert sv == {"url": "https://mcp.deepwiki.com/mcp"}
+
+
+def test_a_stdio_server_keeps_command_args_env():
+ cfg = _nano_cfg([{"name": "probe", "command": ["python3", "-u", "s.py"], "args": ["--x"],
+ "env": {"K": "v"}}])
+ assert cfg["tools"]["mcpServers"]["probe"] == {
+ "command": "python3", "args": ["-u", "s.py", "--x"], "env": {"K": "v"}}
+
+
+def test_no_servers_means_no_tools_section_at_all():
+ cfg = _nano_cfg([])
+ assert "tools" not in cfg and "mcp" not in cfg
+
+
+# ── jcode: the model a resumed turn asked for ───────────────────────────────────────────
+# jcode's --model and --provider are its session's INITIAL ones, and `jcode run` has no model flag,
+# so on --resume the stored model wins and the person's pick is ignored in silence. MEASURED with a
+# control in the same run: two turns in one session, haiku then gemini — jcode served haiku twice,
+# mimo served each as asked. The family tour served all TWELVE of jcode's families with
+# openai/gpt-5.4; the five-scenario column held the same evidence (one `served` entry per pair where
+# mimo had two) and passed it, because its switch target is the subset's first id.
+
+def _jcode_store(d, env, sid, model, provider="openai-compatible"):
+ # the runner points HOME inside the checkpointed workspace before the builder runs, and that is
+ # where jcode keeps its sessions; the builder itself does not set it.
+ env.setdefault("HOME", str(pathlib.Path(d, ".harness", "home")))
+ home = pathlib.Path(env["HOME"], ".jcode", "sessions")
+ home.mkdir(parents=True, exist_ok=True)
+ f = home / f"{sid}.json"
+ f.write_text(json.dumps({"id": sid, "model": model, "provider_key": provider,
+ "messages": [{"role": "user", "content": "hi"}]}))
+ return f
+
+
+def test_resuming_points_the_store_at_the_model_this_turn_asked_for():
+ d, env = _ws(), {}
+ _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ f = _jcode_store(d, env, "sess-1", "anthropic/claude-haiku-4.5")
+ argv = _build_jcode("openai-api", Auth(api_key="k", base_url=UP),
+ "google/gemini-3.6-flash", "next", d, env, resume_session_id="sess-1")
+ assert "--resume" in argv and argv[argv.index("--resume") + 1] == "sess-1"
+ doc = json.loads(f.read_text())
+ assert doc["model"] == "google/gemini-3.6-flash"
+ # the conversation is jcode's to keep; the provider key follows this turn's provider
+ assert doc["provider_key"] == "openai-compatible" and doc["messages"]
+
+
+def test_a_switch_between_connection_kinds_carries_the_provider_key_with_the_model():
+ """jcode joins the stored provider key onto the model when it restores a session: after a turn
+ on the Messages path (`claude-api`) an OpenAI-compatible turn asked for
+ `claude-api:openai/gpt-6.1-sol` and got a 404 (the column's switch row, 2026-10-12)."""
+ d, env = _ws(), {}
+ _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ f = _jcode_store(d, env, "sess-5", "claude-haiku-4-5-20251001")
+ doc = json.loads(f.read_text()); doc["provider_key"] = "claude-api"; f.write_text(json.dumps(doc))
+ _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "openai/gpt-6.1-sol", "next", d, env,
+ resume_session_id="sess-5")
+ doc = json.loads(f.read_text())
+ assert (doc["provider_key"], doc["model"]) == ("openai-compatible", "openai/gpt-6.1-sol")
+ # and back: an Anthropic connection's turn on a session an OpenAI-compatible turn wrote
+ _build_jcode("anthropic", Auth(api_key="k", base_url="https://api.anthropic.com/v1"),
+ "claude-haiku-4-5-20251001", "again", d, env, resume_session_id="sess-5")
+ doc = json.loads(f.read_text())
+ assert (doc["provider_key"], doc["model"]) == ("claude-api", "claude-haiku-4-5-20251001")
+
+
+def test_a_turn_on_the_same_model_leaves_the_store_untouched():
+ d, env = _ws(), {}
+ _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ f = _jcode_store(d, env, "sess-2", "openai/gpt-5.4")
+ before = f.read_text()
+ _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "openai/gpt-5.4", "next", d, env,
+ resume_session_id="sess-2")
+ assert f.read_text() == before
+
+
+def test_a_store_that_is_not_there_or_not_json_does_not_fail_the_turn():
+ d, env = _ws(), {}
+ _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ # no file at all: _jcode_has_session already declines to resume, and this must not raise either
+ assert _jcode_session_model(env, "missing", "gpt-5.4") == ""
+ f = _jcode_store(d, env, "sess-3", "openai/gpt-5.4")
+ f.write_text("{not json")
+ assert _jcode_session_model(env, "sess-3", "google/gemini-3.6-flash") == ""
+ assert f.read_text() == "{not json", "a store it cannot parse is left exactly as it was"
+
+
+def test_no_model_asked_for_means_no_rewrite():
+ d, env = _ws(), {}
+ _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ f = _jcode_store(d, env, "sess-4", "openai/gpt-5.4")
+ assert _jcode_session_model(env, "sess-4", "") == ""
+ assert json.loads(f.read_text())["model"] == "openai/gpt-5.4"
+
+
+# ── nanobot refuses a loopback MCP url, and the product injects one ──────────────────────
+# Found by the browser column (2026-10-10): the `plugs` server is how EVERY base gets the browser
+# tools and it is injected at http://127.0.0.1:8080/v1/mcp/plugs. nanobot was the one base of four
+# that made no browser call at all, twice, and said it had no browser toolset — while its config
+# held the server correctly. Its MCP client runs `validate_url_target` over every url and drops a
+# loopback one with a log line of its own, so nothing reaches the turn record as a refusal.
+
+def test_a_loopback_server_is_bridged_for_nanobot():
+ d = _ws()
+ out = _sse_bridges(d, [{"name": "plugs", "url": "http://127.0.0.1:8080/v1/mcp/plugs",
+ "headers": {"Authorization": "Bearer t"}}], "nanobot")
+ assert out[0].get("command"), "it has to arrive as a stdio command, with no url to validate"
+ assert "url" not in out[0] and "headers" not in out[0]
+ launcher = pathlib.Path(out[0]["command"]).read_text()
+ assert "HR_MCP_URL" in launcher and "127.0.0.1:8080" in launcher
+ assert "Bearer t" not in pathlib.Path(out[0]["command"]).name, "never on the command line"
+
+
+def test_a_public_server_still_goes_to_nanobots_own_client():
+ # measured in both the custom-harness and the plugin columns: its remote client handles a public
+ # streamable-HTTP and SSE server, so bridging those would add a hop for nothing.
+ d = _ws()
+ out = _sse_bridges(d, [{"name": "deepwiki", "url": "https://mcp.deepwiki.com/mcp"}], "nanobot")
+ assert out[0].get("url") == "https://mcp.deepwiki.com/mcp" and "command" not in out[0]
+
+
+def test_which_hosts_count_as_loopback():
+ for u in ("http://127.0.0.1:8080/x", "http://localhost:3000/x", "http://[::1]:9/x",
+ "http://10.1.2.3/x", "http://192.168.0.5/x", "http://172.16.4.4/x",
+ "http://169.254.169.254/latest", "http://api.localhost/x"):
+ assert _mcp_url_is_loopback(u), u
+ for u in ("https://mcp.deepwiki.com/mcp", "https://example.com/x", "http://172.32.0.1/x",
+ "http://1.2.3.4/x"):
+ assert not _mcp_url_is_loopback(u), u
+
+
+def test_a_flat_base_is_untouched_by_this_rule():
+ # the rule is nanobot's; mimo reaches a loopback server itself and must keep doing so
+ d = _ws()
+ out = _sse_bridges(d, [{"name": "plugs", "url": "http://127.0.0.1:8080/v1/mcp/plugs"}], "mimo")
+ assert out[0].get("url") == "http://127.0.0.1:8080/v1/mcp/plugs"
+
+
+# ── nanobot's shell does not inherit the environment layer ───────────────────────────────
+# Its own `_build_env` says so: "Build a minimal environment for subprocess execution. On Unix, only
+# HOME/LANG/TERM are passed by default." MEASURED by the environments column (2026-10-10): three of
+# four bases used the layer's pip, npm and apt packages without installing anything and nanobot
+# failed all three with ModuleNotFoundError. The layer reached the driver process and stopped there.
+
+LAYER = {"HR_ENVIRONMENT": "/env/x", "PROJECT_ROOT": "/env/x", "PYTHONPATH": "/env/x",
+ "VIRTUAL_ENV": "/env/x/.venv", "NODE_PATH": "/env/x/node_modules",
+ "LD_LIBRARY_PATH": "/env/x/apt/usr/lib",
+ "PATH": "/env/x/.venv/bin:/env/x/node_modules/.bin:/env/x/apt/usr/bin:/usr/bin:/bin"}
+
+
+def test_the_layers_variables_and_path_are_handed_to_the_exec_tool():
+ d, env = _ws(), dict(LAYER)
+ _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ ex = json.loads(pathlib.Path(d, ".harness", "nanobot", "config.json").read_text())["tools"]["exec"]
+ assert set(ex["allowedEnvKeys"]) == set(LAYER) - {"PATH"}
+ # only the layer's own PATH entries, and in the order the turn had them
+ assert ex["pathPrepend"] == "/env/x/.venv/bin:/env/x/node_modules/.bin:/env/x/apt/usr/bin"
+ # by ENTRY, not by substring: /env/x/apt/usr/bin legitimately contains "/usr/bin", and the
+ # first version of this assertion failed the implementation for that
+ assert all(e.startswith("/env/x/") for e in ex["pathPrepend"].split(":")), \
+ "the image's own PATH entries are nanobot's to decide"
+
+
+def test_no_environment_means_no_exec_section():
+ d, env = _ws(), {"PATH": "/usr/bin:/bin"}
+ _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ cfg = json.loads(pathlib.Path(d, ".harness", "nanobot", "config.json").read_text())
+ assert "exec" not in (cfg.get("tools") or {})
+
+
+def test_the_exec_section_and_the_mcp_servers_share_the_one_tools_block():
+ d, env = _ws(), dict(LAYER)
+ _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ mcp_servers=[{"name": "deepwiki", "url": "https://mcp.deepwiki.com/mcp"}])
+ t = json.loads(pathlib.Path(d, ".harness", "nanobot", "config.json").read_text())["tools"]
+ assert set(t) == {"mcpServers", "exec"}, "one tools block, or the second overwrites the first"
+
+
+def test_a_layer_with_only_some_of_the_variables_passes_only_those():
+ d, env = _ws(), {"HR_ENVIRONMENT": "/env/y", "PROJECT_ROOT": "/env/y",
+ "PATH": "/env/y/.venv/bin:/usr/bin"}
+ _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ ex = json.loads(pathlib.Path(d, ".harness", "nanobot", "config.json").read_text())["tools"]["exec"]
+ assert set(ex["allowedEnvKeys"]) == {"HR_ENVIRONMENT", "PROJECT_ROOT"}
+ assert ex["pathPrepend"] == "/env/y/.venv/bin"
+
+
[email protected]("build", ["_build_mimo", "_build_jcode", "_build_opensquilla", "_build_nanobot"])
+def test_the_provider_key_never_reaches_the_cli_whatever_the_connection_shape(build):
+ """The CLI's environment is the agent's shell's, and its config files ride the workspace
+ checkpoint: the real key belongs in neither, on any connection a base is offered. A direct
+ Anthropic connection and a custom endpoint left the relay on jcode, opensquilla and mimo (and a
+ custom endpoint on nanobot) and handed the CLI the key itself; the relay reads its placeholder
+ from a bearer or x-api-key and sends the provider the key the way it takes it."""
+ import server
+ key = "sk-real-provider-secret-0123456789"
+ shapes = [("openai-api", Auth(api_key=key, base_url=UP)),
+ ("anthropic", Auth(api_key=key, base_url="https://api.anthropic.com/v1")),
+ ("openai-api", Auth(api_key=key, base_url=UP, api_format="openai"))]
+ if build == "_build_mimo":
+ shapes.append(("openai-api", Auth(api_key=key, base_url="https://proxy.example/v1", api_format="anthropic")))
+ for provider, auth in shapes:
+ d, env = _ws(), {}
+ cmd = getattr(server, build)(provider, auth, "claude-haiku-4.5", "hi", d, env)
+ assert key not in json.dumps(env), (build, provider, auth.api_format, "environment")
+ assert key not in json.dumps(cmd or []), (build, provider, auth.api_format, "argv")
+ for f in pathlib.Path(d).rglob("*"):
+ if f.is_file():
+ assert key.encode() not in f.read_bytes(), (build, provider, auth.api_format, str(f))
+ assert any(str(v).startswith("hr-relay-") for v in env.values()), (build, provider, "no relay placeholder")
+
+
+def test_jcode_runs_on_an_anthropic_connection_only_a_model_its_catalog_lists(monkeypatch):
+ """jcode's Anthropic provider replaces any id its catalog does not list with claude-opus-5-5 and
+ says so only in its own log: a claude-haiku-4.5 turn whose wire id was the dated
+ claude-haiku-4-5-20251001 was answered and billed by Opus (2026-10-12)."""
+ import server
+ monkeypatch.setattr(server, "_JCODE_ANTHROPIC_LISTED", ["claude-opus-5-5", "claude-sonnet-4-6", "claude-haiku-4-5"])
+ a = Auth(api_key="k", base_url="https://api.anthropic.com/v1")
+ # the dated id is the same model under jcode's undated name
+ argv = _build_jcode("anthropic", a, "claude-haiku-4-5-20251001", "hi", _ws(), {})
+ assert argv[argv.index("--model") + 1] == "claude-haiku-4-5"
+ argv = _build_jcode("anthropic", a, "claude-sonnet-4-6", "hi", _ws(), {})
+ assert argv[argv.index("--model") + 1] == "claude-sonnet-4-6"
+ # an id it does not list is refused, never answered by Opus
+ with pytest.raises(server.HTTPException) as e:
+ _build_jcode("anthropic", a, "claude-sonnet-5-5", "hi", _ws(), {})
+ assert "claude-sonnet-5-5" in e.value.detail and "claude-opus-5-5" in e.value.detail
+ # an OpenAI-compatible connection takes any id, as before
+ argv = _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "anthropic/claude-sonnet-5.5", "hi", _ws(), {})
+ assert argv[argv.index("--model") + 1] == "anthropic/claude-sonnet-5.5"
+
+
+def test_opensquillas_route_asks_openai_for_a_stream_without_padding():
+ """OpenAI and Azure pad every streamed chunk with `obfuscation`, the usage trailer included, and
+ opensquilla 0.5.6 fails a turn that has already answered on a trailer key it does not know."""
+ import server
+ from server import _without_stream_obfuscation
+ asked = json.dumps({"model": "gpt-5.4-mini", "stream": True, "stream_options": {"include_usage": True}}).encode()
+ for base in ("https://api.openai.com/v1", "https://agentstudio-oai-e2.openai.azure.com/openai/v1"):
+ out = json.loads(_without_stream_obfuscation(asked, base))
+ assert out["stream_options"] == {"include_usage": True, "include_obfuscation": False}, base
+ # an aggregator's stream, a body that does not stream, and one that already chose are left alone
+ assert _without_stream_obfuscation(asked, "https://ai-gateway.vercel.sh/v1") == asked
+ still = json.dumps({"model": "m", "stream": False}).encode()
+ assert _without_stream_obfuscation(still, "https://api.openai.com/v1") == still
+ chose = json.dumps({"stream": True, "stream_options": {"include_obfuscation": True}}).encode()
+ assert _without_stream_obfuscation(chose, "https://api.openai.com/v1") == chose
+ # only opensquilla's route asks for it
+ d, env = _ws(), {}
+ _build_opensquilla("openai-api", Auth(api_key="k", base_url="https://api.openai.com/v1"), "gpt-5.4-mini", "hi", d, env)
+ tok = next(v for v in env.values() if str(v).startswith("hr-relay-"))
+ assert server._HERMES_RELAY["routes"][tok][2]["plain_stream"] is True
+ d2, env2 = _ws(), {}
+ _build_jcode("openai-api", Auth(api_key="k", base_url="https://api.openai.com/v1"), "gpt-5.4-mini", "hi", d2, env2)
+ tok2 = next(v for v in env2.values() if str(v).startswith("hr-relay-"))
+ assert not server._HERMES_RELAY["routes"][tok2][2].get("plain_stream")
+
+
+def test_after_a_finished_choice_opensquilla_reads_only_a_bare_usage_chunk():
+ """Every provider ends a stream its own way, and opensquilla 0.5.6 fails a turn that has already
+ answered on anything after a finished choice but a bare usage chunk (2026-10-12)."""
+ from server import _plain_trailer_line, _rewrite_stream_line
+ def run(lines, flags={"plain_stream": True}):
+ st = {}
+ return [_rewrite_stream_line(ln, flags, st) for ln in lines]
+ answer = b'data: {"id":"c","choices":[{"index":0,"delta":{"content":"OK"},"finish_reason":null}]}'
+ finish = b'data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":null}'
+ usage = '"usage":{"prompt_tokens":9,"completion_tokens":2,"total_tokens":11}'
+ trailers = {
+ "openai": f'data: {{"id":"c","object":"chat.completion.chunk","choices":[],"obfuscation":"xyz",{usage}}}'.encode(),
+ "azure": f'data: {{"choices":[],"id":"c","latency_checkpoint":{{"t":1}},"routing":{{"r":"x"}},{usage}}}'.encode(),
+ "openrouter": f'data: {{"id":"c","provider":"Fireworks","choices":[{{"index":0,"delta":{{"content":"","role":"assistant"}},"finish_reason":null}}],{usage}}}'.encode(),
+ }
+ for name, trailer in trailers.items():
+ out = run([answer, finish, trailer, b"data: [DONE]"])
+ assert out[0] == answer and out[1] == finish and out[3] == b"data: [DONE]", name
+ got = json.loads(out[2][5:])
+ assert got["choices"] == [] and got["usage"]["total_tokens"] == 11, name
+ assert set(got) <= {"id", "object", "created", "model", "system_fingerprint", "service_tier", "usage", "choices"}, name
+ # a post-finish chunk with no usage at all is dropped; before the finish nothing changes
+ assert run([finish, b'data: {"id":"c","choices":[{"index":0,"delta":{}}]}'])[1] == b""
+ assert run([answer, b'data: {"choices":[],"prompt_filter_results":[]}'])[1] == b'data: {"choices":[],"prompt_filter_results":[]}'
+ # another route's stream is untouched
+ assert run([finish, trailers["openai"]], flags={})[1] == trailers["openai"]
+ assert _plain_trailer_line(b": keep-alive", {"finished": True}) == b": keep-alive"
+
+
+def test_a_field_anthropic_calls_deprecated_for_the_model_is_one_the_relay_drops():
+ """nanobot sends temperature, and claude-sonnet-5.5 on Anthropic's OpenAI-compatible surface
+ refused every turn: "`temperature` is deprecated for this model." (2026-10-12)."""
+ from server import _refused_top_level_field
+ body = b'{"type":"error","error":{"type":"invalid_request_error","message":"`temperature` is deprecated for this model."}}'
+ assert _refused_top_level_field(body) == "temperature"
+ assert _refused_top_level_field(b'{"error":{"message":"Invalid JSON payload received. Unknown name \\"store\\": Cannot find field."}}') == "store"
+ assert _refused_top_level_field(b'{"error":{"message":"max_tokens: must be positive"}}') == ""
+
+
+def test_nanobots_shell_gets_the_harnesss_own_variables_by_name():
+ """Every other base's shell inherits the harness's variables; nanobot's passes only what it is
+ named. The custom-harness dimension's script ran without its STAMP_NONCE (2026-10-12)."""
+ d, env = _ws(), {"STAMP_NONCE": "n-123", "HR_API_URL": "http://127.0.0.1:8080"}
+ _build_nanobot("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
+ caller_keys=["STAMP_NONCE", "HR_API_URL", "NOT_SET"])
+ cfg_path = pathlib.Path(d, ".harness", "nanobot", "config.json")
+ text = cfg_path.read_text()
+ ex = json.loads(text)["tools"]["exec"]
+ assert ex["allowedEnvKeys"] == ["STAMP_NONCE", "HR_API_URL"] # names only, none that is unset
+ assert "n-123" not in text # the value stays in the environment
+ assert "pathPrepend" not in ex # no environment layer, no PATH entry
diff --git a/runner/tests/test_nanobot_driver.py b/runner/tests/test_nanobot_driver.py
new file mode 100644
index 00000000..290ba494
--- /dev/null
+++ b/runner/tests/test_nanobot_driver.py
@@ -0,0 +1,274 @@
+"""runner/nanobot_driver.py — the in-process nanobot turn (HKUDS/nanobot, MIT, pinned to 0.3.5).
+
+nanobot is not installed in the test environment (it lives in its own venv on the data volume), so
+a FAKE `nanobot` module stands in for it. The fake is built from the SDK surface measured on 0.3.5
+— the event constants, the StreamEvent fields, the RunResult fields, `Nanobot.from_config` and the
+async context manager — and the entrypoint pins that surface at install time, so a release that
+renames one of them fails the install rather than the first live turn.
+
+What each test pins is one thing that would otherwise be wrong SILENTLY:
+ * usage reported GROSS (it is a measured fact that cache_read is a SUBSET of input_tokens, so a
+ pass-through would bill the cached part at ~10x)
+ * a run that FAILED reported as a turn that completed with no answer
+ * a tool policy set on the registry instead of the session, which would withhold the built-ins
+ and let every MCP tool through
+"""
+import asyncio
+import dataclasses
+import json
+import pathlib
+import subprocess
+import sys
+import tempfile
+import types
+
+DRIVER = pathlib.Path(__file__).resolve().parents[1] / "nanobot_driver.py"
+
+_CONSTS = {
+ "STREAM_EVENT_RUN_STARTED": "run.started",
+ "STREAM_EVENT_TEXT_DELTA": "text.delta",
+ "STREAM_EVENT_TEXT_COMPLETED": "text.completed",
+ "STREAM_EVENT_REASONING_DELTA": "reasoning.delta",
+ "STREAM_EVENT_REASONING_COMPLETED": "reasoning.completed",
+ "STREAM_EVENT_TOOL_STARTED": "tool.started",
+ "STREAM_EVENT_TOOL_COMPLETED": "tool.completed",
+ "STREAM_EVENT_TOOL_FAILED": "tool.failed",
+ "STREAM_EVENT_RUN_COMPLETED": "run.completed",
+ "STREAM_EVENT_RUN_FAILED": "run.failed",
+}
+
+
+def _fake_nanobot_source(events: list, usage: dict | None = None) -> str:
+ """A `nanobot` package whose Nanobot.stream yields the events a real turn yields."""
+ return f'''
+import dataclasses, sys, types
+_consts = {_CONSTS!r}
+mod = types.ModuleType("nanobot")
+for k, v in _consts.items():
+ setattr(mod, k, v)
+
+class LLMUsage:
+ input_tokens: int = 0
+ output_tokens: int = 0
+ cache_read_tokens: int = 0
+ cache_write_tokens = None
+
+class RunResult:
+ content: str = ""
+ tools_used: list = dataclasses.field(default_factory=list)
+ usage: object = None
+ stop_reason: str = "completed"
+ error: str = ""
+
+class StreamEvent:
+ type: str
+ delta: str = ""
+ name: str = None
+ tool_call_id: str = None
+ arguments: dict = None
+ error: str = None
+ metadata: dict = dataclasses.field(default_factory=dict)
+ usage: object = None
+ result: object = None
+
+# Faithful to nanobot/session/manager.py on 0.3.5: SessionPolicy is a FROZEN dataclass on a
+# mutable Session, which is what makes dataclasses.replace the way to change it.
[email protected](frozen=True)
+class SessionPolicy:
+ persist: bool = True
+ log_content: bool = True
+ disabled_tools: frozenset = frozenset()
+
+class Session:
+ key: str
+ policy: SessionPolicy = dataclasses.field(default_factory=SessionPolicy)
+
+class _Sessions:
+ def __init__(self): self.calls = []
+ def get_or_create(self, key):
+ self.calls.append(key)
+ s = POLICY.get("session") or Session(key=key)
+ POLICY["session"] = s
+ return s
+
+class _Loop:
+ def __init__(self): self.sessions = _Sessions()
+
+POLICY = {{}}
+
+class Nanobot:
+ def __init__(self): self._loop = _Loop(); self.runtime = types.SimpleNamespace(model="m")
+ @classmethod
+ def from_config(cls, config_path=None, workspace=None):
+ POLICY["config_path"] = config_path; POLICY["workspace"] = workspace
+ return cls()
+ async def __aenter__(self): return self
+ async def __aexit__(self, *a): return False
+ async def stream(self, message, session_key="sdk:default"):
+ POLICY["prompt"] = message; POLICY["session_key"] = session_key
+ for spec in {events!r}:
+ kind = spec.pop("_kind")
+ if kind == "run.completed":
+ u = LLMUsage(**{usage or {}!r})
+ yield StreamEvent(type=kind, result=RunResult(usage=u, **spec))
+ else:
+ yield StreamEvent(type=kind, **spec)
+
+mod.Nanobot = Nanobot
+mod.LLMUsage = LLMUsage
+mod.RunResult = RunResult
+mod.StreamEvent = StreamEvent
+mod.POLICY = POLICY
+mod.SessionPolicy = SessionPolicy
+mod.Session = Session
+mod._Sessions = _Sessions
+sys.modules["nanobot"] = mod
+'''
+
+
+def _run(events, usage=None, job_extra=None):
+ """Run the driver in a subprocess with the fake package injected, and parse its NDJSON."""
+ d = tempfile.mkdtemp()
+ (pathlib.Path(d) / "sitecustomize.py").write_text(_fake_nanobot_source(events, usage))
+ job = {"config_path": f"{d}/config.json", "workspace": d, "model": "gpt-5.4",
+ "prompt": "do it", "session_key": "hr:one", "tools_disabled": []}
+ job.update(job_extra or {})
+ env = {"PATH": "/usr/bin:/bin", "PYTHONPATH": d}
+ p = subprocess.run([sys.executable, str(DRIVER), json.dumps(job)],
+ capture_output=True, text=True, env=env)
+ out = [json.loads(ln) for ln in p.stdout.splitlines() if ln.strip().startswith("{")]
+ return p, out
+
+
+def _result(out):
+ return next(e for e in out if e.get("type") == "result")
+
+
+def test_a_normal_turn_becomes_claude_stream_json():
+ p, out = _run([
+ {"_kind": "run.started"},
+ {"_kind": "tool.started", "name": "write_file", "tool_call_id": "c1",
+ "arguments": {"path": "probe.txt"}},
+ {"_kind": "tool.completed", "name": "write_file", "tool_call_id": "c1",
+ "metadata": {"detail": "Written 6 bytes"}},
+ {"_kind": "text.delta", "delta": "DONE"},
+ {"_kind": "run.completed", "content": "DONE", "tools_used": ["write_file"]},
+ ], usage={"input_tokens": 11107, "output_tokens": 29, "cache_read_tokens": 5503})
+ assert p.returncode == 0, p.stderr
+ assert out[0] == {"type": "system", "subtype": "init", "session_id": "hr:one", "model": "gpt-5.4"}
+ use = next(e for e in out if "tool_use" in json.dumps(e))
+ blk = use["message"]["content"][0]
+ assert blk["name"] == "write_file" and blk["input"] == {"path": "probe.txt"}
+ res_blk = next(e for e in out if "tool_result" in json.dumps(e))["message"]["content"][0]
+ assert res_blk["is_error"] is False and res_blk["content"] == "Written 6 bytes"
+ r = _result(out)
+ assert r["subtype"] == "success" and r["is_error"] is False and r["result"] == "DONE"
+
+
+def test_usage_is_netted_because_nanobot_reports_it_gross():
+ # MEASURED on 0.3.5: a two-request turn reported input_tokens 11107 with cache_read_tokens
+ # 5503, while its two requests reported 5506 and 5601 — the cached read is a SUBSET of the
+ # input, not a sibling of it. Passing it through would bill 5503 cached tokens at the full
+ # input rate, the exact overcharge _norm_token_usage's own comment describes.
+ _p, out = _run([{"_kind": "run.completed", "content": "ok"}],
+ usage={"input_tokens": 11107, "output_tokens": 29, "cache_read_tokens": 5503})
+ u = _result(out)["usage"]
+ assert u["input_tokens"] == 11107 - 5503
+ assert u["cache_read_tokens"] == 5503
+ assert u["output_tokens"] == 29
+ # cache_write_tokens is None on an endpoint that reports no write; it is read defensively and
+ # simply left out rather than becoming a 0 the biller has to interpret.
+ assert "cache_write_tokens" not in u
+
+
+def test_a_failed_run_is_a_failed_turn_with_the_reason():
+ _p, out = _run([
+ {"_kind": "text.delta", "delta": "let me try"},
+ {"_kind": "run.failed", "error": "provider returned 401"},
+ ])
+ r = _result(out)
+ assert r["is_error"] is True and r["result"] == "provider returned 401"
+
+
+def test_a_stop_reason_that_is_not_completion_fails_the_turn_and_is_the_reason():
+ # A run that stopped on its iteration cap has not answered the question, and reporting its last
+ # text as the answer is the failure-as-prose shape every normaliser here is written against.
+ _p, out = _run([{"_kind": "run.completed", "content": "partial", "stop_reason": "max_iterations"}])
+ r = _result(out)
+ assert r["is_error"] is True and r["reason"] == "max_iterations"
+
+
+def test_a_stream_that_ends_with_no_terminal_event_is_not_a_success():
+ _p, out = _run([{"_kind": "text.delta", "delta": "half"}])
+ r = _result(out)
+ # An EMPTY result on purpose: the runner's stderr tail is the reason, and a sentence invented
+ # here would shadow it.
+ assert r["is_error"] is True and r["result"] == ""
+
+
+def test_the_tool_policy_is_set_on_the_session_not_on_the_registry():
+ # The loop re-reads session.policy.disabled_tools per turn and applies it to the registry it is
+ # about to use — by which time the MCP provider has registered ITS tools into that registry
+ # too. A registry filtered when the driver started would withhold the built-ins and let every
+ # MCP tool through, which is openhands' half-policy defect.
+ d = tempfile.mkdtemp()
+ (pathlib.Path(d) / "sitecustomize.py").write_text(_fake_nanobot_source(
+ [{"_kind": "run.completed", "content": "ok"}]) + '''
+import json, atexit, sys
+def _dump():
+ s = sys.modules["nanobot"].POLICY.get("session")
+ sys.stderr.write("POLICY=" + json.dumps(sorted(s.policy.disabled_tools) if s else None) + "\\n")
+atexit.register(_dump)
+''')
+ job = {"config_path": f"{d}/config.json", "workspace": d, "model": "m", "prompt": "hi",
+ "session_key": "hr:one", "tools_disabled": ["write_file (File Write)", "exec"]}
+ p = subprocess.run([sys.executable, str(DRIVER), json.dumps(job)],
+ capture_output=True, text=True, env={"PATH": "/usr/bin:/bin", "PYTHONPATH": d})
+ line = next(l for l in p.stderr.splitlines() if l.startswith("POLICY="))
+ assert json.loads(line[len("POLICY="):]) == ["exec", "write_file"]
+
+
+def test_a_crashed_driver_fails_the_turn_rather_than_answering_nothing():
+ d = tempfile.mkdtemp()
+ (pathlib.Path(d) / "sitecustomize.py").write_text(
+ 'import sys, types\nm = types.ModuleType("nanobot")\nsys.modules["nanobot"] = m\n')
+ job = {"config_path": f"{d}/c.json", "workspace": d, "model": "m", "prompt": "hi",
+ "session_key": "s", "tools_disabled": []}
+ p = subprocess.run([sys.executable, str(DRIVER), json.dumps(job)],
+ capture_output=True, text=True, env={"PATH": "/usr/bin:/bin", "PYTHONPATH": d})
+ assert p.returncode == 1
+ out = [json.loads(ln) for ln in p.stdout.splitlines() if ln.strip().startswith("{")]
+ assert out and out[-1]["is_error"] is True
+ # the reason reaches stderr too, which is what the runner collects into the turn's failure text
+ assert "ImportError" in p.stderr or "nanobot driver:" in p.stderr
+
+
+def test_a_tool_policy_that_does_not_take_fails_the_turn_rather_than_running_without_it():
+ # The worst shape of this defect is the quiet one: the console reports the tool as off, the
+ # model is offered it anyway, and nothing says so. Here the session's policy refuses the
+ # assignment, which is what a release that changed SessionPolicy would look like from outside.
+ d = tempfile.mkdtemp()
+ (pathlib.Path(d) / "sitecustomize.py").write_text(
+ _fake_nanobot_source([{"_kind": "run.completed", "content": "ok"}]) + '''
+import sys
+_m = sys.modules["nanobot"]
+class _Stuck:
+ key = "s"
+ @property
+ def policy(self): return _m.SessionPolicy()
+ @policy.setter
+ def policy(self, v): pass
+_m._Sessions.get_or_create = lambda self, key: _Stuck()
+''')
+ job = {"config_path": f"{d}/c.json", "workspace": d, "model": "m", "prompt": "hi",
+ "session_key": "s", "tools_disabled": ["write_file"]}
+ p = subprocess.run([sys.executable, str(DRIVER), json.dumps(job)],
+ capture_output=True, text=True, env={"PATH": "/usr/bin:/bin", "PYTHONPATH": d})
+ assert p.returncode == 1, p.stdout + p.stderr
+ out = [json.loads(ln) for ln in p.stdout.splitlines() if ln.strip().startswith("{")]
+ assert out[-1]["is_error"] is True
+ assert "tool policy" in out[-1]["result"]
diff --git a/runner/tests/test_relay_tool_schema_repair.py b/runner/tests/test_relay_tool_schema_repair.py
new file mode 100644
index 00000000..ce8c7b4e
--- /dev/null
+++ b/runner/tests/test_relay_tool_schema_repair.py
@@ -0,0 +1,98 @@
+"""A channel that refuses the harness's tool declarations gets them normalised, and is remembered.
+
+MEASURED on Vercel, 2026-10-07, the batch-3 nanobot column: one of eight models (gemini-3.6-flash)
+died on its FIRST turn with
+
+ GenerateContentRequest.tools[0].function_declarations[14].parameters.properties[args].items:
+ field predicate failed: $type == Type.ARRAY
+ …properties[args].any_of[0].items: missing field.
+
+— an optional array parameter (`anyOf: [array, null]`, no `items`) that reached Google as sent. The
+relay already carried the normaliser, applied proactively on TokenRouter's Gemini channels only,
+because the comment above it said Vercel normalises these first. It does for most shapes and not for
+this one, so the repair is now also reactive: the provider names the problem, the relay fixes it and
+remembers it for the route. Reactive rather than proactive everywhere on purpose — the normaliser
+flattens anyOf, which loses information a channel that handles it faithfully would have kept.
+"""
+import json
+import os
+import pathlib
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import server as S # noqa: E402
+
+REFUSAL = (b'{"error":{"message":"* GenerateContentRequest.tools[0].function_declarations[14]'
+ b'.parameters.properties[args].items: field predicate failed: $type == Type.ARRAY\\n'
+ b'* GenerateContentRequest.tools[0].function_declarations[14].parameters.properties'
+ b'[args].any_of[0].items: missing field.\\n"}}')
+
+
+def _body(**over):
+ b = {"model": "gemini-3.6-flash", "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"type": "function", "function": {"name": "shell", "parameters": {
+ "type": "object",
+ "properties": {"args": {"anyOf": [{"type": "array"}, {"type": "null"}],
+ "description": "argv"}}}}}]}
+ b.update(over)
+ return json.dumps(b).encode()
+
+
+def test_the_exact_refused_shape_becomes_one_google_accepts():
+ out = json.loads(S._with_gemini_schemas(_body()))
+ args = out["tools"][0]["function"]["parameters"]["properties"]["args"]
+ assert args["type"] == "array", "the anyOf is flattened to the member that carries data"
+ assert args["items"] == {"type": "string"}, "Google requires items on every array"
+ assert args["nullable"] is True, "the null member is kept, as nullable"
+ assert args["description"] == "argv", "and the text the model reads survives"
+ assert "anyOf" not in args and "any_of" not in args
+
+
+def test_the_refusal_text_is_what_triggers_it():
+ # the branch keys on the provider naming its own validator's field path
+ assert b"function_declarations" in REFUSAL
+
+
+def test_a_body_with_nothing_to_fix_is_left_alone_so_the_retry_does_not_loop():
+ # the branch only continues when the normalised body DIFFERS; an unchanged body must fall
+ # through to the next repair instead of resending the same bytes twice.
+ clean = _body(tools=[{"type": "function", "function": {
+ "name": "shell", "parameters": {"type": "object", "properties": {
+ "args": {"type": "array", "items": {"type": "string"}}}}}}])
+ assert S._with_gemini_schemas(clean) == clean
+
+
+def test_vercel_is_still_not_a_proactive_channel():
+ # the point of doing this reactively: Vercel handles most shapes faithfully, and flattening
+ # every anyOf for every base on it would lose what it was getting right.
+ assert not S._gemini_channel("https://ai-gateway.vercel.sh/v1")
+ assert S._gemini_channel("https://api.tokenrouter.com/v1")
+
+
+# ── the memo that stops every turn paying for the same refusal ───────────────────────────
+# Each turn gets its own relay route, so a flag on the route is forgotten at the next turn: the run
+# that found this paid one refused round trip per turn, four turns in a row. The repair is remembered
+# for the runner's life instead, keyed by upstream host and model. Nothing else pins that key, and a
+# memo that silently stopped matching would only cost an extra round trip per turn — the kind of
+# regression no column would ever show.
+
+def test_the_memo_is_keyed_by_upstream_host_and_model_not_by_the_whole_url():
+ a = S._gemini_schema_key("https://ai-gateway.vercel.sh/v1", "google/gemini-3.6-flash")
+ # the same channel and model reached through another path is the same channel and model
+ b = S._gemini_schema_key("https://ai-gateway.vercel.sh/v1/chat/completions", "google/gemini-3.6-flash")
+ assert a == b == ("ai-gateway.vercel.sh", "google/gemini-3.6-flash")
+
+
+def test_the_model_is_matched_without_case_and_a_different_one_is_a_different_key():
+ k = S._gemini_schema_key("https://x.example/v1", "Google/Gemini-3.6-Flash")
+ assert k == ("x.example", "google/gemini-3.6-flash")
+ assert k != S._gemini_schema_key("https://x.example/v1", "google/gemini-3.8-flash")
+ # and the normalisation is NOT applied on a guess to a model that has not refused
+ assert S._gemini_schema_key("https://x.example/v1", "") == ("x.example", "")
+
+
+def test_another_channel_serving_the_same_model_is_not_assumed_to_refuse_too():
+ assert (S._gemini_schema_key("https://ai-gateway.vercel.sh/v1", "google/gemini-3.6-flash")
+ != S._gemini_schema_key("https://generativelanguage.googleapis.com/v1beta/openai",
+ "google/gemini-3.6-flash"))
diff --git a/scripts/support-matrix/custom-harness.mjs b/scripts/support-matrix/custom-harness.mjs
index a130dead..c177398d 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,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,cheetahclaws,agentzero').split(','); // every built-in chat harness, all nineteen (systemone runs decision models only)
+const BASES = (process.env.BASES || 'codex,claude-code,hermes,pi,dsh,opencode,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,cheetahclaws,agentzero,mimo,jcode,opensquilla,nanobot').split(','); // every built-in chat harness, all nineteen (systemone runs decision models only)
const RESULTS = process.env.RESULTS || 'results-custom.json';
// A harness's other kind of tool is an MCP server. A self-contained instance hosts only the
// database and media servers, one needing a database and the other costing real money per call, so
@@ -41,7 +41,20 @@ const toolLabel = (t) => {
const raw = typeof (t && t.arguments) === 'string' ? t.arguments : JSON.stringify((t && t.arguments) || '');
let a = {}; try { a = JSON.parse(raw || '{}') || {}; } catch { /* not json; the raw string still feeds xd:// below */ }
const xd = /xd:\/\/(mcp__[A-Za-z0-9_]+)/.exec(raw || '');
- return [name, a.tool_name, a.tool, a.name, a.server, xd ? xd[0] : ''].filter(Boolean).map(String).join(' ');
+ // A THIRD shape, and it is not a JSON field: mimo's `exec` is a JavaScript sandbox with the tool
+ // registry in scope, so a served MCP turn is two exec calls — one filtering ALL_TOOLS for the
+ // server, one invoking the tool it found BY NAME inside the code (measured 2026-10-07 on mimo
+ // 0.1.15: `const toolName = 'deepwiki_ask_wiki_question'`, and the answer named a real topic from
+ // that wiki). Read the name and the JSON fields alone and that is `exec, exec`, which made a
+ // PASSING base the dimension's only MCP failure. The discriminator is dispatch versus HTTP: a
+ // call whose code names one of the server's TOOLS went through the harness's wiring, while one
+ // carrying the server's URL did not — a shell that curls the endpoint reaches the same data and
+ // proves nothing, so it keeps counting as a miss. No word boundary before the bare names: the
+ // name mimo dispatched has the server's own prefix glued to it.
+ const inCode = (raw && !raw.includes(MCP_URL))
+ ? (/mcp__[A-Za-z0-9_]+|read_wiki_structure|read_wiki_contents|ask_wiki_question/.exec(raw) || [])[0]
+ : '';
+ return [name, a.tool_name, a.tool, a.name, a.server, xd ? xd[0] : '', inCode || ''].filter(Boolean).map(String).join(' ');
};
const MCP_TOOL = new RegExp(`(^|[^a-z])mcp([^a-z]|$)|${MCP_NAME}|read_wiki_structure|read_wiki_contents|ask_question`, 'i');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -107,7 +120,9 @@ const results = {};
// skill's script), something that reads or writes FILES, whatever loads a SKILL, and the MCP path.
// Agent Zero names its file tool `text_editor` and its loader `skills_tool`, so a list written from
// grok's and minimax's names alone picked `text_editor` — the tool the fixture writes with.
-const NEEDED_ID = /^(bash|shell|execute|run_command|run_terminal_command|terminal|code_execution_tool|python.*|node.*|read|read_file|write|write_file|edit|file_edit(or)?|text_editor|str_replace.*|create_file|view|search_replace|apply_patch|glob|grep|list_dir|ls|skills?_?tool|skill|task|search_tool|use_tool|mcp.*)$/i;
+// opensquilla and nanobot name theirs `exec` (and nanobot has `exec_session` too), which `execute`
+// does not match — so the list would have withheld the tool the fixture runs its script with.
+const NEEDED_ID = /^(bash|shell|exec|exec_session|execute|run_command|run_terminal_command|terminal|code_execution_tool|python.*|node.*|read|read_file|write|write_file|edit|file_edit(or)?|text_editor|str_replace.*|create_file|view|search_replace|apply_patch|glob|grep|list_dir|ls|skills?_?tool|skill|task|search_tool|use_tool|mcp.*)$/i;
const PREFERRED = /^(todo_write|todowrite|todo|web_?fetch|web_?search|browser.*|board_.*|link_pr|goal|wait)$/i;
const pickDisabled = (tools) => {
const names = (tools || []).map((t) => String((t && t.name) || t || '')).filter(Boolean);
diff --git a/scripts/support-matrix/family-tour.mjs b/scripts/support-matrix/family-tour.mjs
index 1943322d..ca83566b 100644
--- a/scripts/support-matrix/family-tour.mjs
+++ b/scripts/support-matrix/family-tour.mjs
@@ -15,8 +15,44 @@
// (optional: continue an existing conversation instead of starting one), FAMILIES (optional comma
// list of model ids, one per family; default below), RESULTS (json path), IGNORE_TLS=1.
import fs from 'node:fs';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
import { chromium } from 'playwright';
+// A FAMILY'S TURN HAS TO BE SERVED BY THAT FAMILY. Without this the tour measured only that the
+// conversation survived, and on 2026-10-07 it passed jcode 12 of 12 while every one of those twelve
+// turns was served by openai/gpt-5.4 — jcode's `--model` is its session's INITIAL one, so on
+// --resume the stored model won and the chip the person moved did nothing. A tour that cannot see
+// that is not measuring a model tour.
+//
+// `samemodel.py` is the gateway's own rule and is called rather than copied: an aggregator adds or
+// drops a vendor prefix, a provider appends a dated suffix, and a vendor table renames outright
+// (hunyuan-4-preview is served as tencent/hy4-preview). Reimplementing any of that here would be a
+// second rule to keep in step with the first.
+const HERE = path.dirname(new URL(import.meta.url).pathname);
+// samemodel.py needs 3.10+ (it annotates with `X | None`), and a mac's `python3` is still 3.9, which
+// raised a TypeError on import — a failure this would have swallowed as "nothing to judge on",
+// failing every row for a reason that is about this laptop. The interpreter is therefore CHOSEN,
+// once, by importing the module with it, and a run with none to choose stops instead of measuring.
+const PYTHON = (() => {
+ for (const c of [process.env.PYTHON, 'python3.13', 'python3.12', 'python3.11', 'python3.10', 'python3'].filter(Boolean)) {
+ try {
+ execFileSync(c, ['-c', 'import samemodel'], { cwd: HERE, stdio: 'ignore' });
+ return c;
+ } catch { /* next */ }
+ }
+ console.error('no python that can import samemodel.py (needs 3.10+); set PYTHON=');
+ process.exit(2);
+})();
+const sameModel = (asked, served) => {
+ if (!served) return null; // nothing to judge on — NOT a pass; see the status text below
+ try {
+ return execFileSync(PYTHON, ['-c',
+ 'import sys, samemodel as m; print("1" if m.alias_of(sys.argv[1], sys.argv[2]) else "0")',
+ String(asked), String(served)], { cwd: HERE, encoding: 'utf8' }).trim() === '1';
+ } catch (e) { return null; }
+};
+
const BASE = process.env.BASE, USER = process.env.HR_USER, PASS = process.env.HR_PASS;
const HARNESS = process.env.HARNESS || 'cheetahclaws';
const SID = process.env.SID || '';
@@ -143,10 +179,14 @@ for (const model of FAMILIES) {
const stamp = `tour ${model} ${++editIdx}`;
const edit = `${EDITS[(editIdx - 1) % EDITS.length]} Also set the slide's footer text to exactly "${stamp}". Keep it in tour.pptx.`;
const s = await sendTurn(edit);
- const ok = !s.timedOut && s.last?.status === 'completed' && (s.last.files || []).some((f) => /\.pptx$/i.test(f.filename || f.name || ''));
const deck = (s.last?.files || []).some((f) => /\.pptx$/i.test(f.filename || f.name || ''));
- const row = { family: model, model: s.last?.model, served: s.last?.served_model,
- status: s.timedOut ? `not settled in ${TURN_CAP_S}s, stopped (${s.last?.status})` : (s.last?.status === 'completed' && !deck ? 'completed, deck not produced' : s.last?.status),
+ const served = sameModel(model, s.last?.served_model);
+ const ok = !s.timedOut && s.last?.status === 'completed' && deck && served === true;
+ const row = { family: model, model: s.last?.model, served: s.last?.served_model, served_as_asked: served,
+ status: s.timedOut ? `not settled in ${TURN_CAP_S}s, stopped (${s.last?.status})`
+ : (s.last?.status === 'completed' && !deck ? 'completed, deck not produced'
+ : (s.last?.status === 'completed' && served === false ? `completed, but served ${s.last?.served_model} and not ${model}`
+ : (s.last?.status === 'completed' && served === null ? 'completed, but no served model was recorded — this rule has nothing to judge on' : s.last?.status))),
seconds: s.seconds, edit, tool_calls: (s.last?.tools || []).length, files: (s.last?.files || []).map((f) => f.filename || f.name), ok, error: s.last?.error || '' };
results.turns.push(row);
log(ok ? 'PASS' : 'FAIL', model, '->', row.status, s.seconds + 's', 'served', s.last?.served_model || '', 'tool calls', row.tool_calls, s.last?.error ? '| ' + s.last.error.slice(0, 160) : '', ok ? '' : '| files ' + JSON.stringify(row.files));
diff --git a/scripts/support-matrix/plugins/run-matrix.py b/scripts/support-matrix/plugins/run-matrix.py
index 92fb953e..507755b8 100755
--- a/scripts/support-matrix/plugins/run-matrix.py
+++ b/scripts/support-matrix/plugins/run-matrix.py
@@ -39,7 +39,15 @@ 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", "kilo", "cline", "omp", "pi", "dsh", "kimi", "minimax", "grok", "aider", "openhands", "cheetahclaws", "agentzero"]
+BASES = ["claude-code", "codex", "hermes", "goose", "gemini", "qwen", "opencode", "kilo", "cline",
+ "omp", "pi", "dsh", "kimi", "minimax", "grok", "aider", "openhands", "cheetahclaws",
+ "agentzero",
+ # 2026-10-02: mimo, jcode, opensquilla and nanobot. Every one of them takes a
+ # stdio server, two of them ONLY through the runner's bridge — jcode has no remote
+ # MCP client at all ("HTTP/SSE entries are recognized and skipped with a log line")
+ # and opensquilla takes stdio and SSE but not streamable HTTP, so both are in
+ # _BRIDGED_TRANSPORTS and a remote column measures the bridge on them.
+ "mimo", "jcode", "opensquilla", "nanobot"]
NO_STDIO: set[str] = set()
# The public probe the remote columns call: its SSE end answers PROBE-SSE-<id>, its streamable-HTTP
# end PROBE-HTTP-<id>. Both are the same fixed server, so a wrong answer is the base, not the probe.
diff --git a/scripts/support-matrix/run.mjs b/scripts/support-matrix/run.mjs
index e75a96c2..bd6b361d 100644
--- a/scripts/support-matrix/run.mjs
+++ b/scripts/support-matrix/run.mjs
@@ -6,6 +6,36 @@
// IGNORE_TLS=1 for a self-signed instance.
import { chromium } from 'playwright';
import fs from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+const SM_HERE = path.dirname(new URL(import.meta.url).pathname);
+
+// THE SWITCH TURN HAS TO BE SERVED BY THE MODEL THE CHIP MOVED TO. `substituted` below judges only
+// turns whose record names THIS pair's model, and the switch turn names the partner on purpose — so
+// nothing looked at what served it. jcode's eight pairs passed their switch row on 2026-10-07 while
+// not one switch took: its `--model` is a session's INITIAL model, so on --resume the stored one won.
+// The shape was in the records the whole time — every jcode pair's `served` list had ONE entry where
+// every mimo pair's had two — and no rule read it.
+//
+// samemodel.py is the gateway's own rule, called rather than copied (a vendor prefix, a dated suffix
+// and an outright rename like tencent/hy4-preview for hunyuan-4-preview are all the same model). It
+// needs 3.10+ and a mac's `python3` is 3.9, so the interpreter is chosen by importing the module
+// with it; a run with none to choose stops rather than measuring with a rule that always says no.
+const SM_PYTHON = (() => {
+ for (const c of [process.env.PYTHON, 'python3.13', 'python3.12', 'python3.11', 'python3.10', 'python3'].filter(Boolean)) {
+ try { execFileSync(c, ['-c', 'import samemodel'], { cwd: SM_HERE, stdio: 'ignore' }); return c; } catch { /* next */ }
+ }
+ console.error('no python that can import samemodel.py (needs 3.10+); set PYTHON=');
+ process.exit(2);
+})();
+const sameModel = (asked, served) => {
+ if (!asked || !served) return false;
+ try {
+ return execFileSync(SM_PYTHON, ['-c',
+ 'import sys, samemodel as m; print("1" if m.alias_of(sys.argv[1], sys.argv[2]) else "0")',
+ String(asked), String(served)], { cwd: SM_HERE, encoding: 'utf8' }).trim() === '1';
+ } catch { return false; }
+};
const BASE = process.env.BASE, PROVIDER = process.env.PROVIDER, RESULTS = process.env.RESULTS, LOG = process.env.LOG;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const log = (s) => { const line = `${new Date().toISOString()} ${s}`; console.log(line); fs.appendFileSync(LOG, line + '\n'); };
@@ -14,7 +44,22 @@ const save = (r) => fs.writeFileSync(RESULTS, JSON.stringify(r, null, 1));
const key = (h, m) => `${PROVIDER}|${h}|${m}`;
async function rt(p, s, v) { await p.$eval(s, (el, x) => { const P = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement : HTMLInputElement; Object.getOwnPropertyDescriptor(P.prototype, 'value').set.call(el, x); el.dispatchEvent(new Event('input', { bubbles: true })); }, v); }
const b = await chromium.launch({ headless: true });
-const page = await (await b.newContext({ viewport: { width: 1440, height: 900 }, ignoreHTTPSErrors: process.env.IGNORE_TLS === '1' })).newPage();
+// MUTABLE, and replaceable: the renderer can crash, and a crashed page poisons every pair after it.
+// MEASURED on 2026-10-10: one "page.goto: Page crashed" partway through opensquilla's column left
+// the remaining 32 of 50 pairs with that error and no scenarios at all, and the column read as
+// "49/50 pairs" to a reader counting passes. The pair loop now rebuilds this and retries the pair.
+let page = await (await b.newContext({ viewport: { width: 1440, height: 900 }, ignoreHTTPSErrors: process.env.IGNORE_TLS === '1' })).newPage();
+const CRASHED = /Page crashed|Target (?:page|closed)|Target closed|browser has been closed|Session closed/i;
+async function freshPage() {
+ try { await page.context().close(); } catch { /* already gone */ }
+ page = await (await b.newContext({ viewport: { width: 1440, height: 900 }, ignoreHTTPSErrors: process.env.IGNORE_TLS === '1' })).newPage();
+ await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' }); await sleep(2500);
+ if (page.url().includes('/login')) {
+ await rt(page, '#sh-user', process.env.HR_USER || 'harnessrouter'); await rt(page, '#sh-pass', process.env.HR_PASS);
+ await page.click('button[type=submit]'); await page.waitForURL((u) => !u.pathname.includes('/login'), { timeout: 60000 });
+ }
+ await sleep(1500); await dismissWelcome();
+}
const pill = () => page.evaluate(() => document.querySelector('.hx-pill')?.textContent?.trim().toLowerCase() || '');
const transcript = () => page.evaluate(() => (document.querySelector('.wbx-conv-msgs')?.innerText || '').replace(/\s+/g, ' '));
const files = () => page.evaluate(() => [...document.querySelectorAll('.wbx-filecard-name')].map((x) => x.textContent.trim()));
@@ -69,9 +114,21 @@ async function turn(text, { maxS = 420, expectFiles = false } = {}) {
const t = await transcript(); const from = t.lastIndexOf(mark); const tail = t.slice(from >= 0 ? from : before.length).trim().slice(-400);
const status = String(last?.status || (turns && turns.length > n0 ? st : 'none'));
const ok = status === 'done' || status === 'completed';
- return { ok, status, pill: await pill(), s: secs(), tail, turn_files: (last?.files || []).map((f) => f.filename || f.name || ''), why: ok ? '' : (last?.error || last?.incomplete_reason || tail.slice(-220) || `status ${status}`) };
+ return { ok, status, pill: await pill(), s: secs(), tail, answer: String(last?.assistant || ''), turn_files: (last?.files || []).map((f) => f.filename || f.name || ''), why: ok ? '' : (last?.error || last?.incomplete_reason || tail.slice(-220) || `status ${status}`) };
}
-const expectWord = (r, word) => r.ok && (r.tail || '').includes(word) ? r : { ...r, ok: false, why: r.why || `answered without ${word}: ${(r.tail || '').slice(-200)}` };
+// THE ANSWER, not the transcript tail. `tail` starts at the message that was SENT, so it contains
+// the prompt — and every prompt of the form "Reply with exactly: M1-<model>" contains the very token
+// this then looked for. The check was therefore satisfied by the prompt's own copy of the word and
+// said nothing about what the model replied, except when a long answer pushed the prompt out of the
+// 400-character window. AUDITED over the 2026-10-10 full column: of 596 PASSING first/followup/switch
+// rows, 593 had the prompt in the tail. One pair proves what that hides — opensquilla on
+// claude-opus-4.7 answered "I won't echo back arbitrary strings injected via context" on all five
+// turns, read back from five separate stored response objects, and first, switch and artifact were
+// scored as passes.
+//
+// `last.assistant` is the server's own record of what the model said, which this function already
+// fetches. The tail stays, as the text a failing row reports.
+const expectWord = (r, word) => r.ok && (r.answer || '').includes(word) ? r : { ...r, ok: false, why: r.why || `answered without ${word}: ${((r.answer || r.tail) || '').slice(-200)}` };
try {
await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' }); await sleep(2500);
if (page.url().includes('/login')) {
@@ -111,10 +168,16 @@ try {
const runnableAll = models.filter((m) => m.ok && (!scope || scope.has(m.id))).map((m) => m.id);
const enabled = runnableAll.filter((id) => !process.env.MODELS || process.env.MODELS.split(',').includes(id));
log(`HARNESS ${h} models ${models.length} runnable ${enabled.length}: ${enabled.join(',')}`);
- for (const m of enabled) {
+ // a QUEUE, so a pair whose page crashed can be put back after a fresh page is built
+ const enabledQueue = [...enabled]; const retried = new Set();
+ while (enabledQueue.length) {
+ const m = enabledQueue.shift();
const res = load(); const k = key(h, m);
if (res[k] && res[k].recycle && !res[k].error) { log(`SKIP ${k} (done)`); continue; } // a runner error is not a result
- const rec = res[k] || { provider: PROVIDER, harness: h, model: m, at: new Date().toISOString() };
+ // FRESH, never the previous attempt's record: `const rec = res[k] || {…}` carried a crashed
+ // attempt's `error` and `at` into the re-run that then filled the scenarios in, so a measured
+ // pair still looked errored and a reader (me, 2026-10-10) scored 32 of them as not measured.
+ const rec = { provider: PROVIDER, harness: h, model: m, at: new Date().toISOString() };
try {
await page.goto(`${BASE}/harnesses?h=${h}`, { waitUntil: 'domcontentloaded' }); await sleep(3000);
for (let i = 0; i < 10 && !(await page.locator('.wbx-conv-main.is-hero').count()); i++) { await page.click('button:has-text("New task")').catch(() => {}); await sleep(800); }
@@ -154,8 +217,16 @@ try {
// the sandbox is let go on purpose (what the pool does between visits) and the next turn must
// carry on from the durable checkpoint: the history, the files, the resume id
// the route refuses with 409 while the previous turn is still settling: ask again a few times
+ // The route refuses while a turn is still settling, and retrying the 409 for 30 s was not
+ // enough for a turn that runs long: mimo on gpt-5.6-luna had an artifact turn still
+ // `running` at 478 s, so the recycle row read "recycle refused: HTTP 409 a turn is
+ // running" — a sentence about this driver's patience, not about the base. Wait for the
+ // session's own record to be terminal first, and say so when it never is.
+ let settled = false;
+ for (let i = 0; i < 100; i++) { const d2 = await detailOf(rec.sid); if (TERMINAL.has(String(d2?.turn_status || d2?.status || ''))) { settled = true; break; } await sleep(3000); }
let rc = { code: 0, body: '' };
- for (let i = 0; i < 6; i++) { rc = await page.evaluate(async (sid) => { const r = await fetch(`/api/harness/internal/sessions/${sid}/recycle`, { method: 'POST' }); return { code: r.status, body: (await r.text()).slice(0, 200) }; }, rec.sid); if (rc.code !== 409) break; await sleep(5000); }
+ if (!settled) rc = { code: 0, body: 'the previous turn was still running after 300 s' };
+ else for (let i = 0; i < 6; i++) { rc = await page.evaluate(async (sid) => { const r = await fetch(`/api/harness/internal/sessions/${sid}/recycle`, { method: 'POST' }); return { code: r.status, body: (await r.text()).slice(0, 200) }; }, rec.sid); if (rc.code !== 409) break; await sleep(5000); }
if (rc.code === 200) {
await sleep(2000);
const r5 = await turn('What exact word did I ask you to reply with in my very first message of this task? Reply with just that word.');
@@ -165,7 +236,15 @@ try {
} else rec.recycle = { ok: false, s: 0, why: `recycle refused: HTTP ${rc.code} ${rc.body}`, recycled: rc };
log(`RECYCLE ${k} ${rec.recycle.ok ? 'ok' : 'FAIL'} ${rec.recycle.s}s ${rec.recycle.why}`);
} else { rec.followup = { ok: null, why: 'first turn failed' }; rec.switch = { ok: null, why: 'first turn failed' }; rec.artifact = { ok: null, why: 'first turn failed' }; rec.recycle = { ok: null, why: 'first turn failed' }; }
- } catch (e) { rec.error = String(e).slice(0, 300); log(`ERROR ${k} ${rec.error}`); if (/has been closed/.test(rec.error)) throw e; } // a closed browser ends the worker; the next launch resumes
+ } catch (e) {
+ rec.error = String(e).slice(0, 300); log(`ERROR ${k} ${rec.error}`);
+ if (/browser has been closed/.test(rec.error)) throw e; // the browser itself is gone: end the worker, the next launch resumes
+ if (CRASHED.test(rec.error) && !retried.has(k)) {
+ // one retry on a fresh page: the crash is this driver's, and the pair has not been measured
+ retried.add(k); log(`RECOVER ${k} rebuilding the page and running this pair again`);
+ try { await freshPage(); enabledQueue.push(m); } catch (e2) { log(`RECOVER failed: ${String(e2).slice(0, 160)}`); throw e; }
+ }
+ }
// the record is complete: stamp the connection that served it, then let the session go. Its
// workspace, checkpoint and trace are of no further use, and 170 of them per provider filled
// a 62 GB disk (hr-oss-test, 2026-09-06).
@@ -187,6 +266,20 @@ try {
rec.substituted = withModel.length
? [...new Set(withModel.filter((t) => t.model === m && String(t.served_model).split(',').some((x) => x && x !== m)).map((t) => String(t.served_model)))]
: (rec.served.length && !rec.served.some((sm) => sm.split(',').includes(m)) ? rec.served : []);
+ // The switch row, judged on the SERVED model and not only on the word it echoed back.
+ const partner = rec.switch && rec.switch.to;
+ if (partner && withModel.length) {
+ const swTurns = withModel.filter((t) => String(t.model) === String(partner));
+ rec.switch_served = [...new Set(swTurns.map((t) => String(t.served_model)))];
+ const took = swTurns.length > 0 && swTurns.every((t) => sameModel(partner, String(t.served_model)));
+ if (rec.switch.ok === true && !took) {
+ rec.switch.ok = false;
+ rec.switch.why = swTurns.length
+ ? `the chip moved to ${partner} and the turn was served by ${rec.switch_served.join(',')}`
+ : `no turn record names ${partner}, so the switch cannot be shown to have happened`;
+ log(`SWITCH ${k} -> ${partner} FAIL (on the served model) ${rec.switch.why}`);
+ }
+ }
// No turn of this pair asked for the pair's own model: the picker's choice did not reach the
// request (a wrong option clicked, a composer that reset it), so every check keyed on
// `t.model === m` above would pass over nothing. A finding of its own (render.py), never a clean row.
@@ -208,9 +301,17 @@ try {
const inTok = usages.reduce((n, u) => n + (u ? Number(u.input_tokens || 0) : 0), 0);
const cached = usages.reduce((n, u) => n + (u ? Number(u.cache_read_tokens || (u.input_tokens_details || {}).cached_tokens || 0) : 0), 0);
rec.tokens = { input: inTok, cache_read: cached, turns_with_usage: usages.filter(Boolean).length };
- rec.deleted = await page.evaluate(async (sid) => { const r = await fetch(`/api/harness/v1/sessions/${sid}`, { method: 'DELETE' }); return r.status; }, rec.sid).catch(() => 0);
+ // A PASSING pair is cleaned up; a FAILING one is kept. The delete used to be
+ // unconditional, and that is why two failing jcode rows (2026-10-06) could not be
+ // investigated afterwards: the session was gone, so /files and /turns answered 404 and all
+ // that survived was the judge's own sentence about what it saw. The record says what the
+ // JUDGE saw; the session is the only place that says what the SYSTEM did.
+ const failed = ['first', 'followup', 'switch', 'artifact', 'recycle']
+ .some((n) => rec[n] && rec[n].ok === false);
+ if (failed) { rec.kept = rec.sid; rec.deleted = 0; }
+ else rec.deleted = await page.evaluate(async (sid) => { const r = await fetch(`/api/harness/v1/sessions/${sid}`, { method: 'DELETE' }); return r.status; }, rec.sid).catch(() => 0);
}
- const all = load(); all[k] = rec; save(all); log(`PAIR_DONE ${k} connection=${rec.connection || '?'} turns=${(rec.connections || []).join('+') || '?'}${(rec.foreign || []).length ? ' FOREIGN=' + rec.foreign.join('+') : ''}${(rec.served || []).length ? ' served=' + rec.served.join('+') : ''}${(rec.substituted || []).length ? ' SUBSTITUTED=' + rec.substituted.join('+') : ''} deleted=${rec.deleted || '?'}`);
+ const all = load(); all[k] = rec; save(all); log(`PAIR_DONE ${k} connection=${rec.connection || '?'} turns=${(rec.connections || []).join('+') || '?'}${(rec.foreign || []).length ? ' FOREIGN=' + rec.foreign.join('+') : ''}${(rec.served || []).length ? ' served=' + rec.served.join('+') : ''}${(rec.substituted || []).length ? ' SUBSTITUTED=' + rec.substituted.join('+') : ''}${rec.kept ? ' KEPT=' + rec.kept : ' deleted=' + (rec.deleted || '?')}`);
}
}
} catch (e) { log(`FATAL ${String(e).slice(0, 300)}`); }
diff --git a/ui/public/logos/jcode.png b/ui/public/logos/jcode.png
new file mode 100644
index 00000000..597c2c47
Binary files /dev/null and b/ui/public/logos/jcode.png differ
diff --git a/ui/public/logos/mimo.png b/ui/public/logos/mimo.png
new file mode 100644
index 00000000..32989379
Binary files /dev/null and b/ui/public/logos/mimo.png differ
diff --git a/ui/public/logos/nanobot.svg b/ui/public/logos/nanobot.svg
new file mode 100644
index 00000000..b05d878f
--- /dev/null
+++ b/ui/public/logos/nanobot.svg
@@ -0,0 +1,23 @@
+<svg width="759" height="718" viewBox="0 0 759 718" fill="none" xmlns="http://www.w3.org/2000/svg">
+<title>nanobot mark</title>
+<path d="M229.029 127.134C308.64 112.113 354.143 106.879 379.029 108.134V716.634L272.029 715.634C251.029 715.634 243.029 702.634 201.529 678.134L54.5291 581.634C30.0291 565.134 23.9802 560.075 13.0291 549.134C3.52914 537.634 -1.97086 526.634 3.52914 481.634L28.0291 340.634L29.5291 27.1337C31.0291 -2.36625 53.0291 -6.86625 77.0291 12.6337L229.029 127.134Z" fill="#F4A949" stroke="#F4A949"/>
+<path d="M529.842 126.817C450.231 111.796 404.728 106.562 379.842 107.817V716.317L486.842 715.317C509.342 714.317 570.342 661.817 611.842 637.317L704.342 581.317C728.842 564.817 734.891 559.759 745.842 548.817C755.342 537.317 760.842 526.317 755.342 481.317L730.842 340.317L729.342 26.817C727.842 -2.68287 705.842 -7.18287 681.842 12.3171L529.842 126.817Z" fill="#EF8E30" stroke="#EF8E30"/>
+<path d="M143.342 497.317H1.84164C-6.15857 550.317 22.8417 557.817 56.3419 582.817L143.342 497.317Z" fill="#E27223" stroke="#DF6E22"/>
+<path d="M615.342 496.817H757.001C765.002 549.817 735.842 557.317 702.342 582.317L615.342 496.817Z" fill="#D96016" stroke="#D45F16"/>
+<path d="M379.342 716.317V517.817H288.342C239.842 517.817 243.342 531.817 144.842 640.817L233.342 698.817C245.302 707.847 260.342 717.317 275.342 715.817L379.342 716.317Z" fill="#FBCB89" stroke="#FBCB8A"/>
+<path d="M566.842 382.817C561.842 348.817 509.842 341.317 501.342 382.817V439.317C509.842 477.317 559.342 478.317 566.842 439.317V382.817Z" fill="#B94D0B" stroke="#B5490B"/>
+<path d="M379.342 716.317V517.817H470.342C518.842 517.817 513.342 528.317 611.842 637.317L522.842 698.817C510.881 707.847 495.342 715.817 483.342 715.817L379.342 716.317Z" fill="#F7B066" stroke="#F8B166"/>
+<path d="M258.842 383.199C253.842 349.199 201.842 341.699 193.342 383.199V439.699C201.842 477.699 251.342 478.699 258.842 439.699V383.199Z" fill="#B94D0B" stroke="#B94D0B"/>
+<path d="M439.342 517.817H318.342L379.842 583.317L439.342 517.817Z" fill="#C85513" stroke="#C85513"/>
+<path d="M379.342 583.317V517.817H438.842L379.342 583.317Z" fill="#BA470A" stroke="#B94D0B"/>
+<path d="M367.842 304.817L339.842 109.817C369.864 107.082 387.219 106.437 420.842 109.817L391.342 304.817C382.555 322.184 376.628 321.255 367.842 304.817Z" fill="#D35E14" stroke="#D35E14"/>
+<path d="M446.412 112.822C473.271 116.662 491.893 119.703 529.928 126.325L530.604 126.442L530.284 127.05L529.842 126.817L530.283 127.051C530.283 127.051 530.282 127.054 530.281 127.055C530.279 127.059 530.276 127.064 530.273 127.071C530.265 127.085 530.254 127.107 530.239 127.135C530.209 127.193 530.164 127.279 530.105 127.391C529.986 127.617 529.81 127.951 529.581 128.387C529.122 129.261 528.449 130.543 527.59 132.177C525.872 135.444 523.413 140.12 520.448 145.753C514.519 157.018 506.565 172.113 498.471 187.426C490.377 202.738 482.142 218.27 475.65 230.412C469.165 242.538 464.401 251.316 463.262 253.088C460.97 256.653 457.712 259.067 454.529 259.067C451.263 259.067 448.386 256.547 446.859 250.949C446.467 249.511 446.169 246.271 445.938 241.776C445.705 237.256 445.537 231.406 445.42 224.701C445.186 211.289 445.154 194.441 445.217 177.94C445.279 161.438 445.436 145.281 445.576 133.249C445.647 127.233 445.713 122.248 445.762 118.767C445.786 117.027 445.806 115.662 445.82 114.733C445.827 114.268 445.832 113.912 445.836 113.673C445.838 113.553 445.839 113.462 445.84 113.401C445.84 113.371 445.841 113.348 445.841 113.333C445.841 113.325 445.842 113.319 445.842 113.315C445.842 113.313 445.842 113.311 445.842 113.31C445.845 113.31 445.882 113.31 446.342 113.317L445.842 113.309L445.851 112.742L446.412 112.822Z" fill="#D35E14" stroke="#D35C15"/>
+<path d="M311.842 251.317C314.842 240.317 313.842 112.817 313.842 112.817C281.05 117.181 262.657 120.321 229.842 126.817C229.842 126.817 291.842 246.317 296.342 253.317C300.842 260.317 308.842 262.317 311.842 251.317Z" fill="#DF6E23" stroke="#DA6D1F"/>
+<path d="M562.842 166.317L686.842 67.8171V278.317L562.842 166.317Z" fill="#D66114" stroke="#D86116"/>
+<path d="M196.342 166.317L72.3416 67.8171V278.317L196.342 166.317Z" fill="#E17125" stroke="#E27326"/>
+<path d="M752.342 465.817L625.342 432.817L737.497 377.487L752.342 465.817Z" fill="#D66015"/>
+<path d="M737.842 377.317L737.497 377.487M737.497 377.487L625.342 432.817L752.342 465.817L737.497 377.487Z" stroke="#D66115"/>
+<path d="M6.34164 464.817L134.342 432.004L21.3031 376.986L6.34164 464.817Z" fill="#E06B1F"/>
+<path d="M20.9558 376.817L21.3031 376.986M21.3031 376.986L134.342 432.004L6.34164 464.817L21.3031 376.986Z" stroke="#DF6E1E"/>
+<path d="M379.842 317.775C376.246 317.475 372.636 313.145 368.342 305.112L340.342 110.112C355.495 108.732 367.422 107.884 379.842 107.817V317.775Z" fill="#E16D22" stroke="#E27225"/>
+</svg>
diff --git a/ui/public/logos/opensquilla.png b/ui/public/logos/opensquilla.png
new file mode 100644
index 00000000..5bb6b708
Binary files /dev/null and b/ui/public/logos/opensquilla.png differ
diff --git a/ui/src/components/HarnessLogo.tsx b/ui/src/components/HarnessLogo.tsx
index 2628254e..9eca4f88 100644
--- a/ui/src/components/HarnessLogo.tsx
+++ b/ui/src/components/HarnessLogo.tsx
@@ -25,6 +25,10 @@ const LOGO: Record<string, string> = {
grok: '/logos/grok.png', // Grok's own app icon (grok.com/icon-512x512.png, scaled to 192 px)
agentzero: '/logos/agentzero.png', // Agent Zero's own mark (docs/res/favicon_round.png in the MIT agent0ai/agent-zero repository, scaled to 192 px)
systemone: '/logos/systemone.png', // the System One Harness's own mark (the project has no vendor logo; Jev is TypeSafe's model, not the harness)
+ jcode: '/logos/jcode.png', // jcode's own app icon (assets/app-icons/Jcode.icns in the MIT 1jehuang/jcode repository), the 1024 px face resized. It is a BLACK mark on transparency, so it carries no contrast on a dark surface — upstream ships no light variant
+ opensquilla: '/logos/opensquilla.png', // the OpenSquilla mark (assets/opensquilla-mark.png in the Apache-2.0 TokenRhythm/opensquilla repository), already square
+ nanobot: '/logos/nanobot.svg', // the nanobot mark (images/nanobot_mark.svg in the MIT HKUDS/nanobot repository); an SVG like cursor.svg, which this map already serves
+ mimo: '/logos/mimo.png', // Xiaomi MiMo's own square mark: the site icon of mimo.xiaomi.com (the "Xiaomi" over "MiMO" wordmark, white on black) is 32 px only, so it is drawn again at 192 px from the full-size wordmark that mimo.xiaomi.com/coder serves (coder/assets/logo.png), in the same layout (Richard, 2026-10-12)
};
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 fa2959ce..c4ca92d4 100644
--- a/ui/src/components/HarnessSettings.tsx
+++ b/ui/src/components/HarnessSettings.tsx
@@ -8,7 +8,7 @@ import { zipSync, strToU8 } from 'fflate';
import { SkelPage } from '@/components/Skel';
import { useRouter } from 'next/navigation';
import {
- OOB, oobById, oobDefaultModel, oobModels, useModelCatalog, modelAvailable, modelAvailability, availabilityNote, useBases, getCustom, saveCustom, deleteCustom, createCustom, getSkillFiles, storeMcpSecret, pluginSchemas,
+ OOB, oobById, oobDefaultModel, oobModels, useModelCatalog, modelAvailable, modelAvailability, availabilityNote, useBases, getCustom, saveCustom, deleteCustom, createCustom, getSkillFiles, storeMcpSecret, pluginSchemas, instructionFileLabel,
type CustomHarness, type OobHarness, type HarnessPlugin, getPluginFiles,
useRuntimeDefaults,
listPlugs, getHarnessPlugs, setHarnessPlugs, PLUGS_ENTRY_ID, type Plug, type HarnessPlugs,
@@ -348,7 +348,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">{(base?.id || draft?.base || '') === 'systemone' ? 'Instructions' : ['codex', 'hermes', 'omp', 'pi', 'opencode', 'kilo', 'dsh', 'qwen', 'cline', 'goose', 'kimi', 'minimax', 'aider', 'openhands', 'grok', 'agentzero'].includes(base?.id || draft?.base || '') ? 'AGENTS.md' : 'CLAUDE.md'}</label>
+ <div className="field"><label htmlFor="hsInstructions">{instructionFileLabel(base?.id || draft?.base || '')}</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 408d1233..85d4c916 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' | 'kilo' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | 'minimax' | 'aider' | 'openhands' | 'grok' | 'systemone' | 'cheetahclaws' | 'agentzero' | null; // gateway backend; null = coming soon
+ backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'kilo' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | 'minimax' | 'aider' | 'openhands' | 'grok' | 'systemone' | 'cheetahclaws' | 'agentzero' | 'mimo' | 'jcode' | 'opensquilla' | 'nanobot' | 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)
@@ -215,10 +215,57 @@ export const OOB: OobHarness[] = [
models: ['jev-latest', 'jev-preview', 'jev-1.13', 'laya', 'openthai-systemone', 'system-one-phase2'], defaultModel: 'jev-latest', moreModels: 0,
systemPrompt: 'You act inside a finite set of actions the environment offers each step. Choose the action that moves the goal forward, finish when the goal is reached, and escalate when nothing offered fits.',
tools: [], skills: [] },
+ { id: 'mimo', name: 'MiMo Code', version: 'v0.1.15', backend: 'mimo', status: 'ready',
+ // Placeholder only, like every list above: the gateway's catalog wins once fetched. MiMo Code is
+ // an opencode fork and reaches what opencode reaches, so the list is opencode's.
+ models: ['gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.3-codex', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', '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-4-maverick', '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 MiMo Code, 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: 'jcode', name: 'jcode', version: 'v0.90.0', backend: 'jcode', status: 'ready',
+ // Placeholder only. jcode speaks one OpenAI shape, chat/completions, through the relay, so the
+ // list is the other chat-completions bases' and the two Responses-only ids are not on it.
+ models: ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', '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 jcode, 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: 'opensquilla', name: 'OpenSquilla', version: 'v0.5.6', backend: 'opensquilla', status: 'ready',
+ // Placeholder only; the chat-completions list, for jcode's reason.
+ models: ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', '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 OpenSquilla, an autonomous 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: 'nanobot', name: 'nanobot', version: 'v0.3.5', backend: 'nanobot', status: 'ready',
+ // Placeholder only; the chat-completions list, for jcode's reason.
+ models: ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', '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 nanobot, an autonomous 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: [] },
];
export const oobById = (id: string) => OOB.find((o) => o.id === id) || null;
+// ── the instruction file each base actually reads ─────────────────────────────────────────────
+// The NAME of the file the runner writes for a base, which is the label the settings page puts on
+// the instructions box. It has to agree with runner/server.py's `_agent_doc_path`, and until
+// 2026-10-03 it did not: the page labelled qwen and gemini "AGENTS.md" while the runner wrote
+// QWEN.md and GEMINI.md, so a person edited a box named for a file their agent never read.
+// gateway/tests/test_instruction_file_label.py now holds this map to the runner's function, so the
+// next base that chooses its own name cannot drift the same way.
+//
+// systemone is the one base with no file at all: it reads no workspace and its instructions travel
+// in the job, so the page calls the box "Instructions".
+export const INSTRUCTION_FILE: Record<string, string> = {
+ qwen: 'QWEN.md',
+ gemini: 'GEMINI.md',
+ systemone: 'Instructions',
+};
+const AGENTS_MD_BASES = [
+ 'codex', 'hermes', 'omp', 'pi', 'opencode', 'kilo', 'dsh', 'qwen', 'cline', 'goose', 'kimi',
+ 'minimax', 'aider', 'openhands', 'grok', 'agentzero',
+ 'mimo', 'jcode', 'opensquilla', 'nanobot',
+];
+export function instructionFileLabel(baseId: string | null | undefined): string {
+ const id = baseId || '';
+ return INSTRUCTION_FILE[id] || (AGENTS_MD_BASES.includes(id) ? 'AGENTS.md' : 'CLAUDE.md');
+}
+
// ── model catalog: the GATEWAY owns it, this file does not ────────────────────────────
// The `models` / `defaultModel` fields above used to be the console's own copy of the
// gateway's _MODEL_CATALOG. Two lists meant two places to edit, and only one of them got