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: packages are declared per manager, as the design draws the Packages tab (#325)

github-actions[bot]c928f6fbbc0d
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 0e5923c9..85d78aad 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -55,6 +55,8 @@ 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
+ # the same order runner/environments.py::apply_env sets: apt tools, then node_modules/.bin, then the venv first
+ for d in "$HR_ENVIRONMENT/apt/bin" "$HR_ENVIRONMENT/apt/usr/local/bin" "$HR_ENVIRONMENT/apt/usr/bin"; do [ -d "$d" ] && PATH="$d:$PATH"; done
[ -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
diff --git a/gateway/app.py b/gateway/app.py
index 9f503dfb..dd19a4aa 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -15309,6 +15309,37 @@ 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>")
+ packages: dict | None = None # declared per manager: {"pip": ["moviepy==2.1.1"], "npm": ["[email protected]"], "apt": ["ffmpeg"]}
+ runtime: dict | None = None # {"python": "3.12"}: the interpreter a build makes the venv with
+
+
+_ENV_SPEC_RE = re.compile(r"^@?[A-Za-z0-9][A-Za-z0-9._/+-]{0,99}(?:(?:==|>=|<=|~=|!=|@|=)[A-Za-z0-9._*+^~<>-]{0,60})?$")
+_ENV_MANAGERS = ("pip", "npm", "apt")
+
+
+def _env_specs(packages: dict | None) -> dict:
+ """The declared packages, each a short spec string of one shape, at most 200 per manager."""
+ out = {}
+ for m in _ENV_MANAGERS:
+ seen: list[str] = []
+ for x in ((packages or {}).get(m) or []):
+ t = str(x or "").strip()
+ if t and _ENV_SPEC_RE.match(t) and t not in seen and len(seen) < 200:
+ seen.append(t)
+ out[m] = seen
+ return out
+
+
+def _env_spec_parts(spec: str, manager: str) -> dict:
+ """A spec string as the console shows it: name and version."""
+ if manager == "npm":
+ i = spec.rfind("@")
+ return {"name": spec[:i], "version": spec[i + 1:]} if i > 0 else {"name": spec, "version": ""}
+ for sep in ("==", ">=", "<=", "~=", "!=", "="):
+ if sep in spec:
+ n, v = spec.split(sep, 1)
+ return {"name": n, "version": (sep if sep not in ("==", "=") else "") + v}
+ return {"name": spec, "version": ""}
def _env_slug(name: str) -> str:
@@ -15432,6 +15463,10 @@ def _environment_out(v: dict) -> dict:
"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"), []),
+ # What the owner declared, per manager, as the console edits it; a build installs these
+ # beside the project's own manifests.
+ "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")}
if latest_rec else None),
@@ -15468,10 +15503,13 @@ async def create_environment(body: EnvironmentBody, request: Request) -> dict:
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))
+ specs = _env_specs(body.packages)
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": "[]",
+ "pkg_pip": json.dumps(specs["pip"]), "pkg_npm": json.dumps(specs["npm"]), "pkg_apt": json.dumps(specs["apt"]),
+ "rt_python": str((body.runtime or {}).get("python") or "").strip()[:16],
"created_at": now, "updated_at": now, "deleted": "0"}
await _vg_upsert("Environment", eid, props)
return _environment_out({"id": eid, **props})
@@ -15495,6 +15533,19 @@ async def list_environments(request: Request) -> dict:
return {"environments": items}
[email protected]("/v1/environments/runtimes")
+async def environment_runtimes(request: Request) -> dict:
+ """What a build can be made with on this instance: the Python minors present, the Node major,
+ the OS release for apt. The console offers these and nothing else."""
+ p = await _principal(request)
+ if not p.get("org"):
+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")
+ r = await _env_runner("GET", "/environments/runtimes", "runtimes")
+ if r.status_code != 200:
+ raise _env_runner_error(r, "the runtimes could not be read")
+ return 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)
@@ -15506,9 +15557,14 @@ async def update_environment(env_id: str, body: EnvironmentBody, request: Reques
"""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))})
+ props = {"name": name, "description": str(body.description or "").strip(), "entry": str(body.entry or "").strip(),
+ "updated_at": str(int(time.time() * 1000))}
+ if body.packages is not None:
+ specs = _env_specs(body.packages)
+ props.update({"pkg_pip": json.dumps(specs["pip"]), "pkg_npm": json.dumps(specs["npm"]), "pkg_apt": json.dumps(specs["apt"])})
+ if body.runtime is not None:
+ props["rt_python"] = str((body.runtime or {}).get("python") or "").strip()[:16]
+ await _vg_upsert("Environment", env_id, props)
return _environment_out(await _environment_refresh(await _environment_vertex(str(v.get("org")), env_id) or v))
@@ -15630,8 +15686,11 @@ async def environment_build(env_id: str, request: Request) -> dict:
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
+ spec = {m: json.loads(v.get(f"pkg_{m}") or "[]") for m in _ENV_MANAGERS}
+ spec["python"] = str(v.get("rt_python") or "")
r = await _env_runner("POST", f"/environments/{env_id}/build", env_id,
- params={"version": n, "slug": str(v.get("slug") or ""), "activate": 1})
+ params={"version": n, "slug": str(v.get("slug") or ""), "activate": 1},
+ content=json.dumps(spec).encode())
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),
diff --git a/gateway/tests/test_environments.py b/gateway/tests/test_environments.py
index 4ab33a98..28a479a1 100644
--- a/gateway/tests/test_environments.py
+++ b/gateway/tests/test_environments.py
@@ -5,6 +5,7 @@ rollback, the harness and task references, deletion."""
from __future__ import annotations
import io
+import json
import os
import sys
import time
@@ -160,3 +161,34 @@ def test_environments_are_scoped_to_the_workspace(api):
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
+
+
+def test_declared_packages_and_the_runtime_are_kept_and_handed_to_the_build(api, monkeypatch):
+ eid = api.post("/v1/environments", json={"name": "declared-env", "packages": {"pip": ["pyyaml==6.0.2", " bad spec!", "pyyaml==6.0.2"], "npm": ["[email protected]", "@scope/[email protected]"], "apt": ["ffmpeg"]}, "runtime": {"python": "3.12"}}).json()["id"]
+ e = api.get(f"/v1/environments/{eid}").json()
+ assert [x["spec"] for x in e["declared"]["pip"]] == ["pyyaml==6.0.2"] and e["declared"]["pip"][0] == {"name": "pyyaml", "version": "6.0.2", "spec": "pyyaml==6.0.2"}
+ assert e["declared"]["npm"][1] == {"name": "@scope/pkg", "version": "1.0.0", "spec": "@scope/[email protected]"}
+ assert e["declared"]["apt"] == [{"name": "ffmpeg", "version": "", "spec": "ffmpeg"}] and e["runtime"] == {"python": "3.12"}
+ # an update without packages leaves them; one with packages replaces them
+ api.put(f"/v1/environments/{eid}", json={"name": "declared-env", "entry": "python3 run.py"})
+ assert [x["spec"] for x in api.get(f"/v1/environments/{eid}").json()["declared"]["pip"]] == ["pyyaml==6.0.2"]
+ api.put(f"/v1/environments/{eid}", json={"name": "declared-env", "packages": {"pip": [], "npm": [], "apt": []}, "runtime": {"python": ""}})
+ e = api.get(f"/v1/environments/{eid}").json()
+ assert e["declared"] == {"pip": [], "npm": [], "apt": []} and e["runtime"] == {"python": ""}
+ # the build receives the declared lists and the runtime as its body
+ seen = {}
+ real = app._env_runner
+
+ async def spy(method, path, env_id, **kw):
+ if path.endswith("/build") and method == "POST":
+ seen["body"] = json.loads(kw.get("content") or b"{}")
+ return await real(method, path, env_id, **kw)
+ monkeypatch.setattr(app, "_env_runner", spy)
+ api.put(f"/v1/environments/{eid}", json={"name": "declared-env", "packages": {"pip": ["pyyaml==6.0.2"]}, "runtime": {"python": "3.12"}})
+ api.put(f"/v1/environments/{eid}/files/run.py", content=b"print(1)\n")
+ assert api.post(f"/v1/environments/{eid}/build").status_code == 200
+ assert seen["body"] == {"pip": ["pyyaml==6.0.2"], "npm": [], "apt": [], "python": "3.12"}
+ _wait_build(api, eid, 1) # the runner installs it (network) or fails; either way the record answers
+ monkeypatch.setattr(app, "_env_runner", real)
+ r = api.get("/v1/environments/runtimes")
+ assert r.status_code == 200 and isinstance(r.json().get("python"), list) and "os" in r.json()
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 773c8bd5..7089aebe 100644
--- a/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json
+++ b/protocol/conformance/uhp_conformance/uhp-2026-09-28.schema.json
@@ -1196,6 +1196,42 @@
"$ref": "#/$defs/EnvironmentPackage"
}
},
+ "declared": {
+ "type": "object",
+ "description": "What the owner declared, per manager, as the build installs it beside the project's own\nmanifests: `pip` (`name==1.0`), `npm` (`[email protected]`), `apt` (`name`). Each entry carries\nthe spec as written and its parsed name and version.\n",
+ "properties": {
+ "pip": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/DeclaredPackage"
+ }
+ },
+ "npm": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/DeclaredPackage"
+ }
+ },
+ "apt": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/DeclaredPackage"
+ }
+ }
+ }
+ },
+ "runtime": {
+ "type": "object",
+ "description": "The interpreter a build makes the virtual environment with; empty means the server's default.",
+ "properties": {
+ "python": {
+ "type": "string",
+ "examples": [
+ "3.12"
+ ]
+ }
+ }
+ },
"versions": {
"type": "array",
"items": {
@@ -1224,6 +1260,70 @@
},
"additionalProperties": true
},
+ "DeclaredPackage": {
+ "type": "object",
+ "required": [
+ "spec"
+ ],
+ "properties": {
+ "spec": {
+ "type": "string",
+ "description": "As written: moviepy==2.1.1, [email protected], ffmpeg"
+ },
+ "name": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentRuntimes": {
+ "type": "object",
+ "description": "What a build can be made with on this server, and nothing that is not there.",
+ "properties": {
+ "python": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "examples": [
+ [
+ "3.12",
+ "3.13"
+ ]
+ ]
+ },
+ "node": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "examples": [
+ [
+ "22"
+ ]
+ ]
+ },
+ "os": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ }
+ },
+ "apt": {
+ "type": "boolean",
+ "description": "Whether apt packages can be declared here."
+ }
+ },
+ "additionalProperties": true
+ },
"EnvironmentPackage": {
"type": "object",
"required": [
@@ -1370,6 +1470,38 @@
},
"entry": {
"type": "string"
+ },
+ "packages": {
+ "type": "object",
+ "description": "Declared packages per manager, as spec strings; omitted on update means unchanged.",
+ "properties": {
+ "pip": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "npm": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "apt": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "runtime": {
+ "type": "object",
+ "properties": {
+ "python": {
+ "type": "string"
+ }
+ }
}
},
"additionalProperties": true
diff --git a/protocol/schema/uhp-2026-09-28.openapi.yaml b/protocol/schema/uhp-2026-09-28.openapi.yaml
index a3c4568a..6337b089 100644
--- a/protocol/schema/uhp-2026-09-28.openapi.yaml
+++ b/protocol/schema/uhp-2026-09-28.openapi.yaml
@@ -254,6 +254,18 @@ paths:
'409': { $ref: '#/components/responses/Conflict' }
'422': { $ref: '#/components/responses/UnprocessableEntity' }
+ /v1/environments/runtimes:
+ get:
+ tags: [Environments]
+ operationId: listEnvironmentRuntimes
+ summary: The runtimes a build can be made with here
+ responses:
+ '200':
+ description: The runtimes
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/EnvironmentRuntimes' }
+
/v1/environments/{environment_id}:
parameters:
- $ref: '#/components/parameters/EnvironmentId'
@@ -1622,6 +1634,21 @@ components:
type: array
description: What the active build installed, as the package managers report it.
items: { $ref: '#/components/schemas/EnvironmentPackage' }
+ declared:
+ type: object
+ description: |
+ What the owner declared, per manager, as the build installs it beside the project's own
+ manifests: `pip` (`name==1.0`), `npm` (`[email protected]`), `apt` (`name`). Each entry carries
+ the spec as written and its parsed name and version.
+ properties:
+ pip: { type: array, items: { $ref: '#/components/schemas/DeclaredPackage' } }
+ npm: { type: array, items: { $ref: '#/components/schemas/DeclaredPackage' } }
+ apt: { type: array, items: { $ref: '#/components/schemas/DeclaredPackage' } }
+ runtime:
+ type: object
+ description: The interpreter a build makes the virtual environment with; empty means the server's default.
+ properties:
+ python: { type: string, examples: ['3.12'] }
versions:
type: array
items: { $ref: '#/components/schemas/EnvironmentVersion' }
@@ -1634,6 +1661,29 @@ components:
updatedAt: { type: integer, description: Unix milliseconds }
additionalProperties: true
+ DeclaredPackage:
+ type: object
+ required: [spec]
+ properties:
+ spec: { type: string, description: 'As written: moviepy==2.1.1, [email protected], ffmpeg' }
+ name: { type: string }
+ version: { type: string }
+ additionalProperties: true
+
+ EnvironmentRuntimes:
+ type: object
+ description: What a build can be made with on this server, and nothing that is not there.
+ properties:
+ python: { type: array, items: { type: string }, examples: [['3.12', '3.13']] }
+ node: { type: array, items: { type: string }, examples: [['22']] }
+ os:
+ type: object
+ properties:
+ name: { type: string }
+ version: { type: string }
+ apt: { type: boolean, description: Whether apt packages can be declared here. }
+ additionalProperties: true
+
EnvironmentPackage:
type: object
required: [manager, name]
@@ -1682,6 +1732,17 @@ components:
name: { type: string, description: Must start with a letter or digit; the slug derives from it. }
description: { type: string }
entry: { type: string }
+ packages:
+ type: object
+ description: Declared packages per manager, as spec strings; omitted on update means unchanged.
+ properties:
+ pip: { type: array, items: { type: string } }
+ npm: { type: array, items: { type: string } }
+ apt: { type: array, items: { type: string } }
+ runtime:
+ type: object
+ properties:
+ python: { type: string }
additionalProperties: true
EnvironmentList:
diff --git a/protocol/schema/uhp-2026-09-28.schema.json b/protocol/schema/uhp-2026-09-28.schema.json
index 773c8bd5..7089aebe 100644
--- a/protocol/schema/uhp-2026-09-28.schema.json
+++ b/protocol/schema/uhp-2026-09-28.schema.json
@@ -1196,6 +1196,42 @@
"$ref": "#/$defs/EnvironmentPackage"
}
},
+ "declared": {
+ "type": "object",
+ "description": "What the owner declared, per manager, as the build installs it beside the project's own\nmanifests: `pip` (`name==1.0`), `npm` (`[email protected]`), `apt` (`name`). Each entry carries\nthe spec as written and its parsed name and version.\n",
+ "properties": {
+ "pip": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/DeclaredPackage"
+ }
+ },
+ "npm": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/DeclaredPackage"
+ }
+ },
+ "apt": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/DeclaredPackage"
+ }
+ }
+ }
+ },
+ "runtime": {
+ "type": "object",
+ "description": "The interpreter a build makes the virtual environment with; empty means the server's default.",
+ "properties": {
+ "python": {
+ "type": "string",
+ "examples": [
+ "3.12"
+ ]
+ }
+ }
+ },
"versions": {
"type": "array",
"items": {
@@ -1224,6 +1260,70 @@
},
"additionalProperties": true
},
+ "DeclaredPackage": {
+ "type": "object",
+ "required": [
+ "spec"
+ ],
+ "properties": {
+ "spec": {
+ "type": "string",
+ "description": "As written: moviepy==2.1.1, [email protected], ffmpeg"
+ },
+ "name": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": true
+ },
+ "EnvironmentRuntimes": {
+ "type": "object",
+ "description": "What a build can be made with on this server, and nothing that is not there.",
+ "properties": {
+ "python": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "examples": [
+ [
+ "3.12",
+ "3.13"
+ ]
+ ]
+ },
+ "node": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "examples": [
+ [
+ "22"
+ ]
+ ]
+ },
+ "os": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "version": {
+ "type": "string"
+ }
+ }
+ },
+ "apt": {
+ "type": "boolean",
+ "description": "Whether apt packages can be declared here."
+ }
+ },
+ "additionalProperties": true
+ },
"EnvironmentPackage": {
"type": "object",
"required": [
@@ -1370,6 +1470,38 @@
},
"entry": {
"type": "string"
+ },
+ "packages": {
+ "type": "object",
+ "description": "Declared packages per manager, as spec strings; omitted on update means unchanged.",
+ "properties": {
+ "pip": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "npm": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "apt": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "runtime": {
+ "type": "object",
+ "properties": {
+ "python": {
+ "type": "string"
+ }
+ }
}
},
"additionalProperties": true
diff --git a/protocol/versions/2026-09-28/environments.md b/protocol/versions/2026-09-28/environments.md
index eda9b10e..cdcb66ed 100644
--- a/protocol/versions/2026-09-28/environments.md
+++ b/protocol/versions/2026-09-28/environments.md
@@ -85,6 +85,8 @@ Three rules make it one thing rather than a shared folder:
| `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` |
+| `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 |
@@ -146,6 +148,7 @@ build; the build installs from the manifests ([§4](#4-builds-and-versions)).
## 4. Builds and versions
```http
+GET /v1/environments/runtimes what a build can be made with here: Python minors, Node major, the OS
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
@@ -156,6 +159,9 @@ A build snapshots the source into a new version and installs what the project de
| Manifest at the root | What the build runs |
|---|---|
+| declared `pip` | the same virtual environment (made with `runtime.python` when the server has it), then `pip install` of each spec |
+| declared `npm` | `npm install` of each spec into `node_modules` |
+| declared `apt` | the named packages and the dependencies the image lacks, downloaded by apt and unpacked with dpkg under `apt/` in the version, which a session gets on `PATH` and `LD_LIBRARY_PATH`; nothing is installed into the server |
| `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` |
diff --git a/protocol/versions/2026-09-28/index.md b/protocol/versions/2026-09-28/index.md
index 80014748..89a86ef2 100644
--- a/protocol/versions/2026-09-28/index.md
+++ b/protocol/versions/2026-09-28/index.md
@@ -62,6 +62,7 @@ the [protocol README](../../README.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) |
+| `GET` | `/v1/environments/runtimes` | 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) |
diff --git a/runner/environments.py b/runner/environments.py
index cb8f16f5..ea586b45 100644
--- a/runner/environments.py
+++ b/runner/environments.py
@@ -31,6 +31,8 @@ from __future__ import annotations
import json
import mimetypes
+import platform
+import re
import os
import pathlib
import shutil
@@ -56,6 +58,8 @@ TREE_MAX = 20_000 # entri
# thing SPI-001 says not to trust).
NOT_COPIED = {".venv", "venv", "node_modules", "__pycache__", ".pnpm-store", ".cache", ".hr-build.json"}
_ID_SAFE = set("abcdefghijklmnopqrstuvwxyz0123456789_-")
+_SPEC_RE = re.compile(r"^@?[A-Za-z0-9][A-Za-z0-9._/+-]{0,99}(?:(?:==|>=|<=|~=|!=|@|=)[A-Za-z0-9._*+^~<>-]{0,60})?$") # one declared package
+_ARCH_DIRS = {"amd64": "x86_64-linux-gnu", "arm64": "aarch64-linux-gnu"}
router = APIRouter()
_builds_lock = threading.Lock()
@@ -303,6 +307,44 @@ def import_git(env_id: str, url: str, ref: str = "", *, replace: bool = False) -
return {"imported": "git", "url": url, "ref": ref, **source_stat(env_id)}
+# ── runtimes ────────────────────────────────────────────────────────────────────────────────────
+def runtimes() -> dict:
+ """What a build can be made with, on this box: the Python minors present as python3.N binaries,
+ the Node major, the OS release for apt. Only what is here; nothing offered that is not."""
+ env = _tool_env()
+ pythons = []
+ for minor in range(8, 20):
+ if shutil.which(f"python3.{minor}", path=env.get("PATH")):
+ pythons.append(f"3.{minor}")
+ node = ""
+ try:
+ node = subprocess.run(["node", "--version"], capture_output=True, text=True, timeout=10, env=env).stdout.strip().lstrip("v").split(".")[0]
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ os_name = os_ver = ""
+ try:
+ for line in open("/etc/os-release"):
+ k, _, v = line.strip().partition("=")
+ if k == "ID":
+ os_name = v.strip('"')
+ elif k == "VERSION_ID":
+ os_ver = v.strip('"')
+ except OSError:
+ pass
+ return {"python": pythons, "node": [node] if node else [], "os": {"name": os_name, "version": os_ver},
+ "apt": bool(shutil.which("apt-get") and shutil.which("dpkg"))}
+
+
+def clean_specs(specs) -> list[str]:
+ """Declared packages as short spec strings, each checked against one shape."""
+ out: list[str] = []
+ for x in (specs or []):
+ t = str(x or "").strip()
+ if t and _SPEC_RE.match(t) and t not in out and len(out) < 200:
+ out.append(t)
+ return out
+
+
# ── builds ──────────────────────────────────────────────────────────────────────────────────────
def build_record(env_id: str, n: int) -> dict | None:
p = version_dir(env_id, n) / ".hr-build.json"
@@ -383,6 +425,41 @@ def _packages(dst: pathlib.Path, env: dict) -> list[dict]:
return out
+def _apt_into_layer(log: list[str], dst: pathlib.Path, names: list[str], env: dict, scratch: str, deadline: float) -> 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", "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)
+ 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)
+ (out / ".packages").write_text("\n".join(d.name for d in debs) + "\n")
+ log.append(f"apt: unpacked {len(debs)} archive(s) into apt/")
+
+
+def _apt_packages(dst: pathlib.Path) -> list[dict]:
+ """The archives a build unpacked, as manager/name/version, from their file names."""
+ out = []
+ try:
+ for name in (dst / "apt" / ".packages").read_text().split():
+ parts = name[:-4].split("_") if name.endswith(".deb") else []
+ if len(parts) >= 2:
+ out.append({"manager": "apt", "name": parts[0], "version": parts[1].replace("%3a", ":")})
+ except OSError:
+ 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."""
@@ -427,12 +504,16 @@ def _write_record(dst: pathlib.Path, rec: dict) -> None:
os.replace(tmp, dst / ".hr-build.json")
-def _build(env_id: str, n: int, slug: str, activate: bool) -> None:
+def _build(env_id: str, n: int, slug: str, activate: bool, spec: dict | None = None) -> None:
+ spec = spec or {}
+ pip_specs, npm_specs, apt_specs = clean_specs(spec.get("pip")), clean_specs(spec.get("npm")), clean_specs(spec.get("apt"))
+ want_py = str(spec.get("python") or "") # the node major is the box's one; recorded, not chosen
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}
+ "packages": [], "files": 0, "bytes": 0, "log": log, "runtime": {},
+ "declared": {"pip": pip_specs, "npm": npm_specs, "apt": apt_specs}}
try:
if dst.exists():
shutil.rmtree(dst)
@@ -445,21 +526,43 @@ def _build(env_id: str, n: int, slug: str, activate: bool) -> None:
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"
+ if pip_specs or (dst / "requirements.txt").is_file() or (dst / "pyproject.toml").is_file():
+ # 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)
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():
+ if pip_specs:
+ _run(log, [pip, "install", *pip_specs], str(dst), env, deadline)
+ 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).stdout.strip()
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ if npm_specs or (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 / "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)
+ 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")
+ _run(log, [npm, "install", "--no-audit", "--no-fund", "--save", *npm_specs], str(dst), env, deadline)
+ 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_into_layer(log, dst, apt_specs, env, scratch, 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)
+ if (dst / "apt").is_dir():
+ rec["packages"] += _apt_packages(dst)
_read_only(dst)
rec["files"], rec["bytes"] = _size(dst)
rec["status"], rec["finished_at"] = "ready", int(time.time())
@@ -479,7 +582,7 @@ def _build(env_id: str, n: int, slug: str, activate: bool) -> None:
_builds.pop(f"{env_id}:{n}", None)
-def start_build(env_id: str, n: int, slug: str, activate: bool = True) -> dict:
+def start_build(env_id: str, n: int, slug: str, activate: bool = True, spec: dict | None = None) -> dict:
if not source_dir(env_id).is_dir():
raise HTTPException(409, "the environment has no files yet")
key = f"{env_id}:{n}"
@@ -489,7 +592,7 @@ def start_build(env_id: str, n: int, slug: str, activate: bool = True) -> dict:
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}")
+ t = threading.Thread(target=_build, args=(env_id, n, slug, activate, spec), daemon=True, name=f"env-build-{key}")
_builds[key] = t
t.start()
return {"version": n, "status": "building"}
@@ -586,6 +689,12 @@ def apply_env(env: dict, applied: dict | None) -> None:
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 (real / "apt").is_dir():
+ apt = os.path.join(link, "apt")
+ path_add += [os.path.join(apt, "usr", "bin"), os.path.join(apt, "usr", "local", "bin"), os.path.join(apt, "bin")]
+ arch = _ARCH_DIRS.get({"x86_64": "amd64", "aarch64": "arm64"}.get(platform.machine(), ""), "")
+ libs = [os.path.join(apt, "usr", "lib"), os.path.join(apt, "lib")] + ([os.path.join(apt, "usr", "lib", arch), os.path.join(apt, "lib", arch)] if arch else [])
+ env["LD_LIBRARY_PATH"] = ":".join(libs + ([env["LD_LIBRARY_PATH"]] if env.get("LD_LIBRARY_PATH") else []))
if path_add:
env["PATH"] = ":".join(path_add + [env.get("PATH", "")])
@@ -663,11 +772,21 @@ async def r_import(env_id: str, request: Request, replace: int = 0, git_url: str
pass
[email protected]("/environments/runtimes")
+def r_runtimes() -> dict:
+ return runtimes()
+
+
@router.post("/environments/{env_id}/build")
-def r_build(env_id: str, version: int, slug: str, activate: int = 1) -> dict:
+async def r_build(env_id: str, version: int, slug: str, request: Request, 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))
+ raw = await request.body()
+ try:
+ spec = json.loads(raw) if raw else {}
+ except ValueError:
+ raise HTTPException(400, "the build body is not JSON")
+ return start_build(env_id, int(version), slug, bool(activate), spec if isinstance(spec, dict) else {})
@router.get("/environments/{env_id}/build")
diff --git a/runner/tests/test_environments.py b/runner/tests/test_environments.py
index 9c6434c8..bb19f1b5 100644
--- a/runner/tests/test_environments.py
+++ b/runner/tests/test_environments.py
@@ -162,3 +162,15 @@ def test_the_turn_gets_the_path_the_variables_and_the_instructions(store):
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("")
+
+
+def test_declared_specs_are_checked_and_the_runtimes_are_what_the_box_has(store):
+ assert E.clean_specs(["pyyaml==6.0.2", "[email protected]", "@scope/[email protected]", "ffmpeg", "bad spec!", "", "pyyaml==6.0.2", "../x"]) == \
+ ["pyyaml==6.0.2", "[email protected]", "@scope/[email protected]", "ffmpeg"]
+ rt = E.runtimes()
+ assert isinstance(rt["python"], list) and all(v.startswith("3.") for v in rt["python"]) and isinstance(rt["apt"], bool)
+ # a declared pip package with no network still records what was asked; the manifests path is unchanged
+ E.write_file("henv_d", "run.py", b"print(1)\n")
+ 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": []}
diff --git a/ui/src/app/(app)/environments/[id]/page.tsx b/ui/src/app/(app)/environments/[id]/page.tsx
index b5fff44d..f1019020 100644
--- a/ui/src/app/(app)/environments/[id]/page.tsx
+++ b/ui/src/app/(app)/environments/[id]/page.tsx
@@ -11,13 +11,20 @@ import { SkelPage } from '@/components/Skel';
import { PrismAsync as SyntaxHL } from 'react-syntax-highlighter';
import oneLightTheme from 'react-syntax-highlighter/dist/esm/styles/prism/one-light';
import {
- activateEnvironmentVersion, buildEnvironment, deleteEnvironmentPath, environmentHarnesses,
- fmtBytes, getEnvironment, getEnvironmentBuild, importEnvironmentArchive, importEnvironmentGit, listEnvironmentFiles,
- makeEnvironmentDir, readEnvironmentFile, writeEnvironmentFile,
- type Environment, type EnvironmentBuildRecord, type EnvironmentFileEntry,
+ buildEnvironment, deleteEnvironmentPath, environmentHarnesses,
+ fmtBytes, getEnvironment, getEnvironmentBuild, importEnvironmentArchive, importEnvironmentGit, listEnvironmentFiles, listRuntimes,
+ makeEnvironmentDir, readEnvironmentFile, updateEnvironment, writeEnvironmentFile,
+ type Environment, type EnvironmentBuildRecord, type EnvironmentFileEntry, type EnvironmentRuntimes, type Manager,
} from '@/lib/environments';
-const STATUS_LABEL: Record<Environment['status'], string> = { empty: 'Not built', building: 'Building', ready: 'Ready', failed: 'Build failed' };
+const MANAGERS: Manager[] = ['pip', 'npm', 'apt'];
+const SPEC_HINT: Record<Manager, string> = { pip: 'name==1.0', npm: '[email protected]', apt: 'name' };
+/** The parts of a spec as the row shows them: the name, and the version when one was given. */
+function specParts(spec: string, m: Manager): { name: string; version: string } {
+ if (m === 'npm') { const i = spec.lastIndexOf('@'); return i > 0 ? { name: spec.slice(0, i), version: spec.slice(i + 1) } : { name: spec, version: '' }; }
+ for (const sep of ['==', '>=', '<=', '~=', '!=', '=']) { const i = spec.indexOf(sep); if (i > 0) return { name: spec.slice(0, i), version: (sep === '==' || sep === '=' ? '' : sep) + spec.slice(i + sep.length) }; }
+ return { name: spec, version: '' };
+}
/** The highlighter's language for a file, by extension; plain text for anything else. */
const LANG: Record<string, string> = {
py: 'python', js: 'javascript', mjs: 'javascript', cjs: 'javascript', ts: 'typescript', tsx: 'tsx', jsx: 'jsx', json: 'json',
@@ -68,6 +75,12 @@ export default function EnvironmentPage() {
const [busy, setBusy] = useState('');
const [build, setBuild] = useState<EnvironmentBuildRecord | null>(null);
const [showLog, setShowLog] = useState(false);
+ const [segment, setSegment] = useState<Manager>('pip');
+ const [declared, setDeclared] = useState<Record<Manager, string[]> | null>(null); // what the page holds; saved from the head
+ const [python, setPython] = useState('');
+ const [runtimes, setRuntimes] = useState<EnvironmentRuntimes | null>(null);
+ const [spec, setSpec] = useState('');
+ const [pkgDirty, setPkgDirty] = useState(false);
const [gitOpen, setGitOpen] = useState(false);
const [menu, setMenu] = useState<'add' | null>(null);
const [git, setGit] = useState({ url: '', ref: '', replace: false });
@@ -79,10 +92,12 @@ export default function EnvironmentPage() {
try {
const [e, t, h] = await Promise.all([getEnvironment(id), listEnvironmentFiles(id), environmentHarnesses(id).catch(() => [])]);
setEnv(e); setEntries(t.entries); setHarnesses(h);
+ if (!pkgDirty) { setDeclared({ pip: (e.declared?.pip || []).map((x) => x.spec), npm: (e.declared?.npm || []).map((x) => x.spec), apt: (e.declared?.apt || []).map((x) => x.spec) }); setPython(e.runtime?.python || ''); }
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]);
+ }, [id, pkgDirty]);
useEffect(() => { void reload(); }, [reload]);
+ useEffect(() => { listRuntimes().then(setRuntimes).catch(() => setRuntimes(null)); }, []);
useEffect(() => {
if (!menu) return;
const off = (ev: MouseEvent) => { if (!(ev.target as HTMLElement).closest('.env-menu-wrap')) setMenu(null); };
@@ -111,7 +126,28 @@ export default function EnvironmentPage() {
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); });
+ /** Save changes, from the head: the open file's edit, the declared packages and the runtime, then a
+ * build, so what a session reads is what the page shows. */
+ const saveChanges = () => act('save', async () => {
+ if (editing !== null) {
+ await writeEnvironmentFile(id, openPath, editing);
+ setFile({ text: editing, bytes: new TextEncoder().encode(editing).length, type: file?.type || 'text/plain' }); setEditing(null);
+ }
+ if (pkgDirty && declared && env) {
+ await updateEnvironment(id, { name: env.name, description: env.description, entry: env.entry, packages: declared, runtime: { python } });
+ setPkgDirty(false);
+ }
+ await buildEnvironment(id);
+ });
+ const addSpec = () => {
+ 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);
+ };
+ 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 || '';
const createPath = () => act('create', async () => {
if (!newPath?.value.trim()) return;
const base = parentDir(); const p = (base ? base + '/' : '') + newPath.value.trim().replace(/^\/+/, '');
@@ -131,7 +167,6 @@ export default function EnvironmentPage() {
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));
if (!env && !err) return <SkelPage />;
@@ -160,19 +195,55 @@ export default function EnvironmentPage() {
{env && (
<div className="env-title-row">
<h1>{env.name}</h1>
- <button className="button primary" type="button" disabled={editing === null || busy === 'save'} onClick={() => void saveFile()}>
- {busy === 'save' ? 'Saving\u2026' : 'Save changes'}</button>
+ <button className="button primary" type="button" disabled={!dirty || busy === 'save' || env.status === 'building'} onClick={() => void saveChanges()}>
+ {busy === 'save' ? 'Saving\u2026' : env.status === 'building' ? 'Building\u2026' : 'Save changes'}</button>
</div>
)}
</div>
<div className="env-body">
{err && <div className="hr-error" role="alert">{err}</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>
+ <button className="button small" type="button" onClick={() => setShowLog((v) => !v)}>{showLog ? 'Hide the log' : 'Show the log'}</button>
+ {showLog && <pre className="env-log">{build.log || ''}</pre>}
+ </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 className="env-card-head">
+ <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>{declared ? MANAGERS.reduce((a, m) => a + declared[m].length, 0) : 0}</span></button>
+ </div>
+ {tab === 'packages' && declared && (
+ <>
+ <div className="env-segments" role="tablist" aria-label="Package manager">
+ {MANAGERS.map((m) => (
+ <button key={m} type="button" role="tab" aria-selected={segment === m} className={'env-segment' + (segment === m ? ' is-on' : '')} onClick={() => setSegment(m)}
+ disabled={m === 'apt' && runtimes !== null && !runtimes.apt} title={m === 'apt' && runtimes !== null && !runtimes.apt ? 'apt is not available on this instance' : undefined}>
+ {m} <span>{declared[m].length}</span></button>
+ ))}
+ </div>
+ <label className="env-runtime">
+ {segment === 'pip' ? 'Python' : segment === 'npm' ? 'Node' : (runtimes?.os.name ? runtimes.os.name[0].toUpperCase() + runtimes.os.name.slice(1) : 'OS')}
+ {segment === 'pip' ? (
+ <select value={python || (runtimes?.python[0] ?? '')} onChange={(ev) => { setPython(ev.target.value); setPkgDirty(true); }}>
+ {(runtimes?.python.length ? runtimes.python : [python || '']).map((v) => <option key={v} value={v}>{v || 'default'}</option>)}
+ </select>
+ ) : segment === 'npm' ? (
+ <select value={runtimes?.node[0] ?? ''} disabled><option value={runtimes?.node[0] ?? ''}>{runtimes?.node[0] ?? ''}</option></select>
+ ) : (
+ <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>
+ </>
+ )}
</div>
{tab === 'files' && (
@@ -260,59 +331,19 @@ export default function EnvironmentPage() {
</div>
)}
- {tab === 'packages' && (
+ {tab === 'packages' && declared && (
<div className="env-packages">
- {env.status === 'empty' && !build ? (
- <div className="env-onboard is-packages">
- <h2>Nothing built yet</h2>
- <p>A build copies the files into a version and installs what they declare. Every Task then finds the packages installed, and nothing is installed again.</p>
- <dl className="env-manifests">
- <div><dt><code>requirements.txt</code> or <code>pyproject.toml</code></dt><dd>a Python virtualenv, first on PATH</dd></div>
- <div><dt><code>package.json</code></dt><dd>npm into node_modules, on NODE_PATH</dd></div>
- <div><dt><code>setup.sh</code></dt><dd>runs last, for anything the manifests cannot say</dd></div>
- </dl>
- <button className="button primary" type="button" disabled={busy === 'build' || !env.files.count} onClick={() => void startBuild()}>
- {env.files.count ? 'Build now' : 'Add files first'}</button>
- </div>
- ) : (
- <div className="env-pk-head">
- <span className={'env-status is-' + env.status}><i />{env.status === 'ready' && env.version
- ? `Version ${env.version} is what every session reads`
- : env.status === 'building' ? `Building version ${env.latestVersion}\u2026`
- : env.status === 'failed' ? 'The last build failed; fix the manifests and build again'
- : 'Nothing built yet'}</span>
- <span className="env-pk-actions">
- {build && <button className="button small" type="button" onClick={() => setShowLog((v) => !v)}>{showLog ? 'Hide build log' : 'Build log'}</button>}
- <button className="button primary small" 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()}>
- {env.status === 'building' ? 'Building\u2026' : env.version ? 'Rebuild' : 'Build'}</button>
- </span>
- </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>
+ {declared[segment].length ? declared[segment].map((x) => {
+ const p = specParts(x, segment);
+ 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>
+ <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>
+ );
+ }) : (
+ <div className="env-pkg-empty">No {segment} packages yet. Add one above as <code>{SPEC_HINT[segment]}</code>{segment === 'pip' && ' (the project\u2019s requirements.txt is installed too)'}{segment === 'npm' && ' (the project\u2019s package.json is installed too)'}.</div>
)}
</div>
)}
diff --git a/ui/src/app/(app)/environments/page.tsx b/ui/src/app/(app)/environments/page.tsx
index 9c264c95..bc59f7b6 100644
--- a/ui/src/app/(app)/environments/page.tsx
+++ b/ui/src/app/(app)/environments/page.tsx
@@ -10,13 +10,8 @@ import { createEnvironment, deleteEnvironment, listEnvironments, updateEnvironme
/** The packages column: what the active build installed, counted per manager, or the state that explains why there is none. */
function packagesLine(e: Environment): string {
- if (e.status === 'ready') {
- const by: Record<string, number> = {};
- for (const p of e.packages) by[p.manager] = (by[p.manager] || 0) + 1;
- const parts = Object.entries(by).map(([m, n]) => `${n} ${m}`);
- return parts.length ? parts.join(' \u00b7 ') : 'no packages';
- }
- return e.status === 'building' ? 'building\u2026' : e.status === 'failed' ? 'build failed' : 'not built yet';
+ const parts = (['pip', 'npm', 'apt'] as const).map((m) => [e.declared?.[m]?.length || 0, m] as const).filter(([n]) => n > 0).map(([n, m]) => `${n} ${m}`);
+ return parts.length ? parts.join(' \u00b7 ') : 'no packages';
}
export default function EnvironmentsPage() {
diff --git a/ui/src/app/hr.css b/ui/src/app/hr.css
index 2d0434be..42e3215f 100644
--- a/ui/src/app/hr.css
+++ b/ui/src/app/hr.css
@@ -1130,8 +1130,20 @@ body.hr-resizing iframe { pointer-events: none; }
.env-body { padding: 24px 36px 34px; }
.env-card { display: flex; flex-direction: column; background: var(--surface); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
.env-card > .env-files, .env-card > .env-packages { border-top: 1px solid var(--line); }
-.env-tabs { display: inline-flex; gap: 2px; margin: 12px 16px; padding: 4px; border-radius: 10px; background: var(--surface-subtle); }
-.env-card > .env-tabs { align-self: flex-start; }
+.env-card-head { display: flex; align-items: center; gap: 14px; padding: 12px 16px; flex-wrap: wrap; }
+.env-tabs { display: inline-flex; gap: 2px; padding: 4px; border-radius: 10px; background: var(--surface-subtle); }
+/* the Packages toolbar, as the design draws it: manager segments, the runtime, and Add at the right */
+.env-segments { display: inline-flex; gap: 2px; padding: 3px; border-radius: 9px; background: var(--surface-subtle); }
+.env-segment { display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; border: 0; border-radius: 7px; background: transparent; cursor: pointer; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: var(--muted); }
+.env-segment span { font-size: 11px; color: var(--muted); }
+.env-segment.is-on { background: var(--surface); color: var(--accent); box-shadow: 0 1px 2px rgba(15, 23, 42, .08), 0 0 0 1px var(--line); }
+.env-segment.is-on span { color: var(--accent); }
+.env-segment:disabled { opacity: .5; cursor: default; }
+.env-runtime { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink); }
+.env-runtime select { font: inherit; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; padding: 6px 28px 6px 10px; border: 1px solid var(--line-strong); border-radius: 8px; background: var(--surface); color: var(--ink); }
+.env-add { display: inline-flex; align-items: center; gap: 8px; margin-left: auto; }
+.env-add input { width: 260px; max-width: 100%; font: inherit; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; padding: 8px 12px; border: 1px solid var(--line-strong); border-radius: 8px; color: var(--ink); }
+.env-add input::placeholder { color: var(--muted); }
.env-tab { display: inline-flex; align-items: center; gap: 8px; padding: 7px 14px; 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); color: var(--ink); box-shadow: 0 1px 2px rgba(15, 23, 42, .08), 0 0 0 1px var(--line); }
@@ -1165,21 +1177,21 @@ body.hr-resizing iframe { pointer-events: none; }
.env-code { flex: 1; min-width: 0; overflow: auto; cursor: text; }
.env-code pre { margin: 0 !important; }
.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-actions { display: inline-flex; align-items: center; gap: 8px; }
-.env-pk-head code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
+.env-packages { display: flex; flex-direction: column; min-height: 400px; }
+.env-pkg { display: grid; grid-template-columns: minmax(0, 1fr) auto 32px; align-items: center; gap: 16px; padding: 12px 20px; border-bottom: 1px solid var(--line); }
+.env-pkg-name { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; font-weight: 600; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.env-pkg-version { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; color: var(--muted); }
+.env-pkg-x { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border: 0; border-radius: 6px; background: transparent; color: var(--muted); cursor: pointer; font-size: 14px; }
+.env-pkg-x:hover { background: var(--surface-subtle); color: var(--ink); }
+.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-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-title-row h1 { font-size: 24px; }
+ .env-add { margin-left: 0; width: 100%; }
+ .env-add input { flex: 1; width: auto; }
.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; }
diff --git a/ui/src/lib/environments.ts b/ui/src/lib/environments.ts
index 06975cf1..dd838964 100644
--- a/ui/src/lib/environments.ts
+++ b/ui/src/lib/environments.ts
@@ -17,6 +17,8 @@ export interface Environment {
version: number | null; latestVersion: number | null;
files: { count: number; bytes: number };
packages: EnvironmentPackage[];
+ declared: Record<Manager, DeclaredPackage[]>;
+ runtime: { python: string };
versions: EnvironmentVersion[];
build: EnvironmentVersion | null;
member: string; workspace: string; createdAt: number; updatedAt: number;
@@ -26,13 +28,18 @@ export interface EnvironmentBuildRecord {
started_at?: number | null; finished_at?: number | null; error?: string; log?: string;
packages?: EnvironmentPackage[]; files?: number; bytes?: number;
}
+export type Manager = 'pip' | 'npm' | 'apt';
+export interface DeclaredPackage { name: string; version: string; spec: string }
+export interface EnvironmentRuntimes { python: string[]; node: string[]; os: { name: string; version: string }; apt: boolean }
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 }) =>
+export type EnvironmentInput = { name: string; description?: string; entry?: string; packages?: Record<Manager, string[]>; runtime?: { python: string } };
+export const listRuntimes = () => gw<EnvironmentRuntimes>('GET', '/v1/environments/runtimes');
+export const createEnvironment = (body: EnvironmentInput) =>
gw<Environment>('POST', '/v1/environments', body);
-export const updateEnvironment = (id: string, body: { name: string; description?: string; entry?: string }) =>
+export const updateEnvironment = (id: string, body: EnvironmentInput) =>
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) =>