Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/agent_env/env/envs/computer/utils/composed.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,9 @@ def now() -> str:

def stale(result: dict | None) -> bool:
"""Whether ``result`` was recorded by an agent-env whose composing code differs from this one's, or by one from
before results named it: what it holds may not be what this agent-env composes."""
return result is not None and result.get("composer") != composition()
before results named it: what it holds may not be what this agent-env composes. Never an image a release published
(``published``): its digest fixes it, and what it's made from pins that release, so no other composer makes it."""
return result is not None and not result.get("published") and result.get("composer") != composition()


@functools.cache
Expand Down
101 changes: 68 additions & 33 deletions src/agent_env/env/envs/computer/utils/composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
from agentenv_protocol.computer.apps import apps_folder
from agentenv_protocol.computer.app import BUILD_SETTINGS, SOCKET
from agentenv_protocol.computer.platform import PLATFORM_ENV, applies, entry_for
from packaging.requirements import InvalidRequirement, Requirement
from packaging.utils import canonicalize_name

from agent_env.artifact.artifacts.computer import LOCAL_IMAGE_PREFIX, ComputerArtifact
from agent_env.artifact.artifacts.docker_image import DockerImageArtifact
Expand Down Expand Up @@ -253,13 +255,20 @@ def _with_containers(env: ComputerEnv, pairs: list[tuple[str, str]]) -> list[tup

def _composed(env: ComputerEnv, base: ComputerArtifact, driver: ComputerDriverEnv, form: str, arch: str,
builds: builder.Builds, progress: _Progress) -> dict:
"""``form`` and ``arch`` built or reused, then probed when it built (gate 3)."""
result = _built(env, base, driver, form, arch, builds, progress)
"""``form`` and ``arch`` built or reused, then probed when it built (gate 3). An image a release published that the
record holds unprobed is probed as it is, never built again: no other release's composer makes it."""
result = _unprobed_published(env, form, arch) or _built(env, base, driver, form, arch, builds, progress)
if result["status"] != "unverified":
return result
return _probed(env, driver, form, arch, result, builds.provider, progress)


def _unprobed_published(env: ComputerEnv, form: str, arch: str) -> dict | None:
"""The pair's record, when it's an image a release published that's built but not probed yet."""
record = env.metadata.get("composed", {}).get(form, {}).get(arch) or {}
return dict(record) if record.get("published") and record.get("status") == "unverified" else None


def _composed_disk(env: ComputerEnv, base: ComputerArtifact, driver: ComputerDriverEnv, arch: str,
container: Future | None, builds: builder.Builds, progress: _Progress) -> dict:
"""The disk form of ``arch``, once its container, composed now or before, has built: built or reused, then probed
Expand Down Expand Up @@ -318,11 +327,11 @@ def _composed_vm_bundle(env: ComputerEnv, base: ComputerArtifact, driver: Comput
layer = _stage_driver(context, driver, base, {})
apps = [(app, _stage_app(context, app, base, {})) for app in env.composed_apps()]
parts = [_part(layer, _services(f"driver-{gate.driver_folder(driver)}", layer.install),
{"MCP_PORT": driver.port}, protocol, False)]
{"MCP_PORT": driver.port}, protocol, False, context)]
parts += [_part(staged, dict(zip(gate.programs(app, platform_of(base.os)), [
f"venv/bin/python -m agentenv_protocol.computer.serve_app {shlex.quote(staged.served)}",
*(service.command for service in staged.install.services)])), {"ENVIRONMENT_NAME": app.environment_name},
protocol, True) for app, staged in apps]
protocol, True, context) for app, staged in apps]
if (lock := _vm_bundle_lock(env, base, link, parts, context, arch, progress)) is not None:
packages.stage_wheels(lock, build, env.stored_id)
parts = [replace(part, wheels=tuple(wheel.file for wheel in lock.wheels.get(part.folder, [])))
Expand Down Expand Up @@ -383,15 +392,15 @@ def _composed_windows_disk(env: ComputerEnv, base: ComputerArtifact, driver: Com
parts = [_windows_part(layer, driver_prefix, {
program: windows_disk.argv(command, driver_prefix)
for program, command in _services(f"driver-{name}", layer.install).items()}, {"MCP_PORT": driver.port},
protocol)]
protocol, context)]
for app in env.composed_apps():
staged = _stage_app(context, app, base, {})
prefix = PureWindowsPath(staged.prefix)
server = [str(prefix / "venv" / "Scripts" / "python.exe"), "-m", "agentenv_protocol.computer.serve_app",
staged.served]
commands = [server, *(windows_disk.argv(service.command, prefix) for service in staged.install.services)]
parts.append(_windows_part(staged, prefix, dict(zip(gate.programs(app, platform_of(base.os)), commands)),
{"ENVIRONMENT_NAME": app.environment_name}, protocol))
{"ENVIRONMENT_NAME": app.environment_name}, protocol, context))
values = env.computer_values()
settings = {name: values.get(name, setting.default) for name, setting in base.config.items()
if setting.phase == "build"}
Expand Down Expand Up @@ -494,14 +503,11 @@ async def _provisioned(link: SandboxProvider, source: str, name: str, build: Pat


def _part(layer: _Layer, programs: dict[str, str], environment: dict[str, Any], protocol: bool,
app: bool) -> macos_vm_bundle.Part:
app: bool, context: Path) -> macos_vm_bundle.Part:
"""``layer`` as a VM bundle installs it: its programs, each run directly with its own variables when its service
says so, and a venv's protocol as on Linux: this checkout's source, else an app's pinned to this release, which a
driver's requirements name themselves."""
says so, and a venv's protocol as on Linux (``_protocol_spec``)."""
direct = {service.command: service.environment or {} for service in layer.install.services if service.direct}
extra = "[app]" if app else ""
spec = (f'"$build/context/protocol{extra}"' if protocol else
f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}" if app else None)
spec = _protocol_spec(layer, context, '"$build/context/protocol{extra}"' if protocol else None, app)
return macos_vm_bundle.Part(layer.folder, layer.prefix, layer.install,
{name: (command, direct.get(command)) for name, command in programs.items()},
environment, _venv(layer), spec if _venv(layer) else None, layer.served, layer.steps)
Expand Down Expand Up @@ -530,7 +536,7 @@ def _composed_omarchy_disk(env: ComputerEnv, base: ComputerArtifact, driver: Com
parts = [_omarchy_part(layer, prefix, {
program: omarchy_disk.argv(command, prefix)
for program, command in _services(f"driver-{name}", layer.install).items()}, {"MCP_PORT": driver.port},
protocol)]
protocol, context)]
for app in env.composed_apps():
staged = _stage_app(context, app, base, {})
prefix = PurePosixPath(staged.prefix)
Expand All @@ -540,7 +546,7 @@ def _composed_omarchy_disk(env: ComputerEnv, base: ComputerArtifact, driver: Com
environment = {"ENVIRONMENT_NAME": app.environment_name,
**({PLATFORM_ENV: staged.platform} if staged.platform else {})}
parts.append(_omarchy_part(staged, prefix, dict(zip(gate.programs(app, platform_of(base.os)), commands)),
environment, protocol))
environment, protocol, context))
values = env.computer_values()
settings = {name: values.get(name, setting.default) for name, setting in base.config.items()
if setting.phase == "build"}
Expand Down Expand Up @@ -575,24 +581,21 @@ def say(line: str) -> None:


def _windows_part(layer: _Layer, prefix: PureWindowsPath, services: dict[str, list[str]],
environment: dict[str, Any], protocol: bool) -> windows_disk.Part:
environment: dict[str, Any], protocol: bool, context: Path) -> windows_disk.Part:
"""``layer`` as a Windows disk installs it under ``prefix``: its ``services``' argv by name, with ``environment``,
and a venv's protocol as on Linux: this checkout's source, else an app's pinned to this release, which a driver's
requirements name themselves."""
extra = "[app]" if layer.app else ""
spec = (f"{windows_disk.BUILD}\\context\\protocol{extra}" if protocol else
f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}" if layer.app else None)
and a venv's protocol as on Linux (``_protocol_spec``)."""
spec = _protocol_spec(layer, context, f"{windows_disk.BUILD}\\context\\protocol{{extra}}" if protocol else None,
layer.app)
return windows_disk.Part(layer.folder, prefix, layer.install, services, environment, (spec,) if spec else (),
layer.served, tuple(step for step, _ in layer.steps))


def _omarchy_part(layer: _Layer, prefix: PurePosixPath, services: dict[str, list[str]], environment: dict[str, Any],
protocol: bool) -> omarchy_disk.Part:
protocol: bool, context: Path) -> omarchy_disk.Part:
"""``layer`` as an Omarchy disk installs it under ``prefix``: its ``services``' argv by name, with ``environment``,
an app's own server, install steps and platform, and a venv's protocol as on Windows (``_windows_part``)."""
extra = "[app]" if layer.app else ""
spec = (f"{omarchy_disk.BUILD}/context/protocol{extra}" if protocol else
f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}" if layer.app else None)
an app's own server, install steps and platform, and a venv's protocol as on Linux (``_protocol_spec``)."""
spec = _protocol_spec(layer, context, f"{omarchy_disk.BUILD}/context/protocol{{extra}}" if protocol else None,
layer.app)
return omarchy_disk.Part(layer.folder, prefix, layer.install, services, environment, (spec,) if spec else (),
layer.served, layer.steps, layer.platform)

Expand Down Expand Up @@ -622,7 +625,7 @@ def _built(env: ComputerEnv, base: ComputerArtifact, driver: ComputerDriverEnv,
layer = _stage_driver(context, driver, base, from_store)
apps = [_stage_app(context, app, base, from_store) for app in env.composed_apps()]
layers = [layer, *apps]
wants = _wants(layers, _stage_protocol(context))
wants = _wants(layers, _stage_protocol(context), context)
platform, held = f"linux/{arch}", []

def on() -> builder.Builder:
Expand Down Expand Up @@ -1095,18 +1098,50 @@ def _venv(layer: _Layer) -> bool:
return layer.install.python is not None or layer.app


def _wants(layers: list[_Layer], protocol: bool) -> list[packages.Want]:
"""What each layer asks a lock for; a venv adds the protocol, for an app with its ``app`` extra: from this checkout's
source when ``protocol``, else an app's pinned to this release, which a driver's requirements name themselves."""
def _wants(layers: list[_Layer], protocol: bool, context: Path) -> list[packages.Want]:
"""What each layer asks a lock for; a venv adds the protocol as ``_protocol_spec`` says, from this checkout's
source when ``protocol``."""
wants = []
for layer in layers:
extra = "[app]" if layer.app else ""
adds = ((f"/ctx/protocol{extra}",) if protocol else
(f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}",) if layer.app else ())
wants.append(packages.Want(layer.folder, layer.install, _venv(layer), adds if _venv(layer) else ()))
spec = _protocol_spec(layer, context, "/ctx/protocol{extra}" if protocol else None, layer.app)
wants.append(packages.Want(layer.folder, layer.install, _venv(layer), (spec,) if spec and _venv(layer) else ()))
return wants


def _protocol_spec(layer: _Layer, context: Path, source: str | None, app: bool) -> str | None:
"""What ``layer``'s venv, staged in ``context``, adds for the protocol, an app's with its ``app`` extra: the version
its requirements pin exactly, as each env a release ships pins its release's, so an env one release shipped
composes under another; else this checkout's ``source`` (``{extra}`` where the extra goes), when it runs from one;
else, for an app, this release's. A driver's requirements name the protocol themselves."""
extra = "[app]" if app else ""
if (pinned := _pinned_protocol(context / layer.folder, layer.install)) is not None:
return f"{_PROTOCOL}{extra}=={pinned}" if app else None
if source is not None:
return source.format(extra=extra)
return f"{_PROTOCOL}{extra}=={importlib.metadata.version(_PROTOCOL)}" if app else None


def _pinned_protocol(folder: Path, install: Install) -> str | None:
"""The one version the requirements ``install`` names in ``folder`` pin the protocol to (``==`` or ``===``, no
wildcard), on no condition: a requirement with a marker may not apply where the venv is built, so it pins nothing."""
if install.python is None or not (requirements := folder / install.python).is_file():
return None
for line in requirements.read_text().splitlines():
line = line.split("#", 1)[0].strip()
if not line or line.startswith("-"):
continue
try:
requirement = Requirement(line)
except InvalidRequirement:
continue
if canonicalize_name(requirement.name) != _PROTOCOL or requirement.marker is not None:
continue
for spec in requirement.specifier:
if spec.operator in ("==", "===") and "*" not in spec.version:
return spec.version
return None


def _computer(env: ComputerEnv, base: ComputerArtifact, built: dict[str, str], disks: dict[str, str],
bundles: dict[str, str]) -> dict | None:
"""Write the env's computer over the images ``built``, by arch, joined into one index in the env's image store, signed
Expand Down
Loading
Loading