diff --git a/src/agent_env/agents/agents/opencode/Dockerfile b/src/agent_env/agents/agents/opencode/Dockerfile index 5b71a296d..6b2d5a3b3 100644 --- a/src/agent_env/agents/agents/opencode/Dockerfile +++ b/src/agent_env/agents/agents/opencode/Dockerfile @@ -1,3 +1,17 @@ +# The env's clock: the egress proxy, one static Go binary, and agent-env's libfaketime and its TLS shim, taken from +# agent-env's sources as clock/ and egress/ (shared_sources.toml) and built for this image's libc (Debian bookworm) in +# stages of their own, so no toolchain is left in the image. +FROM public.ecr.aws/docker/library/golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS egress +COPY egress/ /egress/ +RUN cd /egress && go vet ./... && go test -count=1 ./... \ + && CGO_ENABLED=0 GOFLAGS=-mod=readonly go build -trimpath -ldflags=-s -o /out/egress . + +FROM public.ecr.aws/docker/library/python:3.11-slim@sha256:c20888b6acdd1e63e1c433a185bf3ad162c0288fe484616ce062e0d28add2900 AS clock +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + build-essential patch curl ca-certificates +COPY clock/ /clock/ +RUN sh /clock/build.sh /out + FROM public.ecr.aws/docker/library/python:3.11-slim@sha256:c20888b6acdd1e63e1c433a185bf3ad162c0288fe484616ce062e0d28add2900 # Node to install the OpenCode CLI, a native binary, and for the model's commands, checked against its published # checksum; install.sh brings the same. poppler-utils renders a PDF attachment to the page images the model reads. @@ -26,13 +40,35 @@ COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # install.sh and run.sh are install/v1's: in the image, so they stay in its build context. COPY a2a_server.py opencode_bridge.py opencode_kit.py entrypoint.sh install.sh run.sh ./ -# The CLI's cwd, /app, and its state under /data, fixed so neither follows the uid: Modal runs the image as root. +# The CLI's cwd, /app, and its state under /data, fixed so neither follows the uid. RUN useradd --create-home --uid 10001 agent && mkdir -p /app /data \ && chown agent:agent /app /data && chmod 0755 entrypoint.sh +# The env's clock: the follower and the egress proxy, each as its own user, under root's supervisord (root.conf), and +# agent-env's libfaketime and its TLS shim preloaded into every process, faking only the agent's (clock.conf). The +# follower's config is the agent's user's to write (agentenv_protocol.a2a_agent.clock) and the follower's to read. +RUN pip install --no-cache-dir supervisor==4.2.5 \ + && useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin agentenv-clock \ + && useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin agentenv-egress \ + && mkdir -p /usr/local/lib/agentenv-clock /usr/local/lib/agentenv-egress /etc/agentenv \ + && install -d -o agent -g agentenv-clock -m 2750 /etc/agentenv/clock \ + && touch /etc/agentenv/ca.pem \ + && cp /etc/ssl/certs/ca-certificates.crt /etc/agentenv/ca-bundle.pem \ + && cp /etc/ssl/certs/ca-certificates.crt /usr/local/lib/agentenv-egress/roots.pem +COPY --from=clock /out/libfaketimeMT.so.1 /out/libtls_realtime.so /usr/local/lib/agentenv-clock/ +COPY --from=egress /out/egress /usr/local/lib/agentenv-egress/egress +COPY clock/clockpage.py clock/clock-follower /usr/local/lib/agentenv-clock/ +COPY clock/clock.conf /etc/agentenv/clock.conf +COPY root.conf /etc/agentenv/root.conf +COPY start-agent /usr/local/bin/start-agent +RUN sed -i -e "s/^AGENTENV_SESSION_UID=.*/AGENTENV_SESSION_UID=$(id -u agent)/" \ + -e "s/^AGENTENV_CLOCK_PAGE_UID=.*/AGENTENV_CLOCK_PAGE_UID=$(id -u agentenv-clock)/" /etc/agentenv/clock.conf \ + && chmod 0755 /usr/local/lib/agentenv-clock/clock-follower /usr/local/bin/start-agent \ + && printf '%s\n' /usr/local/lib/agentenv-clock/libfaketimeMT.so.1 /usr/local/lib/agentenv-clock/libtls_realtime.so \ + > /etc/ld.so.preload ENV A2A_PORT=8000 PYTHONPATH=/opt/agent HOME=/data XDG_CONFIG_HOME=/data/config XDG_CACHE_HOME=/data/cache \ XDG_DATA_HOME=/data/share XDG_STATE_HOME=/data/state -USER agent WORKDIR /app EXPOSE 8000 -# CMD rather than ENTRYPOINT: Modal passes a sandbox's env to the image's CMD only. -CMD ["/opt/agent/entrypoint.sh"] +# Starts as root, which start-agent needs for the clock; the A2A server and the CLI run as the agent's user. CMD rather +# than ENTRYPOINT: Modal passes a sandbox's env to the image's CMD only. +CMD ["/usr/local/bin/start-agent"] diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 247ca21b4..f75a652c5 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -22,12 +22,15 @@ import os import re import signal +import struct import threading -from collections.abc import Callable, Mapping +import time +from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from typing import Literal +from urllib.parse import urlsplit from jsonschema import Draft202012Validator, SchemaError, ValidationError from pydantic import BaseModel, ConfigDict, model_validator @@ -96,6 +99,82 @@ def _context_xdg(context_id: str) -> dict[str, str]: return {"XDG_DATA_HOME": str(data_dir / "share"), "XDG_STATE_HOME": str(data_dir / "state")} +#: Set by the image (root.conf) where the egress proxy runs: the CLI and the model's commands go out through it +#: while the agent follows an armed clock. +EGRESS_PROXY_ENV = "AGENTENV_EGRESS_PROXY" +#: The clock page agent-env's libfaketime reads the CLI's time from (clock/clockpage.py, version 2): it keeps the last +#: armed clock while the follower reconnects or restarts, which the follower's status doesn't say. +CLOCK_PAGE = "/dev/shm/agentenv-clock" +_PAGE = struct.Struct(" bool: + """Whether the clock page holds an armed clock, so the CLI started now reads the env's time: the page itself, + as libfaketime reads it, retried while a write is under way (seq odd) or its check doesn't match.""" + try: + with open(page_path or CLOCK_PAGE, "rb") as page: + for _ in range(_PAGE_READ_TRIES): + page.seek(0) + raw = page.read(_PAGE.size) + if len(raw) < _PAGE.size: + return False + magic, version, seq, universe, anchor, rate, armed, _, generation, checked, mono_u, mono_a = \ + _PAGE.unpack(raw) + if magic != _PAGE_MAGIC or version != _PAGE_VERSION: + return False + rate_bits = struct.unpack(" list[str]: + """The model endpoint's host when the CLI reaches it directly on an armed clock: over plain HTTP, which has no + certificate to check at the env's date. Over TLS it goes through the egress proxy, which checks the certificate on + real time and, in an agent's image, reaches a private network's address too (``AGENTENV_EGRESS_PRIVATE``).""" + endpoint = urlsplit(base_url or "") + return [endpoint.hostname] if endpoint.hostname and endpoint.scheme == "http" else [] + + +def egress_env(environ: Mapping[str, str], direct: Iterable[str] = (), *, armed: bool = False) -> dict[str, str]: + """The egress proxy for the CLI and what it starts, where the image runs one (FD-5916) and the clock is ``armed``: + they read the env's time, so a client checking a live site's certificate against it would refuse the site once + the clock is months off, and the proxy, on real time, hands it a certificate that holds then. The env's MCP servers + (``direct``) are reached directly: the proxy refuses an address that isn't global, as a local or private gateway's + is. Unarmed, the CLI reads real time and goes out directly, as an image without the proxy does, so a model endpoint + or mirror at a private address keeps working. Hosts the agent was deployed to reach directly (``NO_PROXY``, + ``no_proxy``) stay direct.""" + proxy = environ.get(EGRESS_PROXY_ENV) + if not proxy or not armed: + return {} + configured = [host.strip() for name in ("NO_PROXY", "no_proxy") for host in (environ.get(name) or "").split(",")] + hosts = ",".join(dict.fromkeys([*_DIRECT_HOSTS, *filter(None, configured), *filter(None, direct)])) + return {**{name: proxy for base in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY") for name in (base, base.lower())}, + "NO_PROXY": hosts, "no_proxy": hosts, "NODE_USE_ENV_PROXY": "1"} + + +def cli_env(context_id: str, environ: Mapping[str, str] = os.environ, *, mcp_servers: dict[str, dict] | None = None, + clock_armed: bool = False) -> dict[str, str]: + """The CLI's environment for ``context_id``: this process's, with the context's own data and state dirs. On an + armed clock (``clock_armed``) the CLI goes out through the egress proxy (``egress_env``), reaching the env's MCP + servers (``mcp_servers``), which it connects to itself, and a plain-HTTP model endpoint directly.""" + model_host = model_direct_hosts(environ.get("LITELLM_BASE_URL")) if clock_armed else [] + mcp_hosts = [url.hostname for url in (urlsplit(str(info.get("url") or "")) for info in (mcp_servers or {}).values()) if url.hostname and url.scheme == "http"] + return {**environ, **_context_xdg(context_id), + **egress_env(environ, [*mcp_hosts, *model_host], armed=clock_armed)} + + async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tuple[int, bytes, bytes]: """Run a short CLI command to its end; one that outlives ``timeout_s`` is killed.""" proc = await asyncio.create_subprocess_exec( @@ -113,7 +192,7 @@ async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tup async def export_session(context_id: str, session_id: str, timeout_s: int = _CLI_TIMEOUT_S) -> bytes: """`opencode export ` for the given context: the transcript JSON bytes.""" - env = {**os.environ, **_context_xdg(context_id)} + env = cli_env(context_id, clock_armed=clock_armed()) code, out, err = await _communicate("opencode", "export", session_id, env=env, timeout_s=timeout_s) if code != 0: raise RuntimeError(f"opencode export failed: {err.decode(errors='replace')[:300]}") @@ -123,7 +202,7 @@ async def export_session(context_id: str, session_id: str, timeout_s: int = _CLI async def import_session(context_id: str, json_path: str, timeout_s: int = _CLI_TIMEOUT_S) -> str | None: """`opencode import ` into the given context's data dir: the imported session id, from 'Imported session: '.""" - env = {**os.environ, **_context_xdg(context_id)} + env = cli_env(context_id, clock_armed=clock_armed()) code, out, err = await _communicate("opencode", "import", json_path, env=env, timeout_s=timeout_s) if code != 0: raise RuntimeError(f"opencode import failed: {err.decode(errors='replace')[:300]}") @@ -477,9 +556,8 @@ async def run_opencode( cmd += ["--file", path] env = { - **os.environ, + **cli_env(context_id, mcp_servers=mcp_servers, clock_armed=clock_armed()), "OPENCODE_CONFIG_CONTENT": json.dumps(config), - **_context_xdg(context_id), } logger.info(f"Running opencode (session={session_id}, model={model}, effort={effort}, ctx={context_id[:12]}, mcp={list((mcp_servers or {}).keys())})") diff --git a/src/agent_env/agents/agents/opencode/root.conf b/src/agent_env/agents/agents/opencode/root.conf new file mode 100644 index 000000000..a88ad91dd --- /dev/null +++ b/src/agent_env/agents/agents/opencode/root.conf @@ -0,0 +1,62 @@ +; Root's supervisord (start-agent, FD-5916): the clock follower and the egress proxy, each as its own user, on real +; time, and the A2A server as the agent's user. The server starts with the real-time marker, which agent-env's +; libfaketime takes out of its environment, so the server's own records keep real timestamps and everything it starts, +; the CLI and the model's commands, reads the env's time. Its socket and logs are root's alone, so the agent's user can +; neither stop nor restart any of them. The follower follows nothing until the server writes its config, which +; sync_env_clock has it do, then picks it up within a quarter second. +[supervisord] +nodaemon=true +user=root +logfile=/var/log/agentenv-root/supervisord.log +pidfile=/run/agentenv-root/supervisord.pid +childlogdir=/var/log/agentenv-root + +[unix_http_server] +file=/run/agentenv-root/supervisor.sock +chmod=0700 + +[rpcinterface:supervisor] +supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface + +[supervisorctl] +serverurl=unix:///run/agentenv-root/supervisor.sock + +[program:clock] +command=/usr/local/bin/python3 -I /usr/local/lib/agentenv-clock/clock-follower +user=agentenv-clock +directory=/ +priority=3 +autorestart=true +startsecs=1 +startretries=1000 +redirect_stderr=true +stdout_logfile=/var/log/agentenv-root/clock.log +environment=HOME="/nonexistent",USER="agentenv-clock",LOGNAME="agentenv-clock" + +[program:egress] +command=/usr/local/lib/agentenv-egress/egress serve +user=agentenv-egress +directory=/ +priority=3 +autorestart=true +startsecs=1 +startretries=1000 +redirect_stderr=true +stdout_logfile=/var/log/agentenv-root/egress.log +environment=HOME="/nonexistent",USER="agentenv-egress",LOGNAME="agentenv-egress",AGENTENV_EGRESS_PRIVATE="allow" + +; uvicorn itself, not entrypoint.sh: the marker holds for the process it's given to alone, and a shell that execs +; uvicorn would hand uvicorn an environment without it. +[program:agent] +command=/usr/local/bin/python3 -m uvicorn a2a_server:app --host 0.0.0.0 --port %(ENV_A2A_PORT)s --timeout-graceful-shutdown 5 +user=agent +directory=/app +priority=10 +autorestart=true +stopasgroup=true +killasgroup=true +stopwaitsecs=30 +redirect_stderr=true +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +environment=HOME="/data",USER="agent",LOGNAME="agent",AGENTENV_REAL_TIME="1",AGENTENV_EGRESS_PROXY="http://127.0.0.1:3128",NODE_EXTRA_CA_CERTS="/etc/agentenv/ca.pem",SSL_CERT_FILE="/etc/agentenv/ca-bundle.pem",REQUESTS_CA_BUNDLE="/etc/agentenv/ca-bundle.pem" diff --git a/src/agent_env/agents/agents/opencode/shared_sources.toml b/src/agent_env/agents/agents/opencode/shared_sources.toml new file mode 100644 index 000000000..dc9d15a01 --- /dev/null +++ b/src/agent_env/agents/agents/opencode/shared_sources.toml @@ -0,0 +1,4 @@ +# What this image's build context takes from agent-env's own sources, at the name its Dockerfile copies it from: one +# copy of each, shared with the other images that take it (utils/docker/context.py). Paths are under src/agent_env. +clock = "utils/faketime_clock" +egress = "utils/egress_proxy" diff --git a/src/agent_env/agents/agents/opencode/start-agent b/src/agent_env/agents/agents/opencode/start-agent new file mode 100755 index 000000000..b813e50d9 --- /dev/null +++ b/src/agent_env/agents/agents/opencode/start-agent @@ -0,0 +1,30 @@ +#!/bin/sh +# The image's start (FD-5916). As root, it makes what the agent's user must not touch, the clock page and file (the +# clock user's from their first byte) and the egress proxy's CA (its key the egress user's alone, trusted in the +# system store, agent-env's trust files and every certifi bundle), then starts root's supervisord (root.conf), which +# runs the clock follower and the egress proxy, each as its own user on real time, and the A2A server as the agent's +# user on real time, everything it starts reading the env's time from the page. Until sync_env_clock has the agent +# follow a clock, the page holds real time and the proxy relays TLS untouched. Started as another user, the image runs +# the A2A server alone, as before, on real time. +set -eu +if [ "$(id -u)" != 0 ]; then + exec /opt/agent/entrypoint.sh +fi +install -d -o root -g root -m 0700 /var/log/agentenv-root /run/agentenv-root +install -d -o agentenv-clock -g agentenv-clock -m 0755 /run/agentenv-clock +python3 -I /usr/local/lib/agentenv-clock/clockpage.py create agentenv-clock +AGENTENV_SESSION_USER=agent AGENTENV_EGRESS_NSS=off \ + /usr/local/lib/agentenv-egress/egress boot > /var/log/agentenv-root/egress-boot.log 2>&1 \ + || { cat /var/log/agentenv-root/egress-boot.log >&2; echo "the egress proxy's boot failed" >&2; exit 2; } +# A provider's own CA bundle stays trusted: Sail, for one, points SSL_CERT_FILE and the like at the bundle it signs +# model requests under, and root.conf points the server's trust at agent-env's bundles instead, so the provider's goes +# into them, and into the egress proxy's roots, which carry those requests once the clock is armed. +for bundle in "${SSL_CERT_FILE:-}" "${REQUESTS_CA_BUNDLE:-}" "${NODE_EXTRA_CA_CERTS:-}" "${CURL_CA_BUNDLE:-}"; do + case "$bundle" in ""|/etc/agentenv/*) continue ;; esac + [ -r "$bundle" ] || continue + for target in /etc/agentenv/ca-bundle.pem /etc/agentenv/ca.pem /usr/local/lib/agentenv-egress/roots.pem; do + grep -qxF "# agentenv: $bundle" "$target" 2>/dev/null && continue + { printf '\n# agentenv: %s\n' "$bundle"; cat "$bundle"; } >> "$target" + done +done +exec supervisord -c /etc/agentenv/root.conf diff --git a/tst/integration/task_step/test_agent_env_clock_local.py b/tst/integration/task_step/test_agent_env_clock_local.py index 139c81b89..a17265238 100644 --- a/tst/integration/task_step/test_agent_env_clock_local.py +++ b/tst/integration/task_step/test_agent_env_clock_local.py @@ -89,6 +89,7 @@ class Agent: AGENTS = { "claude-code": Agent(bridge="claude_bridge", version=("claude", "--version"), shows="(Claude Code)", turn=_claude_turn), + "opencode": Agent(bridge="opencode_bridge", version=("opencode", "--version"), shows="1.17.18"), } diff --git a/tst/unit/agents/opencode/test_env_clock.py b/tst/unit/agents/opencode/test_env_clock.py new file mode 100644 index 000000000..a6c494548 --- /dev/null +++ b/tst/unit/agents/opencode/test_env_clock.py @@ -0,0 +1,81 @@ +"""OpenCode on the env's clock (FD-5916): while the clock page is armed the CLI goes out through the image's egress +proxy, and to the hosts NO_PROXY names, the env's MCP servers, which it connects to itself, and a plain-HTTP model +endpoint directly; unarmed, it goes out as before. What every clocked image shares is checked in +tst/unit/agents/test_agent_clock_images.py.""" + +from __future__ import annotations + +import pytest + +from tst.unit.agents.opencode.agent import opencode_bridge + +PROXY = "http://127.0.0.1:3128" + + + +@pytest.fixture(autouse=True) +def _sessions(tmp_path, monkeypatch): + monkeypatch.setattr(opencode_bridge, "SESSIONS_ROOT", str(tmp_path)) + + +def _direct(env: dict[str, str]) -> set[str]: + return set(env["NO_PROXY"].split(",")) + + +def test_on_an_armed_clock_the_cli_goes_out_through_the_proxy(): + env = opencode_bridge.cli_env("ctx", {opencode_bridge.EGRESS_PROXY_ENV: PROXY, "NO_PROXY": "registry.internal"}, + clock_armed=True) + + assert {env[name] for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "https_proxy")} == {PROXY} + assert {"localhost", "host.docker.internal", "registry.internal"} <= _direct(env) + # Still the context's own session store. + assert env["XDG_DATA_HOME"] == str(opencode_bridge.context_data_dir("ctx") / "share") + + +@pytest.mark.parametrize("environ, armed", [({}, True), ({opencode_bridge.EGRESS_PROXY_ENV: PROXY}, False)]) +def test_without_the_proxy_or_an_armed_clock_the_cli_goes_out_directly_as_before(environ, armed): + env = opencode_bridge.cli_env("ctx", environ, clock_armed=armed) + + assert not {"HTTPS_PROXY", "NO_PROXY"} & set(env) + assert set(env) == {*environ, "XDG_DATA_HOME", "XDG_STATE_HOME"} + + +@pytest.mark.parametrize("base_url, direct", [("http://10.0.0.5:4000", True), ("https://litellm.example.com", False)]) +def test_a_model_endpoint_over_plain_http_is_reached_directly_on_an_armed_clock(base_url, direct): + env = opencode_bridge.cli_env("ctx", {opencode_bridge.EGRESS_PROXY_ENV: PROXY, "LITELLM_BASE_URL": base_url}, + clock_armed=True) + assert (base_url.split("//")[1].split(":")[0] in _direct(env)) is direct + + +def test_the_envs_plain_http_mcp_servers_are_reached_directly_and_https_ones_through_the_proxy_on_an_armed_clock(): + servers = {"env": {"url": "http://host.docker.internal:8080/mcp"}, + "gateway": {"url": "https://mcp.gateway.internal/mcp", "headers": {"x": "y"}}} + env = opencode_bridge.cli_env("ctx", {opencode_bridge.EGRESS_PROXY_ENV: PROXY}, mcp_servers=servers, + clock_armed=True) + + # Bun checks an HTTPS server's certificate against the env's date, which the proxy, on real time, doesn't. + assert "host.docker.internal" in _direct(env) and "mcp.gateway.internal" not in _direct(env) + + +def test_start_agent_keeps_a_providers_ca_bundle_trusted_by_the_server_and_the_proxy(tmp_path): + # Sail points SSL_CERT_FILE and the like at the bundle it signs model requests under; root.conf points the server + # at agent-env's bundles, so start-agent adds the provider's to them and to the proxy's roots, once each. + import subprocess + from pathlib import Path + + start = (Path(__file__).parents[4] / "src/agent_env/agents/agents/opencode/start-agent").read_text() + merge = start[start.index('for bundle in "${SSL_CERT_FILE'):start.index("exec supervisord")] + targets = {"/etc/agentenv/ca-bundle.pem": tmp_path / "ca-bundle.pem", "/etc/agentenv/ca.pem": tmp_path / "ca.pem", + "/usr/local/lib/agentenv-egress/roots.pem": tmp_path / "roots.pem"} + for real, fake in targets.items(): + fake.write_text("SYSTEM ROOTS\n") + merge = merge.replace(real, str(fake)) + sail = tmp_path / "sailbox-ca-bundle.crt" + sail.write_text("-----BEGIN CERTIFICATE-----\nSAIL\n-----END CERTIFICATE-----\n") + + subprocess.run(["sh", "-c", merge], check=True, env={"PATH": "/usr/bin:/bin", "SSL_CERT_FILE": str(sail), + "NODE_EXTRA_CA_CERTS": str(sail), "REQUESTS_CA_BUNDLE": "/etc/agentenv/ca-bundle.pem"}) + + for fake in targets.values(): + text = fake.read_text() + assert text.startswith("SYSTEM ROOTS\n") and text.count("SAIL") == 1, (fake.name, text) diff --git a/tst/unit/agents/opencode/test_image_contract.py b/tst/unit/agents/opencode/test_image_contract.py index 180ef8939..b95efaabb 100644 --- a/tst/unit/agents/opencode/test_image_contract.py +++ b/tst/unit/agents/opencode/test_image_contract.py @@ -7,10 +7,13 @@ import ast import json import re +import tomllib from tst.unit.agents.opencode.agent import AGENT_DIR DOCKERFILE = (AGENT_DIR / "Dockerfile").read_text() +SOURCES = AGENT_DIR.parents[2] +SHARED = tomllib.loads((AGENT_DIR / "shared_sources.toml").read_text()) INSTALL_SH = (AGENT_DIR / "install.sh").read_text() @@ -19,10 +22,18 @@ def _copied() -> list[str]: for name in line.split()] +def _in_context(name: str) -> bool: + """Whether the build context has ``name``: from the folder, or under a folder shared_sources.toml takes from + agent-env's own sources at that name.""" + first, _, rest = name.partition("/") + path = SOURCES / SHARED[first] / rest if first in SHARED else AGENT_DIR / name + return path.is_dir() if name.endswith("/") else path.is_file() + + def test_every_file_the_image_copies_is_in_the_folder(): copied = _copied() - assert copied and all((AGENT_DIR / name).is_file() for name in copied), copied + assert copied and all(_in_context(name) for name in copied), copied # install.sh and run.sh are install/v1's; a build context pruned to what the Dockerfile reads keeps them so. assert {"a2a_server.py", "opencode_bridge.py", "opencode_kit.py", "entrypoint.sh", "install.sh", "run.sh", "package.json", "package-lock.json", "requirements.txt"} <= set(copied) @@ -88,7 +99,7 @@ def test_tls_checks_stay_on(): def test_the_image_starts_through_cmd_which_modal_passes_its_env_to(): - assert 'CMD ["/opt/agent/entrypoint.sh"]' in DOCKERFILE + assert 'CMD ["/usr/local/bin/start-agent"]' in DOCKERFILE assert not re.search(r"^ENTRYPOINT", DOCKERFILE, re.MULTILINE)