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
2 changes: 1 addition & 1 deletion AGENTS.md

Large diffs are not rendered by default.

9 changes: 7 additions & 2 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -789,8 +789,13 @@ class MailApp(ComputerAppEnvironment):
models whose fields add to the class's `Settings` and `BuildSettings` on that OS. What's on the
class applies to every OS. `@install(os_type, spec, launch=..., ...)` is the generic form, for an
OS type a plugin adds, with that OS type's own install model as `spec`; `@linux(...)` is
`@install("linux", Linux(...), ...)`. On the computer the class reads what's declared for the OS
it runs on (`platform.detect()`).
`@install("linux", Linux(...), ...)`. `@linux(distribution="omarchy", ...)`, or
`@install("linux/omarchy", ...)`, declares for one distribution, by its /etc/os-release ID, what
replaces the OS type's declaration there. On the computer the class reads what's declared for the
platform its computer was composed for, which the composer sets as `AGENTENV_PLATFORM` for an app
that declares anything for a distribution, else the one it runs on (`platform.detect()`): its
distribution's, else its OS type's. An install step or ready check's `os=` names OS types or
distributions, and one for an OS type runs on all of it.
- **`launch=Launch(...)`** says how it starts in the desktop session: with it (`at="boot"`) or when
the agent opens it (`"demand"`). `ready=Ready(...)` says when it's ready, within `timeout_s` of its
launch: a window matching `launch.window` by its class, instance or title (on Hyprland, a Wayland
Expand Down
56 changes: 34 additions & 22 deletions packages/agentenv-protocol/src/agentenv_protocol/computer/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from .app_data import AppDataPlane
from .app_runtime import AppRuntime
from .errors import InvalidArgument
from .platform import detect
from .platform import PLATFORM_ENV, applies, detect, entry_for, platform_key

#: The environment variable a computer delivers its apps' settings in: JSON of each app's values by its name.
APP_SETTINGS_ENV = "AGENTENV_APP_SETTINGS"
Expand Down Expand Up @@ -327,7 +327,9 @@ def install(os_type: str, spec: BaseModel, *, launch: Optional[Launch] = None, p
the app's own there: its ``launch``; the ``paths`` it keeps its data in, relative to the session user's home, which
serve its data plane when it has no data hooks; its ``skill``, a file of its folder, instead of the class's; and
``settings`` and ``build_settings``, models whose fields add to the class's ``Settings`` and ``BuildSettings`` there.
``@linux`` is this for Linux; an OS type a plugin adds is declared with it."""
``os_type`` may name one of its distributions as ``<os>/<distribution>``, /etc/os-release's ID (``linux/omarchy``),
whose declaration replaces the OS type's there. ``@linux`` is this for Linux; an OS type a plugin adds is declared
with it."""
try:
owned = tuple(_PATHS.validate_python(list(paths or [])))
except ValidationError:
Expand All @@ -344,16 +346,18 @@ def deco(cls: type) -> type:
return deco


def linux(*, files: str = ".", packages: Optional[Packages] = None, python: Optional[str] = None,
sources: Optional[list[AptSource]] = None, downloads: Optional[list[Download]] = None,
run: Optional[list[RunScript]] = None, services: Optional[list[Service]] = None,
ports: Optional[list[int]] = None, launch: Optional[Launch] = None, paths: Optional[list[str]] = None,
skill: Optional[str] = None, settings: Optional[type[BaseModel]] = None,
def linux(*, distribution: Optional[str] = None, files: str = ".", packages: Optional[Packages] = None,
python: Optional[str] = None, sources: Optional[list[AptSource]] = None,
downloads: Optional[list[Download]] = None, run: Optional[list[RunScript]] = None,
services: Optional[list[Service]] = None, ports: Optional[list[int]] = None, launch: Optional[Launch] = None,
paths: Optional[list[str]] = None, skill: Optional[str] = None, settings: Optional[type[BaseModel]] = None,
build_settings: Optional[type[BaseModel]] = None) -> Callable:
"""``@install`` for Linux: how a Linux computer installs the app, ``Linux``'s fields, and what is its own there."""
return install("linux", Linux(files=files, packages=packages, python=python, sources=sources, downloads=downloads,
run=run, services=services or [], ports=ports),
launch=launch, paths=paths, skill=skill, settings=settings, build_settings=build_settings)
"""``@install`` for Linux, or with ``distribution`` for that distribution alone: how such a computer installs the
app, ``Linux``'s fields, and what is its own there."""
spec = Linux(files=files, packages=packages, python=python, sources=sources, downloads=downloads, run=run,
services=services or [], ports=ports)
return install(platform_key("linux", distribution), spec, launch=launch, paths=paths, skill=skill,
settings=settings, build_settings=build_settings)


def windows(*, files: str = ".", python: Optional[str] = None, downloads: Optional[list[Download]] = None,
Expand Down Expand Up @@ -459,18 +463,18 @@ class BuildSettings(BaseModel):
app declares its own, which its install steps read too. None is a secret, since the image keeps them."""

def __init__(self) -> None:
cls, on = type(self), detect().os
cls, on = type(self), _here()
values = json.loads(os.environ.get(APP_SETTINGS_ENV) or "{}").get(os.environ.get("ENVIRONMENT_NAME"), {})
self.settings = cls.settings_on(on).model_validate(values)
self.build_settings = _built_settings(cls, on)
declared = cls._installs.get(on)
declared = entry_for(cls._installs, on)
launch = declared.launch if declared is not None else None
self.launch = self._launch_for(launch) if launch is not None else None
self.paths = list(declared.paths) if declared is not None else []
ready = launch.ready if launch is not None else None
self._computer_app = AppRuntime(
self.launch, {fn.__name__: getattr(self, fn.__name__) for fn in _methods(cls)
if hasattr(fn, _READY_CHECK_ATTR) and _runs_on(getattr(fn, _READY_CHECK_ATTR), on)},
if hasattr(fn, _READY_CHECK_ATTR) and applies(getattr(fn, _READY_CHECK_ATTR), on)},
ready.timeout_s if ready is not None else DEFAULT_TIMEOUT_S, desktop=self._on_desktop(),
launch_fds=self._launch_fds, relaunch_on_start=self._relaunch_on_start(),
launch_running=self._launch_running())
Expand Down Expand Up @@ -509,14 +513,15 @@ async def _relaunched(self, op: str) -> None:

@classmethod
def settings_on(cls, os_type: Optional[str]) -> type[BaseModel]:
"""Its ``Settings`` on ``os_type``, with the fields its OS adds."""
added = declared.settings if (declared := cls._installs.get(os_type)) is not None else None
"""Its ``Settings`` on ``os_type``, an OS type or ``<os>/<distribution>``, with the fields it adds there."""
added = declared.settings if (declared := entry_for(cls._installs, os_type)) is not None else None
return _added(added, cls.Settings) if added is not None else cls.Settings

@classmethod
def build_settings_on(cls, os_type: Optional[str]) -> type[BaseModel]:
"""Its ``BuildSettings`` on ``os_type``, with the fields its OS adds."""
added = declared.build_settings if (declared := cls._installs.get(os_type)) is not None else None
"""Its ``BuildSettings`` on ``os_type``, an OS type or ``<os>/<distribution>``, with the fields it adds
there."""
added = declared.build_settings if (declared := entry_for(cls._installs, os_type)) is not None else None
return _added(added, cls.BuildSettings) if added is not None else cls.BuildSettings

@extension(COMPUTER_APP, op="launch", description=(
Expand Down Expand Up @@ -588,7 +593,7 @@ def _computer_app_skill(self) -> tuple[str, str]:

def _computer_app_skill_file(self) -> Optional[str]:
"""The file of the app's folder holding its skill on this OS, or the class's."""
declared = type(self)._installs.get(detect().os)
declared = entry_for(type(self)._installs, _here())
return declared.skill if declared is not None and declared.skill is not None else type(self).skill

@classmethod
Expand Down Expand Up @@ -618,8 +623,10 @@ def declaration(cls) -> AppDeclaration:
if hasattr(fn, _INSTALL_STEP_ATTR) for scope, os_types in [getattr(fn, _INSTALL_STEP_ATTR)]]
checks = [AppReadyCheck(name=fn.__name__, os=getattr(fn, _READY_CHECK_ATTR)) for fn in methods
if hasattr(fn, _READY_CHECK_ATTR)]
installed_os = {key.partition("/")[0] for key in cls._installs}
for method in [*steps, *checks]:
if unknown := [os_type for os_type in method.os or [] if os_type not in cls._installs]:
if unknown := [os_type for os_type in method.os or []
if entry_for(cls._installs, os_type) is None and os_type not in installed_os]:
Comment on lines +628 to +629

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Malformed scopes silently skip work

declaration() now accepts malformed scopes such as @install_step(os="linux/") or @ready_check(os="linux/ubuntu/extra") when the app declares @linux. entry_for finds the Linux fallback, so these values pass the check. Neither value matches a valid computer platform, so the step or check is silently skipped everywhere.

Validate the scope’s format before checking for a matching install, and add tests for both decorators.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/agentenv-protocol/src/agentenv_protocol/computer/app.py
Line: 628-629

Comment:
**Malformed scopes silently skip work**

`declaration()` now accepts malformed scopes such as `@install_step(os="linux/")` or `@ready_check(os="linux/ubuntu/extra")` when the app declares `@linux`. `entry_for` finds the Linux fallback, so these values pass the check. Neither value matches a valid computer platform, so the step or check is silently skipped everywhere.

Validate the scope’s format before checking for a matching install, and add tests for both decorators.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

raise ValueError(f"{cls.__name__}.{method.name} runs on {unknown[0]!r}, which {cls.__name__} declares "
f"no install for; it declares {', '.join(cls._installs) or 'none'}")
return AppDeclaration(
Expand Down Expand Up @@ -678,8 +685,13 @@ def _built_settings(cls: type[ComputerAppEnvironment], os_type: Optional[str]) -
return cls.build_settings_on(os_type).model_validate(values)


def _runs_on(os_types: Optional[list[str]], os_type: Optional[str]) -> bool:
return os_types is None or os_type in os_types
def _here() -> Optional[str]:
"""The platform this runs on, by the key an app's parts for it are under (``platform_key``): the one its computer
was composed for (``PLATFORM_ENV``), else what it detects."""
if composed := os.environ.get(PLATFORM_ENV):
return composed
running = detect()
return platform_key(running.os, running.distribution)


@functools.cache
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,15 @@
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, Mapping, Optional, TypeVar

PREDICATE_KEYS = ("os", "distribution", "version", "arch", "display")

_ARCH = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}
_Entry = TypeVar("_Entry")
#: The platform (``platform_key``) the computer's composer built an app for, which its server and install steps read in
#: place of what /etc/os-release says, so they act on the install the image holds; unset outside a composed computer.
PLATFORM_ENV = "AGENTENV_PLATFORM"
_OS = {"linux": "linux", "darwin": "macos", "win32": "windows"}


Expand Down Expand Up @@ -52,6 +57,30 @@ def detect(environ: dict | None = None, os_release: Path = Path("/etc/os-release
arch=_ARCH.get(machine, machine or None), display=display)


def platform_key(os_type: Optional[str], distribution: Optional[str] = None) -> Optional[str]:
"""What a platform's own install, launch or known failures are keyed by: ``<os>/<distribution>``, its distribution
being /etc/os-release's ID, or its OS type when it has none."""
if os_type is None:
return None
return f"{os_type}/{distribution}" if distribution else os_type


def entry_for(by_platform: Mapping[str, _Entry], key: Optional[str]) -> Optional[_Entry]:
"""``by_platform``'s entry for the platform ``key`` names: its distribution's, which replaces its OS type's there,
else its OS type's."""
if key is None:
return None
return by_platform[key] if key in by_platform else by_platform.get(key.partition("/")[0])


def applies(keys: Optional[Iterable[str]], key: Optional[str]) -> bool:
"""Whether what's declared for ``keys``, OS types or distributions, or for every OS when None, applies on the
platform ``key`` names: one names its OS type or its distribution."""
if keys is None:
return True
return key is not None and (key in keys or key.partition("/")[0] in keys)


def supported(entry: dict) -> list[Platform]:
"""The platforms a ``supports`` entry names: its ``os`` type, with each of its displays and arches, and its
distribution and version when it names one. ``{"os": {"type": "linux", "display": ["x11"]}, "arch": ["amd64"]}``
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
from typing import NoReturn

from ._load import load_class
from .app import ComputerAppEnvironment, _built_settings
from .platform import detect
from .app import ComputerAppEnvironment, _built_settings, _here

USAGE = "usage: python -m agentenv_protocol.computer.run_install_step <file>:<Class> <method>"

Expand All @@ -33,7 +32,7 @@ def main(argv: list[str]) -> None:
if argv[1] not in {step.name for step in cls.declaration().install_steps}:
raise SystemExit(f"{cls.__name__} has no @install_step method {argv[1]!r}")
app = cls.__new__(cls)
app.settings, app.build_settings = _NoDeploy(), _built_settings(cls, detect().os)
app.settings, app.build_settings = _NoDeploy(), _built_settings(cls, _here())
done = getattr(app, argv[1])()
if inspect.isawaitable(done):
asyncio.run(done)
Expand Down
106 changes: 103 additions & 3 deletions packages/agentenv-protocol/tests/test_computer_declare.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
from agentenv_protocol.computer import AppDeclaration # noqa: E402
from agentenv_protocol.computer._declare import _Stub, _StubModule, declare, main # noqa: E402
from agentenv_protocol.computer import (APP_SETTINGS_ENV, ComputerAppEnvironment, Launch, Linux, # noqa: E402
Windows, install, linux, windows)
Windows, install, install_step, linux, ready_check, windows)
from agentenv_protocol.computer import app as app_module # noqa: E402
from agentenv_protocol.computer.app import BUILD_SETTINGS # noqa: E402
from pydantic import BaseModel # noqa: E402
from agentenv_protocol.computer.platform import Platform # noqa: E402
from agentenv_protocol.computer.platform import PLATFORM_ENV, Platform # noqa: E402

DRIVER = '''import not_installed_here
from not_installed_here.input import Base, Keyboard
Expand Down Expand Up @@ -337,6 +337,106 @@ class BuildSettings(BaseModel):
assert (type(notes.settings), notes.build_settings.edition, notes.launch) == (Notes.Settings, "home", None)


@pytest.mark.parametrize(("distribution", "launched", "checked"), [
("omarchy", ["notes", "--wayland"], ["anywhere", "here"]), ("ubuntu", ["notes"], ["anywhere"]),
(None, ["notes"], ["anywhere"])])
def test_an_app_on_a_distribution_it_declares_for_takes_that_part_and_elsewhere_its_os_types(
monkeypatch, tmp_path, distribution, launched, checked):
class WaylandSettings(BaseModel):
portal: bool = True

@linux(distribution="omarchy", launch=Launch(command=["notes", "--wayland"]), settings=WaylandSettings)
@linux(launch=Launch(command=["notes"]))
class Notes(ComputerAppEnvironment):
@ready_check(os="linux")
def anywhere(self):
return True

@ready_check(os="linux/omarchy")
def here(self):
return True

monkeypatch.setattr(app_module, "detect", lambda: Platform(os="linux", distribution=distribution))
monkeypatch.setenv("ENVIRONMENT_NAME", "notes")
monkeypatch.delenv(APP_SETTINGS_ENV, raising=False)
monkeypatch.chdir(tmp_path)

notes = Notes()

assert set(Notes.declaration().os) == {"linux", "linux/omarchy"}
assert notes.launch.command == launched and hasattr(notes.settings, "portal") == (distribution == "omarchy")
assert sorted(notes._computer_app.ready_checks) == checked


def test_an_install_step_or_ready_check_on_no_os_type_the_app_installs_on_is_refused():
@linux(distribution="omarchy")
class Notes(ComputerAppEnvironment):
@ready_check(os="linux")
def anywhere(self):
return True

@ready_check(os="macos")
def mac(self):
return True

with pytest.raises(ValueError, match="Notes.mac runs on 'macos', which Notes declares no install for"):
Notes.declaration()


@pytest.mark.parametrize(("distribution", "checked"), [("ubuntu", ["anywhere", "on_ubuntu"]),
("omarchy", ["anywhere"])])
def test_an_install_step_or_ready_check_for_a_distribution_runs_there_on_its_os_types_install(
monkeypatch, tmp_path, distribution, checked):
@linux(launch=Launch(command=["notes"]))
class Notes(ComputerAppEnvironment):
@install_step(os="linux/ubuntu")
def fonts(self):
pass

@ready_check(os="linux")
def anywhere(self):
return True

@ready_check(os="linux/ubuntu")
def on_ubuntu(self):
return True

monkeypatch.setattr(app_module, "detect", lambda: Platform(os="linux", distribution=distribution))
monkeypatch.setenv("ENVIRONMENT_NAME", "notes")
monkeypatch.delenv(APP_SETTINGS_ENV, raising=False)
monkeypatch.chdir(tmp_path)

assert [step.os for step in Notes.declaration().install_steps] == [["linux/ubuntu"]]
assert sorted(Notes()._computer_app.ready_checks) == checked


def test_an_app_reads_the_platform_its_computer_was_composed_for_over_what_it_detects(monkeypatch, tmp_path):
@linux(distribution="omarchy", launch=Launch(command=["notes", "--wayland"]))
@linux(launch=Launch(command=["notes"]))
class Notes(ComputerAppEnvironment):
pass

monkeypatch.setattr(app_module, "detect", lambda: Platform(os="linux", distribution="arch"))
monkeypatch.setenv("ENVIRONMENT_NAME", "notes")
monkeypatch.delenv(APP_SETTINGS_ENV, raising=False)
monkeypatch.chdir(tmp_path)
detected = Notes().launch.command
monkeypatch.setenv(PLATFORM_ENV, "linux/omarchy")

assert (detected, Notes().launch.command) == (["notes"], ["notes", "--wayland"])


def test_an_install_step_or_ready_check_for_a_distribution_with_no_install_of_its_own_or_its_os_types_is_refused():
@linux(distribution="omarchy")
class Notes(ComputerAppEnvironment):
@install_step(os="linux/ubuntu")
def fonts(self):
pass

with pytest.raises(ValueError, match="Notes.fonts runs on 'linux/ubuntu', which Notes declares no install for"):
Notes.declaration()


def test_a_declaration_stored_before_each_os_had_its_own_part_reads_as_its_linux_part():
stored = {"supports": LINUX, "permissions": [], "settings": {"type": "object"}, "data": [], "install_steps": [],
"install": {"linux": {"files": ".", "services": [{"name": "imap", "command": "bin/imap"}]}},
Expand All @@ -353,7 +453,7 @@ def test_a_declaration_stored_before_each_os_had_its_own_part_reads_as_its_linux
def test_linux_and_windows_take_every_field_of_their_install_and_what_install_adds_for_an_os():
added = set(inspect.signature(install).parameters) - {"os_type", "spec"}

assert set(inspect.signature(linux).parameters) == set(Linux.model_fields) | added
assert set(inspect.signature(linux).parameters) == set(Linux.model_fields) | added | {"distribution"}
assert set(inspect.signature(windows).parameters) == set(Windows.model_fields) | added


Expand Down
6 changes: 5 additions & 1 deletion src/agent_env/artifact/artifacts/computer.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,18 @@
SettingValue = str | int | float | bool


#: A distribution, as os-release's ID names it here: lowercase letters, digits and "-", from a letter.
DISTRIBUTION = r"^[a-z][a-z0-9-]*$"


class LinuxOS(BaseModel):
"""A Linux base: its distribution and version (``rolling`` for one with no versions, such as Arch), and the display
server its desktop runs, ``none`` for one with no desktop, whose driver's screen is something else, a page say."""

model_config = ConfigDict(extra="forbid")

type: Literal["linux"] = "linux"
distribution: str = Field(pattern=r"^[a-z][a-z0-9-]*$", description="os-release's ID: ubuntu, debian, fedora, arch")
distribution: str = Field(pattern=DISTRIBUTION, description="os-release's ID: ubuntu, debian, fedora, arch")
version: str = Field(min_length=1, description="os-release's VERSION_ID, or rolling")
display: Literal["x11", "wayland", "none"]
build: str | None = None
Expand Down
Loading
Loading