diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 0367f9ea6..88c71d73e 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -74,12 +74,17 @@ The A2A server starts with the real-time marker, so it and its records stay on r hosts it reaches by plain HTTP alone, which have no certificate to check, go direct. `NO_PROXY` goes by host, not scheme, so a host the agent also reaches over TLS stays behind the proxy. The image's proxy reaches private networks too (`AGENTENV_EGRESS_PRIVATE`), so a host over TLS at a private address works at any date as well. Unarmed, the page - holds real time and the CLI goes out directly. + holds real time and the CLI goes out directly. Which way it goes is settled when the bridge starts the CLI, so a clock + armed while a CLI runs reaches its proxy settings with the next one: arm the clock before the turn that needs it. - **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 and Letta Code's too, goes out - the same way. + layout and check it reads the page by, so every agent put on the clock, OpenCode's, Letta Code's, Antigravity's and + Codex's too, goes out the same way. +- **Codex's CLI on real time.** The Codex CLI is a static binary, which the preloaded library never reaches, so it + keeps real time whatever the clock; the commands it runs read the env's time. While the clock is armed, each CLI + run's model relay puts the env's date, read from `date`, where the CLI writes its own, and refuses a call it can't date + (`codex_date.py`). 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/codex/Dockerfile b/src/agent_env/agents/agents/codex/Dockerfile index f477158a0..45baec87f 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 @@ -21,13 +35,38 @@ RUN npm ci --ignore-scripts --omit=dev --no-audit --no-fund --loglevel=error && 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. +COPY a2a_server.py codex_bridge.py codex_config.py codex_date.py codex_kit.py entrypoint.sh install.sh run.sh ./ +# Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, and the model relay +# each CLI run calls the endpoint through (shared_sources.toml). +COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.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 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 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..4da561dcc 100644 --- a/src/agent_env/agents/agents/codex/README.md +++ b/src/agent_env/agents/agents/codex/README.md @@ -24,7 +24,12 @@ Codex reads its settings from `$CODEX_HOME/config.toml`, which the agent writes: server. Its `AgentEnv-Role` header is the role its registration names, unless the task has a role of its own, which reaches that task's CLI alone as `-c` overrides, so tasks of different roles running at once share the file. Codex hands such a server only a few of its own variables, so the entry names `NODE_EXTRA_CA_CERTS`, - `NODE_TLS_REJECT_UNAUTHORIZED` and `SSL_CERT_FILE` for it to pass on. + `NODE_TLS_REJECT_UNAUTHORIZED` and `SSL_CERT_FILE` for it to pass on, and the proxy variables an armed clock sets + (below); `--enable-proxy` has mcp-remote take them, and connect directly when none is set. + +Each CLI run calls the endpoint through a model relay of its own on loopback (`model_relay.py`, shared with the other +agents'), given to it as a `-c` override of the provider's `base_url`, which forwards each call and its answer as they +come. | Extension | Implementation | |---|---| @@ -39,8 +44,26 @@ 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 (`start-agent`), whose supervisord runs the A2A server as the `agent` user; +started as another user, it runs the server alone, as before. Codex's state is in `/home/agent/.codex` whatever the uid. + +The image follows a task env's clock as the agents README describes, once a `sync_env_clock` sets `agent_clock`. The +Codex CLI is a static binary, which the preloaded libfaketime never reaches, so the CLI itself stays on real time: its +threads, their rollouts and the times in its events keep real time, and a clock set behind them breaks nothing. The +commands the model runs, and the MCP clients the CLI starts, read the env's time. The CLI writes the date it tells the +model, the `` of its environment context, and the time of the reminder it gives a turn at `persistent` +effort, from its own clock, so while the clock is armed the run's relay puts the env's date and time there, read from +`date`, in every message of each model call, a resumed thread's earlier ones included (`codex_date.py`). A call whose +date the relay can't read, or that writes a date or time in a form it doesn't know, is refused, so the turn fails rather +than tell the model the machine's date. The `` the CLI names is the container's, which the clock doesn't +change. On an armed clock the CLI's commands and MCP clients go out through the egress proxy, its model calls go to the +relay directly, and the relay, on real time, reaches the endpoint directly. Without a `LITELLM_BASE_URL` the CLI has no +provider of agent-env's and no relay, so nothing tells it the env's date. + +For a model in its catalog, such as `gpt-6-astra`, the CLI runs in code mode: the model calls its tools from JavaScript +it hands the `exec` tool, which runs in `codex-code-mode-host`, another static binary. The tools it calls there follow +the clock as above, but JavaScript's own `Date` in that code reads real time; the `clock` namespace's `sleep` only +waits, so it's unaffected. 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 95d456357..2b1f2097c 100644 --- a/src/agent_env/agents/agents/codex/a2a_server.py +++ b/src/agent_env/agents/agents/codex/a2a_server.py @@ -750,6 +750,7 @@ def _record_event(event: dict) -> None: task_id=cfg.task_id, event_callback=_record_event, max_turns=cfg.max_turns, + mcp_urls=[info["url"] for info in request.mcp_servers.values()], 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 e83a35b5b..f2b7c8854 100644 --- a/src/agent_env/agents/agents/codex/codex_bridge.py +++ b/src/agent_env/agents/agents/codex/codex_bridge.py @@ -17,12 +17,15 @@ import threading import time import uuid -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path -from codex_config import MODEL_HEADERS_ENV, model_headers +from agent_egress import clock_armed, egress_env +from codex_config import MODEL_HEADERS_ENV, endpoint_root, model_headers, relayed_provider +from codex_date import env_date_rewrite +from model_relay import Calls, model_relay logger = logging.getLogger(__name__) WORKSPACE_DIR = os.environ.get("CODEX_WORKSPACE_DIR", "/app") @@ -92,11 +95,13 @@ def get_last_attribution_snapshot() -> dict[str, str | None]: return dict(_last_attribution) -def cli_env(environ: Mapping[str, str], *, project_id: str | None = None, - task_id: str | None = None) -> dict[str, str]: +def cli_env(environ: Mapping[str, str], *, project_id: str | None = None, task_id: str | None = None, + urls: Iterable[str] = (), armed: bool = False) -> dict[str, str]: """The CLI's environment: this process's, with the endpoint's key also under the name codex's own precheck reads, and the run's attribution, which config.toml's env_http_headers sends as headers on each model call. The - run's tags join the x-litellm-tags [model.headers] names.""" + run's tags join the x-litellm-tags [model.headers] names. On an armed clock (``armed``) it has the egress proxy + (``egress_env``) for what the CLI's commands and MCP clients reach, the env's MCP servers (``urls``) among them; + the CLI's model calls go to the turn's relay on loopback, which stays direct.""" env = dict(environ) if env.get("LITELLM_API_KEY") and not env.get("OPENAI_API_KEY"): env["OPENAI_API_KEY"] = env["LITELLM_API_KEY"] @@ -110,7 +115,7 @@ def cli_env(environ: Mapping[str, str], *, project_id: str | None = None, if name.lower() == _TAGS_HEADER), "") if joined := _join_tags(configured, ",".join(tags)): env["LITELLM_TAGS"] = joined - return env + return {**env, **egress_env(environ, urls, armed=armed)} @dataclass @@ -773,6 +778,7 @@ async def _run_codex_once( config_overrides: Sequence[str] = (), max_turns: int | None = None, prior_tool_calls: int = 0, + mcp_urls: Sequence[str] = (), ) -> CodexResult: # 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 @@ -821,7 +827,7 @@ async def _run_codex_once( f"inactivity_watchdog={inactivity_s}s)" ) - subprocess_env = cli_env(os.environ, project_id=project_id, task_id=task_id) + subprocess_env = cli_env(os.environ, project_id=project_id, task_id=task_id, urls=mcp_urls, armed=clock_armed()) if project_id or task_id: _record_attribution(project_id=project_id, task_id=task_id) logger.info( @@ -830,8 +836,14 @@ async def _run_codex_once( subprocess_env.get("LITELLM_TAGS", "(unset)"), ) + # The CLI, a static binary on real time, writes the machine's date; the endpoint is called through a relay of this + # run's own, which tells the model the env's on an armed clock (codex_date). + relays = contextlib.AsyncExitStack() proc = None try: + if (upstream := endpoint_root(os.environ)) is not None: + relay = await relays.enter_async_context(model_relay(upstream, Calls(), rewrite=env_date_rewrite)) + cmd += [arg for override in relayed_provider(relay) for arg in ("-c", override)] proc = await asyncio.create_subprocess_exec( *cmd, stdin=asyncio.subprocess.PIPE, @@ -934,6 +946,7 @@ async def _run_codex_once( ) finally: _RUNNING.discard(proc) + await relays.aclose() if schema_file is not None and schema_file.exists(): try: schema_file.unlink() @@ -954,12 +967,14 @@ async def run_codex( event_callback: Callable[[dict], None] | None = None, config_overrides: Sequence[str] = (), max_turns: int | None = None, + mcp_urls: Sequence[str] = (), ) -> CodexResult: """Run one logical turn with bounded transient recovery. `max_turns` bounds the turn's tool calls, each of which is one model request when the CLI sends no parallel calls, as for a model its catalog has no entry for; `model_requests` counts the requests from the rollout. The turn's - counts include its subagents' calls, read from their own rollouts. + counts include its subagents' calls, read from their own rollouts. `mcp_urls` are the env's MCP servers, which + the CLI's MCP clients connect to. """ deadline = time.monotonic() + timeout_s before = read_rollout(thread_id) or Rollout() @@ -995,6 +1010,7 @@ async def run_codex( config_overrides=config_overrides, max_turns=max_turns, prior_tool_calls=tool_call_count, + mcp_urls=mcp_urls, ) failure = _resumable_api_failure(result) tool_call_count += result.tool_call_count diff --git a/src/agent_env/agents/agents/codex/codex_config.py b/src/agent_env/agents/agents/codex/codex_config.py index 3ba4467c7..18bdbec10 100644 --- a/src/agent_env/agents/agents/codex/codex_config.py +++ b/src/agent_env/agents/agents/codex/codex_config.py @@ -28,8 +28,14 @@ ROLE_HEADER = "AgentEnv-Role" _ROLE_VARIABLE = "AGENTENV_ROLE" # Codex hands a stdio MCP server only a few of its own variables; these tell mcp-remote, a Node client, which -# certificates to trust. +# certificates to trust and, on an armed clock, the egress proxy to go out through (agent_egress.egress_env): Node +# checks an HTTPS server's certificate against the env's date, which the proxy, on real time, doesn't. _TRUST_ENV = ("NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "SSL_CERT_FILE") +_PROXY_ENV = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY", "no_proxy", + "NODE_USE_ENV_PROXY") +# The provider agent-env configures, and the path of LiteLLM's Responses API route under the endpoint's API root. +_PROVIDER = "litellm" +_PROVIDER_PATH = "/openai/v1" # The CLI version CodexTool names the tools of; a test holds it to package.json's @openai/codex. TOOLS_CLI_VERSION = "0.162.1" @@ -203,6 +209,18 @@ def _api_root(url: str) -> str: return urlunsplit(parts._replace(path=parts.path.rstrip("/").removesuffix("/v1").rstrip("/"))) +def endpoint_root(environ: Mapping[str, str]) -> str | None: + """The API root of the endpoint agent-env configured, under which the provider's route is; None without one, when + the CLI has no provider of agent-env's.""" + base_url = environ.get("LITELLM_BASE_URL") or "" + return _api_root(base_url) if base_url else None + + +def relayed_provider(relay: str) -> list[str]: + """The `-c` override that has one CLI run call the provider through ``relay``, a model relay to its API root.""" + return [f"model_providers.{_PROVIDER}.base_url={json.dumps(relay + _PROVIDER_PATH)}"] + + def write_base_config(environ: Mapping[str, str]) -> None: """The settings every turn shares: the collaboration tools, and the model endpoint agent-env configured as a Responses API provider, with its headers and the run's attribution on each call.""" @@ -212,12 +230,11 @@ def write_base_config(environ: Mapping[str, str]) -> None: cfg.setdefault("features", {})["multi_agent_v2"] = True # Off by default since 0.162.0; a selection turns it off again with a `-c` override. cfg.setdefault("tools", {}).setdefault("update_plan", {})["enabled"] = True - base_url = environ.get("LITELLM_BASE_URL") or "" - if base_url: - cfg["model_provider"] = "litellm" + if root := endpoint_root(environ): + cfg["model_provider"] = _PROVIDER provider = { "name": "LiteLLM proxy", - "base_url": _api_root(base_url) + "/openai/v1", + "base_url": root + _PROVIDER_PATH, "env_key": "LITELLM_API_KEY", "wire_api": "responses", # Bound codex retry/idle behavior so a hung stream fails fast @@ -242,7 +259,7 @@ def write_base_config(environ: Mapping[str, str]) -> None: # a Responses API may refuse when the history replays encrypted tool-call arguments. Remote compaction sends # the tools. provider["capabilities"] = {"remote_compaction": "v2"} - cfg.setdefault("model_providers", {})["litellm"] = provider + cfg.setdefault("model_providers", {})[_PROVIDER] = provider _write(cfg) @@ -250,7 +267,9 @@ def _server_entry(url: str, headers: dict[str, str] | None = None) -> dict[str, """Build a codex `mcp_servers.` config table. Wraps the URL in `mcp-remote` (stdio shim), a Node client that trusts the - certificates `_TRUST_ENV` names in the agent's environment. Each header is passed + certificates `_TRUST_ENV` names in the agent's environment and, with + `--enable-proxy`, goes out through the proxy `_PROXY_ENV` names there, directly + when it names none. Each header is passed as a `--header "Name: Value"` arg. The `AgentEnv-Role` header, which the env gateway filters tools by, is mcp-remote's `${AGENTENV_ROLE}`: the role the registration's own headers name, from the entry's env, unless a CLI run passes @@ -258,7 +277,7 @@ 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"] + args: list[str] = [url, "--allow-http", "--enable-proxy"] for k, v in (headers or {}).items(): if k.lower() == ROLE_HEADER.lower(): registered = v @@ -269,7 +288,7 @@ def _server_entry(url: str, headers: dict[str, str] | None = None) -> dict[str, "command": "mcp-remote", "args": args, "env": {_ROLE_VARIABLE: registered}, - "env_vars": list(_TRUST_ENV), + "env_vars": [*_TRUST_ENV, *_PROXY_ENV], "startup_timeout_sec": 60, # Codex silently drops non-`required` servers that miss its hard-coded # 1s startup grace, which mcp-remote always does — but a `required` diff --git a/src/agent_env/agents/agents/codex/codex_date.py b/src/agent_env/agents/agents/codex/codex_date.py new file mode 100644 index 000000000..f45045f5e --- /dev/null +++ b/src/agent_env/agents/agents/codex/codex_date.py @@ -0,0 +1,127 @@ +"""The env's date in Codex's model calls. The Codex CLI is a static binary, which no preloaded library reaches, so it +stays on real time and writes the machine's date where it tells the model the date; while this agent follows an armed +clock, each CLI run's model relay puts the env's date there instead. The patterns below are where the pinned CLI, +TOOLS_CLI_VERSION, writes its date; tst/integration/agent/codex_env_date_test.py checks them against it.""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import os +import re +import signal +import time + +from agent_egress import clock_armed +from model_relay import Refusal + +# The date line of the environment context the CLI gives the model (codex-rs core/src/context/world_state/ +# environment.rs, from turn_context.rs's local_time_context), and the time reminder it gives a persistent turn +# (core/src/context/current_time_reminder.rs). The CLI writes each as a text of its own, between its markers, so a +# text that only quotes one, a task's prompt say, is left as written. +_CONTEXT_MARKERS = ("", "") +_REMINDER_MARKERS = ("", "") +_CURRENT_DATE = re.compile(r"[^<]*") +_DATE_UNAVAILABLE = '' +_REMINDER_TIME = re.compile(r"It is [^<]* UTC\.") +_TIME_REMINDER = re.compile(r"\s*" + _REMINDER_TIME.pattern + r"\s*") +_ROLES = ("user", "developer", "system") +_DATE_TIMEOUT_S = 5 +# How much of what a failing date printed its refusal quotes. +_SHOWN_CHARS = 200 + + +async def env_date_rewrite(body: bytes) -> bytes: + """The model call with the env's date in place of the CLI's, while this agent follows an armed clock; unchanged + otherwise. A call that isn't JSON, a date or time this doesn't know how to place, or a date that can't be read is + refused, so the model is never told the machine's date instead.""" + if not clock_armed(): + return body + try: + request = json.loads(body) + except ValueError as exc: + raise Refusal("the model call isn't JSON this agent can read, so the model can't be told the env's date") \ + from exc + if not isinstance(request, dict): + return body + contexts = [(holder, key) for holder, key in _texts(request) + if _between(holder[key], _CONTEXT_MARKERS) and "{today}", holder[key]) + for holder, key in reminders: + holder[key] = _REMINDER_TIME.sub(f"It is {now_utc} UTC.", holder[key], count=1) + # Escaped, so a lone surrogate an MCP server's tool sent, which UTF-8 can't encode, goes as it came. + return json.dumps(request, separators=(",", ":")).encode() + + +def _texts(request: dict): + """Each text of the request's input messages in ``_ROLES``, as (holder, key), so it can be replaced in place.""" + for item in request.get("input") or []: + if not isinstance(item, dict) or item.get("role") not in _ROLES or item.get("type", "message") != "message": + continue + content = item.get("content") + if isinstance(content, str): + yield item, "content" + elif isinstance(content, list): + yield from ((part, "text") for part in content if isinstance(part, dict) and isinstance(part.get("text"), str)) + + +def _between(text: str, markers: tuple[str, str]) -> bool: + """Whether ``text`` is one of the CLI's fragments: its whole text between the fragment's markers.""" + stripped = text.strip() + return stripped.startswith(markers[0]) and stripped.endswith(markers[1]) + + +async def _env_now() -> tuple[str, str]: + """The env's date as the CLI writes its own, in this zone, and its time in UTC as the CLI's reminder writes it. It + comes from ``date``: this server runs on real time, but what it starts reads the env's clock, as the model's + commands do.""" + def unread(reason: str) -> Refusal: + return Refusal(f"the env's date couldn't be read for the model: {reason}") + + try: + code, out, err = await _read_date() + except TimeoutError: + raise unread(f"date gave no answer within {_DATE_TIMEOUT_S} s") from None + except OSError as exc: + raise unread(f"{type(exc).__name__}: {exc}") from exc + if code != 0: + raise unread(f"date exited {code}: {err.decode(errors='replace').strip()[:_SHOWN_CHARS]}") + try: + seconds, _ = out.decode().split() + day, utc = time.localtime(int(seconds)), time.gmtime(int(seconds)) + except (ValueError, OverflowError, OSError) as exc: + raise unread(f"date printed {out.decode(errors='replace')[:_SHOWN_CHARS]!r}") from exc + return (f"{day.tm_year:04d}-{day.tm_mon:02d}-{day.tm_mday:02d}", + f"{utc.tm_year:04d}-{utc.tm_mon:02d}-{utc.tm_mday:02d} " + f"{utc.tm_hour:02d}:{utc.tm_min:02d}:{utc.tm_sec:02d}") + + +async def _read_date() -> tuple[int, bytes, bytes]: + """``date``'s exit code and output. Past the timeout its process group is killed, which reaches anything it left + holding its output, even after it exited itself.""" + environ = {name: value for name, value in os.environ.items() if name != "AGENTENV_REAL_TIME"} + proc = await asyncio.create_subprocess_exec("date", "+%s %N", stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, env=environ, start_new_session=True) + try: + out, err = await asyncio.wait_for(proc.communicate(), timeout=_DATE_TIMEOUT_S) + except BaseException: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(proc.wait(), _DATE_TIMEOUT_S) + raise + return proc.returncode, out, err diff --git a/src/agent_env/agents/agents/codex/install.sh b/src/agent_env/agents/agents/codex/install.sh index 57fb9d255..0700434a3 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_date.py codex_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.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/requirements.txt b/src/agent_env/agents/agents/codex/requirements.txt index 602ef6008..ffcc1be78 100644 --- a/src/agent_env/agents/agents/codex/requirements.txt +++ b/src/agent_env/agents/agents/codex/requirements.txt @@ -1,8 +1,10 @@ # The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the -# image is built again only when this folder changes. The floor is the first whose Usage gives a turn's counts by -# model (Usage.models); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.640 +# image is built again only when this folder changes. The floor is the first with ModelUsage.of, which the model relay +# reads a call's usage with; raise it when the agent needs a newer protocol. +agentenv-framework-protocol[agent]>=0.1.643 tomli-w==1.2.0 +# The model relay's server and client. +aiohttp>=3.9,<4 # The CA certificates an installed agent's CLI trusts on a target that has none of its own; unpinned, so each build # takes the newest. certifi 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..39cb6deb0 --- /dev/null +++ b/src/agent_env/agents/agents/codex/root.conf @@ -0,0 +1,74 @@ +; 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 +; read the env's time. The Codex CLI is a static binary, which no preloaded library reaches, 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 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. Never restarted: see [eventlistener:agent-exit]. +[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 server's exit, for any reason, stops supervisord and with it the container, as when the server was the +; container's main process: one restarted in place would have lost the env's MCP servers, its config, its peers and its +; running tasks, while the CLI the dead one started went on writing. The follower and the proxy restart in place. +; supervisord exits 0 however it stops, so the container's exit status doesn't tell a crash from a stop; its log does. +[eventlistener:agent-exit] +command=/bin/sh -c 'while echo READY && read -r header; do body=$(head -c "${header##*len:}"); case " $body " in *" processname:agent "*) echo "the A2A server exited ($body): stopping the container" >&2; kill -TERM "$PPID";; esac; printf "RESULT 2\nOK"; done' +events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 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..ba8b8a852 --- /dev/null +++ b/src/agent_env/agents/agents/codex/shared_sources.toml @@ -0,0 +1,6 @@ +# 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" +model_relay = "utils/model_relay" 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..7b84a1e0c --- /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, 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/agent/codex_env_date_test.py b/tst/integration/agent/codex_env_date_test.py new file mode 100644 index 000000000..1551826e3 --- /dev/null +++ b/tst/integration/agent/codex_env_date_test.py @@ -0,0 +1,88 @@ +"""The Codex CLI the agent's package-lock.json pins, against what its bridge relies on to tell the model the env's date +while the CLI runs on real time: every place the CLI writes its date or time into a model call is one the turn's relay +rewrites, so the model is sent the env's date and no copy of the machine's, whether the turn starts a thread or resumes +one. Bumping the CLI runs this against the new version, so a version that moves or adds a date fails here.""" + +import asyncio +import json +import shutil +import subprocess +import time +from pathlib import Path + +import pytest + +from tst.unit.agents.codex.agent import AGENT_DIR, codex_bridge, codex_config, codex_date +from tst.util import fake_responses + +pytestmark = [pytest.mark.integration] + +VERSION = json.loads((AGENT_DIR / "package.json").read_text())["dependencies"]["@openai/codex"] +ENV_TODAY, ENV_NOW = "1950-01-01", "1950-01-01 12:00:00" +_DAY_S = 86400 + + +@pytest.fixture(scope="module") +def codex_bin(tmp_path_factory) -> Path: + """The CLI installed as the image installs it: npm ci from the lockfile.""" + npm = shutil.which("npm") + assert npm and shutil.which("node"), "node and npm install the pinned Codex CLI" + folder = tmp_path_factory.mktemp("codex") + for name in ("package.json", "package-lock.json"): + shutil.copy(AGENT_DIR / name, folder / name) + subprocess.run([npm, "ci", "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund", "--loglevel=error"], + cwd=folder, check=True, timeout=600) + return folder / "node_modules" / ".bin" + + +def _machine_dates() -> set[str]: + """This machine's date for yesterday, today and tomorrow, as the CLI writes one (``%Y-%m-%d``, in this zone and in + UTC), so a turn across midnight is still caught.""" + return {time.strftime("%Y-%m-%d", read(time.time() + offset)) + for offset in (-_DAY_S, 0, _DAY_S) for read in (time.localtime, time.gmtime)} + + +def _texts(body: dict) -> list[str]: + texts = [body["instructions"]] if isinstance(body.get("instructions"), str) else [] + for item in body.get("input") or []: + if isinstance(item, dict) and item.get("type", "message") == "message": + content = item.get("content") + parts = content if isinstance(content, list) else [{"text": content}] + texts += [part["text"] for part in parts if isinstance(part, dict) and isinstance(part.get("text"), str)] + return texts + + +def test_a_turn_on_an_armed_clock_tells_the_model_the_env_date_and_no_other(codex_bin, tmp_path, monkeypatch): + async def env_now() -> tuple[str, str]: + return ENV_TODAY, ENV_NOW + + for name in ("HOME", "CODEX_HOME"): + monkeypatch.setenv(name, str(tmp_path / name.lower())) + monkeypatch.setenv("PATH", f"{codex_bin}:{subprocess.os.environ['PATH']}") + monkeypatch.setenv("LITELLM_API_KEY", "sk-fake") + monkeypatch.setattr(codex_bridge, "SESSIONS_DIR", tmp_path / "codex_home" / "sessions") + monkeypatch.setattr(codex_bridge, "WORKSPACE_DIR", str(tmp_path / "work")) + monkeypatch.setattr(codex_date, "clock_armed", lambda: True) + monkeypatch.setattr(codex_date, "_env_now", env_now) + (tmp_path / "work").mkdir() + + respond = fake_responses.tool_then_answer("exec_command", {"cmd": "echo hello"}, prefix="the shell said: ") + with fake_responses.FakeResponses(respond=respond) as endpoint: + monkeypatch.setenv("LITELLM_BASE_URL", endpoint.url) + codex_config.write_base_config(subprocess.os.environ) + first = asyncio.run(codex_bridge.run_codex("Run echo hello.", None, model="gpt-x", timeout_s=300)) + assert not first.error and first.session_id, (first.error, first.trajectory[-3:]) + second = asyncio.run(codex_bridge.run_codex("Again.", first.session_id, model="gpt-x", timeout_s=300)) + + assert not second.error, (second.error, second.trajectory[-3:]) + sent = [seen.body for seen in endpoint.calls()] + assert len(sent) >= 4 and any("hello" in result for result in endpoint.tool_results()), endpoint.tool_results() + dated = [text for body in sent for text in _texts(body) if "{ENV_TODAY}" in text for text in dated), ( + f"Codex {VERSION} no longer writes its date where codex_date's _CURRENT_DATE finds it: {dated}") + assert all(text.strip().startswith("") and text.strip().endswith("") + for text in dated), f"Codex {VERSION} no longer writes its environment context as a text of its own" + machine = _machine_dates() + for body in sent: + found = [date for date in machine if date in json.dumps(body)] + assert not found, f"Codex {VERSION} wrote this machine's date {found} where the relay doesn't rewrite it" 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 e34e5f3ac..f146e146f 100644 --- a/tst/integration/task_step/test_agent_env_clock_local.py +++ b/tst/integration/task_step/test_agent_env_clock_local.py @@ -2,8 +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 a stub endpoint serves, Anthropic's messages or OpenAI's chat completions, -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 or +responses, 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,12 +16,14 @@ import uuid from collections.abc import Awaitable, Callable from dataclasses import dataclass +from pathlib import Path from datetime import datetime, timezone from typing import Any import pytest from agentenv_protocol.client import ExtensionCallError +import agent_env from agent_env.a2a_agent.a2a_agent import A2AAgent from agent_env.a2a_agent.clock import FOLLOWING_KEY from agent_env.artifact import DockerImageArtifact @@ -40,7 +42,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 import fake_openai, fake_responses from tst.util.capabilities import agent_clock_image, skip_without_agent_clock_image from tst.util.fake_anthropic import FakeAnthropic, tool_then_answer @@ -98,6 +100,29 @@ async def _letta_turn(context: TaskStepContext, endpoint: fake_openai.FakeOpenAI assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results() +async def _codex_turn(context: TaskStepContext, endpoint: fake_responses.FakeResponses) -> None: + """One turn of the real Codex CLI, its proxy variables set: the CLI, a static binary, stays on real time, its model + calls reach the turn's relay on loopback, which the egress proxy would refuse, and the date the relay gives the + model and a `date` the model runs are the env's.""" + endpoint.respond = fake_responses.tool_then_answer("exec_command", {"cmd": "date -u +%FT%TZ"}, + prefix="the shell said: ") + # A model the CLI's catalog doesn't know, which it offers its shell to as exec_command. + await PromptAgentTaskStep(id="ask", version=None, prompt="What's the date? Run date.", agent_name="solver", + model="gpt-x", max_conversation_turns=1).execute(context) + bodies = [json.dumps(call.body) for call in endpoint.calls()] + dated = {m for body in bodies for m in re.findall(r"([^<]*)", body)} + print("the date the model was told:", dated, "date:", endpoint.tool_results()) + assert dated == {VIRTUAL[:10]}, dated + assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results() + assert not [body for body in bodies if str(datetime.now(timezone.utc).date()) in body] + + +def _pinned(agent: str, package: str) -> str: + """The version of ``package`` the agent's package.json pins, which its CLI's --version names.""" + folder = Path(agent_env.__file__).parent / "agents" / "agents" / agent + return json.loads((folder / "package.json").read_text())["dependencies"][package] + + @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 @@ -114,9 +139,11 @@ class Agent: 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=f"codex-cli {_pinned('codex', '@openai/codex')}", + turn=_codex_turn, endpoint=fake_responses.FakeResponses), "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"), + "opencode": Agent(bridge="opencode_bridge", version=("opencode", "--version"), shows=_pinned("opencode", "opencode-ai")), } diff --git a/tst/unit/agents/codex/agent.py b/tst/unit/agents/codex/agent.py index af4353fdb..6feeab08e 100644 --- a/tst/unit/agents/codex/agent.py +++ b/tst/unit/agents/codex/agent.py @@ -1,18 +1,26 @@ -"""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/, clock/ and model_relay/, 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), str(sent(AGENT_DIR, "model_relay/model_relay.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_date = importlib.import_module("codex_date") codex_kit = importlib.import_module("codex_kit") +agent_egress = importlib.import_module("agent_egress") +model_relay = importlib.import_module("model_relay") # 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_codex_builtin_tools.py b/tst/unit/agents/codex/test_codex_builtin_tools.py index db40fbbba..527732a32 100644 --- a/tst/unit/agents/codex/test_codex_builtin_tools.py +++ b/tst/unit/agents/codex/test_codex_builtin_tools.py @@ -206,12 +206,13 @@ def _alive(pid: int) -> bool: def test_a_catalog_read_past_its_time_is_killed_and_fails_the_selection(cli, tmp_path): - """The read gets only the time it's given, and its child doesn't outlive it.""" + """The read gets only the time it's given, and its child doesn't outlive it. The time leaves a loaded machine + time to start the stand-in CLI and its child.""" pid_file = _hanging_cli(tmp_path) tools = a2a_server.CodexConfig(builtin_tools={"disable": "*"}).builtin_tools - with pytest.raises(RuntimeError, match="no catalog within 1s"): - asyncio.run(codex_config.catalog_overrides(tools, timeout_s=1)) + with pytest.raises(RuntimeError, match="no catalog within 3s"): + asyncio.run(codex_config.catalog_overrides(tools, timeout_s=3)) assert not _alive(int(pid_file.read_text())) diff --git a/tst/unit/agents/codex/test_codex_date.py b/tst/unit/agents/codex/test_codex_date.py new file mode 100644 index 000000000..9469824bd --- /dev/null +++ b/tst/unit/agents/codex/test_codex_date.py @@ -0,0 +1,247 @@ +"""The env's date in Codex's model calls (codex_date): on an armed clock each CLI run's relay puts the env's date, as a +``date`` started by the A2A server reads it, where the CLI, a static binary on real time, put its own, in every +environment context of the call, and the env's time in its time reminders; it refuses a call whose date it can't read +or place. Off the clock, or with nothing to rewrite, a call goes as the CLI wrote it.""" + +from __future__ import annotations + +import asyncio +import json +import subprocess +import time + +import httpx +import pytest +from aiohttp import web + +from tst.unit.agents.codex.agent import codex_date, model_relay +from tst.util import fake_date + +# The environment context as Codex 0.162.1 writes it (codex-rs core/src/context/world_state/environment.rs). +CONTEXT = ("\n /app\n bash\n 2026-11-25\n" + " Etc/UTC\n") +LATER = "\n 2026-11-26\n" +REMINDER = "It is 2026-11-25 17:34:15 UTC." +PROMPT = "What's the date? The notes say as written." +OUTPUT = "2026-11-25" + + +def _message(role: str, *texts: str, parts: bool = True) -> dict: + content = [{"type": "input_text", "text": text} for text in texts] if parts else texts[0] + return {"type": "message", "role": role, "content": content} + + +def _call(*, parts: bool = True, later: bool = True, reminder: bool = True) -> dict: + items = [_message("developer", "sandbox"), + _message("user", "# AGENTS.md instructions for /app", CONTEXT, parts=parts) if parts + else _message("user", CONTEXT, parts=False), + _message("user", PROMPT), + {"type": "function_call", "name": "exec_command", "arguments": json.dumps({"cmd": "date"}), + "call_id": "c1"}, + {"type": "function_call_output", "call_id": "c1", "output": OUTPUT}] + if later: + items.append(_message("user", LATER)) + if reminder: + items.append(_message("developer", REMINDER)) + return {"model": "gpt-x", "instructions": "You are Codex.", "input": items, "tools": [], "stream": True} + + +@pytest.fixture +def env_clock(tmp_path, monkeypatch): + """An armed clock, in UTC, whose time the stand-in ``date`` prints (tst/util/fake_date.py).""" + recorded = fake_date.install(tmp_path, monkeypatch) + monkeypatch.setattr(codex_date, "clock_armed", lambda: True) + yield recorded + monkeypatch.undo() + time.tzset() + + +def _rewrite(call: dict) -> dict: + return json.loads(asyncio.run(codex_date.env_date_rewrite(json.dumps(call).encode()))) + + +def _texts(call: dict) -> list[str]: + return [part["text"] if isinstance(part, dict) else part for item in call["input"] if item["type"] == "message" + for part in (item["content"] if isinstance(item["content"], list) else [item["content"]])] + + +@pytest.mark.parametrize("date_out, today, now", [ + ("1801742400 000000000", "2027-02-04", "2027-02-04 12:00:00"), + ("7258161600 250000000", "2200-01-01", "2200-01-01 12:00:00"), + ("-631108800 000000000", "1950-01-01", "1950-01-01 12:00:00"), + # Half a second before 1950: date prints the second below and a positive fraction. + ("-631152001 500000000", "1949-12-31", "1949-12-31 23:59:59"), +]) +@pytest.mark.parametrize("parts", [True, False]) +def test_on_an_armed_clock_the_model_is_told_the_env_date_and_time_a_command_reads(env_clock, monkeypatch, date_out, + today, now, parts): + monkeypatch.setenv("FAKE_DATE_OUT", date_out) + sent = _call(parts=parts) + + call = _rewrite(sent) + + context = CONTEXT.replace("2026-11-25", today) + assert _texts(call) == [t.replace(CONTEXT, context).replace(LATER, LATER.replace("2026-11-26", today)) + .replace(REMINDER, f"It is {now} UTC.") + for t in _texts(sent)] + assert call["input"][3:5] == sent["input"][3:5] # the model's call and what the command printed go as they were + assert {k: v for k, v in call.items() if k != "input"} == {k: v for k, v in sent.items() if k != "input"} + assert "AGENTENV_REAL_TIME" not in env_clock.read_text() and "TZ=UTC" in env_clock.read_text() + + +def test_a_date_outside_an_environment_context_goes_as_written(env_clock, monkeypatch): + """A prompt's own words, which name a date element of their own, aren't the CLI's date.""" + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + + assert PROMPT in _texts(_rewrite(_call())) + + +@pytest.mark.parametrize("quoted", [ + f"Explain this: {CONTEXT}", + "The log said Now: 17:34, which is odd.", + f"{REMINDER} was in the transcript.", +]) +def test_a_prompt_quoting_the_clis_date_or_reminder_goes_as_written_and_isnt_refused(env_clock, monkeypatch, quoted): + """The CLI writes its environment context and reminder each as a text of its own, between its markers.""" + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + call = _call() + call["input"].append(_message("user", quoted)) + + assert _texts(_rewrite(call))[-1] == quoted + + +def test_a_date_the_cli_marked_unavailable_stays_so(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + gone = '\n \n' + call = _call() + call["input"].append(_message("user", gone)) + + assert gone in _texts(_rewrite(call)) + + +def test_the_date_is_written_in_the_zone_the_cli_writes_its_own_in(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801785600 000000000") # 2027-02-05T00:00Z, still the 4th in New York + monkeypatch.setenv("TZ", "America/New_York") + time.tzset() + + texts = _texts(_rewrite(_call())) + + assert "2027-02-04" in texts[2] + assert "It is 2027-02-05 00:00:00 UTC." in texts + assert "Etc/UTC" in texts[2] # the zone the CLI named, which isn't time's to change + + +def test_a_lone_surrogate_in_a_tool_an_mcp_server_sent_goes_as_it_came(env_clock, monkeypatch): + """The CLI sends it escaped, as a server's tool list had it; UTF-8 can't encode it unescaped.""" + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + call = _call() + call["tools"].append({"type": "function", "name": "env_cut", "description": "cut \ud83d"}) + + assert _rewrite(call)["tools"][0]["description"] == "cut \ud83d" + + +@pytest.mark.usefixtures("socket_enabled") +def test_the_relay_sends_the_endpoint_the_call_with_the_env_date(env_clock, monkeypatch): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + received = [] + + async def endpoint(request): + received.append((request.headers["Content-Length"], await request.read())) + return web.json_response({"output": [], "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}}) + + async def run(): + app = web.Application() + app.router.add_post("/openai/v1/responses", endpoint) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + upstream = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}" + try: + async with model_relay.model_relay(upstream, model_relay.Calls(), + rewrite=codex_date.env_date_rewrite) as root: + async with httpx.AsyncClient(timeout=10) as client: + return (await client.post(f"{root}/openai/v1/responses", content=json.dumps(_call()))).status_code + finally: + await runner.cleanup() + + assert asyncio.run(run()) == 200 + ((length, body),) = received + assert int(length) == len(body) and json.loads(body)["stream"] is True + assert CONTEXT.replace("2026-11-25", "2027-02-04") in _texts(json.loads(body)) + + +@pytest.mark.parametrize("armed", [False, True]) +def test_a_call_with_nothing_to_rewrite_or_off_the_clock_goes_as_written_and_reads_no_date(env_clock, monkeypatch, + armed): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + monkeypatch.setattr(codex_date, "clock_armed", lambda: armed) + calls = [json.dumps(_call(), indent=1).encode(), b"not json"] if not armed else [] + nothing = {"model": "gpt-x", "input": [_message("user", "hi"), + {"type": "function_call_output", "call_id": "c", "output": OUTPUT}]} + calls += [json.dumps(nothing, indent=1).encode()] + + for body in calls: + assert asyncio.run(codex_date.env_date_rewrite(body)) == body + assert not env_clock.exists() + + +def test_on_an_armed_clock_a_call_that_isnt_json_is_refused_rather_than_sent_with_the_real_date(env_clock): + with pytest.raises(codex_date.Refusal, match="isn't JSON"): + asyncio.run(codex_date.env_date_rewrite(json.dumps(_call()).encode()[:-1])) + + +@pytest.mark.parametrize("text, what", [ + ('\n 2026-11-25\n', "a date"), + ("\n 2026-11-25\n", "a date"), + ("It is 2026-11-25T17:34:15Z.", "a time"), + ("Now: 17:34", "a time"), +]) +def test_a_date_or_time_written_in_a_form_this_doesnt_know_refuses_the_call(env_clock, monkeypatch, text, what): + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + call = _call() + call["input"].append(_message("user", text)) + + with pytest.raises(codex_date.Refusal, match=f"has {what} this agent doesn't know how to place"): + _rewrite(call) + assert not env_clock.exists() + + +@pytest.mark.parametrize("environ, reason", [ + ({}, "date exited 1: no clock"), + ({"FAKE_DATE_OUT": "1801742400 000000000", "FAKE_DATE_EXIT": "3"}, "date exited 3"), + ({"FAKE_DATE_OUT": "soon"}, "date printed 'soon\\n'"), + ({"FAKE_DATE_OUT": "1 0", "FAKE_DATE_SLEEP": "10"}, "date gave no answer within 2 s"), +]) +def test_a_date_that_cant_be_read_refuses_the_call_rather_than_tell_the_model_real_time(env_clock, monkeypatch, + environ, reason): + """A date that hangs is killed with the sleep it started, which holds its output open, so the refusal comes in + its time.""" + monkeypatch.setattr(codex_date, "_DATE_TIMEOUT_S", 2) + for name, value in environ.items(): + monkeypatch.setenv(name, value) + started = time.monotonic() + + with pytest.raises(codex_date.Refusal) as refused: + _rewrite(_call()) + + assert str(refused.value).startswith(f"the env's date couldn't be read for the model: {reason}") + assert time.monotonic() - started < 6 + + +def test_a_date_that_exits_leaving_a_process_on_its_output_is_refused_and_that_process_killed(env_clock, monkeypatch, + tmp_path): + """The date has exited, so only its session's group still reaches what it left holding the pipes. The timeout + leaves a loaded machine time to start the stand-in and its child.""" + monkeypatch.setattr(codex_date, "_DATE_TIMEOUT_S", 3) + monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") + monkeypatch.setenv("FAKE_DATE_KID", str(tmp_path / "kid")) + + with pytest.raises(codex_date.Refusal, match="date gave no answer within 3 s"): + _rewrite(_call()) + + kid, deadline = (tmp_path / "kid").read_text().strip(), time.monotonic() + 5 + while (state := subprocess.run(["ps", "-o", "stat=", "-p", kid], capture_output=True, text=True).stdout.strip()) \ + and not state.startswith("Z") and time.monotonic() < deadline: + time.sleep(0.1) + assert not state or state.startswith("Z"), state diff --git a/tst/unit/agents/codex/test_codex_executor_outcome.py b/tst/unit/agents/codex/test_codex_executor_outcome.py index 7fe304d5a..8c3e8ae19 100644 --- a/tst/unit/agents/codex/test_codex_executor_outcome.py +++ b/tst/unit/agents/codex/test_codex_executor_outcome.py @@ -183,9 +183,10 @@ async def exercise(): assert seen_thread_ids == [None, "shared-thread"] -def test_every_server_is_required_and_mcp_remote_gets_the_ca_variables(monkeypatch, tmp_path): +def test_every_server_is_required_and_mcp_remote_gets_the_ca_and_proxy_variables(monkeypatch, tmp_path): """Codex drops an optional server that misses its 1s grace, which mcp-remote always does; and codex hands a stdio - server only a few of its variables, so the CA ones are named for it to pass on.""" + server only a few of its variables, so the CA ones, and the egress proxy's an armed clock sets, are named for it to + pass on.""" monkeypatch.setenv("CODEX_HOME", str(tmp_path)) asyncio.run(codex_config.write_mcp_servers( {"envmcp": {"url": "https://gw/mcp", "headers": None}, @@ -193,6 +194,7 @@ def test_every_server_is_required_and_mcp_remote_gets_the_ca_variables(monkeypat servers = tomllib.loads((tmp_path / "config.toml").read_text())["mcp_servers"] assert {name: (server["required"], server["env_vars"]) for name, server in servers.items()} == { - name: (True, ["NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "SSL_CERT_FILE"]) + name: (True, ["NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "SSL_CERT_FILE", "HTTP_PROXY", "HTTPS_PROXY", + "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY", "no_proxy", "NODE_USE_ENV_PROXY"]) for name in ("envmcp", "peer_agents") } \ No newline at end of file diff --git a/tst/unit/agents/codex/test_config_and_mcp.py b/tst/unit/agents/codex/test_config_and_mcp.py index 4b730b46a..bae6d2935 100644 --- a/tst/unit/agents/codex/test_config_and_mcp.py +++ b/tst/unit/agents/codex/test_config_and_mcp.py @@ -149,13 +149,15 @@ async def exercise(): assert first == second == third assert first["env4821"] == { "command": "mcp-remote", - "args": ["https://gw/mcp", "--allow-http", "--header", "X-Tenant: t", "--header", "AgentEnv-Role: ${AGENTENV_ROLE}"], + "args": ["https://gw/mcp", "--allow-http", "--enable-proxy", "--header", "X-Tenant: t", "--header", + "AgentEnv-Role: ${AGENTENV_ROLE}"], "env": {"AGENTENV_ROLE": ""}, - "env_vars": ["NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "SSL_CERT_FILE"], + "env_vars": ["NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "SSL_CERT_FILE", "HTTP_PROXY", "HTTPS_PROXY", + "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY", "no_proxy", "NODE_USE_ENV_PROXY"], "startup_timeout_sec": 60, "required": True, } - assert (first["audited"]["args"][2:], first["audited"]["env"]) == ( + assert (first["audited"]["args"][3:], first["audited"]["env"]) == ( ["--header", "AgentEnv-Role: ${AGENTENV_ROLE}"], {"AGENTENV_ROLE": "auditor"}) assert first["peer_agents"]["args"][0] == "http://127.0.0.1:8000/ext/peer-agents/mcp" servers = ("env4821", "audited", "peer_agents") 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..5840d6b4e --- /dev/null +++ b/tst/unit/agents/codex/test_env_clock.py @@ -0,0 +1,116 @@ +"""Codex 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's MCP clients connect to themselves, so on an armed clock what the CLI starts goes out +through the image's egress proxy, and to loopback, the hosts NO_PROXY names and plain-HTTP hosts directly; unarmed, it +goes out as before. The CLI, a static binary, stays on real time, and each turn's relay tells the model the env's date +(test_codex_date.py). What every clocked image shares is checked in tst/unit/agents/test_agent_clock_images.py.""" + +from __future__ import annotations + +import asyncio +import contextlib +import tomllib + +import pytest + +from tst.unit.agents.codex.agent import agent_egress, codex_bridge, codex_config, codex_date + +PROXY = "http://127.0.0.1:3128" +SERVERS = {"env": {"url": "http://gateway:8080/mcp"}, "remote": {"url": "https://abc-123.w.modal.host/mcp"}} + + +def _direct(env: dict[str, str]) -> set[str]: + return set(env["NO_PROXY"].split(",")) + + +def test_on_an_armed_clock_what_the_cli_starts_goes_out_through_the_proxy(): + env = codex_bridge.cli_env({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} + assert env["NODE_USE_ENV_PROXY"] == "1" + assert {"localhost", "127.0.0.1", "host.docker.internal", "registry.internal"} <= _direct(env) + + +@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(environ, armed): + env = codex_bridge.cli_env(environ, urls=[server["url"] for server in SERVERS.values()], armed=armed) + + assert not {"HTTPS_PROXY", "NO_PROXY", "NODE_USE_ENV_PROXY"} & set(env) + assert env == codex_bridge.cli_env(environ) + + +def test_the_envs_plain_http_mcp_servers_are_reached_directly_and_https_ones_through_the_proxy_on_an_armed_clock(): + """mcp-remote checks an HTTPS server's certificate against the env's date, which the proxy, on real time, doesn't.""" + env = codex_bridge.cli_env({agent_egress.EGRESS_PROXY_ENV: PROXY}, + urls=[server["url"] for server in SERVERS.values()], armed=True) + + assert "gateway" in _direct(env) and "abc-123.w.modal.host" not in _direct(env) + + +def test_mcp_remote_is_handed_the_proxy_and_told_to_use_it(monkeypatch, tmp_path): + """Codex hands a stdio server only the variables its entry names, and mcp-remote's own HTTP client ignores a proxy + unless told to take it; with no proxy variable set, as off the clock, it connects directly.""" + monkeypatch.setenv("CODEX_HOME", str(tmp_path)) + asyncio.run(codex_config.write_mcp_servers(SERVERS)) + + entries = tomllib.loads((tmp_path / "config.toml").read_text())["mcp_servers"] + for entry in entries.values(): + assert "--enable-proxy" in entry["args"] + assert set(agent_egress.egress_env({agent_egress.EGRESS_PROXY_ENV: PROXY}, armed=True)) <= set(entry["env_vars"]) + + +def test_each_cli_run_starts_with_the_clock_as_it_is_then(monkeypatch): + seen = [] + + async def fake_exec(*cmd, env, **kwargs): + seen.append(env) + raise RuntimeError("stop here") + + monkeypatch.setenv(agent_egress.EGRESS_PROXY_ENV, PROXY) + monkeypatch.setattr(codex_bridge.asyncio, "create_subprocess_exec", fake_exec) + for armed in (False, True): + monkeypatch.setattr(codex_bridge, "clock_armed", lambda armed=armed: armed) + with pytest.raises(RuntimeError, match="stop here"): + asyncio.run(codex_bridge._run_codex_once("go", None, mcp_urls=["https://abc-123.w.modal.host/mcp"])) + + assert ["HTTPS_PROXY" in env for env in seen] == [False, True] + assert "abc-123.w.modal.host" not in _direct(seen[1]) + + +def _cli_command(monkeypatch, relay) -> list[str]: + """The command one CLI run starts with, the relay a stand-in for ``model_relay``.""" + seen = [] + + async def fake_exec(*cmd, **kwargs): + seen.append(list(cmd)) + raise RuntimeError("stop here") + + monkeypatch.setattr(codex_bridge, "model_relay", relay) + monkeypatch.setattr(codex_bridge.asyncio, "create_subprocess_exec", fake_exec) + with pytest.raises(RuntimeError, match="stop here"): + asyncio.run(codex_bridge._run_codex_once("go", None, config_overrides=["features.goals=false"])) + [cmd] = seen + return cmd + + +def test_each_cli_run_calls_the_endpoint_through_a_relay_that_puts_the_env_date_in_its_model_calls(monkeypatch): + opened, closed = [], [] + + @contextlib.asynccontextmanager + async def relay(upstream, calls, **options): + opened.append((upstream, options)) + yield "http://127.0.0.1:9/token" + closed.append(upstream) + + monkeypatch.setenv("LITELLM_BASE_URL", "https://llm.example.com/v1/") + cmd = _cli_command(monkeypatch, relay) + + assert opened == [("https://llm.example.com", {"rewrite": codex_date.env_date_rewrite})] + assert closed == ["https://llm.example.com"] # however the run ends + assert cmd[-4:] == ["-c", "features.goals=false", + "-c", 'model_providers.litellm.base_url="http://127.0.0.1:9/token/openai/v1"'] + + +def test_without_an_endpoint_there_is_no_provider_to_relay_and_the_cli_runs_as_before(monkeypatch): + monkeypatch.delenv("LITELLM_BASE_URL", raising=False) + + assert _cli_command(monkeypatch, None)[-2:] == ["-c", "features.goals=false"] diff --git a/tst/unit/agents/codex/test_image_contract.py b/tst/unit/agents/codex/test_image_contract.py index 9c325d3c6..e36ec17d1 100644 --- a/tst/unit/agents/codex/test_image_contract.py +++ b/tst/unit/agents/codex/test_image_contract.py @@ -1,17 +1,21 @@ -"""The agent's folder is its build context: the Dockerfile copies only its own files, pins Node by its checksum and the -CLIs by package-lock.json, keeps TLS checks on, and installs the protocol at or above its floor, which a release -doesn't pin; install.sh brings the same Node and the same CLIs.""" +"""The agent's folder is its build context: the Dockerfile copies only its own files and those its +``shared_sources.toml`` takes from agent-env's sources, pins Node by its checksum and the CLIs by package-lock.json, +keeps TLS checks on, and installs the protocol at or above its floor, which a release doesn't pin; install.sh brings +the same Node and the same CLIs.""" from __future__ import annotations import ast import json import re +import tomllib from tst.unit.agents.codex.agent import AGENT_DIR DOCKERFILE = (AGENT_DIR / "Dockerfile").read_text() INSTALL_SH = (AGENT_DIR / "install.sh").read_text() +SOURCES = AGENT_DIR.parents[2] +SHARED = tomllib.loads((AGENT_DIR / "shared_sources.toml").read_text()) # Harbor bundles pin the same versions (agentenvhub-sdk's _DOC_TOOL_PACKAGES), so a task's documents read alike in both. @@ -23,13 +27,25 @@ 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) + assert {"a2a_server.py", "codex_bridge.py", "codex_config.py", "codex_date.py", "codex_kit.py", "entrypoint.sh", + "install.sh", "run.sh", "package.json", "package-lock.json"} <= set(copied) def _imported(path) -> set[str]: @@ -43,20 +59,28 @@ 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, the clock + page's format and the model relay 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", "model_relay/model_relay.py", "codex_date.py"} <= needed assert needed <= set(_copied()) and needed <= installed, (needed, installed) -def test_the_requirements_are_the_protocol_floor_the_config_writer_and_the_ca_bundle(): +def test_the_requirements_are_the_protocol_floor_the_config_writer_the_relays_http_and_the_ca_bundle(): requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() if line and not line.startswith("#")] - protocol, *others = requirements - assert re.fullmatch(r"agentenv-framework-protocol\[agent\]>=\d+\.\d+\.\d+", protocol), requirements - assert others == ["tomli-w==1.2.0", "certifi"], requirements + assert requirements == ["agentenv-framework-protocol[agent]>=0.1.643", "tomli-w==1.2.0", "aiohttp>=3.9,<4", + "certifi"] def test_the_image_gives_the_models_python_the_document_libraries(): @@ -100,5 +124,12 @@ 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) + + +def test_the_clis_state_stays_under_the_agents_home_whatever_the_uid(): + env = dict(re.findall(r"(\w+)=(\S+)", re.search(r"^ENV (.+)$", DOCKERFILE, re.MULTILINE).group(1))) + + assert env["CODEX_HOME"] == "/home/agent/.codex" + assert "chown agent:agent /app /home/agent/.codex" in DOCKERFILE diff --git a/tst/unit/agents/codex/test_message_contract.py b/tst/unit/agents/codex/test_message_contract.py index cbdeda03f..d93a23549 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_urls": [], } diff --git a/tst/unit/agents/letta_code/test_env_clock.py b/tst/unit/agents/letta_code/test_env_clock.py index 20fc18026..64dd1ff88 100644 --- a/tst/unit/agents/letta_code/test_env_clock.py +++ b/tst/unit/agents/letta_code/test_env_clock.py @@ -14,7 +14,7 @@ import pytest -from tst.unit.agents.letta_code.agent import AGENT_DIR, a2a_server, agent_egress +from tst.unit.agents.letta_code.agent import a2a_server, agent_egress from tst.unit.agents.letta_code.agent import letta_code_bridge as bridge PROXY = "http://127.0.0.1:3128" @@ -177,24 +177,3 @@ async def upload(self, name, path): 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/opencode/test_env_clock.py b/tst/unit/agents/opencode/test_env_clock.py index eabbb6ff0..85a549ae9 100644 --- a/tst/unit/agents/opencode/test_env_clock.py +++ b/tst/unit/agents/opencode/test_env_clock.py @@ -9,11 +9,10 @@ import asyncio import contextlib -import subprocess import pytest -from tst.unit.agents.opencode.agent import AGENT_DIR, agent_egress, opencode_bridge, opencode_date +from tst.unit.agents.opencode.agent import agent_egress, opencode_bridge, opencode_date PROXY = "http://127.0.0.1:3128" @@ -90,25 +89,3 @@ def test_the_envs_plain_http_mcp_servers_are_reached_directly_and_https_ones_thr clock_armed=True) assert "gateway" in _direct(env) and "abc-123.w.modal.host" not in _direct(env) - - -def test_start_agent_keeps_a_providers_ca_bundle_trusted_by_the_server_and_the_proxy(tmp_path): - """Sail points SSL_CERT_FILE and the like at the bundle it signs model requests under; root.conf points the server - at agent-env's bundles, so start-agent adds the provider's to them and to the proxy's roots, once each.""" - 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/opencode/test_opencode_date.py b/tst/unit/agents/opencode/test_opencode_date.py index 64b3c5af2..862f30c2e 100644 --- a/tst/unit/agents/opencode/test_opencode_date.py +++ b/tst/unit/agents/opencode/test_opencode_date.py @@ -6,7 +6,6 @@ import asyncio import json -import os import subprocess import time @@ -15,6 +14,7 @@ from aiohttp import web from tst.unit.agents.opencode.agent import model_relay, opencode_date +from tst.util import fake_date # OpenCode's system prompt as its SystemPrompt.environment writes it (opencode-ai 1.17.18, src/session/system.ts). ENV_BLOCK = ("Here is some useful information about the environment you are running in:\n\n" @@ -37,23 +37,10 @@ def _call(system=SYSTEM, *, parts=False, tools=True, user=SYSTEM) -> dict: @pytest.fixture def env_clock(tmp_path, monkeypatch): - """An armed clock, in UTC, whose time a stand-in ``date`` prints (``FAKE_DATE_OUT``; it fails without one) before - it exits (``FAKE_DATE_EXIT``), recording the environment it got.""" - bin_dir = tmp_path / "bin" - bin_dir.mkdir() - (bin_dir / "date").write_text('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\n[ "$1" = "+%s %N" ] || exit 2\n' - '[ -n "$FAKE_DATE_SLEEP" ] && sleep "$FAKE_DATE_SLEEP"\n' - '[ -n "$FAKE_DATE_KID" ] && { sleep 30 & echo $! > "$FAKE_DATE_KID"; }\n' - '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n' - 'exit "${FAKE_DATE_EXIT:-0}"\n') - (bin_dir / "date").chmod(0o755) - monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}") - monkeypatch.setenv("FAKE_DATE_ENV", str(tmp_path / "date.env")) - monkeypatch.setenv("AGENTENV_REAL_TIME", "1") - monkeypatch.setenv("TZ", "UTC") - time.tzset() + """An armed clock, in UTC, whose time the stand-in ``date`` prints (tst/util/fake_date.py).""" + recorded = fake_date.install(tmp_path, monkeypatch) monkeypatch.setattr(opencode_date, "clock_armed", lambda: True) - yield tmp_path / "date.env" + yield recorded monkeypatch.undo() time.tzset() @@ -185,12 +172,13 @@ def test_a_date_that_cant_be_read_refuses_the_call_rather_than_tell_the_model_re def test_a_date_that_exits_leaving_a_process_on_its_output_is_refused_and_that_process_killed(env_clock, monkeypatch, tmp_path): - """The date has exited, so only its session's group still reaches what it left holding the pipes.""" - monkeypatch.setattr(opencode_date, "_DATE_TIMEOUT_S", 1) + """The date has exited, so only its session's group still reaches what it left holding the pipes. The timeout + leaves a loaded machine time to start the stand-in and its child.""" + monkeypatch.setattr(opencode_date, "_DATE_TIMEOUT_S", 3) monkeypatch.setenv("FAKE_DATE_OUT", "1801742400 000000000") monkeypatch.setenv("FAKE_DATE_KID", str(tmp_path / "kid")) - with pytest.raises(opencode_date.Refusal, match="date gave no answer within 1 s"): + with pytest.raises(opencode_date.Refusal, match="date gave no answer within 3 s"): _rewrite(_call()) kid, deadline = (tmp_path / "kid").read_text().strip(), time.monotonic() + 5 diff --git a/tst/unit/agents/test_agent_clock_images.py b/tst/unit/agents/test_agent_clock_images.py index 14dda4af8..17214bef4 100644 --- a/tst/unit/agents/test_agent_clock_images.py +++ b/tst/unit/agents/test_agent_clock_images.py @@ -207,3 +207,29 @@ def test_every_clocked_image_copies_the_shared_module_and_the_page_format_beside folders = _copied_to((AGENTS_DIR / agent / "Dockerfile").read_text()) assert set.intersection(*(folders.get(name, set()) for name in (*_bridges(agent), *SHARED_FILES))), folders + + +# Their start-agent adds a provider's CA bundle to agent-env's; Claude Code's doesn't yet. +CA_MERGING = ["antigravity", "codex", "letta-code", "opencode"] + + +@pytest.mark.parametrize("agent", CA_MERGING) +def test_start_agent_keeps_a_providers_ca_bundle_trusted_by_the_server_and_the_proxy(agent, 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 = (AGENTS_DIR / agent / "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/util/fake_date.py b/tst/util/fake_date.py new file mode 100644 index 000000000..0f2342e9d --- /dev/null +++ b/tst/util/fake_date.py @@ -0,0 +1,29 @@ +"""A stand-in ``date`` for the tests of the clocked agents' date rewrites (opencode_date, codex_date), which read the +env's time from a ``date`` the A2A server starts: it prints ``FAKE_DATE_OUT`` (and fails without one), sleeps +``FAKE_DATE_SLEEP`` first, leaves a child holding its output when ``FAKE_DATE_KID`` names a file for its pid, and exits +``FAKE_DATE_EXIT``, recording the environment it got.""" + +import os +import time +from pathlib import Path + +SCRIPT = ('#!/bin/sh\nenv > "$FAKE_DATE_ENV"\n[ "$1" = "+%s %N" ] || exit 2\n' + '[ -n "$FAKE_DATE_SLEEP" ] && sleep "$FAKE_DATE_SLEEP"\n' + '[ -n "$FAKE_DATE_KID" ] && { sleep 30 & echo $! > "$FAKE_DATE_KID"; }\n' + '[ -n "$FAKE_DATE_OUT" ] || { echo no clock >&2; exit 1; }\necho "$FAKE_DATE_OUT"\n' + 'exit "${FAKE_DATE_EXIT:-0}"\n') + + +def install(tmp_path: Path, monkeypatch) -> Path: + """Put the stand-in first on PATH, with the server's real-time marker set and the zone UTC; the file the stand-in + records its environment in, there once it has run. The caller undoes ``monkeypatch`` and calls ``time.tzset()``.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + (bin_dir / "date").write_text(SCRIPT) + (bin_dir / "date").chmod(0o755) + monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}") + monkeypatch.setenv("FAKE_DATE_ENV", str(tmp_path / "date.env")) + monkeypatch.setenv("AGENTENV_REAL_TIME", "1") + monkeypatch.setenv("TZ", "UTC") + time.tzset() + return tmp_path / "date.env" diff --git a/tst/util/fake_responses.py b/tst/util/fake_responses.py new file mode 100644 index 000000000..3b5c3ac12 --- /dev/null +++ b/tst/util/fake_responses.py @@ -0,0 +1,129 @@ +"""A fake OpenAI Responses API endpoint, so an agent whose CLI speaks it (Codex) runs with no model key: ``POST +.../responses`` is answered by a responder as server-sent events, a message or a function call then the response's +completion with ``USAGE``, and every request is recorded.""" + +import json +import threading +import uuid +from collections.abc import Callable +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Final + +from tst.util.fake_openai import Seen, Text, ToolCall + +Responder = Callable[[dict], Text | ToolCall] + +USAGE: Final[dict] = {"input_tokens": 100, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 10, + "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 110} + + +def answer(text: str) -> Responder: + """Every request answered with ``text``.""" + return lambda body: Text(text) + + +def tool_then_answer(tool: str, arguments: dict, *, prefix: str = "") -> Responder: + """Call the request's tool named ``tool``, then answer with ``prefix`` and the call's output; answer ``prefix`` + alone to a request that offers no such tool.""" + + def respond(body: dict) -> Text | ToolCall: + result = tool_output(body) + if result is not None: + return Text(prefix + result) + names = {spec.get("name") for spec in body.get("tools") or [] if isinstance(spec, dict)} + return ToolCall(tool, arguments) if tool in names else Text(prefix) + + return respond + + +def tool_output(body: dict) -> str | None: + """The output of the latest function call since the request's last user message, else None.""" + found = None + for item in body.get("input") or []: + if not isinstance(item, dict): + continue + if item.get("type", "message") == "message" and item.get("role") == "user": + found = None + elif item.get("type") == "function_call_output": + output = item.get("output") + found = ("".join(part.get("text", "") for part in output if isinstance(part, dict)) + if isinstance(output, list) else output if isinstance(output, str) else json.dumps(output)) + return found + + +@dataclass(slots=True) +class FakeResponses: + host: str = "127.0.0.1" + respond: Responder = field(default_factory=lambda: answer("ok")) + seen: list[Seen] = field(default_factory=list) + _server: ThreadingHTTPServer | None = None + + @property + def url(self) -> str: + return f"http://{self.host}:{self._server.server_address[1]}" + + def calls(self) -> list[Seen]: + return [seen for seen in self.seen if seen.path.split("?")[0].endswith("/responses")] + + def tool_results(self) -> list[str]: + return [text for seen in self.calls() if (text := tool_output(seen.body)) is not None] + + def __enter__(self) -> "FakeResponses": + fake = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args) -> None: + pass + + def do_GET(self) -> None: + self._send(404, {"error": {"message": f"no route {self.path}"}}) + + def do_POST(self) -> None: + length = int(self.headers.get("content-length") or 0) + body = json.loads(self.rfile.read(length) or b"{}") + fake.seen.append(Seen(self.path, {k.lower(): v for k, v in self.headers.items()}, body)) + if not self.path.split("?")[0].endswith("/responses"): + self._send(404, {"error": {"message": f"no route {self.path}"}}) + return + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.end_headers() + try: + for event in _events(fake.respond(body)): + self.wfile.write(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode()) + except (BrokenPipeError, ConnectionResetError): + pass + + def _send(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() + try: + self.wfile.write(data) + except (BrokenPipeError, ConnectionResetError): + pass + + self._server = ThreadingHTTPServer((self.host, 0), Handler) + 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() + + +def _events(reply: Text | ToolCall) -> list[dict]: + response_id = f"resp_{uuid.uuid4().hex[:12]}" + if isinstance(reply, Text): + item = {"type": "message", "role": "assistant", "id": f"msg_{uuid.uuid4().hex[:12]}", + "content": [{"type": "output_text", "text": reply.text}]} + else: + item = {"type": "function_call", "id": f"fc_{uuid.uuid4().hex[:12]}", "call_id": f"call_{uuid.uuid4().hex[:12]}", + "name": reply.name, "arguments": json.dumps(reply.arguments)} + return [{"type": "response.created", "response": {"id": response_id}}, + {"type": "response.output_item.done", "output_index": 0, "item": item}, + {"type": "response.completed", "response": {"id": response_id, "usage": USAGE}}]