diff --git a/src/agent_env/agents/agents/codex/Dockerfile b/src/agent_env/agents/agents/codex/Dockerfile index f477158a0..17bcd2d54 100644 --- a/src/agent_env/agents/agents/codex/Dockerfile +++ b/src/agent_env/agents/agents/codex/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 for the Codex CLI's launcher and mcp-remote, checked against its published checksum; install.sh brings the same. ARG NODE_VERSION=22.23.3 @@ -22,12 +36,37 @@ COPY requirements.txt model-requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt -r model-requirements.txt # install.sh and run.sh are install/v1's: in the image, so they stay in its build context. COPY a2a_server.py codex_bridge.py codex_config.py codex_kit.py entrypoint.sh install.sh run.sh ./ -# The CLI's cwd, /app, and its state, 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, fixed so neither follows the uid. RUN useradd --create-home --uid 10001 agent && mkdir -p /app /home/agent/.codex \ && chown agent:agent /app /home/agent/.codex && chmod 0755 entrypoint.sh +# The env's clock: the follower and the egress proxy, each as its own user, under root's supervisord (root.conf), and +# agent-env's libfaketime and its TLS shim preloaded into every dynamically linked process, faking only the agent's +# (clock.conf): the model's commands, not the Codex CLI, a static binary. 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 CODEX_HOME=/home/agent/.codex -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/codex/README.md b/src/agent_env/agents/agents/codex/README.md index c01142ad0..a1da1cb4c 100644 --- a/src/agent_env/agents/agents/codex/README.md +++ b/src/agent_env/agents/agents/codex/README.md @@ -39,8 +39,31 @@ Codex reads its settings from `$CODEX_HOME/config.toml`, which the agent writes: | `triggers/v1` | SDK default | The image is `python:3.11-slim` with Node, the CLIs, the agent and the Python packages `model-requirements.txt` pins for -the model's scripts, running as the `agent` user; Codex's state is in -`/home/agent/.codex` whatever the uid. +the model's scripts. It starts as root, runs the env clock's follower and egress proxy under supervisord (`start-agent`, +`root.conf`) and the A2A server as the `agent` user; started as another user, it runs the server alone. Either way the +server's exit ends the container: supervisord never starts it again, and its `agent-exit` listener shuts supervisord +down, while the follower and the proxy restart in place. Codex's state is in `/home/agent/.codex` whatever the uid. + +A task's `sync_env_clock` with `agent_clock` has the agent follow the env's clock (`clock/v1` `sync_time`). agent-env's +libfaketime, preloaded for the `agent` user, then gives the model's commands the env's time. The Codex CLI is a static +binary the library doesn't reach, so the CLI and what it keeps (rollouts, `state.db`, thread ids) stay on real time, +and it checks the model endpoint's certificate on real time and reaches it directly. On an armed clock each CLI run +also gets: + +- each MCP server's `mcp-remote` started by Node itself (`-c mcp_servers..command` and `.args`) with + `AGENTENV_REAL_TIME=1` in its environment, so it stays on real time: the expiry of its cookies and tokens and the age + of its leases are server times or real file times. Its `#!/usr/bin/env node` would start `env` first, which takes the + marker out of what it hands Node. On real time it checks certificates against the real date, so it reaches the + servers directly. +- `-c shell_environment_policy.set.=...` with the egress proxy's variables (`agent_egress.egress_env`), so the + model's commands, which check certificates on the env's date, go out through the proxy, all but loopback, the hosts + `NO_PROXY` names and the model endpoint's and MCP servers' hosts served over plain HTTP alone. +- the env's date and zone before the prompt (``), as `date` shows it: Codex puts the host's real + date in its ``, and the note says so, and that a clock tool and `Date` in JavaScript the model + runs in code mode read real time too. + +Unarmed, a CLI run is as before. So is one of an agent installed with `install/v1`, which runs as root, whose +commands libfaketime doesn't fake, whatever the clock of a computer it's installed in. A `deploy_agent` `builtin_tools` selection turns the CLI's own tools off with `-c` overrides on the task's CLI alone; config.toml stays as it is. `{"disable": "*"}` turns off every setting below, `{"only": [...]}` every one but those whose diff --git a/src/agent_env/agents/agents/codex/a2a_server.py b/src/agent_env/agents/agents/codex/a2a_server.py index c8bea369f..b19e945be 100644 --- a/src/agent_env/agents/agents/codex/a2a_server.py +++ b/src/agent_env/agents/agents/codex/a2a_server.py @@ -724,6 +724,7 @@ def _record_event(event: dict) -> None: task_id=cfg.task_id, event_callback=_record_event, max_turns=cfg.max_turns, + mcp_servers=request.mcp_servers, config_overrides=[*codex_config.role_overrides(request.mcp_servers, cfg.role), *codex_config.builtin_tools_overrides(cfg.builtin_tools), *catalog], diff --git a/src/agent_env/agents/agents/codex/codex_bridge.py b/src/agent_env/agents/agents/codex/codex_bridge.py index 51ca3fb0a..87cad4ba4 100644 --- a/src/agent_env/agents/agents/codex/codex_bridge.py +++ b/src/agent_env/agents/agents/codex/codex_bridge.py @@ -13,6 +13,7 @@ import logging import os import re +import shutil import signal import threading import time @@ -21,11 +22,15 @@ from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path +from typing import Any -from codex_config import MODEL_HEADERS_ENV, model_headers +from agent_egress import EGRESS_PROXY_ENV, clock_armed, egress_env +from codex_config import MODEL_HEADERS_ENV, model_headers, server_args logger = logging.getLogger(__name__) WORKSPACE_DIR = os.environ.get("CODEX_WORKSPACE_DIR", "/app") +# The one switch agent-env's libfaketime takes from a program's environment: that program stays on real time. +REAL_TIME_ENV = "AGENTENV_REAL_TIME" # `todo_list` is excluded: it's a plan update, not a tool invocation. _TOOL_ITEM_TYPES = {"command_execution", "mcp_tool_call", "file_change", "web_search"} @@ -113,6 +118,48 @@ def cli_env(environ: Mapping[str, str], *, project_id: str | None = None, return env +def clock_followed() -> bool: + """Whether the model's commands follow an armed clock: only where the image's root.conf starts this server, as the + user agent-env's libfaketime fakes, with the egress proxy in its environment. An agent installed with install/v1 + runs as root, whose commands stay on real time beside a computer's armed clock.""" + return bool(os.environ.get(EGRESS_PROXY_ENV)) and clock_armed() + + +def _real_time_mcp_remote(name: str, info: Mapping[str, Any]) -> list[str]: + """One MCP server's mcp-remote started by Node itself with the real-time marker: its `#!/usr/bin/env node` would + start env first, which libfaketime loads into, keeps on real time and takes the marker out of what it hands Node.""" + node, script = shutil.which("node"), os.path.realpath(shutil.which("mcp-remote")) + return [f"mcp_servers.{name}.command={json.dumps(node)}", + f"mcp_servers.{name}.args={json.dumps([script, *server_args(info['url'], info.get('headers'))])}", + f'mcp_servers.{name}.env.{REAL_TIME_ENV}="1"'] + + +def clock_overrides(environ: Mapping[str, str], mcp_servers: Mapping[str, Mapping[str, Any]], *, + armed: bool) -> list[str]: + """The `-c` overrides an armed clock adds to a CLI run. The CLI, a static binary libfaketime can't reach, and + mcp-remote, whose cookie and token expiry and leases are server or real file times, stay on real time and go out + directly; the model's commands follow the env's clock, so they get the egress proxy (``egress_env``).""" + if not armed: + return [] + urls = [environ.get("LITELLM_BASE_URL", ""), *(info["url"] for info in mcp_servers.values())] + return [*(override for name, info in mcp_servers.items() for override in _real_time_mcp_remote(name, info)), + *(f"shell_environment_policy.set.{name}={json.dumps(value)}" + for name, value in egress_env(environ, urls, armed=True).items())] + + +async def clock_note() -> str: + """The env's date, put before a turn's prompt on an armed clock: the CLI renders the host's real date into its own + context, so the model is told the date `date` shows, which, run by this real-time server, follows the env's + clock.""" + proc = await asyncio.create_subprocess_exec("date", "+%Y-%m-%d (%A)", stdout=asyncio.subprocess.PIPE) + shown, _ = await proc.communicate() + zone = os.environ.get("TZ") or "UTC" + return (f"\nToday is {shown.decode().strip()} in {zone} on this task's clock, which `date` and " + "every command you run read. What the Codex CLI itself reports of the time, such as the current_date in " + ", a clock tool or Date in JavaScript you run in code mode, is the host's real time; " + "go by this task's clock.\n\n\n") + + @dataclass class CodexResult: response: str @@ -780,7 +827,11 @@ async def _run_codex_once( config_overrides: Sequence[str] = (), max_turns: int | None = None, prior_tool_calls: int = 0, + mcp_servers: Mapping[str, Mapping[str, Any]] | None = None, ) -> CodexResult: + armed = clock_followed() + if armed: + prompt = await clock_note() + prompt # JSON Schema: codex's `--output-schema` flag takes a FILE PATH (unlike # claude-code's inline-JSON `--json-schema`). Write the inner schema to a # per-invocation temp file. Canonical agent-env envelope is @@ -819,7 +870,7 @@ async def _run_codex_once( ] if schema_file is not None: cmd += ["--output-schema", str(schema_file)] - for override in config_overrides: + for override in [*config_overrides, *clock_overrides(os.environ, mcp_servers or {}, armed=armed)]: cmd += ["-c", override] inactivity_s = inactivity_timeout_s(effort) @@ -961,6 +1012,7 @@ async def run_codex( event_callback: Callable[[dict], None] | None = None, config_overrides: Sequence[str] = (), max_turns: int | None = None, + mcp_servers: Mapping[str, Mapping[str, Any]] | None = None, ) -> CodexResult: """Run one logical turn with bounded transient recovery. @@ -1002,6 +1054,7 @@ async def run_codex( event_callback=event_callback, config_overrides=config_overrides, max_turns=max_turns, + mcp_servers=mcp_servers, prior_tool_calls=tool_call_count, ) failure = _resumable_api_failure(result) diff --git a/src/agent_env/agents/agents/codex/codex_config.py b/src/agent_env/agents/agents/codex/codex_config.py index 3ba4467c7..d58021107 100644 --- a/src/agent_env/agents/agents/codex/codex_config.py +++ b/src/agent_env/agents/agents/codex/codex_config.py @@ -258,16 +258,12 @@ def _server_entry(url: str, headers: dict[str, str] | None = None) -> dict[str, concurrent turns of different roles share it. """ registered = "" - args: list[str] = [url, "--allow-http"] for k, v in (headers or {}).items(): if k.lower() == ROLE_HEADER.lower(): registered = v - else: - args += ["--header", f"{k}: {v}"] - args += ["--header", f"{ROLE_HEADER}: ${{{_ROLE_VARIABLE}}}"] return { "command": "mcp-remote", - "args": args, + "args": server_args(url, headers), "env": {_ROLE_VARIABLE: registered}, "env_vars": list(_TRUST_ENV), "startup_timeout_sec": 60, @@ -278,6 +274,15 @@ def _server_entry(url: str, headers: dict[str, str] | None = None) -> dict[str, } +def server_args(url: str, headers: Mapping[str, str] | None = None) -> list[str]: + """mcp-remote's arguments for one server, as its config table gives them.""" + args = [url, "--allow-http"] + for k, v in (headers or {}).items(): + if k.lower() != ROLE_HEADER.lower(): + args += ["--header", f"{k}: {v}"] + return [*args, "--header", f"{ROLE_HEADER}: ${{{_ROLE_VARIABLE}}}"] + + async def write_mcp_servers(servers: Mapping[str, Mapping[str, Any]]) -> None: """Write every registered MCP server's entry, before each turn.""" async with _write_lock: diff --git a/src/agent_env/agents/agents/codex/install.sh b/src/agent_env/agents/agents/codex/install.sh index 57fb9d255..c7b2c6deb 100755 --- a/src/agent_env/agents/agents/codex/install.sh +++ b/src/agent_env/agents/agents/codex/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="a2a_server.py codex_bridge.py codex_config.py codex_kit.py requirements.txt run.sh" +AGENT_FILES="a2a_server.py codex_bridge.py codex_config.py codex_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. @@ -144,7 +144,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/codex $r/bin/mcp-remote $r/app/run.sh" diff --git a/src/agent_env/agents/agents/codex/root.conf b/src/agent_env/agents/agents/codex/root.conf new file mode 100644 index 000000000..27bbb8aec --- /dev/null +++ b/src/agent_env/agents/agents/codex/root.conf @@ -0,0 +1,79 @@ +; 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 the model's commands, which it starts +; through the CLI, read the env's time; the Codex CLI itself is a static binary the library doesn't reach, so it stays +; on real time. Its socket and logs are root's alone, so the agent's user can neither stop nor restart any of them. The +; follower follows nothing until the server writes its config, which sync_env_clock has it do, then picks it up within +; a quarter second. +[supervisord] +nodaemon=true +user=root +logfile=/var/log/agentenv-root/supervisord.log +pidfile=/run/agentenv-root/supervisord.pid +childlogdir=/var/log/agentenv-root + +[unix_http_server] +file=/run/agentenv-root/supervisor.sock +chmod=0700 + +[rpcinterface:supervisor] +supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface + +[supervisorctl] +serverurl=unix:///run/agentenv-root/supervisor.sock + +[program:clock] +command=/usr/local/bin/python3 -I /usr/local/lib/agentenv-clock/clock-follower +user=agentenv-clock +directory=/ +priority=3 +autorestart=true +startsecs=1 +startretries=1000 +redirect_stderr=true +stdout_logfile=/var/log/agentenv-root/clock.log +environment=HOME="/nonexistent",USER="agentenv-clock",LOGNAME="agentenv-clock" + +[program:egress] +command=/usr/local/lib/agentenv-egress/egress serve +user=agentenv-egress +directory=/ +priority=3 +autorestart=true +startsecs=1 +startretries=1000 +redirect_stderr=true +stdout_logfile=/var/log/agentenv-root/egress.log +environment=HOME="/nonexistent",USER="agentenv-egress",LOGNAME="agentenv-egress",AGENTENV_EGRESS_PRIVATE="allow" + +; uvicorn itself, not entrypoint.sh: the marker holds for the process it's given to alone, and a shell that execs +; uvicorn would hand uvicorn an environment without it. It is never started again (agent-exit below). +[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 +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" + +; The A2A server's exit, for any reason, ends the container, as it did when the server was the image's only process: a +; server started again would have lost the task's MCP servers, peers and running tasks, and the CLIs the dead one +; started would go on in the workspace beside it. This listener has root's supervisord, its parent, shut down when the +; server exits or can't start; the follower and the proxy restart in place. +[eventlistener:agent-exit] +command=/usr/local/bin/python3 -I -c "import os, signal, sys + fields = lambda line: dict(field.split(b':', 1) for field in line.split()) + stdin, stdout = sys.stdin.buffer, sys.stdout.buffer + while True: stdout.write(b'READY\n'); stdout.flush(); header = fields(stdin.readline()); event = fields(stdin.read(int(header[b'len']))); event[b'processname'] == b'agent' and os.kill(os.getppid(), signal.SIGTERM); stdout.write(b'RESULT 2\nOK'); stdout.flush()" +events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL +directory=/ +autorestart=true +stdout_logfile=NONE +stderr_logfile=/var/log/agentenv-root/agent-exit.log diff --git a/src/agent_env/agents/agents/codex/shared_sources.toml b/src/agent_env/agents/agents/codex/shared_sources.toml new file mode 100644 index 000000000..6076f3540 --- /dev/null +++ b/src/agent_env/agents/agents/codex/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/codex/start-agent b/src/agent_env/agents/agents/codex/start-agent new file mode 100755 index 000000000..88deed2c5 --- /dev/null +++ b/src/agent_env/agents/agents/codex/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 model's commands 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..4f9cb21f2 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, its CLI included unless it's a static binary as Codex's is, 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 a 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.""" @@ -10,12 +11,14 @@ import asyncio import json import re +import shlex import subprocess import time import uuid 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 @@ -40,6 +43,7 @@ from tst.integration.task_step.test_register_env_triggers_local import _deploy_items from tst.util.capabilities import agent_clock_image, skip_without_agent_clock_image from tst.util.fake_anthropic import FakeAnthropic, tool_then_answer +from tst.util.fake_responses import FakeResponses, shell_then_answer pytestmark = [pytest.mark.integration, pytest.mark.int_test_slow] @@ -75,20 +79,62 @@ async def _claude_turn(context: TaskStepContext, endpoint: FakeAnthropic) -> Non assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results() +# For each mcp-remote the CLI runs, whether Node was started with the real-time marker: libfaketime changed the marker +# in its environment block to AGENTENV_REAL_TIME=0, which the block keeps. A `#!/usr/bin/env node` start hands Node a +# block without it. +_MCP_REMOTE_MARKED = """ +import pathlib +marked = [] +for proc in pathlib.Path("/proc").glob("[0-9]*"): + try: + argv = (proc / "cmdline").read_bytes().split(b"\\0") + if any(arg.endswith((b"mcp-remote/dist/proxy.js", b"bin/mcp-remote")) for arg in argv[:2]): + marked.append(b"AGENTENV_REAL_TIME=0" in (proc / "environ").read_bytes().split(b"\\0")) + except OSError: + pass +print("mcp-remote on real time:", marked) +""" + + +async def _codex_turn(context: TaskStepContext, endpoint: FakeResponses) -> None: + """One turn of the real Codex CLI, which stays on real time: the date the agent tells the model before the prompt + and a shell `date` the model runs are the env's, while the CLI's own date is the host's, and + every mcp-remote it starts is on real time. The model is one the CLI's catalog doesn't know, so it gets the + shell tool directly rather than in code mode.""" + endpoint.respond = shell_then_answer(f"date -u +%FT%TZ; python3 -c {shlex.quote(_MCP_REMOTE_MARKED)}", + prefix="the shell said: ") + await PromptAgentTaskStep(id="ask", version=None, prompt="What's the date? Run date.", agent_name="solver", + model="stand-in", max_conversation_turns=1).execute(context) + bodies = [json.dumps(seen.body) for seen in endpoint.requests()] + told = {m for body in bodies for m in re.findall(r"Today is ([0-9]{4}-[0-9]{2}-[0-9]{2})", body)} + hosts = {m for body in bodies for m in re.findall(r"([0-9-]+)", body)} + print("the agent's date line:", told, "the CLI's own:", hosts, "shell date:", endpoint.tool_results()) + assert told == {VIRTUAL[:10]}, told + assert hosts and VIRTUAL[:10] not in hosts, hosts + assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results() + marked = [re.search(r"mcp-remote on real time: (\[.*\])", result) for result in endpoint.tool_results()] + # One mcp-remote per server the CLI is given: the env's and the agent's own peer_agents server. + [found] = [m.group(1) for m in marked if m] + assert "True" in found and "False" not in found, 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 a stub endpoint of the protocol its CLI speaks.""" bridge: str version: tuple[str, ...] shows: str - turn: Callable[[TaskStepContext, FakeAnthropic], Awaitable[None]] | None = None + turn: Callable[[TaskStepContext, Any], Awaitable[None]] | None = None + endpoint: type = FakeAnthropic AGENTS = { "claude-code": Agent(bridge="claude_bridge", version=("claude", "--version"), shows="(Claude Code)", turn=_claude_turn), + "codex": Agent(bridge="codex_bridge", version=("codex", "--version"), shows="codex-cli", turn=_codex_turn, + endpoint=FakeResponses), "opencode": Agent(bridge="opencode_bridge", version=("opencode", "--version"), shows="1.17.18"), } @@ -120,11 +166,11 @@ 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 + with AGENTS[name].endpoint(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) -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/codex/agent.py b/tst/unit/agents/codex/agent.py index af4353fdb..7d718ab2f 100644 --- a/tst/unit/agents/codex/agent.py +++ b/tst/unit/agents/codex/agent.py @@ -1,18 +1,24 @@ -"""The Codex agent's modules, imported from its folder as its image runs them: by their own names, from the folder on -the path.""" +"""The Codex 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" / "codex" -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 codex_bridge = importlib.import_module("codex_bridge") codex_config = importlib.import_module("codex_config") codex_kit = importlib.import_module("codex_kit") +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("codex_a2a_server", AGENT_DIR / "a2a_server.py") a2a_server = importlib.util.module_from_spec(_spec) diff --git a/tst/unit/agents/codex/test_env_clock.py b/tst/unit/agents/codex/test_env_clock.py new file mode 100644 index 000000000..704e5d192 --- /dev/null +++ b/tst/unit/agents/codex/test_env_clock.py @@ -0,0 +1,260 @@ +"""Codex on the env's clock. The CLI is a static binary agent-env's libfaketime doesn't reach, so it stays on real time, +checks its own certificates on it and goes out directly, its environment as it was. On an armed clock each CLI run +keeps mcp-remote on real time too, started by Node itself with the real-time marker, gives the model's commands, which +follow the env's clock, the egress proxy's variables from the shared rule (tst/unit/agents/test_agent_egress.py), and +tells the model the env's date, which the CLI's own context gives as the host's. Unarmed, or where the image doesn't +start the server as the user libfaketime fakes, a run is what it was before the image followed a 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 os +import shutil +import subprocess +import tomllib +from pathlib import Path + +import pytest + +from tst.unit.agents.codex.agent import AGENT_DIR, agent_egress, codex_bridge, codex_config + +PROXY = "http://127.0.0.1:3128" +PROXY_NAMES = {name for base in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY") + for name in (base, base.lower())} | {"NODE_USE_ENV_PROXY"} +MODEL = "https://litellm.example.com" +SERVERS = {"env": {"url": "https://abc-123.w.modal.host/mcp", + "headers": {"Authorization": "Bearer t", "AgentEnv-Role": "user"}}, + "local": {"url": "http://gateway:8080/mcp", "headers": None}} +URLS = [info["url"] for info in SERVERS.values()] + + +def _overrides(cmd: list[str]) -> list[str]: + return [cmd[i + 1] for i, arg in enumerate(cmd) if arg == "-c"] + + +def _config(overrides: list[str]) -> dict: + """The overrides as the CLI lays them over config.toml: each a TOML key and value.""" + return tomllib.loads("\n".join(overrides)) + + +@pytest.fixture +def image_path(tmp_path, monkeypatch) -> Path: + """Node and mcp-remote on PATH as the image has them: mcp-remote a link, through npm's .bin, to its script, which + starts `#!/usr/bin/env node`. The script, resolved.""" + root = tmp_path / "image" + dist, npm_bin, path = root / "node_modules/mcp-remote/dist", root / "node_modules/.bin", root / "bin" + for folder in (dist, npm_bin, path): + folder.mkdir(parents=True) + script, node = dist / "proxy.js", path / "node" + script.write_text("#!/usr/bin/env node\n") + node.write_bytes(b"\x7fELF") + for program in (script, node): + program.chmod(0o755) + (npm_bin / "mcp-remote").symlink_to("../mcp-remote/dist/proxy.js") + (path / "mcp-remote").symlink_to(npm_bin / "mcp-remote") + monkeypatch.setenv("PATH", str(path)) + return script.resolve() + + +def _starts_on_real_time(server: dict, script: Path, info: dict) -> None: + """An MCP server the CLI starts as the program that reads the marker, Node, not through a `#!` line, whose + interpreter would take the marker out of what it hands Node; with mcp-remote's script and config.toml's + arguments.""" + first = Path(shutil.which(server["command"])).read_bytes() + assert not first.startswith(b"#!"), server["command"] + assert server["args"] == [str(script), *codex_config._server_entry(info["url"], info["headers"])["args"]] + assert server["env"] == {codex_bridge.REAL_TIME_ENV: "1"} + + +def test_on_an_armed_clock_the_models_commands_go_out_through_the_proxy(image_path): + environ = {agent_egress.EGRESS_PROXY_ENV: PROXY, "LITELLM_BASE_URL": MODEL, "NO_PROXY": "registry.internal"} + + shell = _config(codex_bridge.clock_overrides(environ, SERVERS, armed=True))["shell_environment_policy"]["set"] + + assert shell == agent_egress.egress_env(environ, [MODEL, *URLS], armed=True) + assert {shell[name] for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "https_proxy")} == {PROXY} + direct = set(shell["NO_PROXY"].split(",")) + assert {"localhost", "127.0.0.1", "host.docker.internal", "registry.internal", "gateway"} <= direct + assert not {"abc-123.w.modal.host", "litellm.example.com"} & direct + + +def test_on_an_armed_clock_each_mcp_server_is_started_by_node_itself_with_the_real_time_marker(image_path): + environ = {agent_egress.EGRESS_PROXY_ENV: PROXY, "LITELLM_BASE_URL": MODEL} + + servers = _config(codex_bridge.clock_overrides(environ, SERVERS, armed=True))["mcp_servers"] + + assert servers.keys() == SERVERS.keys() + for name, info in SERVERS.items(): + _starts_on_real_time(servers[name], image_path, info) + + +def test_unarmed_a_cli_run_takes_no_override(): + assert codex_bridge.clock_overrides({agent_egress.EGRESS_PROXY_ENV: PROXY}, SERVERS, armed=False) == [] + + +class _Stream: + def __init__(self, data: bytes = b""): + self.data = data + + async def read(self, n: int = -1) -> bytes: + chunk, self.data = (self.data, b"") if n < 0 else (self.data[:n], self.data[n:]) + return chunk + + +class _Stdin: + def __init__(self): + self.data = b"" + + def write(self, data: bytes): + self.data += data + + async def drain(self): + return None + + def close(self): + return None + + +class _CLI: + """A CLI run that answers and completes its turn.""" + + returncode = 0 + + def __init__(self): + events = [{"type": "turn.started"}, {"type": "item.completed", "item": {"type": "agent_message", "text": "ok"}}, + {"type": "turn.completed"}] + self.stdin, self.stderr = _Stdin(), _Stream() + self.stdout = _Stream(b"".join(json.dumps(event).encode() + b"\n" for event in events)) + + async def wait(self): + return 0 + + +class _Date: + async def communicate(self): + return b"2031-03-04 (Tuesday)\n", None + + +@pytest.fixture +def spawned(monkeypatch): + """Every process the bridge starts: `date`, answered with the env's date, and the CLI.""" + runs: list[dict] = [] + + async def fake_exec(*cmd, **kwargs): + proc = _Date() if cmd[0] == "date" else _CLI() + runs.append({"cmd": list(cmd), "kwargs": kwargs, "proc": proc}) + return proc + + monkeypatch.setattr(codex_bridge.asyncio, "create_subprocess_exec", fake_exec) + for name in PROXY_NAMES: + monkeypatch.delenv(name, raising=False) + for name, value in {agent_egress.EGRESS_PROXY_ENV: PROXY, "LITELLM_BASE_URL": MODEL, "LITELLM_API_KEY": "k", + "TZ": "America/Chicago"}.items(): + monkeypatch.setenv(name, value) + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + monkeypatch.delenv(codex_bridge.MODEL_HEADERS_ENV, raising=False) + return runs + + +def _turn() -> None: + asyncio.run(codex_bridge.run_codex(prompt="hi", thread_id=None, model="gpt-x", project_id="p-1", task_id="t-1", + mcp_servers=SERVERS, config_overrides=["features.goals=false"])) + + +def _main_cmd() -> list[str]: + """The CLI's command line as it was before the image followed a clock.""" + return ["codex", "exec", "--cd", codex_bridge.WORKSPACE_DIR, "-", "--json", + "--dangerously-bypass-approvals-and-sandbox", "-c", 'model="gpt-x"', "-c", "features.goals=false"] + + +def _main_env() -> dict[str, str]: + """The CLI's environment as it was before the image followed a clock.""" + return {**os.environ, "OPENAI_API_KEY": "k", "LITELLM_CUSTOMER_ID": "p-1", + "LITELLM_TAGS": "projectId:p-1,taskId:t-1"} + + +def test_unarmed_the_cli_runs_as_it_did_before_the_image_followed_a_clock(spawned, monkeypatch): + monkeypatch.setattr(codex_bridge, "clock_armed", lambda: False) + + _turn() + + [cli] = spawned + assert cli["cmd"] == _main_cmd() + assert cli["kwargs"]["env"] == _main_env() + assert cli["proc"].stdin.data == b"hi" + + +def test_an_armed_page_beside_a_server_the_image_doesnt_start_leaves_the_cli_run_as_before(spawned, monkeypatch): + """An agent installed with install/v1 runs as root in a computer's container, whose commands libfaketime doesn't + fake: the computer's armed page tells nothing of their time.""" + monkeypatch.setattr(codex_bridge, "clock_armed", lambda: True) + monkeypatch.delenv(agent_egress.EGRESS_PROXY_ENV) + + _turn() + + [cli] = spawned + assert cli["cmd"] == _main_cmd() + assert cli["proc"].stdin.data == b"hi" + + +def test_on_an_armed_clock_the_cli_keeps_its_environment_its_children_get_the_clocks_routes_and_the_model_its_date( + spawned, image_path, monkeypatch): + monkeypatch.setattr(codex_bridge, "clock_armed", lambda: True) + + _turn() + + date, cli = spawned + assert date["cmd"] == ["date", "+%Y-%m-%d (%A)"] + overrides = _overrides(cli["cmd"]) + assert overrides[:2] == ['model="gpt-x"', "features.goals=false"] + config = _config(overrides[2:]) + for name, info in SERVERS.items(): + _starts_on_real_time(config["mcp_servers"][name], image_path, info) + assert config["shell_environment_policy"]["set"]["HTTPS_PROXY"] == PROXY + assert cli["kwargs"]["env"] == _main_env() and not PROXY_NAMES & set(cli["kwargs"]["env"]) + prompt = cli["proc"].stdin.data.decode() + assert prompt.startswith("\nToday is 2031-03-04 (Tuesday) in America/Chicago on this task's " + "clock, which `date` and every command you run read.") + assert "current_date in " in prompt and prompt.endswith("\n\nhi") + + +def test_a_task_on_an_armed_clock_reaches_the_cli_with_its_mcp_servers_on_real_time(codex, spawned, image_path, + monkeypatch): + monkeypatch.setattr(codex_bridge, "clock_armed", lambda: True) + + async def exercise(): + async with codex.app.router.lifespan_context(codex.app), codex.client() as client: + for name, info in SERVERS.items(): + await client.post("/ext/mcp-config", json={"name": name, **{k: v for k, v in info.items() if v}}) + await codex.send(client, "hi") + + asyncio.run(exercise()) + + config = _config(_overrides(spawned[-1]["cmd"])) + for name, info in SERVERS.items(): + _starts_on_real_time(config["mcp_servers"][name], image_path, info) + direct = config["shell_environment_policy"]["set"]["NO_PROXY"].split(",") + assert "gateway" in direct and "abc-123.w.modal.host" not in direct + + +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/codex/test_image_contract.py b/tst/unit/agents/codex/test_image_contract.py index eb5be7407..092bfef2e 100644 --- a/tst/unit/agents/codex/test_image_contract.py +++ b/tst/unit/agents/codex/test_image_contract.py @@ -7,10 +7,13 @@ import ast import json import re +import tomllib from tst.unit.agents.codex.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() @@ -23,10 +26,22 @@ def _copied() -> list[str]: for name in line.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((AGENT_DIR / name).is_file() for name in copied), copied + assert copied and all(_in_context(name) for name in copied), copied # install.sh and run.sh are install/v1's; a build context pruned to what the Dockerfile reads keeps them so. assert {"a2a_server.py", "codex_bridge.py", "codex_config.py", "codex_kit.py", "entrypoint.sh", "install.sh", "run.sh", "package.json", "package-lock.json"} <= set(copied) @@ -43,10 +58,19 @@ def _imported(path) -> set[str]: def test_the_image_and_an_install_carry_every_module_the_server_imports(): - modules = {path.stem: path for path in AGENT_DIR.glob("*.py")} - needed = {"a2a_server.py"} | {f"{name}.py" for path in modules.values() for name in _imported(path) & set(modules)} + """The folder's own modules and those the build context takes from agent-env's sources, the egress rule and the + clock page's format among them, each by its name in the context.""" + 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) installed = set(re.search(r'^AGENT_FILES="([^"]+)"$', INSTALL_SH, re.MULTILINE).group(1).split()) + assert {"agent_clock/agent_egress.py", "clock/clockpage.py"} <= needed assert needed <= set(_copied()) and needed <= installed, (needed, installed) @@ -98,5 +122,5 @@ def test_tls_checks_stay_on(): def test_the_image_starts_through_cmd_which_modal_passes_its_env_to(): - assert 'CMD ["/opt/agent/entrypoint.sh"]' in DOCKERFILE + assert 'CMD ["/usr/local/bin/start-agent"]' in DOCKERFILE assert not re.search(r"^ENTRYPOINT", DOCKERFILE, re.MULTILINE) diff --git a/tst/unit/agents/codex/test_message_contract.py b/tst/unit/agents/codex/test_message_contract.py index cbdeda03f..7c5e0ca14 100644 --- a/tst/unit/agents/codex/test_message_contract.py +++ b/tst/unit/agents/codex/test_message_contract.py @@ -134,7 +134,7 @@ async def exercise(): assert call == { "prompt": "line one", "thread_id": None, "model": "gpt-x", "effort": "high", "system_prompt": "be brief", "output_format": schema, "timeout_s": 42, "max_turns": 45, - "project_id": "p-1", "task_id": "t-1", "config_overrides": [], + "project_id": "p-1", "task_id": "t-1", "config_overrides": [], "mcp_servers": {}, } diff --git a/tst/unit/agents/codex/test_server_exit.py b/tst/unit/agents/codex/test_server_exit.py new file mode 100644 index 000000000..06535dd85 --- /dev/null +++ b/tst/unit/agents/codex/test_server_exit.py @@ -0,0 +1,78 @@ +"""The A2A server's exit ends the image's container, as it did when the server was the image's only process: root's +supervisord never starts it again, and its agent-exit listener has supervisord shut down when it exits or can't start, +while the clock follower and the egress proxy keep restarting in place. root.conf is read as supervisord reads it, and +the listener is run as written there, under a stand-in supervisord that speaks its protocol.""" + +from __future__ import annotations + +import configparser +import json +import shlex +import subprocess +import sys + +import pytest + +from tst.unit.agents.codex.agent import AGENT_DIR + +CONF = configparser.RawConfigParser(inline_comment_prefixes=(";", "#"), strict=False) +CONF.read_string((AGENT_DIR / "root.conf").read_text()) +LISTENER = "eventlistener:agent-exit" + +# Sends the listener each event as supervisord does, waiting for its READY and its RESULT, and after each says whether +# the listener had sent this process, its parent, a SIGTERM; blocked, so it stays pending to be seen. +SUPERVISORD = """ +import json, signal, subprocess, sys +signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM}) +listener = subprocess.Popen(json.loads(sys.argv[2]), stdin=subprocess.PIPE, stdout=subprocess.PIPE) +terminated = [] +for serial, (name, payload) in enumerate(json.loads(sys.argv[1]), 1): + assert listener.stdout.readline() == b"READY\\n" + header = f"ver:3.0 server:supervisor serial:{serial} pool:agent-exit poolserial:{serial} eventname:{name} len:{len(payload)}\\n" + listener.stdin.write(header.encode() + payload.encode()) + listener.stdin.flush() + assert listener.stdout.readline() == b"RESULT 2\\n" and listener.stdout.read(2) == b"OK" + terminated.append(signal.SIGTERM in signal.sigpending()) +listener.kill() +print(json.dumps(terminated)) +""" + + +def _exited(name: str) -> tuple[str, str]: + return "PROCESS_STATE_EXITED", f"processname:{name} groupname:{name} from_state:RUNNING expected:0 pid:4242" + + +def _fatal(name: str) -> tuple[str, str]: + return "PROCESS_STATE_FATAL", f"processname:{name} groupname:{name} from_state:BACKOFF" + + +def _terminated(events: list[tuple[str, str]]) -> list[bool]: + _, *args = shlex.split(CONF.get(LISTENER, "command")) + done = subprocess.run([sys.executable, "-c", SUPERVISORD, json.dumps(events), json.dumps([sys.executable, *args])], + capture_output=True, timeout=30, check=True) + return json.loads(done.stdout) + + +def test_the_server_is_never_started_again(): + assert CONF.get("program:agent", "autorestart") == "false" + assert CONF.get("program:agent", "startretries") == "0" + + +def test_the_follower_and_the_proxy_restart_in_place(): + assert CONF.get("program:clock", "autorestart") == CONF.get("program:egress", "autorestart") == "true" + + +def test_the_listener_hears_the_servers_exit_and_failed_start_as_root(): + assert set(CONF.get(LISTENER, "events").split(",")) == {"PROCESS_STATE_EXITED", "PROCESS_STATE_FATAL"} + # supervisord runs as root: a listener as another user couldn't signal it. + assert not CONF.has_option(LISTENER, "user") + + +@pytest.mark.parametrize("event", [_exited, _fatal]) +def test_the_servers_exit_shuts_supervisord_down(event): + assert _terminated([event("agent")]) == [True] + + +def test_the_followers_or_the_proxys_exit_leaves_it_running(): + assert _terminated([_exited("clock"), _fatal("egress"), _exited("agent-exit"), _exited("agent")]) == [ + False, False, False, True] diff --git a/tst/util/fake_responses.py b/tst/util/fake_responses.py new file mode 100644 index 000000000..086ac44af --- /dev/null +++ b/tst/util/fake_responses.py @@ -0,0 +1,139 @@ +"""A fake OpenAI Responses API endpoint, so the real Codex CLI runs with no model key: ``POST /responses`` is +answered by a responder, streamed as the Responses API's server-sent events, and every request is recorded. The CLI +reaches it with LITELLM_BASE_URL set to ``url``, as the Codex agent writes its provider (``/openai/v1``).""" + +from __future__ import annotations + +import json +import threading +import uuid +from collections import deque +from collections.abc import Callable +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from tst.util.fake_anthropic import Seen, Text, answer + +SHELL_TOOLS = ("exec_command", "shell_command", "shell") + + +@dataclass(frozen=True) +class Call: + name: str + arguments: dict + + +Responder = Callable[[dict], Text | Call] + + +def _tool_output(body: dict) -> str | None: + """The output of the tool call the request's last input item answers, or None.""" + items = body.get("input") or [] + last = items[-1] if items and isinstance(items[-1], dict) else {} + if last.get("type") not in ("function_call_output", "custom_tool_call_output"): + return None + output = last.get("output") + if isinstance(output, list): + return "".join(part.get("text", "") for part in output if isinstance(part, dict)) + return str(output) + + +def shell_then_answer(command: str, *, prefix: str = "") -> Responder: + """Run ``command`` with the shell tool the request offers, then answer with ``prefix`` and its output; answer + ``prefix`` alone to a request that offers none, as for a model whose catalog entry runs code mode.""" + + def respond(body: dict) -> Text | Call: + output = _tool_output(body) + if output is not None: + return Text(f"{prefix}{output}") + names = {tool.get("name") for tool in body.get("tools") or [] if isinstance(tool, dict)} + tool = next((name for name in SHELL_TOOLS if name in names), None) + if tool is None: + return Text(prefix or "no shell tool") + arguments = ({"cmd": command} if tool == "exec_command" else {"command": command} if tool == "shell_command" + else {"command": ["bash", "-lc", command]}) + return Call(tool, arguments) + + return respond + + +@dataclass +class FakeResponses: + host: str + respond: Responder = field(default_factory=lambda: answer("pong")) + seen: deque[Seen] = field(default_factory=lambda: deque(maxlen=200)) + _server: ThreadingHTTPServer | None = None + + def __enter__(self) -> FakeResponses: + self._server = ThreadingHTTPServer((self.host, 0), _handler(self)) + self._server.daemon_threads = True + threading.Thread(target=self._server.serve_forever, daemon=True).start() + return self + + def __exit__(self, *exc) -> None: + self._server.shutdown() + self._server.server_close() + + @property + def url(self) -> str: + return f"http://{self.host}:{self._server.server_port}" + + def requests(self) -> list[Seen]: + """The model calls.""" + return [seen for seen in self.seen if seen.path.endswith("/responses")] + + def tool_results(self) -> list[str]: + """The output of each tool call the CLI sent back.""" + return [output for seen in self.requests() if (output := _tool_output(seen.body)) is not None] + + +def _item(reply: Text | Call) -> dict: + if isinstance(reply, Text): + return {"type": "message", "role": "assistant", "id": f"msg_{uuid.uuid4().hex}", + "content": [{"type": "output_text", "text": reply.text}]} + return {"type": "function_call", "id": f"fc_{uuid.uuid4().hex}", "call_id": f"call_{uuid.uuid4().hex}", + "name": reply.name, "arguments": json.dumps(reply.arguments)} + + +def _handler(fake: FakeResponses) -> type[BaseHTTPRequestHandler]: + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args) -> None: + pass + + def do_GET(self) -> None: + self._json(200, {"object": "list", "data": []} if self.path.split("?", 1)[0].endswith("/models") + else {"error": {"message": self.path}}) + + def do_POST(self) -> None: + path = self.path.split("?", 1)[0] + body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}") + fake.seen.append(Seen(path, {k.lower(): v for k, v in self.headers.items()}, body)) + if not path.endswith("/responses"): + return self._json(404, {"error": {"message": path}}) + item, rid = _item(fake.respond(body)), f"resp_{uuid.uuid4().hex}" + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.send_header("cache-control", "no-cache") + self.send_header("connection", "close") + self.end_headers() + for event in ({"type": "response.created", "response": {"id": rid}}, + {"type": "response.output_item.added", "item": item}, + {"type": "response.output_item.done", "item": item}, + {"type": "response.completed", "response": {"id": rid, "usage": { + "input_tokens": 10, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 5, + "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 15}}}): + self.wfile.write(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode()) + self.wfile.flush() + self.close_connection = True + + def _json(self, status: int, payload: dict) -> None: + data = json.dumps(payload).encode() + self.send_response(status) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + return Handler