From 852876954aca3b5096c8179fa4fe526e717d653d Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Fri, 20 Nov 2026 13:42:32 +0100 Subject: [PATCH 1/2] feat(catalogue): add DigitalMate v0.1.12 DigitalMate's latest release, run unpatched as its Personal Agent service with its bundled WorkSwarm runtime. It offers agent.task/v1, proven 3/3 with Muse Spark Contributor in a container. The adapter's tests join the backend suite and stand in for websockets, which that suite does not have. --- AGENTS.md | 3 +- .../catalogue/agents/digitalmate/agent.json | 56 ++++++ .../catalogue/agents/digitalmate/gateway.py | 99 ++++++++++ .../catalogue/agents/digitalmate/prepare.py | 62 ++++++ .../catalogue/agents/digitalmate/run.py | 131 +++++++++++++ app/tests/catalogue_docs.py | 7 + app/tests/test_catalogue_docs.py | 12 +- app/tests/test_digitalmate_gateway.py | 182 ++++++++++++++++++ app/tests/test_digitalmate_run.py | 133 +++++++++++++ app/ui_tests/test_agents.py | 15 ++ docs/agents/supported/README.md | 3 + docs/agents/supported/digitalmate.md | 37 ++++ 12 files changed, 737 insertions(+), 3 deletions(-) create mode 100644 app/nullius/catalogue/agents/digitalmate/agent.json create mode 100644 app/nullius/catalogue/agents/digitalmate/gateway.py create mode 100644 app/nullius/catalogue/agents/digitalmate/prepare.py create mode 100644 app/nullius/catalogue/agents/digitalmate/run.py create mode 100644 app/tests/test_digitalmate_gateway.py create mode 100644 app/tests/test_digitalmate_run.py create mode 100644 docs/agents/supported/digitalmate.md diff --git a/AGENTS.md b/AGENTS.md index 5237e29e..872357a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,8 @@ and its resources. GitLab: made once on the run's machine with its token, its tasks' lock, the stack's command line), `proxy` (a tinyproxy of a unit's own for the tasks that ask for a proxy) and, in `startup/`, `sitecustomize`: its VMs' disk write limit in every process its driver starts), `catalogue/agents//` - (the reference `agent`; JiuwenSwarm's `agent` and mini-swe-agent's `run`, the wrappers that start them) and `catalogue/capabilities//` (the keyword-memory `capability`); `workspace` (and + (the reference `agent`; DigitalMate's `run`, `gateway` and `prepare` (product startup, task submission and runtime installation); + JiuwenSwarm's `agent` and mini-swe-agent's `run`, the wrappers that start them) and `catalogue/capabilities//` (the keyword-memory `capability`); `workspace` (and `workspace_cli`, its shell command), `cli` and `__main__` (the unified `nullius` and `python -m nullius` commands), `paths` (user config, data and cache locations), `prices` (the user's model price list: fetched on request and before a capped run; what a cost is estimated from), `migrate` (explicit copying of legacy checkout storage), `settings`, `hosts`, `constraints` (what Nullius may use on each machine: one table, the container and systemd scope probes, the warnings), `execution`, `progress` (what a run is doing, one line per stage), `prerequisites` (what a recipe needs of each machine it runs on, asked before Run and again as it starts), `onboarding` (the Getting started checklist: what this machine diff --git a/app/nullius/catalogue/agents/digitalmate/agent.json b/app/nullius/catalogue/agents/digitalmate/agent.json new file mode 100644 index 00000000..2684609c --- /dev/null +++ b/app/nullius/catalogue/agents/digitalmate/agent.json @@ -0,0 +1,56 @@ +{ + "schema": "nullius.agent/v1", + "key": "digitalmate", + "label": "DigitalMate", + "summary": "DigitalMate's Personal Agent service with its owned WorkSwarm runtime.", + "upstream": { + "repository": "https://github.com/openJiuwen-ai/DigitalMate", + "tested": "709f4d39d613cf191d0dbb8bf1e4bec8e8695edf", + "license": "Apache-2.0", + "tag": "v0.1.12", + "core": "Bundled WorkSwarm 0d6857507236d1299276caf0f6fe09e5baaa4c23 and agent-core 8f9f112698d5580b749158b21b1a89a54e16a8f9, verified and installed by the release installer", + "version": "0.1.12" + }, + "install": { + "python": "3.13", + "project": ".", + "pip": [ + "websockets==15.0.1" + ] + }, + "start": { + "command": [ + "{install}/.venv/bin/python", + "{here}/run.py", + "--install", + "{install}", + "{prompt}" + ] + }, + "model": { + "apis": [ + "chat" + ], + "env": { + "API_BASE": "{base_url}", + "API_KEY": "{key}", + "MODEL_NAME": "{model}", + "MODEL_PROVIDER": "OpenAI" + } + }, + "offers": [ + "agent.task/v1" + ], + "proven": { + "agent.task/v1": { + "passed": "3/3", + "on": "2026-11-17", + "model": "meta/muse-spark-1.3-contributor", + "provider": "openrouter", + "version": "0.1.12", + "kit_version": 1, + "backend": "container", + "job": "2026-11-17__23-03-44__kit__agent-task-v1__digitalmate" + } + } +} diff --git a/app/nullius/catalogue/agents/digitalmate/gateway.py b/app/nullius/catalogue/agents/digitalmate/gateway.py new file mode 100644 index 00000000..5af1efb3 --- /dev/null +++ b/app/nullius/catalogue/agents/digitalmate/gateway.py @@ -0,0 +1,99 @@ +"""Submit a task through DigitalMate's native Gateway and return its final answer.""" +from __future__ import annotations + +import json +from pathlib import Path +import time +import uuid + +from websockets.exceptions import WebSocketException +from websockets.sync.client import connect + + +class Gateway: + def __init__(self, socket, deadline: float): + self.socket = socket + self.deadline = deadline + self.sequence = 0 + + def request(self, **params) -> dict: + self.sequence += 1 + request_id = f"nullius-{self.sequence}" + end = min(self.deadline, time.monotonic() + 120) + if time.monotonic() >= end: + raise TimeoutError("DigitalMate task deadline exceeded") + self.socket.send(json.dumps({ + "id": request_id, "method": "digitalmate.request", "params": params, + }, ensure_ascii=False)) + while True: + remaining = end - time.monotonic() + if remaining <= 0: + raise TimeoutError("DigitalMate request timed out: " + params["action"]) + reply = json.loads(self.socket.recv(timeout=remaining)) + # Ignore streamed events; only task snapshots contain the final result. + if not isinstance(reply, dict) or reply.get("id") != request_id: + continue + if reply.get("ok") is not True: + error = reply.get("error") or {} + raise RuntimeError("DigitalMate request rejected: " + str(error.get("code", "unknown"))) + result = reply.get("result") + if not isinstance(result, dict): + raise RuntimeError("DigitalMate Gateway returned an invalid response") + return result + + +def find_task(snapshot: dict, room_id: str, submission_id: str) -> dict | None: + root = snapshot.get("snapshot", snapshot) + if not isinstance(root, dict) or not isinstance(root.get("tasks", []), list): + raise RuntimeError("DigitalMate Gateway returned an invalid snapshot") + for task in root.get("tasks", []): + if isinstance(task, dict) and task.get("room_id") == room_id and task.get("submission_id") == submission_id: + return task + return None + + +def final_answer(task: dict) -> str: + if task.get("status") != "completed": + raise RuntimeError("DigitalMate task did not complete: " + str(task.get("status"))) + answer = task.get("result") + if not isinstance(answer, str) or not answer.strip(): + raise RuntimeError("DigitalMate completed without a final answer") + return answer + + +def submit_task(prompt: str, project_path: Path, token: str, *, timeout: float = 600, + url: str = "ws://127.0.0.1:18092/digitalmate/ws") -> str: + """Use the isolated local service; forward the prompt and workspace unchanged.""" + deadline = time.monotonic() + timeout + try: + with connect(url, + additional_headers={"Authorization": "Bearer " + token}, + open_timeout=min(30, timeout), close_timeout=5, + max_size=32 * 1024 * 1024, proxy=None) as socket: + gateway = Gateway(socket, deadline) + created = gateway.request(action="room.create", title="Nullius task", agent_id="digitalmate") + room_id = created.get("room_id") + if not isinstance(room_id, str) or not room_id: + raise RuntimeError("DigitalMate room.create returned no room_id") + submission_id = str(uuid.uuid4()) + snapshot = gateway.request( + action="room.message", room_id=room_id, submission_id=submission_id, + agent_id="digitalmate", text=prompt, project_path=str(project_path), + client={"language": "en", "device": "mobile"}, + ) + task = find_task(snapshot, room_id, submission_id) + if task is None and not snapshot.get("task_id"): + raise RuntimeError("DigitalMate room.message returned no task receipt") + while True: + if task is not None: + status = task.get("status") + if status not in {"pending", "queued", "running"}: + return final_answer(task) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("DigitalMate task deadline exceeded") + time.sleep(min(1, remaining)) + task = find_task(gateway.request(action="snapshot"), room_id, submission_id) + except WebSocketException as error: + # Keep authentication headers and connection internals out of stderr. + raise RuntimeError("DigitalMate Gateway connection failed") from error diff --git a/app/nullius/catalogue/agents/digitalmate/prepare.py b/app/nullius/catalogue/agents/digitalmate/prepare.py new file mode 100644 index 00000000..6c565ccc --- /dev/null +++ b/app/nullius/catalogue/agents/digitalmate/prepare.py @@ -0,0 +1,62 @@ +"""Prepare DigitalMate and WorkSwarm in Nullius's container installation.""" +from __future__ import annotations + +import argparse +import os +from pathlib import Path +import subprocess + +from nullius import paths, settings + +settings.load(paths.settings_file()) +from nullius.standard import container, definitions, install + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, help="Fetch the same pinned commit from a local Git checkout") + args = parser.parse_args() + definition = definitions.get("agent", "digitalmate") + if definition is None: + raise SystemExit("DigitalMate is missing from the effective catalogue") + if args.source: + source = args.source.resolve() + subprocess.run(["git", "-C", str(source), "cat-file", "-e", + definition["upstream"]["tested"] + "^{commit}"], check=True) + # Fetch the same commit locally without changing either repo's Git config. + index = int(os.environ.get("GIT_CONFIG_COUNT", "0")) + os.environ["GIT_CONFIG_COUNT"] = str(index + 1) + os.environ[f"GIT_CONFIG_KEY_{index}"] = "url." + source.as_uri() + ".insteadOf" + os.environ[f"GIT_CONFIG_VALUE_{index}"] = definition["upstream"]["repository"] + image = container.base_image() + run_in = lambda cmd, where, env=None: container.install_argv(image, where, cmd, env) + location = Path(install.packages(definition, run_in=run_in, image=image)) + marker = location / ".digitalmate-runtime-ready" + if marker.exists() and marker.read_text().strip() == definition["upstream"]["tested"]: + print("DigitalMate runtime already prepared:", location) + return + runtime = location / "runtime" + python = str(runtime / "bin/python") + source = location / "src" + commands = [] + # When Nullius installs root contracts, add the service as the Dockerfile does. + if definition["install"].get("project") == ".": + commands.append(["uv", "pip", "install", "--python", str(location / ".venv/bin/python"), + str(source / "harness/personal-agent/services/agent_bridge") + "[geo]"]) + commands += [ + ["uv", "venv", "--clear", "--seed", "--python", str(location / ".venv/bin/python"), str(runtime)], + [python, str(source / "harness/personal-agent/deploy/install_runtime.py")], + ] + try: + with (location / "digitalmate-runtime-install.log").open("a") as log: + for command in commands: + subprocess.run(run_in(command, str(location), {"PIP_NO_CACHE_DIR": "1"}), + env=install.install_env(), stdout=log, stderr=log, check=True) + finally: + install.remove_scratch(str(location)) + marker.write_text(definition["upstream"]["tested"] + "\n") + print("DigitalMate runtime prepared:", location) + + +if __name__ == "__main__": + main() diff --git a/app/nullius/catalogue/agents/digitalmate/run.py b/app/nullius/catalogue/agents/digitalmate/run.py new file mode 100644 index 00000000..fce9771e --- /dev/null +++ b/app/nullius/catalogue/agents/digitalmate/run.py @@ -0,0 +1,131 @@ +"""Start the product service with relay credentials and submit Nullius's task.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time +from urllib.error import URLError +from urllib.request import urlopen +import uuid + +from gateway import submit_task + + +def stop(service: subprocess.Popen) -> None: + # The supervisor and tool children belong to this trial too. + try: + os.killpg(service.pid, signal.SIGTERM) + except ProcessLookupError: + service.wait() + return + try: + service.wait(timeout=15) + except subprocess.TimeoutExpired: + pass + try: + os.killpg(service.pid, signal.SIGKILL) + except ProcessLookupError: + pass + service.wait() + + +def require_container() -> None: + if not any(Path(path).exists() for path in ("/.dockerenv", "/run/.containerenv")): + raise RuntimeError("DigitalMate requires --backend container for service isolation and cleanup") + + +def run(install: Path, prompt: str) -> str: + source = install / "src" + runtime = install / "runtime/bin/python" + launcher = source / "harness/personal-agent/services/agent_bridge/src/server_engine/workswarm_launcher.py" + if not runtime.is_file() or not (install / ".digitalmate-runtime-ready").is_file(): + raise RuntimeError("DigitalMate runtime is not prepared; run app/nullius/catalogue/agents/digitalmate/prepare.py first") + expected = json.loads(Path(__file__).with_name("agent.json").read_text())["upstream"]["tested"] + if (install / ".digitalmate-runtime-ready").read_text().strip() != expected: + raise RuntimeError("DigitalMate runtime pin differs; run prepare.py for this definition") + if not launcher.is_file(): + raise RuntimeError("Pinned DigitalMate installation is missing its product launcher") + for name in ("API_BASE", "API_KEY", "MODEL_NAME"): + if not os.environ.get(name): + raise RuntimeError("Nullius relay setting is missing: " + name) + require_container() + + # Keep product state outside the benchmark workspace and isolated per trial. + with tempfile.TemporaryDirectory(prefix="digitalmate-", dir=Path.home()) as temporary: + state = Path(temporary) + env = dict(os.environ) + token = uuid.uuid4().hex + env.update( + DIGITALMATE_ACCESS_TOKEN=token, + DIGITALMATE_WORKSWARM_COMMAND=json.dumps([str(runtime), str(launcher)]), + DIGITALMATE_SEARCH_PYTHON=sys.executable, + DIGITALMATE_WORKSWARM_TOOL_PYTHON=str(runtime), + ) + # Match the release's deploy/entrypoint.py defaults for its owned state. + env.setdefault("DIGITALMATE_SECRET_STORE", "file") + env.setdefault("DIGITALMATE_MEMORY_BACKEND", "sqlite-offline") + env.setdefault("DIGITALMATE_SCHEDULE_SCAN_ENABLED", "0") + # These values must not redirect this trial to a deployed service. + for key in ("DIGITALMATE_WORKSWARM_WS", "DIGITALMATE_CONFIG_FILE", "DIGITALMATE_CLIENT_AUTH"): + env.pop(key, None) + service = subprocess.Popen( + [sys.executable, "-m", "server_engine.engine_cli", "serve", "--workspace", str(state), + "--host", "127.0.0.1", "--port", "18092"], + env=env, stdin=subprocess.DEVNULL, stdout=sys.stderr, stderr=sys.stderr, + start_new_session=True, + ) + previous = {} + def interrupted(signum, _frame): + raise SystemExit(128 + signum) + for signum in (signal.SIGTERM, signal.SIGINT): + previous[signum] = signal.signal(signum, interrupted) + try: + deadline = time.monotonic() + 180 + while True: + if service.poll() is not None: + raise RuntimeError("DigitalMate service exited during startup; inspect agent stderr") + try: + with urlopen("http://127.0.0.1:18092/health/ready", timeout=2) as response: + if response.status == 200: + break + except (URLError, TimeoutError): + pass + if time.monotonic() >= deadline: + raise RuntimeError("DigitalMate service did not become ready in 180 seconds") + time.sleep(0.5) + return submit_task(prompt, Path.cwd(), token) + finally: + stop(service) + # Preserve WorkSwarm's separate log before deleting trial state. + runtime_log = state / "workswarm/process.log" + if runtime_log.is_file(): + from server_engine.engine_config import redact_credentials + with runtime_log.open("rb") as handle: + handle.seek(max(0, runtime_log.stat().st_size - 32768)) + tail = handle.read().decode("utf-8", errors="replace") + print(redact_credentials(tail, env), file=sys.stderr) + for signum, handler in previous.items(): + signal.signal(signum, handler) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--install", required=True, type=Path) + parser.add_argument("prompt") + args = parser.parse_args() + try: + print(run(args.install.resolve(), args.prompt)) + return 0 + except (RuntimeError, subprocess.SubprocessError, ValueError, OSError) as error: + print("digitalmate-nullius: " + str(error), file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/app/tests/catalogue_docs.py b/app/tests/catalogue_docs.py index 32d44d85..164b9023 100644 --- a/app/tests/catalogue_docs.py +++ b/app/tests/catalogue_docs.py @@ -139,6 +139,11 @@ def _page_of(d: dict) -> str: def _installed_from(d: dict) -> str: """What the install pins: the packages, or the repository at its commit.""" inst, up = d.get("install") or {}, d.get("upstream") or {} + if inst.get("project"): + repo = (up.get("repository") or "").replace("https://", "") + source = f"`{repo}` at `{str(up.get('tested', ''))[:12]}`" + helpers = _chips(list(inst.get("pip") or []) + [x["url"].rsplit("/", 1)[1] for x in inst.get("wheels") or []]) + return source + ("; " + helpers if helpers else "") if inst.get("npm"): return _chips(inst["npm"]) if inst.get("pip") or inst.get("wheels"): @@ -167,6 +172,8 @@ def _driven(d: dict) -> str: def _from(d: dict) -> str: inst = d.get("install") or {} + if inst.get("project"): + return "repository" source = {"npm": "npm", "pip": "PyPI"} return next((source[k] for k in source if inst.get(k)), "repository" if inst.get("project") or (d.get("upstream") or {}).get("repository") else "") diff --git a/app/tests/test_catalogue_docs.py b/app/tests/test_catalogue_docs.py index c92777e0..b6426c89 100644 --- a/app/tests/test_catalogue_docs.py +++ b/app/tests/test_catalogue_docs.py @@ -20,6 +20,14 @@ def test_the_generated_files_are_current(self): self.assertEqual(catalogue_docs.stale(), [], "run: python3 app/tests/catalogue_docs.py --write") + def test_project_with_helper_package_keeps_its_repository_source(self): + entry = {"upstream": {"repository": "https://example.org/agent", "tested": "a" * 40}, + "install": {"project": ".", "pip": ["websockets==15.0.1"]}} + self.assertEqual(catalogue_docs._from(entry), "repository") + installed = catalogue_docs._installed_from(entry) + self.assertIn("example.org/agent", installed) + self.assertIn("websockets==15.0.1", installed) + def test_every_section_has_its_index_with_a_block(self): for kind, folder in catalogue_docs.SECTIONS.items(): path = os.path.join(folder, catalogue_docs.INDEX) @@ -34,12 +42,12 @@ def named(key, text): # a key is a code chip: markdown's in a table, HTML's on a card self.assertTrue(f"`{key}`" in text or f"{key}" in text, key) agents = catalogue_docs.render_agents_index() - for key in ("codex@2.2.2", "codex@0.16.0", "goose", "jiuwenswarm@0.2.7", "jiuwenswarm@0.2.8", "mini-swe-agent", "opencode", "terminus-2"): + for key in ("digitalmate", "codex@2.2.2", "codex@0.16.0", "goose", "jiuwenswarm@0.2.7", "jiuwenswarm@0.2.8", "mini-swe-agent", "opencode", "terminus-2"): named(key, agents) for port in ("agent.task/v1", "agent.workspace/v1", "agent.tools/v1", "agent.conversation/v1"): self.assertIn(f"`{port}`", agents) pages = catalogue_docs.render_pages("agents") - self.assertEqual(sorted(pages), ["codex.md", "goose.md", "jiuwenswarm.md", "mini-swe-agent.md", "opencode.md", "terminus-2.md"]) + self.assertEqual(sorted(pages), ["codex.md", "digitalmate.md", "goose.md", "jiuwenswarm.md", "mini-swe-agent.md", "opencode.md", "terminus-2.md"]) named("codex@0.16.0", pages["codex.md"]) for text in (agents, *pages.values()): self.assertNotIn("2026-", text, "no proof dates on a page") diff --git a/app/tests/test_digitalmate_gateway.py b/app/tests/test_digitalmate_gateway.py new file mode 100644 index 00000000..fe34adf7 --- /dev/null +++ b/app/tests/test_digitalmate_gateway.py @@ -0,0 +1,182 @@ +"""Exercise the adapter against native Gateway frames, without a model or service.""" +from collections import deque +import json +from pathlib import Path +import sys +import unittest +from unittest.mock import MagicMock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "nullius/catalogue/agents/digitalmate")) + + +def stub_websockets(): + """The backend suite has no websockets; every test here patches the socket.""" + try: + import websockets # noqa: F401 + except ImportError: + import types + exceptions = types.ModuleType("websockets.exceptions") + exceptions.WebSocketException = type("WebSocketException", (Exception,), {}) + client = types.ModuleType("websockets.sync.client") + client.connect = None + sys.modules.update({"websockets": types.ModuleType("websockets"), "websockets.exceptions": exceptions, + "websockets.sync": types.ModuleType("websockets.sync"), "websockets.sync.client": client}) + + +stub_websockets() +import gateway # noqa: E402 + + +class Socket: + """A service that advances a task across snapshots and interleaves events.""" + def __init__(self, statuses=("pending", "running", "completed"), *, answer=" FINAL ANSWER: São Paulo\n", + nested=True, receipt_only=False, error=None): + self.statuses = iter(statuses) + self.answer = answer + self.nested = nested + self.receipt_only = receipt_only + self.error = error + self.frames = [] + self.inbox = deque() + self.submission = "" + + def snapshot(self): + task = {"id": "task-1", "room_id": "room-1", "submission_id": self.submission, + "status": next(self.statuses), "result": self.answer} + root = {"tasks": [ + dict(task, room_id="other-room", result="Wrong room"), + dict(task, submission_id="other-submission", result="Wrong submission"), + task, + ]} + return {"snapshot": root} if self.nested else root + + def send(self, message): + frame = json.loads(message) + self.frames.append(frame) + params = frame["params"] + action = params["action"] + reply = {"id": frame["id"], "ok": True} + if action == "room.create": + reply["result"] = {"room_id": "room-1"} + elif action == "room.message": + self.submission = params["submission_id"] + if self.error: + reply.update(ok=False, error=self.error) + else: + reply["result"] = {"task_id": "task-1"} if self.receipt_only else self.snapshot() + elif action == "snapshot": + reply["result"] = self.snapshot() + else: + raise AssertionError("Unexpected action: " + action) + self.inbox.extend([ + json.dumps({"event": "digitalmate.stream", "final": True, "text": "Not the task result"}), + json.dumps({"id": "unrelated-request", "ok": True, "result": {"text": "Wrong reply"}}), + json.dumps(reply), + ]) + + def recv(self, *, timeout): + assert timeout > 0 + return self.inbox.popleft() + + +class GatewayTests(unittest.TestCase): + prompt = ' Read the file.\nReturn {"answer": "its content"}.\n' + workspace = Path("/trial/workspace with spaces") + + def submit(self, socket): + connection = MagicMock() + connection.__enter__.return_value = socket + with patch.object(gateway, "connect", return_value=connection) as connect, \ + patch.object(gateway.time, "sleep"): + answer = gateway.submit_task(self.prompt, self.workspace, "local-test-token") + self.assertEqual(connect.call_args.args, ("ws://127.0.0.1:18092/digitalmate/ws",)) + self.assertEqual(connect.call_args.kwargs["additional_headers"], + {"Authorization": "Bearer local-test-token"}) + connection.__exit__.assert_called_once() + return answer + + def test_native_protocol_preserves_prompt_workspace_and_final_result(self): + for nested in (True, False): + with self.subTest(nested=nested): + socket = Socket(nested=nested) + self.assertEqual(self.submit(socket), socket.answer) + params = [f["params"] for f in socket.frames] + self.assertEqual([p["action"] for p in params], + ["room.create", "room.message", "snapshot", "snapshot"]) + self.assertEqual(params[1]["text"], self.prompt) + self.assertEqual(params[1]["project_path"], str(self.workspace)) + self.assertEqual(params[1]["client"], {"language": "en", "device": "mobile"}) + self.assertTrue(all(f["method"] == "digitalmate.request" for f in socket.frames)) + self.assertEqual(len({f["id"] for f in socket.frames}), len(socket.frames)) + + def test_receipt_only_submission_is_resolved_from_snapshot(self): + socket = Socket(statuses=("completed",), receipt_only=True) + self.assertEqual(self.submit(socket), socket.answer) + self.assertEqual(len(socket.frames), 3) + + def test_immediate_completion_needs_no_polling(self): + socket = Socket(statuses=("completed",)) + self.assertEqual(self.submit(socket), socket.answer) + self.assertEqual(len(socket.frames), 2) + + def test_noncompleted_task_never_returns_plausible_partial_text(self): + for status in ("failed", "waiting", "cancelled", "stale", "blocked", None): + with self.subTest(status=status), self.assertRaisesRegex(RuntimeError, "did not complete"): + self.submit(Socket(statuses=(status,))) + + def test_completed_task_requires_a_nonempty_text_result(self): + for answer in (None, "", " \n", 42, ["42"]): + with self.subTest(answer=answer), self.assertRaisesRegex(RuntimeError, "without a final answer"): + self.submit(Socket(statuses=("completed",), answer=answer)) + + def test_rejected_submission_is_not_retried(self): + socket = Socket(error={"code": "BAD_PARAMS", "message": "private details"}) + with self.assertRaisesRegex(RuntimeError, "request rejected: BAD_PARAMS") as raised: + self.submit(socket) + self.assertNotIn("private details", str(raised.exception)) + self.assertEqual(len(socket.frames), 2) + + def test_expired_deadline_prevents_further_requests(self): + socket = MagicMock() + with self.assertRaises(TimeoutError): + gateway.Gateway(socket, gateway.time.monotonic() - 1).request(action="snapshot") + socket.send.assert_not_called() + + def test_receive_timeout_fails_without_resubmitting(self): + socket = Socket() + with patch.object(socket, "recv", side_effect=TimeoutError), self.assertRaises(TimeoutError): + self.submit(socket) + self.assertEqual(len(socket.frames), 1) + + def test_running_snapshots_cannot_extend_the_overall_deadline(self): + socket = Socket(statuses=("running", "running", "running")) + connection = MagicMock() + connection.__enter__.return_value = socket + clock = [0.0] + def sleep(seconds): + clock[0] += seconds + with patch.object(gateway, "connect", return_value=connection), \ + patch.object(gateway.time, "monotonic", side_effect=lambda: clock[0]), \ + patch.object(gateway.time, "sleep", side_effect=sleep): + with self.assertRaisesRegex(TimeoutError, "deadline exceeded"): + gateway.submit_task(self.prompt, self.workspace, "local-test-token", timeout=2) + self.assertEqual(clock[0], 2) + self.assertEqual([f["params"]["action"] for f in socket.frames], + ["room.create", "room.message", "snapshot"]) + connection.__exit__.assert_called_once() + + def test_connection_failure_is_reported_without_credentials(self): + with patch.object(gateway, "connect", side_effect=gateway.WebSocketException("private header")): + with self.assertRaisesRegex(RuntimeError, "Gateway connection failed") as raised: + gateway.submit_task(self.prompt, self.workspace, "local-test-token") + self.assertNotIn("private header", str(raised.exception)) + + def test_malformed_matching_response_is_rejected(self): + socket = MagicMock() + socket.recv.return_value = json.dumps({"id": "nullius-1", "ok": True, "result": "not a snapshot"}) + with self.assertRaisesRegex(RuntimeError, "invalid response"): + gateway.Gateway(socket, gateway.time.monotonic() + 10).request(action="snapshot") + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_digitalmate_run.py b/app/tests/test_digitalmate_run.py new file mode 100644 index 00000000..ce9aeabf --- /dev/null +++ b/app/tests/test_digitalmate_run.py @@ -0,0 +1,133 @@ +"""The Nullius adapter preserves product answers and owns its trial processes. + +No model, network, runtime installation or real process is needed by these tests. +""" +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import MagicMock, Mock, call, patch + + +AGENT = Path(__file__).resolve().parents[1] / "nullius/catalogue/agents/digitalmate" +sys.path.insert(0, str(AGENT)) +from tests.test_digitalmate_gateway import stub_websockets # noqa: E402 +stub_websockets() +SPEC = importlib.util.spec_from_file_location( + "digitalmate_nullius_run", AGENT / "run.py" +) +assert SPEC is not None and SPEC.loader is not None +adapter = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(adapter) + + +class PreparedInstallTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="digitalmate-nullius-test-") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.install = self.root / "install" + self.relay = {"API_BASE": "http://relay:8080/trial/v1", "API_KEY": "placeholder", "MODEL_NAME": "test-model"} + + def prepare(self): + for relative in ( + "runtime/bin/python", ".digitalmate-runtime-ready", + "src/harness/personal-agent/services/agent_bridge/src/server_engine/workswarm_launcher.py", + ): + file = self.install / relative + file.parent.mkdir(parents=True, exist_ok=True) + file.touch() + (self.install / ".digitalmate-runtime-ready").write_text(json.loads((AGENT / "agent.json").read_text())["upstream"]["tested"]) + + def test_runtime_must_be_prepared_before_a_process_starts(self): + with patch.object(adapter.subprocess, "Popen") as launch: + with self.assertRaisesRegex(RuntimeError, "runtime is not prepared"): + adapter.run(self.install, "question") + self.prepare() + (self.install / ".digitalmate-runtime-ready").unlink() + with self.assertRaisesRegex(RuntimeError, "runtime is not prepared"): + adapter.run(self.install, "question") + launch.assert_not_called() + + def test_stale_runtime_pin_is_refused(self): + self.prepare() + (self.install / ".digitalmate-runtime-ready").write_text("0" * 40) + with patch.object(adapter.subprocess, "Popen") as launch: + with self.assertRaisesRegex(RuntimeError, "runtime pin differs"): + adapter.run(self.install, "question") + launch.assert_not_called() + + def test_product_entry_points_must_exist(self): + self.prepare() + (self.install / "src/harness/personal-agent/services/agent_bridge/src/server_engine/workswarm_launcher.py").unlink() + with patch.object(adapter.subprocess, "Popen") as launch: + with self.assertRaisesRegex(RuntimeError, "missing its product launcher"): + adapter.run(self.install, "question") + launch.assert_not_called() + + def test_each_relay_setting_is_required_before_a_process_starts(self): + self.prepare() + for missing in self.relay: + environment = {key: value for key, value in self.relay.items() if key != missing} + with self.subTest(missing=missing), patch.dict(adapter.os.environ, environment, clear=True): + with patch.object(adapter.subprocess, "Popen") as launch: + with self.assertRaisesRegex(RuntimeError, "relay setting is missing: " + missing): + adapter.run(self.install, "question") + launch.assert_not_called() + + def test_client_failure_still_stops_owned_service(self): + self.prepare() + service = Mock(pid=43210) + service.poll.return_value = None + response = MagicMock() + response.__enter__.return_value.status = 200 + failed = RuntimeError("Gateway disconnected") + with patch.dict(adapter.os.environ, self.relay, clear=True), \ + patch.object(adapter, "require_container"), \ + patch.object(adapter.Path, "home", return_value=self.root), \ + patch.object(adapter.subprocess, "Popen", return_value=service) as launch, \ + patch.object(adapter, "submit_task", side_effect=failed) as submit, \ + patch.object(adapter, "urlopen", return_value=response), \ + patch.object(adapter.signal, "signal", return_value=signal.SIG_DFL), \ + patch.object(adapter, "stop") as stop: + with self.assertRaisesRegex(RuntimeError, "Gateway disconnected"): + adapter.run(self.install, "Keep this prompt unchanged.") + stop.assert_called_once_with(service) + self.assertTrue(launch.call_args.kwargs["start_new_session"]) + self.assertEqual(submit.call_args.args[:2], ("Keep this prompt unchanged.", Path.cwd())) + self.assertEqual(submit.call_args.args[2], launch.call_args.kwargs["env"]["DIGITALMATE_ACCESS_TOKEN"]) + + def test_local_backend_is_refused(self): + with patch.object(adapter.Path, "exists", return_value=False): + with self.assertRaisesRegex(RuntimeError, "requires --backend container"): + adapter.require_container() + + +class ProcessCleanupTests(unittest.TestCase): + def test_cleanup_terminates_group_and_reaps_service_even_after_timeout(self): + for first_wait in (0, subprocess.TimeoutExpired("service", 15)): + with self.subTest(first_wait=first_wait): + service = Mock(pid=43210) + service.wait.side_effect = [first_wait, 0] + with patch.object(adapter.os, "killpg") as kill_group: + adapter.stop(service) + self.assertEqual(kill_group.call_args_list, [ + call(43210, signal.SIGTERM), call(43210, signal.SIGKILL), + ]) + self.assertEqual(service.wait.call_args_list, [call(timeout=15), call()]) + + def test_group_disappearing_during_cleanup_is_harmless(self): + service = Mock(pid=43210) + with patch.object(adapter.os, "killpg", side_effect=[None, ProcessLookupError]): + adapter.stop(service) + service.wait.assert_any_call() + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index ff80abe1..08b2af43 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -75,6 +75,21 @@ def test_capability_source_retains_pin_and_install_details(self): self.assertNotIn('is a promise a benchmark relies on', html) self.assertNotIn("once, in the standard's home", html) + def test_digitalmate_is_in_the_normal_catalogue_with_its_proven_task_port(self): + with patch.object(definitions, "load", _LOAD): + listing = self.get("/agents").get_data(as_text=True) + detail = self.get("/agents/digitalmate").get_data(as_text=True) + self.assertIn('/agents/digitalmate', listing) + self.assertIn('DigitalMate', detail) + self.assertIn('709f4d39d613c', detail) + agent = _GET("agent", "digitalmate") + self.assertEqual(agent["upstream"]["tag"], "v0.1.12") + self.assertEqual(agent["offers"], ["agent.task/v1"]) + proof = agent["proven"]["agent.task/v1"] + self.assertEqual(proof["passed"], "3/3") + self.assertEqual(proof["version"], agent["upstream"]["version"]) + self.assertEqual(proof["model"], "meta/muse-spark-1.3-contributor") + def test_bundled_agents_use_shared_marks(self): with patch.object(definitions, "load", _LOAD): html = self.get("/agents").get_data(as_text=True) diff --git a/docs/agents/supported/README.md b/docs/agents/supported/README.md index b9d7aaaa..ea5db9c0 100644 --- a/docs/agents/supported/README.md +++ b/docs/agents/supported/README.md @@ -9,6 +9,7 @@ Every agent in the catalogue, the ports each version has proven, and the benchma | Agent | Versions (bare key: the default) | What it is | Driven over | From | Licence | |---|---|---|---|---|---| | [Codex](codex.md) | `codex@2.2.2`, `codex@0.16.0` | OpenAI's coding agent. | ACP via `codex-acp` | npm | Apache-2.0 | +| [DigitalMate](digitalmate.md) | `digitalmate` | DigitalMate's Personal Agent service with its owned WorkSwarm runtime. | a command | repository | Apache-2.0 | | [Goose](goose.md) | `goose` | The AAIF's open-source agent, formerly Block's. | ACP | npm | Apache-2.0 | | [JiuwenSwarm](jiuwenswarm.md) | `jiuwenswarm@0.2.7`, `jiuwenswarm@0.2.8` | openJiuwen's agent. | ACP | PyPI | Apache-2.0 | | [mini-swe-agent](mini-swe-agent.md) | `mini-swe-agent` | Princeton's 100-line agent, bash only. | a command | PyPI | MIT | @@ -35,6 +36,7 @@ Every agent in the catalogue, the ports each version has proven, and the benchma codex@2.2.2✓✓✓✓✓✓✓✓✓ codex@0.16.0✓✓✓✓✓–✓✓✓ +digitalmate✓–––––––– goose✓✓✓✓✓–✓✓✓ jiuwenswarm@0.2.7✓✓✓✓––✓✓✓ jiuwenswarm@0.2.8✓✓✓✓✓–✓✓✓ @@ -53,6 +55,7 @@ Every agent in the catalogue, the ports each version has proven, and the benchma codex@2.2.2✓✓✓✓✓✓✓✓✓ codex@0.16.0✓✓✓✓✗✗✓✓✓ +digitalmate✗✓✗✓✗✗✗✗✗ goose✓✓✓✓✗✗✓✓✓ jiuwenswarm@0.2.7✗✓✓✓✗✗✓✓✓ jiuwenswarm@0.2.8✓✓✓✓✗✗✓✓✓ diff --git a/docs/agents/supported/digitalmate.md b/docs/agents/supported/digitalmate.md new file mode 100644 index 00000000..5045c4d7 --- /dev/null +++ b/docs/agents/supported/digitalmate.md @@ -0,0 +1,37 @@ + + +# DigitalMate + +DigitalMate's Personal Agent service with its owned WorkSwarm runtime. + + + + + + + + + +
Keydigitalmate
Driven overa command
Fromrepository
Installedgithub.com/openJiuwen-ai/DigitalMate at 709f4d39d613; websockets==15.0.1
LicenceApache-2.0
CoreBundled WorkSwarm 0d6857507236d1299276caf0f6fe09e5baaa4c23 and agent-core 8f9f112698d5580b749158b21b1a89a54e16a8f9, verified and installed by the release installer
+ +## Versions + + + + + +
VersionUpstreamPortsTools
One taskWorkspace filesMCP toolsConversationSearchComputer usedecoyschainretry
digitalmate0.1.12✓––––––––
+ +## Options + +None declared. + +## Benchmarks it fits + + + + + +
GAIAGSM8KHumanEvalOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0
One task, Workspace files, SearchOne taskWorkspace filesOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace files
digitalmate✗✓✗✓✗✗✗✗✗
+ +- ✗: the missing port, on hover. From 7a8d345be146af49aa2595dc811dd222d02839f9 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Fri, 20 Nov 2026 15:24:13 +0100 Subject: [PATCH 2/2] feat(standard): run an upstream's own install commands after its packages An agent's or capability's install block may list commands, run last in the install folder ({install}) under the same lock and marker. DigitalMate uses them to add its service package and run its release's runtime installer, so a Run installs it like any other agent and the hand-run prepare.py is gone. The task port is proven again on that install. --- AGENTS.md | 2 +- .../catalogue/agents/digitalmate/agent.json | 28 ++++++++- .../catalogue/agents/digitalmate/prepare.py | 62 ------------------- .../catalogue/agents/digitalmate/run.py | 9 +-- app/nullius/standard/definitions.py | 16 ++++- app/nullius/standard/install.py | 5 +- app/tests/test_digitalmate_run.py | 22 ++----- app/tests/test_standard_definitions.py | 10 +++ app/tests/test_standard_install.py | 18 ++++++ docs/standard.md | 1 + 10 files changed, 81 insertions(+), 92 deletions(-) delete mode 100644 app/nullius/catalogue/agents/digitalmate/prepare.py diff --git a/AGENTS.md b/AGENTS.md index 872357a7..d31c1c26 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ and its resources. GitLab: made once on the run's machine with its token, its tasks' lock, the stack's command line), `proxy` (a tinyproxy of a unit's own for the tasks that ask for a proxy) and, in `startup/`, `sitecustomize`: its VMs' disk write limit in every process its driver starts), `catalogue/agents//` - (the reference `agent`; DigitalMate's `run`, `gateway` and `prepare` (product startup, task submission and runtime installation); + (the reference `agent`; DigitalMate's `run` and `gateway` (product startup and task submission); JiuwenSwarm's `agent` and mini-swe-agent's `run`, the wrappers that start them) and `catalogue/capabilities//` (the keyword-memory `capability`); `workspace` (and `workspace_cli`, its shell command), `cli` and `__main__` (the unified `nullius` and `python -m nullius` commands), diff --git a/app/nullius/catalogue/agents/digitalmate/agent.json b/app/nullius/catalogue/agents/digitalmate/agent.json index 2684609c..717fec07 100644 --- a/app/nullius/catalogue/agents/digitalmate/agent.json +++ b/app/nullius/catalogue/agents/digitalmate/agent.json @@ -16,6 +16,30 @@ "project": ".", "pip": [ "websockets==15.0.1" + ], + "commands": [ + [ + "uv", + "pip", + "install", + "--quiet", + "--python", + "{install}/.venv/bin/python", + "{install}/src/harness/personal-agent/services/agent_bridge[geo]" + ], + [ + "uv", + "venv", + "--quiet", + "--seed", + "--python", + "{install}/.venv/bin/python", + "{install}/runtime" + ], + [ + "{install}/runtime/bin/python", + "{install}/src/harness/personal-agent/deploy/install_runtime.py" + ] ] }, "start": { @@ -44,13 +68,13 @@ "proven": { "agent.task/v1": { "passed": "3/3", - "on": "2026-11-17", + "on": "2026-11-20", "model": "meta/muse-spark-1.3-contributor", "provider": "openrouter", "version": "0.1.12", "kit_version": 1, "backend": "container", - "job": "2026-11-17__23-03-44__kit__agent-task-v1__digitalmate" + "job": "2026-11-20__15-16-06__kit__agent-task-v1__digitalmate" } } } diff --git a/app/nullius/catalogue/agents/digitalmate/prepare.py b/app/nullius/catalogue/agents/digitalmate/prepare.py deleted file mode 100644 index 6c565ccc..00000000 --- a/app/nullius/catalogue/agents/digitalmate/prepare.py +++ /dev/null @@ -1,62 +0,0 @@ -"""Prepare DigitalMate and WorkSwarm in Nullius's container installation.""" -from __future__ import annotations - -import argparse -import os -from pathlib import Path -import subprocess - -from nullius import paths, settings - -settings.load(paths.settings_file()) -from nullius.standard import container, definitions, install - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--source", type=Path, help="Fetch the same pinned commit from a local Git checkout") - args = parser.parse_args() - definition = definitions.get("agent", "digitalmate") - if definition is None: - raise SystemExit("DigitalMate is missing from the effective catalogue") - if args.source: - source = args.source.resolve() - subprocess.run(["git", "-C", str(source), "cat-file", "-e", - definition["upstream"]["tested"] + "^{commit}"], check=True) - # Fetch the same commit locally without changing either repo's Git config. - index = int(os.environ.get("GIT_CONFIG_COUNT", "0")) - os.environ["GIT_CONFIG_COUNT"] = str(index + 1) - os.environ[f"GIT_CONFIG_KEY_{index}"] = "url." + source.as_uri() + ".insteadOf" - os.environ[f"GIT_CONFIG_VALUE_{index}"] = definition["upstream"]["repository"] - image = container.base_image() - run_in = lambda cmd, where, env=None: container.install_argv(image, where, cmd, env) - location = Path(install.packages(definition, run_in=run_in, image=image)) - marker = location / ".digitalmate-runtime-ready" - if marker.exists() and marker.read_text().strip() == definition["upstream"]["tested"]: - print("DigitalMate runtime already prepared:", location) - return - runtime = location / "runtime" - python = str(runtime / "bin/python") - source = location / "src" - commands = [] - # When Nullius installs root contracts, add the service as the Dockerfile does. - if definition["install"].get("project") == ".": - commands.append(["uv", "pip", "install", "--python", str(location / ".venv/bin/python"), - str(source / "harness/personal-agent/services/agent_bridge") + "[geo]"]) - commands += [ - ["uv", "venv", "--clear", "--seed", "--python", str(location / ".venv/bin/python"), str(runtime)], - [python, str(source / "harness/personal-agent/deploy/install_runtime.py")], - ] - try: - with (location / "digitalmate-runtime-install.log").open("a") as log: - for command in commands: - subprocess.run(run_in(command, str(location), {"PIP_NO_CACHE_DIR": "1"}), - env=install.install_env(), stdout=log, stderr=log, check=True) - finally: - install.remove_scratch(str(location)) - marker.write_text(definition["upstream"]["tested"] + "\n") - print("DigitalMate runtime prepared:", location) - - -if __name__ == "__main__": - main() diff --git a/app/nullius/catalogue/agents/digitalmate/run.py b/app/nullius/catalogue/agents/digitalmate/run.py index fce9771e..0feaf65d 100644 --- a/app/nullius/catalogue/agents/digitalmate/run.py +++ b/app/nullius/catalogue/agents/digitalmate/run.py @@ -44,13 +44,8 @@ def run(install: Path, prompt: str) -> str: source = install / "src" runtime = install / "runtime/bin/python" launcher = source / "harness/personal-agent/services/agent_bridge/src/server_engine/workswarm_launcher.py" - if not runtime.is_file() or not (install / ".digitalmate-runtime-ready").is_file(): - raise RuntimeError("DigitalMate runtime is not prepared; run app/nullius/catalogue/agents/digitalmate/prepare.py first") - expected = json.loads(Path(__file__).with_name("agent.json").read_text())["upstream"]["tested"] - if (install / ".digitalmate-runtime-ready").read_text().strip() != expected: - raise RuntimeError("DigitalMate runtime pin differs; run prepare.py for this definition") - if not launcher.is_file(): - raise RuntimeError("Pinned DigitalMate installation is missing its product launcher") + if not runtime.is_file() or not launcher.is_file(): + raise RuntimeError("DigitalMate installation is missing its runtime or product launcher") for name in ("API_BASE", "API_KEY", "MODEL_NAME"): if not os.environ.get(name): raise RuntimeError("Nullius relay setting is missing: " + name) diff --git a/app/nullius/standard/definitions.py b/app/nullius/standard/definitions.py index bf25f383..914bd328 100644 --- a/app/nullius/standard/definitions.py +++ b/app/nullius/standard/definitions.py @@ -114,6 +114,8 @@ SLOTS = {"here", "install", "prompt"} _WORD = re.compile(r"^(?:[A-Za-z0-9_./:=@+-]|\{[a-z]+\})+$") _SLOT = re.compile(r"\{([a-z]+)\}") +# An install command's word may also name a package's extras (path[extra,other]). +_INSTALL_WORD = re.compile(r"^(?:[A-Za-z0-9_./:=@+,\[\]-]|\{[a-z]+\})+$") _KEY = re.compile(r"^[a-z][a-z0-9-]{0,39}$") _ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$") _TAG = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+/-]{0,127}$") @@ -343,7 +345,9 @@ def _install(d: dict, where: str = "install") -> List[str]: ``locked``, the project's own lock file (``uv.lock``) installed as its pins, ``pip`` resolved beside them, rather than its loose requirements; ``virtual``, with ``locked``, those pins without the project itself, as - ``uv sync`` installs a project that declares no build system. + ``uv sync`` installs a project that declares no build system; + ``commands``, the upstream's own install steps, run in the folder once its + packages are in (``{install}`` names it). A benchmark's driver has the same block, ``driver.install`` (:func:`driver_install`): ``where`` is the name its problems are said under.""" inst = d.get("install") or {} @@ -402,6 +406,12 @@ def _install_block(d: dict, inst: dict) -> List[str]: bad.append(f"install.prefetch: {m!r} is not a hub model id (owner/name)") if inst.get("prefetch") and not (inst.get("pip") or inst.get("project") or inst.get("indexes") or inst.get("wheels")): bad.append("install: prefetch goes with pip, project or indexes, the environment it is installed in") + if "commands" in inst: + if not isinstance(inst["commands"], list) or not inst["commands"]: + bad.append("install.commands: a list of commands") + else: + for i, cmd in enumerate(inst["commands"]): + bad += _command(f"install.commands[{i}]", cmd, {"install"}, _INSTALL_WORD) return bad @@ -694,12 +704,12 @@ def options_of(d: dict, given: Optional[dict] = None) -> Tuple[dict, List[str]]: return {n: given.get(n, o.get("default")) for n, o in opts.items()}, bad -def _command(where: str, cmd, slots=SLOTS) -> List[str]: +def _command(where: str, cmd, slots=SLOTS, word=_WORD) -> List[str]: if not isinstance(cmd, list) or not cmd or not all(isinstance(w, str) for w in cmd): return [f"{where}: a list of words"] bad = [] for w in cmd: - if not _WORD.match(w): + if not word.match(w): bad.append(f"{where}: {w!r} is not a plain word") for s in _SLOT.findall(w): if s not in slots: diff --git a/app/nullius/standard/install.py b/app/nullius/standard/install.py index 5fd61275..f7c6b335 100644 --- a/app/nullius/standard/install.py +++ b/app/nullius/standard/install.py @@ -4,7 +4,8 @@ - ``agents///`` and ``capabilities///``: the packages a definition's ``install`` names (``npm`` into ``node_modules``, ``pip`` and - ``wheels`` - a wheel by its URL, checked by its sha256 - into a ``uv`` environment), the digest taken over that list so a re-pin installs + ``wheels`` - a wheel by its URL, checked by its sha256 - into a ``uv`` environment, then + its ``commands``, the upstream's own install steps), the digest taken over that list so a re-pin installs beside the old one rather than over it; - ``drivers///``: a benchmark's ``driver.install`` the same way - the environment its upstream's own code needs, which its driver imports @@ -262,6 +263,8 @@ def _steps(inst: dict, where: str, up: Optional[dict], src: Optional[str], log: if inst.get("prefetch"): step([py, "-c", "import sys\nfrom huggingface_hub import snapshot_download\nfor m in sys.argv[1:]: snapshot_download(m)"] + list(inst["prefetch"]), env={"HF_HUB_CACHE": os.path.join(where, HF)}) + for cmd in inst.get("commands") or []: # the upstream's own installer, once its packages are in + step([w.replace("{install}", where) for w in cmd]) def process_env(d: dict, where: str, home: str, options: Optional[dict] = None) -> dict: diff --git a/app/tests/test_digitalmate_run.py b/app/tests/test_digitalmate_run.py index ce9aeabf..6ce38e63 100644 --- a/app/tests/test_digitalmate_run.py +++ b/app/tests/test_digitalmate_run.py @@ -5,7 +5,6 @@ from __future__ import annotations import importlib.util -import json from pathlib import Path import signal import subprocess @@ -37,29 +36,20 @@ def setUp(self): def prepare(self): for relative in ( - "runtime/bin/python", ".digitalmate-runtime-ready", + "runtime/bin/python", "src/harness/personal-agent/services/agent_bridge/src/server_engine/workswarm_launcher.py", ): file = self.install / relative file.parent.mkdir(parents=True, exist_ok=True) file.touch() - (self.install / ".digitalmate-runtime-ready").write_text(json.loads((AGENT / "agent.json").read_text())["upstream"]["tested"]) - def test_runtime_must_be_prepared_before_a_process_starts(self): + def test_runtime_must_be_installed_before_a_process_starts(self): with patch.object(adapter.subprocess, "Popen") as launch: - with self.assertRaisesRegex(RuntimeError, "runtime is not prepared"): + with self.assertRaisesRegex(RuntimeError, "missing its runtime"): adapter.run(self.install, "question") self.prepare() - (self.install / ".digitalmate-runtime-ready").unlink() - with self.assertRaisesRegex(RuntimeError, "runtime is not prepared"): - adapter.run(self.install, "question") - launch.assert_not_called() - - def test_stale_runtime_pin_is_refused(self): - self.prepare() - (self.install / ".digitalmate-runtime-ready").write_text("0" * 40) - with patch.object(adapter.subprocess, "Popen") as launch: - with self.assertRaisesRegex(RuntimeError, "runtime pin differs"): + (self.install / "runtime/bin/python").unlink() + with self.assertRaisesRegex(RuntimeError, "missing its runtime"): adapter.run(self.install, "question") launch.assert_not_called() @@ -67,7 +57,7 @@ def test_product_entry_points_must_exist(self): self.prepare() (self.install / "src/harness/personal-agent/services/agent_bridge/src/server_engine/workswarm_launcher.py").unlink() with patch.object(adapter.subprocess, "Popen") as launch: - with self.assertRaisesRegex(RuntimeError, "missing its product launcher"): + with self.assertRaisesRegex(RuntimeError, "product launcher"): adapter.run(self.install, "question") launch.assert_not_called() diff --git a/app/tests/test_standard_definitions.py b/app/tests/test_standard_definitions.py index 75aa33aa..6c7920fb 100644 --- a/app/tests/test_standard_definitions.py +++ b/app/tests/test_standard_definitions.py @@ -70,6 +70,16 @@ def test_a_project_install_needs_its_upstream_and_a_pinned_shape(self): self.bad(ok, "capability", lambda d: d["env"].update(X="{key}"), "env.X: {key} is not a slot") self.bad(ok, "capability", lambda d: d["env"].update(X="$(rm -rf ~)"), "env.X: a variable name and a plain template") + def test_install_commands_are_plain_words_naming_only_the_install(self): + cmds = [["uv", "pip", "install", "--python", "{install}/.venv/bin/python", "{install}/src/svc[geo,web]"], + ["{install}/runtime/bin/python", "{install}/src/install.py"]] + ok = dict(AGENT, install={"pip": ["agent==1.0"], "commands": cmds}) + self.assertEqual(definitions.problems(ok, "agent"), []) + self.bad(ok, "agent", lambda d: d["install"].update(commands=[]), "install.commands: a list of commands") + self.bad(ok, "agent", lambda d: d["install"].update(commands=["uv pip install x"]), "install.commands[0]: a list of words") + self.bad(ok, "agent", lambda d: d["install"]["commands"][1].append("{home}/x"), "install.commands[1]: {home} is not a slot") + self.bad(ok, "agent", lambda d: d["install"]["commands"][1].append("$(curl x)"), "is not a plain word") + def test_a_wheel_by_url_is_pinned_by_its_digest(self): wheel = {"url": "https://example.org/r/model-1.0-py3-none-any.whl", "sha256": "a" * 64} ok = dict(CAPABILITY, install={"pip": ["lib==1.0"], "wheels": [wheel]}) diff --git a/app/tests/test_standard_install.py b/app/tests/test_standard_install.py index e13c82c0..36ead4dc 100644 --- a/app/tests/test_standard_install.py +++ b/app/tests/test_standard_install.py @@ -265,6 +265,24 @@ def test_a_wheel_is_installed_with_the_pins_once_its_digest_matches(self): self.assertEqual(open(wheel, "rb").read(), self.body) self.assertEqual(runs[-1][-2:], ["lib==1.0", wheel]) # one resolution: the wheel's dependencies are pip's + def test_install_commands_run_last_in_the_install_folder(self): + runs = [] + d = {"key": "a", "_kind": "agent", "install": {"pip": ["lib==1.0"], "commands": [["{install}/.venv/bin/python", "{install}/setup.py"]]}} + with mock.patch.object(install, "_run", side_effect=lambda cmd, *a, **k: runs.append(cmd)): + where = install.packages(d, self.home) + self.assertEqual(runs[-1], [os.path.join(where, ".venv/bin/python"), os.path.join(where, "setup.py")]) + self.assertIn(["uv", "pip", "install", "--quiet", "--python", os.path.join(where, ".venv", "bin", "python"), "lib==1.0"], runs[:-1]) + self.assertTrue(os.path.exists(os.path.join(where, install.MARK))) + + def test_a_failed_install_command_leaves_no_marker(self): + d = {"key": "a", "_kind": "agent", "install": {"commands": [["{install}/missing"]]}} + def run(cmd, *a, **k): + raise install.InstallFailed("missing: exit 1") + with mock.patch.object(install, "_run", side_effect=run): + with self.assertRaises(install.InstallFailed): + install.packages(d, self.home) + self.assertFalse(os.path.exists(os.path.join(install.packages_dir(d, self.home), install.MARK))) + def test_a_wheel_whose_digest_differs_is_refused_and_not_kept(self): with mock.patch.object(install, "_run"): with self.assertRaisesRegex(install.InstallFailed, "wheel .*sha256"): diff --git a/docs/standard.md b/docs/standard.md index 0e649a23..1efad743 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -478,6 +478,7 @@ The upstream's dependencies go in `driver.install` (a capability's `install` is | `project` | The upstream itself, from its clone; `locked: true` installs it at its own lock file's pins (`uv export --frozen`), `pip` resolved beside them | | `virtual` | With `locked`: the lock's pins without the project itself; the driver imports the upstream from its clone | | `extras`, `prefetch` | The project's extras; what to download ahead | +| `commands` | The upstream's own install steps, run last in the install folder (`{install}`) | #### Benchmark options