diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 0b6798057..d421916e0 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -72,12 +72,14 @@ neither, Alpine's for one, gets bash from its own package manager. The agent wor or in `/app` on the host. `agents/pi/` runs the [pi coding agent](https://github.com/earendil-works/pi/tree/main/packages/coding-agent) behind -the protocol's A2A agent framework: each turn is one `pi --mode json` run, the task env's MCP servers go to its -`mcp.json`, and its JSON events are the turn's trajectory. Name it as `pi`, its alias, or by its id, -`@local/agentenv-framework/agents/pi`. It calls +the protocol's A2A agent framework: each turn is one `pi --mode json` run, started as `node /opt/pi/bin/pi`, the task +env's MCP servers go to its `mcp.json`, and its JSON events are the turn's trajectory. Name it as `pi`, its alias, or by +its id, `@local/agentenv-framework/agents/pi`. It calls the `[model]` endpoint as an OpenAI-compatible one and takes its model from the prompt, so its smoke task needs -`[model] default` (or the `agent` role) set. It declares `install/v1` too, for Debian or Ubuntu targets. -Its folder's `README.md` covers the extensions it implements. +`[model] default` (or the `agent` role) set. It declares `install/v1` too, for Debian or Ubuntu targets. Its image can +follow a task env's clock as Claude Code's does, opted in the same way, except that pi itself stays on real time and +only the commands it runs for the model follow the clock. Its folder's `README.md` says why, and covers the extensions +it implements. `agents/codex/` runs OpenAI's [Codex CLI](https://github.com/openai/codex) behind the protocol's A2A agent framework: each turn is one `codex exec --json` run, resumed in the context's Codex thread, the task env's MCP servers go to its diff --git a/src/agent_env/agents/agents/pi/Dockerfile b/src/agent_env/agents/agents/pi/Dockerfile index 7b98c8c09..08379cb66 100644 --- a/src/agent_env/agents/agents/pi/Dockerfile +++ b/src/agent_env/agents/agents/pi/Dockerfile @@ -1,13 +1,53 @@ -# docker build -t pi-a2a src/agent_env/agents/agents/pi +# 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 (Ubuntu 24.04's, on +# the image's own base) 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 mirror.gcr.io/library/ubuntu:24.04@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55 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 mirror.gcr.io/library/ubuntu:24.04@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55 WORKDIR /app # Named sources: agent-env packs the build context install/v1 copies from the COPY sources. COPY a2a_server.py changelog.py install.sh peers.py pi_agent.py requirements.txt start.sh ./ +# Every clocked agent's egress rule, which the bridge imports, and the clock page's format it reads (shared_sources.toml). +COPY agent_clock/agent_egress.py clock/clockpage.py ./ RUN sh install.sh \ && useradd --create-home agent \ && mkdir /workspace \ && chown agent /app /workspace +# 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. +# supervisord goes into the agent's venv, whose bin is on the PATH start-agent runs with. +# supervisor 4.2.5 imports pkg_resources, which a Python 3.12 venv doesn't carry: setuptools before 81 brings it. +RUN /opt/pi-a2a-venv/bin/pip install --no-cache-dir supervisor==4.2.5 'setuptools<81' \ + && 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 PATH="/opt/pi-a2a-venv/bin:/opt/pi/bin:/opt/node/bin:${PATH}" -USER agent EXPOSE 8000 -CMD ["python3", "a2a_server.py"] +# Starts as root, which start-agent needs for the clock; the A2A server and pi 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/pi/README.md b/src/agent_env/agents/agents/pi/README.md index c80c211c7..3ca767441 100644 --- a/src/agent_env/agents/agents/pi/README.md +++ b/src/agent_env/agents/agents/pi/README.md @@ -2,14 +2,17 @@ The [pi coding agent](https://github.com/earendil-works/pi/tree/main/packages/coding-agent) wrapped with the `agentenv_protocol.a2a_agent` framework, shipped in the `agents` bundle as -`@local/agentenv-framework/agents/pi`. This directory is the whole build context: the -protocol package comes from PyPI (`requirements.txt`), and `install.sh` installs Node, pi and the -agent's environment both for the image and for `install/v1`. +`@local/agentenv-framework/agents/pi`. Its build context is this directory and what its `shared_sources.toml` +takes from agent-env's own sources: the clock library (`clock/`), the egress proxy (`egress/`) and the egress rule +every clocked agent shares (`agent_clock/`). The protocol package comes from PyPI (`requirements.txt`), and +`install.sh` installs Node, pinned by version and checksum, pi and the agent's environment, both for the image and for +`install/v1`. -Each task runs `pi --mode json` once in its workspace: `PI_A2A_WORKSPACE`, default `/workspace`, and the task -container's working directory when it's installed there. The prompt goes in on stdin. Images and text -files are attached as `@path`; any other file is saved to disk and its path is added to the prompt, -for pi's tools to use. A file fetched from a URL may be at most 256 MiB. The pi config dir is built fresh for each task: +Each task runs `pi --mode json` once, as `node /opt/pi/bin/pi --mode json`, in its workspace: `PI_A2A_WORKSPACE`, +default `/workspace`, and the task container's working directory when it's installed there. The prompt goes in on +stdin. Images and text files are attached as `@path`; any other file is saved to disk and its path is added to the +prompt, for pi's tools to use. A file fetched from a URL may be at most 256 MiB. The pi config dir is built fresh for +each task: - `models.json` points provider `agentenv` at `LITELLM_BASE_URL`. The key stays a `${LITELLM_API_KEY}` reference, so it is never written to disk. @@ -28,7 +31,7 @@ Sessions live in `~/.pi-a2a/sessions` and skills in `~/.pi-a2a/skills/`. | `snapshot/v1` | `save` uploads the context's pi session (JSONL) and, when asked, the workspace as a gzipped tar; `load` replaces the workspace's contents with the saved ones (extracted aside first, so an archive that fails to extract changes nothing), restores the session and binds it to the target context | | `snapshot/v1` changelog | after enable, every tool result builds `NNNNNN.tar`: the files that changed under the roots, the deleted paths and the session so far. Increments upload in order; a failed one is kept, with those after it, and retried at the next tool result and when the task ends, which fails as `pi.changelog_incomplete` if any is still not uploaded. Past 256 MiB held by failed uploads, they are dropped and capture stops, so every later task fails that way until the changelog is enabled again. `apply` replays them in order, writing only under the replaying agent's own roots (symlinks resolved), and with `resume_conversation` binds the last session to the target context | | `peer-agents/v1` | setting peers registers a loopback MCP server (`peers` at `http://127.0.0.1:$A2A_PORT/mcp`) whose `peer_list` and `peer_send_message` tools send A2A messages, one conversation per A2A context and peer. It answers only loopback clients that send a running task's token, which each task gets in its environment and pi sends as a header, so a task speaks only in its own context's conversations. A peer on the host's loopback is retried at `host.docker.internal` | -| `install/v1` | copies this directory into the task container as `/opt/pi-a2a`, runs `install.sh` (Debian or Ubuntu, as root, with network access), writes the LiteLLM credentials to a 0600 `agent.env` through a heredoc and starts `start.sh`, which sources it. The credentials stay off each command's first line, the only one the installer logs, but core's install contract substitutes them into the script text, so a sandbox that logs whole scripts records them | +| `install/v1` | unpacks the build context into the task container as `/opt/pi-a2a`, runs `install.sh` (Debian or Ubuntu, as root, with network access), which also copies the shared egress rule and the clock page's format beside the bridge, as the image does, writes the LiteLLM credentials to a 0600 `agent.env` through a heredoc and starts `start.sh`, which sources it. An installed agent doesn't follow the env's clock: the target runs neither the follower nor agent-env's libfaketime. The credentials stay off each command's first line, the only one the installer logs, but core's install contract substitutes them into the script text, so a sandbox that logs whole scripts records them | | `triggers/v1` | SDK default | Model requests carry `model_params`, merged into the request body through pi's `samplingParams`. agent-env @@ -51,12 +54,47 @@ An installed agent is started without registration env vars, so it does not get Snapshot `load` and changelog `apply` answer 409 while a task is running, and tasks and snapshot saves wait while either restores the workspace. +## The env's clock + +The image can follow a task env's clock as the other clocked agent images do (`src/agent_env/agents/README.md`): +root's supervisord (`start-agent`, `root.conf`) runs the clock follower and the egress proxy, each as its own user, +and the A2A server as `agent` with the real-time marker, and agent-env's libfaketime is preloaded for `agent`. + +- **Off by default.** Without `agent_clock` on `sync_env_clock`, pi and every command it runs keep real time and go + out directly, and the model reads the env's time from the gateway's `get_time`. +- **Opted in, the commands follow.** Once the agent follows an armed clock, every command pi runs for the model reads + the env's time: `date`, `datetime.now()` and the timestamps its programs write. Files keep real modification times, + as libfaketime is built without faking `stat`. +- **pi itself stays on real time.** The bridge starts pi with the real-time marker, which libfaketime takes out of + pi's environment, so what pi starts follows the clock (`cli_env`); pi's `/proc//environ`, its environment as + it started, shows the marker rewritten in place as `AGENTENV_REAL_TIME=0`. It hands pi's script to `node` itself + (`PI_COMMAND`): run through its `#!/usr/bin/env node`, `env` would take the marker and start node without it. pi + can't follow the clock: before 1970 its compaction throws, as it makes a UUIDv7 from its clock, and its file locks + compare its clock with their modification times. + pi 1.1.0's own prompt carries no date (pi dropped it upstream), so nothing pi shows the model gives another time + than the env's; its trajectory's timestamps and its timings are real time. +- **Through the egress proxy.** While the clock is armed, pi and its commands go out by the rule every clocked agent + shares (`agent_egress.egress_env`): every TLS host through the egress proxy, except loopback (the peers MCP server), + `host.docker.internal`, the hosts `NO_PROXY` names and hosts reached by plain HTTP alone. pi honours `HTTP_PROXY`, + `HTTPS_PROXY` and `NO_PROXY` itself, its model and MCP calls alike; Node programs the model runs do through + `NODE_USE_ENV_PROXY`, which Node honours from 22.21. +- **The changelog needs no change.** Capture compares each file's modification time, size and mode with the previous + scan's, never with a clock, and writes each increment's tar itself, in the server on real time; it runs no `tar`. + +Started as a user other than root, the image runs the A2A server alone, on real time, as before. + +## Usage, errors and building + Usage is summed over the assistant messages. `cost_usd` is only reported when the model has `cost` metadata, and the generated `models.json` sets none. A `stopReason` of `error` is an `infra_error` (`pi.model_error`), `aborted` is an `agent_error`, and a timeout kills pi's process group. +`agent-env a2a-agent put`, as above, builds the image from its build context, shared sources included. A plain +`docker build` of this directory lacks them; to build the image alone: + ```bash -docker build -t pi-a2a src/agent_env/agents/agents/pi +python -c 'from pathlib import Path; from agent_env.utils.docker.build import build_image +d = Path("src/agent_env/agents/agents/pi"); build_image(d / "Dockerfile", d, "pi-a2a", platform=None)' docker run -p 8000:8000 -e LITELLM_BASE_URL=... -e LITELLM_API_KEY=... pi-a2a pytest tst/unit/agents/pi ``` diff --git a/src/agent_env/agents/agents/pi/install.sh b/src/agent_env/agents/agents/pi/install.sh index c2a7f68b0..5cbf7af8d 100644 --- a/src/agent_env/agents/agents/pi/install.sh +++ b/src/agent_env/agents/agents/pi/install.sh @@ -2,7 +2,10 @@ # Installs Node, pi and this agent's Python environment on Debian or Ubuntu, as root. The image build and # install/v1 both run it, so an install into a task container matches the image. set -eu -NODE_VERSION=22.19.0 +NODE_VERSION=22.23.3 +# nodejs.org's SHASUMS256.txt for node-v$NODE_VERSION-linux-.tar.xz. +NODE_SHA256_X64=df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de +NODE_SHA256_ARM64=a44aeb94849a299b22df10b9e622ec2f605c2183501bc40590705131de7c740f PI_VERSION=1.1.0 here=$(cd "$(dirname "$0")" && pwd) @@ -12,14 +15,23 @@ apt-get install -y --no-install-recommends ca-certificates curl git python3 pyth rm -rf /var/lib/apt/lists/* case "$(uname -m)" in - x86_64) arch=x64 ;; - aarch64 | arm64) arch=arm64 ;; + x86_64) arch=x64 node_sha256=$NODE_SHA256_X64 ;; + aarch64 | arm64) arch=arm64 node_sha256=$NODE_SHA256_ARM64 ;; *) echo "unsupported architecture: $(uname -m)" >&2; exit 1 ;; esac -curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-${arch}.tar.xz" | tar -xJ -C /opt +node_archive=$(mktemp) +curl -fsSL --retry 3 -o "$node_archive" "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-${arch}.tar.xz" +echo "$node_sha256 $node_archive" | sha256sum -c - +tar -xJf "$node_archive" -C /opt +rm -f "$node_archive" ln -sfn "/opt/node-v${NODE_VERSION}-linux-${arch}" /opt/node PATH="/opt/node/bin:$PATH" npm install --global --prefix /opt/pi --ignore-scripts \ "@earendil-works/pi-coding-agent@${PI_VERSION}" python3 -m venv /opt/pi-a2a-venv /opt/pi-a2a-venv/bin/pip install --no-cache-dir -r "$here/requirements.txt" +# install/v1 unpacks the build context, which keeps the shared egress rule and the clock page's format in the folders +# shared_sources.toml takes them as; the bridge imports them from beside it, where the image's build copies them. +if [ -d "$here/agent_clock" ]; then + cp "$here/agent_clock/agent_egress.py" "$here/clock/clockpage.py" "$here/" +fi diff --git a/src/agent_env/agents/agents/pi/pi_agent.py b/src/agent_env/agents/agents/pi/pi_agent.py index 1f14a169d..54c4728bf 100644 --- a/src/agent_env/agents/agents/pi/pi_agent.py +++ b/src/agent_env/agents/agents/pi/pi_agent.py @@ -63,6 +63,7 @@ from starlette.exceptions import HTTPException from starlette.routing import Route +from agent_egress import EGRESS_PROXY_ENV, clock_armed, egress_env from changelog import ChangelogCapture, apply as apply_increment from peers import Peers @@ -89,6 +90,12 @@ # The peer MCP server's header naming the run, whose value pi reads from its environment, never from disk. PEER_RUN_HEADER = "X-Pi-A2A-Run" PEER_RUN_ENV = "AGENTENV_MCP_PEER_RUN" +# agent-env's libfaketime keeps a process started with this marker on real time and takes it out of the process's +# environment, so every process that one starts reads the env's clock. +REAL_TIME_ENV = "AGENTENV_REAL_TIME" +# pi's script handed to node rather than run by its ``#!/usr/bin/env node``: the marker reaches only the process it's +# started with, and env would start node without it. install.sh installs pi here for the image and install/v1 alike. +PI_COMMAND = ("node", "/opt/pi/bin/pi") # Deltas are reconstructible from the message_end records, so they are left out of the trajectory. _UNRECORDED_EVENTS = frozenset({"message_update", "tool_execution_update"}) # A context id passes through as its session id only when it has none of pi's ``.`` and ``_``; every derived id @@ -201,6 +208,19 @@ def _mcp_json( return {"mcpServers": servers}, env +def cli_env(environ: Mapping[str, str], base_url: str, mcp_servers: Mapping[str, Any] | None = None, *, + armed: bool = False) -> dict[str, str]: + """The pi CLI's environment, before its run's own variables: this process's; where the image runs the env's clock, + the real-time marker, so pi stays on real time while every command it runs follows the clock; and on an ``armed`` + clock the egress proxy (``egress_env``) for the model endpoint, the env's MCP servers and those commands. + + pi itself can't follow the clock: before 1970 its compaction throws (UUIDv7), and its file locks compare its clock + with their modification times. It shows the model no date of its own, so the model reads the env's time alone.""" + urls = [base_url, *(str(entry.get("url") or "") for entry in (mcp_servers or {}).values())] + real_time = {REAL_TIME_ENV: "1"} if EGRESS_PROXY_ENV in environ else {} + return {**environ, **real_time, **egress_env(environ, urls, armed=armed)} + + def _prompt_text(parts: Sequence[Any], unattached: Sequence[tuple[Path, str]]) -> str: chunks = [] for part in parts: @@ -424,7 +444,7 @@ def __init__( *, home: Path | None = None, workspace: Path | None = None, - pi_command: Sequence[str] = ("pi",), + pi_command: Sequence[str] = PI_COMMAND, ) -> None: self.home = home or Path.home() / ".pi-a2a" self.workspace = workspace or Path("/workspace") @@ -528,7 +548,7 @@ async def _run_pi( argv += [f"@{path}" for path in attached] env = { - **os.environ, + **cli_env(os.environ, base_url, request.mcp_servers, armed=clock_armed()), **mcp_env, "PI_CODING_AGENT_DIR": str(agent_dir), "PI_OFFLINE": "1", diff --git a/src/agent_env/agents/agents/pi/root.conf b/src/agent_env/agents/agents/pi/root.conf new file mode 100644 index 000000000..56e20e458 --- /dev/null +++ b/src/agent_env/agents/agents/pi/root.conf @@ -0,0 +1,76 @@ +; Root's supervisord (start-agent): 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. pi, which the bridge +; starts with the marker again (pi_agent.cli_env), stays on real time too, and the model's commands, which pi starts, +; read 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/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" + +; The server's own interpreter, the venv's, as the image's CMD ran it, not start.sh: the marker holds for the process +; it's given to alone, and a shell that execs the server would hand it an environment without it. It isn't restarted, +; even when it fails to start: what the run gave it (its envs' MCP servers, its config, its peers, the turns it's +; running) lives in its memory, so a server restarted in its place would take turns without them. +[program:agent] +command=/opt/pi-a2a-venv/bin/python3 a2a_server.py +user=agent +directory=/app +priority=10 +autorestart=false +startretries=0 +stopasgroup=true +killasgroup=true +stopwaitsecs=30 +redirect_stderr=true +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +environment=HOME="/home/agent",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" + +; Once the server has exited, or failed to start, root's supervisord stops: it stops the follower and the proxy and +; exits, so the container exits with the server, as it did when the server was its process. Their own exits are left +; to their restarts. The listener speaks supervisord's event listener protocol, and supervisord is its parent. +[eventlistener:agent-exit] +command=/usr/bin/python3 -I -c 'import os, signal, sys + while True: sys.stdout.write("READY\n"); sys.stdout.flush(); header = dict(f.split(":", 1) for f in sys.stdin.readline().split()); event = dict(f.split(":", 1) for f in sys.stdin.read(int(header["len"])).split()); os.kill(os.getppid(), signal.SIGTERM) if event["processname"] == "agent" else None; sys.stdout.write("RESULT 2\nOK"); sys.stdout.flush()' +events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL +user=root +directory=/ diff --git a/src/agent_env/agents/agents/pi/shared_sources.toml b/src/agent_env/agents/agents/pi/shared_sources.toml new file mode 100644 index 000000000..6076f3540 --- /dev/null +++ b/src/agent_env/agents/agents/pi/shared_sources.toml @@ -0,0 +1,5 @@ +# 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" +agent_clock = "utils/agent_clock" diff --git a/src/agent_env/agents/agents/pi/start-agent b/src/agent_env/agents/agents/pi/start-agent new file mode 100755 index 000000000..42b377b25 --- /dev/null +++ b/src/agent_env/agents/agents/pi/start-agent @@ -0,0 +1,30 @@ +#!/bin/sh +# The image's start. 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, the commands pi runs 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 python3 a2a_server.py +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 87468d613..96d066e49 100644 --- a/tst/integration/task_step/test_agent_env_clock_local.py +++ b/tst/integration/task_step/test_agent_env_clock_local.py @@ -1,8 +1,9 @@ """An agent image on a task env's clock (FD-5916), end to end on local Docker: the agent deployed with the env serves clock/v1 sync_time; sync_env_clock declares it a follower at the real gateway and hands it its config; from then on -every program the agent's user runs, its CLI included, reads the env's time while the A2A server stays on real time; a -clock write that waits for followers waits for it; and once teardown_sandboxes takes it down, writes stop waiting for -it. An agent whose CLI speaks a protocol the stub endpoint serves also runs one real turn. +every program the agent's user runs reads the env's time, its CLI included unless its bridge starts the CLI on real +time, as pi's does, while the A2A server stays on real time; a clock write that waits for followers waits for it; and +once teardown_sandboxes takes it down, writes stop waiting for it. An agent whose CLI speaks a protocol the stub +endpoint serves also runs one real turn. Runs over images built beforehand, from this branch: AGENTENV_E2E_AGENT_IMAGES names one per agent, as ``claude-code=,codex=``; an agent it doesn't name is skipped as a missing capability.""" @@ -78,18 +79,27 @@ async def _claude_turn(context: TaskStepContext, endpoint: FakeAnthropic) -> Non @dataclass(frozen=True) class Agent: """What the test needs of an agent's image: its bridge module, a command its CLI answers without a model (which - must return under the preloaded library), and a turn against the stub endpoint, for a CLI that speaks its protocol.""" + must return under the preloaded library), a turn against the stub endpoint, for a CLI that speaks its protocol, and, + for a CLI its bridge starts on real time, a program its bridge starts the same way, with the marker, that prints its + own time, then a command's it runs, then the marker as it sees it.""" bridge: str version: tuple[str, ...] shows: str turn: Callable[[TaskStepContext, FakeAnthropic], Awaitable[None]] | None = None + on_real_time: tuple[str, ...] | None = None +# pi's bridge starts node itself (pi_agent.PI_COMMAND), not through pi's ``#!/usr/bin/env node``. +NODE_ON_REAL_TIME = ("node", "-e", "console.log(new Date().toISOString());" + "console.log(require('child_process').execSync('date -u +%FT%TZ').toString().trim());" + "console.log(process.env.AGENTENV_REAL_TIME ?? 'scrubbed')") + 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"), + "pi": Agent(bridge="pi_agent", version=("pi", "--version"), shows="1.1.0", on_real_time=NODE_ON_REAL_TIME), } @@ -164,6 +174,11 @@ async def _follows_until_torn_down(name: str, spec: Agent, tag: str, endpoint: F assert shown["real"].startswith(str(datetime.now(timezone.utc).year)) assert _routes_through_proxy(container, spec.bridge) # armed: live sites' TLS goes through the proxy assert spec.shows in _in_agent(container, "timeout", "30", *spec.version) # the CLI starts on the env's clock + if spec.on_real_time is not None: + # libfaketime keeps the program started with the marker on real time and takes the marker from what it runs. + own, command, marker = _in_agent(container, *spec.on_real_time, real_time=True).splitlines() + print("started as the bridge starts the CLI:", {"own": own, "command": command, "marker": marker}) + assert own.startswith(str(datetime.now(timezone.utc).year)) and command == VIRTUAL and marker == "scrubbed" if spec.turn is not None: await spec.turn(context, endpoint) diff --git a/tst/unit/agents/pi/agent.py b/tst/unit/agents/pi/agent.py index fdc90b649..05c6fc8e9 100644 --- a/tst/unit/agents/pi/agent.py +++ b/tst/unit/agents/pi/agent.py @@ -1,5 +1,5 @@ -"""The pi agent's modules, imported from its folder as its image runs them: by their own names, from the folder on the -path.""" +"""The pi agent's modules, imported as its image runs them: by their own names, from its folder and from the folders +its build context takes as agent_clock/ and clock/, whose modules the image copies beside the bridge.""" import importlib import importlib.util @@ -7,12 +7,16 @@ from pathlib import Path import agent_env +from tst.util.build_context import sent AGENT_DIR = Path(agent_env.__file__).parent / "agents" / "agents" / "pi" -sys.path.insert(0, str(AGENT_DIR)) +IMPORTED = [str(AGENT_DIR), str(sent(AGENT_DIR, "agent_clock/agent_egress.py").parent), + str(sent(AGENT_DIR, "clock/clockpage.py").parent)] +sys.path[:0] = IMPORTED changelog = importlib.import_module("changelog") peers = importlib.import_module("peers") pi_agent = importlib.import_module("pi_agent") +agent_egress = importlib.import_module("agent_egress") # By its path: Claude Code's a2a_server, imported by the same name, may be loaded already. _spec = importlib.util.spec_from_file_location("pi_a2a_server", AGENT_DIR / "a2a_server.py") a2a_server = importlib.util.module_from_spec(_spec) diff --git a/tst/unit/agents/pi/fake_pi.py b/tst/unit/agents/pi/fake_pi.py index 77e096660..eb1a94d3b 100644 --- a/tst/unit/agents/pi/fake_pi.py +++ b/tst/unit/agents/pi/fake_pi.py @@ -1,6 +1,7 @@ """Stands in for ``pi --mode json``: records its invocation and replays a scripted event stream. -``FAKE_PI_RECORD`` names the file the argv, cwd, stdin and pi config dir contents are written to; +``FAKE_PI_RECORD`` names the file the argv, cwd, stdin, pi config dir contents and the environment's agent-env, pi +and proxy variables are written to; ``FAKE_PI_SCENARIO`` selects the stream (``ok``, ``error``, ``crash``, ``hang``). Like pi, it keeps the conversation in ``/_.jsonl``, found by its header's id and cwd, and its tool call writes ``FAKE_PI_WRITE`` (``name=text``) into the working directory when set. @@ -12,6 +13,8 @@ import time from pathlib import Path +ROUTING = frozenset({"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "NODE_USE_ENV_PROXY"}) + def emit(event): sys.stdout.write(json.dumps(event) + "\n") @@ -51,7 +54,8 @@ def session_file(directory, session_id): "stdin": prompt, "models": json.loads((agent_dir / "models.json").read_text()), "mcp": json.loads((agent_dir / "mcp.json").read_text()), - "env": {key: value for key, value in os.environ.items() if key.startswith(("AGENTENV_MCP_", "PI_"))}, + "env": {key: value for key, value in os.environ.items() + if key.startswith(("AGENTENV_", "PI_")) or key.upper() in ROUTING}, "attachments": {arg: Path(arg[1:]).read_bytes().decode() for arg in argv if arg.startswith("@")}, "history": existing.read_text().splitlines()[1:] if existing else None, })) diff --git a/tst/unit/agents/pi/test_env_clock.py b/tst/unit/agents/pi/test_env_clock.py new file mode 100644 index 000000000..4caa1a75d --- /dev/null +++ b/tst/unit/agents/pi/test_env_clock.py @@ -0,0 +1,195 @@ +"""pi on the env's clock: where the image runs the clock, its bridge starts pi with the real-time marker, which +agent-env's libfaketime takes out of pi's environment, so pi stays on real time while every command it runs follows the +clock; and it hands the shared egress rule (tst/unit/agents/test_agent_egress.py) the model endpoint's URL and every MCP +server's, so on an armed clock pi and its commands go out through the image's egress proxy, and to loopback, the hosts +NO_PROXY names and plain-HTTP hosts directly. With the clock off, the bridge starts pi with the flags it had before and +the server's environment, adding only the marker; what the image adds to the server's environment, clock on or off, is +pinned here too. What every clocked image shares is checked in tst/unit/agents/test_agent_clock_images.py.""" + +from __future__ import annotations + +import json +import re +import subprocess +import sys +from dataclasses import dataclass, field +from pathlib import Path + +import pytest +from starlette.testclient import TestClient + +from tst.unit.agents.pi.agent import AGENT_DIR, a2a_server, agent_egress, pi_agent + +PROXY = "http://127.0.0.1:3128" +ENDPOINT = "https://litellm.example.com" +FAKE_PI = Path(__file__).with_name("fake_pi.py") +ARMED_PAGE = agent_egress.clockpage.encode(2, 1_900_000_000 * 10**9, 10**18, 1.0, 1, 3, 0, 0) +UNARMED_PAGE = agent_egress.clockpage.encode(2, 0, 0, 1.0, 0, 3, 0, 0) +ROUTING = {"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy", + "NODE_USE_ENV_PROXY"} +RUN_OWN = {"PI_CODING_AGENT_DIR", "PI_OFFLINE", "PI_SKIP_VERSION_CHECK", "PI_TELEMETRY", "AGENTENV_MCP_0_HEADER_0"} + + +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 = pi_agent.cli_env({agent_egress.EGRESS_PROXY_ENV: PROXY, "NO_PROXY": "registry.internal", "KEPT": "1"}, ENDPOINT, + armed=True) + + assert {env[name] for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "https_proxy")} == {PROXY} + assert env["NODE_USE_ENV_PROXY"] == "1" and env["KEPT"] == "1" + assert {"localhost", "host.docker.internal", "registry.internal"} <= _direct(env) + + +@pytest.mark.parametrize("armed", [False, True]) +def test_pi_stays_on_real_time_wherever_the_image_runs_the_clock_and_the_commands_it_runs_follow_it(armed): + """pi compares its own clock with times it didn't make on the env's (before 1970 its compaction's UUIDv7 throws; + its file locks compare its clock with their modification times), so it runs on real time, armed or not, as a clock + may arm mid-turn; libfaketime takes the marker out of pi's environment, so what pi starts follows the clock.""" + env = pi_agent.cli_env({agent_egress.EGRESS_PROXY_ENV: PROXY}, ENDPOINT, armed=armed) + + assert env[pi_agent.REAL_TIME_ENV] == "1" + + +def test_the_server_hands_pis_script_to_node_so_the_marker_reaches_pi_and_not_env(): + """pi's bin is a ``#!/usr/bin/env node`` script: run as it is, env would be started with the marker, take it, and + start node faked.""" + assert a2a_server.agent.pi_command == pi_agent.PI_COMMAND == ("node", "/opt/pi/bin/pi") + + +@pytest.mark.parametrize("armed", [False, True]) +def test_an_installed_agent_whose_target_runs_no_clock_starts_pi_as_before(armed): + environ = {"KEPT": "1"} + + assert pi_agent.cli_env(environ, ENDPOINT, {"env": {"url": "http://10.0.0.7:8080/mcp"}}, armed=armed) == environ + + +@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 = pi_agent.cli_env({agent_egress.EGRESS_PROXY_ENV: PROXY}, base_url, 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://gateway.internal:8080/mcp"}, "files": {"url": "https://abc-123.w.modal.host/mcp"}, + pi_agent.PEER_MCP_NAME: {"url": pi_agent.PEER_MCP_URL}} + + env = pi_agent.cli_env({agent_egress.EGRESS_PROXY_ENV: PROXY}, ENDPOINT, servers, armed=True) + + # A command pi runs checks an HTTPS server's certificate against the env's date, which the proxy, on real time, + # doesn't; pi itself, on real time, is fine either way. + assert {"gateway.internal", "127.0.0.1"} <= _direct(env) and "abc-123.w.modal.host" not in _direct(env) + assert "litellm.example.com" not in _direct(env) + + +@dataclass +class Spawned: + """How the agent started pi: the argv and environment it passed, and what the fake CLI recorded of them.""" + + environ: dict[str, str] + argv: list[str] = field(default_factory=list) + env: dict[str, str] = field(default_factory=dict) + record: dict = field(default_factory=dict) + + +@pytest.fixture +def run_task(tmp_path, monkeypatch): + """Runs a task through the agent's A2A route with the fake CLI, on a clock page armed or not, in an image that runs + the clock (its server's environment names the egress proxy) or, ``clocked=False``, an installed agent.""" + real_exec = pi_agent.asyncio.create_subprocess_exec + record = tmp_path / "record.json" + + def run(*, armed: bool, clocked: bool = True) -> Spawned: + page = tmp_path / "agentenv-clock" + page.write_bytes(ARMED_PAGE if armed else UNARMED_PAGE) + spawned = Spawned(environ={ + "PATH": "/usr/bin:/bin", "FAKE_PI_RECORD": str(record), "LITELLM_BASE_URL": "http://litellm.test/v1", + "LITELLM_API_KEY": "sk-test", "NO_PROXY": "registry.internal", "TZ": "America/Chicago", + **({agent_egress.EGRESS_PROXY_ENV: PROXY} if clocked else {})}) + monkeypatch.setattr(agent_egress.clockpage, "PAGE", str(page)) + monkeypatch.setattr(pi_agent.os, "environ", dict(spawned.environ)) + + async def recording_exec(*argv, env, **kwargs): + spawned.argv, spawned.env = list(argv), dict(env) + return await real_exec(*argv, env=env, **kwargs) + + monkeypatch.setattr(pi_agent.asyncio, "create_subprocess_exec", recording_exec) + agent = pi_agent.PiAgent(home=tmp_path / "home", workspace=tmp_path / "ws", + pi_command=(sys.executable, str(FAKE_PI))) + with TestClient(agent.create_app(), client=("127.0.0.1", 50000)) as client: + client.post("/ext/agent-config", json={"model": "anthropic/claude-sonnet", "effort": "high"}) + client.post("/ext/mcp-config", json={"name": "env", "url": "https://abc-123.w.modal.host/mcp", + "headers": {"Authorization": "Bearer t"}}) + reply = client.post("/a2a", json={"jsonrpc": "2.0", "id": "1", "method": "message/send", "params": { + "message": {"kind": "message", "messageId": "m-1", "role": "user", "contextId": "ctx-1", + "parts": [{"kind": "text", "text": "what's the date?"}]}, + "configuration": {"blocking": True}}}).json() + assert reply["result"]["status"]["state"] == "completed", reply + spawned.record = json.loads(record.read_text()) + return spawned + + return run + + +def test_on_an_armed_clock_the_agent_starts_pi_on_real_time_through_the_proxy(run_task): + seen = run_task(armed=True).record["env"] + + assert seen[pi_agent.REAL_TIME_ENV] == "1" + assert seen["HTTPS_PROXY"] == seen["HTTP_PROXY"] == PROXY and seen["NODE_USE_ENV_PROXY"] == "1" + direct = set(seen["NO_PROXY"].split(",")) + assert {"litellm.test", "registry.internal", "127.0.0.1"} <= direct and "abc-123.w.modal.host" not in direct + + +def test_with_the_clock_off_the_agent_starts_pi_with_the_flags_and_environment_it_had_before(run_task): + """Off, pi's environment is the server's, unchanged, with the run's own variables and the real-time marker, which + libfaketime takes out before pi reads it; arming the clock changes the proxy variables alone, and no flag.""" + off, on = run_task(armed=False), run_task(armed=True) + + assert set(off.env) - set(off.environ) == {pi_agent.REAL_TIME_ENV, *RUN_OWN} + assert {name: off.env[name] for name in off.environ} == off.environ + assert off.argv == on.argv + assert {name for name in {*off.env, *on.env} if off.env.get(name) != on.env.get(name)} == {*ROUTING, + "PI_CODING_AGENT_DIR"} + + +@pytest.mark.parametrize("armed", [False, True]) +def test_an_installed_agent_whose_target_runs_no_clock_starts_pi_with_the_runs_own_variables_alone(run_task, armed): + spawned = run_task(armed=armed, clocked=False) + + assert set(spawned.env) - set(spawned.environ) == RUN_OWN + assert {name: spawned.env[name] for name in spawned.environ} == spawned.environ + + +def test_the_image_starts_the_server_and_so_pi_and_its_commands_with_these_variables_clock_on_or_off(): + """supervisord adds SUPERVISOR_ENABLED, SUPERVISOR_SERVER_URL, SUPERVISOR_PROCESS_NAME and SUPERVISOR_GROUP_NAME + beside them, and libfaketime takes the marker out of the server's own environment.""" + conf = (AGENT_DIR / "root.conf").read_text() + environment = re.search(r"^environment=(.+)$", conf[conf.index("[program:agent]"):], re.MULTILINE).group(1) + + assert {pair.split("=", 1)[0] for pair in environment.split(",")} == { + "HOME", "USER", "LOGNAME", pi_agent.REAL_TIME_ENV, agent_egress.EGRESS_PROXY_ENV, "NODE_EXTRA_CA_CERTS", + "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE"} + + +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. + start = (AGENT_DIR / "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/pi/test_image_contract.py b/tst/unit/agents/pi/test_image_contract.py new file mode 100644 index 000000000..94bc75610 --- /dev/null +++ b/tst/unit/agents/pi/test_image_contract.py @@ -0,0 +1,124 @@ +"""The image and an install carry what the server runs: every file the Dockerfile copies is in the build context, every +module the server imports, its own and those the context takes from agent-env's sources, is beside it in the image and +on its path once installed, and install.sh, which both run, pins Node by its checksum and pi by the version the bridge +names.""" + +from __future__ import annotations + +import ast +import posixpath +import re +import subprocess +import sys +import tarfile +import tomllib + +from agent_env.utils.docker.context import BuildContext +from tst.unit.agents.pi.agent import AGENT_DIR, pi_agent + +DOCKERFILE = (AGENT_DIR / "Dockerfile").read_text() +INSTALL_SH = (AGENT_DIR / "install.sh").read_text() +SOURCES = AGENT_DIR.parents[2] +SHARED = tomllib.loads((AGENT_DIR / "shared_sources.toml").read_text()) + + +def _source(name: str): + """Where the build context's ``name`` comes from: the folder, or a folder shared_sources.toml takes from agent-env's + own sources at that name.""" + first, _, rest = name.partition("/") + return SOURCES / SHARED[first] / rest if first in SHARED else AGENT_DIR / name + + +def _copied_into() -> dict[str, set[str]]: + """The folders the image's last stage copies each file of the build context into.""" + workdir, folders = "/", {} + stage = re.split(r"^FROM .*$", DOCKERFILE, flags=re.MULTILINE)[-1] + for instruction, args in re.findall(r"^(WORKDIR|COPY) (.+)$", stage, re.MULTILINE): + if instruction == "WORKDIR": + workdir = posixpath.join(workdir, args) + elif "--from=" not in args: + *sources, dest = args.split() + dest = posixpath.join(workdir, dest) + folder = posixpath.normpath(dest if dest.endswith("/") or len(sources) > 1 else posixpath.dirname(dest)) + for source in sources: + folders.setdefault(source, set()).add(folder) + return folders + + +def _imported(path) -> set[str]: + names = set() + for node in ast.walk(ast.parse(path.read_text())): + if isinstance(node, ast.Import): + names |= {alias.name.split(".")[0] for alias in node.names} + elif isinstance(node, ast.ImportFrom) and node.module: + names.add(node.module.split(".")[0]) + return names + + +def _server_modules() -> dict[str, str]: + """Every module the server imports, transitively, that the build context holds: by module name, its name there.""" + shared = {path.stem: f"{name}/{path.name}" for name, source in SHARED.items() + for path in (SOURCES / source).glob("*.py")} + modules = {**shared, **{path.stem: path.name for path in AGENT_DIR.glob("*.py")}} + needed, pending = {}, ["a2a_server"] + while pending: + module = pending.pop() + if module not in needed: + needed[module] = modules[module] + pending += _imported(_source(modules[module])) & set(modules) + return needed + + +def test_every_file_the_image_copies_is_in_its_build_context(): + copied = _copied_into() + + assert copied and all(_source(name).is_file() or _source(name).is_dir() for name in copied), copied + + +def test_the_image_copies_every_module_the_server_imports_beside_it(): + needed, copied = _server_modules(), _copied_into() + + assert {"pi_agent", "agent_egress", "clockpage", "changelog", "peers"} <= set(needed) + assert all("/app" in copied.get(name, set()) for name in needed.values()), (needed, copied) + assert "WORKDIR /app" in DOCKERFILE and "a2a_server.py" in (AGENT_DIR / "root.conf").read_text() + + +def test_an_install_imports_every_module_the_server_imports_from_the_build_context_it_unpacks(tmp_path): + """install/v1 unpacks the build context, which keeps the shared modules in the folders it takes them as; install.sh + copies them beside the bridge, and start.sh runs the server from there, with no PYTHONPATH the model's commands + would inherit.""" + archive, here = tmp_path / "ctx.tar.gz", tmp_path / "pi-a2a" + BuildContext.of(AGENT_DIR, AGENT_DIR / "Dockerfile").write(archive) + with tarfile.open(archive) as tar: + tar.extractall(here, filter="data") + beside = INSTALL_SH[INSTALL_SH.index('if [ -d "$here/agent_clock" ]'):] + imports = ", ".join(sorted(set(_server_modules()) - {"a2a_server"})) + + subprocess.run(["sh", "-c", f'here={here}; {beside}'], check=True, env={"PATH": "/usr/bin:/bin"}) + subprocess.run([sys.executable, "-c", f"import {imports}"], cwd=here, check=True, env={"PATH": "/usr/bin:/bin"}) + assert "PYTHONPATH" not in (AGENT_DIR / "start.sh").read_text() + + +def test_install_sh_pins_node_by_its_checksum_and_pi_by_the_version_the_bridge_names(): + version = re.search(r"^NODE_VERSION=(\S+)$", INSTALL_SH, re.MULTILINE).group(1) + sums = dict(re.findall(r"^NODE_SHA256_(X64|ARM64)=([0-9a-f]{64})$", INSTALL_SH, re.MULTILINE)) + + # Node honours NODE_USE_ENV_PROXY, which the egress rule sets for the programs the model runs, from 22.21. + assert tuple(int(part) for part in version.split(".")) >= (22, 21) + assert set(sums) == {"X64", "ARM64"} + assert 'echo "$node_sha256 $node_archive" | sha256sum -c -' in INSTALL_SH + assert re.search(r"^PI_VERSION=(\S+)$", INSTALL_SH, re.MULTILINE).group(1) == pi_agent.PI_VERSION + + +def test_the_bridge_starts_the_pi_and_the_node_install_sh_installs(): + """The bridge hands pi's bin to node itself, so node is the process the real-time marker reaches; the image and + start.sh put install.sh's Node first among the nodes on the PATH.""" + node, script = pi_agent.PI_COMMAND + + assert node == "node" and script == "/opt/pi/bin/pi" + assert '--prefix /opt/pi --ignore-scripts \\\n "@earendil-works/pi-coding-agent@${PI_VERSION}"' in INSTALL_SH + assert 'ln -sfn "/opt/node-v${NODE_VERSION}-linux-${arch}" /opt/node' in INSTALL_SH + for path in (re.search(r'^ENV PATH="([^"]+)"$', DOCKERFILE, re.MULTILINE).group(1), + re.search(r'^export PATH="([^"]+)"$', (AGENT_DIR / "start.sh").read_text(), re.MULTILINE).group(1)): + entries = path.split(":") + assert "/opt/node/bin" in entries and not any("node" in entry for entry in entries[:entries.index("/opt/node/bin")]) diff --git a/tst/unit/agents/pi/test_root_conf.py b/tst/unit/agents/pi/test_root_conf.py new file mode 100644 index 000000000..dc3fd9a09 --- /dev/null +++ b/tst/unit/agents/pi/test_root_conf.py @@ -0,0 +1,62 @@ +"""Root's supervisord never restarts the A2A server, which holds what the run gave it in memory: once the server exits, +or fails to start, supervisord stops and the container exits with it, as it did when the server was the container's +process. The follower and the egress proxy keep their restarts.""" + +from __future__ import annotations + +import configparser +import json +import shlex +import subprocess +import sys + +from tst.unit.agents.pi.agent import AGENT_DIR + +CONF = configparser.RawConfigParser() +CONF.read_string((AGENT_DIR / "root.conf").read_text()) +LISTENERS = [section for section in CONF.sections() if section.startswith("eventlistener:")] + +# Plays supervisord to the listener: SIGTERM blocked, so a signal the listener sends its parent waits, pending, to be +# seen after each event's result. +PARENT = """ +import json, signal, subprocess, sys +signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM}) +listener = subprocess.Popen(json.loads(sys.argv[1]), stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) +stopped = [] +for event, name in json.loads(sys.argv[2]): + assert listener.stdout.readline() == "READY\\n" + payload = f"processname:{name} groupname:{name} from_state:RUNNING expected:0 pid:42" + listener.stdin.write(f"ver:3.0 server:supervisor serial:1 pool:agent-exit poolserial:1 eventname:{event} " + f"len:{len(payload)}\\n{payload}") + listener.stdin.flush() + assert listener.stdout.readline() == "RESULT 2\\n" and listener.stdout.read(2) == "OK" + stopped.append(signal.SIGTERM in signal.sigpending()) + if stopped[-1]: + signal.sigwait({signal.SIGTERM}) +listener.kill() +print(json.dumps(stopped)) +""" + + +def test_the_server_is_never_restarted_and_the_follower_and_the_proxy_are(): + assert (CONF.get("program:agent", "autorestart"), CONF.get("program:agent", "startretries")) == ("false", "0") + assert CONF.get("program:clock", "autorestart") == CONF.get("program:egress", "autorestart") == "true" + + +def test_one_listener_hears_the_servers_exit_and_its_failure_to_start_as_root(): + assert len(LISTENERS) == 1 + events = {event.strip() for event in CONF.get(LISTENERS[0], "events").split(",")} + assert events == {"PROCESS_STATE_EXITED", "PROCESS_STATE_FATAL"} + assert CONF.get(LISTENERS[0], "user") == "root" + + +def test_the_listener_stops_supervisord_on_the_servers_exit_alone(): + python, *args = shlex.split(CONF.get(LISTENERS[0], "command")) + events = [["PROCESS_STATE_EXITED", "clock"], ["PROCESS_STATE_FATAL", "egress"], ["PROCESS_STATE_EXITED", "agent"], + ["PROCESS_STATE_EXITED", "clock"], ["PROCESS_STATE_FATAL", "agent"]] + + out = subprocess.run([sys.executable, "-c", PARENT, json.dumps([sys.executable, *args]), json.dumps(events)], + capture_output=True, text=True, timeout=30, check=True).stdout + + assert python == "/usr/bin/python3" + assert json.loads(out) == [False, False, True, False, True]