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
feat(protocol): the Unified Harness Protocol — spec, schema, conformance suite and site
richard-epsilla6fdc8d312f38
diff --git a/.gitignore b/.gitignoreindex f0203629..4faf809c 100644--- a/.gitignore+++ b/.gitignore@@ -7,3 +7,6 @@ __pycache__/.env.env.local.DS_Store++# Generated by protocol/site/build.py — build it, do not commit it.+protocol/site/dist/diff --git a/README.md b/README.mdindex 0f356d35..1aaee6d2 100644--- a/README.md+++ b/README.md@@ -201,6 +201,28 @@ Storage sits behind a small adapter interface (graph / blob / secret). This repoimplementations; the hosted deployment overlays its own against the same interface. That seam iswhy this is genuinely the same codebase rather than a fork that drifts.+## The Unified Harness Protocol++This repository is both an implementation and a standard. The protocol the gateway speaks is+specified, versioned and testable in [`protocol/`](protocol/):++| | |+|---|---|+| [Specification](protocol/versions/2026-08-11/) | Ten normative chapters, version `2026-08-11` |+| [Machine-readable](protocol/schema/) | OpenAPI 3.1 + JSON Schema 2020-12, generated from one source |+| [Conformance suite](protocol/conformance/) | 47 runnable checks — passing it is what "conformant" means |+| [Governance](protocol/GOVERNANCE.md) | How the standard changes: prose first, three artifacts together |++This edition is the reference implementation and+[passes at class Full](protocol/conformance/reports/harnessrouter-ce-0.3.0.json). **The standard can+be implemented without HarnessRouter Cloud** — it is an HTTP contract, and nothing in it requires a+hosted service. Run the suite against your own server:++```bash+pip install -e protocol/conformance+uhp-conformance --base-url https://your-server --api-key "$KEY" --class full+```+## LicenseApache-2.0 — see [LICENSE](LICENSE). Third-party notices are in [NOTICE](NOTICE).diff --git a/gateway/app.py b/gateway/app.pyindex fba68e77..ae0bcb10 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -2394,6 +2394,118 @@ async def llm_broker(path: str, request: Request):media_type=up.headers.get("content-type"))+# ── Unified Harness Protocol: version, discovery, and the error envelope ────────────────+# The protocol this server implements is specified in protocol/ — this section is the part of the+# implementation the specification names directly. Writing the specification exposed three things+# this server did not do, and all three were client-visible defects rather than cosmetic gaps:+#+# 1. Nothing told a client which contract a response was written to. Added UHP-Version on every+# response, and honoured on the way in.+# 2. A client had no way to ask what this server supports; it had to guess, or learn from a 404.+# Added GET /v1/uhp.+# 3. Failures returned a bare human string, so a client had to match on prose to decide whether to+# retry. Added the structured error envelope. The old `detail` string is still emitted beside+# it, because clients in the wild read it — it is documented as deprecated, not removed under+# them.+UHP_VERSION = "2026-08-11"+UHP_VERSIONS = [UHP_VERSION]++# Capabilities are declared, not inferred, and the conformance suite checks each one against the+# behaviour it promises. Reporting false is a supported answer; omitting a key is not, because a+# client cannot tell an omission from an older server.+UHP_CAPABILITIES = {+ "streaming": True,+ "sessions": True,+ "cancellation": True,+ "files_input": True,+ "files_output": True,+ "session_listing": True,+ "harness_management": True,+ "session_sharing": True,+ "idempotency": True,+}+UHP_CONFORMANCE_CLASS = "full"++# status -> (error type, fallback code) for raises that predate uhp_error() and carry only a string.+# The type is always right because it follows from the status; the code is generic, which is honest:+# a made-up specific code would be worse than one that says only as much as the status does.+_UHP_STATUS_TYPE = {+ 400: ("invalid_request_error", "invalid_input"),+ 401: ("authentication_error", "invalid_credential"),+ 403: ("permission_error", "insufficient_scope"),+ 404: ("invalid_request_error", "not_found"),+ 409: ("invalid_request_error", "conflict"),+ 413: ("invalid_request_error", "file_too_large"),+ 422: ("invalid_request_error", "unprocessable"),+ 429: ("rate_limit_error", "rate_limited"),+ 500: ("server_error", "internal_error"),+ 501: ("server_error", "not_implemented"),+ 502: ("server_error", "upstream_error"),+ 503: ("server_error", "unavailable"),+ 504: ("server_error", "timeout"),+}+++def uhp_error(status: int, code: str, message: str, param: str | None = None,+ detail: dict | None = None) -> HTTPException:+ """Raise a failure the protocol names. `raise uhp_error(404, "harness_not_found", ...)`.++ Carries the structured fields through FastAPI's HTTPException.detail so the handler below can+ emit them verbatim instead of guessing from the status.+ """+ etype = _UHP_STATUS_TYPE.get(status, ("server_error", "internal_error"))[0]+ return HTTPException(status, {"__uhp__": True, "type": etype, "code": code,+ "message": message, "param": param, "detail": detail})++[email protected]_handler(HTTPException)+async def _uhp_http_exception(request: Request, exc: HTTPException):+ d = exc.detail+ if isinstance(d, dict) and d.get("__uhp__"):+ err = {k: d.get(k) for k in ("type", "code", "message", "param", "detail")}+ else:+ etype, code = _UHP_STATUS_TYPE.get(exc.status_code, ("server_error", "internal_error"))+ err = {"type": etype, "code": code, "message": str(d) if d else "request failed",+ "param": None, "detail": None}+ body = {"error": err, "detail": err["message"]} # `detail`: deprecated alias, see above+ return JSONResponse(body, status_code=exc.status_code,+ headers={**(exc.headers or {}), "UHP-Version": UHP_VERSION})++[email protected]("http")+async def _uhp_version(request: Request, call_next):+ """Negotiate the protocol version, and state on every response which one was served.++ A client that asks for a version this server cannot serve is refused. Serving it a different+ version quietly would be worse: it would receive a body it may not be able to parse, with+ nothing indicating why.+ """+ want = (request.headers.get("uhp-version") or "").strip()+ if want and want not in UHP_VERSIONS:+ return JSONResponse(+ {"error": {"type": "invalid_request_error", "code": "unsupported_protocol_version",+ "message": f"This server does not implement UHP version '{want}'.",+ "param": "UHP-Version", "detail": {"supported": UHP_VERSIONS}},+ "detail": f"This server does not implement UHP version '{want}'."},+ status_code=400, headers={"UHP-Version": UHP_VERSION})+ resp = await call_next(request)+ resp.headers["UHP-Version"] = UHP_VERSION+ return resp++[email protected]("/v1/uhp")+def uhp_discovery() -> dict:+ """Protocol discovery. Deliberately unauthenticated: a client has to be able to find out whether+ this is a UHP server, and which versions it speaks, BEFORE it decides what credential to present.+ Nothing here is principal-specific."""+ return {"object": "uhp.discovery", "protocol": "uhp",+ "versions": UHP_VERSIONS, "default_version": UHP_VERSION,+ "conformance_class": UHP_CONFORMANCE_CLASS,+ "capabilities": dict(UHP_CAPABILITIES),+ "implementation": {"name": "HarnessRouter Community Edition",+ "version": os.environ.get("HR_VERSION", "0.3.0")}}++@app.get("/healthz")def healthz(bus: int = 0) -> dict:if bus:@@ -2554,7 +2666,7 @@ async def _owned_session(request: Request, sid: str) -> tuple[str, dict]:org = p.get("org", "")v = await _vertex_get(sid)if not v or str(v.get("tenant") or "") != org or str(v.get("status")) == "deleted":- raise HTTPException(404, "session not found")+ raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")return org, v@@ -4566,7 +4678,7 @@ async def create_response(body: CreateResponseBody, request: Request):# the marketplace model is exactly "callers run it, the owner pays infra". Until entitlements# land, the unguessable harness id is the run capability.if hv and str(hv.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")# HR-INF-023: credit admission. BILLING is the harness OWNER's org — the Developer who built the# harness funds its infra consumption (hv["org"], stamped at harness creation), regardless of who# calls it. A turn with no harness vertex (built-in, or an ad-hoc/chained turn that carries no@@ -5120,11 +5232,11 @@ async def get_response(response_id: str, request: Request):principal = await _principal(request)rec = await _resp_get(response_id)if not rec:- raise HTTPException(404, "response not found")+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")# Object-level ownership (LIVE-B): one org must not read another's response. 404 (not 403)# so a cross-org id probe can't confirm existence. Legacy records with no _org stay readable.if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", ""):- raise HTTPException(404, "response not found")+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")# Durable settler for async/background polling: never leave a poller stuck at 'running' if the# owning turn actually finished/died (reconciled from the session vertex + trace).rec = await _reconcile_response(response_id, rec)@@ -5227,11 +5339,11 @@ async def delete_response(response_id: str, request: Request):principal = await _principal(request)rec = await _resp_get(response_id)if not rec:- raise HTTPException(404, "response not found")+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")# V1C02-004: object-level ownership — one org must not delete another's response. 404 (not# 403) so a cross-org id probe can't confirm existence. Legacy records with no _org stay owned.if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", ""):- raise HTTPException(404, "response not found")+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")rec["_deleted"] = Truetry:await _blob_put(f"responses/{response_id}.json", json.dumps(rec, default=str).encode(), kb=RESP_BLOB_KB)@@ -5322,7 +5434,7 @@ async def artifact_by_path(sid: str, path: str, request: Request) -> Response:p = await _principal(request)v = await _vertex_get(sid)if not v or str(v.get("tenant") or "") != p.get("org"):- raise HTTPException(404, "session not found")+ raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")return await _serve_workspace_path(sid, path)@@ -5335,7 +5447,7 @@ async def set_session_share(sid: str, body: ShareBody, request: Request) -> dictp = await _principal(request)v = await _vertex_get(sid)if not v or str(v.get("tenant") or "") != p.get("org"):- raise HTTPException(404, "session not found")+ raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")if body.enabled:token = str(v.get("share_token") or "") or ("shr" + uuid.uuid4().hex)await _vertex_upsert(sid, {"share_token": token, "shared": "1",@@ -5354,7 +5466,7 @@ async def get_session_share(sid: str, request: Request) -> dict:p = await _principal(request)v = await _vertex_get(sid)if not v or str(v.get("tenant") or "") != p.get("org"):- raise HTTPException(404, "session not found")+ raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")return {"enabled": str(v.get("shared") or "") == "1", "token": str(v.get("share_token") or "")}@@ -5432,9 +5544,9 @@ async def list_input_items(response_id: str, request: Request, limit: int = 20,principal = await _principal(request)rec = await _resp_get(response_id)if not rec:- raise HTTPException(404, "response not found")+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", ""):- raise HTTPException(404, "response not found") # LIVE-B: object-level ownership+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id") # LIVE-B: object-level ownershipdata = list(rec.get("_input") or [])if order == "desc":data.reverse()@@ -5452,11 +5564,11 @@ async def cancel_response(response_id: str, request: Request):org = principal.get("org", "")rec = await _resp_get(response_id)if not rec:- raise HTTPException(404, "response not found")+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")# Ownership (LIVE-B): the resolved principal must own this response. 404 (not 403)# so a cross-org probe can't even confirm the id exists.if str(rec.get("_org") or "") != org:- raise HTTPException(404, "response not found")+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")sid = str(rec.get("_session_id") or "")# PRIMARY (safe, cross-replica): a durable per-RESPONSE monotonic terminal latch. The turn's# own loop checks resp_is_cancelled(its resp_id) at every stage and self-terminates within@@ -5750,7 +5862,9 @@ async def session_workspace_files(sid: str, request: Request, changed: bool = Faitems = (json.loads(blob) or {}).get("files") or []except Exception: # noqa: BLE001items = []- files = [{"path": it["path"], "bytes": it.get("bytes"),+ files = [{"object": "file", "id": it["file_id"], "container_id": sid,+ "filename": it["path"].rsplit("/", 1)[-1],+ "path": it["path"], "bytes": it.get("bytes"),"media_type": mimetypes.guess_type(it["path"])[0] or "application/octet-stream","file_id": it["file_id"], "download_url": _file_url(sid, it["file_id"])}for it in items if it.get("path") and it.get("file_id")]@@ -5783,7 +5897,9 @@ async def session_workspace_files(sid: str, request: Request, changed: bool = Faif not _ws_visible(path):continuefid = cfile_by_name.get(path) or _wf_id(path)- files.append({"path": path, "bytes": m.size,+ files.append({"object": "file", "id": fid, "container_id": sid,+ "filename": path.rsplit("/", 1)[-1],+ "path": path, "bytes": m.size,"media_type": mimetypes.guess_type(path)[0] or "application/octet-stream","file_id": fid,"download_url": _file_url(sid, fid)})@@ -6184,6 +6300,21 @@ async def test_mcp_public(body: McpTestBody, request: Request) -> dict:# ── custom harnesses (per-org, server-persisted; replaces the client localStorage seam) ───────+# Bases this server can execute. Derived from the same mapping the turn loop uses+# (_backend_of_harness), so the two cannot disagree: anything not listed here has no backend and+# could only fail at task time.+_SUPPORTED_BASES = ("codex", "claude-code", "claude", "hermes")+++def _require_supported_base(base: str) -> str:+ b = (base or "").strip().lower()+ if b not in _SUPPORTED_BASES:+ raise uhp_error(422, "unsupported_base",+ f"This server cannot run the harness base '{base}'.", "base",+ {"supported": list(_SUPPORTED_BASES)})+ return b++class HarnessBody(BaseModel):name: strbase: str@@ -6226,7 +6357,8 @@ async def _vg_list_by_org(label: str, org: str) -> list[dict]:def _harness_props(body: HarnessBody) -> dict:- return {"name": body.name, "base": body.base, "base_label": body.base_label or body.base,+ base = _require_supported_base(body.base) # refuse at create, not at the first task+ return {"name": body.name, "base": base, "base_label": body.base_label or base,"default_model": body.default_model or "", "system_prompt": body.system_prompt or "","mcp_servers": json.dumps(body.mcp_servers or []), "skills": json.dumps(body.skills or []),"disabled_tools": json.dumps(body.disabled_tools or []),@@ -6343,7 +6475,7 @@ async def get_harness(org: str, hid: str, request: Request) -> dict:await _owned_org(request, org)v = await _vertex_get(hid)if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")return _harness_out(v)@@ -6354,7 +6486,7 @@ async def get_harness_models(org: str, hid: str, request: Request) -> dict:await _owned_org(request, org)v = await _vertex_get(hid)if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")backend = _backend_of_harness(v) or _route_backend(str(v.get("default_model") or ""), None)return {"harness_id": hid,**_harness_models_view(v, backend, await _servable_models(org, backend))}@@ -6367,7 +6499,7 @@ async def get_harness_skill_files(org: str, hid: str, skill_id: str, request: Reawait _owned_org(request, org)v = await _vertex_get(hid)if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")try:skills = json.loads(v.get("skills") or "[]")except Exception: # noqa: BLE001@@ -6386,7 +6518,7 @@ async def update_harness(org: str, hid: str, body: HarnessBody, request: Request# V1C02-005: bind the mutation to the caller's org — a foreign harness id must not be editable.cur = await _vertex_get(hid)if not cur or str(cur.get("org") or "") != org or str(cur.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")# coalesce-upsert: created_at/org are untouched (only the provided props are set)body.skills = await _skills_prepare(body.skills)await _vg_upsert("Harness", hid, {**_harness_props(body), "updated_at": str(int(time.time() * 1000))})@@ -6400,7 +6532,7 @@ async def delete_harness(org: str, hid: str, request: Request) -> dict:# V1C02-005: only delete a harness that belongs to the caller's org.cur = await _vertex_get(hid)if not cur or str(cur.get("org") or "") != org:- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")await _vg_upsert("Harness", hid, {"deleted": "1"})return {"id": hid, "deleted": True}@@ -6411,7 +6543,7 @@ async def _pub_org_member(request: Request) -> tuple[str, str]:p = await _principal(request)org = p.get("org", "")if not org:- raise HTTPException(401, "invalid or missing HarnessRouter API key")+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")return org, p.get("member", "")@@ -6420,7 +6552,7 @@ async def create_harness_public(body: HarnessBody, request: Request) -> dict:p = await _principal(request)org, member = p.get("org", ""), p.get("member", "")if not org:- raise HTTPException(401, "invalid or missing HarnessRouter API key")+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")body.skills = await _skills_prepare(body.skills)hid = _rid("chrn")now = str(int(time.time() * 1000))@@ -6436,7 +6568,7 @@ async def list_harnesses_public(request: Request) -> dict:p = await _principal(request)org = p.get("org", "")if not org:- raise HTTPException(401, "invalid or missing HarnessRouter API key")+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")# Org-scoped, member-agnostic (see list_harnesses): an API key sees every harness in its# org — narrowed to its workspace when the key is workspace-scoped — exactly like the# console, so both surfaces always agree.@@ -6455,7 +6587,7 @@ async def get_harness_public(hid: str, request: Request) -> dict:org, _ = await _pub_org_member(request)v = await _vertex_get(hid)if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")return _harness_out(v)@@ -6483,7 +6615,7 @@ async def get_harness_models_public(hid: str, request: Request) -> dict:org, _ = await _pub_org_member(request)v = await _vertex_get(hid)if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")backend = _backend_of_harness(v) or _route_backend(str(v.get("default_model") or ""), None)return {"harness_id": hid,**_harness_models_view(v, backend, await _servable_models(org, backend))}@@ -6497,7 +6629,7 @@ async def get_harness_skill_files_public(hid: str, skill_id: str, request: Requeorg, _ = await _pub_org_member(request)v = await _vertex_get(hid)if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")try:skills = json.loads(v.get("skills") or "[]")except Exception: # noqa: BLE001@@ -6515,7 +6647,7 @@ async def update_harness_public(hid: str, body: HarnessBody, request: Request) -org, _ = await _pub_org_member(request)v = await _vertex_get(hid)if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")body.skills = await _skills_prepare(body.skills)await _vg_upsert("Harness", hid, {**_harness_props(body), "updated_at": str(int(time.time() * 1000))})return _harness_out(await _vertex_get(hid) or {"id": hid})@@ -6526,6 +6658,6 @@ async def delete_harness_public(hid: str, request: Request) -> dict:org, _ = await _pub_org_member(request)v = await _vertex_get(hid)if not v or v.get("org") != org:- raise HTTPException(404, "harness not found")+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")await _vg_upsert("Harness", hid, {"deleted": "1"})return {"id": hid, "deleted": True}diff --git a/protocol/CHANGELOG.md b/protocol/CHANGELOG.mdnew file mode 100644index 00000000..afc851b5--- /dev/null+++ b/protocol/CHANGELOG.md@@ -0,0 +1,44 @@+# Changelog++All notable changes to the Unified Harness Protocol.++## 2026-08-11 — first published version++The initial specification, extracted from the shipping HarnessRouter implementation rather than+designed in the abstract. Every endpoint and event described here was already running in production+before it was specified; the work was to write down the contract precisely, close the gaps that+writing it down revealed, and make the result testable.++### Defined++- **Architecture** — client / server / harness roles, three conformance classes (Core, Extended,+ Full), the six-object model, transport and authentication.+- **Lifecycle** — `UHP-Version` negotiation, the `GET /v1/uhp` discovery document, task states+ (`in_progress`, `completed`, `failed`, `incomplete`, `cancelled`), session lifecycle, concurrency+ rules.+- **Harnesses** — discovery, the harness object, model catalogues, computed `available`, and+ harness management at class Full.+- **Tasks** — `POST /v1/responses`, the response object, harness selection via `metadata.harness_id`,+ model substitution reporting, idempotency.+- **Streaming** — the SSE event vocabulary, `sequence_number` ordering guarantees, reconnection.+- **Sessions** — continuation via `previous_response_id`, listing, inspection, cancellation, sharing.+- **Files** — inline and uploaded input, artifact annotations, download, preview, retention.+- **Errors** — a single error envelope, a closed set of codes, retry rules.++### Gaps this closed in the reference implementation++Writing the specification exposed three places where the implementation had no defined behaviour:++- **No capability discovery.** A client had to guess what the server supported, or discover it from+ a 404. Added `GET /v1/uhp`.+- **No protocol version on the wire.** Nothing identified which contract a response was written to.+ Added the `UHP-Version` header on every response.+- **Unstructured errors.** Failures returned a bare human-readable string, so a client had to match+ on prose to decide whether to retry. Added the structured error envelope, with the previous string+ retained as a deprecated alias so existing clients keep working.++### Known compromises++Recorded in [VERSIONING.md](VERSIONING.md#the-current-versions-known-compromises): mixed field+casing between the task and harness surfaces, and session deletion living at `/v1/traces/{id}`. Both+are kept for compatibility and marked for a future major version.diff --git a/protocol/GOVERNANCE.md b/protocol/GOVERNANCE.mdnew file mode 100644index 00000000..e9a2b5a6--- /dev/null+++ b/protocol/GOVERNANCE.md@@ -0,0 +1,75 @@+# Governance and change process++UHP is maintained in the [HarnessRouter repository](https://github.com/HarnessRouter/harnessrouter)+under a maintainer-led, proposal-first model. This document defines how it changes.++## Principles++1. **Prose before code.** A change starts as a description of the problem, not a pull request. A+ patch is an answer; the proposal has to establish the question first.+2. **Three artifacts move together.** No change lands unless the specification, the reference+ implementation and the conformance suite are updated in the same change. A specification sentence+ that nothing enforces is a wish.+3. **Compatibility is a feature.** A change that breaks conformant clients requires a new version and+ a migration path, not a note in a changelog.+4. **The bar is a working implementation.** A proposal is not accepted on elegance. Something has to+ run it.++## The process++### 1. Propose++Open a **UHP Enhancement Proposal (UEP)** as a GitHub issue labelled `uep`, containing:++- **Problem** — what a developer cannot do today, concretely.+- **Proposal** — the change, in enough detail to be argued with.+- **Compatibility** — what breaks, and what a client written against the current version experiences.+- **Alternatives** — what else was considered and why it is worse.++Prose is enough. A UEP does not need a patch, and one is not a substitute for the above.++### 2. Discuss++Maintainers respond within 10 working days with one of: **accepted in principle**, **needs work**,+or **declined with reasons**. Declines are recorded, with the reasoning, so the same proposal is not+re-litigated from scratch.++### 3. Implement++An accepted UEP is implemented as one pull request containing all three artifacts:++- [ ] Specification chapter(s) updated+- [ ] `schema/` OpenAPI + JSON Schema updated+- [ ] Reference implementation updated+- [ ] Conformance test added that fails before the change and passes after+- [ ] `CHANGELOG.md` entry++A pull request missing any of these is not ready, however good the code is.++### 4. Release++Additive changes ship into the current version. Breaking changes accumulate into a new dated version+per [VERSIONING.md](VERSIONING.md), published with a migration note.++## Roles++- **Maintainers** — merge rights; responsible for consistency across the three artifacts and for+ responding to UEPs.+- **Contributors** — anyone who opens a UEP, a pull request, or an issue.+- **Implementers** — anyone shipping a UHP server or client. Implementer feedback outranks+ theoretical elegance in every design argument.++## Reporting problems++- **Specification bugs** — ambiguity, a rule that cannot be implemented, disagreement between the+ spec and the suite: open an issue labelled `spec-bug`. These are treated as defects.+- **Bugs in the reference implementation** — GitHub Issues.+- **Security vulnerabilities** — private disclosure, not a public issue. See the repository's+ security policy.++## Conformance claims++"UHP 2026-08-11 conformant (class)" means the conformance suite passes at that class. Publishing the+report alongside the claim is expected. There is no certification body, no fee, and no logo+programme — the suite is the authority, it is in this repository, and anyone can run it against+anyone's server.diff --git a/protocol/README.md b/protocol/README.mdnew file mode 100644index 00000000..9f30f8ec--- /dev/null+++ b/protocol/README.md@@ -0,0 +1,129 @@+# Unified Harness Protocol (UHP)++**An open standard for running complete agent harnesses as shared infrastructure.**++A *harness* is a complete agent runtime — a loop that plans, calls tools, edits files, and reports+back. Codex, Claude Code and Hermes are harnesses. Each one already knows how to do the work; what+none of them agree on is how a product should *drive* one: how to start a task, follow its+progress, continue the conversation, cancel it, get the files it produced, and understand why it+failed.++Today every product answers those questions again, per harness. UHP answers them once.++```+ your product ──▶ UHP ──▶ ┌── Codex+ ├── Claude Code+ ├── Hermes+ └── the harness that ships next year+```++UHP is not a model API and does not replace one. Model APIs give you a *turn*: messages in, tokens+out, tools you have to run yourself. UHP gives you a *task*: work in, and a running agent that uses+its own tools, keeps its own session, and hands back results and files. The unit of exchange is a+job, not a completion.++## Status of this document++| | |+|---|---|+| **Current version** | `2026-08-11` |+| **Status** | Draft standard — stable enough to build on, versioned so it can change safely |+| **Specification** | [`versions/2026-08-11/`](versions/2026-08-11/) |+| **Machine-readable** | [`schema/`](schema/) — OpenAPI 3.1 + JSON Schema 2020-12 |+| **Conformance suite** | [`conformance/`](conformance/) — runnable, and the definition of "conformant" |+| **Change process** | [`GOVERNANCE.md`](GOVERNANCE.md) |+| **Versioning rules** | [`VERSIONING.md`](VERSIONING.md) |+| **License** | Apache-2.0, same as the repository |++## This standard does not require HarnessRouter Cloud++That is the point of writing it down, so it is worth being concrete rather than reassuring.++UHP is an HTTP contract. A conformant server is any server that answers the requests in this+specification with the responses in this specification. It may run agents in containers, in+subprocesses, on a queue, or on someone else's infrastructure. Nothing in the wire format requires+a hosted service, an account, a licence key, or a call home.++Two independent implementations exist to keep that honest:++- **HarnessRouter Community Edition** — the reference implementation, in this repository, running+ wholly on your own machine (`docker run harnessrouter/harnessrouter:0.3.0`). It uses your own+ provider keys and stores everything on a volume you own. It is the implementation the conformance+ suite is developed against.+- **HarnessRouter Cloud** — a commercial hosted implementation of the same protocol.++A client written against this specification works with either, and with any third implementation+that passes the conformance suite. If you find a behaviour the specification does not describe but+your client depends on, that is a specification bug — please+[open an issue](https://github.com/HarnessRouter/harnessrouter/issues).++## What the protocol covers++| Chapter | What it defines |+|---|---|+| [Architecture](versions/2026-08-11/architecture.md) | Roles, conformance classes, and the object model |+| [Lifecycle](versions/2026-08-11/lifecycle.md) | Version negotiation, capability discovery, task lifecycle |+| [Harnesses](versions/2026-08-11/harnesses.md) | Discovering, selecting and configuring a harness |+| [Tasks](versions/2026-08-11/tasks.md) | Sending work and receiving a result |+| [Streaming](versions/2026-08-11/streaming.md) | Following progress as it happens |+| [Sessions](versions/2026-08-11/sessions.md) | Continuing a conversation, and cancelling one |+| [Files](versions/2026-08-11/files.md) | Sending files in, getting artifacts out |+| [Errors](versions/2026-08-11/errors.md) | Failure taxonomy, retries and idempotency |+| [Schema](versions/2026-08-11/schema.md) | The machine-readable definitions and how to use them |++## Quick shape of it++Discover what a server can run, run something, and follow it:++```bash+curl -s https://your-uhp-server/v1/harnesses -H "Authorization: Bearer $KEY"++curl -s -N https://your-uhp-server/v1/responses \+ -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \+ -d '{+ "input": "Summarise README.md in three bullets.",+ "model": "claude-sonnet-4.6",+ "metadata": { "harness_id": "chrn_…" },+ "stream": true+ }'+```++The stream is Server-Sent Events. The last event carries the finished `response` object, including+any files the agent produced. To continue the same conversation, send the next request with+`previous_response_id` set to the id you just received.++Full walk-through: [Tasks](versions/2026-08-11/tasks.md).++## Relationship to the OpenAI Responses API++UHP's task surface is deliberately shaped like the OpenAI Responses API, and a conformant server+MUST accept the subset of that request body described in [Tasks](versions/2026-08-11/tasks.md) and+emit the event vocabulary described in [Streaming](versions/2026-08-11/streaming.md).++This is a compatibility decision, not an accident. Products already have code that speaks Responses;+existing SDKs, streaming parsers, and UI components work against a UHP server with no changes. What+UHP adds is everything a *harness* needs and a model endpoint has no concept of: which harness runs+the work, its tools and skills, the session that survives between tasks, the files that come back,+and the cancellation of work that is already running.++Where UHP extends the Responses surface it does so in documented, additive places — `metadata`, a+small number of extra request fields, and additional object types — never by changing the meaning+of an existing field. A client that ignores every UHP extension still gets a working task.++## Implementing UHP++1. Read [Architecture](versions/2026-08-11/architecture.md) and pick a conformance class.+2. Generate types from [`schema/uhp-2026-08-11.openapi.yaml`](schema/uhp-2026-08-11.openapi.yaml).+3. Run the [conformance suite](conformance/) against your server while you build:+ ```bash+ pip install -e protocol/conformance+ uhp-conformance --base-url https://your-server --api-key "$KEY"+ ```+4. Publish your report. A server that passes at a class MAY describe itself as+ "UHP 2026-08-11 conformant (<class>)".++## Contributing++Changes to this specification follow [`GOVERNANCE.md`](GOVERNANCE.md). The short version: propose in+prose first, and no change lands unless the specification, the reference implementation and the+conformance suite move together.diff --git a/protocol/VERSIONING.md b/protocol/VERSIONING.mdnew file mode 100644index 00000000..159fe7c5--- /dev/null+++ b/protocol/VERSIONING.md@@ -0,0 +1,78 @@+# Versioning and compatibility++## The scheme++UHP versions are dates — `YYYY-MM-DD`, the day the version was published. `2026-08-11` is the+current version.++Dates were chosen over semantic versioning deliberately. SemVer's promise is that a major bump means+"expect breakage" and a minor bump means "safe" — a promise that is only as good as the discipline+of whoever assigns the numbers, and one that is routinely broken in practice. A date claims nothing+it cannot keep. It says when the version was published, it sorts, and it makes an implementation's+age obvious at a glance.++## What may change within a version++A published version is **immutable in structure**. Within a version, a server MAY:++- add optional request fields;+- add fields to response objects;+- add new event types;+- add new error codes with a vendor prefix;+- relax a constraint (accept input it previously rejected).++A server MUST NOT, within a version:++- remove or rename a field;+- change the type or meaning of a field;+- add a required request field;+- remove an event type or error code;+- tighten a constraint (reject input it previously accepted).++Anything in the second list requires a new version.++## Client rules++A conformant client MUST:++1. **Ignore unknown fields.** Not warn, not error — ignore.+2. **Ignore unknown event types.** Skip and continue reading the stream.+3. **Ignore unknown output item types.** Render what it understands.+4. **Treat unknown error codes as their `type`.** An unrecognised `code` with+ `type: "server_error"` is still retryable.++A client that follows these four rules keeps working across every additive change within a version,+which is the entire point of writing them down.++## Server rules++A server MUST:++1. Report the version it served in the `UHP-Version` response header.+2. Reject an unsupported requested version with `unsupported_protocol_version` rather than serving a+ different one.+3. Support at least one full version at a time, and SHOULD support the previous version for at least+ six months after a new one is published.++## Deprecation++A field or endpoint is deprecated by:++1. marking it deprecated in the specification and the OpenAPI document, with the reason and the+ replacement;+2. keeping it working for at least two published versions;+3. removing it no earlier than the second version after the announcement.++Nothing is removed without a working replacement having existed first.++## The current version's known compromises++Recorded here because a specification that hides its own rough edges cannot be trusted about the+smooth ones.++- **Mixed field casing.** The task surface is `snake_case`; the harness object is `camelCase`. Both+ are load-bearing in shipped clients. A future major version should unify them.+- **Session deletion lives at `/v1/traces/{id}`.** The path predates the session vocabulary. It is+ specified as-is rather than quietly renamed, because renaming it would break existing clients for+ a cosmetic gain. A future version should move it to `/v1/sessions/{id}` and deprecate the old path+ through the process above.diff --git a/protocol/conformance/README.md b/protocol/conformance/README.mdnew file mode 100644index 00000000..73a83172--- /dev/null+++ b/protocol/conformance/README.md@@ -0,0 +1,130 @@+# UHP conformance suite++**Passing this suite is what "UHP conformant" means.** Not implementing the endpoints, not a+self-assessment, not passing most of it. The suite is in this repository, it runs against any server+over HTTP, and anyone can run it against anyone's implementation.++## Running it++```bash+pip install -e protocol/conformance++uhp-conformance \+ --base-url https://your-uhp-server \+ --api-key "$UHP_API_KEY" \+ --class full \+ --json report.json+```++| Option | Meaning |+|---|---|+| `--base-url` | Server root. The suite appends `/v1/...` itself. |+| `--api-key` | Bearer token, or set `UHP_API_KEY`. |+| `--class` | `core`, `extended` or `full`. Cumulative — `full` runs everything. |+| `--harness-id` | Run tasks against a specific harness instead of the first one listed. |+| `--model` | Run tasks with a specific model. |+| `--task-timeout` | Seconds to allow one agent task. Default 300. |+| `--only` | Comma-separated check ids, for iterating on one failure. |+| `--json` | Write a machine-readable report. |+| `--plain` | No ANSI colour, for CI logs. |++Exit code is `0` when nothing failed and `1` otherwise, so it drops into CI unchanged.++**The suite runs real agent tasks.** It sends about six of them, which costs real model tokens and a+few minutes. That is deliberate: the defects worth catching — a stream that never flushes, a+cancellation that never terminates, an artifact that cannot be downloaded — are invisible to+anything that only inspects a schema.++## What it checks++47 checks across three classes.++| Class | Checks | Covers |+|---|---|---|+| **Core** | 37 | Discovery, version negotiation, authentication, the error envelope, harnesses, models, task execution (streaming and not), the event stream, sessions, cancellation |+| **Extended** | +8 | Session listing and inspection, file input, artifacts, download headers, path-traversal probes |+| **Full** | +2 | Harness create / update / delete, and refusal of an unsupported base |++Every check names the section of the specification it enforces, so a failure points at the sentence+it violates rather than at a test name.++A few of them are worth calling out, because they catch things a schema check never will:++- **S-04** — `sequence_number` is gapless and monotonic. Without it a client cannot tell a dropped+ event from a server that simply skips numbers.+- **S-09** — the stream is progressive. It measures the spread of event arrival times and fails a+ server that buffers everything and flushes at the end. That is the single most common UHP+ deployment error, it is usually a proxy setting, and it is indistinguishable from a slow agent+ unless something measures it.+- **C-03** — a running task really stops. It starts long work, cancels it, and waits for a terminal+ state. A cancel endpoint that returns `200` and leaves the agent running passes every other kind+ of test.+- **X-07** — artifacts download with `X-Content-Type-Options: nosniff`. Artifacts are+ attacker-influenceable content; served without it, an artifact is stored XSS against the client's+ own origin.+- **X-08** — artifact ids do not traverse out of their container. Probes for `../` and its+ percent-encoded form.++## Outcomes++| Outcome | Meaning |+|---|---|+| **PASS** | The required behaviour was observed. |+| **FAIL** | The behaviour was observed to be wrong. A conformance defect. |+| **SKIP** | The check could not run, with the reason recorded. |+| **ERROR** | The check itself broke — a bug in the suite. |++**A skip is never a pass.** The report states skips separately and repeats that they were not+verified, because a suite that hides unrun checks behind a green summary is how a suite starts+lying about the thing it exists to establish.++## Reference implementation results++HarnessRouter Community Edition 0.3.0, the reference implementation in this repository, run against+a live instance on 2026-08-11:++```+ Summary+ 47/47 passed · 0 failed · 0 skipped · 0 errored+ CONFORMANT — UHP 2026-08-11 (full)+```++The suite is developed against that implementation, which is exactly why the specification says+conformance is defined by the suite and not by the implementation: anything the reference does that+the suite does not require is a HarnessRouter behaviour, not a UHP requirement, and another+implementation is free to do it differently.++Writing and running the suite found four real defects, three in the reference implementation and one+in the suite itself:++1. No capability discovery at all — a client had to guess or learn from a `404`.+2. No protocol version on the wire.+3. Failures returned a bare human string, so a client had to match on prose to decide whether to+ retry.+4. `POST /v1/harnesses` accepted a base the server could not run, deferring the failure to the first+ task — after the client had committed to it. Caught by **F-02** on the first full run.++## Adding a check++A check is a function that asserts one requirement:++```python+@check("T-08", "Tasks reject an empty input", "core", f"{SPEC}/tasks.md#2-input")+def t08(ctx):+ r = ctx.client.post("/v1/responses", body={"input": ""})+ assert r.status == 400, f"empty input returned HTTP {r.status}, expected 400"+```++Rules for a good check:++- **Assert what the specification says, not what the reference implementation does.** Where the+ specification allows latitude, the check must allow it too — otherwise the suite enforces one+ implementation's preferences and every other implementation fails for being different rather than+ for being wrong.+- **Fail with the evidence.** The message should say what was expected, what happened, and why it+ matters. `assert r.status == 200` tells a maintainer nothing.+- **Skip loudly, never silently.** If a precondition is missing, `raise Skip("reason")`.+- **Clean up.** A check that creates a harness deletes it, including when it fails.++Per [GOVERNANCE.md](../GOVERNANCE.md), a specification change is not complete until a check enforces+it — a rule nothing tests is a wish.diff --git a/protocol/conformance/pyproject.toml b/protocol/conformance/pyproject.tomlnew file mode 100644index 00000000..2e70d1ac--- /dev/null+++ b/protocol/conformance/pyproject.toml@@ -0,0 +1,18 @@+[project]+name = "uhp-conformance"+version = "2026.8.11"+description = "Conformance suite for the Unified Harness Protocol (UHP)"+readme = "README.md"+requires-python = ">=3.10"+license = { text = "Apache-2.0" }+dependencies = ["jsonschema>=4.0"]++[project.scripts]+uhp-conformance = "uhp_conformance.cli:main"++[build-system]+requires = ["setuptools>=68"]+build-backend = "setuptools.build_meta"++[tool.setuptools]+packages = ["uhp_conformance"]diff --git a/protocol/conformance/reports/harnessrouter-ce-0.3.0.json b/protocol/conformance/reports/harnessrouter-ce-0.3.0.jsonnew file mode 100644index 00000000..5bda48c7--- /dev/null+++ b/protocol/conformance/reports/harnessrouter-ce-0.3.0.json@@ -0,0 +1,394 @@+{+ "protocol": "uhp",+ "protocol_version": "2026-08-11",+ "target": "HarnessRouter Community Edition 0.3.0 (self-hosted container)",+ "requested_class": "full",+ "conformant": true,+ "highest_class_passed": "full",+ "summary": {+ "pass": 47,+ "fail": 0,+ "skip": 0,+ "error": 0,+ "total": 47+ },+ "checks": [+ {+ "id": "D-01",+ "title": "Discovery document is served",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#2-capability-discovery",+ "outcome": "pass",+ "detail": "conformance_class=full versions=['2026-08-11']"+ },+ {+ "id": "D-02",+ "title": "Discovery is served without authentication",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#2-capability-discovery",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "D-03",+ "title": "Discovery document matches the schema",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/schema.md",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "D-04",+ "title": "default_version is one of versions",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#2-capability-discovery",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "D-05",+ "title": "conformance_class agrees with capabilities",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#2-capability-discovery",+ "outcome": "pass",+ "detail": "class=full"+ },+ {+ "id": "V-01",+ "title": "UHP-Version header on every response",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#1-version-negotiation",+ "outcome": "pass",+ "detail": "UHP-Version: 2026-08-11"+ },+ {+ "id": "V-02",+ "title": "A supported version is honoured",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#1-version-negotiation",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "V-03",+ "title": "An unsupported version is refused, not silently substituted",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#1-version-negotiation",+ "outcome": "pass",+ "detail": "supported=['2026-08-11']"+ },+ {+ "id": "A-01",+ "title": "Authenticated endpoints reject an absent credential",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/architecture.md#5-authentication",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "A-02",+ "title": "Authenticated endpoints reject an invalid credential",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/architecture.md#5-authentication",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "E-01",+ "title": "Errors use the structured envelope",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/errors.md#1-the-error-envelope",+ "outcome": "pass",+ "detail": "code=harness_not_found"+ },+ {+ "id": "E-02",+ "title": "Unknown harness reports harness_not_found",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/errors.md#31-request-and-routing",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "E-03",+ "title": "Unknown response reports response_not_found",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/errors.md#31-request-and-routing",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "E-04",+ "title": "Error messages carry no stack traces",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/errors.md#1-the-error-envelope",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "H-01",+ "title": "Harness list is served and well formed",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/harnesses.md#1-discovering-harnesses",+ "outcome": "pass",+ "detail": "4 harness(es)"+ },+ {+ "id": "H-02",+ "title": "A harness can be fetched by id",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/harnesses.md#1-discovering-harnesses",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "H-03",+ "title": "Model catalogue is served and availability is a boolean",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/harnesses.md#3-models",+ "outcome": "pass",+ "detail": "39/44 models available"+ },+ {+ "id": "H-04",+ "title": "Per-harness model list is served",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/harnesses.md#3-models",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "T-01",+ "title": "A non-streaming task returns a valid Response",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/tasks.md#3-the-response-object",+ "outcome": "pass",+ "detail": "status=completed in 5.2s"+ },+ {+ "id": "T-02",+ "title": "A finished task is in a terminal state",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#3-task-lifecycle",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "T-03",+ "title": "The response names the model that actually ran",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/tasks.md#13-model-selection-and-substitution",+ "outcome": "pass",+ "detail": "model=claude-sonnet-4.6"+ },+ {+ "id": "T-04",+ "title": "The response reports its session",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/lifecycle.md#4-session-lifecycle",+ "outcome": "pass",+ "detail": "session_id=hsess572496c66b58478cb133db32e794aa90"+ },+ {+ "id": "T-05",+ "title": "usage is an object or explicitly null, never fabricated",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/tasks.md#3-the-response-object",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "T-06",+ "title": "A stored response can be read back",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/tasks.md#4-reading-a-task-back",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "T-07",+ "title": "Response ids are prefixed",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/architecture.md#3-object-model",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "S-01",+ "title": "A streaming task emits events",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/streaming.md#1-opening-a-stream",+ "outcome": "pass",+ "detail": "14 events"+ },+ {+ "id": "S-02",+ "title": "Stream content type is text/event-stream",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/streaming.md#1-opening-a-stream",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "S-03",+ "title": "Every event validates against the schema",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/schema.md",+ "outcome": "pass",+ "detail": "14 events valid"+ },+ {+ "id": "S-04",+ "title": "sequence_number starts at 0 and has no gaps",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/streaming.md#3-ordering-guarantees",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "S-05",+ "title": "The first event is response.created",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/streaming.md#3-ordering-guarantees",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "S-06",+ "title": "The stream ends with exactly one terminal event",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/streaming.md#4-terminal-events",+ "outcome": "pass",+ "detail": "terminal=response.completed"+ },+ {+ "id": "S-07",+ "title": "The terminal event carries the complete response",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/streaming.md#4-terminal-events",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "S-08",+ "title": "Streaming and non-streaming agree on the result shape",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/streaming.md#6-non-streaming",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "S-09",+ "title": "The stream is progressive, not buffered to the end",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/streaming.md#1-opening-a-stream",+ "outcome": "pass",+ "detail": "events spread over 8.7s"+ },+ {+ "id": "C-01",+ "title": "A task can continue a session",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/sessions.md#1-continuing-a-session",+ "outcome": "pass",+ "detail": "session hsess572496c66b58478cb133db32e794aa90 extended"+ },+ {+ "id": "C-02",+ "title": "Cancelling a terminal task succeeds and changes nothing",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/sessions.md#4-cancelling",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "C-03",+ "title": "A running task can be cancelled and ends non-running",+ "class": "core",+ "spec": "protocol/versions/2026-08-11/sessions.md#4-cancelling",+ "outcome": "pass",+ "detail": "final status=cancelled"+ },+ {+ "id": "X-01",+ "title": "Sessions can be listed",+ "class": "extended",+ "spec": "protocol/versions/2026-08-11/sessions.md#2-listing-sessions",+ "outcome": "pass",+ "detail": "5 session(s)"+ },+ {+ "id": "X-02",+ "title": "Session listing reports the end of pagination explicitly",+ "class": "extended",+ "spec": "protocol/versions/2026-08-11/sessions.md#2-listing-sessions",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "X-03",+ "title": "A session can be inspected",+ "class": "extended",+ "spec": "protocol/versions/2026-08-11/sessions.md#3-inspecting-a-session",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "X-04",+ "title": "A session's turn history is available",+ "class": "extended",+ "spec": "protocol/versions/2026-08-11/sessions.md#3-inspecting-a-session",+ "outcome": "pass",+ "detail": ""+ },+ {+ "id": "X-05",+ "title": "A file can be sent as task input",+ "class": "extended",+ "spec": "protocol/versions/2026-08-11/files.md#1-sending-files-in",+ "outcome": "pass",+ "detail": "the harness read the file and echoed the token"+ },+ {+ "id": "X-06",+ "title": "Artifacts of a session can be listed",+ "class": "extended",+ "spec": "protocol/versions/2026-08-11/files.md#22-by-listing-the-session",+ "outcome": "pass",+ "detail": "1 artifact(s)"+ },+ {+ "id": "X-07",+ "title": "An artifact downloads as raw bytes with nosniff",+ "class": "extended",+ "spec": "protocol/versions/2026-08-11/files.md#3-downloading",+ "outcome": "pass",+ "detail": "11 bytes, text/plain; charset=utf-8"+ },+ {+ "id": "X-08",+ "title": "Artifact ids do not traverse outside their container",+ "class": "extended",+ "spec": "protocol/versions/2026-08-11/files.md#5-retention-and-scope",+ "outcome": "pass",+ "detail": "traversal probes refused"+ },+ {+ "id": "F-01",+ "title": "A harness can be created, updated and deleted",+ "class": "full",+ "spec": "protocol/versions/2026-08-11/harnesses.md#4-managing-harnesses",+ "outcome": "pass",+ "detail": "created, updated and deleted chrn_beb16b3632d148aabdd8164fcb98fed6"+ },+ {+ "id": "F-02",+ "title": "Creating a harness with an unsupported base is refused",+ "class": "full",+ "spec": "protocol/versions/2026-08-11/harnesses.md#41-create",+ "outcome": "pass",+ "detail": ""+ }+ ],+ "run_date": "2026-08-11"+}\ No newline at end of filediff --git a/protocol/conformance/uhp_conformance/__init__.py b/protocol/conformance/uhp_conformance/__init__.pynew file mode 100644index 00000000..2b96270a--- /dev/null+++ b/protocol/conformance/uhp_conformance/__init__.py@@ -0,0 +1,3 @@+"""UHP conformance suite — the definition of "conformant" for the Unified Harness Protocol."""+__version__ = "2026.8.11"+UHP_VERSION = "2026-08-11"diff --git a/protocol/conformance/uhp_conformance/checks.py b/protocol/conformance/uhp_conformance/checks.pynew file mode 100644index 00000000..a7d5ef4b--- /dev/null+++ b/protocol/conformance/uhp_conformance/checks.py@@ -0,0 +1,702 @@+"""The conformance checks.++Each one enforces a specific requirement of the specification and names it. Checks assert only what+the specification actually says: where the specification allows a server latitude, the check allows+it too, because a suite that enforces the reference implementation's preferences rather than the+standard's requirements would make every other implementation fail for being different rather than+for being wrong.++Running a real agent task costs money and minutes, so the two tasks this suite needs are run once+and shared by every check that inspects them.+"""+from __future__ import annotations++import base64+import json+import time+import uuid++from .registry import Skip, check++SPEC = "protocol/versions/2026-08-11"+++# ── shared fixtures ────────────────────────────────────────────────────────────────────+# Small, deterministic work: the point is to exercise the protocol, not the model.+PROMPT = "Reply with exactly: ok"+++def _harness(ctx) -> dict:+ """A harness to run against, chosen once. Prefers one the caller named."""+ if ctx.state.get("harness"):+ return ctx.state["harness"]+ r = ctx.client.get("/v1/harnesses")+ if r.status != 200 or not isinstance(r.json, dict):+ raise Skip(f"cannot list harnesses (HTTP {r.status})")+ items = r.json.get("harnesses") or []+ if not items:+ raise Skip("this server has no configured harnesses, so no task can be run")+ if ctx.harness_id:+ items = [h for h in items if h.get("id") == ctx.harness_id] or items+ ctx.state["harness"] = items[0]+ return items[0]+++def _run_blocking(ctx) -> dict:+ """One non-streaming task, run once and cached."""+ if "blocking" in ctx.state:+ return ctx.state["blocking"]+ h = _harness(ctx)+ body = {"input": PROMPT, "metadata": {"harness_id": h["id"]}, "stream": False}+ if ctx.model:+ body["model"] = ctx.model+ r = ctx.client.post("/v1/responses", body=body)+ ctx.state["blocking"] = r+ return r+++def _run_stream(ctx) -> list[dict]:+ """One streaming task, run once and cached."""+ if "stream" in ctx.state:+ return ctx.state["stream"]+ h = _harness(ctx)+ body = {"input": PROMPT, "metadata": {"harness_id": h["id"]}, "stream": True}+ if ctx.model:+ body["model"] = ctx.model+ evs = ctx.client.stream("/v1/responses", body, max_seconds=ctx.task_timeout)+ ctx.state["stream"] = evs+ return evs+++def _terminal(evs: list[dict]) -> dict | None:+ term = {"response.completed", "response.incomplete", "response.failed"}+ return next((e for e in reversed(evs) if e.get("type") in term), None)+++# ══════════════════════════════════════════════════════════════════════════════════════+# Core — discovery and version negotiation+# ══════════════════════════════════════════════════════════════════════════════════════++@check("D-01", "Discovery document is served", "core", f"{SPEC}/lifecycle.md#2-capability-discovery")+def d01(ctx):+ r = ctx.client.get("/v1/uhp", auth=False)+ assert r.status == 200, f"GET /v1/uhp returned HTTP {r.status}, expected 200"+ d = r.json+ assert isinstance(d, dict), "discovery document is not a JSON object"+ ctx.state["discovery"] = d+ return f"conformance_class={d.get('conformance_class')} versions={d.get('versions')}"+++@check("D-02", "Discovery is served without authentication", "core",+ f"{SPEC}/lifecycle.md#2-capability-discovery")+def d02(ctx):+ r = ctx.client.get("/v1/uhp", auth=False)+ assert r.status == 200, (+ f"GET /v1/uhp requires authentication (HTTP {r.status}). A client must be able to discover "+ "whether this is a UHP server before deciding what credential to present.")+++@check("D-03", "Discovery document matches the schema", "core", f"{SPEC}/schema.md")+def d03(ctx):+ d = ctx.state.get("discovery") or ctx.client.get("/v1/uhp", auth=False).json+ ctx.validate(d, "Discovery")+++@check("D-04", "default_version is one of versions", "core",+ f"{SPEC}/lifecycle.md#2-capability-discovery")+def d04(ctx):+ d = ctx.state.get("discovery") or {}+ vs, dv = d.get("versions") or [], d.get("default_version")+ assert dv in vs, f"default_version {dv!r} is not in versions {vs!r}"+++@check("D-05", "conformance_class agrees with capabilities", "core",+ f"{SPEC}/lifecycle.md#2-capability-discovery")+def d05(ctx):+ d = ctx.state.get("discovery") or {}+ cls = (d.get("conformance_class") or "").lower()+ caps = d.get("capabilities") or {}+ required = {+ "core": ["streaming", "sessions", "cancellation"],+ "extended": ["streaming", "sessions", "cancellation", "files_input", "files_output",+ "session_listing"],+ "full": ["streaming", "sessions", "cancellation", "files_input", "files_output",+ "session_listing", "harness_management"],+ }.get(cls)+ assert required is not None, f"conformance_class {cls!r} is not core, extended or full"+ missing = [c for c in required if not caps.get(c)]+ assert not missing, (+ f"server claims class {cls!r} but reports these capabilities false or absent: {missing}. "+ "A class claim that contradicts the capability list tells a client two different things.")+ return f"class={cls}"+++@check("V-01", "UHP-Version header on every response", "core",+ f"{SPEC}/lifecycle.md#1-version-negotiation")+def v01(ctx):+ r = ctx.client.get("/v1/uhp", auth=False)+ got = r.header("uhp-version")+ assert got, "response has no UHP-Version header, so a client cannot tell which contract it got"+ return f"UHP-Version: {got}"+++@check("V-02", "A supported version is honoured", "core",+ f"{SPEC}/lifecycle.md#1-version-negotiation")+def v02(ctx):+ d = ctx.state.get("discovery") or {}+ ver = (d.get("versions") or [None])[0]+ if not ver:+ raise Skip("discovery did not advertise any version")+ r = ctx.client.get("/v1/uhp", auth=False, headers={"UHP-Version": ver})+ assert r.status == 200, f"requesting the advertised version {ver!r} returned HTTP {r.status}"+ assert r.header("uhp-version") == ver, (+ f"asked for {ver!r}, server served {r.header('uhp-version')!r}")+++@check("V-03", "An unsupported version is refused, not silently substituted", "core",+ f"{SPEC}/lifecycle.md#1-version-negotiation")+def v03(ctx):+ r = ctx.client.get("/v1/uhp", auth=False, headers={"UHP-Version": "1999-01-01"})+ assert r.status == 400, (+ f"requesting an unsupported version returned HTTP {r.status}, expected 400. Serving a "+ "different version silently gives the client a body it may not be able to parse.")+ err = (r.json or {}).get("error") or {}+ assert err.get("code") == "unsupported_protocol_version", (+ f"expected code 'unsupported_protocol_version', got {err.get('code')!r}")+ supported = ((err.get("detail") or {}).get("supported")) or []+ assert supported, "error detail does not list the versions the server does support"+ return f"supported={supported}"+++# ══════════════════════════════════════════════════════════════════════════════════════+# Core — authentication and the error envelope+# ══════════════════════════════════════════════════════════════════════════════════════++@check("A-01", "Authenticated endpoints reject an absent credential", "core",+ f"{SPEC}/architecture.md#5-authentication")+def a01(ctx):+ r = ctx.client.get("/v1/harnesses", auth=False)+ assert r.status == 401, f"GET /v1/harnesses without a token returned HTTP {r.status}, expected 401"+++@check("A-02", "Authenticated endpoints reject an invalid credential", "core",+ f"{SPEC}/architecture.md#5-authentication")+def a02(ctx):+ r = ctx.client.get("/v1/harnesses", headers={"authorization": "Bearer uhp-conformance-not-a-key"})+ assert r.status == 401, f"an unknown token returned HTTP {r.status}, expected 401"+ err = (r.json or {}).get("error") or {}+ assert err.get("type") == "authentication_error", (+ f"expected error.type 'authentication_error', got {err.get('type')!r}")+++@check("E-01", "Errors use the structured envelope", "core", f"{SPEC}/errors.md#1-the-error-envelope")+def e01(ctx):+ r = ctx.client.get("/v1/harnesses/chrn_uhpconformancenosuchharness00")+ assert r.status == 404, f"unknown harness returned HTTP {r.status}, expected 404"+ ctx.validate(r.json, "ErrorEnvelope")+ err = r.json["error"]+ for f in ("type", "code", "message"):+ assert err.get(f), f"error.{f} is missing or empty"+ return f"code={err['code']}"+++@check("E-02", "Unknown harness reports harness_not_found", "core", f"{SPEC}/errors.md#31-request-and-routing")+def e02(ctx):+ r = ctx.client.get("/v1/harnesses/chrn_uhpconformancenosuchharness00")+ err = (r.json or {}).get("error") or {}+ assert err.get("code") == "harness_not_found", (+ f"expected code 'harness_not_found', got {err.get('code')!r}")+++@check("E-03", "Unknown response reports response_not_found", "core", f"{SPEC}/errors.md#31-request-and-routing")+def e03(ctx):+ r = ctx.client.get("/v1/responses/resp_uhpconformancenosuchresponse")+ assert r.status == 404, f"unknown response returned HTTP {r.status}, expected 404"+ err = (r.json or {}).get("error") or {}+ assert err.get("code") == "response_not_found", (+ f"expected code 'response_not_found', got {err.get('code')!r}")+++@check("E-04", "Error messages carry no stack traces", "core", f"{SPEC}/errors.md#1-the-error-envelope")+def e04(ctx):+ r = ctx.client.get("/v1/harnesses/chrn_uhpconformancenosuchharness00")+ msg = ((r.json or {}).get("error") or {}).get("message") or ""+ for leak in ("Traceback", "File \"/", " at ", "\n File"):+ assert leak not in msg, f"error.message leaks internals ({leak!r} present): {msg[:120]!r}"+++# ══════════════════════════════════════════════════════════════════════════════════════+# Core — harnesses and models+# ══════════════════════════════════════════════════════════════════════════════════════++@check("H-01", "Harness list is served and well formed", "core", f"{SPEC}/harnesses.md#1-discovering-harnesses")+def h01(ctx):+ r = ctx.client.get("/v1/harnesses")+ assert r.status == 200, f"GET /v1/harnesses returned HTTP {r.status}"+ assert isinstance(r.json, dict) and isinstance(r.json.get("harnesses"), list), (+ "response has no `harnesses` array")+ for h in r.json["harnesses"]:+ ctx.validate(h, "Harness")+ return f"{len(r.json['harnesses'])} harness(es)"+++@check("H-02", "A harness can be fetched by id", "core", f"{SPEC}/harnesses.md#1-discovering-harnesses")+def h02(ctx):+ h = _harness(ctx)+ r = ctx.client.get(f"/v1/harnesses/{h['id']}")+ assert r.status == 200, f"GET /v1/harnesses/{{id}} returned HTTP {r.status}"+ assert r.json.get("id") == h["id"], "returned harness has a different id than requested"+ ctx.validate(r.json, "Harness")+++@check("H-03", "Model catalogue is served and availability is a boolean", "core",+ f"{SPEC}/harnesses.md#3-models")+def h03(ctx):+ r = ctx.client.get("/v1/models")+ assert r.status == 200, f"GET /v1/models returned HTTP {r.status}"+ ctx.validate(r.json, "ModelCatalog")+ n = avail = 0+ for b in (r.json.get("backends") or {}).values():+ for m in b.get("models") or []:+ n += 1+ assert isinstance(m.get("available"), bool), (+ f"model {m.get('id')!r} has non-boolean `available` {m.get('available')!r}")+ avail += bool(m["available"])+ return f"{avail}/{n} models available"+++@check("H-04", "Per-harness model list is served", "core", f"{SPEC}/harnesses.md#3-models")+def h04(ctx):+ h = _harness(ctx)+ r = ctx.client.get(f"/v1/harnesses/{h['id']}/models")+ assert r.status == 200, f"GET /v1/harnesses/{{id}}/models returned HTTP {r.status}"+ ctx.validate(r.json, "HarnessModels")+++# ══════════════════════════════════════════════════════════════════════════════════════+# Core — running a task+# ══════════════════════════════════════════════════════════════════════════════════════++@check("T-01", "A non-streaming task returns a valid Response", "core", f"{SPEC}/tasks.md#3-the-response-object")+def t01(ctx):+ r = _run_blocking(ctx)+ assert r.status == 200, f"POST /v1/responses returned HTTP {r.status}: {r.body[:200]!r}"+ ctx.validate(r.json, "Response")+ return f"status={r.json.get('status')} in {r.elapsed_s:.1f}s"+++@check("T-02", "A finished task is in a terminal state", "core", f"{SPEC}/lifecycle.md#3-task-lifecycle")+def t02(ctx):+ r = _run_blocking(ctx)+ st = (r.json or {}).get("status")+ assert st in {"completed", "failed", "incomplete", "cancelled"}, (+ f"a returned non-streaming task has non-terminal status {st!r}")+++@check("T-03", "The response names the model that actually ran", "core", f"{SPEC}/tasks.md#13-model-selection-and-substitution")+def t03(ctx):+ r = _run_blocking(ctx)+ d = r.json or {}+ assert d.get("model"), "response has no `model`, so a client cannot tell what ran"+ meta = d.get("metadata") or {}+ if meta.get("requested_model") and meta["requested_model"] != d["model"]:+ assert meta.get("model_fallback") is True, (+ "the server substituted a model but did not set metadata.model_fallback")+ return f"substituted {meta['requested_model']} -> {d['model']} (correctly reported)"+ return f"model={d['model']}"+++@check("T-04", "The response reports its session", "core", f"{SPEC}/lifecycle.md#4-session-lifecycle")+def t04(ctx):+ r = _run_blocking(ctx)+ sid = ((r.json or {}).get("metadata") or {}).get("session_id")+ assert sid, "response metadata has no session_id, so the session cannot be continued or inspected"+ ctx.state["session_id"] = sid+ return f"session_id={sid}"+++@check("T-05", "usage is an object or explicitly null, never fabricated", "core",+ f"{SPEC}/tasks.md#3-the-response-object")+def t05(ctx):+ r = _run_blocking(ctx)+ d = r.json or {}+ assert "usage" in d, "response has no `usage` key at all"+ u = d["usage"]+ assert u is None or isinstance(u, dict), f"usage is neither null nor an object: {type(u).__name__}"+++@check("T-06", "A stored response can be read back", "core", f"{SPEC}/tasks.md#4-reading-a-task-back")+def t06(ctx):+ r = _run_blocking(ctx)+ rid = (r.json or {}).get("id")+ if not rid:+ raise Skip("the task did not return an id")+ got = ctx.client.get(f"/v1/responses/{rid}")+ assert got.status == 200, f"GET /v1/responses/{{id}} returned HTTP {got.status}"+ assert got.json.get("id") == rid, "read-back returned a different id"+ assert got.json.get("status") == r.json.get("status"), (+ "read-back status differs from the status the task returned; terminal states must not change")+++@check("T-07", "Response ids are prefixed", "core", f"{SPEC}/architecture.md#3-object-model")+def t07(ctx):+ rid = (_run_blocking(ctx).json or {}).get("id") or ""+ assert rid.startswith("resp_"), f"response id {rid!r} is not `resp_`-prefixed"+++# ══════════════════════════════════════════════════════════════════════════════════════+# Core — streaming+# ══════════════════════════════════════════════════════════════════════════════════════++@check("S-01", "A streaming task emits events", "core", f"{SPEC}/streaming.md#1-opening-a-stream")+def s01(ctx):+ evs = _run_stream(ctx)+ assert evs, (f"the stream produced no events "+ f"(HTTP {getattr(ctx.client, 'stream_status', '?')}: "+ f"{getattr(ctx.client, 'stream_error', '')[:200]})")+ return f"{len(evs)} events"+++@check("S-02", "Stream content type is text/event-stream", "core", f"{SPEC}/streaming.md#1-opening-a-stream")+def s02(ctx):+ _run_stream(ctx)+ ct = (getattr(ctx.client, "stream_headers", {}) or {}).get("content-type", "")+ assert "text/event-stream" in ct, f"stream Content-Type is {ct!r}, expected text/event-stream"+++@check("S-03", "Every event validates against the schema", "core", f"{SPEC}/schema.md")+def s03(ctx):+ evs = _run_stream(ctx)+ if not evs:+ raise Skip("no events to validate")+ for e in evs:+ ctx.validate({k: v for k, v in e.items() if k != "__t"}, "Event")+ return f"{len(evs)} events valid"+++@check("S-04", "sequence_number starts at 0 and has no gaps", "core",+ f"{SPEC}/streaming.md#3-ordering-guarantees")+def s04(ctx):+ evs = _run_stream(ctx)+ if not evs:+ raise Skip("no events to check")+ seqs = [e.get("sequence_number") for e in evs]+ assert all(isinstance(s, int) for s in seqs), "some events have no integer sequence_number"+ assert seqs[0] == 0, f"first sequence_number is {seqs[0]}, expected 0"+ expected = list(range(len(seqs)))+ assert seqs == expected, (+ f"sequence_number is not gapless and monotonic; first divergence at index "+ f"{next(i for i, (a, b) in enumerate(zip(seqs, expected)) if a != b)}. "+ "A client cannot distinguish a dropped event from a server that skips numbers.")+++@check("S-05", "The first event is response.created", "core", f"{SPEC}/streaming.md#3-ordering-guarantees")+def s05(ctx):+ evs = _run_stream(ctx)+ if not evs:+ raise Skip("no events to check")+ assert evs[0].get("type") == "response.created", (+ f"first event is {evs[0].get('type')!r}, expected 'response.created'")+++@check("S-06", "The stream ends with exactly one terminal event", "core",+ f"{SPEC}/streaming.md#4-terminal-events")+def s06(ctx):+ evs = _run_stream(ctx)+ if not evs:+ raise Skip("no events to check")+ term = {"response.completed", "response.incomplete", "response.failed"}+ finals = [e for e in evs if e.get("type") in term]+ assert len(finals) == 1, f"found {len(finals)} terminal events, expected exactly 1"+ assert evs[-1].get("type") in term, (+ f"the last event is {evs[-1].get('type')!r}, not a terminal event")+ return f"terminal={finals[0]['type']}"+++@check("S-07", "The terminal event carries the complete response", "core",+ f"{SPEC}/streaming.md#4-terminal-events")+def s07(ctx):+ evs = _run_stream(ctx)+ t = _terminal(evs)+ if not t:+ raise Skip("no terminal event")+ resp = t.get("response")+ assert isinstance(resp, dict), "the terminal event has no `response` object"+ ctx.validate(resp, "Response")+ assert resp.get("status") in {"completed", "failed", "incomplete", "cancelled"}, (+ f"terminal response has non-terminal status {resp.get('status')!r}")+++@check("S-08", "Streaming and non-streaming agree on the result shape", "core",+ f"{SPEC}/streaming.md#6-non-streaming")+def s08(ctx):+ b = (_run_blocking(ctx).json or {})+ t = _terminal(_run_stream(ctx)) or {}+ sresp = t.get("response") or {}+ if not b or not sresp:+ raise Skip("need both a streaming and a non-streaming result")+ for f in ("object", "status"):+ assert f in b and f in sresp, f"{f!r} missing from one of the two paths"+ assert b.get("object") == sresp.get("object") == "response", (+ "the two paths do not both return `object: response`")+++@check("S-09", "The stream is progressive, not buffered to the end", "core",+ f"{SPEC}/streaming.md#1-opening-a-stream")+def s09(ctx):+ evs = _run_stream(ctx)+ if len(evs) < 3:+ raise Skip("too few events to judge progressiveness")+ first, last = evs[0].get("__t", 0), evs[-1].get("__t", 0)+ if last < 0.5:+ raise Skip(f"the whole task finished in {last:.2f}s — too fast to distinguish buffering")+ spread = last - first+ assert spread > 0.05, (+ f"all {len(evs)} events arrived within {spread*1000:.0f}ms of each other after {last:.1f}s. "+ "The stream appears to be buffered and flushed at the end, which a client cannot "+ "distinguish from a hang. Check for response buffering in a proxy.")+ return f"events spread over {spread:.1f}s"+++# ══════════════════════════════════════════════════════════════════════════════════════+# Core — sessions and cancellation+# ══════════════════════════════════════════════════════════════════════════════════════++@check("C-01", "A task can continue a session", "core", f"{SPEC}/sessions.md#1-continuing-a-session")+def c01(ctx):+ first = _run_blocking(ctx)+ rid = (first.json or {}).get("id")+ sid = ((first.json or {}).get("metadata") or {}).get("session_id")+ if not rid or not sid:+ raise Skip("the first task did not return an id and session_id")+ h = _harness(ctx)+ body = {"input": "Reply with exactly: two", "previous_response_id": rid,+ "metadata": {"harness_id": h["id"]}, "stream": False}+ r = ctx.client.post("/v1/responses", body=body)+ assert r.status == 200, f"continuation returned HTTP {r.status}: {r.body[:200]!r}"+ got = ((r.json or {}).get("metadata") or {}).get("session_id")+ assert got == sid, f"continuation ran in session {got!r}, expected the original {sid!r}"+ assert (r.json or {}).get("previous_response_id") == rid, (+ "the continuation does not report the response it continued")+ ctx.state["second_response"] = r.json+ return f"session {sid} extended"+++@check("C-02", "Cancelling a terminal task succeeds and changes nothing", "core",+ f"{SPEC}/sessions.md#4-cancelling")+def c02(ctx):+ rid = (_run_blocking(ctx).json or {}).get("id")+ if not rid:+ raise Skip("no response to cancel")+ before = ctx.client.get(f"/v1/responses/{rid}").json or {}+ r = ctx.client.post(f"/v1/responses/{rid}/cancel")+ assert r.status in (200, 409), (+ f"cancelling a terminal task returned HTTP {r.status}; a client retrying a cancel after a "+ "dropped connection must not be punished for having succeeded")+ after = ctx.client.get(f"/v1/responses/{rid}").json or {}+ assert after.get("status") == before.get("status"), (+ f"cancel changed a terminal status from {before.get('status')!r} to {after.get('status')!r}")+++@check("C-03", "A running task can be cancelled and ends non-running", "core",+ f"{SPEC}/sessions.md#4-cancelling")+def c03(ctx):+ h = _harness(ctx)+ body = {"input": "Count slowly from 1 to 200, one number per line.",+ "metadata": {"harness_id": h["id"]}, "stream": False, "background": True}+ if ctx.model:+ body["model"] = ctx.model+ started = ctx.client.post("/v1/responses", body=body)+ rid = (started.json or {}).get("id")+ if started.status != 200 or not rid:+ raise Skip(f"could not start a cancellable task (HTTP {started.status})")+ time.sleep(2.0)+ r = ctx.client.post(f"/v1/responses/{rid}/cancel")+ assert r.status == 200, f"cancel returned HTTP {r.status}"+ deadline = time.time() + 90+ last = ""+ while time.time() < deadline:+ last = (ctx.client.get(f"/v1/responses/{rid}").json or {}).get("status", "")+ if last in {"cancelled", "completed", "failed", "incomplete"}:+ break+ time.sleep(2.0)+ assert last in {"cancelled", "completed", "failed", "incomplete"}, (+ f"the task was still {last!r} 90s after being cancelled; cancellation must reach a terminal state")+ return f"final status={last}"+++# ══════════════════════════════════════════════════════════════════════════════════════+# Extended — sessions, files, artifacts+# ══════════════════════════════════════════════════════════════════════════════════════++@check("X-01", "Sessions can be listed", "extended", f"{SPEC}/sessions.md#2-listing-sessions")+def x01(ctx):+ r = ctx.client.get("/v1/sessions?limit=5")+ assert r.status == 200, f"GET /v1/sessions returned HTTP {r.status}"+ d = r.json or {}+ key = "sessions" if "sessions" in d else next((k for k, v in d.items() if isinstance(v, list)), None)+ assert key, f"no array of sessions in the response (keys: {list(d)[:6]})"+ return f"{len(d[key])} session(s)"+++@check("X-02", "Session listing reports the end of pagination explicitly", "extended",+ f"{SPEC}/sessions.md#2-listing-sessions")+def x02(ctx):+ d = ctx.client.get("/v1/sessions?limit=5").json or {}+ assert any(k in d for k in ("next_cursor", "cursor", "has_more")), (+ "the listing has no pagination marker, so a client must guess the end from a short page — "+ "a heuristic that is wrong whenever a page is exactly full")+++@check("X-03", "A session can be inspected", "extended", f"{SPEC}/sessions.md#3-inspecting-a-session")+def x03(ctx):+ sid = ctx.state.get("session_id")+ if not sid:+ raise Skip("no session id from an earlier task")+ r = ctx.client.get(f"/v1/sessions/{sid}")+ assert r.status == 200, f"GET /v1/sessions/{{id}} returned HTTP {r.status}"+++@check("X-04", "A session's turn history is available", "extended",+ f"{SPEC}/sessions.md#3-inspecting-a-session")+def x04(ctx):+ sid = ctx.state.get("session_id")+ if not sid:+ raise Skip("no session id from an earlier task")+ r = ctx.client.get(f"/v1/sessions/{sid}/turns")+ assert r.status == 200, f"GET /v1/sessions/{{id}}/turns returned HTTP {r.status}"+++@check("X-05", "A file can be sent as task input", "extended", f"{SPEC}/files.md#1-sending-files-in")+def x05(ctx):+ h = _harness(ctx)+ token = f"uhp-{uuid.uuid4().hex[:8]}"+ data = base64.b64encode(f"The secret token is {token}.".encode()).decode()+ body = {+ "input": [{"role": "user", "content": [+ {"type": "input_text", "text": "Reply with only the secret token from the attached file."},+ {"type": "input_file", "filename": "token.txt",+ "file_data": f"data:text/plain;base64,{data}"}]}],+ "metadata": {"harness_id": h["id"]}, "stream": False,+ }+ if ctx.model:+ body["model"] = ctx.model+ r = ctx.client.post("/v1/responses", body=body)+ assert r.status == 200, f"a task with an inline file returned HTTP {r.status}: {r.body[:200]!r}"+ ctx.validate(r.json, "Response")+ text = json.dumps(r.json.get("output") or [])+ ctx.state["file_input_echoed"] = token in text+ return ("the harness read the file and echoed the token" if token in text+ else "accepted (the harness did not echo the token, which the protocol does not require)")+++def _session_with_artifact(ctx) -> str:+ """A session that has actually produced a file, so the artifact checks test something.++ Reusing the plain text task would leave the artifact checks permanently skipped, which reads as+ "fine" in a report and verifies nothing.+ """+ if "artifact_session" in ctx.state:+ return ctx.state["artifact_session"]+ h = _harness(ctx)+ body = {"input": "Create a file named uhp-conformance.txt containing exactly: artifact-ok",+ "metadata": {"harness_id": h["id"]}, "stream": False}+ if ctx.model:+ body["model"] = ctx.model+ r = ctx.client.post("/v1/responses", body=body)+ sid = ((r.json or {}).get("metadata") or {}).get("session_id") or ctx.state.get("session_id")+ if not sid:+ raise Skip(f"could not run a task that writes a file (HTTP {r.status})")+ ctx.state["artifact_session"] = sid+ return sid+++@check("X-06", "Artifacts of a session can be listed", "extended", f"{SPEC}/files.md#22-by-listing-the-session")+def x06(ctx):+ sid = _session_with_artifact(ctx)+ if not sid:+ raise Skip("no session id from an earlier task")+ r = ctx.client.get(f"/v1/sessions/{sid}/files")+ assert r.status == 200, f"GET /v1/sessions/{{id}}/files returned HTTP {r.status}"+ d = r.json or {}+ files = d.get("files") if isinstance(d.get("files"), list) else None+ assert files is not None, f"no `files` array in the response (keys: {list(d)[:6]})"+ ctx.state["artifacts"] = files+ return f"{len(files)} artifact(s)"+++@check("X-07", "An artifact downloads as raw bytes with nosniff", "extended", f"{SPEC}/files.md#3-downloading")+def x07(ctx):+ arts = ctx.state.get("artifacts")+ if not arts:+ raise Skip("this session produced no artifacts to download")+ a = arts[0]+ cid, fid = a.get("container_id"), a.get("id") or a.get("file_id")+ if not cid or not fid:+ raise Skip(f"artifact has no container_id/file_id (keys: {list(a)[:6]})")+ r = ctx.client.get(f"/v1/containers/{cid}/files/{fid}/content")+ assert r.status == 200, f"artifact download returned HTTP {r.status}"+ assert r.header("x-content-type-options").lower() == "nosniff", (+ "artifact download is missing `X-Content-Type-Options: nosniff`. Artifacts are "+ "attacker-influenceable content; serving them without it is stored XSS against the client's origin.")+ return f"{len(r.body)} bytes, {r.header('content-type')}"+++@check("X-08", "Artifact ids do not traverse outside their container", "extended",+ f"{SPEC}/files.md#5-retention-and-scope")+def x08(ctx):+ arts = ctx.state.get("artifacts")+ cid = (arts[0].get("container_id") if arts else None) or "cntr_uhpconformance"+ for probe in ("../../etc/passwd", "..%2f..%2fetc%2fpasswd"):+ r = ctx.client.get(f"/v1/containers/{cid}/files/{probe}/content")+ assert r.status in (400, 403, 404), (+ f"a traversal probe returned HTTP {r.status}; expected it to be refused")+ assert b"root:" not in r.body, "a traversal probe returned /etc/passwd content"+ return "traversal probes refused"+++# ══════════════════════════════════════════════════════════════════════════════════════+# Full — harness lifecycle+# ══════════════════════════════════════════════════════════════════════════════════════++@check("F-01", "A harness can be created, updated and deleted", "full",+ f"{SPEC}/harnesses.md#4-managing-harnesses")+def f01(ctx):+ # Ask the server which bases it supports rather than copying one off an existing harness: an+ # earlier run (or another client) may have left a harness whose base this server cannot run,+ # and that would make this check fail for the wrong reason.+ probe = ctx.client.post("/v1/harnesses", body={"name": "uhp-conformance-probe",+ "base": "uhp-conformance-unknown-base"})+ supported = (((probe.json or {}).get("error") or {}).get("detail") or {}).get("supported") or []+ if probe.status == 200: # the server accepted it; clean up and fall back+ ctx.client.delete(f"/v1/harnesses/{(probe.json or {}).get('id')}")+ base = (supported or [(_harness(ctx)).get("base") or "claude-code"])[0]+ created = ctx.client.post("/v1/harnesses", body={+ "name": f"uhp-conformance-{uuid.uuid4().hex[:6]}", "base": base})+ assert created.status == 200, f"create returned HTTP {created.status}: {created.body[:200]!r}"+ hid = (created.json or {}).get("id")+ assert hid, "create did not return an id"+ ctx.validate(created.json, "Harness")+ try:+ upd = ctx.client.put(f"/v1/harnesses/{hid}", body={"name": "uhp-conformance-renamed",+ "base": base})+ assert upd.status == 200, f"update returned HTTP {upd.status}"+ assert (upd.json or {}).get("base") == base, "update changed the harness base, which is immutable"+ finally:+ gone = ctx.client.delete(f"/v1/harnesses/{hid}")+ assert gone.status in (200, 204), f"delete returned HTTP {gone.status}"+ after = ctx.client.get(f"/v1/harnesses/{hid}")+ assert after.status == 404, f"a deleted harness still resolves (HTTP {after.status})"+ return f"created, updated and deleted {hid}"+++@check("F-02", "Creating a harness with an unsupported base is refused", "full",+ f"{SPEC}/harnesses.md#41-create")+def f02(ctx):+ r = ctx.client.post("/v1/harnesses", body={"name": "uhp-conformance-bad-base",+ "base": "definitely-not-a-real-harness"})+ assert r.status in (400, 422), (+ f"an unsupported base returned HTTP {r.status}; expected it to be refused. A server that "+ "accepts a base it cannot run fails at task time instead, after the client has committed.")+ if r.status == 200: # defensive: clean up if the server accepted it after all+ ctx.client.delete(f"/v1/harnesses/{(r.json or {}).get('id')}")diff --git a/protocol/conformance/uhp_conformance/cli.py b/protocol/conformance/uhp_conformance/cli.pynew file mode 100644index 00000000..fd579f91--- /dev/null+++ b/protocol/conformance/uhp_conformance/cli.py@@ -0,0 +1,66 @@+"""`uhp-conformance` — run the suite against a server."""+from __future__ import annotations++import argparse+import os+import sys++from . import UHP_VERSION, checks # noqa: F401 — importing checks populates the registry+from .client import Client+from .context import Context+from .registry import CLASSES, Outcome, checks_for+from .report import render, to_json+++def main(argv=None) -> int:+ p = argparse.ArgumentParser(+ prog="uhp-conformance",+ description=f"Run the Unified Harness Protocol {UHP_VERSION} conformance suite "+ f"against a server.")+ p.add_argument("--base-url", required=True,+ help="Server root, e.g. https://host or http://127.0.0.1:3000/api/harness")+ p.add_argument("--api-key", default=os.environ.get("UHP_API_KEY", ""),+ help="Bearer token (or set UHP_API_KEY)")+ p.add_argument("--class", dest="cls", default="core", choices=CLASSES,+ help="Conformance class to test (cumulative). Default: core")+ p.add_argument("--harness-id", default="", help="Run tasks against this harness id")+ p.add_argument("--model", default="", help="Run tasks with this model")+ p.add_argument("--task-timeout", type=float, default=300.0,+ help="Seconds to allow one agent task. Default: 300")+ p.add_argument("--json", dest="json_out", default="", help="Write a JSON report to this path")+ p.add_argument("--only", default="", help="Comma-separated check ids to run")+ p.add_argument("--plain", action="store_true", help="No ANSI colour")+ a = p.parse_args(argv)++ ctx = Context(client=Client(a.base_url, a.api_key), harness_id=a.harness_id,+ model=a.model, task_timeout=a.task_timeout)++ selected = checks_for(a.cls)+ if a.only:+ want = {s.strip().upper() for s in a.only.split(",") if s.strip()}+ selected = [c for c in selected if c.id.upper() in want]+ if not selected:+ print(f"no checks matched --only {a.only!r}", file=sys.stderr)+ return 2++ results = []+ for c in selected:+ results.append(c.run(ctx))+ if not a.plain:+ print(".", end="", flush=True)+ if not a.plain:+ print("\r", end="")++ print(render(results, a.base_url, a.cls, plain=a.plain))++ if a.json_out:+ with open(a.json_out, "w") as f:+ f.write(to_json(results, a.base_url, a.cls) + "\n")+ print(f" JSON report: {a.json_out}\n")++ bad = sum(1 for r in results if r.outcome in (Outcome.FAIL, Outcome.ERROR))+ return 1 if bad else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/protocol/conformance/uhp_conformance/client.py b/protocol/conformance/uhp_conformance/client.pynew file mode 100644index 00000000..4a39eecd--- /dev/null+++ b/protocol/conformance/uhp_conformance/client.py@@ -0,0 +1,130 @@+"""A deliberately thin HTTP client.++The suite tests a server, so it must not paper over anything a server does. This client therefore+does no retrying, no redirect chasing, and no error raising — every check sees the exact status,+headers and body the server sent, including the malformed ones.+"""+from __future__ import annotations++import json+import time+import urllib.error+import urllib.request+from dataclasses import dataclass, field+++@dataclass+class Result:+ status: int+ headers: dict+ body: bytes+ elapsed_s: float+ url: str+ method: str++ @property+ def json(self):+ """Parsed body, or None when it is not JSON. Never raises: a server returning HTML where+ JSON was promised is a finding to report, not an exception to crash the run."""+ try:+ return json.loads(self.body.decode("utf-8"))+ except Exception: # noqa: BLE001+ return None++ def header(self, name: str) -> str:+ return self.headers.get(name.lower(), "")+++@dataclass+class Client:+ base_url: str+ api_key: str = ""+ timeout: float = 300.0+ calls: list = field(default_factory=list)++ def _url(self, path: str) -> str:+ return f"{self.base_url.rstrip('/')}{path}"++ def request(self, method: str, path: str, *, body=None, headers=None,+ auth: bool = True, raw: bytes | None = None, content_type: str | None = None) -> Result:+ url = self._url(path)+ h = {"accept": "application/json"}+ if auth and self.api_key:+ h["authorization"] = f"Bearer {self.api_key}"+ if body is not None:+ raw = json.dumps(body).encode()+ h["content-type"] = "application/json"+ if content_type:+ h["content-type"] = content_type+ h.update({k.lower(): v for k, v in (headers or {}).items()})++ req = urllib.request.Request(url, data=raw, method=method, headers=h)+ t0 = time.time()+ try:+ with urllib.request.urlopen(req, timeout=self.timeout) as r:+ res = Result(r.status, {k.lower(): v for k, v in r.headers.items()},+ r.read(), time.time() - t0, url, method)+ except urllib.error.HTTPError as e:+ res = Result(e.code, {k.lower(): v for k, v in (e.headers or {}).items()},+ e.read(), time.time() - t0, url, method)+ except Exception as e: # noqa: BLE001 — a transport failure is a result, not a crash+ res = Result(0, {}, str(e).encode(), time.time() - t0, url, method)+ self.calls.append(res)+ return res++ def get(self, path, **kw):+ return self.request("GET", path, **kw)++ def post(self, path, **kw):+ return self.request("POST", path, **kw)++ def put(self, path, **kw):+ return self.request("PUT", path, **kw)++ def delete(self, path, **kw):+ return self.request("DELETE", path, **kw)++ def stream(self, path: str, body: dict, *, headers=None, max_seconds: float = 300.0) -> list[dict]:+ """POST and read Server-Sent Events, returning the parsed `data:` objects in arrival order.++ Reads incrementally rather than buffering the whole body, so a server that only flushes at+ the end is measurable (see the streaming-progressiveness check) instead of indistinguishable+ from a fast one.+ """+ url = self._url(path)+ h = {"accept": "text/event-stream", "content-type": "application/json"}+ if self.api_key:+ h["authorization"] = f"Bearer {self.api_key}"+ h.update({k.lower(): v for k, v in (headers or {}).items()})+ req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", headers=h)++ events: list[dict] = []+ t0 = time.time()+ try:+ with urllib.request.urlopen(req, timeout=max_seconds) as r:+ self.stream_headers = {k.lower(): v for k, v in r.headers.items()}+ self.stream_status = r.status+ buf = b""+ for chunk in r:+ buf += chunk+ while b"\n\n" in buf:+ raw, _, buf = buf.partition(b"\n\n")+ for line in raw.split(b"\n"):+ if line.startswith(b"data:"):+ try:+ ev = json.loads(line[5:].strip().decode("utf-8"))+ except Exception: # noqa: BLE001+ continue+ ev["__t"] = time.time() - t0 # arrival time, for progressiveness+ events.append(ev)+ if time.time() - t0 > max_seconds:+ break+ except urllib.error.HTTPError as e:+ self.stream_status = e.code+ self.stream_headers = {k.lower(): v for k, v in (e.headers or {}).items()}+ self.stream_error = e.read().decode("utf-8", "replace")[:500]+ except Exception as e: # noqa: BLE001+ self.stream_status = 0+ self.stream_headers = {}+ self.stream_error = str(e)[:500]+ return eventsdiff --git a/protocol/conformance/uhp_conformance/context.py b/protocol/conformance/uhp_conformance/context.pynew file mode 100644index 00000000..aad8048c--- /dev/null+++ b/protocol/conformance/uhp_conformance/context.py@@ -0,0 +1,49 @@+"""What a check is handed: a client, a schema validator, and state shared between checks."""+from __future__ import annotations++import json+import pathlib+from dataclasses import dataclass, field++try:+ import jsonschema+except ImportError: # pragma: no cover+ jsonschema = None++from .client import Client++SCHEMA_PATH = (pathlib.Path(__file__).resolve().parents[2]+ / "schema" / "uhp-2026-08-11.schema.json")+++@dataclass+class Context:+ client: Client+ harness_id: str = ""+ model: str = ""+ task_timeout: float = 300.0+ state: dict = field(default_factory=dict)+ _schema: dict | None = None++ def validate(self, instance, definition: str) -> None:+ """Validate `instance` against a `$defs` entry, or skip loudly if that is impossible.++ A missing validator must never look like a pass, so this raises Skip rather than returning+ quietly — an unrunnable check is reported as unrun.+ """+ from .registry import Skip+ if jsonschema is None:+ raise Skip("jsonschema is not installed, so schema validation cannot run")+ if self._schema is None:+ if not SCHEMA_PATH.exists():+ raise Skip(f"schema not found at {SCHEMA_PATH}")+ self._schema = json.loads(SCHEMA_PATH.read_text())+ doc = {**self._schema, "$ref": f"#/$defs/{definition}"}+ errors = sorted(jsonschema.Draft202012Validator(doc).iter_errors(instance),+ key=lambda e: list(e.path))+ if errors:+ e = errors[0]+ where = "/".join(str(p) for p in e.path) or "(root)"+ raise AssertionError(+ f"does not match schema {definition}: at {where}: {e.message[:200]}"+ + (f" (+{len(errors)-1} more)" if len(errors) > 1 else ""))diff --git a/protocol/conformance/uhp_conformance/registry.py b/protocol/conformance/uhp_conformance/registry.pynew file mode 100644index 00000000..0a1696d8--- /dev/null+++ b/protocol/conformance/uhp_conformance/registry.py@@ -0,0 +1,83 @@+"""The check registry and result model.++A check has four possible outcomes and each one means something different:++ PASS — the behaviour the specification requires was observed.+ FAIL — the behaviour was observed to be wrong. This is a conformance defect.+ SKIP — the check could not run, and the reason is recorded. A skip is never a pass: a report+ that hides skips behind a green summary is how a suite starts lying.+ ERROR — the check itself broke. A bug in the suite, not necessarily in the server.++Every check states the section of the specification it enforces, so a failure points at the sentence+it violates rather than at a test name.+"""+from __future__ import annotations++import traceback+from dataclasses import dataclass, field+from enum import Enum++CLASSES = ("core", "extended", "full")+++class Outcome(str, Enum):+ PASS = "pass"+ FAIL = "fail"+ SKIP = "skip"+ ERROR = "error"+++class Skip(Exception):+ """Raised by a check that cannot run. The message is the reason, shown in the report."""+++@dataclass+class CheckResult:+ id: str+ title: str+ cls: str+ spec: str+ outcome: Outcome+ detail: str = ""+ evidence: dict = field(default_factory=dict)+++@dataclass+class Check:+ id: str+ title: str+ cls: str+ spec: str+ fn: callable++ def run(self, ctx) -> CheckResult:+ try:+ detail = self.fn(ctx) or ""+ return CheckResult(self.id, self.title, self.cls, self.spec, Outcome.PASS, detail)+ except Skip as e:+ return CheckResult(self.id, self.title, self.cls, self.spec, Outcome.SKIP, str(e))+ except AssertionError as e:+ return CheckResult(self.id, self.title, self.cls, self.spec, Outcome.FAIL, str(e))+ except Exception as e: # noqa: BLE001+ return CheckResult(self.id, self.title, self.cls, self.spec, Outcome.ERROR,+ f"{type(e).__name__}: {e}",+ {"traceback": traceback.format_exc()[-1500:]})+++REGISTRY: list[Check] = []+++def check(id: str, title: str, cls: str, spec: str):+ """Register a check. `cls` is the lowest conformance class that requires the behaviour."""+ assert cls in CLASSES, f"unknown conformance class {cls!r}"++ def deco(fn):+ REGISTRY.append(Check(id, title, cls, spec, fn))+ return fn+ return deco+++def checks_for(cls: str) -> list[Check]:+ """Every check required at `cls`, since the classes are cumulative."""+ upto = CLASSES[: CLASSES.index(cls) + 1]+ return [c for c in REGISTRY if c.cls in upto]diff --git a/protocol/conformance/uhp_conformance/report.py b/protocol/conformance/uhp_conformance/report.pynew file mode 100644index 00000000..4dadedc2--- /dev/null+++ b/protocol/conformance/uhp_conformance/report.py@@ -0,0 +1,103 @@+"""Rendering a run. Human-readable to a terminal, machine-readable to JSON."""+from __future__ import annotations++import json+from .registry import CLASSES, Outcome++GREEN, RED, YELLOW, GREY, BOLD, RESET = (+ "\033[32m", "\033[31m", "\033[33m", "\033[90m", "\033[1m", "\033[0m")+MARK = {Outcome.PASS: f"{GREEN}PASS{RESET}", Outcome.FAIL: f"{RED}FAIL{RESET}",+ Outcome.SKIP: f"{YELLOW}SKIP{RESET}", Outcome.ERROR: f"{RED}ERR {RESET}"}+++def render(results, target: str, cls: str, plain: bool = False) -> str:+ def c(s, colour):+ return s if plain else f"{colour}{s}{RESET}"++ mark = ({o: {Outcome.PASS: "PASS", Outcome.FAIL: "FAIL", Outcome.SKIP: "SKIP",+ Outcome.ERROR: "ERR "}[o] for o in Outcome} if plain else MARK)++ lines = [""]+ lines.append(c(f"UHP conformance — {target}", BOLD))+ lines.append(f"protocol 2026-08-11 · requested class: {cls}")+ lines.append("")++ for k in CLASSES[: CLASSES.index(cls) + 1]:+ group = [r for r in results if r.cls == k]+ if not group:+ continue+ lines.append(c(f" {k.upper()}", BOLD))+ for r in group:+ line = f" {mark[r.outcome]} {r.id:<5} {r.title}"+ if r.detail and r.outcome is Outcome.PASS:+ line += c(f" — {r.detail}", GREY)+ lines.append(line)+ if r.outcome in (Outcome.FAIL, Outcome.ERROR):+ for chunk in _wrap(r.detail, 92):+ lines.append(c(f" {chunk}", RED))+ lines.append(c(f" spec: {r.spec}", GREY))+ elif r.outcome is Outcome.SKIP:+ lines.append(c(f" {r.detail}", YELLOW))+ lines.append("")++ n = {o: sum(1 for r in results if r.outcome is o) for o in Outcome}+ total = len(results)+ lines.append(c(" Summary", BOLD))+ lines.append(f" {n[Outcome.PASS]}/{total} passed · {n[Outcome.FAIL]} failed · "+ f"{n[Outcome.SKIP]} skipped · {n[Outcome.ERROR]} errored")++ achieved = highest_class(results)+ if n[Outcome.FAIL] or n[Outcome.ERROR]:+ lines.append(c(f" NOT CONFORMANT at class '{cls}'", RED))+ if achieved:+ lines.append(f" Highest class fully passed: {achieved}")+ else:+ lines.append(c(f" CONFORMANT — UHP 2026-08-11 ({cls})", GREEN))+ if n[Outcome.SKIP]:+ lines.append(c(" Note: skipped checks were not verified. A skip is not a pass.", YELLOW))+ lines.append("")+ return "\n".join(lines)+++def highest_class(results) -> str:+ """The highest class with no failures or errors, counting the classes below it too."""+ best = ""+ for k in CLASSES:+ upto = CLASSES[: CLASSES.index(k) + 1]+ group = [r for r in results if r.cls in upto]+ if not group:+ continue+ if any(r.outcome in (Outcome.FAIL, Outcome.ERROR) for r in group):+ break+ best = k+ return best+++def _wrap(text: str, width: int):+ words, line = (text or "").split(), ""+ out = []+ for w in words:+ if len(line) + len(w) + 1 > width:+ out.append(line)+ line = w+ else:+ line = f"{line} {w}".strip()+ if line:+ out.append(line)+ return out or [""]+++def to_json(results, target: str, cls: str) -> str:+ n = {o.value: sum(1 for r in results if r.outcome is o) for o in Outcome}+ return json.dumps({+ "protocol": "uhp",+ "protocol_version": "2026-08-11",+ "target": target,+ "requested_class": cls,+ "conformant": n["fail"] == 0 and n["error"] == 0,+ "highest_class_passed": highest_class(results),+ "summary": {**n, "total": len(results)},+ "checks": [{"id": r.id, "title": r.title, "class": r.cls, "spec": r.spec,+ "outcome": r.outcome.value, "detail": r.detail, **r.evidence}+ for r in results],+ }, indent=2)diff --git a/protocol/schema/build.py b/protocol/schema/build.pynew file mode 100644index 00000000..1e66e382--- /dev/null+++ b/protocol/schema/build.py@@ -0,0 +1,76 @@+#!/usr/bin/env python3+"""Derive the JSON Schema document from the OpenAPI document.++The two files describe the same objects. Maintaining both by hand guarantees they drift, and a+client generated from one would then disagree with a validator built on the other — the kind of+inconsistency a standard exists to prevent. So the OpenAPI document is the source, and this script+produces the JSON Schema from it.++ python protocol/schema/build.py # write the JSON Schema+ python protocol/schema/build.py --check # fail if it is out of date (for CI)++`components.schemas` maps to `$defs`, and internal references are rewritten from OpenAPI's+`#/components/schemas/X` to JSON Schema's `#/$defs/X`. Nothing else is transformed: the subset of+OpenAPI 3.1 used here is JSON Schema 2020-12 by construction, which is why 3.1 was chosen.+"""+from __future__ import annotations++import json+import pathlib+import sys++try:+ import yaml+except ImportError: # pragma: no cover - environment guidance, not logic+ sys.exit("PyYAML is required: pip install pyyaml")++HERE = pathlib.Path(__file__).parent+VERSION = "2026-08-11"+SRC = HERE / f"uhp-{VERSION}.openapi.yaml"+OUT = HERE / f"uhp-{VERSION}.schema.json"+++def rewrite_refs(node):+ """`#/components/schemas/X` (OpenAPI) -> `#/$defs/X` (JSON Schema)."""+ if isinstance(node, dict):+ return {+ k: (v.replace("#/components/schemas/", "#/$defs/")+ if k == "$ref" and isinstance(v, str) else rewrite_refs(v))+ for k, v in node.items()+ }+ if isinstance(node, list):+ return [rewrite_refs(v) for v in node]+ return node+++def build() -> dict:+ spec = yaml.safe_load(SRC.read_text())+ defs = rewrite_refs(spec["components"]["schemas"])+ return {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": f"https://unifiedharnessprotocol.io/schema/uhp-{VERSION}.schema.json",+ "title": "Unified Harness Protocol",+ "description": (+ f"Object definitions for UHP {VERSION}. Generated from "+ f"uhp-{VERSION}.openapi.yaml by build.py — do not edit by hand."+ ),+ "$defs": defs,+ }+++def main() -> int:+ doc = build()+ text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"+ if "--check" in sys.argv:+ if not OUT.exists() or OUT.read_text() != text:+ print(f"{OUT.name} is out of date — run: python protocol/schema/build.py")+ return 1+ print(f"{OUT.name} is up to date ({len(doc['$defs'])} definitions)")+ return 0+ OUT.write_text(text)+ print(f"wrote {OUT.name} ({len(doc['$defs'])} definitions)")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/protocol/schema/uhp-2026-08-11.openapi.yaml b/protocol/schema/uhp-2026-08-11.openapi.yamlnew file mode 100644index 00000000..d0e7401c--- /dev/null+++ b/protocol/schema/uhp-2026-08-11.openapi.yaml@@ -0,0 +1,949 @@+openapi: 3.1.0+info:+ title: Unified Harness Protocol+ version: '2026-08-11'+ summary: An open standard for running complete agent harnesses as shared infrastructure.+ description: |+ UHP defines how a product drives a complete agent harness — Codex, Claude Code, Hermes, or any+ other — over HTTP: selecting and configuring a harness, sending work, following progress,+ continuing a session, cancelling execution, handling errors and files, and receiving results.++ This document is normative for **structure**. The prose specification in `protocol/versions/`+ is normative for **behaviour**; where they disagree about behaviour, the prose wins, because+ behaviour is not expressible in OpenAPI.++ Conformance is defined by the suite in `protocol/conformance/`, not by this document.+ license:+ name: Apache-2.0+ identifier: Apache-2.0+ contact:+ name: UHP maintainers+ url: https://github.com/HarnessRouter/harnessrouter++servers:+ - url: https://your-uhp-server+ description: Any conformant UHP server. The protocol requires no hosted service.+ - url: http://127.0.0.1:3000/api/harness+ description: HarnessRouter Community Edition, default local deployment++security:+ - bearerAuth: []++tags:+ - name: Discovery+ description: Protocol version and capability discovery (conformance class Core)+ - name: Harnesses+ description: Discovering, selecting and managing configured harnesses+ - name: Tasks+ description: Running work and reading results+ - name: Sessions+ description: Continuing, inspecting and cancelling sessions+ - name: Files+ description: File input and artifact retrieval (conformance class Extended)++paths:+ /v1/uhp:+ get:+ tags: [Discovery]+ operationId: getDiscovery+ summary: Protocol discovery document+ description: |+ Served without authentication: a client must be able to learn whether it is talking to a UHP+ server, and which versions it speaks, before presenting credentials. The document contains+ nothing principal-specific.+ security: []+ responses:+ '200':+ description: The discovery document+ headers:+ UHP-Version: { $ref: '#/components/headers/UHPVersion' }+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Discovery' }++ /v1/harnesses:+ get:+ tags: [Harnesses]+ operationId: listHarnesses+ summary: List configured harnesses+ responses:+ '200':+ description: Harnesses within the caller's scope. May be empty.+ content:+ application/json:+ schema:+ type: object+ required: [harnesses]+ properties:+ harnesses:+ type: array+ items: { $ref: '#/components/schemas/Harness' }+ '401': { $ref: '#/components/responses/Unauthorized' }+ post:+ tags: [Harnesses]+ operationId: createHarness+ summary: Create a configured harness+ description: Conformance class Full. Check the `harness_management` capability first.+ requestBody:+ required: true+ content:+ application/json:+ schema: { $ref: '#/components/schemas/HarnessCreate' }+ responses:+ '200':+ description: The created harness+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Harness' }+ '401': { $ref: '#/components/responses/Unauthorized' }+ '422': { $ref: '#/components/responses/UnprocessableEntity' }++ /v1/harnesses/{harness_id}:+ parameters:+ - $ref: '#/components/parameters/HarnessId'+ get:+ tags: [Harnesses]+ operationId: getHarness+ summary: Get one harness+ responses:+ '200':+ description: The harness+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Harness' }+ '404': { $ref: '#/components/responses/NotFound' }+ put:+ tags: [Harnesses]+ operationId: updateHarness+ summary: Update a harness configuration+ description: |+ Conformance class Full. `id`, `base` and `createdAt` are immutable — changing the base of an+ existing harness would silently change the behaviour of every session attached to it.+ requestBody:+ required: true+ content:+ application/json:+ schema: { $ref: '#/components/schemas/HarnessCreate' }+ responses:+ '200':+ description: The updated harness+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Harness' }+ '404': { $ref: '#/components/responses/NotFound' }+ delete:+ tags: [Harnesses]+ operationId: deleteHarness+ summary: Delete a harness+ description: Must not delete the sessions or responses that used it.+ responses:+ '200':+ description: Deleted+ content:+ application/json:+ schema:+ type: object+ properties:+ id: { type: string }+ deleted: { type: boolean }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/models:+ get:+ tags: [Harnesses]+ operationId: listModels+ summary: The model catalogue, by backend+ responses:+ '200':+ description: Models grouped by backend, each with computed availability+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ModelCatalog' }+ '401': { $ref: '#/components/responses/Unauthorized' }++ /v1/harnesses/{harness_id}/models:+ parameters:+ - $ref: '#/components/parameters/HarnessId'+ get:+ tags: [Harnesses]+ operationId: listHarnessModels+ summary: Models this harness can run+ responses:+ '200':+ description: The harness's allowed models, default and authorized fallback+ content:+ application/json:+ schema: { $ref: '#/components/schemas/HarnessModels' }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/responses:+ post:+ tags: [Tasks]+ operationId: createResponse+ summary: Run a task+ description: |+ The core of the protocol. With `stream: false` the server returns one Response object when+ the task reaches a terminal state. With `stream: true` it returns `text/event-stream`+ carrying the events defined in the Streaming chapter.++ Retries MUST carry `Idempotency-Key`: without one, a retry after a timeout runs the task a+ second time while the first may still be running.+ parameters:+ - name: Idempotency-Key+ in: header+ required: false+ schema: { type: string, maxLength: 255 }+ description: Repeating a key returns the first request's result and does not re-execute.+ - name: UHP-Version+ in: header+ required: false+ schema: { type: string, examples: ['2026-08-11'] }+ requestBody:+ required: true+ content:+ application/json:+ schema: { $ref: '#/components/schemas/CreateResponseRequest' }+ responses:+ '200':+ description: |+ The finished Response (non-streaming), or the event stream (streaming).+ headers:+ UHP-Version: { $ref: '#/components/headers/UHPVersion' }+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Response' }+ text/event-stream:+ schema:+ type: string+ description: SSE; each `data:` line is one Event object.+ '401': { $ref: '#/components/responses/Unauthorized' }+ '404': { $ref: '#/components/responses/NotFound' }+ '409': { $ref: '#/components/responses/Conflict' }+ '422': { $ref: '#/components/responses/UnprocessableEntity' }+ '429': { $ref: '#/components/responses/RateLimited' }++ /v1/responses/{response_id}:+ parameters:+ - $ref: '#/components/parameters/ResponseId'+ get:+ tags: [Tasks]+ operationId: getResponse+ summary: Read a task back+ responses:+ '200':+ description: The Response+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Response' }+ '404': { $ref: '#/components/responses/NotFound' }+ delete:+ tags: [Tasks]+ operationId: deleteResponse+ summary: Delete a stored response+ description: Must not cancel a running task — deletion and cancellation are different intentions.+ responses:+ '200':+ description: Deleted+ content:+ application/json:+ schema:+ type: object+ properties:+ id: { type: string }+ deleted: { type: boolean }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/responses/{response_id}/input_items:+ parameters:+ - $ref: '#/components/parameters/ResponseId'+ get:+ tags: [Tasks]+ operationId: getResponseInputItems+ summary: The input the task was created with+ responses:+ '200':+ description: Input items+ content:+ application/json:+ schema:+ type: object+ properties:+ object: { type: string, const: list }+ data: { type: array, items: { type: object, additionalProperties: true } }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/responses/{response_id}/cancel:+ parameters:+ - $ref: '#/components/parameters/ResponseId'+ post:+ tags: [Sessions]+ operationId: cancelResponse+ summary: Cancel a running task+ description: |+ Idempotent. Cancelling an already-terminal task succeeds and changes nothing — a client+ retrying a cancel after a dropped connection must not be punished for having succeeded.+ responses:+ '200':+ description: The Response, now cancelling or terminal+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Response' }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/sessions:+ get:+ tags: [Sessions]+ operationId: listSessions+ summary: List sessions+ description: Conformance class Extended.+ parameters:+ - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }+ - { name: cursor, in: query, schema: { type: string } }+ - { name: harness, in: query, schema: { type: string }, description: Filter by harness id }+ responses:+ '200':+ description: A page of sessions+ content:+ application/json:+ schema: { $ref: '#/components/schemas/SessionList' }+ '401': { $ref: '#/components/responses/Unauthorized' }++ /v1/sessions/{session_id}:+ parameters:+ - $ref: '#/components/parameters/SessionId'+ get:+ tags: [Sessions]+ operationId: getSession+ summary: Get one session+ responses:+ '200':+ description: The session+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Session' }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/sessions/{session_id}/turns:+ parameters:+ - $ref: '#/components/parameters/SessionId'+ get:+ tags: [Sessions]+ operationId: getSessionTurns+ summary: The ordered task history of a session+ responses:+ '200':+ description: Turns, oldest first+ content:+ application/json:+ schema:+ type: object+ properties:+ turns: { type: array, items: { type: object, additionalProperties: true } }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/sessions/{session_id}/cancel:+ parameters:+ - $ref: '#/components/parameters/SessionId'+ post:+ tags: [Sessions]+ operationId: cancelSession+ summary: Cancel whatever is running in a session+ responses:+ '200':+ description: Accepted+ content:+ application/json:+ schema:+ type: object+ properties:+ id: { type: string }+ status: { type: string }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/files:+ post:+ tags: [Files]+ operationId: uploadFile+ summary: Upload a file for use as task input+ description: Conformance class Extended.+ requestBody:+ required: true+ content:+ multipart/form-data:+ schema:+ type: object+ required: [file]+ properties:+ file: { type: string, format: binary }+ purpose: { type: string, default: user_data }+ responses:+ '200':+ description: The stored file+ content:+ application/json:+ schema: { $ref: '#/components/schemas/File' }+ '413': { $ref: '#/components/responses/PayloadTooLarge' }++ /v1/sessions/{session_id}/files:+ parameters:+ - $ref: '#/components/parameters/SessionId'+ get:+ tags: [Files]+ operationId: listSessionFiles+ summary: Every artifact of a session+ description: Must include artifacts from earlier tasks, not only the most recent.+ responses:+ '200':+ description: Artifacts+ content:+ application/json:+ schema:+ type: object+ required: [files]+ properties:+ files: { type: array, items: { $ref: '#/components/schemas/File' } }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/sessions/{session_id}/files/archive:+ parameters:+ - $ref: '#/components/parameters/SessionId'+ get:+ tags: [Files]+ operationId: downloadSessionArchive+ summary: Every artifact as one archive+ responses:+ '200':+ description: An archive of the session's artifacts+ content:+ application/zip:+ schema: { type: string, format: binary }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/containers/{container_id}/files/{file_id}/content:+ parameters:+ - $ref: '#/components/parameters/ContainerId'+ - $ref: '#/components/parameters/FileId'+ get:+ tags: [Files]+ operationId: downloadFile+ summary: Download an artifact+ description: |+ Returns raw bytes with the file's own media type — never JSON-wrapped. Servers must send+ `X-Content-Type-Options: nosniff`: artifacts are attacker-influenceable content, and serving+ them without it turns an artifact into stored XSS against the client's origin.+ responses:+ '200':+ description: The bytes+ headers:+ Content-Disposition:+ schema: { type: string }+ X-Content-Type-Options:+ required: true+ schema: { type: string, const: nosniff }+ content:+ '*/*':+ schema: { type: string, format: binary }+ '404': { $ref: '#/components/responses/NotFound' }++ /v1/containers/{container_id}/files/{file_id}/pdf:+ parameters:+ - $ref: '#/components/parameters/ContainerId'+ - $ref: '#/components/parameters/FileId'+ get:+ tags: [Files]+ operationId: previewFile+ summary: A rendered PDF preview of a document artifact+ responses:+ '200':+ description: The rendered PDF+ content:+ application/pdf:+ schema: { type: string, format: binary }+ '404': { $ref: '#/components/responses/NotFound' }+ '501':+ description: This server does not implement preview conversion+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }+ '502':+ description: Conversion of this file failed+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }++components:+ securitySchemes:+ bearerAuth:+ type: http+ scheme: bearer+ description: How tokens are issued is out of scope for this protocol.++ headers:+ UHPVersion:+ description: The protocol version actually used to serve this response.+ required: true+ schema: { type: string, examples: ['2026-08-11'] }++ parameters:+ HarnessId:+ name: harness_id+ in: path+ required: true+ schema: { type: string, pattern: '^chrn_' }+ ResponseId:+ name: response_id+ in: path+ required: true+ schema: { type: string, pattern: '^resp_' }+ SessionId:+ name: session_id+ in: path+ required: true+ schema: { type: string }+ ContainerId:+ name: container_id+ in: path+ required: true+ schema: { type: string }+ FileId:+ name: file_id+ in: path+ required: true+ schema: { type: string }++ responses:+ Unauthorized:+ description: Missing, malformed or unknown credential+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }+ NotFound:+ description: |+ No such object in the caller's scope. Servers return 404 rather than 403 for objects outside+ the caller's scope, so that an id's existence is not disclosed.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }+ Conflict:+ description: '`session_busy` or `harness_mismatch`'+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }+ UnprocessableEntity:+ description: '`model_unavailable` or `unsupported_base`'+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }+ PayloadTooLarge:+ description: '`file_too_large`'+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }+ RateLimited:+ description: '`rate_limited` or `quota_exhausted`'+ headers:+ Retry-After:+ schema: { type: string }+ content:+ application/json:+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }++ schemas:+ Discovery:+ type: object+ required: [object, protocol, versions, default_version, conformance_class, capabilities]+ properties:+ object: { type: string, const: uhp.discovery }+ protocol: { type: string, const: uhp }+ versions:+ type: array+ minItems: 1+ items: { type: string }+ default_version: { type: string }+ conformance_class: { type: string, enum: [core, extended, full] }+ capabilities: { $ref: '#/components/schemas/Capabilities' }+ implementation:+ type: object+ properties:+ name: { type: string }+ version: { type: string }+ additionalProperties: true+ additionalProperties: true++ Capabilities:+ type: object+ description: |+ Named booleans. A server reports `false` for a capability it does not implement rather than+ omitting it, so a client can distinguish "not supported" from "server predates this field".+ A client treats an absent key as `false`.+ properties:+ streaming: { type: boolean }+ sessions: { type: boolean }+ cancellation: { type: boolean }+ files_input: { type: boolean }+ files_output: { type: boolean }+ session_listing: { type: boolean }+ harness_management: { type: boolean }+ session_sharing: { type: boolean }+ idempotency: { type: boolean }+ additionalProperties: { type: boolean }++ Harness:+ type: object+ required: [id, name, base]+ properties:+ id: { type: string, pattern: '^chrn_' }+ object: { type: string, const: harness }+ name: { type: string }+ base:+ type: string+ description: |+ Opaque. Not enumerated by this specification — a client must treat it as a string, or the+ protocol would need revising every time a harness is released.+ examples: [codex, claude-code, hermes]+ baseLabel: { type: string }+ defaultModel: { type: string }+ systemPrompt: { type: string }+ mcpServers: { type: array, items: { type: object, additionalProperties: true } }+ skills: { type: array, items: { type: object, additionalProperties: true } }+ disabledTools: { type: array, items: { type: string } }+ maxStep: { type: [integer, 'null'] }+ timeoutSeconds: { type: [integer, 'null'] }+ createdAt: { type: integer, description: Unix milliseconds }+ additionalProperties: true++ HarnessCreate:+ type: object+ required: [base]+ properties:+ name: { type: string }+ base: { type: string }+ default_model: { type: string }+ system_prompt: { type: string }+ disabled_tools: { type: array, items: { type: string } }+ max_step: { type: [integer, 'null'] }+ timeout_seconds: { type: [integer, 'null'] }+ additionalProperties: true++ ModelCatalog:+ type: object+ required: [backends]+ properties:+ backends:+ type: object+ additionalProperties:+ type: object+ required: [default, models]+ properties:+ default: { type: string }+ models: { type: array, items: { $ref: '#/components/schemas/Model' } }++ HarnessModels:+ type: object+ required: [models]+ properties:+ harness_id: { type: string }+ backend: { type: string }+ default: { type: string }+ fallback: { type: string }+ models: { type: array, items: { $ref: '#/components/schemas/Model' } }++ Model:+ type: object+ required: [id, available]+ properties:+ id: { type: string }+ label: { type: string }+ backend: { type: string }+ available:+ type: boolean+ description: |+ Computed, not asserted: true means the server can serve this model for this harness right+ now. Listing a model as available and then failing the task is the worst outcome for a+ client, because a user has already chosen it.+ default: { type: boolean }+ additionalProperties: true++ CreateResponseRequest:+ type: object+ required: [input]+ properties:+ input:+ oneOf:+ - type: string+ - type: array+ items: { type: object, additionalProperties: true }+ description: A bare string is shorthand for one user message.+ model: { type: string, description: Canonical model id. Omitted means the harness default. }+ metadata:+ type: object+ description: Client metadata. `harness_id` selects the configured harness.+ properties:+ harness_id: { type: string }+ additionalProperties: true+ stream: { type: boolean, default: false }+ previous_response_id: { type: [string, 'null'] }+ instructions: { type: string }+ store: { type: boolean, default: true }+ max_output_tokens: { type: [integer, 'null'] }+ max_step: { type: [integer, 'null'], description: Agent step (tool-call round) budget }+ timeout_seconds: { type: [integer, 'null'], description: Wall-clock budget }+ tools: { type: array, items: { type: object, additionalProperties: true } }+ include: { type: array, items: { type: string } }+ background: { type: boolean, default: false }+ additionalProperties: true++ Response:+ type: object+ required: [id, object, created_at, status, output, model]+ properties:+ id: { type: string, pattern: '^resp_' }+ object: { type: string, const: response }+ created_at: { type: integer, description: Unix seconds }+ status: { $ref: '#/components/schemas/ResponseStatus' }+ error:+ oneOf:+ - type: 'null'+ - $ref: '#/components/schemas/Error'+ description: Non-null only when status is `failed`.+ incomplete_details: { type: [object, 'null'], additionalProperties: true }+ previous_response_id: { type: [string, 'null'] }+ model: { type: string, description: The model that actually ran. }+ output:+ type: array+ items: { $ref: '#/components/schemas/OutputItem' }+ store: { type: boolean }+ usage:+ oneOf:+ - type: 'null'+ - $ref: '#/components/schemas/Usage'+ description: |+ null when the server cannot account for usage. A fabricated zero would be worse than an+ honest absence, because a client cannot tell it from a free task.+ metadata:+ type: object+ properties:+ session_id: { type: string }+ requested_model:+ type: string+ description: Present when the server ran a different model than was requested.+ model_fallback: { type: boolean }+ model_fallback_reason: { type: string }+ additionalProperties: true+ additionalProperties: true++ ResponseStatus:+ type: string+ enum: [in_progress, completed, failed, incomplete, cancelled]+ description: |+ `incomplete` means a budget stopped the work and is usually worth continuing.+ `failed` means it could not be done. `cancelled` means the client asked for a stop, and must+ never be reported as `failed`.++ OutputItem:+ type: object+ required: [type]+ description: |+ A client must tolerate item types it does not recognise. A client that renders only `message`+ items and ignores the rest is a valid client.+ properties:+ id: { type: string }+ type:+ type: string+ examples: [message, reasoning, function_call, function_call_output]+ status: { type: string }+ role: { type: string }+ content:+ type: array+ items: { $ref: '#/components/schemas/ContentPart' }+ summary:+ type: array+ items: { type: object, additionalProperties: true }+ call_id: { type: string }+ name: { type: string }+ arguments: { type: string, description: JSON, as a string }+ output: { type: string }+ additionalProperties: true++ ContentPart:+ type: object+ required: [type]+ properties:+ type: { type: string, examples: [output_text] }+ text: { type: string }+ annotations:+ type: array+ items: { $ref: '#/components/schemas/Annotation' }+ additionalProperties: true++ Annotation:+ type: object+ required: [type]+ properties:+ type: { type: string, const: container_file_citation }+ container_id: { type: string }+ file_id: { type: string }+ filename: { type: string }+ download_url: { type: string, format: uri }+ start_index: { type: integer }+ end_index: { type: integer }+ additionalProperties: true++ Usage:+ type: object+ properties:+ input_tokens: { type: integer, minimum: 0 }+ output_tokens: { type: integer, minimum: 0 }+ total_tokens: { type: integer, minimum: 0 }+ cache_read_tokens: { type: integer, minimum: 0 }+ cache_write_tokens: { type: integer, minimum: 0 }+ additionalProperties: true++ Session:+ type: object+ required: [id]+ properties:+ id: { type: string }+ object: { type: string, const: session }+ harness_id: { type: string }+ title: { type: string }+ status: { type: string }+ created_at: { type: integer }+ updated_at: { type: integer }+ additionalProperties: true++ SessionList:+ type: object+ required: [sessions]+ properties:+ sessions: { type: array, items: { $ref: '#/components/schemas/Session' } }+ next_cursor:+ type: [string, 'null']+ description: |+ null on the last page. A client must not be required to detect the end by receiving fewer+ items than requested — that heuristic is wrong whenever a page is exactly full.+ additionalProperties: true++ File:+ type: object+ required: [id, filename]+ properties:+ id: { type: string }+ object: { type: string, const: file }+ container_id: { type: string }+ filename: { type: string }+ bytes: { type: integer, minimum: 0 }+ created_at: { type: integer }+ additionalProperties: true++ ErrorEnvelope:+ type: object+ required: [error]+ properties:+ error: { $ref: '#/components/schemas/Error' }+ detail:+ type: string+ deprecated: true+ description: |+ A human-readable alias of `error.message`, retained for clients written against+ implementations that predate this envelope. Carries no information not in `error`.+ additionalProperties: true++ Error:+ type: object+ required: [type, code, message]+ properties:+ type:+ type: string+ enum:+ - invalid_request_error+ - authentication_error+ - permission_error+ - rate_limit_error+ - harness_error+ - server_error+ code:+ type: string+ description: |+ Specific and machine-readable. Servers may define additional codes for conditions this+ specification does not cover, and must namespace them with a vendor prefix so a future+ version cannot collide with them.+ examples:+ - unsupported_protocol_version+ - invalid_input+ - harness_not_found+ - response_not_found+ - session_not_found+ - file_not_found+ - session_expired+ - harness_mismatch+ - session_busy+ - file_too_large+ - model_unavailable+ - unsupported_base+ - missing_credential+ - invalid_credential+ - insufficient_scope+ - rate_limited+ - quota_exhausted+ - harness_error+ - harness_unavailable+ - provider_error+ - timeout+ - cancelled+ - preview_unavailable+ - preview_failed+ message:+ type: string+ description: |+ One sentence, safe to show a user. Must not contain credentials, internal hostnames, file+ paths, or stack traces.+ param: { type: [string, 'null'], description: Dotted path to the offending field. }+ detail: { type: [object, 'null'], additionalProperties: true }+ additionalProperties: true++ Event:+ type: object+ required: [type, sequence_number]+ description: |+ One streamed event. `sequence_number` starts at 0 and increases by exactly 1 per event, so a+ client can detect a dropped event rather than silently rendering a gap.+ properties:+ type:+ type: string+ examples:+ - response.created+ - response.in_progress+ - response.output_item.added+ - response.output_item.done+ - response.content_part.added+ - response.content_part.done+ - response.output_text.delta+ - response.output_text.done+ - response.output_text.annotation.added+ - response.reasoning_summary_part.added+ - response.reasoning_summary_text.delta+ - response.reasoning_summary_part.done+ - response.function_call_arguments.delta+ - response.function_call_arguments.done+ - response.completed+ - response.incomplete+ - response.failed+ - error+ sequence_number: { type: integer, minimum: 0 }+ response: { $ref: '#/components/schemas/Response' }+ item: { $ref: '#/components/schemas/OutputItem' }+ part: { $ref: '#/components/schemas/ContentPart' }+ annotation: { $ref: '#/components/schemas/Annotation' }+ delta: { type: string }+ text: { type: string }+ arguments: { type: string }+ item_id: { type: string }+ output_index: { type: integer, minimum: 0 }+ content_index: { type: integer, minimum: 0 }+ summary_index: { type: integer, minimum: 0 }+ annotation_index: { type: integer, minimum: 0 }+ code: { type: string }+ message: { type: string }+ param: { type: [string, 'null'] }+ additionalProperties: truediff --git a/protocol/schema/uhp-2026-08-11.schema.json b/protocol/schema/uhp-2026-08-11.schema.jsonnew file mode 100644index 00000000..936652c3--- /dev/null+++ b/protocol/schema/uhp-2026-08-11.schema.json@@ -0,0 +1,891 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://unifiedharnessprotocol.io/schema/uhp-2026-08-11.schema.json",+ "title": "Unified Harness Protocol",+ "description": "Object definitions for UHP 2026-08-11. Generated from uhp-2026-08-11.openapi.yaml by build.py — do not edit by hand.",+ "$defs": {+ "Discovery": {+ "type": "object",+ "required": [+ "object",+ "protocol",+ "versions",+ "default_version",+ "conformance_class",+ "capabilities"+ ],+ "properties": {+ "object": {+ "type": "string",+ "const": "uhp.discovery"+ },+ "protocol": {+ "type": "string",+ "const": "uhp"+ },+ "versions": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string"+ }+ },+ "default_version": {+ "type": "string"+ },+ "conformance_class": {+ "type": "string",+ "enum": [+ "core",+ "extended",+ "full"+ ]+ },+ "capabilities": {+ "$ref": "#/$defs/Capabilities"+ },+ "implementation": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "version": {+ "type": "string"+ }+ },+ "additionalProperties": true+ }+ },+ "additionalProperties": true+ },+ "Capabilities": {+ "type": "object",+ "description": "Named booleans. A server reports `false` for a capability it does not implement rather than\nomitting it, so a client can distinguish \"not supported\" from \"server predates this field\".\nA client treats an absent key as `false`.\n",+ "properties": {+ "streaming": {+ "type": "boolean"+ },+ "sessions": {+ "type": "boolean"+ },+ "cancellation": {+ "type": "boolean"+ },+ "files_input": {+ "type": "boolean"+ },+ "files_output": {+ "type": "boolean"+ },+ "session_listing": {+ "type": "boolean"+ },+ "harness_management": {+ "type": "boolean"+ },+ "session_sharing": {+ "type": "boolean"+ },+ "idempotency": {+ "type": "boolean"+ }+ },+ "additionalProperties": {+ "type": "boolean"+ }+ },+ "Harness": {+ "type": "object",+ "required": [+ "id",+ "name",+ "base"+ ],+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^chrn_"+ },+ "object": {+ "type": "string",+ "const": "harness"+ },+ "name": {+ "type": "string"+ },+ "base": {+ "type": "string",+ "description": "Opaque. Not enumerated by this specification — a client must treat it as a string, or the\nprotocol would need revising every time a harness is released.\n",+ "examples": [+ "codex",+ "claude-code",+ "hermes"+ ]+ },+ "baseLabel": {+ "type": "string"+ },+ "defaultModel": {+ "type": "string"+ },+ "systemPrompt": {+ "type": "string"+ },+ "mcpServers": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "skills": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "disabledTools": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "maxStep": {+ "type": [+ "integer",+ "null"+ ]+ },+ "timeoutSeconds": {+ "type": [+ "integer",+ "null"+ ]+ },+ "createdAt": {+ "type": "integer",+ "description": "Unix milliseconds"+ }+ },+ "additionalProperties": true+ },+ "HarnessCreate": {+ "type": "object",+ "required": [+ "base"+ ],+ "properties": {+ "name": {+ "type": "string"+ },+ "base": {+ "type": "string"+ },+ "default_model": {+ "type": "string"+ },+ "system_prompt": {+ "type": "string"+ },+ "disabled_tools": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "max_step": {+ "type": [+ "integer",+ "null"+ ]+ },+ "timeout_seconds": {+ "type": [+ "integer",+ "null"+ ]+ }+ },+ "additionalProperties": true+ },+ "ModelCatalog": {+ "type": "object",+ "required": [+ "backends"+ ],+ "properties": {+ "backends": {+ "type": "object",+ "additionalProperties": {+ "type": "object",+ "required": [+ "default",+ "models"+ ],+ "properties": {+ "default": {+ "type": "string"+ },+ "models": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/Model"+ }+ }+ }+ }+ }+ }+ },+ "HarnessModels": {+ "type": "object",+ "required": [+ "models"+ ],+ "properties": {+ "harness_id": {+ "type": "string"+ },+ "backend": {+ "type": "string"+ },+ "default": {+ "type": "string"+ },+ "fallback": {+ "type": "string"+ },+ "models": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/Model"+ }+ }+ }+ },+ "Model": {+ "type": "object",+ "required": [+ "id",+ "available"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "backend": {+ "type": "string"+ },+ "available": {+ "type": "boolean",+ "description": "Computed, not asserted: true means the server can serve this model for this harness right\nnow. Listing a model as available and then failing the task is the worst outcome for a\nclient, because a user has already chosen it.\n"+ },+ "default": {+ "type": "boolean"+ }+ },+ "additionalProperties": true+ },+ "CreateResponseRequest": {+ "type": "object",+ "required": [+ "input"+ ],+ "properties": {+ "input": {+ "oneOf": [+ {+ "type": "string"+ },+ {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": true+ }+ }+ ],+ "description": "A bare string is shorthand for one user message."+ },+ "model": {+ "type": "string",+ "description": "Canonical model id. Omitted means the harness default."+ },+ "metadata": {+ "type": "object",+ "description": "Client metadata. `harness_id` selects the configured harness.",+ "properties": {+ "harness_id": {+ "type": "string"+ }+ },+ "additionalProperties": true+ },+ "stream": {+ "type": "boolean",+ "default": false+ },+ "previous_response_id": {+ "type": [+ "string",+ "null"+ ]+ },+ "instructions": {+ "type": "string"+ },+ "store": {+ "type": "boolean",+ "default": true+ },+ "max_output_tokens": {+ "type": [+ "integer",+ "null"+ ]+ },+ "max_step": {+ "type": [+ "integer",+ "null"+ ],+ "description": "Agent step (tool-call round) budget"+ },+ "timeout_seconds": {+ "type": [+ "integer",+ "null"+ ],+ "description": "Wall-clock budget"+ },+ "tools": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "include": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "background": {+ "type": "boolean",+ "default": false+ }+ },+ "additionalProperties": true+ },+ "Response": {+ "type": "object",+ "required": [+ "id",+ "object",+ "created_at",+ "status",+ "output",+ "model"+ ],+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^resp_"+ },+ "object": {+ "type": "string",+ "const": "response"+ },+ "created_at": {+ "type": "integer",+ "description": "Unix seconds"+ },+ "status": {+ "$ref": "#/$defs/ResponseStatus"+ },+ "error": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/$defs/Error"+ }+ ],+ "description": "Non-null only when status is `failed`."+ },+ "incomplete_details": {+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": true+ },+ "previous_response_id": {+ "type": [+ "string",+ "null"+ ]+ },+ "model": {+ "type": "string",+ "description": "The model that actually ran."+ },+ "output": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/OutputItem"+ }+ },+ "store": {+ "type": "boolean"+ },+ "usage": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/$defs/Usage"+ }+ ],+ "description": "null when the server cannot account for usage. A fabricated zero would be worse than an\nhonest absence, because a client cannot tell it from a free task.\n"+ },+ "metadata": {+ "type": "object",+ "properties": {+ "session_id": {+ "type": "string"+ },+ "requested_model": {+ "type": "string",+ "description": "Present when the server ran a different model than was requested."+ },+ "model_fallback": {+ "type": "boolean"+ },+ "model_fallback_reason": {+ "type": "string"+ }+ },+ "additionalProperties": true+ }+ },+ "additionalProperties": true+ },+ "ResponseStatus": {+ "type": "string",+ "enum": [+ "in_progress",+ "completed",+ "failed",+ "incomplete",+ "cancelled"+ ],+ "description": "`incomplete` means a budget stopped the work and is usually worth continuing.\n`failed` means it could not be done. `cancelled` means the client asked for a stop, and must\nnever be reported as `failed`.\n"+ },+ "OutputItem": {+ "type": "object",+ "required": [+ "type"+ ],+ "description": "A client must tolerate item types it does not recognise. A client that renders only `message`\nitems and ignores the rest is a valid client.\n",+ "properties": {+ "id": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "examples": [+ "message",+ "reasoning",+ "function_call",+ "function_call_output"+ ]+ },+ "status": {+ "type": "string"+ },+ "role": {+ "type": "string"+ },+ "content": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/ContentPart"+ }+ },+ "summary": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "call_id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "arguments": {+ "type": "string",+ "description": "JSON",+ "as a string": null+ },+ "output": {+ "type": "string"+ }+ },+ "additionalProperties": true+ },+ "ContentPart": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "examples": [+ "output_text"+ ]+ },+ "text": {+ "type": "string"+ },+ "annotations": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/Annotation"+ }+ }+ },+ "additionalProperties": true+ },+ "Annotation": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "const": "container_file_citation"+ },+ "container_id": {+ "type": "string"+ },+ "file_id": {+ "type": "string"+ },+ "filename": {+ "type": "string"+ },+ "download_url": {+ "type": "string",+ "format": "uri"+ },+ "start_index": {+ "type": "integer"+ },+ "end_index": {+ "type": "integer"+ }+ },+ "additionalProperties": true+ },+ "Usage": {+ "type": "object",+ "properties": {+ "input_tokens": {+ "type": "integer",+ "minimum": 0+ },+ "output_tokens": {+ "type": "integer",+ "minimum": 0+ },+ "total_tokens": {+ "type": "integer",+ "minimum": 0+ },+ "cache_read_tokens": {+ "type": "integer",+ "minimum": 0+ },+ "cache_write_tokens": {+ "type": "integer",+ "minimum": 0+ }+ },+ "additionalProperties": true+ },+ "Session": {+ "type": "object",+ "required": [+ "id"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "object": {+ "type": "string",+ "const": "session"+ },+ "harness_id": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "status": {+ "type": "string"+ },+ "created_at": {+ "type": "integer"+ },+ "updated_at": {+ "type": "integer"+ }+ },+ "additionalProperties": true+ },+ "SessionList": {+ "type": "object",+ "required": [+ "sessions"+ ],+ "properties": {+ "sessions": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/Session"+ }+ },+ "next_cursor": {+ "type": [+ "string",+ "null"+ ],+ "description": "null on the last page. A client must not be required to detect the end by receiving fewer\nitems than requested — that heuristic is wrong whenever a page is exactly full.\n"+ }+ },+ "additionalProperties": true+ },+ "File": {+ "type": "object",+ "required": [+ "id",+ "filename"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "object": {+ "type": "string",+ "const": "file"+ },+ "container_id": {+ "type": "string"+ },+ "filename": {+ "type": "string"+ },+ "bytes": {+ "type": "integer",+ "minimum": 0+ },+ "created_at": {+ "type": "integer"+ }+ },+ "additionalProperties": true+ },+ "ErrorEnvelope": {+ "type": "object",+ "required": [+ "error"+ ],+ "properties": {+ "error": {+ "$ref": "#/$defs/Error"+ },+ "detail": {+ "type": "string",+ "deprecated": true,+ "description": "A human-readable alias of `error.message`, retained for clients written against\nimplementations that predate this envelope. Carries no information not in `error`.\n"+ }+ },+ "additionalProperties": true+ },+ "Error": {+ "type": "object",+ "required": [+ "type",+ "code",+ "message"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "invalid_request_error",+ "authentication_error",+ "permission_error",+ "rate_limit_error",+ "harness_error",+ "server_error"+ ]+ },+ "code": {+ "type": "string",+ "description": "Specific and machine-readable. Servers may define additional codes for conditions this\nspecification does not cover, and must namespace them with a vendor prefix so a future\nversion cannot collide with them.\n",+ "examples": [+ "unsupported_protocol_version",+ "invalid_input",+ "harness_not_found",+ "response_not_found",+ "session_not_found",+ "file_not_found",+ "session_expired",+ "harness_mismatch",+ "session_busy",+ "file_too_large",+ "model_unavailable",+ "unsupported_base",+ "missing_credential",+ "invalid_credential",+ "insufficient_scope",+ "rate_limited",+ "quota_exhausted",+ "harness_error",+ "harness_unavailable",+ "provider_error",+ "timeout",+ "cancelled",+ "preview_unavailable",+ "preview_failed"+ ]+ },+ "message": {+ "type": "string",+ "description": "One sentence, safe to show a user. Must not contain credentials, internal hostnames, file\npaths, or stack traces.\n"+ },+ "param": {+ "type": [+ "string",+ "null"+ ],+ "description": "Dotted path to the offending field."+ },+ "detail": {+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": true+ }+ },+ "additionalProperties": true+ },+ "Event": {+ "type": "object",+ "required": [+ "type",+ "sequence_number"+ ],+ "description": "One streamed event. `sequence_number` starts at 0 and increases by exactly 1 per event, so a\nclient can detect a dropped event rather than silently rendering a gap.\n",+ "properties": {+ "type": {+ "type": "string",+ "examples": [+ "response.created",+ "response.in_progress",+ "response.output_item.added",+ "response.output_item.done",+ "response.content_part.added",+ "response.content_part.done",+ "response.output_text.delta",+ "response.output_text.done",+ "response.output_text.annotation.added",+ "response.reasoning_summary_part.added",+ "response.reasoning_summary_text.delta",+ "response.reasoning_summary_part.done",+ "response.function_call_arguments.delta",+ "response.function_call_arguments.done",+ "response.completed",+ "response.incomplete",+ "response.failed",+ "error"+ ]+ },+ "sequence_number": {+ "type": "integer",+ "minimum": 0+ },+ "response": {+ "$ref": "#/$defs/Response"+ },+ "item": {+ "$ref": "#/$defs/OutputItem"+ },+ "part": {+ "$ref": "#/$defs/ContentPart"+ },+ "annotation": {+ "$ref": "#/$defs/Annotation"+ },+ "delta": {+ "type": "string"+ },+ "text": {+ "type": "string"+ },+ "arguments": {+ "type": "string"+ },+ "item_id": {+ "type": "string"+ },+ "output_index": {+ "type": "integer",+ "minimum": 0+ },+ "content_index": {+ "type": "integer",+ "minimum": 0+ },+ "summary_index": {+ "type": "integer",+ "minimum": 0+ },+ "annotation_index": {+ "type": "integer",+ "minimum": 0+ },+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ },+ "param": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "additionalProperties": true+ }+ }+}diff --git a/protocol/site/build.py b/protocol/site/build.pynew file mode 100644index 00000000..707d649a--- /dev/null+++ b/protocol/site/build.py@@ -0,0 +1,373 @@+#!/usr/bin/env python3+"""Build the unifiedharnessprotocol.io site from the specification.++The site is GENERATED from the markdown in protocol/, never written separately. A hand-maintained+copy of a specification is a second specification, and the two only ever agree on the day they are+written — the whole point of the standard is that there is one source for what the protocol says.++ python protocol/site/build.py # build into protocol/site/dist+ python protocol/site/build.py --serve # build, then serve on :8000 for review++Output is plain static HTML with no build chain and no runtime dependencies, so it can be published+to any static host.+"""+from __future__ import annotations++import html+import pathlib+import re+import shutil+import sys++try:+ import markdown+except ImportError: # pragma: no cover+ sys.exit("Python-Markdown is required: pip install markdown")++HERE = pathlib.Path(__file__).parent+ROOT = HERE.parent # protocol/+DIST = HERE / "dist"+VERSION = "2026-08-11"+SITE = "unifiedharnessprotocol.io"++# ── information architecture ────────────────────────────────────────────────────────────+# Mirrors the shape a protocol site is expected to have — an introduction, a versioned+# specification, the machine-readable definitions, conformance, and the change process — so a+# developer arriving from another protocol's docs already knows where things are.+NAV = [+ ("Introduction", [+ ("index.html", "What is UHP?", ROOT / "README.md"),+ ]),+ (f"Specification · {VERSION}", [+ ("spec/index.html", "Overview", ROOT / f"versions/{VERSION}/index.md"),+ ("spec/architecture.html", "Architecture", ROOT / f"versions/{VERSION}/architecture.md"),+ ("spec/lifecycle.html", "Lifecycle", ROOT / f"versions/{VERSION}/lifecycle.md"),+ ("spec/harnesses.html", "Harnesses", ROOT / f"versions/{VERSION}/harnesses.md"),+ ("spec/tasks.html", "Tasks", ROOT / f"versions/{VERSION}/tasks.md"),+ ("spec/streaming.html", "Streaming", ROOT / f"versions/{VERSION}/streaming.md"),+ ("spec/sessions.html", "Sessions", ROOT / f"versions/{VERSION}/sessions.md"),+ ("spec/files.html", "Files", ROOT / f"versions/{VERSION}/files.md"),+ ("spec/errors.html", "Errors", ROOT / f"versions/{VERSION}/errors.md"),+ ("spec/schema.html", "Schema", ROOT / f"versions/{VERSION}/schema.md"),+ ]),+ ("Conformance", [+ ("conformance.html", "Conformance suite", ROOT / "conformance/README.md"),+ ]),+ ("Community", [+ ("versioning.html", "Versioning", ROOT / "VERSIONING.md"),+ ("governance.html", "Governance", ROOT / "GOVERNANCE.md"),+ ("changelog.html", "Changelog", ROOT / "CHANGELOG.md"),+ ]),+]++# HarnessRouter's docs palette and type, so the two properties read as one family.+CSS = """+:root{+ --brand:#285aff; --brand-deep:#1641d8; --brand-soft:#eff3ff;+ --canvas:#fbfbfc; --surface:#fff; --subtle:#f7f7f9;+ --line:#e7e7eb; --line-strong:#d8d8df;+ --ink:#111317; --muted:#6f6f78; --faint:#9696a0;+ --mono:"IBM Plex Mono",ui-monospace,SFMono-Regular,Menlo,monospace;+ --sans:"Inter",-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;+ --sidebar:288px; --content:800px;+}+@media (prefers-color-scheme:dark){+ :root{--canvas:#0d0e11;--surface:#131519;--subtle:#181a1f;--line:#24262d;--line-strong:#31343d;+ --ink:#e9eaee;--muted:#9a9ba4;--faint:#6f7078;--brand-soft:#152246;}+}+:root[data-theme=dark]{--canvas:#0d0e11;--surface:#131519;--subtle:#181a1f;--line:#24262d;+ --line-strong:#31343d;--ink:#e9eaee;--muted:#9a9ba4;--faint:#6f7078;--brand-soft:#152246;}+:root[data-theme=light]{--canvas:#fbfbfc;--surface:#fff;--subtle:#f7f7f9;--line:#e7e7eb;+ --line-strong:#d8d8df;--ink:#111317;--muted:#6f6f78;--faint:#9696a0;--brand-soft:#eff3ff;}++*{box-sizing:border-box}+body{margin:0;background:var(--canvas);color:var(--ink);font-family:var(--sans);+ font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}+a{color:var(--brand);text-decoration:none}+a:hover{text-decoration:underline}++header.top{position:sticky;top:0;z-index:30;background:var(--surface);+ border-bottom:1px solid var(--line);display:flex;align-items:center;gap:16px;+ padding:0 20px;height:56px}+.brand{display:flex;align-items:center;gap:10px;font-weight:680;color:var(--ink);letter-spacing:-.01em}+.brand .mark{width:22px;height:22px;border-radius:6px;background:var(--brand);color:#fff;+ display:grid;place-items:center;font:600 11px/1 var(--mono)}+.brand .ver{font:500 11px/1 var(--mono);color:var(--muted);background:var(--subtle);+ border:1px solid var(--line);border-radius:999px;padding:4px 8px}+.top .spacer{flex:1}+.top nav a{color:var(--muted);font-size:14px;font-weight:520;margin-left:18px}+.top nav a:hover{color:var(--ink);text-decoration:none}+#menu{display:none;background:none;border:1px solid var(--line);border-radius:8px;+ color:var(--ink);font-size:18px;line-height:1;padding:6px 10px;cursor:pointer}++.shell{display:grid;grid-template-columns:var(--sidebar) minmax(0,1fr);align-items:start;+ max-width:1320px;margin:0 auto}+aside{position:sticky;top:56px;height:calc(100vh - 56px);overflow-y:auto;+ border-right:1px solid var(--line);padding:24px 16px 48px}+aside .group{margin-bottom:22px}+aside .group h4{margin:0 0 8px;padding:0 10px;font-size:11px;font-weight:660;+ letter-spacing:.07em;text-transform:uppercase;color:var(--faint)}+aside a{display:block;padding:6px 10px;border-radius:7px;color:var(--muted);+ font-size:14px;line-height:1.4}+aside a:hover{background:var(--subtle);color:var(--ink);text-decoration:none}+aside a.active{background:var(--brand-soft);color:var(--brand-deep);font-weight:600}++main{padding:40px 40px 96px;min-width:0}+article{max-width:var(--content)}+article h1{font-size:34px;line-height:1.2;letter-spacing:-.02em;margin:0 0 8px;font-weight:700}+article h2{font-size:22px;line-height:1.3;letter-spacing:-.01em;margin:44px 0 12px;+ font-weight:660;padding-top:20px;border-top:1px solid var(--line)}+article h3{font-size:17px;margin:28px 0 8px;font-weight:640}+article p{margin:0 0 16px;color:var(--ink)}+article ul,article ol{margin:0 0 16px;padding-left:22px}+article li{margin:5px 0}+article strong{font-weight:640}++code{font-family:var(--mono);font-size:.875em;background:var(--subtle);+ border:1px solid var(--line);border-radius:5px;padding:1px 5px}+pre{background:var(--subtle);border:1px solid var(--line);border-radius:10px;+ padding:16px 18px;overflow-x:auto;margin:0 0 20px}+pre code{background:none;border:0;padding:0;font-size:13px;line-height:1.6}++.table-wrap{overflow-x:auto;margin:0 0 20px;border:1px solid var(--line);border-radius:10px}+table{border-collapse:collapse;width:100%;font-size:14px}+th,td{text-align:left;padding:10px 14px;border-bottom:1px solid var(--line);vertical-align:top}+th{background:var(--subtle);font-weight:640;font-size:12.5px;letter-spacing:.02em;+ color:var(--muted);text-transform:uppercase}+tr:last-child td{border-bottom:0}+td code{white-space:nowrap}++blockquote{margin:0 0 20px;padding:14px 18px;background:var(--brand-soft);+ border-left:3px solid var(--brand);border-radius:0 10px 10px 0}+blockquote p:last-child{margin-bottom:0}++hr{border:0;border-top:1px solid var(--line);margin:32px 0}++.hero{padding:56px 0 8px;max-width:var(--content)}+.hero h1{font-size:44px;letter-spacing:-.03em;margin-bottom:14px}+.hero .lede{font-size:19px;color:var(--muted);line-height:1.55}+.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:14px;+ margin:28px 0 8px;max-width:var(--content)}+.card{display:block;border:1px solid var(--line);border-radius:12px;padding:18px;+ background:var(--surface);color:var(--ink)}+.card:hover{border-color:var(--brand);text-decoration:none}+.card b{display:block;font-size:15px;margin-bottom:4px}+.card span{color:var(--muted);font-size:13.5px;line-height:1.5}++.pager{display:flex;justify-content:space-between;gap:16px;margin-top:56px;+ padding-top:20px;border-top:1px solid var(--line);max-width:var(--content)}+.pager a{font-size:14px;font-weight:560}+footer{border-top:1px solid var(--line);margin-top:64px;padding:24px 0 0;+ color:var(--faint);font-size:13px;max-width:var(--content)}++@media (max-width:900px){+ .shell{grid-template-columns:1fr}+ aside{position:fixed;inset:56px auto 0 0;width:280px;background:var(--surface);+ transform:translateX(-100%);transition:transform .18s ease;z-index:25;height:calc(100vh - 56px)}+ aside.open{transform:none;box-shadow:0 12px 40px #0000001f}+ #menu{display:block}+ main{padding:28px 20px 72px}+ .top nav{display:none}+ article h1,.hero h1{font-size:28px}+ .hero{padding:32px 0 4px}+}+@media (max-width:560px){+ /* The wordmark and the version chip together are wider than a phone, and wrapping them broke+ the fixed-height bar. Collapse to the mark, which is what the header is for at this width. */+ header.top{gap:10px;padding:0 14px}+ .brand{font-size:0}+ .brand .mark{font-size:11px}+ .brand .ver,header.top>.ver{display:none}+ main{padding:22px 16px 64px}+}+"""++JS = """+(function(){+ var b=document.getElementById('menu'),s=document.querySelector('aside');+ if(b&&s){b.addEventListener('click',function(){s.classList.toggle('open');});+ s.addEventListener('click',function(e){if(e.target.tagName==='A')s.classList.remove('open');});}+})();+"""+++def render_markdown(text: str) -> str:+ md = markdown.Markdown(extensions=["tables", "fenced_code", "toc", "attr_list", "sane_lists"])+ out = md.convert(text)+ # Tables must scroll inside their own box rather than widening the page on a phone.+ out = re.sub(r"<table>", '<div class="table-wrap"><table>', out)+ out = re.sub(r"</table>", "</table></div>", out)+ return out+++def rewrite_links(html_text: str, depth: int) -> str:+ """Point in-repo markdown links at their built pages."""+ up = "../" * depth+ pairs = [+ (rf'href="(?:\.\./)*versions/{VERSION}/([a-z]+)\.md"', rf'href="{up}spec/\1.html"'),+ (r'href="(?:\.\./)*README\.md"', f'href="{up}index.html"'),+ (r'href="(?:\.\./)*VERSIONING\.md"', f'href="{up}versioning.html"'),+ (r'href="(?:\.\./)*GOVERNANCE\.md"', f'href="{up}governance.html"'),+ (r'href="(?:\.\./)*CHANGELOG\.md"', f'href="{up}changelog.html"'),+ (r'href="(?:\.\./)*conformance/?"', f'href="{up}conformance.html"'),+ (r'href="(?:\.\./)*\.\./conformance/"', f'href="{up}conformance.html"'),+ (r'href="([a-z]+)\.md"', rf'href="\1.html"'),+ (r'href="(?:\.\./)*schema/([^"/]+)"',+ rf'href="{up}schema/\1"'), # the machine-readable files ship with the site+ (r'href="(?:\.\./)*schema/"', f'href="{up}spec/schema.html"'),+ (r'href="versions/2026-08-11/"', f'href="{up}spec/index.html"'),+ # An anchor into another document's section: keep the section, retarget the document.+ (r'href="(?:\.\./)*VERSIONING\.md#([^"]+)"', rf'href="{up}versioning.html#\1"'),+ (r'href="(?:\.\./)*GOVERNANCE\.md#([^"]+)"', rf'href="{up}governance.html#\1"'),+ (r'href="(?:\.\./)*README\.md#([^"]+)"', rf'href="{up}index.html#\1"'),+ (rf'href="(?:\.\./)*versions/{VERSION}/([a-z]+)\.md#([^"]+)"',+ rf'href="{up}spec/\1.html#\2"'),+ ]+ for pat, repl in pairs:+ html_text = re.sub(pat, repl, html_text)+ return html_text+++def flat_pages():+ return [(path, title, src) for _, items in NAV for path, title, src in items]+++def sidebar(current: str, depth: int) -> str:+ up = "../" * depth+ out = []+ for group, items in NAV:+ out.append(f'<div class="group"><h4>{html.escape(group)}</h4>')+ for path, title, _ in items:+ cls = ' class="active"' if path == current else ""+ out.append(f'<a href="{up}{path}"{cls}>{html.escape(title)}</a>')+ out.append("</div>")+ return "\n".join(out)+++def page(current: str, title: str, body: str, depth: int, hero: str = "") -> str:+ up = "../" * depth+ pages = flat_pages()+ idx = next((i for i, (p, _, _) in enumerate(pages) if p == current), -1)+ prev_ = pages[idx - 1] if idx > 0 else None+ next_ = pages[idx + 1] if 0 <= idx < len(pages) - 1 else None+ pager = ""+ if prev_ or next_:+ left = f'<a href="{up}{prev_[0]}">← {html.escape(prev_[1])}</a>' if prev_ else "<span></span>"+ right = f'<a href="{up}{next_[0]}">{html.escape(next_[1])} →</a>' if next_ else "<span></span>"+ pager = f'<div class="pager">{left}{right}</div>'++ return f"""<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>{html.escape(title)} · Unified Harness Protocol</title>+<meta name="description" content="The Unified Harness Protocol (UHP): an open standard for running complete agent harnesses as shared infrastructure.">+<link rel="preconnect" href="https://fonts.googleapis.com">+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">+<style>{CSS}</style>+</head>+<body>+<header class="top">+ <button id="menu" aria-label="Toggle navigation">☰</button>+ <a class="brand" href="{up}index.html"><span class="mark">U</span> Unified Harness Protocol</a>+ <span class="ver">{VERSION}</span>+ <span class="spacer"></span>+ <nav>+ <a href="{up}spec/index.html">Specification</a>+ <a href="{up}conformance.html">Conformance</a>+ <a href="{up}governance.html">Governance</a>+ <a href="https://github.com/HarnessRouter/harnessrouter">GitHub</a>+ </nav>+</header>+<div class="shell">+ <aside>{sidebar(current, depth)}</aside>+ <main>+ {hero}+ <article>{body}</article>+ {pager}+ <footer>+ Unified Harness Protocol {VERSION} · Apache-2.0 ·+ defined and maintained in the+ <a href="https://github.com/HarnessRouter/harnessrouter">HarnessRouter open-source repository</a>.+ The standard can be implemented without HarnessRouter Cloud.+ </footer>+ </main>+</div>+<script>{JS}</script>+</body>+</html>+"""+++HERO = """+<div class="hero">+ <h1>The Unified Harness Protocol</h1>+ <p class="lede">One open standard for driving complete agent harnesses — Codex, Claude Code,+ Hermes, and whatever ships next — so a product integrates once instead of once per harness.</p>+</div>+<div class="cards">+ <a class="card" href="spec/index.html"><b>Read the specification</b>+ <span>Normative, versioned, and testable. Ten chapters from architecture to errors.</span></a>+ <a class="card" href="conformance.html"><b>Run the conformance suite</b>+ <span>47 checks across three classes. Passing it is the only conformance claim that means anything.</span></a>+ <a class="card" href="spec/schema.html"><b>Generate a client</b>+ <span>OpenAPI 3.1 and JSON Schema 2020-12, published per version.</span></a>+ <a class="card" href="governance.html"><b>Propose a change</b>+ <span>Prose first. Spec, reference implementation and suite move together.</span></a>+</div>+"""+++def build() -> int:+ if DIST.exists():+ shutil.rmtree(DIST)+ (DIST / "spec").mkdir(parents=True)++ built = 0+ for path, title, src in flat_pages():+ if not src.exists():+ print(f" !! missing source: {src}")+ return 1+ depth = path.count("/")+ body = rewrite_links(render_markdown(src.read_text()), depth)+ # The home page leads with the hero; its markdown H1 would repeat it.+ hero = ""+ if path == "index.html":+ hero = HERO+ body = re.sub(r"<h1>.*?</h1>", "", body, count=1, flags=re.S)+ body = re.sub(r"<p><strong>An open standard.*?</strong></p>", "", body, count=1, flags=re.S)+ (DIST / path).write_text(page(path, title, body, depth, hero))+ built += 1++ # Publishing metadata: a protocol site that cannot be crawled is a protocol nobody finds.+ (DIST / "robots.txt").write_text(+ f"User-agent: *\nAllow: /\nSitemap: https://{SITE}/sitemap.xml\n")+ urls = "".join(f" <url><loc>https://{SITE}/{p}</loc></url>\n" for p, _, _ in flat_pages())+ (DIST / "sitemap.xml").write_text(+ f'<?xml version="1.0" encoding="UTF-8"?>\n'+ f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n{urls}</urlset>\n')++ # The machine-readable definitions are part of the standard, so they are served with it.+ shutil.copytree(ROOT / "schema", DIST / "schema",+ ignore=shutil.ignore_patterns("build.py", "__pycache__"))++ print(f"built {built} pages + schema into {DIST}")+ return 0+++def main() -> int:+ rc = build()+ if rc or "--serve" not in sys.argv:+ return rc+ import http.server+ import functools+ handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(DIST))+ print(f"serving {DIST} on http://127.0.0.1:8000 — Ctrl-C to stop")+ http.server.HTTPServer(("127.0.0.1", 8000), handler).serve_forever()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/protocol/versions/2026-08-11/architecture.md b/protocol/versions/2026-08-11/architecture.mdnew file mode 100644index 00000000..3bf99a8c--- /dev/null+++ b/protocol/versions/2026-08-11/architecture.md@@ -0,0 +1,140 @@+# Architecture++**Unified Harness Protocol, version `2026-08-11`**++The key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT, RECOMMENDED, MAY and+OPTIONAL in this specification are to be interpreted as described in [RFC 2119][rfc2119] and+[RFC 8174][rfc8174] when, and only when, they appear in all capitals.++[rfc2119]: https://www.rfc-editor.org/rfc/rfc2119+[rfc8174]: https://www.rfc-editor.org/rfc/rfc8174++## 1. Roles++```+┌──────────┐ UHP over HTTP ┌──────────┐ implementation-defined ┌──────────┐+│ Client │ ────────────────▶ │ Server │ ─────────────────────────▶ │ Harness │+└──────────┘ └──────────┘ └──────────┘+```++**Client** — an application that wants work done: a product backend, a CLI, a CI job, another agent.+A client speaks only UHP. It MUST NOT be required to know which harness implementation runs behind+the server, nor how the server executes it.++**Server** — implements this specification. It accepts tasks, drives one or more harnesses, and+reports progress and results in the vocabulary defined here. Everything about *how* it runs a+harness — containers, subprocesses, queues, remote workers — is out of scope for this specification+and MUST NOT leak into the wire format.++**Harness** — a complete agent runtime with its own loop, tools and session state. UHP does not+specify the harness itself; it specifies how a client drives one through a server. Harnesses are+identified by a **base**: a stable string such as `codex`, `claude-code` or `hermes`.++A **configured harness** is a base plus configuration — default model, system prompt, tool+restrictions, skills, MCP servers, step and time budgets. It is the unit a client selects when it+sends work, and it is addressed by a server-assigned id.++> **Why a configured harness, and not just a base?**+> The same base behaves very differently with a different system prompt, a different model, or a+> different tool set. Making the configuration a first-class, addressable object means a product can+> change how its agent behaves without redeploying its backend, and means two products can share a+> server without sharing behaviour.++## 2. Conformance classes++A server declares which class it implements. Each class is cumulative: **Extended** includes+**Core**, **Full** includes **Extended**.++| Class | A server at this class MUST implement |+|---|---|+| **Core** | Capability discovery, harness discovery, non-streaming and streaming task execution, session continuation, cancellation, and the error model. |+| **Extended** | Core, plus file input, artifact retrieval, and session listing/inspection. |+| **Full** | Extended, plus harness lifecycle management (create, update, delete) and session sharing. |++A client MUST NOT assume any capability above **Core** without checking capability discovery+(see [Lifecycle §2](lifecycle.md)). A server MUST NOT advertise a capability it does not implement —+advertising is a promise, and a client that trusts it and receives a `404` has been lied to in a way+it cannot recover from.++The [conformance suite](../../conformance/) tests each class separately and reports per class. A+server that passes at a class MAY describe itself as "UHP 2026-08-11 conformant (<class>)". No+other use of the term "conformant" is meaningful.++## 3. Object model++Six object types. Every one carries an `object` field naming its type, and an `id` with a+type-distinguishing prefix so an identifier is never ambiguous about what it points at.++| Object | `object` value | Id prefix | Lifetime |+|---|---|---|---|+| Harness | `harness` | `chrn_` | Until deleted |+| Response | `response` | `resp_` | Retained per server policy |+| Session | `session` | `hsess` | Until deleted |+| File | `file` | `file_` | With its container |+| Container | `container` | `cntr_` | With its session |+| Event | *(none — events carry `type`)* | — | Streamed, and replayable |++Their relationships:++```+Harness ──┐+ ├──▶ Session ──┬──▶ Response ──▶ Response ──▶ … (one per task, chained)+Model ───┘ └──▶ Container ──▶ File, File, … (artifacts)+```++- A **response** is one task: one request in, one result out. It is the atomic unit of work.+- A **session** is a chain of responses that share conversational context and a working directory.+ A session is created implicitly by the first task and extended by `previous_response_id`.+- A **container** is the file namespace of a session. Files the agent writes become artifacts in it.++> **Why is the session implicit?**+> Requiring `POST /sessions` before any work could be done would add a round trip, a failure mode,+> and an object to clean up — for a concept most first tasks never need. A client that only ever+> sends one-shot tasks never learns the word "session"; a client that needs continuity gets it by+> quoting the id it already has.++## 4. Transport++- All requests MUST be HTTP/1.1 or later over TLS, except for loopback development where a server+ MAY accept plaintext.+- Request and response bodies are `application/json; charset=utf-8`, except file upload+ (`multipart/form-data`) and file download (the file's own media type).+- Streaming uses Server-Sent Events (`text/event-stream`) as described in+ [Streaming](streaming.md).+- Servers MUST accept requests with an absent `Accept` header and default to JSON.++## 5. Authentication++A client authenticates with a bearer token:++```http+Authorization: Bearer <token>+```++How tokens are issued is out of scope. A server MUST reject an absent, malformed, or unknown token+with `401` and the error model in [Errors](errors.md), and MUST NOT distinguish "no such token"+from "token not permitted here" in a way that lets a caller enumerate valid tokens.++A server MUST scope every object to the principal that created it. A client MUST NOT be able to+read, continue, cancel or delete another principal's response, session, or file — including by+guessing an id. Servers MUST return `404`, not `403`, for objects outside the caller's scope, so+that an id's existence is not disclosed.++## 6. Design principles++These are the rules the specification holds itself to. They are included because they explain the+shape of what follows, and because a future change that violates one is probably a mistake.++1. **The client should not be able to tell which harness ran the work** — except by asking. Every+ difference between harnesses that a client can observe is a leak, and each leak is a place where+ swapping harnesses breaks a product.+2. **Progress is a stream of facts, not a rendering.** Events describe what happened — text, a tool+ call, a file — never how to display it.+3. **A field means one thing.** Where UHP extends a borrowed surface, it adds fields; it never+ redefines one.+4. **Absent is not empty, and empty is not zero.** A server that does not know a value omits it. It+ MUST NOT invent a placeholder, an estimate, or a zero.+5. **Failure is a first-class result.** Every failure is reportable in the same envelope as success,+ with a machine-readable code. A client should never have to parse prose to find out what to do.+6. **The specification, the reference implementation and the conformance suite move together.** A+ sentence here that no test enforces is a wish, not a standard.diff --git a/protocol/versions/2026-08-11/errors.md b/protocol/versions/2026-08-11/errors.mdnew file mode 100644index 00000000..28bc8a38--- /dev/null+++ b/protocol/versions/2026-08-11/errors.md@@ -0,0 +1,124 @@+# Errors++**Unified Harness Protocol, version `2026-08-11`**++A client's error handling is only as good as the server's error reporting. This chapter defines one+envelope, a closed set of codes, and which failures are worth retrying.++## 1. The error envelope++Every non-2xx response MUST have this body:++```json+{+ "error": {+ "type": "invalid_request_error",+ "code": "harness_not_found",+ "message": "No harness with id 'chrn_deadbeef'.",+ "param": "metadata.harness_id",+ "detail": null+ }+}+```++| Field | Type | Required | Meaning |+|---|---|---|---|+| `type` | string | yes | Broad class; see §2 |+| `code` | string | yes | Specific, machine-readable reason; see §3 |+| `message` | string | yes | Human-readable, one sentence, no stack trace |+| `param` | string \| null | yes | Dotted path to the offending field, when there is one |+| `detail` | object \| null | yes | Structured extra context, or `null` |++Rules:++- `message` MUST be safe to show a user. It MUST NOT contain credentials, internal hostnames, file+ paths, or stack traces.+- `code` MUST come from §3 where one applies. A server MAY define additional codes for conditions+ this specification does not cover, and MUST namespace them with a vendor prefix (`acme_…`) so a+ future version of this specification cannot collide with them.+- A server MUST NOT return `200` with an error inside. The failure of a *task* is reported as a+ response with `status: "failed"` and HTTP `200`, because the request succeeded; the failure of a+ *request* is a non-2xx with this envelope. Those are different events and MUST NOT be conflated.++> **Compatibility note.** A server MAY additionally include a top-level `detail` string alongside+> `error`, for clients written against implementations that predate this envelope. That field is+> deprecated, carries no information not in `error.message`, and will be removed in a future version.++## 2. Error types++| `type` | HTTP | Meaning |+|---|---|---|+| `invalid_request_error` | 400, 404, 409, 413, 422 | The request was wrong. Retrying it unchanged will fail again. |+| `authentication_error` | 401 | The credential is missing, malformed or unknown. |+| `permission_error` | 403 | Authenticated, but not allowed to do this. |+| `rate_limit_error` | 429 | Too many requests, or a quota is exhausted. |+| `harness_error` | 200 (in a failed response) | The harness ran and failed. |+| `server_error` | 500, 502, 503, 504 | The server failed. Retrying MAY succeed. |++## 3. Error codes++### 3.1 Request and routing++| Code | HTTP | Meaning |+|---|---|---|+| `unsupported_protocol_version` | 400 | `UHP-Version` names a version this server cannot serve. `detail.supported` lists what it can. |+| `invalid_input` | 400 | The body could not be parsed, or a field has the wrong type. |+| `harness_not_found` | 404 | No such harness in the caller's scope. |+| `response_not_found` | 404 | No such response in the caller's scope. |+| `session_not_found` | 404 | No such session in the caller's scope. |+| `file_not_found` | 404 | No such file in the caller's scope. |+| `session_expired` | 404 | The session existed but is past its retention. |+| `harness_mismatch` | 409 | The task named a different harness than the session it continues. |+| `session_busy` | 409 | A task is already running in this session. |+| `file_too_large` | 413 | The upload exceeds the server's limit. `detail.max_bytes` states it. |+| `model_unavailable` | 422 | The requested model cannot be served for this harness. |+| `unsupported_base` | 422 | The requested harness base is not supported by this server. |++### 3.2 Authentication and limits++| Code | HTTP | Meaning |+|---|---|---|+| `missing_credential` | 401 | No bearer token. |+| `invalid_credential` | 401 | The token is malformed, unknown, or revoked. |+| `insufficient_scope` | 403 | The credential cannot perform this operation. |+| `rate_limited` | 429 | Slow down. `Retry-After` SHOULD be set. |+| `quota_exhausted` | 429 | A budget is spent; retrying now will not help. |++### 3.3 Execution++| Code | Where | Meaning |+|---|---|---|+| `harness_error` | failed response | The harness ran and could not complete the work. |+| `harness_unavailable` | 503 | No capacity to run this harness right now. |+| `provider_error` | failed response | The upstream model provider refused or failed. |+| `timeout` | failed response | The task exceeded its wall-clock budget. |+| `cancelled` | cancelled response | The client cancelled it. |+| `preview_unavailable` | 501 | This server does not render previews. |+| `preview_failed` | 502 | Conversion of this file failed. |++## 4. Retrying++| Situation | Retry? |+|---|---|+| `server_error` (500, 502, 503, 504) | Yes, with exponential backoff and jitter |+| `rate_limited` | Yes, after `Retry-After` |+| `quota_exhausted` | No — nothing will change until the quota does |+| `session_busy` | Yes, once the in-flight task is terminal |+| Any `invalid_request_error` | No — fix the request |+| `authentication_error` | No — fix the credential |+| A task that reached `failed` | Only with the client's own judgment; it consumed real resources |++**Retries of `POST /v1/responses` MUST carry an `Idempotency-Key`.** Without one, a retry after a+timeout runs the task a second time — and the first may still be running, editing the same files.+This is the single most damaging mistake a UHP client can make; see [Tasks §6](tasks.md).++## 5. Timeouts++A client SHOULD set generous timeouts. Agent tasks routinely run for minutes; a 30-second HTTP+timeout will cancel healthy work.++- Streaming: no total timeout. Use an inactivity timeout instead — a server SHOULD emit a comment+ line (`: keep-alive`) at least every 30 seconds so the client can distinguish a working agent from+ a dead connection.+- Non-streaming: at least the task's `timeout_seconds`, plus margin.+- A client that gives up MUST NOT assume the task stopped. It has not. Cancel it explicitly.diff --git a/protocol/versions/2026-08-11/files.md b/protocol/versions/2026-08-11/files.mdnew file mode 100644index 00000000..4d65f1e3--- /dev/null+++ b/protocol/versions/2026-08-11/files.md@@ -0,0 +1,137 @@+# Files++**Unified Harness Protocol, version `2026-08-11`**++An agent that can only return text is a chatbot. A harness edits files, writes reports, produces+diagrams. This chapter defines getting files in and artifacts out.++Conformance class **Extended**.++## 1. Sending files in++### 1.1 Inline++For small files, inline the bytes as a data URL:++```json+{+ "input": [+ { "role": "user", "content": [+ { "type": "input_text", "text": "Summarise this." },+ { "type": "input_file", "filename": "q3.pdf",+ "file_data": "data:application/pdf;base64,JVBERi0xLjQK…" }+ ]}+ ]+}+```++### 1.2 By upload++For anything larger, upload once and reference by id:++```http+POST /v1/files+Content-Type: multipart/form-data+```++```json+{ "id": "file_abc123", "object": "file", "filename": "q3.pdf", "bytes": 184320, "created_at": 1786400000 }+```++```json+{ "type": "input_file", "file_id": "file_abc123" }+```++A server MUST accept both forms. Inline avoids a round trip for a 4 KB file; upload avoids+base64-inflating a 40 MB one through every retry. A server MUST document its size limit and MUST+reject an oversized upload with `413` and `code: "file_too_large"` rather than truncating — a+silently truncated input produces a confident, wrong answer.++## 2. Getting artifacts out++Files an agent produces become artifacts of the session's container. They are reported in two+places.++### 2.1 On the response++Artifacts appear as annotations on the assistant message:++```json+{+ "type": "message",+ "content": [+ { "type": "output_text", "text": "I've written the report.",+ "annotations": [+ { "type": "container_file_citation",+ "container_id": "cntr_…",+ "file_id": "file_…",+ "filename": "report.md",+ "download_url": "https://server/v1/containers/cntr_…/files/file_…/content",+ "start_index": 0, "end_index": 24 }+ ]+ }+ ]+}+```++A client that renders only text still shows a correct answer; a client that reads annotations can+offer the file. That is the intended layering — artifacts are additive to the message, never a+replacement for it.++### 2.2 By listing the session++```http+GET /v1/sessions/{session_id}/files+```++```json+{ "files": [ { "id": "file_…", "container_id": "cntr_…", "filename": "report.md",+ "bytes": 2048, "created_at": 1786400240 } ] }+```++A server MUST list every artifact of the session, including files from earlier tasks. Restricting the+list to the most recent task would make a multi-step session's earlier outputs unreachable.++## 3. Downloading++```http+GET /v1/containers/{container_id}/files/{file_id}/content+```++Returns the raw bytes with the file's own `Content-Type`. A server MUST NOT wrap the bytes in JSON.++A server SHOULD send `Content-Disposition` with the original filename, and MUST set+`X-Content-Type-Options: nosniff`. Artifacts are attacker-influenced content — an agent can be+persuaded to write a file — so serving them without those headers turns an artifact into stored+XSS against the client's own origin.++### 3.1 Preview rendering++A server MAY offer a rendered preview of a document format:++```http+GET /v1/containers/{container_id}/files/{file_id}/pdf+```++If a server does not implement conversion it MUST return `501` with+`code: "preview_unavailable"`, not a broken or empty PDF. If conversion fails it MUST return `502`+with `code: "preview_failed"`. A client can then tell "this server never previews" from "this file+would not convert", and only the second is worth retrying.++## 4. Bulk download++```http+GET /v1/sessions/{session_id}/files/archive+```++Returns every artifact of the session as a single archive. A server SHOULD implement this: a session+that produced forty files should not require forty requests.++## 5. Retention and scope++- Artifacts live with their session. Deleting a session MUST make its artifacts unreachable.+- A server MUST scope file access to the owning principal. A `file_id` from another principal MUST+ return `404`, never the bytes.+- A server MUST NOT let a `container_id` / `file_id` pair traverse outside its container. Path+ traversal through artifact ids is the most likely serious vulnerability in a UHP implementation,+ and the conformance suite probes for it.diff --git a/protocol/versions/2026-08-11/harnesses.md b/protocol/versions/2026-08-11/harnesses.mdnew file mode 100644index 00000000..77afcf17--- /dev/null+++ b/protocol/versions/2026-08-11/harnesses.md@@ -0,0 +1,165 @@+# Harnesses++**Unified Harness Protocol, version `2026-08-11`**++Before a client can send work it needs to know what can run it, and with which models. This chapter+defines discovery, the harness object, and — at conformance class **Full** — how harnesses are+created and changed.++## 1. Discovering harnesses++```http+GET /v1/harnesses+```++```json+{+ "harnesses": [+ {+ "id": "chrn_08dae611630d467ab3e67ed792570ae5",+ "object": "harness",+ "name": "Research agent",+ "base": "claude-code",+ "baseLabel": "Claude Code",+ "defaultModel": "claude-sonnet-4.6",+ "systemPrompt": "",+ "mcpServers": [],+ "skills": [],+ "disabledTools": [],+ "maxStep": null,+ "timeoutSeconds": null,+ "createdAt": 1786403298205+ }+ ]+}+```++A server MUST return only harnesses within the caller's scope. The list MAY be empty — a server with+no configured harnesses is valid, and a client MUST handle that rather than assuming index `0`+exists.++```http+GET /v1/harnesses/{harness_id}+```++Returns one harness object, or `404` with `code: "harness_not_found"`.++## 2. The harness object++| Field | Type | Required | Meaning |+|---|---|---|---|+| `id` | string | yes | `chrn_`-prefixed |+| `object` | string | yes | Always `harness` |+| `name` | string | yes | Human-readable label; not an identifier |+| `base` | string | yes | Which harness runtime: `codex`, `claude-code`, `hermes`, … |+| `baseLabel` | string | no | Display name for `base` |+| `defaultModel` | string | no | Model used when a task omits `model` |+| `systemPrompt` | string | no | Additional standing instructions |+| `mcpServers` | array | no | MCP servers attached to this harness |+| `skills` | array | no | Skills available to this harness |+| `disabledTools` | string[] | no | Tools withheld from the agent |+| `maxStep` | integer \| null | no | Default step budget |+| `timeoutSeconds` | integer \| null | no | Default wall-clock budget |+| `createdAt` | integer | yes | Unix milliseconds |++`base` values are not enumerated by this specification. A server MAY support bases this document has+never heard of, and a client MUST treat `base` as an opaque string — anything else means the+protocol has to be revised every time a harness is released, which is exactly the coupling UHP+exists to remove.++## 3. Models++```http+GET /v1/models+```++```json+{+ "backends": {+ "claude": {+ "default": "claude-sonnet-4.6",+ "models": [+ { "id": "claude-sonnet-4.6", "label": "claude-sonnet-4.6", "backend": "claude",+ "available": true, "default": true }+ ]+ }+ }+}+```++```http+GET /v1/harnesses/{harness_id}/models+```++```json+{+ "harness_id": "chrn_…",+ "backend": "claude",+ "default": "claude-sonnet-4.6",+ "fallback": "claude-sonnet-4.6",+ "models": [ { "id": "claude-opus-5", "available": true, "default": false } ]+}+```++### 3.1 `available` is a promise++`available: true` means the server can serve that model for that harness **right now** — a+credential exists and the provider can reach it. `available: false` means a request for it will not+run as asked.++A server MUST compute `available`, not assert it. Listing a model as available and then failing the+task is the worst outcome for a client: it presents a choice to a user, the user picks it, and the+work fails after they have committed to it.++A client SHOULD present unavailable models as disabled rather than hiding them, so a user can see+that a model exists and is not configured, rather than wondering why it is missing.++## 4. Managing harnesses++Conformance class **Full** only. A client MUST check the `harness_management` capability first.++### 4.1 Create++```http+POST /v1/harnesses+```++```json+{ "name": "Research agent", "base": "claude-code", "default_model": "claude-sonnet-4.6" }+```++Returns the created harness object. `base` is REQUIRED and MUST be one the server supports;+otherwise `422` with `code: "unsupported_base"`.++### 4.2 Update++```http+PUT /v1/harnesses/{harness_id}+```++Replaces the mutable configuration. A server MUST NOT change `id`, `base`, or `createdAt`. Changing+the base of an existing harness would silently change the behaviour of every session already+attached to it; a client that wants a different base MUST create a different harness.++### 4.3 Delete++```http+DELETE /v1/harnesses/{harness_id}+```++A server MUST NOT delete the sessions or responses that used the harness. History that disappears+when configuration changes cannot be audited.++## 5. Choosing a harness++Non-normative, but the question every client faces:++| If the task is… | Consider |+|---|---|+| Code editing in a repository | A coding-specialised base (`codex`, `claude-code`) |+| Long-horizon multi-tool work | A base with an explicit step budget and strong tool use |+| Cheap, high-volume classification | The smallest model on any base |++The point of UHP is that this choice stays reversible. A product that speaks UHP can change base or+model with a configuration edit, and can A/B two harnesses against the same input without a second+integration.diff --git a/protocol/versions/2026-08-11/index.md b/protocol/versions/2026-08-11/index.mdnew file mode 100644index 00000000..d1839c05--- /dev/null+++ b/protocol/versions/2026-08-11/index.md@@ -0,0 +1,74 @@+# Unified Harness Protocol — specification `2026-08-11`++An open standard for running complete agent harnesses as shared infrastructure.++This is the normative specification. For an introduction to what UHP is and why it exists, start at+the [protocol README](../../README.md).++## Chapters++| # | Chapter | Defines |+|---|---|---|+| 1 | [Architecture](architecture.md) | Roles, conformance classes, object model, transport, authentication, design principles |+| 2 | [Lifecycle](lifecycle.md) | Version negotiation, capability discovery, task and session states, concurrency |+| 3 | [Harnesses](harnesses.md) | Discovering, selecting, configuring and managing harnesses; models and availability |+| 4 | [Tasks](tasks.md) | Running work, the response object, model substitution, idempotency |+| 5 | [Streaming](streaming.md) | The event vocabulary, ordering guarantees, reconnection |+| 6 | [Sessions](sessions.md) | Continuing, inspecting, cancelling, sharing, deleting |+| 7 | [Files](files.md) | File input, artifacts, download, retention and scope |+| 8 | [Errors](errors.md) | The error envelope, codes, retry rules, timeouts |+| 9 | [Schema](schema.md) | Machine-readable definitions and how to generate from them |++## Endpoint summary++| Method | Path | Class | Chapter |+|---|---|---|---|+| `GET` | `/v1/uhp` | Core | [Lifecycle](lifecycle.md) |+| `GET` | `/v1/harnesses` | Core | [Harnesses](harnesses.md) |+| `GET` | `/v1/harnesses/{id}` | Core | [Harnesses](harnesses.md) |+| `GET` | `/v1/models` | Core | [Harnesses](harnesses.md) |+| `GET` | `/v1/harnesses/{id}/models` | Core | [Harnesses](harnesses.md) |+| `POST` | `/v1/responses` | Core | [Tasks](tasks.md) |+| `GET` | `/v1/responses/{id}` | Core | [Tasks](tasks.md) |+| `GET` | `/v1/responses/{id}/input_items` | Core | [Tasks](tasks.md) |+| `POST` | `/v1/responses/{id}/cancel` | Core | [Sessions](sessions.md) |+| `DELETE` | `/v1/responses/{id}` | Core | [Tasks](tasks.md) |+| `POST` | `/v1/sessions/{id}/cancel` | Core | [Sessions](sessions.md) |+| `GET` | `/v1/sessions` | Extended | [Sessions](sessions.md) |+| `GET` | `/v1/sessions/{id}` | Extended | [Sessions](sessions.md) |+| `GET` | `/v1/sessions/{id}/turns` | Extended | [Sessions](sessions.md) |+| `POST` | `/v1/files` | Extended | [Files](files.md) |+| `GET` | `/v1/sessions/{id}/files` | Extended | [Files](files.md) |+| `GET` | `/v1/sessions/{id}/files/archive` | Extended | [Files](files.md) |+| `GET` | `/v1/containers/{cid}/files/{fid}/content` | Extended | [Files](files.md) |+| `GET` | `/v1/containers/{cid}/files/{fid}/pdf` | Extended | [Files](files.md) |+| `POST` | `/v1/harnesses` | Full | [Harnesses](harnesses.md) |+| `PUT` | `/v1/harnesses/{id}` | Full | [Harnesses](harnesses.md) |+| `DELETE` | `/v1/harnesses/{id}` | Full | [Harnesses](harnesses.md) |+| `POST` | `/v1/sessions/{id}/share` | Full | [Sessions](sessions.md) |+| `GET` | `/v1/sessions/{id}/share` | Full | [Sessions](sessions.md) |+| `DELETE` | `/v1/traces/{id}` | Full | [Sessions](sessions.md) |++## Conformance++A server is conformant at a class when it passes the [conformance suite](../../conformance/) at that+class. Nothing else is a conformance claim — not a self-assessment, not an implementation of the+endpoints, not passing "most" tests.++```bash+pip install -e protocol/conformance+uhp-conformance --base-url https://your-server --api-key "$KEY" --class extended+```++The suite is part of this specification. If the suite and this prose disagree, that is a bug in one+of them and MUST be resolved by changing whichever is wrong — never by leaving them inconsistent.++## Conventions++- MUST / SHOULD / MAY are used as defined in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and+ [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174).+- JSON examples are illustrative; the [schema](../../schema/) is authoritative for structure.+- Field names are `snake_case` on the task surface (inherited from the Responses-compatible shape)+ and `camelCase` on the harness object. This inconsistency is real, is called out here rather than+ hidden, and is retained because changing either would break existing clients for cosmetic gain.+ A future major version SHOULD unify them.diff --git a/protocol/versions/2026-08-11/lifecycle.md b/protocol/versions/2026-08-11/lifecycle.mdnew file mode 100644index 00000000..e4e3c08f--- /dev/null+++ b/protocol/versions/2026-08-11/lifecycle.md@@ -0,0 +1,150 @@+# Lifecycle++**Unified Harness Protocol, version `2026-08-11`**++This chapter defines how a client and server agree on a protocol version, how a client learns what+a server can do, and the states a task moves through from submission to result.++## 1. Version negotiation++UHP versions are dates: `YYYY-MM-DD`, the day the version was published. Dates sort, do not imply a+compatibility promise that semantic versioning would imply and not keep, and make the age of an+implementation obvious. See [VERSIONING.md](../../VERSIONING.md) for the compatibility rules.++A client MAY declare the version it was written against:++```http+UHP-Version: 2026-08-11+```++- If the header is absent, the server MUST assume its own default version and MUST state that+ version in the response header. A client that omits the header is asking for the server's choice,+ and gets it.+- If the header names a version the server supports, the server MUST honour it for that request.+- If the header names a version the server does not support, the server MUST fail the request with+ `400` and `code: "unsupported_protocol_version"`, and the error `detail` MUST list the versions it+ does support. It MUST NOT silently serve a different version — a client that asked for a version+ it can parse should not receive one it cannot.++Every response, including errors, MUST carry the version actually used:++```http+UHP-Version: 2026-08-11+```++## 2. Capability discovery++```http+GET /v1/uhp+```++Unauthenticated or authenticated — a server MUST serve this endpoint without a bearer token, because+a client needs to know whether it is talking to a UHP server *before* it can sensibly present+credentials. The document MUST NOT contain anything principal-specific.++```json+{+ "object": "uhp.discovery",+ "protocol": "uhp",+ "versions": ["2026-08-11"],+ "default_version": "2026-08-11",+ "conformance_class": "full",+ "capabilities": {+ "streaming": true,+ "sessions": true,+ "cancellation": true,+ "files_input": true,+ "files_output": true,+ "session_listing": true,+ "harness_management": true,+ "session_sharing": true,+ "idempotency": true+ },+ "implementation": { "name": "HarnessRouter Community Edition", "version": "0.3.0" }+}+```++| Field | Type | Required | Meaning |+|---|---|---|---|+| `object` | string | yes | Always `uhp.discovery` |+| `protocol` | string | yes | Always `uhp` — lets a client distinguish UHP from a lookalike |+| `versions` | string[] | yes | Every version this server can serve; MUST be non-empty |+| `default_version` | string | yes | Used when the client sends no `UHP-Version`; MUST appear in `versions` |+| `conformance_class` | string | yes | `core`, `extended` or `full` |+| `capabilities` | object | yes | Named booleans; see below |+| `implementation` | object | no | Free-form identification, for debugging and bug reports |++A server MUST report `false` for a capability it does not implement, rather than omitting it, so+that a client can tell "not supported" from "server is older than this field". A client MUST treat+an absent capability key as `false`.++`conformance_class` MUST be consistent with `capabilities`: a server claiming `extended` MUST report+`files_input`, `files_output` and `session_listing` as `true`. The conformance suite checks this,+because a class claim that contradicts the capability list tells a client two different things.++## 3. Task lifecycle++A task moves through these states. `status` on the response object carries the current one.++```+ ┌──────────────┐+ POST /responses │ │+ ────────────────▶│ in_progress │+ │ │+ └──────┬───────┘+ │+ ┌──────────────────┼──────────────────┬───────────────────┐+ ▼ ▼ ▼ ▼+ ┌──────────┐ ┌──────────┐ ┌────────────┐ ┌───────────┐+ │completed │ │ failed │ │ incomplete │ │ cancelled │+ └──────────┘ └──────────┘ └────────────┘ └───────────┘+```++| Status | Meaning | Terminal |+|---|---|---|+| `in_progress` | Accepted and running | no |+| `completed` | The harness finished the work and produced a result | yes |+| `failed` | The task could not be completed; `error` explains why | yes |+| `incomplete` | The harness stopped at a budget — step limit or time limit — with partial output | yes |+| `cancelled` | The client cancelled it; partial output MAY be present | yes |++Rules:++- A server MUST NOT transition out of a terminal state. Once a client has seen `completed`, later+ reads of that response MUST return `completed`.+- `incomplete` MUST be used when a budget stopped the work, and MUST NOT be used for errors. The+ distinction matters to a client: `incomplete` is usually worth continuing, `failed` usually is not.+- A `cancelled` task MUST report `cancelled`, not `failed`. A client that asked for a stop did not+ experience an error.+- Terminal responses MUST retain whatever output was produced before they became terminal. Discarding+ partial work because a task later failed destroys the only evidence of what went wrong.++## 4. Session lifecycle++```+first task ──▶ session created implicitly ──▶ session active ──▶ deleted (client) or expired (server policy)+ ▲ │+ └────┘+ each continued task extends it+```++- A session is created by the server when the first task of a chain runs. Its id MUST be reported in+ the response's `metadata.session_id`.+- A session MUST preserve, across tasks in the chain: conversational context, the working directory+ and its files, and the configured harness.+- A session MUST NOT be extended by a task that names a different configured harness. A server MUST+ fail such a request with `409` and `code: "harness_mismatch"` rather than silently starting a new+ session — continuing a conversation with a different agent is a different conversation, and doing+ it quietly loses work the client believed it had.+- Session expiry is server policy. A server that expires sessions MUST report `404` with+ `code: "session_expired"` on continuation, distinguishable from `session_not_found`.++## 5. Concurrency++- A server MUST accept concurrent tasks in *different* sessions.+- A server MUST NOT run two tasks concurrently in the *same* session: a session has one working+ directory and one conversation, and two agents writing to both is not a defined state. A second+ task for a busy session MUST fail with `409` and `code: "session_busy"`.+- A client that receives `session_busy` SHOULD wait for the in-flight task to reach a terminal state+ and retry. Servers SHOULD include `retry_after_ms` in the error `detail` when they can estimate it,+ and MUST omit it when they cannot rather than guessing.diff --git a/protocol/versions/2026-08-11/schema.md b/protocol/versions/2026-08-11/schema.mdnew file mode 100644index 00000000..ae1fbeed--- /dev/null+++ b/protocol/versions/2026-08-11/schema.md@@ -0,0 +1,62 @@+# Schema++**Unified Harness Protocol, version `2026-08-11`**++The machine-readable definitions are normative for structure. Where this prose and the schema+disagree about the shape of an object, the schema wins; where they disagree about behaviour, the+prose wins, because behaviour is not expressible in JSON Schema.++## Files++| File | Format | Use |+|---|---|---|+| [`uhp-2026-08-11.openapi.yaml`](../../schema/uhp-2026-08-11.openapi.yaml) | OpenAPI 3.1 | Generate clients and servers; browse the API |+| [`uhp-2026-08-11.schema.json`](../../schema/uhp-2026-08-11.schema.json) | JSON Schema 2020-12 | Validate objects and streamed events |++Both are versioned by filename. A published version is immutable: fixing a schema means publishing a+new version, never editing one clients may already have generated from.++## Generating a client++```bash+# TypeScript+npx openapi-typescript protocol/schema/uhp-2026-08-11.openapi.yaml -o uhp.d.ts++# Python+openapi-python-client generate --path protocol/schema/uhp-2026-08-11.openapi.yaml++# Go+oapi-codegen -package uhp protocol/schema/uhp-2026-08-11.openapi.yaml > uhp.gen.go+```++## Validating events++Every streamed event validates against the `Event` definition, which is a discriminated union on+`type`:++```python+import json, jsonschema++schema = json.load(open("protocol/schema/uhp-2026-08-11.schema.json"))+validator = jsonschema.Draft202012Validator(+ {"$ref": "#/$defs/Event", **schema})++for line in stream:+ if line.startswith("data: "):+ validator.validate(json.loads(line[6:]))+```++The conformance suite does exactly this against a live server, so a schema change that the reference+implementation does not satisfy fails CI rather than shipping.++## Extension points++A server MAY add fields anywhere the schema allows additional properties:++- `metadata` on a request or response — the intended place for client and server context.+- `detail` on an error — structured context for a specific failure.+- Additional output item types, and additional event types.++A server MUST NOT redefine the meaning of a specified field, and MUST NOT add a required field: a+client written against this version has to keep working. Vendor-specific fields SHOULD carry a+vendor prefix so that a later version of this specification cannot collide with them.diff --git a/protocol/versions/2026-08-11/sessions.md b/protocol/versions/2026-08-11/sessions.mdnew file mode 100644index 00000000..7b4c7a70--- /dev/null+++ b/protocol/versions/2026-08-11/sessions.md@@ -0,0 +1,127 @@+# Sessions++**Unified Harness Protocol, version `2026-08-11`**++A session is what makes a second task cheaper than the first: the conversation is still there, and+so is the working directory. This chapter defines continuing a session, inspecting one, and stopping+work in one.++## 1. Continuing a session++Send the next task with `previous_response_id`:++```json+{+ "input": "Now add tests for the function you just wrote.",+ "previous_response_id": "resp_a1b2c3"+}+```++The server MUST:++- run the new task in the same session, with the same working directory and its files;+- give the harness the conversational context of the earlier tasks;+- use the same configured harness;+- report the same `metadata.session_id`.++`model` MAY differ between tasks in a session. A server MUST honour a per-task model change, because+switching to a cheaper model for a follow-up is a common and legitimate pattern.++If `previous_response_id` names an unknown response, the server MUST fail with `404` and+`code: "response_not_found"`. If the session it referred to has expired, `404` with+`code: "session_expired"` — a client can retry the first from scratch, and should not retry the+second.++> **Why chain on the response id rather than the session id?**+> Because the response id is what the client already has: it comes back from the task it just ran.+> Chaining on it also names an exact point in the conversation, which leaves room for a server to+> branch from an earlier response later without changing the request shape.++## 2. Listing sessions++Conformance class **Extended**.++```http+GET /v1/sessions?limit=20&cursor=&harness=chrn_…+```++```json+{+ "sessions": [+ {+ "id": "hsess7e78…",+ "object": "session",+ "harness_id": "chrn_…",+ "title": "Summarise README.md",+ "status": "completed",+ "created_at": 1786400000,+ "updated_at": 1786400240+ }+ ],+ "next_cursor": null+}+```++Pagination is cursor-based. A server MUST return `next_cursor: null` on the last page, and MUST NOT+require a client to detect the end by receiving fewer items than it asked for — that heuristic is+wrong whenever a page is exactly full.++## 3. Inspecting a session++```http+GET /v1/sessions/{session_id}+GET /v1/sessions/{session_id}/turns+```++`/turns` returns the ordered task history of the session, so a client can rebuild a transcript it did+not store. Each turn identifies its response id, so a client can fetch the full response for any of+them.++## 4. Cancelling++Two scopes, deliberately distinct:++```http+POST /v1/responses/{response_id}/cancel # stop this task+POST /v1/sessions/{session_id}/cancel # stop whatever is running in this session+```++Semantics:++- Cancellation is a request, not a guarantee of immediacy. A server MUST stop the work as soon as it+ can and MUST reach a terminal state.+- A cancelled task MUST end with `status: "cancelled"`, never `failed`.+- Output produced before cancellation MUST be retained.+- Cancelling an already-terminal task MUST succeed and change nothing. A client retrying a cancel+ after a dropped connection should not receive an error for having succeeded twice.+- Cancelling MUST NOT delete the session. The conversation remains continuable.++A server SHOULD respond to cancel within one second even if the harness takes longer to wind down.+The client is usually a user interface, and a Stop button that does nothing visible for thirty+seconds reads as broken.++## 5. Session sharing++Conformance class **Full**. A server MAY let a client publish a read-only view of a session.++```http+POST /v1/sessions/{session_id}/share+GET /v1/sessions/{session_id}/share+```++If implemented:++- the shared view MUST be read-only — it MUST NOT permit continuing, cancelling, or uploading;+- the server MUST allow revocation;+- the server MUST NOT expose provider credentials, tokens, or another principal's data through it.++## 6. Deleting++```http+DELETE /v1/traces/{session_id}+```++Deletes the session and its stored history. A server MUST cancel any in-flight task in the session+first, and MUST make the session unreadable afterwards. Deletion is the one place where cancel and+delete are legitimately coupled, because the alternative is a running task writing into storage that+no longer has an owner.diff --git a/protocol/versions/2026-08-11/streaming.md b/protocol/versions/2026-08-11/streaming.mdnew file mode 100644index 00000000..9023ef2f--- /dev/null+++ b/protocol/versions/2026-08-11/streaming.md@@ -0,0 +1,161 @@+# Streaming++**Unified Harness Protocol, version `2026-08-11`**++Agent tasks take minutes. Without a stream, a product can only show a spinner and hope. This chapter+defines how a server reports progress while work is happening.++## 1. Opening a stream++Set `"stream": true` on `POST /v1/responses`. The server MUST respond with:++```http+HTTP/1.1 200 OK+Content-Type: text/event-stream+Cache-Control: no-cache+```++Each event is a Server-Sent Events message whose `data` is one JSON object:++```+data: {"type":"response.created","sequence_number":0,"response":{…}}++data: {"type":"response.output_text.delta","sequence_number":7,"item_id":"msg_1","output_index":0,"content_index":0,"delta":"Sum"}++data: {"type":"response.completed","sequence_number":42,"response":{…}}++```++Rules:++- Every event MUST carry `type` and `sequence_number`.+- `sequence_number` MUST start at `0` and increase by exactly 1 per event within a stream. A client+ can therefore detect a dropped event rather than silently rendering a gap.+- The stream MUST end with exactly one terminal event (§4).+- A server MUST NOT buffer the stream to completion before sending it. A stream delivered all at once+ at the end is not a stream, and a client cannot tell the difference between that and a hang.+- Servers behind a proxy MUST disable response buffering. This is the single most common deployment+ error for UHP servers; it looks exactly like the harness being slow.++## 2. Event vocabulary++Events describe *what happened*. They never describe how to display it.++### 2.1 Response lifecycle++| Event | When |+|---|---|+| `response.created` | The task was accepted. Carries the initial `response` with `status: in_progress`. |+| `response.in_progress` | Work has started. |+| `response.completed` | Terminal — success. Carries the final `response`. |+| `response.incomplete` | Terminal — a budget stopped the work. Carries the final `response`. |+| `response.failed` | Terminal — failure. Carries the final `response`, whose `error` is non-null. |++### 2.2 Output items++| Event | When |+|---|---|+| `response.output_item.added` | A new item begins. Carries `output_index` and a shell `item`. |+| `response.output_item.done` | That item is final. Carries the complete `item`. |++### 2.3 Assistant text++| Event | Payload |+|---|---|+| `response.content_part.added` | An empty `output_text` part opens |+| `response.output_text.delta` | `delta`: the next fragment of text |+| `response.output_text.done` | `text`: the complete text of the part |+| `response.content_part.done` | `part`: the finished part |+| `response.output_text.annotation.added` | `annotation`: an artifact citation (see [Files](files.md)) |++Text deltas are fragments, not lines or tokens. A client MUST concatenate them in `sequence_number`+order and MUST NOT assume any particular chunking.++### 2.4 Reasoning++| Event | Payload |+|---|---|+| `response.reasoning_summary_part.added` | An empty summary part opens |+| `response.reasoning_summary_text.delta` | `delta`: the next fragment of the summary |+| `response.reasoning_summary_part.done` | `part`: the finished summary part |++Reasoning is a *summary*, not a verbatim chain of thought. A server MUST NOT be required to expose+raw model reasoning, and a client MUST treat reasoning as optional — many harness and model+combinations produce none, and a client that requires it will break on those.++### 2.5 Tool use++| Event | Payload |+|---|---|+| `response.function_call_arguments.delta` | `delta`: fragment of the JSON arguments |+| `response.function_call_arguments.done` | `arguments`: the complete JSON string |++The tool call itself arrives as an `output_item` of type `function_call`, and its result as+`function_call_output` matched by `call_id`.++### 2.6 Errors++| Event | Payload |+|---|---|+| `error` | `code`, `message`, `param` — an error that did not end the task |++An `error` event MUST be followed by a terminal event. A stream that emits `error` and then stops+without a terminal event is malformed: the client cannot tell whether the task died or the+connection did.++## 3. Ordering guarantees++A server MUST guarantee:++1. `response.created` is the first event.+2. Exactly one terminal event is the last.+3. For any item, `output_item.added` precedes every event referring to it, and `output_item.done`+ follows them all.+4. `sequence_number` is strictly monotonic with no gaps.++A server MUST NOT guarantee, and a client MUST NOT assume:++- that items complete in the order they were added (a long tool call may finish after later text);+- that text arrives in any particular chunk size;+- that any optional event type appears at all.++## 4. Terminal events++Exactly one of `response.completed`, `response.incomplete`, `response.failed`. Each carries the+complete final `response` object — a client that missed intermediate events can rely on this one+alone to render the result. This redundancy is deliberate: a dropped connection mid-stream should+cost latency, not correctness.++A cancelled task terminates with `response.failed` carrying `status: "cancelled"` in the response+object. The status field, not the event name, is authoritative.++## 5. Reconnecting++A dropped connection MUST NOT abort the task. The work continues server-side.++To follow a task after a disconnect, a client re-reads it:++```http+GET /v1/responses/{response_id}+```++or, for a live event feed of a harness's sessions:++```http+GET /v1/harnesses/{harness_id}/events+```++A server MAY additionally support SSE `Last-Event-ID` resumption. If it does, it MUST resume from+the event *after* the given `sequence_number` and MUST NOT replay events the client already saw.++> A client SHOULD treat the stream as an optimisation and the stored response as the source of+> truth. Products written the other way round — where the stream is the only place a result exists —+> lose work every time a load balancer recycles a connection.++## 6. Non-streaming++With `"stream": false` (the default), the server returns a single response object when the task+reaches a terminal state, with the same `output` array the stream would have assembled. The two+paths MUST produce identical results for identical input. A server that assembles a different+`output` for streaming than for non-streaming has two implementations of its own protocol, and one+of them is wrong.diff --git a/protocol/versions/2026-08-11/tasks.md b/protocol/versions/2026-08-11/tasks.mdnew file mode 100644index 00000000..26bd55c6--- /dev/null+++ b/protocol/versions/2026-08-11/tasks.md@@ -0,0 +1,234 @@+# Tasks++**Unified Harness Protocol, version `2026-08-11`**++A task is one unit of work: input in, a result out. It is the endpoint most clients spend all their+time in.++## 1. Run a task++```http+POST /v1/responses+Authorization: Bearer <token>+Content-Type: application/json+```++```json+{+ "input": "Summarise README.md in three bullets.",+ "model": "claude-sonnet-4.6",+ "metadata": { "harness_id": "chrn_08dae611630d467ab3e67ed792570ae5" },+ "stream": true+}+```++### 1.1 Request fields++| Field | Type | Required | Meaning |+|---|---|---|---|+| `input` | string \| item[] | yes | The work. A bare string is shorthand for one user message. See §2. |+| `model` | string | no | Canonical model id. Omitted means the harness's default. |+| `metadata` | object | no | Client metadata. `harness_id` selects the configured harness. See §1.2. |+| `stream` | boolean | no | `true` streams Server-Sent Events; default `false` returns one JSON object. |+| `previous_response_id` | string | no | Continue the session that produced that response. See [Sessions](sessions.md). |+| `instructions` | string | no | Additional system guidance for this task only. |+| `store` | boolean | no | Whether the server retains the response for later reads. Default `true`. |+| `max_output_tokens` | integer | no | Upper bound on generated tokens. |+| `max_step` | integer | no | Upper bound on agent steps (tool-call rounds) for this task. |+| `timeout_seconds` | integer | no | Wall-clock budget for this task. |+| `tools` | array | no | Additional tools offered for this task. |+| `include` | string[] | no | Optional extra content to include in the result. |+| `background` | boolean | no | Return as soon as the task is accepted; follow it with the events endpoint. |++A server MUST ignore request fields it does not understand rather than rejecting the request. A+client MUST NOT rely on an unknown field having an effect.++`max_step` and `timeout_seconds` are budgets, not guarantees of precision: a server MUST stop the+task at or after the budget, MUST report `incomplete`, and MUST NOT report `completed` for work it+truncated.++### 1.2 Selecting the harness++The configured harness is selected by `metadata.harness_id`:++```json+{ "metadata": { "harness_id": "chrn_…" } }+```++- If `harness_id` is absent, the server MUST use a default harness and MUST report which one it used+ in the response `metadata`.+- If `harness_id` names an unknown harness, or one outside the caller's scope, the server MUST fail+ with `404` and `code: "harness_not_found"`.+- If both `previous_response_id` and `harness_id` are present and disagree, the server MUST fail with+ `409` and `code: "harness_mismatch"` (see [Lifecycle §4](lifecycle.md)).++> **Why is the harness in `metadata` rather than a top-level field?**+> Because the task surface is deliberately Responses-compatible (see the+> [README](../../README.md)), and `metadata` is the extension point that surface already defines for+> caller-supplied context. A top-level `harness` field would be a second, conflicting convention for+> the same idea, and every existing Responses SDK would have to be patched to send it.++### 1.3 Model selection and substitution++`model` names a canonical model id, not a provider-specific one. Canonical ids are stable across+providers, so the same request works whether the server reaches a model directly or through an+aggregator.++If the requested model cannot be served for the selected harness, a server MUST NOT fail silently+and MUST NOT pretend it ran what was asked. It MUST do exactly one of:++1. **Fail** with `422` and `code: "model_unavailable"`; or+2. **Substitute** the harness's authorized default, and record the substitution in the response:++```json+{+ "model": "gpt-5.4",+ "metadata": {+ "requested_model": "gpt-5.6-sol",+ "model_fallback": true,+ "model_fallback_reason": "model 'gpt-5.6-sol' is not available for this harness's backend"+ }+}+```++A client can therefore always answer "did the model I asked for actually run?" by comparing `model`+with `metadata.requested_model`.++> This rule exists because its absence is expensive. A server that substitutes silently makes every+> measurement downstream wrong — benchmarks, cost attribution, quality comparisons — and the client+> has no way to detect it. Reporting the substitution costs two fields.++## 2. Input++`input` is either a string or an array of items.++```json+{ "input": "Summarise README.md" }+```++```json+{+ "input": [+ { "role": "user", "content": [+ { "type": "input_text", "text": "Summarise this report." },+ { "type": "input_file", "filename": "q3.pdf", "file_data": "data:application/pdf;base64,…" }+ ]}+ ]+}+```++| Item type | Purpose |+|---|---|+| `input_text` | Text |+| `input_file` | A file, inline as a data URL in `file_data`, or by `file_id` from a prior upload |+| `input_image` | An image, inline or by `file_id` |++A server at conformance class **Core** MUST accept `input_text`. A server at **Extended** MUST also+accept `input_file` and `input_image`. See [Files](files.md).++## 3. The response object++```json+{+ "id": "resp_a1b2c3",+ "object": "response",+ "created_at": 1786400000,+ "status": "completed",+ "error": null,+ "incomplete_details": null,+ "previous_response_id": null,+ "model": "claude-sonnet-4.6",+ "output": [+ { "id": "rs_1", "type": "reasoning", "summary": [ { "type": "summary_text", "text": "…" } ], "status": "completed" },+ { "id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "read_file",+ "arguments": "{\"path\":\"README.md\"}", "status": "completed" },+ { "id": "fco_1", "type": "function_call_output", "call_id": "call_1", "output": "…", "status": "completed" },+ { "id": "msg_1", "type": "message", "role": "assistant", "status": "completed",+ "content": [ { "type": "output_text", "text": "- …\n- …\n- …", "annotations": [] } ] }+ ],+ "store": true,+ "usage": { "input_tokens": 5120, "output_tokens": 240, "total_tokens": 5360 },+ "metadata": { "session_id": "hsess7e78…" }+}+```++| Field | Type | Required | Notes |+|---|---|---|---|+| `id` | string | yes | `resp_`-prefixed |+| `object` | string | yes | Always `response` |+| `created_at` | integer | yes | Unix seconds |+| `status` | string | yes | See [Lifecycle §3](lifecycle.md) |+| `error` | object \| null | yes | Present and non-null only when `status` is `failed` |+| `output` | item[] | yes | Ordered; MAY be empty for a task that produced nothing |+| `model` | string | yes | The model that actually ran |+| `usage` | object \| null | yes | `null` when the server cannot account for usage — never a fabricated zero |+| `metadata` | object | yes | MUST include `session_id`; see §1.3 for substitution fields |+| `previous_response_id` | string \| null | yes | The response this one continues, if any |+| `store` | boolean | yes | Whether this response was retained |++### 3.1 Output items++| `type` | Meaning |+|---|---|+| `message` | Assistant text, in `content[].text`, with `annotations` for artifacts |+| `reasoning` | The agent's summarised thinking, in `summary[].text` |+| `function_call` | A tool the agent invoked, with `arguments` as a JSON string |+| `function_call_output` | The result of that tool call, matched by `call_id` |++A client MUST tolerate output item types it does not recognise, and MUST NOT assume any ordering+beyond the array order given. A client that renders only `message` items and ignores the rest is a+valid client.++## 4. Reading a task back++```http+GET /v1/responses/{response_id}+```++Returns the same response object. A server that retained the response (`store: true`) MUST return it+after completion; a server MAY return `404` with `code: "response_not_found"` for a response created+with `store: false`.++```http+GET /v1/responses/{response_id}/input_items+```++Returns the input the task was created with, for clients that need to reconstruct a transcript+without having stored it themselves.++## 5. Cancelling++```http+POST /v1/responses/{response_id}/cancel+```++See [Sessions §4](sessions.md).++## 6. Idempotency++A client MAY send an idempotency key:++```http+Idempotency-Key: <client-generated-unique-string>+```++A server that advertises `idempotency` MUST, for a repeated key:++- return the result of the **first** request, and+- **not** start a second execution.++If the first request is still running, the server MUST wait for it and return its result rather than+returning a partial or a conflict. Agent tasks are expensive and side-effecting: a retry that runs+the work twice is worse than a slow answer.++Idempotency keys SHOULD be retained for at least 24 hours.++## 7. Deleting++```http+DELETE /v1/responses/{response_id}+```++Deletes the stored response. A server MUST NOT let this cancel a running task — cancellation and+deletion are different intentions, and conflating them means a client cannot clean up history+without stopping work.