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.

feat(backends): Pi, the fourth harness — and MCP for it via the open-source adapter

richard-epsilla3e85f6800584
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3750564b..df908d65 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -163,7 +163,7 @@ jobs:
docker logs smoke 2>&1 | tail -30
LINE=$(docker logs smoke 2>&1 | grep "backends available" | tail -1 || true)
echo "$LINE"
- for b in claude codex hermes; do
+ for b in claude codex hermes pi; do
echo "$LINE" | grep -q "$b" || { echo "::error::$b did not install on ${{ matrix.arch }}"; exit 1; }
done
docker exec smoke ls /opt/harnessrouter/kits
diff --git a/Dockerfile b/Dockerfile
index 6b00461b..0ecef572 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -27,7 +27,7 @@
# This is the SAME console the hosted product runs. Surfaces with no self-hosted backend
# (billing, marketplace, analytics, sign-in) are hidden by the edition flag rather than removed,
# so the two stay one codebase. See ui/src/lib/edition.ts.
-FROM node:20-slim AS ui
+FROM node:22-slim AS ui
WORKDIR /ui
# git: the UI depends on the ReifyUI component library straight from its repository.
RUN apt-get update -y && apt-get install -y --no-install-recommends git ca-certificates \
@@ -84,8 +84,10 @@ RUN set -eux; \
&& rm -rf /var/lib/apt/lists/*; \
fi
-# Node is needed for the UI server and for the npm-based agent CLIs.
-RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
+# Node is needed for the UI server and for the npm-based agent CLIs. 22, not 20: pi's
+# engine floor is >=22.19, and node 20 has been end-of-life since April 2026 anyway —
+# the other CLIs (claude >=18, codex >=20) run unchanged on 22.
+RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& rm -rf /var/lib/apt/lists/* /root/.npm
diff --git a/README.md b/README.md
index 44a9980b..59d80b29 100644
--- a/README.md
+++ b/README.md
@@ -137,8 +137,9 @@ Wait for `ready on :3000`, then open the browser:
```
[harnessrouter] installing Claude Code (Anthropic's terms apply)…
[harnessrouter] installing Codex (Apache-2.0)…
+[harnessrouter] installing Pi (MIT) and its MCP adapter (MIT)…
[harnessrouter] installing Hermes (check its upstream license before use)…
-[harnessrouter] data=/data backends available: claude codex hermes
+[harnessrouter] data=/data backends available: claude codex hermes pi
[harnessrouter] ready on :3000
```
@@ -162,8 +163,9 @@ The agent CLIs are fetched on the first start rather than shipped in the image,
licensing fact rather than a packaging preference. Claude Code is distributed under Anthropic's own
terms and hermes-agent declares no license at all, so neither can be redistributed inside a public
image. Installing them on first run means you install them yourself, from upstream, under those
-terms — which is also why you should read them before you use those two backends. Codex is
-Apache-2.0 and arrives the same way, so all three land in one place.
+terms — which is also why you should read them before you use those two backends. Codex
+(Apache-2.0) and Pi (MIT, with its MIT-licensed MCP adapter) arrive the same way, so all
+four land in one place.
</details>
@@ -256,14 +258,14 @@ problem, because it only offers you providers that work.
| Connection `provider` | Backends that can use it |
|---|---|
-| `anthropic` | Claude Code, Hermes |
-| `openai` | Codex, Hermes |
-| `openrouter` | Codex, Hermes |
-| `azure-foundry` | Codex, Hermes |
+| `anthropic` | Claude Code, Hermes, Pi |
+| `openai` | Codex, Hermes, Pi |
+| `openrouter` | Codex, Hermes, Pi |
+| `azure-foundry` | Codex, Hermes, Pi |
| `bedrock` | Claude Code, Hermes |
-| `tokenrouter` | Claude Code, Codex, Hermes |
-| `vercel` | Claude Code, Codex, Hermes |
-| `llmtr` | Claude Code, Codex, Hermes |
+| `tokenrouter` | Claude Code, Codex, Hermes, Pi |
+| `vercel` | Claude Code, Codex, Hermes, Pi |
+| `llmtr` | Claude Code, Codex, Hermes, Pi |
</details>
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 22ad09d9..5f11f790 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -124,7 +124,7 @@ export HOSTNAME=0.0.0.0
TOOLS="$DATA_DIR/agent-tools"
export PATH="$TOOLS/bin:$PATH"
export NODE_PATH="$TOOLS/lib/node_modules"
-export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes}"
+export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi}"
wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }
# The executable IS the definition of "installed" — an installer that exits 0 without producing
@@ -135,6 +135,7 @@ backend_bin() {
claude) echo "$TOOLS/bin/claude" ;;
codex) echo "$TOOLS/bin/codex" ;;
hermes) echo "$TOOLS/venv/bin/hermes" ;;
+ pi) echo "$TOOLS/bin/pi" ;;
esac
}
@@ -170,6 +171,15 @@ install_backends() {
try_install "Codex" npm install -g --prefix "$TOOLS" --no-audit --no-fund @openai/codex || true
fi
+ if wanted pi && [ ! -x "$(backend_bin pi)" ]; then
+ echo "[harnessrouter] installing Pi (MIT) and its MCP adapter (MIT)…"
+ # --ignore-scripts is pi's own documented install form. The MCP adapter is a pi extension
+ # (github.com/nicobailon/pi-mcp-adapter): pi deliberately ships without MCP, and the runner
+ # mounts this adapter via -e only on turns that actually configure MCP servers.
+ try_install "Pi" npm install -g --prefix "$TOOLS" --no-audit --no-fund --ignore-scripts \
+ @earendil-works/pi-coding-agent pi-mcp-adapter || true
+ fi
+
if wanted hermes && [ ! -x "$(backend_bin hermes)" ]; then
echo "[harnessrouter] installing Hermes (check its upstream license before use)…"
try_install "Hermes" sh -c "\"$PY\" -m venv \"$TOOLS/venv\" \
@@ -185,6 +195,8 @@ install_backends() {
# for hermes aborted the whole entrypoint — exit 1, no message, the log ending on an install line
# so it read as if the install had killed it. HR_BACKENDS=claude, =codex and =claude,codex were
# all unusable, which is exactly the choice the licence note above asks people to make.
+ # Where the runner finds the MCP extension to mount (-e) on pi turns with MCP servers.
+ [ -d "$TOOLS/lib/node_modules/pi-mcp-adapter" ] && export HR_PI_MCP_EXT="$TOOLS/lib/node_modules/pi-mcp-adapter"
if wanted hermes; then verify_hermes_mcp; fi
}
diff --git a/gateway/app.py b/gateway/app.py
index 367963d2..f8429cdb 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -921,6 +921,15 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {
# while an unknown path under /v1 answers {"type":"not_found"}.
("llmtr", "claude"): "tokenrouter", ("llmtr", "codex"): "tokenrouter",
("llmtr", "hermes"): "openai-api",
+ # Pi (earendil-works pi coding agent) is multi-family like hermes: native env auth for the
+ # two vendors it speaks directly, a models.json custom provider for everything with a
+ # base_url. 'tokenrouter' on the runner again means "OpenAI/Anthropic-compatible, api picked
+ # by model family" — TokenRouter, Vercel and LLMTR all serve both shapes from one base_url.
+ ("anthropic", "pi"): "anthropic", ("openai", "pi"): "openai",
+ ("azure-foundry", "pi"): "azure",
+ ("openrouter", "pi"): "openai-api",
+ ("tokenrouter", "pi"): "tokenrouter", ("vercel", "pi"): "tokenrouter",
+ ("llmtr", "pi"): "tokenrouter",
}
@@ -4300,7 +4309,7 @@ def _map_model(conn: dict, friendly: str) -> str | None:
table = _vendor_models(provider)
if friendly and friendly in table:
return table[friendly]
- if backend == "claude" or (backend == "hermes" and provider in ("anthropic", "bedrock")):
+ if backend == "claude" or (backend in ("hermes", "pi") and provider in ("anthropic", "bedrock")):
# Older claude ids the catalog no longer lists still map, and a caller may pass a
# provider-native id directly; _LEGACY_CLAUDE_IDS carries both, keyed bare (opus-4.5).
legacy = _BEDROCK_CLAUDE if provider == "bedrock" else _ANTHROPIC_CLAUDE
@@ -4382,8 +4391,18 @@ _MODEL_CATALOG: dict[str, dict] = {
"mistral-medium-3.5", "step-3.7-flash", "minimax-m3",
"nemotron-3-ultra", "hunyuan-3", "ling-3.0-flash",
"qwen3.7-flash"]},
+ # pi (earendil-works pi coding agent) is multi-family the same way hermes is: the CLI's
+ # unified LLM layer runs either family natively and anything OpenAI/Anthropic-compatible
+ # through a custom provider. The list starts as the gpt + claude catalogs — the two families
+ # whose serving paths the e2e verified — and grows the same way hermes's did: a model is
+ # added when a real pi turn on the live provider has been checked for substitution.
+ "pi": {"default": "gpt-5.4",
+ "models": ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5",
+ "gpt-5.4", "gpt-5.4-mini", "gpt-5.2", "gpt-5.3-codex",
+ "claude-opus-5", "claude-fable-5", "claude-opus-4.8", "claude-sonnet-5",
+ "claude-opus-4.7", "claude-sonnet-4.6", "claude-haiku-4.5"]},
}
-_BARE_MODELS = {"", "claude", "codex", "anthropic", "bedrock", "openai", "hermes"}
+_BARE_MODELS = {"", "claude", "codex", "anthropic", "bedrock", "openai", "hermes", "pi"}
# Union of BOTH tables' values — a dict merge would drop the bedrock ids (shared keys, anthropic
# values win), silently rejecting the us.anthropic.* ids this set exists to allow.
_PROVIDER_CLAUDE_IDS = {v.lower() for v in [*_BEDROCK_CLAUDE.values(), *_ANTHROPIC_CLAUDE.values()]}
@@ -4418,6 +4437,8 @@ def _backend_of_harness(hv: dict | None) -> str:
return "claude"
if base == "hermes":
return "hermes"
+ if base == "pi":
+ return "pi"
return ""
@@ -4427,9 +4448,9 @@ def _model_authorized(requested: str, backend: str) -> bool:
return False
if r in {m.lower() for m in _MODEL_CATALOG.get(backend, {}).get("models", [])}:
return True
- if backend in ("claude", "hermes") and r in _PROVIDER_CLAUDE_IDS:
+ if backend in ("claude", "hermes", "pi") and r in _PROVIDER_CLAUDE_IDS:
return True # power users may pass a provider-native claude id (claude-opus-4-8 / us.anthropic...)
- if backend in ("codex", "hermes") and r.startswith("gpt-"):
+ if backend in ("codex", "hermes", "pi") and r.startswith("gpt-"):
return True # gpt-* family; Azure deployment names vary
return False
@@ -5312,7 +5333,7 @@ async def create_response(body: CreateResponseBody, request: Request):
# explicitly selected — that's not a valid provider id. Treat it as "unset" and inherit, in order:
# previous round's model -> the harness default_model -> connection default (in _map_model).
# This keeps a conversation on the user's chosen model and never ships the bare backend to Bedrock.
- _BARE = {"claude", "codex", "anthropic", "bedrock", "openai", "hermes", ""}
+ _BARE = {"claude", "codex", "anthropic", "bedrock", "openai", "hermes", "pi", ""}
if model_req.lower() in _BARE:
inherited = ""
if body.previous_response_id:
@@ -10811,6 +10832,17 @@ _BASE_CATALOG: dict[str, dict] = {
("WebSearch", "WebSearch"), ("Task", "Task (subagents)")],
"tool_enforcement": "hard",
},
+ "pi": {
+ "label": "Pi", "backend": "pi", "status": "ready",
+ "system_prompt": ("You are Pi, a minimal autonomous coding agent. You operate on a real "
+ "git workspace, reading, writing and editing files and running bash "
+ "to complete the task end to end."),
+ # Pi's four built-in tools, by their real names — -xt enforces these hard, so a disabled
+ # tool is genuinely absent, not merely requested (see _build_pi in the runner).
+ "tools": [("bash", "Bash"), ("read", "File Read"), ("write", "File Write"),
+ ("edit", "Edit")],
+ "tool_enforcement": "hard",
+ },
"hermes": {
"label": "Hermes", "backend": "hermes", "status": "ready",
"system_prompt": ("You are Hermes, a self-improving autonomous agent. You work on a real "
diff --git a/runner/server.py b/runner/server.py
index 3a8ce24c..f520d3d3 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -9,7 +9,7 @@ into the session; see docs/technical/HARNESS_AS_A_SERVICE_DESIGN.md S0.5).
A turn runs ONE backend CLI one-shot over /workspace and normalizes its events into a
single canonical schema (Claude Code `stream-json`) so everything downstream is uniform.
-Backends + providers (registry-driven; adding Pi = a new BACKENDS entry):
+Backends + providers (registry-driven — pi was added as exactly that one entry):
backend "claude" (Claude Code CLI), providers:
- anthropic : ANTHROPIC_API_KEY (+ optional ANTHROPIC_BASE_URL)
- bedrock : CLAUDE_CODE_USE_BEDROCK=1 + AWS creds/bearer + region
@@ -24,6 +24,13 @@ Backends + providers (registry-driven; adding Pi = a new BACKENDS entry):
- azure-foundry : AZURE_FOUNDRY_API_KEY + AZURE_FOUNDRY_BASE_URL (gpt family)
- bedrock : AWS_BEARER_TOKEN_BEDROCK (or key pair) + AWS_REGION (claude family)
- anthropic : ANTHROPIC_API_KEY (+ optional ANTHROPIC_BASE_URL)
+ backend "pi" (earendil-works pi coding agent; `pi -p --mode json` event stream,
+ multi-family like hermes — custom providers via ~/.pi/agent/models.json):
+ - anthropic : ANTHROPIC_API_KEY (native), base_url via models.json when set
+ - openai : OPENAI_API_KEY (native), base_url via models.json when set
+ - azure : models.json openai-responses + base_url
+ - openai-api : models.json openai-completions + base_url (generic aggregator)
+ - tokenrouter : models.json, api by model family (claude -> anthropic-messages)
Creds are injected per-session via env (pool secrets) or a body `auth` override for spikes.
Phase 0b: buffered turn. SSE streaming, git hydrate/commit, mid-turn /input, and the Node
@@ -153,6 +160,10 @@ CHECKPOINT_EXCLUDE = ["./tmp", "./.gcp-sa.json", "./.codex", "./.credentials.jso
# hermes state (state.db conversations) IS checkpointed; its cred files are not.
"./.harness/home/.hermes/.env",
"./.harness/home/.hermes/auth.json",
+ # pi stores provider keys in auth.json, and models.json carries the literal
+ # key for custom providers — neither may travel in a checkpoint tarball.
+ "./.harness/home/.pi/agent/auth.json",
+ "./.harness/home/.pi/agent/models.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.
@@ -164,6 +175,8 @@ CLAUDE_DEFAULT_MODEL = os.environ.get("CLAUDE_DEFAULT_MODEL", "claude-sonnet-4.6
CODEX_DEFAULT_MODEL = os.environ.get("CODEX_DEFAULT_MODEL", "gpt-5.4")
# Hermes default (the gateway maps friendly names to provider ids before the /turn call).
HERMES_DEFAULT_MODEL = os.environ.get("HERMES_DEFAULT_MODEL", "gpt-5.4")
+# Pi default — pi is multi-family the same way hermes is; same reasoning, same default.
+PI_DEFAULT_MODEL = os.environ.get("PI_DEFAULT_MODEL", "gpt-5.4")
CODEX_REASONING_EFFORT = os.environ.get("CODEX_REASONING_EFFORT", "medium")
CODEX_CONTEXT_WINDOW = os.environ.get("CODEX_CONTEXT_WINDOW", "400000")
# Provider defaults (overridable per-turn via auth.base_url). Wired from pool env.
@@ -241,6 +254,7 @@ def _git_ensure(ws: str) -> None:
"# harness: never persist secrets/scratch in the session checkpoint",
"tmp/", ".gcp-sa.json", ".codex/", ".credentials.json", ".harness/**/.credentials.json",
".harness/home/.hermes/.env", ".harness/home/.hermes/auth.json",
+ ".harness/home/.pi/agent/auth.json", ".harness/home/.pi/agent/models.json",
"",
]))
if not (p / ".git").exists():
@@ -251,7 +265,7 @@ def _git_ensure(ws: str) -> None:
# ── input/output file plumbing (OpenAI Responses input_file blocks + container files) ──
# Paths never reported as agent-produced output (internal state / scratch / secrets / vcs).
-_PRODUCED_EXCLUDE_PREFIX = (".harness/", "tmp/", ".codex/", ".git/", ".claude/",
+_PRODUCED_EXCLUDE_PREFIX = (".harness/", "tmp/", ".codex/", ".git/", ".claude/", ".pi/",
"node_modules/", ".venv/", "venv/", "__pycache__/", ".cache/", ".next/")
_PRODUCED_EXCLUDE_NAMES = {".gitignore", ".gcp-sa.json", ".credentials.json"}
# Dependency / install / build-cache noise the agent pulls in (apt debs, npm/py deps, byte-compiled
@@ -394,11 +408,18 @@ def _write_skills(cwd: str, skills: list[dict], backend: str = "claude") -> list
<cwd>/.harness/home/.claude (see _build_claude). ALSO mirrored to the project
`.claude/skills/<name>/` so direct reads and project-scoped discovery both work.
- codex: .harness/skills/<name>/ (surfaced via AGENTS.md; .harness/ stays out of outputs)
+ - pi: .harness/home/.pi/agent/skills/<name>/ — pi's USER-GLOBAL skills dir under the
+ redirected $HOME. User-global on purpose: pi gates project-local files behind its trust
+ decision, and user-global skills load unconditionally (agentskills.io format, which is
+ the same SKILL.md this product already stores).
Each skill: {name, files:[{path, content}]} (or {content} -> SKILL.md).
Returns [{name, desc, entry}] for the skills actually installed (entry = SKILL.md path)."""
if backend == "claude":
rootrels = [".harness/home/.claude/skills", ".claude/skills"]
entryroot = ".claude/skills"
+ elif backend == "pi":
+ rootrels = [".harness/home/.pi/agent/skills"]
+ entryroot = ".harness/home/.pi/agent/skills"
else:
rootrels = [".harness/skills"]
entryroot = ".harness/skills"
@@ -443,9 +464,10 @@ _AGENTS_END = "<!-- harness-skills:end -->"
def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:
- """The agent's instruction file: AGENTS.md for Codex and Hermes (both read AGENTS.md from the
- cwd), CLAUDE.md for Claude Code — each CLI reads its own file as project instructions."""
- return pathlib.Path(cwd) / ("AGENTS.md" if backend in ("codex", "hermes") else "CLAUDE.md")
+ """The agent's instruction file: AGENTS.md for Codex, Hermes and Pi (all three read AGENTS.md
+ from the cwd — pi loads it as a context file, before its project-trust gate), CLAUDE.md for
+ Claude Code — each CLI reads its own file as project instructions."""
+ return pathlib.Path(cwd) / ("AGENTS.md" if backend in ("codex", "hermes", "pi") else "CLAUDE.md")
def _write_agent_doc(cwd: str, backend: str, agent_doc: str | None, skills_meta: list[dict]) -> None:
@@ -1058,6 +1080,220 @@ def _build_codex(provider: str, auth: Auth, model: str, prompt: str, cwd: str,
return ["codex", "exec", *common, "--cd", cwd, prompt]
+# ── pi (earendil-works pi coding agent) ─────────────────────────────────────────
+# One-shot turns run `pi -p --mode json`: a JSONL event stream on stdout (session header,
+# message deltas, tool executions, agent_end). Sessions are JSONL trees under
+# $HOME/.pi/agent/sessions/<cwd-slug>/ — inside the checkpointed workspace, so `--session-id`
+# resumes across sandbox recycling. `--session-id` CREATES the session when the file is missing,
+# which is exactly the fallback the claude/codex paths need explicit existence checks for.
+#
+# The CLI exits 0 even when the provider call fails (verified against 0.84.2 with a bad key:
+# the failure is stopReason="error" + errorMessage ON THE MESSAGE, not an error event, not a
+# nonzero exit). Status therefore comes from the event stream — never from the exit code.
+PI_PROVIDERS = {"anthropic", "openai", "azure", "openai-api", "tokenrouter"}
+
+# api field for models.json, by how the endpoint actually speaks. openai-responses vs
+# openai-completions matters for the same reason it does on hermes: the gpt-5 line refuses
+# tool-carrying requests on /v1/chat/completions (see _HERMES_RESPONSES_API_MODEL).
+_PI_CLAUDE_MODEL = re.compile(r"(?:^|/)(?:us\.anthropic\.)?claude", re.I)
+
+
+def _pi_models_json(api: str, base_url: str, api_key: str, model: str) -> str:
+ """A one-provider ~/.pi/agent/models.json ("hr") for a custom endpoint. Pi's anthropic client
+ appends /v1/messages to baseUrl while its openai clients expect the /v1 to already be there
+ (both read straight off pi's own docs/models.md examples), so the /v1 suffix is normalized
+ per api instead of trusting how the integration happened to store the URL."""
+ base = (base_url or "").rstrip("/")
+ if api == "anthropic-messages":
+ base = base.removesuffix("/v1")
+ elif not base.endswith("/v1"):
+ base += "/v1"
+ return json.dumps({"providers": {"hr": {
+ "baseUrl": base, "api": api, "apiKey": api_key,
+ "models": [{"id": model, "name": model, "reasoning": False,
+ "input": ["text", "image"],
+ "contextWindow": 200000, "maxTokens": 32000}],
+ }}}, indent=2)
+
+
+def _pi_write_mcp(home: pathlib.Path, servers: list[dict] | None) -> bool:
+ """Write $HOME/.pi/agent/mcp.json for pi-mcp-adapter (same input contract as the claude/codex
+ writers: url + optional auth/headers). Returns whether any server was written. The agent-dir
+ location is deliberate: project-local .pi/mcp.json sits behind pi's trust gate; the agent dir
+ does not."""
+ entries: dict = {}
+ for s in servers or []:
+ url = (s or {}).get("url")
+ if not url:
+ continue
+ name = _mcp_name((s or {}).get("name") or (s or {}).get("id") or "mcp")
+ entry: dict = {"url": url}
+ auth = (s or {}).get("auth")
+ if auth:
+ hdr = auth if str(auth).lower().startswith("bearer ") else f"Bearer {auth}"
+ entry["headers"] = {"Authorization": hdr}
+ if isinstance((s or {}).get("headers"), dict):
+ entry.setdefault("headers", {}).update({str(k): str(v) for k, v in s["headers"].items()
+ if k and v is not None})
+ entries[name] = entry
+ if not entries:
+ return False
+ path = home / ".pi" / "agent" / "mcp.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({"mcpServers": entries}, indent=2))
+ return True
+
+
+def _build_pi(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 "anthropic"
+ if pr not in PI_PROVIDERS:
+ raise HTTPException(400, f"unknown pi provider '{pr}' (one of {sorted(PI_PROVIDERS)})")
+ home = pathlib.Path(env.get("HOME") or cwd)
+ (home / ".pi" / "agent").mkdir(parents=True, exist_ok=True)
+
+ # Provider: native env for the two vendors pi speaks natively WITHOUT a base_url override;
+ # everything else (and any base_url override) goes through a models.json custom provider,
+ # because that is the only place pi accepts an endpoint from.
+ 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"pi provider '{pr}' needs a base_url (none configured)")
+ if 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"
+ (home / ".pi" / "agent" / "models.json").write_text(
+ _pi_models_json(api, auth.base_url, auth.api_key or "", model))
+ 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
+
+ cmd = ["pi", "-p", "--mode", "json", "--provider", pname, "--model", model,
+ # The sandbox is the trust boundary (one Hyper-V-isolated box per session), so
+ # project-local files are trusted the same way claude gets
+ # --dangerously-skip-permissions: explicitly, because nobody is there to answer.
+ "--approve",
+ # Discovery off, mounts explicit: a task could drop .pi/extensions/ into the
+ # workspace and have the next turn execute it. -e paths still load.
+ "--no-extensions"]
+ if resume_session_id:
+ # --session-id resumes the project session when its file is in the (re)hydrated
+ # workspace and CREATES it when not — the fresh-start fallback the other backends
+ # implement by hand is pi's documented behavior, so no existence check here.
+ cmd += ["--session-id", resume_session_id]
+ if tools_disabled:
+ # Pi has a real per-tool switch (-xt) — enforcement, not instruction. Names are pi's
+ # own (bash/read/write/edit); catalog labels arrive as "bash (Shell)"-style, keep the id.
+ names = ",".join(sorted({x.split(" (")[0].strip() for x in tools_disabled if x and x.strip()}))
+ if names:
+ cmd += ["--exclude-tools", names]
+ if _pi_write_mcp(home, mcp_servers):
+ ext = os.environ.get("HR_PI_MCP_EXT", "")
+ if ext and os.path.exists(ext):
+ cmd += ["--extension", ext]
+ else:
+ # Servers were configured but the adapter isn't installed: say so in the stream
+ # (errbuf tail) instead of silently running a turn with no tools.
+ print("[pi] MCP servers configured but pi-mcp-adapter not installed "
+ "(HR_PI_MCP_EXT unset or missing) — this turn runs without them", flush=True)
+ cmd.append(prompt)
+ return cmd
+
+
+def _pi_usage_add(state: dict, u: dict | None) -> None:
+ """Accumulate pi per-message usage {input, output, cacheRead, cacheWrite} into the turn total.
+ Pi already reports input as fresh-only (cacheRead separate), matching the canonical contract."""
+ if not isinstance(u, dict):
+ return
+ tot = state.setdefault("_pi_usage", {"input_tokens": 0, "output_tokens": 0,
+ "cache_read_tokens": 0, "cache_write_tokens": 0})
+ for src, dst in (("input", "input_tokens"), ("output", "output_tokens"),
+ ("cacheRead", "cache_read_tokens"), ("cacheWrite", "cache_write_tokens")):
+ v = u.get(src)
+ if isinstance(v, (int, float)):
+ tot[dst] += int(v)
+
+
+def _pi_to_claude(obj: dict, state: dict) -> list[dict]:
+ """Map ONE pi `--mode json` event to zero+ canonical claude stream-json events.
+
+ Text streams from message_update deltas; message_end re-emits only the un-streamed tail
+ (the same self-healing contract as _codex_text_delta: if deltas never arrive, the tail is
+ the whole text). Failure is stopReason=="error" on the assistant message — the CLI exits 0
+ on provider errors, so the result event synthesized at agent_end is the ONLY truthful
+ status signal."""
+ t = obj.get("type")
+ if t == "session":
+ return [{"type": "system", "subtype": "init",
+ "session_id": obj.get("id"), "model": state.get("model")}]
+ if t == "message_update":
+ ev = obj.get("assistantMessageEvent") or {}
+ et = ev.get("type")
+ if et == "text_delta" and ev.get("delta"):
+ state["_pi_text"] = state.get("_pi_text", "") + ev["delta"]
+ state["final"] = state["_pi_text"] # the CURRENT message is the candidate final text
+ return [{"type": "assistant", "message": {"content": [{"type": "text", "text": ev["delta"]}]}}]
+ if et == "thinking_delta" and ev.get("delta"):
+ return [{"type": "assistant", "message": {"content": [{"type": "thinking", "thinking": ev["delta"]}]}}]
+ return []
+ if t == "message_end":
+ msg = obj.get("message") or {}
+ if msg.get("role") != "assistant":
+ return []
+ _pi_usage_add(state, msg.get("usage"))
+ if msg.get("stopReason") == "error":
+ state["_pi_error"] = str(msg.get("errorMessage") or "pi provider error")
+ return []
+ full = "".join(c.get("text") or "" for c in (msg.get("content") or [])
+ if isinstance(c, dict) and c.get("type") == "text")
+ streamed = state.get("_pi_text", "")
+ state["_pi_text"] = ""
+ # `final` is the LAST assistant message's text (claude result semantics), so message_end
+ # REPLACES it — a mid-run "let me look" followed by the answer must not concatenate.
+ if full:
+ state["final"] = full
+ if full and full != streamed:
+ # self-healing tail: with no deltas the tail is the whole text; a non-prefix
+ # revision re-emits in full (duplicate beats missing)
+ tail = full[len(streamed):] if streamed and full.startswith(streamed) else full
+ return [{"type": "assistant", "message": {"content": [{"type": "text", "text": tail}]}}]
+ return []
+ if t == "tool_execution_start":
+ return [{"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": obj.get("toolCallId") or "tool",
+ "name": obj.get("toolName") or "tool", "input": obj.get("args") or {}}]}}]
+ if t == "tool_execution_end":
+ res = obj.get("result")
+ if isinstance(res, dict):
+ # pi ToolResult: {content:[{type:text,...}], details?} — flatten the text blocks
+ parts = [c.get("text") or "" for c in (res.get("content") or [])
+ if isinstance(c, dict) and c.get("type") == "text"]
+ content = "\n".join(x for x in parts if x) or json.dumps(res, default=str)[:4000]
+ else:
+ content = str(res or "")
+ return [{"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": obj.get("toolCallId") or "tool",
+ "is_error": bool(obj.get("isError")), "content": content}]}}]
+ if t == "agent_end":
+ err = state.get("_pi_error")
+ usage = dict(state.get("_pi_usage") or {})
+ usage = {k: v for k, v in usage.items() if v}
+ if err:
+ return [{"type": "result", "subtype": "error", "is_error": True,
+ "result": err, "usage": usage}]
+ return [{"type": "result", "subtype": "success", "is_error": False,
+ "result": state.get("final", ""), "usage": usage}]
+ return []
+
+
# ── 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
@@ -1201,6 +1437,8 @@ BACKENDS = {
"normalize": _codex_to_claude},
"hermes": {"providers": sorted(HERMES_PROVIDERS), "default_model": HERMES_DEFAULT_MODEL,
"normalize": None},
+ "pi": {"providers": sorted(PI_PROVIDERS), "default_model": PI_DEFAULT_MODEL,
+ "normalize": _pi_to_claude},
}
@@ -1969,7 +2207,7 @@ def capabilities(identifier: str = "") -> dict:
class TurnReq(BaseModel):
- backend: str = "claude" # claude | codex | hermes (pi future)
+ backend: str = "claude" # claude | codex | hermes | pi
provider: str | None = None # see BACKENDS[...].providers
model: str | None = None
prompt: str
@@ -2082,6 +2320,11 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
hermes_provider = (req.provider or "bedrock").lower()
hermes_mcp = _hermes_prepare_env(hermes_provider, auth, cwd, env, model=model,
max_turns=req.max_turns, mcp_servers=req.mcp_servers)
+ elif backend == "pi":
+ model = model or PI_DEFAULT_MODEL
+ cmd = _build_pi(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)
else:
mcp_config = _write_mcp_config_claude(cwd, req.mcp_servers)
cmd = _build_claude(req.provider, auth, model, req.prompt, req.max_turns, cwd, env,
diff --git a/runner/tests/test_pi_normalize.py b/runner/tests/test_pi_normalize.py
new file mode 100644
index 00000000..904e44e6
--- /dev/null
+++ b/runner/tests/test_pi_normalize.py
@@ -0,0 +1,210 @@
+"""The pi normalizer, against the CLI's real behavior.
+
+The error-path fixture below is a VERBATIM capture of `pi -p --mode json` (0.84.2) with an
+invalid Anthropic key. The load-bearing fact it encodes: the process exited 0 — failure is
+stopReason="error" on the assistant message, so the synthesized result event is the only place
+status can truthfully come from.
+"""
+import json
+import pathlib
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+from server import _build_pi, _pi_models_json, _pi_to_claude, Auth # noqa: E402
+
+
+def _run(events, model="claude-sonnet-4-6"):
+ state = {"model": model, "final": ""}
+ out = []
+ for ev in events:
+ out.append(_pi_to_claude(ev, state))
+ return out, state
+
+
+def _flat(chunks):
+ return [e for evs in chunks for e in evs]
+
+
+# ── error path: the verbatim bad-key capture ─────────────────────────────────────────
+_ERR_MSG = {"role": "assistant", "content": [], "api": "anthropic-messages",
+ "provider": "anthropic", "model": "claude-haiku-4-5",
+ "usage": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
+ "stopReason": "error",
+ "errorMessage": '401 {"type":"error","error":{"type":"authentication_error",'
+ '"message":"API key is invalid."},"request_id":null}'}
+ERROR_STREAM = [
+ {"type": "session", "version": 3, "id": "11111111-2222-3333-4444-555555555555",
+ "timestamp": "2026-08-20T04:00:19.261Z", "cwd": "/ws"},
+ {"type": "agent_start"},
+ {"type": "turn_start"},
+ {"type": "message_start", "message": {"role": "user", "content": [{"type": "text", "text": "say hi"}]}},
+ {"type": "message_end", "message": {"role": "user", "content": [{"type": "text", "text": "say hi"}]}},
+ {"type": "message_start", "message": _ERR_MSG},
+ {"type": "message_end", "message": _ERR_MSG},
+ {"type": "turn_end", "message": _ERR_MSG, "toolResults": []},
+ {"type": "agent_end", "messages": [_ERR_MSG], "willRetry": False},
+ {"type": "agent_settled"},
+]
+
+
+def test_error_run_yields_error_result_despite_exit_zero():
+ chunks, _ = _run(ERROR_STREAM)
+ evs = _flat(chunks)
+ results = [e for e in evs if e.get("type") == "result"]
+ assert len(results) == 1
+ assert results[0]["is_error"] is True
+ assert "authentication_error" in results[0]["result"]
+
+
+def test_session_header_becomes_init_with_session_id():
+ chunks, _ = _run(ERROR_STREAM)
+ init = _flat(chunks)[0]
+ assert init["type"] == "system" and init["subtype"] == "init"
+ assert init["session_id"] == "11111111-2222-3333-4444-555555555555"
+
+
+def test_user_message_echo_is_not_reemitted():
+ chunks, _ = _run(ERROR_STREAM)
+ texts = [e for e in _flat(chunks) if e.get("type") == "assistant"]
+ assert texts == [] # the prompt echo must not come back as assistant output
+
+
+# ── happy path: deltas, tools, usage ─────────────────────────────────────────────────
+def _ok_msg(text, usage):
+ return {"role": "assistant", "content": [{"type": "text", "text": text}],
+ "usage": usage, "stopReason": "stop"}
+
+
+HAPPY = [
+ {"type": "session", "version": 3, "id": "s1", "cwd": "/ws"},
+ {"type": "agent_start"}, {"type": "turn_start"},
+ {"type": "message_start", "message": {"role": "assistant", "content": []}},
+ {"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "contentIndex": 0, "delta": "Check"}},
+ {"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "contentIndex": 0, "delta": "ing."}},
+ {"type": "message_end", "message": _ok_msg("Checking.", {"input": 10, "output": 2, "cacheRead": 5, "cacheWrite": 0})},
+ {"type": "tool_execution_start", "toolCallId": "t1", "toolName": "bash", "args": {"command": "ls"}},
+ {"type": "tool_execution_end", "toolCallId": "t1", "toolName": "bash",
+ "result": {"content": [{"type": "text", "text": "file.txt"}]}, "isError": False},
+ {"type": "turn_end"}, {"type": "turn_start"},
+ {"type": "message_start", "message": {"role": "assistant", "content": []}},
+ {"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "contentIndex": 0, "delta": "Done"}},
+ {"type": "message_end", "message": _ok_msg("Done. One file.", {"input": 20, "output": 4, "cacheRead": 0, "cacheWrite": 3})},
+ {"type": "turn_end"},
+ {"type": "agent_end", "messages": []},
+ {"type": "agent_settled"},
+]
+
+
+def test_happy_path_streams_deltas_then_only_the_tail():
+ chunks, state = _run(HAPPY)
+ texts = [c["text"] for e in _flat(chunks) if e.get("type") == "assistant"
+ for c in e["message"]["content"] if c.get("type") == "text"]
+ # deltas stream as they arrive; message_end adds only what was never streamed
+ assert texts == ["Check", "ing.", "Done", ". One file."]
+
+
+def test_final_is_last_message_not_a_concatenation():
+ _, state = _run(HAPPY)
+ assert state["final"] == "Done. One file."
+
+
+def test_tool_events_map_to_tool_use_and_tool_result():
+ chunks, _ = _run(HAPPY)
+ evs = _flat(chunks)
+ use = next(c for e in evs if e.get("type") == "assistant"
+ for c in e["message"]["content"] if c.get("type") == "tool_use")
+ assert use["name"] == "bash" and use["input"] == {"command": "ls"}
+ res = next(c for e in evs if e.get("type") == "user"
+ for c in e["message"]["content"] if c.get("type") == "tool_result")
+ assert res["tool_use_id"] == "t1" and res["content"] == "file.txt" and res["is_error"] is False
+
+
+def test_usage_sums_across_messages():
+ chunks, _ = _run(HAPPY)
+ result = next(e for e in _flat(chunks) if e.get("type") == "result")
+ assert result["subtype"] == "success"
+ assert result["usage"] == {"input_tokens": 30, "output_tokens": 6,
+ "cache_read_tokens": 5, "cache_write_tokens": 3}
+ assert result["result"] == "Done. One file."
+
+
+def test_no_deltas_still_emits_full_text():
+ stream = [
+ {"type": "session", "id": "s2", "cwd": "/ws"},
+ {"type": "message_end", "message": _ok_msg("Plain answer.", {"input": 1, "output": 1})},
+ {"type": "agent_end"},
+ ]
+ chunks, state = _run(stream)
+ texts = [c["text"] for e in _flat(chunks) if e.get("type") == "assistant"
+ for c in e["message"]["content"] if c.get("type") == "text"]
+ assert texts == ["Plain answer."]
+ assert state["final"] == "Plain answer."
+
+
+# ── builder ──────────────────────────────────────────────────────────────────────────
+def _cmdline(tmp_path, provider="anthropic", base_url=None, model="claude-sonnet-4-6", **kw):
+ env = {"HOME": str(tmp_path / "home")}
+ auth = Auth(api_key="k-test", base_url=base_url)
+ return _build_pi(provider, auth, model, "do it", str(tmp_path), env,
+ **kw), env
+
+
+def test_build_native_anthropic_sets_env_not_models_json(tmp_path):
+ cmd, env = _cmdline(tmp_path)
+ assert env["ANTHROPIC_API_KEY"] == "k-test"
+ assert "--provider" in cmd and cmd[cmd.index("--provider") + 1] == "anthropic"
+ assert not (tmp_path / "home" / ".pi" / "agent" / "models.json").exists()
+ assert "--approve" in cmd and "--no-extensions" in cmd
+ assert cmd[-1] == "do it"
+
+
+def test_build_tokenrouter_claude_family_uses_anthropic_messages(tmp_path):
+ _cmdline(tmp_path, provider="tokenrouter", base_url="https://tr.example/v1")
+ mj = json.loads((tmp_path / "home" / ".pi" / "agent" / "models.json").read_text())
+ hr = mj["providers"]["hr"]
+ assert hr["api"] == "anthropic-messages"
+ assert hr["baseUrl"] == "https://tr.example" # /v1 stripped: pi appends /v1/messages itself
+ assert hr["apiKey"] == "k-test"
+
+
+def test_build_tokenrouter_gpt5_uses_openai_responses(tmp_path):
+ cmd, _ = _cmdline(tmp_path, provider="tokenrouter", base_url="https://tr.example",
+ model="gpt-5.4-mini")
+ mj = json.loads((tmp_path / "home" / ".pi" / "agent" / "models.json").read_text())
+ assert mj["providers"]["hr"]["api"] == "openai-responses"
+ assert mj["providers"]["hr"]["baseUrl"] == "https://tr.example/v1"
+ assert cmd[cmd.index("--provider") + 1] == "hr"
+
+
+def test_build_openai_api_other_family_uses_completions(tmp_path):
+ _cmdline(tmp_path, provider="openai-api", base_url="https://agg.example/v1",
+ model="deepseek-v4-pro")
+ mj = json.loads((tmp_path / "home" / ".pi" / "agent" / "models.json").read_text())
+ assert mj["providers"]["hr"]["api"] == "openai-completions"
+
+
+def test_build_resume_and_disabled_tools(tmp_path):
+ cmd, _ = _cmdline(tmp_path, resume_session_id="abc-123",
+ tools_disabled=["bash (Shell)", "write"])
+ assert cmd[cmd.index("--session-id") + 1] == "abc-123"
+ assert cmd[cmd.index("--exclude-tools") + 1] == "bash,write"
+
+
+def test_build_mcp_writes_config_and_flags_extension(tmp_path, monkeypatch):
+ ext = tmp_path / "adapter"; ext.mkdir()
+ monkeypatch.setenv("HR_PI_MCP_EXT", str(ext))
+ cmd, _ = _cmdline(tmp_path, mcp_servers=[
+ {"name": "wiki", "url": "https://mcp.example/mcp", "auth": "tok123",
+ "headers": {"X-Org": "o1"}}])
+ mcp = json.loads((tmp_path / "home" / ".pi" / "agent" / "mcp.json").read_text())
+ assert mcp["mcpServers"]["wiki"]["url"] == "https://mcp.example/mcp"
+ assert mcp["mcpServers"]["wiki"]["headers"]["Authorization"] == "Bearer tok123"
+ assert mcp["mcpServers"]["wiki"]["headers"]["X-Org"] == "o1"
+ assert cmd[cmd.index("--extension") + 1] == str(ext)
+
+
+def test_models_json_v1_normalization():
+ a = json.loads(_pi_models_json("anthropic-messages", "https://x.example/v1/", "k", "m"))
+ assert a["providers"]["hr"]["baseUrl"] == "https://x.example"
+ b = json.loads(_pi_models_json("openai-completions", "https://x.example", "k", "m"))
+ assert b["providers"]["hr"]["baseUrl"] == "https://x.example/v1"
diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.ts
index d212960c..2e515720 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' | null; // gateway backend; null = coming soon
+ backend: 'claude' | 'codex' | 'hermes' | 'pi' | 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)
@@ -61,9 +61,11 @@ export const OOB: OobHarness[] = [
models: ['claude-opus-5', 'claude-fable-5', 'claude-opus-4.8', 'claude-sonnet-5', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5'], defaultModel: 'claude-opus-4.8', moreModels: 0,
systemPrompt: 'You are Claude Code, an agentic coding assistant. You work on a real local git working tree with bash, edit files, run tests, and use sub-agents to complete engineering tasks end to end.',
tools: [], skills: [] },
- { id: 'pi', name: 'Pi', version: 'v1.0.1', backend: null, status: 'soon',
- models: [], moreModels: 0,
- systemPrompt: 'Pi harness, coming soon.', tools: [], skills: [] },
+ { id: 'pi', name: 'Pi', version: 'v0.84.2', backend: 'pi', status: 'ready',
+ // Multi-family like Hermes: the gpt + claude catalogs (placeholder until /v1/models lands).
+ models: ['gpt-5.4', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4-mini', 'gpt-5.2', 'claude-opus-5', 'claude-fable-5', 'claude-opus-4.8', 'claude-sonnet-5', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5'], defaultModel: 'gpt-5.4', moreModels: 0,
+ systemPrompt: 'You are Pi, a minimal autonomous coding agent. You operate on a real git workspace, reading, writing and editing files and running bash to complete the task end to end.',
+ tools: [], skills: [] },
{ id: 'hermes', name: 'Hermes', version: 'v0.19.0', backend: 'hermes', status: 'ready',
// Multi-family: Hermes runs any frontier model, the gpt + claude catalogs, default gpt-5.5.
models: ['gpt-5.5', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-opus-5', 'claude-fable-5', 'claude-opus-4.8', 'claude-sonnet-5', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5', 'gemini-3.6-flash', 'deepseek-v4-pro', 'kimi-k3', 'glm-5.2', 'qwen3.7-max'], defaultModel: 'gpt-5.5', moreModels: 0,