Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/agent_env/agents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
49 changes: 44 additions & 5 deletions src/agent_env/agents/agents/codex/Dockerfile
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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"]
29 changes: 26 additions & 3 deletions src/agent_env/agents/agents/codex/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|---|---|
Expand All @@ -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 `<current_date>` 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 `<timezone>` 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
Expand Down
1 change: 1 addition & 0 deletions src/agent_env/agents/agents/codex/a2a_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
32 changes: 24 additions & 8 deletions src/agent_env/agents/agents/codex/codex_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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"]
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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())
Comment thread
earakely-scale marked this conversation as resolved.
Resolved
if project_id or task_id:
_record_attribution(project_id=project_id, task_id=task_id)
logger.info(
Expand All @@ -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,
Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading