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
gateway: a grok turn streams its answer as deltas when partial messages are asked for (#533)
ShryukGrandhi67c35193e321
diff --git a/gateway/app.py b/gateway/app.pyindex b6973d3d..2aebe23f 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -9567,6 +9567,17 @@ async def _idem_replay(resp_id: str, stream: bool):headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})+def _want_partial(backend: str, meta: dict) -> bool:+ """Token-level streaming (CT-127): opt in globally via env HARNESS_STREAM_PARTIAL=1, or per-request+ via metadata.stream_partial (for testing). Claude uses --include-partial-messages; codex diffs+ item.updated (self-healing → batch if it doesn't emit updates); grok (Grok Build 1.0.41) takes the+ same --include-partial-messages and emits Claude Code's stream_event text deltas, which+ _grok_to_claude passes through the claude normaliser. Default off = current batch behavior, so a+ rollback is just flipping the env with no redeploy."""+ return backend in ("claude", "codex", "grok") and (+ os.environ.get("HARNESS_STREAM_PARTIAL", "0") == "1" or bool(meta.get("stream_partial")))++@app.post("/v1/responses")async def create_response(body: CreateResponseBody, request: Request):principal = await _principal(request)@@ -9692,12 +9703,7 @@ async def create_response(body: CreateResponseBody, request: Request):or _route_backend(model_req or body.model, body.backend))# Server-side model permission (CT-124): a model this backend cannot serve is refused here.model_req = await _resolve_model_policy(model_req, hv, backend, org)- # Token-level streaming (CT-127): opt in globally via env HARNESS_STREAM_PARTIAL=1, or per-request- # via metadata.stream_partial (for testing). Claude uses --include-partial-messages; codex diffs- # item.updated (self-healing → batch if it doesn't emit updates). Default off = current batch- # behavior, so a rollback is just flipping the env with no redeploy.- want_partial = (backend in ("claude", "codex") and (- os.environ.get("HARNESS_STREAM_PARTIAL", "0") == "1" or bool(meta.get("stream_partial"))))+ want_partial = _want_partial(backend, meta)# Codex streaming path: run the codex turn via the app-server protocol (the only codex mode that# streams assistant text). Flag-gated (env HARNESS_CODEX_APPSERVER or metadata.codex_appserver);# default off keeps codex on the stable `codex exec` path. Rollback = flip env, no redeploy.diff --git a/gateway/tests/test_stream_partial.py b/gateway/tests/test_stream_partial.pynew file mode 100644index 00000000..9ff18852--- /dev/null+++ b/gateway/tests/test_stream_partial.py@@ -0,0 +1,96 @@+"""Token-level streaming: a streamed grok turn gave its answer only when the turn settled.++The gate that asks the runner for partial messages admitted claude and codex only, so a grok turn+streamed nothing until it ended and the whole answer arrived as ONE response.output_text.delta.+The runner already carried grok's half of the path (--include-partial-messages on the grok argv,+and the claude passthrough that reads grok's `stream_event` framing); what was missing was the+gate, so none of it was reachable.++The default is unchanged: the gate is opt-in, through HARNESS_STREAM_PARTIAL=1 or+metadata.stream_partial, so a rollback is flipping the env with no redeploy.+"""+import os+import pathlib+import sys++import pytest+from fastapi.testclient import TestClient # noqa: E402++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+os.environ.setdefault("HR_BACKING", "local")+import app as A # noqa: E402++ORG = "org_e"+++def api(monkeypatch):+ async def principal(request):+ return {"org": ORG, "member": "me@local"}+ monkeypatch.setattr(A, "_principal", principal)+ monkeypatch.setattr(A, "_response_in_reach", lambda p, rec: _true())+ monkeypatch.setattr(A, "_harness_in_reach", lambda p: _true())+ return TestClient(A.app)+++async def _true():+ return True+++def _run(api, monkeypatch, backend: str, body: dict) -> dict:+ """The body the turn handed the runner's /turn, with the world's edges stubbed out.++ The request goes through the real endpoint, so the gate that decides whether a turn asks for+ partial messages is the one under test, not a helper called directly.+ """++ async def _chain(org, backend, model):+ return [{"backend": backend}]+ monkeypatch.setattr(A, "_resolve_chain", _chain)++ seen: dict = {}++ async def _exec(tr, **kw):+ seen["kwargs"] = kw+ return "completed", [], {}++ monkeypatch.setattr(A, "_resp_execute", _exec)++ # The harness is named in metadata, which is where create_response reads it from+ # (`meta.get("harness_id")`), so the turn really runs on the backend under test.+ r = api.post("/v1/responses", json={"input": "hi", "metadata": {"harness_id": backend}, **body})+ assert r.status_code == 200, r.text+ return seen.get("kwargs") or {}+++def test_a_grok_turn_asks_the_runner_for_partial_messages(api, monkeypatch):+ """The seam the change opens: a grok turn whose gate is open must reach the runner carrying+ `partial_messages`, because that is the only thing that makes the runner add+ `--include-partial-messages` to the grok argv. Without the gate the flag never reaches the+ runner, and none of the runner's existing support helps."""+ monkeypatch.setenv("HARNESS_STREAM_PARTIAL", "1")+ kw = _run(api, monkeypatch, "grok", {})+ assert kw.get("partial_messages") is True, (+ f"the executor was handed {kw.get('partial_messages')!r} instead of the request for "+ "partial messages")+++def test_a_grok_turn_asks_for_no_partial_messages_by_default(api, monkeypatch):+ """The default is unchanged: a turn that asked for nothing gets the batch path, so a server+ that never sets the flag is unaffected by this change."""+ monkeypatch.delenv("HARNESS_STREAM_PARTIAL", raising=False)+ kw = _run(api, monkeypatch, "grok", {})+ assert kw.get("partial_messages") is False, (+ f"the executor was handed {kw.get('partial_messages')!r} with no request for partial "+ "messages")+++def test_a_backend_with_no_partial_path_is_not_asked_for_partial_messages(api, monkeypatch):+ """A backend whose CLI cannot stream partials is not asked to. The gate names the backends+ that can, and a backend outside it stays on the batch path however the request is made."""+ monkeypatch.setenv("HARNESS_STREAM_PARTIAL", "1")+ monkeypatch.setattr(A, "_backend_of_builtin", lambda harness_id: "qwen")+ kw = _run(api, monkeypatch, "qwen", {})+ assert kw.get("partial_messages") is False, (+ f"the executor was handed {kw.get('partial_messages')!r} for a backend that cannot stream "+ "partials")diff --git a/gateway/tests/test_stream_partial_gate.py b/gateway/tests/test_stream_partial_gate.pynew file mode 100644index 00000000..498d97b4--- /dev/null+++ b/gateway/tests/test_stream_partial_gate.py@@ -0,0 +1,36 @@+"""Which backends a streamed task asks for token-level deltas (HARNESS_STREAM_PARTIAL=1 or+metadata.stream_partial), and that the default stays batch.++grok is in the gate because Grok Build 1.0.41 with `--include-partial-messages` emits Claude Code's+`stream_event` content_block_delta lines in its streaming-messages-json (measured at a local stub:+a three-chunk answer came back as three text_delta lines), and _grok_to_claude hands them to the+claude passthrough, which turns each into its own response.output_text.delta.+"""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from app import _want_partial # noqa: E402+++def test_default_is_batch_for_every_backend(monkeypatch):+ monkeypatch.delenv("HARNESS_STREAM_PARTIAL", raising=False)+ for backend in ("claude", "codex", "grok", "hermes"):+ assert _want_partial(backend, {}) is False+++def test_env_switch_streams_grok(monkeypatch):+ monkeypatch.setenv("HARNESS_STREAM_PARTIAL", "1")+ assert _want_partial("grok", {}) is True+ assert _want_partial("claude", {}) is True+ assert _want_partial("codex", {}) is True+++def test_metadata_switch_streams_grok(monkeypatch):+ monkeypatch.delenv("HARNESS_STREAM_PARTIAL", raising=False)+ assert _want_partial("grok", {"stream_partial": True}) is True+++def test_a_backend_without_deltas_stays_batch(monkeypatch):+ monkeypatch.setenv("HARNESS_STREAM_PARTIAL", "1")+ assert _want_partial("hermes", {}) is Falsediff --git a/runner/tests/test_grok_backend.py b/runner/tests/test_grok_backend.pyindex 0df35d95..737d61b7 100644--- a/runner/tests/test_grok_backend.py+++ b/runner/tests/test_grok_backend.py@@ -106,6 +106,26 @@ def test_a_successful_turn_passes_through_with_the_answer_and_leaves_usage_to_thassert res["usage"] == {} and "modelUsage" not in res and "model" not in res+def _delta(text):+ # Captured from 1.0.41 with --include-partial-messages (a stub streaming three chunks).+ return {"type": "stream_event", "event": {"type": "content_block_delta", "index": 0,+ "delta": {"type": "text_delta", "text": text}}, "parent_tool_use_id": None,+ "session_id": SID, "uuid": "d"}+++def test_partial_mode_streams_each_text_delta_and_does_not_repeat_the_whole_message():+ chunks = ["The sky is blue. ", "Grass is green. ", "Snow is white."]+ whole = "".join(chunks)+ start = {"type": "stream_event", "event": {"type": "content_block_start", "index": 0,+ "content_block": {"type": "text", "text": ""}}, "session_id": SID, "uuid": "s"}+ stop = {"type": "stream_event", "event": {"type": "message_stop"}, "session_id": SID, "uuid": "e"}+ message = {**TEXT, "message": {**TEXT["message"], "content": [{"type": "text", "text": whole}]}}+ out, _ = _norm([INIT, start, *map(_delta, chunks), stop, message, {**OK, "result": whole}], partial=True)+ texts = [c["text"] for e in out if e["type"] == "assistant" for c in e["message"]["content"]]+ assert texts == chunks+ assert out[-1]["type"] == "result" and out[-1]["result"] == whole and out[-1]["usage"] == {}++def test_a_provider_failure_is_a_failed_turn_with_the_providers_sentence():out, _ = _norm([INIT, FAIL_401])res = out[-1]