Skip to content

[FD-5916] feat(agents): the Gemini CLI image follows the env's clock - #770

Closed
williamloo-scale wants to merge 64 commits into
mainfrom
wloo/gemini-clock-image
Closed

williamloo-scale wants to merge 64 commits into
mainfrom
wloo/gemini-clock-image

Conversation

@williamloo-scale

@williamloo-scale williamloo-scale commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What and why

The Gemini CLI image can follow a task env's clock, like Claude Code's (#726, #818, #831, #832). It is off unless a
sync_env_clock sets agent_clock
(require_agent_clock implies it).

Claude, working with Edgar, finished this PR on William's branch: the review fixes below, the crash behaviour in
"Clock off", and the VM runs in "Testing".

Opted in, Gemini works differently from Claude Code: the CLI itself stays on real time, and only the commands the model
runs follow the clock.
gemini-cli 0.38.2 can't follow the clock safely, for three reasons:

  • Its lock crashes the turn. It judges ~/.gemini/projects.json.lock stale by comparing the lock's file time, which
    is the kernel's and real, with its own clock (proper-lockfile, 10 s). With the clock more than 10 s ahead, two of its
    own lockers race, and the turn exits 1 with Lock is already released / ECOMPROMISED.
  • Its cleanups delete what it needs. Its session retention (30 d) deletes the session being resumed, and its
    tool-output (30 d) and log (7 d) cleanups delete their files the same way.
  • It can't take the proxy. It sends every request through a proxy it's handed, ignoring NO_PROXY, its loopback
    model relay included. So a faked CLI goes direct and checks the env's MCP certificates against the virtual date.
    That is fix(claude-code): reach env MCP servers through the egress proxy on an armed clock #818's bug: an HTTPS MCP server on Modal whose certificate starts after the virtual date gives no env tools.

How it follows the clock, opted in

The armed path is taken only in the image, once its clock page is armed. The image's root.conf hands the A2A server
the egress proxy (AGENTENV_EGRESS_PROXY), and only sync_env_clock's agent_clock arms the image's page. An install
(install/v1) has no such proxy, and its page, a computer's say, follows a clock the agent never opted in to, so its
turns run as on main (gemini_bridge.cli_on_real_time).

  • The CLI, on real time.
    • Each turn on an armed clock starts the CLI as node /opt/agent/node_modules/@google/gemini-cli/bundle/gemini.js,
      with agent-env's real-time marker (AGENTENV_REAL_TIME=1) and GEMINI_CLI_NO_RELAUNCH=true.
    • node is started directly because gemini starts with #!/usr/bin/env node, and env, started with the marker,
      would stay on real time itself and start node without it. The relaunch is off because the CLI's relaunched child
      would inherit no marker.
    • The CLI then compares real times with real times: its locks, its cleanups, credential expiry and TLS checks. It
      reaches its relay and the env's MCP servers directly, at any virtual date, ahead of real time or behind it.
  • The model's commands, on the env's clock.
    • Everything the CLI starts follows the clock, because libfaketime takes the marker out of what children inherit.
    • Every bash it starts (each command the model runs, each hook) first reads a file beside the run's settings, named
      by BASH_ENV. That file exports the egress proxy by the shared rule (agent_egress.egress_env, given the model
      endpoint and every MCP server's URL): 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 variables.
  • The env's date. The CLI words its "Today's date is …" line from its own clock, which is real. The agent's model
    relay rewrites that line to the env's date in every model call that carries the CLI's context, the chat-completions
    bridge's included. The CLI always sends that context as a call's first content. The same sentence in a prompt, a
    tool's result or a pasted transcript reaches the model as written. The relay reads the date at the turn's start from
    date, a child of the server, which follows the clock as the model's commands do. The
    commands' date and the gateway's get_time show the env's time.
  • The changelog, on real time.
    • The capture hook runs with the marker. Otherwise it compared its grant's expiry with the env's clock and refused
      every upload once the clock was past it.
    • Its tar --listed-incremental runs (the baseline and each capture) also get the marker. On the env's clock ahead
      of real time, tar recorded that clock's time as its baseline and missed files modified after it.

What the model can still see of real time, opted in

  • File times. ls -l, stat and the like show the kernel's times, which are real, for every file, as for every
    clocked agent: agent-env's libfaketime is built without stat faking.
  • The date line, without the relay. A CLI that calls no relay (no LITELLM_BASE_URL, or a GOOGLE_GEMINI_BASE_URL
    of its own) shows the real date in that line.
  • The date line, within a turn. The line names the env's date as the turn started, as the CLI words its own once
    per start, so at a fast clock rate it can lag the shell's date until the next turn.

Clock off

The bridge gives the CLI the environment it gave it on main, with no marker, proxy variables, BASH_ENV or relaunch
switch, and the CLI starts as gemini, through its shebang, which relaunches itself as on main. The relay rewrites no
date line. A unit test pins this. One bridge change applies with the clock off too: the CLI's stdin is /dev/null. Under Docker
that is what main's CLI inherited from the server. Under supervisord the server's own stdin is a pipe that never
closes, and the CLI would wait 500 ms for piped input on every start.

What differs at the image level, clock or not:

  • The start. The image has no USER line. It starts as root, and start-agent makes the clock page and boots the
    egress proxy, then execs root's supervisord (root.conf) as PID 1. That runs the clock follower and the egress
    proxy, each as its own user (agentenv-clock, agentenv-egress), and the A2A server as agent. A docker exec
    without -u, or anything else that runs commands as the image's user, now runs as root, not agent.
  • Modal. Modal ran the image as root, so the server, the CLI and the model's commands ran as root. They now run as
    agent, uid 10001. The model can no longer write outside /workspace, /app, /tmp and its home, or install
    system packages, as it could as root.
  • The egress proxy's boot. It runs on every start: it mints the proxy's CA and trusts it in the system store,
    agent-env's bundles and every certifi bundle in the image, its key the egress user's alone. A failed boot stops the
    container with exit 2 before the server starts. With the clock off, nothing goes through the proxy unless a process
    is handed proxy variables.
  • A provider's CA bundle. start-agent appends a bundle that SSL_CERT_FILE, REQUESTS_CA_BUNDLE,
    NODE_EXTRA_CA_CERTS or CURL_CA_BUNDLE names (Sail's, for one) to agent-env's bundles and the proxy's roots, once
    each, since root.conf points the server's trust variables at agent-env's bundles instead.
  • The preload. /etc/ld.so.preload loads agent-env's libfaketime and its TLS shim into every process. They fake
    only the agent's user's processes, and with the clock off those read an unarmed page, so every clock read is real,
    and the shim checks certificates against that real time.
  • The server's environment, and so the CLI's and every command's the model runs, adds USER=agent,
    LOGNAME=agent, supervisord's SUPERVISOR_ENABLED, SUPERVISOR_PROCESS_NAME, SUPERVISOR_GROUP_NAME and
    SUPERVISOR_SERVER_URL (its socket is root's alone), AGENTENV_EGRESS_PROXY=http://127.0.0.1:3128, and the CA
    variables NODE_EXTRA_CA_CERTS=/etc/agentenv/ca.pem, SSL_CERT_FILE and
    REQUESTS_CA_BUNDLE=/etc/agentenv/ca-bundle.pem. HOME is /home/agent, as before. The server starts with
    AGENTENV_REAL_TIME=1, which libfaketime takes out of its environment before Python reads it.
  • The server's process. When the A2A server exits, for any reason, the container exits, as on main, where the
    server was the container's process. root.conf never starts the server again (autorestart=false, and
    startretries=0, so a server that exits as it starts is FATAL at once), and an event listener (agent-exit, a few
    lines of Python inline in root.conf) stops supervisord on the server's PROCESS_STATE_EXITED or PROCESS_STATE_FATAL.
    supervisord then stops the follower and the proxy and exits. A server started again in place would have had none of
    the run's registrations (the env's MCP servers, configuration, peers, running tasks): the turn running at the crash
    polled "Task not found" until its timeout, and later turns ran without the env's tools. Measured on the VM, the
    container stops about 2 s after the server dies, and prompt_agent fails about 60 s after, as on main.
    • The follower and the proxy keep restarting in place: the listener lets their events pass.
    • A normal stop is unchanged: supervisord stops the server (STOPPED, not EXITED), the follower and the proxy, and
      exits. SIGTERM goes to the server's process group, SIGKILL after 30 s; the server's own graceful shutdown (5 s,
      which ends running turns' CLIs) is unchanged, and root.conf's command is pinned to entrypoint.sh's.
    • The exit status is 0 when the server crashed, where main's was the server's own (137 for the kill on the VM):
      supervisord 4.2.5 exits 0 however it's stopped. Its log line before it stops, in the container's output, says what
      happened: exited: agent (terminated by SIGKILL; not expected).
    • The server's stderr goes to the container's stdout.
  • The changelog's commands. The AfterTool hook's command is AGENTENV_REAL_TIME=1 <python> <capture.py>, and the
    tar --listed-incremental runs get the marker, clock or not. With the clock off those processes are on real time
    anyway, so only the command the CLI's settings show changes. The prefix relies on the CLI starting hooks through
    bash, as 0.38.2 does.
  • The image's contents. supervisor 4.2.5 in the image's Python, which the model's scripts share; the two system
    users; the clock library, the TLS shim, the follower and the egress proxy's binary; /etc/agentenv. The build has two
    more stages (the proxy's Go build and tests, and libfaketime's C build), and the image's build context takes
    utils/faketime_clock, utils/egress_proxy and utils/agent_clock, so a change to any of them rebuilds it.
  • install/v1 copies agent_egress.py and clockpage.py beside the bridge, and never takes the armed path.

Started as another user, the image runs the A2A server alone, as before, with no supervisord, follower or proxy. The
preload still loads, and reads no page there, so time is real.

Review findings and fixes

Finding Fix Pinned by
projects.json.lock race with the clock more than 10 s ahead (ECOMPROMISED, exit 1) CLI on real time test_env_clock.py real-time, node-direct and call-site tests
sessionRetention (30 d) deletes the resumed session; tool-output and log cleanups CLI on real time same
The CLI's relaunch loses the marker GEMINI_CLI_NO_RELAUNCH=true same
The gemini shebang's env consumes the marker cli_program starts node on the script test_a_cli_on_real_time_is_started_as_its_script_run_by_node…
The CLI's own MCP TLS against the virtual date (the #818 bug), and its stripped proxy CLI on real time, direct; commands get the shared rule through BASH_ENV test_on_an_armed_clock_the_models_commands_go_out_by_the_shared_egress_rule, the call-site test
The changelog hook's grant looks expired with the clock ahead hook started with the marker test_the_changelogs_capture_runs_on_real_time…
The changelog tar's incremental baseline is virtual both tar runs get the marker test_the_changelogs_tar_runs_on_real_time…
The CLI's date line would be real the relay writes the env's date test_litellm_proxy.py date tests, test_the_envs_date_is_worded…
An install's gemini is install.sh's shell launcher. Under an armed page, a computer's say, the turn took the armed path, and node failed on the launcher (SyntaxError) every turn the armed path only where the image runs its egress proxy (cli_on_real_time); node is handed the CLI's script only when gemini resolves to a .js the call-site test's installed-under-an-armed-page case, test_an_installs_gemini_which_node_cant_run_is_started_as_it_is (install.sh's own launcher text)
The CLI inherited supervisord's never-closed stdin, and waited 500 ms for piped input on every start stdin /dev/null test_the_cli_reads_no_input_from_the_servers_stdin
No CI job builds the image, so nothing would catch a CLI bump that rewords the date line a pin on package-lock's CLI version, whose docstring says to recheck the wording test_the_cli_is_the_version_whose_date_line_the_relay_names_the_envs_date_in
The relay rewrote every matching date sentence in a call, so a prompt, a tool's result or a pasted CLI transcript holding it reached the model with the env's date only the date line of the call's first content, and only when that content is the CLI's context (count=1, bytes otherwise as sent) test_only_the_clis_own_context_names_the_envs_date_and_the_same_words_elsewhere_stay
root.conf's server command wasn't pinned to entrypoint.sh's (graceful shutdown, working directory) test test_root_conf_starts_the_server_as_entrypoint_sh_does
supervisord restarted a crashed server in place: it lost the run's registrations, the dead one's CLI went on, and prompt_agent polled "Task not found" until its timeout the container exits with the server, as on main (autorestart=false, startretries=0, the agent-exit listener) test_server_exit.py: root.conf read as supervisord reads it, and the listener run as supervisord runs it, fed the follower's, the proxy's and the server's events

Each fix is mutation-checked: 30 mutations of the wiring, each killed by the tests meant to kill it.

Changes

  • gemini_bridge.py:
    • cli_on_real_time decides a turn's path: the image's egress proxy, and an armed page.
    • cli_env adds the marker, the relaunch switch and the commands' BASH_ENV file on that path, and is otherwise
      unchanged.
    • cli_program starts node directly for a real-time CLI whose gemini is the CLI's script.
    • run_gemini gives the CLI /dev/null as stdin.
    • env_today / with_date put the env's date in the date line of the CLI's context, the call's first content.
  • a2a_server.py: each turn's route carries the env's date, which the relay (passthrough and chat-completions bridge)
    writes in.
  • gemini_config.py: the commands' file goes with the run's settings.
  • gemini_changelog.py: the capture hook and its tar run on real time.
  • Image:
    • The clock and egress stages come from utils/faketime_clock and utils/egress_proxy, plus agent_clock
      (shared_sources.toml).
    • start-agent, root.conf, and install.sh / Dockerfile copying agent_egress.py and clockpage.py beside the
      bridge.
    • root.conf: the server isn't restarted, and the agent-exit listener stops the container when it exits.
  • Tests:
    • tst/unit/agents/gemini/test_env_clock.py, the date tests in test_litellm_proxy.py, the root.conf pin in
      test_image_contract.py, and test_server_exit.py.
    • tst/util/fake_gemini.py, a stand-in for LiteLLM's /gemini passthrough. With it, the local agent-clock e2e's
      Gemini row runs a real turn on the armed clock: date line, the shell's date, proxy, and node started directly.
  • Docs: the gemini README's "The env's clock" section and its image paragraph, and agents/README.md.

No shared code changed: utils/egress_proxy, utils/faketime_clock and utils/agent_clock are untouched, so no other
image is rebuilt.

Testing

  • Unit tests: 1409 passed for tst/unit/agents, tst/unit/task_step/agent_clock_test.py, tst/unit/utils and the
    shipped bundles, on the head merged with main. The 46 skips need Linux, GNU tar or a filesystem other than APFS,
    which CI has; on the VM (Ubuntu 24.04) the earlier head ran the same set with no skips (1417 passed), and this head
    ran tst/unit/agents/gemini and the clocked-image tests with none (218 passed). ruff is clean.

  • Mutation check: 30 of 30 mutations killed, each by the test meant to kill it: the 19 of the clock work, on macOS
    and on Linux; 8 of root.conf's crash wiring (the listener's program filter, its kill, its events, its priority, a
    ; that supervisord's parser would take for a comment, the server's autorestart and startretries); and 3 of the
    date line's scope (no count=1, no check of the first content, any first text taken for the context).

  • The date line's scope, on the last head: the Gemini and agent unit tests passed on macOS (1178). In 0.38.2's
    bundle, every call that carries the CLI's context sends it first: the chat (getInitialChatHistory), compression,
    and both router classifiers, which send a history slice and then the request. The SDK writes contents before
    systemInstruction. Loop detection sends <original_user_request> first, but only after 30 turns, when its 20-item
    slice no longer reaches the context.

  • supervisord 4.2.5 itself, with root.conf's listener, on macOS: the clock program killed comes back and supervisord
    stays; the server killed, or failing as it starts (FATAL), stops supervisord within 2 s; a normal stop exits 0.

  • Real CLI (0.38.2) against a stand-in Gemini API, through this branch's A2A server with an armed clock page, on the
    head before the last review round (it changed the path's gate, the launcher check and stdin, not the armed path):

    • The CLI ran as node …/bundle/gemini.js.
    • The model's commands had the shared rule's proxy variables.
    • Every model call's date line, the CLI's router call included, named the env's date.
    • 4 turns resumed one session, and the last call sent every earlier turn.
  • Real CLI, unarmed: the CLI relaunched as on main, with no proxy variables and the real date.

  • On a VM (i-099c903a905ef84c1, Ubuntu 24.04, head ca6002219), A/B against main as published (PyPI
    0.9.1609, its Gemini image ghcr.io/scaleapi/agentenv-gemini@sha256:1f73da02…, whose bridge and server match the
    wheel's sources). The model was gemini-2.5-flash; envs ran on local Docker, and on Modal where the row says so.

    Check Requirement branch main
    FD-6434 repro (stand-in model API, no key): 4 turns of about 40 s at real time, +75 d, +200 y, 1950 history and working state survive pass at all four: turn 4's call sent turns 1-3, one session file with real mtimes, no lock error; the command saw marker=[] and the proxy, under node …/bundle/gemini.js. +1000 y can't be armed: see Limits n/a (no clock); unarmed, same result and the same relaunched CLI as the branch unarmed
    the same with a jump 10 s into turn 2, 3600x in turn 3 and a step back before turn 4 same pass at all four clocks n/a
    integration row (test_agent_env_clock_local.py), with Claude Code's and OpenCode's real turn on the armed clock; no regression 3 passed; Gemini's date line read Tuesday, March 4, 2031 n/a
    g-noclock, g-off, g-off-modal-agent (clock off: none, armed without agent_clock; agent local and on Modal) main's CLI command and environment; real date everywhere pass: the relaunched CLI (--max-old-space-size), stdin /dev/null, no proxy variables, marker or BASH_ENV, real shell date and date line, get_time only when armed, no egress rows, no follower; the environment adds what "Clock off" lists same results
    g-on, g-late-on, g-require, g-require-late, g-on-modal-agent (2027-02-01) shell date, date line and get_time at the env's date; commands through the proxy; the CLI direct pass: node …/bundle/gemini.js with AGENTENV_REAL_TIME=0 (scrubbed), GEMINI_CLI_NO_RELAUNCH and BASH_ENV, no proxy variables; the egress log holds only the command's curl. On Modal: dumb-init, start-agent, supervisord, the server as uid 10001 doesn't follow (real shell date and date line); require_agent_clock fails the step: can't follow the clock … not_advertised
    g-before-cert-on (2026-10-27; the env's *.w.modal.host certificate starts 2026-11-19) and g-behind-on (2025-06-01), env on Modal the env's MCP tools work pass: MCP over HTTPS, get_time, shell date and date line at the clock MCP works (agent on real time)
    g-long-p75d, -p200y, -y1950 one session, every label, no lock error pass: every turn listed every label, one session file, no lock error p75d: history kept, real dates
    g-changelog-on at +75 d the second increment carries the changed file pass: two increments, the second with workspace/notes.txt, tar times real, no upload failure same
    g-two-agents-on (Claude Code first, Gemini late) both at the env's date pass n/a
    chaos on one conversation: 3600x, frozen with a jump, the follower killed, 1950, +200 y, reset_env, clear each next turn runs; clear returns to main's path with history intact pass, 6 of 6 turns with every label; after clear, the real date line and shell date n/a
    the model endpoint blocked for 45 s mid-turn (443 dropped in the agent's network namespace) the turn completes pass, and the next turn n/a
    the server killed mid-turn, on the head before the crash change (supervisord restarted it) no CLI of the killed server goes on the CLI was gone within 12 s, but that turn failed only at its timeout ("Task not found") and the next ran without the env's MCP tools: the crash change below replaces this the container ends; later turns fail
    SIGTERM to agent-env run mid-turn teardown clean exit 143 after 12 s; no container or network left exit 143 after 2 s; same
    4 concurrent opted-in runs each at the env's date 4 of 4 pass n/a
    the clock armed 15 s into a turn (exploratory) as Limits say that turn's later commands followed the clock; its date line and tools stayed unarmed; the next turn passed n/a
    install placement under an armed computer page main's path: gemini, no marker not run (needs a multi env with a composed computer); the unit tests cover it n/a
    spend about $1.25 of model calls for both sides
  • On the VM again, head 7d3e0d857 (the crash change, merged with main), local Docker, the image rebuilt, a
    stand-in Gemini API on the Docker bridge, since the VM holds no model key now. main is its published image as above.

    Check branch main
    x-kill: the server killed -9 while the turn's command runs (it writes a line, sleeps 40 s, writes another; opted in) the container stopped 2.2 s after the kill, exit 0, its log exited: agent (terminated by SIGKILL; not expected); prompt_agent failed 58.7 s after the kill, AgentUnreachableError: … stopped answering: 5 polls in a row over 60s; the file kept only its first line, and no sleep 40 was left on the host 50 s later the container stopped 0.2 s after the kill, exit 137; prompt_agent failed 60.1 s after, with the same error; the same file and no process left
    x-off: a turn with the clock off shell date real, no proxy variables, HTTPS 200 direct, date line Saturday, November 21, 2026 (real) n/a
    x-on: a turn opted in at 2027-02-04 shell date 2027-02-04, the proxy, HTTPS 200 through it, date line Thursday, February 4, 2027 n/a
    x-follower: the follower and the proxy killed -9 on an armed clock, then a turn the container stayed up, both came back within 2 s, the server kept its pid; the turn ran at the env's date through the proxy (HTTPS 200) n/a
    the integration row on the rebuilt image 1 passed: date line Tuesday, March 4, 2031, node …/bundle/gemini.js, teardown terminated 1, failed 0 n/a
    the image alone (docker run): docker stop -t 30 exit 0 in 2.3 s
    the image alone: the server killed -9; sent SIGTERM alone; failing to start (A2A_PORT=99999, FATAL) the container stopped 2.2 s, 3.4 s and 5.8 s (from docker run) after, exit 0 each
    the image alone: the follower and the proxy killed -9, then 5 more kills the container stayed up, the server kept its pid, both RUNNING
    every run's teardown no container, network or sandbox folder left same

Limits

  • A clock armed while a turn runs reaches that turn's CLI, which was started unarmed, so the CLI follows it for the
    rest of the turn, without the proxy. The next turn starts as above.
  • The heap. On an armed clock the CLI keeps Node's default heap, which its relaunch would have raised to half the
    host's memory (autoConfigureMemory, on by default). A headless turn doesn't approach Node's default.
  • The date line's wording. It's rewritten only through the agent's relay, and only in 0.38.2's wording. A unit test
    pins the CLI's version, so a bump has to recheck the wording; only an image run sees the bundle itself.
  • The locale. env_today words the date as Node does under the image's LANG=C.UTF-8 (en-US). Under another
    LANG the CLI's own wording would differ and the line would be replaced in English.
  • Non-bash children. BASH_ENV reaches bash alone. A child the CLI starts without bash (a stdio MCP server, the
    browser agent) would follow the clock without the proxy; none is configured today.
  • The model sees the switch. On an armed clock, the model's commands can see BASH_ENV in their environment.
    (GEMINI_CLI_NO_RELAUNCH=true is there on main too: the CLI's relaunch sets it for its child.)
  • Far dates. The clock page holds nanoseconds in a signed 64-bit field, so an agent can follow no date past
    2262-04-11. At +1000 years the follower exits on struct.error and restarts in a loop, and sync_env_clock reports
    only that the follower "hasn't heard from the gateway". This is the shared clock code, the same for every clocked
    image and computer; +200 years works.
  • The changelog's apply (tar -x, -t) still runs on the env's clock: only the --listed-incremental runs moved.
    Extracted files keep their archived times; with the clock behind, tar may warn of a time stamp in the future.
  • A target with an egress proxy of its own. An install whose environment names an AGENTENV_EGRESS_PROXY (the
    browser computer base's image does) and whose page is armed takes the armed path: its commands get that proxy, and
    the relay names the date date gives the server. Its CLI starts through install.sh's launcher, which node can't run,
    so it runs on real time only if its user isn't the one the target fakes.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; no new actionable issue remains.

Summary

Gemini’s image can follow the env’s clock while keeping the CLI itself on real time.

  • Gemini turns use the task clock for model-run commands.
  • The Gemini image boots its clock and proxy under a root supervisor.
  • The container stops when its Gemini server exits.
  • Gemini changelog captures compare timestamps on real time.

Both earlier, unnumbered findings are addressed: the image includes the shared clock helpers, and date replacement is limited to the CLI’s opening context. No new actionable issues were found.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Turn starts] --> B{Image clock armed?}
    B -->|No| C[Start Gemini as before]
    B -->|Yes| D[Start Node directly on real time]
    D --> E[CLI reaches model relay and MCP directly]
    D --> F[Model-run bash commands follow env clock]
    F --> G[Shared egress proxy rule]
    E --> H[Relay replaces CLI context date]
Loading

Reviews (13) · Last reviewed commit: "fix(agents): only the Gemini CLI's own c..." · Reviewed by Greptile

williamloo-scale and others added 30 commits November 16, 2026 11:29
…5916)

Prototype of the Agents on the Env Clock design, to size the change. The gateway takes followers declared after it
starts; every AgentEnvAgent in an image that runs the clock follower serves clock/v1 sync_time; sync_env_clock and
deploy_agent declare each agent as a follower and hand it its config; the Claude Code image runs the computer base's
follower, egress proxy and libfaketime, copied in until FD-5700; get_time no longer calls the machine's clock unsynced.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…kip unless require_agent_clock

The image's changes move to wloo/claude-code-clock-image, along with the computer base's egress options only it uses:
on CI the image's Claude Code timed out reaching the test's model endpoint. What stays serves sync_time for an agent
whose image runs the follower and is otherwise inert. An agent that can't follow is now skipped even when
tolerate_missing_sync_time is false, which stays about the env's servers; require_agent_clock fails the step instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The image half of the agent clock: the computer base's clock follower and egress proxy, copied in until FD-5700,
libfaketime preloaded for the agent's user, root's supervisord starting them and the A2A server, and the CLI sent
through the proxy. Needs #714 and an agentenv-protocol release with CLOCK_V1.

Not ready: on CI this image's CLI timed out reaching the integration tests' model endpoint, likely the proxy refusing
a private address; it should go through the proxy only once the clock is armed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…gent, retire on teardown

- An agent's sync_time takes only a status of the config it just wrote (its URL and name, written after it), so what
  the follower showed of an earlier gateway or token never passes for success.
- An agent follows one env's clock; another env's is skipped as follows_another_env, as its one follower can't watch
  two gateways. deploy_agent's late follows are recorded with the sync's, so both see it.
- teardown_sandboxes retires a torn-down agent's follower (DELETE /clock/followers, retire_follower), so later writes
  don't wait for it or answer 504 naming it. A declaration no longer replaces a follower the gateway started with.
- Logs say an outcome's synced, reason and follower, never the agent's answer; the timeouts, token size and error
  length are named constants.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…tirement wakes waiting writes

- Which env an agent follows moves from clock_configurations' items to metadata.agent_clock_following, one key per
  agent, so late deploy_agent steps that save at once never overwrite each other's record and teardown still finds it.
- Retiring a follower notifies writes waiting for it, and a watch by a follower retired meanwhile acknowledges nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
… retire however its sandbox goes

- Agent names are percent-encoded into their metadata keys, so team.solver and team_solver never share a record.
- An agent follows the clock of the first env it's registered with, fixed by the agent alone, so two steps arming two
  of its envs at once never both take its one follower.
- teardown_sandboxes retires the follower of every agent whose sandbox it takes down, by agent, sandbox or env name.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…d on local Docker (FD-5916)

Deploys the image with an env, runs sync_env_clock with require_agent_clock, and checks that the agent's user reads
the env's time (date and datetime.now()) while the real-time marker opts out; that a write waiting for followers waits
for the agent, answering 504 naming it while its container is paused; and that after teardown_sandboxes writes no
longer wait for it. Skipped unless AGENTENV_E2E_CLAUDE_CODE_IMAGE names an image built from this branch.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…e survives a server restart; get_time keeps its sentence

- follow retires the follower it declared when the agent's sync_time fails, by an HTTP error or a transport one, so the
  gateway isn't left waiting on every later write for a follower that never watches.
- sync_time saves the task's zone in the follower's config, and the A2A server takes it back when it starts, so a
  server supervisord restarts mid-run keeps the zone as the follower keeps the clock.
- get_time's description keeps "the clock on the machine you are running on is not synchronized": most agents
  won't follow the clock for a while yet.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…through the proxy only on an armed clock

- The agent's libfaketime takes Edgar's init guard: a clock call made while ftpl_really_init runs on that thread, as
  the CLI's allocator makes one when dlsym allocates, reads the kernel's clock instead of waiting on pthread_once, which
  deadlocked: claude --version never returned. The computer base's patch doesn't take it yet; the agent's copy is the
  base's, then the guard, which the drift test checks.
- The CLI goes out through the egress proxy only while the follower follows an armed clock (clock_armed), and reaches a
  plain-HTTP model endpoint directly then: unarmed, it goes out as before, so a private endpoint keeps working.
- egress/ is the base's again after main moved it.
- The e2e test checks claude --version under the preload, and one turn of the real CLI against a stub Messages
  endpoint: its "Today's date is" line and a Bash date are the env's.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
… down alone

Their records stay in deployed_agents after teardown, and calling their gone servers failed the step.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…browser base's egress copy takes boot.go

- test_agent_env_clock_local skips as agentenv-capability-missing: agent_clock_image, which the slow integration job
  allows, as no CI job builds agent images.
- ubuntu-24.04-browser's egress/ is ubuntu-24.04's again, with this PR's AGENTENV_SESSION_USER and AGENTENV_EGRESS_NSS.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…tocol's tests write it

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…lag, not the follower's status

The page is what libfaketime reads, and it keeps the last armed clock while the follower reconnects to a restarted
gateway or restarts itself, when its status says connected false or armed false. A CLI started then reads the env's
time, so it must go through the proxy. Unit tests pin both windows.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ds show

An agent whose card serves clock/v1 sync_time is now checked end to end after the validation DAG: the validation
env's clock is armed frozen in America/Chicago with require_agent_clock, the agent runs `date` through its harness
and must show that instant and zone, a write that waits for followers must be acknowledged, and `date` must show the
time it moved to. A synced follower alone doesn't pass: an image whose preload is missing, or whose harness can't run
under it, follows and still fails. An agent whose card serves no sync_time is skipped. The result is recorded under
validated_a2a_extensions[urn:agentenv:clock/v1] and verifications["a2a_clock"].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ength

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ed with the env

An agent in an image that follows the env's clock reads the env's time, so "is not synchronized, so do not use it"
is false for it. "May not be" holds for every agent, following or not, and get_time answers what a following
agent's clock already shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…he other agent extension clients

It drives an agent's clock/v1 sync_time and the gateway's follower declarations for the steps that call it
(sync_env_clock, deploy_agent, teardown_sandboxes), as object_transfer does for snapshot transfers; it defines no step.
The name mirrors agentenv_protocol.a2a_agent.clock, the agent's side of the same extension. The persisted
metadata key agent_clock_following is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t.clock, where #714 moved it

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…st with an agent's clock/v1 sync_time

0.1.575 is the release that carries #714 (agentenv_protocol.a2a_agent.clock): before it, the image's protocol serves
no clock/v1, so the agent advertises none and sync_env_clock skips it as not_advertised. The image is built again only
when this folder changes, so the floor is what makes it take the release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… gateway refuses at once

A watch that fails fast (connection refused) answers before the follower's quarter-second poll sees a changed config,
and the retry backoff ends early on that change, so the follower kept retrying the old URL in a tight loop and never
followed the new one: an agent re-synced to another gateway after its first one went away stayed on the old clock,
burning a core, and every write that waited for it answered 504. It now checks the config after each failed watch.
The base's, the browser base's and the Claude Code image's copies stay identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ct; name the egress probe's error limit

- egress_env merges the hosts NO_PROXY and no_proxy already name with the direct ones, so a private registry the agent
  was deployed to reach directly isn't sent to the proxy, which refuses it, once the clock is armed.
- egress/upstream.go names its 200-character problem limit (problemChars), in the computer bases' copies too, which
  stay byte for byte the same.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ge, not Claude Code's alone

- tst/unit/agents/test_agent_clock_images.py: every agent folder with clock/ copies the base's clock pieces with the
  init guard, runs the follower, the proxy and the server as their users, preloads libfaketime for the agent's user,
  starts as another user as before, and decides the CLI's proxy with the same clock_armed and egress_env as Claude Code.
- The local e2e runs over each image AGENTENV_E2E_AGENT_IMAGES names (claude-code=<tag>,...), with a CLI turn for an
  agent whose CLI the stub endpoint speaks to.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
#	tst/integration/task_step/test_agent_env_clock_local.py
@earakely-scale

Copy link
Copy Markdown
Collaborator

Hi @williamloo-scale, this is Claude, working with Edgar. Please don't merge this yet. It needs main and a small migration first, or it will turn main red.

#818 merged a single egress rule for every clocked agent: src/agent_env/utils/agent_clock/agent_egress.py. With the clock armed, every TLS host goes through the egress proxy, the env's MCP servers included. Only loopback, host.docker.internal, the deploy's NO_PROXY hosts, and hosts reached only over plain HTTP go direct. NO_PROXY matches by host, so a host also reached over HTTPS stays behind the proxy.

tst/unit/agents/test_agent_clock_images.py on main now requires every clocked agent to:

  • take agent_clock = "utils/agent_clock" in its shared_sources.toml;
  • import clock_armed and egress_env from agent_egress, and define none of the rule itself;
  • have its Dockerfile, and install.sh if it has one, copy agent_clock/agent_egress.py and clock/clockpage.py beside the bridge.

This branch still has its own clock_armed / model_direct_hosts / egress_env. main doesn't require branches to be up to date before merging, so this PR's green checks predate #818, and merging it now would fail main's unit tier for this agent. OpenCode hit exactly this. In #818, commit ddb5993 moved it over, and it makes a short template: the bridge's change is the import plus egress_env(environ, [model_url, *mcp_urls], armed=...).

Why it matters beyond the test: on an armed clock, the CLI checks TLS certificates against the virtual date. An env on Modal whose *.modal.host certificate was issued after that date fails if its MCP host goes direct. We reproduced that on main before #818 (CERT_NOT_YET_VALID, no env tools). #818's PR description has the end-to-end results for Claude Code and OpenCode.

Gemini specifically: gemini-cli builds its proxy agent from HTTPS_PROXY and ignores NO_PROXY. We saw its loopback model calls go to the proxy, which refuses loopback. So keep your _CLI_PROXY_VARS handling on top of the shared egress_env; the test allows post-processing as long as the rule comes from agent_egress.

If it helps, I can push the merge and migration commits to this branch and run the same armed-clock end-to-end check against a Modal env. Just say so here or on Slack.

williamloo-scale and others added 2 commits November 19, 2026 15:06
# Conflicts:
#	src/agent_env/agents/agents/gemini/a2a_server.py
The bridge imports clock_armed and egress_env from agent_clock/agent_egress
and hands it the model endpoint's URLs and every MCP server's, so on an
armed clock an HTTPS MCP host goes through the egress proxy like the rest.
The CLI still gets no HTTP(S)_PROXY (_CLI_PROXY_VARS): it ignores NO_PROXY.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@williamloo-scale

Copy link
Copy Markdown
Contributor Author

Thanks, done. I merged main (v0.9.1595, with #818) and moved this agent onto agent_egress. Its shared_sources.toml takes agent_clock, the image (and install, where it has one) copies agent_egress.py and clockpage.py beside the bridge, and the bridge hands egress_env the model endpoint's URL and every MCP server's, so an HTTPS MCP host stays behind the proxy. The unit tests pass, including test_agent_clock_images.py and test_agent_egress.py. I rebuilt the image and ran the local armed-clock e2e and the A2A validator against a real model through LiteLLM: clock/v1 is supported, synced and follows writes, and both readings (2031-03-03T23:06:07-0600, then a day later) match. (head 4b6538a) The _CLI_PROXY_VARS handling stays on top. One note: the first validator run failed clock/v1 on a gemini CLI lock race (Lock is already released, stat ~/.gemini/projects.json.lock ENOENT), and a rerun passed. I think it's the clock: libfaketime is built with -UFAKE_STAT, so a new lock's mtime is real while Date.now() is the env's, and the CLI's lock takes a lock years older than its stale window as stale. That's not from this PR. I'll raise it separately.

@earakely-scale

Copy link
Copy Markdown
Collaborator

Claude again, working with Edgar. Thanks for the update. The migration onto agent_egress looks right structurally: shared_sources.toml, the import, the Dockerfile, install.sh, and the model URLs plus the MCP URLs passed in.

There's one behavioural gap left, and it's the one #818 fixed for Claude Code.

What happens:

  • cli_env drops _CLI_PROXY_VARS (HTTP(S)_PROXY) from the CLI's environment, because gemini-cli ignores NO_PROXY.
  • gemini-cli connects to the env's MCP servers itself, through httpUrl in its settings (gemini_config._server_entry).
  • So on an armed clock those MCP connections now go direct, and Node checks their TLS certificates against the virtual date.
  • An env on Modal whose *.modal.host certificate was issued after that date fails to connect, and the agent gets no env tools.
  • ALL_PROXY only reaches the commands the model runs.

Evidence: in #818's testing we built a clocked gemini image (throwaway, not committed). With MCP direct, it failed with CERT_NOT_YET_VALID against a Modal env armed before the certificate's start. Through the proxy it passed (proxy log: intercept / outside). The unit tests here can't see this, because they check structure.

Two ways to close it:

  1. Give the CLI the proxy, and move its loopback targets (the attribution proxy on 127.0.0.1, and the peer-agents MCP) to an address the proxy does reach: the container's own IP. The image's proxy allows private addresses. This is what our test build did, and it passed.
  2. Or have the A2A server relay MCP on loopback, the way it already relays model calls. The server stays on real time, so its TLS check holds.

I can push either one and run the armed-clock check against a Modal env, if you'd like.

williamloo-scale and others added 10 commits November 20, 2026 01:30
…env clock

The capture hook is a child of the CLI, so on an armed env clock it read the
env's time: ahead of real time, its grant looked expired and every upload was
refused before it was sent, and tar recorded the env's time as its incremental
baseline, missing writes made after it. The hook now starts with the real-time
marker, and the baseline and capture tar runs get it too, since the marker
reaches no child of the process started with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…and only the model's commands follow it

On an armed clock the CLI judged its projects.json lock stale by real file
times against the env's clock, so two of its own lockers raced and a turn
exited with ECOMPROMISED once the clock was more than 10 s ahead; its session
retention, tool-output and log cleanups would delete files the same way, and
with no proxy of its own (it ignores NO_PROXY, so it can't take one) it checked
its MCP servers' certificates against the env's date.

Now a turn on an armed clock starts the CLI on real time: its script run by
node with the real-time marker, since `gemini`'s env shebang would consume the
marker, and GEMINI_CLI_NO_RELAUNCH, since its relaunched child would inherit
none. Its locks, cleanups and TLS checks compare real times with real times,
and it reaches its loopback relay and MCP servers directly. The commands the
model runs follow the clock and get the shared egress rule from a file every
bash the CLI starts reads first (BASH_ENV). The model relay names the env's
date, read at the turn's start from a child that follows the clock, in the
CLI's "Today's date is" line. Unarmed, the CLI's environment and command are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n Gemini endpoint

The local agent-clock e2e ran no turn for Gemini. It now serves a fake Gemini
API (LiteLLM's /gemini passthrough, tst/util/fake_gemini.py) behind the agent's
model relay and runs one turn on the armed, frozen clock: the CLI's date line
names the env's date, a `date` the model runs shows the env's time with the
egress proxy's variables and no marker, and node runs the CLI's script itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… real time

Also drops a ticket id from their comments, and tightens the cli_env docstring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… reads no stdin

- The armed path is taken only where the image runs its own egress proxy and its page is armed
  (gemini_bridge.cli_on_real_time). An install's page, a computer's say, follows a clock the agent never
  opted in to, and its `gemini` is install.sh's shell launcher, which node failed to parse on every turn
  there. node is now also handed the CLI's script only when `gemini` resolves to a .js.
- The CLI's stdin is /dev/null. It inherited the server's, which under supervisord is a pipe that never
  closes, so the CLI waited 500 ms for piped input on every start; under Docker before supervisord it
  was /dev/null.
- A unit test pins the CLI's version to the 0.38.2 whose date-line wording the relay matches, since no
  CI job builds the image, and another pins root.conf's server command to entrypoint.sh's arguments and
  the image's working directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… main

Under root's supervisord the A2A server was restarted in place after a crash: the dead server's CLI kept running in its
own session, and the new server had none of the run's registrations (the env's MCP servers, config, peers, running
tasks), so later turns ran without env tools and prompt_agent polled "Task not found" until its timeout. On main the
server was the container's process, so the container exited and the run failed at once.

root.conf now never starts the server again (autorestart=false, startretries=0), and an event listener on
PROCESS_STATE_EXITED and PROCESS_STATE_FATAL stops supervisord when the program is the server, so the container exits.
The clock follower and the egress proxy keep restarting in place, and a normal stop is unchanged. supervisord exits 0
however it's stopped, so the container's exit status is 0; its log names the server's exit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On an armed turn the relay rewrote every "Today's date is ... (formatted according to the user's locale)." in a model
call's body, so the same sentence in a prompt, a tool's result or a pasted CLI transcript reached the model with the
env's date. It now rewrites only the date line of the call's first content, and only when that content is the CLI's
environment context. The CLI puts that context first in its chat's history (getInitialChatHistory), and the SDK writes
contents before the rest of the body. A side call that starts without it, such as loop detection's, goes as sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@earakely-scale

Copy link
Copy Markdown
Collaborator

Hi @williamloo-scale, Claude here, working with Edgar. I finished this PR on your branch. Edgar asked me to bring all five clock PRs to the same bar as Claude Code's (#818, #831, #832).

What changed: the gemini CLI now runs on real time on an armed clock, and only the model's commands follow it. That fixes three things:

The env's date still reaches the model: the relay rewrites the CLI's "Today's date" line to the env's date.

Tested on a dedicated VM, with a stand-in model and real models, side by side with main:

  • clock off matches main;
  • opted in (agent_clock), the model sees the env's time;
  • the fix(claude-code): reach env MCP servers through the egress proxy on an armed clock #818 case: HTTPS MCP on a Modal env armed before its certificate, and with a clock behind real time;
  • four-turn history at +75 days, 1950 and 2262;
  • late agents, the require policy, and the agent on Modal;
  • chaos: clock rate and jumps, re-arm, clear, a killed clock follower, env reset, endpoint outages, cancel mid-turn, a killed server, concurrent runs.

Greptile is 5/5 on the head and CI is green.

Also new here: if the A2A server dies, the container now exits, as on main, instead of supervisord restarting the server in place. Edgar decided this after testing showed in-place restarts leave the old CLI writing and the new server without the env's MCP tools. #862 makes the same change for Claude Code and OpenCode.

Merging: the five clock PRs (#765 #768 #769 #770 #771) each add a row to tst/integration/task_step/test_agent_env_clock_local.py, so after the first one lands the others need a main merge that keeps both rows. I can do those merges.

The full details are in the PR description.

Claude, working with Edgar

@earakely-scale

earakely-scale commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Closing this, per Edgar's decision. Claude here, working with Edgar.

Why: on libfaketime, gemini-cli broke in four ways:

  • turns crashed on projects.json.lock once the clock was more than 10 s ahead;
  • the 30-day session retention deleted the resumed session;
  • its file cleanups deleted files by the same comparison;
  • its HTTPS MCP connections failed on a Modal env armed before its certificate, and it can't take the egress proxy because it ignores NO_PROXY.

The version on this branch kept the CLI on real time and only put the model's commands on the clock, so advertising clock/v1 would overstate what the agent does.

Edgar's rule: an agent advertises the clock (clock/v1 sync_time) only if the agent itself faithfully follows libfaketime, as Claude Code, OpenCode and Letta Code (#769) do.

What this agent does instead: it stays as it is on main. It runs on real time, and the env's time is available from the gateway's get_time tool, which has been the default for agents since #832.

  • A task with require_agent_clock fails up front for this agent ("can't follow the clock: not advertised").
  • Plain agent_clock skips it.
  • Its image stays identical to main, so none of the clock image's side effects apply: running as non-root on Modal, slower start and teardown, and the egress-proxy boot.

What's kept: the branch stays for reference. The investigation is in this PR's description and comments, and in Linear FD-6434.

Thanks for all the work on this, William. It's what showed where libfaketime does and doesn't hold up.

Claude, working with Edgar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants