diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 0b6798057..e174e5c8e 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -61,7 +61,8 @@ The A2A server starts with the real-time marker, so it and its records stay on r - **One rule for every clocked agent.** That rule is `agent_egress.py` in `utils/agent_clock`, which only agent images take (`agent_clock = "utils/agent_clock"` in `shared_sources.toml`), so changing it rebuilds no computer base. The bridge imports it, and the image and `install.sh` copy it beside the bridge with the clock's `clockpage.py`, whose - layout and check it reads the page by, so every agent put on the clock, OpenCode's too, goes out the same way. + layout and check it reads the page by, so every agent put on the clock, OpenCode's and Letta Code's too, goes out + the same way. Started as a user other than root, the image runs the A2A server alone, on real time, as before. diff --git a/src/agent_env/agents/agents/letta-code/Dockerfile b/src/agent_env/agents/agents/letta-code/Dockerfile index 53cc4b5a8..7b8b5ddc1 100644 --- a/src/agent_env/agents/agents/letta-code/Dockerfile +++ b/src/agent_env/agents/agents/letta-code/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 Letta Code 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. @@ -25,14 +39,38 @@ 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 mcp_tools.ts a2a_server.py letta_code_bridge.py letta_code_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. +# 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 ./ +# 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 \ && find /opt/agent \( ! -perm -044 -o \( -perm /111 ! -perm -011 \) \) -exec chmod go+rX {} + +# 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/letta-code/README.md b/src/agent_env/agents/agents/letta-code/README.md index 07698dd13..75dce77f6 100644 --- a/src/agent_env/agents/agents/letta-code/README.md +++ b/src/agent_env/agents/agents/letta-code/README.md @@ -32,10 +32,42 @@ direct Letta Code tools through `letta.tools.register`; each tool executes `lett | `install/v1` | Template installer brings checksum-verified Node and uv, the pinned CLI, and a private Python into a container or a Linux host with glibc. Installs git if missing. | | `staging/v1` | SDK default. | -The image runs as user `agent` in `/app`, with state under `/data`, and includes git and `pdftoppm`. PDF attachments -are rendered as page images; other attachments are materialized and their paths passed to the CLI. Headless mode -never loads node-pty, so installation skips dependency scripts and rebuilds only the CLI, sharp and protobufjs. +The image starts as root (`start-agent`), whose supervisord runs the A2A server as user `agent` in `/app`, with state +under `/data`; started as another user, it runs the server alone, as before. Either way the container ends when the +server exits, as before: supervisord never restarts it, and stops once it exits. It includes git and `pdftoppm`. PDF +attachments are rendered as page images; other attachments are materialized and their paths passed to the CLI. Headless +mode never loads node-pty, so installation skips dependency scripts and rebuilds only the CLI, sharp and protobufjs. The end of CLI stderr is included in failures. Cancellation and shutdown kill the CLI's process tree. +The image follows a task env's clock as the agents README describes, only once a `sync_env_clock` sets `agent_clock`. +Letta Code's local backend runs inside each `letta` process, so the whole CLI follows the clock, the "Local time" line +of the environment context it gives the model included, as do the commands the model runs; the A2A server, its model +relay and its records stay on real time. The CLI reaches the model through that relay on loopback, directly, and the env's +MCP servers over TLS through the egress proxy, `letta mcp call` included. The workspace changelog's tar runs on real +time, as file times do. Nothing on the CLI's headless path ages conversations or tool output by file times. What still +reads the env's clock against other times: +- A commit to the git-backed memory, the bridge's or the CLI's, carries the env's date. Before 1970 git stores an + overflowed time, and after 2099 a broken time zone, which `git fsck` flags; `commit`, `ls-tree`, `show`, `log` and + `status`, which the bridge and the CLI run on it, work. +- The memory tool's listing of a folder shows its 10 most recently edited entries, dating committed ones by their + commits, on the env's clock, and uncommitted ones by their files' times, which are real. A clock ahead of real time, + or before 1970, lists committed entries first and one behind it uncommitted ones, which changes the 10 a larger + folder shows. +- A jump back across a compaction makes the CLI's pre-turn compaction check estimate the context's size from its text + rather than from the last reported usage. +- Messages written on 2026-01-01 UTC, the CLI's placeholder date, get timestamps interpolated from the transcript + file's times when loaded, which changes neither their content nor their order. +- A `Retry-After` given as a date (LiteLLM and the providers give seconds) is read against the env's date, and the CLI + waits at most 60 s. +- File locks time out, and those that don't go by their owner's process go stale, on the env's clock, so a rate above + 1 or a jump forward shortens both. A context's own commands are the only ones to take its locks. A jump back + lengthens both: a lock a killed CLI left, the reflection transcript's say, goes stale only once the env's clock + passes the time it was taken plus 90 s, and until then every turn waits 10 s for it at its end and leaves its messages + out of that transcript, logging `Failed to append transcript delta` in the context's `.letta/logs/debug`. A jump back + while a command waits for a held lock stretches the wait by the jump, and a frozen clock (rate 0) stretches it to the + turn's timeout. +- On a frozen clock, every assistant message from a provider that gives no response id (LiteLLM gives one) takes the + same id, made from the time. + Run `agent-env run agents --task letta-code-smoke` for the shell smoke task and `agent-env a2a-agent validate --id letta-code --sandbox local` for the repository's validator. diff --git a/src/agent_env/agents/agents/letta-code/a2a_server.py b/src/agent_env/agents/agents/letta-code/a2a_server.py index becad591e..c31ee00db 100644 --- a/src/agent_env/agents/agents/letta-code/a2a_server.py +++ b/src/agent_env/agents/agents/letta-code/a2a_server.py @@ -506,7 +506,7 @@ async def _capture_changelog(self) -> None: ["tar", f"--listed-incremental={pending_snar}", *_changelog_backup_exclusions(), f"--exclude={_CHANGELOG_DIR}", "-czf", str(archive), *roots, str(record)], - check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=_real_time_env(), ) await config["uploader"].upload(f"{sequence:06d}.tgz", archive) pending_snar.replace(_CHANGELOG_SNAR) @@ -631,6 +631,12 @@ def _removable(path: object) -> bool: and path not in _SYSTEM_DIRS and os.path.lexists(path)) +def _real_time_env() -> dict[str, str]: + """The changelog's tar runs on real time, as file times are: on an env clock ahead, a tar that read it would record + its dump time in the snapshot file ahead of every real change, and the next increment would miss them.""" + return {**os.environ, "AGENTENV_REAL_TIME": "1"} + + def _baseline_changelog(roots: list[str]) -> None: _CHANGELOG_DIR.mkdir(parents=True, exist_ok=True) _CHANGELOG_SNAR.unlink(missing_ok=True) @@ -639,7 +645,7 @@ def _baseline_changelog(roots: list[str]) -> None: ["tar", f"--listed-incremental={_CHANGELOG_SNAR}", *_changelog_backup_exclusions(), "-cf", "/dev/null", *present], - check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=_real_time_env(), ) diff --git a/src/agent_env/agents/agents/letta-code/install.sh b/src/agent_env/agents/agents/letta-code/install.sh index a89987fdf..7522e43db 100644 --- a/src/agent_env/agents/agents/letta-code/install.sh +++ b/src/agent_env/agents/agents/letta-code/install.sh @@ -24,7 +24,7 @@ START_TIMEOUT_S=120 STOP_TIMEOUT_S=10 dockerfile_arg() { sed -n "s/^ARG $1=//p" "$here/Dockerfile"; } NODE_VERSION=$(dockerfile_arg NODE_VERSION) -AGENT_FILES="mcp_tools.ts a2a_server.py letta_code_bridge.py letta_code_kit.py requirements.txt run.sh" +AGENT_FILES="mcp_tools.ts a2a_server.py letta_code_bridge.py letta_code_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py" # put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced; put_dir SRC # DEST copies a folder to DEST, which isn't there. @@ -145,7 +145,7 @@ put "$stage/agent.env" "$root/agent.env" put "$here/package.json" "$root/npm/package.json" put "$here/package-lock.json" "$root/npm/package-lock.json" for file in $AGENT_FILES; do - put "$here/$file" "$root/app/$file" + put "$here/$file" "$root/app/${file##*/}" done on "chmod 0600 $r/agent.env && chmod 0755 $r/bin/uv $r/bin/letta $r/app/run.sh" diff --git a/src/agent_env/agents/agents/letta-code/letta_code_bridge.py b/src/agent_env/agents/agents/letta-code/letta_code_bridge.py index f6c7b4ed9..d49421915 100644 --- a/src/agent_env/agents/agents/letta-code/letta_code_bridge.py +++ b/src/agent_env/agents/agents/letta-code/letta_code_bridge.py @@ -14,7 +14,7 @@ import tarfile import tempfile import threading -from collections.abc import Callable, Mapping +from collections.abc import Callable, Iterable, Mapping from contextlib import asynccontextmanager from dataclasses import dataclass, field from datetime import datetime, timezone @@ -23,6 +23,8 @@ from aiohttp import ClientSession, ClientTimeout, web from jsonschema import Draft202012Validator, SchemaError, ValidationError +from agent_egress import clock_armed, egress_env + logger = logging.getLogger(__name__) # The model a run uses when neither the task nor the agent-config names one; the @@ -57,11 +59,14 @@ def context_data_dir(context_id: str) -> Path: return Path(SESSIONS_ROOT) / ctx_hash -def _context_env(context_id: str) -> dict[str, str]: +def _context_env(context_id: str, urls: Iterable[str] = (), *, armed: bool = False) -> dict[str, str]: + """The CLI's environment for a context: its own data dir as HOME, and on an armed clock (``armed``) the egress + proxy (``egress_env``) for what the CLI and what it starts reach: the model relay, on loopback, which stays direct, + and the env's MCP servers (``urls``), which the CLI connects to itself.""" home = context_data_dir(context_id) home.mkdir(parents=True, exist_ok=True) return {**os.environ, "HOME": str(home), "LETTA_LOCAL_BACKEND_DIR": str(home / ".letta/lc-local-backend"), - "LETTA_LOCAL_BACKEND_EXPERIMENTAL": "1"} + "LETTA_LOCAL_BACKEND_EXPERIMENTAL": "1", **egress_env(os.environ, urls, armed=armed)} async def _communicate(*cmd: str, env: Mapping[str, str], timeout_s: int) -> tuple[int, bytes, bytes]: @@ -435,7 +440,7 @@ async def _turn(prompt, context_id, session_id, model, mcp_servers, system_promp project_id, task_id, role, attachment_paths, effort, event_callback, workspace): model = model or DEFAULT_MODEL handle = "openai-compatible/" + model - env = _context_env(context_id) + env = _context_env(context_id, [info["url"] for info in (mcp_servers or {}).values()], armed=clock_armed()) home = Path(env["HOME"]) (home / "context.json").write_text(json.dumps({"home": str(home)})) attribution = _attribution_headers(project_id, task_id) diff --git a/src/agent_env/agents/agents/letta-code/root.conf b/src/agent_env/agents/agents/letta-code/root.conf new file mode 100644 index 000000000..e01a6626c --- /dev/null +++ b/src/agent_env/agents/agents/letta-code/root.conf @@ -0,0 +1,71 @@ +; 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 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 when the task sets agent_clock, 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. HOME is the image's, /data, under which the CLI's state lives. +; Not restarted: agent-exit ends the container when it exits. +[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=false +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" + +; The A2A server is the container, as it was before the clock: when it exits, or never gets going, this stops +; supervisord, which ends the container, rather than have a fresh server, without the dead one's MCP servers, peers and +; tasks, take its place while the dead one's CLI goes on. A stop of the container stops the server without an exit +; event, and the follower and the proxy restart in place. supervisord exits 0 either way. +[eventlistener:agent-exit] +command=/usr/local/bin/python3 -I -c "while 1: import os, signal, sys; print('READY', flush=True); 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()); event['processname'] == 'agent' and os.kill(os.getppid(), signal.SIGTERM); print('RESULT 2', end='\nOK', flush=True)" +events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL diff --git a/src/agent_env/agents/agents/letta-code/shared_sources.toml b/src/agent_env/agents/agents/letta-code/shared_sources.toml new file mode 100644 index 000000000..6076f3540 --- /dev/null +++ b/src/agent_env/agents/agents/letta-code/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/letta-code/start-agent b/src/agent_env/agents/agents/letta-code/start-agent new file mode 100755 index 000000000..7b84a1e0c --- /dev/null +++ b/src/agent_env/agents/agents/letta-code/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, 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 87468d613..e34e5f3ac 100644 --- a/tst/integration/task_step/test_agent_env_clock_local.py +++ b/tst/integration/task_step/test_agent_env_clock_local.py @@ -2,7 +2,8 @@ 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. +it. An agent whose CLI speaks a protocol a stub endpoint serves, Anthropic's messages or OpenAI's chat completions, +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.""" @@ -16,6 +17,7 @@ from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import datetime, timezone +from typing import Any import pytest from agentenv_protocol.client import ExtensionCallError @@ -38,6 +40,7 @@ local_registry as local_registry, ) from tst.integration.task_step.test_register_env_triggers_local import _deploy_items +from tst.util import fake_openai from tst.util.capabilities import agent_clock_image, skip_without_agent_clock_image from tst.util.fake_anthropic import FakeAnthropic, tool_then_answer @@ -75,20 +78,44 @@ async def _claude_turn(context: TaskStepContext, endpoint: FakeAnthropic) -> Non assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results() +def _text(content) -> str: + return content if isinstance(content, str) else "".join( + part.get("text", "") for part in content or [] if isinstance(part, dict)) + + +async def _letta_turn(context: TaskStepContext, endpoint: fake_openai.FakeOpenAI) -> None: + """One turn of the real Letta Code CLI, its proxy variables set: its model calls reach the bridge's relay on + loopback, which the egress proxy would refuse, and the "Local time" line it gives the model and a Bash `date` the + model runs are the env's.""" + endpoint.respond = fake_openai.tool_then_answer("Bash", {"command": "date -u +%FT%TZ", "description": "Show the date"}, + prefix="the shell said: ") + await PromptAgentTaskStep(id="ask", version=None, prompt="What's the date? Run date.", agent_name="solver", + max_conversation_turns=1).execute(context) + dated = {line for seen in endpoint.completions() for message in seen.body.get("messages") or [] + for line in _text(message.get("content")).splitlines() if "**Local time**" in line} + print("the CLI's Local time line:", dated, "Bash date:", endpoint.tool_results()) + assert dated and all("March 4, 2031" in line for line in dated), dated + assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results() + + @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), and a turn against the stub ``endpoint`` its CLI speaks to, for a CLI + that speaks a stub's protocol.""" bridge: str version: tuple[str, ...] shows: str - turn: Callable[[TaskStepContext, FakeAnthropic], Awaitable[None]] | None = None + turn: Callable[[TaskStepContext, Any], Awaitable[None]] | None = None + endpoint: Callable[..., Any] = FakeAnthropic AGENTS = { "claude-code": Agent(bridge="claude_bridge", version=("claude", "--version"), shows="(Claude Code)", turn=_claude_turn), + "letta-code": Agent(bridge="letta_code_bridge", version=("letta", "--version"), shows="(Letta Code)", + turn=_letta_turn, endpoint=fake_openai.FakeOpenAI), "opencode": Agent(bridge="opencode_bridge", version=("opencode", "--version"), shows="1.17.18"), } @@ -120,11 +147,12 @@ async def _followers(deployed) -> dict: @pytest.mark.parametrize("name", [pytest.param(name, marks=skip_without_agent_clock_image(name)) for name in AGENTS]) @pytest.mark.asyncio async def test_an_agent_image_follows_the_envs_clock_until_it_is_torn_down(local_registry, name): - with FakeAnthropic(host=_host_ips()[-1]) as endpoint: # where this machine's containers reach it - await _follows_until_torn_down(name, AGENTS[name], agent_clock_image(name), endpoint) + spec = AGENTS[name] + with spec.endpoint(host=_host_ips()[-1]) as endpoint: # where this machine's containers reach it + await _follows_until_torn_down(name, spec, agent_clock_image(name), endpoint) -async def _follows_until_torn_down(name: str, spec: Agent, tag: str, endpoint: FakeAnthropic) -> None: +async def _follows_until_torn_down(name: str, spec: Agent, tag: str, endpoint: Any) -> None: _seed_bootstrap_envs() env, deployed, _ = await _deploy_items("agentclock") uid = uuid.uuid4().hex[:8] diff --git a/tst/unit/agents/letta_code/agent.py b/tst/unit/agents/letta_code/agent.py index b29d366ab..76b0bea35 100644 --- a/tst/unit/agents/letta_code/agent.py +++ b/tst/unit/agents/letta_code/agent.py @@ -1,17 +1,23 @@ -"""The Letta Code agent's modules, imported from its folder as its image runs them: by their own names, from the folder -on the path.""" +"""The Letta Code 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 +import os import sys from pathlib import Path import agent_env +from tst.util.build_context import sent AGENT_DIR = Path(agent_env.__file__).parent / "agents" / "agents" / "letta-code" -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)] +PYTHONPATH = os.pathsep.join(IMPORTED) +sys.path[:0] = IMPORTED letta_code_bridge = importlib.import_module("letta_code_bridge") letta_code_kit = importlib.import_module("letta_code_kit") +agent_egress = importlib.import_module("agent_egress") # By its path: another agent's a2a_server, imported by the same name, may be loaded already. _spec = importlib.util.spec_from_file_location("letta_code_a2a_server", AGENT_DIR / "a2a_server.py") a2a_server = importlib.util.module_from_spec(_spec) diff --git a/tst/unit/agents/letta_code/test_env_clock.py b/tst/unit/agents/letta_code/test_env_clock.py new file mode 100644 index 000000000..523c1e10e --- /dev/null +++ b/tst/unit/agents/letta_code/test_env_clock.py @@ -0,0 +1,199 @@ +"""Letta Code on the env's clock: its bridge hands the shared egress rule (tst/unit/agents/test_agent_egress.py) every +MCP server's URL, which the CLI connects to itself, so on an armed clock every ``letta`` command of a turn goes out +through the image's egress proxy, and to loopback, the model relay's among it, the hosts NO_PROXY names and plain-HTTP +hosts directly; unarmed, a turn runs the commands main ran, with the environment main gave them. The workspace +changelog's tar runs on real time whatever the clock. What every clocked image shares is checked in +tst/unit/agents/test_agent_clock_images.py.""" + +from __future__ import annotations + +import asyncio +import json +import subprocess +from contextlib import asynccontextmanager + +import pytest + +from tst.unit.agents.letta_code.agent import AGENT_DIR, a2a_server, agent_egress +from tst.unit.agents.letta_code.agent import letta_code_bridge as bridge + +PROXY = "http://127.0.0.1:3128" +RELAY = "http://127.0.0.1:41000/v1" +PROXY_VARS = {"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy", + "NODE_USE_ENV_PROXY"} + + +@pytest.fixture(autouse=True) +def _sessions(tmp_path, monkeypatch): + monkeypatch.setattr(bridge, "SESSIONS_ROOT", str(tmp_path)) + + +def _env(monkeypatch, environ: dict[str, str], *, urls=(), armed: bool) -> dict[str, str]: + for name in (agent_egress.EGRESS_PROXY_ENV, *PROXY_VARS): + monkeypatch.delenv(name, raising=False) + for name, value in environ.items(): + monkeypatch.setenv(name, value) + return bridge._context_env("ctx", urls, armed=armed) + + +def test_on_an_armed_clock_the_cli_goes_out_through_the_proxy(monkeypatch): + env = _env(monkeypatch, {agent_egress.EGRESS_PROXY_ENV: PROXY, "NO_PROXY": "registry.internal"}, armed=True) + + assert {env[name] for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "https_proxy")} == {PROXY} + # The model relay the CLI is pointed at is on loopback. + assert {"localhost", "127.0.0.1", "host.docker.internal", "registry.internal"} <= set(env["NO_PROXY"].split(",")) + assert env["NODE_USE_ENV_PROXY"] == "1" + + +@pytest.mark.parametrize("environ, armed", [({}, True), ({agent_egress.EGRESS_PROXY_ENV: PROXY}, False)]) +def test_without_the_proxy_or_an_armed_clock_the_cli_goes_out_directly_as_before(monkeypatch, environ, armed): + assert not {"HTTPS_PROXY", "NO_PROXY"} & set(_env(monkeypatch, environ, armed=armed)) + + +def test_the_envs_plain_http_mcp_servers_are_reached_directly_and_https_ones_through_the_proxy_on_an_armed_clock( + monkeypatch): + """Node checks an HTTPS server's certificate against the env's date, which the proxy, on real time, doesn't.""" + urls = ["http://10.0.0.5:8080/mcp", "https://abc-123.w.modal.host/mcp"] + direct = set(_env(monkeypatch, {agent_egress.EGRESS_PROXY_ENV: PROXY}, urls=urls, armed=True)["NO_PROXY"].split(",")) + + assert "10.0.0.5" in direct and "abc-123.w.modal.host" not in direct + + +class _Proc: + """A ``letta`` command that answers as the CLI does: an agent's id to ``agents create``, an empty tool catalog to + ``mcp tools``, a successful result to the turn's own run.""" + + pid = None + returncode = 0 + + def __init__(self, cmd: tuple[str, ...]): + if "create" in cmd: + self.out = b'{"id": "agent-1"}' + elif "tools" in cmd: + self.out = b"[]" + elif "-p" in cmd: + self.out = json.dumps({"type": "result", "subtype": "success", "result": "ok", + "conversation_id": "local-conv-1"}).encode() + b"\n" + else: + self.out = b"" + self.stdout, self.stderr = asyncio.StreamReader(), asyncio.StreamReader() + self.stdout.feed_data(self.out) + for stream in (self.stdout, self.stderr): + stream.feed_eof() + + async def communicate(self): + return self.out, b"" + + async def wait(self): + return 0 + + +def _turn(monkeypatch, tmp_path, *, armed: bool, environ: dict[str, str]) -> list[tuple[tuple[str, ...], dict]]: + """Every command one turn of the bridge starts, with the environment each starts with, for an env MCP server over + TLS, one over plain HTTP and the peer-agents one.""" + spawned = [] + + async def spawn(*cmd, env, **_): + spawned.append((cmd, dict(env))) + return _Proc(cmd) + + @asynccontextmanager + async def relay(*_args, **_kwargs): + yield RELAY + + monkeypatch.setattr(bridge.asyncio, "create_subprocess_exec", spawn) + monkeypatch.setattr(bridge, "model_relay", relay) + monkeypatch.setattr(bridge, "_configure_agent", lambda *args: None) + monkeypatch.setattr(bridge, "clock_armed", lambda: armed) + monkeypatch.setattr(bridge.os, "environ", dict(environ)) + servers = {"env": {"url": "https://abc-123.w.modal.host/mcp"}, "local": {"url": "http://gateway:8080/mcp"}, + "peers": {"url": "http://127.0.0.1:8000/peers/mcp"}} + result = asyncio.run(bridge.run_letta_code("hi", "ctx", model="m", mcp_servers=servers, workspace=str(tmp_path))) + assert result.error is None and result.session_id == "local-conv-1" + return spawned + + +IMAGE_ENV = {agent_egress.EGRESS_PROXY_ENV: PROXY, "PATH": "/usr/local/bin:/usr/bin:/bin", + "NODE_EXTRA_CA_CERTS": "/etc/agentenv/ca.pem", "LITELLM_BASE_URL": "https://litellm.example.com"} + + +def test_on_an_armed_clock_every_command_of_a_turn_goes_out_through_the_proxy_but_to_loopback_and_plain_http( + monkeypatch, tmp_path): + spawned = _turn(monkeypatch, tmp_path, armed=True, environ={**IMAGE_ENV, "HOME": str(tmp_path / "data")}) + + assert [cmd[3] for cmd, _ in spawned] == ["connect", "agents", "mcp", "-p"] + for _, env in spawned: + hosts = env["NO_PROXY"].split(",") + assert env["HTTPS_PROXY"] == env["https_proxy"] == PROXY and env["NODE_USE_ENV_PROXY"] == "1" + assert "abc-123.w.modal.host" not in hosts and {"gateway", "127.0.0.1"} <= set(hosts) + + +def test_unarmed_a_turn_runs_mains_commands_with_mains_environment(monkeypatch, tmp_path): + """With the clock off, the bridge adds nothing to what the CLI ran with before the clock: the image's own variables + (the proxy's address, agent-env's CA bundles) pass through untouched, as every other variable of the server's.""" + environ = {**IMAGE_ENV, "HOME": str(tmp_path / "data")} + spawned = _turn(monkeypatch, tmp_path, armed=False, environ=environ) + home = bridge.context_data_dir("ctx") + base = {**environ, "HOME": str(home), "LETTA_LOCAL_BACKEND_DIR": str(home / ".letta/lc-local-backend"), + "LETTA_LOCAL_BACKEND_EXPERIMENTAL": "1"} + handle = "openai-compatible/m" + + assert spawned == [ + (("letta", "--backend", "local", "connect", "openai-compatible", "--base-url", RELAY, "--api-key", "relay"), + base), + (("letta", "--backend", "local", "agents", "create", "--model", handle), base), + (("letta", "--backend", "local", "mcp", "tools", "--full", "--agent", "agent-1"), base), + (("letta", "--backend", "local", "-p", "hi", "--output-format", "stream-json", "--yolo", "--model", handle, + "--toolset", "default", "--agent", "agent-1", "--new"), {**base, "LETTA_AGENT_ID": "agent-1"}), + ] + + +def test_the_workspace_changelogs_tar_runs_on_real_time(monkeypatch, tmp_path): + """tar's dump time goes into the snapshot file, and the next increment takes only files changed after it: a tar on + an env clock ahead of real time would miss every change, as file times stay real.""" + runs = [] + + def run(cmd, **kwargs): + runs.append((cmd, kwargs.get("env"))) + return subprocess.CompletedProcess(cmd, 0) + + class Uploader: + async def upload(self, name, path): + pass + + changelog = tmp_path / "changelog" + monkeypatch.setattr(a2a_server, "_CHANGELOG_DIR", changelog) + monkeypatch.setattr(a2a_server, "_CHANGELOG_SNAR", changelog / "state.snar") + monkeypatch.setattr(a2a_server, "_CHANGELOG_META_DIR", tmp_path / "meta") + monkeypatch.setattr(a2a_server.subprocess, "run", run) + workspace = tmp_path / "app" + workspace.mkdir() + a2a_server._baseline_changelog([str(workspace)]) + (changelog / "state.snar").write_bytes(b"") + agent = a2a_server.LettaCodeChangelogAgent() + agent._changelog = {"roots": [str(workspace)], "sequence": 0, "present": [str(workspace)], "uploader": Uploader()} + asyncio.run(agent._capture_changelog()) + + assert [cmd[1].split("=")[0] for cmd, _ in runs] == ["--listed-incremental"] * 2 + assert all(env == {**a2a_server.os.environ, "AGENTENV_REAL_TIME": "1"} for _, env in runs), runs + + +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/letta_code/test_image_contract.py b/tst/unit/agents/letta_code/test_image_contract.py new file mode 100644 index 000000000..657a5157e --- /dev/null +++ b/tst/unit/agents/letta_code/test_image_contract.py @@ -0,0 +1,88 @@ +"""The agent's folder is its build context: every file the Dockerfile copies is in it, or in a folder its +``shared_sources.toml`` takes from agent-env's sources, and the image and an install both carry every module the A2A +server imports, the egress rule and the clock page's format among them, and the mod the bridge installs.""" + +from __future__ import annotations + +import ast +import re +import subprocess +import tomllib + +from tst.unit.agents.letta_code.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() + + +def _copied() -> list[str]: + return [name for line in re.findall(r"^COPY (?!--from=)(.+) \S+$", DOCKERFILE, re.MULTILINE) + for name in line.split()] + + +def _installed() -> set[str]: + return set(re.search(r'^AGENT_FILES="([^"]+)"$', INSTALL_SH, re.MULTILINE).group(1).split()) + + +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 _in_context(name: str) -> bool: + path = _source(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(_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", "letta_code_bridge.py", "letta_code_kit.py", "mcp_tools.ts", "entrypoint.sh", "install.sh", + "run.sh", "package.json", "package-lock.json", "requirements.txt"} <= set(copied) + + +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 test_the_image_and_an_install_carry_every_module_the_server_imports(): + 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 = set(), ["a2a_server"] + while pending: + if (name := modules[pending.pop()]) not in needed: + needed.add(name) + pending += _imported(_source(name)) & set(modules) + # Not imported: the bridge copies it into each context as the mod that registers the env's MCP tools. + needed.add("mcp_tools.ts") + + assert {"agent_clock/agent_egress.py", "clock/clockpage.py", "letta_code_bridge.py"} <= needed + assert needed <= set(_copied()) and needed <= _installed(), (needed, _installed()) + assert all(_in_context(name) for name in _installed()) + + +def test_an_install_puts_every_file_by_its_own_name_in_the_one_folder_run_sh_imports_from(): + """A file the build context takes from a shared folder, ``agent_clock/agent_egress.py`` say, lands beside the + server, as the image copies it, not in a folder of that name off the path.""" + start = INSTALL_SH.index("for file in $AGENT_FILES; do") + loop = INSTALL_SH[start:INSTALL_SH.index("\ndone\n", start) + len("\ndone")] + agent_files = re.search(r"^AGENT_FILES=.*$", INSTALL_SH, re.MULTILINE).group(0) + script = f'{agent_files}\nhere=/ctx root=/r\nput() {{ printf "%s %s\\n" "$1" "$2"; }}\n{loop}\n' + + placed = subprocess.run(["bash", "-c", script], check=True, capture_output=True, text=True).stdout.splitlines() + + assert sorted(placed) == sorted(f"/ctx/{name} /r/app/{name.rsplit('/', 1)[-1]}" for name in _installed()) + assert 'PYTHONPATH="$root/app"' in (AGENT_DIR / "run.sh").read_text() diff --git a/tst/unit/agents/letta_code/test_server_exit.py b/tst/unit/agents/letta_code/test_server_exit.py new file mode 100644 index 000000000..d4aeb6ecd --- /dev/null +++ b/tst/unit/agents/letta_code/test_server_exit.py @@ -0,0 +1,81 @@ +"""The A2A server is the container, as it was before the image ran supervisord: root.conf restarts the clock follower +and the egress proxy in place, never the server, and its event listener stops supervisord, so the container ends, once +the server exits or fails to start. A restarted server would have lost its MCP servers, peers and tasks while the dead +one's CLI went on in the workspace.""" + +from __future__ import annotations + +import configparser +import json +import shlex +import subprocess +import sys + +from tst.unit.agents.letta_code.agent import AGENT_DIR + +EVENTS = {"PROCESS_STATE_EXITED", "PROCESS_STATE_FATAL"} + + +def _conf() -> configparser.RawConfigParser: + """root.conf as supervisord reads it: a ';' or '#' after whitespace starts a comment.""" + conf = configparser.RawConfigParser(inline_comment_prefixes=(";", "#"), strict=False) + conf.read_string((AGENT_DIR / "root.conf").read_text()) + return conf + + +def _listener() -> configparser.SectionProxy: + listeners = [name for name in _conf().sections() if name.startswith("eventlistener:")] + assert len(listeners) == 1, listeners + return _conf()[listeners[0]] + + +def test_the_server_is_never_restarted_and_the_follower_and_the_proxy_are(): + conf = _conf() + + assert conf["program:agent"]["autorestart"] == "false" + assert conf["program:clock"]["autorestart"] == conf["program:egress"]["autorestart"] == "true" + + +def test_one_listener_hears_every_way_a_program_ends_on_its_own_as_root_which_may_stop_supervisord(): + """A stop, the container's or supervisorctl's, ends a program as STOPPED, which it doesn't hear.""" + listener = _listener() + + assert set(listener["events"].split(",")) == EVENTS + assert "user" not in listener + + +# Plays supervisord to the listener, as its parent, so the listener's signal comes here: each event as the eventlistener +# protocol sends it, then whether the listener sent SIGTERM before it answered. +SUPERVISORD = r""" +import json, signal, subprocess, sys +signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM}) +listener = subprocess.Popen(sys.argv[1:], stdin=subprocess.PIPE, stdout=subprocess.PIPE) +stopped = [] +for name, event, state in json.loads(sys.stdin.read()): + assert listener.stdout.readline() == b"READY\n" + payload = f"processname:{name} groupname:{name} {state}".encode() + header = f"ver:3.0 server:supervisor serial:1 pool:agent-exit poolserial:1 eventname:{event} len:{len(payload)}\n" + listener.stdin.write(header.encode() + payload) + listener.stdin.flush() + assert listener.stdout.read(11) == b"RESULT 2\nOK" + stopped.append(signal.SIGTERM in signal.sigpending()) + if stopped[-1]: + signal.sigwait({signal.SIGTERM}) +listener.kill() +print(json.dumps(stopped)) +""" + + +def test_the_listener_stops_supervisord_when_the_server_exits_or_fails_to_start_and_for_nothing_else(): + exited, fatal = "from_state:RUNNING expected:0 pid:7", "from_state:BACKOFF" + events = [("clock", "PROCESS_STATE_EXITED", exited), ("egress", "PROCESS_STATE_FATAL", fatal), + ("agent", "PROCESS_STATE_EXITED", exited), ("clock", "PROCESS_STATE_FATAL", fatal), + ("agent", "PROCESS_STATE_FATAL", fatal)] + # supervisord expands '%(name)s' in a command, so a bare '%' would break it. + command = shlex.split(_listener()["command"] % {}) + assert command[0] == "/usr/local/bin/python3" + + result = subprocess.run([sys.executable, "-c", SUPERVISORD, sys.executable, *command[1:]], + input=json.dumps(events), capture_output=True, text=True, timeout=60, check=True) + + assert json.loads(result.stdout) == [False, False, True, False, True]