Skip to content

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.

Qoder Cloud Agent as the qoder backend: the first remote runtime (#438)

Shi Peipei4b93d3b25d9f
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 6803229a..d16eb5d5 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -212,7 +212,7 @@ export NODE_PATH="$TOOLS/lib/node_modules"
#
# gajae is NOT among them, and the gateway offers no gajae base either: its CLI cannot run under
# this product's write-wall. gateway/app.py carries the measurement, above _MODEL_CATALOG["mimo"].
-export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,agentzero,systemone,cheetahclaws,mimo,jcode,opensquilla,nanobot}"
+export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,agentzero,systemone,cheetahclaws,mimo,jcode,opensquilla,nanobot,qoder}"
wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }
# The executable IS the definition of "installed" — an installer that exits 0 without producing
@@ -240,6 +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" ;;
mimo) echo "$TOOLS/bin/mimo" ;;
gajae) echo "$TOOLS/bin/gjc" ;;
jcode) echo "$TOOLS/bin/jcode" ;;
diff --git a/docs/harness-verification.md b/docs/harness-verification.md
index 96bd14a1..6b3e4375 100644
--- a/docs/harness-verification.md
+++ b/docs/harness-verification.md
@@ -226,6 +226,99 @@ and need no edit — they were hand-written lists once, and each silently missed
Its models must be honest: every id the picker offers must run as itself, and a turn that ran on a
different model fails rather than quietly succeeding.
+### Remote runtimes
+
+A remote runtime is a harness whose agent loop runs somewhere this runner does not spawn it: a
+hosted session reached over an API, with the turn process here an HTTP client to it. Qoder Cloud
+Agent (`qoder`, `runner/qoder_driver.py`) is the first. The registry entry declares it —
+`BACKENDS[...]["remote"] = True` — and that flag is what the runner keys the differences below on,
+so the second one follows the same shape instead of rediscovering it. The per-turn contract does
+not change: one process per turn, `__hr_init`, one `{"m","p"}` line per event, `__hr_result`, and
+`server.py` unaware of the wire. What changes is that three things every local backend gets for
+free have to be built, and several of the registration points above have no object.
+
+**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.
+- *3 and 4, `_write_skills` and `_agent_doc_path` as places a loader looks.* Nothing on this box
+ loads 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
+ instructions travel in the job and become the remote Agent's system prompt
+ (`_write_agent_doc` writes nothing, the systemone precedent).
+- *A plugin's stdio MCP servers.* They are processes on this box; a remote runtime cannot dial
+ them. The driver reports each one as `system/mcp_unavailable` and the base lists no tool for
+ them. URL servers are configured on the remote Agent, and their bearer travels to the vendor
+ (qoder: a Vault credential, created per session and deleted with it); the base's description
+ says so, because the harness owner's token then lives at the vendor.
+- *Environments* (`runner/environments.py`). The layer is mounted read-only in THIS sandbox; the
+ remote session sees only what the driver uploads. A turn that names one is refused before any
+ process starts (`turn()`, 400), rather than run without it.
+- *7, `CHECKPOINT_EXCLUDE` for credentials.* The driver writes none: it holds the relay's
+ placeholder. What it does write is `.harness/<backend>/state.json`, the ids of everything it
+ created remotely, and that file MUST travel in the checkpoint (continuation and deletion on
+ another sandbox depend on it).
+
+**Must be answered instead, each in the PR description and each with a test:**
+
+- *Input files.* `_write_input_files` lands them in a workspace the runtime cannot see. The driver
+ uploads what was staged and tells the model where it is mounted; what the vendor will not take
+ (qoder: anything but a text-type file, 5 MB) fails the turn before anything is created, naming
+ the file, and the base's description states the limit.
+- *Artifacts.* Nothing under `.harness/` is a produced file (`_PRODUCED_EXCLUDE_PREFIX`). A
+ delivered artifact is written to the workspace ROOT and rides the checkpoint, diff and download
+ path unchanged. The driver keeps the list the stream declared and verifies every one landed with
+ its declared size; one missing, expired or refused ends the turn `incomplete` naming it, even
+ when the remote run reports success. **Artifact names are input**: only a plain file name is
+ written — no path separator, no `..`, nothing opening a dot directory, no control characters —
+ an existing file is never overwritten (the new one lands as `name (2).ext` and the record says
+ so) and a symlink is never followed. `../x` and `.harness/x` are pinned refused.
+- *Cancellation.* `_kill_proc_tree` is SIGSTOP then SIGKILL; neither runs a handler, and a killed
+ client leaves the remote turn running and billing. For a `remote` backend `_stop_proc` sends
+ SIGTERM first and waits `_REMOTE_STOP_GRACE_S` while the reader loop keeps draining stdout, so
+ the driver's own line — "cancel accepted", or "cancel failed, session <id> may still be running"
+ — reaches the record before the kill. The same path serves the wall-clock cap. A driver that
+ dies without its result ends the turn with "the session may still be running" (`_qoder_eof`).
+- *Continuation.* `_SESSION_PRESENT` has no probe for it: the driver itself asks the vendor
+ whether the session the caller named is there and takes a message, emits `resume_lost` when it
+ is not, and starts a new one. A session still running an earlier turn is a conflict and fails
+ the turn; it is never retried blindly. `hard` has to hold across turns too: a session that
+ pins its Agent's configuration at creation gets its tools replaced before every message
+ (qoder: `POST /sessions/{id}` with `agent.tools`), pinned by a test that disables a tool
+ between two turns.
+- *Recovery.* The runner replays nothing. A dropped stream is the driver's to resume from its
+ last event id inside the turn; the message is NEVER sent twice — when its acknowledgement is
+ lost the session's history decides whether it arrived. A stream that ends without a terminal
+ event asks the session's status before deciding.
+- *Served model, usage, charge.* Rule 2 and the token columns read what the relay saw; on a
+ pass-through route the relay sees nothing it may use, and the vendor reports what it reports.
+ qoder's public API exposes neither token counts nor the model that served, so its rows read
+ "served model unreported", the token cells are empty, and the result carries no `usage` and no
+ `model`. What it does expose goes on the result as `charge: {amount, unit, basis}` — a shape
+ that names no vendor, so the next runtime uses the same field — never folded into the token
+ columns, and with `basis: "snapshot"` when the figure can lag the turn (qoder's sandbox charges
+ settle after idle). A vendor figure that is the session's running total, as qoder's is, is
+ charged per turn as what the turn added to it, with the total beside it (`session_total`);
+ charging the total as it stands bills every earlier turn again. Every `stop_reason` other than the vendor's normal end is `incomplete` with
+ the raw reason, and a typed error event with no retry left is `failed` with the vendor's
+ sentence.
+- *Deletion.* Since 0.32.0 a delete removes data for real, and for this backend the conversation,
+ the input files, the artifacts and every Agent, Skill, Vault and Environment the driver created
+ live at the vendor. `DELETE /workspace` takes the connection in its body (`WorkspaceDelete`) and
+ runs the driver in purge mode before removing the folder (`_remote_purge`); each remote delete
+ that fails is reported with its id in the answer and the log, never swallowed. The lifecycle is
+ one of everything per session — created on the first turn, updated when the harness changed,
+ deleted with the session — so nothing outlives it and the per-turn runner keeps no state at
+ harness level.
+- *The relay is still the credential boundary.* The vendor's API is HTTPS with a bearer, which is
+ exactly what the loopback relay fronts: the base is registered as a PASS-THROUGH route
+ (`_qoder_relay_route`, `_HermesRelayHandler._passthrough`) — no body rewrite, no retry ladder,
+ and NONE of the taps, because a session object through the model-call taps would record the
+ CONFIGURED 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.
+
## What the matrix did not see, and what changed (2026-09-30)
A customer ran twelve of their production tasks across seven bases and nine models on a 2026-09-30
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index 47c17c8c..00a65197 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -3172,6 +3172,145 @@ The patch was run against the real `hermes-agent` 0.19.0 file: it changes two pl
Not shown live: a server that cannot be reached still opening the breaker. When the tool server was stopped mid-task Hermes dropped its tools ("Unknown tool") before the breaker came into it. That half is covered by the test of the patched check, where an error that did not come from a tool's own answer still counts.
+## The qoder backend: Qoder Cloud Agent, the first remote runtime (2026-10-09) — behaviour measured at a stub, NO column yet
+
+Qoder Cloud Agent runs the agent loop in Qoder's cloud and is reached over its Managed API
+(REST + SSE, `/api/v1/cloud`). The runner's turn process, `runner/qoder_driver.py`, is an HTTP
+client to it: it creates one Environment, one Agent and one Session per HarnessRouter session,
+posts the message, follows the event stream and lands delivered artifacts in the workspace root.
+The registry marks the backend `remote`, and `docs/harness-verification.md` ("Remote runtimes")
+lists what that changes. Issue #236 holds the design discussion.
+
+### Behaviour measured before any column
+
+Measured against a stub of the Managed API built from the public reference
+(`runner/tests/test_qoder_backend.py`, the driver run as the subprocess it is), not against
+api.qoder.com; the live column is the next step and needs a tenant's PAT.
+
+- A turn with a tool call and a delivered artifact: the delta text then only the remainder of the
+ buffered message; the tool call and result under Qoder's event ids; the artifact in the
+ workspace ROOT with its declared bytes, nothing under `.harness/`; the result with no usage, no
+ model, and `charge: {amount, unit: "qoder_credits", basis: "snapshot"}` from the session's usage
+ snapshot, less what the session had used before the turn (the snapshot is the session's running
+ total: 0.35 after the recorded session's first turn, 0.61 after its second, so the second is
+ charged 0.26). The Agent's toolset carries the disabled tool out of the whitelist, in
+ `disallowed_tools` and `enabled: false`; every enabled one `always_allow`.
+- A declared artifact that does not land, a name with a path, `..`, a dot directory or a control
+ character: the turn is `incomplete` naming the file, nothing is written for it, and nothing is
+ even fetched for a refused name. An existing file is never overwritten (`name (2).ext`) and a
+ symlink is never followed.
+- A tool disabled between two turns of one session: the Agent gets a new version AND the session's
+ own tools are replaced (`POST /sessions/{id}`, `agent.tools`) before the message goes.
+- A session archived at Qoder, or an id the state never knew: `resume_lost`, then a new session; a
+ session still running an earlier turn: a conflict, failed, and the message is not sent.
+- A pending confirmation (`stop_reason: requires_action`): answered — `allow`, or `deny` with a
+ message for a tool the harness disabled — and the turn goes on to its real stop.
+- Every `stop_reason` other than `end_turn` is `incomplete` with the raw reason; a `session.error`
+ with `retry_status: retrying` is waited on, one with `exhausted`/`terminal` fails the turn with
+ Qoder's sentence; `session.status_terminated` fails it.
+- Input files: uploaded once by content hash, mounted at `/mnt/session/uploads/<name>` and named
+ in the system prompt; a binary file fails the turn before anything is created, naming it.
+- Skills: published as custom Skill resources from the staged bundle (bare file tree under the
+ frontmatter name), a new version only when the bytes changed, bound on the Agent; a bundle
+ whose `name` is not a Qoder skill name is reported, not published. A URL MCP server's bearer
+ becomes a Vault credential and the session names the vault; a stdio server is reported
+ `mcp_unavailable`.
+- SIGTERM mid-turn: `POST /sessions/{id}/cancel` reaches the stub, the record carries "cancel
+ accepted by Qoder for session <id>", exit 0; through the runner, `cancel_turn` on a `remote`
+ backend sends SIGTERM first and the driver's last lines reach the turn record before the kill,
+ while a local backend's stop is the SIGKILL it always was.
+- The relay route: a session object naming the configured model passes through and the turn's
+ served model stays empty; DELETE goes up; a 404 comes down as the API wrote it; a stalled stream
+ is closed without an error event. The stub sees the real credential and never the placeholder;
+ the driver sees the placeholder and never the credential.
+- The purge: cancel then delete the session, delete artifact and input files, archive the Agent,
+ delete the Vault, the Skills and the Environment (archived when still referenced); an object
+ already gone is not a failure; a delete the API refuses is reported with its id and the exit says
+ so. `DELETE /workspace` with the connection in its body runs it through the relay; without a
+ credential the folder still goes and the answer says what was left at Qoder.
+
+### Live, against api.qoder.com (2026-10-09, Global region, model `efficient`)
+
+The driver run directly against the Managed API with a tenant PAT, no gateway in the path; the
+recorded history is `runner/tests/fixtures/qoder/live-session-events.json` and a test reads the
+driver's mapping off it.
+
+- **First turn** (12.7 s): Environment, Agent (v1) and Session created; `Write` then
+ `DeliverArtifacts`; `agent.artifact_delivered` with `file_id`, `original_filename: hello.md`,
+ `size: 36`, `content_type`; the file landed in the workspace root with the declared bytes;
+ `session.usage` then `session.status_idle {end_turn}`; charge snapshot
+ `{model_credits: 0.35, sandbox_runtime_credits: 0.03, total_credits: 0.38}`. The event order was
+ the one the reference describes; `agent.thinking` carried no content; `span.model_request_end`
+ carried `model_usage.credits` and no token count, as documented.
+- **Second turn on the same session, Bash disabled between the turns** (5.7 s): the Agent went to
+ v2 and the session's tools were replaced (`session.updated` is in the history); asked to run a
+ shell command, the model answered "I don't have a Bash shell tool available. My available tools
+ are: Read, Grep, Glob, Write, Edit, WebFetch, ImageSearch, ImageGen, and DeliverArtifacts" and
+ recalled the first turn's file verbatim — `hard` across turns, and continuation, on the wire.
+- **Cancellation**: a `sleep 120` Bash step, SIGTERM to the driver 5 s in: `POST /cancel` answered
+ 202 at once and the record carries "cancel accepted by Qoder for session <id>"; the remote
+ session still read `running` 3 s later and `idle` within 20 s, its history ending in
+ `session.status_idle {stop_reason: {type: "cancelled"}}` — the abort is asynchronous, and
+ `cancelled` is a `stop_reason` value the reference does not list (it would read as `incomplete`
+ with that raw reason on a turn that saw it). The cancelled turn billed 0.29 model credits.
+- **Purge**: cancel, delete session, delete the artifact file, archive the Agent all answered as
+ documented; `DELETE /environments/{id}` answered **409** even after the session was deleted, and
+ the archive fallback took it.
+- **Models**: `GET /models` listed 17 ids for this tenant (`auto`, `ultimate`, `performance`,
+ `efficient`, `smodel`, `qmodel_38max`, `qfmodel`, `qmodel_latest`, `qmodel`, `kmodel_latest`,
+ `kmodel`, `gmodel`, `gfmodel`, `dmodel`, `dfmodel`, `mmodel`, and a tenant-private dog-fooding
+ mode), each with its `price_factor` and, for most, an `efforts` list — more than the reference's
+ one documented id. The China-region base answered 401 to this token, so a connection is one
+ region. The catalog carries the sixteen public ids; `ultimate` and `efficient` have completed
+ turns.
+
+### 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 session
+idle 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`.
+
+### Versions and the column
+
+Public reference `04-Managed层`, API version as served on 2026-10-09; no Qoder API version header
+is documented. The live column (five scenarios, custom-harness dimension, the family tour where it
+applies — Qoder picks the model, so a "switch" is a different Qoder id) and a `scripts/benchmark`
+column run once a tenant PAT is on the instance, and this section gains what they measured.
+
+### Through a self-hosted instance (2026-10-10, 0.33.0-rc.2 to rc.4, Global region, Pro Trial account)
+
+Owner trust, the Qoder connection added to the instance, driven through the console and the API.
+
+- **A plan without credits is refused at the session**, with Qoder's sentence on the record: `402
+ billing_error: You have no available credit`. The Environment, Agent and Skills made before the
+ refusal were deleted with the task (the Agent archived), which also proved the purge live.
+- **Delivered file, follow-up, charge.** qfmodel wrote and delivered `hello.md`; the follow-up on
+ the same Qoder session recalled its line. The first turn was charged 0.29 credits and the second
+ 0.03 against a session total of 0.32: the snapshot is the session's running total, and before the
+ per-turn delta the second turn read 0.32. qfmodel is not free here: a small turn bills about
+ 0.23 model credits although `GET /models` gives it a price factor of 0.
+- **A tool disabled between turns.** A custom harness ran `uname -s` through Bash, then had Bash
+ disabled; the next turn answered NO SHELL and called nothing. Qoder's session showed `Bash` in
+ `disallowed_tools` and `enabled: false` while the Agent stayed at version 1.
+- **Cancel.** Stop on a turn running `sleep 120`: the record says `cancel accepted by Qoder for
+ session …`, and the Qoder session was idle 6 s after the stop.
+- **Files written and never delivered.** On rc.3 the artifact scenario failed on `auto` and
+ `performance`: the agent wrote the file and answered DONE without calling DeliverArtifacts,
+ though both Qoder's system prompt and ours tell it to. On rc.4, which asks once for what was
+ written and not delivered, one turn of the artifact scenario per model: the 14 ids run there all
+ delivered `HELLO` and answered DONE, and the ask was needed on 10 of the 12 whose Qoder history
+ was read (qmodel_latest and kmodel delivered unasked). `ultimate` delivered unasked in the rc.3
+ matrix, and `smodel` on rc.3 when the prompt said to deliver. qfmodel ran the five console
+ scenarios, all ok (the first try lost the file card in the console while the record held the
+ file; the retry passed).
+- **Cost of one small turn**, in credits: qfmodel 0.33, gfmodel 0.26, dfmodel 0.31, qmodel 0.41,
+ mmodel 0.43, efficient 0.41, auto 0.29, kmodel 0.92, dmodel 1.25, gmodel 1.61, kmodel_latest
+ 2.36, qmodel_38max 2.44, qmodel_latest 2.47, performance 4.27, smodel 11.2. Qoder also lists
+ `cmodel` (Cantus, price factor 4); it is not in the catalog, not having been measured.
+
## Five bases added together, four of them offered (2026-10-02/06)
MiMo Code (XiaomiMiMo/MiMo-Code, MIT), Gajae-Code (Yeachan-Heo/gajae-code, MIT), jcode
diff --git a/gateway/app.py b/gateway/app.py
index 9dfebab2..0ec20b7a 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -968,7 +968,11 @@ _BROKERABLE_PROVIDERS = {"anthropic", "tokenrouter", "openai", "azure", "azure-f
# turn dying on a 400 nobody can read. gemini-cli 0.58.0 honours GOOGLE_GEMINI_BASE_URL on the
# API-key path (measured 2026-09-06: pointed at a dead port it retried "fetch failed" against it),
# so the native paths can be brokered later; until the broker carries them, this set is the guard.
-_NATIVE_ONLY_BACKENDS = {"gemini"}
+_NATIVE_ONLY_BACKENDS = {"gemini",
+ # qoder: the driver speaks Qoder's own control API (sessions, events, files),
+ # which the broker's model doors do not carry; the runner's loopback relay is
+ # its credential boundary, and that needs the connection's key on the box
+ "qoder"}
# ── A harness that drives another harness ─────────────────────────────────────────────────────
@@ -1340,6 +1344,9 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {
# systemone speaks the provider's decisions endpoint through the loopback relay: TypeSafe's own
# API (/v1/systemone) and OpenRouter, the one aggregator serving Jev (beta since 2026-09-18).
("openrouter", "systemone"): "openrouter", ("typesafe", "systemone"): "typesafe",
+ # qoder runs on Qoder's own hosted runtime and bills through Qoder's model access: a connection
+ # carries a Qoder PAT or SAT and nothing else drives it, so the one pair is its own provider.
+ ("qoder", "qoder"): "qoder",
("tokenrouter", "openhands"): "tokenrouter", ("vercel", "openhands"): "tokenrouter",
("llmtr", "openhands"): "tokenrouter",
("custom", "openhands"): "openai-api",
@@ -2854,6 +2861,8 @@ async def _adopt_orphan_turn(sid: str, org: str, v: dict) -> bool:
rec["status"] = "done" if terminal == "completed" else terminal
if translator.usage:
rec["usage"] = translator.usage
+ if translator.charge:
+ rec["charge"] = translator.charge
await _vertex_upsert(sid, {"status": rec["status"], "turn_status": rec["status"]})
try:
# Every terminal outcome collects. A cancelled or failed turn may already have written the
@@ -3985,7 +3994,10 @@ def _broker_token(request: Request) -> str:
_PROVIDER_BASE = {"openai": "https://api.openai.com/v1", "anthropic": "https://api.anthropic.com/v1",
# Google AI Studio keys answer on Gemini's OpenAI-compatible surface (chat
# completions); a key alone names the endpoint, the same way an OpenAI key does.
- "google": "https://generativelanguage.googleapis.com/v1beta/openai"}
+ "google": "https://generativelanguage.googleapis.com/v1beta/openai",
+ # Qoder's Managed API, global region; the China region (api.qoder.com.cn) is a
+ # connection with its base_url set
+ "qoder": "https://api.qoder.com/api/v1/cloud"}
def _with_provider_base(conn: dict | None) -> dict | None:
@@ -5138,6 +5150,40 @@ async def _session_index() -> dict:
return idx
+async def _remote_delete_body(sid: str, v: dict | None) -> dict | None:
+ """What the runner's DELETE /workspace needs for a session of a REMOTE backend: the connection
+ whose runtime holds the session's objects, so the runner can delete them there too (the
+ conversation, the files, the Agent the turns created — runner _remote_purge). None for a local
+ backend, where the folder is all there is. The connection is the org's integration for that
+ provider, handed over the way a turn hands it (_auth_from_conn: owner trust, the key; broker
+ trust, nothing — this backend is not brokered — and the runner then says what was left)."""
+ backend = str((v or {}).get("backend") or "").lower()
+ if backend != "qoder":
+ return None
+ try:
+ integs = await _integrations_doc()
+ except Exception: # noqa: BLE001
+ integs = []
+ # The connection the session's turns ran on (last_connection, "integration:<name>"): its objects
+ # live in THAT account. Another Qoder connection's key would be refused there and leave them
+ # billing, so with more than one and the session's own gone, nothing is guessed.
+ qoders = [i for i in integs if str(i.get("provider") or "").lower() == "qoder"]
+ last = str((v or {}).get("last_connection") or "")
+ used = last.split(":", 1)[1] if last.startswith("integration:") else ""
+ integ = next((i for i in qoders if str(i.get("name") or "") == used), None) if used else None
+ if integ is None and len(qoders) == 1 and not used:
+ integ = qoders[0]
+ if not integ:
+ print(f"[delete] session {sid}: a qoder session whose connection ({last or 'unrecorded'}) is not "
+ f"configured among {len(qoders)} qoder integration(s); its remote objects cannot be deleted "
+ "from here", flush=True)
+ return {"backend": backend}
+ conn = {"name": f"integration:{integ.get('name') or ''}", "backend": backend, "provider": "qoder",
+ **{k: val for k, val in (integ.get("config") or {}).items() if val not in (None, "")}}
+ auth = _auth_from_conn(_with_provider_base(conn) or conn, sid)
+ return {"backend": backend, "auth": auth}
+
+
async def _session_purge(sid: str, v: dict | None, index: dict | None = None) -> None:
"""Everything a session left, removed: its transcript and trace, its responses, the files its
tasks produced, their previews and change list, its media, the record of every plugin call it
@@ -5192,7 +5238,7 @@ async def _session_purge(sid: str, v: dict | None, index: dict | None = None) ->
# delete fails — the session is already unreadable by the time this runs.
if POOL_ENDPOINT:
try:
- await _sandbox("/workspace", sid, "DELETE")
+ await _sandbox("/workspace", sid, "DELETE", body=await _remote_delete_body(sid, v))
except Exception: # noqa: BLE001
pass
await _media_session_purge(sid)
@@ -5301,6 +5347,19 @@ _PROVIDER_CATALOG: dict[str, dict] = {
"secret_label": "API Key",
"key_hint": "apikey_…",
},
+ # Qoder Cloud Agent: a hosted agent runtime, not a model endpoint. The key is a personal access
+ # token or a service-account token; Qoder picks and bills the model behind it, so only the qoder
+ # base can use this connection, and nothing it serves appears in another base's picker. The
+ # global region's base is fixed here; a China-region tenant sets base_url to
+ # https://api.qoder.com.cn/api/v1/cloud on the connection. A key is checked at GET /models.
+ "qoder": {
+ "label": "Qoder Cloud Agent",
+ "base_url": "https://api.qoder.com/api/v1/cloud",
+ "fields": [],
+ "secret": "api_key",
+ "secret_label": "Access token (PAT or SAT)",
+ "key_hint": "a Qoder personal or service-account token",
+ },
"tokenrouter": {
"label": "TokenRouter",
"base_url": "https://api.tokenrouter.com/v1",
@@ -6016,6 +6075,9 @@ def _blocks_from_canonical(ev: dict) -> list[tuple[str, object]]:
elif t == "result":
out.append(("result", {"text": ev.get("result") or "", "usage": ev.get("usage"),
"is_error": bool(ev.get("is_error")),
+ # what a remote runtime billed the turn, in its own unit, when it says
+ # (qoder: credits; never folded into the token counts)
+ **({"charge": ev["charge"]} if isinstance(ev.get("charge"), dict) else {}),
# the thinking level asked and the one applied (runner: _stamp_thinking);
# absent for a turn that asked for none
**({"reasoning": ev["reasoning"]} if ev.get("reasoning") else {}),
@@ -6096,6 +6158,9 @@ class _RespTranslator:
self.out_index = -1
self.output: list[dict] = []
self.usage: dict | None = None
+ # {"amount", "unit", "basis", ...}: what a remote runtime charged for the turn, in its own
+ # unit (qoder credits), when its API said; None for every backend whose cost is its tokens.
+ self.charge: dict | None = None
self.error: dict | None = None
self.cur: dict | None = None
self.any_text = False
@@ -6113,6 +6178,8 @@ class _RespTranslator:
meta["environment"] = self.environment
if self.ignored:
meta["ignored_fields"] = self.ignored
+ if self.charge:
+ meta["charge"] = self.charge
return {"id": self.resp_id, "object": "response", "created_at": int(self.created_at),
"status": status, "error": self.error,
"incomplete_details": ({"reason": self.incomplete_reason, "handoff": self.handoff}
@@ -6220,6 +6287,8 @@ class _RespTranslator:
elif kind == "result":
if payload.get("model"):
self.served_model = str(payload["model"])
+ if isinstance(payload.get("charge"), dict):
+ self.charge = payload["charge"]
r = payload.get("reasoning")
if isinstance(r, dict) and self.reasoning is not None:
self.reasoning = {"effort": self.reasoning.get("effort") or r.get("effort"),
@@ -6749,6 +6818,30 @@ _VENDOR_MODELS["openrouter"].update({"jev-1.13": "typesafe/jev-1.13", "jev-lates
# the pinned id stays OpenRouter's alone and the preview stays TypeSafe's: a harness resolves the id
# it names through the table of the connection that serves it, and nothing is guessed across them.
_VENDOR_MODELS["typesafe"] = {"jev-latest": "jev-latest", "jev-preview": "jev-preview"}
+# Qoder's own catalogue, as GET /api/v1/cloud/models lists it for the tenant: the ids are Qoder's
+# names and reach the Agent verbatim. `ultimate` is the one the public reference documents; the
+# column measures the tenant's list and this table grows from what ran.
+_VENDOR_MODELS["qoder"] = {m: m for m in (
+ # as GET /api/v1/cloud/models listed them for a Global-region tenant on 2026-10-09; the display
+ # name is Qoder's and the id reaches the Agent verbatim. A tenant-private id (the dog-fooding
+ # mode) is not offered.
+ "auto", # Auto
+ "ultimate", # Ultimate
+ "performance", # Performance
+ "efficient", # Efficient
+ "smodel", # Sonus
+ "qmodel_38max", # Qwen3.8-Max
+ "qfmodel", # Qwen3.8-Flash
+ "qmodel_latest", # Qwen3.7-Max
+ "qmodel", # Qwen3.7-Plus
+ "kmodel_latest", # Kimi-K3
+ "kmodel", # Kimi-K2.8-Preview
+ "gmodel", # GLM-5.3
+ "gfmodel", # GLM-5.3-Flash
+ "dmodel", # DeepSeek-V4-Pro
+ "dfmodel", # DeepSeek-Flash
+ "mmodel", # MiniMax-M3
+)}
# Vercel's AI Gateway carries the same catalogue under nearly the same slugs, so it starts from
# OpenRouter's table too. Only the vendor prefix differs on four of them, and it differs because
@@ -7397,6 +7490,16 @@ _MODEL_CATALOG["systemone"] = {"default": "jev-latest",
# models the hosted service serves, reachable with a HarnessRouter key
"models": ["jev-latest", "jev-preview", "jev-1.13",
"laya", "openthai-systemone", "system-one-phase2"]}
+# qoder: Qoder's own model ids (_VENDOR_MODELS["qoder"]), the ones its GET /models lists. Qoder
+# chooses what serves an id and reports neither the served model nor token counts on its public
+# API, so these rows read "the id completed a turn" (docs/harness-verification.md, remote runtimes);
+# the list is what the column has run, starting from the documented id.
+_MODEL_CATALOG["qoder"] = {"default": "ultimate",
+ # every one completed a turn that delivered the file it was asked for, on
+ # 0.33.0-rc.3 and rc.4 against api.qoder.com (2026-10-10); qfmodel also ran
+ # the five console scenarios. Qoder also lists cmodel (Cantus), not measured
+ # and not offered: one turn there costs about 16 credits
+ "models": list(_VENDOR_MODELS["qoder"])}
# A pair the matrix failed twice on the one aggregator that serves the id is not offered on that
# harness (2026-09-13, five scenarios each): llama-4-maverick on OpenRouter under qwen writes the
# tool call as prose; llama-3.3-70b on OpenRouter fails the recall under goose, the artifact under
@@ -8377,6 +8480,8 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
# finalize record — it's what the per-model llm.* metering bills.
if translator.usage:
rec["usage"] = translator.usage
+ if translator.charge:
+ rec["charge"] = translator.charge # a remote runtime's own bill for the turn, beside the tokens
_cancel_req.pop(sid, None) # turn settled — a leftover Stop must not hit the next turn
await _browser_close(sid, "turn_end") # before the checkpoint and the finalize: the stop row belongs in the trace (see _adopt_orphan_turn)
await _checkpoint(sid, rec)
@@ -9115,6 +9220,11 @@ async def create_response(body: CreateResponseBody, request: Request):
# here, before anything is allocated, so a missing or unbuilt environment is a 4xx and not a
# failed turn.
environment = await _environment_for_turn(org, _task_environment_ref(body, hv))
+ if environment and not _backend_takes_environments(_backend_of_harness(hv) or _backend_of_builtin(harness_id or "")):
+ # The layer is mounted in THIS sandbox; a remote runtime sees none of it. Refused in words
+ # rather than run without the project the task named.
+ raise uhp_error(400, "environment_unsupported",
+ "This harness runs in a remote runtime and cannot mount an environment.", "environment")
# HR-INF-023: credit admission. BILLING is the harness OWNER's org — the Developer who built the
# harness funds its infra consumption (hv["org"], stamped at harness creation), regardless of who
# calls it. A turn with no harness vertex (built-in, or an ad-hoc/chained turn that carries no
@@ -16883,6 +16993,35 @@ _BASE_CATALOG: dict[str, dict] = {
# an MCP server. Pinned by gateway/tests/test_systemone_catalog.py.
"skills": False,
},
+ "qoder": {
+ "label": "Qoder Cloud Agent", "backend": "qoder", "status": "ready",
+ # The remote Agent's `system`, before the harness's own instructions and the runner's
+ # delivery contract (runner/qoder_driver.py system_prompt): a file reaches the person only
+ # when the agent delivers it.
+ "system_prompt": ("You are Qoder, an autonomous coding agent running in a cloud sandbox with "
+ "shell and file access. Read, edit and run what the task needs, and deliver "
+ "every file the user should receive with DeliverArtifacts."),
+ # The built-ins of agent_toolset_20260401, in Qoder's own names (pinned equal to the runner's
+ # QODER_TOOLS by gateway/tests/test_qoder_catalog.py). A disabled tool is withheld by the
+ # Agent's configuration itself — out of the whitelist, named disallowed, `enabled: false` —
+ # and the session's tools are replaced before every turn, so the deny lands before any
+ # execution: `hard` by UHP §4.3, on every turn of a session. The enabled ones run
+ # `always_allow`, so the remote turn never pauses for a confirmation nobody is here to give.
+ "tools": [("Bash", "Shell"), ("Read", "File Read"), ("Write", "File Write"), ("Edit", "Edit"),
+ ("Glob", "Glob"), ("Grep", "Search"), ("WebFetch", "Web Fetch"), ("WebSearch", "Web Search"),
+ ("ImageSearch", "Image Search"), ("ImageGen", "Image Generation"),
+ ("DeliverArtifacts", "Deliver Artifacts")],
+ "tool_enforcement": "hard",
+ # The runtime is Qoder's, not a process on this box (runner BACKENDS["qoder"]["remote"]):
+ # skills are published to Qoder as Skill resources bound on the session's Agent (so
+ # `skills` stays on); a plugin's stdio MCP servers cannot be reached from there and are
+ # reported unavailable; URL MCP servers are dialled by Qoder's cloud with their bearer held
+ # there in a Vault created for the session; input files are text-type only, 5 MB; an
+ # environment layer cannot be mounted. Token counts and the served model are not on Qoder's
+ # public API: the turn carries a `charge` in Qoder credits instead.
+ "environments": False,
+ "remote": True,
+ },
"qwen": {
"label": "Qwen Code", "backend": "qwen", "status": "ready",
"system_prompt": ("You are Qwen Code, an autonomous coding agent. You work on a real git "
@@ -17034,6 +17173,14 @@ _BASE_CATALOG: dict[str, dict] = {
# `claude` is accepted as an alias for `claude-code` because existing harnesses store it.
_SUPPORTED_BASES = tuple(_BASE_CATALOG) + ("claude",)
+
+def _backend_takes_environments(backend: str) -> bool:
+ """Whether a turn on `backend` can mount an environment layer (runner/environments.py). A base
+ whose runtime is remote reads nothing from this box and declares `environments: False`; the
+ turn is refused before anything is allocated rather than run without the layer it named."""
+ b = str(backend or "").lower()
+ return all(bool(e.get("environments", True)) for e in _BASE_CATALOG.values() if e.get("backend") == b)
+
# The per-harness URL (/{hid}/v1/*) accepts every base id the catalog declares, plus stored chrn
# ids — DERIVED, so adding a base to _BASE_CATALOG routes its public URL with no second edit.
_HID_PREFIX_RE = re.compile(
@@ -19546,6 +19693,10 @@ async def list_bases(request: Request) -> dict:
if b.get("skills", True) else []),
"builtinSkillsEnumerable": False,
"takesSkills": bool(b.get("skills", True)),
+ # False for a base whose runtime is remote (qoder): an environment is mounted on this
+ # box only, and a turn that names one is refused (_backend_takes_environments), so the
+ # console offers none rather than a choice every Task would then fail on
+ "takesEnvironments": bool(b.get("environments", True)),
})
# The limits a turn gets when neither the request nor the harness sets one, so the console can
# show the number that will apply rather than a placeholder of its own.
diff --git a/gateway/tests/test_instruction_file_label.py b/gateway/tests/test_instruction_file_label.py
index 5659a9a7..0bb27e3d 100644
--- a/gateway/tests/test_instruction_file_label.py
+++ b/gateway/tests/test_instruction_file_label.py
@@ -25,9 +25,9 @@ UI = pathlib.Path(__file__).resolve().parents[2] / "ui" / "src"
HARNESS_TS = UI / "lib" / "harness.ts"
SETTINGS_TSX = UI / "components" / "HarnessSettings.tsx"
-# The one base that reads no workspace: its instructions travel in the job, so there is no file to
-# name and the page says so instead of inventing one.
-NO_FILE = {"systemone"}
+# The bases that read no workspace file: systemone's instructions travel in the job, qoder's with the
+# hosted session it drives, so there is no file to name and the page says so instead of inventing one.
+NO_FILE = {"systemone", "qoder"}
def _label_map() -> dict:
diff --git a/gateway/tests/test_qoder_catalog.py b/gateway/tests/test_qoder_catalog.py
new file mode 100644
index 00000000..a64220a0
--- /dev/null
+++ b/gateway/tests/test_qoder_catalog.py
@@ -0,0 +1,155 @@
+"""The qoder base: a remote runtime, and what the catalog says about it is what the runner does.
+
+Qoder Cloud Agent runs the agent loop in Qoder's cloud; the runner's turn process is an HTTP client
+to it (runner/qoder_driver.py). What these pin:
+
+ the tool list is Qoder's own names and EQUALS the runner's whitelist, so a toggle the console
+ shows always withholds a tool the Agent was actually offered; enforcement is `hard`
+ the base takes skills (published to Qoder) and NOT environments (mounted on this box only)
+ one provider drives it, `qoder`, its own; no aggregator, no custom endpoint, no harnessrouter row
+ the model ids are Qoder's, in its vendor table and in no other base's picker
+ the connection is not brokered: owner trust runs it, broker trust refuses it with the reason
+ a turn's `charge` (a remote runtime's bill in its own unit) rides the result into the response's
+ metadata and the turn record, beside — never inside — the token usage
+ a session delete hands the runner the qoder connection so the remote objects go too
+"""
+import asyncio
+import os
+import pathlib
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as gw # noqa: E402
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "runner"))
+import server as rs # noqa: E402
+
+BASE = gw._BASE_CATALOG["qoder"]
+
+
+def test_the_tool_list_is_the_runners_whitelist_and_the_enforcement_is_hard():
+ assert BASE["backend"] == "qoder" and BASE["status"] == "ready"
+ assert tuple(sorted(n for n, _ in BASE["tools"])) == tuple(sorted(rs.QODER_TOOLS))
+ assert BASE["tool_enforcement"] == "hard"
+ assert "DeliverArtifacts" in BASE["system_prompt"]
+
+
+def test_the_base_takes_skills_and_not_environments():
+ assert gw._base_takes_skills("qoder") is True
+ assert BASE["environments"] is False and BASE["remote"] is True
+ assert gw._backend_takes_environments("qoder") is False
+ for b in ("claude", "codex", "systemone", "goose"):
+ assert gw._backend_takes_environments(b) is True
+ assert gw._backend_takes_environments("") is True
+
+
+def test_the_console_is_told_the_base_takes_no_environment(monkeypatch):
+ """The harness settings page offered every environment on a qoder harness, and a Task on a
+ harness that named one was then refused, every time. /v1/bases says it the way it says
+ takesSkills, and the page offers none."""
+ async def org_member(_request):
+ return "local", "owner"
+
+ async def servable(_org, _backend):
+ return set()
+
+ monkeypatch.setattr(gw, "_pub_org_member", org_member)
+ monkeypatch.setattr(gw, "_servable_models", servable)
+ bases = {b["id"]: b for b in asyncio.run(gw.list_bases(None))["bases"]}
+ assert bases["qoder"]["takesEnvironments"] is False
+ assert all(b["takesEnvironments"] is True for k, b in bases.items() if k != "qoder")
+
+
+def test_one_provider_its_own_and_nothing_else_drives_it():
+ wired = {p for (p, b) in gw._INTEGRATION_WIRING if b == "qoder"}
+ assert wired == {"qoder"} and gw._INTEGRATION_WIRING[("qoder", "qoder")] == "qoder"
+ assert {b for (p, b) in gw._INTEGRATION_WIRING if p == "qoder"} == {"qoder"}
+ assert not any("qoder" in s for s in gw._CUSTOM_FORMAT_BACKENDS.values())
+ prov = gw._PROVIDER_CATALOG["qoder"]
+ assert prov["base_url"] == "https://api.qoder.com/api/v1/cloud" and prov["fields"] == [] and prov["secret"] == "api_key"
+ assert gw._PROVIDER_BASE["qoder"] == prov["base_url"] == rs.QODER_DEFAULT_BASE
+ assert gw._provider_base_url("qoder", prov["base_url"]) == prov["base_url"] # no /v1 of its own
+
+
+def test_the_model_ids_are_qoders_and_in_no_other_picker():
+ cat = gw._MODEL_CATALOG["qoder"]
+ assert cat["default"] in cat["models"] and set(cat["models"]) <= set(gw._VENDOR_MODELS["qoder"])
+ for backend, entry in gw._MODEL_CATALOG.items():
+ if backend != "qoder":
+ assert not set(entry["models"]) & set(gw._VENDOR_MODELS["qoder"]), backend
+ for vendor, table in gw._VENDOR_MODELS.items():
+ if vendor != "qoder":
+ assert not set(table) & set(gw._VENDOR_MODELS["qoder"]), vendor
+ assert gw._route_backend(None, "qoder") == "qoder"
+ assert gw._backend_of_harness({"base": "qoder"}) == "qoder"
+
+
+def test_the_connection_is_owner_trust_only(monkeypatch):
+ conn = {"name": "integration:q", "backend": "qoder", "provider": "qoder", "api_key": "pat", "base_url": gw._PROVIDER_BASE["qoder"]}
+ monkeypatch.setattr(gw, "SANDBOX_TRUST", "owner")
+ auth = gw._auth_from_conn(conn, "sess")
+ assert auth["api_key"] == "pat" and auth["base_url"] == gw._PROVIDER_BASE["qoder"]
+ monkeypatch.setattr(gw, "SANDBOX_TRUST", "broker")
+ assert "qoder" in gw._NATIVE_ONLY_BACKENDS and "qoder" not in gw._BROKERABLE_PROVIDERS
+ assert gw._auth_from_conn(conn, "sess") is None
+
+
+def test_the_charge_rides_the_result_into_the_response_and_the_record():
+ charge = {"amount": 2.0, "unit": "qoder_credits", "basis": "snapshot"}
+ kinds = gw._blocks_from_canonical({"type": "result", "subtype": "success", "result": "done",
+ "usage": {}, "charge": charge, "_ts": 1.0})
+ res = [p for k, p in kinds if k == "result"][0]
+ assert res["charge"] == charge and res["usage"] == {}
+ tr = gw._RespTranslator("resp_x", "ultimate", None, True, 1.0, sid="sess_x")
+ tr._handle("result", res)
+ assert tr.charge == charge and tr.usage is None # never folded into the tokens
+ obj = tr._response_obj("completed")
+ assert obj["metadata"]["charge"] == charge and obj["usage"] is None
+ # a backend with tokens and no charge is as before
+ tr2 = gw._RespTranslator("resp_y", "m", None, True, 1.0, sid="sess_y")
+ tr2._handle("result", {"text": "x", "usage": {"input_tokens": 3, "output_tokens": 4}, "is_error": False, "model": ""})
+ assert tr2.charge is None and "charge" not in tr2._response_obj("completed")["metadata"]
+
+
+def test_a_session_delete_carries_the_qoder_connection_to_the_runner(monkeypatch):
+ monkeypatch.setattr(gw, "SANDBOX_TRUST", "owner")
+
+ async def integs():
+ return [{"name": "qoder-main", "provider": "qoder", "config": {"api_key": "pat", "base_url": ""}},
+ {"name": "openai", "provider": "openai", "config": {"api_key": "sk"}}]
+
+ monkeypatch.setattr(gw, "_integrations_doc", integs)
+ body = asyncio.run(gw._remote_delete_body("sess_1", {"backend": "qoder"}))
+ assert body["backend"] == "qoder" and body["auth"]["api_key"] == "pat"
+ assert body["auth"]["base_url"] == gw._PROVIDER_BASE["qoder"]
+ assert asyncio.run(gw._remote_delete_body("sess_1", {"backend": "claude"})) is None
+ assert asyncio.run(gw._remote_delete_body("sess_1", None)) is None
+ # broker trust: the connection is not brokered, so nothing goes, and the runner will say what was left
+ monkeypatch.setattr(gw, "SANDBOX_TRUST", "broker")
+ assert asyncio.run(gw._remote_delete_body("sess_1", {"backend": "qoder"})) == {"backend": "qoder", "auth": None}
+
+ async def none():
+ return []
+
+ monkeypatch.setattr(gw, "_integrations_doc", none)
+ assert asyncio.run(gw._remote_delete_body("sess_1", {"backend": "qoder"})) == {"backend": "qoder"}
+
+
+def test_a_session_delete_uses_the_qoder_account_its_turns_ran_on(monkeypatch):
+ """With two Qoder connections, the session's objects live in the account its turns used
+ (last_connection); the other account's key would be refused there and leave them billing."""
+ monkeypatch.setattr(gw, "SANDBOX_TRUST", "owner")
+
+ async def integs():
+ return [{"name": "qoder-a", "provider": "qoder", "config": {"api_key": "pat-a"}},
+ {"name": "qoder-b", "provider": "qoder", "config": {"api_key": "pat-b"}}]
+
+ monkeypatch.setattr(gw, "_integrations_doc", integs)
+ v = {"backend": "qoder", "last_connection": "integration:qoder-b"}
+ assert asyncio.run(gw._remote_delete_body("sess_1", v))["auth"]["api_key"] == "pat-b"
+ # the session's own connection is gone and two others remain: nothing is guessed
+ v = {"backend": "qoder", "last_connection": "integration:qoder-old"}
+ assert asyncio.run(gw._remote_delete_body("sess_1", v)) == {"backend": "qoder"}
+ # no record of which ran, two candidates: nothing is guessed either
+ assert asyncio.run(gw._remote_delete_body("sess_1", {"backend": "qoder"})) == {"backend": "qoder"}
diff --git a/runner/qoder_driver.py b/runner/qoder_driver.py
new file mode 100644
index 00000000..bdee3f15
--- /dev/null
+++ b/runner/qoder_driver.py
@@ -0,0 +1,1239 @@
+"""One Qoder Cloud Agent 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's
+normaliser (_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.
+
+The credential never enters this process. The job carries the runner's loopback relay as the
+base and a placeholder bearer; the relay holds the PAT and forwards this route verbatim (no body
+rewrites, 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.
+
+Everything the turn creates at Qoder — the Environment, the Agent, the Session, uploaded input
+files, delivered artifact files, a Vault for MCP bearers, Skill resources — is recorded in
+<cwd>/.harness/qoder/state.json, which travels in the checkpoint. A follow-up turn finds the
+session to continue there; `DELETE /workspace` runs this file in purge mode so a delete reaches
+Qoder (nothing the session created outlives it).
+
+Cancellation: the runner sends SIGTERM and waits a bounded grace before its SIGKILL (a remote
+backend, BACKENDS[...]["remote"]). The handler raises out of whatever read is in flight, the
+turn posts `POST /sessions/{id}/cancel`, says on stdout whether that was accepted, and exits.
+Without that call the remote turn would keep running and billing after the local process died.
+"""
+from __future__ import annotations
+
+import hashlib
+import http.client
+import json
+import mimetypes
+import os
+import pathlib
+import re
+import shutil
+import signal
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import uuid
+
+STATE_REL = os.path.join(".harness", "qoder", "state.json")
+
+# The built-in tools of agent_toolset_20260401 (agents/schemas.md, "内置工具名"), the names
+# `tools_disabled` matches exactly. The gateway's catalog is pinned equal to this tuple.
+TOOLS = ("Bash", "DeliverArtifacts", "Edit", "Glob", "Grep", "ImageGen", "ImageSearch", "Read",
+ "WebFetch", "WebSearch", "Write")
+TOOLSET = "agent_toolset_20260401"
+EFFORTS = ("none", "low", "medium", "high", "xhigh", "max")
+
+# Files the upload endpoint accepts (files/schemas.md): text MIME types, and this extension list.
+# Anything else is refused by Qoder with a 400, so it is refused here first, naming the file.
+UPLOAD_MIME_PREFIX = "text/"
+UPLOAD_MIME = {"application/json", "application/xml", "application/javascript", "application/x-yaml",
+ "application/x-toml"}
+UPLOAD_EXT = {".txt", ".md", ".csv", ".json", ".xml", ".yaml", ".yml", ".toml", ".ini", ".conf", ".cfg",
+ ".env", ".log", ".html", ".htm", ".css", ".scss", ".less", ".js", ".jsx", ".ts", ".tsx",
+ ".vue", ".svelte", ".py", ".go", ".rs", ".java", ".kt", ".scala", ".c", ".cpp", ".cc", ".h",
+ ".hpp", ".rb", ".php", ".swift", ".r", ".lua", ".pl", ".sh", ".bash", ".zsh", ".fish",
+ ".ps1", ".sql", ".graphql", ".gql", ".proto", ".dockerfile", ".makefile", ".gitignore",
+ ".editorconfig", ".eslintrc", ".prettierrc", ".tex", ".rst", ".adoc", ".org", ".svg"}
+UPLOAD_BARE = {"dockerfile", "makefile", "gemfile", "rakefile", "procfile", "vagrantfile", "justfile",
+ "brewfile"}
+UPLOAD_MAX_BYTES = 5 * 1024 * 1024
+MOUNT_ROOT = "/mnt/session/uploads"
+# The largest delivered artifact landed in the workspace. A download goes to disk as it arrives (never
+# held whole in memory) and is cut off past this.
+ARTIFACT_MAX_BYTES = int(os.environ.get("HR_QODER_ARTIFACT_MAX_BYTES") or 2 * 1024 ** 3)
+
+# How long one call may take, and how long a stream read may go without a byte. The stream
+# carries a heartbeat about every 15 s, so a read that waits this long is a dead connection, and
+# the turn reconnects from the last event id rather than hanging on it.
+CALL_TIMEOUT_S = 120.0
+STREAM_READ_TIMEOUT_S = 90.0
+STREAM_RECONNECTS = 20
+
+_SKILL_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
+
+
+def _emit(method: str, payload) -> None:
+ sys.stdout.write(json.dumps({"m": method, "p": payload}, default=str) + "\n")
+ sys.stdout.flush()
+
+
+class Cancelled(BaseException):
+ """The runner asked the turn to stop (SIGTERM). A BaseException so no `except Exception`
+ on the way out swallows it."""
+
+
+class ApiError(Exception):
+ 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."""
+
+ 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
+ try:
+ 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
+
+
+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)
+
+
+# ── state ────────────────────────────────────────────────────────────────────────────────────────
+def state_path(cwd: str) -> pathlib.Path:
+ return pathlib.Path(cwd) / STATE_REL
+
+
+def load_state(cwd: str) -> dict:
+ try:
+ doc = json.loads(state_path(cwd).read_text())
+ return doc if isinstance(doc, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def save_state(cwd: str, st: dict) -> None:
+ p = state_path(cwd)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ tmp = p.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(st, indent=1, sort_keys=True))
+ os.replace(tmp, p)
+
+
+def _sha(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+# ── artifacts ────────────────────────────────────────────────────────────────────────────────────
+def artifact_name(original: str) -> tuple[str, str]:
+ """(the plain name to write under the workspace root, "") or ("", why it was refused).
+
+ `original_filename` comes from the remote run, and in the end from the model: a name is
+ input. Only a plain file name lands: no path separator of either kind, no `..`, nothing that
+ opens a dot directory the runner owns, no control characters, and nothing that is only dots
+ or whitespace."""
+ name = (original or "").strip()
+ if not name:
+ return "", "empty artifact name"
+ if "/" in name or "\\" in name or "\0" in name:
+ return "", f"artifact name carries a path: {original!r}"
+ if name in (".", "..") or name.startswith(".."):
+ return "", f"artifact name is a traversal: {original!r}"
+ if any(ord(c) < 32 for c in name):
+ return "", f"artifact name carries control characters: {original!r}"
+ if name.startswith("."):
+ # .harness, .git and the CLI homes live here, and a hidden file is never a deliverable
+ return "", f"artifact name opens a dot directory or hidden file: {original!r}"
+ if len(name.encode("utf-8")) > 240:
+ # a file name is at most 255 BYTES; cut by bytes, keeping the extension and room for " (n)"
+ stem, ext = os.path.splitext(name)
+ ext = ext if len(ext.encode("utf-8")) <= 16 else ""
+ name = stem.encode("utf-8")[:240 - len(ext.encode("utf-8"))].decode("utf-8", "ignore").rstrip() + ext
+ return name, ""
+
+
+def land_artifact(cwd: str, name: str, data: bytes | pathlib.Path) -> tuple[str, str]:
+ """Write `data` as `name` under the workspace root; (the relative path written, a note).
+
+ An existing path is never overwritten and a symlink is never followed: a second artifact of
+ the same name in one session (or a file the agent of an earlier turn left) lands beside it as
+ `name (2).ext`, and the note says so. The write is to a temporary name and renamed into place
+ with O_EXCL semantics, so a race with the agent's own files cannot replace one."""
+ root = pathlib.Path(cwd)
+ stem, ext = os.path.splitext(name)
+ candidate, n, note = name, 1, ""
+ while True:
+ target = root / candidate
+ if target.is_symlink():
+ n += 1
+ candidate = f"{stem} ({n}){ext}"
+ note = f"{name!r} was a symlink; written as {candidate!r}"
+ continue
+ try:
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
+ except FileExistsError:
+ n += 1
+ candidate = f"{stem} ({n}){ext}"
+ note = f"{name!r} already existed; written as {candidate!r}"
+ continue
+ with os.fdopen(fd, "wb") as f:
+ if isinstance(data, (bytes, bytearray)):
+ f.write(data)
+ else: # a download already on disk (see Turn.artifact)
+ with open(data, "rb") as src:
+ shutil.copyfileobj(src, f, 1 << 20)
+ return candidate, note
+
+
+# ── the Agent definition ────────────────────────────────────────────────────────────────────────
+def tools_config(disabled: list[str]) -> list[dict]:
+ """The toolset entry: the enabled built-ins as a strict whitelist, each `always_allow` so no
+ call ever pauses for a confirmation nobody is here to give, and the disabled ones named in
+ `disallowed_tools` as well. Both lists, because an EMPTY `enabled_tools` means "the default
+ set" to Qoder, not "nothing"."""
+ off = {t for t in (disabled or []) if t in TOOLS}
+ on = [t for t in TOOLS if t not in off]
+ entry: dict = {"type": TOOLSET,
+ "configs": [{"name": t, "enabled": True, "permission_policy": {"type": "always_allow"}}
+ for t in on]}
+ if on:
+ entry["enabled_tools"] = on
+ if off:
+ entry["disallowed_tools"] = sorted(off)
+ entry["configs"] += [{"name": t, "enabled": False} for t in sorted(off)]
+ return [entry]
+
+
+def mcp_config(servers: list[dict]) -> tuple[list[dict], list[dict], list[dict]]:
+ """(mcp_servers for the Agent, the servers whose bearer needs a Vault credential, the ones this
+ backend cannot offer). Only a Streamable HTTP URL reaches Qoder; a plugin's stdio server is a
+ process on this box, which Qoder's cloud cannot dial. A header other than a bearer has no
+ home in a Vault credential either."""
+ out, creds, dropped = [], [], []
+ seen: set[str] = set()
+ for i, s in enumerate(servers or []):
+ if not isinstance(s, dict):
+ continue
+ raw_name = str(s.get("name") or s.get("id") or f"mcp{i}")
+ name = re.sub(r"[^A-Za-z0-9_-]+", "-", raw_name).strip("-") or f"mcp{i}"
+ url = str(s.get("url") or "").strip()
+ if not url:
+ dropped.append({"name": raw_name, "reason": "stdio server: a process on the runner's box"})
+ continue
+ if name in seen:
+ name = f"{name}-{i}"
+ seen.add(name)
+ out.append({"name": name, "type": "url", "url": url})
+ auth = s.get("auth")
+ hdrs = s.get("headers") if isinstance(s.get("headers"), dict) else {}
+ bearer = ""
+ if auth:
+ bearer = str(auth)
+ for k, v in hdrs.items():
+ if str(k).lower() == "authorization" and v:
+ bearer = str(v)
+ elif v:
+ dropped.append({"name": raw_name, "reason": f"header {k} cannot travel: Qoder takes a bearer in a Vault only"})
+ if bearer:
+ if bearer.lower().startswith("bearer "):
+ bearer = bearer[7:].strip()
+ creds.append({"url": url, "token": bearer})
+ return out, creds, dropped
+
+
+def agent_body(job: dict, skills: list[dict], mcp_servers: list[dict]) -> dict:
+ model: str | dict = str(job.get("model") or "ultimate")
+ effort = str(job.get("effort") or "").strip().lower()
+ if effort and effort in EFFORTS:
+ model = {"id": model, "effort": effort}
+ name = f"harnessrouter {pathlib.Path(str(job.get('cwd') or '')).name or 'session'}"[:256]
+ return {"name": name, "model": model,
+ "description": "Created by HarnessRouter for one session; deleted with it.",
+ "system": system_prompt(job),
+ "tools": tools_config(job.get("tools_disabled") or []),
+ "mcp_servers": mcp_servers,
+ "skills": [{"type": "custom", "skill_id": s["id"], "version": s["version"]} for s in skills],
+ "metadata": {"harnessrouter": "1"}}
+
+
+def system_prompt(job: dict) -> str:
+ """The harness's instructions, then the contract this runtime has instead of a workspace: a
+ file reaches the person only when it is delivered. A file written in Qoder's sandbox and never
+ passed to DeliverArtifacts does not exist to the user, and the artifact scenario measures it."""
+ base = str(job.get("agent_doc") or "").strip()
+ lines = ["## Delivering files", "",
+ "You run in a remote sandbox. The user sees NO file you write unless you deliver it: when "
+ "a task produces a deliverable (a document, a deck, code, an export), save it and then call "
+ "DeliverArtifacts with its path. Deliver each file once, by a plain file name; an "
+ "undelivered file is lost to the user.",
+ "", f"Files the user attaches are mounted read-only under `{MOUNT_ROOT}/`; each message "
+ "names the ones it brought."]
+ block = "\n".join(lines)
+ return (base + "\n\n" + block) if base else block
+
+
+def config_hash(body: dict) -> str:
+ return _sha(json.dumps(body, sort_keys=True).encode())
+
+
+# ── skills ───────────────────────────────────────────────────────────────────────────────────────
+def skill_tree(folder: str) -> tuple[str, list[tuple[str, bytes]], str]:
+ """(the frontmatter name, [(relative path, bytes)], "") for a skill folder, or ("", [], why).
+ Qoder requires the package's single top-level directory to equal SKILL.md's `name`, which
+ must match ^[a-z0-9][a-z0-9_-]*$ — a bundle whose name does not cannot be published."""
+ root = pathlib.Path(folder)
+ manifest = root / "SKILL.md"
+ if not manifest.is_file():
+ return "", [], f"{root.name}: no SKILL.md"
+ name = ""
+ try:
+ head = manifest.read_text(encoding="utf-8", errors="replace")
+ except OSError as e:
+ return "", [], f"{root.name}: {e}"
+ if head.startswith("---"):
+ for ln in head.split("\n")[1:60]:
+ if ln.strip() == "---":
+ break
+ if ln.startswith("name:"):
+ name = ln.split(":", 1)[1].strip().strip("'\"")
+ if not name or not _SKILL_NAME_RE.match(name) or len(name) > 64:
+ return "", [], f"{root.name}: SKILL.md name {name!r} is not a Qoder skill name"
+ files: list[tuple[str, bytes]] = []
+ total = 0
+ for p in sorted(root.rglob("*")):
+ if p.is_file() and not p.is_symlink():
+ data = p.read_bytes()
+ total += len(data)
+ files.append((f"{name}/{p.relative_to(root).as_posix()}", data))
+ if total > 50 * 1024 * 1024:
+ return "", [], f"{root.name}: {total} bytes, over the 50 MB package limit"
+ return name, files, ""
+
+
+def publish_skills(api: Api, 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."""
+ known: dict = st.setdefault("skills", {})
+ out: list[dict] = []
+ for s in skills or []:
+ folder = str((s or {}).get("dir") or "")
+ name, files, why = skill_tree(folder)
+ if why:
+ notes.append(f"skill not published: {why}")
+ continue
+ digest = _sha(b"".join(_sha(d).encode() + p.encode() for p, d in files))
+ rec = known.get(name) or {}
+ 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)
+ if rec.get("id"):
+ ver = api.request("POST", f"/skills/{rec['id']}/versions", data=body,
+ headers={"content-type": ctype})
+ version = str((ver or {}).get("version") or "")
+ else:
+ created = api.request("POST", "/skills", data=body, headers={"content-type": ctype})
+ rec = {"id": str((created or {}).get("id") or "")}
+ version = str((created or {}).get("latest_version") or "")
+ if not rec.get("id") or not version:
+ notes.append(f"skill {name}: Qoder returned no id/version")
+ continue
+ rec.update(sha=digest, version=version)
+ known[name] = rec
+ out.append({"id": rec["id"], "version": version})
+ return out
+
+
+# ── input files ──────────────────────────────────────────────────────────────────────────────────
+def upload_ok(rel: str, size: int) -> str:
+ """"" when the upload endpoint takes this file, else why not."""
+ base = os.path.basename(rel)
+ ext = os.path.splitext(base)[1].lower()
+ mime = (mimetypes.guess_type(base)[0] or "").lower()
+ if size > UPLOAD_MAX_BYTES:
+ return f"{rel}: {size} bytes, over Qoder's 5 MB upload limit"
+ if ext in UPLOAD_EXT or base.lower() in UPLOAD_BARE or mime.startswith(UPLOAD_MIME_PREFIX) or mime in UPLOAD_MIME:
+ return ""
+ 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]:
+ """Upload the runner's staged input files once each (by content hash); → the file resources
+ to mount, with the mount path the model is told."""
+ known: dict = st.setdefault("files", {})
+ out: list[dict] = []
+ for rel in rels or []:
+ p = pathlib.Path(cwd) / rel
+ try:
+ data = p.read_bytes()
+ except OSError:
+ continue
+ 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})
+ rec = {"id": str((created or {}).get("id") or ""), "sha": digest, "mounted": []}
+ known[rel] = rec
+ mount = f"{MOUNT_ROOT}/{rel.lstrip('/')}"
+ out.append({"type": "file", "file_id": rec["id"], "mount_path": mount, "_rel": rel})
+ return out
+
+
+# ── the turn ─────────────────────────────────────────────────────────────────────────────────────
+class Turn:
+ def __init__(self, job: dict):
+ self.job = job
+ self.cwd = str(job.get("cwd") or os.getcwd())
+ self.api = Api(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 = ""
+ self.final = ""
+ self.streamed: dict[str, str] = {} # delta text already emitted, by event id
+ self.declared: list[dict] = [] # artifacts the stream announced
+ self.landed: list[dict] = []
+ self.artifact_failures: list[str] = []
+ self.usage: dict | None = None
+ self.error: dict | None = None
+ self.stop_reason: dict | None = None
+ self.terminated = False
+ self.last_event_id = ""
+ self.pending_confirm: list[str] = []
+ self.deny_ids: set[str] = set() # pending confirmations of tools the harness disabled
+ self.replaying: dict[str, int] = {} # a reconnect is replaying deltas of this message: bytes seen
+ self.disabled = {str(t) for t in (job.get("tools_disabled") or [])}
+ self.mounts: list[str] = [] # where this turn's attached files are mounted
+ self.written: list[str] = [] # paths the agent wrote or edited this turn
+ self.delivered_paths: set[str] = set() # paths it passed to DeliverArtifacts
+ self.nudging = False # the delivery round (deliver_written) is running
+
+ # ── remote objects ──
+ def ensure_environment(self) -> str:
+ env_id = str(self.st.get("environment_id") or "")
+ if env_id:
+ return env_id
+ created = self.api.request("POST", "/environments", {
+ "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"}})
+ env_id = str((created or {}).get("id") or "")
+ if not env_id:
+ raise ApiError(0, "api_error", "environment create returned no id", "/environments")
+ self.st["environment_id"] = env_id
+ save_state(self.cwd, self.st)
+ return env_id
+
+ def ensure_vault(self, creds: list[dict]) -> list[str]:
+ """The session's Vault, holding one active static_bearer credential per MCP server URL with
+ THIS turn's token. A server URL is unique among a vault's active credentials, so a token that
+ changed since the last turn (a rotated key, or the per-turn credential the gateway mints for
+ a server it hosts itself, which expires) archives the old credential and creates the new one:
+ a vault that kept the first turn's token fails that server on every later turn. Only a hash
+ of each token is kept in the state, never the token."""
+ if not creds:
+ 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"}})
+ vid = str((created or {}).get("id") or "")
+ if not vid:
+ raise ApiError(0, "api_error", "vault create returned no id", "/vaults")
+ self.st["vault_id"] = vid
+ save_state(self.cwd, self.st)
+ have: dict = self.st.setdefault("vault_creds", {}) # url -> {"id", "sha"}
+ for c in creds:
+ sha = _sha(c["token"].encode())
+ cur = have.get(c["url"]) or {}
+ if cur.get("id") and cur.get("sha") == sha:
+ continue
+ if cur.get("id"):
+ self._archive_credential(vid, cur["id"])
+ have[c["url"]] = {"id": self._create_credential(vid, c), "sha": sha}
+ save_state(self.cwd, self.st)
+ return [vid]
+
+ def _create_credential(self, vid: str, c: dict) -> str:
+ body = {"auth": {"type": "static_bearer", "mcp_server_url": c["url"], "token": c["token"]}}
+ try:
+ doc = self.api.request("POST", f"/vaults/{vid}/credentials", body)
+ except ApiError as e:
+ if e.status != 409:
+ raise
+ # an active credential for this URL that the state does not know: archived, then made anew
+ for old in self._active_credentials(vid, c["url"]):
+ self._archive_credential(vid, old)
+ doc = self.api.request("POST", f"/vaults/{vid}/credentials", body)
+ 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 cid
+
+ def _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 []:
+ if not isinstance(x, dict) or not x.get("id") or x.get("archived_at"):
+ continue
+ if url in (x.get("mcp_server_url"), (x.get("auth") or {}).get("mcp_server_url")):
+ out.append(str(x["id"]))
+ return out
+
+ def _archive_credential(self, vid: str, cid: str) -> None:
+ try:
+ self.api.request("POST", f"/vaults/{vid}/credentials/{cid}/archive")
+ except ApiError as e:
+ if e.status not in (404, 409): # gone, or archived already
+ raise
+
+ def ensure_agent(self, body: dict) -> tuple[str, int, bool]:
+ """(agent id, version, whether the configuration changed this turn)."""
+ digest = config_hash(body)
+ aid = str(self.st.get("agent_id") or "")
+ if aid and self.st.get("agent_hash") == digest and self.st.get("agent_version"):
+ return aid, int(self.st["agent_version"]), False
+ if aid:
+ current = self.api.request("GET", f"/agents/{aid}")
+ version = int((current or {}).get("version") or 1)
+ updated = self.api.request("POST", f"/agents/{aid}", {**body, "version": version})
+ else:
+ updated = self.api.request("POST", "/agents", body)
+ aid = str((updated or {}).get("id") or "")
+ version = int((updated or {}).get("version") or 1)
+ if not aid:
+ raise ApiError(0, "api_error", "agent create returned no id", "/agents")
+ self.st.update(agent_id=aid, agent_version=version, agent_hash=digest)
+ save_state(self.cwd, self.st)
+ return aid, version, True
+
+ def find_session(self, resume: str) -> tuple[str, bool]:
+ """(the session to continue, False) or ("", lost): the id the caller named, when the state
+ knows it and Qoder still has it in a state that takes a message."""
+ if not resume:
+ return "", False
+ if resume != str(self.st.get("session_id") or ""):
+ return "", True
+ try:
+ doc = self.api.request("GET", f"/sessions/{resume}")
+ except ApiError as e:
+ if e.status == 404:
+ return "", True
+ raise
+ if not isinstance(doc, dict) or doc.get("archived_at") or doc.get("status") == "terminated":
+ return "", True
+ if doc.get("status") in ("running", "rescheduling"):
+ raise ApiError(409, "invalid_request_error",
+ "the Qoder session is still processing an earlier turn; cancel it or wait",
+ f"/sessions/{resume}")
+ return resume, False
+
+ def create_session(self, aid: str, version: int, env_id: str, vault_ids: list[str],
+ resources: list[dict]) -> str:
+ body: dict = {"agent": {"id": aid, "type": "agent", "version": version},
+ "environment_id": env_id,
+ "title": f"HarnessRouter {pathlib.Path(self.cwd).name}"[:200],
+ "metadata": {"harnessrouter": "1"}}
+ if vault_ids:
+ body["vault_ids"] = vault_ids
+ if 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)
+ sid = str((doc or {}).get("id") or "")
+ if not sid:
+ raise ApiError(0, "api_error", "session create returned no id", "/sessions")
+ self.st["session_id"] = sid
+ self.st.setdefault("sessions", [])
+ if sid not in self.st["sessions"]:
+ self.st["sessions"].append(sid)
+ for r in resources:
+ self.st["files"][r["_rel"]].setdefault("mounted", []).append(sid)
+ save_state(self.cwd, self.st)
+ return sid
+
+ def mount_resources(self, sid: str, resources: list[dict]) -> None:
+ for r in resources:
+ rec = self.st["files"][r["_rel"]]
+ if sid in (rec.get("mounted") or []):
+ continue
+ try:
+ self.api.request("POST", f"/sessions/{sid}/resources",
+ {"type": "file", "file_id": r["file_id"], "mount_path": r["mount_path"]})
+ except ApiError as e:
+ if e.status != 409:
+ raise
+ rec.setdefault("mounted", []).append(sid)
+ 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
+ if not isinstance(doc, dict):
+ return False
+ t = str(doc.get("type") or ev or "")
+ if t == "heartbeat":
+ return False
+ if eid and t not in ("event_start", "event_delta"):
+ self.last_event_id = eid
+ if not started[0]:
+ # events before this turn's message are history, not this turn
+ if (t == "user.message" and doc.get("id") == posted_id) or t == "session.status_running":
+ started[0] = True
+ return False
+ if t == "event_start":
+ e = doc.get("event") or {}
+ if e.get("type") == "agent.message" and e.get("id"):
+ mid = str(e["id"])
+ if mid in self.streamed:
+ # a reconnect replays the message's start and its retained deltas: what was
+ # already written is not written twice
+ self.replaying[mid] = 0
+ else:
+ self.streamed[mid] = ""
+ return False
+ if t == "event_delta":
+ if self.nudging:
+ return False # the delivery round's own words are not the turn's answer
+ d = doc.get("delta") or {}
+ c = d.get("content") or {}
+ txt = str(c.get("text") or "") if c.get("type") == "text" else ""
+ mid = str(doc.get("event_id") or "")
+ if not txt or not mid:
+ return False
+ if mid in self.replaying:
+ pos, have = self.replaying[mid], len(self.streamed.get(mid, ""))
+ if pos + len(txt) <= have:
+ self.replaying[mid] = pos + len(txt)
+ return False
+ txt = txt[max(0, have - pos):]
+ del self.replaying[mid]
+ self.streamed[mid] = self.streamed.get(mid, "") + txt
+ _emit("text", {"text": txt})
+ return False
+ if t == "agent.message":
+ full = "".join(str(c.get("text") or "") for c in (doc.get("content") or [])
+ if isinstance(c, dict) and c.get("type") == "text")
+ seen = self.streamed.pop(str(doc.get("id") or ""), "")
+ if self.nudging:
+ return False
+ if full:
+ self.final = full
+ if full and full != seen:
+ if not seen:
+ _emit("text", {"text": full})
+ elif full.startswith(seen):
+ _emit("text", {"text": full[len(seen):]})
+ return False
+ if t == "agent.thinking":
+ return False # the content is not public; the event is only a marker
+ if t in ("agent.tool_use", "agent.mcp_tool_use", "agent.custom_tool_use"):
+ name = str(doc.get("name") or "tool")
+ if t == "agent.mcp_tool_use" and doc.get("mcp_server_name"):
+ name = f"mcp__{doc['mcp_server_name']}__{name}"
+ inp = doc.get("input") if isinstance(doc.get("input"), dict) else {}
+ _emit("tool_use", {"id": str(doc.get("id") or ""), "name": name, "input": inp,
+ "permission": doc.get("evaluated_permission")})
+ if t == "agent.tool_use" and name in ("Write", "Edit") and inp.get("file_path"):
+ if str(inp["file_path"]) not in self.written:
+ self.written.append(str(inp["file_path"]))
+ if t == "agent.tool_use" and name == "DeliverArtifacts":
+ for f in inp.get("files") or []:
+ if isinstance(f, dict) and f.get("path"):
+ self.delivered_paths.add(str(f["path"]))
+ if doc.get("evaluated_permission") == "ask" and doc.get("id"):
+ self.pending_confirm.append(str(doc["id"]))
+ bare = str(doc.get("name") or "")
+ if name in self.disabled or bare in self.disabled:
+ self.deny_ids.add(str(doc["id"]))
+ return False
+ if t in ("agent.tool_result", "agent.mcp_tool_result"):
+ text = "\n".join(str(c.get("text") or "") for c in (doc.get("content") or [])
+ if isinstance(c, dict) and c.get("type") == "text")
+ _emit("tool_result", {"tool_use_id": str(doc.get("tool_use_id") or doc.get("mcp_tool_use_id") or ""),
+ "text": text, "is_error": bool(doc.get("is_error"))})
+ return False
+ if t == "agent.artifact_delivered":
+ self.artifact(doc)
+ return False
+ if t == "session.usage":
+ self.usage = {k: doc.get(k) for k in ("model_credits", "sandbox_runtime_credits", "total_credits")}
+ return False
+ if t == "session.error":
+ err = doc.get("error") if isinstance(doc.get("error"), dict) else {}
+ retry = str(((err.get("retry_status") or {}).get("type")) or "")
+ self.error = {"message": str(err.get("message") or "Qoder reported an error"),
+ "type": str(err.get("type") or ""), "retry": retry}
+ _emit("error", self.error)
+ return False
+ if t == "session.status_rescheduled":
+ _emit("notice", {"text": "Qoder is retrying the model request (rescheduling)"})
+ return False
+ if t == "session.status_idle":
+ self.stop_reason = doc.get("stop_reason") if isinstance(doc.get("stop_reason"), dict) else {"type": ""}
+ if self.stop_reason.get("type") == "requires_action":
+ self.confirm(list(self.stop_reason.get("event_ids") or []) or self.pending_confirm)
+ self.pending_confirm = []
+ self.stop_reason = None # the turn goes on; its real stop is still to come
+ return False
+ return True
+ if t in ("session.status_terminated", "session.deleted"):
+ self.terminated = True
+ return True
+ return False
+
+ def confirm(self, event_ids: list[str]) -> None:
+ """Answer every pending tool confirmation: deny a tool the harness disabled, allow the rest.
+ The Agent's permission policy makes this path rare (always_allow on every built-in); an MCP
+ tool whose server-side default asks still gets its answer here instead of parking the
+ session, which never times out on its own."""
+ events = []
+ for eid in event_ids:
+ deny = eid in self.deny_ids
+ ev: dict = {"type": "user.tool_confirmation", "tool_use_id": eid, "result": "deny" if deny else "allow"}
+ if deny:
+ 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})
+
+ def artifact(self, doc: dict) -> None:
+ fid = str(doc.get("file_id") or "")
+ original = str(doc.get("original_filename") or "")
+ size = doc.get("size")
+ rec = {"file_id": fid, "name": original, "size": size}
+ self.declared.append(rec)
+ self.st.setdefault("artifacts", [])
+ if fid and fid not in self.st["artifacts"]:
+ self.st["artifacts"].append(fid)
+ save_state(self.cwd, self.st)
+ name, why = artifact_name(original)
+ if not why and isinstance(size, int) and size > ARTIFACT_MAX_BYTES:
+ why = f"{original}: {size} bytes declared, over the {ARTIFACT_MAX_BYTES}-byte artifact limit"
+ if why:
+ self.artifact_failures.append(why)
+ _emit("artifact", {**rec, "status": "refused", "reason": why})
+ return
+ # The download goes to disk as it arrives, under .harness/ (never a produced file), and is
+ # landed from there; nothing about one artifact (a full disk, a name the filesystem will not
+ # take) is let out of here, where it would read as a dropped stream and lose its reason.
+ part = pathlib.Path(self.cwd) / ".harness" / "qoder" / f"download-{uuid.uuid4().hex}.part"
+ try:
+ got, why = self._download(fid, original, part)
+ if got is not None and isinstance(size, int) and size >= 0 and got != size:
+ why, got = f"{original}: {got} bytes landed, {size} declared", None
+ if got is None:
+ self.artifact_failures.append(why or f"{original}: download failed")
+ _emit("artifact", {**rec, "status": "failed", "reason": why})
+ return
+ try:
+ written, note = land_artifact(self.cwd, name, part)
+ except OSError as e:
+ why = f"{original}: could not be written: {type(e).__name__}: {e}"[:300]
+ self.artifact_failures.append(why)
+ _emit("artifact", {**rec, "status": "failed", "reason": why})
+ return
+ finally:
+ try:
+ part.unlink()
+ except OSError:
+ pass
+ if note:
+ self.notes.append(note)
+ self.landed.append({**rec, "path": written})
+ _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."""
+ 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 travels
+ part.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)
+ return n, ""
+ except ApiError as e:
+ why = f"{original}: {e}"
+ if e.status in (404, 410, 403):
+ break
+ except (urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError) as e:
+ why = f"{original}: download failed: {type(e).__name__}: {e}"[:300]
+ return None, why
+
+ def run_stream(self, posted_id: str) -> None:
+ """Read the session's stream until this turn ends, reconnecting from the last event id on
+ a drop; the message is never sent again.
+
+ The stream is opened AFTER the message is posted, with the message's own event id as the
+ cursor: the server replays from there, so nothing of this turn is missed however long the
+ 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 = 0
+ idle_eofs = 0
+ while True:
+ try:
+ resp = self.api.stream(path, 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
+ attempts += 1
+ if attempts <= STREAM_RECONNECTS:
+ continue
+ raise
+ except (urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError) as e:
+ attempts += 1
+ if 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))
+ continue
+ try:
+ for eid, ev, data in iter_sse(resp):
+ if self.handle(eid, ev, data, posted_id, started):
+ return
+ except (http.client.HTTPException, TimeoutError, OSError) 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
+ finally:
+ try:
+ resp.close()
+ except Exception: # noqa: BLE001
+ pass
+ # 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}")
+ status = str((doc or {}).get("status") or "")
+ if status == "terminated":
+ self.terminated = True
+ return
+ if status == "idle" and started[0]:
+ idle_eofs += 1
+ if idle_eofs >= 2:
+ if (self.stop_reason or {}).get("type") != "requires_action":
+ self.stop_reason = self.stop_reason or {"type": "end_turn"}
+ return
+ attempts += 1
+ if attempts > STREAM_RECONNECTS:
+ raise ApiError(0, "stream", "the event stream ended without a terminal event")
+ time.sleep(min(0.5 * attempts, 5.0))
+
+ 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."""
+ 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}]}]}
+ try:
+ doc = self.api.request("POST", f"/sessions/{self.session_id}/events", body)
+ for e in (doc or {}).get("data") or []:
+ 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 "")
+ try:
+ doc = self.api.request("GET", f"/sessions/{self.session_id}{q}")
+ except ApiError:
+ doc = None
+ 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"})
+ return str(e.get("id") or "")
+ raise ApiError(0, "api_error", "the message could not be delivered", f"/sessions/{self.session_id}/events")
+
+ def undelivered(self) -> list[str]:
+ """Files the agent wrote or edited this turn that never reached the person: not passed to
+ DeliverArtifacts and not among the delivered names. Scratch space, the read-only uploads and
+ dot paths are not deliverables."""
+ names = {str(d.get("name") or "") for d in self.declared}
+ out: list[str] = []
+ for p in self.written:
+ if p in out or p in self.delivered_paths or os.path.basename(p) in names:
+ continue
+ if p.startswith(("/tmp/", MOUNT_ROOT + "/")) or any(s.startswith(".") for s in p.split("/") if s):
+ continue
+ out.append(p)
+ return out
+
+ def deliver_written(self) -> None:
+ """A file the agent wrote and did not deliver is lost to the person: Qoder's sandbox is
+ not this workspace, and DeliverArtifacts is the only way a file comes back. Every local
+ base gets what its turn wrote (the runner collects the workspace), so here a turn that ended
+ normally with such files asks the session, once, to deliver them. Measured 2026-10-10 on
+ 0.33.0-rc.3: `auto` wrote the file the matrix's artifact scenario asked for and answered DONE
+ without delivering it, though the system prompt says to twice. The round's own words are
+ not shown or kept as the answer; what it delivers lands like any artifact."""
+ if self.terminated or (self.stop_reason or {}).get("type") != "end_turn":
+ return
+ missing = self.undelivered()
+ if not missing:
+ return
+ line = f"asked Qoder to deliver {len(missing)} file(s) the agent wrote but did not deliver: {', '.join(missing)}"
+ self.notes.append(line)
+ _emit("notice", {"text": line})
+ self.nudging, self.stop_reason = True, None
+ try:
+ posted = self.post_message("Deliver these files you wrote to the user now with DeliverArtifacts, in one "
+ "call, without changing them: " + ", ".join(missing) +
+ ". Then reply with only: DELIVERED")
+ self.run_stream(posted)
+ finally:
+ self.nudging = False
+
+ def last_history_id(self) -> str:
+ try:
+ doc = self.api.request("GET", f"/sessions/{self.session_id}/events?limit=1&order=desc")
+ return str((doc or {}).get("first_id") or "")
+ except (ApiError, urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError):
+ return ""
+
+ def snapshot_usage(self) -> None:
+ try:
+ doc = self.api.request("GET", f"/sessions/{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):
+ pass
+
+ def charge(self) -> dict | None:
+ """This turn's charge: the session's usage now, less what the session had used when the
+ turn began. Qoder's usage is the SESSION's running total (the recorded live session read
+ 0.35 credits after its first turn and 0.61 after its second), so the snapshot as it stands
+ would bill every earlier turn again on each new one. Sandbox credits settle after idle, so
+ what settles late is counted on the next turn rather than lost or counted twice."""
+ if not self.usage or self.usage.get("total_credits") is None:
+ return None
+ before = (self.st.get("usage_seen") or {}).get(self.session_id) or {}
+
+ def spent(k: str):
+ now = self.usage.get(k)
+ if not isinstance(now, (int, float)):
+ return now
+ was = before.get(k)
+ return round(max(now - (was if isinstance(was, (int, float)) else 0), 0), 6)
+
+ return {"amount": spent("total_credits"), "unit": "qoder_credits", "basis": "snapshot",
+ "model_credits": spent("model_credits"),
+ "sandbox_runtime_credits": spent("sandbox_runtime_credits"),
+ "session_total": self.usage.get("total_credits")}
+
+ def cancel_remote(self) -> str:
+ """Stop the remote turn; → the line the record keeps about it."""
+ 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)
+ return f"cancel accepted by Qoder for session {self.session_id}"
+ except Exception as e: # noqa: BLE001
+ return f"cancel failed ({str(e)[:200]}); Qoder session {self.session_id} may still be running"
+
+ # ── main ──
+ def run(self) -> int:
+ job = self.job
+ resume = str(job.get("resume_session_id") or "")
+ sid, lost = self.find_session(resume)
+ if lost:
+ _emit("resume_lost", {"requested_session_id": resume})
+ _emit("__hr_init", {"session_id": sid, "agent_id": self.st.get("agent_id") or ""})
+
+ # input files first: a file Qoder cannot take fails the turn before anything is created
+ rels = [str(r) for r in (job.get("input_files") or [])]
+ for rel in rels:
+ try:
+ size = os.path.getsize(os.path.join(self.cwd, rel))
+ except OSError:
+ continue
+ why = upload_ok(rel, size)
+ if why:
+ self.result("failed", why)
+ return 0
+ env_id = self.ensure_environment()
+ servers, creds, dropped = mcp_config(job.get("mcp_servers") or [])
+ if dropped:
+ _emit("mcp_unavailable", {"servers": dropped})
+ vault_ids = self.ensure_vault(creds)
+ bindings = publish_skills(self.api, self.st, job.get("skills") or [], self.notes)
+ save_state(self.cwd, self.st)
+ resources = upload_inputs(self.api, self.st, self.cwd, rels)
+ save_state(self.cwd, self.st)
+ # The files this message brought are named IN the message. The Agent's system prompt cannot
+ # carry them: a session keeps the Agent version it was created with, so a file attached on a
+ # later turn was mounted and never mentioned, and the model did not know it was there.
+ self.mounts = [r["mount_path"] for r in resources]
+ body = agent_body(job, bindings, servers)
+ aid, version, changed = self.ensure_agent(body)
+ if sid:
+ 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.mount_resources(sid, resources)
+ else:
+ sid = self.create_session(aid, version, env_id, vault_ids, resources)
+ self.session_id = sid
+ _emit("session", {"session_id": sid, "agent_id": aid, "agent_version": version,
+ "environment_id": env_id})
+ posted = self.post_message()
+ self.run_stream(posted)
+ self.deliver_written()
+ self.snapshot_usage()
+ save_state(self.cwd, self.st)
+
+ missing = [d for d in self.declared if not any(l["file_id"] == d["file_id"] for l in self.landed)]
+ lost = self.undelivered()
+ if self.terminated:
+ self.result("failed", (self.error or {}).get("message") or "the Qoder session was terminated")
+ elif self.error and self.error.get("retry") in ("terminal", "exhausted") and not self.final:
+ self.result("failed", self.error["message"])
+ elif str((self.stop_reason or {}).get("type") or "") != "end_turn":
+ self.result("incomplete", f"stop_reason {json.dumps(self.stop_reason or {})}")
+ elif missing or self.artifact_failures or lost:
+ self.result("incomplete", "artifact not delivered: " + "; ".join(
+ self.artifact_failures + [m["name"] for m in missing] + [f"{p} (written, never delivered)" for p in lost]))
+ else:
+ self.result("completed", "")
+ return 0
+
+ def result(self, status: str, reason: str) -> None:
+ charge = self.charge()
+ if charge and self.session_id:
+ # what the session had used by the end of this turn: the next turn's charge starts here
+ self.st.setdefault("usage_seen", {})[self.session_id] = dict(self.usage or {})
+ try:
+ save_state(self.cwd, self.st)
+ except OSError:
+ pass
+ _emit("__hr_result", {"status": status, "reason": reason, "final": self.final,
+ "session_id": self.session_id or self.st.get("session_id") or "",
+ "charge": charge, "notes": self.notes,
+ "artifacts": self.landed})
+
+
+# ── purge ────────────────────────────────────────────────────────────────────────────────────────
+def purge(job: dict) -> int:
+ """Delete at Qoder everything the session's turns created there, in dependency order; every
+ failure 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)
+ done: list[str] = []
+ failed: list[dict] = []
+
+ def attempt(label: str, method: str, path: str, body: dict | None = None, ok_status=(404,)) -> bool:
+ try:
+ api.request(method, path, body)
+ done.append(label)
+ return True
+ except ApiError as e:
+ if e.status in ok_status:
+ done.append(label + " (already gone)")
+ return True
+ failed.append({"what": label, "error": str(e)})
+ except Exception as e: # noqa: BLE001
+ failed.append({"what": label, "error": f"{type(e).__name__}: {e}"[:300]})
+ return False
+
+ 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}")
+ for fid in list(st.get("artifacts") or []):
+ attempt(f"delete artifact file {fid}", "DELETE", f"/files/{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']}")
+ if st.get("agent_id"):
+ attempt(f"archive agent {st['agent_id']}", "POST", f"/agents/{st['agent_id']}/archive")
+ if st.get("vault_id"):
+ attempt(f"delete vault {st['vault_id']}", "DELETE", f"/vaults/{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']}")
+ if st.get("environment_id"):
+ eid = st["environment_id"]
+ try:
+ api.request("DELETE", f"/environments/{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")
+ else:
+ failed.append({"what": f"delete environment {eid}", "error": str(e)})
+ except Exception as e: # noqa: BLE001
+ failed.append({"what": f"delete environment {eid}", "error": f"{type(e).__name__}: {e}"[:300]})
+ _emit("purge", {"done": done, "failed": failed, "state": STATE_REL})
+ return 0 if not failed else 1
+
+
+# ── entry ────────────────────────────────────────────────────────────────────────────────────────
+def main() -> int:
+ job = json.loads(sys.argv[1])
+ if job.get("purge"):
+ return purge(job)
+ turn = Turn(job)
+
+ def on_term(signum, frame): # noqa: ARG001
+ raise Cancelled()
+
+ signal.signal(signal.SIGTERM, on_term)
+ try:
+ return turn.run()
+ except Cancelled:
+ signal.signal(signal.SIGTERM, signal.SIG_IGN) # the cancel call itself is not interrupted
+ line = turn.cancel_remote()
+ _emit("notice", {"text": line})
+ turn.result("cancelled", line)
+ return 0
+ 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])
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/runner/server.py b/runner/server.py
index d8b97a06..761d624f 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -57,6 +57,7 @@ import re
import shlex
import shutil
import signal
+import sys
import socket
import sqlite3
import subprocess
@@ -1380,6 +1381,14 @@ def _write_skills(cwd: str, skills: list[dict], backend: str = "claude") -> list
# config.yaml, so a tree another backend wrote is not swept in (kimi's reason).
rootrels = [".harness/home/.minimax/skills"]
entryroot = ".harness/home/.minimax/skills"
+ elif backend == "qoder":
+ # Not where a loader looks — nothing on this box loads them. The folders are staged here
+ # for the driver to publish as Qoder Skill resources bound on the session's Agent, which
+ # Qoder's sandbox then installs under the skill's own name. Under .harness/ so the bundle
+ # is never a produced file, and checkpointed so the content hash the driver keeps is
+ # comparable next turn.
+ rootrels = [".harness/skills"]
+ entryroot = ".harness/skills"
elif backend in ("opencode", "kilo"):
# Kilo CLI is opencode's fork and keeps the same `skills.paths` key (core/src/v1/config/
# skills.ts at 7.8.1), so it takes the same directory.
@@ -1875,8 +1884,8 @@ def _write_agent_doc(cwd: str, backend: str, agent_doc: str | None, skills_meta:
workspace PARENT, the user saw an empty turn, and three turns went to copying files into view.
An instruction is the right mechanism here: writes cannot be walled in a sandbox whose point is
real bash, and widening collection would ship every scratch file as a deliverable."""
- if backend == "systemone":
- return # reads no workspace; its instructions travel in the job (see _build_systemone)
+ if backend in ("systemone", "qoder"):
+ return # reads no workspace; its instructions travel in the job (_build_systemone, _build_qoder)
p = _agent_doc_path(cwd, backend)
base = (agent_doc or "").strip()
lines = [_AGENTS_BEGIN, "## Workspace", "",
@@ -4997,12 +5006,27 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
self.wfile.write(data)
return
base, key, flags = route
+ if self.command == "DELETE" and not flags.get("passthrough"):
+ # DELETE is a remote runtime's (its own objects, deleted through its API). A model
+ # provider's route stays GET and POST: a sandbox must not delete what the org's key owns
+ # there (files, fine-tunes, batches) through the relay that holds that key.
+ data = b'{"error": "this route does not forward DELETE"}'
+ self.send_response(405)
+ self.send_header("allow", "GET, POST")
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
tail = self.path.removeprefix("/v1") if self.path.startswith("/v1/") else self.path
drop = {"host", "content-length", "authorization", "x-goog-api-key", "x-api-key", "connection",
"accept-encoding", "transfer-encoding"}
headers = {k: v for k, v in self.headers.items() if k.lower() not in drop}
headers["authorization"] = f"Bearer {key}"
headers.setdefault("accept", "*/*")
+ if flags.get("passthrough"):
+ self._passthrough(base, key, tail, headers, body)
+ return
if tail.split("?", 1)[0] == "/messages" and not flags.get("bedrock_anthropic"):
# An Anthropic Messages call (goose's and hermes's anthropic providers, litellm's
# anthropic/ route, the claude CLI on a custom endpoint). Anthropic reads the key from
@@ -5493,6 +5517,92 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(data)
+ def _passthrough(self, base: str, key: str, tail: str, headers: dict, body: bytes | None) -> None:
+ """A route that is only the credential boundary: the request goes up as the client wrote it
+ and the answer comes down as the provider wrote it. No body rewrite, no retry ladder, and
+ NONE of the taps — not the served model, not usage, not the finish reason.
+
+ This is the route a remote runtime's control API rides (Qoder's Managed API, see
+ _qoder_relay_route). Those objects carry a `"model":"…"` field that is the CONFIGURED model,
+ not what served: a session object through the model-call taps would be recorded as a served
+ model and scored by the matrix as a substitution check the backend cannot make. Stalls are
+ not narrated either: a long remote tool step can be silent for longer than the relay's wait,
+ and an error event written into this stream would be read by the driver as the API's own.
+ The connection simply closes, and the driver resumes from its last event id."""
+ req = urllib.request.Request(base.rstrip("/") + tail, data=body, method=self.command, headers=headers)
+ try:
+ resp = urllib.request.urlopen(req, timeout=HR_RELAY_UPSTREAM_TIMEOUT_S)
+ except urllib.error.HTTPError as e:
+ data = e.read()
+ self.send_response(e.code)
+ self.send_header("content-type", e.headers.get("content-type") or "application/json")
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ except (urllib.error.URLError, http.client.HTTPException, TimeoutError, OSError) as e:
+ reason = f"{type(e).__name__}: {e}"[:300]
+ print(f"[relay] upstream did not answer {tail} (passthrough): {reason}", flush=True)
+ payload = json.dumps({"type": "error", "error": {
+ "type": "upstream_unavailable", "message": f"the provider did not answer: {reason}"}}).encode()
+ try:
+ self.send_response(504 if isinstance(e, TimeoutError) or "timed out" in str(e) else 502)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ except OSError:
+ pass
+ return
+ ctype = resp.headers.get("content-type") or ""
+ if "text/event-stream" in ctype:
+ self.send_response(resp.status)
+ self.send_header("content-type", ctype)
+ self.send_header("transfer-encoding", "chunked")
+ self.end_headers()
+ while True:
+ try:
+ chunk = resp.read1(65536)
+ except (http.client.HTTPException, TimeoutError, OSError) as e:
+ # the stream stopped: closed, not narrated (see above)
+ print(f"[relay] passthrough stream on {tail} stopped: {type(e).__name__}: {e}"[:300], flush=True)
+ self.close_connection = True
+ return
+ if not chunk:
+ break
+ try:
+ self.wfile.write(f"{len(chunk):x}\r\n".encode() + chunk + b"\r\n")
+ self.wfile.flush()
+ except OSError:
+ self.close_connection = True
+ return
+ try:
+ self.wfile.write(b"0\r\n\r\n")
+ except OSError:
+ # the driver read its terminal event and closed first (seen on 0.33.0-rc.4 as a
+ # BrokenPipeError traceback per finished stream): nothing is lost
+ self.close_connection = True
+ return
+ try:
+ data = resp.read()
+ except (http.client.HTTPException, TimeoutError, OSError) as e:
+ payload = json.dumps({"type": "error", "error": {
+ "type": "upstream_unavailable", "message": f"the provider stopped answering mid-body: {e}"[:300]}}).encode()
+ try:
+ self.send_response(502)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ except OSError:
+ pass
+ return
+ self.send_response(resp.status)
+ self.send_header("content-type", ctype)
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
def _bedrock_anthropic(self, origin: str, key: str, body: bytes) -> None:
"""Anthropic Messages -> Bedrock InvokeModel, both directions.
@@ -5587,10 +5697,30 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802 — model listings and the like
self._forward(None)
+ def do_DELETE(self): # noqa: N802 — a remote runtime's objects are deleted through its API
+ self._forward(None)
+
def log_message(self, *a): # diagnostics belong on stderr, never stdout
pass
+def _qoder_relay_route(base_url: str, api_key: str) -> tuple[str, str]:
+ """Register one Qoder turn's API base as a pass-through route; → (relay base, placeholder).
+
+ The relay is the credential boundary and nothing else here: the PAT stays in this process, the
+ driver is handed a placeholder, and every call — session create, events, the SSE stream, file
+ upload, DELETE — goes up verbatim (_HermesRelayHandler._passthrough). The base is joined as
+ stored (…/api/v1/cloud), never given a /v1 of its own."""
+ with _HERMES_RELAY["lock"]:
+ if _HERMES_RELAY["server"] is None:
+ srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _HermesRelayHandler)
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ _HERMES_RELAY["server"], _HERMES_RELAY["port"] = srv, srv.server_address[1]
+ tok = "hr-relay-" + uuid.uuid4().hex
+ _HERMES_RELAY["routes"][tok] = ((base_url or "").rstrip("/"), api_key, _turn_route({"passthrough": True}))
+ return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok
+
+
def _bedrock_anthropic_route(origin: str, api_key: str) -> tuple[str, str]:
"""Register a Bedrock-Anthropic adapter route; -> (relay base_url, placeholder bearer)."""
with _HERMES_RELAY["lock"]:
@@ -8708,6 +8838,146 @@ OPENHANDS_PYTHON = os.environ.get("HR_OPENHANDS_PYTHON",
"/data/agent-tools/openhands-venv/bin/python")
OPENHANDS_DRIVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "openhands_driver.py")
+# ── qoder: Qoder Cloud Agent, a hosted runtime reached over REST + SSE (api.qoder.com) ────────
+# The first backend whose runtime is not a process this runner spawns. The turn process is
+# runner/qoder_driver.py, an HTTP client to Qoder's Managed API: it creates (or continues) a
+# session there, posts the message, follows the event stream and lands delivered artifacts in the
+# workspace. BACKENDS marks it `remote`, which is what gives it a graceful stop (_stop_proc) so the
+# remote turn is cancelled before the local process is killed.
+#
+# Qoder picks and bills the model itself; a connection carries Qoder's PAT or SAT and nothing else,
+# so the backend has one provider, `qoder`. The public API reports neither token counts nor the
+# served model (only credits), so a turn's result carries no usage and no model, and a `charge`
+# instead — docs/harness-verification.md, "remote runtimes".
+QODER_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
+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 to
+# qoder_driver.TOOLS and to the gateway's catalog by tests.
+QODER_TOOLS = ("Bash", "DeliverArtifacts", "Edit", "Glob", "Grep", "ImageGen", "ImageSearch", "Read",
+ "WebFetch", "WebSearch", "Write")
+QODER_EFFORTS = ("none", "low", "medium", "high", "xhigh", "max")
+
+
+def _build_qoder(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, agent_doc: str = "",
+ input_files: list[str] | None = None, skills: list[dict] | None = None) -> list[str]:
+ """One Qoder turn's job, as argv for the driver.
+
+ The harness's instructions travel in the job and become the Agent's `system`: this backend
+ reads no workspace file (the systemone precedent). Disabled tools are withheld by the Agent's
+ tool configuration, the enabled ones `always_allow`, so the remote turn never pauses for a
+ confirmation nobody is here to give. Input files the runner staged are named for the driver to
+ upload and mount; skills are the folders _write_skills produced, for the driver to publish."""
+ pr = provider or "qoder"
+ if pr not in QODER_PROVIDERS:
+ raise HTTPException(400, f"unknown qoder provider '{pr}' (one of {sorted(QODER_PROVIDERS)})")
+ if not auth.api_key:
+ raise HTTPException(400, "qoder needs a PAT or SAT (none configured)")
+ base = (auth.base_url or QODER_DEFAULT_BASE).rstrip("/")
+ relay_base, relay_tok = _qoder_relay_route(base, auth.api_key)
+ env["QODER_API_KEY"] = relay_tok # the placeholder; the route is found by it, and holds no tap
+ thinking = _TURN_THINKING.get() or {}
+ effort = str(thinking.get("asked") or "")
+ if effort:
+ # Qoder's Agent takes the level by the same names; one it does not know is not sent
+ thinking["applied"] = effort if effort in QODER_EFFORTS else ""
+ job = {"cwd": cwd, "prompt": prompt, "model": model, "base_url": relay_base, "api_key": relay_tok,
+ "resume_session_id": resume_session_id or "",
+ "agent_doc": agent_doc or "",
+ "tools_disabled": [str(t) for t in (tools_disabled or []) if t],
+ "mcp_servers": [s for s in (mcp_servers or []) if isinstance(s, dict)],
+ "input_files": list(input_files or []),
+ "skills": list(skills or []),
+ "effort": effort if effort in QODER_EFFORTS else ""}
+ return [QODER_PYTHON, QODER_DRIVER, json.dumps(job)]
+
+
+def _qoder_to_claude(obj: dict, state: dict) -> list[dict]:
+ """Map ONE driver NDJSON line to canonical claude stream-json events.
+
+ The result carries no usage and no model: Qoder's public API reports neither. It carries
+ `charge` ({amount, unit: "qoder_credits", basis: "snapshot"}) when the session's usage snapshot
+ was readable, and `reason` for an `incomplete` turn (every stop_reason other than end_turn,
+ and an artifact the stream declared that did not land)."""
+ m = obj.get("m")
+ p = obj.get("p") if isinstance(obj.get("p"), dict) else {}
+ if m == "__hr_init":
+ sid = str(p.get("session_id") or "")
+ if sid:
+ state["_qoder_init"] = True
+ return [{"type": "system", "subtype": "init", "session_id": sid, "model": state.get("model")}]
+ return []
+ if m == "session":
+ if state.get("_qoder_init"):
+ return []
+ state["_qoder_init"] = True
+ return [{"type": "system", "subtype": "init", "session_id": str(p.get("session_id") or ""),
+ "model": state.get("model")}]
+ if m == "resume_lost":
+ return [{"type": "system", "subtype": "resume_lost",
+ "requested_session_id": str(p.get("requested_session_id") or "")}]
+ if m == "text":
+ txt = str(p.get("text") or "")
+ if not txt:
+ return []
+ state["_qoder_text"] = state.get("_qoder_text", "") + txt
+ state["final"] = state["_qoder_text"]
+ return [{"type": "assistant", "message": {"content": [{"type": "text", "text": txt}]}}]
+ if m == "tool_use":
+ if state.get("_qoder_text") and not state["_qoder_text"].endswith("\n"):
+ state["_qoder_text"] += "\n\n"
+ return [{"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": str(p.get("id") or ""), "name": str(p.get("name") or "tool"),
+ "input": p.get("input") if isinstance(p.get("input"), dict) else {}}]}}]
+ if m == "tool_result":
+ return [{"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": str(p.get("tool_use_id") or ""),
+ "is_error": bool(p.get("is_error")), "content": str(p.get("text") or "")}]}}]
+ if m == "mcp_unavailable":
+ servers = [{"name": str(s.get("name"))} for s in (p.get("servers") or [])
+ if isinstance(s, dict) and s.get("name")]
+ return [{"type": "system", "subtype": "mcp_unavailable", "servers": servers}] if servers else []
+ if m in ("notice", "error"):
+ state.setdefault("_qoder_notices", []).append(str(p.get("text") or p.get("message") or ""))
+ return []
+ if m == "__hr_result":
+ status = str(p.get("status") or "")
+ final = str(p.get("final") or "") or state.get("_qoder_text", "")
+ reason = str(p.get("reason") or "")
+ ev: dict = {"type": "result", "usage": {}}
+ if p.get("charge"):
+ ev["charge"] = p["charge"]
+ if status == "completed":
+ state["final"] = final
+ ev.update(subtype="success", is_error=False, result=final)
+ elif status == "incomplete":
+ state["final"] = final
+ ev.update(subtype="incomplete", is_error=False, result=final or reason, reason=reason)
+ else:
+ # failed, cancelled: the reason is the answer the record shows
+ ev.update(subtype="error", is_error=True, result=reason or final or "the Qoder turn failed",
+ reason=reason)
+ return [ev]
+ return []
+
+
+def _qoder_eof(state: dict, rc: int) -> list[dict]:
+ """The driver emits its own result, so this fires only when it died before reaching it. The
+ remote session may still be running then: the record says so, with what the driver last said."""
+ notes = [n for n in state.get("_qoder_notices") or [] if n]
+ tail = notes[-1] if notes else f"qoder driver exited {rc} without a result"
+ return [{"type": "result", "subtype": "error", "is_error": True, "usage": {},
+ "result": f"{tail}; the Qoder session may still be running"}]
+
+
+_qoder_to_claude.eof = _qoder_eof # type: ignore[attr-defined]
+
+
# ── systemone: the System One Harness (github.com/HarnessRouter/SystemOneHarness, Apache-2.0) ──
# A loop over a decision model rather than a coding CLI: TypeSafe's Jev answers typed questions with
# probabilities and writes no text, so the harness compiles the environment's actions into one
@@ -10516,6 +10786,11 @@ BACKENDS = {
"systemone": {"providers": sorted(SYSTEMONE_PROVIDERS),
"default_model": SYSTEMONE_DEFAULT_MODEL,
"normalize": _claude_passthrough},
+ # Qoder's runtime is not a process this runner spawns: the driver is an HTTP client to a hosted
+ # session. `remote` is what gives a stop its grace (SIGTERM, then the kill) so the driver can
+ # cancel the remote turn before it dies — see _stop_proc.
+ "qoder": {"providers": sorted(QODER_PROVIDERS), "default_model": QODER_DEFAULT_MODEL,
+ "normalize": _qoder_to_claude, "remote": True},
# MiMo Code is an opencode FORK whose `run --format json` stream is opencode's line for line
# (measured on 0.1.15), so it shares opencode's normaliser rather than carrying a copy — the
# same relationship omp has to pi.
@@ -10699,9 +10974,37 @@ def _descendant_pids(root: int) -> list[int]:
return out
+# How long a remote backend's driver has between the runner's SIGTERM and its SIGKILL: enough for
+# one cancel call to the remote API and the line that reports it, not enough to hold a stop.
+_REMOTE_STOP_GRACE_S = float(os.environ.get("HR_REMOTE_STOP_GRACE_S", "5") or 5)
+
+
+def _stop_proc(proc: subprocess.Popen, rec: dict) -> None:
+ """End a turn's process the way its backend needs.
+
+ A local CLI is its own runtime: the process group is stopped and killed and the turn is over
+ (_kill_proc_tree). A REMOTE backend's process is a client of a runtime elsewhere, and killing
+ the client leaves that runtime running and billing. So for a backend whose registry entry says
+ `remote`, SIGTERM goes to the driver first and it has _REMOTE_STOP_GRACE_S to cancel the remote
+ turn and say so on stdout — the reader loop is still draining, so the line reaches the record —
+ before the kill the local backends get at once. The same path serves a cancel and the wall-clock
+ cap. SIGTERM precedes the SIGSTOP in _kill_proc_tree on purpose: a stopped process cannot run a
+ handler."""
+ spec = BACKENDS.get(str(rec.get("backend") or "")) or {}
+ if spec.get("remote") and proc.poll() is None:
+ try:
+ proc.send_signal(signal.SIGTERM)
+ except Exception: # noqa: BLE001
+ pass
+ deadline = time.monotonic() + _REMOTE_STOP_GRACE_S
+ while time.monotonic() < deadline and proc.poll() is None:
+ time.sleep(0.05)
+ _kill_proc_tree(proc, str(rec.get("turn_id") or ""))
+
+
def _kill_capped(proc: subprocess.Popen, rec: dict) -> None:
rec["capped"] = True
- _kill_proc_tree(proc, str(rec.get("turn_id") or ""))
+ _stop_proc(proc, rec)
def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, model: str,
@@ -11902,7 +12205,7 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
# would be a turn in another session's identity.
raise HTTPException(400, "cwd is decided by the session identifier")
os.makedirs(cwd, exist_ok=True)
- _write_input_files(cwd, req.files) # land caller-attached files in the workspace pre-run
+ input_files = _write_input_files(cwd, req.files) # land caller-attached files in the workspace pre-run
# Built-in skills the harness disabled must NOT be mounted. On BusinessOS built-ins aren't
# image-mounted (there is no _mount_builtin_skills), and the gateway already drops suppress markers
# from req.skills, so this filter is a parity guard: never write a skill whose name is suppressed.
@@ -11952,6 +12255,10 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
if note:
agent_doc = ((agent_doc + "\n\n") if agent_doc.strip() else "") + note
turn_environment = environments.resolve(req.environment) # 409 when nothing is built: before any process starts
+ if turn_environment and spec.get("remote"):
+ # The layer is mounted read-only in THIS sandbox; a remote runtime sees only what its driver
+ # uploads. Said here, before anything starts, rather than run without it.
+ raise HTTPException(400, f"the {backend} backend runs in a remote runtime and cannot mount an environment")
_write_agent_doc(cwd, backend, agent_doc, installed_skills, environment=turn_environment)
# The harness's own variables under the runner's, so nothing a caller names shadows the
# runner's credentials or paths; the platform's HR_ names come after and win (below).
@@ -12111,6 +12418,17 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
resume_session_id=req.resume_session_id,
mcp_servers=req.mcp_servers,
tools_disabled=req.tools_disabled, max_turns=req.max_turns)
+ elif backend == "qoder":
+ model = model or QODER_DEFAULT_MODEL
+ # The agent doc becomes the remote Agent's system prompt; the skill folders _write_skills
+ # staged are published by the driver; the input files the runner landed are uploaded and
+ # mounted by it. Nothing on this box is read by the runtime.
+ cmd = _build_qoder(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, agent_doc=agent_doc,
+ input_files=input_files,
+ skills=[{"name": s["name"], "dir": os.path.dirname(os.path.join(cwd, s["entry"]))}
+ for s in installed_skills])
elif backend == "systemone":
model = model or SYSTEMONE_DEFAULT_MODEL
cmd = _build_systemone(req.provider, auth, model, req.prompt, cwd, env,
@@ -12237,8 +12555,55 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
"host": socket.gethostname(), "max_seconds": cap}
+class WorkspaceDelete(BaseModel):
+ """What a session delete may carry: the connection of a REMOTE backend, so the objects the
+ session created at that runtime can be deleted too (_remote_purge). Absent for a local one."""
+ auth: Auth | None = None
+ backend: str | None = None
+
+
+def _remote_purge(ws: str, auth: Auth | None) -> dict | None:
+ """Delete what a remote backend's turns created outside this box, before the folder goes.
+
+ The driver recorded every remote id it made in the session's .harness/ state; the same driver,
+ in purge mode, deletes them through the relay (the credential stays here as on a turn). A
+ delete that could not reach the runtime is reported with its ids and logged, never swallowed:
+ the folder is still removed, since the session is already unreadable, but the answer says what
+ is left. None when the session made nothing remote."""
+ state = pathlib.Path(ws) / QODER_STATE_REL
+ if not state.is_file():
+ return None
+ if not (auth and auth.api_key):
+ print(f"[workspace] {ws}: remote Qoder objects recorded but no credential came with the delete; "
+ f"left in place: {state.read_text()[:600]}", flush=True)
+ return {"backend": "qoder", "purged": False, "reason": "no credential", "state": QODER_STATE_REL}
+ base = (auth.base_url or QODER_DEFAULT_BASE).rstrip("/")
+ relay_base, relay_tok = _qoder_relay_route(base, auth.api_key)
+ job = {"purge": True, "cwd": ws, "base_url": relay_base, "api_key": relay_tok}
+ try:
+ proc = subprocess.run([QODER_PYTHON, QODER_DRIVER, json.dumps(job)], capture_output=True, text=True,
+ timeout=180, **_as_session(ws))
+ except Exception as e: # noqa: BLE001
+ print(f"[workspace] {ws}: remote purge did not run: {type(e).__name__}: {e}", flush=True)
+ return {"backend": "qoder", "purged": False, "reason": f"purge did not run: {e}"[:300]}
+ report: dict = {}
+ for line in (proc.stdout or "").splitlines():
+ try:
+ obj = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(obj, dict) and obj.get("m") == "purge" and isinstance(obj.get("p"), dict):
+ report = obj["p"]
+ failed = report.get("failed") or []
+ if failed or proc.returncode != 0:
+ print(f"[workspace] {ws}: remote purge left objects at Qoder: {json.dumps(failed)[:1500]} "
+ f"(exit {proc.returncode}) {(proc.stderr or '')[-500:]}", flush=True)
+ return {"backend": "qoder", "purged": not failed and proc.returncode == 0,
+ "done": report.get("done") or [], "failed": failed}
+
+
@app.delete("/workspace")
-async def delete_workspace(identifier: str = "") -> dict:
+async def delete_workspace(identifier: str = "", body: WorkspaceDelete | None = None) -> dict:
"""Remove a session's working folder for good (session delete, Sessions §6).
This lives in the runner and not the gateway on purpose: the gateway runs as an unprivileged
@@ -12246,7 +12611,10 @@ async def delete_workspace(identifier: str = "") -> dict:
process that made the wall can take it down. The folder is the session's memory on this box;
the durable tarball is the gateway's to delete. A shared root (sandbox-per-session) is never
removed. The gateway stops any live turn before asking; turn records here carry no session
- identity, so this end cannot second-guess that."""
+ identity, so this end cannot second-guess that.
+
+ A session of a REMOTE backend made objects elsewhere too; with the connection in the body they
+ are deleted first (_remote_purge), and the answer carries what that reached."""
ident = (identifier or "").strip()
if not ident:
raise HTTPException(status_code=400, detail="identifier required")
@@ -12262,6 +12630,7 @@ async def delete_workspace(identifier: str = "") -> dict:
_ws_marker_clear(ident)
if not os.path.isdir(ws):
return {"identifier": ident, "removed": False, "reason": "no folder"}
+ remote = await run_in_threadpool(_remote_purge, ws, body.auth if body else None)
uid = _session_uid(ws)
shutil.rmtree(ws, ignore_errors=True)
if uid is not None:
@@ -12271,7 +12640,10 @@ async def delete_workspace(identifier: str = "") -> dict:
subprocess.run(["groupdel", f"hs{uid}"], capture_output=True)
except OSError:
pass
- return {"identifier": ident, "removed": not os.path.isdir(ws)}
+ out = {"identifier": ident, "removed": not os.path.isdir(ws)}
+ if remote is not None:
+ out["remote"] = remote
+ return out
@app.post("/turn/{turn_id}/cancel")
@@ -12286,7 +12658,11 @@ def cancel_turn(turn_id: str) -> dict:
rec["cancelled"] = True
proc = rec.get("proc")
if proc is not None:
- _kill_proc_tree(proc, turn_id)
+ if (BACKENDS.get(str(rec.get("backend") or "")) or {}).get("remote"):
+ # the grace is waited on a thread of its own, so this answer is not held for it
+ threading.Thread(target=_stop_proc, args=(proc, rec), daemon=True).start()
+ else:
+ _kill_proc_tree(proc, turn_id)
return {"turn_id": turn_id, "status": "cancelling", "cancelled": True}
diff --git a/runner/tests/fixtures/qoder/live-session-events.json b/runner/tests/fixtures/qoder/live-session-events.json
new file mode 100644
index 00000000..7c34d58c
--- /dev/null
+++ b/runner/tests/fixtures/qoder/live-session-events.json
@@ -0,0 +1,375 @@
+[
+ {
+ "id": "evt_00rv4y8m1ntvklo39jxt",
+ "processed_at": "2026-10-09T03:09:11.989752107Z",
+ "type": "session.status_running"
+ },
+ {
+ "agent_name": "harnessrouter live-ws1",
+ "id": "evt_00rv4y8m1ntvljcw6kq3",
+ "processed_at": "2026-10-09T03:09:11.989752107Z",
+ "session_thread_id": "sthr_00rv4y7nzicqoxu769ok",
+ "type": "session.thread_status_running"
+ },
+ {
+ "content": [
+ {
+ "text": "Create a file named hello.md containing exactly the line: Hello from HarnessRouter live test. Then deliver it with DeliverArtifacts. Reply with one short sentence when done.",
+ "type": "text"
+ }
+ ],
+ "id": "evt_00rv4y8j2a70i2z1fuw8",
+ "processed_at": "2026-10-09T03:09:11.989752107Z",
+ "type": "user.message"
+ },
+ {
+ "id": "evt_00rv4y8j4s3cxtujzmz4",
+ "processed_at": "2026-10-09T03:09:12.032189121Z",
+ "type": "span.model_request_start"
+ },
+ {
+ "id": "evt_00rv4ybbfq0hsvdjgjrd",
+ "processed_at": "2026-10-09T03:09:13.760879Z",
+ "type": "agent.thinking"
+ },
+ {
+ "evaluated_permission": "allow",
+ "id": "evt_00rv4ybzuo0004mic0tg",
+ "input": {
+ "content": "Hello from HarnessRouter live test.\n",
+ "file_path": "/data/hello.md"
+ },
+ "name": "Write",
+ "processed_at": "2026-10-09T03:09:14.280972Z",
+ "type": "agent.tool_use"
+ },
+ {
+ "id": "evt_00rv4ycz88uf4nercl7f",
+ "is_error": false,
+ "model_request_start_id": "evt_00rv4y8j4s3cxtujzmz4",
+ "model_usage": {
+ "credits": 0.27
+ },
+ "processed_at": "2026-10-09T03:09:14.280972Z",
+ "type": "span.model_request_end"
+ },
+ {
+ "content": [
+ {
+ "text": "Write file /data/hello.md successfully\n\n--- /data/hello.md\n+++ /data/hello.md\n@@ -0,0 +1,2 @@\n+Hello from HarnessRouter live test.\n+",
+ "type": "text"
+ }
+ ],
+ "id": "evt_00rv4yhnzwb9cyiwfmsz",
+ "is_error": false,
+ "processed_at": "2026-10-09T03:09:16.734162Z",
+ "tool_use_id": "evt_00rv4ybzuo0004mic0tg",
+ "type": "agent.tool_result"
+ },
+ {
+ "id": "evt_00rv4yhqcsv0hn4cos2n",
+ "processed_at": "2026-10-09T03:09:16.767099439Z",
+ "type": "span.model_request_start"
+ },
+ {
+ "id": "evt_00rv4yj7cmio0wdrr34d",
+ "processed_at": "2026-10-09T03:09:19.443238Z",
+ "type": "agent.thinking"
+ },
+ {
+ "evaluated_permission": "allow",
+ "id": "evt_00rv4ymwy6kn5mjhi022",
+ "input": {
+ "files": [
+ {
+ "path": "/data/hello.md"
+ }
+ ]
+ },
+ "name": "DeliverArtifacts",
+ "processed_at": "2026-10-09T03:09:19.819914Z",
+ "type": "agent.tool_use"
+ },
+ {
+ "id": "evt_00rv4ynmw4ykgke06ccm",
+ "is_error": false,
+ "model_request_start_id": "evt_00rv4yhqcsv0hn4cos2n",
+ "model_usage": {
+ "credits": 0.04
+ },
+ "processed_at": "2026-10-09T03:09:19.819914Z",
+ "type": "span.model_request_end"
+ },
+ {
+ "content_type": "text/markdown",
+ "file_id": "file_00rv4you3vw8wpwq624j",
+ "id": "evt_00rv4yp7cui9sapw4gkh",
+ "original_filename": "hello.md",
+ "processed_at": "2026-10-09T03:09:20.644172Z",
+ "size": 36,
+ "type": "agent.artifact_delivered"
+ },
+ {
+ "content": [
+ {
+ "text": "Delivered 1/1 artifact(s):\n- delivered hello.md (file_id=file_00rv4you3vw8wpwq624j, 36 bytes)",
+ "type": "text"
+ }
+ ],
+ "id": "evt_00rv4ypa28jr4061rxic",
+ "is_error": false,
+ "processed_at": "2026-10-09T03:09:20.685128Z",
+ "tool_use_id": "evt_00rv4ymwy6kn5mjhi022",
+ "type": "agent.tool_result"
+ },
+ {
+ "id": "evt_00rv4ypcmmsjlloiq530",
+ "processed_at": "2026-10-09T03:09:20.720708031Z",
+ "type": "span.model_request_start"
+ },
+ {
+ "id": "evt_00rv4yqr4n01sm5vuunn",
+ "processed_at": "2026-10-09T03:09:22.024343Z",
+ "type": "agent.thinking"
+ },
+ {
+ "content": [
+ {
+ "text": "Done—hello.md has been created and delivered.",
+ "type": "text"
+ }
+ ],
+ "id": "evt_00rv4ys20oz5sw9z2zpn",
+ "processed_at": "2026-10-09T03:09:22.137665Z",
+ "type": "agent.message"
+ },
+ {
+ "id": "evt_00rv4ys3r4m4gnmyp7lt",
+ "is_error": false,
+ "model_request_start_id": "evt_00rv4ypcmmsjlloiq530",
+ "model_usage": {
+ "credits": 0.03
+ },
+ "processed_at": "2026-10-09T03:09:22.137665Z",
+ "type": "span.model_request_end"
+ },
+ {
+ "agent_name": "harnessrouter live-ws1",
+ "id": "evt_00rv4ys4640747he4bao",
+ "processed_at": "2026-10-09T03:09:22.137665Z",
+ "session_thread_id": "sthr_00rv4y7nzicqoxu769ok",
+ "stop_reason": {
+ "type": "end_turn"
+ },
+ "type": "session.thread_status_idle"
+ },
+ {
+ "id": "evt_00rv4ys4sl3b4cwpk6cu",
+ "model_credits": 0.35,
+ "processed_at": "2026-10-09T03:09:22.137665Z",
+ "sandbox_runtime_credits": 0,
+ "total_credits": 0.35,
+ "type": "session.usage"
+ },
+ {
+ "id": "evt_00rv4ys2x5tz4r6nhvgg",
+ "processed_at": "2026-10-09T03:09:22.137665Z",
+ "stop_reason": {
+ "type": "end_turn"
+ },
+ "type": "session.status_idle"
+ },
+ {
+ "agent": {
+ "description": "Created by HarnessRouter for one session; deleted with it.",
+ "id": "agent_00rv4y759agowv21tpo8",
+ "mcp_servers": [],
+ "model": {
+ "effective_context_window": 200000,
+ "id": "efficient"
+ },
+ "multiagent": null,
+ "name": "harnessrouter live-ws1",
+ "skills": [],
+ "system": "Be brief.\n\n## Delivering files\n\nYou run in a remote sandbox. The user sees NO file you write unless you deliver it: when a task produces a deliverable (a document, a deck, code, an export), save it and then call DeliverArtifacts with its path. Deliver each file once, by a plain file name; an undelivered file is lost to the user.",
+ "tools": [
+ {
+ "configs": [
+ {
+ "enabled": true,
+ "name": "DeliverArtifacts",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": true,
+ "name": "Edit",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": true,
+ "name": "Glob",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": true,
+ "name": "Grep",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": true,
+ "name": "ImageGen",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": true,
+ "name": "ImageSearch",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": true,
+ "name": "Read",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": true,
+ "name": "WebFetch",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": true,
+ "name": "Write",
+ "permission_policy": {
+ "type": "always_allow"
+ }
+ },
+ {
+ "enabled": false,
+ "name": "Bash"
+ },
+ {
+ "enabled": false,
+ "name": "WebSearch"
+ }
+ ],
+ "disallowed_tools": [
+ "Bash",
+ "WebSearch"
+ ],
+ "enabled_tools": [
+ "DeliverArtifacts",
+ "Edit",
+ "Glob",
+ "Grep",
+ "ImageGen",
+ "ImageSearch",
+ "Read",
+ "WebFetch",
+ "Write"
+ ],
+ "type": "agent_toolset_20260401"
+ }
+ ],
+ "type": "agent",
+ "version": 1
+ },
+ "id": "evt_00rv50or76kg0d69q695",
+ "processed_at": "2026-10-09T03:09:57.777562571Z",
+ "type": "session.updated"
+ },
+ {
+ "id": "evt_00rv50pqs8kxs3nx71zl",
+ "processed_at": "2026-10-09T03:09:58.255615488Z",
+ "type": "session.status_running"
+ },
+ {
+ "agent_name": "harnessrouter live-ws1",
+ "id": "evt_00rv50pqs8kxtkwoyatw",
+ "processed_at": "2026-10-09T03:09:58.255615488Z",
+ "session_thread_id": "sthr_00rv4y7nzicqoxu769ok",
+ "type": "session.thread_status_running"
+ },
+ {
+ "content": [
+ {
+ "text": "Using the Bash shell tool, run the command: cat /data/hello.md and tell me the output verbatim. If the shell tool is not available to you, say exactly which tool is missing and what hello.md said in our earlier turn.",
+ "type": "text"
+ }
+ ],
+ "id": "evt_00rv50pocu4u9t0u09p0",
+ "processed_at": "2026-10-09T03:09:58.255615488Z",
+ "type": "user.message"
+ },
+ {
+ "id": "evt_00rv50pofc16pfdh3n0y",
+ "processed_at": "2026-10-09T03:09:58.290841397Z",
+ "type": "span.model_request_start"
+ },
+ {
+ "id": "evt_00rv50sc7x24gf0laxo5",
+ "processed_at": "2026-10-09T03:10:00.967483Z",
+ "type": "agent.thinking"
+ },
+ {
+ "content": [
+ {
+ "text": "I don't have a Bash shell tool available. My available tools are: Read, Grep, Glob, Write, Edit, WebFetch, ImageSearch, ImageGen, and DeliverArtifacts — no Bash/shell execution tool is among them.\n\nFrom our earlier turn, hello.md contained exactly:\n\n```\nHello from HarnessRouter live test.\n```",
+ "type": "text"
+ }
+ ],
+ "id": "evt_00rv50v32d6gwmddbj1u",
+ "processed_at": "2026-10-09T03:10:01.905504Z",
+ "type": "agent.message"
+ },
+ {
+ "id": "evt_00rv50wq8j1ts1zm4mzx",
+ "is_error": false,
+ "model_request_start_id": "evt_00rv50pofc16pfdh3n0y",
+ "model_usage": {
+ "credits": 0.23
+ },
+ "processed_at": "2026-10-09T03:10:01.905504Z",
+ "type": "span.model_request_end"
+ },
+ {
+ "agent_name": "harnessrouter live-ws1",
+ "id": "evt_00rv50wql0jk1wq7cmu5",
+ "processed_at": "2026-10-09T03:10:01.905504Z",
+ "session_thread_id": "sthr_00rv4y7nzicqoxu769ok",
+ "stop_reason": {
+ "type": "end_turn"
+ },
+ "type": "session.thread_status_idle"
+ },
+ {
+ "id": "evt_00rv50wr7hmo09aswreu",
+ "model_credits": 0.58,
+ "processed_at": "2026-10-09T03:10:01.905504Z",
+ "sandbox_runtime_credits": 0.03,
+ "total_credits": 0.61,
+ "type": "session.usage"
+ },
+ {
+ "id": "evt_00rv50wpek9ogpqk8hsb",
+ "processed_at": "2026-10-09T03:10:01.905504Z",
+ "stop_reason": {
+ "type": "end_turn"
+ },
+ "type": "session.status_idle"
+ }
+]
diff --git a/runner/tests/test_qoder_backend.py b/runner/tests/test_qoder_backend.py
new file mode 100644
index 00000000..c767e352
--- /dev/null
+++ b/runner/tests/test_qoder_backend.py
@@ -0,0 +1,1086 @@
+"""The qoder backend: Qoder Cloud Agent, a hosted runtime reached over REST + SSE.
+
+The first backend whose runtime is not a process the runner spawns, so what these pin is what the
+remote shape changes (docs/harness-verification.md, "remote runtimes"):
+
+ the relay route is a pass-through: a session object naming the configured model passes it and the
+ turn's served model stays EMPTY; a DELETE goes up; a stalled stream is closed, not narrated
+ a stop reaches the driver: SIGTERM, the grace, and the driver's own line about the remote cancel
+ arrives in the record before the kill
+ artifacts land in the workspace ROOT under a plain name, every declared one or the turn is
+ `incomplete`; `../x` and `.harness/x` are refused and nothing is written for them; an existing
+ file is never overwritten
+ hard holds across turns: a tool disabled between two turns of one session is withheld on the
+ second (the session's tools are replaced before the message goes)
+ continuation: the session the caller names is continued; one that is gone reports resume_lost
+ a pending confirmation is answered (allow, or deny for a disabled tool) rather than parked
+ a purge reaches every remote id the state recorded, and a delete that fails is reported, not
+ swallowed; `DELETE /workspace` runs it with the connection the gateway sends
+ the credential never reaches the driver: it holds the relay's placeholder
+
+A stub of the Managed API (runner/tests/fixtures-free, built here) answers the driver, run as the
+real subprocess it is; nothing here reaches api.qoder.com.
+"""
+import http.server
+import json
+import pathlib
+import signal
+import subprocess
+import sys
+import threading
+import time
+import urllib.request
+
+import pytest
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import qoder_driver as drv # noqa: E402
+import server as rs # noqa: E402
+
+DRIVER = str(pathlib.Path(__file__).resolve().parents[1] / "qoder_driver.py")
+
+
+# ── a stub of the Managed API ──────────────────────────────────────────────────────────────────────
+class Stub:
+ """Scripted sessions: each session's stream serves one STAGE of events per connection, then
+ closes; a `user.message` makes the session running, a `user.tool_confirmation` keeps it running
+ for the next stage, and the stage that carries an end_turn idle makes it idle."""
+
+ def __init__(self):
+ self.calls: list[tuple[str, str, dict | None, dict]] = []
+ self.n = 0
+ self.sessions: dict[str, dict] = {}
+ self.agents: dict[str, dict] = {}
+ self.blobs: dict[str, bytes] = {}
+ self.vault_creds: dict[str, list[dict]] = {} # vault id -> its credentials
+ self.env_delete_409 = False
+ self.fail_deletes = False # every DELETE of a vault/skill/file answers 500
+ self.hang_streams = False
+ self.script: list[list[dict]] = [[]] # the stages a NEW session gets
+ self.token_seen: set[str] = set()
+ self.lock = threading.Lock()
+ stub = self
+
+ class H(http.server.BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *a): # noqa: D102
+ pass
+
+ def _send(self, code: int, doc, ctype="application/json"):
+ data = json.dumps(doc).encode() if not isinstance(doc, (bytes, bytearray)) else bytes(doc)
+ self.send_response(code)
+ self.send_header("content-type", ctype)
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def _err(self, code: int, kind: str, msg: str):
+ self._send(code, {"type": "error", "request_id": "r", "error": {"type": kind, "message": msg}})
+
+ def _body(self):
+ n = int(self.headers.get("content-length") or 0)
+ raw = self.rfile.read(n) if n else b""
+ ctype = self.headers.get("content-type") or ""
+ if "json" in ctype and raw:
+ try:
+ return json.loads(raw)
+ except ValueError:
+ return {"_raw": raw.decode("utf-8", "replace")}
+ if "multipart" in ctype:
+ return {"_multipart": raw.decode("utf-8", "replace")}
+ return None
+
+ def do_GET(self): # noqa: N802
+ self._handle("GET")
+
+ def do_POST(self): # noqa: N802
+ self._handle("POST")
+
+ def do_DELETE(self): # noqa: N802
+ self._handle("DELETE")
+
+ def _handle(self, method: str):
+ path, _, query = self.path.partition("?")
+ body = self._body() if method != "GET" else None
+ hdrs = {k.lower(): v for k, v in self.headers.items()}
+ with stub.lock:
+ stub.calls.append((method, self.path, body, hdrs))
+ if path.startswith("/blob/"):
+ fid = path.split("/blob/", 1)[1]
+ if "authorization" in hdrs:
+ return self._err(400, "test", "a presigned download must carry no credential")
+ 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 ")
+ stub.token_seen.add(tok)
+ parts = [p for p in path.split("/") if p]
+ if method == "DELETE" and stub.fail_deletes and parts and parts[0] in ("vaults", "skills", "files"):
+ return self._err(500, "api_error", "storage unavailable")
+ try:
+ return self._route(method, parts, query, body)
+ except Exception as e: # noqa: BLE001
+ return self._err(500, "api_error", f"{type(e).__name__}: {e}")
+
+ def _new(self, prefix: str) -> str:
+ with stub.lock:
+ stub.n += 1
+ return f"{prefix}_{stub.n}"
+
+ def _route(self, method, parts, query, body): # noqa: C901
+ if parts == ["environments"] and method == "POST":
+ return self._send(200, {"id": self._new("env"), "type": "environment"})
+ if len(parts) == 2 and parts[0] == "environments" and method == "DELETE":
+ if stub.env_delete_409:
+ return self._err(409, "invalid_request_error", "in use; archive instead")
+ return self._send(200, {"id": parts[1], "type": "environment_deleted"})
+ if len(parts) == 3 and parts[0] == "environments" and parts[2] == "archive":
+ return self._send(200, {"id": parts[1], "archived_at": "now"})
+ if parts == ["agents"] and method == "POST":
+ aid = self._new("agent")
+ stub.agents[aid] = {"id": aid, "version": 1, **(body or {})}
+ return self._send(200, stub.agents[aid])
+ if len(parts) == 2 and parts[0] == "agents":
+ a = stub.agents.get(parts[1])
+ if not a:
+ return self._err(404, "not_found_error", "no agent")
+ if method == "GET":
+ return self._send(200, a)
+ if int((body or {}).get("version", -1)) != a["version"]:
+ return self._err(409, "conflict_error", "version")
+ a.update({k: v for k, v in (body or {}).items() if k != "version"})
+ a["version"] += 1
+ return self._send(200, a)
+ if len(parts) == 3 and parts[0] == "agents" and parts[2] == "archive":
+ return self._send(200, {"id": parts[1], "archived_at": "now"})
+ if parts == ["vaults"] and method == "POST":
+ return self._send(200, {"id": self._new("vault"), "credentials": []})
+ if len(parts) == 3 and parts[0] == "vaults" and parts[2] == "credentials":
+ # as Qoder documents it: an mcp_server_url is unique among a vault's ACTIVE credentials
+ creds = stub.vault_creds.setdefault(parts[1], [])
+ if method == "GET":
+ return self._send(200, {"data": [dict(c) for c in creds], "has_more": False})
+ url = ((body or {}).get("auth") or {}).get("mcp_server_url")
+ if any(c["mcp_server_url"] == url and not c.get("archived_at") for c in creds):
+ return self._err(409, "invalid_request_error", "an active credential exists for this server")
+ cid = self._new("vcred")
+ creds.append({"id": cid, "mcp_server_url": url, "token": ((body or {}).get("auth") or {}).get("token")})
+ return self._send(200, {"id": cid, "type": "vault_credential"})
+ if len(parts) == 5 and parts[0] == "vaults" and parts[2] == "credentials" and parts[4] == "archive":
+ for c in stub.vault_creds.get(parts[1], []):
+ if c["id"] == parts[3]:
+ c["archived_at"] = "now"
+ return self._send(200, {"id": c["id"], "archived_at": "now"})
+ return self._err(404, "not_found_error", "no credential")
+ if len(parts) == 2 and parts[0] == "vaults" and method == "DELETE":
+ return self._send(200, {"id": parts[1], "type": "vault_deleted"})
+ if parts == ["skills"] and method == "POST":
+ return self._send(201, {"id": self._new("skill"), "latest_version": "100"})
+ if len(parts) == 3 and parts[0] == "skills" and parts[2] == "versions":
+ return self._send(201, {"skill_id": parts[1], "version": "200"})
+ if len(parts) == 2 and parts[0] == "skills" and method == "DELETE":
+ return self._send(200, {"id": parts[1], "type": "skill_deleted"})
+ if parts == ["files"] and method == "POST":
+ return self._send(200, {"id": self._new("file"), "type": "file", "downloadable": False})
+ if len(parts) == 3 and parts[0] == "files" and parts[2] == "content":
+ 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"})
+ 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":
+ sid = self._new("sess")
+ stub.sessions[sid] = {"id": sid, "type": "session", "status": "idle", "archived_at": None,
+ "agent": {"id": (body or {}).get("agent", {}).get("id"), "model": {"id": "ultimate"}},
+ "usage": {"model_credits": 1.5, "sandbox_runtime_credits": 0.5, "total_credits": 2.0},
+ "stages": [list(s) for s in stub.script], "stage": 0, "events": [],
+ "resources": list((body or {}).get("resources") or [])}
+ return self._send(200, stub.sessions[sid])
+ if len(parts) >= 2 and parts[0] == "sessions":
+ s = stub.sessions.get(parts[1])
+ if not s:
+ return self._err(404, "not_found_error", f"Session '{parts[1]}' was not found.")
+ if len(parts) == 2:
+ if method == "DELETE":
+ return self._send(200, {"id": s["id"], "type": "session_deleted"})
+ if method == "POST":
+ s["updated"] = body
+ return self._send(200, {k: v for k, v in s.items() if k not in ("stages", "events")})
+ return self._send(200, {k: v for k, v in s.items() if k not in ("stages", "events")})
+ if parts[2] == "cancel":
+ s["status"] = "idle"
+ s["cancelled"] = True
+ return self._send(202, {"id": s["id"], "type": "session", "status": "canceling"})
+ if parts[2] == "resources":
+ s["resources"].append(body)
+ return self._send(200, {"id": self._new("sesr"), **(body or {})})
+ if parts[2] == "events" and len(parts) == 3 and method == "POST":
+ out = []
+ for e in (body or {}).get("events") or []:
+ eid = self._new("evt")
+ rec = {"id": eid, **e, "processed_at": "t"}
+ s["events"].append(rec)
+ out.append(rec)
+ if e.get("type") in ("user.message", "user.tool_confirmation"):
+ s["status"] = "running"
+ return self._send(200, {"data": out})
+ if parts[2] == "events" and len(parts) == 3:
+ return self._send(200, {"data": s["events"][-20:], "first_id": (s["events"][-1]["id"] if s["events"] else None),
+ "last_id": None, "has_more": False, "next_page": None})
+ if parts[2] == "events" and parts[3] == "stream":
+ return self._stream(s)
+ return self._err(404, "not_found_error", f"no route {method} {'/'.join(parts)}")
+
+ def _stream(self, s: dict):
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.send_header("transfer-encoding", "chunked")
+ self.end_headers()
+
+ def frame(eid: str, ev: str, doc: dict):
+ raw = f"id: {eid}\nevent: {ev}\ndata: {json.dumps(doc)}\n\n".encode()
+ self.wfile.write(f"{len(raw):x}\r\n".encode() + raw + b"\r\n")
+ self.wfile.flush()
+
+ if stub.hang_streams:
+ for _ in range(600):
+ raw = b"event: heartbeat\ndata: {}\n\n"
+ try:
+ self.wfile.write(f"{len(raw):x}\r\n".encode() + raw + b"\r\n")
+ self.wfile.flush()
+ except OSError:
+ return
+ time.sleep(0.1)
+ return
+ stage = s["stages"][s["stage"]] if s["stage"] < len(s["stages"]) else []
+ s["stage"] += 1
+ for ev in stage:
+ doc = dict(ev)
+ if doc.get("type") in ("event_start", "event_delta"):
+ eid = doc.get("event_id") or doc.get("event", {}).get("id") or "evt_x"
+ else:
+ eid = doc.setdefault("id", self._new("evt"))
+ s["events"].append(doc)
+ if doc.get("type") == "session.status_idle" and (doc.get("stop_reason") or {}).get("type") == "end_turn":
+ s["status"] = "idle"
+ if doc.get("type") == "session.status_terminated":
+ s["status"] = "terminated"
+ frame(eid, doc["type"], doc)
+ time.sleep(0.01)
+ self.wfile.write(b"0\r\n\r\n")
+
+ self.srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
+ threading.Thread(target=self.srv.serve_forever, daemon=True).start()
+ self.base = f"http://127.0.0.1:{self.srv.server_address[1]}"
+
+ def close(self):
+ self.srv.shutdown()
+
+ def posted(self, method: str, path: str) -> list[tuple]:
+ return [c for c in self.calls if c[0] == method and c[1].split("?", 1)[0] == path]
+
+
+def stub():
+ s = Stub()
+ yield s
+ s.close()
+
+
+IDLE = {"type": "session.status_idle", "stop_reason": {"type": "end_turn"}}
+RUNNING = {"type": "session.status_running"}
+
+
+def run_driver(job: dict, stub: Stub, timeout: float = 30.0, base: str | None = None, token: str = "placeholder"):
+ job = {"base_url": base or stub.base, "api_key": token, "model": "ultimate", **job}
+ proc = subprocess.run([sys.executable, DRIVER, json.dumps(job)], capture_output=True, text=True, timeout=timeout)
+ lines = [json.loads(ln) for ln in proc.stdout.splitlines() if ln.strip().startswith("{")]
+ return lines, proc
+
+
+def normalise(lines: list[dict]) -> tuple[list[dict], dict]:
+ state = {"model": "ultimate", "final": ""}
+ out: list[dict] = []
+ for obj in lines:
+ out += rs._qoder_to_claude(obj, state)
+ return out, state
+
+
+def result_of(events: list[dict]) -> dict:
+ return [e for e in events if e.get("type") == "result"][-1]
+
+
+# ── the turn, end to end against the stub ─────────────────────────────────────────────────────────
+def test_a_turn_with_a_tool_call_and_an_artifact(tmp_path, stub):
+ stub.blobs["file_art"] = b"hello report"
+ stub.script = [[RUNNING,
+ {"type": "event_start", "event": {"id": "evt_m1", "type": "agent.message"}},
+ {"type": "event_delta", "event_id": "evt_m1", "delta": {"type": "content_delta", "index": 0, "content": {"type": "text", "text": "Writing "}}},
+ {"type": "agent.message", "id": "evt_m1", "content": [{"type": "text", "text": "Writing the report."}]},
+ {"type": "agent.tool_use", "id": "evt_t1", "name": "Write", "input": {"file_path": "/data/report.md"}, "evaluated_permission": "allow"},
+ {"type": "agent.tool_result", "id": "evt_r1", "tool_use_id": "evt_t1", "content": [{"type": "text", "text": "ok"}], "is_error": False},
+ {"type": "agent.artifact_delivered", "file_id": "file_art", "original_filename": "report.md", "size": 12, "content_type": "text/markdown"},
+ {"type": "session.usage", "model_credits": 1.5, "sandbox_runtime_credits": 0.5, "total_credits": 2.0},
+ IDLE]]
+ lines, proc = run_driver({"cwd": str(tmp_path), "prompt": "write a report", "tools_disabled": ["Bash"],
+ "agent_doc": "Be terse."}, stub)
+ assert proc.returncode == 0, proc.stderr
+ events, state = normalise(lines)
+ res = result_of(events)
+ assert res["subtype"] == "success" and not res["is_error"], res
+ assert res["charge"] == {"amount": 2.0, "unit": "qoder_credits", "basis": "snapshot",
+ "model_credits": 1.5, "sandbox_runtime_credits": 0.5, "session_total": 2.0}
+ assert res["usage"] == {} and "model" not in res # neither is reported by the API
+ assert rs._status_from_result(res, 0) == "done"
+ texts = [c["text"] for e in events if e.get("type") == "assistant" for c in e["message"]["content"] if c["type"] == "text"]
+ assert "".join(texts) == "Writing the report." # the delta, then only the remainder
+ tools = [c for e in events if e.get("type") == "assistant" for c in e["message"]["content"] if c["type"] == "tool_use"]
+ assert tools == [{"type": "tool_use", "id": "evt_t1", "name": "Write", "input": {"file_path": "/data/report.md"}}]
+ results = [c for e in events if e.get("type") == "user" for c in e["message"]["content"]]
+ assert results == [{"type": "tool_result", "tool_use_id": "evt_t1", "is_error": False, "content": "ok"}]
+ # the artifact landed in the workspace ROOT, not under .harness/, with the declared bytes
+ assert (tmp_path / "report.md").read_bytes() == b"hello report"
+ assert not (tmp_path / ".harness" / "report.md").exists()
+ # the Agent: the disabled tool is out of the whitelist AND named disallowed; the rest always_allow
+ agent = stub.posted("POST", "/agents")[0][2]
+ ts = agent["tools"][0]
+ assert ts["type"] == "agent_toolset_20260401" and "Bash" not in ts["enabled_tools"] and ts["disallowed_tools"] == ["Bash"]
+ assert all(c["permission_policy"]["type"] == "always_allow" for c in ts["configs"] if c.get("enabled"))
+ assert {c["name"] for c in ts["configs"] if c.get("enabled") is False} == {"Bash"}
+ assert agent["system"].startswith("Be terse.") and "DeliverArtifacts" in agent["system"]
+ # the session pinned the Agent's version and the environment the turn created
+ sess = stub.posted("POST", "/sessions")[0][2]
+ assert sess["agent"] == {"id": agent_id(stub), "type": "agent", "version": 1} and sess["environment_id"].startswith("env_")
+ # the message went once, then the stream was opened from its id
+ msgs = [c for c in stub.calls if c[0] == "POST" and c[1].endswith("/events")]
+ assert len(msgs) == 1 and msgs[0][2]["events"][0]["content"] == [{"type": "text", "text": "write a report"}]
+ streams = [c for c in stub.calls if "/events/stream" in c[1]]
+ assert streams and streams[0][3].get("last-event-id", "").startswith("evt_")
+ # the state records every remote id for the next turn and for the purge
+ st = json.loads((tmp_path / ".harness" / "qoder" / "state.json").read_text())
+ assert st["session_id"].startswith("sess_") and st["agent_id"].startswith("agent_") and st["environment_id"].startswith("env_")
+ assert st["artifacts"] == ["file_art"]
+
+
+def agent_id(stub: Stub) -> str:
+ return next(iter(stub.agents))
+
+
+def test_a_declared_artifact_that_does_not_land_makes_the_turn_incomplete(tmp_path, stub):
+ stub.script = [[RUNNING,
+ {"type": "agent.message", "content": [{"type": "text", "text": "done"}]},
+ {"type": "agent.artifact_delivered", "file_id": "file_missing", "original_filename": "out.txt", "size": 3, "content_type": "text/plain"},
+ IDLE]]
+ lines, proc = run_driver({"cwd": str(tmp_path), "prompt": "x"}, stub)
+ events, _ = normalise(lines)
+ res = result_of(events)
+ assert res["subtype"] == "incomplete" and not res["is_error"]
+ assert "out.txt" in res["reason"] and rs._status_from_result(res, 0) == "incomplete"
+ assert not (tmp_path / "out.txt").exists()
+
+
[email protected]("bad", ["../x.txt", ".harness/x.txt", "sub/dir/x.txt", "..", ".env", "a\\b.txt"])
+def test_an_artifact_name_that_is_not_a_plain_file_name_is_refused(tmp_path, stub, bad):
+ stub.blobs["file_bad"] = b"evil"
+ stub.script = [[RUNNING,
+ {"type": "agent.artifact_delivered", "file_id": "file_bad", "original_filename": bad, "size": 4, "content_type": "text/plain"},
+ IDLE]]
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "x"}, stub)
+ events, _ = normalise(lines)
+ res = result_of(events)
+ assert res["subtype"] == "incomplete" and repr(bad) in res["reason"]
+ written = [p for p in tmp_path.rglob("*") if p.is_file() and "state.json" not in p.name]
+ assert written == [], written
+ assert not (tmp_path.parent / "x.txt").exists()
+ # nothing was even fetched for a refused name
+ assert not [c for c in stub.calls if c[1].startswith("/files/file_bad/content")]
+
+
+def test_an_existing_file_is_never_overwritten_and_a_symlink_is_never_followed(tmp_path):
+ (tmp_path / "report.md").write_text("mine")
+ written, note = drv.land_artifact(str(tmp_path), "report.md", b"theirs")
+ assert written == "report (2).md" and "already existed" in note
+ assert (tmp_path / "report.md").read_text() == "mine" and (tmp_path / "report (2).md").read_bytes() == b"theirs"
+ outside = tmp_path.parent / "outside.txt"
+ outside.write_text("keep")
+ (tmp_path / "link.txt").symlink_to(outside)
+ written, note = drv.land_artifact(str(tmp_path), "link.txt", b"x")
+ assert written == "link (2).txt" and "symlink" in note and outside.read_text() == "keep"
+
+
+def test_artifact_names_are_input():
+ for bad in ("../x", ".harness/x", "a/b", "a\\b", "..", ".", ".git", "", "x\x00y", "evil\n.txt"):
+ name, why = drv.artifact_name(bad)
+ assert name == "" and why, bad
+ assert drv.artifact_name("report.pdf") == ("report.pdf", "")
+ assert drv.artifact_name(" spaced name.md ") == ("spaced name.md", "")
+
+
+# ── continuation, and hard across turns ───────────────────────────────────────────────────────────
+def test_a_tool_disabled_between_two_turns_is_withheld_on_the_second(tmp_path, stub):
+ stub.script = [[RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "one"}]}, IDLE]]
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "first"}, stub)
+ sid = json.loads((tmp_path / ".harness" / "qoder" / "state.json").read_text())["session_id"]
+ stub.sessions[sid]["stages"] = [[RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "two"}]}, IDLE]]
+ stub.sessions[sid]["stage"] = 0
+ lines, proc = run_driver({"cwd": str(tmp_path), "prompt": "second", "resume_session_id": sid,
+ "tools_disabled": ["Bash", "WebFetch"]}, stub)
+ events, _ = normalise(lines)
+ assert result_of(events)["subtype"] == "success"
+ assert len(stub.posted("POST", "/sessions")) == 1, "the session was continued, not recreated"
+ # the Agent got a new version AND the session's own tools were replaced before the message
+ agent_posts = [c for c in stub.calls if c[0] == "POST" and c[1] == f"/agents/{agent_id(stub)}"]
+ assert agent_posts and "Bash" not in agent_posts[-1][2]["tools"][0]["enabled_tools"]
+ upd = stub.sessions[sid]["updated"]
+ assert upd["agent"]["tools"][0]["disallowed_tools"] == ["Bash", "WebFetch"]
+ order = [c for c in stub.calls if c[0] == "POST" and c[1] in (f"/sessions/{sid}", f"/sessions/{sid}/events")]
+ assert [c[1] for c in order][-2:] == [f"/sessions/{sid}", f"/sessions/{sid}/events"]
+ # the init event names the session the caller asked to continue
+ assert [e for e in events if e.get("subtype") == "init"][0]["session_id"] == sid
+ assert not [e for e in events if e.get("subtype") == "resume_lost"]
+
+
+def test_a_session_that_is_gone_is_reported_as_lost_and_a_new_one_is_made(tmp_path, stub):
+ stub.script = [[RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "one"}]}, IDLE]]
+ run_driver({"cwd": str(tmp_path), "prompt": "first"}, stub)
+ st = json.loads((tmp_path / ".harness" / "qoder" / "state.json").read_text())
+ stub.sessions[st["session_id"]]["archived_at"] = "2026-01-01T00:00:00Z" # archived at Qoder
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "second", "resume_session_id": st["session_id"]}, stub)
+ events, _ = normalise(lines)
+ lost = [e for e in events if e.get("subtype") == "resume_lost"]
+ assert lost == [{"type": "system", "subtype": "resume_lost", "requested_session_id": st["session_id"]}]
+ assert len(stub.posted("POST", "/sessions")) == 2
+ assert result_of(events)["subtype"] == "success"
+ # an id the state never knew is lost too, without a network call
+ stub.calls.clear()
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "third", "resume_session_id": "sess_never"}, stub)
+ events, _ = normalise(lines)
+ assert [e for e in events if e.get("subtype") == "resume_lost"]
+ assert not [c for c in stub.calls if c[1] == "/sessions/sess_never"]
+
+
+def test_a_session_still_running_an_earlier_turn_is_a_conflict_not_a_retry(tmp_path, stub):
+ stub.script = [[RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "one"}]}, IDLE]]
+ run_driver({"cwd": str(tmp_path), "prompt": "first"}, stub)
+ sid = json.loads((tmp_path / ".harness" / "qoder" / "state.json").read_text())["session_id"]
+ stub.sessions[sid]["status"] = "running"
+ stub.calls.clear()
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "second", "resume_session_id": sid}, stub)
+ events, _ = normalise(lines)
+ res = result_of(events)
+ assert res["subtype"] == "error" and "still processing" in res["result"]
+ assert not [c for c in stub.calls if c[1] == f"/sessions/{sid}/events" and c[0] == "POST"]
+
+
+# ── confirmations, status mapping ─────────────────────────────────────────────────────────────────
+def test_a_pending_confirmation_is_answered_and_the_turn_goes_on(tmp_path, stub):
+ stub.script = [[RUNNING,
+ {"type": "agent.mcp_tool_use", "id": "evt_ask1", "name": "query", "mcp_server_name": "docs", "input": {}, "evaluated_permission": "ask"},
+ {"type": "agent.mcp_tool_use", "id": "evt_ask2", "name": "delete_all", "mcp_server_name": "docs", "input": {}, "evaluated_permission": "ask"},
+ {"type": "session.status_idle", "stop_reason": {"type": "requires_action", "event_ids": ["evt_ask1", "evt_ask2"]}}],
+ [{"type": "agent.message", "content": [{"type": "text", "text": "done"}]}, IDLE]]
+ lines, proc = run_driver({"cwd": str(tmp_path), "prompt": "x", "tools_disabled": ["mcp__docs__delete_all"]}, stub)
+ events, _ = normalise(lines)
+ assert result_of(events)["subtype"] == "success", lines
+ confirms = [e for c in stub.calls if c[0] == "POST" and c[1].endswith("/events")
+ for e in (c[2] or {}).get("events", []) if e["type"] == "user.tool_confirmation"]
+ assert confirms == [{"type": "user.tool_confirmation", "tool_use_id": "evt_ask1", "result": "allow"},
+ {"type": "user.tool_confirmation", "tool_use_id": "evt_ask2", "result": "deny",
+ "deny_message": "This tool is disabled for this harness."}]
+ names = [c["name"] for e in events if e.get("type") == "assistant" for c in e["message"]["content"] if c["type"] == "tool_use"]
+ assert names == ["mcp__docs__query", "mcp__docs__delete_all"]
+
+
+def test_every_stop_reason_but_end_turn_is_incomplete_with_the_raw_reason(tmp_path, stub):
+ stub.script = [[RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "partial"}]},
+ {"type": "session.status_idle", "stop_reason": {"type": "max_steps"}}]]
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "x"}, stub)
+ events, _ = normalise(lines)
+ res = result_of(events)
+ assert res["subtype"] == "incomplete" and "max_steps" in res["reason"] and res["result"] == "partial"
+
+
+def test_a_terminal_error_fails_the_turn_with_qoders_sentence_and_a_retrying_one_is_waited_on(tmp_path, stub):
+ stub.script = [[RUNNING,
+ {"type": "session.error", "error": {"type": "model_error", "message": "upstream 503", "retry_status": {"type": "retrying"}}},
+ {"type": "session.status_rescheduled"},
+ {"type": "session.error", "error": {"type": "model_error", "message": "model unavailable", "retry_status": {"type": "exhausted"}}},
+ {"type": "session.status_idle", "stop_reason": {"type": "error"}}]]
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "x"}, stub)
+ events, _ = normalise(lines)
+ res = result_of(events)
+ assert res["subtype"] == "error" and res["result"] == "model unavailable" and rs._status_from_result(res, 0) == "failed"
+
+
+def test_a_terminated_session_fails_the_turn(tmp_path, stub):
+ stub.script = [[RUNNING, {"type": "session.status_terminated"}]]
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "x"}, stub)
+ res = result_of(normalise(lines)[0])
+ assert res["subtype"] == "error" and "terminated" in res["result"]
+
+
+def test_the_eof_names_a_driver_that_died_before_its_result():
+ state = {"_qoder_notices": ["event stream dropped (TimeoutError); resuming from evt_9"]}
+ ev = rs._qoder_eof(state, -9)[0]
+ assert ev["type"] == "result" and ev["is_error"] and "may still be running" in ev["result"]
+ assert "resuming from evt_9" in ev["result"]
+
+
+# ── the live stream's shapes ──────────────────────────────────────────────────────────────────────
+def test_the_recorded_live_session_maps_field_for_field(tmp_path, monkeypatch):
+ """fixtures/qoder/live-session-events.json is the buffered event history of a real two-turn
+ session on api.qoder.com (2026-10-09, model `efficient`, ids as Qoder issued them): a Write, a
+ DeliverArtifacts, the delivered artifact, the answer, then a second turn after the Agent was
+ updated. The driver's handler reads every field the normaliser depends on off these shapes."""
+ events = json.loads((pathlib.Path(__file__).parent / "fixtures" / "qoder" / "live-session-events.json").read_text())
+ emitted: list[dict] = []
+ monkeypatch.setattr(drv, "_emit", lambda m, p: emitted.append({"m": m, "p": p}))
+ turn = drv.Turn({"cwd": str(tmp_path), "base_url": "http://127.0.0.1:1", "api_key": "x", "prompt": "p"})
+ turn.session_id = "sess_live"
+ fetched: list[str] = []
+ monkeypatch.setattr(drv.Turn, "artifact", lambda self, doc: fetched.append(doc["file_id"]) or self.declared.append(doc))
+ first = [e for e in events[:events.index(next(e for e in events if e["type"] == "session.updated"))]]
+ done = False
+ for e in first:
+ done = turn.handle(e["id"], e["type"], json.dumps(e), "", [True]) or done
+ assert 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
+ tools = [x["p"] for x in emitted if x["m"] == "tool_use"]
+ assert tools[0]["name"] == "Write" and tools[0]["input"]["file_path"] == "/data/hello.md" and tools[0]["id"].startswith("evt_")
+ assert tools[1]["name"] == "DeliverArtifacts" and tools[1]["input"]["files"] == [{"path": "/data/hello.md"}]
+ results = [x["p"] for x in emitted if x["m"] == "tool_result"]
+ assert results[0]["tool_use_id"] == tools[0]["id"] and "successfully" in results[0]["text"] and results[0]["is_error"] is False
+ assert fetched == ["file_00rv4you3vw8wpwq624j"] and turn.declared[0]["original_filename"] == "hello.md" and turn.declared[0]["size"] == 36
+ assert turn.final.startswith("Done") and turn.stop_reason == {"type": "end_turn"}
+ # the stream's session.usage carried no sandbox charge yet (it settles after idle: GET /sessions
+ # read 0.03 and 0.38 seconds later), which is why the driver re-reads the snapshot after idle
+ # and the charge says basis: snapshot
+ assert turn.usage == {"model_credits": 0.35, "sandbox_runtime_credits": 0, "total_credits": 0.35}
+ events_, state = normalise(emitted + [{"m": "__hr_result", "p": {"status": "completed", "final": turn.final, "charge": turn.charge()}}])
+ res = result_of(events_)
+ assert res["subtype"] == "success" and res["charge"]["amount"] == 0.35 and res["charge"]["unit"] == "qoder_credits"
+ assert res["charge"]["basis"] == "snapshot"
+
+
+def test_each_turn_is_charged_what_it_added_to_the_sessions_running_total(tmp_path, monkeypatch):
+ """Qoder's session usage is the session's running total, not the turn's: the recorded live
+ session read 0.35 credits after its first turn and 0.61 after its second (model 0.35 + 0.23,
+ sandbox 0.03 settled by then). Charging the snapshot as it stands billed the first turn again on
+ the second; each turn now carries what it added, and the total beside it."""
+ events = json.loads((pathlib.Path(__file__).parent / "fixtures" / "qoder" / "live-session-events.json").read_text())
+ cut = events.index(next(e for e in events if e["type"] == "session.updated"))
+ monkeypatch.setattr(drv, "_emit", lambda m, p: emitted.append({"m": m, "p": p}))
+ monkeypatch.setattr(drv.Turn, "artifact", lambda self, doc: None)
+ charges = []
+ for part in (events[:cut], events[cut:]):
+ emitted: list[dict] = []
+ turn = 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.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]
+ assert [c["model_credits"] for c in charges] == [0.35, 0.23]
+ assert [c["sandbox_runtime_credits"] for c in charges] == [0, 0.03]
+ assert [c["session_total"] for c in charges] == [0.35, 0.61]
+ # a continuation that lost its session starts a new running total: nothing is subtracted from it
+ turn = drv.Turn({"cwd": str(tmp_path), "base_url": "http://127.0.0.1:1", "api_key": "x", "prompt": "p"})
+ turn.session_id, turn.usage = "sess_new", {"model_credits": 0.1, "sandbox_runtime_credits": 0, "total_credits": 0.1}
+ assert turn.charge()["amount"] == 0.1
+
+
+def test_a_file_written_and_not_delivered_is_asked_for_once_and_the_answer_stays_the_agents(tmp_path, stub):
+ """Measured on 0.33.0-rc.3 (model `auto`): the agent wrote the file the task asked for and
+ answered DONE without delivering it, so the person got nothing. The turn now asks the session,
+ once, to deliver what was written; that round's words are not the answer."""
+ stub.blobs["file_late"] = b"HELLO"
+ write = {"type": "agent.tool_use", "id": "evt_w", "name": "Write", "evaluated_permission": "allow",
+ "input": {"file_path": "/data/hello-qoder.txt", "content": "HELLO"}}
+ scratch = {"type": "agent.tool_use", "id": "evt_s", "name": "Write", "evaluated_permission": "allow",
+ "input": {"file_path": "/tmp/scratch.py", "content": "x"}}
+ deliver = {"type": "agent.tool_use", "id": "evt_d", "name": "DeliverArtifacts", "evaluated_permission": "allow",
+ "input": {"files": [{"path": "/data/hello-qoder.txt"}]}}
+ stub.script = [[RUNNING, write, scratch, {"type": "agent.message", "id": "evt_a", "content": [{"type": "text", "text": "DONE"}]}, IDLE],
+ [RUNNING, deliver,
+ {"type": "agent.artifact_delivered", "file_id": "file_late", "original_filename": "hello-qoder.txt", "size": 5},
+ {"type": "agent.message", "id": "evt_b", "content": [{"type": "text", "text": "DELIVERED"}]}, IDLE]]
+ lines, proc = run_driver({"cwd": str(tmp_path), "prompt": "make hello-qoder.txt, reply DONE"}, stub)
+ assert proc.returncode == 0, proc.stderr
+ res = result_of(normalise(lines)[0])
+ assert res["subtype"] == "success" and res["result"] == "DONE", res
+ assert (tmp_path / "hello-qoder.txt").read_bytes() == b"HELLO"
+ sent = [c[2]["events"][0]["content"][0]["text"] for c in stub.posted("POST", f"/sessions/{sess_id(stub)}/events")]
+ assert len(sent) == 2 and "/data/hello-qoder.txt" in sent[1] and "/tmp/scratch.py" not in sent[1]
+ texts = [x["p"]["text"] for x in (json.loads(ln) for ln in proc.stdout.splitlines() if ln.startswith("{")) if x.get("m") == "text"]
+ assert "DELIVERED" not in "".join(texts)
+
+
+def test_a_file_still_not_delivered_after_the_ask_makes_the_turn_incomplete(tmp_path, stub):
+ write = {"type": "agent.tool_use", "id": "evt_w", "name": "Write", "evaluated_permission": "allow",
+ "input": {"file_path": "/data/report.md", "content": "r"}}
+ stub.script = [[RUNNING, write, {"type": "agent.message", "content": [{"type": "text", "text": "DONE"}]}, IDLE],
+ [RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "I cannot."}]}, IDLE]]
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "x"}, stub)
+ res = result_of(normalise(lines)[0])
+ assert res["subtype"] == "incomplete" and "/data/report.md (written, never delivered)" in res["reason"], res
+ 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."""
+ 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()})
+ 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()
+
+
+# ── 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")
+ stub.script = [[RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "read"}]}, IDLE]]
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "x", "input_files": ["spec.md"]}, stub)
+ assert result_of(normalise(lines)[0])["subtype"] == "success"
+ up = stub.posted("POST", "/files")
+ assert len(up) == 1 and 'filename="spec.md"' in up[0][2]["_multipart"] and "# spec" in up[0][2]["_multipart"]
+ sess = stub.posted("POST", "/sessions")[0][2]
+ assert sess["resources"] == [{"type": "file", "file_id": "file_" + sess["resources"][0]["file_id"].split("_")[1],
+ "mount_path": "/mnt/session/uploads/spec.md"}]
+ msg = stub.posted("POST", f"/sessions/{sess_id(stub)}/events")[0][2]["events"][0]["content"][0]["text"]
+ assert "/mnt/session/uploads/spec.md" in msg and msg.endswith("x")
+ # a second turn does not upload the same bytes again
+ stub.calls.clear()
+ sid = sess_id(stub)
+ stub.sessions[sid]["stages"], stub.sessions[sid]["stage"] = [[RUNNING, IDLE]], 0
+ run_driver({"cwd": str(tmp_path), "prompt": "y", "input_files": ["spec.md"], "resume_session_id": sid}, stub)
+ assert not stub.posted("POST", "/files")
+ # a file attached on a LATER turn: the session keeps the Agent version (and the system prompt) it
+ # was created with, so the model learns of the file from the message that brought it
+ (tmp_path / "notes.txt").write_text("later")
+ stub.calls.clear()
+ stub.sessions[sid]["stages"], stub.sessions[sid]["stage"] = [[RUNNING, IDLE]], 0
+ run_driver({"cwd": str(tmp_path), "prompt": "z", "input_files": ["notes.txt"], "resume_session_id": sid}, stub)
+ mounted = [c[2] for c in stub.calls if c[0] == "POST" and c[1] == f"/sessions/{sid}/resources"]
+ assert mounted and mounted[0]["mount_path"] == "/mnt/session/uploads/notes.txt"
+ msg = stub.posted("POST", f"/sessions/{sid}/events")[0][2]["events"][0]["content"][0]["text"]
+ assert "/mnt/session/uploads/notes.txt" in msg and msg.endswith("z")
+ # a binary file: refused here, before anything is created, naming the file
+ fresh = tmp_path / "fresh"
+ fresh.mkdir()
+ (fresh / "photo.png").write_bytes(b"\x89PNG")
+ stub.calls.clear()
+ lines, _ = run_driver({"cwd": str(fresh), "prompt": "x", "input_files": ["photo.png"]}, stub)
+ res = result_of(normalise(lines)[0])
+ assert res["subtype"] == "error" and "photo.png" in res["result"] and "text-type" in res["result"]
+ assert not stub.posted("POST", "/environments")
+
+
+def sess_id(stub: Stub) -> str:
+ return next(iter(stub.sessions))
+
+
+def test_the_upload_rule_is_qoders():
+ assert drv.upload_ok("notes.md", 10) == ""
+ assert drv.upload_ok("Makefile", 10) == ""
+ assert drv.upload_ok("deck.pptx", 10) and "text-type" in drv.upload_ok("deck.pptx", 10)
+ assert "5 MB" in drv.upload_ok("big.txt", 6 * 1024 * 1024)
+
+
+# ── skills and MCP ────────────────────────────────────────────────────────────────────────────────
+def test_skills_are_published_once_by_content_and_a_stdio_server_is_declared_unavailable(tmp_path, stub):
+ sk = tmp_path / ".harness" / "skills" / "deck-maker"
+ sk.mkdir(parents=True)
+ (sk / "SKILL.md").write_text("---\nname: deck-maker\ndescription: makes decks\n---\n# Deck\n")
+ (sk / "scripts").mkdir()
+ (sk / "scripts" / "run.sh").write_text("echo hi\n")
+ bad = tmp_path / ".harness" / "skills" / "Bad Name"
+ bad.mkdir()
+ (bad / "SKILL.md").write_text("---\nname: Bad Name\ndescription: x\n---\n")
+ stub.script = [[RUNNING, {"type": "agent.message", "content": [{"type": "text", "text": "ok"}]}, IDLE]]
+ job = {"cwd": str(tmp_path), "prompt": "x",
+ "skills": [{"name": "deck-maker", "dir": str(sk)}, {"name": "Bad Name", "dir": str(bad)}],
+ "mcp_servers": [{"name": "docs", "url": "https://mcp.example/mcp", "auth": "Bearer s3cret"},
+ {"name": "local", "command": "/x/launch.sh"}]}
+ lines, _ = run_driver(job, stub)
+ events, _ = normalise(lines)
+ assert result_of(events)["subtype"] == "success"
+ pub = stub.posted("POST", "/skills")
+ assert len(pub) == 1 and 'filename="deck-maker/SKILL.md"' in pub[0][2]["_multipart"] and 'filename="deck-maker/scripts/run.sh"' in pub[0][2]["_multipart"]
+ agent = stub.posted("POST", "/agents")[0][2]
+ assert agent["skills"] == [{"type": "custom", "skill_id": "skill_" + agent["skills"][0]["skill_id"].split("_")[1], "version": "100"}]
+ assert agent["mcp_servers"] == [{"name": "docs", "type": "url", "url": "https://mcp.example/mcp"}]
+ # the bearer went into a Vault credential and the session names the vault; the token never in the Agent
+ cred = [c for c in stub.calls if c[0] == "POST" and "/credentials" in c[1]][0][2]
+ assert cred["auth"] == {"type": "static_bearer", "mcp_server_url": "https://mcp.example/mcp", "token": "s3cret"}
+ assert "s3cret" not in json.dumps(agent)
+ assert stub.posted("POST", "/sessions")[0][2]["vault_ids"]
+ unavailable = [e for e in events if e.get("subtype") == "mcp_unavailable"]
+ assert unavailable == [{"type": "system", "subtype": "mcp_unavailable", "servers": [{"name": "local"}]}]
+ # the second turn: same bytes, no new skill version; changed bytes, a new version of the same skill
+ stub.calls.clear()
+ sid = sess_id(stub)
+ stub.sessions[sid]["stages"], stub.sessions[sid]["stage"] = [[RUNNING, IDLE]], 0
+ run_driver({**job, "prompt": "y", "resume_session_id": sid}, stub)
+ assert not stub.posted("POST", "/skills")
+ (sk / "SKILL.md").write_text("---\nname: deck-maker\ndescription: makes better decks\n---\n")
+ stub.calls.clear()
+ stub.sessions[sid]["stages"], stub.sessions[sid]["stage"] = [[RUNNING, IDLE]], 0
+ run_driver({**job, "prompt": "z", "resume_session_id": sid}, stub)
+ versions = [c for c in stub.calls if c[0] == "POST" and c[1].endswith("/versions")]
+ assert len(versions) == 1 and not stub.posted("POST", "/skills")
+
+
+# ── cancellation: the stop reaches the driver and the remote turn ─────────────────────────────────
+def test_sigterm_cancels_the_remote_turn_and_the_record_says_so(tmp_path, stub):
+ stub.hang_streams = True
+ job = {"base_url": stub.base, "api_key": "placeholder", "model": "ultimate", "cwd": str(tmp_path), "prompt": "long"}
+ proc = subprocess.Popen([sys.executable, DRIVER, json.dumps(job)], stdout=subprocess.PIPE, text=True)
+ deadline = time.monotonic() + 20
+ while time.monotonic() < deadline and not [c for c in stub.calls if "/events/stream" in c[1]]:
+ time.sleep(0.05)
+ time.sleep(0.3)
+ proc.send_signal(signal.SIGTERM)
+ out, _ = proc.communicate(timeout=15)
+ lines = [json.loads(ln) for ln in out.splitlines() if ln.startswith("{")]
+ sid = sess_id(stub)
+ assert stub.sessions[sid].get("cancelled") is True
+ notices = [l["p"]["text"] for l in lines if l["m"] == "notice"]
+ assert any(f"cancel accepted by Qoder for session {sid}" in n for n in notices)
+ res = [l for l in lines if l["m"] == "__hr_result"][-1]["p"]
+ assert res["status"] == "cancelled" and sid in res["reason"]
+ assert proc.returncode == 0
+
+
+def test_a_remote_backends_stop_is_a_sigterm_with_a_grace_before_the_kill(tmp_path, monkeypatch):
+ """The runner's own path: _stop_proc on a `remote` backend sends SIGTERM first and keeps reading
+ stdout through the grace, so the driver's last line is in the record; a local backend is killed
+ at once. The child here stands in for the driver: it prints a line on SIGTERM and exits."""
+ child = ("import signal, sys, time, json\n"
+ "def h(*a):\n"
+ " print(json.dumps({'m': 'notice', 'p': {'text': 'cancel accepted by Qoder for session sess_1'}}), flush=True)\n"
+ " print(json.dumps({'m': '__hr_result', 'p': {'status': 'cancelled', 'reason': 'cancel accepted', 'final': ''}}), flush=True)\n"
+ " sys.exit(0)\n"
+ "signal.signal(signal.SIGTERM, h)\n"
+ "print(json.dumps({'m': 'session', 'p': {'session_id': 'sess_1'}}), flush=True)\n"
+ "time.sleep(30)\n")
+ rec = {"status": "running", "events": [], "result": "", "done": False, "started": time.time(),
+ "backend": "qoder", "model": "ultimate"}
+ monkeypatch.setitem(rs._turns, "tq", rec)
+ t = threading.Thread(target=rs._run_turn_bg, args=("tq", [sys.executable, "-c", child], {}, str(tmp_path),
+ rs._qoder_to_claude, "ultimate", 60))
+ t.start()
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline and not rec.get("proc"):
+ time.sleep(0.02)
+ while time.monotonic() < deadline and not rec["events"]:
+ time.sleep(0.02)
+ out = rs.cancel_turn("tq")
+ assert out["cancelled"] is True
+ t.join(timeout=15)
+ assert rec["done"] and rec["status"] == "cancelled"
+ res = [e for e in rec["events"] if e.get("type") == "result"]
+ assert res and res[-1]["result"] == "cancel accepted", rec["events"] # the handler's line reached the record
+ assert rec["exit_code"] == 0 # SIGTERM, handled; not SIGKILL's -9
+ # a local backend's stop is the kill it always was
+ local = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"], start_new_session=True)
+ rs._stop_proc(local, {"backend": "claude", "turn_id": ""})
+ assert local.wait(timeout=5) == -signal.SIGKILL
+
+
+# ── the relay route ───────────────────────────────────────────────────────────────────────────────
+def test_the_qoder_route_passes_through_and_records_no_served_model(stub):
+ stub.script = []
+ base, tok = rs._qoder_relay_route(stub.base, "real-pat")
+ try:
+ assert tok.startswith("hr-relay-") and base.endswith("/v1")
+ # create a session through the relay: its object names the configured model
+ req = urllib.request.Request(base + "/sessions", data=json.dumps({"agent": {"id": "agent_x"}, "environment_id": "env_x"}).encode(),
+ method="POST", headers={"authorization": f"Bearer {tok}", "content-type": "application/json"})
+ with urllib.request.urlopen(req, timeout=10) as r:
+ doc = json.loads(r.read())
+ assert doc["agent"]["model"] == {"id": "ultimate"}
+ req = urllib.request.Request(base + f"/sessions/{doc['id']}", headers={"authorization": f"Bearer {tok}"})
+ with urllib.request.urlopen(req, timeout=10) as r:
+ assert b'"model"' in r.read()
+ assert rs._relay_served_model({"QODER_API_KEY": tok}) == "" # the tap is off on this route
+ assert rs._relay_usage({"QODER_API_KEY": tok}) == {} and rs._relay_last_finish({"QODER_API_KEY": tok}) == ""
+ # the stub saw the real credential; the client only ever held the placeholder
+ assert "real-pat" in stub.token_seen and tok not in stub.token_seen
+ # DELETE goes up
+ req = urllib.request.Request(base + f"/sessions/{doc['id']}", method="DELETE", headers={"authorization": f"Bearer {tok}"})
+ with urllib.request.urlopen(req, timeout=10) as r:
+ assert json.loads(r.read())["type"] == "session_deleted"
+ assert [c for c in stub.calls if c[0] == "DELETE"]
+ # a 4xx comes down as the API wrote it
+ req = urllib.request.Request(base + "/sessions/sess_nope", headers={"authorization": f"Bearer {tok}"})
+ try:
+ urllib.request.urlopen(req, timeout=10)
+ assert False, "a 404 must come through"
+ except urllib.error.HTTPError as e:
+ assert e.code == 404 and json.loads(e.read())["error"]["type"] == "not_found_error"
+ finally:
+ rs._HERMES_RELAY["routes"].pop(tok, None)
+
+
+def test_a_stalled_passthrough_stream_is_closed_not_narrated(monkeypatch):
+ """A long remote tool step can be silent past the relay's wait. On a model route the relay
+ writes an error event into the stream; on this one the connection simply closes, so the
+ driver resumes from its last event id instead of reading an error the API never sent."""
+ class H(http.server.BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *a): # noqa: D102
+ pass
+
+ def do_GET(self): # noqa: N802
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.send_header("transfer-encoding", "chunked")
+ self.end_headers()
+ raw = b'id: evt_1\nevent: agent.message\ndata: {"type":"agent.message","id":"evt_1","content":[]}\n\n'
+ self.wfile.write(f"{len(raw):x}\r\n".encode() + raw + b"\r\n")
+ self.wfile.flush()
+ time.sleep(3)
+ try:
+ self.wfile.write(b"0\r\n\r\n")
+ except OSError:
+ pass
+
+ srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ monkeypatch.setattr(rs, "HR_RELAY_UPSTREAM_TIMEOUT_S", 1.0)
+ base, tok = rs._qoder_relay_route(f"http://127.0.0.1:{srv.server_address[1]}", "k")
+ try:
+ req = urllib.request.Request(base + "/sessions/s/events/stream", headers={"authorization": f"Bearer {tok}"})
+ got = b""
+ try:
+ with urllib.request.urlopen(req, timeout=10) as r:
+ while True:
+ chunk = r.read1(4096)
+ if not chunk:
+ break
+ got += chunk
+ except (http.client.HTTPException, OSError):
+ pass # the close is the point
+ assert b"evt_1" in got
+ assert b"upstream_unavailable" not in got and b"error" not in got.lower().replace(b"agent.message", b"")
+ finally:
+ rs._HERMES_RELAY["routes"].pop(tok, None)
+ srv.shutdown()
+
+
+# ── the builder ───────────────────────────────────────────────────────────────────────────────────
+def test_the_builder_hands_the_driver_the_relay_and_a_placeholder_never_the_key(tmp_path):
+ env: dict = {}
+ auth = rs.Auth(api_key="pat-secret")
+ cmd = rs._build_qoder("qoder", auth, "ultimate", "hi", str(tmp_path), env, resume_session_id="sess_9",
+ tools_disabled=["Bash"], agent_doc="Rules.", input_files=["a.md"],
+ skills=[{"name": "s", "dir": "/x/s"}])
+ tok = None
+ try:
+ assert cmd[0] == rs.QODER_PYTHON and cmd[1] == rs.QODER_DRIVER
+ job = json.loads(cmd[2])
+ tok = job["api_key"]
+ assert tok.startswith("hr-relay-") and "pat-secret" not in cmd[2] and "pat-secret" not in json.dumps(env)
+ assert job["base_url"].startswith("http://127.0.0.1:") and job["base_url"].endswith("/v1")
+ assert rs._HERMES_RELAY["routes"][tok][0] == rs.QODER_DEFAULT_BASE and rs._HERMES_RELAY["routes"][tok][1] == "pat-secret"
+ assert rs._HERMES_RELAY["routes"][tok][2].get("passthrough") is True
+ assert job["resume_session_id"] == "sess_9" and job["tools_disabled"] == ["Bash"] and job["agent_doc"] == "Rules."
+ assert job["input_files"] == ["a.md"] and job["skills"] == [{"name": "s", "dir": "/x/s"}]
+ assert env["QODER_API_KEY"] == tok
+ finally:
+ if tok:
+ rs._HERMES_RELAY["routes"].pop(tok, None)
+ with pytest.raises(rs.HTTPException):
+ rs._build_qoder("qoder", rs.Auth(), "ultimate", "hi", str(tmp_path), {}) # no PAT
+ with pytest.raises(rs.HTTPException):
+ rs._build_qoder("openai", auth, "ultimate", "hi", str(tmp_path), {}) # not a provider of this base
+
+
+def test_the_registration_points():
+ assert rs.BACKENDS["qoder"]["remote"] is True and rs.BACKENDS["qoder"]["normalize"] is rs._qoder_to_claude
+ assert rs.BACKENDS["qoder"]["providers"] == ["qoder"]
+ assert rs.QODER_TOOLS == drv.TOOLS
+ assert rs.QODER_EFFORTS == drv.EFFORTS
+ assert rs._SESSION_PRESENT.get("qoder") is None # the driver itself reports a lost session
+ assert not any(b.get("remote") for k, b in rs.BACKENDS.items() if k != "qoder")
+
+
+def test_no_agent_doc_is_written_and_skills_are_staged_under_harness(tmp_path):
+ rs._write_agent_doc(str(tmp_path), "qoder", "Rules.", [])
+ assert not list(tmp_path.iterdir()), "this backend reads no workspace file"
+ installed = rs._write_skills(str(tmp_path), [{"name": "deck", "files": [{"path": "SKILL.md", "content": "---\nname: deck\ndescription: d\n---\n"}]}], "qoder")
+ assert installed and installed[0]["entry"].startswith(".harness/skills/deck/")
+ assert (tmp_path / ".harness" / "skills" / "deck" / "SKILL.md").is_file()
+
+
+# ── the purge ─────────────────────────────────────────────────────────────────────────────────────
+def write_state(ws: pathlib.Path, **extra) -> dict:
+ st = {"environment_id": "env_1", "agent_id": "agent_1", "agent_version": 2, "session_id": "sess_1",
+ "sessions": ["sess_1"], "vault_id": "vault_1", "skills": {"deck": {"id": "skill_1", "sha": "x", "version": "1"}},
+ "files": {"spec.md": {"id": "file_in", "sha": "y", "mounted": ["sess_1"]}}, "artifacts": ["file_art"], **extra}
+ (ws / ".harness" / "qoder").mkdir(parents=True, exist_ok=True)
+ (ws / ".harness" / "qoder" / "state.json").write_text(json.dumps(st))
+ return st
+
+
+def test_the_purge_reaches_every_recorded_id_and_reports_what_it_could_not(tmp_path, stub):
+ stub.sessions["sess_1"] = {"id": "sess_1", "status": "idle", "archived_at": None, "stages": [], "stage": 0, "events": [], "resources": []}
+ stub.agents["agent_1"] = {"id": "agent_1", "version": 2}
+ write_state(tmp_path)
+ lines, proc = run_driver({"purge": True, "cwd": str(tmp_path)}, stub)
+ assert proc.returncode == 0
+ report = [l for l in lines if l["m"] == "purge"][-1]["p"]
+ assert report["failed"] == []
+ seen = [(c[0], c[1]) for c in stub.calls]
+ for want in (("POST", "/sessions/sess_1/cancel"), ("DELETE", "/sessions/sess_1"), ("DELETE", "/files/file_art"),
+ ("DELETE", "/files/file_in"), ("POST", "/agents/agent_1/archive"), ("DELETE", "/vaults/vault_1"),
+ ("DELETE", "/skills/skill_1"), ("DELETE", "/environments/env_1")):
+ assert want in seen, want
+ assert seen.index(("DELETE", "/sessions/sess_1")) < seen.index(("DELETE", "/files/file_in")) # the session first
+ # an environment still referenced is archived, as the API says to
+ stub.calls.clear()
+ stub.env_delete_409 = True
+ lines, proc = run_driver({"purge": True, "cwd": str(tmp_path)}, stub)
+ assert ("POST", "/environments/env_1/archive") in [(c[0], c[1]) for c in stub.calls]
+ assert [l for l in lines if l["m"] == "purge"][-1]["p"]["failed"] == []
+ # an object already gone is not a failure; a delete the API refuses is reported with its id,
+ # and the exit says so
+ stub.env_delete_409 = False
+ stub.sessions.pop("sess_1")
+ stub.agents.pop("agent_1")
+ stub.fail_deletes = True
+ stub.calls.clear()
+ lines, proc = run_driver({"purge": True, "cwd": str(tmp_path)}, stub)
+ report = [l for l in lines if l["m"] == "purge"][-1]["p"]
+ assert proc.returncode == 1 and report["failed"]
+ assert any(f["what"] == "delete vault vault_1" and "500" in f["error"] for f in report["failed"]), report
+ assert "delete session sess_1 (already gone)" in report["done"]
+
+
+def test_delete_workspace_purges_at_qoder_with_the_connection_it_is_sent(tmp_path, stub, monkeypatch):
+ import asyncio
+ root = tmp_path / "root"
+ root.mkdir()
+ monkeypatch.setattr(rs, "WORKSPACE_ROOT", str(root))
+ monkeypatch.setattr(rs, "_SANDBOX_PER_SESSION", False)
+ sid = "hsessqoder0123456789abcdef0123456789"
+ ws = pathlib.Path(rs._ws(sid))
+ ws.mkdir(parents=True)
+ stub.sessions["sess_1"] = {"id": "sess_1", "status": "idle", "archived_at": None, "stages": [], "stage": 0, "events": [], "resources": []}
+ stub.agents["agent_1"] = {"id": "agent_1", "version": 2}
+ write_state(ws)
+ out = asyncio.run(rs.delete_workspace(sid, rs.WorkspaceDelete(auth=rs.Auth(api_key="real-pat", base_url=stub.base))))
+ assert out["removed"] is True and out["remote"]["purged"] is True and not ws.exists()
+ assert ("DELETE", "/sessions/sess_1") in [(c[0], c[1]) for c in stub.calls]
+ assert "real-pat" in stub.token_seen # through the relay: the credential stayed in the runner
+ # without a credential the folder still goes, and the answer says what was left at Qoder
+ ws.mkdir(parents=True)
+ write_state(ws)
+ out = asyncio.run(rs.delete_workspace(sid))
+ assert out["removed"] is True and out["remote"] == {"backend": "qoder", "purged": False, "reason": "no credential",
+ "state": rs.QODER_STATE_REL}
+ # a session with no remote state answers as before
+ ws.mkdir(parents=True)
+ out = asyncio.run(rs.delete_workspace(sid))
+ assert out["removed"] is True and "remote" not in out
+
+
+# ── review fixes (2026-10-09) ─────────────────────────────────────────────────────────────────────
+def test_a_changed_mcp_token_replaces_the_vault_credential_and_no_token_is_kept(tmp_path, stub):
+ """The gateway mints a per-turn credential for a server it hosts, and keys rotate: a vault that
+ kept the first turn's token failed that server on every later turn. An unchanged token is not
+ sent again; a changed one archives the old credential and creates the new one."""
+ stub.script = [[RUNNING, IDLE]]
+ job = {"cwd": str(tmp_path), "prompt": "x",
+ "mcp_servers": [{"name": "db", "url": "https://hr.example/v1/mcp/database", "auth": "tok-1"}]}
+ run_driver(job, stub)
+ sid = sess_id(stub)
+ vid = stub.posted("POST", "/sessions")[0][2]["vault_ids"][0]
+
+ def again(token):
+ stub.calls.clear()
+ stub.sessions[sid]["stages"], stub.sessions[sid]["stage"] = [[RUNNING, IDLE]], 0
+ lines, _ = run_driver({**job, "prompt": "y", "resume_session_id": sid,
+ "mcp_servers": [{**job["mcp_servers"][0], "auth": token}]}, stub)
+ return result_of(normalise(lines)[0])
+
+ assert again("tok-1")["subtype"] == "success"
+ assert not [c for c in stub.calls if "/credentials" in c[1]] # same token: nothing sent
+ assert again("tok-2")["subtype"] == "success"
+ active = [c for c in stub.vault_creds[vid] if not c.get("archived_at")]
+ assert [c["token"] for c in active] == ["tok-2"] and len(stub.vault_creds[vid]) == 2
+ state = (tmp_path / ".harness" / "qoder" / "state.json").read_text()
+ assert "tok-1" not in state and "tok-2" not in state # a hash, never the token
+
+
+def test_an_active_credential_the_state_does_not_know_is_archived_and_made_anew(tmp_path, stub):
+ stub.script = [[RUNNING, IDLE]]
+ job = {"cwd": str(tmp_path), "prompt": "x", "mcp_servers": [{"name": "docs", "url": "https://mcp.example/mcp", "auth": "a"}]}
+ run_driver(job, stub)
+ sid = sess_id(stub)
+ st_path = tmp_path / ".harness" / "qoder" / "state.json"
+ st = json.loads(st_path.read_text())
+ st.pop("vault_creds") # e.g. a driver killed between the create and the save
+ st_path.write_text(json.dumps(st))
+ stub.sessions[sid]["stages"], stub.sessions[sid]["stage"] = [[RUNNING, IDLE]], 0
+ lines, _ = run_driver({**job, "prompt": "y", "resume_session_id": sid,
+ "mcp_servers": [{**job["mcp_servers"][0], "auth": "b"}]}, stub)
+ assert result_of(normalise(lines)[0])["subtype"] == "success"
+ vid = st["vault_id"]
+ assert [c["token"] for c in stub.vault_creds[vid] if not c.get("archived_at")] == ["b"]
+
+
+def test_a_model_route_does_not_forward_delete(stub):
+ """DELETE through the relay is a remote runtime's alone: a sandbox must not delete what an org's
+ provider key owns (files, fine-tunes) through the relay that holds the key."""
+ base, tok = rs._hermes_relay_route(stub.base + "/v1", "sk-real")
+ try:
+ req = urllib.request.Request(base + "/files/file_1", method="DELETE", headers={"authorization": f"Bearer {tok}"})
+ try:
+ urllib.request.urlopen(req, timeout=10)
+ assert False, "a DELETE on a model route must be refused"
+ except urllib.error.HTTPError as e:
+ assert e.code == 405
+ assert not [c for c in stub.calls if c[0] == "DELETE"]
+ finally:
+ rs._HERMES_RELAY["routes"].pop(tok, None)
+
+
+def test_an_artifact_over_the_limit_or_unwritable_fails_with_its_reason(tmp_path, stub, monkeypatch):
+ monkeypatch.setenv("HR_QODER_ARTIFACT_MAX_BYTES", "8")
+ stub.blobs["file_big"] = b"0123456789"
+ stub.blobs["file_ok"] = b"tiny"
+ stub.script = [[RUNNING,
+ {"type": "agent.artifact_delivered", "file_id": "file_big", "original_filename": "big.bin", "size": 10},
+ {"type": "agent.artifact_delivered", "file_id": "file_ok", "original_filename": "ok.txt", "size": 4},
+ IDLE]]
+ lines, _ = run_driver({"cwd": str(tmp_path), "prompt": "x"}, stub)
+ res = result_of(normalise(lines)[0])
+ assert res["subtype"] == "incomplete" and "big.bin" in res["reason"] and "limit" in res["reason"]
+ assert (tmp_path / "ok.txt").read_bytes() == b"tiny" and not (tmp_path / "big.bin").exists()
+ assert not list((tmp_path / ".harness" / "qoder").glob("*.part")) # no download left behind
+ # a workspace the file cannot be written to: that artifact fails with the reason; the turn goes on
+ monkeypatch.delenv("HR_QODER_ARTIFACT_MAX_BYTES")
+ ro = tmp_path / "ro"
+ (ro / ".harness" / "qoder").mkdir(parents=True)
+ ro.chmod(0o555)
+ try:
+ stub.script = [[RUNNING, {"type": "agent.artifact_delivered", "file_id": "file_ok", "original_filename": "ok.txt", "size": 4},
+ {"type": "agent.message", "content": [{"type": "text", "text": "done"}]}, IDLE]]
+ lines, _ = run_driver({"cwd": str(ro), "prompt": "x"}, stub)
+ res = result_of(normalise(lines)[0])
+ assert res["subtype"] == "incomplete" and "could not be written" in res["reason"], res
+ assert not [ln for ln in lines if ln.get("m") == "notice" and "dropped" in str(ln.get("p"))]
+ finally:
+ ro.chmod(0o755)
+
+
+def test_a_long_artifact_name_is_cut_by_bytes_keeping_its_extension():
+ name, why = drv.artifact_name("é" * 200 + ".pdf")
+ assert not why and name.endswith(".pdf") and len(name.encode("utf-8")) <= 240
diff --git a/scripts/support-matrix/custom-harness.mjs b/scripts/support-matrix/custom-harness.mjs
index c177398d..0e61012a 100644
--- a/scripts/support-matrix/custom-harness.mjs
+++ b/scripts/support-matrix/custom-harness.mjs
@@ -14,7 +14,7 @@ import { chromium } from 'playwright';
import crypto from 'node:crypto';
const BASE = process.env.BASE;
-const BASES = (process.env.BASES || 'codex,claude-code,hermes,pi,dsh,opencode,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,cheetahclaws,agentzero,mimo,jcode,opensquilla,nanobot').split(','); // every built-in chat harness, all nineteen (systemone runs decision models only)
+const BASES = (process.env.BASES || 'codex,claude-code,hermes,pi,dsh,opencode,kilo,qwen,gemini,cline,omp,goose,kimi,minimax,grok,aider,openhands,cheetahclaws,agentzero,mimo,jcode,opensquilla,nanobot,qoder').split(','); // every built-in chat harness, all nineteen (systemone runs decision models only)
const RESULTS = process.env.RESULTS || 'results-custom.json';
// A harness's other kind of tool is an MCP server. A self-contained instance hosts only the
// database and media servers, one needing a database and the other costing real money per call, so
diff --git a/ui/public/logos/qoder.png b/ui/public/logos/qoder.png
new file mode 100644
index 00000000..98452e46
Binary files /dev/null and b/ui/public/logos/qoder.png differ
diff --git a/ui/src/components/HarnessLogo.tsx b/ui/src/components/HarnessLogo.tsx
index 9eca4f88..10e33c28 100644
--- a/ui/src/components/HarnessLogo.tsx
+++ b/ui/src/components/HarnessLogo.tsx
@@ -25,6 +25,7 @@ const LOGO: Record<string, string> = {
grok: '/logos/grok.png', // Grok's own app icon (grok.com/icon-512x512.png, scaled to 192 px)
agentzero: '/logos/agentzero.png', // Agent Zero's own mark (docs/res/favicon_round.png in the MIT agent0ai/agent-zero repository, scaled to 192 px)
systemone: '/logos/systemone.png', // the System One Harness's own mark (the project has no vendor logo; Jev is TypeSafe's model, not the harness)
+ qoder: '/logos/qoder.png', // Qoder's own app icon (the apple-touch icon qoder.com serves, 412 px, scaled to 192 px)
jcode: '/logos/jcode.png', // jcode's own app icon (assets/app-icons/Jcode.icns in the MIT 1jehuang/jcode repository), the 1024 px face resized. It is a BLACK mark on transparency, so it carries no contrast on a dark surface — upstream ships no light variant
opensquilla: '/logos/opensquilla.png', // the OpenSquilla mark (assets/opensquilla-mark.png in the Apache-2.0 TokenRhythm/opensquilla repository), already square
nanobot: '/logos/nanobot.svg', // the nanobot mark (images/nanobot_mark.svg in the MIT HKUDS/nanobot repository); an SVG like cursor.svg, which this map already serves
diff --git a/ui/src/components/HarnessSettings.tsx b/ui/src/components/HarnessSettings.tsx
index c4ca92d4..1e3d789e 100644
--- a/ui/src/components/HarnessSettings.tsx
+++ b/ui/src/components/HarnessSettings.tsx
@@ -256,6 +256,9 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {
// Built-ins the harness has not replaced with one of its own. A built-in is implicit: the
// harness stores an entry only when its answer differs from the image's default.
const takesSkills = srvBase?.takesSkills !== false;
+ // A base whose runtime is elsewhere (Qoder Cloud Agent) cannot open an environment: a Task that
+ // names one is refused, so none is offered, and one already chosen can only be cleared.
+ const takesEnvironments = srvBase?.takesEnvironments !== false;
const baseSkills = (takesSkills ? (srvBase?.builtinSkills || []) : []).filter((b) => !ownSkills.some(({ s }) => s.name === b.name));
const disabledTools = new Set(draft?.disabledTools || []);
@@ -608,16 +611,17 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {
<div><h3>Workspace</h3><p>Project files and packages every Task opens in.</p></div>
<div className="field-stack">
<div className="field"><label>Environment</label>
- <select value={draft?.environment || ''} disabled={readOnly || environments === null} onChange={(e) => upd({ environment: e.target.value })}>
+ <select value={draft?.environment || ''} disabled={readOnly || environments === null || (!takesEnvironments && !draft?.environment)} onChange={(e) => upd({ environment: e.target.value })}>
<option value="">None</option>
- {(environments || []).map((en) => <option key={en.id} value={en.id}>{en.name}</option>)}
+ {(takesEnvironments || draft?.environment) && (environments || []).map((en) => <option key={en.id} value={en.id}>{en.name}</option>)}
</select></div>
- {draft?.environment && (() => { const en = (environments || []).find((x) => x.id === draft.environment); return en ? (
+ {!takesEnvironments && <span className="field-help">{base?.name || 'This base'} runs in its own cloud, so its Tasks cannot open an environment.{draft?.environment ? ' Choose None, or every Task on this Harness is refused.' : ''}</span>}
+ {takesEnvironments && draft?.environment && (() => { const en = (environments || []).find((x) => x.id === draft.environment); return en ? (
<span className="field-help">{en.status === 'ready'
? <>Every Task reads <code>{en.mount}</code> (version {en.version}) and its {en.packages.length} installed {en.packages.length === 1 ? 'package' : 'packages'}. <a href={`/environments/${en.id}`}>Open the environment</a>.</>
: <>This environment has no built version yet, so Tasks on this Harness are refused until it is built. <a href={`/environments/${en.id}`}>Build it</a>.</>}</span>
) : <span className="field-help">This environment is no longer there; choose another or none.</span>; })()}
- {!draft?.environment && <span className="field-help">{environments && environments.length === 0 ? <>No environments yet. <a href="/environments">Create one</a> to give Tasks a ready project.</> : 'Tasks start from an empty workspace.'}</span>}
+ {takesEnvironments && !draft?.environment && <span className="field-help">{environments && environments.length === 0 ? <>No environments yet. <a href="/environments">Create one</a> to give Tasks a ready project.</> : 'Tasks start from an empty workspace.'}</span>}
</div>
</section>
diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.ts
index 85d4c916..5322fa0a 100644
--- a/ui/src/lib/harness.ts
+++ b/ui/src/lib/harness.ts
@@ -20,7 +20,7 @@ export interface OobHarness {
defaultModel?: string; // the backend default, NOT necessarily models[0]
moreModels?: number; // "+N" pill
status: 'ready' | 'soon';
- backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'kilo' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | 'minimax' | 'aider' | 'openhands' | 'grok' | 'systemone' | 'cheetahclaws' | 'agentzero' | 'mimo' | 'jcode' | 'opensquilla' | 'nanobot' | null; // gateway backend; null = coming soon
+ backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'kilo' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | 'minimax' | 'aider' | 'openhands' | 'grok' | 'systemone' | 'cheetahclaws' | 'agentzero' | 'mimo' | 'jcode' | 'opensquilla' | 'nanobot' | 'qoder' | null; // gateway backend; null = coming soon
systemPrompt: string; // the harness's built-in system prompt (shown read-only)
tools: string[]; // built-in tools (read-only)
skills: string[]; // built-in skills (read-only)
@@ -215,6 +215,13 @@ export const OOB: OobHarness[] = [
models: ['jev-latest', 'jev-preview', 'jev-1.13', 'laya', 'openthai-systemone', 'system-one-phase2'], defaultModel: 'jev-latest', moreModels: 0,
systemPrompt: 'You act inside a finite set of actions the environment offers each step. Choose the action that moves the goal forward, finish when the goal is reached, and escalate when nothing offered fits.',
tools: [], skills: [] },
+ { id: 'qoder', name: 'Qoder Cloud Agent', version: 'Managed API', backend: 'qoder', status: 'ready',
+ // Placeholder only: the gateway's catalog wins once fetched. Qoder's own model ids, as its
+ // GET /models lists them for the tenant; the runtime is Qoder's cloud, not a process on this
+ // box, and Qoder picks and bills the model behind an id.
+ models: ['auto', 'ultimate', 'performance', 'efficient', 'smodel', 'qmodel_38max', 'qfmodel', 'qmodel_latest', 'qmodel', 'kmodel_latest', 'kmodel', 'gmodel', 'gfmodel', 'dmodel', 'dfmodel', 'mmodel'], defaultModel: 'ultimate', moreModels: 0,
+ systemPrompt: 'You are Qoder, an autonomous coding agent running in a cloud sandbox with shell and file access. Read, edit and run what the task needs, and deliver every file the user should receive with DeliverArtifacts.',
+ tools: ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'WebFetch', 'WebSearch', 'ImageSearch', 'ImageGen', 'DeliverArtifacts'], skills: [] },
{ id: 'mimo', name: 'MiMo Code', version: 'v0.1.15', backend: 'mimo', status: 'ready',
// Placeholder only, like every list above: the gateway's catalog wins once fetched. MiMo Code is
// an opencode fork and reaches what opencode reaches, so the list is opencode's.
@@ -249,12 +256,14 @@ export const oobById = (id: string) => OOB.find((o) => o.id === id) || null;
// gateway/tests/test_instruction_file_label.py now holds this map to the runner's function, so the
// next base that chooses its own name cannot drift the same way.
//
-// systemone is the one base with no file at all: it reads no workspace and its instructions travel
-// in the job, so the page calls the box "Instructions".
+// systemone and qoder have no file at all: systemone reads no workspace and its instructions travel
+// in the job, and qoder's travel with the hosted session it drives, so the page calls the box
+// "Instructions".
export const INSTRUCTION_FILE: Record<string, string> = {
qwen: 'QWEN.md',
gemini: 'GEMINI.md',
systemone: 'Instructions',
+ qoder: 'Instructions',
};
const AGENTS_MD_BASES = [
'codex', 'hermes', 'omp', 'pi', 'opencode', 'kilo', 'dsh', 'qwen', 'cline', 'goose', 'kimi',
@@ -375,6 +384,10 @@ export interface BaseInfo {
* offered actions and reads no documents), so none are offered and none can be added. Absent
* on older gateways, which is the same as true. */
takesSkills?: boolean;
+ /** false means a Task on this base cannot open an environment (Qoder Cloud Agent runs in its own
+ * cloud, and the layer is mounted on this box only), so none is offered. Absent on older
+ * gateways, which is the same as true. */
+ takesEnvironments?: boolean;
}
let _bases: Record<string, BaseInfo> | null = null;