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
dual loop: a harness that drives another one, and the handoff on the result (#232)
github-actions[bot]f1b69ab48585
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 77e7386d..77174c4b 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -57,7 +57,7 @@ jobs:# runner itself does not, so it stays out of requirements.txt and lives with pytest here.# The System One Harness is on the runner's venv in the image (docker/entrypoint.sh pins the tag);# the driver's tests import it, and skip without it, so the suite installs the same pin.- - run: pip install -r runner/requirements.txt pytest pytest-asyncio httpx "systemone-harness @ git+https://github.com/HarnessRouter/[email protected]"+ - run: pip install -r runner/requirements.txt pytest pytest-asyncio httpx "systemone-harness @ git+https://github.com/HarnessRouter/[email protected]"- run: python -m pytest runner/tests -qconformance:diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex babd2e5f..627672d7 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -346,7 +346,7 @@ KIMI_PIN="${HR_KIMI_VERSION:-2.0.0}"; KIMI_PIN="${KIMI_PIN#v}"# decision model, pinned by git tag. Its own venv on the data volume like openhands and aider: three# small dependencies (httpx, pyyaml, the MCP SDK), installed once and rebuilt when the pin moves.# The executable is the venv's python, which the runner hands runner/systemone_driver.py.-SYSTEMONE_PIN="${HR_SYSTEMONE_VERSION:-0.3.1}"; SYSTEMONE_PIN="${SYSTEMONE_PIN#v}"+SYSTEMONE_PIN="${HR_SYSTEMONE_VERSION:-0.4.0}"; SYSTEMONE_PIN="${SYSTEMONE_PIN#v}"# HR_SYSTEMONE_SPEC overrides where pip takes the package from (a mirror, a fork, a local tree# copied into a derived image); the version proven below is the pin either way. The browser extra# brings Browser Use, and with it the page and game environments; the Chromium they drive isdiff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.mdindex ac9d4da4..3dd76a0a 100644--- a/docs/support-matrix-notes.md+++ b/docs/support-matrix-notes.md@@ -1270,7 +1270,7 @@ both from the doc.## systemone: the System One Harness as the fifteenth base (2026-09-19)Not a coding CLI. The base runs the open-source System One Harness-(github.com/HarnessRouter/SystemOneHarness, Apache-2.0, pinned at v0.3.1 in `docker/entrypoint.sh`)+(github.com/HarnessRouter/SystemOneHarness, Apache-2.0, pinned at v0.4.0 in `docker/entrypoint.sh`)over TypeSafe's Jev, a decision model: it answers typed questions (a choice, a yes/no probability,a score) with probabilities in one pass and writes no text. Every step is one request carryingthe next action as a choice over what the environment offers right now, every parameter of every@@ -1326,3 +1326,32 @@ an OpenRouter connection; an order-desk turn on jev-preview completes in 6 actioout), and on jev-latest the same; a turn on jev-1.13 with only a TypeSafe connection answers 400`invalid_input`, "no provider configured for backend systemone". The harness alone (`s1 run` withTYPESAFE_API_KEY) completes the order desk in 5 actions, 0.86 s wall.+### The dual loop (2026-09-21)++An outer harness calibrates an inner one through the platform's own API (docs/dual-loop.md in the+System One Harness repository, Appendix B). On this tree:++- **A harness that drives another one.** `calibrates` on a harness names the one harness it may+ drive. Every turn of such a harness is handed `HR_API_URL`, `HR_INNER_HARNESS` and+ `HR_CALIBRATION_TOKEN`, a credential signed like the broker's, scoped to that harness and good for+ the turn's wall-clock cap plus a margin. With it the turn starts that harness's runs, reads their+ sessions, turns and files, reads and publishes that harness's package (`PUT+ /v1/harnesses/{id}/plugin`, or `PUT /v1/harnesses/{id}` with `plugins`) and relaunches its kit;+ every other route answers 403, a session of another harness is not found, and the credential+ cannot change `calibrates`. Never an org key, never a provider key.+- **The package's configuration.** The driver reads `config.yaml` at the root of the package the+ environment's server runs from (the root is the `PLUGIN_ROOT` the runner's launcher exports): its+ instructions and gate replace the space's, its encoder settings shape the state, its version rides+ the trace, and the server gets the same file as `SYSTEMONE_CONFIG`. `trace.json` lands in the+ session workspace. A request's `metadata.systemone.script` selects a scripted provider, a probe.+- **The handoff.** A run that ends on a refusal or an escalation carries the branch on the result+ event, the status body and the response's `incomplete_details` beside its reason; the console says+ where it handed off and on what judgment. Null on every other ending.++Measured on hr-test, 2026-09-21, on a derived image of 851e4d1 with the harness at v0.4.0: a+Calibrator on the pi base read the Mario harness by name, listed its sessions, was refused on keys+and on the harness list, and started an inner run on it; a Mario run on the package's config v1+wrote `trace.json` with `config_version: 1` and 61 archived frames; a probe with a four-action+script ran on `script/s1` and finished. The calibration itself (baseline, one change, validation)+runs on a Calibrator on the claude base with the calibrate package.+diff --git a/gateway/app.py b/gateway/app.pyindex f9291375..80318092 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -868,6 +868,70 @@ _BROKERABLE_PROVIDERS = {"anthropic", "tokenrouter", "openai", "azure", "azure-f_NATIVE_ONLY_BACKENDS = {"gemini"}+# ── A harness that drives another harness ─────────────────────────────────────────────────────+# A Calibrator (docs/dual-loop.md, Appendix B) starts runs on ONE inner harness, reads those runs+# and publishes that harness's package. Its turn process gets the platform's own API and a+# credential scoped to exactly that: never an org key, never a provider key, and it expires with+# the turn. The credential is signed like the broker's (sid|org|inner|exp + hmac) and resolves to+# a principal that carries its scope, which the routes below enforce.+HR_PLATFORM_API_URL = os.environ.get("HR_PLATFORM_API_URL", "http://127.0.0.1:8080")+_CALIBRATION_TTL_S = int(os.environ.get("HR_CALIBRATION_TTL_S", str(3 * 3600)))+++def _mint_calibration_token(sid: str, org: str, inner: str, ttl_s: int) -> str:+ exp = str(int(time.time()) + max(int(ttl_s), 60))+ body = f"{sid}|{org}|{inner}|{exp}"+ sig = hmac.new((INTERNAL_KEY or "dev-insecure").encode(), b"calibration|" + body.encode(),+ hashlib.sha256).hexdigest()+ return "hrc_" + base64.urlsafe_b64encode(body.encode()).decode().rstrip("=") + "." + sig+++def _verify_calibration_token(tok: str) -> dict | None:+ """{sid, org, inner, exp} for a valid unexpired credential, else None."""+ try:+ raw, sig = tok[len("hrc_"):].split(".", 1)+ body = base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4)).decode()+ want = hmac.new((INTERNAL_KEY or "dev-insecure").encode(), b"calibration|" + body.encode(),+ hashlib.sha256).hexdigest()+ if not hmac.compare_digest(want, sig):+ return None+ sid, org, inner, exp = body.split("|")+ if int(exp) < time.time() or not (org and inner):+ return None+ return {"sid": sid, "org": org, "inner": inner, "exp": int(exp)}+ except Exception: # noqa: BLE001 - malformed is invalid+ return None+++def _calibration_route_allowed(method: str, path: str, inner: str) -> bool:+ """The routes the credential may reach: start and read runs (the harness check is on the+ session), read and publish the ONE harness it drives, relaunch its kit."""+ if path.startswith("/api/harness/"):+ path = path[len("/api/harness"):]+ h = re.escape(inner)+ allowed = (+ ("POST", r"/v1/responses"), ("GET", r"/v1/responses/[^/]+"), ("POST", r"/v1/responses/[^/]+/cancel"),+ ("GET", r"/v1/sessions"), ("GET", r"/v1/sessions/[^/]+"), ("GET", r"/v1/sessions/[^/]+/turns"),+ ("GET", r"/v1/sessions/[^/]+/files(/.*)?"),+ ("GET", rf"/v1/harnesses/{h}"), ("PUT", rf"/v1/harnesses/{h}"),+ ("GET", rf"/v1/harnesses/{h}/plugin"), ("PUT", rf"/v1/harnesses/{h}/plugin"),+ ("POST", r"/v1/kits/[^/]+/launch"),+ )+ return any(m == method.upper() and re.fullmatch(pat, path) for m, pat in allowed)+++def _calibration_env(hv: dict | None, org: str, sid: str, timeout_s: int | None) -> dict | None:+ """What a turn of a harness that drives another one is handed, or None: the platform's own+ API and a credential scoped to the harness it names, good for the turn's wall-clock cap plus+ a margin (the default ceiling when the turn carries none)."""+ inner = str((hv or {}).get("calibrates") or "").strip()+ if not inner:+ return None+ ttl = (int(timeout_s) + 600) if timeout_s else _CALIBRATION_TTL_S+ return {"HR_API_URL": HR_PLATFORM_API_URL, "HR_INNER_HARNESS": inner,+ "HR_CALIBRATION_TOKEN": _mint_calibration_token(sid, org, inner, ttl)}++def _mint_turn_cred(sid: str, conn_name: str) -> str:"""Per-turn credential: sid.conn.exp.hmac — resolvable back to exactly one connection."""exp = str(int(time.time()) + _BROKER_TTL_S)@@ -2497,6 +2561,7 @@ async def _adopt_orphan_turn(sid: str, org: str, v: dict) -> bool:translator.incomplete_reason = "timeout"elif st == "incomplete":translator.incomplete_reason = str(s.get("reason") or "incomplete")+ translator.handoff = s.get("handoff") if isinstance(s.get("handoff"), dict) else Nonebreakif terminal is None:return False # still running / adoption interrupted — later sweep retries@@ -4040,6 +4105,8 @@ async def list_sessions(request: Request, limit: int = 20, cursor: str = "",if not org:raise HTTPException(400, "no org resolved for this principal")harness = harness or str(request.headers.get("x-harness-id") or "")+ if p.get("calibration"):+ harness = str(p["calibration"].get("inner") or "") # the credential sees one harness's runs# A workspace-scoped principal (workspace-stamped API key, or the console's workspace header)# sees only its workspace's sessions; unscoped principals keep the whole-org view.return await _session_cards(org, limit, cursor, member, harness,@@ -4053,6 +4120,9 @@ async def _owned_session(request: Request, sid: str) -> tuple[str, dict]:v = await _vertex_get(sid)if not v or str(v.get("tenant") or "") != org or str(v.get("status")) == "deleted":raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")+ c = p.get("calibration")+ if c and str(v.get("harness_id") or "") != str(c.get("inner") or ""):+ raise uhp_error(404, "session_not_found", "No session with that id.", "session_id") # not its harness'sreturn org, v@@ -5183,6 +5253,11 @@ class _RespTranslator:# confidently sent an operator debugging a 400-step default that was never reached.# "max_steps" | "timeout" | "interrupted"; empty = unknown (old records).self.incomplete_reason: str = ""+ # The handoff of a run that stopped on a refusal or an escalation (systemone): the state it+ # stopped on, the questions, the answers with their probabilities, the weakest judgment, the+ # threshold, the risk class and the step, so a router can hand the same state to a System+ # Two harness or a person without reading the trace (#227). None on every other ending.+ self.handoff: dict | None = None# run metadata (CT-124): the model the caller asked for, and whether the gateway substituted# the harness's authorized default because the request was unavailable for this backend.self.requested_model = ""@@ -5222,7 +5297,7 @@ class _RespTranslator:meta["ignored_fields"] = self.ignoredreturn {"id": self.resp_id, "object": "response", "created_at": int(self.created_at),"status": status, "error": self.error,- "incomplete_details": ({"reason": self.incomplete_reason}+ "incomplete_details": ({"reason": self.incomplete_reason, "handoff": self.handoff}if status == "incomplete" and self.incomplete_reason else None),"previous_response_id": self.prev, "model": self.model,"output": self.output, "store": self.store, "usage": self.usage,@@ -6765,7 +6840,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, sharness_id: str = "", max_step: int = 40,timeout_s: int | None = None,hdr_vals: dict[str, str] | None = None,- partial_messages: bool = False,+ partial_messages: bool = False, probe: dict | None = None,codex_appserver: bool = False,hv: dict | None = None) -> tuple[str, list[dict], dict]:"""Hydrate → run turn over the connection chain → translate events to `emit` → collect produced@@ -6940,6 +7015,13 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s# Image generation, when an integration can serve it. A per-turn credential for# the broker, never a provider key — see _image_auth."image_auth": image_auth,+ # A harness that drives another one: the platform's own API and a credential+ # scoped to that harness, for this turn (see _calibration_env).+ "env": _calibration_env(hv, org, sid, timeout_s),+ # A probe (docs/dual-loop.md, Appendix B): `metadata.systemone.script` names the+ # actions a scripted provider answers instead of the model. The additive+ # extension point of the protocol; nothing else of the metadata reaches the runner.+ "metadata": probe,# idempotency: all _sandbox_json retries of THIS turn share the response id, so a# lost/slow first reply that gets retried dedups to the same runner turn (no re-exec)."idempotency_key": f"{translator.resp_id}:{name}",@@ -7083,6 +7165,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s# retried on another connection, because nothing went wrong with this one.terminal = "incomplete"translator.incomplete_reason = str(s.get("reason") or "incomplete")+ translator.handoff = s.get("handoff") if isinstance(s.get("handoff"), dict) else Noneelif st in ("cancelled", "timeout"):# user cancel / wall-clock cap end the SESSION's turn — never retry it# on the next connection in the chain (that would re-run the whole task)@@ -7281,7 +7364,16 @@ async def _principal(request: Request) -> dict:return hdrauth = h.get("authorization", "")if auth[:7].lower() == "bearer ":- p = await _apikey_resolve(auth[7:].strip())+ tok = auth[7:].strip()+ if tok.startswith("hrc_"):+ c = _verify_calibration_token(tok)+ if not c:+ raise HTTPException(401, "calibration credential invalid or expired")+ if not _calibration_route_allowed(request.method, request.url.path, c["inner"]):+ raise uhp_error(403, "forbidden", "This credential drives one harness: it starts that "+ "harness's runs, reads them, and publishes its package. Nothing else.")+ return {"org": c["org"], "member": f"calibrator:{c['sid']}", "calibration": c}+ p = await _apikey_resolve(tok)if p:return praise HTTPException(401, "missing or invalid API key")@@ -7505,6 +7597,7 @@ async def create_response(body: CreateResponseBody, request: Request):if not org:raise HTTPException(400, "no org resolved for this principal")meta = body.metadata or {}+ probe = {"systemone": meta["systemone"]} if isinstance(meta.get("systemone"), dict) else None# Request idempotency: the durable control store is the SINGLE authority (create_item = atomic# reservation). No in-process/blob/Redis fallback — a keyed request without the store fails# closed (503), never runs a divergent degraded path. idem_sha_v/idem_rhash are computed here@@ -7539,6 +7632,10 @@ async def create_response(body: CreateResponseBody, request: Request):_pv = await _vertex_get(_psid) if _psid else Noneharness_id = str((_pv or {}).get("harness_id") or "")harness_name = str(meta.get("harness_name") or "")+ _cal = principal.get("calibration")+ if _cal and harness_id != str(_cal.get("inner") or ""):+ raise uhp_error(403, "forbidden", "This credential starts runs on the one harness it drives.",+ "metadata.harness_id", {"harness_id": _cal.get("inner")})hv = await _harness_vertex(harness_id) if harness_id else None# A deleted harness cannot run new turns (same 404 as the read endpoints). Cross-org runs are# ALLOWED — sibling products legitimately run a user's harness under a platform credential, and@@ -7774,7 +7871,7 @@ async def create_response(body: CreateResponseBody, request: Request):prompt=prompt, files_in=files_in, resume=resume, emit=bus_emit_bg,model_req=model_req, user_text=user_text, harness_id=harness_id,max_step=max_step, timeout_s=timeout_s, hdr_vals=hdr_vals,- partial_messages=want_partial, codex_appserver=want_appserver, hv=hv)+ partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe)# A failed turn says why in the transcript, not only in the response record: fail()# carries the message as an error event, which the console prints under the answer.for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):@@ -7823,7 +7920,7 @@ async def create_response(body: CreateResponseBody, request: Request):tr, org=org, member=member, sid=sid, backend=backend, chain=chain,prompt=prompt, files_in=files_in, resume=resume, emit=emit, model_req=model_req,user_text=user_text, harness_id=harness_id, max_step=max_step,- timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv)+ timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe)# A failed turn says why in the transcript, not only in the response record: fail()# carries the message as an error event, which the console prints under the answer.for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):@@ -7881,7 +7978,7 @@ async def create_response(body: CreateResponseBody, request: Request):tr, org=org, member=member, sid=sid, backend=backend, chain=chain,prompt=prompt, files_in=files_in, resume=resume, emit=bus_emit, model_req=model_req,user_text=user_text, harness_id=harness_id, max_step=max_step,- timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv)+ timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe)# A failed turn says why in the transcript, not only in the response record: fail()# carries the message as an error event, which the console prints under the answer.for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):@@ -8163,6 +8260,7 @@ async def _session_turns_data(sid: str, limit: int = 0) -> dict:"error": ((rec.get("error") or {}).get("message") or None) if isinstance(rec.get("error"), dict) else None,"incomplete_reason": ((rec.get("incomplete_details") or {}).get("reason")or None),+ "handoff": ((rec.get("incomplete_details") or {}).get("handoff") or None),"_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.@@ -13666,6 +13764,11 @@ class HarnessBody(BaseModel):max_step: int | None = _either("max_step") # default agent step budget for this harness's turnstimeout_seconds: int | None = _either("timeout_seconds") # default per-turn wall-clock capadditional_headers: list | None = _either("additional_headers") # header NAMES callers may pass per request+ # The one harness this harness may drive through the platform's own API, by id: a Calibrator+ # names the harness it calibrates. Every turn of a harness that names one is handed HR_API_URL+ # and HR_CALIBRATION_TOKEN, a credential scoped to that harness and expiring with the turn+ # (docs/dual-loop.md in the System One Harness repository, Appendix B).+ calibrates: str | None = _either("calibrates")def _harness_out(v: dict) -> dict:@@ -13696,6 +13799,7 @@ def _harness_out(v: dict) -> dict:"additionalHeaders": [h for h in _parse(v.get("additional_headers")) if isinstance(h, str) and h.strip()],"maxStep": int(v.get("max_step")) if str(v.get("max_step") or "").isdigit() else None,"timeoutSeconds": int(v.get("timeout_seconds")) if str(v.get("timeout_seconds") or "").isdigit() else None,+ "calibrates": str(v.get("calibrates") or ""),"member": v.get("member") or "", "workspace": v.get("workspace") or "", "createdAt": created}@@ -13712,6 +13816,7 @@ def _harness_props(body: HarnessBody) -> dict:"disabled_tools": json.dumps(body.disabled_tools or []),"additional_headers": json.dumps([str(h).strip() for h in (body.additional_headers or [])if isinstance(h, str) and str(h).strip()]),+ "calibrates": str(body.calibrates or "").strip(),"max_step": str(body.max_step) if body.max_step else "","timeout_seconds": str(body.timeout_seconds) if body.timeout_seconds else ""}@@ -14777,6 +14882,8 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Nonawait _vg_upsert("Harness", want_h, {"kit": kit_id, "updated_at": now0})existing = await _vertex_get(want_h) or {**target, "kit": kit_id}print(f"[kits] {kit_id} now runs on {want_h}", flush=True)+ if p.get("calibration") and str((existing or {}).get("id") or "") != str(p["calibration"].get("inner") or ""):+ raise uhp_error(403, "forbidden", "This credential relaunches the kit on the harness it drives only.", "harness")if decl and not db_in and not existing:# Declaring launch.database is what makes it required: every panel this kit builds would# have nothing to read, so a launch without a connection is not a partial success.@@ -15459,12 +15566,45 @@ async def export_harness_plugin_public(hid: str, request: Request) -> dict:return await _harness_export_plugin(await _mcp_migrate(org, hid, v) or v)+class PluginPublishBody(BaseModel):+ name: str | None = None+ files: list[dict] | None = None # [{path, content|content_b64}], plugin.json among them+ blob: str | None = None # or a handle this server issued++[email protected]("/v1/harnesses/{hid}/plugin")+async def publish_harness_plugin(hid: str, body: PluginPublishBody, request: Request) -> dict:+ """Publish a package version onto a harness: the package replaces the one of the same name the+ harness holds (a kit's, or one installed by hand) and every other package stays; the harness's+ next turn runs it. This is `set_config` for a harness whose configuration lives in its package+ (docs/dual-loop.md, Appendix B), and the route a calibration credential publishes through."""+ 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 uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ v = await _mcp_migrate(org, hid, v)+ item = {k: getattr(body, k) for k in ("name", "files", "blob") if getattr(body, k)}+ if not item.get("files") and not item.get("blob"):+ raise uhp_error(400, "invalid_input", "A package needs files or a blob handle.", "files")+ previous = _plugins_of(v)+ name = _plugin_read_package(item["files"], item.get("name"))["name"] if item.get("files") else str(item.get("name") or "")+ kept = [{"name": e["name"], "blob": e["blob"]} for e in previous if e["name"] != name and e.get("blob")]+ hb = HarnessBody(name=str(v.get("name") or ""), base=str(v.get("base") or ""), plugins=[item] + kept)+ hb.plugins = await _plugins_prepare(hb, org, previous=previous)+ await _vg_upsert("Harness", hid, {"plugins": json.dumps(hb.plugins), "updated_at": str(int(time.time() * 1000))})+ out = _harness_out(await _vertex_get(hid) or {"id": hid})+ return {"id": hid, "published": name, "plugins": out["plugins"]}++@app.put("/v1/harnesses/{hid}")async def update_harness_public(hid: str, body: HarnessBody, 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 uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ _p = await _principal(request)+ if _p.get("calibration") and str(body.calibrates or "") != str(v.get("calibrates") or ""):+ raise uhp_error(403, "forbidden", "A calibration credential cannot grant calibration.", "calibrates")v = await _mcp_migrate(org, hid, v)if body.base and body.base != str(v.get("base") or ""): # Harnesses §5.2, as in update_harnessraise uhp_error(409, "harness_mismatch",diff --git a/gateway/tests/test_dual_loop.py b/gateway/tests/test_dual_loop.pynew file mode 100644index 00000000..72a23e0c--- /dev/null+++ b/gateway/tests/test_dual_loop.py@@ -0,0 +1,115 @@+"""The dual loop's platform side (docs/dual-loop.md in the System One Harness repository, App. B).++A Calibrator harness drives ONE inner harness through the platform's own API. Its turn is handed+the API and a credential scoped to that harness and expiring with the turn: never an org key,+never a provider key. The credential reaches the routes that start and read that harness's runs+and publish its package, and nothing else. A run that ends on a refusal or an escalation carries+its handoff beside its reason.+"""+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 gw # noqa: E402++INNER = "chrn_0123456789abcdef0123456789abcdef"+++def test_a_harness_that_drives_another_names_it_and_the_setting_round_trips():+ body = gw.HarnessBody(name="Calibrator", base="pi", calibrates=INNER)+ assert gw._harness_props(body)["calibrates"] == INNER+ assert gw._harness_out({"id": "h", "calibrates": INNER})["calibrates"] == INNER+ assert gw._harness_out({"id": "h"})["calibrates"] == ""+++def test_a_turn_of_such_a_harness_is_handed_the_api_and_a_scoped_credential_and_no_other_turn_is():+ assert gw._calibration_env({"calibrates": ""}, "org", "hsess1", 600) is None+ assert gw._calibration_env(None, "org", "hsess1", 600) is None+ env = gw._calibration_env({"calibrates": INNER}, "org-a", "hsess1", 600)+ assert env["HR_API_URL"] == gw.HR_PLATFORM_API_URL and env["HR_INNER_HARNESS"] == INNER+ tok = env["HR_CALIBRATION_TOKEN"]+ assert tok.startswith("hrc_")+ c = gw._verify_calibration_token(tok)+ assert c["org"] == "org-a" and c["inner"] == INNER and c["sid"] == "hsess1"+ assert 600 < c["exp"] - time.time() <= 1200 # the turn's cap plus a margin+++def test_the_credential_expires_and_a_tampered_one_is_nothing():+ tok = gw._mint_calibration_token("hsess1", "org-a", INNER, 60)+ assert gw._verify_calibration_token(tok) is not None+ # an expired one, built the way the minter builds them with a past expiry (the minter itself+ # never mints one shorter than a minute)+ import base64+ import hashlib+ import hmac+ body = f"hsess1|org-a|{INNER}|{int(time.time()) - 5}"+ sig = hmac.new((gw.INTERNAL_KEY or "dev-insecure").encode(), b"calibration|" + body.encode(), hashlib.sha256).hexdigest()+ expired = "hrc_" + base64.urlsafe_b64encode(body.encode()).decode().rstrip("=") + "." + sig+ assert gw._verify_calibration_token(expired) is None+ head, sig = tok.split(".", 1)+ assert gw._verify_calibration_token(head + "." + ("0" if sig[0] != "0" else "1") + sig[1:]) is None+ assert gw._verify_calibration_token("hrc_garbage") is None+ assert gw._verify_calibration_token("hrc_") is None+++def test_the_credential_reaches_its_harness_s_routes_and_nothing_else():+ ok = gw._calibration_route_allowed+ other = "chrn_ffffffffffffffffffffffffffffffff"+ assert ok("POST", "/v1/responses", INNER)+ assert ok("GET", "/v1/responses/resp_1", INNER)+ assert ok("POST", "/v1/responses/resp_1/cancel", INNER)+ assert ok("GET", "/v1/sessions", INNER) and ok("GET", "/v1/sessions/hsess1", INNER)+ assert ok("GET", "/v1/sessions/hsess1/turns", INNER)+ assert ok("GET", "/v1/sessions/hsess1/files", INNER) and ok("GET", "/v1/sessions/hsess1/files/observations/000001.jpg", INNER)+ assert ok("GET", f"/v1/harnesses/{INNER}", INNER) and ok("PUT", f"/v1/harnesses/{INNER}", INNER)+ assert ok("GET", f"/v1/harnesses/{INNER}/plugin", INNER) and ok("PUT", f"/v1/harnesses/{INNER}/plugin", INNER)+ assert ok("POST", "/v1/kits/mario/launch", INNER)+ assert ok("get", "/api/harness/v1/sessions", INNER) # through the console's proxy prefix+ # not its harness, not its business+ assert not ok("GET", f"/v1/harnesses/{other}", INNER) and not ok("PUT", f"/v1/harnesses/{other}/plugin", INNER)+ assert not ok("DELETE", f"/v1/harnesses/{INNER}", INNER)+ assert not ok("POST", "/v1/harnesses", INNER)+ assert not ok("POST", "/v1/orgs/org-a/keys", INNER) and not ok("GET", "/v1/orgs/org-a/keys", INNER)+ assert not ok("GET", "/v1/admin/integrations", INNER) and not ok("PUT", "/v1/admin/integrations", INNER)+ assert not ok("PUT", "/v1/sessions/hsess1/files/x.txt", INNER)+ assert not ok("DELETE", "/v1/sessions/hsess1", INNER)+ assert not ok("GET", "/v1/harnesses", INNER)+++def test_the_principal_of_a_credential_carries_its_scope_and_is_refused_off_its_routes():+ import asyncio+ from fastapi import HTTPException+ tok = gw._mint_calibration_token("hsess1", "org-a", INNER, 600)++ class _Req:+ def __init__(self, method, path, auth):+ self.method = method+ self.headers = {"authorization": auth}+ self.url = type("U", (), {"path": path})()++ p = asyncio.run(gw._principal(_Req("POST", "/v1/responses", "Bearer " + tok)))+ assert p["org"] == "org-a" and p["member"] == "calibrator:hsess1" and p["calibration"]["inner"] == INNER+ with pytest.raises(HTTPException) as e:+ asyncio.run(gw._principal(_Req("POST", "/v1/orgs/org-a/keys", "Bearer " + tok)))+ assert e.value.status_code == 403+ with pytest.raises(HTTPException) as e:+ asyncio.run(gw._principal(_Req("POST", "/v1/responses", "Bearer hrc_forged.deadbeef")))+ assert e.value.status_code == 401+++def test_an_incomplete_response_carries_the_handoff_beside_its_reason():+ t = gw._RespTranslator("resp_1", "m", None, True, time.time())+ t.incomplete_reason = "no_confident_action"+ t.handoff = {"reason": "no_confident_action", "step": 7, "weakest": 0.41, "threshold": 0.7, "risk": "write",+ "state": "...", "questions": {}, "answers": {}}+ out = t._response_obj("incomplete")+ assert out["incomplete_details"] == {"reason": "no_confident_action", "handoff": t.handoff}+ t2 = gw._RespTranslator("resp_2", "m", None, True, time.time())+ t2.incomplete_reason = "max_steps"+ assert t2._response_obj("incomplete")["incomplete_details"] == {"reason": "max_steps", "handoff": None}+ assert t2._response_obj("completed")["incomplete_details"] is Nonediff --git a/gateway/tests/test_incomplete_reason.py b/gateway/tests/test_incomplete_reason.pyindex fba85c13..1392b219 100644--- a/gateway/tests/test_incomplete_reason.py+++ b/gateway/tests/test_incomplete_reason.py@@ -22,7 +22,7 @@ def test_a_capped_turn_names_its_cap():tr = _tr()tr.incomplete_reason = "max_steps"d = tr._response_obj("incomplete")- assert d["incomplete_details"] == {"reason": "max_steps"}+ assert d["incomplete_details"] == {"reason": "max_steps", "handoff": None} # a capped run hands nothing offdef test_an_unknown_cause_stays_null_rather_than_guessing():diff --git a/runner/server.py b/runner/server.pyindex b18f50cb..67bc2c87 100644--- a/runner/server.py+++ b/runner/server.py@@ -5719,7 +5719,8 @@ def _systemone_relay_route(provider: str, base_url: str, api_key: str) -> tuple[def _build_systemone(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,resume_session_id: str | None = None, mcp_servers: list[dict] | None = None,tools_disabled: list[str] | None = None, max_turns: int | None = None,- timeout_seconds: int | None = None, agent_doc: str = "") -> list[str]:+ timeout_seconds: int | None = None, agent_doc: str = "",+ metadata: dict | None = None) -> list[str]:"""The System One Harness, one turn: the job rides argv as JSON, the driver emits claude-shapedstream-json. The harness's MCP servers ARE the environment (the first one; the driver says soin the trace when there are more); with none, the built-in order desk. `tools_disabled` are@@ -5743,7 +5744,7 @@ def _build_systemone(provider: str, auth: Auth, model: str, prompt: str, cwd: st"mcp_servers": [s for s in (mcp_servers or []) if (s or {}).get("url") or (s or {}).get("command")],"tools_disabled": list(tools_disabled or []),"max_turns": max_turns, "timeout_seconds": timeout_seconds,- "agent_doc": agent_doc or ""}+ "agent_doc": agent_doc or "", "metadata": metadata or None}return [SYSTEMONE_PYTHON, SYSTEMONE_DRIVER, json.dumps(job)]@@ -6319,6 +6320,10 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, melse "timeout" if rec.get("capped")else _status_from_result(result_ev, rc))rec["reason"] = str((result_ev or {}).get("reason") or "")+ # The handoff a run ended on (systemone: the state it refused or escalated on), or None; it+ # rides the status body beside the reason so the gateway can report it without the trace.+ _ho = (result_ev or {}).get("handoff")+ rec["handoff"] = _ho if isinstance(_ho, dict) else None# Never leave a failure opaque: surface the captured CLI stderr (and result-event error) so the# gateway/trace shows WHY it failed (throttling, model error, etc.) instead of an empty string.if rec["status"] in ("failed", "error", "timeout"):@@ -7196,6 +7201,9 @@ class TurnReq(BaseModel):skills_suppressed: list[str] | None = None # built-in skill names to NOT mount (harness disabled them)tools_disabled: list[str] | None = None # built-in tool names to disable (claude: --disallowedTools)image_auth: dict | None = None # {base_url, api_key, model} for image generation via the broker+ env: dict | None = None # names for the turn process, HR_-prefixed only (a harness that+ # drives another one gets HR_API_URL + HR_CALIBRATION_TOKEN)+ metadata: dict | None = None # systemone: {"systemone": {"script": [...]}} selects a scripted provider (a probe)idempotency_key: str = "" # dedup a retried /turn: same key -> same turn, no re-execpartial_messages: bool = False # claude: stream token-level deltas (--include-partial-messages)vision: bool = True # pi: whether the model's channel accepts image input@@ -7286,6 +7294,12 @@ def turn(req: TurnReq, identifier: str = "") -> dict:("HR_IMAGE_MODEL", req.image_auth.get("model"))):if v:env[k] = str(v)+ # Names the gateway hands the turn process for the platform's own API: a harness that drives+ # another one gets HR_API_URL and HR_CALIBRATION_TOKEN, a credential scoped to that harness+ # and expiring with the turn. HR_-prefixed only, so nothing here shadows a CLI's own variable.+ for k, val in (req.env or {}).items():+ if isinstance(k, str) and k.startswith("HR_") and val not in (None, ""):+ env[k] = str(val)# CRITICAL for resume: both CLIs write their conversation transcripts under $HOME# (~/.claude/projects/*.jsonl, ~/.codex/sessions/*) — NOT under CLAUDE_CONFIG_DIR. The default# $HOME is outside /workspace, so transcripts were never checkpointed and `--resume` found nothing@@ -7391,7 +7405,8 @@ def turn(req: TurnReq, identifier: str = "") -> dict:cmd = _build_systemone(req.provider, auth, model, req.prompt, cwd, env,resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,tools_disabled=req.tools_disabled, max_turns=req.max_turns,- timeout_seconds=req.timeout_seconds, agent_doc=agent_doc)+ timeout_seconds=req.timeout_seconds, agent_doc=agent_doc,+ metadata=req.metadata)elif backend == "gemini":model = model or GEMINI_DEFAULT_MODELcmd = _build_gemini(req.provider, auth, model, req.prompt, cwd, env,@@ -7533,4 +7548,5 @@ def get_turn(turn_id: str, since: int = 0) -> dict:"result": rec.get("result", ""), "exit_code": rec.get("exit_code"),"error": rec.get("error"), "backend": rec["backend"], "model": rec["model"],"session_id": rec.get("session_id"), "reason": rec.get("reason") or "",+ "handoff": rec.get("handoff"),"events": evs, "n_total": n, "elapsed": round(time.time() - rec["started"], 1)}diff --git a/runner/systemone_driver.py b/runner/systemone_driver.pyindex 9ead49e2..7cb3516a 100644--- a/runner/systemone_driver.py+++ b/runner/systemone_driver.py@@ -33,6 +33,7 @@ from __future__ import annotationsimport dataclassesimport json+import osimport pathlibimport sysimport uuid@@ -66,6 +67,28 @@ def _server_entry(s: dict) -> dict | None:return None+def _package_root(entry: dict | None) -> str:+ """The root of the package a stdio server runs from. The runner hands a plugin's server as a+ launcher script (see the runner's _plugin_launchers): the entry carries no cwd, and the script+ exports PLUGIN_ROOT before it execs the server; that export is read here, so the root is the+ one the server itself gets, never a guess. An entry with a cwd of its own keeps it."""+ e = entry or {}+ if e.get("cwd"):+ return str(e["cwd"])+ cmd = str(e.get("command") or "")+ if not cmd.endswith(".sh") or not os.path.isfile(cmd):+ return ""+ try:+ import shlex+ for line in open(cmd, encoding="utf-8"):+ if line.startswith("export PLUGIN_ROOT="):+ parts = shlex.split(line[len("export "):])+ return parts[0].split("=", 1)[1] if parts and "=" in parts[0] else ""+ except (OSError, ValueError):+ return ""+ return ""++def _provider_path(provider: str) -> str:"""Where the decisions endpoint sits under the route's base. OpenRouter: /api + /alpha/decisions.TypeSafe direct: host + /v1/systemone."""@@ -74,7 +97,7 @@ def _provider_path(provider: str) -> str:def run_turn(job: dict, provider=None, emit=_emit) -> dict:"""Run one turn and emit its events; returns the result event. `provider` is injectable for tests."""- from systemone_harness import Controller, DecisionProvider+ from systemone_harness import Config, Controller, DecisionProvider, ScriptProvider, StateEncoderfrom systemone_harness.envs import McpEnvironment, OrderWorkflowfrom systemone_harness.trace import Step, reasoning_text@@ -86,6 +109,19 @@ def run_turn(job: dict, provider=None, emit=_emit) -> dict:notes: list[str] = []servers = [e for e in (_server_entry(s) for s in (job.get("mcp_servers") or [])) if e]+ # The package's configuration (docs/dual-loop.md, Appendix B): config.yaml at the root the+ # environment's server runs from. Its instructions and gate replace the space's, its encoder+ # settings shape the state, its version rides the trace; the same file reaches the server as+ # SYSTEMONE_CONFIG, so the environment reads its tunables from where the loop reads.+ cfg = None+ root = _package_root(servers[0]) if servers else ""+ cfg_path = os.path.join(root, "config.yaml") if root else ""+ if cfg_path and os.path.exists(cfg_path):+ try:+ cfg = Config.load(cfg_path)+ servers[0]["env"] = {**(servers[0].get("env") or {}), "SYSTEMONE_CONFIG": cfg_path}+ except Exception as exc: # noqa: BLE001 - a package whose configuration does not load runs without it, and says so+ notes.append(f"config.yaml was not read ({exc}); the package runs without it.")env = Nonetry:if servers:@@ -101,6 +137,15 @@ def run_turn(job: dict, provider=None, emit=_emit) -> dict:env = OrderWorkflow("ship_cheapest")space = OrderWorkflow.action_space()notes.append("No MCP server is configured; the built-in order desk is the environment.")+ encoder = None+ if cfg is not None:+ if cfg.instructions:+ space.instructions = cfg.instructions+ space.gate = cfg.gate+ if cfg.encoder:+ encoder = StateEncoder(instructions=space.instructions,+ **{k: int(v) for k, v in cfg.encoder.items() if k in ("history_steps", "budget_tokens")})+ notes.append(f"Configuration v{cfg.version} from the package.")state_dir = cwd / ".harness" / "systemone" / sidprior: list[Step] = []@@ -120,6 +165,12 @@ def run_turn(job: dict, provider=None, emit=_emit) -> dict:path=_provider_path(str(job.get("provider") or "openrouter")),api_key=str(job.get("api_key") or ""), model=model,headers={"X-Title": "HarnessRouter"})+ # A probe: the request's metadata.systemone.script names the actions a scripted provider+ # answers, so the environment is measured at a place without the model deciding anything.+ script = ((job.get("metadata") or {}).get("systemone") or {}).get("script")+ if script:+ provider = ScriptProvider([str(a) for a in script])+ notes.append("A scripted provider answers this run, a probe; the model is not called.")first = {"done": False}def on_step(step) -> None:@@ -140,9 +191,11 @@ def run_turn(job: dict, provider=None, emit=_emit) -> dict:emit({"type": "assistant", "message": {"content": [{"type": "thinking", "thinking": reasoning_text(step)}]}})- ctl = Controller(space, env, provider, max_steps=int(job.get("max_turns") or 100),+ ctl = Controller(space, env, provider, encoder=encoder, max_steps=int(job.get("max_turns") or 100),timeout_seconds=job.get("timeout_seconds") or None,- disabled=set(job.get("tools_disabled") or []), on_step=on_step)+ disabled=set(job.get("tools_disabled") or []), on_step=on_step,+ config_version=int(cfg.version) if cfg else 0,+ trace_path=str(cwd / "trace.json")) # the run record, in the session workspacerun = ctl.run(str(job.get("prompt") or ""), reset=not resumed,task_instructions=str(job.get("agent_doc") or ""), prior=prior)if not first["done"] and notes:@@ -170,6 +223,7 @@ def run_turn(job: dict, provider=None, emit=_emit) -> dict:subtype, is_error = "error", Trueresult = {"type": "result", "subtype": subtype, "is_error": is_error,"result": text if not is_error else (run.error or text), "reason": run.reason,+ "handoff": _handoff_of(run),"session_id": sid, "model": run.served_model or model,"usage": {"input_tokens": int(run.usage.get("input_tokens", 0)),"output_tokens": int(run.usage.get("output_tokens", 0))} if run.steps else {}}@@ -183,6 +237,23 @@ def run_turn(job: dict, provider=None, emit=_emit) -> dict:pass+def _handoff_of(run) -> dict | None:+ """The run's handoff branch, when it ended on a refusal or an escalation: the state it stopped+ on, the questions, the answers with their probabilities, the weakest judgment, the threshold,+ the risk class and the step (System One Harness 0.4.0, SystemOneHarness#3). None on every other+ ending, and None on a harness that predates the field."""+ ho = getattr(run, "handoff", None)+ if ho is None:+ return None+ if isinstance(ho, dict):+ return ho+ try:+ import dataclasses+ return dataclasses.asdict(ho)+ except Exception: # noqa: BLE001 - an object of another shape: its public fields+ return {k: v for k, v in vars(ho).items() if not k.startswith("_")}++def _blank_step() -> dict:return {"index": 0, "started_at": 0.0, "state": {}, "state_tokens": 0, "questions": {}, "answers": {},"action": "", "params": {}, "action_confidence": 0.0, "weakest": 0.0, "threshold": 0.0,@@ -200,7 +271,8 @@ def main(argv: list[str] | None = None) -> int:result = run_turn(job)except Exception as exc: # noqa: BLE001 - a crash is a failed turn with its reason, never a silent exit_emit({"type": "result", "subtype": "error", "is_error": True,- "result": f"{type(exc).__name__}: {exc}", "reason": "harness_error", "usage": {}})+ "result": f"{type(exc).__name__}: {exc}", "reason": "harness_error", "handoff": None,+ "usage": {}})return 1return 0 if not result.get("is_error") else 1diff --git a/runner/tests/test_systemone_backend.py b/runner/tests/test_systemone_backend.pyindex 2827ef75..47b50df6 100644--- a/runner/tests/test_systemone_backend.py+++ b/runner/tests/test_systemone_backend.py@@ -121,6 +121,7 @@ def test_a_turn_is_init_then_a_call_and_result_per_action_then_the_sentence_and_assert text[-1]["message"]["content"][0]["text"] == "The environment reached a terminal state after 6 actions."assert events[-1] is result and result["subtype"] == "success" and result["is_error"] is Falseassert result["reason"] == "environment_terminal" and result["usage"]["input_tokens"] > 0+ assert result["handoff"] is None # a completed run hands nothing off (#227)assert result["model"] == "recorded/jev" and result["session_id"] == events[0]["session_id"]assert server._status_from_result(result, 0) == "done"# the manifest is a file in the workspace, where the artifact cards read from@@ -165,6 +166,13 @@ def test_a_refusal_streak_is_incomplete_with_its_reason_not_a_failure():result = drv.run_turn(_job(cwd, resume_session_id=sid), provider=RecordedProvider(shaky), emit=events.append)assert result["subtype"] == "incomplete" and result["is_error"] is Falseassert result["reason"] == "no_confident_action"+ # the handoff rides the result event beside the reason: the branch a router can send on+ # without reading the trace (#227). A harness that predates the field hands None.+ assert "handoff" in result+ if result["handoff"] is not None:+ assert isinstance(result["handoff"], dict)+ assert result["handoff"].get("reason") == "no_confident_action"+ assert {"state", "questions", "answers", "weakest", "threshold", "risk", "step"} <= set(result["handoff"])assert server._status_from_result(result, 0) == "incomplete"thinking = [e["message"]["content"][0]["thinking"] for e in eventsif e["type"] == "assistant" and e["message"]["content"][0]["type"] == "thinking"]@@ -185,3 +193,39 @@ def test_an_mcp_entry_carries_its_auth_as_a_header_and_a_targetless_one_is_droppassert e == {"url": "https://h/mcp", "headers": {"A": "b", "Authorization": "Bearer tok"}, "transport": "sse"}assert drv._server_entry({"name": "plugin", "command": "./run.sh", "args": [1]})["args"] == ["1"]assert drv._server_entry({"name": "nothing"}) is None+++def test_a_probe_answers_from_its_script_and_the_trace_lands_in_the_workspace(tmp_path):+ """docs/dual-loop.md, Appendix B: `metadata.systemone.script` selects a scripted provider, so the+ environment is measured at a place without the model; the run record is trace.json in the+ session workspace, with the configuration version (0 here: the desk ships no config.yaml)."""+ import json+ events = []+ job = {"cwd": str(tmp_path), "model": "jev-latest", "prompt": "ship it", "provider": "typesafe",+ "base_url": "http://127.0.0.1:1/v1", "api_key": "x", "max_turns": 4,+ "metadata": {"systemone": {"script": ["pack"]}}}+ result = drv.run_turn(job, emit=events.append)+ assert result["model"] == "script/s1" # the scripted provider, not the model+ assert result["is_error"] is False and "handoff" in result+ trace = json.loads((tmp_path / "trace.json").read_text())+ assert trace.get("config_version") == 0 and isinstance(trace.get("steps"), list)+ thinking = " ".join(c.get("thinking", "") for e in events if e.get("type") == "assistant"+ for c in e["message"]["content"] if c.get("type") == "thinking")+ assert "probe" in thinking+++def test_the_package_root_is_read_from_the_launcher_the_runner_hands_the_driver(tmp_path):+ """The runner hands a plugin's server as a launcher script with no cwd; the script exports+ PLUGIN_ROOT before it execs the server. The driver reads that export, so config.yaml is looked+ for where the server itself runs (measured on hr-test 2026-09-21: the first run on a package+ with a config carried config_version 0 because the root was taken from a cwd that is not there)."""+ root = tmp_path / ".harness" / "plugins" / "mario_env"+ root.mkdir(parents=True)+ launcher = tmp_path / ".launch-mario.sh"+ import shlex+ launcher.write_text("#!/bin/sh\nexport FOO=bar\nexport PLUGIN_ROOT=" + shlex.quote(str(root)) + "\n"+ "export PLUGIN_DATA=/x\nexec /bin/true \"$@\"\n")+ assert drv._package_root({"command": str(launcher), "args": []}) == str(root)+ assert drv._package_root({"command": str(launcher), "cwd": "/elsewhere"}) == "/elsewhere"+ assert drv._package_root({"command": "/usr/bin/env"}) == ""+ assert drv._package_root({"url": "https://x/mcp"}) == "" and drv._package_root(None) == ""diff --git a/ui/src/components/TaskChat.tsx b/ui/src/components/TaskChat.tsxindex ed87e06f..b3e57460 100644--- a/ui/src/components/TaskChat.tsx+++ b/ui/src/components/TaskChat.tsx@@ -105,6 +105,11 @@ function makeWbMarkdown(getSid: () => string | null, getHarness?: () => string |const BASE_TINT: Record<string, string> = {codex: '#0E8C6A', 'claude-code': '#C2613D', pi: '#6E55FF', hermes: '#2563EB', omp: '#FF6B00',};+/** A probability from a handoff as two decimals, or a question mark when it is not a number. */+function probText(x: unknown): string {+ return typeof x === 'number' ? x.toFixed(2) : '?';+}+function baseTint(id: string): string {if (BASE_TINT[id]) return BASE_TINT[id];let h = 0;@@ -585,6 +590,13 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on: null}</div>)}+ {m.status === 'incomplete' && m.handoff && (+ <div className="wbx-incomplete-why">+ {`It handed off at step ${String(m.handoff.step ?? '?')}: ${String(m.handoff.reason ?? m.incompleteReason ?? '')}. `+ + `The weakest judgment was ${probText(m.handoff.weakest)} against a threshold of ${probText(m.handoff.threshold)}`+ + `${m.handoff.risk ? ` on a ${String(m.handoff.risk)} action` : ''}.`}+ </div>+ )}<OutputFiles files={m.files.filter((f) => !isInternalOutput(f.filename))}onPreview={setPreview} />{m.status !== 'running' && asstText(m) && (diff --git a/ui/src/lib/conversation.ts b/ui/src/lib/conversation.tsindex ae80670b..4dab678d 100644--- a/ui/src/lib/conversation.ts+++ b/ui/src/lib/conversation.ts@@ -51,6 +51,8 @@ export interface AsstMsg { role: 'assistant'; blocks: Block[]; files: RespFile[]* gateway's incomplete_details. Absent on records from before the field existed, which is* why the badge itself must not assert a cause. */incompleteReason?: string;+ /** The handoff a run ended on (a refusal or an escalation): reason, step, weakest, threshold, risk. */+ handoff?: Record<string, unknown>;/** Seconds this turn took and the credits it cost, when the gateway kept them. */elapsed?: number; credits?: number }// AGENTS.md / CLAUDE.md are harness-internal instruction files the runner seeds into the workspace@@ -84,6 +86,7 @@ export function msgsFromTurns(turns: SessionTurn[]): { msgs: Msg[]; running: booif (st === 'running') running = true;m.push({ role: 'assistant', blocks, files: t.files || [], status: st,incompleteReason: (t as { incomplete_reason?: string }).incomplete_reason || undefined,+ handoff: (t as { handoff?: Record<string, unknown> | null }).handoff || undefined,elapsed: typeof t.elapsed === 'number' ? t.elapsed : undefined,credits: typeof t.credits === 'number' ? t.credits : undefined });}diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.tsindex 01c5b15b..e1eacd18 100644--- a/ui/src/lib/harness.ts+++ b/ui/src/lib/harness.ts@@ -154,7 +154,7 @@ export const OOB: OobHarness[] = [models: ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-3.3-70b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning', 'nemotron-3-super'], defaultModel: 'gpt-5.4', moreModels: 0,systemPrompt: 'You are OpenHands, an autonomous coding agent. You work on a real git workspace with shell and file access, reading and editing files and running commands to complete the task end to end.',tools: [], skills: [] },- { id: 'systemone', name: 'System One', version: 'v0.3.1', backend: 'systemone', status: 'ready',+ { id: 'systemone', name: 'System One', version: 'v0.4.0', backend: 'systemone', status: 'ready',// Placeholder only: the gateway's catalog wins once fetched. Jev, a decision model, under the// ids its two providers serve: jev-latest on both (the default), jev-preview on TypeSafe's own// API, jev-1.13 on OpenRouter. There is no chat model on this base because the loop asks typed