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
qoder: the driver speaks Qoder's own Python SDK; the relay reads a DELETE's body (#469)
Shi Peipei0c43dc333abb
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 1f6e40c6..ac8a3fdf 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -62,7 +62,9 @@ jobs:# the driver's tests import it, and skip without it, so the suite installs the same pin.# CheetahClaws the same way: its driver tests run the pinned package against a stub endpoint# (they skip without it), and it resolves beside the runner's own pins (pip check is clean).- - run: pip install -r runner/requirements.txt pytest pytest-asyncio httpx "systemone-harness @ git+https://github.com/HarnessRouter/[email protected]" "cheetahclaws==3.5.88"+ # Qoder's SDK the same way: the qoder driver imports it (the image pins it in its own venv),+ # and the driver's tests run it as a subprocess against a stub Managed API.+ - run: pip install -r runner/requirements.txt pytest pytest-asyncio httpx "systemone-harness @ git+https://github.com/HarnessRouter/[email protected]" "cheetahclaws==3.5.88" "qca-sdk==0.6.0"- run: python -m pytest runner/tests -qconformance:diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 7f076845..6ed241e9 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -240,10 +240,10 @@ backend_bin() {systemone) echo "$TOOLS/systemone-venv/bin/python" ;;cheetahclaws) echo "$TOOLS/cheetahclaws-venv/bin/cheetahclaws-ready" ;;agentzero) echo "$TOOLS/agentzero-venv/bin/agentzero-ready" ;;- # qoder has NO binary: its runtime is Qoder's cloud, and the turn process is runner/qoder_driver.py- # on the runner's own interpreter (stdlib only). Nothing is installed, pinned or verified for it,- # and the image's interpreter is what "installed" means here.- qoder) echo "$PY" ;;+ # qoder has no binary of its own: its runtime is Qoder's cloud, and the turn process is+ # runner/qoder_driver.py on Qoder's SDK, in a venv of its own (install_qoder). The venv's+ # interpreter is what "installed" means here.+ qoder) echo "$TOOLS/qoder-venv/bin/python" ;;mimo) echo "$TOOLS/bin/mimo" ;;gajae) echo "$TOOLS/bin/gjc" ;;jcode) echo "$TOOLS/bin/jcode" ;;@@ -338,6 +338,70 @@ if aider.__version__ != want:&& chmod +x "$TOOLS/aider-venv/bin/aider-ready"}+# Qoder Cloud Agents' Python SDK, MIT (QoderAI/qoder-cloud-agents-sdk-python, PyPI `qca-sdk`), pinned+# to 0.6.0. The qoder backend's runtime is Qoder's cloud; what this box needs is the client the+# driver (runner/qoder_driver.py) speaks it with, in a venv of its own so its httpx/pydantic/anyio+# stay off the runner's. VERIFIED the way cheetahclaws is: the wheel is downloaded on its own and+# compared against the digest pinned here (PyPI's sha256 for qca_sdk-0.6.0-py3-none-any.whl,+# 2026-10-16) before it is installed; an operator who overrides the version supplies HR_QODER_SHA256+# for it, or is told the wheel is unverified. The import check asserts the client and the methods the+# driver reaches for, so an SDK refactor fails the install here rather than the first live turn.+QODER_PIN="${HR_QODER_SDK_VERSION:-0.6.0}"+if [ "$QODER_PIN" = "0.6.0" ]; then+ QODER_SHA256="${HR_QODER_SHA256:-97d76fece7a489394e3dc237fece652bb6130f7cf5b1870aa6e9216e4ac8773f}"+else+ QODER_SHA256="${HR_QODER_SHA256:-}"+fi+install_qoder() {+ qd_py="${HR_QODER_BASE_PYTHON:-python3}"+ rm -rf "$TOOLS/qoder-venv"+ "$qd_py" -m venv "$TOOLS/qoder-venv" || return 1+ qd_tmp="$(mktemp -d)"+ "$TOOLS/qoder-venv/bin/pip" download -q --disable-pip-version-check --no-deps \+ --only-binary=:all: -d "$qd_tmp" "qca-sdk==$QODER_PIN" || { rm -rf "$qd_tmp"; return 1; }+ qd_whl="$qd_tmp/qca_sdk-$QODER_PIN-py3-none-any.whl"+ [ -f "$qd_whl" ] || { echo "qca-sdk $QODER_PIN: no wheel was downloaded"; rm -rf "$qd_tmp"; return 1; }+ if [ -n "$QODER_SHA256" ]; then+ qd_have="$(sha256sum "$qd_whl" | awk '{print $1}')"+ if [ "$QODER_SHA256" != "$qd_have" ]; then+ echo "qca-sdk $QODER_PIN: wheel digest mismatch (want $QODER_SHA256, have $qd_have)"+ rm -rf "$qd_tmp"; return 1+ fi+ fi+ "$TOOLS/qoder-venv/bin/pip" install -q --disable-pip-version-check "$qd_whl" \+ || { rm -rf "$qd_tmp"; return 1; }+ rm -rf "$qd_tmp"+ "$TOOLS/qoder-venv/bin/python" -c '+import sys, importlib.metadata as md+want = sys.argv[1]+have = md.version("qca-sdk")+if have != want:+ sys.exit("qca-sdk %s installed, wanted %s" % (have, want))+# every call runner/qoder_driver.py makes, on the client it makes them on+import qca+from qca.managed import Managed+for name in ("APIStatusError", "APIConnectionError", "APITimeoutError", "APIResponseValidationError", "APIError"):+ getattr(qca, name)+m = Managed(pat="probe", base_url="http://127.0.0.1:9/")+for path in ("environments.create", "environments.delete", "environments.archive",+ "vaults.create", "vaults.delete", "vaults.credentials.create", "vaults.credentials.list", "vaults.credentials.archive",+ "agents.create", "agents.retrieve", "agents.update", "agents.archive",+ "sessions.create", "sessions.retrieve", "sessions.update", "sessions.cancel", "sessions.delete",+ "sessions.resources.add", "sessions.events.send", "sessions.events.list", "sessions.events.stream",+ "files.upload", "files.download", "files.delete",+ "skills.create", "skills.versions.create", "skills.delete"):+ obj = m+ for part in path.split("."):+ obj = getattr(obj, part)+ if not callable(obj):+ sys.exit("qca-sdk %s: %s is not callable" % (have, path))+' "$QODER_PIN" || return 1+ # Written LAST, after the install and the checks proved the venv good: the marker is what the+ # boot compares against the pin, so a half-built venv is rebuilt rather than trusted.+ printf '#!/bin/sh\necho %s\n' "$QODER_PIN" > "$TOOLS/qoder-venv/bin/qoder-ready" \+ && chmod +x "$TOOLS/qoder-venv/bin/qoder-ready"+}+# CheetahClaws, Apache-2.0 (SAIL-Research-Lab/cheetahclaws, PyPI `cheetahclaws`), pinned to 3.5.88.## Its own venv, the aider/openhands precedent: runner/cheetahclaws_driver.py drives the CLI's agent@@ -1282,6 +1346,17 @@ install_backends() {try_install "CheetahClaws" install_cheetahclaws || truefi[ -x "$TOOLS/cheetahclaws-venv/bin/python" ] && export HR_CHEETAHCLAWS_PYTHON="$TOOLS/cheetahclaws-venv/bin/python"+ # The qoder backend's SDK, ~15 MB with its dependencies. The marker names the version the venv was+ # built for, so a pin bump rebuilds it; the session lives at Qoder and in the workspace, not here.+ if wanted qoder && [ "$("$TOOLS/qoder-venv/bin/qoder-ready" 2>/dev/null)" != "$QODER_PIN" ]; then+ echo "[harnessrouter] installing the Qoder Cloud Agents SDK qca-sdk $QODER_PIN (MIT)…"+ if [ -z "$QODER_SHA256" ]; then+ echo "[harnessrouter] WARN: HR_QODER_SDK_VERSION=$QODER_PIN overrides the pinned 0.6.0, and no"+ echo "[harnessrouter] HR_QODER_SHA256 was given — this qca-sdk wheel is UNVERIFIED."+ fi+ try_install "Qoder SDK" install_qoder || true+ fi+ [ -x "$TOOLS/qoder-venv/bin/python" ] && export HR_QODER_PYTHON="$TOOLS/qoder-venv/bin/python"if wanted agentzero && [ "$("$TOOLS/agentzero-venv/bin/agentzero-ready" 2>/dev/null)" != "$AGENTZERO_PIN" ]; thenecho "[harnessrouter] installing Agent Zero $AGENTZERO_PIN (MIT) — ~640 MB, this takes a minute or two…"try_install "Agent Zero" install_agentzero || truediff --git a/docs/harness-verification.md b/docs/harness-verification.mdindex 6b3e4375..a0eafff0 100644--- a/docs/harness-verification.md+++ b/docs/harness-verification.md@@ -239,8 +239,12 @@ free have to be built, and several of the registration points above have no obje**Not applicable, and the base says so rather than skipping it:**-- *15, the installer.* There is no binary. `docker/entrypoint.sh` installs nothing for it, and the- catalog entry's notes say the runtime is remote.+- *15, the installer.* There is no binary of the runtime to install; what is installed is the+ CLIENT the driver speaks it with. qoder's driver runs on Qoder's own Python SDK (`qca-sdk`),+ which `docker/entrypoint.sh` installs into a venv of its own (`install_qoder`), pinned and+ verified the way cheetahclaws' wheel is (the wheel's sha256 beside the version, an import check+ of every method the driver calls), with `backend_bin` the venv's interpreter. The catalog+ entry's notes say the runtime is remote.- *3 and 4, `_write_skills` and `_agent_doc_path` as places a loader looks.* Nothing on this boxloads anything. Skills are staged under `.harness/skills/` for the DRIVER to publish (qoder:as Skill resources bound on the session's Agent, reused by content hash); the harness's@@ -316,8 +320,13 @@ free have to be built, and several of the registration points above have no objeand NONE of the taps, because a session object through the model-call taps would record theCONFIGURED model as the served one and the matrix would score a check the backend cannot make.A stalled pass-through stream is closed, not narrated with an error event the driver would read- as the API's own. DELETE is forwarded. On the hosted service a sandbox never holds a vendor- credential, so this is not optional there.+ as the API's own. DELETE is forwarded WITH its body: a client that sends one (Qoder's SDK sends+ `{}`) left two bytes on the keep-alive socket when the relay did not read them, and the next+ request on that connection opened with `{}DELETE`, a 501 that three purge steps "failed" on. On+ the hosted service a sandbox never holds a vendor credential, so this is not optional there. A+ vendor SDK on the route changes none of this: it takes the relay as its base URL and the+ placeholder as its token, and the SDK's own guards (retrying a POST only under an+ `Idempotency-Key`, refusing a download link that is not a web address) are the driver's for free.## What the matrix did not see, and what changed (2026-09-30)diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.mdindex 2bfc9d17..45958916 100644--- a/docs/support-matrix-notes.md+++ b/docs/support-matrix-notes.md@@ -3503,14 +3503,64 @@ driver's mapping off it.region. The catalog carries the sixteen public ids; `ultimate` and `efficient` have completedturns.+### The transport: Qoder's Python SDK (2026-10-16)++The driver's wire moved from a hand-written `urllib` client to Qoder's own SDK (`qca-sdk` 0.6.0,+MIT, PyPI), installed into `$TOOLS/qoder-venv` by `install_qoder` with the wheel's sha256 pinned+and an import check of every method the driver calls. The per-turn contract, the state file, the+business rules (cancel, artifacts, names as input, hard across turns, purge) and all 43 tests are+unchanged; what changed:++- Every `user.message` carries an `Idempotency-Key` (a fresh UUID), which is what the SDK itself+ requires before it retries a POST — so the "is the message POST idempotent" question below is+ answered by the vendor's own client: that header is the mechanism.+- The SDK fetches and follows the artifact's presigned link itself and refuses one that is not an+ http(s) URL; the driver's own check of the same became the SDK's.+- The reconnect loop stays in the driver (a stream that ends without a terminal event is decided by+ the session's status, which the SDK's ResumableStream does not consult); the SDK's SSE decoder,+ typed calls and error classes replace the hand-rolled ones.+- A bug the switch found: the relay's `do_DELETE` did not read a DELETE's body. The SDK sends `{}`,+ the two bytes stayed on the keep-alive socket, and the next request opened with `{}DELETE` — a+ 501 from upstream that made a purge report three failures behind one session delete. Fixed and+ pinned by a test.+- Live on the SDK transport (Global, `efficient`): a first turn with Write + DeliverArtifacts in+ 21 s, the artifact landed, charge 0.23 credits; the purge deleted the session, the file and the+ Agent and archived the Environment.+- Found in review, each pinned by a test that fails without it: the SDK raises the storage host's+ answer to the presigned link with the same class as the API's own, so a lapsed link (a 403 at the+ store) read as the file refused and was not asked for again; a refusal of the request that+ carries no credential is now the link's, and gets one fresh link as before. A purge on an+ interpreter without the SDK died in a traceback while the runner removed the folder; it now+ reports every recorded id as left. An OSError that reaches the top (the SDK wraps the network's)+ ends the turn as the workspace's, not without a result.+- Measured on the candidate 0.34.2-rc.1 (main plus this change, 2026-10-16), in a side instance+ on a copy of the test instance's settings, through api.qoder.com (Global): the image's+ fresh-volume smoke test installed the SDK on amd64 and arm64 and listed all 26 bases; an upgraded+ volume built the venv at boot (`qoder-ready` 0.6.0) and the runner ran the driver on it. The+ console column, `run.mjs` through Playwright, passed 45 of 45 scenarios (first, follow-up,+ switch, artifact, recycle) on nine of the twelve offered ids: auto, ultimate, qmodel_38max,+ qmodel, gmodel, gfmodel, dmodel, dfmodel, mmodel. performance, kmodel_latest and smodel were not+ run (the account's trial credits; smodel costs about 11 a turn). Through the API on qfmodel: an+ input file mounted and read, a follow-up on the same Qoder session, a skill published and used,+ Bash disabled and absent from the agent's tools, a cancel 16 s in that Qoder recorded as+ `session.status_idle` with `stop_reason: cancelled`, and every session delete purged at Qoder+ (sessions, files and skills 404 afterwards, Agents and Environments archived; nothing left).+ Claude Code, Codex (with a follow-up) and Hermes completed on the same candidate. The whole run+ cost 14 credits.+- `install_qoder` run as written in the image's base (`python:3.12-slim`): the venv built in 17 s,+ the marker says 0.6.0, the import check passed, a wrong digest was refused with both digests+ named; the driver run on that venv's interpreter from inside the container completed a live turn+ (artifact landed, 0.42 credits) and its purge.+### Not yet confirmed with Qoder (the driver's defaults until then)The presigned artifact URL's lifetime (a lapsed link is re-requested, never a failure in itself);whether a delivered artifact can carry directory structure (flat names are written); the sessionidle TTL and auto-archive (an archived or missing session is `resume_lost`); the billing of failed-and cancelled runs (no figure is given for them); whether `POST /sessions/{id}/events` is-idempotent as a contract (the message is never sent twice, the history decides); the files-reference's text-only rule against the message schema's image `file_id`.+and cancelled runs (no figure is given for them); the files reference's text-only rule against the+message schema's image `file_id`. Answered since: `POST /sessions/{id}/events` is idempotent under+an `Idempotency-Key` header — the vendor's own SDK sends one and retries a POST only under one —+and every message the driver sends carries it (the history is now the fallback, not the guard).### Versions and the columndiff --git a/runner/qoder_driver.py b/runner/qoder_driver.pyindex 13a48ee0..7e15eef1 100644--- a/runner/qoder_driver.py+++ b/runner/qoder_driver.py@@ -1,15 +1,23 @@-"""One Qoder Cloud Agent turn, as a runner subprocess.+"""One Qoder Cloud Agents turn, as a runner subprocess.Spawned per turn by server.py under the same contract as every other backend: `__hr_init` first,one `{"m": ..., "p": ...}` JSON line per event on stdout, `__hr_result` last, and server.py'snormaliser (_qoder_to_claude) unaware of the wire. What differs is that the agent loop runs in-Qoder's cloud, not in this sandbox: this process is an HTTP client to a REST + SSE API (Managed-mode, `/api/v1/cloud`), so what a CLI driver spends on a subprocess this one spends on a session.+Qoder's cloud, not in this sandbox: this process is a client of a REST + SSE API (Managed mode,+`/api/v1/cloud`), so what a CLI driver spends on a subprocess this one spends on a session.++The wire is Qoder's own Python SDK (`qca-sdk`, pinned in docker/entrypoint.sh into its own venv,+imported in Client so the module loads without it): typed calls, the SDK's retry classification+(a POST is retried only under an `Idempotency-Key`, which every user.message here carries), and+its SSE decoder. The reconnect loop stays here rather than in the SDK's ResumableStream, because+a stream that ends without a terminal event is decided by the SESSION's status (idle twice with no+idle event seen = the event was lost; running = reconnect), which the stream alone cannot know.The credential never enters this process. The job carries the runner's loopback relay as thebase and a placeholder bearer; the relay holds the PAT and forwards this route verbatim (no bodyrewrites, no served-model or usage taps, see _qoder_relay_route in server.py). The one network-call that bypasses the relay is the presigned artifact download, which carries no credential.+call that bypasses the relay is the presigned artifact download, which carries no credential and+which the SDK follows itself (`files.download`), refusing a link that is not a web address.Everything the turn creates at Qoder — the Environment, the Agent, the Session, uploaded inputfiles, delivered artifact files, a Vault for MCP bearers, Skill resources — is recorded in@@ -25,7 +33,6 @@ Without that call the remote turn would keep running and billing after the localfrom __future__ import annotationsimport hashlib-import http.clientimport jsonimport mimetypesimport os@@ -35,9 +42,6 @@ import shutilimport signalimport sysimport time-import urllib.error-import urllib.parse-import urllib.requestimport uuidSTATE_REL = os.path.join(".harness", "qoder", "state.json")@@ -89,116 +93,196 @@ class Cancelled(BaseException):class ApiError(Exception):+ """Qoder answered with an error: the status and the envelope's type and message. Status 0 is+ the driver's own verdict on an answer it could not use (no id where one was due)."""+def __init__(self, status: int, kind: str, message: str, path: str = ""):super().__init__(f"{status} {kind}: {message}")self.status, self.kind, self.message, self.path = status, kind, message, path-# ── HTTP ────────────────────────────────────────────────────────────────────────────────────────-class Api:- """The Managed API through the relay: `base` is the relay's address, `token` a placeholder."""+class NetError(Exception):+ """Nothing answered: the connection was refused, dropped, or timed out."""+++class LinkRefused(Exception):+ """The storage host refused a presigned download link; a lapsed one is refused there (403 on+ most stores), and the rule is that a fresh link is asked for, never that the file is gone."""+++# ── the SDK ─────────────────────────────────────────────────────────────────────────────────────+def _plain(obj):+ """A pydantic model (or a list of them) as JSON-compatible dicts, extras included; anything+ else as it is. The handlers below read dicts, as they did off the wire."""+ if isinstance(obj, list):+ return [_plain(x) for x in obj]+ dump = getattr(obj, "model_dump", None)+ return dump(mode="json", exclude_none=True) if callable(dump) else obj+++class Client:+ """The Managed API through the relay, on Qoder's SDK: `base` is the relay's address, `token`+ a placeholder. Every method answers plain dicts and raises ApiError / NetError, so the turn's+ logic reads one shape whatever the SDK's models and exceptions are called."""def __init__(self, base: str, token: str):- self.base = base.rstrip("/")- self.token = token-- def _headers(self, extra: dict | None = None) -> dict:- h = {"authorization": f"Bearer {self.token}", "accept": "application/json"}- if extra:- h.update(extra)- return h-- def request(self, method: str, path: str, body: dict | None = None, *, data: bytes | None = None,- headers: dict | None = None, timeout: float = CALL_TIMEOUT_S):- """One call; the parsed JSON answer (None for an empty body). Raises ApiError on 4xx/5xx- with the envelope's type and message, urllib.error.URLError when nothing answered."""- hdrs = self._headers(headers)- payload = data- if body is not None:- payload = json.dumps(body).encode()- hdrs["content-type"] = "application/json"- req = urllib.request.Request(self.base + path, data=payload, method=method, headers=hdrs)- try:- with urllib.request.urlopen(req, timeout=timeout) as resp:- raw = resp.read()- except urllib.error.HTTPError as e:- raw = e.read()- kind, msg = _error_fields(raw)- raise ApiError(e.code, kind, msg or raw[:300].decode("utf-8", "replace"), path) from None- if not raw:- return None+ import httpx # noqa: PLC0415 — the SDK's own dependency, present wherever the SDK is+ from qca.managed import Managed # noqa: PLC0415 — installed in the backend's venv, not the runner's+ import qca # noqa: PLC0415++ self._x = qca+ self._httpx = httpx+ self.base = base.rstrip("/") + "/"+ self.m = Managed(pat=token, base_url=self.base, timeout=httpx.Timeout(CALL_TIMEOUT_S), max_retries=2)++ # one place turns the SDK's exceptions into the driver's two+ def _call(self, path: str, fn, *a, **kw):+ x = self._xtry:- return json.loads(raw)- except ValueError:- return {"_raw": raw[:300].decode("utf-8", "replace")}-- def stream(self, path: str, last_event_id: str = ""):- """An open SSE response for `path` (a GET); the caller reads it with iter_sse."""- hdrs = self._headers({"accept": "text/event-stream"})- if last_event_id:- hdrs["last-event-id"] = last_event_id- req = urllib.request.Request(self.base + path, method="GET", headers=hdrs)- try:- return urllib.request.urlopen(req, timeout=STREAM_READ_TIMEOUT_S)- except urllib.error.HTTPError as e:- raw = e.read()- kind, msg = _error_fields(raw)- raise ApiError(e.code, kind, msg or raw[:300].decode("utf-8", "replace"), path) from None+ return _plain(fn(*a, **kw))+ except x.APIStatusError as e:+ body = e.body if isinstance(e.body, dict) else {}+ err = body.get("error") if isinstance(body.get("error"), dict) else {}+ kind = str(err.get("type") or body.get("code") or "")+ msg = str(err.get("message") or body.get("message") or str(e))[:300]+ raise ApiError(int(e.status_code), kind, msg, path) from None+ except x.APIConnectionError as e: # APITimeoutError is one of these+ raise NetError(f"{type(e).__name__}: {e}"[:300]) from None+ except x.APIResponseValidationError as e:+ raise ApiError(0, "api_error", f"an answer the SDK could not read: {e}"[:300], path) from None+ # environments+ def environment_create(self, body: dict) -> dict:+ return self._call("/environments", self.m.environments.create, **body)-def _error_fields(raw: bytes) -> tuple[str, str]:- try:- doc = json.loads(raw)- err = doc.get("error") if isinstance(doc, dict) else None- if isinstance(err, dict):- return str(err.get("type") or ""), str(err.get("message") or "")- except ValueError:- pass- return "", ""---def multipart(parts: list[tuple[str, str | None, str, bytes]]) -> tuple[bytes, str]:- """A multipart/form-data body from (field, filename or None, content type, bytes) parts;- returns (body, content-type header)."""- boundary = "----hr" + uuid.uuid4().hex- out = bytearray()- for field, filename, ctype, data in parts:- out += f"--{boundary}\r\n".encode()- disp = f'form-data; name="{field}"'- if filename is not None:- disp += f'; filename="{filename.replace(chr(34), "_")}"'- out += f"Content-Disposition: {disp}\r\n".encode()- if filename is not None:- out += f"Content-Type: {ctype}\r\n".encode()- out += b"\r\n" + data + b"\r\n"- out += f"--{boundary}--\r\n".encode()- return bytes(out), f"multipart/form-data; boundary={boundary}"---def iter_sse(resp):- """(id, event, data) per SSE message off an open response; a comment line is skipped. Ends- at EOF; a socket timeout or a dropped connection raises out (the caller reconnects)."""- sid, ev, data = "", "", []- while True:- line = resp.readline()- if not line:- return- line = line.rstrip(b"\r\n").decode("utf-8", "replace")- if line == "":- if ev or data:- yield sid, ev, "\n".join(data)- sid, ev, data = "", "", []- continue- if line.startswith(":"):- continue- field, _, value = line.partition(":")- value = value[1:] if value.startswith(" ") else value- if field == "id":- sid = value- elif field == "event":- ev = value- elif field == "data":- data.append(value)+ def environment_delete(self, eid: str) -> dict:+ return self._call(f"/environments/{eid}", self.m.environments.delete, eid)++ def environment_archive(self, eid: str) -> dict:+ return self._call(f"/environments/{eid}/archive", self.m.environments.archive, eid)++ # vaults+ def vault_create(self, display_name: str, metadata: dict) -> dict:+ return self._call("/vaults", self.m.vaults.create, display_name=display_name, metadata=metadata)++ def vault_delete(self, vid: str) -> dict:+ return self._call(f"/vaults/{vid}", self.m.vaults.delete, vid)++ def credential_create(self, vid: str, auth: dict) -> dict:+ return self._call(f"/vaults/{vid}/credentials", self.m.vaults.credentials.create, vid, auth=auth)++ def credentials_list(self, vid: str) -> list[dict]:+ page = self._call(f"/vaults/{vid}/credentials", self.m.vaults.credentials.list, vid)+ return list((page or {}).get("data") or [])++ def credential_archive(self, vid: str, cid: str) -> dict:+ return self._call(f"/vaults/{vid}/credentials/{cid}/archive", self.m.vaults.credentials.archive, cid, vault_id=vid)++ # agents+ def agent_create(self, body: dict) -> dict:+ return self._call("/agents", self.m.agents.create, **body)++ def agent_retrieve(self, aid: str) -> dict:+ return self._call(f"/agents/{aid}", self.m.agents.retrieve, aid)++ def agent_update(self, aid: str, body: dict, version: int) -> dict:+ return self._call(f"/agents/{aid}", self.m.agents.update, aid, version=version, **body)++ def agent_archive(self, aid: str) -> dict:+ return self._call(f"/agents/{aid}/archive", self.m.agents.archive, aid)++ # sessions+ def session_create(self, body: dict) -> dict:+ return self._call("/sessions", self.m.sessions.create, **body)++ def session_retrieve(self, sid: str) -> dict:+ return self._call(f"/sessions/{sid}", self.m.sessions.retrieve, sid)++ def session_update(self, sid: str, body: dict) -> dict:+ return self._call(f"/sessions/{sid}", self.m.sessions.update, sid, **body)++ def session_cancel(self, sid: str) -> dict:+ return self._call(f"/sessions/{sid}/cancel", self.m.sessions.cancel, sid,+ timeout=self._httpx.Timeout(20.0))++ def session_delete(self, sid: str) -> dict:+ return self._call(f"/sessions/{sid}", self.m.sessions.delete, sid)++ def resource_add(self, sid: str, file_id: str, mount_path: str) -> dict:+ return self._call(f"/sessions/{sid}/resources", self.m.sessions.resources.add, sid,+ type="file", file_id=file_id, mount_path=mount_path)++ def events_send(self, sid: str, events: list[dict], idempotency_key: str = "") -> list[dict]:+ hdrs = {"Idempotency-Key": idempotency_key} if idempotency_key else None+ doc = self._call(f"/sessions/{sid}/events", self.m.sessions.events.send, sid, events=events,+ extra_headers=hdrs)+ return list((doc or {}).get("data") or [])++ def events_list(self, sid: str, **query) -> dict:+ return self._call(f"/sessions/{sid}/events", self.m.sessions.events.list, sid, **query) or {}++ def events_stream(self, sid: str, last_event_id: str = ""):+ """An open SDK Stream of SessionStreamEvent, deltas of agent.message requested; the caller+ iterates it and reads `.last_event_id` after each event for the cursor."""+ x = self._x+ try:+ return self.m.sessions.events.stream(+ sid, event_deltas=["agent.message"], last_event_id=last_event_id or None,+ timeout=self._httpx.Timeout(CALL_TIMEOUT_S, read=STREAM_READ_TIMEOUT_S))+ except x.APIStatusError as e:+ body = e.body if isinstance(e.body, dict) else {}+ err = body.get("error") if isinstance(body.get("error"), dict) else {}+ raise ApiError(int(e.status_code), str(err.get("type") or ""), str(err.get("message") or e)[:300],+ f"/sessions/{sid}/events/stream") from None+ except x.APIConnectionError as e:+ raise NetError(f"{type(e).__name__}: {e}"[:300]) from None++ def stream_errors(self) -> tuple:+ """What a read off an open stream raises when the connection goes (the caller reconnects)."""+ x = self._x+ return (x.APIConnectionError, x.APITimeoutError)++ def stream_error_frame(self) -> type:+ """What a read raises when the stream carries an `error` frame of its own."""+ return self._x.APIError++ # files+ def file_upload(self, name: str, data: bytes, ctype: str) -> dict:+ return self._call("/files", self.m.files.upload, file=(name, data, ctype), name=name)++ def file_download(self, fid: str):+ """An open binary download of the file's bytes (the SDK fetched the presigned link and+ refused one that is not http(s)); iterate `.iter_bytes()`, then `.close()`."""+ x = self._x+ try:+ return self.m.files.download(fid)+ except x.APIStatusError as e:+ if "authorization" not in e.request.headers:+ # The SDK makes two requests here and raises the same class for both. The storage+ # request is the one that carries no credential (the presigned link is the+ # authority), so a refusal there is the link's, not the file's.+ raise LinkRefused(f"the storage host refused the download link ({e.status_code})") from None+ body = e.body if isinstance(e.body, dict) else {}+ err = body.get("error") if isinstance(body.get("error"), dict) else {}+ raise ApiError(int(e.status_code), str(err.get("type") or ""), str(err.get("message") or e)[:300],+ f"/files/{fid}/content") from None+ except x.APIConnectionError as e:+ raise NetError(f"{type(e).__name__}: {e}"[:300]) from None+ except x.APIResponseValidationError as e:+ raise ApiError(0, "api_error", "the download link is not a web address", f"/files/{fid}/content") from e++ def file_delete(self, fid: str) -> dict:+ return self._call(f"/files/{fid}", self.m.files.delete, fid)++ # skills+ def skill_create(self, files: list[tuple[str, bytes, str]]) -> dict:+ return self._call("/skills", self.m.skills.create, files=files)++ def skill_version_create(self, skill_id: str, files: list[tuple[str, bytes, str]]) -> dict:+ return self._call(f"/skills/{skill_id}/versions", self.m.skills.versions.create, skill_id, files=files)++ def skill_delete(self, skill_id: str) -> dict:+ return self._call(f"/skills/{skill_id}", self.m.skills.delete, skill_id)# ── state ────────────────────────────────────────────────────────────────────────────────────────@@ -428,9 +512,10 @@ def skill_tree(folder: str) -> tuple[str, list[tuple[str, bytes]], str]:return name, files, ""-def publish_skills(api: Api, st: dict, skills: list[dict], notes: list[str]) -> list[dict]:+def publish_skills(api: Client, st: dict, skills: list[dict], notes: list[str]) -> list[dict]:"""Each harness skill bundle as a Qoder custom Skill (a new version when its bytes changed),- reused across the session's turns by content hash; → the bindings for the Agent."""+ reused across the session's turns by content hash; → the bindings for the Agent. The package+ goes as a bare file tree, each part's filename its path under the skill's directory."""known: dict = st.setdefault("skills", {})out: list[dict] = []for s in skills or []:@@ -444,15 +529,12 @@ def publish_skills(api: Api, st: dict, skills: list[dict], notes: list[str]) ->if rec.get("id") and rec.get("sha") == digest and rec.get("version"):out.append({"id": rec["id"], "version": rec["version"]})continue- parts = [("files", path, mimetypes.guess_type(path)[0] or "application/octet-stream", data)- for path, data in files]- body, ctype = multipart(parts)+ parts = [(path, data, mimetypes.guess_type(path)[0] or "application/octet-stream") for path, data in files]if rec.get("id"):- ver = api.request("POST", f"/skills/{rec['id']}/versions", data=body,- headers={"content-type": ctype})+ ver = api.skill_version_create(rec["id"], parts)version = str((ver or {}).get("version") or "")else:- created = api.request("POST", "/skills", data=body, headers={"content-type": ctype})+ created = api.skill_create(parts)rec = {"id": str((created or {}).get("id") or "")}version = str((created or {}).get("latest_version") or "")if not rec.get("id") or not version:@@ -477,7 +559,7 @@ def upload_ok(rel: str, size: int) -> str:return f"{rel}: Qoder accepts text-type input files only (binary, image and archive files are refused)"-def upload_inputs(api: Api, st: dict, cwd: str, rels: list[str]) -> list[dict]:+def upload_inputs(api: Client, st: dict, cwd: str, rels: list[str]) -> list[dict]:"""Upload the runner's staged input files once each (by content hash); → the file resourcesto mount, with the mount path the model is told."""known: dict = st.setdefault("files", {})@@ -491,10 +573,7 @@ def upload_inputs(api: Api, st: dict, cwd: str, rels: list[str]) -> list[dict]:digest = _sha(data)rec = known.get(rel) or {}if not (rec.get("id") and rec.get("sha") == digest):- body, ctype = multipart([("file", os.path.basename(rel),- mimetypes.guess_type(rel)[0] or "text/plain", data),- ("name", None, "", os.path.basename(rel).encode())])- created = api.request("POST", "/files", data=body, headers={"content-type": ctype})+ created = api.file_upload(os.path.basename(rel), data, mimetypes.guess_type(rel)[0] or "text/plain")rec = {"id": str((created or {}).get("id") or ""), "sha": digest, "mounted": []}known[rel] = recmount = f"{MOUNT_ROOT}/{rel.lstrip('/')}"@@ -507,7 +586,7 @@ class Turn:def __init__(self, job: dict):self.job = jobself.cwd = str(job.get("cwd") or os.getcwd())- self.api = Api(str(job.get("base_url") or ""), str(job.get("api_key") or ""))+ self.api = Client(str(job.get("base_url") or ""), str(job.get("api_key") or ""))self.st = load_state(self.cwd)self.notes: list[str] = []self.session_id = ""@@ -535,7 +614,7 @@ class Turn:env_id = str(self.st.get("environment_id") or "")if env_id:return env_id- created = self.api.request("POST", "/environments", {+ created = self.api.environment_create({"name": f"harnessrouter {pathlib.Path(self.cwd).name}"[:256],"description": "Created by HarnessRouter for one session; deleted with it.","config": {"type": "cloud"}, "metadata": {"harnessrouter": "1"}})@@ -557,9 +636,7 @@ class Turn:return [self.st["vault_id"]] if self.st.get("vault_id") else []vid = str(self.st.get("vault_id") or "")if not vid:- created = self.api.request("POST", "/vaults", {- "display_name": f"harnessrouter {pathlib.Path(self.cwd).name}"[:255],- "metadata": {"harnessrouter": "1"}})+ created = self.api.vault_create(f"harnessrouter {pathlib.Path(self.cwd).name}"[:255], {"harnessrouter": "1"})vid = str((created or {}).get("id") or "")if not vid:raise ApiError(0, "api_error", "vault create returned no id", "/vaults")@@ -578,25 +655,24 @@ class Turn:return [vid]def _create_credential(self, vid: str, c: dict) -> str:- body = {"auth": {"type": "static_bearer", "mcp_server_url": c["url"], "token": c["token"]}}+ auth = {"type": "static_bearer", "mcp_server_url": c["url"], "token": c["token"]}try:- doc = self.api.request("POST", f"/vaults/{vid}/credentials", body)+ doc = self.api.credential_create(vid, auth)except ApiError as e:if e.status != 409:raise# an active credential for this URL that the state does not know: archived, then made anewfor old in self._active_credentials(vid, c["url"]):self._archive_credential(vid, old)- doc = self.api.request("POST", f"/vaults/{vid}/credentials", body)+ doc = self.api.credential_create(vid, auth)cid = str((doc or {}).get("id") or "")if not cid:raise ApiError(0, "api_error", "credential create returned no id", f"/vaults/{vid}/credentials")return ciddef _active_credentials(self, vid: str, url: str) -> list[str]:- doc = self.api.request("GET", f"/vaults/{vid}/credentials")out = []- for x in (doc or {}).get("data") or []:+ for x in self.api.credentials_list(vid):if not isinstance(x, dict) or not x.get("id") or x.get("archived_at"):continueif url in (x.get("mcp_server_url"), (x.get("auth") or {}).get("mcp_server_url")):@@ -605,7 +681,7 @@ class Turn:def _archive_credential(self, vid: str, cid: str) -> None:try:- self.api.request("POST", f"/vaults/{vid}/credentials/{cid}/archive")+ self.api.credential_archive(vid, cid)except ApiError as e:if e.status not in (404, 409): # gone, or archived alreadyraise@@ -617,11 +693,11 @@ class Turn:if aid and self.st.get("agent_hash") == digest and self.st.get("agent_version"):return aid, int(self.st["agent_version"]), Falseif aid:- current = self.api.request("GET", f"/agents/{aid}")+ current = self.api.agent_retrieve(aid)version = int((current or {}).get("version") or 1)- updated = self.api.request("POST", f"/agents/{aid}", {**body, "version": version})+ updated = self.api.agent_update(aid, body, version)else:- updated = self.api.request("POST", "/agents", body)+ updated = self.api.agent_create(body)aid = str((updated or {}).get("id") or "")version = int((updated or {}).get("version") or 1)if not aid:@@ -638,7 +714,7 @@ class Turn:if resume != str(self.st.get("session_id") or ""):return "", Truetry:- doc = self.api.request("GET", f"/sessions/{resume}")+ doc = self.api.session_retrieve(resume)except ApiError as e:if e.status == 404:return "", True@@ -661,7 +737,7 @@ class Turn:body["vault_ids"] = vault_idsif resources:body["resources"] = [{k: v for k, v in r.items() if not k.startswith("_")} for r in resources]- doc = self.api.request("POST", "/sessions", body)+ doc = self.api.session_create(body)sid = str((doc or {}).get("id") or "")if not sid:raise ApiError(0, "api_error", "session create returned no id", "/sessions")@@ -680,8 +756,7 @@ class Turn:if sid in (rec.get("mounted") or []):continuetry:- self.api.request("POST", f"/sessions/{sid}/resources",- {"type": "file", "file_id": r["file_id"], "mount_path": r["mount_path"]})+ self.api.resource_add(sid, r["file_id"], r["mount_path"])except ApiError as e:if e.status != 409:raise@@ -689,15 +764,11 @@ class Turn:save_state(self.cwd, self.st)# ── the stream ──- def handle(self, eid: str, ev: str, data: str, posted_id: str, started: list[bool]) -> bool:- """One SSE message; True when the turn is over."""- try:- doc = json.loads(data) if data else {}- except ValueError:- return False+ def handle(self, eid: str, doc: dict, posted_id: str, started: list[bool]) -> bool:+ """One stream event, as the SDK decoded it; True when the turn is over."""if not isinstance(doc, dict):return False- t = str(doc.get("type") or ev or "")+ t = str(doc.get("type") or "")if t == "heartbeat":return Falseif eid and t not in ("event_start", "event_delta"):@@ -821,7 +892,7 @@ class Turn:ev["deny_message"] = "This tool is disabled for this harness."events.append(ev)if events:- self.api.request("POST", f"/sessions/{self.session_id}/events", {"events": events})+ self.api.events_send(self.session_id, events, idempotency_key=uuid.uuid4().hex)def artifact(self, doc: dict) -> None:fid = str(doc.get("file_id") or "")@@ -873,37 +944,32 @@ class Turn:_emit("artifact", {**rec, "status": "landed", "path": written})def _download(self, fid: str, original: str, part: pathlib.Path) -> tuple[int | None, str]:- """(bytes written to `part`, "") or (None, why). The presigned link is asked for again once- if the first one fails (its lifetime is not documented); a refused file is not retried."""+ """(bytes written to `part`, "") or (None, why). The SDK asks for the presigned link and+ follows it (refusing one that is not http(s)); the link is asked for again once if the+ first fails (its lifetime is not documented); a refused file is not retried."""why = ""for _attempt in (0, 1):try:- link = self.api.request("GET", f"/files/{fid}/content")- url = str((link or {}).get("url") or "")- if not url:- return None, f"{original}: no download url"- if urllib.parse.urlsplit(url).scheme.lower() not in ("https", "http"):- # urllib also opens file:, ftp: and data: URLs; a link that is not a web address- # would land a file of this box (or anything else) as the artifact- return None, f"{original}: the download link is not a web address"- req = urllib.request.Request(url, method="GET") # presigned: no credential travelspart.parent.mkdir(parents=True, exist_ok=True)n = 0- with urllib.request.urlopen(req, timeout=CALL_TIMEOUT_S) as resp, open(part, "wb") as out:- while True:- chunk = resp.read(1 << 20)- if not chunk:- break- n += len(chunk)- if n > ARTIFACT_MAX_BYTES:- return None, f"{original}: over the {ARTIFACT_MAX_BYTES}-byte artifact limit"- out.write(chunk)+ resp = self.api.file_download(fid)+ try:+ with open(part, "wb") as out:+ for chunk in resp.iter_bytes(1 << 20):+ n += len(chunk)+ if n > ARTIFACT_MAX_BYTES:+ return None, f"{original}: over the {ARTIFACT_MAX_BYTES}-byte artifact limit"+ out.write(chunk)+ finally:+ resp.close()return n, ""except ApiError as e:why = f"{original}: {e}"- if e.status in (404, 410, 403):+ if e.status in (0, 404, 410, 403):break- except (urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError) as e:+ except (NetError, LinkRefused, OSError) as e:+ why = f"{original}: download failed: {type(e).__name__}: {e}"[:300]+ except Exception as e: # noqa: BLE001 — the storage host dropped mid-body (httpx's own errors)why = f"{original}: download failed: {type(e).__name__}: {e}"[:300]return None, why@@ -916,12 +982,13 @@ class Turn:open took, and nothing of an earlier turn is read as this one's."""started = [bool(posted_id)]self.last_event_id = posted_id- path = f"/sessions/{self.session_id}/events/stream?event_deltas%5B%5D=agent.message"attempts = 0idle_eofs = 0+ dropped = self.api.stream_errors()+ error_frame = self.api.stream_error_frame()while True:try:- resp = self.api.stream(path, self.last_event_id)+ stream = self.api.events_stream(self.session_id, self.last_event_id)except ApiError as e:if e.status in (400, 404) and self.last_event_id:self.last_event_id = "" # the cursor is gone; start from now@@ -929,33 +996,37 @@ class Turn:if attempts <= STREAM_RECONNECTS:continueraise- except (urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError) as e:+ except NetError as e:attempts += 1if attempts > STREAM_RECONNECTS:raise ApiError(0, "stream", f"the event stream could not be opened: {e}"[:300])time.sleep(min(2.0 * attempts, 15.0))continuetry:- for eid, ev, data in iter_sse(resp):- if self.handle(eid, ev, data, posted_id, started):+ for ev in stream:+ eid = str(stream.last_event_id or "")+ if self.handle(eid, _plain(ev), posted_id, started):return- except (http.client.HTTPException, TimeoutError, OSError) as e:+ except dropped as e:attempts += 1_emit("notice", {"text": f"event stream dropped ({type(e).__name__}); resuming from {self.last_event_id or 'now'}"})if attempts > STREAM_RECONNECTS:raise ApiError(0, "stream", f"the event stream kept dropping: {e}"[:300])time.sleep(min(2.0 * attempts, 15.0))continue+ except error_frame as e:+ # the stream itself said `error`: Qoder's own word, and the turn's reason+ raise ApiError(0, "stream", str(e)[:300], f"/sessions/{self.session_id}/events/stream") from Nonefinally:try:- resp.close()+ stream.close()except Exception: # noqa: BLE001pass# EOF without a terminal event: the server closed the stream. Where the session stands# decides: terminated ends the turn; running (or a turn resumed after a confirmation)# means reconnect from the cursor; idle twice in a row with no idle event seen means# the event was lost on the wire and the turn is over.- doc = self.api.request("GET", f"/sessions/{self.session_id}")+ doc = self.api.session_retrieve(self.session_id)status = str((doc or {}).get("status") or "")if status == "terminated":self.terminated = True@@ -973,26 +1044,29 @@ class Turn:def post_message(self, text: str | None = None) -> str:"""Send the turn's message once (or `text`, the delivery round's); → the user.message event- id. If the call itself fails after it may have been delivered, the session's history says- whether it was, and the message is never sent a second time."""+ id. The message carries an Idempotency-Key, the API's own guard against a retried POST+ running twice (the SDK retries a POST only under one). If the call still fails after it may+ have been delivered, the session's history says whether it was, and the message is never+ sent a second time."""before = self.last_history_id()if text is None:text = str(self.job.get("prompt") or "")if self.mounts:text = ("[Attached files, mounted read-only: " + ", ".join(f"`{m}`" for m in self.mounts) + "]\n\n" + text)- body = {"events": [{"type": "user.message", "content": [{"type": "text", "text": text}]}]}+ events = [{"type": "user.message", "content": [{"type": "text", "text": text}]}]try:- doc = self.api.request("POST", f"/sessions/{self.session_id}/events", body)- for e in (doc or {}).get("data") or []:+ for e in self.api.events_send(self.session_id, events, idempotency_key=uuid.uuid4().hex):if isinstance(e, dict) and e.get("type") == "user.message":return str(e.get("id") or "")return ""- except (urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError):- q = "/events?limit=20&order=asc&types=user.message" + (f"&after_id={before}" if before else "")+ except NetError:+ query: dict = {"limit": 20, "order": "asc", "types": ["user.message"]}+ if before:+ query["after_id"] = beforetry:- doc = self.api.request("GET", f"/sessions/{self.session_id}{q}")+ doc = self.api.events_list(self.session_id, **query)except ApiError:- doc = None+ doc = {}for e in (doc or {}).get("data") or []:if isinstance(e, dict) and e.get("type") == "user.message":_emit("notice", {"text": "the message's acknowledgement was lost; the session history shows it arrived"})@@ -1040,18 +1114,18 @@ class Turn:def last_history_id(self) -> str:try:- doc = self.api.request("GET", f"/sessions/{self.session_id}/events?limit=1&order=desc")+ doc = self.api.events_list(self.session_id, limit=1, order="desc")return str((doc or {}).get("first_id") or "")- except (ApiError, urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError):+ except (ApiError, NetError):return ""def snapshot_usage(self) -> None:try:- doc = self.api.request("GET", f"/sessions/{self.session_id}")+ doc = self.api.session_retrieve(self.session_id)u = (doc or {}).get("usage")if isinstance(u, dict) and u:self.usage = {k: u.get(k) for k in ("model_credits", "sandbox_runtime_credits", "total_credits")}- except (ApiError, urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError):+ except (ApiError, NetError):passdef charge(self) -> dict | None:@@ -1081,7 +1155,7 @@ class Turn:if not self.session_id:return "cancelled before a Qoder session existed"try:- self.api.request("POST", f"/sessions/{self.session_id}/cancel", timeout=20.0)+ self.api.session_cancel(self.session_id)return f"cancel accepted by Qoder for session {self.session_id}"except Exception as e: # noqa: BLE001return f"cancel failed ({str(e)[:200]}); Qoder session {self.session_id} may still be running"@@ -1125,8 +1199,7 @@ class Turn:if changed:# a session pins its Agent version; its tools and servers are what it lets a# later turn replace, so a tool disabled between turns is withheld on this one- self.api.request("POST", f"/sessions/{sid}", {"agent": {"tools": body["tools"],- "mcp_servers": body["mcp_servers"]}})+ self.api.session_update(sid, {"agent": {"tools": body["tools"], "mcp_servers": body["mcp_servers"]}})self.mount_resources(sid, resources)else:sid = self.create_session(aid, version, env_id, vault_ids, resources)@@ -1174,14 +1247,24 @@ def purge(job: dict) -> int:"""Delete at Qoder everything the session's turns created there, in dependency order; everyfailure is reported with its id, never swallowed. Exit 0 when nothing failed."""cwd = str(job.get("cwd") or os.getcwd())- api = Api(str(job.get("base_url") or ""), str(job.get("api_key") or ""))st = load_state(cwd)+ try:+ api = Client(str(job.get("base_url") or ""), str(job.get("api_key") or ""))+ except ImportError as e:+ # Without the SDK nothing can be deleted, and the runner removes the folder (and this+ # state with it) whatever the answer is: the report names every recorded id, so what is+ # left at Qoder is in the runner's log rather than in a traceback.+ _emit("purge", {"done": [], "failed": [{+ "what": "everything recorded: " + json.dumps(st)[:1200],+ "error": f"the Qoder SDK (qca-sdk) is not installed in this interpreter: {e}"[:300]}],+ "state": STATE_REL})+ return 1done: list[str] = []failed: list[dict] = []- def attempt(label: str, method: str, path: str, body: dict | None = None, ok_status=(404,)) -> bool:+ def attempt(label: str, fn, *a, ok_status=(404,)) -> bool:try:- api.request(method, path, body)+ fn(*a)done.append(label)return Trueexcept ApiError as e:@@ -1195,30 +1278,30 @@ def purge(job: dict) -> int:sessions = list(st.get("sessions") or ([st["session_id"]] if st.get("session_id") else []))for sid in sessions:- attempt(f"cancel session {sid}", "POST", f"/sessions/{sid}/cancel", ok_status=(404, 409))- attempt(f"delete session {sid}", "DELETE", f"/sessions/{sid}")+ attempt(f"cancel session {sid}", api.session_cancel, sid, ok_status=(404, 409))+ attempt(f"delete session {sid}", api.session_delete, sid)for fid in list(st.get("artifacts") or []):- attempt(f"delete artifact file {fid}", "DELETE", f"/files/{fid}")+ attempt(f"delete artifact file {fid}", api.file_delete, fid)for rel, rec in (st.get("files") or {}).items():if isinstance(rec, dict) and rec.get("id"):- attempt(f"delete input file {rec['id']} ({rel})", "DELETE", f"/files/{rec['id']}")+ attempt(f"delete input file {rec['id']} ({rel})", api.file_delete, rec["id"])if st.get("agent_id"):- attempt(f"archive agent {st['agent_id']}", "POST", f"/agents/{st['agent_id']}/archive")+ attempt(f"archive agent {st['agent_id']}", api.agent_archive, st["agent_id"])if st.get("vault_id"):- attempt(f"delete vault {st['vault_id']}", "DELETE", f"/vaults/{st['vault_id']}")+ attempt(f"delete vault {st['vault_id']}", api.vault_delete, st["vault_id"])for name, rec in (st.get("skills") or {}).items():if isinstance(rec, dict) and rec.get("id"):- attempt(f"delete skill {rec['id']} ({name})", "DELETE", f"/skills/{rec['id']}")+ attempt(f"delete skill {rec['id']} ({name})", api.skill_delete, rec["id"])if st.get("environment_id"):eid = st["environment_id"]try:- api.request("DELETE", f"/environments/{eid}")+ api.environment_delete(eid)done.append(f"delete environment {eid}")except ApiError as e:if e.status == 404:done.append(f"delete environment {eid} (already gone)")elif e.status == 409: # still referenced: the API says to archive it instead- attempt(f"archive environment {eid}", "POST", f"/environments/{eid}/archive")+ attempt(f"archive environment {eid}", api.environment_archive, eid)else:failed.append({"what": f"delete environment {eid}", "error": str(e)})except Exception as e: # noqa: BLE001@@ -1232,7 +1315,12 @@ def main() -> int:job = json.loads(sys.argv[1])if job.get("purge"):return purge(job)- turn = Turn(job)+ try:+ turn = Turn(job)+ except ImportError as e:+ _emit("__hr_result", {"status": "failed", "final": "", "charge": None,+ "reason": f"the Qoder SDK (qca-sdk) is not installed in this interpreter: {e}"[:500]})+ return 0def on_term(signum, frame): # noqa: ARG001raise Cancelled()@@ -1249,8 +1337,13 @@ def main() -> int:except ApiError as e:turn.result("failed", f"Qoder API {e.path}: {e}"[:1000])return 0- except (urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError) as e:- turn.result("failed", f"Qoder did not answer: {type(e).__name__}: {e}"[:1000])+ except NetError as e:+ turn.result("failed", f"Qoder did not answer: {e}"[:1000])+ return 0+ except OSError as e:+ # this box, not Qoder: a workspace file that could not be read or written. The SDK raises+ # its own classes for the network, so what is left here is local, and said so.+ turn.result("failed", f"the workspace: {type(e).__name__}: {e}"[:1000])return 0diff --git a/runner/server.py b/runner/server.pyindex a85a73da..95daa638 100644--- a/runner/server.py+++ b/runner/server.py@@ -5910,7 +5910,10 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):self._forward(None)def do_DELETE(self): # noqa: N802 — a remote runtime's objects are deleted through its API- self._forward(None)+ # A DELETE may carry a body (Qoder's SDK sends `{}`); left unread, those bytes stay on the+ # keep-alive socket and open the NEXT request's line ("{}DELETE", a 501 from the upstream).+ n = int(self.headers.get("content-length") or 0)+ self._forward(self.rfile.read(n) if n else None)def log_message(self, *a): # diagnostics belong on stderr, never stdoutpass@@ -9095,7 +9098,11 @@ OPENHANDS_DRIVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "opeQODER_DEFAULT_MODEL = os.environ.get("QODER_DEFAULT_MODEL", "ultimate")QODER_PROVIDERS = {"qoder"}QODER_DEFAULT_BASE = "https://api.qoder.com/api/v1/cloud"-QODER_PYTHON = os.environ.get("HR_QODER_PYTHON", sys.executable) # stdlib only: the runner's own interpreter+# The driver speaks Qoder's SDK (qca-sdk), installed by docker/entrypoint.sh into its own venv+# (pinned and verified there, like every other backend's package); its interpreter is what runs+# the driver. The runner's own interpreter serves where that venv is not built (tests).+QODER_PYTHON = os.environ.get("HR_QODER_PYTHON") or (+ "/data/agent-tools/qoder-venv/bin/python" if os.path.exists("/data/agent-tools/qoder-venv/bin/python") else sys.executable)QODER_DRIVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qoder_driver.py")QODER_STATE_REL = os.path.join(".harness", "qoder", "state.json") # the driver's record of its remote ids# The built-ins of agent_toolset_20260401, the names tools_disabled matches; pinned equal todiff --git a/runner/tests/test_qoder_backend.py b/runner/tests/test_qoder_backend.pyindex 1b982d4c..c5649225 100644--- a/runner/tests/test_qoder_backend.py+++ b/runner/tests/test_qoder_backend.py@@ -55,6 +55,8 @@ class Stub:self.vault_creds: dict[str, list[dict]] = {} # vault id -> its credentialsself.env_delete_409 = Falseself.fail_deletes = False # every DELETE of a vault/skill/file answers 500+ self.bad_link = "" # a download link to answer instead of the blob's http one+ self.blob_refusals = 0 # the storage host refuses this many link fetches (403, a lapsed link)self.hang_streams = Falseself.script: list[list[dict]] = [[]] # the stages a NEW session getsself.token_seen: set[str] = set()@@ -110,6 +112,9 @@ class Stub:fid = path.split("/blob/", 1)[1]if "authorization" in hdrs:return self._err(400, "test", "a presigned download must carry no credential")+ if stub.blob_refusals:+ stub.blob_refusals -= 1+ return self._err(403, "AccessDenied", "Request has expired")data = stub.blobs.get(fid)return self._send(200, data, "application/octet-stream") if data is not None else self._err(404, "not_found_error", "no blob")tok = hdrs.get("authorization", "").removeprefix("Bearer ")@@ -186,7 +191,7 @@ class Stub:if parts[1] not in stub.blobs:return self._err(404, "not_found_error", "no file")host = self.headers.get("host")- return self._send(200, {"url": f"http://{host}/blob/{parts[1]}", "expires_at": "2099-01-01T00:00:00Z"})+ return self._send(200, {"url": stub.bad_link or f"http://{host}/blob/{parts[1]}", "expires_at": "2099-01-01T00:00:00Z"})if len(parts) == 2 and parts[0] == "files" and method == "DELETE":return self._send(200, {"id": parts[1], "type": "file_deleted"})if parts == ["sessions"] and method == "POST":@@ -543,7 +548,7 @@ def test_the_recorded_live_session_maps_field_for_field(tmp_path, monkeypatch):first = [e for e in events[:events.index(next(e for e in events if e["type"] == "session.updated"))]]done = Falsefor e in first:- done = turn.handle(e["id"], e["type"], json.dumps(e), "", [True]) or done+ done = turn.handle(e["id"], e, "", [True]) or doneassert done, "the first turn's status_idle ends it"kinds = [x["m"] for x in emitted]assert kinds.count("tool_use") == 2 and kinds.count("tool_result") == 2 and "text" in kinds@@ -579,7 +584,7 @@ def test_each_turn_is_charged_what_it_added_to_the_sessions_running_total(tmp_paturn = drv.Turn({"cwd": str(tmp_path), "base_url": "http://127.0.0.1:1", "api_key": "x", "prompt": "p"})turn.session_id = "sess_live"for e in part:- turn.handle(e["id"], e["type"], json.dumps(e), "", [True])+ turn.handle(e["id"], e, "", [True])turn.result("completed", "")charges.append([x["p"]["charge"] for x in emitted if x["m"] == "__hr_result"][0])assert [c["amount"] for c in charges] == [0.35, 0.26]@@ -629,17 +634,43 @@ def test_a_file_still_not_delivered_after_the_ask_makes_the_turn_incomplete(tmp_assert len(stub.posted("POST", f"/sessions/{sess_id(stub)}/events")) == 2 # asked once, not again-def test_a_download_link_that_is_not_a_web_address_lands_nothing(tmp_path, monkeypatch):- """urllib opens file:, ftp: and data: URLs as readily as https:. The link comes from Qoder's- answer; one that is not a web address would land a file of this box as the artifact."""+def test_a_download_link_that_is_not_a_web_address_lands_nothing(tmp_path, stub):+ """A client that opened file:, ftp: or data: URLs as readily as https: would land a file of+ this box as the artifact. The link comes from Qoder's answer; the SDK refuses one that is not+ a web address, and the driver reports it as such and writes nothing."""secret = tmp_path / "secret.txt"secret.write_text("not for the workspace")- turn = drv.Turn({"cwd": str(tmp_path / "ws"), "base_url": "http://127.0.0.1:1", "api_key": "x", "prompt": "p"})- monkeypatch.setattr(turn.api, "request", lambda *a, **k: {"url": secret.as_uri()})+ stub.blobs["file_x"] = b"x"+ stub.bad_link = secret.as_uri()+ turn = drv.Turn({"cwd": str(tmp_path / "ws"), "base_url": stub.base, "api_key": "x", "prompt": "p"})got, why = turn._download("file_x", "secret.txt", tmp_path / "ws" / "part")assert got is None and "not a web address" in why and not (tmp_path / "ws" / "part").exists()+def test_a_lapsed_download_link_is_asked_for_again_while_a_refused_file_is_not(tmp_path, stub):+ """The storage host answers a lapsed presigned link with 403, and the SDK raises that as the+ same class as the API's own 403. The link's refusal gets one fresh link; the API's refusal of+ the file ends the download at once."""+ stub.blobs["file_x"] = b"report"+ stub.blob_refusals = 1+ turn = drv.Turn({"cwd": str(tmp_path / "ws"), "base_url": stub.base, "api_key": "x", "prompt": "p"})+ part = tmp_path / "ws" / "part"+ got, why = turn._download("file_x", "report.txt", part)+ assert (got, why) == (6, "") and part.read_bytes() == b"report"+ assert len([c for c in stub.calls if c[1] == "/files/file_x/content"]) == 2+ # twice refused: the second link fails too, and the reason says it was the link+ stub.calls.clear()+ stub.blob_refusals = 2+ got, why = turn._download("file_x", "report.txt", tmp_path / "ws" / "part2")+ assert got is None and "refused the download link (403)" in why+ assert len([c for c in stub.calls if c[1] == "/files/file_x/content"]) == 2+ # the API's own refusal (no such file) is not retried+ stub.calls.clear()+ got, why = turn._download("file_gone", "gone.txt", tmp_path / "ws" / "part3")+ assert got is None and "404" in why+ assert len([c for c in stub.calls if c[1] == "/files/file_gone/content"]) == 1++# ── input files ───────────────────────────────────────────────────────────────────────────────────def test_input_files_are_uploaded_and_mounted_and_a_binary_one_fails_the_turn_up_front(tmp_path, stub):(tmp_path / "spec.md").write_text("# spec")@@ -874,6 +905,46 @@ def test_a_stalled_passthrough_stream_is_closed_not_narrated(monkeypatch):srv.shutdown()+def test_a_delete_with_a_body_through_the_relay_does_not_corrupt_the_next_request(stub):+ """Qoder's SDK sends `{}` as a DELETE's body. The relay's do_DELETE forwarded the request and+ left those two bytes unread on the keep-alive socket, so the NEXT request on the connection+ opened with "{}DELETE" and the stub answered 501 (found when the purge moved onto the SDK:+ the artifact file, the agent and the skill all "failed" behind one session delete)."""+ import http.client as hc+ stub.sessions["sess_1"] = {"id": "sess_1", "status": "idle", "archived_at": None, "stages": [], "stage": 0, "events": [], "resources": []}+ base, tok = rs._qoder_relay_route(stub.base, "real-pat")+ try:+ host, port = base.split("//", 1)[1].split("/", 1)[0].split(":")+ conn = hc.HTTPConnection(host, int(port), timeout=10)+ conn.request("DELETE", "/v1/sessions/sess_1", body=b"{}",+ headers={"authorization": f"Bearer {tok}", "content-type": "application/json"})+ first = conn.getresponse()+ assert first.status == 200 and json.loads(first.read())["type"] == "session_deleted"+ conn.request("GET", "/v1/sessions/sess_1", headers={"authorization": f"Bearer {tok}"})+ second = conn.getresponse()+ assert second.status == 200, second.read()[:200] # not 501 "Unsupported method ('{}GET')"+ assert json.loads(second.read())["id"] == "sess_1"+ finally:+ rs._HERMES_RELAY["routes"].pop(tok, None)+++def test_every_message_carries_an_idempotency_key_and_the_sdks_own_headers_pass_the_relay(tmp_path, stub):+ """The API's guard against a retried POST running twice is the Idempotency-Key header, which+ is also the SDK's own condition for retrying a POST at all; every user.message carries one, a+ fresh one per message. The route is the SDK's, so its User-Agent reaches Qoder."""+ stub.script = [[RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "one"}]}, IDLE]]+ base, tok = rs._qoder_relay_route(stub.base, "real-pat")+ try:+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "first"}, stub, base=base, token=tok)+ assert result_of(normalise(lines)[0])["subtype"] == "success"+ msgs = [c for c in stub.calls if c[0] == "POST" and c[1].endswith("/events")]+ assert msgs and all(len(c[3].get("idempotency-key", "")) == 32 for c in msgs)+ assert all(c[3].get("user-agent", "").startswith("qca-python/") for c in msgs)+ assert "real-pat" in stub.token_seen and tok not in stub.token_seen+ finally:+ rs._HERMES_RELAY["routes"].pop(tok, None)++# ── the builder ───────────────────────────────────────────────────────────────────────────────────def test_the_builder_hands_the_driver_the_relay_and_a_placeholder_never_the_key(tmp_path):env: dict = {}@@ -963,6 +1034,42 @@ def test_the_purge_reaches_every_recorded_id_and_reports_what_it_could_not(tmp_passert "delete session sess_1 (already gone)" in report["done"]+def test_without_the_sdk_a_turn_fails_in_words_and_a_purge_names_what_it_left(tmp_path, stub):+ # The interpreter the runner falls back to (its own) has no qca-sdk: a turn must fail with the+ # reason, and a purge must report every recorded id rather than die in a traceback, since the+ # runner removes the folder, and the state with it, whatever the purge answers.+ def run_without_sdk(job: dict):+ job = {"base_url": stub.base, "api_key": "placeholder", "model": "ultimate", **job}+ boot = ("import runpy, sys; sys.modules['qca'] = None; sys.modules['qca.managed'] = None; "+ "sys.argv = sys.argv[1:]; runpy.run_path(sys.argv[0], run_name='__main__')")+ proc = subprocess.run([sys.executable, "-c", boot, DRIVER, json.dumps(job)],+ capture_output=True, text=True, timeout=30)+ return [json.loads(ln) for ln in proc.stdout.splitlines() if ln.strip().startswith("{")], proc++ lines, proc = run_without_sdk({"cwd": str(tmp_path), "prompt": "hi"})+ res = [l for l in lines if l["m"] == "__hr_result"][-1]["p"]+ assert res["status"] == "failed" and "qca-sdk" in res["reason"]+ assert not stub.calls+ write_state(tmp_path)+ lines, proc = run_without_sdk({"purge": True, "cwd": str(tmp_path)})+ assert proc.returncode == 1 and "Traceback" not in proc.stderr+ report = [l for l in lines if l["m"] == "purge"][-1]["p"]+ assert report["done"] == [] and "qca-sdk" in report["failed"][0]["error"]+ for rid in ("sess_1", "file_art", "file_in", "agent_1", "vault_1", "skill_1", "env_1"):+ assert rid in report["failed"][0]["what"], rid+ assert not stub.calls+++def test_a_workspace_that_cannot_be_written_fails_the_turn_in_words(tmp_path, stub):+ # The SDK raises its own classes for the network, so an OSError that reaches the top is this+ # box's: it ends the turn with a result that says so, never a traceback with no result.+ (tmp_path / ".harness").mkdir()+ (tmp_path / ".harness" / "qoder").write_text("a file where the state's folder goes")+ lines, proc = run_driver({"cwd": str(tmp_path), "prompt": "hi"}, stub)+ res = [l for l in lines if l["m"] == "__hr_result"][-1]["p"]+ assert res["status"] == "failed" and res["reason"].startswith("the workspace: ") and "Traceback" not in proc.stderr++def test_delete_workspace_purges_at_qoder_with_the_connection_it_is_sent(tmp_path, stub, monkeypatch):import asyncioroot = tmp_path / "root"