HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
"""Cloud upload: a local harness pushed to a hosted workspace, one way, upsert on its own id.
The hosted side is a mock at the HTTP boundary, which pins the contract this feature depends on:
GET /v1/me resolves a key to org + workspace, PUT /v1/harnesses/{id} creates or replaces."""
import asyncio
import json
import re
import sys
from pathlib import Path
import httpx
import pytest
from fastapi.testclient import TestClient
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import app as gw # noqa: E402 (environment: conftest.py)
ORG = "local"
CLOUD = "https://cloud.test"
class Cloud:
"""What the hosted gateway does, as far as this feature can see."""
def __init__(self):
self.keys = {"sk-hr-good": {"org": "org_e", "org_name": "Example Co", "workspace": "ws_r", "workspace_name": "Research", "member": "owner"},
"sk-hr-nows": {"org": "org_e", "org_name": "Example Co", "workspace": "", "workspace_name": "", "member": "owner"}}
self.harnesses: dict[str, dict] = {}
self.calls: list[tuple[str, str]] = []
def handle(self, req: httpx.Request) -> httpx.Response:
self.calls.append((req.method, req.url.path))
tok = req.headers.get("authorization", "").removeprefix("Bearer ")
me = self.keys.get(tok)
if not me:
return httpx.Response(401, json={"error": {"message": "invalid key"}})
if req.url.path == "/v1/me":
return httpx.Response(200, json=me)
# UHP Harnesses §5: POST creates and names the id; PUT replaces a harness of the key's
# workspace, and answers 404 for any other id (it never creates)
if req.url.path == "/v1/harnesses" and req.method == "POST":
body = json.loads(req.content)
hid = f"chrn_{len(self.calls):032x}"
self.harnesses[hid] = {**body, "org": me["org"], "workspace": me["workspace"]}
return httpx.Response(200, json={**body, "id": hid})
if req.url.path.startswith("/v1/harnesses/") and req.method == "PUT":
hid = req.url.path.rsplit("/", 1)[-1]
had = self.harnesses.get(hid)
# the hosted id pattern: anything else is no harness (404), by design
if not re.fullmatch(r"chrn_[0-9a-f]{32}", hid) or not had or (had["org"], had["workspace"]) != (me["org"], me["workspace"]):
return httpx.Response(404, json={"error": {"message": "No harness with that id."}})
body = json.loads(req.content)
self.harnesses[hid] = {**body, "org": me["org"], "workspace": me["workspace"]}
return httpx.Response(200, json={**body, "id": hid})
return httpx.Response(404, json={"error": {"message": "no route"}})
@pytest.fixture()
def cloud(monkeypatch):
c = Cloud()
real = httpx.AsyncClient
class Patched(real):
def __init__(self, *a, **kw):
kw["transport"] = httpx.MockTransport(lambda r: c.handle(r)) # a test may swap the handler
super().__init__(*a, **kw)
monkeypatch.setattr(gw.httpx, "AsyncClient", Patched)
monkeypatch.setattr(gw, "_checked_clients", {}) # built afresh, so on this test's cloud
return c
@pytest.fixture()
def api(monkeypatch):
async def principal(request):
return {"org": ORG, "member": "me@local"}
monkeypatch.setattr(gw, "_principal", principal)
asyncio.run(gw.BACKING.secrets.put(gw.GLOBAL_TENANT, gw._CLOUD_UPLOAD_KEY, "", require_encryption=True))
asyncio.run(gw.BACKING.secrets.put(gw.GLOBAL_TENANT, gw._CLOUD_UPLOAD_RECORDS_KEY, ""))
return TestClient(gw.app)
def _harness(api, name="Philz one-pager", **extra) -> str:
r = api.post("/v1/harnesses", json={"name": name, "base": "dsh", "default_model": "deepseek-v4-flash",
"system_prompt": "Make decks.", **extra})
assert r.status_code == 200, r.text
return r.json()["id"]
def test_nothing_is_configured_until_a_key_is_saved(api, cloud):
assert api.get("/v1/cloud-upload/targets").json() == {"targets": [], "last": ""}
r = api.post("/v1/harnesses/upload", json={"ids": ["chrn_" + "0" * 32]})
assert r.status_code == 400 and "no cloud workspace" in r.text
assert cloud.calls == []
def test_test_resolves_the_key_to_a_label_without_saving_and_shows_no_ids(api, cloud):
r = api.post("/v1/cloud-upload/targets/test", json={"api_key": "sk-hr-good", "base_url": CLOUD})
assert r.status_code == 200
j = r.json()
assert j["label"] == "Research (owner)"
assert "org_e" not in json.dumps(j) and "ws_r" not in json.dumps(j) # internal ids never shown
assert api.get("/v1/cloud-upload/targets").json()["targets"] == []
def test_a_bad_key_and_a_key_without_a_workspace_are_refused(api, cloud):
assert api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-wrong", "base_url": CLOUD}).status_code == 401
r = api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-nows", "base_url": CLOUD})
assert r.status_code == 400 and "workspace" in r.text
def test_stored_targets_keep_the_key_out_and_can_be_removed(api, cloud):
r = api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
assert r.status_code == 200
j = r.json()
assert j["label"] == "Research (owner)" and "sk-hr-good" not in json.dumps(j)
assert j["key_hint"].startswith("sk-hr-") and "…" in j["key_hint"]
lst = api.get("/v1/cloud-upload/targets").json()
assert len(lst["targets"]) == 1 and lst["last"] == j["id"]
left = api.delete(f"/v1/cloud-upload/targets?id={j['id']}").json()
assert left["targets"] == [] and left["last"] == ""
def test_upload_creates_the_copy_then_replaces_that_same_copy(api, cloud):
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
hid = _harness(api)
r = api.post(f"/v1/harnesses/{hid}/upload")
assert r.status_code == 200, r.text
assert r.json()["action"] == "create" and r.json()["ok"] is True
remote = r.json()["remote_id"]
assert ("POST", "/v1/harnesses") in cloud.calls # created as UHP creates, never by PUT
sent = cloud.harnesses[remote]
assert sent["name"] == "Philz one-pager" and sent["base"] == "dsh" and sent["system_prompt"] == "Make decks."
assert sent["source"] == "selfhost" and sent["workspace"] == "ws_r" # landed in the key's workspace
assert "api_key" not in json.dumps(sent) # nothing secret travels
st = api.get(f"/v1/harnesses/{hid}/upload").json()
assert st["uploaded"] is True and st["changed"] is False and st["target"] == "Research (owner)"
# edit locally: the chip says changed; upload again: replace, in place, the same copy
api.put(f"/v1/harnesses/{hid}", json={"name": "Philz one-pager v2", "base": "dsh"})
assert api.get(f"/v1/harnesses/{hid}/upload").json()["changed"] is True
r = api.post(f"/v1/harnesses/{hid}/upload")
assert r.json()["action"] == "replace" and r.json()["remote_id"] == remote
assert ("PUT", f"/v1/harnesses/{remote}") in cloud.calls and cloud.harnesses[remote]["name"] == "Philz one-pager v2"
assert len(cloud.harnesses) == 1
assert api.get(f"/v1/harnesses/{hid}/upload").json()["changed"] is False
def test_skills_travel_with_their_files_inlined(api, cloud):
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
big = "x" * (gw._SKILL_INLINE_MAX + 100) # forces the local blob offload
hid = _harness(api, skills=[{"name": "deck", "files": [{"path": "SKILL.md", "content": big}]}])
assert "blob" in json.dumps(asyncio.run(gw._vertex_get(hid)).get("skills")) # offloaded locally
up = api.post(f"/v1/harnesses/{hid}/upload")
assert up.status_code == 200
sk = cloud.harnesses[up.json()["remote_id"]]["skills"][0]
assert sk["name"] == "deck" and "blob" not in sk and sk["files"][0]["content"] == big
def test_batch_runs_every_row_and_skips_builtins(api, cloud):
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
a, b = _harness(api, "A"), _harness(api, "B")
r = api.post("/v1/harnesses/upload", json={"ids": [a, "codex", b, "chrn_" + "f" * 32]})
assert r.status_code == 200
rows = {x["id"]: x for x in r.json()["results"]}
assert rows[a]["ok"] and rows[a]["action"] == "create"
assert rows[b]["ok"] and rows[b]["action"] == "create"
assert rows["codex"]["action"] == "skip" and rows["codex"]["error"] == "built-in"
assert rows["chrn_" + "f" * 32]["action"] == "skip" and rows["chrn_" + "f" * 32]["error"] == "not found"
assert sorted(h["name"] for h in cloud.harnesses.values()) == ["A", "B"]
st = api.get("/v1/cloud-upload/status").json()["harnesses"]
assert st[a]["uploaded"] and st[b]["uploaded"]
def test_a_cloud_error_on_one_row_does_not_stop_the_others(api, cloud, monkeypatch):
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
a, b = _harness(api, "A"), _harness(api, "B")
real = cloud.handle
def flaky(req):
if req.method == "POST" and json.loads(req.content).get("name") == "A":
return httpx.Response(500, json={"error": {"message": "hosted hiccup"}})
return real(req)
cloud.handle = flaky
rows = {x["id"]: x for x in api.post("/v1/harnesses/upload", json={"ids": [a, b]}).json()["results"]}
assert rows[a]["ok"] is False and "hosted hiccup" in rows[a]["error"]
assert rows[b]["ok"] is True
assert api.get(f"/v1/harnesses/{a}/upload").json()["uploaded"] is False # a failed upload leaves no record
def test_a_copy_deleted_on_cloud_is_created_again(api, cloud):
"""The copy a destination's record names may be deleted on Cloud since; its PUT answers 404, and
the deploy creates a new copy, which every later deploy replaces. Any other failure creates
nothing."""
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
hid = _harness(api, "Deleted there")
first = api.post(f"/v1/harnesses/{hid}/upload").json()["remote_id"]
del cloud.harnesses[first]
r = api.post(f"/v1/harnesses/{hid}/upload")
assert r.status_code == 200, r.text
again = r.json()["remote_id"]
assert r.json()["action"] == "create" and again != first and cloud.harnesses[again]["name"] == "Deleted there"
r2 = api.post(f"/v1/harnesses/{hid}/upload")
assert r2.json()["remote_id"] == again and r2.json()["action"] == "replace"
assert list(cloud.harnesses) == [again]
real = cloud.handle
def flaky(req):
if req.method == "PUT":
return httpx.Response(500, json={"error": {"message": "boom"}})
return real(req)
cloud.handle = flaky
assert api.post(f"/v1/harnesses/{hid}/upload").status_code == 502 # a non-404 creates nothing
assert list(cloud.harnesses) == [again]
def test_a_record_from_before_remote_ids_replaces_the_copy_at_the_local_id(api, cloud):
"""An upload before remote ids were kept recorded only the fingerprint: its copy is at the
harness's own id. The next deploy replaces that copy and creates nothing."""
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
hid = _harness(api, "Older upload")
target = asyncio.run(gw._cloud_targets())["targets"][api.get("/v1/cloud-upload/targets").json()["last"]]
cloud.harnesses[hid] = {"name": "Older upload", "org": "org_e", "workspace": "ws_r"}
rec = asyncio.run(gw._cloud_records())
rec.setdefault("harnesses", {})[hid] = {gw._cloud_tkey(target): {"fingerprint": "old", "uploaded_at": 1, "target": "Research (owner)"}}
asyncio.run(gw.BACKING.secrets.put(gw.GLOBAL_TENANT, gw._CLOUD_UPLOAD_RECORDS_KEY, json.dumps(rec)))
r = api.post(f"/v1/harnesses/{hid}/upload")
assert r.status_code == 200, r.text
assert r.json()["action"] == "replace" and r.json()["remote_id"] == hid
assert list(cloud.harnesses) == [hid] and cloud.harnesses[hid]["system_prompt"] == "Make decks."
assert ("POST", "/v1/harnesses") not in cloud.calls
assert api.get(f"/v1/harnesses/{hid}/upload").json()["changed"] is False
def test_the_same_harness_uploads_to_every_workspace_a_key_points_at(api, cloud):
"""It is just an upload: wherever there is a key, it lands. Each target keeps its own hosted
copy and its own chip state; a second workspace in the SAME org gets its own copy rather
than silently updating the first one's."""
cloud.keys["sk-hr-ws2"] = {"org": "org_e", "org_name": "Example Co", "workspace": "ws_2",
"workspace_name": "Second", "member": "owner"}
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
hid = _harness(api, "Everywhere")
r1 = api.post(f"/v1/harnesses/{hid}/upload").json()
assert r1["action"] == "create"
# switch the key to another workspace of the same org: its own copy, its own id
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-ws2", "base_url": CLOUD})
assert api.get(f"/v1/harnesses/{hid}/upload").json()["uploaded"] is True # chip: most recent upload anywhere
r2 = api.post(f"/v1/harnesses/{hid}/upload").json()
assert r2["action"] == "create" and r2["remote_id"] != r1["remote_id"]
assert cloud.harnesses[r1["remote_id"]]["workspace"] == "ws_r"
assert cloud.harnesses[r2["remote_id"]]["workspace"] == "ws_2"
st = api.get(f"/v1/harnesses/{hid}/upload").json()
assert st["uploaded"] is True and st["target"] == "Second (owner)"
# back to the first workspace: its record is intact, replace goes to its own copy
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
r3 = api.post(f"/v1/harnesses/{hid}/upload").json()
assert r3["action"] == "replace" and r3["remote_id"] == r1["remote_id"]
def test_a_target_stored_before_the_cloud_knew_its_name_heals_on_listing(api, cloud):
"""A key added while the hosted side answered empty names keeps working and picks up the
name the moment the hosted side can answer, with no re-adding."""
cloud.keys["sk-hr-good"] = {**cloud.keys["sk-hr-good"], "workspace_name": "", "member": ""}
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
assert api.get("/v1/cloud-upload/targets").json()["targets"][0]["label"] == "Cloud workspace"
cloud.keys["sk-hr-good"] = {**cloud.keys["sk-hr-good"], "workspace_name": "Test Workspace", "member": "owner"}
j = api.get("/v1/cloud-upload/targets").json()
assert j["targets"][0]["label"] == "Test Workspace (owner)"
# healed persistently: no further /v1/me calls once complete
n = len([c for c in cloud.calls if c[1] == "/v1/me"])
api.get("/v1/cloud-upload/targets")
assert len([c for c in cloud.calls if c[1] == "/v1/me"]) == n
def test_a_revoked_key_is_named_not_hidden(api, cloud):
"""A revoked key must read as 'key revoked', never as a generic label. Heal marks it on the
401; a working key that later answers clears the mark."""
cloud.keys["sk-hr-good"] = {**cloud.keys["sk-hr-good"], "workspace_name": "", "member": ""}
api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
dead = cloud.keys.pop("sk-hr-good") # revoke on the hosted side
j = api.get("/v1/cloud-upload/targets").json()
assert j["targets"][0]["revoked"] is True
cloud.keys["sk-hr-good"] = {**dead, "workspace_name": "Test Workspace", "member": "owner"}
j = api.get("/v1/cloud-upload/targets").json() # un-revoked: heals and clears the mark
assert j["targets"][0]["revoked"] is False and j["targets"][0]["label"] == "Test Workspace (owner)"
def test_discovery_reports_the_version_this_build_is(api, monkeypatch):
"""The literal that used to sit in the discovery document went stale and told every client
0.3.0 six releases later. The version comes from the build now, and an unreleased build says
so rather than claiming a number."""
monkeypatch.delenv("HR_VERSION", raising=False)
assert api.get("/v1/uhp").json()["implementation"]["version"] == "dev"
monkeypatch.setenv("HR_VERSION", "0.9.1")
assert api.get("/v1/uhp").json()["implementation"]["version"] == "0.9.1"
def test_a_destination_on_a_private_network_is_refused_on_a_shared_deployment(api, cloud, monkeypatch):
"""The test route fetches the destination for any caller with a key and returns what it
answers (reported privately). On a shared deployment the rule an MCP address follows applies:
https only, and no address that resolves to a private, local or metadata range; nothing is
fetched. A self-hosted box's own network stays allowed."""
monkeypatch.setattr(gw, "_pool_is_local", lambda: False)
for base in ("https://10.0.0.5", "https://169.254.169.254", "https://127.0.0.1:8080", "https://[::1]",
"http://cloud.example", "https:///no-host"):
for route in ("/v1/cloud-upload/targets/test", "/v1/cloud-upload/targets"):
r = api.post(route, json={"api_key": "sk-hr-good", "base_url": base})
assert r.status_code == 400 and "cannot be used" in r.text, (base, route, r.status_code, r.text[:200])
assert cloud.calls == []
assert asyncio.run(gw._cloud_base_refused("https://140.82.112.3")) is None # a public address
monkeypatch.setattr(gw, "_pool_is_local", lambda: True)
assert asyncio.run(gw._cloud_base_refused("http://10.0.0.5:3000")) is None # the operator's own network
def test_a_destination_stored_before_the_check_is_not_called(api, cloud, monkeypatch):
hid = _harness(api)
monkeypatch.setattr(gw, "_pool_is_local", lambda: False)
before = list(cloud.calls)
out = asyncio.run(gw._cloud_upload_one(ORG, hid, {"base_url": "https://10.0.0.5", "api_key": "sk-hr-good"}, {}))
assert out["ok"] is False and "cannot be used" in out["error"] and cloud.calls == before