diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md
index 0b6798057..3d37503af 100644
--- a/src/agent_env/agents/README.md
+++ b/src/agent_env/agents/README.md
@@ -61,7 +61,9 @@ The A2A server starts with the real-time marker, so it and its records stay on r
- **One rule for every clocked agent.** That rule is `agent_egress.py` in `utils/agent_clock`, which only agent images
take (`agent_clock = "utils/agent_clock"` in `shared_sources.toml`), so changing it rebuilds no computer base. The
bridge imports it, and the image and `install.sh` copy it beside the bridge with the clock's `clockpage.py`, whose
- layout and check it reads the page by, so every agent put on the clock, OpenCode's too, goes out the same way.
+ layout and check it reads the page by, so every agent put on the clock, OpenCode's and Gemini's too, goes out the
+ same way. Gemini's image follows the clock in its own way: its CLI stays on real time, and only the commands the
+ model runs follow the clock and go out by that rule, as its folder's `README.md` says.
Started as a user other than root, the image runs the A2A server alone, on real time, as before.
@@ -94,8 +96,9 @@ by its id, `@local/agentenv-framework/agents/gemini`. It calls the `[model]` end
`/gemini`, which a LiteLLM gateway serves, through a proxy in the agent that adds the run's attribution; a model
named with a provider prefix, such as `vertex_ai/...`, goes to `/v1/chat/completions` instead. It takes its
model from the prompt, so its smoke task needs `[model] default` (or the `agent` role) set. It declares `install/v1`
-too, into a container or onto a `vm` sandbox's Linux host, with glibc. Its folder's `README.md` covers the extensions
-it implements.
+too, into a container or onto a `vm` sandbox's Linux host, with glibc. Its image can follow a task env's clock, as
+Claude Code's does, once a `sync_env_clock` sets `agent_clock`. Its folder's `README.md` covers the extensions it
+implements and how it follows the clock.
`agents/opencode/` runs the [OpenCode](https://github.com/anomalyco/opencode) CLI behind the protocol's A2A agent
framework: each turn is one `opencode run --format json` run, resumed in the context's OpenCode session, the task env's
diff --git a/src/agent_env/agents/agents/gemini/Dockerfile b/src/agent_env/agents/agents/gemini/Dockerfile
index c2f7159ef..4a6e9fb4c 100644
--- a/src/agent_env/agents/agents/gemini/Dockerfile
+++ b/src/agent_env/agents/agents/gemini/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 Gemini CLI, checked against its published checksum; install.sh brings the same.
ARG NODE_VERSION=22.23.3
@@ -21,13 +35,37 @@ COPY requirements.txt model-requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt -r model-requirements.txt
# install.sh and run.sh are install/v1's: in the image, so they stay in its build context.
COPY a2a_server.py gemini_bridge.py gemini_changelog.py gemini_config.py gemini_kit.py entrypoint.sh install.sh run.sh ./
-# The CLI's cwd and file-tool boundary, /workspace, and its state, fixed so neither follows the uid: Modal runs the
-# image as root. /app is kept, empty and writable, for tasks that name it.
+# Every clocked agent's egress rule, which the bridge imports, and the clock page's format it reads (shared_sources.toml).
+COPY agent_clock/agent_egress.py clock/clockpage.py ./
+# The CLI's cwd and file-tool boundary, /workspace, and its state, fixed so neither follows the uid. /app is kept,
+# empty and writable, for tasks that name it.
RUN useradd --create-home --uid 10001 agent && mkdir -p /workspace/inputs /app /home/agent/.gemini \
&& chown agent:agent /workspace /workspace/inputs /app /home/agent/.gemini && 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 GEMINI_CLI_HOME=/home/agent GEMINI_CWD=/workspace
-USER agent
WORKDIR /workspace
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/gemini/README.md b/src/agent_env/agents/agents/gemini/README.md
index c455edc07..424642ffa 100644
--- a/src/agent_env/agents/agents/gemini/README.md
+++ b/src/agent_env/agents/agents/gemini/README.md
@@ -37,7 +37,43 @@ CLI by its last segment, and the proxy translates its generate calls to `/v1/cha
| `attribution-probe/v1` | the `project_id` and `task_id` the proxy last sent |
| `install/v1` | `install.sh`, into a task container (as root, the CLI working in `/workspace`) or onto a `vm` sandbox's Linux host: Node and uv checked against their checksums, the CLI from `package-lock.json` and the agent's requirements in a Python of its own, which the target's own Node and Python are never replaced by; the model's commands get the agent's where the target has none. Node's builds need glibc |
| `triggers/v1` | SDK default |
+| `clock/v1` | the framework's `sync_time`, in the image, which runs the clock follower |
The image is `python:3.11-slim` with Node, the CLI, the agent and the Python packages `model-requirements.txt` pins for
-the model's scripts, running as the `agent` user; the CLI's state is in
-`/home/agent/.gemini` (`GEMINI_CLI_HOME`) whatever the uid.
+the model's scripts. It starts as root, whose supervisord (`start-agent`, `root.conf`) runs the clock follower and the
+egress proxy, each as its own user, and the A2A server as the `agent` user, on real time; the CLI's state is in
+`/home/agent/.gemini` (`GEMINI_CLI_HOME`) whatever the uid. When the A2A server exits, supervisord stops and the
+container exits with it, as when the server was the container's process, so a run fails at once rather than going on
+with a new server that has none of its registrations; the follower and the proxy restart in place. Started as another
+user, it runs the A2A server alone.
+
+## The env's clock
+
+The image can follow a task env's clock as Claude Code's does, with agent-env's libfaketime preloaded for the `agent`
+user and the computer base's follower and egress proxy (`src/agent_env/agents/README.md`), and only once a
+`sync_env_clock` sets `agent_clock`. Unarmed, the CLI runs exactly as it did before it could: the same environment, and
+started as `gemini`. So does an install's (`install/v1`), which has no egress proxy of the image's: its clock page, a
+computer's say, follows a clock the agent never opted in to. On an armed clock the CLI itself stays on real time, and
+only the commands the model runs follow the clock:
+
+- **The CLI, on real time.** Each turn starts the CLI's script with node itself, with agent-env's real-time marker and
+ `GEMINI_CLI_NO_RELAUNCH`, so neither `gemini`'s `#!/usr/bin/env node` line nor the CLI's relaunch of itself hands node
+ an environment the marker is gone from. It judges its `projects.json` lock stale, its sessions, tool outputs and logs
+ old and its credentials expired by real file and server times, which would be wrong on the env's clock, and it checks
+ certificates against real time, so it reaches its model relay and the env's MCP servers directly, an HTTPS server on
+ Modal included, whatever the clock shows. It keeps Node's default heap, which its relaunch would have raised to half
+ the host's memory.
+- **The model's commands, on the env's clock.** Every bash the CLI starts, each command the model runs and each hook,
+ first reads a file beside the run's settings (`BASH_ENV`) that exports the egress proxy by the rule every clocked
+ agent shares (`agent_egress.egress_env`): every TLS host through the proxy but loopback, `host.docker.internal`, the
+ deploy's `NO_PROXY` hosts and hosts reached over plain HTTP alone. The CLI itself is handed no proxy, since it would
+ send every request through one, `NO_PROXY` or not, its loopback relay included.
+- **The env's date.** The CLI words its "Today's date is" line from its own clock, so the model relay names the env's
+ date there instead, read as the turn starts from `date`, which follows the clock as the model's commands do. A CLI
+ that calls no relay, with no `LITELLM_BASE_URL` or with a `GOOGLE_GEMINI_BASE_URL` of its own, shows the real date
+ there. The commands' `date` and the gateway's `get_time` show the env's time.
+- **The changelog, on real time.** The capture hook and its `tar` run with the marker: the hook checks its grant's
+ expiry, and tar the times its incremental snapshot compares, against real time, as both are.
+
+A clock armed while a turn runs reaches that turn's CLI, which was started to follow it, without the proxy; the next
+turn starts as above.
diff --git a/src/agent_env/agents/agents/gemini/a2a_server.py b/src/agent_env/agents/agents/gemini/a2a_server.py
index 1021a70c9..56e789875 100644
--- a/src/agent_env/agents/agents/gemini/a2a_server.py
+++ b/src/agent_env/agents/agents/gemini/a2a_server.py
@@ -67,7 +67,9 @@
chats_dir_for_cwd,
cli_env,
cli_model,
+ cli_on_real_time,
detect_format,
+ env_today,
find_session_file,
gemini_request_to_openai,
get_last_attribution_snapshot,
@@ -82,6 +84,7 @@
run_gemini,
transcript_session_id,
wants_sse,
+ with_date,
)
from gemini_changelog import (
HOOK_TIMEOUT_S,
@@ -197,11 +200,13 @@ class GeminiConfig(AgentConfig):
@dataclass(frozen=True)
class _Route:
- """What the proxy forwards one run's model calls with."""
+ """What the proxy forwards one run's model calls with: on an armed clock, ``today``, the env's date as the run
+ started, which the CLI's date line names in place of its own, on real time."""
model: str | None
project_id: str | None
task_id: str | None
+ today: str | None = None
# install.sh, from the build context install_agent unpacks, brings Node, the Gemini CLI and a Python of the agent's
@@ -362,16 +367,16 @@ def _answer(uploaded: Uploaded) -> dict[str, Any]:
async def _vertex_openai_bridge(
- rest: str, request: Request, base: str, route_model: str, project_id: str | None, task_id: str | None,
+ rest: str, request: Request, body: bytes, base: str, route_model: str, project_id: str | None,
+ task_id: str | None,
) -> Response:
- """Translate the CLI's native-Gemini generate call into an OpenAI
+ """Translate the CLI's native-Gemini generate call, ``body``, into an OpenAI
/v1/chat/completions call whose `model` is the provider-prefixed route
string (e.g. vertex_ai/global/gemini-3.1-pro-preview) — the only endpoint
that reaches Vertex — then translate the response back to a single native
Gemini GenerateContentResponse (SSE-framed when the CLI asked for
streamGenerateContent). Attribution headers are injected identically to the
passthrough path so cost tagging is preserved."""
- body = await request.body()
try:
greq = json.loads(body) if body else {}
except json.JSONDecodeError:
@@ -544,9 +549,10 @@ async def run(self, request: TaskRequest[GeminiConfig]) -> TaskResult:
async with self._context_locks_guard:
self._active_contexts.add(context_id)
token = uuid.uuid4().hex
- self._routes[token] = _Route(cfg.model, cfg.project_id, cfg.task_id)
own = self.session_ref_for_context(context_id)
try:
+ armed = cli_on_real_time(os.environ)
+ self._routes[token] = _Route(cfg.model, cfg.project_id, cfg.task_id, env_today() if armed else None)
with run_settings(request.mcp_servers, cfg.role, cfg.system_prompt) as settings:
base_url = None
if os.environ.get("LITELLM_BASE_URL"):
@@ -566,7 +572,10 @@ async def run(self, request: TaskRequest[GeminiConfig]) -> TaskResult:
attachment_paths=attachment_paths or None,
timeout_s=cfg.timeout_seconds,
event_callback=lambda event: self._on_event(event, request),
- env=cli_env(os.environ, system_settings=settings, base_url=base_url),
+ env=cli_env(
+ os.environ, system_settings=settings, base_url=base_url, clock_armed=armed,
+ mcp_urls=[str(info.get("url") or "") for info in (request.mcp_servers or {}).values()],
+ ),
cwd=GEMINI_CWD,
other_sessions=lambda: {*self.bound_session_refs(), *self._claimed_sessions} - {own},
)
@@ -751,7 +760,8 @@ async def load_snapshot(self, request: ObjectSnapshotLoadRequest) -> ObjectSnaps
return ObjectSnapshotLoadResponse(context_id=new_context_id)
async def litellm_gemini_proxy(self, request: Request) -> Response:
- """Forward one run's model call to LiteLLM with that run's attribution headers."""
+ """Forward one run's model call to LiteLLM with that run's attribution headers, its date line naming the env's
+ date when the run started on an armed clock."""
route = self._routes.get(request.path_params["token"])
if route is None:
raise HTTPException(status_code=404, detail="no running turn has this proxy route")
@@ -764,13 +774,13 @@ async def litellm_gemini_proxy(self, request: Request) -> Response:
# OpenAI-compat endpoint instead. Everything else (countTokens, the native
# AI-Studio models) keeps the verbatim passthrough below.
route_model = (route.model or "").strip()
+ body = with_date(await request.body(), route.today)
if needs_openai_route(route_model) and is_generate_path(rest):
- return await _vertex_openai_bridge(rest, request, base, route_model, route.project_id, route.task_id)
+ return await _vertex_openai_bridge(rest, request, body, base, route_model, route.project_id, route.task_id)
fwd_headers = _upstream_headers(
{k: v for k, v in request.headers.items() if k.lower() not in _PROXY_DROP_REQ_HEADERS},
route.project_id, route.task_id,
)
- body = await request.body()
try:
async with httpx.AsyncClient(timeout=_DEFAULT_TIMEOUT_S) as client:
upstream = await client.request(
diff --git a/src/agent_env/agents/agents/gemini/gemini_bridge.py b/src/agent_env/agents/agents/gemini/gemini_bridge.py
index b98ff2059..ff15289c6 100644
--- a/src/agent_env/agents/agents/gemini/gemini_bridge.py
+++ b/src/agent_env/agents/agents/gemini/gemini_bridge.py
@@ -14,15 +14,19 @@
import logging
import os
import re
+import shlex
+import shutil
import signal
+import subprocess
import threading
import time
-from collections.abc import Callable, Collection, Mapping
+from collections.abc import Callable, Collection, Iterable, Mapping
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
-from gemini_config import SYSTEM_SETTINGS_ENV, gemini_home
+from agent_egress import EGRESS_PROXY_ENV, clock_armed, egress_env
+from gemini_config import SYSTEM_SETTINGS_ENV, commands_env_path, gemini_home
logger = logging.getLogger(__name__)
@@ -274,19 +278,84 @@ def model_headers(raw: str | None) -> dict[str, str]:
return {str(name): str(value) for name, value in headers.items()}
-def cli_env(environ: Mapping[str, str], *, system_settings: Path, base_url: str | None) -> dict[str, str]:
+#: agent-env's libfaketime keeps a process started with this marker on real time, and takes it out of the environment
+#: that process's children inherit, so they follow the clock.
+REAL_TIME_ENV = "AGENTENV_REAL_TIME"
+
+
+def cli_env(environ: Mapping[str, str], *, system_settings: Path, base_url: str | None,
+ mcp_urls: Iterable[str] = (), clock_armed: bool = False) -> dict[str, str]:
"""The CLI's environment for one run: this process's, with the endpoint's key under the name the CLI reads, its
model calls sent to ``base_url`` (the attribution proxy, for this run) unless the environment names its own
- endpoint, and the run's own system settings."""
+ endpoint, and the run's own system settings. On an armed clock the CLI stays on real time, relaunching nothing (its
+ child would lose the marker), so it judges its locks, cleanups and certificates by real time and goes out directly,
+ as it must: it sends every request through a proxy it's handed, loopback ones included. Only the model's commands
+ follow the clock, and they get ``egress_env``'s proxy for the model endpoint and ``mcp_urls`` from a file beside
+ the settings that every bash the CLI starts reads first (BASH_ENV)."""
env = dict(environ)
if env.get("LITELLM_API_KEY") and not env.get("GEMINI_API_KEY"):
env["GEMINI_API_KEY"] = env["LITELLM_API_KEY"]
if base_url and not environ.get("GOOGLE_GEMINI_BASE_URL"):
env["GOOGLE_GEMINI_BASE_URL"] = base_url
env[SYSTEM_SETTINGS_ENV] = str(system_settings)
+ if not clock_armed:
+ return env
+ env.update({REAL_TIME_ENV: "1", "GEMINI_CLI_NO_RELAUNCH": "true"})
+ urls = [env.get("GOOGLE_GEMINI_BASE_URL", ""), env.get("LITELLM_BASE_URL", ""), *mcp_urls]
+ if egress := egress_env(environ, urls, armed=True):
+ commands = commands_env_path(system_settings)
+ commands.write_text("".join(f"export {name}={shlex.quote(value)}\n" for name, value in egress.items()))
+ env["BASH_ENV"] = str(commands)
return env
+def cli_on_real_time(environ: Mapping[str, str]) -> bool:
+ """Whether a turn starting now keeps its CLI on real time: in the image, whose root.conf hands its server the egress
+ proxy, once its clock page is armed, which there only sync_env_clock's ``agent_clock`` does. An install's page, a
+ computer's say, follows a clock the agent never opted in to, so there the CLI runs as it did before."""
+ return bool(environ.get(EGRESS_PROXY_ENV)) and clock_armed()
+
+
+def cli_program(env: Mapping[str, str] | None) -> list[str]:
+ """What starts the CLI: ``gemini``, or, for one kept on real time, its script run by node itself, since the image's
+ ``gemini`` links to a script that starts with ``#!/usr/bin/env node``, and env, started with the marker, would stay
+ on real time and hand node an environment without it. An install's ``gemini`` is a shell launcher, which node can't
+ run, so it's started as it is."""
+ if not env or env.get(REAL_TIME_ENV) != "1":
+ return ["gemini"]
+ path = env.get("PATH")
+ script = os.path.realpath(shutil.which("gemini", path=path))
+ return [shutil.which("node", path=path), script] if script.endswith(".js") else ["gemini"]
+
+
+# The CLI's environment context, the first content of its chat's calls (getInitialChatHistory), and its date line,
+# which the CLI words from its own clock.
+_CONTEXT_OPENING = "\nThis is the Gemini CLI. We are setting up the context for our chat.\nToday's date is "
+_DATE_LINE = re.compile(rb"(Today's date is )[^\"\\]{1,80}?( \(formatted according to the user's locale\)\.)")
+
+
+def env_today() -> str:
+ """Today on the env's clock, worded as the CLI's date line words it in the image's locale: from ``date``, which,
+ as a child of this process kept on real time, follows the clock as the model's commands do."""
+ return subprocess.run(["date", "+%A, %B %-d, %Y"], capture_output=True, text=True, check=True).stdout.strip()
+
+
+def _opens_with_context(body: bytes) -> bool:
+ try:
+ return json.loads(body)["contents"][0]["parts"][0]["text"].startswith(_CONTEXT_OPENING)
+ except (ValueError, LookupError):
+ return False
+
+
+def with_date(body: bytes, today: str | None) -> bytes:
+ """A model call's body with the CLI's date line naming ``today``, the env's; the body as it came without one. Only
+ the line of a call's first content, the CLI's context, changes, the first in the body since the SDK writes
+ ``contents`` before the rest: the same words in a prompt, a tool's result or a side call stay as they came."""
+ if today is None or not _opens_with_context(body):
+ return body
+ return _DATE_LINE.sub(lambda match: match[1] + today.encode() + match[2], body, count=1)
+
+
@dataclass
class GeminiResult:
response: str
@@ -519,7 +588,7 @@ async def run_gemini(
prompt = f"{prompt}\n\n{refs}" if prompt else refs
cmd = [
- "gemini", "-p", prompt,
+ *cli_program(env), "-p", prompt,
"--output-format", "stream-json",
"--approval-mode", "yolo",
]
@@ -535,6 +604,8 @@ async def run_gemini(
started = time.time()
proc = await _started(asyncio.create_subprocess_exec(
*cmd,
+ # Not the server's, which under supervisord is a pipe that never closes: the CLI would wait 500 ms for input.
+ stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=dict(env) if env is not None else None,
diff --git a/src/agent_env/agents/agents/gemini/gemini_changelog.py b/src/agent_env/agents/agents/gemini/gemini_changelog.py
index fe2d53799..b3cbead8a 100644
--- a/src/agent_env/agents/agents/gemini/gemini_changelog.py
+++ b/src/agent_env/agents/agents/gemini/gemini_changelog.py
@@ -47,16 +47,23 @@
_META_MEMBER = re.compile(rf"(?:^|/)[^/]+{re.escape(META_DIR_SUFFIX)}/{re.escape(META_NAME)}\Z")
_TAR_STDERR_TAIL_CHARS = 2000
_TAR_VERSION_TIMEOUT_S = 30
+# The marker agent-env's libfaketime keeps a program started with on real time, and takes out of what its children
+# inherit: the capture compares its grant's expiry, and its tar file times, with its own clock, and both are real.
+_REAL_TIME_ENV = "AGENTENV_REAL_TIME"
_FAILED_INCREMENTS_LOGGED = 5
# The post-tool hook, run by the agent's own Python, as a child of the CLI after every tool call, so an increment
-# includes that tool's writes. It exits 0 on a capture error, so the error never reaches the model.
+# includes that tool's writes. It exits 0 on a capture error, so the error never reaches the model. It runs on real
+# time, as its grant's expiry is.
CAPTURE_SCRIPT = r'''import asyncio, fcntl, json, os, shutil, signal, subprocess, sys, time
from pathlib import Path
from agentenv_protocol.transfers import NamespaceUploader, WriteNamespaceGrant
CFG = "/tmp/changelog/config.json"
+# tar runs on real time, as the file times it compares with its last run's are: on an env clock ahead of them, it
+# would record that clock's time as its baseline and miss what changed since.
+REAL_TIME = {"AGENTENV_REAL_TIME": "1"}
STDERR_TAIL_CHARS = 500
TURN_POLL_S = 0.05
TOOL_NAME_CHARS = 40
@@ -221,6 +228,7 @@ def main():
["tar", "--ignore-failed-read", "--listed-incremental=" + work, "--exclude=" + changelog_dir,
"-czf", local, *members],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, pass_fds=(lock.fileno(),),
+ env=dict(os.environ, **REAL_TIME),
)
archived = True
try:
@@ -413,7 +421,7 @@ def __init__(
self.snar = f"{directory}/state.snar"
self.config_path = f"{directory}/config.json"
self.capture_path = f"{directory}/capture.py"
- self.hook_command = f"{shlex.quote(sys.executable)} {shlex.quote(self.capture_path)}"
+ self.hook_command = f"{_REAL_TIME_ENV}=1 {shlex.quote(sys.executable)} {shlex.quote(self.capture_path)}"
def capture_script(self) -> str:
"""``CAPTURE_SCRIPT`` reading this changelog's config."""
@@ -462,6 +470,7 @@ def _reset(self, roots: list[str], write_namespace: dict) -> None:
["tar", "--ignore-failed-read", f"--listed-incremental={self.snar}", f"--exclude={self.directory}",
"-cf", "/dev/null", *present],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ env={**os.environ, _REAL_TIME_ENV: "1"},
)
async def apply(self, request: ObjectChangelogApplyRequest) -> ObjectChangelogApplyResponse:
diff --git a/src/agent_env/agents/agents/gemini/gemini_config.py b/src/agent_env/agents/agents/gemini/gemini_config.py
index a1f324c89..588b32e9e 100644
--- a/src/agent_env/agents/agents/gemini/gemini_config.py
+++ b/src/agent_env/agents/agents/gemini/gemini_config.py
@@ -59,6 +59,11 @@ def _server_entry(url: str, headers: Mapping[str, str] | None, role: str | None)
return entry
+def commands_env_path(settings: Path) -> Path:
+ """Where a run's commands get their environment from, beside its settings, which take it with them."""
+ return settings.with_suffix(".sh")
+
+
def _default_system_settings() -> dict[str, Any]:
try:
settings = json.loads(_DEFAULT_SYSTEM_SETTINGS.read_text())
@@ -72,8 +77,8 @@ def run_settings(servers: Mapping[str, Mapping[str, Any]], role: str | None,
system_prompt: str | None) -> Iterator[Path]:
"""One run's system settings, in an owner-only file of its own that names `servers` with `role`; with a
`system_prompt`, also a context file the CLI layers on its own system prompt (the CLI has no flag for one, and
- replacing its system prompt would lose its tool protocol). The settings go when the run ends, the context file
- when the last run naming it does."""
+ replacing its system prompt would lose its tool protocol). The settings go when the run ends, with the commands'
+ environment written beside them, and the context file when the last run naming it does."""
home = gemini_home()
runs = home / "agentenv-runs"
runs.mkdir(mode=0o700, parents=True, exist_ok=True)
@@ -91,6 +96,7 @@ def run_settings(servers: Mapping[str, Mapping[str, Any]], role: str | None,
"fileName": [_WORKSPACE_CONTEXT_FILE, context.name],
}
path = runs / f"{token}.json"
+ stack.callback(commands_env_path(path).unlink, missing_ok=True)
# It carries the MCP servers' headers.
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as handle:
stack.callback(path.unlink, missing_ok=True)
diff --git a/src/agent_env/agents/agents/gemini/install.sh b/src/agent_env/agents/agents/gemini/install.sh
index 954472462..9985e557d 100755
--- a/src/agent_env/agents/agents/gemini/install.sh
+++ b/src/agent_env/agents/agents/gemini/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 gemini_bridge.py gemini_changelog.py gemini_config.py gemini_kit.py requirements.txt run.sh"
+AGENT_FILES="a2a_server.py gemini_bridge.py gemini_changelog.py gemini_config.py gemini_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py"
# put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced; put_dir SRC
# DEST copies a folder to DEST, which isn't there.
@@ -132,7 +132,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/gemini $r/app/run.sh"
diff --git a/src/agent_env/agents/agents/gemini/root.conf b/src/agent_env/agents/agents/gemini/root.conf
new file mode 100644
index 000000000..f4df38eed
--- /dev/null
+++ b/src/agent_env/agents/agents/gemini/root.conf
@@ -0,0 +1,85 @@
+; Root's supervisord (start-agent): the clock follower and the egress proxy, each as its own user, on real
+; time, and the A2A server as the agent's user. The server starts with the real-time marker, which agent-env's
+; libfaketime takes out of its environment, so the server's own records keep real timestamps and everything it starts
+; reads the env's time, but the CLI, which it starts with the marker again on an armed clock, so only the model's
+; commands follow the clock (gemini_bridge.cli_env). Its socket and logs are root's alone, so the agent's user can
+; neither stop nor restart any of them. The follower follows nothing until the server writes its config, which
+; sync_env_clock has it do, then picks it up within a quarter second. When the server exits, the container exits with it
+; (agent-exit), as it did when the server was the container's process; the follower and the proxy restart in place.
+[supervisord]
+nodaemon=true
+user=root
+logfile=/var/log/agentenv-root/supervisord.log
+pidfile=/run/agentenv-root/supervisord.pid
+childlogdir=/var/log/agentenv-root
+
+[unix_http_server]
+file=/run/agentenv-root/supervisor.sock
+chmod=0700
+
+[rpcinterface:supervisor]
+supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
+
+[supervisorctl]
+serverurl=unix:///run/agentenv-root/supervisor.sock
+
+[program:clock]
+command=/usr/local/bin/python3 -I /usr/local/lib/agentenv-clock/clock-follower
+user=agentenv-clock
+directory=/
+priority=3
+autorestart=true
+startsecs=1
+startretries=1000
+redirect_stderr=true
+stdout_logfile=/var/log/agentenv-root/clock.log
+environment=HOME="/nonexistent",USER="agentenv-clock",LOGNAME="agentenv-clock"
+
+[program:egress]
+command=/usr/local/lib/agentenv-egress/egress serve
+user=agentenv-egress
+directory=/
+priority=3
+autorestart=true
+startsecs=1
+startretries=1000
+redirect_stderr=true
+stdout_logfile=/var/log/agentenv-root/egress.log
+environment=HOME="/nonexistent",USER="agentenv-egress",LOGNAME="agentenv-egress",AGENTENV_EGRESS_PRIVATE="allow"
+
+; uvicorn itself, not entrypoint.sh: the marker holds for the process it's given to alone, and a shell that execs
+; uvicorn would hand uvicorn an environment without it. It isn't restarted, nor started again when it exits as it starts
+; (startretries=0, FATAL at once): a server started in a dead one's place would have none of the run's registrations
+; (the env's MCP servers, its config, its peers, its running tasks), and the CLIs of the dead one's turns would go on
+; beside it. agent-exit stops the container instead, so the run fails at once.
+[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=/workspace
+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"
+
+; Stops supervisord, its parent, and so the container, once the A2A server has exited or given up starting (EXITED,
+; or FATAL when it exits as it starts); the follower's and the proxy's exits it lets pass, as supervisord restarts them,
+; and a normal stop is no exit (the server is STOPPED). supervisord 4.2.5 exits 0 however it's stopped, so the
+; container's status doesn't say the server crashed; supervisord's line before it stops, "exited: agent (...; not
+; expected)", does. It runs as root, supervisord's user, to signal it, and speaks supervisord's event listener protocol:
+; READY, then a header line and the payload of the length it gives, then RESULT 2 OK.
+[eventlistener:agent-exit]
+command=/usr/local/bin/python3 -I -c 'import os,signal,sys
+ def fields(line): return dict(word.split(b":",1) for word in line.split())
+ def payload(header): return fields(sys.stdin.buffer.read(int(fields(header)[b"len"])))
+ def stop(event): event[b"processname"]==b"agent" and os.kill(os.getppid(),signal.SIGTERM)
+ def say(text): sys.stdout.buffer.write(text);sys.stdout.buffer.flush()
+ say(b"READY\n")
+ for header in sys.stdin.buffer: stop(payload(header));say(b"RESULT 2\nOKREADY\n")'
+events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL
+priority=1
diff --git a/src/agent_env/agents/agents/gemini/shared_sources.toml b/src/agent_env/agents/agents/gemini/shared_sources.toml
new file mode 100644
index 000000000..6076f3540
--- /dev/null
+++ b/src/agent_env/agents/agents/gemini/shared_sources.toml
@@ -0,0 +1,5 @@
+# What this image's build context takes from agent-env's own sources, at the name its Dockerfile copies it from: one
+# copy of each, shared with the other images that take it (utils/docker/context.py). Paths are under src/agent_env.
+clock = "utils/faketime_clock"
+egress = "utils/egress_proxy"
+agent_clock = "utils/agent_clock"
diff --git a/src/agent_env/agents/agents/gemini/start-agent b/src/agent_env/agents/agents/gemini/start-agent
new file mode 100755
index 000000000..e1e6f7c5a
--- /dev/null
+++ b/src/agent_env/agents/agents/gemini/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 but the CLI reading the env's time from the page. Until sync_env_clock has
+# the agent follow a clock, the page holds real time and the proxy relays TLS untouched. Started as another user, the
+# image runs the A2A server alone, as before, on real time.
+set -eu
+if [ "$(id -u)" != 0 ]; then
+ exec /opt/agent/entrypoint.sh
+fi
+install -d -o root -g root -m 0700 /var/log/agentenv-root /run/agentenv-root
+install -d -o agentenv-clock -g agentenv-clock -m 0755 /run/agentenv-clock
+python3 -I /usr/local/lib/agentenv-clock/clockpage.py create agentenv-clock
+AGENTENV_SESSION_USER=agent AGENTENV_EGRESS_NSS=off \
+ /usr/local/lib/agentenv-egress/egress boot > /var/log/agentenv-root/egress-boot.log 2>&1 \
+ || { cat /var/log/agentenv-root/egress-boot.log >&2; echo "the egress proxy's boot failed" >&2; exit 2; }
+# A provider's own CA bundle stays trusted: Sail, for one, points SSL_CERT_FILE and the like at the bundle it signs
+# model requests under, and root.conf points the server's trust at agent-env's bundles instead, so the provider's goes
+# into them, and into the egress proxy's roots, which carry those requests once the clock is armed.
+for bundle in "${SSL_CERT_FILE:-}" "${REQUESTS_CA_BUNDLE:-}" "${NODE_EXTRA_CA_CERTS:-}" "${CURL_CA_BUNDLE:-}"; do
+ case "$bundle" in ""|/etc/agentenv/*) continue ;; esac
+ [ -r "$bundle" ] || continue
+ for target in /etc/agentenv/ca-bundle.pem /etc/agentenv/ca.pem /usr/local/lib/agentenv-egress/roots.pem; do
+ grep -qxF "# agentenv: $bundle" "$target" 2>/dev/null && continue
+ { printf '\n# agentenv: %s\n' "$bundle"; cat "$bundle"; } >> "$target"
+ done
+done
+exec supervisord -c /etc/agentenv/root.conf
diff --git a/tst/integration/task_step/test_agent_env_clock_local.py b/tst/integration/task_step/test_agent_env_clock_local.py
index 87468d613..68c6a39fa 100644
--- a/tst/integration/task_step/test_agent_env_clock_local.py
+++ b/tst/integration/task_step/test_agent_env_clock_local.py
@@ -1,8 +1,8 @@
"""An agent image on a task env's clock (FD-5916), end to end on local Docker: the agent deployed with the env serves
clock/v1 sync_time; sync_env_clock declares it a follower at the real gateway and hands it its config; from then on
-every program the agent's user runs, its CLI included, reads the env's time while the A2A server stays on real time; a
-clock write that waits for followers waits for it; and once teardown_sandboxes takes it down, writes stop waiting for
-it. An agent whose CLI speaks a protocol the stub endpoint serves also runs one real turn.
+every program the agent's user runs reads the env's time while the A2A server, and the Gemini CLI it starts, stay on
+real time; a clock write that waits for followers waits for it; and once teardown_sandboxes takes it down, writes stop
+waiting for it. An agent whose CLI speaks a protocol a stub endpoint serves also runs one real turn.
Runs over images built beforehand, from this branch: AGENTENV_E2E_AGENT_IMAGES names one per agent, as
``claude-code=,codex=``; an agent it doesn't name is skipped as a missing capability."""
@@ -40,6 +40,7 @@
from tst.integration.task_step.test_register_env_triggers_local import _deploy_items
from tst.util.capabilities import agent_clock_image, skip_without_agent_clock_image
from tst.util.fake_anthropic import FakeAnthropic, tool_then_answer
+from tst.util.fake_gemini import FakeGemini, shell_then_answer
pytestmark = [pytest.mark.integration, pytest.mark.int_test_slow]
@@ -75,20 +76,42 @@ async def _claude_turn(context: TaskStepContext, endpoint: FakeAnthropic) -> Non
assert any(VIRTUAL in result for result in endpoint.tool_results()), endpoint.tool_results()
+async def _gemini_turn(context: TaskStepContext, endpoint: FakeGemini) -> None:
+ """One turn of the real Gemini CLI, which stays on real time while the model's commands follow the clock: the date
+ line the model gets is the env's, which the agent's model relay writes in, and a `date` the model runs shows the
+ env's time, with the egress proxy's variables and no marker, under a CLI node runs itself."""
+ endpoint.respond = shell_then_answer(
+ 'date -u +%FT%TZ; echo "proxy=${HTTPS_PROXY:-} marker=[${AGENTENV_REAL_TIME:-}] '
+ 'cli=$(tr "\\0" " " < /proc/$PPID/cmdline)"', prefix="the shell said: ")
+ await PromptAgentTaskStep(id="ask", version=None, prompt="What's the date? Run date.", agent_name="solver",
+ max_conversation_turns=1).execute(context)
+ dated = {m for call in endpoint.generate_calls()
+ for m in re.findall(r"Today's date is ([^(\"]+?) \(formatted", json.dumps(call.body))}
+ results = endpoint.tool_results()
+ print("the CLI's date line:", dated, "shell:", results)
+ assert dated == {"Tuesday, March 4, 2031"}, dated
+ assert any(VIRTUAL in r and "proxy=http://127.0.0.1:3128" in r and "marker=[]" in r for r in results), results
+ assert any("node /opt/agent/node_modules/@google/gemini-cli/bundle/gemini.js" in r for r in results), results
+
+
@dataclass(frozen=True)
class Agent:
"""What the test needs of an agent's image: its bridge module, a command its CLI answers without a model (which
- must return under the preloaded library), and a turn against the stub endpoint, for a CLI that speaks its protocol."""
+ must return under the preloaded library), and a turn against the stub endpoint of its protocol, for a CLI one
+ serves."""
bridge: str
version: tuple[str, ...]
shows: str
- turn: Callable[[TaskStepContext, FakeAnthropic], Awaitable[None]] | None = None
+ turn: Callable[[TaskStepContext, FakeAnthropic | FakeGemini], Awaitable[None]] | None = None
+ endpoint: type[FakeAnthropic] | type[FakeGemini] = FakeAnthropic
AGENTS = {
"claude-code": Agent(bridge="claude_bridge", version=("claude", "--version"), shows="(Claude Code)",
turn=_claude_turn),
+ "gemini": Agent(bridge="gemini_bridge", version=("gemini", "--version"), shows="0.38.2", turn=_gemini_turn,
+ endpoint=FakeGemini),
"opencode": Agent(bridge="opencode_bridge", version=("opencode", "--version"), shows="1.17.18"),
}
@@ -120,11 +143,11 @@ async def _followers(deployed) -> dict:
@pytest.mark.parametrize("name", [pytest.param(name, marks=skip_without_agent_clock_image(name)) for name in AGENTS])
@pytest.mark.asyncio
async def test_an_agent_image_follows_the_envs_clock_until_it_is_torn_down(local_registry, name):
- with FakeAnthropic(host=_host_ips()[-1]) as endpoint: # where this machine's containers reach it
+ with AGENTS[name].endpoint(host=_host_ips()[-1]) as endpoint: # where this machine's containers reach it
await _follows_until_torn_down(name, AGENTS[name], agent_clock_image(name), endpoint)
-async def _follows_until_torn_down(name: str, spec: Agent, tag: str, endpoint: FakeAnthropic) -> None:
+async def _follows_until_torn_down(name: str, spec: Agent, tag: str, endpoint: FakeAnthropic | FakeGemini) -> None:
_seed_bootstrap_envs()
env, deployed, _ = await _deploy_items("agentclock")
uid = uuid.uuid4().hex[:8]
diff --git a/tst/unit/agents/gemini/agent.py b/tst/unit/agents/gemini/agent.py
index 583404a5d..9afcd8b55 100644
--- a/tst/unit/agents/gemini/agent.py
+++ b/tst/unit/agents/gemini/agent.py
@@ -1,19 +1,25 @@
-"""The Gemini agent's modules, imported from its folder as its image runs them: by their own names, from the folder on
-the path."""
+"""The Gemini agent's modules, imported as its image runs them: by their own names, from its folder and from the folders
+its build context takes as agent_clock/ and clock/, whose modules the image copies beside the bridge."""
import importlib
import importlib.util
+import os
import sys
from pathlib import Path
import agent_env
+from tst.util.build_context import sent
AGENT_DIR = Path(agent_env.__file__).parent / "agents" / "agents" / "gemini"
-sys.path.insert(0, str(AGENT_DIR))
+IMPORTED = [str(AGENT_DIR), str(sent(AGENT_DIR, "agent_clock/agent_egress.py").parent),
+ str(sent(AGENT_DIR, "clock/clockpage.py").parent)]
+PYTHONPATH = os.pathsep.join(IMPORTED)
+sys.path[:0] = IMPORTED
gemini_config = importlib.import_module("gemini_config")
gemini_kit = importlib.import_module("gemini_kit")
gemini_changelog = importlib.import_module("gemini_changelog")
gemini_bridge = importlib.import_module("gemini_bridge")
+agent_egress = importlib.import_module("agent_egress")
# By its path: another agent's a2a_server, imported by the same name, may be loaded already.
_spec = importlib.util.spec_from_file_location("gemini_a2a_server", AGENT_DIR / "a2a_server.py")
a2a_server = importlib.util.module_from_spec(_spec)
diff --git a/tst/unit/agents/gemini/test_card_contract.py b/tst/unit/agents/gemini/test_card_contract.py
index 510fcc4b7..18c0cb09a 100644
--- a/tst/unit/agents/gemini/test_card_contract.py
+++ b/tst/unit/agents/gemini/test_card_contract.py
@@ -8,7 +8,7 @@
import subprocess
import sys
-from tst.unit.agents.gemini.agent import AGENT_DIR, a2a_server
+from tst.unit.agents.gemini.agent import AGENT_DIR, PYTHONPATH, a2a_server
from tst.unit.agents.gemini.support import card
_GEMINI_SKILL = {
@@ -232,7 +232,7 @@ def test_install_mode_reads_the_card_by_importing_agent_card():
"from a2a_server import AGENT_CARD; "
"print(json.dumps(AGENT_CARD.model_dump()))"
)
- env = {k: v for k, v in os.environ.items() if not k.startswith("LITELLM_")}
+ env = {**{k: v for k, v in os.environ.items() if not k.startswith("LITELLM_")}, "PYTHONPATH": PYTHONPATH}
out = subprocess.run([sys.executable, "-c", script], cwd=AGENT_DIR, env=env, capture_output=True, text=True,
check=True)
exported = json.loads(out.stdout)
diff --git a/tst/unit/agents/gemini/test_env_clock.py b/tst/unit/agents/gemini/test_env_clock.py
new file mode 100644
index 000000000..01daf4169
--- /dev/null
+++ b/tst/unit/agents/gemini/test_env_clock.py
@@ -0,0 +1,309 @@
+"""Gemini on the env's clock. On an armed clock the CLI itself stays on real time and goes out directly: started as its
+script run by node, with no relaunch of its own, so the real-time marker reaches the process that runs it, it compares
+its locks', sessions', tool outputs' and logs' real file times, its credentials' expiry and its MCP servers'
+certificates with real time. The commands the model runs follow the clock and go out by the shared egress rule
+(tst/unit/agents/test_agent_egress.py), from a file every bash the CLI starts reads first, which the CLI never reads
+itself, as it would send every request through a proxy it's handed, NO_PROXY or not. The model's date line names the
+env's date (test_litellm_proxy.py), and the changelog's capture and its tar run on real time. Unarmed, the CLI runs
+exactly as before. What every clocked image shares is checked in tst/unit/agents/test_agent_clock_images.py."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import re
+import shlex
+import subprocess
+import sys
+from datetime import datetime
+from pathlib import Path
+from urllib.parse import urlsplit
+
+import pytest
+
+from tst.unit.agents.gemini.agent import AGENT_DIR, a2a_server, agent_egress, gemini_bridge, gemini_config
+from tst.unit.agents.gemini.fake_cli import FakeCLI
+from tst.unit.agents.gemini.support import namespace_grant, send, settings as user_settings
+
+PROXY = "http://127.0.0.1:3128"
+ATTRIBUTION_PROXY = "http://127.0.0.1:8000/litellm-gemini/token"
+PROXY_VARS = {"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY",
+ "no_proxy", "NODE_USE_ENV_PROXY"}
+MCP_URLS = ["http://gateway:8080/mcp", "https://abc-123.w.modal.host/mcp"]
+ENV_TODAY = "Tuesday, March 3, 2031"
+CHANGELOG_PATH = a2a_server.SNAPSHOT_V1.endpoint + "/changelog"
+
+
+def _page(armed: int) -> bytes:
+ return agent_egress.clockpage.encode(2, 1_900_000_000 * 10**9, 10**18, 1.0, armed, 3, 0, 0)
+
+
+@pytest.fixture
+def run_settings(tmp_path) -> Path:
+ path = tmp_path / "agentenv-runs" / "run.json"
+ path.parent.mkdir()
+ path.write_text("{}")
+ return path
+
+
+def _env(environ, run_settings, **kwargs) -> dict[str, str]:
+ return gemini_bridge.cli_env(environ, system_settings=run_settings, base_url=ATTRIBUTION_PROXY, **kwargs)
+
+
+def _commands_env(env: dict[str, str]) -> dict[str, str]:
+ """The environment of a command the model runs: `bash -c`, as the CLI starts each, in the CLI's environment."""
+ script = f"{shlex.quote(sys.executable)} -c 'import json, os; print(json.dumps(dict(os.environ)))'"
+ return json.loads(subprocess.run(["bash", "-c", script], env=env, capture_output=True, check=True).stdout)
+
+
+def test_on_an_armed_clock_the_cli_stays_on_real_time_with_no_relaunch_and_no_proxy_of_its_own(run_settings):
+ env = _env({agent_egress.EGRESS_PROXY_ENV: PROXY}, run_settings, clock_armed=True, mcp_urls=MCP_URLS)
+
+ assert (env["AGENTENV_REAL_TIME"], env["GEMINI_CLI_NO_RELAUNCH"]) == ("1", "true")
+ assert not PROXY_VARS & set(env)
+
+
+def test_on_an_armed_clock_the_models_commands_go_out_by_the_shared_egress_rule(run_settings):
+ """An env MCP server over TLS goes through the proxy, since the model's curl to it checks its certificate against
+ the env's date; plain-HTTP and loopback hosts and the deploy's NO_PROXY go direct."""
+ environ = {agent_egress.EGRESS_PROXY_ENV: PROXY, "NO_PROXY": "registry.internal",
+ "LITELLM_BASE_URL": "https://litellm.example.com"}
+ env = _env(environ, run_settings, clock_armed=True, mcp_urls=[*MCP_URLS, ""])
+
+ seen = _commands_env(env)
+ rule = agent_egress.egress_env(environ, [ATTRIBUTION_PROXY, environ["LITELLM_BASE_URL"], *MCP_URLS], armed=True)
+ assert {name: seen[name] for name in rule} == rule
+ direct = seen["NO_PROXY"].split(",")
+ assert {"127.0.0.1", "gateway", "registry.internal"} <= set(direct) and "abc-123.w.modal.host" not in direct
+ assert env["BASH_ENV"] == str(gemini_config.commands_env_path(run_settings))
+
+
+@pytest.mark.parametrize("name", ["LITELLM_BASE_URL", "GOOGLE_GEMINI_BASE_URL"])
+@pytest.mark.parametrize("base_url, direct", [("http://10.0.0.5:4000", True), ("https://litellm.example.com", False)])
+def test_the_models_commands_reach_a_model_endpoint_over_plain_http_directly(run_settings, name, base_url, direct):
+ env = _env({agent_egress.EGRESS_PROXY_ENV: PROXY, name: base_url}, run_settings, clock_armed=True)
+
+ assert (urlsplit(base_url).hostname in _commands_env(env)["NO_PROXY"].split(",")) is direct
+
+
+@pytest.mark.parametrize("environ, added", [
+ ({}, {"GOOGLE_GEMINI_BASE_URL": ATTRIBUTION_PROXY}),
+ ({agent_egress.EGRESS_PROXY_ENV: PROXY, "LITELLM_API_KEY": "k", "LITELLM_BASE_URL": "https://gw",
+ "NO_PROXY": "registry.internal", "HTTPS_PROXY": "http://corporate:8080"},
+ {"GEMINI_API_KEY": "k", "GOOGLE_GEMINI_BASE_URL": ATTRIBUTION_PROXY}),
+ ({"GEMINI_API_KEY": "own", "GOOGLE_GEMINI_BASE_URL": "https://own", "LITELLM_API_KEY": "k"}, {}),
+], ids=["bare", "image", "own-endpoint"])
+def test_unarmed_the_cli_runs_exactly_as_before(run_settings, environ, added):
+ """The environment the CLI had before it could follow the clock, this process's with its key, its endpoint and its
+ settings and nothing else; started as `gemini`, with no file written for its commands."""
+ env = _env(environ, run_settings, clock_armed=False, mcp_urls=MCP_URLS)
+
+ assert env == {**environ, **added, gemini_config.SYSTEM_SETTINGS_ENV: str(run_settings)}
+ assert gemini_bridge.cli_program(env) == ["gemini"]
+ assert not gemini_config.commands_env_path(run_settings).exists()
+
+
+def test_the_envs_date_is_worded_as_the_clis_date_line_words_it():
+ """The CLI's line is Node's toLocaleDateString in en-US, which the image's locale (C.UTF-8) gives: the weekday,
+ the month, the day and the year. Here, with no clock to follow, `date` reads real time."""
+ before = datetime.now()
+ today = gemini_bridge.env_today()
+
+ assert today in {f"{day:%A}, {day:%B} {day.day}, {day.year}" for day in (before, datetime.now())}
+
+
+def test_the_commands_environment_goes_with_the_runs_settings(monkeypatch, tmp_path):
+ monkeypatch.setenv("GEMINI_CLI_HOME", str(tmp_path))
+ with gemini_config.run_settings({}, None, None) as path:
+ commands = Path(_env({agent_egress.EGRESS_PROXY_ENV: PROXY}, path, clock_armed=True)["BASH_ENV"])
+ assert commands.is_file() and commands.parent == path.parent
+
+ assert list((tmp_path / ".gemini" / "agentenv-runs").iterdir()) == []
+
+
+def _installed_like_the_image(root: Path) -> tuple[Path, Path]:
+ """node, and `gemini` on PATH as a link to the CLI's script, through node_modules/.bin, as the image has them."""
+ script = root / "node_modules" / "@google" / "gemini-cli" / "bundle" / "gemini.js"
+ script.parent.mkdir(parents=True)
+ script.write_text("#!/usr/bin/env node\n")
+ (root / "node_modules" / ".bin").mkdir()
+ (root / "node_modules" / ".bin" / "gemini").symlink_to("../@google/gemini-cli/bundle/gemini.js")
+ bin_dir = root / "bin"
+ bin_dir.mkdir()
+ (bin_dir / "gemini").symlink_to(root / "node_modules" / ".bin" / "gemini")
+ node = bin_dir / "node"
+ node.write_text("#!/bin/sh\n")
+ for path in (script, node):
+ path.chmod(0o755)
+ return node, script
+
+
+def _spawned(monkeypatch, env: dict[str, str]) -> tuple[list[str], dict]:
+ """The command one turn starts the CLI with, and how."""
+ started = []
+
+ async def fake_exec(*cmd, **kwargs):
+ started.append((list(cmd), kwargs))
+ return FakeCLI(b'{"type":"result","status":"success","stats":{}}\n')
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec)
+ asyncio.run(gemini_bridge.run_gemini(prompt="hi", session_id=None, env=env))
+ ((cmd, kwargs),) = started
+ return cmd, kwargs
+
+
+@pytest.mark.parametrize("armed", [False, True])
+def test_a_cli_on_real_time_is_started_as_its_script_run_by_node_so_the_marker_reaches_node(
+ monkeypatch, tmp_path, run_settings, armed):
+ """`gemini` starts with `#!/usr/bin/env node`: env, started with the marker, would stay on real time itself and
+ start node without it."""
+ node, script = _installed_like_the_image(tmp_path)
+ env = _env({"PATH": str(node.parent), agent_egress.EGRESS_PROXY_ENV: PROXY}, run_settings, clock_armed=armed)
+
+ cmd, spawned = _spawned(monkeypatch, env)
+
+ program = [str(node), os.path.realpath(script)] if armed else ["gemini"]
+ assert cmd == [*program, "-p", "hi", "--output-format", "stream-json", "--approval-mode", "yolo"]
+ assert spawned["env"].get("AGENTENV_REAL_TIME") == ("1" if armed else None)
+
+
+def _installed_by_install_sh(root: Path) -> Path:
+ """`gemini` as install.sh writes it: a shell script that runs the CLI under the install's own node."""
+ install = (AGENT_DIR / "install.sh").read_text()
+ quoted = re.search(r"^quoted\(\) \{.*\}$", install, re.MULTILINE)[0]
+ launcher = re.search(r"^printf '#!/bin/sh.*?> \"\$stage/gemini\"$", install, re.MULTILINE | re.DOTALL)[0]
+ stage = root / "bin"
+ stage.mkdir()
+ subprocess.run(["bash", "-c", f"{quoted}\n{launcher}"], check=True,
+ env={"PATH": os.environ["PATH"], "root": str(root), "stage": str(stage)})
+ (stage / "gemini").chmod(0o755)
+ return stage / "gemini"
+
+
+def test_an_installs_gemini_which_node_cant_run_is_started_as_it_is(tmp_path):
+ """Handed install.sh's launcher, node would fail on its first line, a shell's: a target that runs an egress proxy
+ of its own, with its page armed, starts that CLI as before."""
+ launcher = _installed_by_install_sh(tmp_path)
+ assert launcher.read_text().startswith("#!/bin/sh\n")
+
+ assert gemini_bridge.cli_program({"PATH": str(launcher.parent), "AGENTENV_REAL_TIME": "1"}) == ["gemini"]
+
+
+@pytest.mark.parametrize("armed", [False, True])
+def test_the_cli_reads_no_input_from_the_servers_stdin(monkeypatch, tmp_path, run_settings, armed):
+ """Under supervisord, the server's stdin is a pipe that never closes, which the CLI would wait 500 ms on for piped
+ input every turn; under Docker, before supervisord, it was /dev/null."""
+ node, _ = _installed_like_the_image(tmp_path)
+ env = _env({"PATH": str(node.parent), agent_egress.EGRESS_PROXY_ENV: PROXY}, run_settings, clock_armed=armed)
+
+ _, spawned = _spawned(monkeypatch, env)
+
+ assert spawned["stdin"] == asyncio.subprocess.DEVNULL
+
+
+def test_the_cli_is_the_version_whose_date_line_the_relay_names_the_envs_date_in():
+ """The relay finds the CLI's date line by 0.38.2's wording (gemini_bridge._DATE_LINE), in a bundle no CI job builds:
+ a CLI bump checks that wording in the new bundle, then moves this pin."""
+ lock = json.loads((AGENT_DIR / "package-lock.json").read_text())
+
+ assert lock["packages"]["node_modules/@google/gemini-cli"]["version"] == "0.38.2"
+
+
+@pytest.mark.parametrize("armed, image", [(False, True), (True, True), (True, False)],
+ ids=["unarmed", "armed", "installed-under-an-armed-page"])
+def test_a_turn_on_an_armed_clock_starts_its_cli_on_real_time_and_names_the_envs_date(
+ monkeypatch, tmp_path, home, agent, client, armed, image):
+ """The call site: the turn reads the clock page, and on the image's armed one hands the CLI the marker, its
+ commands the proxy for the env's MCP server over TLS, and its model calls the env's date for the whole turn. An
+ install has no egress proxy of the image's, and its page, a computer's say, follows a clock the agent never opted in
+ to: its turns run as before."""
+ page = tmp_path / "agentenv-clock"
+ page.write_bytes(_page(int(armed)))
+ monkeypatch.setattr(agent_egress.clockpage, "PAGE", str(page))
+ monkeypatch.setattr(a2a_server, "env_today", lambda: ENV_TODAY)
+ for name in (*PROXY_VARS, agent_egress.EGRESS_PROXY_ENV):
+ monkeypatch.delenv(name, raising=False)
+ if image:
+ monkeypatch.setenv(agent_egress.EGRESS_PROXY_ENV, PROXY)
+ monkeypatch.setenv("LITELLM_BASE_URL", "https://litellm.example.com")
+ for name, url in zip(("modal", "gateway"), MCP_URLS):
+ client.post(a2a_server.MCP_CONFIG_V1.endpoint, json={"url": url, "name": name})
+ seen = {}
+
+ async def fake_run_gemini(**kwargs):
+ env = kwargs["env"]
+ seen.update(env=env, route=agent._routes[env["GOOGLE_GEMINI_BASE_URL"].rsplit("/", 1)[1]],
+ commands=_commands_env(env))
+ return gemini_bridge.GeminiResult(response="ok", tool_call_count=0, session_id=None)
+
+ monkeypatch.setattr(a2a_server, "run_gemini", fake_run_gemini)
+ send(client, "go")
+
+ env, commands = seen["env"], seen["commands"]
+ assert not PROXY_VARS & set(env)
+ if not (armed and image):
+ assert "AGENTENV_REAL_TIME" not in env and "BASH_ENV" not in env and seen["route"].today is None
+ assert not PROXY_VARS & set(commands) and gemini_bridge.cli_program(env) == ["gemini"]
+ return
+ assert (env["AGENTENV_REAL_TIME"], seen["route"].today) == ("1", ENV_TODAY)
+ direct = commands["NO_PROXY"].split(",")
+ assert commands["HTTPS_PROXY"] == PROXY and "gateway" in direct and "abc-123.w.modal.host" not in direct
+ assert not Path(env["BASH_ENV"]).exists()
+
+
+def test_the_changelogs_capture_runs_on_real_time_as_its_grants_expiry_is(home, changelog_dir, client):
+ """The CLI starts it in bash as a child, which follows the env's clock: on one ahead of real time, the grant would
+ look expired to it, and it would refuse every upload before sending it."""
+ client.post(CHANGELOG_PATH, json={"write_namespace": namespace_grant(), "roots": [str(home)]})
+
+ ((command,),) = [[h["command"] for h in e["hooks"]] for e in user_settings(home)["hooks"]["AfterTool"]]
+ assert shlex.split(command) == ["AGENTENV_REAL_TIME=1", sys.executable, str(changelog_dir / "capture.py")]
+ assert a2a_server.is_missing_capture_command(command) is False
+
+
+def _recording_tar(directory: Path) -> Path:
+ """A tar on PATH that records the marker it was started with, then fails, so a capture uploads nothing."""
+ directory.mkdir()
+ log = directory / "markers"
+ tar = directory / "tar"
+ tar.write_text(f'#!/bin/sh\necho "${{AGENTENV_REAL_TIME:-}}" >> {shlex.quote(str(log))}\nexit 2\n')
+ tar.chmod(0o755)
+ return log
+
+
+def test_the_changelogs_tar_runs_on_real_time_for_its_baseline_and_each_capture(monkeypatch, tmp_path, home,
+ changelog_dir, client):
+ """Its --listed-incremental snapshot keeps the time it ran: on an env clock ahead of real time that would be after
+ the next tool call's writes, which the next capture would then miss. The capture's Python, started with the marker,
+ hands it to no child, so it hands it to tar itself."""
+ markers = _recording_tar(tmp_path / "bin")
+ monkeypatch.setenv("PATH", f"{markers.parent}{os.pathsep}{os.environ['PATH']}")
+ monkeypatch.delenv("AGENTENV_REAL_TIME", raising=False)
+ client.post(CHANGELOG_PATH, json={"write_namespace": namespace_grant(), "roots": [str(home)]})
+
+ subprocess.run([sys.executable, str(changelog_dir / "capture.py")], input='{"tool_name": "write_file"}',
+ text=True, capture_output=True, check=True, timeout=60)
+
+ assert markers.read_text().split() == ["1", "1"]
+
+
+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/gemini/test_image_contract.py b/tst/unit/agents/gemini/test_image_contract.py
index 021fab736..e57d95466 100644
--- a/tst/unit/agents/gemini/test_image_contract.py
+++ b/tst/unit/agents/gemini/test_image_contract.py
@@ -7,10 +7,14 @@
import ast
import json
import re
+import shlex
+import tomllib
from tst.unit.agents.gemini.agent import AGENT_DIR
DOCKERFILE = (AGENT_DIR / "Dockerfile").read_text()
+SOURCES = AGENT_DIR.parents[2]
+SHARED = tomllib.loads((AGENT_DIR / "shared_sources.toml").read_text())
INSTALL_SH = (AGENT_DIR / "install.sh").read_text()
@@ -23,10 +27,22 @@ def _copied() -> list[str]:
for name in line.split()]
+def _source(name: str):
+ """Where the build context's ``name`` comes from: the folder, or a folder shared_sources.toml takes from agent-env's
+ own sources at that name."""
+ first, _, rest = name.partition("/")
+ return SOURCES / SHARED[first] / rest if first in SHARED else AGENT_DIR / name
+
+
+def _in_context(name: str) -> bool:
+ path = _source(name)
+ return path.is_dir() if name.endswith("/") else path.is_file()
+
+
def test_every_file_the_image_copies_is_in_the_folder():
copied = _copied()
- assert copied and all((AGENT_DIR / name).is_file() for name in copied), copied
+ assert copied and all(_in_context(name) for name in copied), copied
# install.sh and run.sh are install/v1's; a build context pruned to what the Dockerfile reads keeps them so.
assert {"a2a_server.py", "gemini_bridge.py", "gemini_changelog.py", "gemini_config.py", "gemini_kit.py",
"entrypoint.sh", "install.sh", "run.sh", "package.json", "package-lock.json"} <= set(copied)
@@ -43,10 +59,19 @@ def _imported(path) -> set[str]:
def test_the_image_and_an_install_carry_every_module_the_server_imports():
- modules = {path.stem: path for path in AGENT_DIR.glob("*.py")}
- needed = {"a2a_server.py"} | {f"{name}.py" for path in modules.values() for name in _imported(path) & set(modules)}
+ """The folder's own modules and those the build context takes from agent-env's sources, the egress rule and the
+ clock page's format among them, each by its name in the context."""
+ shared = {path.stem: f"{name}/{path.name}" for name, source in SHARED.items()
+ for path in (SOURCES / source).glob("*.py")}
+ modules = {**shared, **{path.stem: path.name for path in AGENT_DIR.glob("*.py")}}
+ needed, pending = set(), ["a2a_server"]
+ while pending:
+ if (name := modules[pending.pop()]) not in needed:
+ needed.add(name)
+ pending += _imported(_source(name)) & set(modules)
installed = set(re.search(r'^AGENT_FILES="([^"]+)"$', INSTALL_SH, re.MULTILINE).group(1).split())
+ assert {"agent_clock/agent_egress.py", "clock/clockpage.py"} <= needed
assert needed <= set(_copied()) and needed <= installed, (needed, installed)
@@ -99,5 +124,21 @@ 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_root_conf_starts_the_server_as_entrypoint_sh_does():
+ """root.conf runs uvicorn itself, for the marker to reach it, so it repeats entrypoint.sh's arguments, the graceful
+ shutdown that ends running turns' CLIs among them, on the port the image's ENV names, in its working directory."""
+ conf = (AGENT_DIR / "root.conf").read_text()
+ section = re.search(r"^\[program:agent\]\n(.*?)(?=^\[|\Z)", conf, re.MULTILINE | re.DOTALL)[1]
+ program = dict(line.split("=", 1) for line in section.splitlines() if "=" in line and not line.startswith(";"))
+ entrypoint = (AGENT_DIR / "entrypoint.sh").read_text()
+ started = shlex.split(re.search(r"^exec (uvicorn .+)$", entrypoint, re.MULTILINE)[1])
+
+ command = shlex.split(program["command"])
+ assert command[:3] == ["/usr/local/bin/python3", "-m", "uvicorn"]
+ assert command[3:] == [arg.replace("${A2A_PORT:-8000}", "%(ENV_A2A_PORT)s") for arg in started[1:]]
+ assert re.search(r"^ENV .*\bA2A_PORT=8000\b", DOCKERFILE, re.MULTILINE)
+ assert program["directory"] == re.findall(r"^WORKDIR (\S+)$", DOCKERFILE, re.MULTILINE)[-1]
diff --git a/tst/unit/agents/gemini/test_litellm_proxy.py b/tst/unit/agents/gemini/test_litellm_proxy.py
index a2ed2dafc..8b93f7f0b 100644
--- a/tst/unit/agents/gemini/test_litellm_proxy.py
+++ b/tst/unit/agents/gemini/test_litellm_proxy.py
@@ -221,6 +221,65 @@ def test_an_error_response_logs_the_litellm_routing_headers_that_are_present(cap
assert "x-litellm-model-api-base" not in message and "x-litellm-response-cost" not in message
+# ── the env's date on an armed clock ─────────────────────────────────────────────
+
+# The CLI's environment context as 0.38.2 sends it, its date line worded by its own clock, which is real time.
+_CONTEXT = ("\nThis is the Gemini CLI. We are setting up the context for our chat.\n"
+ "Today's date is Friday, November 20, 2026 (formatted according to the user's locale).\n"
+ "My operating system is: linux\n")
+_DATED = {"contents": [{"role": "user", "parts": [{"text": _CONTEXT}]},
+ {"role": "user", "parts": [{"text": "Today's date is what, by your clock?"}]}]}
+ENV_TODAY = "Tuesday, March 3, 2031"
+
+
+@pytest.mark.parametrize("today", [None, ENV_TODAY], ids=["unarmed", "armed"])
+def test_the_clis_date_line_names_the_envs_date_on_an_armed_clock_and_is_forwarded_as_sent_otherwise(
+ upstream, agent, client, today):
+ """The CLI stays on real time on an armed clock, so its date line is real; the model sees the env's date there
+ instead, as its commands do, and nothing else in the call changes."""
+ agent._routes[TOKEN] = a2a_server._Route(None, None, None, today)
+ sent = json.dumps(_DATED).encode()
+
+ client.post(GENERATE, content=sent)
+
+ (request,) = upstream.requests
+ assert request.content == (sent if today is None else sent.replace(b"Friday, November 20, 2026", today.encode()))
+
+
+def test_only_the_clis_own_context_names_the_envs_date_and_the_same_words_elsewhere_stay(upstream, agent, client):
+ """A prompt, a tool's result and a transcript the model reads may hold the CLI's date sentence, or its whole
+ context, as written on another day; the model gets them as they were, with the env's date in the CLI's own. A side
+ call of the CLI's, loop detection's say, sends recent turns without its context, and goes as sent."""
+ agent._routes[TOKEN] = a2a_server._Route(None, None, None, ENV_TODAY)
+ sentence = "Today's date is Monday, May 4, 2026 (formatted according to the user's locale)."
+ transcript = _CONTEXT.replace("Friday, November 20, 2026", "Monday, May 4, 2026")
+ shell = {"functionResponse": {"name": "run_shell_command", "response": {"output": f"{sentence}\n{transcript}"}}}
+ turns = [{"role": "user", "parts": [{"text": f"Is this right? {sentence}\n{transcript}"}]},
+ {"role": "user", "parts": [shell]}]
+ sent, side = (json.dumps({"contents": contents}, separators=(",", ":")).encode()
+ for contents in ([{"role": "user", "parts": [{"text": _CONTEXT}]}, *turns], turns))
+
+ client.post(GENERATE, content=sent)
+ client.post(GENERATE, content=side)
+
+ turn, side_call = upstream.requests
+ assert turn.content == sent.replace(b"Friday, November 20, 2026", ENV_TODAY.encode())
+ assert turn.content.count(b"Monday, May 4, 2026") == 4
+ assert side_call.content == side
+
+
+def test_the_chat_completions_bridge_names_the_envs_date_too(vertex, agent, client):
+ agent._routes[TOKEN] = a2a_server._Route("vertex_ai/global/gemini-3.1-pro-preview", "p-1", None, ENV_TODAY)
+
+ client.post(GENERATE, json=_DATED)
+
+ (request,) = vertex.requests
+ messages = json.loads(request.content)["messages"]
+ assert f"Today's date is {ENV_TODAY} (formatted" in messages[0]["content"]
+ assert "November 20, 2026" not in request.content.decode()
+ assert messages[1]["content"] == "Today's date is what, by your clock?"
+
+
# ── provider-prefixed models: the chat-completions bridge ────────────────────────
diff --git a/tst/unit/agents/gemini/test_object_transfer.py b/tst/unit/agents/gemini/test_object_transfer.py
index 22192b7df..cb719422a 100644
--- a/tst/unit/agents/gemini/test_object_transfer.py
+++ b/tst/unit/agents/gemini/test_object_transfer.py
@@ -333,7 +333,8 @@ def test_enable_installs_the_capture_as_an_after_tool_hook_run_by_the_agents_pyt
(entry,) = settings(home)["hooks"]["AfterTool"]
assert entry == {"matcher": ".*", "hooks": [{
- "type": "command", "command": f"{sys.executable} {changelog_dir / 'capture.py'}", "timeout": 600000}]}
+ "type": "command", "command": f"AGENTENV_REAL_TIME=1 {sys.executable} {changelog_dir / 'capture.py'}",
+ "timeout": 600000}]}
def test_enable_refuses_while_a_turn_runs(home, changelog_dir, agent, client):
diff --git a/tst/unit/agents/gemini/test_server_exit.py b/tst/unit/agents/gemini/test_server_exit.py
new file mode 100644
index 000000000..07509f85e
--- /dev/null
+++ b/tst/unit/agents/gemini/test_server_exit.py
@@ -0,0 +1,85 @@
+"""When the image's A2A server exits, the container exits with it, as when the server was the container's process:
+root.conf never starts it again, and its event listener, run here as supervisord runs it, stops supervisord, its parent,
+on the server's EXITED or FATAL alone, while the follower and the proxy keep restarting in place."""
+
+from __future__ import annotations
+
+import configparser
+import json
+import shlex
+import subprocess
+import sys
+
+import pytest
+
+from tst.unit.agents.gemini.agent import AGENT_DIR
+
+ACK = "RESULT 2\nOKREADY\n"
+
+# The listener's parent, standing in for supervisord: SIGTERM blocked, so one the listener sends is pending by the time
+# its acknowledgement, written after the signal, is read.
+PARENT = """
+import json, signal, subprocess, sys
+signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
+listener = subprocess.Popen(json.loads(sys.argv[1]), stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+ready, acks = listener.stdout.read(6).decode(), []
+for name, payload in json.loads(sys.argv[2]):
+ header = f"ver:3.0 server:supervisor serial:1 pool:agent-exit poolserial:1 eventname:{name} len:{len(payload)}\\n"
+ listener.stdin.write((header + payload).encode())
+ listener.stdin.flush()
+ acks.append([listener.stdout.read(17).decode(), signal.SIGTERM in signal.sigpending()])
+listener.stdin.close()
+listener.wait()
+print(json.dumps({"ready": ready, "acks": acks}))
+"""
+
+
+def _conf() -> configparser.RawConfigParser:
+ """root.conf as supervisord reads it: ';' or '#' after whitespace starts a comment, and a continuation line is a
+ line of its value."""
+ conf = configparser.RawConfigParser(inline_comment_prefixes=(";", "#"), strict=False)
+ conf.read_string((AGENT_DIR / "root.conf").read_text())
+ return conf
+
+
+def _event(name: str, program: str, from_state: str) -> list[str]:
+ extra = " expected:0 pid:4242" if name == "PROCESS_STATE_EXITED" else ""
+ return [name, f"processname:{program} groupname:{program} from_state:{from_state}{extra}"]
+
+
+def _listen(events: list[list[str]]) -> dict:
+ command = shlex.split(_conf()["eventlistener:agent-exit"]["command"])
+ assert command[0] == "/usr/local/bin/python3"
+ argv = [sys.executable, "-c", PARENT, json.dumps([sys.executable, *command[1:]]), json.dumps(events)]
+ done = subprocess.run(argv, capture_output=True, text=True, timeout=60)
+ assert done.returncode == 0, done.stderr
+ return json.loads(done.stdout)
+
+
+def test_the_server_is_never_started_again_and_the_follower_and_the_proxy_are():
+ conf = _conf()
+
+ assert (conf["program:agent"]["autorestart"], conf["program:agent"]["startretries"]) == ("false", "0")
+ assert conf["program:clock"]["autorestart"] == conf["program:egress"]["autorestart"] == "true"
+
+
+def test_the_listener_hears_the_server_exit_or_give_up_starting_and_is_ready_before_it_starts():
+ conf = _conf()
+ listener = conf["eventlistener:agent-exit"]
+
+ assert set(listener["events"].split(",")) == {"PROCESS_STATE_EXITED", "PROCESS_STATE_FATAL"}
+ assert "%" not in listener["command"]
+ assert int(listener["priority"]) < int(conf["program:agent"]["priority"])
+
+
+@pytest.mark.parametrize(("name", "from_state"),
+ [("PROCESS_STATE_EXITED", "RUNNING"), ("PROCESS_STATE_FATAL", "BACKOFF")])
+def test_the_listener_stops_supervisord_when_the_server_exits_and_lets_the_followers_and_proxys_exits_pass(
+ name, from_state):
+ others = [_event("PROCESS_STATE_EXITED", "clock", "RUNNING"), _event("PROCESS_STATE_EXITED", "egress", "RUNNING"),
+ _event("PROCESS_STATE_FATAL", "clock", "BACKOFF")]
+
+ heard = _listen([*others, _event(name, "agent", from_state)])
+
+ assert heard["ready"] == "READY\n"
+ assert heard["acks"] == [[ACK, False]] * len(others) + [[ACK, True]]
diff --git a/tst/util/fake_gemini.py b/tst/util/fake_gemini.py
new file mode 100644
index 000000000..b3072e217
--- /dev/null
+++ b/tst/util/fake_gemini.py
@@ -0,0 +1,142 @@
+"""A fake Gemini API, as LiteLLM's /gemini passthrough serves it, so the real Gemini CLI runs with no model key: each
+``:streamGenerateContent`` (one server-sent event) and ``:generateContent`` call is answered by a responder, and every
+request is recorded. The CLI's own calls that offer no tools, such as its next-speaker check, are answered with text, or
+with a JSON object when they ask for one."""
+
+from __future__ import annotations
+
+import json
+import threading
+from collections import deque
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+
+@dataclass(frozen=True)
+class Text:
+ text: str
+
+
+@dataclass(frozen=True)
+class Call:
+ name: str
+ args: dict
+
+
+@dataclass
+class Seen:
+ path: str
+ body: dict
+
+
+Responder = Callable[[dict], Text | Call]
+GENERATE = (":generateContent", ":streamGenerateContent")
+
+
+def answer(text: str) -> Responder:
+ """Every request answered with ``text``."""
+ return lambda body: Text(text)
+
+
+def shell_then_answer(command: str, *, prefix: str = "") -> Responder:
+ """Run ``command`` with the CLI's shell tool, then answer with ``prefix`` and the tool's output."""
+
+ def respond(body: dict) -> Text | Call:
+ result = _tool_result_text(body)
+ return Text(f"{prefix}{result}") if result is not None else Call("run_shell_command", {"command": command})
+
+ return respond
+
+
+def _tool_result_text(body: dict) -> str | None:
+ """The output of the tool call the latest content answers, or None."""
+ contents = body.get("contents") or []
+ for part in contents[-1].get("parts", []) if contents else ():
+ if "functionResponse" in part:
+ return json.dumps(part["functionResponse"].get("response"))
+ return None
+
+
+@dataclass
+class FakeGemini:
+ host: str
+ respond: Responder = field(default_factory=lambda: answer("pong"))
+ # The latest requests only: each call resends the whole history.
+ seen: deque[Seen] = field(default_factory=lambda: deque(maxlen=200))
+ _server: ThreadingHTTPServer | None = None
+ _lock: threading.Lock = field(default_factory=threading.Lock)
+
+ def __enter__(self) -> FakeGemini:
+ self._server = ThreadingHTTPServer((self.host, 0), _handler(self))
+ self._server.daemon_threads = True
+ threading.Thread(target=self._server.serve_forever, daemon=True).start()
+ return self
+
+ def __exit__(self, *exc) -> None:
+ self._server.shutdown()
+ self._server.server_close()
+
+ @property
+ def url(self) -> str:
+ return f"http://{self.host}:{self._server.server_port}"
+
+ def generate_calls(self) -> list[Seen]:
+ """The model calls that offer the model tools: the turn's own, not the CLI's utility calls or token counts."""
+ return [seen for seen in self.seen if seen.path.endswith(GENERATE) and seen.body.get("tools")]
+
+ def tool_results(self) -> list[str]:
+ """The output of each tool call the CLI sent back."""
+ return [text for seen in self.generate_calls() if (text := _tool_result_text(seen.body)) is not None]
+
+
+_SCHEMA_VALUES = {"STRING": "user", "INTEGER": 1, "NUMBER": 1, "BOOLEAN": False, "ARRAY": [], "OBJECT": {}}
+
+
+def _schema_answer(schema: dict) -> dict:
+ """An object of ``schema``'s properties, each of its type: the CLI's router and next-speaker check ask for one."""
+ return {name: _SCHEMA_VALUES.get(str(prop.get("type")).upper(), "user")
+ for name, prop in (schema.get("properties") or {}).items()}
+
+
+def _reply(fake: FakeGemini, body: dict) -> dict:
+ if body.get("tools"):
+ reply = fake.respond(body)
+ else:
+ schema = (body.get("generationConfig") or {}).get("responseJsonSchema")
+ reply = Text(json.dumps(_schema_answer(schema)) if isinstance(schema, dict) else "fake")
+ part = ({"text": reply.text} if isinstance(reply, Text)
+ else {"functionCall": {"name": reply.name, "args": reply.args}})
+ return {"candidates": [{"content": {"role": "model", "parts": [part]}, "finishReason": "STOP", "index": 0}],
+ "usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "totalTokenCount": 15}}
+
+
+def _handler(fake: FakeGemini) -> type[BaseHTTPRequestHandler]:
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *args) -> None:
+ pass
+
+ def do_POST(self) -> None:
+ path = self.path.split("?", 1)[0]
+ body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}")
+ with fake._lock:
+ fake.seen.append(Seen(path, body))
+ if path.endswith(":countTokens"):
+ return self._send(200, json.dumps({"totalTokens": 10}).encode(), "application/json")
+ if not path.endswith(GENERATE):
+ return self._send(404, json.dumps({"error": {"message": path}}).encode(), "application/json")
+ reply = json.dumps(_reply(fake, body))
+ if path.endswith(":streamGenerateContent"):
+ return self._send(200, f"data: {reply}\r\n\r\n".encode(), "text/event-stream")
+ self._send(200, reply.encode(), "application/json")
+
+ def _send(self, status: int, data: bytes, content_type: str) -> None:
+ self.send_response(status)
+ self.send_header("content-type", content_type)
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ return Handler