Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
63 commits
Select commit Hold shift + click to select a range
ae1d4be
feat(agents): agents follow the env's clock the way computers do (FD-…
williamloo-scale Nov 16, 2026
eea933c
refactor(agents): leave the Claude Code image to its own PR; agents s…
williamloo-scale Nov 17, 2026
608a93d
Merge origin/main
williamloo-scale Nov 17, 2026
182cef0
feat(agents): the Claude Code image follows the env's clock (FD-5916)
williamloo-scale Nov 17, 2026
bce00d4
fix(agents): agent clock review: new config's status, one clock per a…
williamloo-scale Nov 17, 2026
84381b8
fix(agents): keep each agent's clock record on a key of its own; a re…
williamloo-scale Nov 17, 2026
56dac45
fix(agents): agent clock keys can't collide; one clock env per agent;…
williamloo-scale Nov 17, 2026
c726743
chore: drop test run output committed by mistake
williamloo-scale Nov 17, 2026
5e8c756
Merge #714
williamloo-scale Nov 17, 2026
3b6f499
test(agents): the Claude Code image follows the env's clock end to en…
williamloo-scale Nov 17, 2026
cecc686
fix(agents): a failed agent sync retires its follower; the task's zon…
williamloo-scale Nov 17, 2026
afe55b4
Merge origin/main
williamloo-scale Nov 17, 2026
d523a6e
Merge #714
williamloo-scale Nov 17, 2026
ac0a39e
fix(agents): libfaketime's init can't deadlock the CLI; the CLI goes …
williamloo-scale Nov 17, 2026
c8ed6e1
fix(agents): a later clock sync leaves agents teardown_sandboxes took…
williamloo-scale Nov 17, 2026
b5d3b4b
fix(ci): the agent clock e2e skips as a declared capability gap; the …
williamloo-scale Nov 17, 2026
25af21a
chore: drop test-run output committed again, and ignore where the pro…
williamloo-scale Nov 17, 2026
7216c7c
fix(agents): route the CLI through egress by the clock page's armed f…
williamloo-scale Nov 17, 2026
fc3134b
Merge #714
williamloo-scale Nov 17, 2026
f8bd9ff
feat(a2a-agent): validate clock/v1 by the time the agent's own comman…
earakely-scale Nov 17, 2026
f9af1b6
refactor(a2a-agent): name the clock validation's timeouts and error l…
williamloo-scale Nov 17, 2026
43fdb97
fix(gateway): get_time says the machine's clock may not be synchroniz…
earakely-scale Nov 18, 2026
8bf8e4c
refactor(a2a-agent): move agent_clock to a2a_agent/clock.py, beside t…
earakely-scale Nov 18, 2026
810f42e
Merge #714
williamloo-scale Nov 18, 2026
686fdf1
test(agents): the agent clock e2e imports FOLLOWING_KEY from a2a_agen…
williamloo-scale Nov 18, 2026
9d7d6c0
Merge origin/main (#714 merged)
williamloo-scale Nov 18, 2026
1ff90bd
fix(agents): the Claude Code image installs protocol 0.1.575, the fir…
earakely-scale Nov 18, 2026
ca97b37
fix(computers): the clock follower follows a changed config while its…
earakely-scale Nov 18, 2026
0875e06
fix(agents): an armed clock keeps the agent's own NO_PROXY hosts dire…
williamloo-scale Nov 18, 2026
bb4f07f
test(agents): the agent clock checks run over every clocked agent ima…
williamloo-scale Nov 18, 2026
db76619
feat(agents): the pi image follows the env's clock (FD-5916)
williamloo-scale Nov 18, 2026
fef5804
fix(agents): pi's supervisord gets setuptools, whose pkg_resources su…
williamloo-scale Nov 18, 2026
a3f9e34
Merge main into #726: the clock and egress proxy now live in utils (#…
earakely-scale Nov 18, 2026
3c60fda
refactor(agents): the Claude Code image takes the clock and egress pr…
earakely-scale Nov 18, 2026
c5c4c3f
Merge #726: the clock and egress proxy come from utils
williamloo-scale Nov 18, 2026
150c563
test(agents): Claude Code's contract test takes the folders shared_so…
williamloo-scale Nov 18, 2026
4d17529
refactor(agents): the image takes the clock and egress proxy from uti…
williamloo-scale Nov 18, 2026
35bf07b
Merge #726
williamloo-scale Nov 18, 2026
aed27ee
fix(agents): a private HTTPS model endpoint is reached directly on an…
williamloo-scale Nov 18, 2026
0f4d1fd
fix(agents): a private HTTPS model endpoint is reached directly on an…
williamloo-scale Nov 18, 2026
032d11e
Merge #726
williamloo-scale Nov 18, 2026
590e3b1
test(agents): the clock test's HTTPS model hosts resolve publicly wit…
williamloo-scale Nov 18, 2026
a6f3720
fix(agents): the model host's lookup is bounded and kept, so a slow r…
williamloo-scale Nov 18, 2026
5b241d1
fix(agents): the model host's lookup is bounded and kept, as #726's is
williamloo-scale Nov 18, 2026
6fffd85
Merge #726
williamloo-scale Nov 18, 2026
4cf8922
Merge main (#726 merged)
williamloo-scale Nov 18, 2026
140eda8
refactor(agents): follow the merged Claude Code image (#726): the pro…
williamloo-scale Nov 18, 2026
32b1b56
fix(agents): keep a provider's CA bundle trusted, and send HTTPS MCP …
williamloo-scale Nov 18, 2026
e348853
Merge main: the control token (#780, #784)
williamloo-scale Nov 19, 2026
82c6e22
Merge remote-tracking branch 'origin/main' into wloo/pi-clock-image
williamloo-scale Nov 19, 2026
4f88129
Merge remote-tracking branch 'origin/main' into wloo/pi-clock-image
williamloo-scale Nov 19, 2026
a4e9b4b
refactor(pi): take the shared egress rule (#818)
williamloo-scale Nov 19, 2026
fffdf44
Merge remote-tracking branch 'origin/main' into wloo/pi-clock-image
williamloo-scale Nov 20, 2026
1ba2b19
Merge remote-tracking branch 'origin/main' into wloo/pi-clock-image
earakely-scale Nov 20, 2026
46e1b48
fix(agents): pi stays on real time while the commands it runs follow …
earakely-scale Nov 20, 2026
9bf18b3
build(agents): pi's install checks Node against its published checksu…
earakely-scale Nov 20, 2026
6e00710
docs(agents): the pi README builds from the build context and says ho…
earakely-scale Nov 20, 2026
b68eeab
fix(agents): the bridge hands pi's script to node, so the real-time m…
earakely-scale Nov 20, 2026
9c06371
fix(agents): an installed pi gets the shared modules beside its bridg…
earakely-scale Nov 20, 2026
8e9a7c8
Merge remote-tracking branch 'origin/main' into wloo/pi-clock-image
earakely-scale Nov 20, 2026
18f7e64
test(agents): pi's clock row checks that pi, started as the bridge st…
earakely-scale Nov 20, 2026
8f5df2b
Merge remote-tracking branch 'origin/main' into wloo/pi-clock-image
earakely-scale Nov 21, 2026
68f14c4
fix(agents): the pi container exits when its A2A server does, as on main
earakely-scale Nov 21, 2026
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
12 changes: 7 additions & 5 deletions src/agent_env/agents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,14 @@ neither, Alpine's for one, gets bash from its own package manager. The agent wor
or in `/app` on the host.

`agents/pi/` runs the [pi coding agent](https://github.com/earendil-works/pi/tree/main/packages/coding-agent) behind
the protocol's A2A agent framework: each turn is one `pi --mode json` run, the task env's MCP servers go to its
`mcp.json`, and its JSON events are the turn's trajectory. Name it as `pi`, its alias, or by its id,
`@local/agentenv-framework/agents/pi`. It calls
the protocol's A2A agent framework: each turn is one `pi --mode json` run, started as `node /opt/pi/bin/pi`, the task
env's MCP servers go to its `mcp.json`, and its JSON events are the turn's trajectory. Name it as `pi`, its alias, or by
its id, `@local/agentenv-framework/agents/pi`. It calls
the `[model]` endpoint as an OpenAI-compatible one and takes its model from the prompt, so its smoke task needs
`[model] default` (or the `agent` role) set. It declares `install/v1` too, for Debian or Ubuntu targets.
Its folder's `README.md` covers the extensions it implements.
`[model] default` (or the `agent` role) set. It declares `install/v1` too, for Debian or Ubuntu targets. Its image can
follow a task env's clock as Claude Code's does, opted in the same way, except that pi itself stays on real time and
only the commands it runs for the model follow the clock. Its folder's `README.md` says why, and covers the extensions
it implements.

`agents/codex/` runs OpenAI's [Codex CLI](https://github.com/openai/codex) behind the protocol's A2A agent framework:
each turn is one `codex exec --json` run, resumed in the context's Codex thread, the task env's MCP servers go to its
Expand Down
46 changes: 43 additions & 3 deletions src/agent_env/agents/agents/pi/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,13 +1,53 @@
# docker build -t pi-a2a src/agent_env/agents/agents/pi
# The env's clock: the egress proxy, one static Go binary, and agent-env's libfaketime and its TLS shim, taken from
# agent-env's sources as clock/ and egress/ (shared_sources.toml) and built for this image's libc (Ubuntu 24.04's, on
# the image's own base) in stages of their own, so no toolchain is left in the image.
FROM public.ecr.aws/docker/library/golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS egress
COPY egress/ /egress/
RUN cd /egress && go vet ./... && go test -count=1 ./... \
&& CGO_ENABLED=0 GOFLAGS=-mod=readonly go build -trimpath -ldflags=-s -o /out/egress .

FROM mirror.gcr.io/library/ubuntu:24.04@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55 AS clock
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
build-essential patch curl ca-certificates
COPY clock/ /clock/
RUN sh /clock/build.sh /out

FROM mirror.gcr.io/library/ubuntu:24.04@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55
WORKDIR /app
# Named sources: agent-env packs the build context install/v1 copies from the COPY sources.
COPY a2a_server.py changelog.py install.sh peers.py pi_agent.py requirements.txt start.sh ./
# Every clocked agent's egress rule, which the bridge imports, and the clock page's format it reads (shared_sources.toml).
COPY agent_clock/agent_egress.py clock/clockpage.py ./
RUN sh install.sh \
&& useradd --create-home agent \
&& mkdir /workspace \
&& chown agent /app /workspace
# The env's clock: the follower and the egress proxy, each as its own user, under root's supervisord (root.conf), and
# agent-env's libfaketime and its TLS shim preloaded into every process, faking only the agent's (clock.conf). The
# follower's config is the agent's user's to write (agentenv_protocol.a2a_agent.clock) and the follower's to read.
# supervisord goes into the agent's venv, whose bin is on the PATH start-agent runs with.
# supervisor 4.2.5 imports pkg_resources, which a Python 3.12 venv doesn't carry: setuptools before 81 brings it.
RUN /opt/pi-a2a-venv/bin/pip install --no-cache-dir supervisor==4.2.5 'setuptools<81' \
&& useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin agentenv-clock \
&& useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin agentenv-egress \
&& mkdir -p /usr/local/lib/agentenv-clock /usr/local/lib/agentenv-egress /etc/agentenv \
&& install -d -o agent -g agentenv-clock -m 2750 /etc/agentenv/clock \
&& touch /etc/agentenv/ca.pem \
&& cp /etc/ssl/certs/ca-certificates.crt /etc/agentenv/ca-bundle.pem \
&& cp /etc/ssl/certs/ca-certificates.crt /usr/local/lib/agentenv-egress/roots.pem
COPY --from=clock /out/libfaketimeMT.so.1 /out/libtls_realtime.so /usr/local/lib/agentenv-clock/
COPY --from=egress /out/egress /usr/local/lib/agentenv-egress/egress
COPY clock/clockpage.py clock/clock-follower /usr/local/lib/agentenv-clock/
COPY clock/clock.conf /etc/agentenv/clock.conf
COPY root.conf /etc/agentenv/root.conf
COPY start-agent /usr/local/bin/start-agent
RUN sed -i -e "s/^AGENTENV_SESSION_UID=.*/AGENTENV_SESSION_UID=$(id -u agent)/" \
-e "s/^AGENTENV_CLOCK_PAGE_UID=.*/AGENTENV_CLOCK_PAGE_UID=$(id -u agentenv-clock)/" /etc/agentenv/clock.conf \
&& chmod 0755 /usr/local/lib/agentenv-clock/clock-follower /usr/local/bin/start-agent \
&& printf '%s\n' /usr/local/lib/agentenv-clock/libfaketimeMT.so.1 /usr/local/lib/agentenv-clock/libtls_realtime.so \
> /etc/ld.so.preload
ENV PATH="/opt/pi-a2a-venv/bin:/opt/pi/bin:/opt/node/bin:${PATH}"
USER agent
EXPOSE 8000
CMD ["python3", "a2a_server.py"]
# Starts as root, which start-agent needs for the clock; the A2A server and pi run as the agent's user. CMD rather
# than ENTRYPOINT: Modal passes a sandbox's env to the image's CMD only.
CMD ["/usr/local/bin/start-agent"]
56 changes: 47 additions & 9 deletions src/agent_env/agents/agents/pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

The [pi coding agent](https://github.com/earendil-works/pi/tree/main/packages/coding-agent) wrapped
with the `agentenv_protocol.a2a_agent` framework, shipped in the `agents` bundle as
`@local/agentenv-framework/agents/pi`. This directory is the whole build context: the
protocol package comes from PyPI (`requirements.txt`), and `install.sh` installs Node, pi and the
agent's environment both for the image and for `install/v1`.
`@local/agentenv-framework/agents/pi`. Its build context is this directory and what its `shared_sources.toml`
takes from agent-env's own sources: the clock library (`clock/`), the egress proxy (`egress/`) and the egress rule
every clocked agent shares (`agent_clock/`). The protocol package comes from PyPI (`requirements.txt`), and
`install.sh` installs Node, pinned by version and checksum, pi and the agent's environment, both for the image and for
`install/v1`.

Each task runs `pi --mode json` once in its workspace: `PI_A2A_WORKSPACE`, default `/workspace`, and the task
container's working directory when it's installed there. The prompt goes in on stdin. Images and text
files are attached as `@path`; any other file is saved to disk and its path is added to the prompt,
for pi's tools to use. A file fetched from a URL may be at most 256 MiB. The pi config dir is built fresh for each task:
Each task runs `pi --mode json` once, as `node /opt/pi/bin/pi --mode json`, in its workspace: `PI_A2A_WORKSPACE`,
default `/workspace`, and the task container's working directory when it's installed there. The prompt goes in on
stdin. Images and text files are attached as `@path`; any other file is saved to disk and its path is added to the
prompt, for pi's tools to use. A file fetched from a URL may be at most 256 MiB. The pi config dir is built fresh for
each task:

- `models.json` points provider `agentenv` at `LITELLM_BASE_URL`. The key stays a `${LITELLM_API_KEY}`
reference, so it is never written to disk.
Expand All @@ -28,7 +31,7 @@ Sessions live in `~/.pi-a2a/sessions` and skills in `~/.pi-a2a/skills/<name>`.
| `snapshot/v1` | `save` uploads the context's pi session (JSONL) and, when asked, the workspace as a gzipped tar; `load` replaces the workspace's contents with the saved ones (extracted aside first, so an archive that fails to extract changes nothing), restores the session and binds it to the target context |
| `snapshot/v1` changelog | after enable, every tool result builds `NNNNNN.tar`: the files that changed under the roots, the deleted paths and the session so far. Increments upload in order; a failed one is kept, with those after it, and retried at the next tool result and when the task ends, which fails as `pi.changelog_incomplete` if any is still not uploaded. Past 256 MiB held by failed uploads, they are dropped and capture stops, so every later task fails that way until the changelog is enabled again. `apply` replays them in order, writing only under the replaying agent's own roots (symlinks resolved), and with `resume_conversation` binds the last session to the target context |
| `peer-agents/v1` | setting peers registers a loopback MCP server (`peers` at `http://127.0.0.1:$A2A_PORT/mcp`) whose `peer_list` and `peer_send_message` tools send A2A messages, one conversation per A2A context and peer. It answers only loopback clients that send a running task's token, which each task gets in its environment and pi sends as a header, so a task speaks only in its own context's conversations. A peer on the host's loopback is retried at `host.docker.internal` |
| `install/v1` | copies this directory into the task container as `/opt/pi-a2a`, runs `install.sh` (Debian or Ubuntu, as root, with network access), writes the LiteLLM credentials to a 0600 `agent.env` through a heredoc and starts `start.sh`, which sources it. The credentials stay off each command's first line, the only one the installer logs, but core's install contract substitutes them into the script text, so a sandbox that logs whole scripts records them |
| `install/v1` | unpacks the build context into the task container as `/opt/pi-a2a`, runs `install.sh` (Debian or Ubuntu, as root, with network access), which also copies the shared egress rule and the clock page's format beside the bridge, as the image does, writes the LiteLLM credentials to a 0600 `agent.env` through a heredoc and starts `start.sh`, which sources it. An installed agent doesn't follow the env's clock: the target runs neither the follower nor agent-env's libfaketime. The credentials stay off each command's first line, the only one the installer logs, but core's install contract substitutes them into the script text, so a sandbox that logs whole scripts records them |
| `triggers/v1` | SDK default |

Model requests carry `model_params`, merged into the request body through pi's `samplingParams`. agent-env
Expand All @@ -51,12 +54,47 @@ An installed agent is started without registration env vars, so it does not get

Snapshot `load` and changelog `apply` answer 409 while a task is running, and tasks and snapshot saves wait while either restores the workspace.

## The env's clock

The image can follow a task env's clock as the other clocked agent images do (`src/agent_env/agents/README.md`):
root's supervisord (`start-agent`, `root.conf`) runs the clock follower and the egress proxy, each as its own user,
and the A2A server as `agent` with the real-time marker, and agent-env's libfaketime is preloaded for `agent`.

- **Off by default.** Without `agent_clock` on `sync_env_clock`, pi and every command it runs keep real time and go
out directly, and the model reads the env's time from the gateway's `get_time`.
- **Opted in, the commands follow.** Once the agent follows an armed clock, every command pi runs for the model reads
the env's time: `date`, `datetime.now()` and the timestamps its programs write. Files keep real modification times,
as libfaketime is built without faking `stat`.
- **pi itself stays on real time.** The bridge starts pi with the real-time marker, which libfaketime takes out of
pi's environment, so what pi starts follows the clock (`cli_env`); pi's `/proc/<pid>/environ`, its environment as
it started, shows the marker rewritten in place as `AGENTENV_REAL_TIME=0`. It hands pi's script to `node` itself
(`PI_COMMAND`): run through its `#!/usr/bin/env node`, `env` would take the marker and start node without it. pi
can't follow the clock: before 1970 its compaction throws, as it makes a UUIDv7 from its clock, and its file locks
compare its clock with their modification times.
pi 1.1.0's own prompt carries no date (pi dropped it upstream), so nothing pi shows the model gives another time
than the env's; its trajectory's timestamps and its timings are real time.
- **Through the egress proxy.** While the clock is armed, pi and its commands go out by the rule every clocked agent
shares (`agent_egress.egress_env`): every TLS host through the egress proxy, except loopback (the peers MCP server),
`host.docker.internal`, the hosts `NO_PROXY` names and hosts reached by plain HTTP alone. pi honours `HTTP_PROXY`,
`HTTPS_PROXY` and `NO_PROXY` itself, its model and MCP calls alike; Node programs the model runs do through
`NODE_USE_ENV_PROXY`, which Node honours from 22.21.
- **The changelog needs no change.** Capture compares each file's modification time, size and mode with the previous
scan's, never with a clock, and writes each increment's tar itself, in the server on real time; it runs no `tar`.

Started as a user other than root, the image runs the A2A server alone, on real time, as before.

## Usage, errors and building

Usage is summed over the assistant messages. `cost_usd` is only reported when the model has `cost`
metadata, and the generated `models.json` sets none. A `stopReason` of `error` is an `infra_error`
(`pi.model_error`), `aborted` is an `agent_error`, and a timeout kills pi's process group.

`agent-env a2a-agent put`, as above, builds the image from its build context, shared sources included. A plain
`docker build` of this directory lacks them; to build the image alone:

```bash
docker build -t pi-a2a src/agent_env/agents/agents/pi
python -c 'from pathlib import Path; from agent_env.utils.docker.build import build_image
d = Path("src/agent_env/agents/agents/pi"); build_image(d / "Dockerfile", d, "pi-a2a", platform=None)'
docker run -p 8000:8000 -e LITELLM_BASE_URL=... -e LITELLM_API_KEY=... pi-a2a
pytest tst/unit/agents/pi
```
20 changes: 16 additions & 4 deletions src/agent_env/agents/agents/pi/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
# Installs Node, pi and this agent's Python environment on Debian or Ubuntu, as root. The image build and
# install/v1 both run it, so an install into a task container matches the image.
set -eu
NODE_VERSION=22.19.0
NODE_VERSION=22.23.3
# nodejs.org's SHASUMS256.txt for node-v$NODE_VERSION-linux-<arch>.tar.xz.
NODE_SHA256_X64=df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de
NODE_SHA256_ARM64=a44aeb94849a299b22df10b9e622ec2f605c2183501bc40590705131de7c740f
PI_VERSION=1.1.0
here=$(cd "$(dirname "$0")" && pwd)

Expand All @@ -12,14 +15,23 @@ apt-get install -y --no-install-recommends ca-certificates curl git python3 pyth
rm -rf /var/lib/apt/lists/*

case "$(uname -m)" in
x86_64) arch=x64 ;;
aarch64 | arm64) arch=arm64 ;;
x86_64) arch=x64 node_sha256=$NODE_SHA256_X64 ;;
aarch64 | arm64) arch=arm64 node_sha256=$NODE_SHA256_ARM64 ;;
*) echo "unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac
curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-${arch}.tar.xz" | tar -xJ -C /opt
node_archive=$(mktemp)
curl -fsSL --retry 3 -o "$node_archive" "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-${arch}.tar.xz"
echo "$node_sha256 $node_archive" | sha256sum -c -
tar -xJf "$node_archive" -C /opt
rm -f "$node_archive"
ln -sfn "/opt/node-v${NODE_VERSION}-linux-${arch}" /opt/node
PATH="/opt/node/bin:$PATH" npm install --global --prefix /opt/pi --ignore-scripts \
"@earendil-works/pi-coding-agent@${PI_VERSION}"

python3 -m venv /opt/pi-a2a-venv
/opt/pi-a2a-venv/bin/pip install --no-cache-dir -r "$here/requirements.txt"
# install/v1 unpacks the build context, which keeps the shared egress rule and the clock page's format in the folders
# shared_sources.toml takes them as; the bridge imports them from beside it, where the image's build copies them.
if [ -d "$here/agent_clock" ]; then
cp "$here/agent_clock/agent_egress.py" "$here/clock/clockpage.py" "$here/"
fi
24 changes: 22 additions & 2 deletions src/agent_env/agents/agents/pi/pi_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
from starlette.exceptions import HTTPException
from starlette.routing import Route

from agent_egress import EGRESS_PROXY_ENV, clock_armed, egress_env
from changelog import ChangelogCapture, apply as apply_increment
from peers import Peers

Expand All @@ -89,6 +90,12 @@
# The peer MCP server's header naming the run, whose value pi reads from its environment, never from disk.
PEER_RUN_HEADER = "X-Pi-A2A-Run"
PEER_RUN_ENV = "AGENTENV_MCP_PEER_RUN"
# agent-env's libfaketime keeps a process started with this marker on real time and takes it out of the process's
# environment, so every process that one starts reads the env's clock.
REAL_TIME_ENV = "AGENTENV_REAL_TIME"
# pi's script handed to node rather than run by its ``#!/usr/bin/env node``: the marker reaches only the process it's
# started with, and env would start node without it. install.sh installs pi here for the image and install/v1 alike.
PI_COMMAND = ("node", "/opt/pi/bin/pi")
# Deltas are reconstructible from the message_end records, so they are left out of the trajectory.
_UNRECORDED_EVENTS = frozenset({"message_update", "tool_execution_update"})
# A context id passes through as its session id only when it has none of pi's ``.`` and ``_``; every derived id
Expand Down Expand Up @@ -201,6 +208,19 @@ def _mcp_json(
return {"mcpServers": servers}, env


def cli_env(environ: Mapping[str, str], base_url: str, mcp_servers: Mapping[str, Any] | None = None, *,
armed: bool = False) -> dict[str, str]:
"""The pi CLI's environment, before its run's own variables: this process's; where the image runs the env's clock,
the real-time marker, so pi stays on real time while every command it runs follows the clock; and on an ``armed``
clock the egress proxy (``egress_env``) for the model endpoint, the env's MCP servers and those commands.

pi itself can't follow the clock: before 1970 its compaction throws (UUIDv7), and its file locks compare its clock
with their modification times. It shows the model no date of its own, so the model reads the env's time alone."""
urls = [base_url, *(str(entry.get("url") or "") for entry in (mcp_servers or {}).values())]
real_time = {REAL_TIME_ENV: "1"} if EGRESS_PROXY_ENV in environ else {}
return {**environ, **real_time, **egress_env(environ, urls, armed=armed)}


def _prompt_text(parts: Sequence[Any], unattached: Sequence[tuple[Path, str]]) -> str:
chunks = []
for part in parts:
Expand Down Expand Up @@ -424,7 +444,7 @@ def __init__(
*,
home: Path | None = None,
workspace: Path | None = None,
pi_command: Sequence[str] = ("pi",),
pi_command: Sequence[str] = PI_COMMAND,
) -> None:
self.home = home or Path.home() / ".pi-a2a"
self.workspace = workspace or Path("/workspace")
Expand Down Expand Up @@ -528,7 +548,7 @@ async def _run_pi(
argv += [f"@{path}" for path in attached]

env = {
**os.environ,
**cli_env(os.environ, base_url, request.mcp_servers, armed=clock_armed()),
**mcp_env,
"PI_CODING_AGENT_DIR": str(agent_dir),
"PI_OFFLINE": "1",
Expand Down
Loading
Loading