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 build shows its stage and log while it runs; Add asks the registry before a package is declared (#335)

github-actions[bot]642b9dcbf3b5
diff --git a/docs/environments.md b/docs/environments.md
index 9bf2c2b7..4c6eef35 100644
--- a/docs/environments.md
+++ b/docs/environments.md
@@ -76,6 +76,12 @@ harness object and on `POST /v1/responses`; `environment` on the session object.
modes still hold for any non-root agent; root is the operator's own choice. Measured on
hr-test 2026-09-28: before the groups, any session could list and read every environment's
source and layers; after, a session reads its own and gets EACCES on the others.
+- **While it builds**: the runner writes `.hr-build.json` as each step ends, with `stage` (copying files,
+ python packages, node packages, system packages, setup.sh, finishing) and the log so far; the page
+ polls it every 3 s and shows a strip with the stage, the elapsed seconds and the log tail. Add asks
+ `GET /v1/environments/packages/check` (runner `check_package`: PyPI JSON, the npm registry, the box's
+ apt lists) and refuses a name that is not there or a pin that was never published; a row reads the
+ installed version, or "installing", or "installs on save" with the version the registry reported.
- **The turn**: the gateway resolves the environment (`metadata.environment` on the request, 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
diff --git a/gateway/app.py b/gateway/app.py
index f8a40661..4c203061 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -15478,7 +15478,7 @@ def _environment_out(v: dict) -> dict:
"declared": {m: [_env_spec_parts(x, m) | {"spec": x} for x in _j(v.get(f"pkg_{m}"), [])] for m in _ENV_MANAGERS},
"runtime": {"python": str(v.get("rt_python") or "")},
"versions": vers,
- "build": ({k: latest_rec.get(k) for k in ("version", "status", "started_at", "finished_at", "error")}
+ "build": ({k: latest_rec.get(k) for k in ("version", "status", "started_at", "finished_at", "error", "stage")}
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)}
@@ -15556,6 +15556,26 @@ async def environment_runtimes(request: Request) -> dict:
return r.json()
[email protected]("/v1/environments/packages/check")
+async def environment_package_check(request: Request, manager: str = "", spec: str = "") -> dict:
+ """What the manager's registry says about a package before a build: whether the name exists,
+ its latest version, whether an exact pin is published. The console asks on Add, so a typo is
+ refused where it is typed instead of failing a build. Optional in the protocol (Environments §4)."""
+ p = await _principal(request)
+ if not p.get("org"):
+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")
+ if manager not in _ENV_MANAGERS:
+ raise uhp_error(400, "environment_invalid", "manager must be pip, npm or apt.")
+ if not spec.strip() or not _env_specs({manager: [spec]}).get(manager):
+ raise uhp_error(400, "environment_invalid", "That is not a package spec.")
+ r = await _env_runner("GET", "/environments/packages/check", "packages", params={"manager": manager, "spec": spec.strip()})
+ if r.status_code == 400:
+ raise uhp_error(400, "environment_invalid", str((r.json() or {}).get("detail") or "That is not a package spec."))
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the registry could not be asked")
+ return {"object": "environment.package", **r.json()}
+
+
@app.get("/v1/environments/{env_id}")
async def get_environment(env_id: str, request: Request) -> dict:
_, v = await _owned_environment(request, env_id)
diff --git a/gateway/tests/test_environments.py b/gateway/tests/test_environments.py
index d62a9dec..abc72994 100644
--- a/gateway/tests/test_environments.py
+++ b/gateway/tests/test_environments.py
@@ -204,3 +204,17 @@ def test_the_task_names_its_environment_in_metadata_like_the_harness():
assert app._task_environment_ref(NS(metadata=None), hv) == "henv_harness"
assert app._task_environment_ref(NS(metadata={}), None) == ""
assert not hasattr(app.CreateResponseBody.model_fields, "environment") and "environment" not in app.CreateResponseBody.model_fields
+
+
+def test_the_package_check_is_the_registrys_answer_and_refuses_a_manager_it_cannot_build_with(api, monkeypatch):
+ answers = {"https://pypi.org/pypi/pip/json": (200, {"info": {"name": "pip", "version": "25.2"}, "releases": {"25.2": []}}),
+ "https://pypi.org/pypi/nope-nope-nope/json": (404, {})}
+ monkeypatch.setattr(E, "_http_json", lambda url: answers.get(url, (503, {})))
+ r = api.get("/v1/environments/packages/check?manager=pip&spec=pip")
+ assert r.status_code == 200 and r.json()["object"] == "environment.package" and r.json()["exists"] is True and r.json()["latest"] == "25.2"
+ r = api.get("/v1/environments/packages/check?manager=pip&spec=nope-nope-nope")
+ assert r.status_code == 200 and r.json()["exists"] is False and "not on PyPI" in r.json()["error"]
+ r = api.get("/v1/environments/packages/check?manager=cargo&spec=serde")
+ assert r.status_code == 400 and r.json()["error"]["code"] == "environment_invalid"
+ r = api.get("/v1/environments/packages/check?manager=pip&spec=")
+ assert r.status_code == 400
diff --git a/protocol/CHANGELOG.md b/protocol/CHANGELOG.md
index 4ef7d574..b39b2789 100644
--- a/protocol/CHANGELOG.md
+++ b/protocol/CHANGELOG.md
@@ -18,6 +18,14 @@ EN-07 asserts the response echo; `post2`: EN-02 compares the returned bytes, whi
read) and the reference server (0.26.7) changed together. The reference server passes the full
class, 84 of 84, on `post2`.
+**Patch of 2026-09-29, second, same version.** A build's record says which step is running
+(`stage`) and carries its log while it runs, and a server MUST write it as steps end, so a client
+can show progress ([Environments §4](versions/2026-09-28/environments.md#4-builds-and-versions)).
+An optional `GET /v1/environments/packages/check` answers what the manager's registry says about a
+spec before any build (`EnvironmentPackageCheck`), so a client can refuse a typo where it is
+typed. Suite `2026.9.28.post3`: EN-09 exercises the check on a server that offers it; reference
+server 0.26.9.
+
- **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
diff --git a/protocol/conformance/pyproject.toml b/protocol/conformance/pyproject.toml
index 9af061d6..9ddc8ceb 100644
--- a/protocol/conformance/pyproject.toml
+++ b/protocol/conformance/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "uhp-conformance"
-version = "2026.9.28.post2"
+version = "2026.9.28.post3"
description = "Conformance suite for the Unified Harness Protocol (UHP)"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/protocol/conformance/uhp_conformance/checks.py b/protocol/conformance/uhp_conformance/checks.py
index dd8df2a8..0bb45607 100644
--- a/protocol/conformance/uhp_conformance/checks.py
+++ b/protocol/conformance/uhp_conformance/checks.py
@@ -1914,6 +1914,25 @@ def en07(ctx):
return f"read {mount}/data/hello.txt; write refused; metadata.environment reported"
+@check("EN-09", "A package check answers for a known name and reports one that is not there", "full",
+ f"{SPEC}/environments.md#4-builds-and-versions")
+def en09(ctx):
+ _environments_supported(ctx)
+ r = ctx.client.get("/v1/environments/packages/check?manager=pip&spec=pip")
+ if r.status == 404:
+ raise Skip("the server offers no package check (optional in Environments §4)")
+ assert r.status == 200, f"the check answered HTTP {r.status}: {r.text[:200]}"
+ j = r.json or {}
+ ctx.validate(j, "EnvironmentPackageCheck")
+ assert j.get("exists") is True and j.get("latest"), f"pip must be known to PyPI with a latest version: {j}"
+ r = ctx.client.get(f"/v1/environments/packages/check?manager=pip&spec=uhp-conformance-no-such-package-{uuid.uuid4().hex[:10]}")
+ assert r.status == 200 and (r.json or {}).get("exists") is False, (
+ f"a name that is not on the registry must be reported as not there, not refused: HTTP {r.status} {r.text[:160]}")
+ r = ctx.client.get("/v1/environments/packages/check?manager=cargo&spec=serde")
+ assert r.status == 400 and _error_code(r) == "environment_invalid", f"a manager the server does not build with must be refused with environment_invalid: HTTP {r.status}"
+ return f"pip {j.get('latest')} known; an unknown name reported; an unknown manager 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]
diff --git a/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json b/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json
index b6a08ecd..d37b10ef 100644
--- a/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json
+++ b/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json
@@ -1282,6 +1282,55 @@
},
"additionalProperties": true
},
+ "EnvironmentPackageCheck": {
+ "type": "object",
+ "required": [
+ "manager",
+ "name",
+ "spec",
+ "exists"
+ ],
+ "description": "What the manager's registry says about a spec, before any build.",
+ "properties": {
+ "object": {
+ "type": "string",
+ "const": "environment.package"
+ },
+ "manager": {
+ "type": "string",
+ "enum": [
+ "pip",
+ "npm",
+ "apt"
+ ]
+ },
+ "name": {
+ "type": "string"
+ },
+ "spec": {
+ "type": "string"
+ },
+ "exists": {
+ "type": [
+ "boolean",
+ "null"
+ ],
+ "description": "null when the registry could not be asked"
+ },
+ "latest": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string",
+ "description": "The exact pin when it is published; empty otherwise"
+ },
+ "error": {
+ "type": "string",
+ "description": "In words: why the spec was refused, or why the registry could not be asked"
+ }
+ },
+ "additionalProperties": true
+ },
"EnvironmentRuntimes": {
"type": "object",
"description": "What a build can be made with on this server, and nothing that is not there.",
@@ -1440,6 +1489,10 @@
"error": {
"type": "string"
},
+ "stage": {
+ "type": "string",
+ "description": "The step a running build is on; empty once it ended"
+ },
"log": {
"type": "string"
},
diff --git a/protocol/schema/uhp-2026-09-28.openapi.yaml b/protocol/schema/uhp-2026-09-28.openapi.yaml
index 50beaa66..7d696c73 100644
--- a/protocol/schema/uhp-2026-09-28.openapi.yaml
+++ b/protocol/schema/uhp-2026-09-28.openapi.yaml
@@ -266,6 +266,26 @@ paths:
application/json:
schema: { $ref: '#/components/schemas/EnvironmentRuntimes' }
+ /v1/environments/packages/check:
+ get:
+ tags: [Environments]
+ operationId: checkEnvironmentPackage
+ summary: What the manager's registry says about a spec, before any build
+ description: |
+ Optional (a server without it answers 404). Whether the name exists, its latest version,
+ and whether an exact pin is published, so a client can refuse a typo where it is typed.
+ `environment_invalid` for a manager other than pip, npm or apt, or a string that is not a spec.
+ parameters:
+ - { name: manager, in: query, required: true, schema: { type: string, enum: [pip, npm, apt] } }
+ - { name: spec, in: query, required: true, schema: { type: string }, description: "A spec as the build takes it: numpy, numpy==2.3.1, [email protected], ffmpeg" }
+ responses:
+ '200':
+ description: The registry's answer
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentPackageCheck' }
+ '400': { $ref: '#/components/responses/BadRequest' }
+
/v1/environments/{environment_id}:
parameters:
- $ref: '#/components/parameters/EnvironmentId'
@@ -1673,6 +1693,21 @@ components:
version: { type: string }
additionalProperties: true
+ EnvironmentPackageCheck:
+ type: object
+ required: [manager, name, spec, exists]
+ description: What the manager's registry says about a spec, before any build.
+ properties:
+ object: { type: string, const: environment.package }
+ manager: { type: string, enum: [pip, npm, apt] }
+ name: { type: string }
+ spec: { type: string }
+ exists: { type: [boolean, 'null'], description: "null when the registry could not be asked" }
+ latest: { type: string }
+ version: { type: string, description: "The exact pin when it is published; empty otherwise" }
+ error: { type: string, description: "In words: why the spec was refused, or why the registry could not be asked" }
+ additionalProperties: true
+
EnvironmentRuntimes:
type: object
description: What a build can be made with on this server, and nothing that is not there.
@@ -1722,6 +1757,7 @@ components:
started_at: { type: [integer, 'null'] }
finished_at: { type: [integer, 'null'] }
error: { type: string }
+ stage: { type: string, description: "The step a running build is on; empty once it ended" }
log: { type: string }
packages: { type: array, items: { $ref: '#/components/schemas/EnvironmentPackage' } }
files: { type: integer }
diff --git a/protocol/schema/uhp-2026-09-28.schema.json b/protocol/schema/uhp-2026-09-28.schema.json
index b6a08ecd..d37b10ef 100644
--- a/protocol/schema/uhp-2026-09-28.schema.json
+++ b/protocol/schema/uhp-2026-09-28.schema.json
@@ -1282,6 +1282,55 @@
},
"additionalProperties": true
},
+ "EnvironmentPackageCheck": {
+ "type": "object",
+ "required": [
+ "manager",
+ "name",
+ "spec",
+ "exists"
+ ],
+ "description": "What the manager's registry says about a spec, before any build.",
+ "properties": {
+ "object": {
+ "type": "string",
+ "const": "environment.package"
+ },
+ "manager": {
+ "type": "string",
+ "enum": [
+ "pip",
+ "npm",
+ "apt"
+ ]
+ },
+ "name": {
+ "type": "string"
+ },
+ "spec": {
+ "type": "string"
+ },
+ "exists": {
+ "type": [
+ "boolean",
+ "null"
+ ],
+ "description": "null when the registry could not be asked"
+ },
+ "latest": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string",
+ "description": "The exact pin when it is published; empty otherwise"
+ },
+ "error": {
+ "type": "string",
+ "description": "In words: why the spec was refused, or why the registry could not be asked"
+ }
+ },
+ "additionalProperties": true
+ },
"EnvironmentRuntimes": {
"type": "object",
"description": "What a build can be made with on this server, and nothing that is not there.",
@@ -1440,6 +1489,10 @@
"error": {
"type": "string"
},
+ "stage": {
+ "type": "string",
+ "description": "The step a running build is on; empty once it ended"
+ },
"log": {
"type": "string"
},
diff --git a/protocol/versions/2026-09-28/environments.md b/protocol/versions/2026-09-28/environments.md
index bf61a39c..7c2cbf00 100644
--- a/protocol/versions/2026-09-28/environments.md
+++ b/protocol/versions/2026-09-28/environments.md
@@ -88,7 +88,7 @@ Three rules make it one thing rather than a shared folder:
| `declared` | object | client | What the owner declared, per manager, as spec strings the build installs beside the project's manifests: `pip` (`moviepy==2.1.1`), `npm` (`[email protected]`), `apt` (`ffmpeg`); read back with each spec's `name` and `version` |
| `runtime` | object | client | `python`: the interpreter a build makes the virtual environment with, one of `GET /v1/environments/runtimes`; empty for the server's default |
| `versions` | array | server | Every build: `version`, `status`, times, `error`, size |
-| `build` | object or null | server | The latest build's status |
+| `build` | object or null | server | The latest build's status, and its `stage` while it runs |
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
@@ -149,6 +149,7 @@ build; the build installs from the manifests ([§4](#4-builds-and-versions)).
```http
GET /v1/environments/runtimes what a build can be made with here: Python minors, Node major, the OS
+GET /v1/environments/packages/check?manager=&spec= what the manager's registry says about a spec, before any build (MAY)
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
@@ -174,7 +175,11 @@ 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
+reason as `error`. While it builds, the record says which step is running as `stage` (on the
+reference server: `copying files`, `python packages`, `node packages`, `system packages`,
+`setup.sh`, `finishing`) and carries the log so far, so a client can show progress rather than a
+spinner; a server MUST write the record as steps end, not only at the end of the build. 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)).
@@ -184,6 +189,14 @@ A failed build changes nothing: the previous active version stays active, and `s
an earlier finished build; nothing is rebuilt, and a version that never finished cannot be
activated (`environment_not_ready`).
+A server MAY answer `GET /v1/environments/packages/check?manager=&spec=` with what the manager's
+registry says about a spec before any build: whether the name exists, its latest version, and
+whether an exact pin is published (`EnvironmentPackageCheck`: `manager`, `name`, `spec`, `exists`
+true, false, or null when the registry could not be asked, `latest`, `version` for a published
+pin, `error` in words). A client that offers it refuses a typo where it is typed instead of
+failing a build minutes later; a client MUST NOT require it, and a server without it answers
+`404`. The reference server asks PyPI, the npm registry, and its own apt lists.
+
> **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:
diff --git a/runner/environments.py b/runner/environments.py
index 874c82ae..166748a9 100644
--- a/runner/environments.py
+++ b/runner/environments.py
@@ -45,6 +45,9 @@ import tarfile
import tempfile
import threading
import time
+import urllib.error
+import urllib.parse
+import urllib.request
import zipfile
from fastapi import APIRouter, HTTPException, Request, Response
@@ -479,6 +482,100 @@ def runtimes() -> dict:
"apt": bool(shutil.which("apt-get") and shutil.which("dpkg"))}
+REGISTRY_TIMEOUT = 8
+_apt_lists_at = 0.0
+
+
+def spec_parts(spec: str, manager: str) -> tuple[str, str]:
+ """A spec's name and exact pin: npm's name@version, pip's name==version, apt's name=version.
+ A range (>=, ~=, ...) is a name with no pin; the installer resolves it at build time."""
+ s = spec.strip()
+ if manager == "npm":
+ i = s.rfind("@")
+ return (s[:i], s[i + 1:]) if i > 0 else (s, "")
+ for sep in ("==", "="):
+ if sep in s:
+ n, v = s.split(sep, 1)
+ return n.strip(), v.strip()
+ for sep in (">=", "<=", "~=", "!=", ">", "<"):
+ if sep in s:
+ return s.split(sep, 1)[0].strip(), ""
+ return s, ""
+
+
+def _http_json(url: str) -> tuple[int, dict]:
+ req = urllib.request.Request(url, headers={"User-Agent": "harnessrouter-environments/1", "Accept": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=REGISTRY_TIMEOUT) as r:
+ return r.status, json.loads(r.read().decode("utf-8", "replace") or "{}")
+ except urllib.error.HTTPError as e:
+ return e.code, {}
+
+
+def _apt_lists() -> None:
+ """apt's package lists, refreshed at most every six hours: what a build's apt would see."""
+ global _apt_lists_at
+ if time.time() - _apt_lists_at < 6 * 3600:
+ return
+ subprocess.run(["apt-get", "update", "-qq"], capture_output=True, timeout=180, env=_tool_env())
+ _apt_lists_at = time.time()
+
+
+def check_package(manager: str, spec: str) -> dict:
+ """What the manager's registry says about a declared package before any build: whether the
+ name exists, its latest version, and whether an exact pin is published. pip asks PyPI, npm the
+ npm registry, apt this box's own package lists (the ones a build would download from). A typo
+ is refused at the moment it is typed instead of failing a build minutes later. `exists` is
+ None when the registry could not be asked; the build is then the check."""
+ manager = (manager or "").strip().lower()
+ if manager not in ("pip", "npm", "apt"):
+ raise HTTPException(400, "manager must be pip, npm or apt")
+ spec = (spec or "").strip()
+ if not _SPEC_RE.match(spec):
+ raise HTTPException(400, "that is not a package spec")
+ name, pin = spec_parts(spec, manager)
+ out = {"manager": manager, "name": name, "spec": spec, "exists": None, "latest": "", "version": "", "error": ""}
+ try:
+ if manager == "pip":
+ st, j = _http_json(f"https://pypi.org/pypi/{urllib.parse.quote(name)}/json")
+ if st == 404:
+ out.update(exists=False, error=f"{name} is not on PyPI")
+ return out
+ if st != 200:
+ raise RuntimeError(f"PyPI answered {st}")
+ info = j.get("info") or {}
+ out.update(exists=True, latest=str(info.get("version") or ""), name=str(info.get("name") or name))
+ versions = set((j.get("releases") or {}).keys())
+ elif manager == "npm":
+ st, j = _http_json("https://registry.npmjs.org/" + urllib.parse.quote(name, safe="@").replace("/", "%2F"))
+ if st == 404:
+ out.update(exists=False, error=f"{name} is not on the npm registry")
+ return out
+ if st != 200:
+ raise RuntimeError(f"the npm registry answered {st}")
+ out.update(exists=True, latest=str((j.get("dist-tags") or {}).get("latest") or ""))
+ versions = set((j.get("versions") or {}).keys())
+ else:
+ _apt_lists()
+ env = _tool_env()
+ r = subprocess.run(["apt-cache", "policy", name], capture_output=True, text=True, timeout=60, env=env)
+ cand = next((ln.split(":", 1)[1].strip() for ln in r.stdout.splitlines() if ln.strip().startswith("Candidate:")), "")
+ if not cand or cand == "(none)":
+ out.update(exists=False, error=f"{name} is not in this server's apt sources")
+ return out
+ out.update(exists=True, latest=cand)
+ m = subprocess.run(["apt-cache", "madison", name], capture_output=True, text=True, timeout=60, env=env)
+ versions = {ln.split("|")[1].strip() for ln in m.stdout.splitlines() if ln.count("|") >= 2}
+ if pin:
+ if pin in versions:
+ out["version"] = pin
+ else:
+ out["error"] = f"{name} {pin} is not published; the latest is {out['latest']}"
+ except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired) as e:
+ out.update(exists=None, error=f"the registry could not be asked: {str(e)[:120]}")
+ return out
+
+
def clean_specs(specs) -> list[str]:
"""Declared packages as short spec strings, each checked against one shape."""
out: list[str] = []
@@ -532,9 +629,14 @@ def _tool_env() -> dict:
return env
-def _run(log: list[str], cmd: list[str], cwd: str, env: dict, deadline: float, run_as: dict | None = None) -> None:
+def _run(log: list[str], cmd: list[str], cwd: str, env: dict, deadline: float, run_as: dict | None = None,
+ flush=None) -> None:
+ """One build command. `flush` writes the record after the command line and again after its
+ output, so a build's log is readable while the build runs, not only when it ends."""
left = max(1, int(deadline - time.time()))
log.append(f"$ {' '.join(cmd)}")
+ if flush:
+ flush()
try:
r = subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True, timeout=left, **(run_as or {}))
except subprocess.TimeoutExpired:
@@ -543,6 +645,8 @@ def _run(log: list[str], cmd: list[str], cwd: str, env: dict, deadline: float, r
log.append(r.stdout.rstrip()[-20000:])
if r.stderr.strip():
log.append(r.stderr.rstrip()[-20000:])
+ if flush:
+ flush()
if r.returncode != 0:
raise RuntimeError(f"{cmd[0]} exited {r.returncode}")
@@ -570,24 +674,24 @@ def _packages(dst: pathlib.Path, env: dict, run_as: dict | None = None) -> list[
return out
-def _apt_into_layer(log: list[str], dst: pathlib.Path, names: list[str], env: dict, scratch: str, deadline: float) -> None:
+def _apt_into_layer(log: list[str], dst: pathlib.Path, names: list[str], env: dict, scratch: str, deadline: float, flush=None) -> None:
"""System packages, unpacked into the layer rather than installed into the box: apt resolves
and downloads each named package with the dependencies the image lacks, and dpkg unpacks every
archive under <version>/apt, which a turn puts on PATH and LD_LIBRARY_PATH. The image's own
packages stay the image's; nothing here changes the container."""
cache = pathlib.Path(scratch) / "apt-archives"
cache.mkdir(parents=True, exist_ok=True)
- _run(log, ["apt-get", "update", "-qq"], str(dst), env, deadline)
+ _run(log, ["apt-get", "update", "-qq"], str(dst), env, deadline, flush=flush)
_run(log, ["apt-get", "install", "-y", "--download-only", "--reinstall", "-o", f"Dir::Cache::archives={cache}",
"-o", "Debug::NoLocking=1", *[n.split("=", 1)[0] if "=" in n and not n.startswith("=") else n for n in names]],
- str(dst), env, deadline)
+ str(dst), env, deadline, flush=flush)
debs = sorted(cache.glob("*.deb"))
if not debs:
raise RuntimeError("apt downloaded nothing for " + ", ".join(names))
out = dst / "apt"
out.mkdir(exist_ok=True)
for deb in debs:
- _run(log, ["dpkg", "-x", str(deb), str(out)], str(dst), env, deadline)
+ _run(log, ["dpkg", "-x", str(deb), str(out)], str(dst), env, deadline, flush=flush)
(out / ".packages").write_text("\n".join(d.name for d in debs) + "\n")
log.append(f"apt: unpacked {len(debs)} archive(s) into apt/")
@@ -661,8 +765,20 @@ def _build(env_id: str, n: int, slug: str, activate: bool, spec: dict | None = 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, "runtime": {},
+ "packages": [], "files": 0, "bytes": 0, "log": log, "runtime": {}, "stage": "starting",
"declared": {"pip": pip_specs, "npm": npm_specs, "apt": apt_specs}}
+
+ def flush() -> None:
+ """The record on disk IS what the owner sees while the build runs: written as each step ends."""
+ try:
+ _write_record(dst, rec)
+ except OSError:
+ pass
+
+ def stage(name: str) -> None:
+ rec["stage"] = name
+ flush()
+
try:
_claim(env_id)
gid = env_gid(env_id)
@@ -674,6 +790,7 @@ def _build(env_id: str, n: int, slug: str, activate: bool, spec: dict | None = N
os.chmod(dst.parent, 0o750)
deadline = time.time() + BUILD_TIMEOUT
env = _tool_env()
+ stage("copying files")
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])
@@ -687,53 +804,58 @@ def _build(env_id: str, n: int, slug: str, activate: bool, spec: dict | None = N
_own(dst, gid, gid)
os.chown(scratch, gid, gid)
if pip_specs or (dst / "requirements.txt").is_file() or (dst / "pyproject.toml").is_file():
+ stage("python packages")
# The interpreter the owner chose, when the box has it; the image's python3 otherwise.
python = (shutil.which(f"python{want_py}", path=env.get("PATH")) if want_py else None) \
or shutil.which("python3", path=env.get("PATH")) or "python3"
- _run(log, [python, "-m", "venv", ".venv"], str(dst), env, deadline, as_build)
+ _run(log, [python, "-m", "venv", ".venv"], str(dst), env, deadline, as_build, flush)
pip = str(dst / ".venv" / "bin" / "pip")
if (dst / "requirements.txt").is_file():
- _run(log, [pip, "install", "-r", "requirements.txt"], str(dst), env, deadline, as_build)
+ _run(log, [pip, "install", "-r", "requirements.txt"], str(dst), env, deadline, as_build, flush)
if (dst / "pyproject.toml").is_file():
- _run(log, [pip, "install", "."], str(dst), env, deadline, as_build)
+ _run(log, [pip, "install", "."], str(dst), env, deadline, as_build, flush)
if pip_specs:
- _run(log, [pip, "install", *pip_specs], str(dst), env, deadline, as_build)
+ _run(log, [pip, "install", *pip_specs], str(dst), env, deadline, as_build, flush)
try:
rec["runtime"]["python"] = subprocess.run([str(dst / ".venv" / "bin" / "python"), "-c", "import platform; print(platform.python_version())"],
capture_output=True, text=True, timeout=30, env=env, **as_build).stdout.strip()
except (OSError, subprocess.TimeoutExpired):
pass
if npm_specs or (dst / "package.json").is_file():
+ stage("node packages")
npm = shutil.which("npm", path=env.get("PATH")) or "npm"
if (dst / "package.json").is_file():
_run(log, [npm, "ci" if (dst / "package-lock.json").is_file() else "install", "--no-audit", "--no-fund"],
- str(dst), env, deadline, as_build)
+ str(dst), env, deadline, as_build, flush)
if npm_specs:
if not (dst / "package.json").is_file():
(dst / "package.json").write_text(json.dumps({"name": slug or "environment", "version": "0.0.0", "private": True}, indent=2) + "\n")
if as_build:
os.chown(dst / "package.json", gid, gid)
- _run(log, [npm, "install", "--no-audit", "--no-fund", "--save", *npm_specs], str(dst), env, deadline, as_build)
+ _run(log, [npm, "install", "--no-audit", "--no-fund", "--save", *npm_specs], str(dst), env, deadline, as_build, flush)
try:
rec["runtime"]["node"] = subprocess.run(["node", "--version"], capture_output=True, text=True, timeout=10, env=env).stdout.strip().lstrip("v")
except (OSError, subprocess.TimeoutExpired):
pass
if apt_specs: # apt-get and dpkg -x run none of the packages' code; apt's lists need root
- _apt_into_layer(log, dst, apt_specs, env, scratch, deadline)
+ stage("system packages")
+ _apt_into_layer(log, dst, apt_specs, env, scratch, deadline, flush)
if (dst / "setup.sh").is_file():
- _run(log, ["bash", "setup.sh"], str(dst), {**env, "ENV_ROOT": str(dst)}, deadline, as_build)
+ stage("setup.sh")
+ _run(log, ["bash", "setup.sh"], str(dst), {**env, "ENV_ROOT": str(dst)}, deadline, as_build, flush)
+ stage("finishing")
rec["packages"] = _packages(dst, env, as_build)
if (dst / "apt").is_dir():
rec["packages"] += _apt_packages(dst)
_read_only(dst, gid)
rec["files"], rec["bytes"] = _size(dst)
- rec["status"], rec["finished_at"] = "ready", int(time.time())
+ rec["status"], rec["finished_at"], rec["stage"] = "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]
+ rec["status"], rec["finished_at"], rec["error"], rec["stage"] = "failed", int(time.time()), str(e)[:500], ""
log.append(f"failed: {e}")
try:
_write_record(dst, rec)
@@ -939,6 +1061,11 @@ def r_runtimes() -> dict:
return runtimes()
[email protected]("/environments/packages/check")
+def r_check_package(manager: str, spec: str) -> dict:
+ return check_package(manager, spec)
+
+
@router.post("/environments/{env_id}/build")
async def r_build(env_id: str, version: int, slug: str, request: Request, activate: int = 1) -> dict:
if not slug_ok(slug):
diff --git a/runner/tests/test_environments.py b/runner/tests/test_environments.py
index cdd237e7..5785ed6d 100644
--- a/runner/tests/test_environments.py
+++ b/runner/tests/test_environments.py
@@ -212,3 +212,71 @@ def test_declared_specs_are_checked_and_the_runtimes_are_what_the_box_has(store)
E.start_build("henv_d", 1, "declared", spec={"pip": [], "npm": [], "apt": [], "python": rt["python"][-1] if rt["python"] else ""})
rec = _wait("henv_d", 1)
assert rec["status"] == "ready" and rec["declared"] == {"pip": [], "npm": [], "apt": []}
+
+
+def test_a_build_writes_its_record_as_each_step_ends_with_the_stage(store, monkeypatch):
+ """The record on disk is what the owner reads while a build runs: written as steps end, with
+ the step's name, not only when the build is over."""
+ writes: list[tuple[str, int]] = []
+ real = E._write_record
+
+ def spy(dst, rec):
+ writes.append((str(rec.get("stage")), len(rec.get("log") or [])))
+ real(dst, rec)
+ monkeypatch.setattr(E, "_write_record", spy)
+ E.write_file("henv_s", "requirements.txt", b"")
+ E.write_file("henv_s", "setup.sh", b"#!/bin/sh\necho preparing\n")
+ E.start_build("henv_s", 1, "staged")
+ rec = _wait("henv_s", 1)
+ assert rec["status"] == "ready" and rec["stage"] == ""
+ stages = [w[0] for w in writes]
+ assert stages[0] == "starting" and "copying files" in stages and "python packages" in stages and "setup.sh" in stages and "finishing" in stages
+ assert len(writes) >= 8, writes # the start, each stage, and after each command's line and output
+ logs = [w[1] for w in writes]
+ assert logs == sorted(logs) and logs[-1] > logs[0] # the log only grows between writes
+
+
+def test_a_package_check_asks_the_registry_and_refuses_what_is_not_there(monkeypatch):
+ answers = {
+ "https://pypi.org/pypi/numpy/json": (200, {"info": {"name": "numpy", "version": "2.5.3"}, "releases": {"2.5.3": [], "2.5.2": []}}),
+ "https://pypi.org/pypi/numpyy/json": (404, {}),
+ "https://registry.npmjs.org/@types%2Fnode": (200, {"dist-tags": {"latest": "24.1.0"}, "versions": {"24.1.0": {}, "22.0.0": {}}}),
+ "https://registry.npmjs.org/no-such-pkg-xyz": (404, {}),
+ }
+ monkeypatch.setattr(E, "_http_json", lambda url: answers.get(url, (503, {})))
+ ok = E.check_package("pip", "numpy")
+ assert ok["exists"] is True and ok["latest"] == "2.5.3" and ok["version"] == "" and not ok["error"]
+ pinned = E.check_package("pip", "numpy==2.5.2")
+ assert pinned["exists"] is True and pinned["version"] == "2.5.2"
+ missing_pin = E.check_package("pip", "numpy==9.9")
+ assert missing_pin["exists"] is True and missing_pin["version"] == "" and "9.9 is not published" in missing_pin["error"] and "2.5.3" in missing_pin["error"]
+ gone = E.check_package("pip", "numpyy")
+ assert gone["exists"] is False and "not on PyPI" in gone["error"]
+ scoped = E.check_package("npm", "@types/[email protected]")
+ assert scoped["exists"] is True and scoped["name"] == "@types/node" and scoped["version"] == "24.1.0"
+ assert E.check_package("npm", "no-such-pkg-xyz")["exists"] is False
+ down = E.check_package("pip", "requests")
+ assert down["exists"] is None and "could not be asked" in down["error"]
+ with pytest.raises(HTTPException):
+ E.check_package("cargo", "serde")
+ with pytest.raises(HTTPException):
+ E.check_package("pip", "not a spec !!")
+ # apt: the box's own lists
+ calls = []
+
+ def fake_run(cmd, **kw):
+ calls.append(cmd[:2])
+ class R:
+ stdout = ""
+ returncode = 0
+ out = R()
+ if cmd[:2] == ["apt-cache", "policy"]:
+ out.stdout = "jq:\n Installed: (none)\n Candidate: 1.7.1-3\n" if cmd[2] == "jq" else "N: Unable to locate package nope\n"
+ if cmd[:2] == ["apt-cache", "madison"]:
+ out.stdout = " jq | 1.7.1-3 | http://deb.debian.org bookworm/main amd64 Packages\n"
+ return out
+ monkeypatch.setattr(E.subprocess, "run", fake_run)
+ monkeypatch.setattr(E, "_apt_lists", lambda: None)
+ apt = E.check_package("apt", "jq=1.7.1-3")
+ assert apt["exists"] is True and apt["latest"] == "1.7.1-3" and apt["version"] == "1.7.1-3"
+ assert E.check_package("apt", "nope")["exists"] is False
diff --git a/ui/src/app/(app)/environments/[id]/page.tsx b/ui/src/app/(app)/environments/[id]/page.tsx
index c470f79e..7f8ea97b 100644
--- a/ui/src/app/(app)/environments/[id]/page.tsx
+++ b/ui/src/app/(app)/environments/[id]/page.tsx
@@ -14,7 +14,7 @@ import {
buildEnvironment, deleteEnvironmentPath, environmentHarnesses,
fmtBytes, getEnvironment, getEnvironmentBuild, importEnvironmentArchive, importEnvironmentGit, listEnvironmentFiles, listRuntimes,
makeEnvironmentDir, readEnvironmentFile, updateEnvironment, writeEnvironmentFile,
- type Environment, type EnvironmentBuildRecord, type EnvironmentFileEntry, type EnvironmentRuntimes, type Manager,
+ type Environment, type EnvironmentBuildRecord, type EnvironmentFileEntry, type EnvironmentRuntimes, type Manager, checkPackage,
} from '@/lib/environments';
const MANAGERS: Manager[] = ['pip', 'npm', 'apt'];
@@ -80,6 +80,10 @@ export default function EnvironmentPage() {
const [python, setPython] = useState('');
const [runtimes, setRuntimes] = useState<EnvironmentRuntimes | null>(null);
const [spec, setSpec] = useState('');
+ const [checking, setChecking] = useState(false); // the registry is being asked about the spec in the Add field
+ const [addErr, setAddErr] = useState(''); // what the registry said when it refused the spec
+ const [resolved, setResolved] = useState<Record<string, string>>({}); // `${manager}:${name}` → the version the registry reported on Add
+ const [now, setNow] = useState(() => Date.now()); // ticks while a build runs, for the elapsed seconds
const [pkgDirty, setPkgDirty] = useState(false);
const [gitOpen, setGitOpen] = useState(false);
const [menu, setMenu] = useState<'add' | null>(null);
@@ -107,7 +111,8 @@ export default function EnvironmentPage() {
useEffect(() => {
if (env?.status !== 'building') return;
const t = setInterval(() => void reload(), 3000);
- return () => clearInterval(t);
+ const tick = setInterval(() => setNow(Date.now()), 1000);
+ return () => { clearInterval(t); clearInterval(tick); };
}, [env?.status, reload]);
const tree = useMemo(() => treeOf(entries || []), [entries]);
@@ -139,15 +144,39 @@ export default function EnvironmentPage() {
}
await buildEnvironment(id);
});
- const addSpec = () => {
+ /** Add asks the registry first: a name that is not there, or a pin that was never published, is
+ * refused here with the registry's own answer instead of failing a build minutes later. What
+ * the registry reported (the pin, else the latest) is what the row shows until a build installs it. */
+ const addSpec = async () => {
const t = spec.trim();
- if (!t || !declared) return;
- setDeclared({ ...declared, [segment]: [...declared[segment].filter((x) => specParts(x, segment).name !== specParts(t, segment).name), t] });
- setSpec(''); setPkgDirty(true);
+ if (!t || !declared || checking) return;
+ setChecking(true); setAddErr('');
+ try {
+ const c = await checkPackage(segment, t);
+ if (c.exists === false || (c.exists && c.error)) { setAddErr(c.error || `${c.name} was not found.`); return; }
+ if (c.error) setAddErr(c.error); // the registry could not be asked: added anyway; the build is then the check
+ const name = specParts(t, segment).name;
+ setDeclared({ ...declared, [segment]: [...declared[segment].filter((x) => specParts(x, segment).name !== name), t] });
+ setResolved((r) => ({ ...r, [`${segment}:${name.toLowerCase()}`]: c.version || c.latest || '' }));
+ setSpec(''); setPkgDirty(true);
+ } catch (e) { setAddErr(e instanceof Error ? e.message : 'The package could not be checked.'); }
+ finally { setChecking(false); }
};
const dropSpec = (m: Manager, x: string) => { if (!declared) return; setDeclared({ ...declared, [m]: declared[m].filter((y) => y !== x) }); setPkgDirty(true); };
const dirty = editing !== null || pkgDirty;
const installedVersion = (m: Manager, name: string) => env?.packages.find((p) => p.manager === m && p.name.toLowerCase() === name.toLowerCase())?.version || '';
+ /** What a row's version column says: the version the active build installed, else that a build
+ * is installing it now, else that it installs on save, with the version the registry reported. */
+ const rowState = (m: Manager, x: string): { text: string; note: string } => {
+ const p = specParts(x, m);
+ const installed = installedVersion(m, p.name);
+ if (installed && (!p.version || p.version === installed)) return { text: installed, note: '' };
+ const known = p.version || resolved[`${m}:${p.name.toLowerCase()}`] || '';
+ if (env?.status === 'building') return { text: known, note: 'installing' };
+ return { text: known || 'latest', note: 'installs on save' };
+ };
+ const logTail = (log: string, n: number) => log.split('\n').filter((l) => l.trim()).slice(-n).join('\n');
+ const buildElapsed = build?.started_at ? Math.max(0, Math.round(now / 1000 - build.started_at)) : null;
const createPath = () => act('create', async () => {
if (!newPath?.value.trim()) return;
const base = parentDir(); const p = (base ? base + '/' : '') + newPath.value.trim().replace(/^\/+/, '');
@@ -203,6 +232,16 @@ export default function EnvironmentPage() {
<div className="env-body">
{err && <div className="hr-error" role="alert">{err}</div>}
+ {env?.status === 'building' && (
+ <div className="env-build-live" role="status" aria-live="polite">
+ <div className="env-build-live-head">
+ <strong>Building version {build?.version ?? env.latestVersion ?? ''}</strong>
+ {build?.stage && <span>{build.stage}</span>}
+ {buildElapsed !== null && <span>{buildElapsed} s</span>}
+ </div>
+ {build?.log && <pre className="env-log">{logTail(build.log, 12)}</pre>}
+ </div>
+ )}
{env?.status === 'failed' && build?.error && (
<div className="hr-error env-build-failed" role="alert">
<div><strong>The last build failed.</strong> {build.error} Fix the packages or the files and save again.</div>
@@ -238,9 +277,9 @@ export default function EnvironmentPage() {
<select value={runtimes?.os.version ?? ''} disabled><option value={runtimes?.os.version ?? ''}>{runtimes?.os.version ?? ''}</option></select>
)}
</label>
- <form className="env-add" onSubmit={(ev) => { ev.preventDefault(); addSpec(); }}>
- <input value={spec} placeholder={SPEC_HINT[segment]} aria-label={`Add a ${segment} package`} spellCheck={false} onChange={(ev) => setSpec(ev.target.value)} />
- <button className="button" type="submit" disabled={!spec.trim()}>Add</button>
+ <form className="env-add" onSubmit={(ev) => { ev.preventDefault(); void addSpec(); }}>
+ <input value={spec} placeholder={SPEC_HINT[segment]} aria-label={`Add a ${segment} package`} spellCheck={false} onChange={(ev) => { setSpec(ev.target.value); if (addErr) setAddErr(''); }} />
+ <button className="button" type="submit" disabled={!spec.trim() || checking}>{checking ? 'Checking\u2026' : 'Add'}</button>
</form>
</>
)}
@@ -333,12 +372,14 @@ export default function EnvironmentPage() {
{tab === 'packages' && declared && (
<div className="env-packages">
+ {addErr && <div className="env-add-error" role="alert">{addErr}</div>}
{declared[segment].length ? declared[segment].map((x) => {
const p = specParts(x, segment);
+ const st = rowState(segment, x);
return (
<div key={x} className="env-pkg">
<code className="env-pkg-name">{p.name}</code>
- <span className="env-pkg-version">{p.version || installedVersion(segment, p.name) || 'latest'}</span>
+ <span className="env-pkg-version">{st.text}{st.note && <em className="env-pkg-note">{st.note}</em>}</span>
<button className="env-pkg-x" type="button" aria-label={`Remove ${p.name}`} onClick={() => dropSpec(segment, x)}><iconify-icon icon="tabler:x"></iconify-icon></button>
</div>
);
diff --git a/ui/src/app/hr.css b/ui/src/app/hr.css
index d0cec12b..cf99f338 100644
--- a/ui/src/app/hr.css
+++ b/ui/src/app/hr.css
@@ -1192,6 +1192,12 @@ body.hr-resizing iframe { pointer-events: none; }
.env-pkg-empty { padding: 20px; font-size: 13px; color: var(--muted); }
.env-pkg-empty code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
.env-build-failed { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
+.env-build-live { flex: none; display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; padding: 12px 16px; background: var(--surface); border: 1px solid var(--line); border-radius: 10px; }
+.env-build-live-head { display: flex; align-items: center; gap: 14px; font-size: 13px; color: var(--muted); font-variant-numeric: tabular-nums; }
+.env-build-live-head strong { color: var(--ink); }
+.env-build-live .env-log { max-height: 180px; }
+.env-add-error { padding: 10px 20px; font-size: 13px; color: #b91c1c; background: #fef2f2; border-bottom: 1px solid var(--line); }
+.env-pkg-note { margin-left: 10px; font-style: normal; color: var(--muted); opacity: .75; }
.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); }
@media (max-width: 768px) {
.env-root { height: calc(100vh - var(--v2-mobilebar-h)); } /* under the mobile bar, which exists at this width only */
diff --git a/ui/src/lib/environments.ts b/ui/src/lib/environments.ts
index dd838964..5a8c2b84 100644
--- a/ui/src/lib/environments.ts
+++ b/ui/src/lib/environments.ts
@@ -10,6 +10,7 @@ export interface EnvironmentPackage { manager: string; name: string; version: st
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;
+ stage?: string; // the step a running build is on; empty once it ended
}
export interface Environment {
id: string; object: 'environment'; name: string; slug: string; description: string; entry: string;
@@ -27,6 +28,7 @@ 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;
+ stage?: string; // the step a running build is on; empty once it ended
}
export type Manager = 'pip' | 'npm' | 'apt';
export interface DeclaredPackage { name: string; version: string; spec: string }
@@ -45,6 +47,11 @@ export const deleteEnvironment = (id: string) => gw<{ id: string; deleted: boole
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`);
+// What the manager's registry says about a spec before any build: whether the name exists, its
+// latest version, whether an exact pin is published. exists is null when the registry could not be asked.
+export interface PackageCheck { manager: Manager; name: string; spec: string; exists: boolean | null; latest: string; version: string; error: string }
+export const checkPackage = (manager: Manager, spec: string) =>
+ gw<PackageCheck>('GET', `/v1/environments/packages/check?manager=${manager}&spec=${encodeURIComponent(spec)}`);
export const getEnvironmentBuild = (id: string, version: number) =>
gw<EnvironmentBuildRecord>('GET', `/v1/environments/${id}/builds/${version}`);
export const activateEnvironmentVersion = (id: string, version: number) =>