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
UHP 2026-10-19, addition: each turn says when it began and ended (created_at, completed_at)
github-actions[bot]bb8567f076ac
diff --git a/gateway/app.py b/gateway/app.pyindex d3fdace3..1e427d8a 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -4990,6 +4990,7 @@ async def _stop_session(org: str, sid: str, v: dict, rid_hint: str = "") -> tuplrec = await _resp_get(rid)if rec and str(rec.get("status") or "") in ("running", "in_progress", "queued", "starting"):rec["status"] = "cancelled"+ rec.setdefault("_completed_at", time.time()) # the turns feed's completed_at_resp_cache_forget(rid)await _blob_put(f"responses/{rid}.json", json.dumps(rec, default=str).encode(), kb=RESP_BLOB_KB)await _vg_upsert("HarnessResponse", rid, {"status": "cancelled"})@@ -7996,8 +7997,15 @@ async def _harness_models_view(hv: dict | None, backend: str, servable: set[str]# ── response record store (blob = source of truth; VG vertex = index/fallback) ──────────+# a turn record still running: no end time yet+_TURN_LIVE = frozenset({"running", "in_progress", "queued", "starting"})++async def _resp_put(rid: str, stored: dict, org: str, sid: str, prev: str | None,status: str, created_at: float, store: bool) -> None:+ if status not in _TURN_LIVE and "_completed_at" not in stored:+ # when the turn ended, for the turns feed's completed_at; stripped from the response object+ stored = {**stored, "_completed_at": time.time()}try:_resp_cache_forget(rid)await _blob_put(f"responses/{rid}.json", json.dumps(stored, default=str).encode(), kb=RESP_BLOB_KB)@@ -9994,6 +10002,15 @@ async def session_turns(sid: str, request: Request, limit: int = 0) -> dict:return await _session_turns_data(sid, limit=limit)+def _unix_s(ts) -> int | None:+ """A time as whole Unix seconds, the form every UHP time takes; None when there is none."""+ try:+ t = float(ts)+ return int(t) if t > 0 else None+ except (TypeError, ValueError, OverflowError):+ return None++async def _session_turns_data(sid: str, limit: int = 0) -> dict:# find this session's response ids (HarnessResponse vertices carry session_id)ids: list[str] = []@@ -10001,6 +10018,8 @@ async def _session_turns_data(sid: str, limit: int = 0) -> dict:rows = await BACKING.graph.find("HarnessResponse", {"session_id": safe_sid})rows.sort(key=lambda x: str(x.get("created_at") or ""))ids = [str(x.get("id")) for x in rows if x.get("id")]+ # each row's birth as the index holds it: a turn's time when its record carries none+ born = {str(x.get("id")): x.get("created_at") for x in rows if x.get("id")}if limit and limit > 0:ids = ids[-limit:] # last N turns only — bounds blob fetches AND response sizeturns = []@@ -10054,6 +10073,13 @@ async def _session_turns_data(sid: str, limit: int = 0) -> dict:"incomplete_reason": ((rec.get("incomplete_details") or {}).get("reason")or None),"handoff": ((rec.get("incomplete_details") or {}).get("handoff") or None),+ # When the turn began and when it ended, Unix seconds like the response+ # object's created_at, from the record itself (no read per row). completed_at+ # is null while the turn runs and on a record that never said when it ended+ # (before 2026-10-19, or settled by a reconcile that cannot know).+ "created_at": _unix_s(rec.get("created_at") or born.get(rid)),+ "completed_at": (None if str(rec.get("status") or "") in _TURN_LIVE+ else _unix_s(rec.get("_completed_at"))),"_model": rec.get("model") or "", "_created_at": rec.get("created_at") or 0})# Only the LAST turn can be in-flight, and only it can need reconciliation — both want the# session vertex, so read it ONCE.@@ -10437,6 +10463,7 @@ async def cancel_response(response_id: str, request: Request):# Not confirmed as the live turn: latch this record cancelled in blob + graph (keep# them consistent) and let the turn's own resp_is_cancelled check settle it.rec["status"] = "cancelled"+ rec.setdefault("_completed_at", time.time()) # the turns feed's completed_attry:_resp_cache_forget(response_id)await _blob_put(f"responses/{response_id}.json",diff --git a/gateway/tests/test_turn_times.py b/gateway/tests/test_turn_times.pynew file mode 100644index 00000000..ebef0aa5--- /dev/null+++ b/gateway/tests/test_turn_times.py@@ -0,0 +1,179 @@+"""The turns feed says when each turn began and ended (UHP 2026-10-19, Sessions §3).++GET /v1/sessions/{id}/turns carried no time on its rows, so a reader had to fetch each turn's+response for it. Every row now carries `created_at`, and `completed_at` (null while the turn runs,+or when nobody knows when it ended), both in Unix seconds like every other time in the protocol,+read from the turn's own record: no read per row. The share view reads the same rows.+"""+import asyncio+import json+import os+import pathlib+import sys+import time++import pytest++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+os.environ.setdefault("HR_BACKING", "local")+import app as A # noqa: E402++BORN = 1792384812.25 # 2026-10-19T04:40:12.25Z+SECS = 1792384812+_n = [0]+++class Store:+ """The response records and their index rows, in memory."""++ def __init__(self):+ self.blobs: dict[str, bytes] = {}+ self.rows: dict[str, dict] = {}++ async def blob_put(self, key, data, kb=None):+ self.blobs[key] = data+ return True++ async def blob_get(self, key, kb=None):+ return self.blobs.get(key)++ async def vg_upsert(self, label, vid, props, raise_on_fail=False):+ self.rows.setdefault(vid, {"id": vid}).update(props)++ async def find(self, label, props):+ return [dict(r) for r in self.rows.values() if r.get("session_id") == props.get("session_id")]++ def record(self, rid: str) -> dict:+ return json.loads(self.blobs[f"responses/{rid}.json"])+++def store(monkeypatch):+ s = Store()+ monkeypatch.setattr(A, "_blob_put", s.blob_put)+ monkeypatch.setattr(A, "_blob_get", s.blob_get)+ monkeypatch.setattr(A, "_vg_upsert", s.vg_upsert)+ monkeypatch.setattr(A.BACKING, "graph", s, raising=False)++ async def vertex_get(sid):+ return {"status": "running"}+ monkeypatch.setattr(A, "_vertex_get", vertex_get)+ monkeypatch.setattr(A, "_prefix_from_vertex", lambda sid, v: None)+ return s+++def _ids() -> tuple[str, str]:+ _n[0] += 1+ return f"hsess_times{_n[0]}", f"resp_times{_n[0]}"+++def _record(rid: str, sid: str, status: str, created_at: float = BORN) -> dict:+ return {"id": rid, "object": "response", "created_at": int(created_at), "status": status, "error": None,+ "output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "Done."}]}]+ if status == "completed" else [],+ "_session_id": sid, "_org": "org.times", "_input": [{"role": "user", "content": "hello"}]}+++def _put(rid, sid, status, created_at=BORN):+ return A._resp_put(rid, _record(rid, sid, status, created_at), "org.times", sid, None, status, created_at, True)+++def _feed(sid):+ return asyncio.run(A._session_turns_data(sid))["turns"]+++def test_a_row_carries_created_at_and_completed_at_once_the_turn_is_done(store):+ sid, rid = _ids()+ asyncio.run(_put(rid, sid, "running"))+ before = time.time()+ asyncio.run(_put(rid, sid, "completed"))+ after = time.time()+ (row,) = _feed(sid)+ assert row["status"] == "completed"+ assert row["created_at"] == SECS and type(row["created_at"]) is int+ stamp = store.record(rid)["_completed_at"]+ assert before <= stamp <= after+ assert type(row["completed_at"]) is int and row["completed_at"] == int(stamp)+ assert row["completed_at"] >= row["created_at"]+ # the stamp stays internal: the response object never shows it+ assert "_completed_at" not in A._strip_internal(store.record(rid))+++def test_a_running_turn_has_completed_at_null(store):+ sid, rid = _ids()+ asyncio.run(_put(rid, sid, "running"))+ (row,) = _feed(sid)+ assert row["status"] == "running"+ assert row["created_at"] == SECS and row["completed_at"] is None+ assert "_completed_at" not in store.record(rid)+++def test_a_cancel_that_latches_the_record_says_when_the_turn_ended(store, monkeypatch):+ """A cancel that cannot prove it owns the live turn latches the record itself: that is its end."""+ sid, rid = _ids()+ asyncio.run(_put(rid, sid, "running"))++ async def principal(request):+ return {"org": "org.times"}++ async def in_reach(principal, rec):+ return True++ async def vertex_get(sid):+ return {"status": "done"} # the sandbox is not on this turn: no fast path+ monkeypatch.setattr(A, "_principal", principal)+ monkeypatch.setattr(A, "_response_in_reach", in_reach)+ monkeypatch.setattr(A, "_vertex_get", vertex_get)+ monkeypatch.setattr(A.control_store, "enabled", lambda: False)+ before = time.time()+ out = asyncio.run(A.cancel_response(rid, None))+ assert out["status"] == "cancelled" and "_completed_at" not in out+ stamp = store.record(rid)["_completed_at"]+ assert before <= stamp <= time.time()+ (row,) = _feed(sid)+ assert row["status"] == "cancelled" and row["completed_at"] == int(stamp)+++def test_a_record_that_never_said_when_it_ended_reads_null_and_its_birth_falls_back_to_the_index(store):+ sid, rid = _ids()+ old = {k: v for k, v in _record(rid, sid, "completed").items() if k != "created_at"} # before either field+ store.blobs[f"responses/{rid}.json"] = json.dumps(old).encode()+ store.rows[rid] = {"id": rid, "session_id": sid, "status": "completed", "created_at": str(BORN)}+ (row,) = _feed(sid)+ assert row["created_at"] == SECS and row["completed_at"] is None+++def test_the_share_view_carries_the_same_fields(store, monkeypatch):+ sid, rid = _ids()+ asyncio.run(_put(rid, sid, "completed"))++ async def share_sid(token):+ return sid if token == "tok" else None+ monkeypatch.setattr(A, "_share_sid", share_sid)+ (row,) = asyncio.run(A.share_turns("tok"))["turns"]+ assert row["created_at"] == SECS and type(row["completed_at"]) is int+ assert row == _feed(sid)[0]+++def test_the_time_form():+ assert A._unix_s(BORN) == SECS and A._unix_s(str(BORN)) == SECS and A._unix_s(SECS) == SECS+ assert A._unix_s(None) is None and A._unix_s(0) is None and A._unix_s("x") is None+ assert A._unix_s(float("inf")) is None and A._unix_s(float("nan")) is None+++def test_the_rows_match_the_protocols_turn_item(store):+ """What the conformance suite checks (Sessions §3): the rows, running and done, against TurnItem."""+ jsonschema = pytest.importorskip("jsonschema")+ schema = json.loads((pathlib.Path(__file__).resolve().parents[2] / "protocol" / "conformance"+ / "uhp_conformance" / "uhp-2026-10-19.schema.json").read_text())+ props = schema["$defs"]["TurnItem"]["properties"]+ assert props["created_at"]["type"] == "integer" and props["completed_at"]["type"] == ["integer", "null"]+ sid, done = _ids()+ _, live = _ids()+ asyncio.run(_put(done, sid, "completed"))+ asyncio.run(_put(live, sid, "running", created_at=BORN + 5))+ rows = _feed(sid)+ assert [r["completed_at"] is None for r in rows] == [False, True]+ v = jsonschema.Draft202012Validator({**schema, "$ref": "#/$defs/TurnItem"})+ for r in rows:+ assert not list(v.iter_errors(r)), rdiff --git a/protocol/CHANGELOG.md b/protocol/CHANGELOG.mdindex 7fc0beb7..dd6235a8 100644--- a/protocol/CHANGELOG.md+++ b/protocol/CHANGELOG.md@@ -2,6 +2,14 @@All notable changes to the Unified Harness Protocol.+## 2026-10-19, addition: when each turn began and ended++Additive. Each item of a session's `turns` ([Sessions §3](versions/2026-10-19/sessions.md#3-inspecting-a-session))+SHOULD carry `created_at`, when the turn began, and `completed_at`, when it ended, both in Unix+seconds as every other time in the protocol. `completed_at` is `null` while the turn is running and+when the server does not know when it ended. An imported turn carries the time it was imported for+both. A client no longer reads each turn's response to learn its time. `TurnItem` gains both fields.+## 2026-10-19, addition: earlier turns (capability `input_history`)Additive. A request without `previous_response_id` may carry the conversation so far as `user` anddiff --git a/protocol/conformance/uhp_conformance/uhp-2026-10-19.schema.json b/protocol/conformance/uhp_conformance/uhp-2026-10-19.schema.jsonindex 9823b771..c40d4631 100644--- a/protocol/conformance/uhp_conformance/uhp-2026-10-19.schema.json+++ b/protocol/conformance/uhp_conformance/uhp-2026-10-19.schema.json@@ -1130,6 +1130,17 @@"imported": {"type": "boolean","description": "A turn the session was started with (Tasks §2.1, capability `input_history`): completed,\nno model ran and nothing was spent. `false`, or absent, for a turn that ran.\n"+ },+ "created_at": {+ "type": "integer",+ "description": "When the turn began, in Unix seconds, as the Response's `created_at`. An imported turn\ncarries the time it was imported.\n"+ },+ "completed_at": {+ "type": [+ "integer",+ "null"+ ],+ "description": "When the turn ended, in Unix seconds. `null` while the turn is running, and when the\nserver does not know when it ended. An imported turn carries the time it was imported.\n"}},"additionalProperties": truediff --git a/protocol/schema/uhp-2026-10-19.openapi.yaml b/protocol/schema/uhp-2026-10-19.openapi.yamlindex 763d08e4..98e58e43 100644--- a/protocol/schema/uhp-2026-10-19.openapi.yaml+++ b/protocol/schema/uhp-2026-10-19.openapi.yaml@@ -2333,6 +2333,16 @@ components:description: |A turn the session was started with (Tasks §2.1, capability `input_history`): completed,no model ran and nothing was spent. `false`, or absent, for a turn that ran.+ created_at:+ type: integer+ description: |+ When the turn began, in Unix seconds, as the Response's `created_at`. An imported turn+ carries the time it was imported.+ completed_at:+ type: [integer, 'null']+ description: |+ When the turn ended, in Unix seconds. `null` while the turn is running, and when the+ server does not know when it ended. An imported turn carries the time it was imported.additionalProperties: trueEnvironment:diff --git a/protocol/schema/uhp-2026-10-19.schema.json b/protocol/schema/uhp-2026-10-19.schema.jsonindex 9823b771..c40d4631 100644--- a/protocol/schema/uhp-2026-10-19.schema.json+++ b/protocol/schema/uhp-2026-10-19.schema.json@@ -1130,6 +1130,17 @@"imported": {"type": "boolean","description": "A turn the session was started with (Tasks §2.1, capability `input_history`): completed,\nno model ran and nothing was spent. `false`, or absent, for a turn that ran.\n"+ },+ "created_at": {+ "type": "integer",+ "description": "When the turn began, in Unix seconds, as the Response's `created_at`. An imported turn\ncarries the time it was imported.\n"+ },+ "completed_at": {+ "type": [+ "integer",+ "null"+ ],+ "description": "When the turn ended, in Unix seconds. `null` while the turn is running, and when the\nserver does not know when it ended. An imported turn carries the time it was imported.\n"}},"additionalProperties": truediff --git a/protocol/versions/2026-10-19/index.md b/protocol/versions/2026-10-19/index.mdindex 6fd4a9bc..0f9eee75 100644--- a/protocol/versions/2026-10-19/index.md+++ b/protocol/versions/2026-10-19/index.md@@ -120,6 +120,9 @@ Against `2026-10-04`, one rule changes and the rest is additive.publication and additive: with the `input_history` capability, the messages before the last `user`message are the conversation so far, kept as the session's first turns marked `imported`. Beyonda server's bounds the request is read as without the capability, never refused.+- **Each turn says when it began and ended** ([Sessions §3](sessions.md#3-inspecting-a-session)),+ added after publication and additive: a session's turns carry `created_at` and `completed_at` in+ Unix seconds, `completed_at` `null` while the turn runs or when its end is not known.- **Harness writes refuse what they cannot store** ([Harnesses §5.1](harnesses.md#51-create)): a fieldthe harness does not have, and a `default_model` its base does not run, are `422`. Both maintainedservers have done this since 2026-10-10, inside `2026-10-04`; this version states it.diff --git a/protocol/versions/2026-10-19/sessions.md b/protocol/versions/2026-10-19/sessions.mdindex ea6b57c4..f351f856 100644--- a/protocol/versions/2026-10-19/sessions.md+++ b/protocol/versions/2026-10-19/sessions.md@@ -94,6 +94,12 @@ against one implementation's habits.A server with the `input_history` capability marks each turn a session was started with([Tasks §2.1](tasks.md#21-earlier-turns)) `imported: true`, and every turn that ran `imported: false`.+Each turn SHOULD also carry `created_at`, when it began, and `completed_at`, when it ended, both+integers in Unix seconds like the Response's `created_at` ([Tasks §3](tasks.md#3-the-response-object)).+`completed_at` is `null` while the turn is running and when the server does not know when it ended.+An imported turn carries the time it was imported for both, so a client reading a session's history+never has to fetch each turn's response to learn when it happened.+A session whose turns read an environment carries `environment`, the environment's id, so a clientcan tell which project a conversation worked in ([Environments §6](environments.md#6-what-a-session-sees)).