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.

Environments: a project's files and dependencies, built once, read-only in every session that names it (UHP 2026-09-28) (#321)

github-actions[bot]8acddcfcb900
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 478f17b8..0e5923c9 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -40,6 +40,27 @@ mkdir -p "$HARNESS_WORKSPACE"
# by their session's uid (0700); the runner sets that as it allocates them.
chown "$PRODUCT:$PRODUCT" "$DATA_DIR" "$HARNESS_WORKSPACE"
chmod 751 "$DATA_DIR" "$HARNESS_WORKSPACE" # traversable by sessions, neither listable nor writable
+# Environments (runner/environments.py): project layers built once and read by every session that
+# names one. Root's, readable by every session uid, writable by none: that ownership is the
+# read-only guarantee, so nothing here is handed to $PRODUCT. /env holds the links sessions are told.
+export HR_ENV_ROOT="${HR_ENV_ROOT:-$DATA_DIR/environments}"
+mkdir -p "$HR_ENV_ROOT" /env
+chmod 755 "$HR_ENV_ROOT" /env
+# A login shell (`bash -lc`, which codex uses for its commands) runs /etc/profile, and Debian's
+# sets PATH from scratch, which dropped the environment's venv and node_modules/.bin that the runner
+# had put first (measured on 0.26.0-rc.1: `python3` was /usr/local's, not the venv's). The runner
+# names the environment in HR_ENVIRONMENT, which a login shell keeps; this profile drop-in puts the
+# environment back at the head of PATH after /etc/profile has had its say.
+mkdir -p /etc/profile.d
+cat > /etc/profile.d/hr-environment.sh <<'PROFILE'
+# HarnessRouter: the task's environment (runner/environments.py) stays first on PATH in login shells.
+if [ -n "$HR_ENVIRONMENT" ]; then
+ [ -d "$HR_ENVIRONMENT/node_modules/.bin" ] && PATH="$HR_ENVIRONMENT/node_modules/.bin:$PATH"
+ [ -d "$HR_ENVIRONMENT/.venv/bin" ] && PATH="$HR_ENVIRONMENT/.venv/bin:$PATH" && export VIRTUAL_ENV="$HR_ENVIRONMENT/.venv"
+ export PATH
+fi
+PROFILE
+chmod 644 /etc/profile.d/hr-environment.sh
for f in "$DATA_DIR"/*.db "$DATA_DIR"/*.db-* "$DATA_DIR"/selfhost-auth.json; do
if [ -e "$f" ]; then chown "$PRODUCT:$PRODUCT" "$f"; chmod 600 "$f"; fi
done
diff --git a/docs/environments.md b/docs/environments.md
new file mode 100644
index 00000000..64cc0f89
--- /dev/null
+++ b/docs/environments.md
@@ -0,0 +1,133 @@
+# Environments
+
+A project's files and its installed dependencies, built once and read by every task session that
+names it. This is the design of record for the self-hosted server (shipped in 0.26) and for the
+hosted service (to be built to the same contract); the wire contract is the
+[Environments chapter](../protocol/versions/2026-09-28/environments.md) of UHP `2026-09-28`.
+
+## The problem it solves
+
+A session's working directory is made for one conversation. It starts empty, is checkpointed after
+every turn as a tarball with dependency directories excluded, and is restored before the next turn.
+Everything a task needs is uploaded into it, and everything it installs is reinstalled the next
+time. For a task that is a project, a content pipeline with scripts, assets, templates and a hundred
+packages, opened by several people many times a day, that is the wrong shape (Spiral, SPI-001 to
+SPI-004): every session paid the upload and the install again, and two sessions could not share
+one copy.
+
+## The contract a session sees
+
+```
+/env/content-studio the environment: complete, READ-ONLY, shared by every session
+ scripts/ assets/ data/ … the project's files, as the owner put them in
+ .venv/ node_modules/ installed once, when the environment was built
+/data/workspaces/<sid> the session's working directory: writable, private, checkpointed,
+ the only place artifacts come from (unchanged)
+PROJECT_ROOT=/env/content-studio
+PATH=/env/content-studio/.venv/bin:/env/content-studio/node_modules/.bin:…
+PYTHONPATH=/env/content-studio NODE_PATH=/env/content-studio/node_modules:…
+```
+
+The agent's instruction file carries a "Project environment" section (runner/environments.py,
+`doc_section`): where the project is, that it is read-only and shared, that its dependencies are
+installed, to write outputs to the working directory, to run scripts by absolute path, and the
+owner's `entry` line when there is one. Richard's decision (2026-09-28): a fixed read-only path
+with a private cwd, not a copy-on-write working directory inside the project; the reasons are in
+the chapter's first note.
+
+## Objects and operations
+
+An environment (`henv_…`) belongs to an org and a workspace, like a harness. It has a **source**
+(the files the owner edits: upload one by one, import an archive or a git repository, edit in the
+console), **versions** (builds: the source copied, then `.venv` / `node_modules` installed from
+`requirements.txt` / `pyproject.toml` / `package.json`, then `setup.sh`, then the tree made
+read-only), and one **active** version, the one sessions read. A build that succeeds becomes
+active; a failed one changes nothing; rollback is a pointer to an earlier build. A harness names
+the environment its tasks read; a task can name another. A task on an environment with nothing
+built is refused before it starts (`environment_not_ready`).
+
+Routes: `/v1/environments`, `…/{id}`, `…/{id}/files[/{path}]`, `…/{id}/import`, `…/{id}/build`,
+`…/{id}/builds/{n}`, `…/{id}/versions[/{n}/activate]`, `…/{id}/harnesses`; `environment` on the
+harness object and on `POST /v1/responses`; `environment` on the session object.
+
+## Self-hosted implementation (this repository)
+
+- **Record**: the gateway (`gateway/app.py`, "Environments" section): an `Environment` vertex
+ with org, workspace, name, slug, description, entry, status, active/latest version, the
+ versions list and the active build's packages, refreshed from the runner on reads.
+- **Bytes**: the runner (`runner/environments.py`) owns `/data/environments/<id>/`:
+ `source/` (editable), `versions/<n>/` (a build, root-owned, `a+rX`, with `.hr-build.json`:
+ status, log, packages, size), `active` → `versions/<n>`. The mount `/env/<slug>` is a link to
+ `active`, on the container's rootfs, remade lazily after a restart. Builds run in a thread of
+ the runner with the image's own `python3` and `npm`, caches in a scratch directory, a wall clock
+ of `HR_ENV_BUILD_TIMEOUT` (1800 s). Dependency directories in the source are never copied.
+- **Read-only**: the write-wall (`HR_SESSION_UIDS`): an agent runs as its session's uid, the layer
+ is root's, `chmod 755/644`, so a write fails with EACCES. Without the wall (a development box)
+ the permissions still hold for any non-root agent; root is the operator's own choice.
+- **The turn**: the gateway resolves the environment (request field, else the harness's) before
+ anything is allocated, passes `{id, slug, entry}` to the runner, stamps the session vertex with
+ `environment` and the turn record with the version. The runner resolves the mount before writing
+ the agent doc (a 409 there fails the turn before any process starts), then sets the variables.
+- **Checkpoints** are unchanged: the environment is outside the workspace, so it is never in one.
+
+## How the hosted service implements it
+
+Reviewed with the hosted session on 2026-09-28; the corrections are theirs. The hosted service runs
+one session per Azure Container Apps dynamic session out of the custom-container pool
+(`harness-sessions-e2`: 1 vCPU, 2 GiB, about 4 GiB of ephemeral disk, a 1800 s cooldown after
+which the container is recycled). There is no pool host to keep a cache on, no volume and no bind
+mount a session can be given, and nothing in a sandbox may hold a blob credential. The same
+contract is built like this:
+
+1. **Record.** The same `Environment` vertex on the HR tenant, registered with the seed script
+ (label and edges) before the gateway that writes it rolls, as the billing labels were: a write
+ before the seed 400s. Same routes, same object, `mount` stays `/env/<slug>`.
+2. **Source.** One blob per file (`environments/<id>/source/<path>`) plus a small index blob with
+ the tree, so the console's editor reads and writes one file at a time. A build materialises
+ `environments/<id>/versions/<n>/source.tgz` from them first, so the build's input is one
+ immutable object: reproducible, one download.
+3. **Build = a sandbox job, never a gateway thread.** A gateway replica has no toolchain, no disk
+ and may restart. The build takes a sandbox from the pool under the identifier `env-<id>-<n>`
+ (no colons; the charset is the pool's), the policy gate runs BEFORE the sandbox is allocated
+ (deficit and plan refusals; a build counts as a task for the Free plan's concurrency), and the
+ "one build at a time per environment" lock and the build's status live in the control store as
+ a lease with a TTL, swept by the straggler sweep, exactly as turns are, so a replica restart
+ orphans nothing. Inside the sandbox the same `runner/environments.py::_build` runs (the one
+ function both sides call), with `source.tgz` as its input and a 1800 s wall clock. The build is
+ metered as agent work under the org, with its own receipt line ("Environment build",
+ `agent.active_second`, the per-task cost cap applied), not a new ledger unit.
+4. **Blob access is the gateway's, in one shape.** The sandbox never sees the account key. For the
+ layer, the gateway mints a per-blob, minutes-lived SAS (write-only for the build's output,
+ read-only for a turn's input) and hands it in the build or turn body, so a layer of a few
+ hundred MB does not pass through a gateway replica that has no disk. The build writes
+ `layer.tgz` (zstd) and `.hr-build.json` (status, log, packages, sizes) with its write SAS; a
+ turn's hydrate downloads `layer.tgz` with its read SAS. The source files and index are written
+ only by the API (the gateway streams them itself, as it streams checkpoints).
+5. **The mount = extract at hydrate.** This IS the hosted design, not a first slice: when a turn
+ names an environment, `/hydrate` downloads the active version's `layer.tgz` and extracts it to
+ `/env/<slug>` once per session lifetime (the container lives until the cooldown recycles it, so
+ later turns of the session find it in place), root-owned with 755/644 as extracted, no
+ `chmod -R` pass; the agent runs as the image's agent uid (10001), which is the same wall the
+ self-hosted server uses. The turn record carries `env_hydrate_ms` so the cost is visible. If
+ sharing a layer across sessions is ever needed, the ACA-native shape is a session pool whose
+ image bakes the layer, a different product decision; a bind mount is not promised.
+6. **Isolation.** The container is the boundary: one session cannot see another's container at
+ all; the layer is root's and the agent is not; the source and the layers are written only by
+ the API and the build's write SAS.
+7. **Versions, rollback, retention.** `active_version` on the vertex is the pointer; the gateway
+ passes `version` in the turn body so a hydrate is deterministic, and stamps the session with
+ the version it started on, which later turns of that session keep. The active version plus the
+ last three are kept; an environment's blobs are deleted with it; layers are counted in
+ `/internal/storage-usage`.
+8. **Sizes.** The ephemeral disk also holds the workspace, so the layer cap is a fraction of it, per
+ plan, enforced at build time from the recorded size: a layer over the cap fails the build with
+ the size in the log. Import 512 MiB and file 64 MiB stay the env-tunable caps; measure the disk
+ with `df` in a session before writing the number into a plan.
+
+## What is not in this slice
+
+- Environment-level system packages (apt): the image provides `ffmpeg`, LibreOffice, Playwright;
+ a project that needs more says so in `setup.sh`, which runs with the build's privileges.
+- Cross-workspace sharing beyond the org's workspaces; a marketplace of environments.
+- Controlled updates from inside a session (SPI-006): a session cannot write the environment; a
+ "promote these files to the next version" flow is a later design with review and versioning.
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.md
index f1199b6c..f819cf74 100644
--- a/docs/self-hosting-guide.md
+++ b/docs/self-hosting-guide.md
@@ -8,6 +8,7 @@ Detailed installation, configuration, API, and deployment instructions. For the
- [Restarts, upgrades, and backups](#restarts-upgrades-and-backups)
- [Starter kits](#starter-kits)
- [Plugins](#plugins)
+- [Environments](#environments)
- [What it is](#what-it-is)
- [Why self-host](#why-self-host)
- [The Unified Harness Protocol](#the-unified-harness-protocol)
@@ -677,6 +678,41 @@ no markup, read from the same table the hosted service bills from. Every call an
written down on the task's trace (event type `plug`, plug `browser`, with the minutes and the
vendor's figure on the session row).
+## Environments
+
+A task's workspace starts empty and is checkpointed after every turn with its dependency
+directories left out, so a project that is uploaded into it is uploaded again next time and its
+packages are installed again. An **environment** is that project as one thing: its files and its
+installed dependencies, built once, and read by every task that names it.
+
+Every task that uses one finds it at `/env/<slug>` (the name, as a path segment), read-only and
+shared, with the environment's Python virtualenv and `node_modules` first on `PATH`, the project on
+`PYTHONPATH`, and `PROJECT_ROOT` naming the path. The task's own workspace stays what it was:
+writable, private to the session, checkpointed, and the only place its outputs come from. Two tasks
+on one environment share every byte of it and cannot read each other's workspace or write the
+environment; behind the write-wall an agent runs as its session's user and the environment is
+root's, so a write fails rather than being merely discouraged. The agent's instruction file says all
+of this, and repeats the "how it is run" line you gave.
+
+On the console, **Environments** (under Build): create one, then put the project in, one file at a
+time, as an archive, or from a git repository (the tree is kept; a single wrapping folder is
+stripped), and press **Build**. The build copies the files into a new version and installs what they
+declare (`requirements.txt` or `pyproject.toml` into `.venv`, `package.json` with npm, then
+`setup.sh` for anything else), logs the installers' output, and makes the version the one tasks
+read when it succeeds. Editing files afterwards changes nothing a task sees until the next build;
+an older version can be made active again with one click. Then name the environment under a
+harness's settings (**Project environment**), or on one task with `environment` in the request. A
+task on an environment with nothing built is refused before it starts.
+
+Where it lives: `/data/environments/<id>/` on the data volume (`source/`, `versions/<n>/`,
+`active`), with the `/env/<slug>` links remade after a restart. A build runs in the runner with the
+image's own `python3` and `npm` and the network, for at most `HR_ENV_BUILD_TIMEOUT` seconds
+(1800); an import may be `HR_ENV_IMPORT_MAX_BYTES` (512 MiB) and a file `HR_ENV_FILE_MAX_BYTES`
+(64 MiB). System packages are the image's (`ffmpeg`, LibreOffice, Playwright are there); a
+`setup.sh` runs with the build's privileges, so it is yours to trust. The API is under
+`/v1/environments`, in the [API reference](#using-the-api) and in the
+[Environments chapter](../protocol/versions/2026-09-28/environments.md) of the protocol.
+
## What it is
An *agent harness* is the runtime layer around a model; Codex, Claude Code, and Hermes are harnesses. In this repo's API you also create *harness* objects: a saved configuration whose `base` is one of those runtimes, plus a model, instructions, and limits. A *task* is one run of that configuration, a real conversation against a real POSIX workspace with bash and git, streamed back as it happens.
diff --git a/gateway/app.py b/gateway/app.py
index 2a41bebf..9f503dfb 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -3956,11 +3956,11 @@ async def llm_broker(path: str, request: Request):
# retry. Added the structured error envelope. The old `detail` string is still emitted beside
# it, because clients in the wild read it — it is documented as deprecated, not removed under
# them.
-UHP_VERSION = "2026-09-12"
+UHP_VERSION = "2026-09-28"
# Both versions, one code path: 2026-09-12 is additive to 2026-08-11 (plugins, and nothing
# the earlier version defined changes shape), so the same objects answer either request and
# the header is the only thing that differs. VERSIONING.md, server rule 3.
-UHP_VERSIONS = [UHP_VERSION, "2026-08-11"]
+UHP_VERSIONS = [UHP_VERSION, "2026-09-12", "2026-08-11"]
# The Agent Plugins manifest schemas this server installs (Plugins §7). A package targeting
# another version is refused with unsupported_plugin_schema naming this list.
UHP_PLUGIN_SCHEMAS = ["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"]
@@ -3979,6 +3979,7 @@ UHP_CAPABILITIES = {
"session_sharing": True,
"idempotency": True,
"plugins": True,
+ "environments": True,
}
UHP_CONFORMANCE_CLASS = "full"
@@ -7147,7 +7148,8 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
hdr_vals: dict[str, str] | None = None,
partial_messages: bool = False, probe: dict | None = None,
codex_appserver: bool = False,
- hv: dict | None = None) -> tuple[str, list[dict], dict]:
+ hv: dict | None = None,
+ environment: dict | None = None) -> tuple[str, list[dict], dict]:
"""Hydrate → run turn over the connection chain → translate events to `emit` → collect produced
files → checkpoint + persist trace. Returns (status, produced_files, rec).
model_req: the caller-selected model (honored over the connection default when provided)."""
@@ -7232,6 +7234,13 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
if mcp_servers or skills or skills_suppressed or tools_disabled:
rec["plugins"] = {"mcp": [m.get("name") for m in mcp_servers], "skills": [s.get("name") for s in skills],
"skills_off": skills_suppressed, "tools_off": tools_disabled}
+ if environment:
+ # Provenance: which layer, at which build, this turn read. The session carries the id so its
+ # detail names it; the turn record carries the version, since a rebuild changes what the
+ # next turn sees and the record must say which one this was.
+ rec["environment"] = {"id": environment["id"], "slug": environment["slug"],
+ "version": environment.get("version"), "path": environment.get("path")}
+ await _vertex_upsert(sid, {"environment": environment["id"], "environment_slug": environment["slug"]})
# The harness's configured instructions are the agent's CLAUDE.md (claude) / AGENTS.md (codex) —
# written into the workspace by the runner, NOT injected as a system prompt. The model keeps the
# CLI's default system prompt; persistent project instructions live in the doc the agent reads.
@@ -7330,6 +7339,9 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
"auth": sandbox_auth, "resume_session_id": resume, "files": files_in,
"mcp_servers": mcp_servers, "skills": skills, "plugins": plugin_pkgs, "agent_doc": agent_doc,
"skills_suppressed": skills_suppressed, "tools_disabled": turn_tools_off,
+ # The project layer, read-only at /env/<slug> (runner/environments.py): id, slug, entry.
+ "environment": ({"id": environment["id"], "slug": environment["slug"],
+ "entry": environment.get("entry") or ""} if environment else None),
# Image generation, when an integration can serve it. A per-turn credential for
# the broker, never a provider key — see _image_auth.
"image_auth": image_auth,
@@ -7877,6 +7889,7 @@ class CreateResponseBody(BaseModel):
backend: str | None = None # non-OpenAI convenience: force codex|claude
max_step: int | None = None # per-request agent step budget (claude --max-turns)
timeout_seconds: int | None = None # per-request wall-clock cap for the turn
+ environment: str | None = None # an environment id for this task; overrides the harness's (UHP Environments)
_IDEM_TERMINAL = {"completed", "failed", "incomplete", "cancelled", "error"}
@@ -7964,6 +7977,10 @@ async def create_response(body: CreateResponseBody, request: Request):
# the marketplace model is exactly "callers run it, the owner pays infra". Until entitlements
# land, the unguessable harness id is the run capability.
_turn_harness_check(harness_id, hv)
+ # The project layer this task reads: the request's, else the harness's. Resolved and checked
+ # 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, body.environment or str((hv or {}).get("environment") or ""))
# 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
@@ -8194,7 +8211,7 @@ async def create_response(body: CreateResponseBody, request: Request):
prompt=prompt, files_in=files_in, resume=resume, emit=bus_emit_bg,
model_req=model_req, user_text=user_text, harness_id=harness_id,
max_step=max_step, timeout_s=timeout_s, hdr_vals=hdr_vals,
- partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe)
+ partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment)
# A failed turn says why in the transcript, not only in the response record: fail()
# carries the message as an error event, which the console prints under the answer.
for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):
@@ -8243,7 +8260,7 @@ async def create_response(body: CreateResponseBody, request: Request):
tr, org=org, member=member, sid=sid, backend=backend, chain=chain,
prompt=prompt, files_in=files_in, resume=resume, emit=emit, model_req=model_req,
user_text=user_text, harness_id=harness_id, max_step=max_step,
- timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe)
+ timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment)
# A failed turn says why in the transcript, not only in the response record: fail()
# carries the message as an error event, which the console prints under the answer.
for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):
@@ -8301,7 +8318,7 @@ async def create_response(body: CreateResponseBody, request: Request):
tr, org=org, member=member, sid=sid, backend=backend, chain=chain,
prompt=prompt, files_in=files_in, resume=resume, emit=bus_emit, model_req=model_req,
user_text=user_text, harness_id=harness_id, max_step=max_step,
- timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe)
+ timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment)
# A failed turn says why in the transcript, not only in the response record: fail()
# carries the message as an error event, which the console prints under the answer.
for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):
@@ -15128,6 +15145,7 @@ class HarnessBody(BaseModel):
# and HR_CALIBRATION_TOKEN, a credential scoped to that harness and expiring with the turn
# (docs/dual-loop.md in the System One Harness repository, Appendix B).
calibrates: str | None = _either("calibrates")
+ environment: str | None = None # the environment (henv_) this harness's tasks read at /env/<slug>; UHP Environments
def _harness_out(v: dict) -> dict:
@@ -15160,6 +15178,7 @@ def _harness_out(v: dict) -> dict:
"maxStep": int(v.get("max_step")) if str(v.get("max_step") or "").isdigit() else None,
"timeoutSeconds": int(v.get("timeout_seconds")) if str(v.get("timeout_seconds") or "").isdigit() else None,
"calibrates": str(v.get("calibrates") or ""),
+ "environment": str(v.get("environment") or ""),
"member": v.get("member") or "", "workspace": v.get("workspace") or "", "createdAt": created}
@@ -15178,6 +15197,7 @@ def _harness_props(body: HarnessBody) -> dict:
if isinstance(h, str) and str(h).strip()]),
"env": json.dumps(_env_clean(body.env)),
"calibrates": str(body.calibrates or "").strip(),
+ "environment": str(body.environment or "").strip(),
"max_step": str(body.max_step) if body.max_step else "",
"timeout_seconds": str(body.timeout_seconds) if body.timeout_seconds else ""}
@@ -15273,6 +15293,394 @@ async def _skill_bundle_files(sk: dict) -> list:
files = [{"path": "SKILL.md", "content": sk["content"]}]
return files or []
+
+# ── Environments (UHP 2026-09-28, Environments chapter) ───────────────────────────────────────
+# A project's files and its installed dependencies, built once and read by every session that
+# names it: read-only at /env/<slug> beside the session's own writable workspace. The record lives
+# here (org, workspace, name, slug, status, versions); the bytes live with the runner, which owns
+# the data volume, builds the layer in the image's own toolchain and links it where sessions look
+# (runner/environments.py). Every route below is the record plus a call to the runner.
+_ENV_IMPORT_MAX = int(os.environ.get("HR_ENV_IMPORT_MAX_BYTES", str(512 * 1024 * 1024))) # one archive
+_ENV_FILE_MAX = int(os.environ.get("HR_ENV_FILE_MAX_BYTES", str(64 * 1024 * 1024))) # one file
+_ENV_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
+
+
+class EnvironmentBody(BaseModel):
+ name: str
+ description: str | None = ""
+ entry: str | None = "" # how the project is run, in the owner's words ("python3 run.py --episode <id>")
+
+
+def _env_slug(name: str) -> str:
+ """The path segment sessions see: the name, lower-cased, non-word runs as one dash."""
+ s = re.sub(r"[^a-z0-9._-]+", "-", str(name or "").strip().lower()).strip("-.")
+ return s[:64] if _ENV_SLUG_RE.match(s or "-") else ""
+
+
+async def _env_runner(method: str, path: str, env_id: str, *, params: dict | None = None,
+ content=None, timeout: float = 120.0) -> httpx.Response:
+ """The runner call an environment route makes. The runner owns the bytes; this process owns the
+ record. `identifier` rides along as every runner call's does, so a per-identifier pool routes
+ an environment's work to one place."""
+ if not POOL_ENDPOINT:
+ raise uhp_error(503, "environment_unavailable", "No runner is configured to hold environments.")
+ kw: dict = {"content": content} if content is not None else {}
+ try:
+ return await _client().request(method, f"{POOL_ENDPOINT}{path}", params={"identifier": env_id, **(params or {})},
+ headers=_pool_headers(), timeout=timeout, **kw)
+ except httpx.HTTPError as e:
+ raise uhp_error(502, "environment_unavailable", f"The runner did not answer: {type(e).__name__}.")
+
+
+def _env_runner_error(r: httpx.Response, fallback: str) -> HTTPException:
+ """A runner refusal, in the protocol's envelope: its 4xx is the caller's mistake (a bad path, a
+ version that is not built), anything else is the platform's."""
+ try:
+ msg = (r.json() or {}).get("detail") or fallback
+ except ValueError:
+ msg = fallback
+ if r.status_code == 404:
+ return uhp_error(404, "not_found", str(msg))
+ if r.status_code == 409:
+ return uhp_error(409, "environment_not_ready", str(msg))
+ if 400 <= r.status_code < 500:
+ return uhp_error(422, "environment_invalid", str(msg))
+ return uhp_error(502, "environment_unavailable", f"The runner failed: HTTP {r.status_code}.")
+
+
+async def _environment_vertex(org: str, env_id: str) -> dict | None:
+ if not env_id or not re.fullmatch(r"henv_[0-9a-f]{32}", env_id):
+ return None
+ v = await BACKING.graph.get(env_id, label="Environment")
+ if not v or str(v.get("org") or "") != org or str(v.get("deleted") or "0") == "1":
+ return None
+ return v
+
+
+async def _environment_check_ref(org: str, env_id: str | None) -> None:
+ """A harness may name an environment of its own org, or none."""
+ if env_id and not await _environment_vertex(org, env_id):
+ raise uhp_error(404, "environment_not_found", "No environment with that id.", "environment")
+
+
+async def _environment_for_turn(org: str, env_id: str) -> dict | None:
+ """What a task reads, checked before the turn starts: the environment exists in this org and
+ has a built version. Returns {id, slug, entry, version, path} or None for a task with none."""
+ if not env_id:
+ return None
+ v = await _environment_vertex(org, env_id)
+ if not v:
+ raise uhp_error(404, "environment_not_found", "No environment with that id.", "environment")
+ v = await _environment_refresh(v)
+ if str(v.get("status") or "") != "ready" or not str(v.get("active_version") or ""):
+ raise uhp_error(409, "environment_not_ready",
+ "The environment has no built version yet: build it, then run the task.", "environment",
+ {"status": v.get("status") or "empty"})
+ slug = str(v.get("slug") or "")
+ return {"id": env_id, "slug": slug, "entry": str(v.get("entry") or ""),
+ "version": int(v.get("active_version")), "path": f"/env/{slug}"}
+
+
+async def _environment_refresh(v: dict) -> dict:
+ """The record, brought up to date with what the runner holds: the source's size, the versions,
+ the active one and the latest build's status. Persisted when anything moved, so the list (which
+ reads records only) tells the truth a moment after a build finishes."""
+ eid = str(v.get("id") or "")
+ r = await _env_runner("GET", f"/environments/{eid}", eid)
+ if r.status_code != 200:
+ return v
+ live = r.json() or {}
+ src, vers, active = live.get("source") or {}, live.get("versions") or [], live.get("active")
+ latest = max([int(x.get("version") or 0) for x in vers] or [0])
+ latest_rec = next((x for x in vers if int(x.get("version") or 0) == latest), None) if latest else None
+ if active:
+ status = "ready"
+ elif latest_rec and latest_rec.get("status") == "building":
+ status = "building"
+ elif latest_rec and latest_rec.get("status") == "failed":
+ status = "failed"
+ else:
+ status = "empty"
+ packages = v.get("packages") or "[]"
+ if active and str(active) != str(v.get("active_version") or ""):
+ b = await _env_runner("GET", f"/environments/{eid}/build", eid, params={"version": int(active)})
+ if b.status_code == 200:
+ packages = json.dumps((b.json() or {}).get("packages") or [])
+ props = {"status": status, "active_version": str(active or ""), "latest_version": str(latest or ""),
+ "files_count": str(int(src.get("count") or 0)), "files_bytes": str(int(src.get("bytes") or 0)),
+ "versions": json.dumps(vers), "packages": packages}
+ if any(str(v.get(k) or "") != str(val) for k, val in props.items()):
+ await _vg_upsert("Environment", eid, props)
+ v = {**v, **props}
+ return v
+
+
+def _environment_out(v: dict) -> dict:
+ def _j(s, default):
+ try:
+ return json.loads(s) if s else default
+ except Exception: # noqa: BLE001
+ return default
+ vers = _j(v.get("versions"), [])
+ latest = max([int(x.get("version") or 0) for x in vers] or [0])
+ latest_rec = next((x for x in vers if int(x.get("version") or 0) == latest), None)
+ active = int(v.get("active_version")) if str(v.get("active_version") or "").isdigit() else None
+ slug = str(v.get("slug") or "")
+ return {"id": v.get("id"), "object": "environment", "name": v.get("name") or "", "slug": slug,
+ "description": v.get("description") or "", "entry": v.get("entry") or "",
+ "status": v.get("status") or "empty", "mount": f"/env/{slug}",
+ "version": active, "latestVersion": latest or None,
+ "files": {"count": int(v.get("files_count") or 0), "bytes": int(v.get("files_bytes") or 0)},
+ "packages": _j(v.get("packages"), []),
+ "versions": vers,
+ "build": ({k: latest_rec.get(k) for k in ("version", "status", "started_at", "finished_at", "error")}
+ if latest_rec else None),
+ "member": v.get("member") or "", "workspace": v.get("workspace") or "",
+ "createdAt": int(v.get("created_at") or 0), "updatedAt": int(v.get("updated_at") or 0)}
+
+
+async def _owned_environment(request: Request, env_id: str) -> tuple[dict, dict]:
+ p = await _principal(request)
+ org = p.get("org", "")
+ if not org:
+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")
+ v = await _environment_vertex(org, env_id)
+ if not v:
+ raise uhp_error(404, "environment_not_found", "No environment with that id.", "environment_id")
+ ws = str(p.get("workspace") or "")
+ if ws and not _workspace_keep(str(v.get("workspace") or ""), ws, bool(p.get("workspace_default"))):
+ raise uhp_error(404, "environment_not_found", "No environment with that id.", "environment_id")
+ return p, v
+
+
[email protected]("/v1/environments")
+async def create_environment(body: EnvironmentBody, request: Request) -> dict:
+ p = await _principal(request)
+ org, member = p.get("org", ""), p.get("member", "")
+ if not org:
+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")
+ name = str(body.name or "").strip()
+ slug = _env_slug(name)
+ if not name or not slug:
+ raise uhp_error(422, "environment_invalid", "Give the environment a name that starts with a letter or digit.", "name")
+ # One slug per instance: the mount path is a place on the box that runs every session.
+ if any(str(r.get("deleted") or "0") != "1" for r in await BACKING.graph.find("Environment", {"slug": slug})):
+ raise uhp_error(409, "environment_exists", f"An environment is already mounted at /env/{slug}; choose another name.", "name")
+ eid = _rid("henv")
+ now = str(int(time.time() * 1000))
+ props = {"org": org, "member": member, "workspace": str(p.get("workspace") or ""),
+ "name": name, "slug": slug, "description": str(body.description or "").strip(),
+ "entry": str(body.entry or "").strip(), "status": "empty", "active_version": "", "latest_version": "",
+ "files_count": "0", "files_bytes": "0", "versions": "[]", "packages": "[]",
+ "created_at": now, "updated_at": now, "deleted": "0"}
+ await _vg_upsert("Environment", eid, props)
+ return _environment_out({"id": eid, **props})
+
+
[email protected]("/v1/environments")
+async def list_environments(request: Request) -> dict:
+ p = await _principal(request)
+ org = p.get("org", "")
+ if not org:
+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")
+ rows = [r for r in await _vg_list_by_org("Environment", org) if str(r.get("deleted") or "0") != "1"]
+ ws = str(p.get("workspace") or "")
+ if ws:
+ rows = [r for r in rows if _workspace_keep(str(r.get("workspace") or ""), ws, bool(p.get("workspace_default")))]
+ # A build finishes in the runner; a record that says "building" is brought up to date here so
+ # the list never shows a spinner over a layer that is ready.
+ rows = [await _environment_refresh(r) if str(r.get("status") or "") == "building" else r for r in rows]
+ items = [_environment_out(r) for r in rows]
+ items.sort(key=lambda x: x["createdAt"], reverse=True)
+ return {"environments": items}
+
+
[email protected]("/v1/environments/{env_id}")
+async def get_environment(env_id: str, request: Request) -> dict:
+ _, v = await _owned_environment(request, env_id)
+ return _environment_out(await _environment_refresh(v))
+
+
[email protected]("/v1/environments/{env_id}")
+async def update_environment(env_id: str, body: EnvironmentBody, request: Request) -> dict:
+ """Name, description and entry. The slug (the mount path) stays: sessions and instructions name it."""
+ _, v = await _owned_environment(request, env_id)
+ name = str(body.name or "").strip() or str(v.get("name") or "")
+ await _vg_upsert("Environment", env_id, {"name": name, "description": str(body.description or "").strip(),
+ "entry": str(body.entry or "").strip(),
+ "updated_at": str(int(time.time() * 1000))})
+ return _environment_out(await _environment_refresh(await _environment_vertex(str(v.get("org")), env_id) or v))
+
+
[email protected]("/v1/environments/{env_id}")
+async def delete_environment(env_id: str, request: Request) -> dict:
+ _, v = await _owned_environment(request, env_id)
+ v = await _environment_refresh(v)
+ if str(v.get("status") or "") == "building":
+ raise uhp_error(409, "environment_busy", "A build is running; wait for it before deleting.")
+ r = await _env_runner("DELETE", f"/environments/{env_id}", env_id, params={"slug": str(v.get("slug") or "")})
+ if r.status_code >= 500:
+ raise _env_runner_error(r, "the environment's files could not be removed")
+ await _vg_upsert("Environment", env_id, {"deleted": "1", "updated_at": str(int(time.time() * 1000))})
+ return {"id": env_id, "deleted": True}
+
+
[email protected]("/v1/environments/{env_id}/files")
+async def environment_files(env_id: str, request: Request) -> dict:
+ """The source tree: every file and directory a person put in, with sizes. Not the built layer."""
+ await _owned_environment(request, env_id)
+ r = await _env_runner("GET", f"/environments/{env_id}/tree", env_id)
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the files could not be listed")
+ return r.json()
+
+
[email protected]("/v1/environments/{env_id}/files/{path:path}")
+async def environment_file(env_id: str, path: str, request: Request) -> Response:
+ await _owned_environment(request, env_id)
+ r = await _env_runner("GET", f"/environments/{env_id}/source", env_id, params={"path": path})
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the file could not be read")
+ return Response(content=r.content, media_type=r.headers.get("content-type") or "application/octet-stream")
+
+
[email protected]("/v1/environments/{env_id}/files/{path:path}")
+async def environment_put_file(env_id: str, path: str, request: Request) -> dict:
+ """One file, its bytes as the body; its directories are made on the way."""
+ await _owned_environment(request, env_id)
+ declared = int(request.headers.get("content-length") or 0)
+ if declared > _ENV_FILE_MAX:
+ raise uhp_error(413, "file_too_large", f"A file may be at most {_ENV_FILE_MAX} bytes.", "path",
+ {"max_bytes": _ENV_FILE_MAX})
+ data = await request.body()
+ if len(data) > _ENV_FILE_MAX:
+ raise uhp_error(413, "file_too_large", f"A file may be at most {_ENV_FILE_MAX} bytes.", "path",
+ {"max_bytes": _ENV_FILE_MAX})
+ r = await _env_runner("PUT", f"/environments/{env_id}/source", env_id, params={"path": path.rstrip("/")}, content=data)
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the file could not be written")
+ await _vg_upsert("Environment", env_id, {"updated_at": str(int(time.time() * 1000))})
+ return r.json()
+
+
+class EnvironmentDirectoryBody(BaseModel):
+ path: str
+
+
[email protected]("/v1/environments/{env_id}/directories")
+async def environment_make_directory(env_id: str, body: EnvironmentDirectoryBody, request: Request) -> dict:
+ """An empty directory, by name. Its own request rather than a trailing slash on PUT: a proxy that
+ normalises paths turns `scripts/` into `scripts`, and the result was a 0-byte file (rc.1)."""
+ await _owned_environment(request, env_id)
+ r = await _env_runner("POST", f"/environments/{env_id}/mkdir", env_id, params={"path": str(body.path or "").strip("/")})
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the directory could not be made")
+ await _vg_upsert("Environment", env_id, {"updated_at": str(int(time.time() * 1000))})
+ return r.json()
+
+
[email protected]("/v1/environments/{env_id}/files/{path:path}")
+async def environment_delete_file(env_id: str, path: str, request: Request) -> dict:
+ await _owned_environment(request, env_id)
+ r = await _env_runner("DELETE", f"/environments/{env_id}/source", env_id, params={"path": path.rstrip("/")})
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the path could not be removed")
+ await _vg_upsert("Environment", env_id, {"updated_at": str(int(time.time() * 1000))})
+ return r.json()
+
+
+class EnvironmentImportBody(BaseModel):
+ git: dict | None = None # {"url": ..., "ref": ...}
+ replace: bool = False
+
+
[email protected]("/v1/environments/{env_id}/import")
+async def environment_import(env_id: str, request: Request, replace: int = 0) -> dict:
+ """A whole project at once, keeping its tree: a zip or tar archive as the body, or a JSON body
+ naming a git repository. `?replace=1` clears the source first."""
+ await _owned_environment(request, env_id)
+ ctype = (request.headers.get("content-type") or "").split(";")[0].strip().lower()
+ if ctype == "application/json":
+ body = EnvironmentImportBody(**(await request.json() or {}))
+ git = body.git or {}
+ if not str(git.get("url") or ""):
+ raise uhp_error(422, "environment_invalid", "Name a git url, or send an archive as the body.", "git.url")
+ r = await _env_runner("POST", f"/environments/{env_id}/import", env_id, timeout=900.0,
+ params={"replace": int(bool(replace or body.replace)), "git_url": str(git.get("url")),
+ "git_ref": str(git.get("ref") or "")}, content=b"")
+ else:
+ declared = int(request.headers.get("content-length") or 0)
+ if declared > _ENV_IMPORT_MAX:
+ raise uhp_error(413, "file_too_large", f"An import may be at most {_ENV_IMPORT_MAX} bytes.", None,
+ {"max_bytes": _ENV_IMPORT_MAX})
+ r = await _env_runner("POST", f"/environments/{env_id}/import", env_id, timeout=900.0,
+ params={"replace": int(bool(replace))}, content=request.stream())
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the import failed")
+ await _vg_upsert("Environment", env_id, {"updated_at": str(int(time.time() * 1000))})
+ return r.json()
+
+
[email protected]("/v1/environments/{env_id}/build")
+async def environment_build(env_id: str, request: Request) -> dict:
+ """Snapshot the source into a new version and install what its manifests declare; the version
+ becomes the one sessions read when the build succeeds. Returns at once; poll the build."""
+ _, v = await _owned_environment(request, env_id)
+ v = await _environment_refresh(v)
+ if str(v.get("status") or "") == "building":
+ raise uhp_error(409, "environment_busy", "A build is already running.")
+ n = int(v.get("latest_version") or 0) + 1
+ r = await _env_runner("POST", f"/environments/{env_id}/build", env_id,
+ params={"version": n, "slug": str(v.get("slug") or ""), "activate": 1})
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the build could not start")
+ await _vg_upsert("Environment", env_id, {"status": "building", "latest_version": str(n),
+ "updated_at": str(int(time.time() * 1000))})
+ return {"id": env_id, "object": "environment.build", "version": n, "status": "building"}
+
+
[email protected]("/v1/environments/{env_id}/builds/{version}")
+async def environment_build_status(env_id: str, version: int, request: Request) -> dict:
+ """The build's record: status, log, packages, size. The record the runner wrote, verbatim."""
+ _, v = await _owned_environment(request, env_id)
+ r = await _env_runner("GET", f"/environments/{env_id}/build", env_id, params={"version": int(version)})
+ if r.status_code != 200:
+ raise _env_runner_error(r, "no such build")
+ rec = r.json() or {}
+ if rec.get("status") in ("ready", "failed") and str(v.get("status") or "") == "building":
+ await _environment_refresh(v)
+ return {"id": env_id, "object": "environment.build", **rec}
+
+
[email protected]("/v1/environments/{env_id}/versions")
+async def environment_versions(env_id: str, request: Request) -> dict:
+ _, v = await _owned_environment(request, env_id)
+ v = await _environment_refresh(v)
+ return {"id": env_id, "active": int(v.get("active_version")) if str(v.get("active_version") or "").isdigit() else None,
+ "versions": json.loads(v.get("versions") or "[]")}
+
+
[email protected]("/v1/environments/{env_id}/versions/{version}/activate")
+async def environment_activate(env_id: str, version: int, request: Request) -> dict:
+ """Point sessions at an older build: rollback, nothing rebuilt."""
+ _, v = await _owned_environment(request, env_id)
+ r = await _env_runner("POST", f"/environments/{env_id}/activate", env_id,
+ params={"version": int(version), "slug": str(v.get("slug") or "")})
+ if r.status_code != 200:
+ raise _env_runner_error(r, "that version cannot be activated")
+ return _environment_out(await _environment_refresh(v))
+
+
[email protected]("/v1/environments/{env_id}/harnesses")
+async def environment_harnesses(env_id: str, request: Request) -> dict:
+ """The harnesses of the org that read this environment."""
+ p, _ = await _owned_environment(request, env_id)
+ rows = await _vg_list_by_org("Harness", p.get("org", ""))
+ items = [{"id": r.get("id"), "name": r.get("name") or "", "base": r.get("base") or ""}
+ for r in rows if str(r.get("deleted") or "0") != "1" and str(r.get("environment") or "") == env_id]
+ return {"id": env_id, "harnesses": items}
+
+
# ── Plugins (UHP 2026-09-12, Plugins chapter) ─────────────────────────────────────────────
# A plugin IS an Agent Plugins 1.0.0 package: plugin.json at the root, MCP servers in mcp.json,
# skills under skills/. This gateway reads one the way that specification's client conformance
@@ -15815,6 +16223,7 @@ async def create_harness(org: str, body: HarnessBody, request: Request) -> dict:
workspace = request.headers.get("x-harness-workspace", "")
body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)
body.skills = await _skills_prepare(body.skills)
+ await _environment_check_ref(org, body.environment)
body.plugins = await _plugins_prepare(body, org)
hid = _rid("chrn")
now = str(int(time.time() * 1000))
@@ -15931,6 +16340,7 @@ async def update_harness(org: str, hid: str, body: HarnessBody, request: Request
# coalesce-upsert: created_at/org are untouched (only the provided props are set)
body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)
body.skills = await _skills_prepare(body.skills)
+ await _environment_check_ref(org, body.environment)
body.plugins = await _plugins_prepare(body, org, previous=_plugins_of(cur))
await _vg_upsert("Harness", hid, {**_harness_props(body), "updated_at": str(int(time.time() * 1000))})
# AFTER the write: _harness_props can still refuse this save (an unsupported base), and a
@@ -16079,6 +16489,7 @@ async def create_harness_public(body: HarnessBody, request: Request) -> dict:
raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")
body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)
body.skills = await _skills_prepare(body.skills)
+ await _environment_check_ref(org, body.environment)
body.plugins = await _plugins_prepare(body, org)
hid = _rid("chrn")
now = str(int(time.time() * 1000))
@@ -16210,6 +16621,7 @@ async def _kit_plugin_ensure(org: str, hid: str, v: dict, kit_plugin: dict,
return None
body = HarnessBody(name=str(v.get("name") or ""), base=str(v.get("base") or ""),
plugins=[e for e in have if e["name"] != want["name"]] + [kit_plugin])
+ await _environment_check_ref(org, body.environment)
body.plugins = await _plugins_prepare(body, org, previous=have, reserved_mcp=reserved_mcp)
await _vg_upsert("Harness", hid, {"plugins": json.dumps(body.plugins), "skills": json.dumps([]),
"updated_at": str(int(time.time() * 1000))})
@@ -16353,6 +16765,7 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
body.skills = await _skills_prepare(body.skills)
# The hosted entries launch attaches below (a kit's database, the media server) are names a
# plugin's own servers must not take, so they count as the harness's here.
+ await _environment_check_ref(org, body.environment)
body.plugins = await _plugins_prepare(body, org, reserved_mcp=tuple(
str(d["name"]) for d in (decl, media_decl) if d and d.get("name")))
hid = _rid("chrn")
@@ -17059,6 +17472,7 @@ async def update_harness_public(hid: str, body: HarnessBody, request: Request) -
body.base = str(v.get("base") or body.base)
body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)
body.skills = await _skills_prepare(body.skills)
+ await _environment_check_ref(org, body.environment)
body.plugins = await _plugins_prepare(body, org, previous=_plugins_of(v))
await _vg_upsert("Harness", hid, {**_harness_props(body), "updated_at": str(int(time.time() * 1000))})
# AFTER the write: see update_harness.
diff --git a/gateway/tests/test_environments.py b/gateway/tests/test_environments.py
new file mode 100644
index 00000000..4ab33a98
--- /dev/null
+++ b/gateway/tests/test_environments.py
@@ -0,0 +1,162 @@
+"""Environments (UHP 2026-09-28, Environments chapter), driven through the public surface with the
+runner's own environment module answering behind the gateway's runner call: create and scope, the
+source files, an archive import, a build that becomes the active read-only layer, versions and
+rollback, the harness and task references, deletion."""
+from __future__ import annotations
+
+import io
+import os
+import sys
+import time
+import zipfile
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "runner"))
+import app # noqa: E402
+import environments as E # noqa: E402 (the runner's module)
+
+ORG = "envorg"
+H = {"x-harness-internal": "test-internal-key", "x-harness-org": ORG, "x-harness-member": "[email protected]"}
+
+
[email protected](scope="module")
+def api(tmp_path_factory):
+ """The gateway's app, with the runner's environment routes answering its `_env_runner` calls
+ in-process: real bytes on a temp volume, real builds (a venv with nothing in it, so no network)."""
+ root = tmp_path_factory.mktemp("envstore")
+ E.ENV_ROOT, E.ENV_MOUNT = str(root / "environments"), str(root / "env")
+ E._tool_env = lambda: {**os.environ, "PIP_NO_CACHE_DIR": "1", "PIP_DISABLE_PIP_VERSION_CHECK": "1"}
+ mini = FastAPI()
+ mini.include_router(E.router)
+ rc = TestClient(mini)
+
+ async def fake_env_runner(method, path, env_id, *, params=None, content=None, timeout=120.0):
+ if content is not None and hasattr(content, "__aiter__"):
+ content = b"".join([c async for c in content])
+ return rc.request(method, path, params={"identifier": env_id, **(params or {})}, content=content)
+
+ app._env_runner = fake_env_runner
+ with TestClient(app.app) as c:
+ class Api:
+ def __getattr__(self, m):
+ def call(path, **kw):
+ kw["headers"] = {**H, **(kw.get("headers") or {})}
+ return getattr(c, m)(path, **kw)
+ return call
+ yield Api()
+
+
+def _wait_build(api, eid, n, seconds=240):
+ for _ in range(seconds * 4):
+ b = api.get(f"/v1/environments/{eid}/builds/{n}").json()
+ if b["status"] in ("ready", "failed"):
+ return b
+ time.sleep(0.25)
+ raise AssertionError("build did not finish")
+
+
+def test_an_environment_is_created_with_a_slug_and_an_empty_status(api):
+ r = api.post("/v1/environments", json={"name": "Content Studio", "description": "the studio", "entry": "python3 run.py"})
+ assert r.status_code == 200, r.text
+ e = r.json()
+ assert e["object"] == "environment" and e["id"].startswith("henv_") and e["slug"] == "content-studio"
+ assert e["mount"] == "/env/content-studio" and e["status"] == "empty" and e["version"] is None
+ assert e["entry"] == "python3 run.py" and e["files"] == {"count": 0, "bytes": 0}
+ # one mount per instance: the same name again is refused, a name that is no slug is refused
+ r = api.post("/v1/environments", json={"name": "content studio"})
+ assert r.status_code == 409 and r.json()["error"]["code"] == "environment_exists"
+ r = api.post("/v1/environments", json={"name": "###"})
+ assert r.status_code == 422 and r.json()["error"]["code"] == "environment_invalid"
+ assert any(x["id"] == e["id"] for x in api.get("/v1/environments").json()["environments"])
+
+
+def test_files_go_in_and_come_back_and_a_path_out_of_the_tree_is_refused(api):
+ eid = api.post("/v1/environments", json={"name": "files-env"}).json()["id"]
+ assert api.put(f"/v1/environments/{eid}/files/scripts/render.py", content=b"print('render')\n").status_code == 200
+ assert api.post(f"/v1/environments/{eid}/directories", json={"path": "assets/brand"}).status_code == 200
+ r = api.get(f"/v1/environments/{eid}/files/scripts/render.py")
+ assert r.status_code == 200 and r.content == b"print('render')\n"
+ t = api.get(f"/v1/environments/{eid}/files").json()
+ assert {x["path"] for x in t["entries"]} == {"assets", "assets/brand", "scripts", "scripts/render.py"} and t["count"] == 1
+ r = api.put(f"/v1/environments/{eid}/files/../escape.txt", content=b"x")
+ assert r.status_code in (404, 422) # the router normalises `..` away or the runner refuses it
+ assert api.get(f"/v1/environments/{eid}/files/escape.txt").status_code == 404
+ assert api.delete(f"/v1/environments/{eid}/files/scripts").status_code == 200
+ assert api.get(f"/v1/environments/{eid}/files").json()["count"] == 0
+ assert api.get(f"/v1/environments/{eid}").json()["files"]["count"] == 0
+
+
+def test_an_archive_import_keeps_the_tree(api):
+ eid = api.post("/v1/environments", json={"name": "import-env"}).json()["id"]
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("proj-main/run.py", "print(1)\n")
+ zf.writestr("proj-main/scripts/lib/util.py", "x = 1\n")
+ zf.writestr("proj-main/requirements.txt", "")
+ r = api.post(f"/v1/environments/{eid}/import", content=buf.getvalue(), headers={"content-type": "application/zip"})
+ assert r.status_code == 200 and r.json()["written"] == 3, r.text
+ assert {x["path"] for x in api.get(f"/v1/environments/{eid}/files").json()["entries"] if not x["dir"]} == \
+ {"run.py", "scripts/lib/util.py", "requirements.txt"}
+ r = api.post(f"/v1/environments/{eid}/import", json={"git": {}})
+ assert r.status_code == 422
+
+
+def test_a_build_becomes_the_active_version_and_a_task_may_read_it(api):
+ eid = api.post("/v1/environments", json={"name": "build-env", "entry": "python3 run.py"}).json()["id"]
+ # nothing to read yet: a harness may name it, a task may not run on it
+ h = api.post("/v1/harnesses", json={"name": "env-harness", "base": next(iter(app._BASE_CATALOG)), "environment": eid}).json()
+ assert h["environment"] == eid
+ with pytest.raises(Exception) as ex:
+ import asyncio
+ asyncio.run(app._environment_for_turn(ORG, eid))
+ assert "environment_not_ready" in str(getattr(ex.value, "detail", ex.value))
+ api.put(f"/v1/environments/{eid}/files/run.py", content=b"import sys\nprint(sys.prefix)\n")
+ api.put(f"/v1/environments/{eid}/files/requirements.txt", content=b"")
+ r = api.post(f"/v1/environments/{eid}/build")
+ assert r.status_code == 200 and r.json() == {"id": eid, "object": "environment.build", "version": 1, "status": "building"}
+ assert api.post(f"/v1/environments/{eid}/build").status_code == 409 # one at a time
+ b = _wait_build(api, eid, 1)
+ assert b["status"] == "ready", b.get("log")
+ assert any(pk["manager"] == "pip" for pk in b["packages"]) and "run.py" not in b.get("error", "")
+ e = api.get(f"/v1/environments/{eid}").json()
+ assert e["status"] == "ready" and e["version"] == 1 and e["latestVersion"] == 1
+ assert e["build"]["status"] == "ready" and e["packages"] == b["packages"]
+ spec = __import__("asyncio").run(app._environment_for_turn(ORG, eid))
+ assert spec == {"id": eid, "slug": "build-env", "entry": "python3 run.py", "version": 1, "path": "/env/build-env"}
+ # the runner's view agrees: the mount points at version 1, read-only
+ assert E.active_version(eid) == 1 and os.path.islink(E.mount_path("build-env"))
+ # a second build, then rollback by pointer
+ api.put(f"/v1/environments/{eid}/files/run.py", content=b"print('v2')\n")
+ api.post(f"/v1/environments/{eid}/build")
+ assert _wait_build(api, eid, 2)["status"] == "ready"
+ assert api.get(f"/v1/environments/{eid}").json()["version"] == 2
+ r = api.post(f"/v1/environments/{eid}/versions/1/activate")
+ assert r.status_code == 200 and r.json()["version"] == 1 and r.json()["latestVersion"] == 2
+ assert api.post(f"/v1/environments/{eid}/versions/9/activate").status_code == 409
+ v = api.get(f"/v1/environments/{eid}/versions").json()
+ assert v["active"] == 1 and [x["version"] for x in v["versions"]] == [1, 2]
+ assert api.get(f"/v1/environments/{eid}/harnesses").json()["harnesses"][0]["id"] == h["id"]
+ # the session detail names the environment a turn ran with (stamped by the turn)
+ api.delete(f"/v1/harnesses/{h['id']}")
+ assert api.delete(f"/v1/environments/{eid}").status_code == 200
+ assert api.get(f"/v1/environments/{eid}").status_code == 404
+ assert not os.path.lexists(E.mount_path("build-env"))
+
+
+def test_a_harness_cannot_name_an_environment_that_is_not_there(api):
+ r = api.post("/v1/harnesses", json={"name": "bad-env", "base": next(iter(app._BASE_CATALOG)),
+ "environment": "henv_00000000000000000000000000000000"})
+ assert r.status_code == 404 and r.json()["error"]["code"] == "environment_not_found"
+
+
+def test_environments_are_scoped_to_the_workspace(api):
+ ws = {"x-harness-workspace": "ws1"}
+ eid = api.post("/v1/environments", json={"name": "ws-env"}, headers=ws).json()["id"]
+ assert any(x["id"] == eid for x in api.get("/v1/environments", headers=ws).json()["environments"])
+ assert not any(x["id"] == eid for x in api.get("/v1/environments", headers={"x-harness-workspace": "ws2"}).json()["environments"])
+ assert api.get(f"/v1/environments/{eid}", headers={"x-harness-workspace": "ws2"}).status_code == 404
+ assert any(x["id"] == eid for x in api.get("/v1/environments").json()["environments"]) # an org-wide key sees all
diff --git a/gateway/tests/test_plugins.py b/gateway/tests/test_plugins.py
index bf2e2674..fafef70f 100644
--- a/gateway/tests/test_plugins.py
+++ b/gateway/tests/test_plugins.py
@@ -68,10 +68,10 @@ def _create(api, **cfg):
return r.json()
-def test_discovery_advertises_both_versions_and_the_plugin_schemas(api):
+def test_discovery_advertises_every_version_and_the_plugin_schemas(api):
d = api.get("/v1/uhp").json()
- assert d["versions"] == ["2026-09-12", "2026-08-11"] and d["default_version"] == "2026-09-12"
- assert d["capabilities"]["plugins"] is True
+ assert d["versions"] == ["2026-09-28", "2026-09-12", "2026-08-11"] and d["default_version"] == "2026-09-28"
+ assert d["capabilities"]["plugins"] is True and d["capabilities"]["environments"] is True
assert d["plugin_schemas"] == [MANIFEST_SCHEMA]
# Both versions from one code path: a 2026-08-11 request is honoured and echoed as such.
r = api.get("/v1/uhp", headers={"UHP-Version": "2026-08-11"})
diff --git a/protocol/CHANGELOG.md b/protocol/CHANGELOG.md
index 9263009d..0a5fee75 100644
--- a/protocol/CHANGELOG.md
+++ b/protocol/CHANGELOG.md
@@ -2,6 +2,23 @@
All notable changes to the Unified Harness Protocol.
+## 2026-09-28
+
+Additive to `2026-09-12`: every request and object valid under the previous version is valid here.
+
+- **Environments** ([Environments](versions/2026-09-28/environments.md)), the Environments
+ sub-protocol, optional at every class behind the `environments` capability. An environment is a
+ project's files and installed dependencies, built once and mounted read-only at a fixed path in
+ every session that names it, beside the session's own writable working directory. The chapter
+ defines the object (`henv_`), files by path and whole-project import, builds and versions with
+ an active pointer and rollback, the `environment` field on the harness object and on a task,
+ what a session sees (the mount, the variables, the instruction, the record), and the errors.
+- The session object carries `environment` ([Sessions §3](versions/2026-09-28/sessions.md#3-inspecting-a-session)).
+- New error codes: `environment_not_found`, `environment_not_ready`, `environment_busy`,
+ `environment_exists`, `environment_invalid`, `environment_unavailable`.
+- Conformance suite `2026.9.28`: checks EN-01 to EN-08 (EN-07 runs one task that reads the
+ environment and tries to write it), skipped on a server without the capability.
+
## Conformance suite 2026.9.12.post4 (2026-09-27)
- The public fixture answers at `https://uhp-fixture.harnessrouter.ai/mcp`, the suite's new default;
diff --git a/protocol/README.md b/protocol/README.md
index 605ea4fe..a4af52d7 100644
--- a/protocol/README.md
+++ b/protocol/README.md
@@ -38,9 +38,9 @@ job, not a completion.
| | |
|---|---|
-| **Current version** | `2026-09-12` |
+| **Current version** | `2026-09-28` |
| **Status** | Draft standard — stable enough to build on, versioned so it can change safely |
-| **Specification** | [`versions/2026-09-12/`](versions/2026-09-12/) |
+| **Specification** | [`versions/2026-09-28/`](versions/2026-09-28/) |
| **Machine-readable** | [`schema/`](schema/) — OpenAPI 3.1 + JSON Schema 2020-12 |
| **Conformance suite** | [`conformance/`](conformance/) — runnable, and the definition of "conformant" |
| **Change process** | [`GOVERNANCE.md`](GOVERNANCE.md) |
@@ -65,17 +65,18 @@ your client depends on, that is a specification bug — please
| Chapter | What it defines |
|---|---|
-| [Architecture](versions/2026-09-12/architecture.md) | Roles, conformance classes, and the object model |
-| [Lifecycle](versions/2026-09-12/lifecycle.md) | Version negotiation, capability discovery, task lifecycle |
-| [Harnesses](versions/2026-09-12/harnesses.md) | Discovering, selecting and configuring a harness |
-| [Plugins](versions/2026-09-12/plugins.md) | Packages of tools and skills, installed into a harness as one unit |
-| [Tasks](versions/2026-09-12/tasks.md) | Sending work and receiving a result |
-| [Streaming](versions/2026-09-12/streaming.md) | Following progress as it happens |
-| [Sessions](versions/2026-09-12/sessions.md) | Continuing a conversation, and cancelling one |
-| [Files](versions/2026-09-12/files.md) | Sending files in, getting artifacts out |
-| [Errors](versions/2026-09-12/errors.md) | Failure taxonomy, retries and idempotency |
-| [Security](versions/2026-09-12/security.md) | What an implementer must get right, collected in one place |
-| [Schema](versions/2026-09-12/schema.md) | The machine-readable definitions and how to use them |
+| [Architecture](versions/2026-09-28/architecture.md) | Roles, conformance classes, and the object model |
+| [Lifecycle](versions/2026-09-28/lifecycle.md) | Version negotiation, capability discovery, task lifecycle |
+| [Harnesses](versions/2026-09-28/harnesses.md) | Discovering, selecting and configuring a harness |
+| [Plugins](versions/2026-09-28/plugins.md) | Packages of tools and skills, installed into a harness as one unit |
+| [Environments](versions/2026-09-28/environments.md) | A project's files and installed dependencies, built once and read-only in every session that names it |
+| [Tasks](versions/2026-09-28/tasks.md) | Sending work and receiving a result |
+| [Streaming](versions/2026-09-28/streaming.md) | Following progress as it happens |
+| [Sessions](versions/2026-09-28/sessions.md) | Continuing a conversation, and cancelling one |
+| [Files](versions/2026-09-28/files.md) | Sending files in, getting artifacts out |
+| [Errors](versions/2026-09-28/errors.md) | Failure taxonomy, retries and idempotency |
+| [Security](versions/2026-09-28/security.md) | What an implementer must get right, collected in one place |
+| [Schema](versions/2026-09-28/schema.md) | The machine-readable definitions and how to use them |
## Quick shape of it
@@ -98,13 +99,13 @@ The stream is Server-Sent Events. The last event carries the finished `response`
any files the agent produced. To continue the same conversation, send the next request with
`previous_response_id` set to the id you just received.
-Full walk-through: [Tasks](versions/2026-09-12/tasks.md).
+Full walk-through: [Tasks](versions/2026-09-28/tasks.md).
## Relationship to the OpenAI Responses API
UHP's task surface is deliberately shaped like the OpenAI Responses API, and a conformant server
-MUST accept the subset of that request body described in [Tasks](versions/2026-09-12/tasks.md) and
-emit the event vocabulary described in [Streaming](versions/2026-09-12/streaming.md).
+MUST accept the subset of that request body described in [Tasks](versions/2026-09-28/tasks.md) and
+emit the event vocabulary described in [Streaming](versions/2026-09-28/streaming.md).
This is a compatibility decision, not an accident. Products already have code that speaks Responses;
existing SDKs, streaming parsers, and UI components work against a UHP server with no changes. What
@@ -118,7 +119,7 @@ of an existing field. A client that ignores every UHP extension still gets a wor
## Implementing UHP
-1. Read [Architecture](versions/2026-09-12/architecture.md) and pick a conformance class.
+1. Read [Architecture](versions/2026-09-28/architecture.md) and pick a conformance class.
2. Generate types from [`schema/uhp-2026-09-12.openapi.yaml`](schema/uhp-2026-09-12.openapi.yaml).
3. Run the [conformance suite](conformance/) against your server while you build:
```bash
diff --git a/protocol/VERSIONING.md b/protocol/VERSIONING.md
index 6be9fafb..9a1cd8a8 100644
--- a/protocol/VERSIONING.md
+++ b/protocol/VERSIONING.md
@@ -2,8 +2,8 @@
## The scheme
-UHP versions are dates — `YYYY-MM-DD`, the day the version was published. `2026-09-12` is the
-current version; `2026-08-11` remains published and served.
+UHP versions are dates — `YYYY-MM-DD`, the day the version was published. `2026-09-28` is the
+current version; `2026-09-12` and `2026-08-11` remain published and served.
Dates were chosen over semantic versioning deliberately. SemVer's promise is that a major bump means
"expect breakage" and a minor bump means "safe" — a promise that is only as good as the discipline
@@ -52,8 +52,8 @@ A server MUST:
2. Reject an unsupported requested version with `unsupported_protocol_version` rather than serving a
different one.
3. Support at least one full version at a time, and SHOULD support the previous version for at least
- six months after a new one is published. When the newer version is additive, as `2026-09-12` is
- to `2026-08-11`, both are served from one code path: the same objects answer either request,
+ six months after a new one is published. When the newer version is additive, as `2026-09-28` is
+ to `2026-09-12` and that one to `2026-08-11`, all are served from one code path: the same objects answer either request,
and the only difference a client sees is the version echoed in the header.
## Deprecation
diff --git a/protocol/conformance/pyproject.toml b/protocol/conformance/pyproject.toml
index 06a57b26..aa8a0e78 100644
--- a/protocol/conformance/pyproject.toml
+++ b/protocol/conformance/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "uhp-conformance"
-version = "2026.9.12.post4"
+version = "2026.9.28"
description = "Conformance suite for the Unified Harness Protocol (UHP)"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/protocol/conformance/uhp_conformance/__init__.py b/protocol/conformance/uhp_conformance/__init__.py
index 5877a3d7..0648d830 100644
--- a/protocol/conformance/uhp_conformance/__init__.py
+++ b/protocol/conformance/uhp_conformance/__init__.py
@@ -1,6 +1,6 @@
"""UHP conformance suite — the definition of "conformant" for the Unified Harness Protocol."""
__version__ = "2026.9.12.post4"
-UHP_VERSION = "2026-09-12"
+UHP_VERSION = "2026-09-28"
# The MCP server the plugin checks point a plugin at. It must resolve and answer: a host is
# allowed to refuse a server it cannot reach at configuration time and record that in `skipped`,
# so an unresolvable placeholder made those checks measure the refusal instead of the plugin. The
diff --git a/protocol/conformance/uhp_conformance/checks.py b/protocol/conformance/uhp_conformance/checks.py
index 4d723c1f..16575d51 100644
--- a/protocol/conformance/uhp_conformance/checks.py
+++ b/protocol/conformance/uhp_conformance/checks.py
@@ -18,7 +18,7 @@ import uuid
from .registry import Skip, check
-SPEC = "protocol/versions/2026-09-12"
+SPEC = "protocol/versions/2026-09-28"
# ── shared fixtures ────────────────────────────────────────────────────────────────────
@@ -1714,3 +1714,221 @@ def r08(ctx):
# would diagnose one bug twice.
ctx.client.delete(f"/v1/sessions/{sid}/share")
return "published with no body"
+
+
+# ══════════════════════════════════════════════════════════════════════════════════════
+# Environments (2026-09-28) — optional capability; a project's files and installed dependencies,
+# built once and read by every session that names it. Checks EN-01 to EN-06 need no model: they
+# drive the object, its files, a build and the reference. EN-07 runs one task on it.
+# ══════════════════════════════════════════════════════════════════════════════════════
+def _environments_supported(ctx) -> None:
+ d = ctx.state.get("discovery") or ctx.client.get("/v1/uhp", auth=False).json or {}
+ ctx.state["discovery"] = d
+ if not (d.get("capabilities") or {}).get("environments"):
+ raise Skip("this server reports the environments capability false or absent, and the "
+ "Environments chapter is optional at every class")
+
+
+def _managed_environment(ctx) -> dict:
+ """One environment for the whole series, created once with a file and an empty requirements
+ manifest (a build that needs no network), remembered for cleanup."""
+ if ctx.state.get("environment"):
+ return ctx.state["environment"]
+ r = ctx.client.post("/v1/environments", body={"name": f"uhp-conformance-{uuid.uuid4().hex[:6]}",
+ "description": "the conformance suite's environment",
+ "entry": "python3 run.py"})
+ assert r.status == 200, f"POST /v1/environments returned HTTP {r.status}: {r.text[:200]}"
+ e = r.json or {}
+ ctx.validate(e, "Environment")
+ ctx.state["environment"] = e
+ ctx.state.setdefault("_cleanup_environments", []).append(e.get("id"))
+ return e
+
+
+def _built_environment(ctx) -> dict:
+ """The environment with a finished build, waited for once."""
+ e = _managed_environment(ctx)
+ if ctx.state.get("environment_built"):
+ return ctx.state["environment_built"]
+ eid = e["id"]
+ for path, body in (("run.py", b"import sys\nprint(sys.prefix)\n"), ("requirements.txt", b""),
+ ("data/hello.txt", b"hello from the environment\n")):
+ r = ctx.client.put(f"/v1/environments/{eid}/files/{path}", raw=body, content_type="application/octet-stream")
+ assert r.status == 200, f"PUT files/{path} returned HTTP {r.status}: {r.text[:200]}"
+ r = ctx.client.post(f"/v1/environments/{eid}/build")
+ assert r.status == 200, f"POST build returned HTTP {r.status}: {r.text[:200]}"
+ n = int((r.json or {}).get("version") or 0)
+ assert n >= 1, f"the build did not name a version: {r.json}"
+ deadline = time.time() + ctx.task_timeout
+ rec = {}
+ while time.time() < deadline:
+ rec = ctx.client.get(f"/v1/environments/{eid}/builds/{n}").json or {}
+ if rec.get("status") in ("ready", "failed"):
+ break
+ time.sleep(2)
+ assert rec.get("status") == "ready", f"the build did not become ready: {rec.get('status')!r} {str(rec.get('error') or '')[:200]}"
+ e = ctx.client.get(f"/v1/environments/{eid}").json or {}
+ ctx.state["environment_built"] = e
+ return e
+
+
+@check("EN-01", "An environment is created with a fixed mount path and reads back", "full",
+ f"{SPEC}/environments.md#2-the-environment-object")
+def en01(ctx):
+ _environments_supported(ctx)
+ e = _managed_environment(ctx)
+ assert str(e.get("id") or "").startswith("henv_"), f"id {e.get('id')!r} does not carry the henv_ prefix"
+ assert e.get("status") == "empty" and e.get("version") is None, (
+ f"a new environment must be empty with no version; got status={e.get('status')!r} version={e.get('version')!r}")
+ assert str(e.get("mount") or "").startswith("/") and e["mount"].endswith("/" + e["slug"]), (
+ f"mount {e.get('mount')!r} must be an absolute path ending in the slug {e.get('slug')!r}")
+ got = ctx.client.get(f"/v1/environments/{e['id']}").json or {}
+ ctx.validate(got, "Environment")
+ assert got.get("slug") == e["slug"] and got.get("mount") == e["mount"], "the slug and mount must be stable across reads"
+ return f"{e['id']} at {e['mount']}"
+
+
+@check("EN-02", "Files go in by path and come back byte for byte; escapes are refused", "full",
+ f"{SPEC}/environments.md#3-files")
+def en02(ctx):
+ _environments_supported(ctx)
+ e = _managed_environment(ctx)
+ eid = e["id"]
+ body = b"nested\x00bytes\n"
+ r = ctx.client.put(f"/v1/environments/{eid}/files/probe/nested/blob.bin", raw=body, content_type="application/octet-stream")
+ assert r.status == 200, f"PUT returned HTTP {r.status}"
+ r = ctx.client.get(f"/v1/environments/{eid}/files/probe/nested/blob.bin")
+ assert r.status == 200 and r.raw == body, "the bytes must come back exactly as sent"
+ tree = ctx.client.get(f"/v1/environments/{eid}/files").json or {}
+ ctx.validate(tree, "EnvironmentFileList")
+ paths = {x.get("path") for x in tree.get("entries") or []}
+ assert "probe/nested/blob.bin" in paths and "probe/nested" in paths, f"the tree must list the file and its directories: {sorted(paths)[:10]}"
+ r = ctx.client.put(f"/v1/environments/{eid}/files/..%2Fescape.txt", raw=b"no", content_type="application/octet-stream")
+ assert r.status in (400, 404, 422), f"a path that escapes the root must be refused, got HTTP {r.status}"
+ assert ctx.client.delete(f"/v1/environments/{eid}/files/probe").status == 200, "a directory tree is removable"
+ paths = {x.get("path") for x in (ctx.client.get(f"/v1/environments/{eid}/files").json or {}).get("entries") or []}
+ assert "probe" not in paths, "the removed tree must be gone"
+ return "round trip, tree, escape refused, removal"
+
+
+@check("EN-03", "A build snapshots the source and becomes the active version", "full",
+ f"{SPEC}/environments.md#4-builds-and-versions")
+def en03(ctx):
+ _environments_supported(ctx)
+ e = _built_environment(ctx)
+ assert e.get("status") == "ready" and e.get("version") == 1, f"after the first build: status={e.get('status')!r} version={e.get('version')!r}"
+ vers = ctx.client.get(f"/v1/environments/{e['id']}/versions").json or {}
+ assert vers.get("active") == 1 and [v.get("version") for v in vers.get("versions") or []] == [1], f"versions: {vers}"
+ b = ctx.client.get(f"/v1/environments/{e['id']}/builds/1").json or {}
+ ctx.validate(b, "EnvironmentBuild")
+ assert b.get("status") == "ready" and isinstance(b.get("packages"), list), "a ready build lists its packages"
+ return f"version 1 ready, {len(b.get('packages') or [])} packages"
+
+
+@check("EN-04", "Editing the source changes nothing until the next build; rollback is a pointer", "full",
+ f"{SPEC}/environments.md#4-builds-and-versions")
+def en04(ctx):
+ _environments_supported(ctx)
+ e = _built_environment(ctx)
+ eid = e["id"]
+ ctx.client.put(f"/v1/environments/{eid}/files/data/hello.txt", raw=b"changed\n", content_type="application/octet-stream")
+ assert (ctx.client.get(f"/v1/environments/{eid}").json or {}).get("version") == 1, "an edit must not change the active version"
+ r = ctx.client.post(f"/v1/environments/{eid}/build")
+ assert r.status == 200 and (r.json or {}).get("version") == 2, f"the second build must be version 2: HTTP {r.status} {r.json}"
+ deadline = time.time() + ctx.task_timeout
+ rec = {}
+ while time.time() < deadline:
+ rec = ctx.client.get(f"/v1/environments/{eid}/builds/2").json or {}
+ if rec.get("status") in ("ready", "failed"):
+ break
+ time.sleep(2)
+ assert rec.get("status") == "ready", f"build 2: {rec.get('status')!r} {str(rec.get('error') or '')[:200]}"
+ assert (ctx.client.get(f"/v1/environments/{eid}").json or {}).get("version") == 2, "a finished build becomes the active version"
+ r = ctx.client.post(f"/v1/environments/{eid}/versions/1/activate")
+ assert r.status == 200 and (r.json or {}).get("version") == 1, f"activating version 1 must make it active: HTTP {r.status} {r.json}"
+ r = ctx.client.post(f"/v1/environments/{eid}/versions/99/activate")
+ assert r.status in (404, 409), f"activating a version that was never built must be refused, got HTTP {r.status}"
+ assert _error_code(r) in ("environment_not_ready", "not_found", ""), f"unexpected code {_error_code(r)!r}"
+ return "edit invisible, build 2 active, rollback to 1"
+
+
+@check("EN-05", "A harness names an environment; a task on an unbuilt one is refused before it starts", "full",
+ f"{SPEC}/environments.md#5-attaching-an-environment")
+def en05(ctx):
+ _environments_supported(ctx)
+ e = _built_environment(ctx)
+ h = _managed_harness(ctx, environment=e["id"])
+ got = ctx.client.get(f"/v1/harnesses/{h['id']}").json or {}
+ assert got.get("environment") == e["id"], f"the harness must report the environment it names: {got.get('environment')!r}"
+ r = ctx.client.post("/v1/harnesses", body={"name": "uhp-conformance-bad-env", "base": _supported_base(ctx),
+ "environment": "henv_00000000000000000000000000000000"})
+ assert r.status == 404 and _error_code(r) == "environment_not_found", (
+ f"a harness naming an environment that is not there must be refused with environment_not_found: HTTP {r.status} {_error_code(r)!r}")
+ if r.status == 200:
+ ctx.client.delete(f"/v1/harnesses/{(r.json or {}).get('id')}")
+ empty = ctx.client.post("/v1/environments", body={"name": f"uhp-conformance-empty-{uuid.uuid4().hex[:6]}"}).json or {}
+ ctx.state.setdefault("_cleanup_environments", []).append(empty.get("id"))
+ r = ctx.client.post("/v1/responses", body={"input": PROMPT, "metadata": {"harness_id": h["id"]},
+ "environment": empty.get("id"), "stream": False})
+ assert r.status == 409 and _error_code(r) == "environment_not_ready", (
+ f"a task on an environment with nothing built must be refused with environment_not_ready before it starts: HTTP {r.status} {_error_code(r)!r}")
+ return "harness reference reads back; unknown refused; unbuilt refused"
+
+
+@check("EN-06", "The environment's harness list names the harness that reads it", "full",
+ f"{SPEC}/environments.md#5-attaching-an-environment")
+def en06(ctx):
+ _environments_supported(ctx)
+ e = _built_environment(ctx)
+ h = _managed_harness(ctx, environment=e["id"])
+ ids = {x.get("id") for x in (ctx.client.get(f"/v1/environments/{e['id']}/harnesses").json or {}).get("harnesses") or []}
+ assert h["id"] in ids, "the harness that names the environment must be listed"
+ return f"{len(ids)} harness(es) read it"
+
+
+@check("EN-07", "A task reads the environment at its mount path, read-only, and its session names it", "full",
+ f"{SPEC}/environments.md#6-what-a-session-sees")
+def en07(ctx):
+ _environments_supported(ctx)
+ e = _built_environment(ctx)
+ h = _managed_harness(ctx, environment=e["id"])
+ mount = e["mount"]
+ body = {"input": (f"Run this shell command and reply with its output only, nothing else: "
+ f"cat {mount}/data/hello.txt; touch {mount}/write-probe 2>&1 | tail -1; echo WRITE_RC=$?"),
+ "metadata": {"harness_id": h["id"]}, "stream": False}
+ if ctx.model:
+ body["model"] = ctx.model
+ r = ctx.client.post("/v1/responses", body=body)
+ assert r.status == 200, f"the task did not start: HTTP {r.status} {r.text[:200]}"
+ resp = r.json or {}
+ text = " ".join(str(c.get("text") or "") for it in resp.get("output") or [] for c in it.get("content") or [] if isinstance(c, dict))
+ assert "hello from the environment" in text, f"the agent could not read the file at {mount}: {text[-300:]!r}"
+ assert "WRITE_RC=0" not in text or "denied" in text.lower() or "read-only" in text.lower(), (
+ f"a write under {mount} must fail (the layer is read-only): {text[-300:]!r}")
+ sid = str(((resp.get("metadata") or {}).get("session_id")) or "")
+ if sid:
+ s = ctx.client.get(f"/v1/sessions/{sid}").json or {}
+ assert s.get("environment") == e["id"], f"the session must name the environment its turn read: {s.get('environment')!r}"
+ return f"read {mount}/data/hello.txt; write refused"
+
+
+@check("EN-08", "Configured environments are cleaned up", "full", f"{SPEC}/environments.md#2-the-environment-object")
+def en08(ctx):
+ ids = [i for i in ctx.state.get("_cleanup_environments") or [] if i]
+ if not ids:
+ raise Skip("no environments were created by earlier checks")
+ # the harnesses that named them go first (F-07 ran before this series existed; its list is spent)
+ for hid in [i for i in ctx.state.get("_cleanup_harnesses") or [] if i]:
+ ctx.client.delete(f"/v1/harnesses/{hid}")
+ left = []
+ for eid in ids:
+ r = ctx.client.delete(f"/v1/environments/{eid}")
+ if r.status == 409: # a build still running: wait for it, then delete
+ for _ in range(60):
+ time.sleep(2)
+ if ctx.client.delete(f"/v1/environments/{eid}").status == 200:
+ break
+ if ctx.client.get(f"/v1/environments/{eid}").status != 404:
+ left.append(eid)
+ assert not left, f"these environments still resolve after delete: {left}"
+ return f"{len(ids)} removed"
diff --git a/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json b/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json
new file mode 100644
index 00000000..773c8bd5
--- /dev/null
+++ b/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json
@@ -0,0 +1,1764 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://unifiedharnessprotocol.org/schema/uhp-2026-09-28.schema.json",
+ "title": "Unified Harness Protocol",
+ "description": "Object definitions for UHP 2026-09-28. Generated from uhp-2026-09-28.openapi.yaml by build.py — do not edit by hand.",
+ "$defs": {
+ "Discovery": {
+ "type": "object",
+ "required": [
+ "object",
+ "protocol",
+ "versions",
+ "default_version",
+ "conformance_class",
+ "capabilities"
+ ],
+ "properties": {
+ "object": {
+ "type": "string",
+ "const": "uhp.discovery"
+ },
+ "protocol": {
+ "type": "string",
+ "const": "uhp"
+ },
+ "versions": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "string"
+ }
+ },
+ "default_version": {
+ "type": "string"
+ },
+ "conformance_class": {
+ "type": "string",
+ "enum": [
+ "core",
+ "extended",
+ "full"
+ ]
+ },
+ "capabilities": {
+ "$ref": "#/$defs/Capabilities"
+ },
+ "plugin_schemas": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": "The Agent Plugins manifest schema identifiers this server installs. Present and non-empty\nwhen `capabilities.plugins` is true.\n",
+ "examples": [
+ [
+ "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"
+ ]
+ ]
+ },
+ "implementation": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ }
+ },
+ "additionalProperties": true
+ },
+ "Capabilities": {
+ "type": "object",
+ "description": "Named booleans. A server reports `false` for a capability it does not implement rather than\nomitting it, so a client can distinguish \"not supported\" from \"server predates this field\".\nA client treats an absent key as `false`.\n",
+ "properties": {
+ "streaming": {
+ "type": "boolean"
+ },
+ "sessions": {
+ "type": "boolean"
+ },
+ "cancellation": {
+ "type": "boolean"
+ },
+ "files_input": {
+ "type": "boolean"
+ },
+ "files_output": {
+ "type": "boolean"
+ },
+ "session_listing": {
+ "type": "boolean"
+ },
+ "harness_management": {
+ "type": "boolean"
+ },
+ "session_sharing": {
+ "type": "boolean"
+ },
+ "idempotency": {
+ "type": "boolean"
+ },
+ "plugins": {
+ "type": "boolean",
+ "description": "The server installs Agent Plugins packages into harnesses, serves their files, and exports\na harness as a package. Optional at every class.\n"
+ },
+ "environments": {
+ "type": "boolean",
+ "description": "The server holds environments: a project's files and installed dependencies, built once,\nread-only at a fixed path in every session that names one. Optional at every class.\n"
+ }
+ },
+ "additionalProperties": {
+ "type": "boolean"
+ }
+ },
+ "Harness": {
+ "type": "object",
+ "required": [
+ "id",
+ "name",
+ "base"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^chrn_"
+ },
+ "object": {
+ "type": "string",
+ "const": "harness"
+ },
+ "name": {
+ "type": "string"
+ },
+ "base": {
+ "type": "string",
+ "description": "Opaque. Not enumerated by this specification — a client must treat it as a string, or the\nprotocol would need revising every time a harness is released.\n",
+ "examples": [
+ "codex",
+ "claude-code",
+ "hermes"
+ ]
+ },
+ "baseLabel": {
+ "type": "string"
+ },
+ "defaultModel": {
+ "type": "string"
+ },
+ "systemPrompt": {
+ "type": "string"
+ },
+ "mcpServers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/McpServer"
+ }
+ },
+ "skills": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Skill"
+ }
+ },
+ "plugins": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Plugin"
+ },
+ "description": "Installed plugins. Their servers and skills join the harness's own for every turn;\n`mcpServers` and `skills` above report only what was written to them directly.\n"
+ },
+ "environment": {
+ "type": "string",
+ "description": "The environment (`henv_`) this harness's tasks read, mounted read-only at its `mount`;\nempty when none. A task may name another with its own `environment` field.\n"
+ },
+ "disabledTools": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "maxStep": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "timeoutSeconds": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "createdAt": {
+ "type": "integer",
+ "description": "Unix milliseconds"
+ }
+ },
+ "additionalProperties": true
+ },
+ "McpServer": {
+ "type": "object",
+ "required": [
+ "name",
+ "url"
+ ],
+ "description": "A remote MCP server attached to a harness. Only enabled entries are connected for a turn; a\ndisabled entry must not be contacted at all. An unreachable server must not fail the task.\nUnchanged from 2026-08-11: a process (stdio) server is declared inside a plugin, see\nPluginMcpServer.\n",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Sanitised to a CLI-safe identifier by the server."
+ },
+ "url": {
+ "type": "string",
+ "format": "uri"
+ },
+ "transport": {
+ "type": "string",
+ "enum": [
+ "http",
+ "sse"
+ ],
+ "default": "http"
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "auth": {
+ "type": "string",
+ "description": "Bearer token, or a server-side reference the server resolves. A server must never return\na resolved credential to a client.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "PluginMcpServer": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "description": "An MCP server a plugin's mcp.json declares, derived by the server. The harness MCP server\nobject plus the `stdio` transport: `url` is required for `http` and `sse`, `command` for\n`stdio`. Placeholders are reported unexpanded; `enabled` is always true, the plugin's own\n`enabled` governs.\n",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "transport": {
+ "type": "string",
+ "enum": [
+ "http",
+ "sse",
+ "stdio"
+ ],
+ "default": "http",
+ "description": "`http` is Streamable HTTP (`streamable-http` in mcp.json); `sse` the older HTTP+SSE\ntransport; `stdio` a process the server launches inside the agent's sandbox.\n"
+ },
+ "url": {
+ "type": "string",
+ "format": "uri",
+ "description": "Endpoint (`http` and `sse`)."
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "Fixed request headers (`http` and `sse`). Never subject to placeholder expansion."
+ },
+ "command": {
+ "type": "string",
+ "description": "One executable token (`stdio`): a bare name resolved on the sandbox's search path, or a\nplugin-relative path beginning with `./`. Never a shell string, never expanded.\n"
+ },
+ "args": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Arguments (`stdio`). `${PLUGIN_ROOT}` and `${PLUGIN_DATA}` expand at run time."
+ },
+ "env": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "Environment overlay (`stdio`). Must not name PLUGIN_ROOT or PLUGIN_DATA; the server sets\nthose. Values expand at run time.\n"
+ },
+ "cwd": {
+ "type": "string",
+ "description": "Working directory (`stdio`). Defaults to the plugin root; must stay within the plugin\nroot or PLUGIN_DATA.\n"
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true
+ }
+ },
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "transport": {
+ "const": "stdio"
+ }
+ },
+ "required": [
+ "transport"
+ ]
+ },
+ "then": {
+ "required": [
+ "command"
+ ]
+ },
+ "else": {
+ "required": [
+ "url"
+ ]
+ }
+ }
+ ],
+ "additionalProperties": true
+ },
+ "Skill": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "description": "A skill is a FOLDER, not a file. A server must materialise the whole folder where the agent\ncan read it — materialising only SKILL.md breaks every skill carrying references, scripts or\ndata. Round-tripping a harness through GET and PUT must not lose skill contents.\n",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true,
+ "description": "false suppresses the skill, including one inherited from the base."
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/SkillFile"
+ },
+ "description": "The bundle. Must contain a SKILL.md."
+ },
+ "content": {
+ "type": "string",
+ "description": "Shorthand for a single-file bundle whose only member is SKILL.md."
+ },
+ "blob": {
+ "type": "string",
+ "description": "Server-assigned handle for a bundle stored out of line. A client receives it, passes it\nback unchanged, and reads the files from the skill files endpoint.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "SkillFile": {
+ "type": "object",
+ "required": [
+ "path"
+ ],
+ "description": "One file of a skill folder or of a plugin package.",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Relative to the skill's own folder, or to the plugin root; nested directories are\nsupported. A server must reject a path that escapes the folder.\n",
+ "examples": [
+ "SKILL.md",
+ "references/codes.md",
+ "assets/logo.png"
+ ]
+ },
+ "content": {
+ "type": "string",
+ "description": "Text content."
+ },
+ "content_b64": {
+ "type": "string",
+ "description": "Base64 for binary content; preserved byte-for-byte."
+ }
+ },
+ "additionalProperties": true
+ },
+ "FileList": {
+ "type": "object",
+ "required": [
+ "files"
+ ],
+ "properties": {
+ "files": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/SkillFile"
+ }
+ }
+ }
+ },
+ "Plugin": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "description": "An Agent Plugins package installed into a harness: `plugin.json` at the root, MCP servers in\n`mcp.json`, skills under `skills/`. A client writes `files` (or passes back `blob`) and\noptionally `name` and `enabled`; the server derives `manifest`, `mcpServers`, `skills` and\n`skipped` from the package on every write and ignores those fields on input. A refused\npackage leaves the harness unchanged.\n",
+ "properties": {
+ "name": {
+ "type": "string",
+ "pattern": "^(?!.*(--|\\.\\.))[a-z0-9]([a-z0-9.-]*[a-z0-9])?$",
+ "maxLength": 64,
+ "description": "The manifest's `name`. Optional on write; if sent it must equal the manifest's."
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true,
+ "description": "false keeps the plugin installed and inert; nothing in it is materialised or contacted."
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/SkillFile"
+ },
+ "description": "The package. Must contain `plugin.json` at its root."
+ },
+ "blob": {
+ "type": "string",
+ "description": "Server-assigned handle for a package stored out of line. A client passes it back unchanged\nand reads the files from the plugin files endpoint.\n"
+ },
+ "manifest": {
+ "$ref": "#/$defs/PluginManifest"
+ },
+ "mcpServers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PluginMcpServer"
+ },
+ "description": "Derived from `mcp.json`. Placeholders are reported unexpanded; `enabled` is always true,\nthe plugin's own `enabled` governs.\n"
+ },
+ "skills": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PluginSkill"
+ },
+ "description": "Derived from `skills/`, one entry per immediate child directory with a SKILL.md."
+ },
+ "skipped": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PluginSkipped"
+ },
+ "description": "What the server found and could not load. Present on every plugin object the server\nreturns, empty when nothing was skipped.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "PluginManifest": {
+ "type": "object",
+ "required": [
+ "$schema",
+ "name"
+ ],
+ "description": "`plugin.json`, parsed. Mirrors the Agent Plugins 1.0.0 manifest schema\n(https://agent-plugins.org/schemas/1.0.0/plugin.schema.json, Apache-2.0) field for field, and\npermits additional properties because a UHP client ignores fields it does not know. The\nschema a manifest's own `$schema` names is authoritative; a server validates against that.\n",
+ "properties": {
+ "$schema": {
+ "type": "string",
+ "format": "uri"
+ },
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "pattern": "^(?!.*(--|\\.\\.))[a-z0-9]([a-z0-9.-]*[a-z0-9])?$"
+ },
+ "version": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "author": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "email": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "homepage": {
+ "type": "string"
+ },
+ "repository": {
+ "type": "string"
+ },
+ "license": {
+ "type": "string"
+ },
+ "keywords": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "extensions": {
+ "type": "object",
+ "description": "Client-specific data keyed by reverse-domain namespace, per Agent Plugins §8.",
+ "additionalProperties": {
+ "type": "object"
+ }
+ }
+ },
+ "additionalProperties": true
+ },
+ "PluginSkill": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The SKILL.md frontmatter name",
+ "equal to the directory name.": null
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "PluginSkipped": {
+ "type": "object",
+ "required": [
+ "path",
+ "reason"
+ ],
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Where in the package, e.g. `skills/broken`, `mcp.json#/mcpServers/redline`, `plugin.json#/vendorField`.",
+ "examples": [
+ "skills/broken",
+ "mcp.json#/mcpServers/redline"
+ ]
+ },
+ "reason": {
+ "type": "string",
+ "description": "One sentence."
+ }
+ },
+ "additionalProperties": true
+ },
+ "HarnessCreate": {
+ "type": "object",
+ "required": [
+ "base"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "base": {
+ "type": "string"
+ },
+ "default_model": {
+ "type": "string"
+ },
+ "system_prompt": {
+ "type": "string"
+ },
+ "mcp_servers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/McpServer"
+ }
+ },
+ "skills": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Skill"
+ }
+ },
+ "plugins": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Plugin"
+ },
+ "description": "Requires the `plugins` capability. Each item needs `files` or `blob`."
+ },
+ "environment": {
+ "type": "string",
+ "description": "An environment id of the caller's scope",
+ "or empty. Requires the `environments` capability.": null
+ },
+ "disabled_tools": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "max_step": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "timeout_seconds": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "additionalProperties": true
+ },
+ "ModelCatalog": {
+ "type": "object",
+ "required": [
+ "backends"
+ ],
+ "properties": {
+ "backends": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "object",
+ "required": [
+ "default",
+ "models"
+ ],
+ "properties": {
+ "default": {
+ "type": "string"
+ },
+ "models": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Model"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "HarnessModels": {
+ "type": "object",
+ "required": [
+ "models"
+ ],
+ "properties": {
+ "harness_id": {
+ "type": "string"
+ },
+ "backend": {
+ "type": "string"
+ },
+ "default": {
+ "type": "string"
+ },
+ "fallback": {
+ "type": "string"
+ },
+ "models": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Model"
+ }
+ }
+ }
+ },
+ "Model": {
+ "type": "object",
+ "required": [
+ "id",
+ "available"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "label": {
+ "type": "string"
+ },
+ "backend": {
+ "type": "string"
+ },
+ "available": {
+ "type": "boolean",
+ "description": "Computed, not asserted: true means the server can serve this model for this harness right\nnow. Listing a model as available and then failing the task is the worst outcome for a\nclient, because a user has already chosen it.\n"
+ },
+ "default": {
+ "type": "boolean"
+ }
+ },
+ "additionalProperties": true
+ },
+ "CreateResponseRequest": {
+ "type": "object",
+ "required": [
+ "input"
+ ],
+ "properties": {
+ "input": {
+ "oneOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ ],
+ "description": "A bare string is shorthand for one user message."
+ },
+ "model": {
+ "type": "string",
+ "description": "Canonical model id. Omitted means the harness default."
+ },
+ "metadata": {
+ "type": "object",
+ "description": "Client metadata. `harness_id` selects the configured harness.",
+ "properties": {
+ "harness_id": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "stream": {
+ "type": "boolean",
+ "default": false
+ },
+ "previous_response_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "instructions": {
+ "type": "string"
+ },
+ "store": {
+ "type": "boolean",
+ "default": true
+ },
+ "max_output_tokens": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "max_step": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "description": "Agent step (tool-call round) budget"
+ },
+ "timeout_seconds": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "description": "Wall-clock budget"
+ },
+ "environment": {
+ "type": "string",
+ "description": "The environment this task reads, overriding the harness's. Refused with\n`environment_not_found` or `environment_not_ready` before the task starts.\n"
+ },
+ "tools": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ },
+ "description": "Reserved and ignored. Accepted for wire compatibility, never acted on, and reported in\n`metadata.ignored_fields` on the response. A UHP harness invokes and executes tools\nitself and reports them in `output`; there is no input path for a tool result, so the\nclient-executed tool loop this field implies cannot be completed by a conformant server.\nConfigure tools on the harness instead — see Harnesses §4.1. Tasks §1.4.\n"
+ },
+ "include": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Reserved and ignored. Accepted for wire compatibility, never acted on, and reported in\n`metadata.ignored_fields` on the response. No values are enumerated, so any string a\nserver recognised would be one it named itself. Tasks §1.4.\n"
+ },
+ "background": {
+ "type": "boolean",
+ "default": false
+ }
+ },
+ "additionalProperties": true
+ },
+ "Response": {
+ "type": "object",
+ "required": [
+ "id",
+ "object",
+ "created_at",
+ "status",
+ "output",
+ "model"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^resp_"
+ },
+ "object": {
+ "type": "string",
+ "const": "response"
+ },
+ "created_at": {
+ "type": "integer",
+ "description": "Unix seconds"
+ },
+ "status": {
+ "$ref": "#/$defs/ResponseStatus"
+ },
+ "error": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/$defs/Error"
+ }
+ ],
+ "description": "Non-null only when status is `failed`."
+ },
+ "incomplete_details": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "additionalProperties": true
+ },
+ "previous_response_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "model": {
+ "type": "string",
+ "description": "The model that actually ran."
+ },
+ "output": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/OutputItem"
+ }
+ },
+ "store": {
+ "type": "boolean"
+ },
+ "usage": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/$defs/Usage"
+ }
+ ],
+ "description": "null when the server cannot account for usage. A fabricated zero would be worse than an\nhonest absence, because a client cannot tell it from a free task.\n"
+ },
+ "metadata": {
+ "type": "object",
+ "properties": {
+ "session_id": {
+ "type": "string"
+ },
+ "requested_model": {
+ "type": "string",
+ "description": "Present when the server ran a different model than was requested."
+ },
+ "model_fallback": {
+ "type": "boolean"
+ },
+ "model_fallback_reason": {
+ "type": "string"
+ },
+ "ignored_fields": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Request fields the server did not act on, by name, in any order. Required when the\nrequest carried `tools` or `include`, which are reserved and ignored. A silently\nignored field is indistinguishable from an honoured one. Tasks §1.1 and §1.4.\n"
+ }
+ },
+ "additionalProperties": true
+ }
+ },
+ "additionalProperties": true
+ },
+ "ResponseStatus": {
+ "type": "string",
+ "enum": [
+ "in_progress",
+ "completed",
+ "failed",
+ "incomplete",
+ "cancelled"
+ ],
+ "description": "`incomplete` means a budget stopped the work and is usually worth continuing.\n`failed` means it could not be done. `cancelled` means the client asked for a stop, and must\nnever be reported as `failed`.\n"
+ },
+ "OutputItem": {
+ "type": "object",
+ "required": [
+ "type"
+ ],
+ "description": "A client must tolerate item types it does not recognise. A client that renders only `message`\nitems and ignores the rest is a valid client.\n",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string",
+ "examples": [
+ "message",
+ "reasoning",
+ "function_call",
+ "function_call_output"
+ ]
+ },
+ "status": {
+ "type": "string"
+ },
+ "role": {
+ "type": "string"
+ },
+ "content": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/ContentPart"
+ }
+ },
+ "summary": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "call_id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "arguments": {
+ "type": "string",
+ "description": "JSON",
+ "as a string": null
+ },
+ "output": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "ContentPart": {
+ "type": "object",
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "examples": [
+ "output_text"
+ ]
+ },
+ "text": {
+ "type": "string"
+ },
+ "annotations": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Annotation"
+ }
+ }
+ },
+ "additionalProperties": true
+ },
+ "Annotation": {
+ "type": "object",
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "container_file_citation"
+ },
+ "container_id": {
+ "type": "string"
+ },
+ "file_id": {
+ "type": "string"
+ },
+ "filename": {
+ "type": "string"
+ },
+ "download_url": {
+ "type": "string",
+ "format": "uri"
+ },
+ "start_index": {
+ "type": "integer"
+ },
+ "end_index": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "Usage": {
+ "type": "object",
+ "properties": {
+ "input_tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "output_tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "total_tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "cache_read_tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "cache_write_tokens": {
+ "type": "integer",
+ "minimum": 0
+ }
+ },
+ "additionalProperties": true
+ },
+ "SessionShare": {
+ "type": "object",
+ "description": "A published read-only view of a session (Sessions §5). `url` may be relative, resolving\nagainst the base URL the caller is already using — a server behind a proxy cannot know its\npublic origin, and a base-relative path survives every fronting. The share's id MUST NOT\nfunction as a credential for the rest of the API.\n",
+ "required": [
+ "id",
+ "url"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "description": "SHOULD be \"session.share\""
+ },
+ "enabled": {
+ "type": "boolean"
+ }
+ },
+ "additionalProperties": true
+ },
+ "TurnItem": {
+ "type": "object",
+ "description": "One turn of a session's history (Sessions §3). Previously an object with no stated shape,\nwhich kept every conformance check at \"the endpoint answered 200\" and made transcript\nrebuilding an exercise in one implementation's habits.\n",
+ "required": [
+ "id",
+ "status"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The response id, usable with GET /v1/responses/{id}"
+ },
+ "status": {
+ "type": "string"
+ },
+ "user": {
+ "type": "string"
+ },
+ "assistant": {
+ "type": "string"
+ },
+ "tools": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ },
+ "additionalProperties": true
+ },
+ "Environment": {
+ "type": "object",
+ "required": [
+ "id",
+ "name",
+ "slug",
+ "status",
+ "mount"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^henv_"
+ },
+ "object": {
+ "type": "string",
+ "const": "environment"
+ },
+ "name": {
+ "type": "string"
+ },
+ "slug": {
+ "type": "string",
+ "description": "The path segment sessions see; derived from the name at creation and fixed after."
+ },
+ "description": {
+ "type": "string"
+ },
+ "entry": {
+ "type": "string",
+ "description": "How the project is run, in the owner's words; repeated to the agent."
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "empty",
+ "building",
+ "ready",
+ "failed"
+ ],
+ "description": "`ready` means a built version is active and tasks may read it. `empty` means nothing\nwas built yet; `building` and `failed` describe the latest build.\n"
+ },
+ "mount": {
+ "type": "string",
+ "description": "Where a session finds the environment, read-only. `/env/<slug>` on the reference server."
+ },
+ "version": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "description": "The active build",
+ "the one sessions read; null until one is ready.": null
+ },
+ "latestVersion": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "files": {
+ "type": "object",
+ "description": "The source's size (what the owner put in, before any build).",
+ "properties": {
+ "count": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "bytes": {
+ "type": "integer",
+ "minimum": 0
+ }
+ }
+ },
+ "packages": {
+ "type": "array",
+ "description": "What the active build installed, as the package managers report it.",
+ "items": {
+ "$ref": "#/$defs/EnvironmentPackage"
+ }
+ },
+ "versions": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/EnvironmentVersion"
+ }
+ },
+ "build": {
+ "description": "The latest build's status, or null before the first.",
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/$defs/EnvironmentVersion"
+ }
+ ]
+ },
+ "createdAt": {
+ "type": "integer",
+ "description": "Unix milliseconds"
+ },
+ "updatedAt": {
+ "type": "integer",
+ "description": "Unix milliseconds"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentPackage": {
+ "type": "object",
+ "required": [
+ "manager",
+ "name"
+ ],
+ "properties": {
+ "manager": {
+ "type": "string",
+ "examples": [
+ "pip",
+ "npm"
+ ]
+ },
+ "name": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentVersion": {
+ "type": "object",
+ "required": [
+ "version",
+ "status"
+ ],
+ "properties": {
+ "version": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "building",
+ "ready",
+ "failed",
+ "unknown"
+ ]
+ },
+ "started_at": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "finished_at": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "error": {
+ "type": "string"
+ },
+ "files": {
+ "type": "integer"
+ },
+ "bytes": {
+ "type": "integer"
+ },
+ "packages": {
+ "type": "integer",
+ "description": "How many packages the build installed."
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentBuild": {
+ "type": "object",
+ "required": [
+ "id",
+ "version",
+ "status"
+ ],
+ "description": "A build's record; the log is the installers' own output, capped by the server.",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "const": "environment.build"
+ },
+ "version": {
+ "type": "integer"
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "building",
+ "ready",
+ "failed"
+ ]
+ },
+ "started_at": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "finished_at": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "error": {
+ "type": "string"
+ },
+ "log": {
+ "type": "string"
+ },
+ "packages": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/EnvironmentPackage"
+ }
+ },
+ "files": {
+ "type": "integer"
+ },
+ "bytes": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentCreate": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Must start with a letter or digit; the slug derives from it."
+ },
+ "description": {
+ "type": "string"
+ },
+ "entry": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentList": {
+ "type": "object",
+ "required": [
+ "environments"
+ ],
+ "properties": {
+ "environments": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Environment"
+ }
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentFileEntry": {
+ "type": "object",
+ "required": [
+ "path",
+ "dir"
+ ],
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Relative to the environment's root."
+ },
+ "dir": {
+ "type": "boolean"
+ },
+ "bytes": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "mtime": {
+ "type": "integer",
+ "description": "Unix seconds."
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentFileList": {
+ "type": "object",
+ "required": [
+ "entries"
+ ],
+ "properties": {
+ "entries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/EnvironmentFileEntry"
+ }
+ },
+ "count": {
+ "type": "integer",
+ "description": "Files",
+ "not directories.": null
+ },
+ "bytes": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentImport": {
+ "type": "object",
+ "description": "The JSON form of an import: a git repository. The other form is the archive itself as the\nrequest body (a zip or a tar, any content type but `application/json`).\n",
+ "properties": {
+ "git": {
+ "type": "object",
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "url": {
+ "type": "string"
+ },
+ "ref": {
+ "type": "string",
+ "description": "A branch or tag; the default branch when omitted."
+ }
+ }
+ },
+ "replace": {
+ "type": "boolean",
+ "default": false,
+ "description": "Clear the source before importing."
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentImportResult": {
+ "type": "object",
+ "properties": {
+ "written": {
+ "type": "integer"
+ },
+ "skipped": {
+ "type": "integer",
+ "description": "Members that must not land (links",
+ "escapes) and were dropped.": null
+ },
+ "count": {
+ "type": "integer"
+ },
+ "bytes": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "Session": {
+ "type": "object",
+ "required": [
+ "id"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "const": "session"
+ },
+ "harness_id": {
+ "type": "string"
+ },
+ "environment": {
+ "type": "string",
+ "description": "The environment the session's turns read",
+ "when one did.": null
+ },
+ "title": {
+ "type": "string"
+ },
+ "status": {
+ "type": "string"
+ },
+ "created_at": {
+ "type": "integer"
+ },
+ "updated_at": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "SessionList": {
+ "type": "object",
+ "required": [
+ "sessions"
+ ],
+ "properties": {
+ "sessions": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Session"
+ }
+ },
+ "next_cursor": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "null on the last page. A client must not be required to detect the end by receiving fewer\nitems than requested — that heuristic is wrong whenever a page is exactly full.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "File": {
+ "type": "object",
+ "required": [
+ "id",
+ "filename"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "const": "file"
+ },
+ "container_id": {
+ "type": "string"
+ },
+ "filename": {
+ "type": "string"
+ },
+ "bytes": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "created_at": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "ErrorEnvelope": {
+ "type": "object",
+ "required": [
+ "error"
+ ],
+ "properties": {
+ "error": {
+ "$ref": "#/$defs/Error"
+ },
+ "detail": {
+ "type": "string",
+ "deprecated": true,
+ "description": "A human-readable alias of `error.message`, retained for clients written against\nimplementations that predate this envelope. Carries no information not in `error`.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "Error": {
+ "type": "object",
+ "required": [
+ "type",
+ "code",
+ "message"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "invalid_request_error",
+ "authentication_error",
+ "permission_error",
+ "rate_limit_error",
+ "harness_error",
+ "server_error"
+ ]
+ },
+ "code": {
+ "type": "string",
+ "description": "Specific and machine-readable. Servers may define additional codes for conditions this\nspecification does not cover, and must namespace them with a vendor prefix so a future\nversion cannot collide with them.\n",
+ "examples": [
+ "unsupported_protocol_version",
+ "invalid_input",
+ "harness_not_found",
+ "response_not_found",
+ "session_not_found",
+ "plugin_not_found",
+ "file_not_found",
+ "session_expired",
+ "harness_mismatch",
+ "session_busy",
+ "plugin_conflict",
+ "file_too_large",
+ "model_unavailable",
+ "unsupported_base",
+ "plugin_invalid",
+ "unsupported_plugin_schema",
+ "environment_not_found",
+ "environment_not_ready",
+ "environment_busy",
+ "environment_exists",
+ "environment_invalid",
+ "environment_unavailable",
+ "unsupported_transport",
+ "missing_credential",
+ "invalid_credential",
+ "insufficient_scope",
+ "rate_limited",
+ "quota_exhausted",
+ "harness_error",
+ "harness_unavailable",
+ "provider_error",
+ "timeout",
+ "cancelled",
+ "preview_unavailable",
+ "preview_failed"
+ ]
+ },
+ "message": {
+ "type": "string",
+ "description": "One sentence, safe to show a user. Must not contain credentials, internal hostnames, file\npaths, or stack traces.\n"
+ },
+ "param": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Dotted path to the offending field."
+ },
+ "detail": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "additionalProperties": true
+ }
+ },
+ "additionalProperties": true
+ },
+ "Event": {
+ "type": "object",
+ "required": [
+ "type",
+ "sequence_number"
+ ],
+ "description": "One streamed event. `sequence_number` starts at 0 and increases by exactly 1 per event, so a\nclient can detect a dropped event rather than silently rendering a gap.\n",
+ "properties": {
+ "type": {
+ "type": "string",
+ "examples": [
+ "response.created",
+ "response.in_progress",
+ "response.output_item.added",
+ "response.output_item.done",
+ "response.content_part.added",
+ "response.content_part.done",
+ "response.output_text.delta",
+ "response.output_text.done",
+ "response.output_text.annotation.added",
+ "response.reasoning_summary_part.added",
+ "response.reasoning_summary_text.delta",
+ "response.reasoning_summary_part.done",
+ "response.function_call_arguments.delta",
+ "response.function_call_arguments.done",
+ "response.completed",
+ "response.incomplete",
+ "response.failed",
+ "error"
+ ]
+ },
+ "sequence_number": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "response": {
+ "$ref": "#/$defs/Response"
+ },
+ "item": {
+ "$ref": "#/$defs/OutputItem"
+ },
+ "part": {
+ "$ref": "#/$defs/ContentPart"
+ },
+ "annotation": {
+ "$ref": "#/$defs/Annotation"
+ },
+ "delta": {
+ "type": "string"
+ },
+ "text": {
+ "type": "string"
+ },
+ "arguments": {
+ "type": "string"
+ },
+ "item_id": {
+ "type": "string"
+ },
+ "output_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "content_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "summary_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "annotation_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "code": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ },
+ "param": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "additionalProperties": true
+ }
+ }
+}
diff --git a/protocol/schema/build.py b/protocol/schema/build.py
index 8a807750..32eb7fde 100644
--- a/protocol/schema/build.py
+++ b/protocol/schema/build.py
@@ -25,7 +25,7 @@ except ImportError: # pragma: no cover - environment guidance, not logic
sys.exit("PyYAML is required: pip install pyyaml")
HERE = pathlib.Path(__file__).parent
-VERSION = "2026-09-12"
+VERSION = "2026-09-28"
SRC = HERE / f"uhp-{VERSION}.openapi.yaml"
OUT = HERE / f"uhp-{VERSION}.schema.json"
diff --git a/protocol/schema/uhp-2026-09-28.openapi.yaml b/protocol/schema/uhp-2026-09-28.openapi.yaml
new file mode 100644
index 00000000..a3c4568a
--- /dev/null
+++ b/protocol/schema/uhp-2026-09-28.openapi.yaml
@@ -0,0 +1,1896 @@
+openapi: 3.1.0
+info:
+ title: Unified Harness Protocol
+ version: '2026-09-28'
+ summary: An open standard for running complete agent harnesses as shared infrastructure.
+ description: |
+ UHP defines how a product drives a complete agent harness — Codex, Claude Code, Hermes, or any
+ other — over HTTP: selecting and configuring a harness, sending work, following progress,
+ continuing a session, cancelling execution, handling errors and files, and receiving results.
+
+ This document is normative for **structure**. The prose specification in `protocol/versions/`
+ is normative for **behaviour**; where they disagree about behaviour, the prose wins, because
+ behaviour is not expressible in OpenAPI.
+
+ Conformance is defined by the suite in `protocol/conformance/`, not by this document.
+
+ This version is additive to 2026-08-11. It adds plugins (packages of tools and skills in the
+ Agent Plugins format, installed into a harness, with stdio MCP servers inside them), the
+ `plugins` capability, and the error codes those need. Every request and object valid under
+ 2026-08-11 is valid here, and no object 2026-08-11 defined changes shape, so a server serves
+ both versions from one code path.
+ license:
+ name: Apache-2.0
+ identifier: Apache-2.0
+ contact:
+ name: UHP maintainers
+ url: https://github.com/HarnessRouter/harnessrouter
+
+servers:
+ - url: https://your-uhp-server
+ description: Any conformant UHP server. The protocol requires no hosted service.
+ - url: http://127.0.0.1:3000/api/harness
+ description: HarnessRouter Community Edition, default local deployment
+
+security:
+ - bearerAuth: []
+
+tags:
+ - name: Discovery
+ description: Protocol version and capability discovery (conformance class Core)
+ - name: Harnesses
+ description: Discovering, selecting and managing configured harnesses
+ - name: Tasks
+ description: Running work and reading results
+ - name: Sessions
+ description: Continuing, inspecting and cancelling sessions
+ - name: Files
+ description: File input and artifact retrieval (conformance class Extended)
+ - name: Plugins
+ description: Packages of tools and skills installed into a harness (optional capability `plugins`).
+ - name: Environments
+ description: A project's files and installed dependencies, built once and read by every session that names it (optional capability `environments`).
+ description: Packages of tools and skills installed into a harness (capability `plugins`)
+
+paths:
+ /v1/uhp:
+ get:
+ tags: [Discovery]
+ operationId: getDiscovery
+ summary: Protocol discovery document
+ description: |
+ Served without authentication: a client must be able to learn whether it is talking to a UHP
+ server, and which versions it speaks, before presenting credentials. The document contains
+ nothing principal-specific.
+ security: []
+ responses:
+ '200':
+ description: The discovery document
+ headers:
+ UHP-Version: { $ref: '#/components/headers/UHPVersion' }
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Discovery' }
+
+ /v1/harnesses:
+ get:
+ tags: [Harnesses]
+ operationId: listHarnesses
+ summary: List configured harnesses
+ responses:
+ '200':
+ description: Harnesses within the caller's scope. May be empty.
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [harnesses]
+ properties:
+ harnesses:
+ type: array
+ items: { $ref: '#/components/schemas/Harness' }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ post:
+ tags: [Harnesses]
+ operationId: createHarness
+ summary: Create a configured harness
+ description: Conformance class Full. Check the `harness_management` capability first.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/HarnessCreate' }
+ responses:
+ '200':
+ description: The created harness
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Harness' }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '422': { $ref: '#/components/responses/UnprocessableEntity' }
+
+ /v1/harnesses/{harness_id}:
+ parameters:
+ - $ref: '#/components/parameters/HarnessId'
+ get:
+ tags: [Harnesses]
+ operationId: getHarness
+ summary: Get one harness
+ responses:
+ '200':
+ description: The harness
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Harness' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ put:
+ tags: [Harnesses]
+ operationId: updateHarness
+ summary: Update a harness configuration
+ description: |
+ Conformance class Full. `id`, `base` and `createdAt` are immutable — changing the base of an
+ existing harness would silently change the behaviour of every session attached to it.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/HarnessCreate' }
+ responses:
+ '200':
+ description: The updated harness
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Harness' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ delete:
+ tags: [Harnesses]
+ operationId: deleteHarness
+ summary: Delete a harness
+ description: Must not delete the sessions or responses that used it.
+ responses:
+ '200':
+ description: Deleted
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id: { type: string }
+ deleted: { type: boolean }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/harnesses/{harness_id}/skills/{skill_name}/files:
+ parameters:
+ - $ref: '#/components/parameters/HarnessId'
+ - $ref: '#/components/parameters/SkillName'
+ get:
+ tags: [Harnesses]
+ operationId: getSkillFiles
+ summary: The complete file list of one skill
+ description: |
+ Conformance class Full. Whether or not the server stores the bundle out of line, this returns
+ every file of the skill folder, byte-for-byte.
+ responses:
+ '200':
+ description: The skill's files
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/FileList' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/harnesses/{harness_id}/plugins/{plugin_name}/files:
+ parameters:
+ - $ref: '#/components/parameters/HarnessId'
+ - $ref: '#/components/parameters/PluginName'
+ get:
+ tags: [Plugins]
+ operationId: getPluginFiles
+ summary: The complete package of one installed plugin
+ description: |
+ Conformance class Full, capability `plugins`. Every file of the package, byte-for-byte, whether
+ or not the server stores it out of line. `404` with `plugin_not_found` when the harness has no
+ plugin of that name.
+ responses:
+ '200':
+ description: The plugin's files
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/FileList' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/harnesses/{harness_id}/plugin:
+ parameters:
+ - $ref: '#/components/parameters/HarnessId'
+ get:
+ tags: [Plugins]
+ operationId: exportHarnessPlugin
+ summary: The harness's own tools and skills as an Agent Plugins package
+ description: |
+ Conformance class Full, capability `plugins`. Builds a package from the harness's direct
+ `mcpServers` and `skills`: a `plugin.json` whose name derives from the harness name, an
+ `mcp.json` of the enabled servers with `auth` and `headers` omitted (each omission recorded in
+ `skipped`), and each enabled skill folder. Installed plugins, the system prompt, the model,
+ the base and `disabledTools` are not included. The result installs into another harness by
+ passing it to `plugins` unchanged.
+ responses:
+ '200':
+ description: The package
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Plugin' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/environments:
+ get:
+ tags: [Environments]
+ operationId: listEnvironments
+ summary: The caller's environments
+ description: Conformance class Full, capability `environments`. Scoped like harnesses.
+ responses:
+ '200':
+ description: The list
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentList' }
+ post:
+ tags: [Environments]
+ operationId: createEnvironment
+ summary: Create an environment
+ description: |
+ An empty environment with a name; its slug (the path sessions see) derives from the name and
+ cannot change afterwards. `environment_exists` when another environment already occupies
+ that path; `environment_invalid` when the name yields no path segment.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentCreate' }
+ responses:
+ '200':
+ description: The environment
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Environment' }
+ '409': { $ref: '#/components/responses/Conflict' }
+ '422': { $ref: '#/components/responses/UnprocessableEntity' }
+
+ /v1/environments/{environment_id}:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ get:
+ tags: [Environments]
+ operationId: getEnvironment
+ summary: One environment, with its versions and the active build's packages
+ responses:
+ '200':
+ description: The environment
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Environment' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ put:
+ tags: [Environments]
+ operationId: updateEnvironment
+ summary: Rename, or change the description or entry
+ description: The slug stays; a session's instructions name it.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentCreate' }
+ responses:
+ '200':
+ description: The environment
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Environment' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ delete:
+ tags: [Environments]
+ operationId: deleteEnvironment
+ summary: Delete the environment and every version of it
+ description: |
+ Refused with `environment_busy` while a build runs. Harnesses that named it keep the
+ reference; their next task is refused with `environment_not_found`.
+ responses:
+ '200':
+ description: Deleted
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id: { type: string }
+ deleted: { type: boolean, const: true }
+ '404': { $ref: '#/components/responses/NotFound' }
+ '409': { $ref: '#/components/responses/Conflict' }
+
+ /v1/environments/{environment_id}/files:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ get:
+ tags: [Environments]
+ operationId: listEnvironmentFiles
+ summary: The source tree
+ description: What the owner put in, every file and directory with its size. Not the built layer.
+ responses:
+ '200':
+ description: The tree
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentFileList' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/environments/{environment_id}/files/{path}:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ - $ref: '#/components/parameters/EnvironmentPath'
+ get:
+ tags: [Environments]
+ operationId: getEnvironmentFile
+ summary: One file's bytes
+ responses:
+ '200':
+ description: The file, with its content type
+ content:
+ '*/*':
+ schema: { type: string, format: binary }
+ '404': { $ref: '#/components/responses/NotFound' }
+ put:
+ tags: [Environments]
+ operationId: putEnvironmentFile
+ summary: Write one file
+ description: |
+ The body is the file's bytes; the directories on its path are made. A server MUST reject a
+ path that escapes the root with `environment_invalid`, and an oversized file with
+ `file_too_large` rather than truncating it. Writing the source changes nothing a session
+ sees until the next build. An empty directory is made with `POST …/directories`.
+ requestBody:
+ required: true
+ content:
+ '*/*':
+ schema: { type: string, format: binary }
+ responses:
+ '200':
+ description: Written
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ path: { type: string }
+ bytes: { type: integer }
+ dir: { type: boolean }
+ '404': { $ref: '#/components/responses/NotFound' }
+ '413': { $ref: '#/components/responses/PayloadTooLarge' }
+ '422': { $ref: '#/components/responses/UnprocessableEntity' }
+ delete:
+ tags: [Environments]
+ operationId: deleteEnvironmentFile
+ summary: Remove a file or a directory tree
+ responses:
+ '200':
+ description: Removed
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ path: { type: string }
+ deleted: { type: boolean }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/environments/{environment_id}/directories:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ post:
+ tags: [Environments]
+ operationId: makeEnvironmentDirectory
+ summary: Make an empty directory
+ description: Its own request rather than a trailing slash on a file path, which a proxy may normalise away.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [path]
+ properties:
+ path: { type: string, description: Relative to the environment's root. }
+ responses:
+ '200':
+ description: Made
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ path: { type: string }
+ dir: { type: boolean, const: true }
+ '404': { $ref: '#/components/responses/NotFound' }
+ '422': { $ref: '#/components/responses/UnprocessableEntity' }
+
+ /v1/environments/{environment_id}/import:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ post:
+ tags: [Environments]
+ operationId: importEnvironment
+ summary: Import a whole project, keeping its tree
+ description: |
+ Either an archive (zip or tar) as the body, or a JSON body naming a git repository. A single
+ directory wrapping everything (the shape of a repository archive) is stripped. Members that
+ must not land (links, paths that escape the root) are dropped and counted in `skipped`, never
+ written. `?replace=1` clears the source first. Dependency directories in the archive
+ (`node_modules`, `.venv`) are not what a build installs: the build installs from the
+ manifests, in the server's own toolchain.
+ parameters:
+ - name: replace
+ in: query
+ schema: { type: integer, enum: [0, 1], default: 0 }
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentImport' }
+ '*/*':
+ schema: { type: string, format: binary }
+ responses:
+ '200':
+ description: What landed
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentImportResult' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ '413': { $ref: '#/components/responses/PayloadTooLarge' }
+ '422': { $ref: '#/components/responses/UnprocessableEntity' }
+
+ /v1/environments/{environment_id}/build:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ post:
+ tags: [Environments]
+ operationId: buildEnvironment
+ summary: Build a new version from the source
+ description: |
+ Snapshots the source into the next version, installs what its manifests declare
+ (`requirements.txt`, `pyproject.toml`, `package.json`, then `setup.sh` when present), and
+ makes the version the active one when it succeeds. Returns at once; poll the build. One
+ build at a time per environment (`environment_busy`). Sessions started before the build
+ finishes keep reading the version they started with.
+ responses:
+ '200':
+ description: The build started
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentBuild' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ '409': { $ref: '#/components/responses/Conflict' }
+
+ /v1/environments/{environment_id}/builds/{version}:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ - $ref: '#/components/parameters/BuildVersion'
+ get:
+ tags: [Environments]
+ operationId: getEnvironmentBuild
+ summary: A build's record, log included
+ responses:
+ '200':
+ description: The build
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentBuild' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/environments/{environment_id}/versions:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ get:
+ tags: [Environments]
+ operationId: listEnvironmentVersions
+ summary: Every build, and which one is active
+ responses:
+ '200':
+ description: The versions
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id: { type: string }
+ active: { type: [integer, 'null'] }
+ versions: { type: array, items: { $ref: '#/components/schemas/EnvironmentVersion' } }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/environments/{environment_id}/versions/{version}/activate:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ - $ref: '#/components/parameters/BuildVersion'
+ post:
+ tags: [Environments]
+ operationId: activateEnvironmentVersion
+ summary: Make an older build the active one
+ description: Rollback by pointer; nothing is rebuilt. Only a finished build can be activated (`environment_not_ready`).
+ responses:
+ '200':
+ description: The environment, with its new active version
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Environment' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ '409': { $ref: '#/components/responses/Conflict' }
+
+ /v1/environments/{environment_id}/harnesses:
+ parameters:
+ - $ref: '#/components/parameters/EnvironmentId'
+ get:
+ tags: [Environments]
+ operationId: listEnvironmentHarnesses
+ summary: The harnesses that read this environment
+ responses:
+ '200':
+ description: The harnesses, id, name and base each
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id: { type: string }
+ harnesses:
+ type: array
+ items:
+ type: object
+ properties:
+ id: { type: string }
+ name: { type: string }
+ base: { type: string }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/models:
+ get:
+ tags: [Harnesses]
+ operationId: listModels
+ summary: The model catalogue, by backend
+ responses:
+ '200':
+ description: Models grouped by backend, each with computed availability
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ModelCatalog' }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+
+ /v1/harnesses/{harness_id}/models:
+ parameters:
+ - $ref: '#/components/parameters/HarnessId'
+ get:
+ tags: [Harnesses]
+ operationId: listHarnessModels
+ summary: Models this harness can run
+ responses:
+ '200':
+ description: The harness's allowed models, default and authorized fallback
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/HarnessModels' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/responses:
+ post:
+ tags: [Tasks]
+ operationId: createResponse
+ summary: Run a task
+ description: |
+ The core of the protocol. With `stream: false` the server returns one Response object when
+ the task reaches a terminal state. With `stream: true` it returns `text/event-stream`
+ carrying the events defined in the Streaming chapter.
+
+ Retries MUST carry `Idempotency-Key`: without one, a retry after a timeout runs the task a
+ second time while the first may still be running.
+ parameters:
+ - name: Idempotency-Key
+ in: header
+ required: false
+ schema: { type: string, maxLength: 255 }
+ description: Repeating a key returns the first request's result and does not re-execute.
+ - name: UHP-Version
+ in: header
+ required: false
+ schema: { type: string, examples: ['2026-08-11'] }
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/CreateResponseRequest' }
+ responses:
+ '200':
+ description: |
+ The finished Response (non-streaming), or the event stream (streaming).
+ headers:
+ UHP-Version: { $ref: '#/components/headers/UHPVersion' }
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Response' }
+ text/event-stream:
+ schema:
+ type: string
+ description: SSE; each `data:` line is one Event object.
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ '409': { $ref: '#/components/responses/Conflict' }
+ '422': { $ref: '#/components/responses/UnprocessableEntity' }
+ '429': { $ref: '#/components/responses/RateLimited' }
+
+ /v1/responses/{response_id}:
+ parameters:
+ - $ref: '#/components/parameters/ResponseId'
+ get:
+ tags: [Tasks]
+ operationId: getResponse
+ summary: Read a task back
+ responses:
+ '200':
+ description: The Response
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Response' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ delete:
+ tags: [Tasks]
+ operationId: deleteResponse
+ summary: Delete a stored response
+ description: Must not cancel a running task — deletion and cancellation are different intentions.
+ responses:
+ '200':
+ description: Deleted
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id: { type: string }
+ deleted: { type: boolean }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/responses/{response_id}/input_items:
+ parameters:
+ - $ref: '#/components/parameters/ResponseId'
+ get:
+ tags: [Tasks]
+ operationId: getResponseInputItems
+ summary: The input the task was created with
+ responses:
+ '200':
+ description: Input items
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ object: { type: string, const: list }
+ data: { type: array, items: { type: object, additionalProperties: true } }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/responses/{response_id}/cancel:
+ parameters:
+ - $ref: '#/components/parameters/ResponseId'
+ post:
+ tags: [Sessions]
+ operationId: cancelResponse
+ summary: Cancel a running task
+ description: |
+ Idempotent. Cancelling an already-terminal task succeeds and changes nothing — a client
+ retrying a cancel after a dropped connection must not be punished for having succeeded.
+ responses:
+ '200':
+ description: The Response, now cancelling or terminal
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Response' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/sessions:
+ get:
+ tags: [Sessions]
+ operationId: listSessions
+ summary: List sessions
+ description: Conformance class Extended.
+ parameters:
+ - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
+ - { name: cursor, in: query, schema: { type: string } }
+ - { name: harness, in: query, schema: { type: string }, description: Filter by harness id }
+ responses:
+ '200':
+ description: A page of sessions
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/SessionList' }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+
+ /v1/sessions/{session_id}:
+ parameters:
+ - $ref: '#/components/parameters/SessionId'
+ get:
+ tags: [Sessions]
+ operationId: getSession
+ summary: Get one session
+ responses:
+ '200':
+ description: The session
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Session' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/sessions/{session_id}/turns:
+ parameters:
+ - $ref: '#/components/parameters/SessionId'
+ get:
+ tags: [Sessions]
+ operationId: getSessionTurns
+ summary: The ordered task history of a session
+ responses:
+ '200':
+ description: Turns, oldest first
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ turns: { type: array, items: { $ref: '#/components/schemas/TurnItem' } }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/sessions/{session_id}/share:
+ parameters:
+ - $ref: '#/components/parameters/SessionId'
+ post:
+ tags: [Sessions]
+ operationId: shareSession
+ summary: Publish a read-only view of the session (Sessions §5, class Full)
+ description: |
+ A body is OPTIONAL; no body means publish. A server MAY accept `{"enabled": bool}` as a
+ toggle. Sharing itself is a MAY; a server that does not implement it answers 404/405/501.
+ requestBody:
+ required: false
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ enabled: { type: boolean, default: true }
+ additionalProperties: true
+ responses:
+ '200':
+ description: The share
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/SessionShare' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ get:
+ tags: [Sessions]
+ operationId: getSessionShare
+ summary: Read the session's share back
+ responses:
+ '200':
+ description: The share, agreeing with what POST published
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/SessionShare' }
+ '404': { $ref: '#/components/responses/NotFound' }
+ delete:
+ tags: [Sessions]
+ operationId: revokeSessionShare
+ summary: Revoke — every link minted for the session stops resolving
+ responses:
+ '200':
+ description: Revoked
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/SessionShare' }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/sessions/{session_id}/cancel:
+ parameters:
+ - $ref: '#/components/parameters/SessionId'
+ post:
+ tags: [Sessions]
+ operationId: cancelSession
+ summary: Cancel whatever is running in a session
+ responses:
+ '200':
+ description: Accepted
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id: { type: string }
+ status: { type: string }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/files:
+ post:
+ tags: [Files]
+ operationId: uploadFile
+ summary: Upload a file for use as task input
+ description: Conformance class Extended.
+ requestBody:
+ required: true
+ content:
+ multipart/form-data:
+ schema:
+ type: object
+ required: [file]
+ properties:
+ file: { type: string, format: binary }
+ purpose: { type: string, default: user_data }
+ responses:
+ '200':
+ description: The stored file
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/File' }
+ '413': { $ref: '#/components/responses/PayloadTooLarge' }
+
+ /v1/sessions/{session_id}/files:
+ parameters:
+ - $ref: '#/components/parameters/SessionId'
+ get:
+ tags: [Files]
+ operationId: listSessionFiles
+ summary: Every artifact of a session
+ description: Must include artifacts from earlier tasks, not only the most recent.
+ responses:
+ '200':
+ description: Artifacts
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [files]
+ properties:
+ files: { type: array, items: { $ref: '#/components/schemas/File' } }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/sessions/{session_id}/files/archive:
+ parameters:
+ - $ref: '#/components/parameters/SessionId'
+ get:
+ tags: [Files]
+ operationId: downloadSessionArchive
+ summary: Every artifact as one archive
+ responses:
+ '200':
+ description: An archive of the session's artifacts
+ content:
+ application/zip:
+ schema: { type: string, format: binary }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/containers/{container_id}/files/{file_id}/content:
+ parameters:
+ - $ref: '#/components/parameters/ContainerId'
+ - $ref: '#/components/parameters/FileId'
+ get:
+ tags: [Files]
+ operationId: downloadFile
+ summary: Download an artifact
+ description: |
+ Returns raw bytes with the file's own media type — never JSON-wrapped. Servers must send
+ `X-Content-Type-Options: nosniff`: artifacts are attacker-influenceable content, and serving
+ them without it turns an artifact into stored XSS against the client's origin.
+ responses:
+ '200':
+ description: The bytes
+ headers:
+ Content-Disposition:
+ schema: { type: string }
+ X-Content-Type-Options:
+ required: true
+ schema: { type: string, const: nosniff }
+ content:
+ '*/*':
+ schema: { type: string, format: binary }
+ '404': { $ref: '#/components/responses/NotFound' }
+
+ /v1/containers/{container_id}/files/{file_id}/pdf:
+ parameters:
+ - $ref: '#/components/parameters/ContainerId'
+ - $ref: '#/components/parameters/FileId'
+ get:
+ tags: [Files]
+ operationId: previewFile
+ summary: A rendered PDF preview of a document artifact
+ responses:
+ '200':
+ description: The rendered PDF
+ content:
+ application/pdf:
+ schema: { type: string, format: binary }
+ '404': { $ref: '#/components/responses/NotFound' }
+ '501':
+ description: This server does not implement preview conversion
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
+ '502':
+ description: Conversion of this file failed
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
+
+components:
+ securitySchemes:
+ bearerAuth:
+ type: http
+ scheme: bearer
+ description: How tokens are issued is out of scope for this protocol.
+
+ headers:
+ UHPVersion:
+ description: The protocol version actually used to serve this response.
+ required: true
+ schema: { type: string, examples: ['2026-08-11'] }
+
+ parameters:
+ EnvironmentId:
+ name: environment_id
+ in: path
+ required: true
+ schema: { type: string, pattern: '^henv_' }
+ EnvironmentPath:
+ name: path
+ in: path
+ required: true
+ description: A path relative to the environment's root. A trailing slash names a directory.
+ schema: { type: string }
+ BuildVersion:
+ name: version
+ in: path
+ required: true
+ schema: { type: integer, minimum: 1 }
+ HarnessId:
+ name: harness_id
+ in: path
+ required: true
+ schema: { type: string, pattern: '^chrn_' }
+ SkillName:
+ name: skill_name
+ in: path
+ required: true
+ schema: { type: string }
+ PluginName:
+ name: plugin_name
+ in: path
+ required: true
+ schema: { type: string }
+ ResponseId:
+ name: response_id
+ in: path
+ required: true
+ schema: { type: string, pattern: '^resp_' }
+ SessionId:
+ name: session_id
+ in: path
+ required: true
+ schema: { type: string }
+ ContainerId:
+ name: container_id
+ in: path
+ required: true
+ schema: { type: string }
+ FileId:
+ name: file_id
+ in: path
+ required: true
+ schema: { type: string }
+
+ responses:
+ Unauthorized:
+ description: Missing, malformed or unknown credential
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
+ NotFound:
+ description: |
+ No such object in the caller's scope. Servers return 404 rather than 403 for objects outside
+ the caller's scope, so that an id's existence is not disclosed.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
+ Conflict:
+ description: '`session_busy` or `harness_mismatch`'
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
+ UnprocessableEntity:
+ description: '`model_unavailable` or `unsupported_base`'
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
+ PayloadTooLarge:
+ description: '`file_too_large`'
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
+ RateLimited:
+ description: '`rate_limited` or `quota_exhausted`'
+ headers:
+ Retry-After:
+ schema: { type: string }
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
+
+ schemas:
+ Discovery:
+ type: object
+ required: [object, protocol, versions, default_version, conformance_class, capabilities]
+ properties:
+ object: { type: string, const: uhp.discovery }
+ protocol: { type: string, const: uhp }
+ versions:
+ type: array
+ minItems: 1
+ items: { type: string }
+ default_version: { type: string }
+ conformance_class: { type: string, enum: [core, extended, full] }
+ capabilities: { $ref: '#/components/schemas/Capabilities' }
+ plugin_schemas:
+ type: array
+ items: { type: string, format: uri }
+ description: |
+ The Agent Plugins manifest schema identifiers this server installs. Present and non-empty
+ when `capabilities.plugins` is true.
+ examples: [['https://agent-plugins.org/schemas/1.0.0/plugin.schema.json']]
+ implementation:
+ type: object
+ properties:
+ name: { type: string }
+ version: { type: string }
+ additionalProperties: true
+ additionalProperties: true
+
+ Capabilities:
+ type: object
+ description: |
+ Named booleans. A server reports `false` for a capability it does not implement rather than
+ omitting it, so a client can distinguish "not supported" from "server predates this field".
+ A client treats an absent key as `false`.
+ properties:
+ streaming: { type: boolean }
+ sessions: { type: boolean }
+ cancellation: { type: boolean }
+ files_input: { type: boolean }
+ files_output: { type: boolean }
+ session_listing: { type: boolean }
+ harness_management: { type: boolean }
+ session_sharing: { type: boolean }
+ idempotency: { type: boolean }
+ plugins:
+ type: boolean
+ description: |
+ The server installs Agent Plugins packages into harnesses, serves their files, and exports
+ a harness as a package. Optional at every class.
+ environments:
+ type: boolean
+ description: |
+ The server holds environments: a project's files and installed dependencies, built once,
+ read-only at a fixed path in every session that names one. Optional at every class.
+ additionalProperties: { type: boolean }
+
+ Harness:
+ type: object
+ required: [id, name, base]
+ properties:
+ id: { type: string, pattern: '^chrn_' }
+ object: { type: string, const: harness }
+ name: { type: string }
+ base:
+ type: string
+ description: |
+ Opaque. Not enumerated by this specification — a client must treat it as a string, or the
+ protocol would need revising every time a harness is released.
+ examples: [codex, claude-code, hermes]
+ baseLabel: { type: string }
+ defaultModel: { type: string }
+ systemPrompt: { type: string }
+ mcpServers: { type: array, items: { $ref: '#/components/schemas/McpServer' } }
+ skills: { type: array, items: { $ref: '#/components/schemas/Skill' } }
+ plugins:
+ type: array
+ items: { $ref: '#/components/schemas/Plugin' }
+ description: |
+ Installed plugins. Their servers and skills join the harness's own for every turn;
+ `mcpServers` and `skills` above report only what was written to them directly.
+ environment:
+ type: string
+ description: |
+ The environment (`henv_`) this harness's tasks read, mounted read-only at its `mount`;
+ empty when none. A task may name another with its own `environment` field.
+ disabledTools: { type: array, items: { type: string } }
+ maxStep: { type: [integer, 'null'] }
+ timeoutSeconds: { type: [integer, 'null'] }
+ createdAt: { type: integer, description: Unix milliseconds }
+ additionalProperties: true
+
+ McpServer:
+ type: object
+ required: [name, url]
+ description: |
+ A remote MCP server attached to a harness. Only enabled entries are connected for a turn; a
+ disabled entry must not be contacted at all. An unreachable server must not fail the task.
+ Unchanged from 2026-08-11: a process (stdio) server is declared inside a plugin, see
+ PluginMcpServer.
+ properties:
+ name: { type: string, description: Sanitised to a CLI-safe identifier by the server. }
+ url: { type: string, format: uri }
+ transport: { type: string, enum: [http, sse], default: http }
+ enabled: { type: boolean, default: true }
+ headers: { type: object, additionalProperties: { type: string } }
+ auth:
+ type: string
+ description: |
+ Bearer token, or a server-side reference the server resolves. A server must never return
+ a resolved credential to a client.
+ additionalProperties: true
+
+ PluginMcpServer:
+ type: object
+ required: [name]
+ description: |
+ An MCP server a plugin's mcp.json declares, derived by the server. The harness MCP server
+ object plus the `stdio` transport: `url` is required for `http` and `sse`, `command` for
+ `stdio`. Placeholders are reported unexpanded; `enabled` is always true, the plugin's own
+ `enabled` governs.
+ properties:
+ name: { type: string }
+ transport:
+ type: string
+ enum: [http, sse, stdio]
+ default: http
+ description: |
+ `http` is Streamable HTTP (`streamable-http` in mcp.json); `sse` the older HTTP+SSE
+ transport; `stdio` a process the server launches inside the agent's sandbox.
+ url: { type: string, format: uri, description: Endpoint (`http` and `sse`). }
+ headers:
+ type: object
+ additionalProperties: { type: string }
+ description: Fixed request headers (`http` and `sse`). Never subject to placeholder expansion.
+ command:
+ type: string
+ description: |
+ One executable token (`stdio`): a bare name resolved on the sandbox's search path, or a
+ plugin-relative path beginning with `./`. Never a shell string, never expanded.
+ args:
+ type: array
+ items: { type: string }
+ description: Arguments (`stdio`). `${PLUGIN_ROOT}` and `${PLUGIN_DATA}` expand at run time.
+ env:
+ type: object
+ additionalProperties: { type: string }
+ description: |
+ Environment overlay (`stdio`). Must not name PLUGIN_ROOT or PLUGIN_DATA; the server sets
+ those. Values expand at run time.
+ cwd:
+ type: string
+ description: |
+ Working directory (`stdio`). Defaults to the plugin root; must stay within the plugin
+ root or PLUGIN_DATA.
+ enabled: { type: boolean, default: true }
+ allOf:
+ - if:
+ properties: { transport: { const: stdio } }
+ required: [transport]
+ then: { required: [command] }
+ else: { required: [url] }
+ additionalProperties: true
+
+ Skill:
+ type: object
+ required: [name]
+ description: |
+ A skill is a FOLDER, not a file. A server must materialise the whole folder where the agent
+ can read it — materialising only SKILL.md breaks every skill carrying references, scripts or
+ data. Round-tripping a harness through GET and PUT must not lose skill contents.
+ properties:
+ name: { type: string }
+ enabled:
+ type: boolean
+ default: true
+ description: false suppresses the skill, including one inherited from the base.
+ files:
+ type: array
+ items: { $ref: '#/components/schemas/SkillFile' }
+ description: The bundle. Must contain a SKILL.md.
+ content:
+ type: string
+ description: Shorthand for a single-file bundle whose only member is SKILL.md.
+ blob:
+ type: string
+ description: |
+ Server-assigned handle for a bundle stored out of line. A client receives it, passes it
+ back unchanged, and reads the files from the skill files endpoint.
+ additionalProperties: true
+
+ SkillFile:
+ type: object
+ required: [path]
+ description: One file of a skill folder or of a plugin package.
+ properties:
+ path:
+ type: string
+ description: |
+ Relative to the skill's own folder, or to the plugin root; nested directories are
+ supported. A server must reject a path that escapes the folder.
+ examples: ['SKILL.md', 'references/codes.md', 'assets/logo.png']
+ content: { type: string, description: Text content. }
+ content_b64: { type: string, description: Base64 for binary content; preserved byte-for-byte. }
+ additionalProperties: true
+
+ FileList:
+ type: object
+ required: [files]
+ properties:
+ files:
+ type: array
+ items: { $ref: '#/components/schemas/SkillFile' }
+
+ Plugin:
+ type: object
+ required: [name]
+ description: |
+ An Agent Plugins package installed into a harness: `plugin.json` at the root, MCP servers in
+ `mcp.json`, skills under `skills/`. A client writes `files` (or passes back `blob`) and
+ optionally `name` and `enabled`; the server derives `manifest`, `mcpServers`, `skills` and
+ `skipped` from the package on every write and ignores those fields on input. A refused
+ package leaves the harness unchanged.
+ properties:
+ name:
+ type: string
+ pattern: '^(?!.*(--|\.\.))[a-z0-9]([a-z0-9.-]*[a-z0-9])?$'
+ maxLength: 64
+ description: The manifest's `name`. Optional on write; if sent it must equal the manifest's.
+ enabled:
+ type: boolean
+ default: true
+ description: false keeps the plugin installed and inert; nothing in it is materialised or contacted.
+ files:
+ type: array
+ items: { $ref: '#/components/schemas/SkillFile' }
+ description: The package. Must contain `plugin.json` at its root.
+ blob:
+ type: string
+ description: |
+ Server-assigned handle for a package stored out of line. A client passes it back unchanged
+ and reads the files from the plugin files endpoint.
+ manifest: { $ref: '#/components/schemas/PluginManifest' }
+ mcpServers:
+ type: array
+ items: { $ref: '#/components/schemas/PluginMcpServer' }
+ description: |
+ Derived from `mcp.json`. Placeholders are reported unexpanded; `enabled` is always true,
+ the plugin's own `enabled` governs.
+ skills:
+ type: array
+ items: { $ref: '#/components/schemas/PluginSkill' }
+ description: Derived from `skills/`, one entry per immediate child directory with a SKILL.md.
+ skipped:
+ type: array
+ items: { $ref: '#/components/schemas/PluginSkipped' }
+ description: |
+ What the server found and could not load. Present on every plugin object the server
+ returns, empty when nothing was skipped.
+ additionalProperties: true
+
+ PluginManifest:
+ type: object
+ required: ['$schema', name]
+ description: |
+ `plugin.json`, parsed. Mirrors the Agent Plugins 1.0.0 manifest schema
+ (https://agent-plugins.org/schemas/1.0.0/plugin.schema.json, Apache-2.0) field for field, and
+ permits additional properties because a UHP client ignores fields it does not know. The
+ schema a manifest's own `$schema` names is authoritative; a server validates against that.
+ properties:
+ '$schema': { type: string, format: uri }
+ name:
+ type: string
+ minLength: 1
+ maxLength: 64
+ pattern: '^(?!.*(--|\.\.))[a-z0-9]([a-z0-9.-]*[a-z0-9])?$'
+ version: { type: string }
+ description: { type: string }
+ author:
+ type: object
+ properties:
+ name: { type: string }
+ email: { type: string }
+ url: { type: string }
+ additionalProperties: true
+ homepage: { type: string }
+ repository: { type: string }
+ license: { type: string }
+ keywords: { type: array, items: { type: string } }
+ extensions:
+ type: object
+ description: Client-specific data keyed by reverse-domain namespace, per Agent Plugins §8.
+ additionalProperties: { type: object }
+ additionalProperties: true
+
+ PluginSkill:
+ type: object
+ required: [name]
+ properties:
+ name: { type: string, description: The SKILL.md frontmatter name, equal to the directory name. }
+ description: { type: string }
+ additionalProperties: true
+
+ PluginSkipped:
+ type: object
+ required: [path, reason]
+ properties:
+ path:
+ type: string
+ description: Where in the package, e.g. `skills/broken`, `mcp.json#/mcpServers/redline`, `plugin.json#/vendorField`.
+ examples: ['skills/broken', 'mcp.json#/mcpServers/redline']
+ reason: { type: string, description: One sentence. }
+ additionalProperties: true
+
+ HarnessCreate:
+ type: object
+ required: [base]
+ properties:
+ name: { type: string }
+ base: { type: string }
+ default_model: { type: string }
+ system_prompt: { type: string }
+ mcp_servers: { type: array, items: { $ref: '#/components/schemas/McpServer' } }
+ skills: { type: array, items: { $ref: '#/components/schemas/Skill' } }
+ plugins:
+ type: array
+ items: { $ref: '#/components/schemas/Plugin' }
+ description: Requires the `plugins` capability. Each item needs `files` or `blob`.
+ environment: { type: string, description: An environment id of the caller's scope, or empty. Requires the `environments` capability. }
+ disabled_tools: { type: array, items: { type: string } }
+ max_step: { type: [integer, 'null'] }
+ timeout_seconds: { type: [integer, 'null'] }
+ additionalProperties: true
+
+ ModelCatalog:
+ type: object
+ required: [backends]
+ properties:
+ backends:
+ type: object
+ additionalProperties:
+ type: object
+ required: [default, models]
+ properties:
+ default: { type: string }
+ models: { type: array, items: { $ref: '#/components/schemas/Model' } }
+
+ HarnessModels:
+ type: object
+ required: [models]
+ properties:
+ harness_id: { type: string }
+ backend: { type: string }
+ default: { type: string }
+ fallback: { type: string }
+ models: { type: array, items: { $ref: '#/components/schemas/Model' } }
+
+ Model:
+ type: object
+ required: [id, available]
+ properties:
+ id: { type: string }
+ label: { type: string }
+ backend: { type: string }
+ available:
+ type: boolean
+ description: |
+ Computed, not asserted: true means the server can serve this model for this harness right
+ now. Listing a model as available and then failing the task is the worst outcome for a
+ client, because a user has already chosen it.
+ default: { type: boolean }
+ additionalProperties: true
+
+ CreateResponseRequest:
+ type: object
+ required: [input]
+ properties:
+ input:
+ oneOf:
+ - type: string
+ - type: array
+ items: { type: object, additionalProperties: true }
+ description: A bare string is shorthand for one user message.
+ model: { type: string, description: Canonical model id. Omitted means the harness default. }
+ metadata:
+ type: object
+ description: Client metadata. `harness_id` selects the configured harness.
+ properties:
+ harness_id: { type: string }
+ additionalProperties: true
+ stream: { type: boolean, default: false }
+ previous_response_id: { type: [string, 'null'] }
+ instructions: { type: string }
+ store: { type: boolean, default: true }
+ max_output_tokens: { type: [integer, 'null'] }
+ max_step: { type: [integer, 'null'], description: Agent step (tool-call round) budget }
+ timeout_seconds: { type: [integer, 'null'], description: Wall-clock budget }
+ environment:
+ type: string
+ description: |
+ The environment this task reads, overriding the harness's. Refused with
+ `environment_not_found` or `environment_not_ready` before the task starts.
+ tools:
+ type: array
+ items: { type: object, additionalProperties: true }
+ description: |
+ Reserved and ignored. Accepted for wire compatibility, never acted on, and reported in
+ `metadata.ignored_fields` on the response. A UHP harness invokes and executes tools
+ itself and reports them in `output`; there is no input path for a tool result, so the
+ client-executed tool loop this field implies cannot be completed by a conformant server.
+ Configure tools on the harness instead — see Harnesses §4.1. Tasks §1.4.
+ include:
+ type: array
+ items: { type: string }
+ description: |
+ Reserved and ignored. Accepted for wire compatibility, never acted on, and reported in
+ `metadata.ignored_fields` on the response. No values are enumerated, so any string a
+ server recognised would be one it named itself. Tasks §1.4.
+ background: { type: boolean, default: false }
+ additionalProperties: true
+
+ Response:
+ type: object
+ required: [id, object, created_at, status, output, model]
+ properties:
+ id: { type: string, pattern: '^resp_' }
+ object: { type: string, const: response }
+ created_at: { type: integer, description: Unix seconds }
+ status: { $ref: '#/components/schemas/ResponseStatus' }
+ error:
+ oneOf:
+ - type: 'null'
+ - $ref: '#/components/schemas/Error'
+ description: Non-null only when status is `failed`.
+ incomplete_details: { type: [object, 'null'], additionalProperties: true }
+ previous_response_id: { type: [string, 'null'] }
+ model: { type: string, description: The model that actually ran. }
+ output:
+ type: array
+ items: { $ref: '#/components/schemas/OutputItem' }
+ store: { type: boolean }
+ usage:
+ oneOf:
+ - type: 'null'
+ - $ref: '#/components/schemas/Usage'
+ description: |
+ null when the server cannot account for usage. A fabricated zero would be worse than an
+ honest absence, because a client cannot tell it from a free task.
+ metadata:
+ type: object
+ properties:
+ session_id: { type: string }
+ requested_model:
+ type: string
+ description: Present when the server ran a different model than was requested.
+ model_fallback: { type: boolean }
+ model_fallback_reason: { type: string }
+ ignored_fields:
+ type: array
+ items: { type: string }
+ description: |
+ Request fields the server did not act on, by name, in any order. Required when the
+ request carried `tools` or `include`, which are reserved and ignored. A silently
+ ignored field is indistinguishable from an honoured one. Tasks §1.1 and §1.4.
+ additionalProperties: true
+ additionalProperties: true
+
+ ResponseStatus:
+ type: string
+ enum: [in_progress, completed, failed, incomplete, cancelled]
+ description: |
+ `incomplete` means a budget stopped the work and is usually worth continuing.
+ `failed` means it could not be done. `cancelled` means the client asked for a stop, and must
+ never be reported as `failed`.
+
+ OutputItem:
+ type: object
+ required: [type]
+ description: |
+ A client must tolerate item types it does not recognise. A client that renders only `message`
+ items and ignores the rest is a valid client.
+ properties:
+ id: { type: string }
+ type:
+ type: string
+ examples: [message, reasoning, function_call, function_call_output]
+ status: { type: string }
+ role: { type: string }
+ content:
+ type: array
+ items: { $ref: '#/components/schemas/ContentPart' }
+ summary:
+ type: array
+ items: { type: object, additionalProperties: true }
+ call_id: { type: string }
+ name: { type: string }
+ arguments: { type: string, description: JSON, as a string }
+ output: { type: string }
+ additionalProperties: true
+
+ ContentPart:
+ type: object
+ required: [type]
+ properties:
+ type: { type: string, examples: [output_text] }
+ text: { type: string }
+ annotations:
+ type: array
+ items: { $ref: '#/components/schemas/Annotation' }
+ additionalProperties: true
+
+ Annotation:
+ type: object
+ required: [type]
+ properties:
+ type: { type: string, const: container_file_citation }
+ container_id: { type: string }
+ file_id: { type: string }
+ filename: { type: string }
+ download_url: { type: string, format: uri }
+ start_index: { type: integer }
+ end_index: { type: integer }
+ additionalProperties: true
+
+ Usage:
+ type: object
+ properties:
+ input_tokens: { type: integer, minimum: 0 }
+ output_tokens: { type: integer, minimum: 0 }
+ total_tokens: { type: integer, minimum: 0 }
+ cache_read_tokens: { type: integer, minimum: 0 }
+ cache_write_tokens: { type: integer, minimum: 0 }
+ additionalProperties: true
+
+ SessionShare:
+ type: object
+ description: |
+ A published read-only view of a session (Sessions §5). `url` may be relative, resolving
+ against the base URL the caller is already using — a server behind a proxy cannot know its
+ public origin, and a base-relative path survives every fronting. The share's id MUST NOT
+ function as a credential for the rest of the API.
+ required: [id, url]
+ properties:
+ id: { type: string }
+ url: { type: string }
+ object: { type: string, description: 'SHOULD be "session.share"' }
+ enabled: { type: boolean }
+ additionalProperties: true
+
+ TurnItem:
+ type: object
+ description: |
+ One turn of a session's history (Sessions §3). Previously an object with no stated shape,
+ which kept every conformance check at "the endpoint answered 200" and made transcript
+ rebuilding an exercise in one implementation's habits.
+ required: [id, status]
+ properties:
+ id: { type: string, description: "The response id, usable with GET /v1/responses/{id}" }
+ status: { type: string }
+ user: { type: string }
+ assistant: { type: string }
+ tools: { type: array, items: { type: object, additionalProperties: true } }
+ files: { type: array, items: { type: object, additionalProperties: true } }
+ additionalProperties: true
+
+ Environment:
+ type: object
+ required: [id, name, slug, status, mount]
+ properties:
+ id: { type: string, pattern: '^henv_' }
+ object: { type: string, const: environment }
+ name: { type: string }
+ slug:
+ type: string
+ description: The path segment sessions see; derived from the name at creation and fixed after.
+ description: { type: string }
+ entry:
+ type: string
+ description: How the project is run, in the owner's words; repeated to the agent.
+ status:
+ type: string
+ enum: [empty, building, ready, failed]
+ description: |
+ `ready` means a built version is active and tasks may read it. `empty` means nothing
+ was built yet; `building` and `failed` describe the latest build.
+ mount:
+ type: string
+ description: Where a session finds the environment, read-only. `/env/<slug>` on the reference server.
+ version: { type: [integer, 'null'], description: The active build, the one sessions read; null until one is ready. }
+ latestVersion: { type: [integer, 'null'] }
+ files:
+ type: object
+ description: The source's size (what the owner put in, before any build).
+ properties:
+ count: { type: integer, minimum: 0 }
+ bytes: { type: integer, minimum: 0 }
+ packages:
+ type: array
+ description: What the active build installed, as the package managers report it.
+ items: { $ref: '#/components/schemas/EnvironmentPackage' }
+ versions:
+ type: array
+ items: { $ref: '#/components/schemas/EnvironmentVersion' }
+ build:
+ description: The latest build's status, or null before the first.
+ oneOf:
+ - type: 'null'
+ - $ref: '#/components/schemas/EnvironmentVersion'
+ createdAt: { type: integer, description: Unix milliseconds }
+ updatedAt: { type: integer, description: Unix milliseconds }
+ additionalProperties: true
+
+ EnvironmentPackage:
+ type: object
+ required: [manager, name]
+ properties:
+ manager: { type: string, examples: [pip, npm] }
+ name: { type: string }
+ version: { type: string }
+ additionalProperties: true
+
+ EnvironmentVersion:
+ type: object
+ required: [version, status]
+ properties:
+ version: { type: integer, minimum: 1 }
+ status: { type: string, enum: [building, ready, failed, unknown] }
+ started_at: { type: [integer, 'null'] }
+ finished_at: { type: [integer, 'null'] }
+ error: { type: string }
+ files: { type: integer }
+ bytes: { type: integer }
+ packages: { type: integer, description: How many packages the build installed. }
+ additionalProperties: true
+
+ EnvironmentBuild:
+ type: object
+ required: [id, version, status]
+ description: A build's record; the log is the installers' own output, capped by the server.
+ properties:
+ id: { type: string }
+ object: { type: string, const: environment.build }
+ version: { type: integer }
+ status: { type: string, enum: [building, ready, failed] }
+ started_at: { type: [integer, 'null'] }
+ finished_at: { type: [integer, 'null'] }
+ error: { type: string }
+ log: { type: string }
+ packages: { type: array, items: { $ref: '#/components/schemas/EnvironmentPackage' } }
+ files: { type: integer }
+ bytes: { type: integer }
+ additionalProperties: true
+
+ EnvironmentCreate:
+ type: object
+ required: [name]
+ properties:
+ name: { type: string, description: Must start with a letter or digit; the slug derives from it. }
+ description: { type: string }
+ entry: { type: string }
+ additionalProperties: true
+
+ EnvironmentList:
+ type: object
+ required: [environments]
+ properties:
+ environments: { type: array, items: { $ref: '#/components/schemas/Environment' } }
+ additionalProperties: true
+
+ EnvironmentFileEntry:
+ type: object
+ required: [path, dir]
+ properties:
+ path: { type: string, description: Relative to the environment's root. }
+ dir: { type: boolean }
+ bytes: { type: integer, minimum: 0 }
+ mtime: { type: integer, description: Unix seconds. }
+ additionalProperties: true
+
+ EnvironmentFileList:
+ type: object
+ required: [entries]
+ properties:
+ entries: { type: array, items: { $ref: '#/components/schemas/EnvironmentFileEntry' } }
+ count: { type: integer, description: Files, not directories. }
+ bytes: { type: integer }
+ additionalProperties: true
+
+ EnvironmentImport:
+ type: object
+ description: |
+ The JSON form of an import: a git repository. The other form is the archive itself as the
+ request body (a zip or a tar, any content type but `application/json`).
+ properties:
+ git:
+ type: object
+ required: [url]
+ properties:
+ url: { type: string }
+ ref: { type: string, description: A branch or tag; the default branch when omitted. }
+ replace: { type: boolean, default: false, description: Clear the source before importing. }
+ additionalProperties: true
+
+ EnvironmentImportResult:
+ type: object
+ properties:
+ written: { type: integer }
+ skipped: { type: integer, description: Members that must not land (links, escapes) and were dropped. }
+ count: { type: integer }
+ bytes: { type: integer }
+ additionalProperties: true
+
+ Session:
+ type: object
+ required: [id]
+ properties:
+ id: { type: string }
+ object: { type: string, const: session }
+ harness_id: { type: string }
+ environment: { type: string, description: The environment the session's turns read, when one did. }
+ title: { type: string }
+ status: { type: string }
+ created_at: { type: integer }
+ updated_at: { type: integer }
+ additionalProperties: true
+
+ SessionList:
+ type: object
+ required: [sessions]
+ properties:
+ sessions: { type: array, items: { $ref: '#/components/schemas/Session' } }
+ next_cursor:
+ type: [string, 'null']
+ description: |
+ null on the last page. A client must not be required to detect the end by receiving fewer
+ items than requested — that heuristic is wrong whenever a page is exactly full.
+ additionalProperties: true
+
+ File:
+ type: object
+ required: [id, filename]
+ properties:
+ id: { type: string }
+ object: { type: string, const: file }
+ container_id: { type: string }
+ filename: { type: string }
+ bytes: { type: integer, minimum: 0 }
+ created_at: { type: integer }
+ additionalProperties: true
+
+ ErrorEnvelope:
+ type: object
+ required: [error]
+ properties:
+ error: { $ref: '#/components/schemas/Error' }
+ detail:
+ type: string
+ deprecated: true
+ description: |
+ A human-readable alias of `error.message`, retained for clients written against
+ implementations that predate this envelope. Carries no information not in `error`.
+ additionalProperties: true
+
+ Error:
+ type: object
+ required: [type, code, message]
+ properties:
+ type:
+ type: string
+ enum:
+ - invalid_request_error
+ - authentication_error
+ - permission_error
+ - rate_limit_error
+ - harness_error
+ - server_error
+ code:
+ type: string
+ description: |
+ Specific and machine-readable. Servers may define additional codes for conditions this
+ specification does not cover, and must namespace them with a vendor prefix so a future
+ version cannot collide with them.
+ examples:
+ - unsupported_protocol_version
+ - invalid_input
+ - harness_not_found
+ - response_not_found
+ - session_not_found
+ - plugin_not_found
+ - file_not_found
+ - session_expired
+ - harness_mismatch
+ - session_busy
+ - plugin_conflict
+ - file_too_large
+ - model_unavailable
+ - unsupported_base
+ - plugin_invalid
+ - unsupported_plugin_schema
+ - environment_not_found
+ - environment_not_ready
+ - environment_busy
+ - environment_exists
+ - environment_invalid
+ - environment_unavailable
+ - unsupported_transport
+ - missing_credential
+ - invalid_credential
+ - insufficient_scope
+ - rate_limited
+ - quota_exhausted
+ - harness_error
+ - harness_unavailable
+ - provider_error
+ - timeout
+ - cancelled
+ - preview_unavailable
+ - preview_failed
+ message:
+ type: string
+ description: |
+ One sentence, safe to show a user. Must not contain credentials, internal hostnames, file
+ paths, or stack traces.
+ param: { type: [string, 'null'], description: Dotted path to the offending field. }
+ detail: { type: [object, 'null'], additionalProperties: true }
+ additionalProperties: true
+
+ Event:
+ type: object
+ required: [type, sequence_number]
+ description: |
+ One streamed event. `sequence_number` starts at 0 and increases by exactly 1 per event, so a
+ client can detect a dropped event rather than silently rendering a gap.
+ properties:
+ type:
+ type: string
+ examples:
+ - response.created
+ - response.in_progress
+ - response.output_item.added
+ - response.output_item.done
+ - response.content_part.added
+ - response.content_part.done
+ - response.output_text.delta
+ - response.output_text.done
+ - response.output_text.annotation.added
+ - response.reasoning_summary_part.added
+ - response.reasoning_summary_text.delta
+ - response.reasoning_summary_part.done
+ - response.function_call_arguments.delta
+ - response.function_call_arguments.done
+ - response.completed
+ - response.incomplete
+ - response.failed
+ - error
+ sequence_number: { type: integer, minimum: 0 }
+ response: { $ref: '#/components/schemas/Response' }
+ item: { $ref: '#/components/schemas/OutputItem' }
+ part: { $ref: '#/components/schemas/ContentPart' }
+ annotation: { $ref: '#/components/schemas/Annotation' }
+ delta: { type: string }
+ text: { type: string }
+ arguments: { type: string }
+ item_id: { type: string }
+ output_index: { type: integer, minimum: 0 }
+ content_index: { type: integer, minimum: 0 }
+ summary_index: { type: integer, minimum: 0 }
+ annotation_index: { type: integer, minimum: 0 }
+ code: { type: string }
+ message: { type: string }
+ param: { type: [string, 'null'] }
+ additionalProperties: true
diff --git a/protocol/schema/uhp-2026-09-28.schema.json b/protocol/schema/uhp-2026-09-28.schema.json
new file mode 100644
index 00000000..773c8bd5
--- /dev/null
+++ b/protocol/schema/uhp-2026-09-28.schema.json
@@ -0,0 +1,1764 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://unifiedharnessprotocol.org/schema/uhp-2026-09-28.schema.json",
+ "title": "Unified Harness Protocol",
+ "description": "Object definitions for UHP 2026-09-28. Generated from uhp-2026-09-28.openapi.yaml by build.py — do not edit by hand.",
+ "$defs": {
+ "Discovery": {
+ "type": "object",
+ "required": [
+ "object",
+ "protocol",
+ "versions",
+ "default_version",
+ "conformance_class",
+ "capabilities"
+ ],
+ "properties": {
+ "object": {
+ "type": "string",
+ "const": "uhp.discovery"
+ },
+ "protocol": {
+ "type": "string",
+ "const": "uhp"
+ },
+ "versions": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "string"
+ }
+ },
+ "default_version": {
+ "type": "string"
+ },
+ "conformance_class": {
+ "type": "string",
+ "enum": [
+ "core",
+ "extended",
+ "full"
+ ]
+ },
+ "capabilities": {
+ "$ref": "#/$defs/Capabilities"
+ },
+ "plugin_schemas": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": "The Agent Plugins manifest schema identifiers this server installs. Present and non-empty\nwhen `capabilities.plugins` is true.\n",
+ "examples": [
+ [
+ "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"
+ ]
+ ]
+ },
+ "implementation": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ }
+ },
+ "additionalProperties": true
+ },
+ "Capabilities": {
+ "type": "object",
+ "description": "Named booleans. A server reports `false` for a capability it does not implement rather than\nomitting it, so a client can distinguish \"not supported\" from \"server predates this field\".\nA client treats an absent key as `false`.\n",
+ "properties": {
+ "streaming": {
+ "type": "boolean"
+ },
+ "sessions": {
+ "type": "boolean"
+ },
+ "cancellation": {
+ "type": "boolean"
+ },
+ "files_input": {
+ "type": "boolean"
+ },
+ "files_output": {
+ "type": "boolean"
+ },
+ "session_listing": {
+ "type": "boolean"
+ },
+ "harness_management": {
+ "type": "boolean"
+ },
+ "session_sharing": {
+ "type": "boolean"
+ },
+ "idempotency": {
+ "type": "boolean"
+ },
+ "plugins": {
+ "type": "boolean",
+ "description": "The server installs Agent Plugins packages into harnesses, serves their files, and exports\na harness as a package. Optional at every class.\n"
+ },
+ "environments": {
+ "type": "boolean",
+ "description": "The server holds environments: a project's files and installed dependencies, built once,\nread-only at a fixed path in every session that names one. Optional at every class.\n"
+ }
+ },
+ "additionalProperties": {
+ "type": "boolean"
+ }
+ },
+ "Harness": {
+ "type": "object",
+ "required": [
+ "id",
+ "name",
+ "base"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^chrn_"
+ },
+ "object": {
+ "type": "string",
+ "const": "harness"
+ },
+ "name": {
+ "type": "string"
+ },
+ "base": {
+ "type": "string",
+ "description": "Opaque. Not enumerated by this specification — a client must treat it as a string, or the\nprotocol would need revising every time a harness is released.\n",
+ "examples": [
+ "codex",
+ "claude-code",
+ "hermes"
+ ]
+ },
+ "baseLabel": {
+ "type": "string"
+ },
+ "defaultModel": {
+ "type": "string"
+ },
+ "systemPrompt": {
+ "type": "string"
+ },
+ "mcpServers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/McpServer"
+ }
+ },
+ "skills": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Skill"
+ }
+ },
+ "plugins": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Plugin"
+ },
+ "description": "Installed plugins. Their servers and skills join the harness's own for every turn;\n`mcpServers` and `skills` above report only what was written to them directly.\n"
+ },
+ "environment": {
+ "type": "string",
+ "description": "The environment (`henv_`) this harness's tasks read, mounted read-only at its `mount`;\nempty when none. A task may name another with its own `environment` field.\n"
+ },
+ "disabledTools": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "maxStep": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "timeoutSeconds": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "createdAt": {
+ "type": "integer",
+ "description": "Unix milliseconds"
+ }
+ },
+ "additionalProperties": true
+ },
+ "McpServer": {
+ "type": "object",
+ "required": [
+ "name",
+ "url"
+ ],
+ "description": "A remote MCP server attached to a harness. Only enabled entries are connected for a turn; a\ndisabled entry must not be contacted at all. An unreachable server must not fail the task.\nUnchanged from 2026-08-11: a process (stdio) server is declared inside a plugin, see\nPluginMcpServer.\n",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Sanitised to a CLI-safe identifier by the server."
+ },
+ "url": {
+ "type": "string",
+ "format": "uri"
+ },
+ "transport": {
+ "type": "string",
+ "enum": [
+ "http",
+ "sse"
+ ],
+ "default": "http"
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "auth": {
+ "type": "string",
+ "description": "Bearer token, or a server-side reference the server resolves. A server must never return\na resolved credential to a client.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "PluginMcpServer": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "description": "An MCP server a plugin's mcp.json declares, derived by the server. The harness MCP server\nobject plus the `stdio` transport: `url` is required for `http` and `sse`, `command` for\n`stdio`. Placeholders are reported unexpanded; `enabled` is always true, the plugin's own\n`enabled` governs.\n",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "transport": {
+ "type": "string",
+ "enum": [
+ "http",
+ "sse",
+ "stdio"
+ ],
+ "default": "http",
+ "description": "`http` is Streamable HTTP (`streamable-http` in mcp.json); `sse` the older HTTP+SSE\ntransport; `stdio` a process the server launches inside the agent's sandbox.\n"
+ },
+ "url": {
+ "type": "string",
+ "format": "uri",
+ "description": "Endpoint (`http` and `sse`)."
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "Fixed request headers (`http` and `sse`). Never subject to placeholder expansion."
+ },
+ "command": {
+ "type": "string",
+ "description": "One executable token (`stdio`): a bare name resolved on the sandbox's search path, or a\nplugin-relative path beginning with `./`. Never a shell string, never expanded.\n"
+ },
+ "args": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Arguments (`stdio`). `${PLUGIN_ROOT}` and `${PLUGIN_DATA}` expand at run time."
+ },
+ "env": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "Environment overlay (`stdio`). Must not name PLUGIN_ROOT or PLUGIN_DATA; the server sets\nthose. Values expand at run time.\n"
+ },
+ "cwd": {
+ "type": "string",
+ "description": "Working directory (`stdio`). Defaults to the plugin root; must stay within the plugin\nroot or PLUGIN_DATA.\n"
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true
+ }
+ },
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "transport": {
+ "const": "stdio"
+ }
+ },
+ "required": [
+ "transport"
+ ]
+ },
+ "then": {
+ "required": [
+ "command"
+ ]
+ },
+ "else": {
+ "required": [
+ "url"
+ ]
+ }
+ }
+ ],
+ "additionalProperties": true
+ },
+ "Skill": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "description": "A skill is a FOLDER, not a file. A server must materialise the whole folder where the agent\ncan read it — materialising only SKILL.md breaks every skill carrying references, scripts or\ndata. Round-tripping a harness through GET and PUT must not lose skill contents.\n",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true,
+ "description": "false suppresses the skill, including one inherited from the base."
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/SkillFile"
+ },
+ "description": "The bundle. Must contain a SKILL.md."
+ },
+ "content": {
+ "type": "string",
+ "description": "Shorthand for a single-file bundle whose only member is SKILL.md."
+ },
+ "blob": {
+ "type": "string",
+ "description": "Server-assigned handle for a bundle stored out of line. A client receives it, passes it\nback unchanged, and reads the files from the skill files endpoint.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "SkillFile": {
+ "type": "object",
+ "required": [
+ "path"
+ ],
+ "description": "One file of a skill folder or of a plugin package.",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Relative to the skill's own folder, or to the plugin root; nested directories are\nsupported. A server must reject a path that escapes the folder.\n",
+ "examples": [
+ "SKILL.md",
+ "references/codes.md",
+ "assets/logo.png"
+ ]
+ },
+ "content": {
+ "type": "string",
+ "description": "Text content."
+ },
+ "content_b64": {
+ "type": "string",
+ "description": "Base64 for binary content; preserved byte-for-byte."
+ }
+ },
+ "additionalProperties": true
+ },
+ "FileList": {
+ "type": "object",
+ "required": [
+ "files"
+ ],
+ "properties": {
+ "files": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/SkillFile"
+ }
+ }
+ }
+ },
+ "Plugin": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "description": "An Agent Plugins package installed into a harness: `plugin.json` at the root, MCP servers in\n`mcp.json`, skills under `skills/`. A client writes `files` (or passes back `blob`) and\noptionally `name` and `enabled`; the server derives `manifest`, `mcpServers`, `skills` and\n`skipped` from the package on every write and ignores those fields on input. A refused\npackage leaves the harness unchanged.\n",
+ "properties": {
+ "name": {
+ "type": "string",
+ "pattern": "^(?!.*(--|\\.\\.))[a-z0-9]([a-z0-9.-]*[a-z0-9])?$",
+ "maxLength": 64,
+ "description": "The manifest's `name`. Optional on write; if sent it must equal the manifest's."
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true,
+ "description": "false keeps the plugin installed and inert; nothing in it is materialised or contacted."
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/SkillFile"
+ },
+ "description": "The package. Must contain `plugin.json` at its root."
+ },
+ "blob": {
+ "type": "string",
+ "description": "Server-assigned handle for a package stored out of line. A client passes it back unchanged\nand reads the files from the plugin files endpoint.\n"
+ },
+ "manifest": {
+ "$ref": "#/$defs/PluginManifest"
+ },
+ "mcpServers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PluginMcpServer"
+ },
+ "description": "Derived from `mcp.json`. Placeholders are reported unexpanded; `enabled` is always true,\nthe plugin's own `enabled` governs.\n"
+ },
+ "skills": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PluginSkill"
+ },
+ "description": "Derived from `skills/`, one entry per immediate child directory with a SKILL.md."
+ },
+ "skipped": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PluginSkipped"
+ },
+ "description": "What the server found and could not load. Present on every plugin object the server\nreturns, empty when nothing was skipped.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "PluginManifest": {
+ "type": "object",
+ "required": [
+ "$schema",
+ "name"
+ ],
+ "description": "`plugin.json`, parsed. Mirrors the Agent Plugins 1.0.0 manifest schema\n(https://agent-plugins.org/schemas/1.0.0/plugin.schema.json, Apache-2.0) field for field, and\npermits additional properties because a UHP client ignores fields it does not know. The\nschema a manifest's own `$schema` names is authoritative; a server validates against that.\n",
+ "properties": {
+ "$schema": {
+ "type": "string",
+ "format": "uri"
+ },
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "pattern": "^(?!.*(--|\\.\\.))[a-z0-9]([a-z0-9.-]*[a-z0-9])?$"
+ },
+ "version": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "author": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "email": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "homepage": {
+ "type": "string"
+ },
+ "repository": {
+ "type": "string"
+ },
+ "license": {
+ "type": "string"
+ },
+ "keywords": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "extensions": {
+ "type": "object",
+ "description": "Client-specific data keyed by reverse-domain namespace, per Agent Plugins §8.",
+ "additionalProperties": {
+ "type": "object"
+ }
+ }
+ },
+ "additionalProperties": true
+ },
+ "PluginSkill": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The SKILL.md frontmatter name",
+ "equal to the directory name.": null
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "PluginSkipped": {
+ "type": "object",
+ "required": [
+ "path",
+ "reason"
+ ],
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Where in the package, e.g. `skills/broken`, `mcp.json#/mcpServers/redline`, `plugin.json#/vendorField`.",
+ "examples": [
+ "skills/broken",
+ "mcp.json#/mcpServers/redline"
+ ]
+ },
+ "reason": {
+ "type": "string",
+ "description": "One sentence."
+ }
+ },
+ "additionalProperties": true
+ },
+ "HarnessCreate": {
+ "type": "object",
+ "required": [
+ "base"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "base": {
+ "type": "string"
+ },
+ "default_model": {
+ "type": "string"
+ },
+ "system_prompt": {
+ "type": "string"
+ },
+ "mcp_servers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/McpServer"
+ }
+ },
+ "skills": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Skill"
+ }
+ },
+ "plugins": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Plugin"
+ },
+ "description": "Requires the `plugins` capability. Each item needs `files` or `blob`."
+ },
+ "environment": {
+ "type": "string",
+ "description": "An environment id of the caller's scope",
+ "or empty. Requires the `environments` capability.": null
+ },
+ "disabled_tools": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "max_step": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "timeout_seconds": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "additionalProperties": true
+ },
+ "ModelCatalog": {
+ "type": "object",
+ "required": [
+ "backends"
+ ],
+ "properties": {
+ "backends": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "object",
+ "required": [
+ "default",
+ "models"
+ ],
+ "properties": {
+ "default": {
+ "type": "string"
+ },
+ "models": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Model"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "HarnessModels": {
+ "type": "object",
+ "required": [
+ "models"
+ ],
+ "properties": {
+ "harness_id": {
+ "type": "string"
+ },
+ "backend": {
+ "type": "string"
+ },
+ "default": {
+ "type": "string"
+ },
+ "fallback": {
+ "type": "string"
+ },
+ "models": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Model"
+ }
+ }
+ }
+ },
+ "Model": {
+ "type": "object",
+ "required": [
+ "id",
+ "available"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "label": {
+ "type": "string"
+ },
+ "backend": {
+ "type": "string"
+ },
+ "available": {
+ "type": "boolean",
+ "description": "Computed, not asserted: true means the server can serve this model for this harness right\nnow. Listing a model as available and then failing the task is the worst outcome for a\nclient, because a user has already chosen it.\n"
+ },
+ "default": {
+ "type": "boolean"
+ }
+ },
+ "additionalProperties": true
+ },
+ "CreateResponseRequest": {
+ "type": "object",
+ "required": [
+ "input"
+ ],
+ "properties": {
+ "input": {
+ "oneOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ ],
+ "description": "A bare string is shorthand for one user message."
+ },
+ "model": {
+ "type": "string",
+ "description": "Canonical model id. Omitted means the harness default."
+ },
+ "metadata": {
+ "type": "object",
+ "description": "Client metadata. `harness_id` selects the configured harness.",
+ "properties": {
+ "harness_id": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "stream": {
+ "type": "boolean",
+ "default": false
+ },
+ "previous_response_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "instructions": {
+ "type": "string"
+ },
+ "store": {
+ "type": "boolean",
+ "default": true
+ },
+ "max_output_tokens": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "max_step": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "description": "Agent step (tool-call round) budget"
+ },
+ "timeout_seconds": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "description": "Wall-clock budget"
+ },
+ "environment": {
+ "type": "string",
+ "description": "The environment this task reads, overriding the harness's. Refused with\n`environment_not_found` or `environment_not_ready` before the task starts.\n"
+ },
+ "tools": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ },
+ "description": "Reserved and ignored. Accepted for wire compatibility, never acted on, and reported in\n`metadata.ignored_fields` on the response. A UHP harness invokes and executes tools\nitself and reports them in `output`; there is no input path for a tool result, so the\nclient-executed tool loop this field implies cannot be completed by a conformant server.\nConfigure tools on the harness instead — see Harnesses §4.1. Tasks §1.4.\n"
+ },
+ "include": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Reserved and ignored. Accepted for wire compatibility, never acted on, and reported in\n`metadata.ignored_fields` on the response. No values are enumerated, so any string a\nserver recognised would be one it named itself. Tasks §1.4.\n"
+ },
+ "background": {
+ "type": "boolean",
+ "default": false
+ }
+ },
+ "additionalProperties": true
+ },
+ "Response": {
+ "type": "object",
+ "required": [
+ "id",
+ "object",
+ "created_at",
+ "status",
+ "output",
+ "model"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^resp_"
+ },
+ "object": {
+ "type": "string",
+ "const": "response"
+ },
+ "created_at": {
+ "type": "integer",
+ "description": "Unix seconds"
+ },
+ "status": {
+ "$ref": "#/$defs/ResponseStatus"
+ },
+ "error": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/$defs/Error"
+ }
+ ],
+ "description": "Non-null only when status is `failed`."
+ },
+ "incomplete_details": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "additionalProperties": true
+ },
+ "previous_response_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "model": {
+ "type": "string",
+ "description": "The model that actually ran."
+ },
+ "output": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/OutputItem"
+ }
+ },
+ "store": {
+ "type": "boolean"
+ },
+ "usage": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/$defs/Usage"
+ }
+ ],
+ "description": "null when the server cannot account for usage. A fabricated zero would be worse than an\nhonest absence, because a client cannot tell it from a free task.\n"
+ },
+ "metadata": {
+ "type": "object",
+ "properties": {
+ "session_id": {
+ "type": "string"
+ },
+ "requested_model": {
+ "type": "string",
+ "description": "Present when the server ran a different model than was requested."
+ },
+ "model_fallback": {
+ "type": "boolean"
+ },
+ "model_fallback_reason": {
+ "type": "string"
+ },
+ "ignored_fields": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Request fields the server did not act on, by name, in any order. Required when the\nrequest carried `tools` or `include`, which are reserved and ignored. A silently\nignored field is indistinguishable from an honoured one. Tasks §1.1 and §1.4.\n"
+ }
+ },
+ "additionalProperties": true
+ }
+ },
+ "additionalProperties": true
+ },
+ "ResponseStatus": {
+ "type": "string",
+ "enum": [
+ "in_progress",
+ "completed",
+ "failed",
+ "incomplete",
+ "cancelled"
+ ],
+ "description": "`incomplete` means a budget stopped the work and is usually worth continuing.\n`failed` means it could not be done. `cancelled` means the client asked for a stop, and must\nnever be reported as `failed`.\n"
+ },
+ "OutputItem": {
+ "type": "object",
+ "required": [
+ "type"
+ ],
+ "description": "A client must tolerate item types it does not recognise. A client that renders only `message`\nitems and ignores the rest is a valid client.\n",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string",
+ "examples": [
+ "message",
+ "reasoning",
+ "function_call",
+ "function_call_output"
+ ]
+ },
+ "status": {
+ "type": "string"
+ },
+ "role": {
+ "type": "string"
+ },
+ "content": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/ContentPart"
+ }
+ },
+ "summary": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "call_id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "arguments": {
+ "type": "string",
+ "description": "JSON",
+ "as a string": null
+ },
+ "output": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "ContentPart": {
+ "type": "object",
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "examples": [
+ "output_text"
+ ]
+ },
+ "text": {
+ "type": "string"
+ },
+ "annotations": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Annotation"
+ }
+ }
+ },
+ "additionalProperties": true
+ },
+ "Annotation": {
+ "type": "object",
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "container_file_citation"
+ },
+ "container_id": {
+ "type": "string"
+ },
+ "file_id": {
+ "type": "string"
+ },
+ "filename": {
+ "type": "string"
+ },
+ "download_url": {
+ "type": "string",
+ "format": "uri"
+ },
+ "start_index": {
+ "type": "integer"
+ },
+ "end_index": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "Usage": {
+ "type": "object",
+ "properties": {
+ "input_tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "output_tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "total_tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "cache_read_tokens": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "cache_write_tokens": {
+ "type": "integer",
+ "minimum": 0
+ }
+ },
+ "additionalProperties": true
+ },
+ "SessionShare": {
+ "type": "object",
+ "description": "A published read-only view of a session (Sessions §5). `url` may be relative, resolving\nagainst the base URL the caller is already using — a server behind a proxy cannot know its\npublic origin, and a base-relative path survives every fronting. The share's id MUST NOT\nfunction as a credential for the rest of the API.\n",
+ "required": [
+ "id",
+ "url"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "description": "SHOULD be \"session.share\""
+ },
+ "enabled": {
+ "type": "boolean"
+ }
+ },
+ "additionalProperties": true
+ },
+ "TurnItem": {
+ "type": "object",
+ "description": "One turn of a session's history (Sessions §3). Previously an object with no stated shape,\nwhich kept every conformance check at \"the endpoint answered 200\" and made transcript\nrebuilding an exercise in one implementation's habits.\n",
+ "required": [
+ "id",
+ "status"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The response id, usable with GET /v1/responses/{id}"
+ },
+ "status": {
+ "type": "string"
+ },
+ "user": {
+ "type": "string"
+ },
+ "assistant": {
+ "type": "string"
+ },
+ "tools": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ },
+ "additionalProperties": true
+ },
+ "Environment": {
+ "type": "object",
+ "required": [
+ "id",
+ "name",
+ "slug",
+ "status",
+ "mount"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^henv_"
+ },
+ "object": {
+ "type": "string",
+ "const": "environment"
+ },
+ "name": {
+ "type": "string"
+ },
+ "slug": {
+ "type": "string",
+ "description": "The path segment sessions see; derived from the name at creation and fixed after."
+ },
+ "description": {
+ "type": "string"
+ },
+ "entry": {
+ "type": "string",
+ "description": "How the project is run, in the owner's words; repeated to the agent."
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "empty",
+ "building",
+ "ready",
+ "failed"
+ ],
+ "description": "`ready` means a built version is active and tasks may read it. `empty` means nothing\nwas built yet; `building` and `failed` describe the latest build.\n"
+ },
+ "mount": {
+ "type": "string",
+ "description": "Where a session finds the environment, read-only. `/env/<slug>` on the reference server."
+ },
+ "version": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "description": "The active build",
+ "the one sessions read; null until one is ready.": null
+ },
+ "latestVersion": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "files": {
+ "type": "object",
+ "description": "The source's size (what the owner put in, before any build).",
+ "properties": {
+ "count": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "bytes": {
+ "type": "integer",
+ "minimum": 0
+ }
+ }
+ },
+ "packages": {
+ "type": "array",
+ "description": "What the active build installed, as the package managers report it.",
+ "items": {
+ "$ref": "#/$defs/EnvironmentPackage"
+ }
+ },
+ "versions": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/EnvironmentVersion"
+ }
+ },
+ "build": {
+ "description": "The latest build's status, or null before the first.",
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/$defs/EnvironmentVersion"
+ }
+ ]
+ },
+ "createdAt": {
+ "type": "integer",
+ "description": "Unix milliseconds"
+ },
+ "updatedAt": {
+ "type": "integer",
+ "description": "Unix milliseconds"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentPackage": {
+ "type": "object",
+ "required": [
+ "manager",
+ "name"
+ ],
+ "properties": {
+ "manager": {
+ "type": "string",
+ "examples": [
+ "pip",
+ "npm"
+ ]
+ },
+ "name": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentVersion": {
+ "type": "object",
+ "required": [
+ "version",
+ "status"
+ ],
+ "properties": {
+ "version": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "building",
+ "ready",
+ "failed",
+ "unknown"
+ ]
+ },
+ "started_at": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "finished_at": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "error": {
+ "type": "string"
+ },
+ "files": {
+ "type": "integer"
+ },
+ "bytes": {
+ "type": "integer"
+ },
+ "packages": {
+ "type": "integer",
+ "description": "How many packages the build installed."
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentBuild": {
+ "type": "object",
+ "required": [
+ "id",
+ "version",
+ "status"
+ ],
+ "description": "A build's record; the log is the installers' own output, capped by the server.",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "const": "environment.build"
+ },
+ "version": {
+ "type": "integer"
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "building",
+ "ready",
+ "failed"
+ ]
+ },
+ "started_at": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "finished_at": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "error": {
+ "type": "string"
+ },
+ "log": {
+ "type": "string"
+ },
+ "packages": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/EnvironmentPackage"
+ }
+ },
+ "files": {
+ "type": "integer"
+ },
+ "bytes": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentCreate": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Must start with a letter or digit; the slug derives from it."
+ },
+ "description": {
+ "type": "string"
+ },
+ "entry": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentList": {
+ "type": "object",
+ "required": [
+ "environments"
+ ],
+ "properties": {
+ "environments": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Environment"
+ }
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentFileEntry": {
+ "type": "object",
+ "required": [
+ "path",
+ "dir"
+ ],
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Relative to the environment's root."
+ },
+ "dir": {
+ "type": "boolean"
+ },
+ "bytes": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "mtime": {
+ "type": "integer",
+ "description": "Unix seconds."
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentFileList": {
+ "type": "object",
+ "required": [
+ "entries"
+ ],
+ "properties": {
+ "entries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/EnvironmentFileEntry"
+ }
+ },
+ "count": {
+ "type": "integer",
+ "description": "Files",
+ "not directories.": null
+ },
+ "bytes": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentImport": {
+ "type": "object",
+ "description": "The JSON form of an import: a git repository. The other form is the archive itself as the\nrequest body (a zip or a tar, any content type but `application/json`).\n",
+ "properties": {
+ "git": {
+ "type": "object",
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "url": {
+ "type": "string"
+ },
+ "ref": {
+ "type": "string",
+ "description": "A branch or tag; the default branch when omitted."
+ }
+ }
+ },
+ "replace": {
+ "type": "boolean",
+ "default": false,
+ "description": "Clear the source before importing."
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentImportResult": {
+ "type": "object",
+ "properties": {
+ "written": {
+ "type": "integer"
+ },
+ "skipped": {
+ "type": "integer",
+ "description": "Members that must not land (links",
+ "escapes) and were dropped.": null
+ },
+ "count": {
+ "type": "integer"
+ },
+ "bytes": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "Session": {
+ "type": "object",
+ "required": [
+ "id"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "const": "session"
+ },
+ "harness_id": {
+ "type": "string"
+ },
+ "environment": {
+ "type": "string",
+ "description": "The environment the session's turns read",
+ "when one did.": null
+ },
+ "title": {
+ "type": "string"
+ },
+ "status": {
+ "type": "string"
+ },
+ "created_at": {
+ "type": "integer"
+ },
+ "updated_at": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "SessionList": {
+ "type": "object",
+ "required": [
+ "sessions"
+ ],
+ "properties": {
+ "sessions": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/Session"
+ }
+ },
+ "next_cursor": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "null on the last page. A client must not be required to detect the end by receiving fewer\nitems than requested — that heuristic is wrong whenever a page is exactly full.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "File": {
+ "type": "object",
+ "required": [
+ "id",
+ "filename"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "const": "file"
+ },
+ "container_id": {
+ "type": "string"
+ },
+ "filename": {
+ "type": "string"
+ },
+ "bytes": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "created_at": {
+ "type": "integer"
+ }
+ },
+ "additionalProperties": true
+ },
+ "ErrorEnvelope": {
+ "type": "object",
+ "required": [
+ "error"
+ ],
+ "properties": {
+ "error": {
+ "$ref": "#/$defs/Error"
+ },
+ "detail": {
+ "type": "string",
+ "deprecated": true,
+ "description": "A human-readable alias of `error.message`, retained for clients written against\nimplementations that predate this envelope. Carries no information not in `error`.\n"
+ }
+ },
+ "additionalProperties": true
+ },
+ "Error": {
+ "type": "object",
+ "required": [
+ "type",
+ "code",
+ "message"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "invalid_request_error",
+ "authentication_error",
+ "permission_error",
+ "rate_limit_error",
+ "harness_error",
+ "server_error"
+ ]
+ },
+ "code": {
+ "type": "string",
+ "description": "Specific and machine-readable. Servers may define additional codes for conditions this\nspecification does not cover, and must namespace them with a vendor prefix so a future\nversion cannot collide with them.\n",
+ "examples": [
+ "unsupported_protocol_version",
+ "invalid_input",
+ "harness_not_found",
+ "response_not_found",
+ "session_not_found",
+ "plugin_not_found",
+ "file_not_found",
+ "session_expired",
+ "harness_mismatch",
+ "session_busy",
+ "plugin_conflict",
+ "file_too_large",
+ "model_unavailable",
+ "unsupported_base",
+ "plugin_invalid",
+ "unsupported_plugin_schema",
+ "environment_not_found",
+ "environment_not_ready",
+ "environment_busy",
+ "environment_exists",
+ "environment_invalid",
+ "environment_unavailable",
+ "unsupported_transport",
+ "missing_credential",
+ "invalid_credential",
+ "insufficient_scope",
+ "rate_limited",
+ "quota_exhausted",
+ "harness_error",
+ "harness_unavailable",
+ "provider_error",
+ "timeout",
+ "cancelled",
+ "preview_unavailable",
+ "preview_failed"
+ ]
+ },
+ "message": {
+ "type": "string",
+ "description": "One sentence, safe to show a user. Must not contain credentials, internal hostnames, file\npaths, or stack traces.\n"
+ },
+ "param": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Dotted path to the offending field."
+ },
+ "detail": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "additionalProperties": true
+ }
+ },
+ "additionalProperties": true
+ },
+ "Event": {
+ "type": "object",
+ "required": [
+ "type",
+ "sequence_number"
+ ],
+ "description": "One streamed event. `sequence_number` starts at 0 and increases by exactly 1 per event, so a\nclient can detect a dropped event rather than silently rendering a gap.\n",
+ "properties": {
+ "type": {
+ "type": "string",
+ "examples": [
+ "response.created",
+ "response.in_progress",
+ "response.output_item.added",
+ "response.output_item.done",
+ "response.content_part.added",
+ "response.content_part.done",
+ "response.output_text.delta",
+ "response.output_text.done",
+ "response.output_text.annotation.added",
+ "response.reasoning_summary_part.added",
+ "response.reasoning_summary_text.delta",
+ "response.reasoning_summary_part.done",
+ "response.function_call_arguments.delta",
+ "response.function_call_arguments.done",
+ "response.completed",
+ "response.incomplete",
+ "response.failed",
+ "error"
+ ]
+ },
+ "sequence_number": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "response": {
+ "$ref": "#/$defs/Response"
+ },
+ "item": {
+ "$ref": "#/$defs/OutputItem"
+ },
+ "part": {
+ "$ref": "#/$defs/ContentPart"
+ },
+ "annotation": {
+ "$ref": "#/$defs/Annotation"
+ },
+ "delta": {
+ "type": "string"
+ },
+ "text": {
+ "type": "string"
+ },
+ "arguments": {
+ "type": "string"
+ },
+ "item_id": {
+ "type": "string"
+ },
+ "output_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "content_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "summary_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "annotation_index": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "code": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ },
+ "param": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "additionalProperties": true
+ }
+ }
+}
diff --git a/protocol/site/build.py b/protocol/site/build.py
index 75efc360..bb5b4ac0 100644
--- a/protocol/site/build.py
+++ b/protocol/site/build.py
@@ -28,14 +28,14 @@ except ImportError: # pragma: no cover
HERE = pathlib.Path(__file__).parent
ROOT = HERE.parent # protocol/
DIST = HERE / "dist"
-VERSION = "2026-09-12"
+VERSION = "2026-09-28"
# Published specification versions, latest first. The spec is served under a per-version path
# (/spec/<date>/…, mirroring MCP's /specification/<date>/…) so every version keeps a permanent
# address: a citation to the 2026-08-11 architecture never silently becomes a later version. Only
# the specification is versioned this way; conformance, governance and versioning are living docs.
# Every version listed is built from its own frozen tree under protocol/versions/<date>/; the latest
# is the one in the sidebar, the rest are served at their dated addresses with a notice.
-VERSIONS = ["2026-09-12", "2026-08-11"]
+VERSIONS = ["2026-09-28", "2026-09-12", "2026-08-11"]
SITE = "unifiedharnessprotocol.org"
# The specification's chapters, in reading order. NAV builds their per-version paths from this so
@@ -46,6 +46,7 @@ SPEC_CHAPTERS = [
("lifecycle", "Lifecycle"),
("harnesses", "Harnesses"),
("plugins", "Plugins"),
+ ("environments", "Environments"),
("tasks", "Tasks"),
("streaming", "Streaming"),
("sessions", "Sessions"),
diff --git a/protocol/versions/2026-09-28/architecture.md b/protocol/versions/2026-09-28/architecture.md
new file mode 100644
index 00000000..fd5d3279
--- /dev/null
+++ b/protocol/versions/2026-09-28/architecture.md
@@ -0,0 +1,146 @@
+# Architecture
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+The key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT, RECOMMENDED, MAY and
+OPTIONAL in this specification are to be interpreted as described in [RFC 2119][rfc2119] and
+[RFC 8174][rfc8174] when, and only when, they appear in all capitals.
+
+[rfc2119]: https://www.rfc-editor.org/rfc/rfc2119
+[rfc8174]: https://www.rfc-editor.org/rfc/rfc8174
+
+## 1. Roles
+
+```
+┌──────────┐ UHP over HTTP ┌──────────┐ implementation-defined ┌──────────┐
+│ Client │ ────────────────▶ │ Server │ ─────────────────────────▶ │ Harness │
+└──────────┘ └──────────┘ └──────────┘
+```
+
+**Client** — an application that wants work done: a product backend, a CLI, a CI job, another agent.
+A client speaks only UHP. It MUST NOT be required to know which harness implementation runs behind
+the server, nor how the server executes it.
+
+**Server** — implements this specification. It accepts tasks, drives one or more harnesses, and
+reports progress and results in the vocabulary defined here. Everything about *how* it runs a
+harness — containers, subprocesses, queues, remote workers — is out of scope for this specification
+and MUST NOT leak into the wire format.
+
+**Harness** — a complete agent runtime with its own loop, tools and session state. UHP does not
+specify the harness itself; it specifies how a client drives one through a server. Harnesses are
+identified by a **base**: a stable string such as `codex`, `claude-code` or `hermes`.
+
+A **configured harness** is a base plus configuration — default model, system prompt, tool
+restrictions, skills, MCP servers, step and time budgets. It is the unit a client selects when it
+sends work, and it is addressed by a server-assigned id.
+
+> **Why a configured harness, and not just a base?**
+> The same base behaves very differently with a different system prompt, a different model, or a
+> different tool set. Making the configuration a first-class, addressable object means a product can
+> change how its agent behaves without redeploying its backend, and means two products can share a
+> server without sharing behaviour.
+
+## 2. Conformance classes
+
+A server declares which class it implements. Each class is cumulative: **Extended** includes
+**Core**, **Full** includes **Extended**.
+
+| Class | A server at this class MUST implement |
+|---|---|
+| **Core** | Capability discovery, harness discovery, non-streaming and streaming task execution, session continuation, cancellation, and the error model. |
+| **Extended** | Core, plus file input, artifact retrieval, and session listing/inspection. |
+| **Full** | Extended, plus harness lifecycle management (create, update, delete) and session sharing. |
+
+A client MUST NOT assume any capability above **Core** without checking capability discovery
+(see [Lifecycle §2](lifecycle.md)). A server MUST NOT advertise a capability it does not implement —
+advertising is a promise, and a client that trusts it and receives a `404` has been lied to in a way
+it cannot recover from.
+
+The [conformance suite](../../conformance/) tests each class separately and reports per class. A
+server that passes at a class MAY describe itself as "UHP <version> conformant (<class>)", naming
+the version its discovery document serves as `default_version`, which the suite reports. No
+other use of the term "conformant" is meaningful.
+
+## 3. Object model
+
+Seven object types. Every one carries an `object` field naming its type, and an `id` with a
+type-distinguishing prefix so an identifier is never ambiguous about what it points at.
+
+| Object | `object` value | Id prefix | Lifetime |
+|---|---|---|---|
+| Harness | `harness` | `chrn_` | Until deleted |
+| Response | `response` | `resp_` | Retained per server policy |
+| Session | `session` | `hsess` | Until deleted |
+| File | `file` | `file_` | With its container |
+| Container | `container` | `cntr_` | With its session |
+| Environment | `environment` | `henv_` | Until deleted; optional, see [Environments](environments.md) |
+| Event | *(none — events carry `type`)* | — | Streamed, and replayable |
+
+Their relationships:
+
+```
+Harness ──┐
+ ├──▶ Session ──┬──▶ Response ──▶ Response ──▶ … (one per task, chained)
+Model ───┘ └──▶ Container ──▶ File, File, … (artifacts)
+```
+
+- A **response** is one task: one request in, one result out. It is the atomic unit of work.
+- A **session** is a chain of responses that share conversational context and a working directory.
+ A session is created implicitly by the first task and extended by `previous_response_id`.
+- A **container** is the file namespace of a session. Files the agent writes become artifacts in it.
+- An **environment** is a project's files and installed dependencies, built once and mounted read-only
+ into every session that names it; a harness names one as the default for its tasks. It is never
+ part of a container: artifacts come from the working directory, the environment is what the
+ working directory reads ([Environments](environments.md)).
+
+> **Why is the session implicit?**
+> Requiring `POST /sessions` before any work could be done would add a round trip, a failure mode,
+> and an object to clean up — for a concept most first tasks never need. A client that only ever
+> sends one-shot tasks never learns the word "session"; a client that needs continuity gets it by
+> quoting the id it already has.
+
+## 4. Transport
+
+- All requests MUST be HTTP/1.1 or later over TLS, except for loopback development where a server
+ MAY accept plaintext.
+- Request and response bodies are `application/json; charset=utf-8`, except file upload
+ (`multipart/form-data`) and file download (the file's own media type).
+- Streaming uses Server-Sent Events (`text/event-stream`) as described in
+ [Streaming](streaming.md).
+- Servers MUST accept requests with an absent `Accept` header and default to JSON.
+
+## 5. Authentication
+
+A client authenticates with a bearer token:
+
+```http
+Authorization: Bearer <token>
+```
+
+How tokens are issued is out of scope. A server MUST reject an absent, malformed, or unknown token
+with `401` and the error model in [Errors](errors.md), and MUST NOT distinguish "no such token"
+from "token not permitted here" in a way that lets a caller enumerate valid tokens.
+
+A server MUST scope every object to the principal that created it. A client MUST NOT be able to
+read, continue, cancel or delete another principal's response, session, or file — including by
+guessing an id. Servers MUST return `404`, not `403`, for objects outside the caller's scope, so
+that an id's existence is not disclosed.
+
+## 6. Design principles
+
+These are the rules the specification holds itself to. They are included because they explain the
+shape of what follows, and because a future change that violates one is probably a mistake.
+
+1. **The client should not be able to tell which harness ran the work** — except by asking. Every
+ difference between harnesses that a client can observe is a leak, and each leak is a place where
+ swapping harnesses breaks a product.
+2. **Progress is a stream of facts, not a rendering.** Events describe what happened — text, a tool
+ call, a file — never how to display it.
+3. **A field means one thing.** Where UHP extends a borrowed surface, it adds fields; it never
+ redefines one.
+4. **Absent is not empty, and empty is not zero.** A server that does not know a value omits it. It
+ MUST NOT invent a placeholder, an estimate, or a zero.
+5. **Failure is a first-class result.** Every failure is reportable in the same envelope as success,
+ with a machine-readable code. A client should never have to parse prose to find out what to do.
+6. **The specification, the reference implementation and the conformance suite move together.** A
+ sentence here that no test enforces is a wish, not a standard.
diff --git a/protocol/versions/2026-09-28/environments.md b/protocol/versions/2026-09-28/environments.md
new file mode 100644
index 00000000..eda9b10e
--- /dev/null
+++ b/protocol/versions/2026-09-28/environments.md
@@ -0,0 +1,266 @@
+# Environments
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+A session's working directory ([Architecture §3](architecture.md#3-object-model)) is made for one
+conversation: it is created empty, kept across turns, and everything the agent needs is put there
+again for every session that needs it. That is the right shape for a task's own files and the wrong
+shape for a project: a content pipeline with its scripts, assets, templates and a hundred installed
+packages, opened by many people, many times a day. Installed into a working directory it is
+installed once per session, uploaded once per session, and a session's checkpoint carries none of
+it forward.
+
+An **environment** is that project as one object: its files and its installed dependencies, built
+once, and read by every session that names it. A session sees it at a fixed path, read-only, beside
+its own working directory, which stays writable, private, and the only place artifacts come from.
+
+This chapter is the Environments sub-protocol. It is optional: a server advertises it with the
+`environments` capability, and a server that does not implement it is conformant at every class.
+
+## 1. What an environment is
+
+```
+/env/content-studio the environment: complete, read-only, shared (this chapter)
+ scripts/ assets/ data/ the project's files, as the owner put them in
+ .venv/ node_modules/ its dependencies, installed once when it was built
+<working directory> the session's own: writable, private, checkpointed (Files chapter)
+```
+
+Three rules make it one thing rather than a shared folder:
+
+- **It is built, not copied.** The owner puts files in ([§3](#3-files)); a build ([§4](#4-builds-and-versions))
+ snapshots them into a version and installs what the project's manifests declare, in the server's
+ own toolchain. Dependency directories that arrive with the files are not what a session gets;
+ what the build installed is. A virtualenv made on a laptop does not run in a container, and the
+ build is what makes the promise "no reinstall" true.
+- **A session reads the active version and cannot write it.** Two sessions on one environment share
+ every byte of it and none of each other's working directory. A server MUST refuse writes into the
+ environment from a session: the path is read-only, not merely described as such.
+- **The path is fixed.** The server tells the client where the environment is mounted (`mount`) and
+ tells the agent the same, so a project's scripts can be run by absolute path from any working
+ directory, and their outputs land where the user sees them.
+
+> **Why not let the session start inside the project?**
+> A working directory that *is* the project, copy-on-write, reads well until two facts collide:
+> artifacts and project files are then the same directory, so the server can no longer say which
+> files a task produced, and every write must be layered by a mechanism (overlay filesystems,
+> per-session copies) that not every sandbox has. Two paths, one of them read-only, keeps both
+> answers simple: what the task produced is in the working directory, what the project is stays in
+> the environment.
+
+## 2. The environment object
+
+```json
+{
+ "id": "henv_2f1c9d4e8a7b4c3d9e6f5a4b3c2d1e0f",
+ "object": "environment",
+ "name": "Content Studio",
+ "slug": "content-studio",
+ "description": "The teaser pipeline: episodes in, teasers and thumbnails out.",
+ "entry": "python3 run.py --episode <id>",
+ "status": "ready",
+ "mount": "/env/content-studio",
+ "version": 3,
+ "latestVersion": 3,
+ "files": { "count": 16, "bytes": 48213 },
+ "packages": [ { "manager": "pip", "name": "moviepy", "version": "2.1.1" },
+ { "manager": "npm", "name": "sharp", "version": "0.33.5" } ],
+ "versions": [ { "version": 3, "status": "ready", "started_at": 1790570000, "finished_at": 1790570094, "packages": 10 } ],
+ "build": { "version": 3, "status": "ready", "started_at": 1790570000, "finished_at": 1790570094, "error": "" },
+ "createdAt": 1790560000000,
+ "updatedAt": 1790570094000
+}
+```
+
+| Field | Type | Written by | Meaning |
+|---|---|---|---|
+| `id` | string | server | `henv_`-prefixed ([Architecture §3](architecture.md#3-object-model)) |
+| `name` | string | client | Human-readable; must begin with a letter or digit |
+| `slug` | string | server | The path segment sessions see, derived from the name at creation. It never changes: a session's instructions name it |
+| `description` | string | client | |
+| `entry` | string | client | How the project is run, in the owner's words. Repeated to the agent verbatim ([§6](#6-what-a-session-sees)) |
+| `status` | string | server | `empty` (nothing built), `building`, `ready` (a version is active), `failed` (the latest build failed and none is active) |
+| `mount` | string | server | Where a session finds it, read-only. `/env/<slug>` on the reference server; a server MAY choose another root, and MUST keep it constant for the environment's lifetime |
+| `version` | integer or null | server | The active build, the one sessions read |
+| `latestVersion` | integer or null | server | The newest build, active or not |
+| `files` | object | server | The source's size: what the owner put in, before any build |
+| `packages` | array | server | What the active build installed, as the package managers report it: `manager`, `name`, `version` |
+| `versions` | array | server | Every build: `version`, `status`, times, `error`, size |
+| `build` | object or null | server | The latest build's status |
+
+Environments are scoped like harnesses: a caller sees the environments of its own scope
+([Architecture §5](architecture.md#5-authentication)), and a harness may name only an environment
+of the same scope.
+
+```http
+POST /v1/environments create (name, description, entry)
+GET /v1/environments list
+GET /v1/environments/{id} one, with its versions
+PUT /v1/environments/{id} rename; description; entry
+DELETE /v1/environments/{id} delete every version
+```
+
+`POST` refuses a name that yields no path segment with `environment_invalid`, and a slug another
+environment already occupies with `environment_exists`: the mount path is a place, and two
+environments cannot be in it. `DELETE` refuses while a build runs (`environment_busy`). A harness
+that named a deleted environment keeps the reference; its next task is refused with
+`environment_not_found` ([§5](#5-attaching-an-environment)).
+
+## 3. Files
+
+The source is edited by path, the way a plugin's package is ([Plugins §2.1](plugins.md#21-files)),
+but one file per request, because a project is larger than a package:
+
+```http
+GET /v1/environments/{id}/files the tree: every file and directory, with sizes
+GET /v1/environments/{id}/files/{path} one file's bytes, with its content type
+PUT /v1/environments/{id}/files/{path} write one file (the body is its bytes; its directories are made)
+POST /v1/environments/{id}/directories make an empty directory: {"path": "assets/brand"}
+DELETE /v1/environments/{id}/files/{path} remove a file or a directory tree
+POST /v1/environments/{id}/import a whole project at once
+```
+
+- `path` is relative to the environment's root. A server MUST refuse a path that escapes the root,
+ or names anything other than a regular file or directory, with `environment_invalid`.
+- A server MUST preserve bytes as sent, and MUST refuse an oversized file with `file_too_large`
+ (`detail.max_bytes` states the limit) rather than truncating it.
+- Writing the source changes nothing a session sees until the next build ([§4](#4-builds-and-versions)).
+
+### 3.1 Import
+
+A project arrives as one thing. `POST /v1/environments/{id}/import` takes either an archive (a zip
+or a tar, as the request body with any content type but `application/json`) or a JSON body naming
+a git repository:
+
+```json
+{ "git": { "url": "https://github.com/example/content-studio", "ref": "main" }, "replace": true }
+```
+
+The tree is kept as it is in the archive or repository. A single directory wrapping everything (the
+shape of a repository archive) is stripped, so the project's root is the environment's root.
+Members that must not land, links and paths that escape the root, are dropped and counted in
+`skipped`, never written. `replace` clears the source first; without it the import lands over what
+is there. Dependency directories in an archive (`node_modules`, `.venv`) are not copied into a
+build; the build installs from the manifests ([§4](#4-builds-and-versions)).
+
+## 4. Builds and versions
+
+```http
+POST /v1/environments/{id}/build start a build: the next version
+GET /v1/environments/{id}/builds/{version} its record: status, log, packages, size
+GET /v1/environments/{id}/versions every build, and which one is active
+POST /v1/environments/{id}/versions/{version}/activate make a finished build the active one
+```
+
+A build snapshots the source into a new version and installs what the project declares:
+
+| Manifest at the root | What the build runs |
+|---|---|
+| `requirements.txt` | a Python virtual environment at `.venv`, then `pip install -r requirements.txt` |
+| `pyproject.toml` | the same virtual environment, then `pip install .` |
+| `package.json` | `npm ci` when a lockfile is present, else `npm install`, into `node_modules` |
+| `setup.sh` | run last, in the version's directory, for what the manifests cannot say |
+
+A server MAY support other manifests and MUST document which it runs. Installs happen in the
+server's own toolchain, the one sessions run in, so what the build installed runs where the
+session runs. Nothing else is written into the version after the build: the layer is made
+read-only and stays so.
+
+`POST …/build` returns at once with the version number; the record at `…/builds/{version}` says
+`building`, then `ready` or `failed`, with the installers' own output as `log` and the failure's
+reason as `error`. One build runs at a time per environment (`environment_busy`). When a build
+succeeds it becomes the active version: the next session to start reads it. A session that started
+earlier keeps the version it started with for the rest of its turn; a server SHOULD let it keep
+that version for later turns too, and MUST say which version a turn read ([§6](#6-what-a-session-sees)).
+
+A failed build changes nothing: the previous active version stays active, and `status` says
+`failed` only when no version is active at all. Rolling back is `POST …/versions/{n}/activate` on
+an earlier finished build; nothing is rebuilt, and a version that never finished cannot be
+activated (`environment_not_ready`).
+
+> **Why versions rather than a rebuild in place?**
+> A rebuild in place would change a layer that sessions are reading at that moment, and a
+> failed one would leave them nothing. Versions make a build atomic from the session's side:
+> the old layer is whole until the new one is, and the switch is one pointer.
+
+## 5. Attaching an environment
+
+A harness names the environment its tasks read, and a task may name a different one:
+
+```json
+{ "name": "Teaser cutter", "base": "codex", "environment": "henv_2f1c9d4e8a7b4c3d9e6f5a4b3c2d1e0f" }
+```
+
+```json
+{ "input": "Render the teaser for episode 12.", "metadata": { "harness_id": "chrn_…" },
+ "environment": "henv_2f1c9d4e8a7b4c3d9e6f5a4b3c2d1e0f" }
+```
+
+- `environment` on a harness ([Harnesses §2](harnesses.md#2-the-harness-object)) is the default
+ for every task of that harness; the task's own field overrides it for that task.
+- A server MUST refuse a harness write that names an environment outside the caller's scope, or
+ none at all, with `environment_not_found`.
+- A server MUST refuse a task whose environment is not `ready` **before the task starts**:
+ `environment_not_found` for one that is not there, `environment_not_ready` for one with nothing
+ built. A task that fails minutes later for want of its project is the outcome this rule exists
+ to prevent.
+- `GET /v1/environments/{id}/harnesses` lists the harnesses that name it, so an owner sees what a
+ rebuild will reach.
+
+## 6. What a session sees
+
+For a task that runs with an environment, a server MUST:
+
+1. mount the active version at `mount`, read-only, before the agent starts;
+2. keep the session's working directory as it was: writable, private to the session, the source of
+ its artifacts ([Files §2](files.md#2-getting-artifacts-out)), and unchanged in how it is
+ checkpointed. The environment is never part of a checkpoint;
+3. make the environment's installed dependencies the ones the agent's shell runs: on the reference
+ server `PATH` begins with the version's `.venv/bin` and `node_modules/.bin`, `PYTHONPATH` and
+ `NODE_PATH` begin with the environment, `PROJECT_ROOT` names `mount`;
+4. tell the agent, in its instructions, where the project is, that it is read-only and shared, that
+ its dependencies are installed, where to write, and the `entry` when the owner gave one;
+5. record which environment and version the turn read: the session object carries
+ `environment` ([Sessions §3](sessions.md#3-inspecting-a-session)), and the turn's record the
+ version.
+
+Two sessions on one environment MUST NOT be able to read each other's working directory or write
+the environment. How a server enforces that is its own business: a per-session container with a
+read-only mount, a per-session user without write permission on a shared directory, or a copy
+made read-only. What a client may rely on is the outcome.
+
+## 7. Discovery
+
+```json
+{ "capabilities": { "environments": true } }
+```
+
+A server that reports `environments: true` implements every endpoint in this chapter. One that
+does not implement the chapter reports `false` or omits it, and MUST answer the endpoints with
+`404`, never with a partial implementation.
+
+## 8. Errors
+
+| Code | Status | When |
+|---|---|---|
+| `environment_not_found` | 404 | No such environment in the caller's scope; on a harness write or a task, the referenced one |
+| `environment_not_ready` | 409 | A task on an environment with no active version; activating a version that never finished |
+| `environment_busy` | 409 | A build is running: a second build, or a delete |
+| `environment_exists` | 409 | The name's slug is another environment's mount |
+| `environment_invalid` | 422 | A name that is no path segment; a file path that escapes the root; an import that is neither archive nor repository |
+| `environment_unavailable` | 502 or 503 | The server's build or storage backend did not answer |
+| `file_too_large` | 413 | A file or an import over the server's limit ([Files §1](files.md#1-sending-files-in)) |
+
+## 9. Security
+
+- The build runs the project's own manifests and `setup.sh` with the server's toolchain and network.
+ A server MUST run it with no more privilege than a task gets, and MUST NOT let it read another
+ environment or any session. On a single-tenant self-hosted server the owner is the only author;
+ a multi-tenant server treats a build as a task of the tenant that owns the environment.
+- Read-only is enforced, not described ([§6](#6-what-a-session-sees)). An agent told not to write
+ will still try; the write must fail.
+- A file path is confined to the environment's root at every endpoint ([§3](#3-files)), and an
+ imported archive's members are confined the same way: links out of the root and absolute paths
+ are dropped, never followed.
+- Environments are scoped with the harnesses that use them; a harness cannot name an environment
+ of another scope ([§5](#5-attaching-an-environment)).
diff --git a/protocol/versions/2026-09-28/errors.md b/protocol/versions/2026-09-28/errors.md
new file mode 100644
index 00000000..45f2baaa
--- /dev/null
+++ b/protocol/versions/2026-09-28/errors.md
@@ -0,0 +1,135 @@
+# Errors
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+A client's error handling is only as good as the server's error reporting. This chapter defines one
+envelope, a closed set of codes, and which failures are worth retrying.
+
+## 1. The error envelope
+
+Every non-2xx response MUST have this body:
+
+```json
+{
+ "error": {
+ "type": "invalid_request_error",
+ "code": "harness_not_found",
+ "message": "No harness with id 'chrn_deadbeef'.",
+ "param": "metadata.harness_id",
+ "detail": null
+ }
+}
+```
+
+| Field | Type | Required | Meaning |
+|---|---|---|---|
+| `type` | string | yes | Broad class; see §2 |
+| `code` | string | yes | Specific, machine-readable reason; see §3 |
+| `message` | string | yes | Human-readable, one sentence, no stack trace |
+| `param` | string \| null | yes | Dotted path to the offending field, when there is one |
+| `detail` | object \| null | yes | Structured extra context, or `null` |
+
+Rules:
+
+- `message` MUST be safe to show a user. It MUST NOT contain credentials, internal hostnames, file
+ paths, or stack traces.
+- `code` MUST come from §3 where one applies. A server MAY define additional codes for conditions
+ this specification does not cover, and MUST namespace them with a vendor prefix (`acme_…`) so a
+ future version of this specification cannot collide with them.
+- A server MUST NOT return `200` with an error inside. The failure of a *task* is reported as a
+ response with `status: "failed"` and HTTP `200`, because the request succeeded; the failure of a
+ *request* is a non-2xx with this envelope. Those are different events and MUST NOT be conflated.
+
+> **Compatibility note.** A server MAY additionally include a top-level `detail` string alongside
+> `error`, for clients written against implementations that predate this envelope. That field is
+> deprecated, carries no information not in `error.message`, and will be removed in a future version.
+
+## 2. Error types
+
+| `type` | HTTP | Meaning |
+|---|---|---|
+| `invalid_request_error` | 400, 404, 409, 413, 422 | The request was wrong. Retrying it unchanged will fail again. |
+| `authentication_error` | 401 | The credential is missing, malformed or unknown. |
+| `permission_error` | 403 | Authenticated, but not allowed to do this. |
+| `rate_limit_error` | 429 | Too many requests, or a quota is exhausted. |
+| `harness_error` | 200 (in a failed response) | The harness ran and failed. |
+| `server_error` | 500, 502, 503, 504 | The server failed. Retrying MAY succeed. |
+
+## 3. Error codes
+
+### 3.1 Request and routing
+
+| Code | HTTP | Meaning |
+|---|---|---|
+| `unsupported_protocol_version` | 400 | `UHP-Version` names a version this server cannot serve. `detail.supported` lists what it can. |
+| `invalid_input` | 400 | The body could not be parsed, or a field has the wrong type. |
+| `harness_not_found` | 404 | No such harness in the caller's scope. |
+| `response_not_found` | 404 | No such response in the caller's scope. |
+| `session_not_found` | 404 | No such session in the caller's scope. |
+| `plugin_not_found` | 404 | The harness has no plugin of that name. |
+| `file_not_found` | 404 | No such file in the caller's scope. |
+| `session_expired` | 404 | The session existed but is past its retention. |
+| `harness_mismatch` | 409 | The task named a different harness than the session it continues. |
+| `session_busy` | 409 | A task is already running in this session. |
+| `plugin_conflict` | 409 | Two plugins share a name, or a component name collides across the harness and its plugins. `detail.component`, `detail.name` and `detail.between` say which. |
+| `file_too_large` | 413 | The upload exceeds the server's limit. `detail.max_bytes` states it. |
+| `model_unavailable` | 422 | The requested model cannot be served for this harness. |
+| `unsupported_base` | 422 | The requested harness base is not supported by this server. |
+| `environment_not_found` | 404 | No such environment in the caller's scope, on a read, a harness write or a task ([Environments §8](environments.md#8-errors)). |
+| `environment_not_ready` | 409 | A task on an environment with no active version, or activating an unfinished build. |
+| `environment_busy` | 409 | A build is running: a second build or a delete must wait. |
+| `environment_exists` | 409 | The name's slug is already another environment's mount path. |
+| `environment_invalid` | 422 | A name that is no path segment, a file path that escapes the root, or an import that is neither archive nor repository. |
+| `environment_unavailable` | 502 | The server's build or storage backend did not answer. |
+| `plugin_invalid` | 422 | The package is not a valid Agent Plugins package: no manifest, a fatal manifest error, a path that escapes the root, or a `name` that contradicts the manifest. `detail.path` and `detail.reason` say where. |
+| `unsupported_plugin_schema` | 422 | The manifest's `$schema` names an Agent Plugins version this server does not install. `detail.supported` lists what it does. |
+| `unsupported_transport` | 422 | A plugin declares an MCP server whose transport cannot be run for this harness base. `detail.transport` and `detail.base` say which. |
+
+### 3.2 Authentication and limits
+
+| Code | HTTP | Meaning |
+|---|---|---|
+| `missing_credential` | 401 | No bearer token. |
+| `invalid_credential` | 401 | The token is malformed, unknown, or revoked. |
+| `insufficient_scope` | 403 | The credential cannot perform this operation. |
+| `rate_limited` | 429 | Slow down. `Retry-After` SHOULD be set. |
+| `quota_exhausted` | 429 | A budget is spent; retrying now will not help. |
+
+### 3.3 Execution
+
+| Code | Where | Meaning |
+|---|---|---|
+| `harness_error` | failed response | The harness ran and could not complete the work. |
+| `harness_unavailable` | 503 | No capacity to run this harness right now. |
+| `provider_error` | failed response | The upstream model provider refused or failed. |
+| `timeout` | failed response | The task exceeded its wall-clock budget. |
+| `cancelled` | cancelled response | The client cancelled it. |
+| `preview_unavailable` | 501 | This server does not render previews. |
+| `preview_failed` | 502 | Conversion of this file failed. |
+
+## 4. Retrying
+
+| Situation | Retry? |
+|---|---|
+| `server_error` (500, 502, 503, 504) | Yes, with exponential backoff and jitter |
+| `rate_limited` | Yes, after `Retry-After` |
+| `quota_exhausted` | No — nothing will change until the quota does |
+| `session_busy` | Yes, once the in-flight task is terminal |
+| Any `invalid_request_error` | No — fix the request |
+| `authentication_error` | No — fix the credential |
+| A task that reached `failed` | Only with the client's own judgment; it consumed real resources |
+
+**Retries of `POST /v1/responses` MUST carry an `Idempotency-Key`.** Without one, a retry after a
+timeout runs the task a second time — and the first may still be running, editing the same files.
+This is the single most damaging mistake a UHP client can make; see [Tasks §6](tasks.md).
+
+## 5. Timeouts
+
+A client SHOULD set generous timeouts. Agent tasks routinely run for minutes; a 30-second HTTP
+timeout will cancel healthy work.
+
+- Streaming: no total timeout. Use an inactivity timeout instead — a server SHOULD emit a comment
+ line (`: keep-alive`) at least every 30 seconds so the client can distinguish a working agent from
+ a dead connection.
+- Non-streaming: at least the task's `timeout_seconds`, plus margin.
+- A client that gives up MUST NOT assume the task stopped. It has not. Cancel it explicitly.
diff --git a/protocol/versions/2026-09-28/files.md b/protocol/versions/2026-09-28/files.md
new file mode 100644
index 00000000..f7a309f1
--- /dev/null
+++ b/protocol/versions/2026-09-28/files.md
@@ -0,0 +1,137 @@
+# Files
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+An agent that can only return text is a chatbot. A harness edits files, writes reports, produces
+diagrams. This chapter defines getting files in and artifacts out.
+
+Conformance class **Extended**.
+
+## 1. Sending files in
+
+### 1.1 Inline
+
+For small files, inline the bytes as a data URL:
+
+```json
+{
+ "input": [
+ { "role": "user", "content": [
+ { "type": "input_text", "text": "Summarise this." },
+ { "type": "input_file", "filename": "q3.pdf",
+ "file_data": "data:application/pdf;base64,JVBERi0xLjQK…" }
+ ]}
+ ]
+}
+```
+
+### 1.2 By upload
+
+For anything larger, upload once and reference by id:
+
+```http
+POST /v1/files
+Content-Type: multipart/form-data
+```
+
+```json
+{ "id": "file_abc123", "object": "file", "filename": "q3.pdf", "bytes": 184320, "created_at": 1786400000 }
+```
+
+```json
+{ "type": "input_file", "file_id": "file_abc123" }
+```
+
+A server MUST accept both forms. Inline avoids a round trip for a 4 KB file; upload avoids
+base64-inflating a 40 MB one through every retry. A server MUST document its size limit and MUST
+reject an oversized upload with `413` and `code: "file_too_large"` rather than truncating — a
+silently truncated input produces a confident, wrong answer.
+
+## 2. Getting artifacts out
+
+Files an agent produces become artifacts of the session's container. They are reported in two
+places.
+
+### 2.1 On the response
+
+Artifacts appear as annotations on the assistant message:
+
+```json
+{
+ "type": "message",
+ "content": [
+ { "type": "output_text", "text": "I've written the report.",
+ "annotations": [
+ { "type": "container_file_citation",
+ "container_id": "cntr_…",
+ "file_id": "file_…",
+ "filename": "report.md",
+ "download_url": "https://server/v1/containers/cntr_…/files/file_…/content",
+ "start_index": 0, "end_index": 24 }
+ ]
+ }
+ ]
+}
+```
+
+A client that renders only text still shows a correct answer; a client that reads annotations can
+offer the file. That is the intended layering — artifacts are additive to the message, never a
+replacement for it.
+
+### 2.2 By listing the session
+
+```http
+GET /v1/sessions/{session_id}/files
+```
+
+```json
+{ "files": [ { "id": "file_…", "container_id": "cntr_…", "filename": "report.md",
+ "bytes": 2048, "created_at": 1786400240 } ] }
+```
+
+A server MUST list every artifact of the session, including files from earlier tasks. Restricting the
+list to the most recent task would make a multi-step session's earlier outputs unreachable.
+
+## 3. Downloading
+
+```http
+GET /v1/containers/{container_id}/files/{file_id}/content
+```
+
+Returns the raw bytes with the file's own `Content-Type`. A server MUST NOT wrap the bytes in JSON.
+
+A server SHOULD send `Content-Disposition` with the original filename, and MUST set
+`X-Content-Type-Options: nosniff`. Artifacts are attacker-influenced content — an agent can be
+persuaded to write a file — so serving them without those headers turns an artifact into stored
+XSS against the client's own origin.
+
+### 3.1 Preview rendering
+
+A server MAY offer a rendered preview of a document format:
+
+```http
+GET /v1/containers/{container_id}/files/{file_id}/pdf
+```
+
+If a server does not implement conversion it MUST return `501` with
+`code: "preview_unavailable"`, not a broken or empty PDF. If conversion fails it MUST return `502`
+with `code: "preview_failed"`. A client can then tell "this server never previews" from "this file
+would not convert", and only the second is worth retrying.
+
+## 4. Bulk download
+
+```http
+GET /v1/sessions/{session_id}/files/archive
+```
+
+Returns every artifact of the session as a single archive. A server SHOULD implement this: a session
+that produced forty files should not require forty requests.
+
+## 5. Retention and scope
+
+- Artifacts live with their session. Deleting a session MUST make its artifacts unreachable.
+- A server MUST scope file access to the owning principal. A `file_id` from another principal MUST
+ return `404`, never the bytes.
+- A server MUST NOT let a `container_id` / `file_id` pair traverse outside its container. Path
+ traversal through artifact ids is the most likely serious vulnerability in a UHP implementation,
+ and the conformance suite probes for it.
diff --git a/protocol/versions/2026-09-28/harnesses.md b/protocol/versions/2026-09-28/harnesses.md
new file mode 100644
index 00000000..60a8c4c3
--- /dev/null
+++ b/protocol/versions/2026-09-28/harnesses.md
@@ -0,0 +1,272 @@
+# Harnesses
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+Before a client can send work it needs to know what can run it, and with which models. This chapter
+defines discovery, the harness object, and — at conformance class **Full** — how harnesses are
+created and changed.
+
+## 1. Discovering harnesses
+
+```http
+GET /v1/harnesses
+```
+
+```json
+{
+ "harnesses": [
+ {
+ "id": "chrn_08dae611630d467ab3e67ed792570ae5",
+ "object": "harness",
+ "name": "Research agent",
+ "base": "claude-code",
+ "baseLabel": "Claude Code",
+ "defaultModel": "claude-sonnet-4.6",
+ "systemPrompt": "",
+ "mcpServers": [],
+ "skills": [],
+ "plugins": [],
+ "disabledTools": [],
+ "maxStep": null,
+ "timeoutSeconds": null,
+ "createdAt": 1786403298205
+ }
+ ]
+}
+```
+
+A server MUST return only harnesses within the caller's scope. The list MAY be empty — a server with
+no configured harnesses is valid, and a client MUST handle that rather than assuming index `0`
+exists.
+
+```http
+GET /v1/harnesses/{harness_id}
+```
+
+Returns one harness object, or `404` with `code: "harness_not_found"`.
+
+## 2. The harness object
+
+| Field | Type | Required | Meaning |
+|---|---|---|---|
+| `id` | string | yes | `chrn_`-prefixed |
+| `object` | string | yes | Always `harness` |
+| `name` | string | yes | Human-readable label; not an identifier |
+| `base` | string | yes | Which harness runtime: `codex`, `claude-code`, `hermes`, … |
+| `baseLabel` | string | no | Display name for `base` |
+| `defaultModel` | string | no | Model used when a task omits `model` |
+| `systemPrompt` | string | no | Additional standing instructions |
+| `mcpServers` | array | no | MCP servers attached to this harness |
+| `skills` | array | no | Skills available to this harness |
+| `plugins` | array | no | Installed plugins, each a package of tools and skills; see [Plugins](plugins.md) |
+| `environment` | string | no | The environment this harness's tasks read, mounted read-only; requires the `environments` capability. See [Environments](environments.md) |
+| `disabledTools` | string[] | no | Tools withheld from the agent |
+| `maxStep` | integer \| null | no | Default step budget |
+| `timeoutSeconds` | integer \| null | no | Default wall-clock budget |
+| `createdAt` | integer | yes | Unix milliseconds |
+
+`base` values are not enumerated by this specification. A server MAY support bases this document has
+never heard of, and a client MUST treat `base` as an opaque string — anything else means the
+protocol has to be revised every time a harness is released, which is exactly the coupling UHP
+exists to remove.
+
+## 3. Models
+
+```http
+GET /v1/models
+```
+
+```json
+{
+ "backends": {
+ "claude": {
+ "default": "claude-sonnet-4.6",
+ "models": [
+ { "id": "claude-sonnet-4.6", "label": "claude-sonnet-4.6", "backend": "claude",
+ "available": true, "default": true }
+ ]
+ }
+ }
+}
+```
+
+```http
+GET /v1/harnesses/{harness_id}/models
+```
+
+```json
+{
+ "harness_id": "chrn_…",
+ "backend": "claude",
+ "default": "claude-sonnet-4.6",
+ "fallback": "claude-sonnet-4.6",
+ "models": [ { "id": "claude-opus-5", "available": true, "default": false } ]
+}
+```
+
+### 3.1 `available` is a promise
+
+`available: true` means the server can serve that model for that harness **right now** — a
+credential exists and the provider can reach it. `available: false` means a request for it will not
+run as asked.
+
+A server MUST compute `available`, not assert it. Listing a model as available and then failing the
+task is the worst outcome for a client: it presents a choice to a user, the user picks it, and the
+work fails after they have committed to it.
+
+A client SHOULD present unavailable models as disabled rather than hiding them, so a user can see
+that a model exists and is not configured, rather than wondering why it is missing.
+
+## 4. Tools and skills
+
+A configured harness carries three things that decide what its agent can do. All three are part of
+the harness object and are set the same way it is.
+
+### 4.1 MCP servers
+
+```json
+{ "mcpServers": [
+ { "name": "vault", "url": "https://mcp.example.com/mcp", "transport": "http", "enabled": true }
+] }
+```
+
+| Field | Required | Meaning |
+|---|---|---|
+| `name` | yes | Identifies the server to the agent; sanitised to a CLI-safe identifier |
+| `url` | yes | Endpoint |
+| `transport` | no | `http` (Streamable HTTP, default) or `sse` |
+| `enabled` | no | Absent or `true` means enabled |
+| `headers` | no | Extra request headers |
+| `auth` | no | Bearer token, or a server-side reference the server resolves |
+
+This list carries remote servers only, exactly as it did in the previous version. An MCP server that
+runs as a process (`stdio`) is declared inside a plugin, which is what gives it a root to run from
+and a directory to keep state in ([Plugins §2.2](plugins.md#22-what-the-server-derives)).
+
+A server MUST connect only the **enabled** entries for a turn. A disabled entry MUST NOT be
+contacted at all — not connected and then hidden, which would still leak the turn's existence to
+whoever operates that endpoint.
+
+An MCP server that cannot be reached MUST NOT fail the task. The turn MUST proceed without those
+tools, because a third-party endpoint being down is not a reason to lose the user's work. A server
+SHOULD make the degradation visible in the run rather than silent.
+
+> A server MUST NOT advertise MCP support it cannot deliver. If the harness runtime behind it cannot
+> speak the configured transport, that is a broken installation, and reporting it only in a log file
+> inside the workspace is indistinguishable — to the user — from the model refusing to use the tool.
+
+### 4.2 Skills
+
+A skill is a **folder**, not a file:
+
+```json
+{ "skills": [
+ { "name": "vault-manual", "enabled": true, "files": [
+ { "path": "SKILL.md", "content": "---\nname: vault-manual\n---\n…" },
+ { "path": "references/codes.md", "content": "…" },
+ { "path": "scripts/helper.sh", "content": "#!/bin/sh\n…" },
+ { "path": "assets/logo.png", "content_b64": "iVBORw0KGgo…" }
+ ]}
+] }
+```
+
+- `files[].path` is relative to the skill's own folder and MUST support nested directories. A server
+ MUST reject a path that escapes the folder.
+- Text is carried in `content`; binary in `content_b64`. A server MUST preserve both byte-for-byte.
+- A bundle MUST contain a `SKILL.md`; a server MUST reject one that does not, at configuration time
+ rather than at run time.
+- A server MUST materialise the **whole folder** where the agent can read it. Materialising only
+ `SKILL.md` breaks every skill that carries references, scripts or data — which is most non-trivial
+ skills.
+- `enabled: false` suppresses a skill, including one inherited from the base.
+
+A server MAY store large bundles out of line, and MUST return the complete file list from:
+
+```http
+GET /v1/harnesses/{harness_id}/skills/{skill_id}/files
+```
+
+Round-tripping a harness through `GET` and `PUT` MUST NOT lose skill contents. This is the failure
+worth designing against: an unrelated edit — renaming the harness — silently emptying a skill folder
+that the user cannot tell is gone until an agent behaves oddly weeks later.
+
+### 4.3 Disabled tools
+
+```json
+{ "disabledTools": ["WebSearch"] }
+```
+
+Names come from the harness base's own tool catalogue. Enforcement differs by runtime and a server
+MUST NOT overstate it:
+
+- Where the runtime supports per-tool restriction, the server MUST enforce it as a hard block.
+- Where it does not, the server MUST still convey the restriction to the agent — as a standing
+ instruction — and MUST NOT silently drop it. Dropping it is the worst outcome: the operator
+ believes a tool is off, and it is not.
+
+A client that requires a guaranteed block SHOULD confirm the harness base supports one rather than
+assuming `disabledTools` is always hard.
+
+### 4.4 Plugins
+
+```json
+{ "plugins": [ { "name": "contract-review", "enabled": true, "blob": "plg_…" } ] }
+```
+
+A plugin is an [Agent Plugins](https://agent-plugins.org/specification) package: `plugin.json`,
+`mcp.json` and `skills/`, carried as one folder and installed whole. Its servers and skills join the
+harness's own for every turn; the harness's own `mcpServers` and `skills` report only what was
+written to them and never absorb a plugin's. The object, the composition rule, the export of a
+harness as a package, and what a hosted server owes a running plugin are in the
+[Plugins chapter](plugins.md). The capability is `plugins`; a server without it is conformant at
+every class.
+
+## 5. Managing harnesses
+
+Conformance class **Full** only. A client MUST check the `harness_management` capability first.
+
+### 5.1 Create
+
+```http
+POST /v1/harnesses
+```
+
+```json
+{ "name": "Research agent", "base": "claude-code", "default_model": "claude-sonnet-4.6" }
+```
+
+Returns the created harness object. `base` is REQUIRED and MUST be one the server supports;
+otherwise `422` with `code: "unsupported_base"`.
+
+### 5.2 Update
+
+```http
+PUT /v1/harnesses/{harness_id}
+```
+
+Replaces the mutable configuration. A server MUST NOT change `id`, `base`, or `createdAt`. Changing
+the base of an existing harness would silently change the behaviour of every session already
+attached to it; a client that wants a different base MUST create a different harness.
+
+### 5.3 Delete
+
+```http
+DELETE /v1/harnesses/{harness_id}
+```
+
+A server MUST NOT delete the sessions or responses that used the harness. History that disappears
+when configuration changes cannot be audited.
+
+## 6. Choosing a harness
+
+Non-normative, but the question every client faces:
+
+| If the task is… | Consider |
+|---|---|
+| Code editing in a repository | A coding-specialised base (`codex`, `claude-code`) |
+| Long-horizon multi-tool work | A base with an explicit step budget and strong tool use |
+| Cheap, high-volume classification | The smallest model on any base |
+
+The point of UHP is that this choice stays reversible. A product that speaks UHP can change base or
+model with a configuration edit, and can A/B two harnesses against the same input without a second
+integration.
diff --git a/protocol/versions/2026-09-28/index.md b/protocol/versions/2026-09-28/index.md
new file mode 100644
index 00000000..80014748
--- /dev/null
+++ b/protocol/versions/2026-09-28/index.md
@@ -0,0 +1,103 @@
+# Unified Harness Protocol — specification `2026-09-28`
+
+An open standard for running complete agent harnesses as shared infrastructure.
+
+This is the normative specification. For an introduction to what UHP is and why it exists, start at
+the [protocol README](../../README.md).
+
+## Chapters
+
+| # | Chapter | Defines |
+|---|---|---|
+| 1 | [Architecture](architecture.md) | Roles, conformance classes, object model, transport, authentication, design principles |
+| 2 | [Lifecycle](lifecycle.md) | Version negotiation, capability discovery, task and session states, concurrency |
+| 3 | [Harnesses](harnesses.md) | Discovering, selecting, configuring and managing harnesses; models and availability |
+| 4 | [Plugins](plugins.md) | Packages of tools and skills, in the Agent Plugins format, installed into a harness; composition; export |
+| 5 | [Environments](environments.md) | A project's files and installed dependencies, built once, read-only in every session that names it; builds, versions, attachment |
+| 6 | [Tasks](tasks.md) | Running work, the response object, model substitution, idempotency |
+| 7 | [Streaming](streaming.md) | The event vocabulary, ordering guarantees, reconnection |
+| 8 | [Sessions](sessions.md) | Continuing, inspecting, cancelling, sharing, deleting |
+| 9 | [Files](files.md) | File input, artifacts, download, retention and scope |
+| 10 | [Errors](errors.md) | The error envelope, codes, retry rules, timeouts |
+| 11 | [Security](security.md) | Credentials, object scope, artifacts, injection, exhaustion, plugins, environments, error hygiene |
+| 12 | [Schema](schema.md) | Machine-readable definitions and how to generate from them |
+
+## Endpoint summary
+
+| Method | Path | Class | Chapter |
+|---|---|---|---|
+| `GET` | `/v1/uhp` | Core | [Lifecycle](lifecycle.md) |
+| `GET` | `/v1/harnesses` | Core | [Harnesses](harnesses.md) |
+| `GET` | `/v1/harnesses/{id}` | Core | [Harnesses](harnesses.md) |
+| `GET` | `/v1/models` | Core | [Harnesses](harnesses.md) |
+| `GET` | `/v1/harnesses/{id}/models` | Core | [Harnesses](harnesses.md) |
+| `POST` | `/v1/responses` | Core | [Tasks](tasks.md) |
+| `GET` | `/v1/responses/{id}` | Core | [Tasks](tasks.md) |
+| `GET` | `/v1/responses/{id}/input_items` | Core | [Tasks](tasks.md) |
+| `POST` | `/v1/responses/{id}/cancel` | Core | [Sessions](sessions.md) |
+| `DELETE` | `/v1/responses/{id}` | Core | [Tasks](tasks.md) |
+| `POST` | `/v1/sessions/{id}/cancel` | Core | [Sessions](sessions.md) |
+| `GET` | `/v1/sessions` | Extended | [Sessions](sessions.md) |
+| `GET` | `/v1/sessions/{id}` | Extended | [Sessions](sessions.md) |
+| `GET` | `/v1/sessions/{id}/turns` | Extended | [Sessions](sessions.md) |
+| `POST` | `/v1/files` | Extended | [Files](files.md) |
+| `GET` | `/v1/sessions/{id}/files` | Extended | [Files](files.md) |
+| `GET` | `/v1/sessions/{id}/files/archive` | Extended | [Files](files.md) |
+| `GET` | `/v1/containers/{cid}/files/{fid}/content` | Extended | [Files](files.md) |
+| `GET` | `/v1/containers/{cid}/files/{fid}/pdf` | Extended | [Files](files.md) |
+| `POST` | `/v1/harnesses` | Full | [Harnesses](harnesses.md) |
+| `PUT` | `/v1/harnesses/{id}` | Full | [Harnesses](harnesses.md) |
+| `DELETE` | `/v1/harnesses/{id}` | Full | [Harnesses](harnesses.md) |
+| `GET` | `/v1/harnesses/{id}/skills/{name}/files` | Full | [Harnesses](harnesses.md) |
+| `GET` | `/v1/harnesses/{id}/plugins/{name}/files` | Full, `plugins` | [Plugins](plugins.md) |
+| `GET` | `/v1/harnesses/{id}/plugin` | Full, `plugins` | [Plugins](plugins.md) |
+| `POST` | `/v1/sessions/{id}/share` | Full | [Sessions](sessions.md) |
+| `GET` | `/v1/sessions/{id}/share` | Full | [Sessions](sessions.md) |
+| `DELETE` | `/v1/sessions/{id}` | Full | [Sessions](sessions.md) |
+| `DELETE` | `/v1/traces/{id}` | Full | [Sessions](sessions.md) (older path, same operation) |
+| `GET` | `/v1/environments` | Full, capability `environments` | [Environments](environments.md) |
+| `POST` | `/v1/environments` | Full, capability `environments` | [Environments](environments.md) |
+| `GET` `PUT` `DELETE` | `/v1/environments/{id}` | Full, capability `environments` | [Environments](environments.md) |
+| `GET` | `/v1/environments/{id}/files` | Full, capability `environments` | [Environments](environments.md) |
+| `GET` `PUT` `DELETE` | `/v1/environments/{id}/files/{path}` | Full, capability `environments` | [Environments](environments.md) |
+| `POST` | `/v1/environments/{id}/directories` | Full, capability `environments` | [Environments](environments.md) |
+| `POST` | `/v1/environments/{id}/import` | Full, capability `environments` | [Environments](environments.md) |
+| `POST` | `/v1/environments/{id}/build` | Full, capability `environments` | [Environments](environments.md) |
+| `GET` | `/v1/environments/{id}/builds/{version}` | Full, capability `environments` | [Environments](environments.md) |
+| `GET` | `/v1/environments/{id}/versions` | Full, capability `environments` | [Environments](environments.md) |
+| `POST` | `/v1/environments/{id}/versions/{version}/activate` | Full, capability `environments` | [Environments](environments.md) |
+| `GET` | `/v1/environments/{id}/harnesses` | Full, capability `environments` | [Environments](environments.md) |
+
+The `plugins` column entries are served only by a server whose discovery document reports the
+`plugins` capability; the capability is optional at every class.
+
+## What changed in this version
+
+This version is additive to `2026-08-11`: every request and object that was valid then is valid
+now, and a client written against the previous version keeps working against a server that serves
+this one. It adds the [Plugins](plugins.md) chapter, with `stdio` MCP servers inside plugins, the
+`plugins` capability, and five error codes. A server may serve both versions from one code path. The [changelog](../../CHANGELOG.md) has the full list.
+
+## Conformance
+
+A server is conformant at a class when it passes the [conformance suite](../../conformance/) at that
+class. Nothing else is a conformance claim — not a self-assessment, not an implementation of the
+endpoints, not passing "most" tests.
+
+```bash
+pip install -e protocol/conformance
+uhp-conformance --base-url https://your-server --api-key "$KEY" --class extended
+```
+
+The suite is part of this specification. If the suite and this prose disagree, that is a bug in one
+of them and MUST be resolved by changing whichever is wrong — never by leaving them inconsistent.
+
+## Conventions
+
+- MUST / SHOULD / MAY are used as defined in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and
+ [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174).
+- JSON examples are illustrative; the [schema](../../schema/) is authoritative for structure.
+- Field names are `snake_case` on the task surface (inherited from the Responses-compatible shape)
+ and `camelCase` on the harness object. This inconsistency is real, is called out here rather than
+ hidden, and is retained because changing either would break existing clients for cosmetic gain.
+ A future major version SHOULD unify them.
diff --git a/protocol/versions/2026-09-28/lifecycle.md b/protocol/versions/2026-09-28/lifecycle.md
new file mode 100644
index 00000000..4ce5eb4c
--- /dev/null
+++ b/protocol/versions/2026-09-28/lifecycle.md
@@ -0,0 +1,154 @@
+# Lifecycle
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+This chapter defines how a client and server agree on a protocol version, how a client learns what
+a server can do, and the states a task moves through from submission to result.
+
+## 1. Version negotiation
+
+UHP versions are dates: `YYYY-MM-DD`, the day the version was published. Dates sort, do not imply a
+compatibility promise that semantic versioning would imply and not keep, and make the age of an
+implementation obvious. See [VERSIONING.md](../../VERSIONING.md) for the compatibility rules.
+
+A client MAY declare the version it was written against:
+
+```http
+UHP-Version: 2026-09-28
+```
+
+- If the header is absent, the server MUST assume its own default version and MUST state that
+ version in the response header. A client that omits the header is asking for the server's choice,
+ and gets it.
+- If the header names a version the server supports, the server MUST honour it for that request.
+- If the header names a version the server does not support, the server MUST fail the request with
+ `400` and `code: "unsupported_protocol_version"`, and the error `detail` MUST list the versions it
+ does support. It MUST NOT silently serve a different version — a client that asked for a version
+ it can parse should not receive one it cannot.
+
+Every response, including errors, MUST carry the version actually used:
+
+```http
+UHP-Version: 2026-09-28
+```
+
+## 2. Capability discovery
+
+```http
+GET /v1/uhp
+```
+
+Unauthenticated or authenticated — a server MUST serve this endpoint without a bearer token, because
+a client needs to know whether it is talking to a UHP server *before* it can sensibly present
+credentials. The document MUST NOT contain anything principal-specific.
+
+```json
+{
+ "object": "uhp.discovery",
+ "protocol": "uhp",
+ "versions": ["2026-09-28", "2026-09-12", "2026-08-11"],
+ "default_version": "2026-09-28",
+ "conformance_class": "full",
+ "capabilities": {
+ "streaming": true,
+ "sessions": true,
+ "cancellation": true,
+ "files_input": true,
+ "files_output": true,
+ "session_listing": true,
+ "harness_management": true,
+ "session_sharing": true,
+ "idempotency": true,
+ "plugins": true,
+ "environments": true
+ },
+ "plugin_schemas": ["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"],
+ "implementation": { "name": "HarnessRouter Community Edition", "version": "0.3.0" }
+}
+```
+
+| Field | Type | Required | Meaning |
+|---|---|---|---|
+| `object` | string | yes | Always `uhp.discovery` |
+| `protocol` | string | yes | Always `uhp` — lets a client distinguish UHP from a lookalike |
+| `versions` | string[] | yes | Every version this server can serve; MUST be non-empty |
+| `default_version` | string | yes | Used when the client sends no `UHP-Version`; MUST appear in `versions` |
+| `conformance_class` | string | yes | `core`, `extended` or `full` |
+| `capabilities` | object | yes | Named booleans; see below |
+| `plugin_schemas` | string[] | when `plugins` is true | The Agent Plugins manifest schemas the server installs; see [Plugins §7](plugins.md#7-discovery) |
+| `implementation` | object | no | Free-form identification, for debugging and bug reports |
+
+A server MUST report `false` for a capability it does not implement, rather than omitting it, so
+that a client can tell "not supported" from "server is older than this field". A client MUST treat
+an absent capability key as `false`.
+
+`conformance_class` MUST be consistent with `capabilities`: a server claiming `extended` MUST report
+`files_input`, `files_output` and `session_listing` as `true`. The conformance suite checks this,
+because a class claim that contradicts the capability list tells a client two different things.
+
+## 3. Task lifecycle
+
+A task moves through these states. `status` on the response object carries the current one.
+
+```
+ ┌──────────────┐
+ POST /responses │ │
+ ────────────────▶│ in_progress │
+ │ │
+ └──────┬───────┘
+ │
+ ┌──────────────────┼──────────────────┬───────────────────┐
+ ▼ ▼ ▼ ▼
+ ┌──────────┐ ┌──────────┐ ┌────────────┐ ┌───────────┐
+ │completed │ │ failed │ │ incomplete │ │ cancelled │
+ └──────────┘ └──────────┘ └────────────┘ └───────────┘
+```
+
+| Status | Meaning | Terminal |
+|---|---|---|
+| `in_progress` | Accepted and running | no |
+| `completed` | The harness finished the work and produced a result | yes |
+| `failed` | The task could not be completed; `error` explains why | yes |
+| `incomplete` | The harness stopped at a budget — step limit or time limit — with partial output | yes |
+| `cancelled` | The client cancelled it; partial output MAY be present | yes |
+
+Rules:
+
+- A server MUST NOT transition out of a terminal state. Once a client has seen `completed`, later
+ reads of that response MUST return `completed`.
+- `incomplete` MUST be used when a budget stopped the work, and MUST NOT be used for errors. The
+ distinction matters to a client: `incomplete` is usually worth continuing, `failed` usually is not.
+- A `cancelled` task MUST report `cancelled`, not `failed`. A client that asked for a stop did not
+ experience an error.
+- Terminal responses MUST retain whatever output was produced before they became terminal. Discarding
+ partial work because a task later failed destroys the only evidence of what went wrong.
+
+## 4. Session lifecycle
+
+```
+first task ──▶ session created implicitly ──▶ session active ──▶ deleted (client) or expired (server policy)
+ ▲ │
+ └────┘
+ each continued task extends it
+```
+
+- A session is created by the server when the first task of a chain runs. Its id MUST be reported in
+ the response's `metadata.session_id`.
+- A session MUST preserve, across tasks in the chain: conversational context, the working directory
+ and its files, and the configured harness.
+- A session MUST NOT be extended by a task that names a different configured harness. A server MUST
+ fail such a request with `409` and `code: "harness_mismatch"` rather than silently starting a new
+ session — continuing a conversation with a different agent is a different conversation, and doing
+ it quietly loses work the client believed it had.
+- Session expiry is server policy. A server that expires sessions MUST report `404` with
+ `code: "session_expired"` on continuation, distinguishable from `session_not_found`.
+
+## 5. Concurrency
+
+- A server MUST accept concurrent tasks in *different* sessions.
+- A server MUST NOT run two tasks concurrently in the *same* session: a session has one working
+ directory and one conversation, and two agents writing to both is not a defined state. A second
+ task for a busy session MUST fail with `409` and `code: "session_busy"`.
+- A client that receives `session_busy` SHOULD wait for the in-flight task to reach a terminal state
+ and retry. Servers SHOULD include `retry_after_ms` in the error `detail` when they can estimate it,
+ and MUST omit it when they cannot rather than guessing.
diff --git a/protocol/versions/2026-09-28/plugins.md b/protocol/versions/2026-09-28/plugins.md
new file mode 100644
index 00000000..18436bfa
--- /dev/null
+++ b/protocol/versions/2026-09-28/plugins.md
@@ -0,0 +1,380 @@
+# Plugins
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+A harness carries the tools and skills its agent can use ([Harnesses §4](harnesses.md#4-tools-and-skills)).
+Until this version they could only be attached one at a time, to one harness. An operator who wanted
+the same three MCP servers and two skills on a second harness, or in a different product, entered
+them again. A **plugin** is those same components carried as one named, versioned package that
+installs into any harness on any UHP server, and into any other client that reads the same package
+format.
+
+This chapter is the Harness Plugins sub-protocol. It is optional: a server advertises it with the
+`plugins` capability, and a server that does not implement it is conformant at every class.
+
+## 1. What a plugin is
+
+UHP does not define a package format. A UHP plugin **is** an
+[Agent Plugins](https://agent-plugins.org/specification) package, version 1.0.0: a folder with a
+`plugin.json` manifest at its root, MCP servers declared in `mcp.json`, and skills under `skills/`,
+each skill an [Agent Skills](https://agentskills.io/specification) folder with a `SKILL.md`.
+
+Agent Plugins wraps Agent Skills without redefining them: it says where a skill lives inside the
+package and defers the skill's own format to the Agent Skills specification. This chapter does the
+same one layer up. It says how a package travels over UHP, how it is bound to a harness, and what a
+hosted server owes it. Everything about the package's contents defers to Agent Plugins.
+
+```
+Agent Skills SKILL.md and its folder what one skill is
+Agent Plugins plugin.json + mcp.json + skills/ how skills and tools are packaged
+UHP Plugins this chapter how a package is installed into a hosted harness
+```
+
+A plugin carries three things, and the harness object already had a place for two of them:
+
+| Part | Where in the package | What it becomes in the harness |
+|---|---|---|
+| Meta | `plugin.json` | The plugin's identity: `name`, `version`, `author`, `license`, … |
+| Tools | `mcp.json` | MCP servers of the harness ([Harnesses §4.1](harnesses.md#41-mcp-servers)) |
+| Skills | `skills/<name>/SKILL.md` | Skills of the harness ([Harnesses §4.2](harnesses.md#42-skills)) |
+
+> **Why adopt a format rather than define one?**
+> A package format is worth exactly the number of places it installs. Agent Plugins is maintained
+> by a steering committee drawn from the major agent clients, so a plugin written for one of them
+> installs into a UHP harness unchanged, and a plugin exported from a UHP harness ([§5](#5-exporting-a-harness-as-a-plugin))
+> installs into them. A UHP-specific format would need converting at every boundary, and the
+> conversion is where contents get lost.
+
+## 2. The plugin object
+
+```json
+{
+ "name": "contract-review",
+ "enabled": true,
+ "manifest": {
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
+ "name": "contract-review",
+ "version": "1.2.0",
+ "description": "Clause extraction and a risk checklist for commercial agreements.",
+ "author": { "name": "Example Legal Tools" },
+ "license": "MIT"
+ },
+ "mcpServers": [
+ { "name": "clauses", "transport": "http", "url": "https://mcp.example.com/clauses", "enabled": true },
+ { "name": "redline", "transport": "stdio", "command": "./bin/redline",
+ "args": ["--data", "${PLUGIN_DATA}"], "enabled": true }
+ ],
+ "skills": [
+ { "name": "risk-checklist", "description": "Turn an agreement into a JSON risk checklist." }
+ ],
+ "skipped": [],
+ "files": [
+ { "path": "plugin.json", "content": "{ … }" },
+ { "path": "mcp.json", "content": "{ … }" },
+ { "path": "skills/risk-checklist/SKILL.md", "content": "---\nname: risk-checklist\n…" },
+ { "path": "skills/risk-checklist/references/clauses.md", "content": "…" },
+ { "path": "bin/redline", "content_b64": "f0VMRgIB…" }
+ ]
+}
+```
+
+| Field | Type | Written by | Meaning |
+|---|---|---|---|
+| `name` | string | either | The manifest's `name`; unique among the harness's plugins |
+| `enabled` | boolean | client | Absent or `true` means installed and active |
+| `files` | array | client | The package, as files relative to the plugin root |
+| `blob` | string | server | Handle for a package the server stores out of line |
+| `manifest` | object | server | `plugin.json`, parsed |
+| `mcpServers` | array | server | The servers `mcp.json` declares, as plugin MCP server objects (`PluginMcpServer`) |
+| `skills` | array | server | The skills found under `skills/`: `name` and `description` each |
+| `skipped` | array | server | Components the server found and could not load, each with the reason |
+
+The server-written fields are derived from the package on every write. A client MAY send them back
+unchanged, which is what a client does when it `PUT`s what it read, and the server MUST recompute
+them rather than store what was sent. A client MUST NOT rely on changing them: editing `mcpServers`
+on a plugin changes nothing, because the package is the source and `mcp.json` is where the servers
+are.
+
+### 2.1 Files
+
+The rules are the ones skills already follow ([Harnesses §4.2](harnesses.md#42-skills)):
+
+- `files[].path` is relative to the plugin root and MUST support nested directories. A server MUST
+ reject a path that escapes the root, or that names anything other than a regular file, with
+ `plugin_invalid`.
+- Text travels in `content`; binary in `content_b64`. A server MUST preserve both byte-for-byte.
+- The package MUST contain `plugin.json` at its root. A server MUST reject one that does not, at
+ configuration time rather than at run time.
+- A server MUST materialise the **whole package** where the agent can read it. A plugin's skills
+ carry references and scripts, and its stdio servers carry the executables they launch.
+- A server MAY store the package out of line and return `blob` in place of `files`. It MUST then
+ return the complete file list from
+ `GET /v1/harnesses/{harness_id}/plugins/{plugin_name}/files` ([§3.1](#31-reading-the-files)).
+- A server SHOULD cap package size, and MUST refuse an oversized one with `file_too_large`
+ (`detail.max_bytes` states the limit) rather than truncating it.
+
+### 2.2 What the server derives
+
+On every write the server reads the package as an Agent Plugins client would, and records what it
+found on the object.
+
+**`manifest`.** The server MUST validate `plugin.json` against the rules of Agent Plugins §5 for the
+version its `$schema` names. A `$schema` the server does not support is refused with
+`unsupported_plugin_schema`; `detail.supported` lists the identifiers it does support. An unknown
+top-level field, or a non-object `extensions`, is not fatal: the field is ignored and recorded in
+`skipped`. Any other violation is fatal, and the write is refused with `plugin_invalid`.
+
+**`mcpServers`.** From `mcp.json`, read as Agent Plugins §7.2 says. Each valid server entry becomes
+one plugin MCP server object, mapped as follows. An invalid entry is recorded in `skipped` and the
+rest still load. If `mcp.json` itself is invalid, or its `$schema` names a different Agent Plugins
+version than `plugin.json`, every server in it is skipped with that reason.
+
+| `mcp.json` `type` | UHP `transport` | Fields carried |
+|---|---|---|
+| `streamable-http` | `http` | `url`, `headers` |
+| `sse` | `sse` | `url`, `headers` |
+| `stdio` | `stdio` | `command`, `args`, `env`, `cwd` |
+
+`${PLUGIN_ROOT}` and `${PLUGIN_DATA}` are reported exactly as written. A server MUST NOT expand them
+in what it returns to a client: the expansion is a filesystem path inside the server's sandbox, which
+is not the client's business and changes from turn to turn. `enabled` on each derived server is
+always `true`; the plugin's own `enabled` is what turns them off, together.
+
+A plugin MCP server object is the harness MCP server object of
+[Harnesses §4.1](harnesses.md#41-mcp-servers) plus the `stdio` transport, with `command`, `args`,
+`env` and `cwd` in place of `url`, `headers` and `auth`. `command` is one executable token, never a
+shell string: a bare name, or a plugin-relative path beginning with `./`.
+
+> **Why is `stdio` declared only inside a plugin?**
+> A process needs somewhere to run from and somewhere to keep state, and a plugin is the object
+> that provides both: `PLUGIN_ROOT` and `PLUGIN_DATA` are defined by the package, not by the
+> harness. A stdio server on the harness's own list would need a second set of rules for a root
+> it does not have, and it could not be exported, because its executable would not travel with
+> it. So the harness's own list stays what it was in the previous version, remote servers only,
+> and a process is two files away: a `plugin.json` and an `mcp.json` make a complete plugin. That
+> keeps every object the previous version defined byte-for-byte unchanged, which is what lets a
+> server serve both versions from one code path ([§4.1](#41-the-direct-fields-are-unchanged)).
+
+**`skills`.** Each immediate child directory of `skills/` that contains a regular file named
+`SKILL.md` is one skill, per Agent Plugins §7.1. A server MUST NOT search deeper. Each skill MUST
+conform to Agent Skills, including the rule that its frontmatter `name` equals its directory name; a
+skill that does not is recorded in `skipped` and the rest still load. The derived entry carries the
+frontmatter `name` and `description`.
+
+**`skipped`.** Each entry is `{ "path": …, "reason": … }`, where `path` locates the component in
+the package (`skills/broken`, `mcp.json#/mcpServers/redline`, `plugin.json#/vendorField`) and
+`reason` is one sentence. A server MUST return `skipped` on every plugin object, empty when nothing
+was skipped, so a client can tell "nothing skipped" from "server does not report skips".
+
+> **Why is a broken component recorded rather than refused?**
+> Two rules meet here. [Harnesses §4.2](harnesses.md#42-skills) refuses a skill without a
+> `SKILL.md` at configuration time, because a bundle that is stored and then silently ignored at
+> run time is the hardest failure a user can be handed. Agent Plugins §11.3 requires the opposite
+> inside a package: a failure isolated to one component MUST NOT stop the rest from loading,
+> because a package is written by someone other than the person installing it, and one stale entry
+> should not take the whole plugin down with it. Both are right about their own case. The
+> reconciliation is the one [Tasks §1.1](tasks.md#11-request-fields) already makes for reserved
+> fields: ignoring is allowed, silent ignoring is not. The package installs, and what did not load
+> is written on the object, where the person configuring the harness can see it. The manifest is
+> the exception. Without a valid manifest there is no plugin to isolate failures within, so a fatal
+> manifest error refuses the write.
+
+## 3. Installing a plugin
+
+Plugins are part of the harness object and are set the way its other configuration is set
+([Harnesses §5](harnesses.md#5-managing-harnesses)): conformance class **Full**, and the `plugins`
+capability MUST be `true`.
+
+```http
+POST /v1/harnesses
+```
+
+```json
+{
+ "name": "Contract Review Agent",
+ "base": "claude-code",
+ "plugins": [
+ { "files": [
+ { "path": "plugin.json", "content": "{\"$schema\":\"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json\",\"name\":\"contract-review\"}" },
+ { "path": "skills/risk-checklist/SKILL.md", "content": "---\nname: risk-checklist\ndescription: …\n---\n…" }
+ ] }
+ ]
+}
+```
+
+- `name` on the write is OPTIONAL. If present it MUST equal the manifest's `name`; otherwise the
+ write is refused with `plugin_invalid`. The manifest is the source of the name, so that a plugin
+ renamed on install is still the plugin its author published.
+- Two plugins with the same `name` in one harness MUST be refused with `plugin_conflict`.
+- A refused write MUST leave the harness unchanged. A plugin is installed whole or not at all.
+- `PUT /v1/harnesses/{harness_id}` replaces `plugins` as it replaces every other mutable field.
+ Round-tripping a harness through `GET` and `PUT` MUST NOT lose package contents; a client that
+ sends back `{ "name": "contract-review", "blob": "…" }` keeps the package it read.
+- `enabled: false` keeps the plugin installed and inert. Nothing in it is materialised, and none of
+ its MCP servers is contacted ([Harnesses §4.1](harnesses.md#41-mcp-servers)).
+
+### 3.1 Reading the files
+
+```http
+GET /v1/harnesses/{harness_id}/plugins/{plugin_name}/files
+```
+
+```json
+{ "files": [ { "path": "plugin.json", "content": "…" }, { "path": "bin/redline", "content_b64": "…" } ] }
+```
+
+The complete package, byte-for-byte, whether or not the server stores it out of line. `404` with
+`plugin_not_found` when the harness has no plugin of that name.
+
+## 4. Composition: what the agent gets
+
+A harness's **effective configuration** is what its agent runs with. A server computes it from the
+harness object for every turn:
+
+- the effective MCP servers are the harness's enabled `mcpServers`, plus the `mcpServers` of every
+ enabled plugin;
+- the effective skills are the harness's enabled `skills`, plus the `skills` of every enabled plugin;
+- `disabledTools` applies to all of them alike.
+
+### 4.1 The direct fields are unchanged
+
+`mcpServers` and `skills` on the harness keep exactly the meaning they had in the previous version.
+They report what a client wrote there and nothing else. A plugin's components are reported on the
+plugin and are never copied into the direct fields.
+
+A harness with no plugins is what it was before this version, with `plugins` an empty array. Every
+harness that exists today is a valid harness under this version, and every client written against
+the previous version keeps working, by the client rules in [Versioning](../../VERSIONING.md): it
+ignores `plugins` and sees a harness with fewer tools than the agent actually has, which is already
+what it sees for tools the base provides on its own.
+
+The converse holds too. Nothing this version defines changes the shape of an object the previous
+version defined, so a server that implements plugins serves both versions from one code path: it
+lists both in `versions`, answers a `2026-08-11` request with the same objects, and the `plugins`
+field is simply one more field that version's clients ignore. A server that has not implemented
+plugins keeps serving `2026-08-11`, reports the `plugins` capability `false`, and is conformant
+at every class under this version's suite; the plugin checks skip, and a skip is never a pass.
+
+> **Why not report the effective set in `mcpServers`?**
+> Because of the round trip. A client that reads a harness and `PUT`s it back after an unrelated
+> edit is the case [Harnesses §4.2](harnesses.md#42-skills) is designed around. If `mcpServers`
+> carried plugin-derived servers, that `PUT` would write them into the direct list, and the harness
+> would then carry every plugin server twice: once from the plugin and once as its own. Uninstalling
+> the plugin would leave its servers behind. So the direct fields report what was written to them,
+> and a client that wants the effective set takes the union, which this section makes a one-line
+> computation with no server-specific rules in it.
+
+### 4.2 One namespace, checked at configuration time
+
+Within a harness, MCP server names MUST be unique across the direct list and every enabled plugin,
+and skill names likewise. A write that would create a collision MUST be refused with `409` and
+`plugin_conflict`; `detail.component` is `mcp_server` or `skill`, `detail.name` is the colliding
+name, and `detail.between` names the two owners, each either `harness` or a plugin name.
+
+> **Why refuse rather than prefix?**
+> The agent sees one flat namespace: one MCP configuration, one skills directory. Whether a server
+> could prefix a plugin's components with the plugin's name depends on the harness base, and for
+> skills it cannot: Agent Skills requires a skill's `name` to equal its directory name, so renaming
+> the directory breaks the skill. A rule the protocol cannot keep on every base is not a rule. So
+> the ambiguity is refused at configuration time, where a person is present to resolve it, rather
+> than resolved silently at run time, where nobody is. Disabling either side clears the conflict.
+
+### 4.3 The direct fields are a plugin without a name
+
+The direct `mcpServers` and `skills` of a harness are exactly the contents of a plugin: tools and
+skills, with the harness standing in for the manifest. This is not an analogy. [§5](#5-exporting-a-harness-as-a-plugin)
+makes it an operation.
+
+## 5. Exporting a harness as a plugin
+
+```http
+GET /v1/harnesses/{harness_id}/plugin
+```
+
+Returns a plugin object whose `files` are an Agent Plugins package built from the harness's direct
+configuration. The result installs into another harness by passing it to `plugins` unchanged, or
+into any other Agent Plugins client by writing its files to disk.
+
+| In the package | Built from |
+|---|---|
+| `plugin.json` | `$schema` for Agent Plugins 1.0.0 and `name` derived from the harness `name` |
+| `mcp.json` | The enabled direct `mcpServers`; `http` becomes `streamable-http`, `sse` stays `sse` |
+| `skills/<name>/…` | Each enabled direct skill, the whole folder |
+
+- The derived `name` is the harness `name` lower-cased, with every run of characters outside
+ `a-z`, `0-9` and `.` replaced by one `-`, leading and trailing `-` removed, and `..` collapsed to
+ `.`. If nothing remains, the harness `id` is used the same way. The result satisfies Agent Plugins
+ §5.5 by construction.
+- `auth` and `headers` MUST be omitted from every server in `mcp.json`. They are credentials the
+ operator entered for this harness, and a package travels. Each omission is recorded in
+ `skipped`, with the server's path in `mcp.json`, so the person exporting knows what to re-enter.
+- Installed plugins are not included. A plugin does not contain plugins; a client that wants one of
+ them reads its files ([§3.1](#31-reading-the-files)).
+- `systemPrompt`, `defaultModel`, `disabledTools` and `base` are not included. They describe the
+ harness, not its tools and skills, and Agent Plugins has no portable place for them.
+- A harness with nothing to export still returns a valid package: a manifest and nothing else.
+
+## 6. Running with plugins
+
+What a hosted server owes an installed, enabled plugin at run time:
+
+- **Skills** are materialised as [Harnesses §4.2](harnesses.md#42-skills) requires: the whole folder,
+ where the agent reads skills.
+- **Remote MCP servers** (`http`, `sse`) are connected as [Harnesses §4.1](harnesses.md#41-mcp-servers)
+ requires. Placeholder expansion MUST NOT be performed in `url` or `headers`.
+- **stdio MCP servers** run inside the same sandbox as the agent, with the same privileges, and never
+ anywhere else. A server MUST set `PLUGIN_ROOT` and `PLUGIN_DATA` in the subprocess environment,
+ MUST expand `${PLUGIN_ROOT}` and `${PLUGIN_DATA}` in `args`, `env` and `cwd`, MUST NOT expand
+ anything else, and MUST resolve `command` as Agent Plugins §7.2.1 says: a bare executable name, or
+ a plugin-relative path beginning with `./`, with no expansion in `command` itself. The default
+ working directory is the plugin root. The containment rules of Agent Plugins §4.1 apply: a
+ `command` or `cwd` that resolves outside the plugin root (or, for `cwd`, outside `PLUGIN_DATA`)
+ is an invalid entry.
+- **`PLUGIN_DATA`** MUST exist and be writable before the first subprocess launches, and MUST persist
+ for the life of the session ([Sessions](sessions.md)), which is the unit of workspace persistence
+ in UHP. A server MAY keep it longer. Agent Plugins asks for persistence across plugin updates; on
+ a hosted server the session is the boundary a client can reason about, so it is the one promised.
+- **A server that cannot run a transport for a base** MUST refuse the write with
+ `unsupported_transport`, naming the transport and the base in `detail`, rather than accept the
+ plugin and skip the server at run time. The rule of Harnesses §4.1 holds: a server MUST NOT
+ advertise MCP support it cannot deliver.
+- **An MCP server that fails** MUST NOT fail the task, exactly as for a directly attached one. A
+ stdio server that exits is the same event as a remote one that refuses the connection.
+- **A disabled plugin** is not materialised and nothing in it is contacted or launched.
+
+## 7. Discovery
+
+A server that implements this chapter reports it in the discovery document
+([Lifecycle §2](lifecycle.md#2-capability-discovery)):
+
+```json
+{
+ "capabilities": { "harness_management": true, "plugins": true },
+ "plugin_schemas": ["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"]
+}
+```
+
+`plugin_schemas` lists the Agent Plugins manifest schema identifiers the server accepts, and MUST be
+present and non-empty when `plugins` is `true`. A client MUST check both before offering to install
+a package, and MUST NOT offer a package whose `$schema` the server does not list.
+
+A server that reports `plugins: true` MUST accept `plugins` on harness create and update, MUST serve
+the files endpoint ([§3.1](#31-reading-the-files)), and MUST serve the export
+([§5](#5-exporting-a-harness-as-a-plugin)). There is no partial form of the capability.
+
+## 8. Relationship to Agent Plugins conformance
+
+A UHP server with `plugins: true` is an Agent Plugins *client* in that specification's terms
+(§11): it loads a package from a directory, validates the closed manifest, discovers both component
+types from their fixed locations, and, when it launches subprocesses, provides the two environment
+variables and expands them. This chapter adds to that, and never subtracts:
+
+- what Agent Plugins §11.3 says a client SHOULD report, this chapter says a server MUST report, on
+ the object, as `skipped`;
+- placeholders are returned to clients unexpanded;
+- `PLUGIN_DATA` persistence is promised for the life of a session;
+- component names are unique within a harness, and a collision is refused at configuration time.
+
+Agent Plugins itself is versioned by its schema identifiers (§10.1). A later Agent Plugins version
+appears in UHP as a new entry in `plugin_schemas`, which is an additive change to a server and needs
+no new UHP version.
diff --git a/protocol/versions/2026-09-28/schema.md b/protocol/versions/2026-09-28/schema.md
new file mode 100644
index 00000000..647533a7
--- /dev/null
+++ b/protocol/versions/2026-09-28/schema.md
@@ -0,0 +1,71 @@
+# Schema
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+The machine-readable definitions are normative for structure. Where this prose and the schema
+disagree about the shape of an object, the schema wins; where they disagree about behaviour, the
+prose wins, because behaviour is not expressible in JSON Schema.
+
+## Files
+
+| File | Format | Use |
+|---|---|---|
+| [`uhp-2026-09-28.openapi.yaml`](../../schema/uhp-2026-09-28.openapi.yaml) | OpenAPI 3.1 | Generate clients and servers; browse the API |
+| [`uhp-2026-09-28.schema.json`](../../schema/uhp-2026-09-28.schema.json) | JSON Schema 2020-12 | Validate objects and streamed events |
+
+Both are versioned by filename. A published version is immutable: fixing a schema means publishing a
+new version, never editing one clients may already have generated from.
+
+## Generating a client
+
+```bash
+# TypeScript
+npx openapi-typescript protocol/schema/uhp-2026-09-28.openapi.yaml -o uhp.d.ts
+
+# Python
+openapi-python-client generate --path protocol/schema/uhp-2026-09-28.openapi.yaml
+
+# Go
+oapi-codegen -package uhp protocol/schema/uhp-2026-09-28.openapi.yaml > uhp.gen.go
+```
+
+## Validating events
+
+Every streamed event validates against the `Event` definition, which is a discriminated union on
+`type`:
+
+```python
+import json, jsonschema
+
+schema = json.load(open("protocol/schema/uhp-2026-09-28.schema.json"))
+validator = jsonschema.Draft202012Validator(
+ {"$ref": "#/$defs/Event", **schema})
+
+for line in stream:
+ if line.startswith("data: "):
+ validator.validate(json.loads(line[6:]))
+```
+
+The conformance suite does exactly this against a live server, so a schema change that the reference
+implementation does not satisfy fails CI rather than shipping.
+
+## The plugin manifest
+
+`PluginManifest` mirrors the Agent Plugins 1.0.0 manifest schema field for field, and is looser in
+one way: it permits additional properties, because a UHP client MUST ignore fields it does not know
+([Versioning](../../VERSIONING.md)) and a later Agent Plugins version will add some. The
+authoritative schema for a manifest is the one its own `$schema` names; a UHP server validates
+against that, and the definition here describes only the shape a client may rely on
+([Plugins §2.2](plugins.md#22-what-the-server-derives)).
+
+## Extension points
+
+A server MAY add fields anywhere the schema allows additional properties:
+
+- `metadata` on a request or response — the intended place for client and server context.
+- `detail` on an error — structured context for a specific failure.
+- Additional output item types, and additional event types.
+
+A server MUST NOT redefine the meaning of a specified field, and MUST NOT add a required field: a
+client written against this version has to keep working. Vendor-specific fields SHOULD carry a
+vendor prefix so that a later version of this specification cannot collide with them.
diff --git a/protocol/versions/2026-09-28/security.md b/protocol/versions/2026-09-28/security.md
new file mode 100644
index 00000000..b8d54b19
--- /dev/null
+++ b/protocol/versions/2026-09-28/security.md
@@ -0,0 +1,158 @@
+# Security considerations
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+A UHP server runs an agent that executes tools, writes files, and holds a provider credential, on
+behalf of a caller it has never met. That is a larger blast radius than a model endpoint, and the
+requirements here are collected in one place so an implementer can check them off rather than
+rediscover them.
+
+Requirements stated in other chapters are repeated here rather than only cross-referenced. A
+security rule a reader has to assemble from six chapters is a rule that gets missed.
+
+## 1. Credentials
+
+- A server MUST authenticate every endpoint except `GET /v1/uhp`
+ ([Lifecycle §2](lifecycle.md)).
+- A server MUST NOT distinguish "no such token" from "token not permitted here" in a way that lets a
+ caller enumerate valid tokens.
+- A server MUST NOT echo a credential — the caller's or a provider's — in any response body, error
+ message, event, log line, or artifact.
+- A server SHOULD support revoking a credential, and revocation MUST take effect for new requests
+ immediately.
+
+### 1.1 Provider credentials
+
+The credential a server uses to reach a model provider is the most valuable secret in the system,
+and the agent's own sandbox is the least trustworthy place in it: an agent can be induced to read
+its environment and print it.
+
+- A server SHOULD NOT place a provider credential where the agent's tools can read it.
+- A server that must give a harness a credential SHOULD issue a short-lived, single-session one, and
+ MUST be able to revoke it independently of the underlying key.
+- A server MUST NOT accept a caller-supplied upstream URL for a brokered request without validating
+ it against a configured allow-list. An unvalidated upstream turns the server into an SSRF proxy
+ with its own credential attached.
+
+## 2. Object scope
+
+- Every object — harness, response, session, container, file — MUST be scoped to the principal that
+ created it.
+- A request for an object outside the caller's scope MUST return `404`, never `403`. `403` confirms
+ the id exists, which is exactly what an enumerating attacker wants
+ ([Architecture §5](architecture.md)).
+- Scope MUST be enforced on every operation, not only on read. Cancel, delete, continue and download
+ are all object access.
+
+> The conformance suite cannot fully verify this with one credential. An implementer SHOULD run the
+> equivalent check with two principals: create an object as A, then attempt every operation on it as
+> B, and confirm each returns `404`.
+
+## 3. Artifacts are attacker-influenced content
+
+An agent can be persuaded to write a file with chosen content and a chosen name. Everything that
+serves artifacts MUST treat them as hostile.
+
+- Artifact downloads MUST be served with `X-Content-Type-Options: nosniff`. Without it, an artifact
+ named `x.html` becomes stored XSS against the client's own origin
+ ([Files §3](files.md)).
+- Artifacts SHOULD be served from a different origin than the console or application UI, so that a
+ successful injection cannot reach first-party cookies or storage.
+- A server MUST NOT allow a `container_id` / `file_id` pair to address anything outside its
+ container. Path traversal through artifact ids is the most likely serious vulnerability in a UHP
+ implementation; the conformance suite probes for it (X-08), and passing that probe is a floor, not
+ proof.
+- A server SHOULD cap artifact size and count per session.
+
+## 4. Prompt injection is in scope for the client
+
+A harness that reads a web page, a repository, or an uploaded file may encounter instructions
+addressed to it. UHP cannot prevent this, and a specification that pretended otherwise would be
+worse than one that says so plainly.
+
+What the protocol does provide, and a client SHOULD use:
+
+- **`disabledTools`** on a configured harness — the smallest tool set that can do the job is the
+ smallest injection surface.
+- **`max_step` and `timeout_seconds`** — a bounded task cannot be induced into an unbounded one.
+- **Separate harnesses for separate trust levels.** A harness that reads untrusted input SHOULD NOT
+ be the same configured harness that holds privileged tools or MCP servers.
+- **The event stream.** Tool calls are visible as they happen; a client can surface or gate them.
+
+A server MUST NOT claim that any of this makes an agent safe to point at untrusted input.
+
+## 5. Resource exhaustion
+
+- A server MUST bound task duration, and MUST report `incomplete` rather than `completed` when a
+ budget stopped the work ([Lifecycle §3](lifecycle.md)).
+- A server MUST refuse a second concurrent task in the same session (`session_busy`) — two agents in
+ one working directory is not a defined state, and is also a cheap way to multiply cost.
+- A server SHOULD rate-limit task creation per principal and SHOULD expose remaining budget through
+ `rate_limit_error` responses rather than by failing opaquely.
+- A server MUST bound upload size and reject with `file_too_large` rather than truncating. A silently
+ truncated input produces a confident, wrong answer.
+
+## 6. Data handling
+
+- Session artifacts and transcripts MUST be unreachable after the session is deleted.
+- A server SHOULD document its retention period. "Indefinite" is an answer; silence is not.
+- Session sharing, where implemented, MUST be read-only and revocable, and MUST NOT expose
+ credentials or another principal's data ([Sessions §5](sessions.md)).
+
+## 7. Transport
+
+- TLS MUST be used except on loopback.
+- A server SHOULD send `Strict-Transport-Security`.
+- A server serving any HTML MUST send `X-Frame-Options: DENY` or an equivalent
+ `frame-ancestors 'none'` policy.
+
+## 8. Error hygiene
+
+- `error.message` MUST be safe to show a user: no credentials, internal hostnames, file paths, or
+ stack traces ([Errors §1](errors.md)).
+- A server SHOULD log the detail it withholds, with a correlation id it returns in `error.detail`,
+ so an operator can diagnose what a caller cannot see.
+
+## 9. Plugins are third-party code
+
+A plugin ([Plugins](plugins.md)) is instructions and executables written by someone other than the
+operator installing it. Installing one extends the harness's trust to its author.
+
+- A stdio MCP server declared by a plugin MUST run inside the sandbox that runs the agent, with the
+ agent's privileges and no more. It MUST NOT run on the server host, and MUST NOT be launched
+ through a shell.
+- A server MUST expand only `${PLUGIN_ROOT}` and `${PLUGIN_DATA}`, only in `args`, `env` and `cwd`,
+ and MUST NOT perform any other placeholder or environment-variable expansion. A plugin that could
+ read the sandbox's environment into its own process arguments would read whatever credentials the
+ sandbox holds ([§1](#1-credentials)).
+- A `command` or `cwd` that resolves outside the plugin root is an invalid entry, never a permitted
+ one ([Plugins §6](plugins.md#6-running-with-plugins)).
+- Plugins are installed by whoever manages the harness (class Full), never per request. A
+ per-request plugin would be a per-request MCP server, which [Tasks §1.4](tasks.md#14-reserved-fields-tools-and-include)
+ already declines for the same reason: narrowing is safe, widening is escalation.
+- A skill inside a plugin is prompt content and is subject to [§4](#4-prompt-injection-is-in-scope-for-the-client).
+ A client SHOULD show the manifest's `author`, `homepage` and `repository` before installing, and
+ SHOULD show `skipped` after, so that what did not load is not mistaken for what did.
+- A server MUST omit `auth` and `headers` from an exported package
+ ([Plugins §5](plugins.md#5-exporting-a-harness-as-a-plugin)). An export is meant to leave.
+
+## 10. Environments are shared, and built from what the owner sends
+
+An environment ([Environments](environments.md)) is read by every session that names it, and its
+build runs the project's own manifests and `setup.sh`. Three rules follow:
+
+- **Read-only is enforced.** An agent told not to write will still try; a server MUST make the
+ write fail, by a read-only mount, a user without permission, or an equivalent, and MUST NOT rely
+ on the instruction ([Environments §6](environments.md#6-what-a-session-sees)).
+- **A build has a task's privileges, not the server's.** It runs with the toolchain and network a
+ task gets and no more; it cannot read another environment or any session. On a multi-tenant
+ server it is a job of the tenant that owns the environment ([Environments §9](environments.md#9-security)).
+- **Paths are confined at every endpoint.** A file path, an archive member and a repository tree
+ are all held to the environment's root; links out of it and absolute paths are dropped, never
+ followed ([Environments §3](environments.md#3-files)).
+
+## 11. Reporting a vulnerability
+
+Vulnerabilities in the reference implementation or in this specification follow private disclosure,
+not a public issue. See the repository's security policy. A specification bug that makes a secure
+implementation impossible is treated as a vulnerability, not as a documentation defect.
diff --git a/protocol/versions/2026-09-28/sessions.md b/protocol/versions/2026-09-28/sessions.md
new file mode 100644
index 00000000..ea43b3d7
--- /dev/null
+++ b/protocol/versions/2026-09-28/sessions.md
@@ -0,0 +1,177 @@
+# Sessions
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+A session is what makes a second task cheaper than the first: the conversation is still there, and
+so is the working directory. This chapter defines continuing a session, inspecting one, and stopping
+work in one.
+
+## 1. Continuing a session
+
+Send the next task with `previous_response_id`:
+
+```json
+{
+ "input": "Now add tests for the function you just wrote.",
+ "previous_response_id": "resp_a1b2c3"
+}
+```
+
+The server MUST:
+
+- run the new task in the same session, with the same working directory and its files;
+- give the harness the conversational context of the earlier tasks;
+- use the same configured harness;
+- report the same `metadata.session_id`.
+
+`model` MAY differ between tasks in a session. A server MUST honour a per-task model change, because
+switching to a cheaper model for a follow-up is a common and legitimate pattern.
+
+If `previous_response_id` names an unknown response, the server MUST fail with `404` and
+`code: "response_not_found"`. If the session it referred to has expired, `404` with
+`code: "session_expired"` — a client can retry the first from scratch, and should not retry the
+second.
+
+> **Why chain on the response id rather than the session id?**
+> Because the response id is what the client already has: it comes back from the task it just ran.
+> Chaining on it also names an exact point in the conversation, which leaves room for a server to
+> branch from an earlier response later without changing the request shape.
+
+## 2. Listing sessions
+
+Conformance class **Extended**.
+
+```http
+GET /v1/sessions?limit=20&cursor=&harness=chrn_…
+```
+
+```json
+{
+ "sessions": [
+ {
+ "id": "hsess7e78…",
+ "object": "session",
+ "harness_id": "chrn_…",
+ "title": "Summarise README.md",
+ "status": "completed",
+ "created_at": 1786400000,
+ "updated_at": 1786400240
+ }
+ ],
+ "next_cursor": null
+}
+```
+
+Pagination is cursor-based. A server MUST return `next_cursor: null` on the last page, and MUST NOT
+require a client to detect the end by receiving fewer items than it asked for — that heuristic is
+wrong whenever a page is exactly full.
+
+## 3. Inspecting a session
+
+```http
+GET /v1/sessions/{session_id}
+GET /v1/sessions/{session_id}/turns
+```
+
+`/turns` returns the ordered task history of the session, so a client can rebuild a transcript it did
+not store. Each turn identifies its response id, so a client can fetch the full response for any of
+them.
+
+Each item in `turns` MUST carry at least:
+
+| Field | Type | Meaning |
+|---|---|---|
+| `id` | string | The response id of the turn, usable with `GET /v1/responses/{id}`. |
+| `status` | string | The turn's status, in the response-status vocabulary of [Tasks §1](tasks.md). |
+
+and SHOULD carry, when the server has them: `user` (string, the user message), `assistant` (string,
+the assistant's final text), `tools` (array, the tool calls of the turn), and `files` (array, the
+files the turn produced). A server MAY add fields; a client MUST ignore fields it does not
+understand. This was previously an object with no stated shape, which meant no conformance check
+could assert anything past the status code, and every client that rebuilt a transcript did so
+against one implementation's habits.
+
+A session whose turns read an environment carries `environment`, the environment's id, so a client
+can tell which project a conversation worked in ([Environments §6](environments.md#6-what-a-session-sees)).
+
+## 4. Cancelling
+
+Two scopes, deliberately distinct:
+
+```http
+POST /v1/responses/{response_id}/cancel # stop this task
+POST /v1/sessions/{session_id}/cancel # stop whatever is running in this session
+```
+
+Semantics:
+
+- Cancellation is a request, not a guarantee of immediacy. A server MUST stop the work as soon as it
+ can and MUST reach a terminal state.
+- A cancelled task MUST end with `status: "cancelled"`, never `failed`.
+- Output produced before cancellation MUST be retained.
+- Cancelling an already-terminal task MUST succeed and change nothing. A client retrying a cancel
+ after a dropped connection should not receive an error for having succeeded twice.
+- Cancelling MUST NOT delete the session. The conversation remains continuable.
+
+A server SHOULD respond to cancel within one second even if the harness takes longer to wind down.
+The client is usually a user interface, and a Stop button that does nothing visible for thirty
+seconds reads as broken.
+
+## 5. Session sharing
+
+Conformance class **Full**. A server MAY let a client publish a read-only view of a session.
+
+```http
+POST /v1/sessions/{session_id}/share # publish (a body is OPTIONAL; no body means publish)
+GET /v1/sessions/{session_id}/share # read the share back
+DELETE /v1/sessions/{session_id}/share # revoke
+```
+
+If implemented, the share object returned by `POST` and `GET` MUST carry:
+
+| Field | Type | Meaning |
+|---|---|---|
+| `id` | string | The share's identity. |
+| `url` | string | Where the shared view is served. May be relative, in which case it resolves against the base URL the caller is already using — a server behind a proxy cannot know its public origin, and a base-relative path survives every fronting. |
+
+`object` SHOULD be `"session.share"`. A server MAY carry additional fields (the reference also
+returns an `enabled` toggle and accepts `{"enabled": bool}` bodies); a client MUST ignore fields it
+does not understand. A second `POST` MAY return the existing share or mint a new one, but
+revocation MUST reach every link minted for the session — revoking only the newest tells an
+operator the session is private while somebody still holds a working link.
+
+The rules, unchanged:
+
+- the shared view MUST be read-only — it MUST NOT permit continuing, cancelling, or uploading;
+- `GET` on the published `url` MUST serve the view to a holder of the link with no other
+ credential — a view only its creator can open has not been published to anyone;
+- after `DELETE`, and after the session itself is deleted (§6), the published `url` MUST stop
+ resolving (404 or 410);
+- the share's id MUST NOT function as a credential for the rest of the API;
+- the server MUST NOT expose provider credentials, tokens, or another principal's data through the
+ view.
+
+These were previously behaviors the conformance suite had to discover by probing (the endpoints and
+the object had no stated shape, so a portable check could only guess at paths and skip when the
+guesses missed). They are codified from the shapes the reference implementation demonstrates and
+the R-series measures; the suite now asserts them.
+
+## 6. Deleting
+
+```http
+DELETE /v1/sessions/{session_id}
+```
+
+Deletes the session and its stored history: the transcript, the trace, and the working folder the
+session's tasks wrote. Afterwards the session MUST NOT count toward any storage or memory allowance
+the server enforces, because deletion is how a client makes room. A server MUST answer `2xx`, and a
+later `GET /v1/sessions/{session_id}` MUST return `404`.
+
+`DELETE /v1/traces/{session_id}` is the older path for the same operation. It predates the session
+vocabulary; a server MAY keep serving it (the reference implementation does, as the same handler),
+but the path above is the one the protocol names and the one clients SHOULD use.
+
+A server MUST cancel any in-flight task in the session first, and MUST make the session
+unreadable afterwards. Deletion is the one place where cancel and
+delete are legitimately coupled, because the alternative is a running task writing into storage that
+no longer has an owner.
diff --git a/protocol/versions/2026-09-28/streaming.md b/protocol/versions/2026-09-28/streaming.md
new file mode 100644
index 00000000..eab3ce14
--- /dev/null
+++ b/protocol/versions/2026-09-28/streaming.md
@@ -0,0 +1,161 @@
+# Streaming
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+Agent tasks take minutes. Without a stream, a product can only show a spinner and hope. This chapter
+defines how a server reports progress while work is happening.
+
+## 1. Opening a stream
+
+Set `"stream": true` on `POST /v1/responses`. The server MUST respond with:
+
+```http
+HTTP/1.1 200 OK
+Content-Type: text/event-stream
+Cache-Control: no-cache
+```
+
+Each event is a Server-Sent Events message whose `data` is one JSON object:
+
+```
+data: {"type":"response.created","sequence_number":0,"response":{…}}
+
+data: {"type":"response.output_text.delta","sequence_number":7,"item_id":"msg_1","output_index":0,"content_index":0,"delta":"Sum"}
+
+data: {"type":"response.completed","sequence_number":42,"response":{…}}
+
+```
+
+Rules:
+
+- Every event MUST carry `type` and `sequence_number`.
+- `sequence_number` MUST start at `0` and increase by exactly 1 per event within a stream. A client
+ can therefore detect a dropped event rather than silently rendering a gap.
+- The stream MUST end with exactly one terminal event (§4).
+- A server MUST NOT buffer the stream to completion before sending it. A stream delivered all at once
+ at the end is not a stream, and a client cannot tell the difference between that and a hang.
+- Servers behind a proxy MUST disable response buffering. This is the single most common deployment
+ error for UHP servers; it looks exactly like the harness being slow.
+
+## 2. Event vocabulary
+
+Events describe *what happened*. They never describe how to display it.
+
+### 2.1 Response lifecycle
+
+| Event | When |
+|---|---|
+| `response.created` | The task was accepted. Carries the initial `response` with `status: in_progress`. |
+| `response.in_progress` | Work has started. |
+| `response.completed` | Terminal — success. Carries the final `response`. |
+| `response.incomplete` | Terminal — a budget stopped the work. Carries the final `response`. |
+| `response.failed` | Terminal — failure. Carries the final `response`, whose `error` is non-null. |
+
+### 2.2 Output items
+
+| Event | When |
+|---|---|
+| `response.output_item.added` | A new item begins. Carries `output_index` and a shell `item`. |
+| `response.output_item.done` | That item is final. Carries the complete `item`. |
+
+### 2.3 Assistant text
+
+| Event | Payload |
+|---|---|
+| `response.content_part.added` | An empty `output_text` part opens |
+| `response.output_text.delta` | `delta`: the next fragment of text |
+| `response.output_text.done` | `text`: the complete text of the part |
+| `response.content_part.done` | `part`: the finished part |
+| `response.output_text.annotation.added` | `annotation`: an artifact citation (see [Files](files.md)) |
+
+Text deltas are fragments, not lines or tokens. A client MUST concatenate them in `sequence_number`
+order and MUST NOT assume any particular chunking.
+
+### 2.4 Reasoning
+
+| Event | Payload |
+|---|---|
+| `response.reasoning_summary_part.added` | An empty summary part opens |
+| `response.reasoning_summary_text.delta` | `delta`: the next fragment of the summary |
+| `response.reasoning_summary_part.done` | `part`: the finished summary part |
+
+Reasoning is a *summary*, not a verbatim chain of thought. A server MUST NOT be required to expose
+raw model reasoning, and a client MUST treat reasoning as optional — many harness and model
+combinations produce none, and a client that requires it will break on those.
+
+### 2.5 Tool use
+
+| Event | Payload |
+|---|---|
+| `response.function_call_arguments.delta` | `delta`: fragment of the JSON arguments |
+| `response.function_call_arguments.done` | `arguments`: the complete JSON string |
+
+The tool call itself arrives as an `output_item` of type `function_call`, and its result as
+`function_call_output` matched by `call_id`.
+
+### 2.6 Errors
+
+| Event | Payload |
+|---|---|
+| `error` | `code`, `message`, `param` — an error that did not end the task |
+
+An `error` event MUST be followed by a terminal event. A stream that emits `error` and then stops
+without a terminal event is malformed: the client cannot tell whether the task died or the
+connection did.
+
+## 3. Ordering guarantees
+
+A server MUST guarantee:
+
+1. `response.created` is the first event.
+2. Exactly one terminal event is the last.
+3. For any item, `output_item.added` precedes every event referring to it, and `output_item.done`
+ follows them all.
+4. `sequence_number` is strictly monotonic with no gaps.
+
+A server MUST NOT guarantee, and a client MUST NOT assume:
+
+- that items complete in the order they were added (a long tool call may finish after later text);
+- that text arrives in any particular chunk size;
+- that any optional event type appears at all.
+
+## 4. Terminal events
+
+Exactly one of `response.completed`, `response.incomplete`, `response.failed`. Each carries the
+complete final `response` object — a client that missed intermediate events can rely on this one
+alone to render the result. This redundancy is deliberate: a dropped connection mid-stream should
+cost latency, not correctness.
+
+A cancelled task terminates with `response.failed` carrying `status: "cancelled"` in the response
+object. The status field, not the event name, is authoritative.
+
+## 5. Reconnecting
+
+A dropped connection MUST NOT abort the task. The work continues server-side.
+
+To follow a task after a disconnect, a client re-reads it:
+
+```http
+GET /v1/responses/{response_id}
+```
+
+or, for a live event feed of a harness's sessions:
+
+```http
+GET /v1/harnesses/{harness_id}/events
+```
+
+A server MAY additionally support SSE `Last-Event-ID` resumption. If it does, it MUST resume from
+the event *after* the given `sequence_number` and MUST NOT replay events the client already saw.
+
+> A client SHOULD treat the stream as an optimisation and the stored response as the source of
+> truth. Products written the other way round — where the stream is the only place a result exists —
+> lose work every time a load balancer recycles a connection.
+
+## 6. Non-streaming
+
+With `"stream": false` (the default), the server returns a single response object when the task
+reaches a terminal state, with the same `output` array the stream would have assembled. The two
+paths MUST produce identical results for identical input. A server that assembles a different
+`output` for streaming than for non-streaming has two implementations of its own protocol, and one
+of them is wrong.
diff --git a/protocol/versions/2026-09-28/tasks.md b/protocol/versions/2026-09-28/tasks.md
new file mode 100644
index 00000000..15e4a75d
--- /dev/null
+++ b/protocol/versions/2026-09-28/tasks.md
@@ -0,0 +1,288 @@
+# Tasks
+
+**Unified Harness Protocol, version `2026-09-28`**
+
+A task is one unit of work: input in, a result out. It is the endpoint most clients spend all their
+time in.
+
+## 1. Run a task
+
+```http
+POST /v1/responses
+Authorization: Bearer <token>
+Content-Type: application/json
+```
+
+```json
+{
+ "input": "Summarise README.md in three bullets.",
+ "model": "claude-sonnet-4.6",
+ "metadata": { "harness_id": "chrn_08dae611630d467ab3e67ed792570ae5" },
+ "stream": true
+}
+```
+
+### 1.1 Request fields
+
+| Field | Type | Required | Meaning |
+|---|---|---|---|
+| `input` | string \| item[] | yes | The work. A bare string is shorthand for one user message. See §2. |
+| `model` | string | no | Canonical model id. Omitted means the harness's default. |
+| `metadata` | object | no | Client metadata. `harness_id` selects the configured harness. See §1.2. |
+| `stream` | boolean | no | `true` streams Server-Sent Events; default `false` returns one JSON object. |
+| `previous_response_id` | string | no | Continue the session that produced that response. See [Sessions](sessions.md). |
+| `instructions` | string | no | Additional system guidance for this task only. |
+| `store` | boolean | no | Whether the server retains the response for later reads. Default `true`. |
+| `max_output_tokens` | integer | no | Upper bound on generated tokens. |
+| `max_step` | integer | no | Upper bound on agent steps (tool-call rounds) for this task. |
+| `timeout_seconds` | integer | no | Wall-clock budget for this task. |
+| `environment` | string | no | The environment this task reads, overriding the harness's; refused with `environment_not_found` or `environment_not_ready` before the task starts. Requires the `environments` capability ([Environments §5](environments.md#5-attaching-an-environment)). |
+| `tools` | array | no | **Reserved and ignored.** Accepted, never acted on. See §1.4. |
+| `include` | string[] | no | **Reserved and ignored.** Accepted, never acted on. See §1.4. |
+| `background` | boolean | no | Return as soon as the task is accepted; follow it with the events endpoint. |
+
+A server MUST ignore request fields it does not understand rather than rejecting the request. A
+client MUST NOT rely on an unknown field having an effect.
+
+Ignoring MUST be observable. When a server does not act on a field the request carried, it MUST
+name that field in `metadata.ignored_fields` on the response — an array of request-field names, in
+any order. This is the same principle as model substitution in §1.3: where the server did not do
+what the request literally said, the response says so. A silently ignored field is
+indistinguishable from an honoured one, and a client cannot tell which it got.
+
+`tools` and `include` are reserved and ignored (§1.4), so a server MUST name them in
+`metadata.ignored_fields` whenever a request carries them. A server MUST NOT reject a request for
+carrying either.
+
+`max_step` and `timeout_seconds` are budgets, not guarantees of precision: a server MUST stop the
+task at or after the budget, MUST report `incomplete`, and MUST NOT report `completed` for work it
+truncated.
+
+### 1.2 Selecting the harness
+
+The configured harness is selected by `metadata.harness_id`:
+
+```json
+{ "metadata": { "harness_id": "chrn_…" } }
+```
+
+- If `harness_id` is absent, the server MUST use a default harness and MUST report which one it used
+ in the response `metadata`.
+- If `harness_id` names an unknown harness, or one outside the caller's scope, the server MUST fail
+ with `404` and `code: "harness_not_found"`.
+- If both `previous_response_id` and `harness_id` are present and disagree, the server MUST fail with
+ `409` and `code: "harness_mismatch"` (see [Lifecycle §4](lifecycle.md)).
+
+> **Why is the harness in `metadata` rather than a top-level field?**
+> Because the task surface is deliberately Responses-compatible (see the
+> [README](../../README.md)), and `metadata` is the extension point that surface already defines for
+> caller-supplied context. A top-level `harness` field would be a second, conflicting convention for
+> the same idea, and every existing Responses SDK would have to be patched to send it.
+
+### 1.3 Model selection and substitution
+
+`model` names a canonical model id, not a provider-specific one. Canonical ids are stable across
+providers, so the same request works whether the server reaches a model directly or through an
+aggregator.
+
+If the requested model cannot be served for the selected harness, a server MUST NOT fail silently
+and MUST NOT pretend it ran what was asked. It MUST do exactly one of:
+
+1. **Fail** with `422` and `code: "model_unavailable"`; or
+2. **Substitute** the harness's authorized default, and record the substitution in the response:
+
+```json
+{
+ "model": "gpt-5.4",
+ "metadata": {
+ "requested_model": "gpt-5.6-sol",
+ "model_fallback": true,
+ "model_fallback_reason": "model 'gpt-5.6-sol' is not available for this harness's backend"
+ }
+}
+```
+
+A client can therefore always answer "did the model I asked for actually run?" by comparing `model`
+with `metadata.requested_model`.
+
+> This rule exists because its absence is expensive. A server that substitutes silently makes every
+> measurement downstream wrong — benchmarks, cost attribution, quality comparisons — and the client
+> has no way to detect it. Reporting the substitution costs two fields.
+
+### 1.4 Reserved fields: `tools` and `include`
+
+Both fields arrived with the OpenAI Responses wire shape this version stays compatible with. Neither
+was designed for UHP, and neither has ever had defined semantics here. They are **reserved**: a
+server accepts them, never acts on them, and reports them under `metadata.ignored_fields` (§1.1).
+
+This is a decision rather than a gap left open, so implementers can stop carrying them as unfinished
+work and client authors can stop building on them.
+
+**`tools` cannot mean what it means in the Responses API.** There, the field exists because the
+*client* executes tools: the model emits a `function_call`, the client runs it, and returns a
+`function_call_output` as input on the next request. UHP puts both of those in `output` (§3.1). The
+harness invokes and executes tools itself and reports them as observability. There is no input path
+for a tool result, so the loop `tools` implies cannot be completed by a conformant server — not
+because implementations are immature, but because the object model has no place for the return leg.
+
+**`tools` also cannot mean "MCP servers for this task", which is the other plausible reading.**
+[Harnesses](harnesses.md) §4.1 already specifies MCP servers on the harness, with a
+field table and the semantics that matter: a disabled entry MUST NOT be contacted, an unreachable
+server MUST NOT fail the task. A request-level form would be a second mechanism for one behaviour.
+
+More importantly, it would be an **escalation primitive**. If a request can attach an MCP server,
+anyone holding an API key can point the agent at an endpoint of their choosing, and the agent
+executes tools server-side with the harness's credentials and workspace access. The harness owner
+and the API caller are routinely different parties — a product configures a harness, and its end
+users drive tasks against it. Request-level declaration silently moves a capability decision from
+the accountable party to any caller. The configured harness is a first-class object precisely so
+that decision is made once, deliberately, by whoever owns the consequences.
+
+The durable rule underneath, which applies beyond this field: **narrowing is safe, widening is
+escalation.** A future version could reasonably add a typed per-request tool *disable* list. It
+should never add a per-request *grant*.
+
+**`include` has no vocabulary.** It is `array of string` with no enumerated values, so any string a
+server recognises is one that server named itself. Recognising a value would be inventing a
+vocabulary no other implementation shares.
+
+**How an agent gets tools:** configure them on the harness. See
+[Harnesses](harnesses.md) §4.1 for MCP servers and §4.2 for skills.
+
+Removal is a question for the next version. This one is additive-only and cannot drop a field, so
+the honest form here is to say plainly that these two do nothing.
+
+## 2. Input
+
+`input` is either a string or an array of items.
+
+```json
+{ "input": "Summarise README.md" }
+```
+
+```json
+{
+ "input": [
+ { "role": "user", "content": [
+ { "type": "input_text", "text": "Summarise this report." },
+ { "type": "input_file", "filename": "q3.pdf", "file_data": "data:application/pdf;base64,…" }
+ ]}
+ ]
+}
+```
+
+| Item type | Purpose |
+|---|---|
+| `input_text` | Text |
+| `input_file` | A file, inline as a data URL in `file_data`, or by `file_id` from a prior upload |
+| `input_image` | An image, inline or by `file_id` |
+
+A server at conformance class **Core** MUST accept `input_text`. A server at **Extended** MUST also
+accept `input_file` and `input_image`. See [Files](files.md).
+
+## 3. The response object
+
+```json
+{
+ "id": "resp_a1b2c3",
+ "object": "response",
+ "created_at": 1786400000,
+ "status": "completed",
+ "error": null,
+ "incomplete_details": null,
+ "previous_response_id": null,
+ "model": "claude-sonnet-4.6",
+ "output": [
+ { "id": "rs_1", "type": "reasoning", "summary": [ { "type": "summary_text", "text": "…" } ], "status": "completed" },
+ { "id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "read_file",
+ "arguments": "{\"path\":\"README.md\"}", "status": "completed" },
+ { "id": "fco_1", "type": "function_call_output", "call_id": "call_1", "output": "…", "status": "completed" },
+ { "id": "msg_1", "type": "message", "role": "assistant", "status": "completed",
+ "content": [ { "type": "output_text", "text": "- …\n- …\n- …", "annotations": [] } ] }
+ ],
+ "store": true,
+ "usage": { "input_tokens": 5120, "output_tokens": 240, "total_tokens": 5360 },
+ "metadata": { "session_id": "hsess7e78…" }
+}
+```
+
+| Field | Type | Required | Notes |
+|---|---|---|---|
+| `id` | string | yes | `resp_`-prefixed |
+| `object` | string | yes | Always `response` |
+| `created_at` | integer | yes | Unix seconds |
+| `status` | string | yes | See [Lifecycle §3](lifecycle.md) |
+| `error` | object \| null | yes | Present and non-null only when `status` is `failed` |
+| `output` | item[] | yes | Ordered; MAY be empty for a task that produced nothing |
+| `model` | string | yes | The model that actually ran |
+| `usage` | object \| null | yes | `null` when the server cannot account for usage — never a fabricated zero |
+| `metadata` | object | yes | MUST include `session_id`; see §1.3 for substitution fields |
+| `previous_response_id` | string \| null | yes | The response this one continues, if any |
+| `store` | boolean | yes | Whether this response was retained |
+
+### 3.1 Output items
+
+| `type` | Meaning |
+|---|---|
+| `message` | Assistant text, in `content[].text`, with `annotations` for artifacts |
+| `reasoning` | The agent's summarised thinking, in `summary[].text` |
+| `function_call` | A tool the agent invoked, with `arguments` as a JSON string |
+| `function_call_output` | The result of that tool call, matched by `call_id` |
+
+A client MUST tolerate output item types it does not recognise, and MUST NOT assume any ordering
+beyond the array order given. A client that renders only `message` items and ignores the rest is a
+valid client.
+
+## 4. Reading a task back
+
+```http
+GET /v1/responses/{response_id}
+```
+
+Returns the same response object. A server that retained the response (`store: true`) MUST return it
+after completion; a server MAY return `404` with `code: "response_not_found"` for a response created
+with `store: false`.
+
+```http
+GET /v1/responses/{response_id}/input_items
+```
+
+Returns the input the task was created with, for clients that need to reconstruct a transcript
+without having stored it themselves.
+
+## 5. Cancelling
+
+```http
+POST /v1/responses/{response_id}/cancel
+```
+
+See [Sessions §4](sessions.md).
+
+## 6. Idempotency
+
+A client MAY send an idempotency key:
+
+```http
+Idempotency-Key: <client-generated-unique-string>
+```
+
+A server that advertises `idempotency` MUST, for a repeated key:
+
+- return the result of the **first** request, and
+- **not** start a second execution.
+
+If the first request is still running, the server MUST wait for it and return its result rather than
+returning a partial or a conflict. Agent tasks are expensive and side-effecting: a retry that runs
+the work twice is worse than a slow answer.
+
+Idempotency keys SHOULD be retained for at least 24 hours.
+
+## 7. Deleting
+
+```http
+DELETE /v1/responses/{response_id}
+```
+
+Deletes the stored response. A server MUST NOT let this cancel a running task — cancellation and
+deletion are different intentions, and conflating them means a client cannot clean up history
+without stopping work.
diff --git a/runner/environments.py b/runner/environments.py
new file mode 100644
index 00000000..cb8f16f5
--- /dev/null
+++ b/runner/environments.py
@@ -0,0 +1,699 @@
+"""Environments: a project's files and its installed dependencies, built once and read by every
+session that names it.
+
+The contract a session sees (UHP 2026-09-28, Environments chapter):
+
+ /env/<slug> the environment, READ-ONLY, shared by every session that uses it
+ <cwd> the session's own workspace: writable, private, where artifacts land
+ PROJECT_ROOT=/env/<slug> plus the environment's venv and node_modules on PATH/PYTHONPATH/NODE_PATH
+
+Why a layer beside the workspace and not a copy into it: the workspace is checkpointed after every
+turn and restored before the next one, and dependency directories are excluded from that tarball
+because they are large and reinstallable (CHECKPOINT_EXCLUDE). An environment is the opposite
+kind of thing: installed once, never checkpointed, never reinstalled, read by many sessions at
+once. Putting it beside the workspace keeps both facts true at zero copy per session.
+
+Layout on disk (ENV_ROOT, on the data volume):
+
+ <ENV_ROOT>/<id>/source/ the editable project: what the console's file tree shows
+ <ENV_ROOT>/<id>/versions/<n>/ one build: the source copied, then .venv and node_modules
+ installed into it, then made read-only (root-owned, a+rX)
+ <ENV_ROOT>/<id>/versions/<n>/.hr-build.json the build's record: status, log, packages, size
+ <ENV_ROOT>/<id>/active symlink -> versions/<n>: the version sessions see
+ <ENV_MOUNT>/<slug> symlink -> <ENV_ROOT>/<id>/active: the path the agent is told
+
+A build is a snapshot: editing the source after it changes nothing a session sees until the next
+build. Rolling back is pointing `active` at an older version. Behind the write-wall
+(HR_SESSION_UIDS) a session runs as its own uid and the layer is root's, so a write into it fails
+with EACCES; that is the enforcement, not an instruction.
+"""
+from __future__ import annotations
+
+import json
+import mimetypes
+import os
+import pathlib
+import shutil
+import stat
+import subprocess
+import tarfile
+import tempfile
+import threading
+import time
+import zipfile
+
+from fastapi import APIRouter, HTTPException, Request, Response
+from fastapi.responses import JSONResponse
+
+ENV_ROOT = os.environ.get("HR_ENV_ROOT") or os.path.join(
+ os.path.dirname(os.environ.get("HARNESS_WORKSPACE", "/data/workspaces").rstrip("/")) or "/data", "environments")
+ENV_MOUNT = os.environ.get("HR_ENV_MOUNT", "/env")
+BUILD_TIMEOUT = int(os.environ.get("HR_ENV_BUILD_TIMEOUT", "1800")) # the whole build, seconds
+LOG_MAX = 200_000 # characters of build log kept
+TREE_MAX = 20_000 # entries a tree listing returns
+# Dependency and cache directories never copied from the source into a build: the build installs
+# its own, from the manifests, in the image's own toolchain (a venv copied from a laptop is the
+# thing SPI-001 says not to trust).
+NOT_COPIED = {".venv", "venv", "node_modules", "__pycache__", ".pnpm-store", ".cache", ".hr-build.json"}
+_ID_SAFE = set("abcdefghijklmnopqrstuvwxyz0123456789_-")
+
+router = APIRouter()
+_builds_lock = threading.Lock()
+_builds: dict[str, threading.Thread] = {} # "<id>:<n>" -> the thread building it
+
+
+# ── paths ───────────────────────────────────────────────────────────────────────────────────────
+def _check_id(env_id: str) -> str:
+ s = str(env_id or "").strip()
+ if not s or len(s) > 80 or any(c not in _ID_SAFE for c in s.lower()):
+ raise HTTPException(400, "environment id must be a short [a-z0-9_-] token")
+ return s
+
+
+def slug_ok(slug: str) -> bool:
+ s = str(slug or "")
+ return bool(s) and len(s) <= 64 and s[0].isalnum() and all(c.isalnum() or c in "-_." for c in s) and ".." not in s
+
+
+def env_dir(env_id: str) -> pathlib.Path:
+ return pathlib.Path(ENV_ROOT) / _check_id(env_id)
+
+
+def source_dir(env_id: str) -> pathlib.Path:
+ return env_dir(env_id) / "source"
+
+
+def version_dir(env_id: str, n: int) -> pathlib.Path:
+ return env_dir(env_id) / "versions" / str(int(n))
+
+
+def active_link(env_id: str) -> pathlib.Path:
+ return env_dir(env_id) / "active"
+
+
+def mount_path(slug: str) -> str:
+ return os.path.join(ENV_MOUNT, slug)
+
+
+def _safe_rel(root: pathlib.Path, rel: str) -> pathlib.Path:
+ """A path under root, or 400. Symlinks inside the source are followed for the containment check
+ so a link that points out of the tree cannot be read or written through."""
+ raw = str(rel or "").replace("\\", "/")
+ if raw.startswith("/") or (len(raw) > 1 and raw[1] == ":"):
+ raise HTTPException(400, "path must be relative to the environment, not absolute")
+ rel = raw.strip("/")
+ if not rel or any(part in ("", ".", "..") for part in rel.split("/")):
+ raise HTTPException(400, "path must be relative, without . or .. segments")
+ base = root.resolve()
+ p = (base / rel).resolve()
+ try:
+ p.relative_to(base)
+ except ValueError:
+ raise HTTPException(400, "path escapes the environment")
+ return p
+
+
+# ── the source: files a person edits ─────────────────────────────────────────────────────────────
+def tree(env_id: str) -> list[dict]:
+ """Every entry under the source, deepest last within a directory, as the console's tree wants
+ it: path, dir flag, bytes, mtime. Symlinks are listed as what they are and never followed."""
+ src = source_dir(env_id)
+ out: list[dict] = []
+ if not src.is_dir():
+ return out
+ for dirpath, dirnames, filenames in os.walk(src):
+ dirnames.sort()
+ rel_dir = os.path.relpath(dirpath, src)
+ for d in dirnames:
+ out.append({"path": os.path.normpath(os.path.join(rel_dir, d)), "dir": True, "bytes": 0, "mtime": 0})
+ for f in sorted(filenames):
+ full = os.path.join(dirpath, f)
+ try:
+ st = os.lstat(full)
+ except OSError:
+ continue
+ out.append({"path": os.path.normpath(os.path.join(rel_dir, f)), "dir": False,
+ "bytes": int(st.st_size), "mtime": int(st.st_mtime),
+ **({"link": True} if stat.S_ISLNK(st.st_mode) else {})})
+ if len(out) >= TREE_MAX:
+ break
+ return out[:TREE_MAX]
+
+
+def source_stat(env_id: str) -> dict:
+ n = b = 0
+ for e in tree(env_id):
+ if not e["dir"]:
+ n += 1
+ b += e["bytes"]
+ return {"count": n, "bytes": b}
+
+
+def read_file(env_id: str, rel: str) -> tuple[bytes, str]:
+ p = _safe_rel(source_dir(env_id), rel)
+ if not p.is_file():
+ raise HTTPException(404, "no such file in the environment")
+ return p.read_bytes(), (mimetypes.guess_type(p.name)[0] or "application/octet-stream")
+
+
+def write_file(env_id: str, rel: str, data: bytes) -> dict:
+ src = source_dir(env_id)
+ src.mkdir(parents=True, exist_ok=True)
+ p = _safe_rel(src, rel)
+ if p.is_dir():
+ raise HTTPException(409, "a directory is at that path")
+ p.parent.mkdir(parents=True, exist_ok=True)
+ tmp = p.with_name(p.name + ".hr-tmp")
+ tmp.write_bytes(data)
+ os.replace(tmp, p)
+ return {"path": rel.strip("/"), "bytes": len(data)}
+
+
+def make_dir(env_id: str, rel: str) -> dict:
+ src = source_dir(env_id)
+ src.mkdir(parents=True, exist_ok=True)
+ p = _safe_rel(src, rel)
+ p.mkdir(parents=True, exist_ok=True)
+ return {"path": rel.strip("/"), "dir": True}
+
+
+def delete_path(env_id: str, rel: str) -> dict:
+ p = _safe_rel(source_dir(env_id), rel)
+ if p.is_dir() and not p.is_symlink():
+ shutil.rmtree(p)
+ elif p.exists() or p.is_symlink():
+ p.unlink()
+ else:
+ raise HTTPException(404, "nothing at that path")
+ return {"path": rel.strip("/"), "deleted": True}
+
+
+def _members_zip(zf: zipfile.ZipFile) -> list[tuple[str, bool, int]]:
+ return [(i.filename, i.is_dir(), i.file_size) for i in zf.infolist()]
+
+
+def _strip_common_root(names: list[str]) -> str:
+ """GitHub's archives and most folder zips wrap everything in one directory; the project is
+ what is inside it. The common first segment, when EVERY entry has the same one and nothing sits
+ beside it, is stripped."""
+ firsts = {n.split("/", 1)[0] for n in names if n.strip("/")}
+ if len(firsts) == 1:
+ root = next(iter(firsts))
+ if all(n == root or n == root + "/" or n.startswith(root + "/") for n in names if n.strip("/")):
+ return root + "/"
+ return ""
+
+
+def _member_ok(name: str) -> str | None:
+ """The relative path a member may land at, or None for one that must not land at all."""
+ n = name.replace("\\", "/")
+ if n.startswith("/") or any(part in ("..", "") for part in n.strip("/").split("/") if n.strip("/")):
+ return None
+ return n.strip("/")
+
+
+def import_archive(env_id: str, data_path: str, *, replace: bool = False) -> dict:
+ """Extract a zip or tar archive into the source. Only regular files and directories land:
+ symlinks, hard links, devices and any member that names a path outside the source are
+ dropped and counted, never written. A single wrapping directory is stripped."""
+ src = source_dir(env_id)
+ if replace and src.exists():
+ shutil.rmtree(src)
+ src.mkdir(parents=True, exist_ok=True)
+ written = skipped = 0
+ if zipfile.is_zipfile(data_path):
+ with zipfile.ZipFile(data_path) as zf:
+ names = [i.filename for i in zf.infolist()]
+ root = _strip_common_root(names)
+ for info in zf.infolist():
+ rel = _member_ok(info.filename)
+ if rel is None or (root and not (rel + "/").startswith(root)):
+ skipped += 1
+ continue
+ rel = rel[len(root):] if root else rel
+ if not rel:
+ continue
+ mode = (info.external_attr >> 16) & 0xFFFF
+ if stat.S_ISLNK(mode):
+ skipped += 1
+ continue
+ dest = _safe_rel(src, rel)
+ if info.is_dir():
+ dest.mkdir(parents=True, exist_ok=True)
+ continue
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ with zf.open(info) as fin, open(dest, "wb") as fout:
+ shutil.copyfileobj(fin, fout)
+ if mode & 0o111:
+ os.chmod(dest, 0o755)
+ written += 1
+ elif tarfile.is_tarfile(data_path):
+ with tarfile.open(data_path) as tf:
+ members = tf.getmembers()
+ root = _strip_common_root([m.name for m in members])
+ for m in members:
+ rel = _member_ok(m.name)
+ if rel is None or (root and not (rel + "/").startswith(root)):
+ skipped += 1
+ continue
+ rel = rel[len(root):] if root else rel
+ if not rel:
+ continue
+ if not (m.isreg() or m.isdir()):
+ skipped += 1
+ continue
+ dest = _safe_rel(src, rel)
+ if m.isdir():
+ dest.mkdir(parents=True, exist_ok=True)
+ continue
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ fin = tf.extractfile(m)
+ if fin is None:
+ skipped += 1
+ continue
+ with fin, open(dest, "wb") as fout:
+ shutil.copyfileobj(fin, fout)
+ if m.mode & 0o111:
+ os.chmod(dest, 0o755)
+ written += 1
+ else:
+ raise HTTPException(400, "the upload is neither a zip nor a tar archive")
+ return {"written": written, "skipped": skipped, **source_stat(env_id)}
+
+
+def import_git(env_id: str, url: str, ref: str = "", *, replace: bool = False) -> dict:
+ """Clone a repository's tree (shallow, one ref) into the source, without its .git."""
+ if not str(url).startswith(("https://", "http://", "git@", "ssh://")):
+ raise HTTPException(400, "git url must be https://, http://, ssh:// or git@")
+ with tempfile.TemporaryDirectory(prefix="hr-env-git-") as tmp:
+ cmd = ["git", "clone", "--depth", "1", "--quiet"] + (["--branch", ref] if ref else []) + [url, tmp + "/repo"]
+ try:
+ subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=600,
+ env={**os.environ, "GIT_TERMINAL_PROMPT": "0"})
+ except subprocess.CalledProcessError as e:
+ raise HTTPException(400, f"git clone failed: {(e.stderr or '')[-400:].strip()}")
+ except subprocess.TimeoutExpired:
+ raise HTTPException(504, "git clone did not finish in 10 minutes")
+ shutil.rmtree(tmp + "/repo/.git", ignore_errors=True)
+ src = source_dir(env_id)
+ if replace and src.exists():
+ shutil.rmtree(src)
+ src.mkdir(parents=True, exist_ok=True)
+ shutil.copytree(tmp + "/repo", src, dirs_exist_ok=True, symlinks=False)
+ return {"imported": "git", "url": url, "ref": ref, **source_stat(env_id)}
+
+
+# ── builds ──────────────────────────────────────────────────────────────────────────────────────
+def build_record(env_id: str, n: int) -> dict | None:
+ p = version_dir(env_id, n) / ".hr-build.json"
+ try:
+ return json.loads(p.read_text())
+ except (OSError, ValueError):
+ return None
+
+
+def versions(env_id: str) -> list[dict]:
+ root = env_dir(env_id) / "versions"
+ out = []
+ if root.is_dir():
+ for e in sorted(root.iterdir(), key=lambda x: int(x.name) if x.name.isdigit() else 0):
+ if e.name.isdigit():
+ rec = build_record(env_id, int(e.name)) or {"version": int(e.name), "status": "unknown"}
+ out.append({k: rec.get(k) for k in ("version", "status", "started_at", "finished_at", "error", "files", "bytes")
+ } | {"packages": len(rec.get("packages") or [])})
+ return out
+
+
+def active_version(env_id: str) -> int | None:
+ try:
+ target = os.readlink(active_link(env_id))
+ except OSError:
+ return None
+ name = os.path.basename(target.rstrip("/"))
+ return int(name) if name.isdigit() else None
+
+
+def _tool_env() -> dict:
+ """The environment the build's commands run in: the runner's own (the image's toolchain, the
+ same python3 and node an agent gets), minus anything secret-shaped, with caches kept out of
+ the layer."""
+ from server import _child_env # the same scrub agents get; imported late to avoid a cycle
+ env = _child_env()
+ env["PIP_NO_CACHE_DIR"] = "1"
+ env["PIP_DISABLE_PIP_VERSION_CHECK"] = "1"
+ env["npm_config_fund"] = env["npm_config_audit"] = "false"
+ env["npm_config_update_notifier"] = "false"
+ return env
+
+
+def _run(log: list[str], cmd: list[str], cwd: str, env: dict, deadline: float) -> None:
+ left = max(1, int(deadline - time.time()))
+ log.append(f"$ {' '.join(cmd)}")
+ try:
+ r = subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True, timeout=left)
+ except subprocess.TimeoutExpired:
+ raise RuntimeError(f"{cmd[0]} did not finish within the build's {BUILD_TIMEOUT}s")
+ if r.stdout.strip():
+ log.append(r.stdout.rstrip()[-20000:])
+ if r.stderr.strip():
+ log.append(r.stderr.rstrip()[-20000:])
+ if r.returncode != 0:
+ raise RuntimeError(f"{cmd[0]} exited {r.returncode}")
+
+
+def _packages(dst: pathlib.Path, env: dict) -> list[dict]:
+ out: list[dict] = []
+ pip = dst / ".venv" / "bin" / "pip"
+ if pip.is_file():
+ try:
+ r = subprocess.run([str(pip), "list", "--format=json"], capture_output=True, text=True, timeout=120, env=env)
+ for row in json.loads(r.stdout or "[]"):
+ out.append({"manager": "pip", "name": str(row.get("name")), "version": str(row.get("version"))})
+ except (OSError, ValueError, subprocess.TimeoutExpired):
+ pass
+ if (dst / "node_modules").is_dir():
+ try:
+ r = subprocess.run(["npm", "ls", "--json", "--depth=0"], cwd=str(dst), capture_output=True, text=True,
+ timeout=120, env=env)
+ deps = (json.loads(r.stdout or "{}") or {}).get("dependencies") or {}
+ for name, info in sorted(deps.items()):
+ out.append({"manager": "npm", "name": name, "version": str((info or {}).get("version") or "")})
+ except (OSError, ValueError, subprocess.TimeoutExpired):
+ pass
+ return out
+
+
+def _read_only(dst: pathlib.Path) -> None:
+ """Root's, readable by everyone, writable by nobody else: directories 755, files keep their
+ execute bits and lose group/other write."""
+ for dirpath, dirnames, filenames in os.walk(dst):
+ try:
+ os.chmod(dirpath, 0o755)
+ except OSError:
+ pass
+ for f in filenames:
+ p = os.path.join(dirpath, f)
+ try:
+ st = os.lstat(p)
+ if stat.S_ISLNK(st.st_mode):
+ continue
+ os.chmod(p, 0o755 if st.st_mode & 0o111 else 0o644)
+ except OSError:
+ continue
+
+
+def _size(dst: pathlib.Path) -> tuple[int, int]:
+ n = b = 0
+ for dirpath, _, filenames in os.walk(dst):
+ for f in filenames:
+ try:
+ st = os.lstat(os.path.join(dirpath, f))
+ except OSError:
+ continue
+ if stat.S_ISREG(st.st_mode):
+ n += 1
+ b += st.st_size
+ return n, b
+
+
+def _write_record(dst: pathlib.Path, rec: dict) -> None:
+ dst.mkdir(parents=True, exist_ok=True)
+ rec = dict(rec)
+ if isinstance(rec.get("log"), list):
+ text = "\n".join(rec["log"])
+ rec["log"] = text[-LOG_MAX:] if len(text) > LOG_MAX else text
+ tmp = dst / ".hr-build.json.tmp"
+ tmp.write_text(json.dumps(rec, indent=1))
+ os.replace(tmp, dst / ".hr-build.json")
+
+
+def _build(env_id: str, n: int, slug: str, activate: bool) -> None:
+ src, dst = source_dir(env_id), version_dir(env_id, n)
+ started = int(time.time())
+ log: list[str] = []
+ rec = {"version": n, "status": "building", "started_at": started, "finished_at": None, "error": "",
+ "packages": [], "files": 0, "bytes": 0, "log": log}
+ try:
+ if dst.exists():
+ shutil.rmtree(dst)
+ _write_record(dst, rec)
+ deadline = time.time() + BUILD_TIMEOUT
+ env = _tool_env()
+ log.append(f"copying the project ({source_stat(env_id)['count']} files)")
+ shutil.copytree(src, dst, symlinks=False, dirs_exist_ok=True,
+ ignore=lambda d, names: [x for x in names if x in NOT_COPIED])
+ with tempfile.TemporaryDirectory(prefix="hr-env-build-") as scratch:
+ env["HOME"] = env["TMPDIR"] = scratch
+ env["npm_config_cache"] = os.path.join(scratch, "npm-cache")
+ if (dst / "requirements.txt").is_file() or (dst / "pyproject.toml").is_file():
+ python = shutil.which("python3", path=env.get("PATH")) or "python3"
+ _run(log, [python, "-m", "venv", ".venv"], str(dst), env, deadline)
+ pip = str(dst / ".venv" / "bin" / "pip")
+ if (dst / "requirements.txt").is_file():
+ _run(log, [pip, "install", "-r", "requirements.txt"], str(dst), env, deadline)
+ if (dst / "pyproject.toml").is_file():
+ _run(log, [pip, "install", "."], str(dst), env, deadline)
+ if (dst / "package.json").is_file():
+ npm = shutil.which("npm", path=env.get("PATH")) or "npm"
+ _run(log, [npm, "ci" if (dst / "package-lock.json").is_file() else "install", "--no-audit", "--no-fund"],
+ str(dst), env, deadline)
+ if (dst / "setup.sh").is_file():
+ _run(log, ["bash", "setup.sh"], str(dst), {**env, "ENV_ROOT": str(dst)}, deadline)
+ rec["packages"] = _packages(dst, env)
+ _read_only(dst)
+ rec["files"], rec["bytes"] = _size(dst)
+ rec["status"], rec["finished_at"] = "ready", int(time.time())
+ log.append(f"ready: {rec['files']} files, {len(rec['packages'])} packages, {int(time.time()) - started}s")
+ _write_record(dst, rec)
+ if activate:
+ activate_version(env_id, n, slug)
+ except Exception as e: # noqa: BLE001 — the record IS the report; nothing else sees this thread
+ rec["status"], rec["finished_at"], rec["error"] = "failed", int(time.time()), str(e)[:500]
+ log.append(f"failed: {e}")
+ try:
+ _write_record(dst, rec)
+ except OSError:
+ pass
+ finally:
+ with _builds_lock:
+ _builds.pop(f"{env_id}:{n}", None)
+
+
+def start_build(env_id: str, n: int, slug: str, activate: bool = True) -> dict:
+ if not source_dir(env_id).is_dir():
+ raise HTTPException(409, "the environment has no files yet")
+ key = f"{env_id}:{n}"
+ with _builds_lock:
+ if key in _builds and _builds[key].is_alive():
+ raise HTTPException(409, "that version is already building")
+ for k, t in _builds.items():
+ if k.startswith(env_id + ":") and t.is_alive():
+ raise HTTPException(409, "another version of this environment is building")
+ t = threading.Thread(target=_build, args=(env_id, n, slug, activate), daemon=True, name=f"env-build-{key}")
+ _builds[key] = t
+ t.start()
+ return {"version": n, "status": "building"}
+
+
+def activate_version(env_id: str, n: int, slug: str) -> dict:
+ dst = version_dir(env_id, n)
+ rec = build_record(env_id, n)
+ if not dst.is_dir() or not rec or rec.get("status") != "ready":
+ raise HTTPException(409, f"version {n} is not a finished build")
+ link = active_link(env_id)
+ tmp = link.with_name("active.tmp")
+ if tmp.is_symlink() or tmp.exists():
+ tmp.unlink()
+ os.symlink(os.path.join("versions", str(n)), tmp)
+ os.replace(tmp, link) # atomic: a session mid-turn sees the old or the new, never neither
+ ensure_mount(env_id, slug)
+ return {"version": n, "status": "ready", "path": mount_path(slug)}
+
+
+def ensure_mount(env_id: str, slug: str) -> str:
+ """The path sessions are told, as a link to the environment's active version. Created on the
+ container's rootfs, so it is remade after a restart; idempotent."""
+ if not slug_ok(slug):
+ raise HTTPException(400, "environment slug is not a path segment")
+ if active_version(env_id) is None:
+ raise HTTPException(409, "the environment has no built version")
+ os.makedirs(ENV_MOUNT, mode=0o755, exist_ok=True)
+ try:
+ os.chmod(ENV_MOUNT, 0o755)
+ except OSError:
+ pass
+ target = str(active_link(env_id))
+ link = mount_path(slug)
+ try:
+ if os.readlink(link) == target:
+ return link
+ except OSError:
+ pass
+ tmp = link + ".tmp"
+ if os.path.lexists(tmp):
+ os.unlink(tmp)
+ os.symlink(target, tmp)
+ os.replace(tmp, link)
+ return link
+
+
+def drop_mount(slug: str) -> None:
+ link = mount_path(slug)
+ if os.path.islink(link):
+ os.unlink(link)
+
+
+def delete_environment(env_id: str, slug: str = "") -> dict:
+ if slug:
+ drop_mount(slug)
+ d = env_dir(env_id)
+ if d.exists():
+ shutil.rmtree(d, ignore_errors=True)
+ return {"id": env_id, "deleted": True}
+
+
+# ── the turn ────────────────────────────────────────────────────────────────────────────────────
+def resolve(spec: dict | None) -> dict | None:
+ """What a turn's environment is on this box: the link at the path the agent is told (made if
+ the container restarted), the version behind it, the entry the owner declared. None when the
+ turn has no environment; 409 when the environment has nothing built."""
+ if not spec:
+ return None
+ env_id, slug = _check_id(spec.get("id")), str(spec.get("slug") or "")
+ link = ensure_mount(env_id, slug)
+ if not pathlib.Path(link).resolve().is_dir():
+ raise HTTPException(409, "the environment's active version is missing on disk")
+ return {"id": env_id, "slug": slug, "path": link, "version": active_version(env_id),
+ "entry": str(spec.get("entry") or "")}
+
+
+def apply_env(env: dict, applied: dict | None) -> None:
+ """The variables that make the layer's interpreter and packages the ones an agent runs:
+ PROJECT_ROOT, the venv first on PATH (so `python3` is the venv's), the project on PYTHONPATH
+ (so `from scripts.lib import x` works from anywhere), node_modules on NODE_PATH."""
+ if not applied:
+ return
+ link = applied["path"]
+ real = pathlib.Path(link).resolve()
+ env["PROJECT_ROOT"] = link
+ env["HR_ENVIRONMENT"] = link
+ env["PYTHONPATH"] = link + (":" + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
+ path_add = []
+ if (real / ".venv" / "bin").is_dir():
+ path_add.append(os.path.join(link, ".venv", "bin"))
+ env["VIRTUAL_ENV"] = os.path.join(link, ".venv")
+ if (real / "node_modules" / ".bin").is_dir():
+ path_add.append(os.path.join(link, "node_modules", ".bin"))
+ if (real / "node_modules").is_dir():
+ env["NODE_PATH"] = os.path.join(link, "node_modules") + (":" + env["NODE_PATH"] if env.get("NODE_PATH") else "")
+ if path_add:
+ env["PATH"] = ":".join(path_add + [env.get("PATH", "")])
+
+
+def apply_to_turn(env: dict, spec: dict | None) -> dict | None:
+ """resolve + apply_env in one call, for a caller that has no doc to write first."""
+ applied = resolve(spec)
+ apply_env(env, applied)
+ return applied
+
+
+def doc_section(applied: dict | None) -> list[str]:
+ """The lines the agent's instruction file carries for its environment: where the project is,
+ that it is read-only and shared, where to write, and how it is run when the owner said."""
+ if not applied:
+ return []
+ path = applied["path"]
+ lines = ["## Project environment", "",
+ f"The project `{applied['slug']}` is at `{path}` (also `$PROJECT_ROOT`). It is READ-ONLY and shared "
+ "with other sessions: its files are complete and its dependencies are already installed "
+ "(its Python virtualenv and node_modules are on your PATH; `python3` and `node` from your "
+ "shell use them), so do not install packages or copy the project to start. Do not try to "
+ "write under it: write every output, log and scratch file to your working directory, and "
+ "copy a project file there first if you need to change it. Run the project's scripts by "
+ f"their absolute path (for example `python3 {path}/<script>.py`) with your working directory "
+ "as the current directory, so relative outputs land where the user sees them."]
+ if applied.get("entry"):
+ lines += ["", f"How the project is run: `{applied['entry']}`"]
+ lines.append("")
+ return lines
+
+
+# ── routes (internal: the gateway drives these; the write-wall middleware in server.py guards them) ──
[email protected]("/environments/{env_id}/tree")
+def r_tree(env_id: str) -> dict:
+ return {"entries": tree(env_id), **source_stat(env_id)}
+
+
[email protected]("/environments/{env_id}/source")
+def r_read(env_id: str, path: str) -> Response:
+ data, ctype = read_file(env_id, path)
+ return Response(content=data, media_type=ctype)
+
+
[email protected]("/environments/{env_id}/source")
+async def r_write(env_id: str, path: str, request: Request) -> dict:
+ return write_file(env_id, path, await request.body())
+
+
[email protected]("/environments/{env_id}/mkdir")
+def r_mkdir(env_id: str, path: str) -> dict:
+ return make_dir(env_id, path)
+
+
[email protected]("/environments/{env_id}/source")
+def r_delete(env_id: str, path: str) -> dict:
+ return delete_path(env_id, path)
+
+
[email protected]("/environments/{env_id}/import")
+async def r_import(env_id: str, request: Request, replace: int = 0, git_url: str = "", git_ref: str = "") -> dict:
+ if git_url:
+ return import_git(env_id, git_url, git_ref, replace=bool(replace))
+ fd, spool = tempfile.mkstemp(prefix="hr-env-import-")
+ try:
+ with os.fdopen(fd, "wb") as out:
+ async for chunk in request.stream():
+ if chunk:
+ out.write(chunk)
+ return import_archive(env_id, spool, replace=bool(replace))
+ finally:
+ try:
+ os.unlink(spool)
+ except OSError:
+ pass
+
+
[email protected]("/environments/{env_id}/build")
+def r_build(env_id: str, version: int, slug: str, activate: int = 1) -> dict:
+ if not slug_ok(slug):
+ raise HTTPException(400, "environment slug is not a path segment")
+ return start_build(env_id, int(version), slug, bool(activate))
+
+
[email protected]("/environments/{env_id}/build")
+def r_build_status(env_id: str, version: int) -> dict:
+ rec = build_record(env_id, int(version))
+ if not rec:
+ raise HTTPException(404, "no such build")
+ return rec
+
+
[email protected]("/environments/{env_id}/versions")
+def r_versions(env_id: str) -> dict:
+ return {"versions": versions(env_id), "active": active_version(env_id)}
+
+
[email protected]("/environments/{env_id}/activate")
+def r_activate(env_id: str, version: int, slug: str) -> dict:
+ return activate_version(env_id, int(version), slug)
+
+
[email protected]("/environments/{env_id}")
+def r_delete_env(env_id: str, slug: str = "") -> dict:
+ return delete_environment(env_id, slug)
+
+
[email protected]("/environments/{env_id}")
+def r_get(env_id: str) -> JSONResponse:
+ return JSONResponse({"id": env_id, "source": source_stat(env_id), "versions": versions(env_id),
+ "active": active_version(env_id), "root": ENV_ROOT})
diff --git a/runner/server.py b/runner/server.py
index 6d1bc6fb..13089d7a 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -73,7 +73,10 @@ from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
+import environments # the read-only project layer a turn may name (runner/environments.py)
+
app = FastAPI(title="harness-runner")
+app.include_router(environments.router)
WORKSPACE_ROOT = os.environ.get("HARNESS_WORKSPACE", "/workspace")
# Session ids are opaque to us and arrive over the wire, so they are sanitized before becoming a
@@ -1335,7 +1338,8 @@ def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:
else "CLAUDE.md")
-def _write_agent_doc(cwd: str, backend: str, agent_doc: str | None, skills_meta: list[dict]) -> None:
+def _write_agent_doc(cwd: str, backend: str, agent_doc: str | None, skills_meta: list[dict],
+ environment: dict | None = None) -> None:
"""Compose the agent's instruction file from (1) the harness's user-authored doc and (2) a managed
block: the workspace contract, always, plus an 'Available skills' section when skills are
installed. The user doc is the base; the managed block is appended inside HTML-comment markers.
@@ -1359,6 +1363,7 @@ def _write_agent_doc(cwd: str, backend: str, agent_doc: str | None, skills_meta:
"under it. Never write output to an absolute path outside it (/tmp, /app, the "
"workspace parent directory, or your home directory): those files are not collected, "
"and the user will never see them.", ""]
+ lines += environments.doc_section(environment)
if skills_meta:
lines += ["## Available skills", "",
"These skills are installed in this workspace. When a task matches one, read its "
@@ -7625,6 +7630,7 @@ class TurnReq(BaseModel):
vision: bool = True # pi: whether the model's channel accepts image input
vision_auth: dict | None = None # hermes: {provider, model, base_url, api_key} for its image questions
codex_appserver: bool = False # codex: run via app-server (streams item/agentMessage/delta)
+ environment: dict | None = None # {id, slug, entry}: the project layer at /env/<slug>, read-only (environments.py)
@app.post("/turn")
@@ -7697,7 +7703,8 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
if _off:
agent_doc = ((agent_doc + "\n\n") if agent_doc.strip() else "") + \
f"## Disabled tools\n\nDo NOT use these tools — they are disabled for this harness: {_off}."
- _write_agent_doc(cwd, backend, agent_doc, installed_skills)
+ turn_environment = environments.resolve(req.environment) # 409 when nothing is built: before any process starts
+ _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).
env = {**_caller_env(req.env), **_child_env()}
@@ -7740,6 +7747,7 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
# opaque UnknownError. Proven by env bisection on a live failure: with 40 inherited variables,
# removing or correcting PWD alone flips the turn from failing to passing.
env["PWD"] = cwd
+ environments.apply_env(env, turn_environment)
auth = _adapt_custom_auth(req.auth or Auth())
model = req.model or spec["default_model"]
use_appserver = backend == "codex" and bool(req.codex_appserver)
diff --git a/runner/tests/test_environments.py b/runner/tests/test_environments.py
new file mode 100644
index 00000000..9c6434c8
--- /dev/null
+++ b/runner/tests/test_environments.py
@@ -0,0 +1,164 @@
+"""Environments (runner/environments.py): the source a person edits, an archive import that keeps
+the tree and drops what must not land, a build that snapshots the source and installs what the
+manifests declare, versions with an atomic active pointer, the mount link sessions are told, and
+the variables and instructions a turn gets."""
+import io
+import json
+import os
+import pathlib
+import stat
+import sys
+import tarfile
+import time
+import zipfile
+
+import pytest
+from fastapi import HTTPException
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import environments as E # noqa: E402
+
+
+def store(tmp_path, monkeypatch):
+ monkeypatch.setattr(E, "ENV_ROOT", str(tmp_path / "environments"))
+ monkeypatch.setattr(E, "ENV_MOUNT", str(tmp_path / "env"))
+ return tmp_path
+
+
+def test_source_files_round_trip_and_the_tree_counts_them(store):
+ E.write_file("henv_a", "scripts/render.py", b"print('hi')\n")
+ E.write_file("henv_a", "config.yaml", b"a: 1\n")
+ E.make_dir("henv_a", "assets/brand")
+ data, ctype = E.read_file("henv_a", "scripts/render.py")
+ assert data == b"print('hi')\n" and ctype.startswith("text/")
+ t = E.tree("henv_a")
+ assert {e["path"] for e in t if e["dir"]} == {"assets", "assets/brand", "scripts"}
+ assert {e["path"] for e in t if not e["dir"]} == {"scripts/render.py", "config.yaml"}
+ assert E.source_stat("henv_a") == {"count": 2, "bytes": 17}
+ E.delete_path("henv_a", "scripts")
+ assert {e["path"] for e in E.tree("henv_a")} == {"assets", "assets/brand", "config.yaml"}
+
+
+def test_a_path_out_of_the_source_is_refused(store):
+ E.write_file("henv_a", "ok.txt", b"x")
+ for bad in ("../x", "/etc/passwd", "a/../../x", ".", ""):
+ with pytest.raises(HTTPException) as e:
+ E.write_file("henv_a", bad, b"x")
+ assert e.value.status_code == 400
+ with pytest.raises(HTTPException):
+ E.read_file("henv_a", "../ok.txt")
+ with pytest.raises(HTTPException):
+ E._check_id("../henv")
+
+
+def test_import_strips_one_wrapping_directory_and_drops_escapes_and_links(store, tmp_path):
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("proj-main/run.py", "print(1)\n")
+ zf.writestr("proj-main/scripts/lib/util.py", "x = 1\n")
+ zf.writestr("proj-main/../evil.txt", "no")
+ info = zipfile.ZipInfo("proj-main/link")
+ info.external_attr = (stat.S_IFLNK | 0o777) << 16
+ zf.writestr(info, "/etc/passwd")
+ p = tmp_path / "up.zip"
+ p.write_bytes(buf.getvalue())
+ out = E.import_archive("henv_z", str(p))
+ assert out["written"] == 2 and out["skipped"] == 2
+ assert {e["path"] for e in E.tree("henv_z") if not e["dir"]} == {"run.py", "scripts/lib/util.py"}
+ assert not (E.source_dir("henv_z") / "link").exists()
+ # a tarball with no wrapper keeps its top level; replace= wipes what was there
+ t = tmp_path / "up.tgz"
+ with tarfile.open(t, "w:gz") as tf:
+ for name, text in (("a.txt", "A"), ("d/b.txt", "B")):
+ ti = tarfile.TarInfo(name); data = text.encode(); ti.size = len(data)
+ tf.addfile(ti, io.BytesIO(data))
+ ti = tarfile.TarInfo("d/ln"); ti.type = tarfile.SYMTYPE; ti.linkname = "../../x"
+ tf.addfile(ti)
+ out = E.import_archive("henv_z", str(t), replace=True)
+ assert out["written"] == 2 and out["skipped"] == 1
+ assert {e["path"] for e in E.tree("henv_z") if not e["dir"]} == {"a.txt", "d/b.txt"}
+
+
+def _wait(env_id, n, timeout=240):
+ for _ in range(timeout * 4):
+ rec = E.build_record(env_id, n)
+ if rec and rec["status"] in ("ready", "failed"):
+ return rec
+ time.sleep(0.25)
+ raise AssertionError("build did not finish")
+
+
+def test_a_build_snapshots_the_source_installs_and_becomes_the_active_read_only_layer(store):
+ E.write_file("henv_b", "scripts/render.py", b"import sys\nprint(sys.prefix)\n")
+ E.write_file("henv_b", "requirements.txt", b"") # a venv with nothing in it: no network needed
+ E.write_file("henv_b", "node_modules/left/over.js", b"//") # never copied: the build installs its own
+ E.write_file("henv_b", "run.sh", b"#!/bin/sh\necho run\n")
+ os.chmod(E.source_dir("henv_b") / "run.sh", 0o755)
+ E.start_build("henv_b", 1, "content-studio")
+ rec = _wait("henv_b", 1)
+ assert rec["status"] == "ready", rec["log"]
+ v1 = E.version_dir("henv_b", 1)
+ assert (v1 / "scripts" / "render.py").is_file() and not (v1 / "node_modules").exists()
+ assert (v1 / ".venv" / "bin" / "python3").exists() or (v1 / ".venv" / "bin" / "python").exists()
+ assert any(p["manager"] == "pip" and p["name"] == "pip" for p in rec["packages"])
+ assert rec["files"] > 3 and rec["bytes"] > 0
+ assert oct(os.stat(v1 / "scripts" / "render.py").st_mode & 0o777) == "0o644"
+ assert oct(os.stat(v1 / "run.sh").st_mode & 0o777) == "0o755"
+ assert oct(os.stat(v1).st_mode & 0o777) == "0o755"
+ assert E.active_version("henv_b") == 1
+ link = E.mount_path("content-studio")
+ assert os.path.islink(link) and pathlib.Path(link).resolve() == v1.resolve()
+ assert E.versions("henv_b")[0]["version"] == 1 and E.versions("henv_b")[0]["status"] == "ready"
+ # the source changes; sessions keep seeing the build until the next one
+ E.write_file("henv_b", "scripts/render.py", b"print('v2')\n")
+ assert (v1 / "scripts" / "render.py").read_bytes() == b"import sys\nprint(sys.prefix)\n"
+ E.start_build("henv_b", 2, "content-studio")
+ assert _wait("henv_b", 2)["status"] == "ready"
+ assert E.active_version("henv_b") == 2 and pathlib.Path(link).resolve() == E.version_dir("henv_b", 2).resolve()
+ # rollback is the pointer, nothing is rebuilt
+ E.activate_version("henv_b", 1, "content-studio")
+ assert E.active_version("henv_b") == 1 and pathlib.Path(link).resolve() == v1.resolve()
+ with pytest.raises(HTTPException):
+ E.activate_version("henv_b", 9, "content-studio")
+ E.delete_environment("henv_b", "content-studio")
+ assert not E.env_dir("henv_b").exists() and not os.path.lexists(link)
+
+
+def test_a_failed_build_records_why_and_never_becomes_active(store):
+ E.write_file("henv_f", "setup.sh", b"#!/bin/sh\necho preparing\nexit 3\n")
+ E.start_build("henv_f", 1, "broken")
+ rec = _wait("henv_f", 1)
+ assert rec["status"] == "failed" and "exited 3" in rec["error"] and "preparing" in rec["log"]
+ assert E.active_version("henv_f") is None
+ with pytest.raises(HTTPException) as e:
+ E.resolve({"id": "henv_f", "slug": "broken"})
+ assert e.value.status_code == 409
+
+
+def test_the_turn_gets_the_path_the_variables_and_the_instructions(store):
+ E.write_file("henv_t", "requirements.txt", b"")
+ E.write_file("henv_t", "package.json", json.dumps({"name": "p", "version": "1.0.0", "private": True}).encode())
+ E.start_build("henv_t", 1, "studio")
+ rec = _wait("henv_t", 1)
+ assert rec["status"] == "ready", rec["log"]
+ applied = E.resolve({"id": "henv_t", "slug": "studio", "entry": "python3 run.py"})
+ link = E.mount_path("studio")
+ assert applied == {"id": "henv_t", "slug": "studio", "path": link, "version": 1, "entry": "python3 run.py"}
+ env = {"PATH": "/usr/bin", "NODE_PATH": "/tools/node_modules"}
+ E.apply_env(env, applied)
+ assert env["PROJECT_ROOT"] == link and env["PYTHONPATH"] == link
+ assert env["PATH"].startswith(link + "/.venv/bin:") and env["PATH"].endswith(":/usr/bin")
+ assert env["VIRTUAL_ENV"] == link + "/.venv"
+ if (pathlib.Path(link) / "node_modules").is_dir(): # npm made one even with no dependencies
+ assert env["NODE_PATH"].startswith(link + "/node_modules:")
+ doc = "\n".join(E.doc_section(applied))
+ assert "## Project environment" in doc and link in doc and "READ-ONLY" in doc and "python3 run.py" in doc
+ assert E.doc_section(None) == []
+ # the mount link survives a restart: remade from the store when it is gone
+ os.unlink(link)
+ assert E.resolve({"id": "henv_t", "slug": "studio"})["path"] == link and os.path.islink(link)
+
+
+def test_the_slug_is_a_path_segment(store):
+ assert E.slug_ok("content-studio") and E.slug_ok("a.b_c") and not E.slug_ok("../x") and not E.slug_ok("a/b") and not E.slug_ok("")
diff --git a/ui/src/app/(app)/environments/[id]/page.tsx b/ui/src/app/(app)/environments/[id]/page.tsx
new file mode 100644
index 00000000..c4ecfad2
--- /dev/null
+++ b/ui/src/app/(app)/environments/[id]/page.tsx
@@ -0,0 +1,321 @@
+'use client';
+// One environment, from Richard's console design (2026-09-28): a white head with the back link
+// and the name; a card with two tabs, Project files (a tree with folder counts, find-a-file, new
+// file / new folder / upload, and the file open beside it with line numbers) and Packages (what
+// the active build installed). Above the card, what the service knows: status, version, mount,
+// the Harnesses that read it, and the actions: build, import, rename, delete. Nothing here is
+// derived on the client; every count and status is the service's.
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useParams, useRouter } from 'next/navigation';
+import { SkelPage } from '@/components/Skel';
+import {
+ activateEnvironmentVersion, buildEnvironment, deleteEnvironment, deleteEnvironmentPath, environmentHarnesses,
+ fmtBytes, getEnvironment, getEnvironmentBuild, importEnvironmentArchive, importEnvironmentGit, listEnvironmentFiles,
+ makeEnvironmentDir, readEnvironmentFile, updateEnvironment, writeEnvironmentFile,
+ type Environment, type EnvironmentBuildRecord, type EnvironmentFileEntry,
+} from '@/lib/environments';
+
+const STATUS_LABEL: Record<Environment['status'], string> = { empty: 'Not built', building: 'Building', ready: 'Ready', failed: 'Build failed' };
+const STATUS_CLASS: Record<Environment['status'], string> = { empty: 'neutral', building: 'warn', ready: 'ok', failed: 'err' };
+
+type Node = { name: string; path: string; dir: boolean; bytes: number; children: Node[]; count: number };
+
+/** The flat listing as a tree, directories first, each directory counting the files under it. */
+function treeOf(entries: EnvironmentFileEntry[]): Node[] {
+ const root: Node = { name: '', path: '', dir: true, bytes: 0, children: [], count: 0 };
+ const byPath = new Map<string, Node>([['', root]]);
+ const ensure = (p: string, dir: boolean, bytes = 0): Node => {
+ const have = byPath.get(p);
+ if (have) return have;
+ const i = p.lastIndexOf('/');
+ const parent = ensure(i < 0 ? '' : p.slice(0, i), true);
+ const n: Node = { name: i < 0 ? p : p.slice(i + 1), path: p, dir, bytes, children: [], count: 0 };
+ parent.children.push(n); byPath.set(p, n);
+ return n;
+ };
+ for (const e of entries) ensure(e.path, e.dir, e.bytes);
+ const count = (n: Node): number => { n.count = n.dir ? n.children.reduce((a, c) => a + count(c), 0) : 1; return n.count; };
+ count(root);
+ const sort = (n: Node) => { n.children.sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name)); n.children.forEach(sort); };
+ sort(root);
+ return root.children;
+}
+
+export default function EnvironmentPage() {
+ const { id } = useParams<{ id: string }>();
+ const router = useRouter();
+ const [env, setEnv] = useState<Environment | null>(null);
+ const [entries, setEntries] = useState<EnvironmentFileEntry[] | null>(null);
+ const [harnesses, setHarnesses] = useState<{ id: string; name: string; base: string }[]>([]);
+ const [tab, setTab] = useState<'files' | 'packages'>('files');
+ const [q, setQ] = useState('');
+ const [open, setOpen] = useState<Set<string>>(new Set());
+ const [sel, setSel] = useState<string>(''); // the highlighted node: a file or a folder (where new files land)
+ const [openPath, setOpenPath] = useState<string>(''); // the file in the viewer; selecting a folder leaves it in place
+ const [file, setFile] = useState<{ text: string | null; bytes: number; type: string } | null>(null);
+ const [editing, setEditing] = useState<string | null>(null);
+ const [err, setErr] = useState('');
+ const [busy, setBusy] = useState('');
+ const [build, setBuild] = useState<EnvironmentBuildRecord | null>(null);
+ const [showLog, setShowLog] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const [renaming, setRenaming] = useState(false);
+ const [meta, setMeta] = useState({ name: '', description: '', entry: '' });
+ const [gitOpen, setGitOpen] = useState(false);
+ const [git, setGit] = useState({ url: '', ref: '', replace: false });
+ const [newPath, setNewPath] = useState<{ kind: 'file' | 'dir'; value: string } | null>(null);
+ const uploadRef = useRef<HTMLInputElement>(null);
+ const archiveRef = useRef<HTMLInputElement>(null);
+
+ const reload = useCallback(async () => {
+ try {
+ const [e, t, h] = await Promise.all([getEnvironment(id), listEnvironmentFiles(id), environmentHarnesses(id).catch(() => [])]);
+ setEnv(e); setEntries(t.entries); setHarnesses(h); setMeta({ name: e.name, description: e.description, entry: e.entry });
+ if (e.latestVersion) setBuild(await getEnvironmentBuild(id, e.latestVersion).catch(() => null));
+ } catch (e) { setErr(e instanceof Error ? e.message : 'The environment could not be read.'); }
+ }, [id]);
+ useEffect(() => { void reload(); }, [reload]);
+ useEffect(() => {
+ if (env?.status !== 'building') return;
+ const t = setInterval(() => void reload(), 3000);
+ return () => clearInterval(t);
+ }, [env?.status, reload]);
+
+ const tree = useMemo(() => treeOf(entries || []), [entries]);
+ const needle = q.trim().toLowerCase();
+ const matches = useMemo(() => (needle ? (entries || []).filter((e) => !e.dir && e.path.toLowerCase().includes(needle)) : []), [entries, needle]);
+
+ const openFile = async (path: string) => {
+ setSel(path); setOpenPath(path); setEditing(null);
+ try { setFile(await readEnvironmentFile(id, path)); } catch (e) { setFile(null); setErr(e instanceof Error ? e.message : 'The file could not be read.'); }
+ };
+ const toggle = (p: string) => setOpen((s) => { const n = new Set(s); if (n.has(p)) n.delete(p); else n.add(p); return n; });
+ const parentDir = () => { if (!sel) return ''; const e = (entries || []).find((x) => x.path === sel); if (e?.dir) return sel; const i = sel.lastIndexOf('/'); return i < 0 ? '' : sel.slice(0, i); };
+
+ const act = async (label: string, fn: () => Promise<unknown>) => {
+ setBusy(label); setErr('');
+ try { await fn(); await reload(); } catch (e) { setErr(e instanceof Error ? e.message : `${label} failed.`); }
+ finally { setBusy(''); }
+ };
+ const saveFile = () => act('save', async () => { if (editing === null) return; await writeEnvironmentFile(id, openPath, editing); setFile({ text: editing, bytes: new TextEncoder().encode(editing).length, type: file?.type || 'text/plain' }); setEditing(null); });
+ const createPath = () => act('create', async () => {
+ if (!newPath?.value.trim()) return;
+ const base = parentDir(); const p = (base ? base + '/' : '') + newPath.value.trim().replace(/^\/+/, '');
+ if (newPath.kind === 'dir') { await makeEnvironmentDir(id, p); setOpen((s) => new Set(s).add(p)); }
+ else { await writeEnvironmentFile(id, p, ''); setNewPath(null); await openFile(p); return; }
+ setNewPath(null);
+ });
+ const upload = (files: FileList | null) => act('upload', async () => {
+ if (!files?.length) return;
+ const base = parentDir();
+ for (const f of Array.from(files)) {
+ const rel = (f as File & { webkitRelativePath?: string }).webkitRelativePath || f.name;
+ await writeEnvironmentFile(id, (base ? base + '/' : '') + rel, f);
+ }
+ });
+ const importArchive = (files: FileList | null) => act('import', async () => { if (files?.[0]) await importEnvironmentArchive(id, files[0]); });
+ const importGit = () => act('import', async () => { if (!git.url.trim()) return; await importEnvironmentGit(id, git.url.trim(), git.ref.trim(), git.replace); setGitOpen(false); });
+ const remove = (p: string) => act('remove', async () => { await deleteEnvironmentPath(id, p); if (sel === p || sel.startsWith(p + '/')) setSel(''); if (openPath === p || openPath.startsWith(p + '/')) { setOpenPath(''); setFile(null); } });
+ const startBuild = () => act('build', async () => { await buildEnvironment(id); setTab('packages'); setShowLog(true); });
+ const activate = (n: number) => act('activate', () => activateEnvironmentVersion(id, n));
+ const saveMeta = () => act('rename', async () => { await updateEnvironment(id, meta); setRenaming(false); });
+ const destroy = () => act('delete', async () => { await deleteEnvironment(id); router.push('/environments'); });
+
+ if (!env && !err) return <SkelPage />;
+
+ const renderNode = (n: Node, depth: number): React.ReactNode => (
+ <div key={n.path}>
+ <div className={'env-node' + (sel === n.path ? ' is-selected' : '')} style={{ paddingLeft: 12 + depth * 14 }}
+ onClick={() => (n.dir ? (toggle(n.path), setSel(n.path)) : void openFile(n.path))}
+ onKeyDown={(ev) => { if (ev.key === 'Enter') { if (n.dir) toggle(n.path); else void openFile(n.path); } }} role="treeitem" tabIndex={0}
+ aria-expanded={n.dir ? open.has(n.path) : undefined}>
+ {n.dir ? <iconify-icon icon={open.has(n.path) ? 'tabler:chevron-down' : 'tabler:chevron-right'} className="env-chev"></iconify-icon> : <span className="env-chev" />}
+ <iconify-icon icon={n.dir ? 'tabler:folder' : 'tabler:file'}></iconify-icon>
+ <span className="env-node-name">{n.name}</span>
+ {n.dir && <span className="env-node-count">{n.count}</span>}
+ <button className="env-node-x" type="button" aria-label={`Remove ${n.name}`} title="Remove" onClick={(ev) => { ev.stopPropagation(); void remove(n.path); }}>
+ <iconify-icon icon="tabler:x"></iconify-icon></button>
+ </div>
+ {n.dir && open.has(n.path) && n.children.map((c) => renderNode(c, depth + 1))}
+ </div>
+ );
+
+ const lines = editing === null && file?.text !== null && file?.text !== undefined ? file.text.split('\n') : [];
+
+ return (
+ <section className="view is-active collection-view" id="view-environment">
+ <div className="env-head">
+ <a className="env-back" href="/environments"><iconify-icon icon="tabler:arrow-left"></iconify-icon>Environments</a>
+ {env && (
+ <div className="env-title-row">
+ {renaming ? (
+ <div className="env-rename">
+ <input value={meta.name} aria-label="Name" onChange={(ev) => setMeta({ ...meta, name: ev.target.value })} />
+ <input value={meta.description} placeholder="Description" aria-label="Description" onChange={(ev) => setMeta({ ...meta, description: ev.target.value })} />
+ <input value={meta.entry} placeholder="How it is run" aria-label="How it is run" onChange={(ev) => setMeta({ ...meta, entry: ev.target.value })} />
+ <button className="button primary small" type="button" disabled={busy === 'rename'} onClick={() => void saveMeta()}>Save</button>
+ <button className="button small" type="button" onClick={() => { setRenaming(false); setMeta({ name: env.name, description: env.description, entry: env.entry }); }}>Cancel</button>
+ </div>
+ ) : (
+ <h1>{env.name}</h1>
+ )}
+ <div className="env-actions">
+ <span className={'status ' + STATUS_CLASS[env.status]}>{STATUS_LABEL[env.status]}{env.version ? ` · v${env.version}` : ''}</span>
+ <button className="button primary" type="button" disabled={env.status === 'building' || busy === 'build' || !env.files.count}
+ title={!env.files.count ? 'Add files first' : 'Snapshot the files and install the packages they declare'} onClick={() => void startBuild()}>
+ <iconify-icon icon="tabler:hammer"></iconify-icon>{env.status === 'building' ? 'Building…' : env.version ? 'Rebuild' : 'Build'}</button>
+ <button className="button" type="button" onClick={() => archiveRef.current?.click()} disabled={busy === 'import'}><iconify-icon icon="tabler:file-zip"></iconify-icon>Import archive</button>
+ <input ref={archiveRef} type="file" hidden accept=".zip,.tar,.tgz,.tar.gz" onChange={(ev) => { void importArchive(ev.target.files); ev.target.value = ''; }} />
+ <button className="button" type="button" onClick={() => setGitOpen(true)}><iconify-icon icon="tabler:brand-git"></iconify-icon>Import from git</button>
+ <button className="button" type="button" onClick={() => setRenaming(true)}><iconify-icon icon="tabler:pencil"></iconify-icon>Rename</button>
+ {confirmDelete ? (
+ <span className="env-confirm">
+ <span>Delete every version and file?</span>
+ <button className="button danger small" type="button" disabled={busy === 'delete'} onClick={() => void destroy()}>Delete</button>
+ <button className="button small" type="button" onClick={() => setConfirmDelete(false)}>Keep</button>
+ </span>
+ ) : (
+ <button className="button" type="button" onClick={() => setConfirmDelete(true)}><iconify-icon icon="tabler:trash"></iconify-icon>Delete</button>
+ )}
+ </div>
+ </div>
+ )}
+ {env && (
+ <div className="env-facts">
+ <span><em>Path in every session</em><code>{env.mount}</code><span className="env-dim">read-only</span></span>
+ {env.entry && <span><em>Run with</em><code>{env.entry}</code></span>}
+ <span><em>Read by</em>{harnesses.length ? harnesses.map((h) => <a key={h.id} href={`/harnesses/${h.id}`}>{h.name}</a>) : <span className="env-dim">no Harness yet. Name it under a Harness&apos;s settings.</span>}</span>
+ {env.description && <span><em>About</em>{env.description}</span>}
+ </div>
+ )}
+ </div>
+
+ <div className="env-body">
+ {err && <div className="hr-error" role="alert">{err}</div>}
+ {env && (
+ <div className="env-card">
+ <div className="env-tabs" role="tablist">
+ <button type="button" role="tab" aria-selected={tab === 'files'} className={'env-tab' + (tab === 'files' ? ' is-on' : '')} onClick={() => setTab('files')}>Project files <span>{env.files.count}</span></button>
+ <button type="button" role="tab" aria-selected={tab === 'packages'} className={'env-tab' + (tab === 'packages' ? ' is-on' : '')} onClick={() => setTab('packages')}>Packages <span>{env.status === 'ready' ? env.packages.length : (build?.packages?.length ?? 0)}</span></button>
+ </div>
+
+ {tab === 'files' && (
+ <div className="env-files">
+ <aside className="env-tree-pane">
+ <div className="env-tree-tools">
+ <label className="env-find"><iconify-icon icon="tabler:search"></iconify-icon><input value={q} placeholder="Find a file" aria-label="Find a file" onChange={(ev) => setQ(ev.target.value)} /></label>
+ <button className="icon-button" type="button" title="New file" aria-label="New file" onClick={() => setNewPath({ kind: 'file', value: '' })}><iconify-icon icon="tabler:file-plus"></iconify-icon></button>
+ <button className="icon-button" type="button" title="New folder" aria-label="New folder" onClick={() => setNewPath({ kind: 'dir', value: '' })}><iconify-icon icon="tabler:folder-plus"></iconify-icon></button>
+ <button className="icon-button" type="button" title="Upload files" aria-label="Upload files" onClick={() => uploadRef.current?.click()}><iconify-icon icon="tabler:upload"></iconify-icon></button>
+ <input ref={uploadRef} type="file" hidden multiple onChange={(ev) => { void upload(ev.target.files); ev.target.value = ''; }} />
+ </div>
+ {newPath && (
+ <div className="env-newpath">
+ <span className="env-dim">{parentDir() ? parentDir() + '/' : ''}</span>
+ <input value={newPath.value} autoFocus placeholder={newPath.kind === 'dir' ? 'folder name' : 'file name'} aria-label={newPath.kind === 'dir' ? 'Folder name' : 'File name'}
+ onChange={(ev) => setNewPath({ ...newPath, value: ev.target.value })}
+ onKeyDown={(ev) => { if (ev.key === 'Enter') void createPath(); if (ev.key === 'Escape') setNewPath(null); }} />
+ <button className="button small" type="button" onClick={() => void createPath()}>Add</button>
+ </div>
+ )}
+ <div className="env-tree" role="tree">
+ {needle ? (
+ matches.length ? matches.map((m) => (
+ <div key={m.path} className={'env-node' + (sel === m.path ? ' is-selected' : '')} style={{ paddingLeft: 12 }} role="treeitem" tabIndex={0}
+ onClick={() => void openFile(m.path)} onKeyDown={(ev) => { if (ev.key === 'Enter') void openFile(m.path); }}>
+ <span className="env-chev" /><iconify-icon icon="tabler:file"></iconify-icon><span className="env-node-name">{m.path}</span></div>
+ )) : <div className="env-tree-empty">No file matches.</div>
+ ) : tree.length ? tree.map((n) => renderNode(n, 0)) : (
+ <div className="env-tree-empty">No files yet. Upload files, or import an archive or a git repository from the header.</div>
+ )}
+ </div>
+ </aside>
+ <div className="env-view">
+ {openPath && file ? (
+ <>
+ <div className="env-view-head">
+ <code>{openPath}</code>
+ <span className="env-dim">{fmtBytes(file.bytes)}</span>
+ {file.text !== null && (editing === null
+ ? <button className="button small" type="button" onClick={() => setEditing(file.text || '')}>Edit</button>
+ : <><button className="button primary small" type="button" disabled={busy === 'save'} onClick={() => void saveFile()}>Save</button>
+ <button className="button small" type="button" onClick={() => setEditing(null)}>Cancel</button></>)}
+ </div>
+ {file.text === null ? (
+ <div className="env-binary">A binary file ({file.type}, {fmtBytes(file.bytes)}). It is in the environment as uploaded.</div>
+ ) : editing !== null ? (
+ <textarea className="env-editor" value={editing} spellCheck={false} onChange={(ev) => setEditing(ev.target.value)} />
+ ) : (
+ <pre className="env-code">{lines.map((l, i) => <span key={i} className="env-line"><span className="env-ln">{i + 1}</span><span className="env-lt">{l}</span></span>)}</pre>
+ )}
+ </>
+ ) : (
+ <div className="env-view-empty">{entries?.length ? 'Open a file to read it.' : ''}</div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {tab === 'packages' && (
+ <div className="env-packages">
+ <div className="env-pk-head">
+ {env.status === 'ready' && env.version
+ ? <span>Installed in version {env.version}, the one every session reads.</span>
+ : env.status === 'building' ? <span>Building version {env.latestVersion}…</span>
+ : env.status === 'failed' ? <span>The last build failed. Fix the manifests and build again.</span>
+ : <span>Nothing built yet. Add a <code>requirements.txt</code>, <code>pyproject.toml</code> or <code>package.json</code> (and a <code>setup.sh</code> for anything else), then build.</span>}
+ {build && <button className="button small" type="button" onClick={() => setShowLog((v) => !v)}>{showLog ? 'Hide build log' : 'Build log'}</button>}
+ </div>
+ {showLog && build && (
+ <pre className="env-log">{`version ${build.version} · ${build.status}${build.error ? ' · ' + build.error : ''}\n${build.log || ''}`}</pre>
+ )}
+ {env.packages.length > 0 && (
+ <table className="env-table">
+ <thead><tr><th>Package</th><th>Version</th><th>Manager</th></tr></thead>
+ <tbody>{env.packages.map((p) => <tr key={p.manager + p.name}><td><code>{p.name}</code></td><td className="env-mono">{p.version}</td><td>{p.manager}</td></tr>)}</tbody>
+ </table>
+ )}
+ {env.versions.length > 0 && (
+ <div className="env-versions">
+ <h3>Versions</h3>
+ {env.versions.slice().reverse().map((v) => (
+ <div key={v.version} className="env-version">
+ <span className="env-mono">v{v.version}</span>
+ <span className={'status ' + (v.status === 'ready' ? 'ok' : v.status === 'failed' ? 'err' : 'warn')}>{v.status}</span>
+ <span className="env-dim">{v.finished_at ? new Date(v.finished_at * 1000).toLocaleString() : ''}{v.packages ? ` · ${v.packages} packages` : ''}{v.bytes ? ` · ${fmtBytes(v.bytes)}` : ''}</span>
+ {v.status === 'ready' && (env.version === v.version
+ ? <span className="env-dim">active</span>
+ : <button className="button small" type="button" disabled={busy === 'activate'} onClick={() => void activate(v.version)}>Use this version</button>)}
+ {v.error && <span className="env-err">{v.error}</span>}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {gitOpen && (
+ <div className="kit-overlay" role="dialog" aria-modal="true" aria-labelledby="env-git-title" onMouseDown={(ev) => { if (ev.target === ev.currentTarget) setGitOpen(false); }}>
+ <div className="kit-dialog">
+ <button className="kit-dialog-x" type="button" onClick={() => setGitOpen(false)} aria-label="Close"><iconify-icon icon="tabler:x"></iconify-icon></button>
+ <h2 id="env-git-title">Import from git</h2>
+ <p className="kit-dialog-sub">The repository&apos;s tree at a branch or tag, without its history. A private repository needs a token in the URL.</p>
+ <div className="kit-custom">
+ <label className="kit-field"><span>Repository URL</span><input value={git.url} autoFocus placeholder="https://github.com/org/project" onChange={(ev) => setGit({ ...git, url: ev.target.value })} /></label>
+ <label className="kit-field"><span>Branch or tag</span><input value={git.ref} placeholder="main" onChange={(ev) => setGit({ ...git, ref: ev.target.value })} /></label>
+ <label className="db-sample"><input type="checkbox" checked={git.replace} onChange={(ev) => setGit({ ...git, replace: ev.target.checked })} /><span><strong>Replace the current files</strong><em>Otherwise the repository lands over what is here.</em></span></label>
+ </div>
+ <div className="kit-dialog-actions">
+ <span className="kit-dialog-spacer" />
+ <button className="button" type="button" onClick={() => setGitOpen(false)}>Cancel</button>
+ <button className="button primary" type="button" disabled={busy === 'import' || !git.url.trim()} onClick={() => void importGit()}>{busy === 'import' ? 'Importing…' : 'Import'}</button>
+ </div>
+ </div>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/ui/src/app/(app)/environments/page.tsx b/ui/src/app/(app)/environments/page.tsx
new file mode 100644
index 00000000..e2f16674
--- /dev/null
+++ b/ui/src/app/(app)/environments/page.tsx
@@ -0,0 +1,113 @@
+'use client';
+// Environments: a project's files and its installed dependencies, built once and read by every
+// Task session that names it (read-only at /env/<slug>, beside the session's own workspace).
+// This page is the shelf: one row per environment with what the service knows about it; the work
+// (files, build, versions) happens on the environment's own page.
+import { useCallback, useEffect, useState } from 'react';
+import { useRouter } from 'next/navigation';
+import { SkelRows } from '@/components/Skel';
+import { createEnvironment, fmtBytes, listEnvironments, type Environment } from '@/lib/environments';
+
+const STATUS_LABEL: Record<Environment['status'], string> = { empty: 'Not built', building: 'Building', ready: 'Ready', failed: 'Build failed' };
+const STATUS_CLASS: Record<Environment['status'], string> = { empty: 'neutral', building: 'warn', ready: 'ok', failed: 'err' };
+
+export default function EnvironmentsPage() {
+ const router = useRouter();
+ const [items, setItems] = useState<Environment[] | null>(null);
+ const [err, setErr] = useState('');
+ const [creating, setCreating] = useState(false);
+ const [form, setForm] = useState({ name: '', description: '', entry: '' });
+ const [busy, setBusy] = useState(false);
+
+ const reload = useCallback(async () => {
+ try { setItems(await listEnvironments()); setErr(''); }
+ catch (e) { setErr(e instanceof Error ? e.message : 'The environments could not be read.'); }
+ }, []);
+ useEffect(() => { void reload(); }, [reload]);
+ // a build finishes in the background: while one shows as building, the list re-reads
+ useEffect(() => {
+ if (!items?.some((e) => e.status === 'building')) return;
+ const t = setInterval(() => void reload(), 4000);
+ return () => clearInterval(t);
+ }, [items, reload]);
+
+ const create = async () => {
+ if (!form.name.trim()) return;
+ setBusy(true); setErr('');
+ try {
+ const e = await createEnvironment({ name: form.name.trim(), description: form.description.trim(), entry: form.entry.trim() });
+ setCreating(false); setForm({ name: '', description: '', entry: '' });
+ router.push(`/environments/${e.id}`);
+ } catch (e) { setErr(e instanceof Error ? e.message : 'The environment could not be created.'); }
+ finally { setBusy(false); }
+ };
+
+ return (
+ <section className="view is-active collection-view" id="view-environments"><div className="page">
+ <div className="page-header">
+ <div>
+ <h1>Environments</h1>
+ <p>A project and its installed dependencies, built once and opened by every Task that uses it. Sessions read it at its own path and keep their outputs in their own workspace.</p>
+ </div>
+ <div className="page-actions">
+ <button className="button primary" type="button" onClick={() => setCreating(true)}>
+ <iconify-icon icon="tabler:plus"></iconify-icon>New environment</button>
+ </div>
+ </div>
+
+ {err && <div className="hr-error" role="alert">{err}</div>}
+
+ {items === null && !err && <SkelRows rows={3} />}
+
+ {items !== null && items.length === 0 && (
+ <div className="session-empty env-empty">
+ <iconify-icon icon="tabler:stack-2"></iconify-icon>
+ <strong>No environments yet</strong>
+ <span>Create one, import your project (an archive or a git repository), build it, and name it on a Harness. Every Task of that Harness then starts with the project in place and its packages installed.</span>
+ </div>
+ )}
+
+ {items !== null && items.length > 0 && (
+ <div className="env-list">
+ <div className="env-row env-row-head"><span>Name</span><span>Status</span><span>Version</span><span>Files</span><span>Packages</span><span>Updated</span></div>
+ {items.map((e) => (
+ <a key={e.id} className="env-row" href={`/environments/${e.id}`}>
+ <span className="env-name"><iconify-icon icon="tabler:stack-2"></iconify-icon><span><strong>{e.name}</strong><em>{e.mount}</em></span></span>
+ <span><span className={'status ' + STATUS_CLASS[e.status]}>{STATUS_LABEL[e.status]}</span></span>
+ <span className="env-mono">{e.version ? `v${e.version}` : '—'}</span>
+ <span className="env-mono">{e.files.count}{e.files.bytes ? <em> {fmtBytes(e.files.bytes)}</em> : null}</span>
+ <span className="env-mono">{e.status === 'ready' ? e.packages.length : '—'}</span>
+ <span className="env-dim">{e.updatedAt ? new Date(e.updatedAt).toLocaleString() : ''}</span>
+ </a>
+ ))}
+ </div>
+ )}
+
+ {creating && (
+ <div className="kit-overlay" role="dialog" aria-modal="true" aria-labelledby="env-new-title"
+ onMouseDown={(ev) => { if (ev.target === ev.currentTarget) setCreating(false); }}>
+ <div className="kit-dialog">
+ <button className="kit-dialog-x" type="button" onClick={() => setCreating(false)} aria-label="Close"><iconify-icon icon="tabler:x"></iconify-icon></button>
+ <h2 id="env-new-title">New environment</h2>
+ <p className="kit-dialog-sub">Name it after the project. Sessions will find it at a path made from the name; that path does not change afterwards.</p>
+ <div className="kit-custom">
+ <label className="kit-field"><span>Name</span>
+ <input value={form.name} placeholder="Content Studio" autoFocus onChange={(ev) => setForm({ ...form, name: ev.target.value })}
+ onKeyDown={(ev) => { if (ev.key === 'Enter') void create(); }} /></label>
+ <label className="kit-field"><span>Description</span>
+ <input value={form.description} placeholder="What the project does" onChange={(ev) => setForm({ ...form, description: ev.target.value })} /></label>
+ <label className="kit-field"><span>How it is run</span>
+ <input value={form.entry} placeholder="python3 run.py --episode <id>" onChange={(ev) => setForm({ ...form, entry: ev.target.value })} />
+ <span className="kit-choice-why">Optional. Told to the agent word for word, so it starts the project the way you do.</span></label>
+ </div>
+ <div className="kit-dialog-actions">
+ <span className="kit-dialog-spacer" />
+ <button className="button" type="button" onClick={() => setCreating(false)}>Cancel</button>
+ <button className="button primary" type="button" disabled={busy || !form.name.trim()} onClick={() => void create()}>{busy ? 'Creating…' : 'Create'}</button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div></section>
+ );
+}
diff --git a/ui/src/app/hr.css b/ui/src/app/hr.css
index 154b77ec..cc81a287 100644
--- a/ui/src/app/hr.css
+++ b/ui/src/app/hr.css
@@ -1046,3 +1046,97 @@ body.hr-resizing iframe { pointer-events: none; }
.wbx-browser-grip { display: none; }
.wbx-browser-btn { padding: 0 10px; }
}
+
+/* ── Environments (Richard's console design, 2026-09-28) ─────────────────────────────────────
+ The shelf: one row per environment. The page: a white head (back link, name, status, actions,
+ facts), then a card with two tabs; the files tab is a tree beside the open file. */
+.env-list { display: flex; flex-direction: column; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); overflow: hidden; }
+.env-row { display: grid; grid-template-columns: minmax(200px, 2fr) 120px 80px 110px 90px minmax(120px, 1fr); align-items: center; gap: 12px;
+ padding: 12px 16px; border-top: 1px solid var(--line); color: var(--ink); text-decoration: none; font-size: 13.5px; }
+.env-row:first-child { border-top: 0; }
+.env-row-head { font-size: 11px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); background: var(--surface-subtle); }
+a.env-row:hover { background: var(--surface-subtle); }
+.env-name { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.env-name iconify-icon { font-size: 18px; color: var(--muted); flex: none; }
+.env-name > span { display: flex; flex-direction: column; min-width: 0; }
+.env-name strong { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.env-name em { font-style: normal; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11.5px; color: var(--muted); }
+.env-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
+.env-mono em { font-style: normal; color: var(--muted); }
+.env-dim { color: var(--muted); font-size: 12.5px; }
+.env-empty { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; max-width: 560px; }
+.env-empty iconify-icon { font-size: 26px; color: var(--muted); }
+@media (max-width: 900px) {
+ .env-row { grid-template-columns: minmax(160px, 2fr) 110px 70px; }
+ .env-row > :nth-child(n+4) { display: none; }
+}
+
+.env-head { padding: 22px 36px 18px; background: var(--surface); border-bottom: 1px solid var(--line); }
+.env-back { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--muted); text-decoration: none; }
+.env-back:hover { color: var(--ink); }
+.env-title-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-top: 10px; }
+.env-title-row h1 { margin: 0; font-size: 26px; font-weight: 700; letter-spacing: -.02em; color: var(--ink); }
+.env-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.env-actions .button { display: inline-flex; align-items: center; gap: 6px; }
+.env-confirm { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; color: var(--ink); }
+.env-rename { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; flex: 1; }
+.env-rename input { font: inherit; font-size: 14px; padding: 7px 10px; border: 1px solid var(--line-strong); border-radius: 8px; min-width: 160px; }
+.env-facts { display: flex; flex-wrap: wrap; gap: 6px 28px; margin-top: 14px; font-size: 13px; color: var(--ink); }
+.env-facts > span { display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.env-facts em { font-style: normal; font-size: 11px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); }
+.env-facts code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; background: var(--surface-subtle); padding: 2px 7px; border-radius: 6px; }
+.env-facts a { color: var(--accent); text-decoration: none; }
+.env-body { padding: 24px 36px 34px; }
+.env-card { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
+.env-tabs { display: flex; gap: 4px; padding: 12px 16px; border-bottom: 1px solid var(--line); }
+.env-tab { display: inline-flex; align-items: center; gap: 7px; padding: 7px 12px; border: 0; border-radius: 8px; background: transparent; cursor: pointer;
+ font: inherit; font-size: 13.5px; font-weight: 600; color: var(--muted); }
+.env-tab.is-on { background: var(--surface-subtle); color: var(--ink); }
+.env-tab span { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; color: var(--accent); }
+.env-files { display: grid; grid-template-columns: 280px minmax(0, 1fr); min-height: 520px; }
+.env-tree-pane { border-right: 1px solid var(--line); display: flex; flex-direction: column; min-width: 0; }
+.env-tree-tools { display: flex; align-items: center; gap: 4px; padding: 12px 10px 8px; }
+.env-find { flex: 1; display: flex; align-items: center; gap: 6px; padding: 6px 9px; border: 1px solid var(--line-strong); border-radius: 7px; color: var(--muted); min-width: 0; }
+.env-find input { flex: 1; min-width: 0; border: 0; outline: none; background: transparent; font: inherit; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; color: var(--ink); }
+.env-newpath { display: flex; align-items: center; gap: 6px; padding: 0 10px 8px; }
+.env-newpath input { flex: 1; min-width: 0; font: inherit; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; padding: 5px 8px; border: 1px solid var(--line-strong); border-radius: 6px; }
+.env-tree { flex: 1; overflow: auto; padding: 4px 0 12px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
+.env-node { display: flex; align-items: center; gap: 6px; padding: 5px 10px 5px 12px; cursor: pointer; color: var(--ink); white-space: nowrap; }
+.env-node:hover { background: var(--surface-subtle); }
+.env-node.is-selected { background: color-mix(in srgb, var(--accent) 8%, transparent); color: var(--accent); }
+.env-node iconify-icon { font-size: 14px; color: var(--muted); flex: none; }
+.env-node.is-selected iconify-icon { color: var(--accent); }
+.env-chev { width: 12px; font-size: 12px !important; flex: none; }
+.env-node-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+.env-node-count { color: var(--muted); font-size: 11px; }
+.env-node-x { display: none; border: 0; background: none; color: var(--muted); cursor: pointer; padding: 0 2px; font-size: 12px; }
+.env-node:hover .env-node-x { display: inline-flex; }
+.env-tree-empty { padding: 16px 14px; color: var(--muted); font-family: inherit; font-size: 13px; line-height: 1.5; white-space: normal; }
+.env-view { display: flex; flex-direction: column; min-width: 0; }
+.env-view-head { display: flex; align-items: center; gap: 10px; padding: 12px 16px; border-bottom: 1px solid var(--line); font-size: 12.5px; }
+.env-view-head code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--ink); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+.env-view-empty { padding: 40px 16px; color: var(--muted); font-size: 13px; }
+.env-binary { padding: 24px 16px; color: var(--muted); font-size: 13px; }
+.env-code { margin: 0; padding: 14px 0; overflow: auto; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; line-height: 1.7; color: var(--ink); }
+.env-line { display: flex; }
+.env-ln { flex: none; width: 48px; padding-right: 16px; text-align: right; color: var(--line-strong); user-select: none; }
+.env-lt { white-space: pre; }
+.env-editor { flex: 1; min-height: 480px; margin: 0; padding: 14px 16px; border: 0; outline: none; resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; line-height: 1.7; color: var(--ink); background: transparent; }
+.env-packages { padding: 16px; display: flex; flex-direction: column; gap: 14px; }
+.env-pk-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; font-size: 13px; color: var(--muted); }
+.env-pk-head code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
+.env-log { margin: 0; padding: 12px 14px; max-height: 320px; overflow: auto; background: var(--surface-subtle); border-radius: 8px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11.5px; line-height: 1.55; white-space: pre-wrap; color: var(--ink); }
+.env-table { width: 100%; border-collapse: collapse; font-size: 13px; }
+.env-table th { text-align: left; font-size: 11px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); padding: 6px 8px; border-bottom: 1px solid var(--line); }
+.env-table td { padding: 7px 8px; border-bottom: 1px solid var(--line); }
+.env-table code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
+.env-versions h3 { margin: 6px 0 8px; font-size: 13px; font-weight: 650; color: var(--ink); }
+.env-version { display: flex; align-items: center; gap: 12px; padding: 8px 0; border-top: 1px solid var(--line); font-size: 13px; flex-wrap: wrap; }
+.env-err { color: var(--amber); font-size: 12.5px; }
+@media (max-width: 900px) {
+ .env-head { padding: 18px 16px 14px; }
+ .env-body { padding: 16px 0 24px; }
+ .env-files { grid-template-columns: minmax(0, 1fr); }
+ .env-tree-pane { border-right: 0; border-bottom: 1px solid var(--line); max-height: 320px; }
+ .env-ln { width: 40px; padding-right: 10px; }
+}
diff --git a/ui/src/components/ApiReference.tsx b/ui/src/components/ApiReference.tsx
index 1944895c..5301a4cd 100644
--- a/ui/src/components/ApiReference.tsx
+++ b/ui/src/components/ApiReference.tsx
@@ -296,6 +296,7 @@ curl "${mgmtBase}/sessions/{session_id}/files?changed=true" \\
<Param name="mcp_servers" type="array">Tool connections: <code>{`{name, url, auth?, enabled}`}</code>. For <code>auth</code>, pass a secrets ref (below) or a <code>$headers.&#123;Name&#125;</code> per-request reference.</Param>
<Param name="skills" type="array"><code>{`{name, files:[{path, content|content_b64}]}`}</code>, a bundle MUST include a <code>SKILL.md</code>; invalid bundles are rejected with 400. Skills can be whole folders: <code>path</code> is the file&apos;s relative path inside the skill (nested layouts like <code>guides/SKILL.md</code> install as-is); the root <code>SKILL.md</code> needs YAML frontmatter (<code>name</code>, <code>description</code>). Bundles over ~48&nbsp;KB are offloaded server-side and the saved agent returns that skill as <code>{`{name, enabled, blob}`}</code> with no <code>files</code>, normal; the folder still mounts into every run. On later updates pass such entries back unchanged; only include <code>files</code> when changing content.</Param>
<Param name="plugins" type="array">Packages in the Agent Plugins format: <code>{`{files:[{path, content|content_b64}], enabled?}`}</code>, each with a <code>plugin.json</code> at its root, tools in <code>mcp.json</code>, Skills under <code>skills/</code>. The saved agent returns each as <code>{`{name, enabled, blob, manifest, mcpServers, skills, skipped}`}</code>; pass such entries back unchanged, and include <code>files</code> only for a new or changed package.</Param>
+ <Param name="environment" type="string">An environment id (<code>henv_…</code>): the project every run of this agent reads at its path, read-only, with its packages installed. See Environments below.</Param>
<Param name="disabled_tools" type="array">Inherited/built-in tool names to disable.</Param>
<Param name="additional_headers" type="array">Header NAMES your product passes per request for app-level auth (see Additional headers above).</Param>
<Param name="max_step" type="integer">Default agent step budget (default 400).</Param>
@@ -337,6 +338,56 @@ curl "${mgmtBase}/sessions/{session_id}/files?changed=true" \\
format. Credentials are never included; each omission is listed in <code>skipped</code>.</p>
</Endpoint>
+ <h3 className="apidoc-h3">Environments</h3>
+ <p className="hr-meta">A project and its installed dependencies, built once and read by every run that names it: mounted
+ read-only at <code>/env/&#123;slug&#125;</code> in the run&apos;s sandbox, beside the run&apos;s own writable
+ workspace, with its Python virtualenv and node_modules on <code>PATH</code>. Name it on an agent
+ (<code>environment</code> above) or on one run (<code>environment</code> in the task body). Two runs on
+ one environment share every byte of it and none of each other&apos;s workspace.</p>
+ <Endpoint method="POST" path="/v1/environments">
+ <p className="hr-meta">Create one. Returns it with its <code>id</code> and its <code>mount</code>, the path runs will see.</p>
+ <div className="apidoc-sub">Request body</div>
+ <ParamTable>
+ <Param name="name" type="string" req>Starts with a letter or digit; the path segment (<code>slug</code>) derives from it and does not change.</Param>
+ <Param name="description" type="string">What the project is.</Param>
+ <Param name="entry" type="string">How it is run, in your words (<code>python3 run.py --episode &lt;id&gt;</code>); repeated to the agent word for word.</Param>
+ </ParamTable>
+ <CodeBlock code={`curl -X POST $BASE/v1/environments -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \\
+ -d '{"name": "Content Studio", "entry": "python3 run.py --episode <id>"}'`} />
+ </Endpoint>
+ <Endpoint method="PUT" path="/v1/environments/{id}/files/{path}">
+ <p className="hr-meta">Write one file (the body is its bytes; its folders are made on the way).
+ <code> GET</code> reads it back, <code>DELETE</code> removes a file or a folder, <code>POST /v1/environments/&#123;id&#125;/directories</code>
+ with <code>{`{"path": "assets/brand"}`}</code> makes an empty folder, and <code>GET /v1/environments/&#123;id&#125;/files</code>
+ lists the tree. Editing changes nothing a run sees until the next build.</p>
+ <CodeBlock code={`curl -X PUT "$BASE/v1/environments/$ENV/files/scripts/render.py" -H "Authorization: Bearer $KEY" \\
+ --data-binary @scripts/render.py`} />
+ </Endpoint>
+ <Endpoint method="POST" path="/v1/environments/{id}/import">
+ <p className="hr-meta">A whole project at once, keeping its tree: a zip or tar as the body, or
+ <code> {`{"git": {"url": "...", "ref": "main"}}`}</code>. A single wrapping folder is stripped; links and paths
+ that escape the root are dropped; <code>?replace=1</code> clears the files first.</p>
+ <CodeBlock code={`curl -X POST "$BASE/v1/environments/$ENV/import?replace=1" -H "Authorization: Bearer $KEY" \\
+ -H "Content-Type: application/zip" --data-binary @content-studio.zip`} />
+ </Endpoint>
+ <Endpoint method="POST" path="/v1/environments/{id}/build">
+ <p className="hr-meta">Snapshot the files into the next version and install what they declare:
+ <code> requirements.txt</code> / <code>pyproject.toml</code> into a virtualenv, <code>package.json</code> with npm,
+ then <code>setup.sh</code>. Returns at once; poll <code>GET /v1/environments/&#123;id&#125;/builds/&#123;version&#125;</code>
+ for <code>building</code> → <code>ready</code> (with the packages and the log) or <code>failed</code> (with the reason).
+ A finished build becomes the version runs read; <code>POST …/versions/&#123;n&#125;/activate</code> rolls back to an
+ earlier one.</p>
+ <CodeBlock code={`curl -X POST $BASE/v1/environments/$ENV/build -H "Authorization: Bearer $KEY"
+curl $BASE/v1/environments/$ENV/builds/1 -H "Authorization: Bearer $KEY"`} />
+ </Endpoint>
+ <Endpoint method="POST" path="/v1/responses">
+ <p className="hr-meta">A run on an environment: the agent&apos;s harness names it, or the run does. A run on
+ an environment with nothing built is refused with <code>environment_not_ready</code> before it starts.</p>
+ <CodeBlock code={`curl -X POST $BASE/v1/responses -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \\
+ -d '{"input": "Render the teaser for episode 12 into my working directory.",
+ "metadata": {"harness_id": "chrn_..."}, "environment": "henv_..."}'`} />
+ </Endpoint>
+
<Endpoint method="GET" path="/v1/models">
<p className="hr-meta">The current model catalog per engine, each with its default. Build model
pickers from this, don&apos;t hardcode model names. The map is keyed by <b>backend</b>, not
diff --git a/ui/src/components/HarnessSettings.tsx b/ui/src/components/HarnessSettings.tsx
index 5b3510db..ebf42e52 100644
--- a/ui/src/components/HarnessSettings.tsx
+++ b/ui/src/components/HarnessSettings.tsx
@@ -21,6 +21,7 @@ import { fetchTraceWindow, statsFor, p95Of, avgCreditsOf, timeAgo, type TraceCar
// hosted workspace. Hidden and inert on hosted builds.
import { SELF_HOSTED } from '@/lib/edition';
import { CloudUploadDialog } from '@/components/CloudUploadDialog';
+import { listEnvironments, type Environment } from '@/lib/environments';
import { statusOne, type CloudStatus } from '@/lib/cloud-upload';
type Skill = CustomHarness['skills'][number];
@@ -39,6 +40,8 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {
const oob = oobById(id);
const [saved, setSaved] = useState<CustomHarness | null>(null);
const [draft, setDraft] = useState<CustomHarness | null>(null);
+ const [environments, setEnvironments] = useState<Environment[] | null>(null);
+ useEffect(() => { listEnvironments().then(setEnvironments).catch(() => setEnvironments([])); }, []);
const [loaded, setLoaded] = useState(false);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState<string | null>(null);
@@ -579,7 +582,24 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {
</section>
<section className="form-section">
- <div><h3>Environment</h3><p>Variables every Task's shell and tools start with. Put a secret behind a request header or a stored secret, never as a literal; the agent never sees the value in its prompt, and anything it prints is redacted from the record.</p></div>
+ <div><h3>Project environment</h3><p>A project and its installed dependencies, built once on the Environments page. Every Task of this Harness then starts with it in place, read-only at its own path, and keeps its outputs in the Task's own workspace.</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 })}>
+ <option value="">None</option>
+ {(environments || []).map((en) => <option key={en.id} value={en.id}>{en.name}{en.status === 'ready' ? ` (v${en.version}, ${en.mount})` : ' (not built yet)'}</option>)}
+ </select></div>
+ {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>}
+ </div>
+ </section>
+
+ <section className="form-section">
+ <div><h3>Environment variables</h3><p>Variables every Task's shell and tools start with. Put a secret behind a request header or a stored secret, never as a literal; the agent never sees the value in its prompt, and anything it prints is redacted from the record.</p></div>
<div className="field-stack">
<div className="section-actions"><strong>{Object.keys(draft?.env || {}).length} variables</strong>
{!readOnly && <button className="button small" type="button" onClick={() => setEnvRows((r) => [...r, { name: '', value: '' }])}><iconify-icon icon="tabler:plus"></iconify-icon>Add variable</button>}</div>
diff --git a/ui/src/components/revamp/Shell.tsx b/ui/src/components/revamp/Shell.tsx
index 3da75289..05766a5b 100644
--- a/ui/src/components/revamp/Shell.tsx
+++ b/ui/src/components/revamp/Shell.tsx
@@ -68,6 +68,7 @@ const NAV_GROUPS: { label: string | null; items: NavItem[] }[] = [
// Services the workspace connects once (a browser, a repository, a project); each Harness
// includes the ones it needs under its settings.
{ href: '/plugins', icon: 'lucide:plug', label: 'Plugins' },
+ { href: '/environments', icon: 'tabler:stack-2', label: 'Environments' },
] },
{ label: 'Access', items: [
{ href: '/keys', icon: 'tabler:key', label: 'API Keys' },
diff --git a/ui/src/lib/edition.ts b/ui/src/lib/edition.ts
index 7861285c..d4a66093 100644
--- a/ui/src/lib/edition.ts
+++ b/ui/src/lib/edition.ts
@@ -32,7 +32,7 @@ export const LOCAL_MEMBER = 'local@localhost';
* API Keys is here because the box mints and serves them itself: /keys worked in every CE
* release and only the entry was missing, so the README sent people to the URL by hand. The
* key is how a product calls its own instance, which is the point of self-hosting. */
-export const SELF_HOSTED_NAV = ['/kits', '/harnesses', '/tasks', '/plugins', '/keys', '/integrations'];
+export const SELF_HOSTED_NAV = ['/kits', '/harnesses', '/tasks', '/plugins', '/environments', '/keys', '/integrations'];
/** Orgs allowed to see platform-admin surfaces (global model routing).
*
diff --git a/ui/src/lib/environments.ts b/ui/src/lib/environments.ts
new file mode 100644
index 00000000..06975cf1
--- /dev/null
+++ b/ui/src/lib/environments.ts
@@ -0,0 +1,87 @@
+// Environments (UHP Environments chapter): a project's files and its installed dependencies,
+// built once and read by every Task session that names it, read-only at a fixed path beside the
+// session's own writable workspace. Every function here is one call to the service; nothing is
+// derived on the client.
+import { authHeaders } from '@/lib/chat';
+import { harnessFetch } from '@/lib/hfetch';
+import { gw } from '@/lib/harness';
+
+export interface EnvironmentPackage { manager: string; name: string; version: string }
+export interface EnvironmentVersion {
+ version: number; status: 'building' | 'ready' | 'failed' | 'unknown';
+ started_at?: number | null; finished_at?: number | null; error?: string; files?: number; bytes?: number; packages?: number;
+}
+export interface Environment {
+ id: string; object: 'environment'; name: string; slug: string; description: string; entry: string;
+ status: 'empty' | 'building' | 'ready' | 'failed'; mount: string;
+ version: number | null; latestVersion: number | null;
+ files: { count: number; bytes: number };
+ packages: EnvironmentPackage[];
+ versions: EnvironmentVersion[];
+ build: EnvironmentVersion | null;
+ member: string; workspace: string; createdAt: number; updatedAt: number;
+}
+export interface EnvironmentBuildRecord {
+ id: string; version: number; status: 'building' | 'ready' | 'failed';
+ started_at?: number | null; finished_at?: number | null; error?: string; log?: string;
+ packages?: EnvironmentPackage[]; files?: number; bytes?: number;
+}
+export interface EnvironmentFileEntry { path: string; dir: boolean; bytes: number; mtime: number; link?: boolean }
+
+export const listEnvironments = () => gw<{ environments: Environment[] }>('GET', '/v1/environments').then((d) => d.environments);
+export const getEnvironment = (id: string) => gw<Environment>('GET', `/v1/environments/${id}`);
+export const createEnvironment = (body: { name: string; description?: string; entry?: string }) =>
+ gw<Environment>('POST', '/v1/environments', body);
+export const updateEnvironment = (id: string, body: { name: string; description?: string; entry?: string }) =>
+ gw<Environment>('PUT', `/v1/environments/${id}`, body);
+export const deleteEnvironment = (id: string) => gw<{ id: string; deleted: boolean }>('DELETE', `/v1/environments/${id}`);
+export const listEnvironmentFiles = (id: string) =>
+ gw<{ entries: EnvironmentFileEntry[]; count: number; bytes: number }>('GET', `/v1/environments/${id}/files`);
+export const buildEnvironment = (id: string) => gw<{ version: number; status: string }>('POST', `/v1/environments/${id}/build`);
+export const getEnvironmentBuild = (id: string, version: number) =>
+ gw<EnvironmentBuildRecord>('GET', `/v1/environments/${id}/builds/${version}`);
+export const activateEnvironmentVersion = (id: string, version: number) =>
+ gw<Environment>('POST', `/v1/environments/${id}/versions/${version}/activate`);
+export const environmentHarnesses = (id: string) =>
+ gw<{ harnesses: { id: string; name: string; base: string }[] }>('GET', `/v1/environments/${id}/harnesses`).then((d) => d.harnesses);
+
+const encodePath = (p: string) => p.split('/').map(encodeURIComponent).join('/');
+
+async function raw(method: string, path: string, body?: BodyInit | null, contentType?: string): Promise<Response> {
+ const headers: Record<string, string> = { ...authHeaders() };
+ delete headers['content-type']; delete headers['Content-Type'];
+ if (contentType) headers['content-type'] = contentType;
+ const r = await harnessFetch(`/api/harness${path}`, { method, headers, body: body ?? undefined, cache: 'no-store' });
+ if (!r.ok) {
+ let detail = `${r.status}`;
+ try { const j = await r.json(); detail = j?.error?.message || j?.detail || detail; } catch { /* keep the status */ }
+ throw new Error(String(detail));
+ }
+ return r;
+}
+
+/** One file's bytes, as text when it is text (the caller decides what to do with a binary). */
+export async function readEnvironmentFile(id: string, path: string): Promise<{ text: string | null; bytes: number; type: string }> {
+ const r = await raw('GET', `/v1/environments/${id}/files/${encodePath(path)}`);
+ const type = r.headers.get('content-type') || 'application/octet-stream';
+ const buf = await r.arrayBuffer();
+ const textual = /^(text\/|application\/(json|xml|yaml|x-yaml|javascript|toml|x-sh|x-python))/.test(type) || /\.(md|txt|py|js|ts|tsx|jsx|json|yaml|yml|toml|sh|cfg|ini|csv|html|css|env|lock)$/i.test(path);
+ let text: string | null = null;
+ if (textual && buf.byteLength <= 2 * 1024 * 1024) {
+ const dec = new TextDecoder('utf-8', { fatal: true });
+ try { text = dec.decode(buf); } catch { text = null; }
+ }
+ return { text, bytes: buf.byteLength, type };
+}
+export const writeEnvironmentFile = (id: string, path: string, body: Blob | string) =>
+ raw('PUT', `/v1/environments/${id}/files/${encodePath(path)}`, body, typeof body === 'string' ? 'text/plain; charset=utf-8' : (body.type || 'application/octet-stream')).then((r) => r.json());
+export const makeEnvironmentDir = (id: string, path: string) =>
+ gw<{ path: string; dir: boolean }>('POST', `/v1/environments/${id}/directories`, { path: path.replace(/\/+$/, '') });
+export const deleteEnvironmentPath = (id: string, path: string) =>
+ raw('DELETE', `/v1/environments/${id}/files/${encodePath(path)}`).then((r) => r.json());
+export const importEnvironmentArchive = (id: string, file: File, replace = false) =>
+ raw('POST', `/v1/environments/${id}/import${replace ? '?replace=1' : ''}`, file, file.type || 'application/octet-stream').then((r) => r.json());
+export const importEnvironmentGit = (id: string, url: string, ref = '', replace = false) =>
+ gw<{ written?: number; count: number; bytes: number }>('POST', `/v1/environments/${id}/import`, { git: { url, ref }, replace });
+
+export const fmtBytes = (n: number) => n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MB` : `${(n / 1024 ** 3).toFixed(2)} GB`;
diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.ts
index a754c225..b899da4b 100644
--- a/ui/src/lib/harness.ts
+++ b/ui/src/lib/harness.ts
@@ -56,6 +56,8 @@ export interface CustomHarness {
// skipped from the package on every save; a saved plugin round-trips as {name, enabled, blob}
// plus those derived fields, and a freshly picked one carries its `files` until it is saved.
plugins?: HarnessPlugin[];
+ // The environment (henv_) every Task of this Harness reads at its mount path, read-only; '' for none.
+ environment?: string;
createdAt: number;
}
@@ -425,6 +427,7 @@ function harnessBody(input: Partial<CustomHarness> & { name: string; base: strin
timeout_seconds: input.timeoutSeconds || null,
additional_headers: input.additionalHeaders || [],
env: input.env || {},
+ environment: input.environment || '',
};
}