From 6b73964ba99f70f97d97125380e7bdb6b106c2bb Mon Sep 17 00:00:00 2001 From: William Loo Date: Thu, 19 Nov 2026 16:26:55 -0800 Subject: [PATCH 1/8] [FD-6368] feat(task_step): agents follow the env's clock only when sync_env_clock opts in (agent_clock) sync_env_clock had every agent registered with the env follow its clock, and deploy_agent every agent it deployed while the clock was armed. An agent on the env's clock reads a date its files' modification times don't share, and a CLI that judges a file's age by them breaks: Claude Code's transcript cleanup deletes the live conversation once the env's date is more than 30 days ahead (FD-6368). agent_clock, off by default, now decides it; require_agent_clock implies it. The armed clock's configuration records it, so an agent deployed later follows only a clock armed with it, and a clock a run armed before this change has none follow. Images are unchanged: an agent that isn't asked to follow keeps real time. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/agent_env/a2a_agent/clock.py | 12 ++-- src/agent_env/agents/README.md | 9 ++- .../task_step/task_steps/sync_env_clock.py | 23 +++++--- tst/unit/task_step/agent_clock_test.py | 58 +++++++++++++++---- 4 files changed, 78 insertions(+), 24 deletions(-) diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index f03f55579..59c844fdb 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -3,8 +3,9 @@ runs reads the env's time. ``follow`` declares it at the gateway as a follower with a read token of its own, then calls its ``sync_time`` with the follower's config: the gateway's watch URL as the agent's sandbox reaches it, the name the gateway knows it by and that token. From then on a clock write that waits for followers (``wait_followers_s``) waits -for the agent too. ``sync_env_clock`` has every agent registered with the env follow once it has armed the clock, and -``deploy_agent`` an agent it deploys while the clock is armed. An agent has one follower, so it follows one env's +for the agent too. Only a task that opts in (``sync_env_clock``'s ``agent_clock``, off by default) has agents follow: +``sync_env_clock`` has every agent registered with the env follow once it has armed the clock, and ``deploy_agent`` an +agent it deploys while that clock is armed. An agent has one follower, so it follows one env's clock: the first env it's registered with (``clock_env``), whatever order steps arm clocks in, even at once; another env's is reported and skipped (``follows_another_env``). When ``teardown_sandboxes`` takes the agent's sandbox down, ``retire_followers`` has the gateway it follows stop waiting for it. Which @@ -189,13 +190,16 @@ def _armed(context: TaskStepContext, env: DeployedEnv) -> Optional[dict]: async def follow_armed_clocks(context: TaskStepContext, agent: DeployedAgent, *, timeout: float = LATE_FOLLOW_TIMEOUT_S) -> list[dict]: """Have an agent ``deploy_agent`` just deployed follow the clock of each env registered with it that this run has - armed, as ``sync_env_clock`` has every agent then: one that can't is reported and skipped, or fails the step under - that step's ``require_agent_clock``.""" + armed with ``agent_clock``, as ``sync_env_clock`` has every agent then: one that can't is reported and skipped, or + fails the step under that step's ``require_agent_clock``. A clock armed without it, or by a run from before it, is + one agents don't follow.""" outcomes = [] for env_id in agent.env_ids: env = _agent_deployment(context, agent, env_id) if env is None or gateway_url_of(env) is None or (armed := _armed(context, env)) is None: continue + if not armed.get("agent_clock", False): + continue outcome = await follow_in(context, agent, env, env_get_time_url=armed.get("env_get_time_url"), timezone=armed.get("timezone"), timeout=timeout) if not outcome["synced"] and armed.get("require_agent_clock", False): diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 10d858f57..871d771d1 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -40,9 +40,12 @@ its own user under root's supervisord (`start-agent`, `root.conf`), with agent-e agent's user. The A2A server starts with the real-time marker, so it and its records stay on real time, and serves clock/v1's `sync_time`, which the protocol's framework serves on the card of any agent in an image with the follower -(`agentenv_protocol.a2a_agent.clock`). Once `sync_env_clock` has armed the clock, it declares the agent at the gateway -as a follower with a read token of its own and calls that `sync_time` with the follower's config, which the server -writes; `deploy_agent` does the same for an agent it deploys while the clock is armed. From then on the CLI, its own +(`agentenv_protocol.a2a_agent.clock`). An agent follows the env's clock only when the task opts in: once a +`sync_env_clock` with `agent_clock` (off by default; `require_agent_clock` implies it) has armed the clock, it declares +the agent at the gateway as a follower with a read token of its own and calls that `sync_time` with the follower's +config, which the server writes; `deploy_agent` does the same for an agent it deploys while that clock is armed. +Without it the agent keeps real time, as its files' modification times do: a CLI that judges a file's age by them, as +Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the env's date is ahead. From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for followers waits for the agent. While the clock is armed the CLI goes out through the egress proxy, which keeps TLS working at any date the clock shows, a live site's, an env MCP server's or the model endpoint's; only loopback hosts diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index 53d6c1f70..f21128882 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -5,10 +5,11 @@ env card lists (``legacy_protocol.backing_servers``) whose own card advertises it, at the route that card gives. An env whose card offers no set_time has no gateway clock to arm, as a computer deployed alone, and is refused saying to deploy it in a multi env; a record that kept no card is refused saying so. -Then has every agent registered with the env whose card serves clock/v1 sync_time follow the clock as a computer does -(``agent_env.a2a_agent.clock``), so every program it runs reads the env's time and later clock writes can wait for it. -An agent that can't is skipped, as every agent is until its image runs the follower, or fails the step with -require_agent_clock. +With agent_clock (off by default), then has every agent registered with the env whose card serves clock/v1 sync_time +follow the clock as a computer does (``agent_env.a2a_agent.clock``), so every program it runs reads the env's time and +later clock writes can wait for it. An agent that can't is skipped, as every agent is until its image runs the follower, +or fails the step with require_agent_clock. Without it, agents keep real time: a CLI that judges its files' age by +their modification times, which stay real, would take a fresh file for one as old as the env's date is ahead. Non-advertisers are skipped when tolerate_missing_sync_time (default True), and websites always. Place right before prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 and start it with set_env_clock_rate right before prompt_agent. @@ -82,6 +83,7 @@ def __init__( timeout_seconds: int = 30, timezone: Optional[str] = None, require_agent_clock: bool = False, + agent_clock: bool = False, ): """virtual_seconds_per_real_second = clock speed (1.0 real time, 0 frozen, 86400 cap = 1 real s -> 1 virtual day). For ~V virtual seconds over an ~R-real-second task, pass V/R. @@ -90,8 +92,11 @@ def __init__( that zone, the gateway's clock is armed in it, so its get_time answers in it too, and every synced server is told the zone (a server that cannot take it fails the step). + agent_clock = have every agent registered with the env follow its clock, and an agent deploy_agent deploys + later on it too; off, they keep real time. + require_agent_clock = fail the step when an agent registered with the env can't follow its clock, rather than - skip it; apart from tolerate_missing_sync_time, which is about the env's servers.""" + skip it; apart from tolerate_missing_sync_time, which is about the env's servers. It implies agent_clock.""" super().__init__(id, version, depends_on=depends_on, fail_task_on_error=fail_task_on_error) if not isinstance(virtual_time, str): raise ValueError("virtual_time must be an RFC3339 string") @@ -101,6 +106,7 @@ def __init__( self.virtual_seconds_per_real_second = virtual_seconds_per_real_second self.tolerate_missing_sync_time = tolerate_missing_sync_time self.require_agent_clock = require_agent_clock + self.agent_clock = agent_clock or require_agent_clock self.timeout_seconds = timeout_seconds self.timezone = timezone.strip() if isinstance(timezone, str) else timezone self.armed_virtual_time = resolve_virtual_time(virtual_time, self.timezone) @@ -117,6 +123,8 @@ def to_dict(self) -> dict: base["timezone"] = self.timezone if self.require_agent_clock: base["require_agent_clock"] = True + if self.agent_clock: + base["agent_clock"] = True return base @classmethod @@ -131,6 +139,7 @@ def from_dict(cls, data: dict) -> SyncEnvClockTaskStep: timeout_seconds=data.get("timeout_seconds", 30), timezone=data.get("timezone"), require_agent_clock=data.get("require_agent_clock", False), + agent_clock=data.get("agent_clock", False), ) async def _backing_servers(self, deployed) -> list[BackingServer]: @@ -177,13 +186,13 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: entry = {"service": service, "environment": service, **({} if server.mcp else {"website": True}), **outcome} (synced if outcome.get("synced") else skipped).append(entry) - agents = await self._follow_agents(context, deployed, env_get_time_url) + agents = await self._follow_agents(context, deployed, env_get_time_url) if self.agent_clock else [] configuration = { "step_id": self.id, "env_id": self.env_id, "deploy_step_id": (deployed.metadata or {}).get("deploy_step_id"), "virtual_time": self.virtual_time, "virtual_seconds_per_real_second": self.virtual_seconds_per_real_second, "env_get_time_url": env_get_time_url, "synced": synced, "skipped": skipped, "agents": agents, - "require_agent_clock": self.require_agent_clock, + "require_agent_clock": self.require_agent_clock, "agent_clock": self.agent_clock, } if self.timezone is not None: configuration.update(timezone=self.timezone, armed_at=self.armed_virtual_time, diff --git a/tst/unit/task_step/agent_clock_test.py b/tst/unit/task_step/agent_clock_test.py index 551ba0cd0..a5b92f2c6 100644 --- a/tst/unit/task_step/agent_clock_test.py +++ b/tst/unit/task_step/agent_clock_test.py @@ -1,8 +1,8 @@ -"""Agents on the env's clock: once sync_env_clock has armed it, every agent registered with the env whose card serves +"""Agents on the env's clock: once sync_env_clock has armed it with agent_clock, every agent registered with the env whose card serves clock/v1 sync_time is declared at the gateway as a follower with a token of its own and handed the follower's config; one that doesn't is reported and skipped, even when the env's servers must follow (tolerate_missing_sync_time false), or fails the step under require_agent_clock; and an agent -deploy_agent deploys while the clock is armed follows the same way.""" +deploy_agent deploys while the clock is armed follows the same way. Without agent_clock, the default, no agent follows.""" import dataclasses import json from types import SimpleNamespace @@ -15,7 +15,7 @@ from agent_env.a2a_agent import clock as agent_clock from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep from tst.unit.task_step.sync_env_clock_test import (CLOCK_URL, T0, _CARD, _CLOCK_EXT, _ZONE_EXT, _carded, _composed_card, _mock_http, - _step) + _step as _sync_step) AGENT_URL = "http://solver:8000" AGENT_CONTROL_TOKEN = "the-agents-control-token" @@ -23,6 +23,11 @@ "request": {"required": ["env_get_time_url"], "optional": ["timezone", "watch_url", "name", "read_token"]}} +def _step(**kw) -> SyncEnvClockTaskStep: + """A sync_env_clock step that has agents follow (agent_clock), unless ``kw`` says otherwise.""" + return _sync_step(**{"agent_clock": True, **kw}) + + def _agent(name="solver", sync_time=SYNC_TIME, env_ids=("e1",), env_step_id=None) -> DeployedAgent: extensions = [{"uri": EXT_CLOCK_URI, "params": {"endpoint": "/ext/clock", "methods": {"sync_time": sync_time}}}] return DeployedAgent(agent_name=name, api_url=AGENT_URL, a2a_url=AGENT_URL, env_ids=list(env_ids), @@ -49,7 +54,7 @@ async def test_an_agent_is_declared_a_follower_then_handed_its_config_with_the_s context.deployed_envs = [_carded(await _composed_card({"mcp-email": [_ZONE_EXT]}))] await SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time="2026-01-01T06:00:00", - timezone="America/Chicago").execute(context) + timezone="America/Chicago", agent_clock=True).execute(context) declared, synced = sent[3], sent[4] assert (declared.method, str(declared.url)) == ("PUT", f"{_CARD}/clock/followers") @@ -148,7 +153,7 @@ async def test_an_agent_deployed_while_the_clock_is_armed_follows_it(monkeypatch sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) context = await _context() context.metadata["clock_configurations"] = [ - {"step_id": "sync", "env_id": "e1", "virtual_time": T0, "env_get_time_url": CLOCK_URL, "timezone": "Asia/Tokyo", + {"step_id": "sync", "env_id": "e1", "virtual_time": T0, "env_get_time_url": CLOCK_URL, "agent_clock": True, "timezone": "Asia/Tokyo", "require_agent_clock": False}, {"step_id": "rate", "env_id": "e1", "virtual_seconds_per_real_second": 60, "virtual_time": T0}, ] @@ -173,7 +178,7 @@ async def test_an_agent_deployed_before_any_clock_is_armed_is_left_alone(monkeyp async def test_a_late_agent_that_cant_follow_fails_a_deploy_only_under_require_agent_clock(monkeypatch): _mock_http(monkeypatch) context = await _context() - context.metadata["clock_configurations"] = [{"env_id": "e1", "env_get_time_url": CLOCK_URL}] + context.metadata["clock_configurations"] = [{"env_id": "e1", "env_get_time_url": CLOCK_URL, "agent_clock": True}] [skipped] = await agent_clock.follow_armed_clocks(context, _agent("late", sync_time=None), timeout=5) assert (skipped["synced"], skipped["reason"]) == (False, "not_advertised") context.metadata["clock_configurations"][0]["require_agent_clock"] = True @@ -181,6 +186,39 @@ async def test_a_late_agent_that_cant_follow_fails_a_deploy_only_under_require_a await agent_clock.follow_armed_clocks(context, _agent("late", sync_time=None), timeout=5) +@pytest.mark.asyncio +async def test_without_agent_clock_no_agent_follows_and_one_deployed_later_doesnt_either(monkeypatch): + """Off by default: an agent on the env's clock judges its files' age by real modification times (FD-6368).""" + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + _no_servers(monkeypatch) + context = await _context(_agent()) + + await _sync_step().execute(context) + + assert [r.url.path for r in sent][3:] == [] + [configuration] = context.metadata["clock_configurations"] + assert (configuration["agents"], configuration["agent_clock"]) == ([], False) + assert await agent_clock.follow_armed_clocks(context, _agent("late"), timeout=5) == [] + assert [r.url.path for r in sent][3:] == [] + + +@pytest.mark.asyncio +async def test_a_clock_armed_by_a_run_from_before_agent_clock_has_no_late_agent_follow(monkeypatch): + sent = _mock_http(monkeypatch) + context = await _context() + context.metadata["clock_configurations"] = [{"env_id": "e1", "env_get_time_url": CLOCK_URL}] + + assert await agent_clock.follow_armed_clocks(context, _agent("late"), timeout=5) == [] + assert sent == [] + + +def test_agent_clock_round_trips_is_left_out_when_off_and_require_agent_clock_implies_it(): + assert "agent_clock" not in _sync_step().to_dict() and _sync_step().agent_clock is False + on = _sync_step(agent_clock=True).to_dict() + assert on["agent_clock"] is True and SyncEnvClockTaskStep.from_dict(on).agent_clock is True + assert _sync_step(require_agent_clock=True).agent_clock is True + + def test_require_agent_clock_round_trips_and_is_left_out_when_off(): assert "require_agent_clock" not in _step().to_dict() strict = _step(require_agent_clock=True).to_dict() @@ -192,7 +230,7 @@ def test_require_agent_clock_round_trips_and_is_left_out_when_off(): async def test_an_agent_follows_the_first_envs_clock_and_another_envs_is_reported_and_skipped(monkeypatch): sent = _mock_http(monkeypatch) context = await _context() # e1 alone is deployed and armed: whether e0 has been armed yet doesn't matter - context.metadata["clock_configurations"] = [{"env_id": "e1", "env_get_time_url": CLOCK_URL}] + context.metadata["clock_configurations"] = [{"env_id": "e1", "env_get_time_url": CLOCK_URL, "agent_clock": True}] [outcome] = await agent_clock.follow_armed_clocks(context, _agent("late", env_ids=("e0", "e1")), timeout=5) @@ -252,7 +290,7 @@ async def test_late_agents_deployed_at_once_each_save_only_their_own_record(monk _mock_http(monkeypatch) pre = await _context() - pre.metadata["clock_configurations"] = [{"env_id": "e1", "env_get_time_url": CLOCK_URL}] + pre.metadata["clock_configurations"] = [{"env_id": "e1", "env_get_time_url": CLOCK_URL, "agent_clock": True}] saved = {} for name in ("first", "second"): # each from the same context, as two deploy_agent steps at once post = copy.deepcopy(pre) @@ -363,14 +401,14 @@ async def test_a_late_agent_follows_only_its_own_deployments_armed_clock(monkeyp sent = _mock_http(monkeypatch) context = await _two_deployments() context.metadata["clock_configurations"] = [ - {"env_id": "e1", "deploy_step_id": "deploy-b", "env_get_time_url": CLOCK_URL}] + {"env_id": "e1", "deploy_step_id": "deploy-b", "env_get_time_url": CLOCK_URL, "agent_clock": True}] late = _agent("late", env_step_id="deploy-a") assert await agent_clock.follow_armed_clocks(context, late, timeout=5) == [] assert sent == [] context.metadata["clock_configurations"].append({"env_id": "e1", "deploy_step_id": "deploy-a", - "env_get_time_url": CLOCK_URL}) + "env_get_time_url": CLOCK_URL, "agent_clock": True}) [outcome] = await agent_clock.follow_armed_clocks(context, late, timeout=5) assert outcome["synced"] is True assert str(sent[0].url) == "https://sandbox.example/sb-a/clock/followers" From 1ac9ecdd0953079a1d6ccf0998db9a198b4c1cfe Mon Sep 17 00:00:00 2001 From: William Loo Date: Thu, 19 Nov 2026 16:46:23 -0800 Subject: [PATCH 2/8] [FD-6368] feat(protocol): an agent loads the clock libraries only once sync_time opts it in An agent image preloaded agent-env's libfaketime into every process of the agent's user from boot (/etc/ld.so.preload), whether or not a task used the clock. AgentEnvAgent's clock/v1 sync_time is now the opt-in: an image that names its clock libraries (AGENTENV_CLOCK_PRELOAD) loads them into nothing, and once the follower takes sync_time's config the server puts them in LD_PRELOAD for every program it starts from then on, and drops the real-time marker it was started with. A server restarted mid-run loads them again, as it takes back the task's zone. An image that names none, as every one before this, is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/agentenv_protocol/a2a_agent/clock.py | 45 +++++++++++-- .../agentenv_protocol/a2a_agent/framework.py | 5 +- .../tests/test_a2a_agent_clock.py | 66 ++++++++++++++++++- src/agent_env/agents/README.md | 7 +- 4 files changed, 112 insertions(+), 11 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py index d1d66aef6..4eaa85e11 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py @@ -1,6 +1,9 @@ -"""An agent's side of clock/v1. An agent image that follows the env's clock runs the computer base's follower, and -agent-env's libfaketime is preloaded for the agent's user, so every program the A2A server starts reads universe time -from the follower's page; the server itself starts with the real-time marker and stays on real time. +"""An agent's side of clock/v1. An agent image that follows the env's clock runs the computer base's follower and +carries agent-env's libfaketime, which reads universe time from the follower's page; the server itself stays on real +time. Following is opt-in: ``sync_time`` is what puts what the server starts on the env's clock. An image that names +its clock libraries (``PRELOAD_ENV``) loads them into no program until then, so a task that never asks runs its CLI as +an image without the clock does; once called, every program the server starts loads them (``LD_PRELOAD``). An older +image preloads them into every process of the agent's user from boot (``/etc/ld.so.preload``) and names none. The framework serves clock/v1's ``sync_time``, the method every server and computer that follows the clock serves, on the card of an agent in such an image (``follows``), so the card is what tells core the agent follows. Unlike a @@ -22,6 +25,13 @@ from ..computer import clock as follower from ..computer.errors import InvalidArgument, TargetUnavailable +#: Set by an image whose clock is opt-in: the libraries, as LD_PRELOAD names them, that put a program on the follower's +#: page. +PRELOAD_ENV = "AGENTENV_CLOCK_PRELOAD" +#: The marker agent-env's libfaketime keeps a program on real time by, and takes out of its environment; one this server +#: was started with would keep everything it starts on real time. +REAL_TIME_ENV = "AGENTENV_REAL_TIME" + def follows() -> bool: """Whether this agent's image runs the clock follower.""" @@ -68,6 +78,29 @@ def set_zone(timezone: str) -> str: return zone +def preload() -> bool: + """Every program this server starts from now on loads the image's clock libraries (``PRELOAD_ENV``), and so reads + the env's time once the follower arms its page; the server itself, already running, stays on real time. Whether + the image names any: one that preloads them for every process already has them in every program.""" + libraries = (os.environ.get(PRELOAD_ENV) or "").replace(":", " ").split() + if not libraries: + return False + loaded = (os.environ.get("LD_PRELOAD") or "").replace(":", " ").split() + os.environ["LD_PRELOAD"] = " ".join(dict.fromkeys([*loaded, *libraries])) + os.environ.pop(REAL_TIME_ENV, None) + return True + + +def restore() -> str | None: + """What ``sync_time`` set for what this server starts, set again: called when it starts, so one that restarts + mid-run keeps the clock libraries and the task's zone, as the follower keeps the clock. The zone, or None when a + config saved none or isn't there, when nothing is restored.""" + if not Path(follower.CONFIG).exists(): + return None + preload() + return restore_zone() + + def restore_zone() -> str | None: """The task's zone ``sync_time`` saved, set again for what this server starts: called when it starts, so one that restarts mid-run keeps the zone, as the follower keeps the clock. None when there's none, or it isn't a zone.""" @@ -85,8 +118,9 @@ def restore_zone() -> str | None: async def sync_time(env_get_time_url: str, timezone: str | None = None, watch_url: str | None = None, name: str | None = None, read_token: str | None = None) -> dict: - """``clock/v1``'s ``sync_time`` on an agent: the follower configured to follow the gateway at ``watch_url`` as - ``name`` with ``read_token``, the task's ``timezone`` set for what this server starts, and an answer once the + """``clock/v1``'s ``sync_time`` on an agent, the call that opts it into the env's clock: the follower configured to + follow the gateway at ``watch_url`` as ``name`` with ``read_token``, the task's ``timezone`` set and the clock + libraries loaded (``preload``) for what this server starts once it follows, and an answer once the follower shows the gateway's version for that config, never what it showed of one before. ``env_get_time_url`` is taken as every server takes it and not used: the follower reads the gateway's watch, not its time.""" if not follows(): @@ -99,4 +133,5 @@ async def sync_time(env_get_time_url: str, timezone: str | None = None, watch_ur zone = set_zone(timezone) if timezone is not None else os.environ.get("TZ") or "UTC" written = write_config(watch_url, name, read_token, zone) shown = await follower.following("this agent's clock follower", follower.CONNECT_WAIT_S, url=watch_url, name=name, since_ns=written) + preload() return {"synced": True, "timezone": zone, "env_get_time_url": env_get_time_url, "follower": shown} diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index 63f954de7..8de281b87 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -1036,11 +1036,12 @@ async def clock_sync_time(self, request: ClockSyncTimeRequest) -> dict[str, Any] def _with_clock(definition: _AgentDefinition) -> _AgentDefinition: """``definition`` serving clock/v1 where the agent's image runs the clock follower, so every agent in such an - image follows the env's clock with no code of its own, and takes back the task's zone if it restarted mid-run; + image can follow the env's clock with no code of its own, and takes back the clock libraries and the task's zone if + it restarted mid-run; unchanged elsewhere, or where the agent declares it.""" if not agent_clock.follows() or any(a.definition.uri == CLOCK_V1.uri for a in definition.extensions): return definition - agent_clock.restore_zone() # a server restarted mid-run takes back the task's zone + agent_clock.restore() # a server restarted mid-run takes back the clock libraries and the task's zone return dataclasses.replace(definition, extensions=(*definition.extensions, ExtensionActivation(CLOCK_V1))) diff --git a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py index 492800497..d82ed3c01 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py @@ -1,6 +1,7 @@ """An agent's side of clock/v1: in an image that runs the clock follower, every AgentEnvAgent serves sync_time with no -code of its own; called by sync_env_clock, it writes the follower's config from the request, sets the task's zone for -what the server starts, and answers once the follower shows the gateway's current version, or says why it doesn't.""" +code of its own; called by sync_env_clock, the opt-in, it writes the follower's config from the request, sets the +task's zone and loads the image's clock libraries for what the server starts, and answers once the follower shows the +gateway's current version, or says why it doesn't.""" from __future__ import annotations import json @@ -20,6 +21,7 @@ TaskResult, a2a_agent, ) +from agentenv_protocol.a2a_agent import clock as agent_clock from agentenv_protocol.computer import clock as follower REQUEST = {"env_get_time_url": "http://gw/clock/time", "watch_url": "http://gw/clock/watch", "name": "agent-solver", @@ -41,6 +43,18 @@ def image(tmp_path, monkeypatch): time.tzset() +LIBRARIES = "/usr/local/lib/agentenv-clock/libfaketimeMT.so.1:/usr/local/lib/agentenv-clock/libtls_realtime.so" + + +@pytest.fixture +def opt_in(monkeypatch): + """An image whose clock is opt-in: it names its clock libraries, preloads nothing, and starts the server with the + real-time marker, as an image from before did.""" + monkeypatch.setenv(agent_clock.PRELOAD_ENV, LIBRARIES) + monkeypatch.delenv("LD_PRELOAD", raising=False) + monkeypatch.setenv(agent_clock.REAL_TIME_ENV, "1") + + def _status(image, **status) -> None: (image / "status.json").write_text(json.dumps(status)) @@ -182,6 +196,54 @@ def test_a_server_restarted_mid_run_takes_back_the_tasks_zone(image, monkeypatch assert os.environ["TZ"] == "America/Chicago" and time.strftime("%Z") in {"CST", "CDT"} +def test_until_sync_time_no_program_the_server_starts_loads_the_clock_libraries(image, opt_in): + with _app() as client: + assert _clock(client) is not None + + assert "LD_PRELOAD" not in os.environ and os.environ[agent_clock.REAL_TIME_ENV] == "1" + + +def test_sync_time_loads_the_clock_libraries_into_what_the_server_starts_once_it_follows(image, opt_in, monkeypatch): + monkeypatch.setenv("LD_PRELOAD", "/opt/other.so") + _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") + with _app() as client: + assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 + assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 # again: nothing loaded twice + + assert os.environ["LD_PRELOAD"].split() == ["/opt/other.so", *LIBRARIES.split(":")] + assert agent_clock.REAL_TIME_ENV not in os.environ + + +def test_a_sync_time_the_follower_doesnt_take_loads_nothing(image, opt_in): + _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:2") + with _app() as client: + assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 404 + + assert "LD_PRELOAD" not in os.environ + + +def test_an_image_that_preloads_for_every_process_has_nothing_loaded(image, monkeypatch): + monkeypatch.delenv(agent_clock.PRELOAD_ENV, raising=False) + monkeypatch.delenv("LD_PRELOAD", raising=False) + _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") + with _app() as client: + assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 + + assert "LD_PRELOAD" not in os.environ + + +def test_a_server_restarted_mid_run_loads_the_clock_libraries_again(image, opt_in, monkeypatch): + _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") + with _app() as client: + assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 + monkeypatch.delenv("LD_PRELOAD") # the restarted server's environment: the image's + + with _app() as client: + assert client.get("/.well-known/agent.json").status_code == 200 + + assert os.environ["LD_PRELOAD"].split() == LIBRARIES.split(":") + + @pytest.mark.parametrize("config", ['{"watch_url": "u", "name": "n", "token": "t"}', '{"timezone": "Mars/Olympus"}', "not json", None]) def test_a_server_starting_without_a_saved_zone_keeps_its_own(image, monkeypatch, config): diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 871d771d1..1060fc09f 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -44,8 +44,11 @@ The A2A server starts with the real-time marker, so it and its records stay on r `sync_env_clock` with `agent_clock` (off by default; `require_agent_clock` implies it) has armed the clock, it declares the agent at the gateway as a follower with a read token of its own and calls that `sync_time` with the follower's config, which the server writes; `deploy_agent` does the same for an agent it deploys while that clock is armed. -Without it the agent keeps real time, as its files' modification times do: a CLI that judges a file's age by them, as -Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the env's date is ahead. From then on the CLI, its own +That call is also what loads agent-env's libfaketime: an image names its clock libraries (`AGENTENV_CLOCK_PRELOAD`) +and preloads them into nothing, and `sync_time` puts them in `LD_PRELOAD` for every program the server starts from then +on (`agentenv_protocol.a2a_agent.clock.preload`), as a server restarted mid-run does again. Without it the agent's CLI +runs with no libfaketime, on real time, as its files' modification times are: a CLI that judges a file's age by them, +as Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the env's date is ahead. From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for followers waits for the agent. While the clock is armed the CLI goes out through the egress proxy, which keeps TLS working at any date the clock shows, a live site's, an env MCP server's or the model endpoint's; only loopback hosts From 79f51d22792b611a76947ab41606cecbc7b085ce Mon Sep 17 00:00:00 2001 From: William Loo Date: Thu, 19 Nov 2026 17:06:11 -0800 Subject: [PATCH 3/8] docs(agents): the opt-in preload is for an image that names its libraries; Claude Code's and OpenCode's still preload for every process Co-Authored-By: Claude Opus 5.5 (1M context) --- src/agent_env/agents/README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 1060fc09f..edb14e795 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -44,11 +44,13 @@ The A2A server starts with the real-time marker, so it and its records stay on r `sync_env_clock` with `agent_clock` (off by default; `require_agent_clock` implies it) has armed the clock, it declares the agent at the gateway as a follower with a read token of its own and calls that `sync_time` with the follower's config, which the server writes; `deploy_agent` does the same for an agent it deploys while that clock is armed. -That call is also what loads agent-env's libfaketime: an image names its clock libraries (`AGENTENV_CLOCK_PRELOAD`) -and preloads them into nothing, and `sync_time` puts them in `LD_PRELOAD` for every program the server starts from then -on (`agentenv_protocol.a2a_agent.clock.preload`), as a server restarted mid-run does again. Without it the agent's CLI -runs with no libfaketime, on real time, as its files' modification times are: a CLI that judges a file's age by them, -as Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the env's date is ahead. From then on the CLI, its own +Without it the agent's CLI runs on real time, as its files' modification times are: a CLI that judges a file's age by +them, as Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the env's date is +ahead. In an image whose clock is opt-in, that call is also what loads agent-env's libfaketime: the image names its +clock libraries (`AGENTENV_CLOCK_PRELOAD`) and preloads them into nothing, and `sync_time` puts them in `LD_PRELOAD` for +every program the server starts from then on (`agentenv_protocol.a2a_agent.clock.preload`), as a server restarted +mid-run does again. Claude Code's and OpenCode's images still preload them into every process of the agent's user +(`/etc/ld.so.preload`), where an unarmed page leaves the time real, until they move over. From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for followers waits for the agent. While the clock is armed the CLI goes out through the egress proxy, which keeps TLS working at any date the clock shows, a live site's, an env MCP server's or the model endpoint's; only loopback hosts From deb463f9b731a31cb5dc826db187b17d063ea01b Mon Sep 17 00:00:00 2001 From: William Loo Date: Thu, 19 Nov 2026 17:15:00 -0800 Subject: [PATCH 4/8] [FD-6368] feat(protocol): clock/v1's use_env_time is the agent's opt-in; sync_time only configures the follower AgentEnvAgent serves a second clock/v1 method, use_env_time: it loads the image's clock libraries (AGENTENV_CLOCK_PRELOAD) into LD_PRELOAD for what the server starts, and is refused before sync_time has configured the follower. sync_time no longer loads anything. A server restarted mid-run loads them again only once use_env_time was called. Core calls use_env_time right after sync_time where an agent's card serves it, which it does only for a task whose sync_env_clock sets agent_clock; a use_env_time that fails fails the step and retires the follower, as a failed sync_time does. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/agentenv_protocol/a2a_agent/clock.py | 44 ++++++++----- .../agentenv_protocol/a2a_agent/extensions.py | 12 +++- .../agentenv_protocol/a2a_agent/framework.py | 7 +++ .../tests/test_a2a_agent_clock.py | 63 +++++++++++++------ src/agent_env/a2a_agent/clock.py | 25 ++++++-- src/agent_env/agents/README.md | 9 +-- tst/unit/task_step/agent_clock_test.py | 44 ++++++++++++- 7 files changed, 157 insertions(+), 47 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py index 4eaa85e11..6e7f6bae0 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py @@ -1,9 +1,10 @@ """An agent's side of clock/v1. An agent image that follows the env's clock runs the computer base's follower and carries agent-env's libfaketime, which reads universe time from the follower's page; the server itself stays on real -time. Following is opt-in: ``sync_time`` is what puts what the server starts on the env's clock. An image that names -its clock libraries (``PRELOAD_ENV``) loads them into no program until then, so a task that never asks runs its CLI as -an image without the clock does; once called, every program the server starts loads them (``LD_PRELOAD``). An older -image preloads them into every process of the agent's user from boot (``/etc/ld.so.preload``) and names none. +time. Reading the env's time is opt-in: ``sync_time`` configures the follower, and ``use_env_time``, which core calls +only for a task that asks, puts what the server starts on the follower's page. An image that names its clock libraries +(``PRELOAD_ENV``) loads them into no program until then, so a task that never asks runs its CLI as an image without the +clock does; once called, every program the server starts loads them (``LD_PRELOAD``). An older image preloads them into +every process of the agent's user from boot (``/etc/ld.so.preload``) and names none. The framework serves clock/v1's ``sync_time``, the method every server and computer that follows the clock serves, on the card of an agent in such an image (``follows``), so the card is what tells core the agent follows. Unlike a @@ -91,13 +92,30 @@ def preload() -> bool: return True -def restore() -> str | None: - """What ``sync_time`` set for what this server starts, set again: called when it starts, so one that restarts - mid-run keeps the clock libraries and the task's zone, as the follower keeps the clock. The zone, or None when a - config saved none or isn't there, when nothing is restored.""" +def _opted_in() -> Path: + """Kept beside the follower's config once ``use_env_time`` is called, so a server restarted mid-run loads the clock + libraries again.""" + return Path(follower.CONFIG).with_name("use-env-time") + + +def use_env_time() -> dict: + """``clock/v1``'s ``use_env_time`` on an agent, the opt-in: every program this server starts from now on reads the + env's time from the follower's page (``preload``), which ``sync_time`` has configured. Whether the image's + libraries were loaded now (``preloaded``): false for an image that preloads them for every process already.""" + if not follows(): + raise TargetUnavailable("this agent's image doesn't run the clock follower") if not Path(follower.CONFIG).exists(): - return None - preload() + raise InvalidArgument("use_env_time follows sync_time, which configures the follower it reads; none has") + _opted_in().touch(mode=0o640) + return {"env_time": True, "preloaded": preload()} + + +def restore() -> str | None: + """What ``sync_time`` and ``use_env_time`` set for what this server starts, set again: called when it starts, so one + that restarts mid-run keeps the task's zone and, once opted in, the clock libraries, as the follower keeps the + clock. The zone, or None when a config saved none or isn't there.""" + if _opted_in().exists(): + preload() return restore_zone() @@ -118,9 +136,8 @@ def restore_zone() -> str | None: async def sync_time(env_get_time_url: str, timezone: str | None = None, watch_url: str | None = None, name: str | None = None, read_token: str | None = None) -> dict: - """``clock/v1``'s ``sync_time`` on an agent, the call that opts it into the env's clock: the follower configured to - follow the gateway at ``watch_url`` as ``name`` with ``read_token``, the task's ``timezone`` set and the clock - libraries loaded (``preload``) for what this server starts once it follows, and an answer once the + """``clock/v1``'s ``sync_time`` on an agent: the follower configured to follow the gateway at ``watch_url`` as + ``name`` with ``read_token``, the task's ``timezone`` set for what this server starts, and an answer once the follower shows the gateway's version for that config, never what it showed of one before. ``env_get_time_url`` is taken as every server takes it and not used: the follower reads the gateway's watch, not its time.""" if not follows(): @@ -133,5 +150,4 @@ async def sync_time(env_get_time_url: str, timezone: str | None = None, watch_ur zone = set_zone(timezone) if timezone is not None else os.environ.get("TZ") or "UTC" written = write_config(watch_url, name, read_token, zone) shown = await follower.following("this agent's clock follower", follower.CONNECT_WAIT_S, url=watch_url, name=name, since_ns=written) - preload() return {"synced": True, "timezone": zone, "env_get_time_url": env_get_time_url, "follower": shown} diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py index 8de0a8f16..b969d473f 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py @@ -1456,8 +1456,9 @@ def _configure_trajectory( CLOCK_V1 = ExtensionDefinition( uri="urn:agentenv:clock/v1", description=( - "Follow the env's clock: the agent's image runs the clock follower, so every program the agent runs reads " - "the env's time. Served where the image has the follower." + "Follow the env's clock: the agent's image runs the clock follower, which sync_time configures; " + "use_env_time, the opt-in, then has every program the agent starts read the env's time. Served where the " + "image has the follower." ), endpoint="/ext/clock", core_operations={ @@ -1469,6 +1470,13 @@ def _configure_trajectory( request_model=ClockSyncTimeRequest, response_required=("synced", "timezone", "follower"), ), + "use_env_time": _op( + "use_env_time", + "POST", + "/ext/clock/use-env-time", + SDK, + response_required=("env_time", "preloaded"), + ), }, ) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index 8de281b87..8b2918b4e 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -686,6 +686,7 @@ def handlers(self) -> dict[tuple[str, str], Callable]: (TRIGGERS_V1.uri, "decide"): self.triggers_decide, (TRIGGERS_V1.uri, "state"): self.triggers_state, (CLOCK_V1.uri, "sync_time"): self.clock_sync_time, + (CLOCK_V1.uri, "use_env_time"): self.clock_use_env_time, } async def agent_config_set(self, request: AgentConfig) -> dict[str, Any]: @@ -1033,6 +1034,12 @@ async def clock_sync_time(self, request: ClockSyncTimeRequest) -> dict[str, Any] except ComputerError as exc: raise HTTPException(status_code=exc.STATUS, detail=f"{exc.CODE}: {exc}") from exc + async def clock_use_env_time(self) -> dict[str, Any]: + try: + return agent_clock.use_env_time() + except ComputerError as exc: + raise HTTPException(status_code=exc.STATUS, detail=f"{exc.CODE}: {exc}") from exc + def _with_clock(definition: _AgentDefinition) -> _AgentDefinition: """``definition`` serving clock/v1 where the agent's image runs the clock follower, so every agent in such an diff --git a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py index d82ed3c01..2a72e6f88 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py @@ -1,7 +1,7 @@ """An agent's side of clock/v1: in an image that runs the clock follower, every AgentEnvAgent serves sync_time with no -code of its own; called by sync_env_clock, the opt-in, it writes the follower's config from the request, sets the -task's zone and loads the image's clock libraries for what the server starts, and answers once the follower shows the -gateway's current version, or says why it doesn't.""" +code of its own; called by sync_env_clock, it writes the follower's config from the request, sets the task's zone for +what the server starts, and answers once the follower shows the gateway's current version, or says why it doesn't; +use_env_time, the opt-in, then loads the image's clock libraries into what the server starts.""" from __future__ import annotations import json @@ -196,52 +196,75 @@ def test_a_server_restarted_mid_run_takes_back_the_tasks_zone(image, monkeypatch assert os.environ["TZ"] == "America/Chicago" and time.strftime("%Z") in {"CST", "CDT"} -def test_until_sync_time_no_program_the_server_starts_loads_the_clock_libraries(image, opt_in): +def _synced(image, client) -> None: + _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") + assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 + + +def test_the_card_serves_use_env_time_beside_sync_time(image): with _app() as client: - assert _clock(client) is not None + methods = _clock(client)["params"]["methods"] + + assert set(methods) == {"sync_time", "use_env_time"} + assert methods["use_env_time"]["method"] == "POST" + + +def test_sync_time_alone_loads_the_clock_libraries_into_nothing(image, opt_in): + with _app() as client: + _synced(image, client) assert "LD_PRELOAD" not in os.environ and os.environ[agent_clock.REAL_TIME_ENV] == "1" -def test_sync_time_loads_the_clock_libraries_into_what_the_server_starts_once_it_follows(image, opt_in, monkeypatch): +def test_use_env_time_loads_the_clock_libraries_into_what_the_server_starts(image, opt_in, monkeypatch): monkeypatch.setenv("LD_PRELOAD", "/opt/other.so") - _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") with _app() as client: - assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 - assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 # again: nothing loaded twice + _synced(image, client) + answer = client.post("/ext/clock/use-env-time") + assert client.post("/ext/clock/use-env-time").status_code == 200 # again: nothing loaded twice + assert answer.status_code == 200 and answer.json() == {"env_time": True, "preloaded": True} assert os.environ["LD_PRELOAD"].split() == ["/opt/other.so", *LIBRARIES.split(":")] assert agent_clock.REAL_TIME_ENV not in os.environ -def test_a_sync_time_the_follower_doesnt_take_loads_nothing(image, opt_in): - _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:2") +def test_use_env_time_before_sync_time_is_refused_and_loads_nothing(image, opt_in): with _app() as client: - assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 404 + answer = client.post("/ext/clock/use-env-time") + assert answer.status_code == 400 and "sync_time" in answer.text assert "LD_PRELOAD" not in os.environ +def test_use_env_time_takes_no_request_fields(image, opt_in): + with _app() as client: + _synced(image, client) + assert client.post("/ext/clock/use-env-time", json={"x": 1}).status_code == 400 + + def test_an_image_that_preloads_for_every_process_has_nothing_loaded(image, monkeypatch): monkeypatch.delenv(agent_clock.PRELOAD_ENV, raising=False) monkeypatch.delenv("LD_PRELOAD", raising=False) - _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") with _app() as client: - assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 + _synced(image, client) + answer = client.post("/ext/clock/use-env-time") - assert "LD_PRELOAD" not in os.environ + assert answer.json() == {"env_time": True, "preloaded": False} and "LD_PRELOAD" not in os.environ -def test_a_server_restarted_mid_run_loads_the_clock_libraries_again(image, opt_in, monkeypatch): - _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") +@pytest.mark.parametrize("opted_in", [True, False]) +def test_a_server_restarted_mid_run_loads_the_clock_libraries_again_only_once_opted_in(image, opt_in, monkeypatch, + opted_in): with _app() as client: - assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 - monkeypatch.delenv("LD_PRELOAD") # the restarted server's environment: the image's + _synced(image, client) + if opted_in: + assert client.post("/ext/clock/use-env-time").status_code == 200 + monkeypatch.delenv("LD_PRELOAD", raising=False) # the restarted server's environment: the image's with _app() as client: assert client.get("/.well-known/agent.json").status_code == 200 - assert os.environ["LD_PRELOAD"].split() == LIBRARIES.split(":") + assert (os.environ.get("LD_PRELOAD", "").split() == LIBRARIES.split(":")) is opted_in @pytest.mark.parametrize("config", ['{"watch_url": "u", "name": "n", "token": "t"}', '{"timezone": "Mars/Olympus"}', diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index 59c844fdb..2d33b6f37 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -55,6 +55,13 @@ def _sync_time(agent: DeployedAgent) -> tuple[Optional[dict], Optional[str]]: return A2AAgent.operation(A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI), "sync_time") +def _use_env_time(agent: DeployedAgent) -> Optional[str]: + """The path of the agent's clock/v1 ``use_env_time``, the opt-in that has what it starts read the env's time; None + for an image from before it, which has every program read it from boot.""" + method, path = A2AAgent.operation(A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI), "use_env_time") + return path if method is not None else None + + def _fields(method: dict) -> set[str]: request = method.get("request") or {} return {*request.get("required", ()), *request.get("optional", ()), *(request.get("properties") or {})} @@ -70,7 +77,8 @@ def watch_url_for(agent: DeployedAgent, env: DeployedEnv) -> str: async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Optional[str], timezone: Optional[str], timeout: float) -> dict: - """Have ``agent`` follow ``env``'s gateway clock. ``{"synced": False, "reason": ...}`` for an agent that can't: + """Have ``agent`` follow ``env``'s gateway clock: its ``sync_time``, then its ``use_env_time`` where its card serves + one, so what it starts reads the env's time. ``{"synced": False, "reason": ...}`` for an agent that can't: its card serves no ``sync_time`` (``not_advertised``) or one without the follower's fields (``no_follower_fields``), or the gateway takes no followers after it starts (``gateway_takes_no_followers``); raises for one that serves it and fails, having retired the follower it declared, or can't take the task's zone, as for @@ -91,16 +99,23 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op return {"synced": False, "reason": "gateway_takes_no_followers"} body = {"env_get_time_url": env_get_time_url or "", "watch_url": watch_url_for(agent, env), "name": name, "read_token": token, **({"timezone": timezone} if timezone is not None else {})} - url = (agent.a2a_url or agent.api_url).rstrip("/") + path + base = (agent.a2a_url or agent.api_url).rstrip("/") + opt_in = _use_env_time(agent) try: async with httpx.AsyncClient() as client: - answer = await client.post(url, json=body, timeout=timeout, - headers={**sandbox_request_headers_for_url(url), **agent.control_headers}) + answer = await client.post(base + path, json=body, timeout=timeout, + headers={**sandbox_request_headers_for_url(base + path), **agent.control_headers}) + if answer.status_code < 400 and opt_in is not None: + using = await client.post(base + opt_in, timeout=timeout, + headers={**sandbox_request_headers_for_url(base + opt_in), **agent.control_headers}) + if using.status_code >= 400: + answer = using except httpx.HTTPError as e: why = f"({type(e).__name__}): {e}" else: if answer.status_code < 400: - return {"synced": True, "follower": name, "result": answer.json()} + return {"synced": True, "follower": name, "result": answer.json(), + **({"env_time": using.json()} if opt_in is not None else {})} why = f"(HTTP {answer.status_code}): {answer.text}" # Declared and not following: the gateway would wait for it on every later write, and nothing records it to retire. await _retire(env, name, timeout=RETIRE_TIMEOUT_S) diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index edb14e795..c10ed67d1 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -46,10 +46,11 @@ the agent at the gateway as a follower with a read token of its own and calls th config, which the server writes; `deploy_agent` does the same for an agent it deploys while that clock is armed. Without it the agent's CLI runs on real time, as its files' modification times are: a CLI that judges a file's age by them, as Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the env's date is -ahead. In an image whose clock is opt-in, that call is also what loads agent-env's libfaketime: the image names its -clock libraries (`AGENTENV_CLOCK_PRELOAD`) and preloads them into nothing, and `sync_time` puts them in `LD_PRELOAD` for -every program the server starts from then on (`agentenv_protocol.a2a_agent.clock.preload`), as a server restarted -mid-run does again. Claude Code's and OpenCode's images still preload them into every process of the agent's user +ahead. After `sync_time`, core calls clock/v1's `use_env_time`, the agent's opt-in, where its card serves it: in an +image whose clock is opt-in, that is what loads agent-env's libfaketime. The image names its clock libraries +(`AGENTENV_CLOCK_PRELOAD`) and preloads them into nothing, and `use_env_time` puts them in `LD_PRELOAD` for every +program the server starts from then on (`agentenv_protocol.a2a_agent.clock.preload`), as a server restarted mid-run +does again. Claude Code's and OpenCode's images still preload them into every process of the agent's user (`/etc/ld.so.preload`), where an unarmed page leaves the time real, until they move over. From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for followers waits for the agent. While the clock is armed the CLI goes out through the egress proxy, which keeps TLS diff --git a/tst/unit/task_step/agent_clock_test.py b/tst/unit/task_step/agent_clock_test.py index a5b92f2c6..bedd460c2 100644 --- a/tst/unit/task_step/agent_clock_test.py +++ b/tst/unit/task_step/agent_clock_test.py @@ -21,6 +21,7 @@ AGENT_CONTROL_TOKEN = "the-agents-control-token" SYNC_TIME = {"method": "POST", "endpoint": "/ext/clock/sync-time", "request": {"required": ["env_get_time_url"], "optional": ["timezone", "watch_url", "name", "read_token"]}} +USE_ENV_TIME = {"method": "POST", "endpoint": "/ext/clock/use-env-time"} def _step(**kw) -> SyncEnvClockTaskStep: @@ -28,8 +29,9 @@ def _step(**kw) -> SyncEnvClockTaskStep: return _sync_step(**{"agent_clock": True, **kw}) -def _agent(name="solver", sync_time=SYNC_TIME, env_ids=("e1",), env_step_id=None) -> DeployedAgent: - extensions = [{"uri": EXT_CLOCK_URI, "params": {"endpoint": "/ext/clock", "methods": {"sync_time": sync_time}}}] +def _agent(name="solver", sync_time=SYNC_TIME, env_ids=("e1",), env_step_id=None, use_env_time=None) -> DeployedAgent: + methods = {"sync_time": sync_time, **({"use_env_time": use_env_time} if use_env_time else {})} + extensions = [{"uri": EXT_CLOCK_URI, "params": {"endpoint": "/ext/clock", "methods": methods}}] return DeployedAgent(agent_name=name, api_url=AGENT_URL, a2a_url=AGENT_URL, env_ids=list(env_ids), env_bindings={env_id: env_step_id for env_id in env_ids} if env_step_id else {}, a2a_card={"capabilities": {"extensions": extensions if sync_time else []}}, @@ -68,6 +70,44 @@ async def test_an_agent_is_declared_a_follower_then_handed_its_config_with_the_s assert (agent["agent"], agent["synced"], agent["follower"]) == ("solver", True, "agent-solver") +@pytest.mark.asyncio +async def test_an_agent_whose_card_serves_use_env_time_is_opted_in_after_sync_time(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + _no_servers(monkeypatch) + context = await _context(_agent(use_env_time=USE_ENV_TIME)) + + await _step().execute(context) + + assert [(r.method, "/" + "/".join(r.url.path.split("/")[-2:])) for r in sent][3:] == [ + ("PUT", "/clock/followers"), ("POST", "/clock/sync-time"), ("POST", "/clock/use-env-time")] + assert sent[-1].headers[CONTROL_TOKEN_HEADER] == AGENT_CONTROL_TOKEN and sent[-1].content == b"" + [agent] = context.metadata["clock_configurations"][0]["agents"] + assert agent["synced"] is True and "env_time" in agent + + +@pytest.mark.asyncio +async def test_a_use_env_time_that_fails_fails_the_step_and_its_follower_is_retired(monkeypatch): + import httpx + + real, sent = httpx.AsyncClient, [] + + def handle(request: httpx.Request) -> httpx.Response: + sent.append((request.method, request.url.path)) + if request.url.path == "/ext/clock/use-env-time": + return httpx.Response(400, json={"detail": "invalid_argument: no config"}) + return httpx.Response(200, json={"env_get_time_url": CLOCK_URL} if request.url.path.endswith("/state") else {}) + + monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **k: real(transport=httpx.MockTransport(handle))) + _no_servers(monkeypatch) + context = await _context(_agent(use_env_time=USE_ENV_TIME)) + + with pytest.raises(RuntimeError, match="agent 'solver' doesn't follow the clock of env 'e1' \\(HTTP 400\\): .*no config"): + await _step().execute(context) + + assert [(m, "/" + "/".join(p.split("/")[-2:])) for m, p in sent[-2:]] == [ + ("POST", "/clock/use-env-time"), ("DELETE", "/clock/followers")] + + @pytest.mark.asyncio async def test_only_the_agents_registered_with_the_env_follow_its_clock(monkeypatch): sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) From 453e0d237b155ab1bcd600c8495824d7cde2d7b2 Mon Sep 17 00:00:00 2001 From: William Loo Date: Thu, 19 Nov 2026 18:41:55 -0800 Subject: [PATCH 5/8] fix(protocol): use_env_time is an optional clock/v1 feature, so an agent with its own sync_time still starts As a core operation, use_env_time left an agent that overrides CLOCK_V1.sync_time only partly overriding clock/v1's SDK operations, and build_registry refused it. It is now the optional feature env_time, which the SDK's own clock turns on; an agent that declares clock/v1 itself serves sync_time alone, as before. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../agentenv_protocol/a2a_agent/extensions.py | 21 ++++++++++++------- .../agentenv_protocol/a2a_agent/framework.py | 3 ++- .../tests/test_a2a_agent_clock.py | 18 ++++++++++++++++ 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py index b969d473f..81cda42b1 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py @@ -1470,13 +1470,20 @@ def _configure_trajectory( request_model=ClockSyncTimeRequest, response_required=("synced", "timezone", "follower"), ), - "use_env_time": _op( - "use_env_time", - "POST", - "/ext/clock/use-env-time", - SDK, - response_required=("env_time", "preloaded"), - ), + }, + # Optional, so an agent that serves its own sync_time needn't serve it; the SDK's clock turns it on. + optional_features={ + "env_time": OperationGroup( + { + "use_env_time": _op( + "use_env_time", + "POST", + "/ext/clock/use-env-time", + SDK, + response_required=("env_time", "preloaded"), + ) + } + ) }, ) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index 8b2918b4e..ac08571d8 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -1049,7 +1049,8 @@ def _with_clock(definition: _AgentDefinition) -> _AgentDefinition: if not agent_clock.follows() or any(a.definition.uri == CLOCK_V1.uri for a in definition.extensions): return definition agent_clock.restore() # a server restarted mid-run takes back the clock libraries and the task's zone - return dataclasses.replace(definition, extensions=(*definition.extensions, ExtensionActivation(CLOCK_V1))) + return dataclasses.replace(definition, extensions=(*definition.extensions, + ExtensionActivation(CLOCK_V1, features=frozenset({"env_time"})))) class DefaultExtensionHandlers: diff --git a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py index 2a72e6f88..dbf0fa3d3 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py @@ -22,6 +22,8 @@ a2a_agent, ) from agentenv_protocol.a2a_agent import clock as agent_clock +from agentenv_protocol.a2a_agent import extension +from agentenv_protocol.a2a_agent.extensions import ClockSyncTimeRequest from agentenv_protocol.computer import clock as follower REQUEST = {"env_get_time_url": "http://gw/clock/time", "watch_url": "http://gw/clock/watch", "name": "agent-solver", @@ -209,6 +211,22 @@ def test_the_card_serves_use_env_time_beside_sync_time(image): assert methods["use_env_time"]["method"] == "POST" +def test_an_agent_that_serves_its_own_sync_time_still_starts_without_use_env_time(image): + + @a2a_agent(identity=AgentIdentity(name="own-clock", description="test", version="1"), extensions=(CLOCK_V1,)) + class Agent(AgentEnvAgent): + async def run(self, request: TaskRequest) -> TaskResult: + return TaskResult.text("ok") + + @extension(CLOCK_V1.sync_time) + async def sync_time(self, request: ClockSyncTimeRequest) -> dict: + return {"synced": True, "timezone": "UTC", "follower": {}} + + with TestClient(Agent().create_app()) as client: + assert set(_clock(client)["params"]["methods"]) == {"sync_time"} + assert client.post("/ext/clock/use-env-time").status_code == 404 + + def test_sync_time_alone_loads_the_clock_libraries_into_nothing(image, opt_in): with _app() as client: _synced(image, client) From 5091afb7c8b9cbd5168a2c1296fa92f7e449cf17 Mon Sep 17 00:00:00 2001 From: William Loo Date: Thu, 19 Nov 2026 19:13:53 -0800 Subject: [PATCH 6/8] refactor(clock): use_env_time arms the follower's page; libfaketime stays preloaded and reads real time until then Keeping /etc/ld.so.preload and toggling what it reads is smaller and complete: libfaketime already reads real time from an unarmed page, and every issue so far (FD-6368, gemini's lock, the proxy's TLS) needs an armed one. The follower takes env_time from its config: false, it follows and acknowledges the gateway's versions while the page stays real time; missing, as a computer's config is, it arms as before. An agent's sync_time writes env_time false (true kept for the same gateway and name); use_env_time turns it on and answers once the follower shows it. The LD_PRELOAD opt-in, AGENTENV_CLOCK_PRELOAD and the restart marker are gone, and images need no change beyond the follower they copy. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/agentenv_protocol/a2a_agent/clock.py | 100 +++++++----------- .../agentenv_protocol/a2a_agent/extensions.py | 2 +- .../agentenv_protocol/a2a_agent/framework.py | 7 +- .../tests/test_a2a_agent_clock.py | 90 ++++++---------- src/agent_env/agents/README.md | 10 +- .../utils/faketime_clock/clock-follower | 10 +- .../env/envs/test_computer_clock_follower.py | 21 ++++ 7 files changed, 110 insertions(+), 130 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py index 6e7f6bae0..4552f9884 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py @@ -1,10 +1,8 @@ -"""An agent's side of clock/v1. An agent image that follows the env's clock runs the computer base's follower and -carries agent-env's libfaketime, which reads universe time from the follower's page; the server itself stays on real -time. Reading the env's time is opt-in: ``sync_time`` configures the follower, and ``use_env_time``, which core calls -only for a task that asks, puts what the server starts on the follower's page. An image that names its clock libraries -(``PRELOAD_ENV``) loads them into no program until then, so a task that never asks runs its CLI as an image without the -clock does; once called, every program the server starts loads them (``LD_PRELOAD``). An older image preloads them into -every process of the agent's user from boot (``/etc/ld.so.preload``) and names none. +"""An agent's side of clock/v1. An agent image that follows the env's clock runs the computer base's follower, and +agent-env's libfaketime is preloaded for the agent's user, so every program the A2A server starts reads its time from +the follower's page; the server itself starts with the real-time marker and stays on real time. Reading the env's time +is opt-in: ``sync_time`` has the follower follow the gateway with ``env_time`` off, so it acknowledges the gateway's +versions while the page stays real time, and ``use_env_time``, which core calls only for a task that asks, turns it on. The framework serves clock/v1's ``sync_time``, the method every server and computer that follows the clock serves, on the card of an agent in such an image (``follows``), so the card is what tells core the agent follows. Unlike a @@ -26,28 +24,29 @@ from ..computer import clock as follower from ..computer.errors import InvalidArgument, TargetUnavailable -#: Set by an image whose clock is opt-in: the libraries, as LD_PRELOAD names them, that put a program on the follower's -#: page. -PRELOAD_ENV = "AGENTENV_CLOCK_PRELOAD" -#: The marker agent-env's libfaketime keeps a program on real time by, and takes out of its environment; one this server -#: was started with would keep everything it starts on real time. -REAL_TIME_ENV = "AGENTENV_REAL_TIME" - def follows() -> bool: """Whether this agent's image runs the clock follower.""" return follower.follows() -def write_config(watch_url: str, name: str, read_token: str, timezone: str | None = None) -> int: - """The follower's config, with the task's ``timezone`` for ``restore_zone``, written beside its place and renamed - into it, so the follower, which reads it every quarter second, never reads half of one; readable by this user and - the follower's group alone. When it was +def _config() -> dict: + try: + config = json.loads(Path(follower.CONFIG).read_text()) + except (OSError, ValueError): + return {} + return config if isinstance(config, dict) else {} + + +def write_config(watch_url: str, name: str, read_token: str, timezone: str | None = None, env_time: bool = False) -> int: + """The follower's config, with the task's ``timezone`` for ``restore_zone`` and whether the page reads the env's + time (``env_time``), written beside its place and renamed into it, so the follower, which reads it every quarter + second, never reads half of one; readable by this user and the follower's group alone. When it was written (``st_mtime_ns``), which a status must postdate to be of this config; 0 when the config was this one already, which the follower goes on following without writing its status anew.""" path = Path(follower.CONFIG) raw = json.dumps({"watch_url": watch_url, "name": name, "token": read_token, - **({"timezone": timezone} if timezone else {})}).encode() + **({"timezone": timezone} if timezone else {}), "env_time": env_time}).encode() try: if path.read_bytes() == raw: return 0 @@ -79,46 +78,6 @@ def set_zone(timezone: str) -> str: return zone -def preload() -> bool: - """Every program this server starts from now on loads the image's clock libraries (``PRELOAD_ENV``), and so reads - the env's time once the follower arms its page; the server itself, already running, stays on real time. Whether - the image names any: one that preloads them for every process already has them in every program.""" - libraries = (os.environ.get(PRELOAD_ENV) or "").replace(":", " ").split() - if not libraries: - return False - loaded = (os.environ.get("LD_PRELOAD") or "").replace(":", " ").split() - os.environ["LD_PRELOAD"] = " ".join(dict.fromkeys([*loaded, *libraries])) - os.environ.pop(REAL_TIME_ENV, None) - return True - - -def _opted_in() -> Path: - """Kept beside the follower's config once ``use_env_time`` is called, so a server restarted mid-run loads the clock - libraries again.""" - return Path(follower.CONFIG).with_name("use-env-time") - - -def use_env_time() -> dict: - """``clock/v1``'s ``use_env_time`` on an agent, the opt-in: every program this server starts from now on reads the - env's time from the follower's page (``preload``), which ``sync_time`` has configured. Whether the image's - libraries were loaded now (``preloaded``): false for an image that preloads them for every process already.""" - if not follows(): - raise TargetUnavailable("this agent's image doesn't run the clock follower") - if not Path(follower.CONFIG).exists(): - raise InvalidArgument("use_env_time follows sync_time, which configures the follower it reads; none has") - _opted_in().touch(mode=0o640) - return {"env_time": True, "preloaded": preload()} - - -def restore() -> str | None: - """What ``sync_time`` and ``use_env_time`` set for what this server starts, set again: called when it starts, so one - that restarts mid-run keeps the task's zone and, once opted in, the clock libraries, as the follower keeps the - clock. The zone, or None when a config saved none or isn't there.""" - if _opted_in().exists(): - preload() - return restore_zone() - - def restore_zone() -> str | None: """The task's zone ``sync_time`` saved, set again for what this server starts: called when it starts, so one that restarts mid-run keeps the zone, as the follower keeps the clock. None when there's none, or it isn't a zone.""" @@ -137,7 +96,8 @@ def restore_zone() -> str | None: async def sync_time(env_get_time_url: str, timezone: str | None = None, watch_url: str | None = None, name: str | None = None, read_token: str | None = None) -> dict: """``clock/v1``'s ``sync_time`` on an agent: the follower configured to follow the gateway at ``watch_url`` as - ``name`` with ``read_token``, the task's ``timezone`` set for what this server starts, and an answer once the + ``name`` with ``read_token``, on real time until ``use_env_time`` (as it was, for the same gateway and name), the + task's ``timezone`` set for what this server starts, and an answer once the follower shows the gateway's version for that config, never what it showed of one before. ``env_get_time_url`` is taken as every server takes it and not used: the follower reads the gateway's watch, not its time.""" if not follows(): @@ -148,6 +108,24 @@ async def sync_time(env_get_time_url: str, timezone: str | None = None, watch_ur + (", ".join(k for k, v in (("watch_url", watch_url), ("name", name), ("read_token", read_token)) if v) or "none of them")) zone = set_zone(timezone) if timezone is not None else os.environ.get("TZ") or "UTC" - written = write_config(watch_url, name, read_token, zone) + kept = _config() + env_time = kept.get("env_time") is True and (kept.get("watch_url"), kept.get("name")) == (watch_url, name) + written = write_config(watch_url, name, read_token, zone, env_time) shown = await follower.following("this agent's clock follower", follower.CONNECT_WAIT_S, url=watch_url, name=name, since_ns=written) return {"synced": True, "timezone": zone, "env_get_time_url": env_get_time_url, "follower": shown} + + +async def use_env_time() -> dict: + """``clock/v1``'s ``use_env_time`` on an agent, the opt-in: the follower ``sync_time`` configured arms the page as + the gateway's clock is, so every program this server starts reads the env's time; an answer once the follower + shows that config. Refused before ``sync_time``. An image whose follower predates ``env_time`` arms it from + ``sync_time`` on.""" + if not follows(): + raise TargetUnavailable("this agent's image doesn't run the clock follower") + config = _config() + if not all(isinstance(config.get(key), str) and config[key] for key in ("watch_url", "name", "token")): + raise InvalidArgument("use_env_time follows sync_time, which configures the follower it arms; none has") + written = write_config(config["watch_url"], config["name"], config["token"], config.get("timezone"), True) + shown = await follower.following("this agent's clock follower", follower.CONNECT_WAIT_S, url=config["watch_url"], + name=config["name"], since_ns=written) + return {"env_time": True, "follower": shown} diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py index 81cda42b1..c69f0ebfc 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py @@ -1480,7 +1480,7 @@ def _configure_trajectory( "POST", "/ext/clock/use-env-time", SDK, - response_required=("env_time", "preloaded"), + response_required=("env_time", "follower"), ) } ) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index ac08571d8..b00b0b4e6 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -1036,19 +1036,18 @@ async def clock_sync_time(self, request: ClockSyncTimeRequest) -> dict[str, Any] async def clock_use_env_time(self) -> dict[str, Any]: try: - return agent_clock.use_env_time() + return await agent_clock.use_env_time() except ComputerError as exc: raise HTTPException(status_code=exc.STATUS, detail=f"{exc.CODE}: {exc}") from exc def _with_clock(definition: _AgentDefinition) -> _AgentDefinition: """``definition`` serving clock/v1 where the agent's image runs the clock follower, so every agent in such an - image can follow the env's clock with no code of its own, and takes back the clock libraries and the task's zone if - it restarted mid-run; + image follows the env's clock with no code of its own, and takes back the task's zone if it restarted mid-run; unchanged elsewhere, or where the agent declares it.""" if not agent_clock.follows() or any(a.definition.uri == CLOCK_V1.uri for a in definition.extensions): return definition - agent_clock.restore() # a server restarted mid-run takes back the clock libraries and the task's zone + agent_clock.restore_zone() # a server restarted mid-run takes back the task's zone return dataclasses.replace(definition, extensions=(*definition.extensions, ExtensionActivation(CLOCK_V1, features=frozenset({"env_time"})))) diff --git a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py index dbf0fa3d3..c46c3fc97 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py @@ -1,7 +1,7 @@ """An agent's side of clock/v1: in an image that runs the clock follower, every AgentEnvAgent serves sync_time with no -code of its own; called by sync_env_clock, it writes the follower's config from the request, sets the task's zone for -what the server starts, and answers once the follower shows the gateway's current version, or says why it doesn't; -use_env_time, the opt-in, then loads the image's clock libraries into what the server starts.""" +code of its own; called by sync_env_clock, it writes the follower's config from the request, on real time, sets the +task's zone for what the server starts, and answers once the follower shows the gateway's current version, or says why +it doesn't; use_env_time, the opt-in, then has the follower arm the page as the gateway's clock is.""" from __future__ import annotations import json @@ -21,7 +21,6 @@ TaskResult, a2a_agent, ) -from agentenv_protocol.a2a_agent import clock as agent_clock from agentenv_protocol.a2a_agent import extension from agentenv_protocol.a2a_agent.extensions import ClockSyncTimeRequest from agentenv_protocol.computer import clock as follower @@ -45,18 +44,6 @@ def image(tmp_path, monkeypatch): time.tzset() -LIBRARIES = "/usr/local/lib/agentenv-clock/libfaketimeMT.so.1:/usr/local/lib/agentenv-clock/libtls_realtime.so" - - -@pytest.fixture -def opt_in(monkeypatch): - """An image whose clock is opt-in: it names its clock libraries, preloads nothing, and starts the server with the - real-time marker, as an image from before did.""" - monkeypatch.setenv(agent_clock.PRELOAD_ENV, LIBRARIES) - monkeypatch.delenv("LD_PRELOAD", raising=False) - monkeypatch.setenv(agent_clock.REAL_TIME_ENV, "1") - - def _status(image, **status) -> None: (image / "status.json").write_text(json.dumps(status)) @@ -131,7 +118,7 @@ def test_sync_time_writes_the_followers_config_sets_the_zone_and_answers_once_it "armed": True}} config = image / "follower.json" assert json.loads(config.read_text()) == {"watch_url": "http://gw/clock/watch", "name": "agent-solver", - "token": "token", "timezone": "America/Chicago"} + "token": "token", "timezone": "America/Chicago", "env_time": False} assert stat.S_IMODE(config.stat().st_mode) == 0o640 assert os.environ["TZ"] == "America/Chicago" and time.strftime("%Z") in {"CST", "CDT"} assert [p.name for p in image.iterdir() if p.name.startswith("follower.json.")] == [] @@ -198,9 +185,13 @@ def test_a_server_restarted_mid_run_takes_back_the_tasks_zone(image, monkeypatch assert os.environ["TZ"] == "America/Chicago" and time.strftime("%Z") in {"CST", "CDT"} -def _synced(image, client) -> None: - _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") - assert client.post("/ext/clock/sync-time", json=REQUEST).status_code == 200 +def _synced(image, client, request=REQUEST) -> None: + _follows_the_next_config(image, connected=True, url=request["watch_url"], name=request["name"], version="b:3") + assert client.post("/ext/clock/sync-time", json=request).status_code == 200 + + +def _env_time(image): + return json.loads((image / "follower.json").read_text())["env_time"] def test_the_card_serves_use_env_time_beside_sync_time(image): @@ -212,7 +203,6 @@ def test_the_card_serves_use_env_time_beside_sync_time(image): def test_an_agent_that_serves_its_own_sync_time_still_starts_without_use_env_time(image): - @a2a_agent(identity=AgentIdentity(name="own-clock", description="test", version="1"), extensions=(CLOCK_V1,)) class Agent(AgentEnvAgent): async def run(self, request: TaskRequest) -> TaskResult: @@ -227,62 +217,52 @@ async def sync_time(self, request: ClockSyncTimeRequest) -> dict: assert client.post("/ext/clock/use-env-time").status_code == 404 -def test_sync_time_alone_loads_the_clock_libraries_into_nothing(image, opt_in): +def test_sync_time_alone_has_the_follower_follow_on_real_time(image): with _app() as client: _synced(image, client) - assert "LD_PRELOAD" not in os.environ and os.environ[agent_clock.REAL_TIME_ENV] == "1" + assert _env_time(image) is False -def test_use_env_time_loads_the_clock_libraries_into_what_the_server_starts(image, opt_in, monkeypatch): - monkeypatch.setenv("LD_PRELOAD", "/opt/other.so") +def test_use_env_time_has_the_follower_arm_the_page_and_answers_once_it_shows_that_config(image): with _app() as client: _synced(image, client) - answer = client.post("/ext/clock/use-env-time") - assert client.post("/ext/clock/use-env-time").status_code == 200 # again: nothing loaded twice - - assert answer.status_code == 200 and answer.json() == {"env_time": True, "preloaded": True} - assert os.environ["LD_PRELOAD"].split() == ["/opt/other.so", *LIBRARIES.split(":")] - assert agent_clock.REAL_TIME_ENV not in os.environ - - -def test_use_env_time_before_sync_time_is_refused_and_loads_nothing(image, opt_in): - with _app() as client: + _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", + version="b:3", armed=True) answer = client.post("/ext/clock/use-env-time") - assert answer.status_code == 400 and "sync_time" in answer.text - assert "LD_PRELOAD" not in os.environ + assert answer.status_code == 200, answer.text + assert answer.json() == {"env_time": True, "follower": {"name": "agent-solver", "url": "http://gw/clock/watch", + "version": "b:3", "armed": True}} + assert json.loads((image / "follower.json").read_text()) == { + "watch_url": "http://gw/clock/watch", "name": "agent-solver", "token": "token", "timezone": "UTC", + "env_time": True} -def test_use_env_time_takes_no_request_fields(image, opt_in): +def test_sync_time_again_keeps_env_time_for_the_same_gateway_and_name_and_not_for_another(image): with _app() as client: _synced(image, client) - assert client.post("/ext/clock/use-env-time", json={"x": 1}).status_code == 400 + _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") + assert client.post("/ext/clock/use-env-time").status_code == 200 + _synced(image, client, {**REQUEST, "read_token": "another-token"}) + assert _env_time(image) is True + _synced(image, client, {**REQUEST, "watch_url": "http://other-gw/clock/watch"}) + assert _env_time(image) is False -def test_an_image_that_preloads_for_every_process_has_nothing_loaded(image, monkeypatch): - monkeypatch.delenv(agent_clock.PRELOAD_ENV, raising=False) - monkeypatch.delenv("LD_PRELOAD", raising=False) + +def test_use_env_time_before_sync_time_is_refused_and_writes_nothing(image): with _app() as client: - _synced(image, client) answer = client.post("/ext/clock/use-env-time") - assert answer.json() == {"env_time": True, "preloaded": False} and "LD_PRELOAD" not in os.environ + assert answer.status_code == 400 and "sync_time" in answer.text + assert not (image / "follower.json").exists() -@pytest.mark.parametrize("opted_in", [True, False]) -def test_a_server_restarted_mid_run_loads_the_clock_libraries_again_only_once_opted_in(image, opt_in, monkeypatch, - opted_in): +def test_use_env_time_takes_no_request_fields(image): with _app() as client: _synced(image, client) - if opted_in: - assert client.post("/ext/clock/use-env-time").status_code == 200 - monkeypatch.delenv("LD_PRELOAD", raising=False) # the restarted server's environment: the image's - - with _app() as client: - assert client.get("/.well-known/agent.json").status_code == 200 - - assert (os.environ.get("LD_PRELOAD", "").split() == LIBRARIES.split(":")) is opted_in + assert client.post("/ext/clock/use-env-time", json={"x": 1}).status_code == 400 @pytest.mark.parametrize("config", ['{"watch_url": "u", "name": "n", "token": "t"}', '{"timezone": "Mars/Olympus"}', diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index c10ed67d1..5cf30c22a 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -46,12 +46,10 @@ the agent at the gateway as a follower with a read token of its own and calls th config, which the server writes; `deploy_agent` does the same for an agent it deploys while that clock is armed. Without it the agent's CLI runs on real time, as its files' modification times are: a CLI that judges a file's age by them, as Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the env's date is -ahead. After `sync_time`, core calls clock/v1's `use_env_time`, the agent's opt-in, where its card serves it: in an -image whose clock is opt-in, that is what loads agent-env's libfaketime. The image names its clock libraries -(`AGENTENV_CLOCK_PRELOAD`) and preloads them into nothing, and `use_env_time` puts them in `LD_PRELOAD` for every -program the server starts from then on (`agentenv_protocol.a2a_agent.clock.preload`), as a server restarted mid-run -does again. Claude Code's and OpenCode's images still preload them into every process of the agent's user -(`/etc/ld.so.preload`), where an unarmed page leaves the time real, until they move over. From then on the CLI, its own +ahead. After `sync_time`, which has the follower follow the gateway with +`env_time` off, so it acknowledges each version while the page stays real time, core calls clock/v1's `use_env_time`, +the agent's opt-in, where its card serves it: the follower then arms the page as the gateway's clock is. libfaketime is +preloaded for the agent's user either way and reads real time from an unarmed page. From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for followers waits for the agent. While the clock is armed the CLI goes out through the egress proxy, which keeps TLS working at any date the clock shows, a live site's, an env MCP server's or the model endpoint's; only loopback hosts diff --git a/src/agent_env/utils/faketime_clock/clock-follower b/src/agent_env/utils/faketime_clock/clock-follower index fee4586b7..f046176b4 100755 --- a/src/agent_env/utils/faketime_clock/clock-follower +++ b/src/agent_env/utils/faketime_clock/clock-follower @@ -7,7 +7,9 @@ neither write it nor stop it. Core writes its config, the gateway's watch URL as this computer reaches it, the computer's name and its read token, through the sandbox's root channel (``CONFIG``, readable by root and this user alone); never through the driver, which runs as the session user. It reads the config every quarter second, during a watch too, and follows a changed one at -once. Until there is one, the clock stays as root made it at boot: real time. It reports how it's doing in ``STATUS``, +once. Until there is one, the clock stays as root made it at boot: real time. A config with ``env_time`` false, as an +agent's is until it opts in (clock/v1 ``use_env_time``), is followed and acknowledged as any other while the page +stays real time; a computer's names none and is armed as the gateway is. It reports how it's doing in ``STATUS``, which anyone may read and which holds no token: the gateway it follows, whether it's connected, the version it shows, or its last error. @@ -116,10 +118,12 @@ class Follower: def __init__(self, raw: bytes, config: dict): self.raw, self.url, self.name, self.token = raw, config["watch_url"], config["name"], config["token"] + # Whether the page follows the gateway's clock or stays real time while the follower acknowledges it. + self.env_time = config.get("env_time", True) is not False self.after, self.samples, self.written = "", [], None self.errors, self.backoff = 0, RETRY_FIRST_S self.status = {"url": self.url, "name": self.name, "connected": False, "version": None, "armed": False, - "error": None} + "env_time": self.env_time, "error": None} def report(self, **fields) -> None: self.status.update(fields) @@ -171,7 +175,7 @@ class Follower: self.samples = (self.samples + [{"delay": max(0.0, (t4 - t1) - held), "theta": ((body["received"] - t1) + (body["sent"] - t4)) / 2}])[-SAMPLES:] theta, dropped = offset(self.samples) - armed, universe, rate, anchor = state_of(body, theta) + armed, universe, rate, anchor = state_of(body if self.env_time else {}, theta) meaning = (armed, rate, universe - rate * anchor if armed else 0.0) changed = body["version"] != self.after moved = (self.written is None or meaning[:2] != self.written[:2] diff --git a/tst/unit/env/envs/test_computer_clock_follower.py b/tst/unit/env/envs/test_computer_clock_follower.py index 9f57d3f2d..47a8ffd96 100644 --- a/tst/unit/env/envs/test_computer_clock_follower.py +++ b/tst/unit/env/envs/test_computer_clock_follower.py @@ -167,6 +167,27 @@ def test_it_follows_the_gateway_its_config_names_and_acknowledges_each_version_w gateway.close() +def test_a_config_without_env_time_is_acknowledged_on_real_time_until_it_opts_in(follower): + """An agent's config names env_time false until clock/v1 use_env_time: the follower acknowledges the gateway's + versions, so clock writes can wait for it, while every program keeps real time.""" + gateway = Gateway() + try: + gateway.set("boot:1", datetime(2020, 1, 1, tzinfo=timezone.utc), 1.0) + config = {"watch_url": gateway.url, "name": "agent-solver", "token": "t"} + follower.configure({**config, "env_time": False}) + + status = follower.until(lambda: (s := follower.status()).get("version") == "boot:1" and s) + assert (status["armed"], status["env_time"]) == (False, False) + assert abs(follower.universe() - time.time()) < 2 + follower.until(lambda: ("boot:1", "agent-solver", "Bearer t") in gateway.watches) + + follower.configure({**config, "env_time": True}) + follower.until(lambda: follower.status().get("env_time") is True and follower.status().get("armed")) + assert abs(follower.universe() - datetime(2020, 1, 1, tzinfo=timezone.utc).timestamp()) < 2 + finally: + gateway.close() + + def test_a_changed_config_is_followed_at_once_during_a_held_watch(follower): first, second = Gateway(hold=30), Gateway(hold=30) try: From 7496597014920aced4915ca0ecea53156624ad08 Mon Sep 17 00:00:00 2001 From: William Loo Date: Thu, 19 Nov 2026 19:20:52 -0800 Subject: [PATCH 7/8] fix(protocol): an agent that declares clock/v1 and leaves it to the SDK serves use_env_time too _with_clock added the env_time feature only for agents that don't declare clock/v1, so one declaring it with the SDK's handlers served sync_time alone: the SDK's sync_time keeps real time until use_env_time, which core then never called, and the agent stayed on real time with require_agent_clock. Its declaration now gets env_time too; an agent that serves a clock/v1 operation of its own keeps its declaration. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../agentenv_protocol/a2a_agent/framework.py | 28 ++++++++++++++----- .../tests/test_a2a_agent_clock.py | 11 ++++++++ 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index b00b0b4e6..89bf34067 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -81,7 +81,7 @@ from . import clock as agent_clock from .control_token import REFUSAL, carries_control_token, log_guard, log_refusal, take_control_token from .peer_agents import PEER_MCP_PATH, PEER_MCP_SERVER_NAME, PeerAgents -from .registry import RegisteredOperation, build_registry +from .registry import RegisteredOperation, _discover_bindings, build_registry from .staging import STAGING_ENDPOINT, StagingStore, staging_routes from .tasks.v1 import ( AgentConfig, @@ -1041,11 +1041,25 @@ async def clock_use_env_time(self) -> dict[str, Any]: raise HTTPException(status_code=exc.STATUS, detail=f"{exc.CODE}: {exc}") from exc -def _with_clock(definition: _AgentDefinition) -> _AgentDefinition: - """``definition`` serving clock/v1 where the agent's image runs the clock follower, so every agent in such an - image follows the env's clock with no code of its own, and takes back the task's zone if it restarted mid-run; - unchanged elsewhere, or where the agent declares it.""" - if not agent_clock.follows() or any(a.definition.uri == CLOCK_V1.uri for a in definition.extensions): +def _with_clock(definition: _AgentDefinition, agent: Any = None) -> _AgentDefinition: + """``definition`` serving clock/v1, its opt-in ``use_env_time`` (feature ``env_time``) included, where the agent's + image runs the clock follower, so every agent in such an image can follow the env's clock with no code of its own, + and takes back the task's zone if it restarted mid-run. An agent that declares clock/v1 itself and leaves its + operations to the SDK gets ``use_env_time`` too, as the SDK's ``sync_time`` keeps real time until it; one that + serves an operation of its own keeps its declaration as it is. Unchanged where the image has no follower.""" + if not agent_clock.follows(): + return definition + declared = next((a for a in definition.extensions if a.definition.uri == CLOCK_V1.uri), None) + if declared is not None: + own = agent is not None and any(binding.extension.uri == CLOCK_V1.uri + for binding, _ in _discover_bindings(agent)) + if own or "env_time" in declared.features: + return definition + agent_clock.restore_zone() + opted = dataclasses.replace(declared, features=declared.features | {"env_time"}) + return dataclasses.replace(definition, extensions=tuple(opted if a is declared else a + for a in definition.extensions)) + if agent is not None and any(binding.extension.uri == CLOCK_V1.uri for binding, _ in _discover_bindings(agent)): return definition agent_clock.restore_zone() # a server restarted mid-run takes back the task's zone return dataclasses.replace(definition, extensions=(*definition.extensions, @@ -1165,7 +1179,7 @@ def __init__(self, agent: Any, definition: _AgentDefinition | None = None) -> No "agent instance is already bound to an application; create a new " "agent instance for each application" ) - definition = _with_clock(definition) + definition = _with_clock(definition, agent) self.agent = agent self.definition = definition self.rpc_path = _rpc_path(definition.identity.url) diff --git a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py index c46c3fc97..df0e4ed55 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py @@ -217,6 +217,17 @@ async def sync_time(self, request: ClockSyncTimeRequest) -> dict: assert client.post("/ext/clock/use-env-time").status_code == 404 +def test_an_agent_that_declares_the_clock_and_leaves_it_to_the_sdk_serves_use_env_time_too(image): + """Its sync_time is the SDK's, which keeps real time until use_env_time, so it must serve that too.""" + with _app(extensions=(CLOCK_V1,)) as client: + assert set(_clock(client)["params"]["methods"]) == {"sync_time", "use_env_time"} + _synced(image, client) + _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") + assert client.post("/ext/clock/use-env-time").status_code == 200 + + assert _env_time(image) is True + + def test_sync_time_alone_has_the_follower_follow_on_real_time(image): with _app() as client: _synced(image, client) From 48a65eca4144ab077e1fa9bbbbf7720d9361581d Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 19 Nov 2026 21:41:13 -0800 Subject: [PATCH 8/8] refactor(task_step): the agent clock's opt-in is sync_env_clock's agent_clock alone The framework only has agents follow from two places, sync_env_clock and deploy_agent's late follow, and both are gated on agent_clock. So sync_time keeps its meaning, "follow the env's clock", and a task that doesn't opt in never calls it: its agents keep real time and read the env's time from get_time. This drops clock/v1's use_env_time, the follower's env_time and the SDK's sync_time change. No protocol release or floor raise, and no agent image or computer base rebuilds: utils/faketime_clock is unchanged. An older framework calling sync_time gets today's behaviour. Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/a2a_agent/clock.py | 47 ++------ .../agentenv_protocol/a2a_agent/extensions.py | 19 +--- .../agentenv_protocol/a2a_agent/framework.py | 38 ++----- .../tests/test_a2a_agent_clock.py | 100 +----------------- src/agent_env/a2a_agent/clock.py | 25 +---- src/agent_env/agents/README.md | 13 +-- .../utils/faketime_clock/clock-follower | 10 +- .../env/envs/test_computer_clock_follower.py | 21 ---- tst/unit/task_step/agent_clock_test.py | 44 +------- 9 files changed, 37 insertions(+), 280 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py index 4552f9884..d1d66aef6 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py @@ -1,8 +1,6 @@ """An agent's side of clock/v1. An agent image that follows the env's clock runs the computer base's follower, and -agent-env's libfaketime is preloaded for the agent's user, so every program the A2A server starts reads its time from -the follower's page; the server itself starts with the real-time marker and stays on real time. Reading the env's time -is opt-in: ``sync_time`` has the follower follow the gateway with ``env_time`` off, so it acknowledges the gateway's -versions while the page stays real time, and ``use_env_time``, which core calls only for a task that asks, turns it on. +agent-env's libfaketime is preloaded for the agent's user, so every program the A2A server starts reads universe time +from the follower's page; the server itself starts with the real-time marker and stays on real time. The framework serves clock/v1's ``sync_time``, the method every server and computer that follows the clock serves, on the card of an agent in such an image (``follows``), so the card is what tells core the agent follows. Unlike a @@ -30,23 +28,15 @@ def follows() -> bool: return follower.follows() -def _config() -> dict: - try: - config = json.loads(Path(follower.CONFIG).read_text()) - except (OSError, ValueError): - return {} - return config if isinstance(config, dict) else {} - - -def write_config(watch_url: str, name: str, read_token: str, timezone: str | None = None, env_time: bool = False) -> int: - """The follower's config, with the task's ``timezone`` for ``restore_zone`` and whether the page reads the env's - time (``env_time``), written beside its place and renamed into it, so the follower, which reads it every quarter - second, never reads half of one; readable by this user and the follower's group alone. When it was +def write_config(watch_url: str, name: str, read_token: str, timezone: str | None = None) -> int: + """The follower's config, with the task's ``timezone`` for ``restore_zone``, written beside its place and renamed + into it, so the follower, which reads it every quarter second, never reads half of one; readable by this user and + the follower's group alone. When it was written (``st_mtime_ns``), which a status must postdate to be of this config; 0 when the config was this one already, which the follower goes on following without writing its status anew.""" path = Path(follower.CONFIG) raw = json.dumps({"watch_url": watch_url, "name": name, "token": read_token, - **({"timezone": timezone} if timezone else {}), "env_time": env_time}).encode() + **({"timezone": timezone} if timezone else {})}).encode() try: if path.read_bytes() == raw: return 0 @@ -96,8 +86,7 @@ def restore_zone() -> str | None: async def sync_time(env_get_time_url: str, timezone: str | None = None, watch_url: str | None = None, name: str | None = None, read_token: str | None = None) -> dict: """``clock/v1``'s ``sync_time`` on an agent: the follower configured to follow the gateway at ``watch_url`` as - ``name`` with ``read_token``, on real time until ``use_env_time`` (as it was, for the same gateway and name), the - task's ``timezone`` set for what this server starts, and an answer once the + ``name`` with ``read_token``, the task's ``timezone`` set for what this server starts, and an answer once the follower shows the gateway's version for that config, never what it showed of one before. ``env_get_time_url`` is taken as every server takes it and not used: the follower reads the gateway's watch, not its time.""" if not follows(): @@ -108,24 +97,6 @@ async def sync_time(env_get_time_url: str, timezone: str | None = None, watch_ur + (", ".join(k for k, v in (("watch_url", watch_url), ("name", name), ("read_token", read_token)) if v) or "none of them")) zone = set_zone(timezone) if timezone is not None else os.environ.get("TZ") or "UTC" - kept = _config() - env_time = kept.get("env_time") is True and (kept.get("watch_url"), kept.get("name")) == (watch_url, name) - written = write_config(watch_url, name, read_token, zone, env_time) + written = write_config(watch_url, name, read_token, zone) shown = await follower.following("this agent's clock follower", follower.CONNECT_WAIT_S, url=watch_url, name=name, since_ns=written) return {"synced": True, "timezone": zone, "env_get_time_url": env_get_time_url, "follower": shown} - - -async def use_env_time() -> dict: - """``clock/v1``'s ``use_env_time`` on an agent, the opt-in: the follower ``sync_time`` configured arms the page as - the gateway's clock is, so every program this server starts reads the env's time; an answer once the follower - shows that config. Refused before ``sync_time``. An image whose follower predates ``env_time`` arms it from - ``sync_time`` on.""" - if not follows(): - raise TargetUnavailable("this agent's image doesn't run the clock follower") - config = _config() - if not all(isinstance(config.get(key), str) and config[key] for key in ("watch_url", "name", "token")): - raise InvalidArgument("use_env_time follows sync_time, which configures the follower it arms; none has") - written = write_config(config["watch_url"], config["name"], config["token"], config.get("timezone"), True) - shown = await follower.following("this agent's clock follower", follower.CONNECT_WAIT_S, url=config["watch_url"], - name=config["name"], since_ns=written) - return {"env_time": True, "follower": shown} diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py index c69f0ebfc..8de0a8f16 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py @@ -1456,9 +1456,8 @@ def _configure_trajectory( CLOCK_V1 = ExtensionDefinition( uri="urn:agentenv:clock/v1", description=( - "Follow the env's clock: the agent's image runs the clock follower, which sync_time configures; " - "use_env_time, the opt-in, then has every program the agent starts read the env's time. Served where the " - "image has the follower." + "Follow the env's clock: the agent's image runs the clock follower, so every program the agent runs reads " + "the env's time. Served where the image has the follower." ), endpoint="/ext/clock", core_operations={ @@ -1471,20 +1470,6 @@ def _configure_trajectory( response_required=("synced", "timezone", "follower"), ), }, - # Optional, so an agent that serves its own sync_time needn't serve it; the SDK's clock turns it on. - optional_features={ - "env_time": OperationGroup( - { - "use_env_time": _op( - "use_env_time", - "POST", - "/ext/clock/use-env-time", - SDK, - response_required=("env_time", "follower"), - ) - } - ) - }, ) INSTALL_V1 = ExtensionDefinition( diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index 89bf34067..63f954de7 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -81,7 +81,7 @@ from . import clock as agent_clock from .control_token import REFUSAL, carries_control_token, log_guard, log_refusal, take_control_token from .peer_agents import PEER_MCP_PATH, PEER_MCP_SERVER_NAME, PeerAgents -from .registry import RegisteredOperation, _discover_bindings, build_registry +from .registry import RegisteredOperation, build_registry from .staging import STAGING_ENDPOINT, StagingStore, staging_routes from .tasks.v1 import ( AgentConfig, @@ -686,7 +686,6 @@ def handlers(self) -> dict[tuple[str, str], Callable]: (TRIGGERS_V1.uri, "decide"): self.triggers_decide, (TRIGGERS_V1.uri, "state"): self.triggers_state, (CLOCK_V1.uri, "sync_time"): self.clock_sync_time, - (CLOCK_V1.uri, "use_env_time"): self.clock_use_env_time, } async def agent_config_set(self, request: AgentConfig) -> dict[str, Any]: @@ -1034,36 +1033,15 @@ async def clock_sync_time(self, request: ClockSyncTimeRequest) -> dict[str, Any] except ComputerError as exc: raise HTTPException(status_code=exc.STATUS, detail=f"{exc.CODE}: {exc}") from exc - async def clock_use_env_time(self) -> dict[str, Any]: - try: - return await agent_clock.use_env_time() - except ComputerError as exc: - raise HTTPException(status_code=exc.STATUS, detail=f"{exc.CODE}: {exc}") from exc - -def _with_clock(definition: _AgentDefinition, agent: Any = None) -> _AgentDefinition: - """``definition`` serving clock/v1, its opt-in ``use_env_time`` (feature ``env_time``) included, where the agent's - image runs the clock follower, so every agent in such an image can follow the env's clock with no code of its own, - and takes back the task's zone if it restarted mid-run. An agent that declares clock/v1 itself and leaves its - operations to the SDK gets ``use_env_time`` too, as the SDK's ``sync_time`` keeps real time until it; one that - serves an operation of its own keeps its declaration as it is. Unchanged where the image has no follower.""" - if not agent_clock.follows(): - return definition - declared = next((a for a in definition.extensions if a.definition.uri == CLOCK_V1.uri), None) - if declared is not None: - own = agent is not None and any(binding.extension.uri == CLOCK_V1.uri - for binding, _ in _discover_bindings(agent)) - if own or "env_time" in declared.features: - return definition - agent_clock.restore_zone() - opted = dataclasses.replace(declared, features=declared.features | {"env_time"}) - return dataclasses.replace(definition, extensions=tuple(opted if a is declared else a - for a in definition.extensions)) - if agent is not None and any(binding.extension.uri == CLOCK_V1.uri for binding, _ in _discover_bindings(agent)): +def _with_clock(definition: _AgentDefinition) -> _AgentDefinition: + """``definition`` serving clock/v1 where the agent's image runs the clock follower, so every agent in such an + image follows the env's clock with no code of its own, and takes back the task's zone if it restarted mid-run; + unchanged elsewhere, or where the agent declares it.""" + if not agent_clock.follows() or any(a.definition.uri == CLOCK_V1.uri for a in definition.extensions): return definition agent_clock.restore_zone() # a server restarted mid-run takes back the task's zone - return dataclasses.replace(definition, extensions=(*definition.extensions, - ExtensionActivation(CLOCK_V1, features=frozenset({"env_time"})))) + return dataclasses.replace(definition, extensions=(*definition.extensions, ExtensionActivation(CLOCK_V1))) class DefaultExtensionHandlers: @@ -1179,7 +1157,7 @@ def __init__(self, agent: Any, definition: _AgentDefinition | None = None) -> No "agent instance is already bound to an application; create a new " "agent instance for each application" ) - definition = _with_clock(definition, agent) + definition = _with_clock(definition) self.agent = agent self.definition = definition self.rpc_path = _rpc_path(definition.identity.url) diff --git a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py index df0e4ed55..492800497 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py @@ -1,7 +1,6 @@ """An agent's side of clock/v1: in an image that runs the clock follower, every AgentEnvAgent serves sync_time with no -code of its own; called by sync_env_clock, it writes the follower's config from the request, on real time, sets the -task's zone for what the server starts, and answers once the follower shows the gateway's current version, or says why -it doesn't; use_env_time, the opt-in, then has the follower arm the page as the gateway's clock is.""" +code of its own; called by sync_env_clock, it writes the follower's config from the request, sets the task's zone for +what the server starts, and answers once the follower shows the gateway's current version, or says why it doesn't.""" from __future__ import annotations import json @@ -21,8 +20,6 @@ TaskResult, a2a_agent, ) -from agentenv_protocol.a2a_agent import extension -from agentenv_protocol.a2a_agent.extensions import ClockSyncTimeRequest from agentenv_protocol.computer import clock as follower REQUEST = {"env_get_time_url": "http://gw/clock/time", "watch_url": "http://gw/clock/watch", "name": "agent-solver", @@ -118,7 +115,7 @@ def test_sync_time_writes_the_followers_config_sets_the_zone_and_answers_once_it "armed": True}} config = image / "follower.json" assert json.loads(config.read_text()) == {"watch_url": "http://gw/clock/watch", "name": "agent-solver", - "token": "token", "timezone": "America/Chicago", "env_time": False} + "token": "token", "timezone": "America/Chicago"} assert stat.S_IMODE(config.stat().st_mode) == 0o640 assert os.environ["TZ"] == "America/Chicago" and time.strftime("%Z") in {"CST", "CDT"} assert [p.name for p in image.iterdir() if p.name.startswith("follower.json.")] == [] @@ -185,97 +182,6 @@ def test_a_server_restarted_mid_run_takes_back_the_tasks_zone(image, monkeypatch assert os.environ["TZ"] == "America/Chicago" and time.strftime("%Z") in {"CST", "CDT"} -def _synced(image, client, request=REQUEST) -> None: - _follows_the_next_config(image, connected=True, url=request["watch_url"], name=request["name"], version="b:3") - assert client.post("/ext/clock/sync-time", json=request).status_code == 200 - - -def _env_time(image): - return json.loads((image / "follower.json").read_text())["env_time"] - - -def test_the_card_serves_use_env_time_beside_sync_time(image): - with _app() as client: - methods = _clock(client)["params"]["methods"] - - assert set(methods) == {"sync_time", "use_env_time"} - assert methods["use_env_time"]["method"] == "POST" - - -def test_an_agent_that_serves_its_own_sync_time_still_starts_without_use_env_time(image): - @a2a_agent(identity=AgentIdentity(name="own-clock", description="test", version="1"), extensions=(CLOCK_V1,)) - class Agent(AgentEnvAgent): - async def run(self, request: TaskRequest) -> TaskResult: - return TaskResult.text("ok") - - @extension(CLOCK_V1.sync_time) - async def sync_time(self, request: ClockSyncTimeRequest) -> dict: - return {"synced": True, "timezone": "UTC", "follower": {}} - - with TestClient(Agent().create_app()) as client: - assert set(_clock(client)["params"]["methods"]) == {"sync_time"} - assert client.post("/ext/clock/use-env-time").status_code == 404 - - -def test_an_agent_that_declares_the_clock_and_leaves_it_to_the_sdk_serves_use_env_time_too(image): - """Its sync_time is the SDK's, which keeps real time until use_env_time, so it must serve that too.""" - with _app(extensions=(CLOCK_V1,)) as client: - assert set(_clock(client)["params"]["methods"]) == {"sync_time", "use_env_time"} - _synced(image, client) - _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") - assert client.post("/ext/clock/use-env-time").status_code == 200 - - assert _env_time(image) is True - - -def test_sync_time_alone_has_the_follower_follow_on_real_time(image): - with _app() as client: - _synced(image, client) - - assert _env_time(image) is False - - -def test_use_env_time_has_the_follower_arm_the_page_and_answers_once_it_shows_that_config(image): - with _app() as client: - _synced(image, client) - _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", - version="b:3", armed=True) - answer = client.post("/ext/clock/use-env-time") - - assert answer.status_code == 200, answer.text - assert answer.json() == {"env_time": True, "follower": {"name": "agent-solver", "url": "http://gw/clock/watch", - "version": "b:3", "armed": True}} - assert json.loads((image / "follower.json").read_text()) == { - "watch_url": "http://gw/clock/watch", "name": "agent-solver", "token": "token", "timezone": "UTC", - "env_time": True} - - -def test_sync_time_again_keeps_env_time_for_the_same_gateway_and_name_and_not_for_another(image): - with _app() as client: - _synced(image, client) - _follows_the_next_config(image, connected=True, url="http://gw/clock/watch", name="agent-solver", version="b:3") - assert client.post("/ext/clock/use-env-time").status_code == 200 - _synced(image, client, {**REQUEST, "read_token": "another-token"}) - assert _env_time(image) is True - _synced(image, client, {**REQUEST, "watch_url": "http://other-gw/clock/watch"}) - - assert _env_time(image) is False - - -def test_use_env_time_before_sync_time_is_refused_and_writes_nothing(image): - with _app() as client: - answer = client.post("/ext/clock/use-env-time") - - assert answer.status_code == 400 and "sync_time" in answer.text - assert not (image / "follower.json").exists() - - -def test_use_env_time_takes_no_request_fields(image): - with _app() as client: - _synced(image, client) - assert client.post("/ext/clock/use-env-time", json={"x": 1}).status_code == 400 - - @pytest.mark.parametrize("config", ['{"watch_url": "u", "name": "n", "token": "t"}', '{"timezone": "Mars/Olympus"}', "not json", None]) def test_a_server_starting_without_a_saved_zone_keeps_its_own(image, monkeypatch, config): diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index 2d33b6f37..59c844fdb 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -55,13 +55,6 @@ def _sync_time(agent: DeployedAgent) -> tuple[Optional[dict], Optional[str]]: return A2AAgent.operation(A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI), "sync_time") -def _use_env_time(agent: DeployedAgent) -> Optional[str]: - """The path of the agent's clock/v1 ``use_env_time``, the opt-in that has what it starts read the env's time; None - for an image from before it, which has every program read it from boot.""" - method, path = A2AAgent.operation(A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI), "use_env_time") - return path if method is not None else None - - def _fields(method: dict) -> set[str]: request = method.get("request") or {} return {*request.get("required", ()), *request.get("optional", ()), *(request.get("properties") or {})} @@ -77,8 +70,7 @@ def watch_url_for(agent: DeployedAgent, env: DeployedEnv) -> str: async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Optional[str], timezone: Optional[str], timeout: float) -> dict: - """Have ``agent`` follow ``env``'s gateway clock: its ``sync_time``, then its ``use_env_time`` where its card serves - one, so what it starts reads the env's time. ``{"synced": False, "reason": ...}`` for an agent that can't: + """Have ``agent`` follow ``env``'s gateway clock. ``{"synced": False, "reason": ...}`` for an agent that can't: its card serves no ``sync_time`` (``not_advertised``) or one without the follower's fields (``no_follower_fields``), or the gateway takes no followers after it starts (``gateway_takes_no_followers``); raises for one that serves it and fails, having retired the follower it declared, or can't take the task's zone, as for @@ -99,23 +91,16 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op return {"synced": False, "reason": "gateway_takes_no_followers"} body = {"env_get_time_url": env_get_time_url or "", "watch_url": watch_url_for(agent, env), "name": name, "read_token": token, **({"timezone": timezone} if timezone is not None else {})} - base = (agent.a2a_url or agent.api_url).rstrip("/") - opt_in = _use_env_time(agent) + url = (agent.a2a_url or agent.api_url).rstrip("/") + path try: async with httpx.AsyncClient() as client: - answer = await client.post(base + path, json=body, timeout=timeout, - headers={**sandbox_request_headers_for_url(base + path), **agent.control_headers}) - if answer.status_code < 400 and opt_in is not None: - using = await client.post(base + opt_in, timeout=timeout, - headers={**sandbox_request_headers_for_url(base + opt_in), **agent.control_headers}) - if using.status_code >= 400: - answer = using + answer = await client.post(url, json=body, timeout=timeout, + headers={**sandbox_request_headers_for_url(url), **agent.control_headers}) except httpx.HTTPError as e: why = f"({type(e).__name__}): {e}" else: if answer.status_code < 400: - return {"synced": True, "follower": name, "result": answer.json(), - **({"env_time": using.json()} if opt_in is not None else {})} + return {"synced": True, "follower": name, "result": answer.json()} why = f"(HTTP {answer.status_code}): {answer.text}" # Declared and not following: the gateway would wait for it on every later write, and nothing records it to retire. await _retire(env, name, timeout=RETIRE_TIMEOUT_S) diff --git a/src/agent_env/agents/README.md b/src/agent_env/agents/README.md index 5cf30c22a..75e3cb990 100644 --- a/src/agent_env/agents/README.md +++ b/src/agent_env/agents/README.md @@ -44,14 +44,11 @@ The A2A server starts with the real-time marker, so it and its records stay on r `sync_env_clock` with `agent_clock` (off by default; `require_agent_clock` implies it) has armed the clock, it declares the agent at the gateway as a follower with a read token of its own and calls that `sync_time` with the follower's config, which the server writes; `deploy_agent` does the same for an agent it deploys while that clock is armed. -Without it the agent's CLI runs on real time, as its files' modification times are: a CLI that judges a file's age by -them, as Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the env's date is -ahead. After `sync_time`, which has the follower follow the gateway with -`env_time` off, so it acknowledges each version while the page stays real time, core calls clock/v1's `use_env_time`, -the agent's opt-in, where its card serves it: the follower then arms the page as the gateway's clock is. libfaketime is -preloaded for the agent's user either way and reads real time from an unarmed page. From then on the CLI, its own -"Today's date is" line included, and every command the model runs read the env's time, and a clock write that waits for -followers waits for the agent. While the clock is armed the CLI goes out through the egress proxy, which keeps TLS +From then on the CLI, its own "Today's date is" line included, and every command the model runs read the env's time, +and a clock write that waits for followers waits for the agent. Without `agent_clock` the agent keeps real time, as its +files' modification times do, and reads the env's time only from the gateway's `get_time`: a CLI that judges a file's +age by those times, as Claude Code's transcript cleanup does, would otherwise take a fresh file for one as old as the +env's date is ahead. While the clock is armed the CLI goes out through the egress proxy, which keeps TLS working at any date the clock shows, a live site's, an env MCP server's or the model endpoint's; only loopback hosts (the peer-agents MCP server's), `host.docker.internal`, the hosts the agent's `NO_PROXY` names and the hosts it reaches by plain HTTP alone, which have no certificate to check, go direct. `NO_PROXY` goes by host, not scheme, so a host the diff --git a/src/agent_env/utils/faketime_clock/clock-follower b/src/agent_env/utils/faketime_clock/clock-follower index f046176b4..fee4586b7 100755 --- a/src/agent_env/utils/faketime_clock/clock-follower +++ b/src/agent_env/utils/faketime_clock/clock-follower @@ -7,9 +7,7 @@ neither write it nor stop it. Core writes its config, the gateway's watch URL as this computer reaches it, the computer's name and its read token, through the sandbox's root channel (``CONFIG``, readable by root and this user alone); never through the driver, which runs as the session user. It reads the config every quarter second, during a watch too, and follows a changed one at -once. Until there is one, the clock stays as root made it at boot: real time. A config with ``env_time`` false, as an -agent's is until it opts in (clock/v1 ``use_env_time``), is followed and acknowledged as any other while the page -stays real time; a computer's names none and is armed as the gateway is. It reports how it's doing in ``STATUS``, +once. Until there is one, the clock stays as root made it at boot: real time. It reports how it's doing in ``STATUS``, which anyone may read and which holds no token: the gateway it follows, whether it's connected, the version it shows, or its last error. @@ -118,12 +116,10 @@ class Follower: def __init__(self, raw: bytes, config: dict): self.raw, self.url, self.name, self.token = raw, config["watch_url"], config["name"], config["token"] - # Whether the page follows the gateway's clock or stays real time while the follower acknowledges it. - self.env_time = config.get("env_time", True) is not False self.after, self.samples, self.written = "", [], None self.errors, self.backoff = 0, RETRY_FIRST_S self.status = {"url": self.url, "name": self.name, "connected": False, "version": None, "armed": False, - "env_time": self.env_time, "error": None} + "error": None} def report(self, **fields) -> None: self.status.update(fields) @@ -175,7 +171,7 @@ class Follower: self.samples = (self.samples + [{"delay": max(0.0, (t4 - t1) - held), "theta": ((body["received"] - t1) + (body["sent"] - t4)) / 2}])[-SAMPLES:] theta, dropped = offset(self.samples) - armed, universe, rate, anchor = state_of(body if self.env_time else {}, theta) + armed, universe, rate, anchor = state_of(body, theta) meaning = (armed, rate, universe - rate * anchor if armed else 0.0) changed = body["version"] != self.after moved = (self.written is None or meaning[:2] != self.written[:2] diff --git a/tst/unit/env/envs/test_computer_clock_follower.py b/tst/unit/env/envs/test_computer_clock_follower.py index 47a8ffd96..9f57d3f2d 100644 --- a/tst/unit/env/envs/test_computer_clock_follower.py +++ b/tst/unit/env/envs/test_computer_clock_follower.py @@ -167,27 +167,6 @@ def test_it_follows_the_gateway_its_config_names_and_acknowledges_each_version_w gateway.close() -def test_a_config_without_env_time_is_acknowledged_on_real_time_until_it_opts_in(follower): - """An agent's config names env_time false until clock/v1 use_env_time: the follower acknowledges the gateway's - versions, so clock writes can wait for it, while every program keeps real time.""" - gateway = Gateway() - try: - gateway.set("boot:1", datetime(2020, 1, 1, tzinfo=timezone.utc), 1.0) - config = {"watch_url": gateway.url, "name": "agent-solver", "token": "t"} - follower.configure({**config, "env_time": False}) - - status = follower.until(lambda: (s := follower.status()).get("version") == "boot:1" and s) - assert (status["armed"], status["env_time"]) == (False, False) - assert abs(follower.universe() - time.time()) < 2 - follower.until(lambda: ("boot:1", "agent-solver", "Bearer t") in gateway.watches) - - follower.configure({**config, "env_time": True}) - follower.until(lambda: follower.status().get("env_time") is True and follower.status().get("armed")) - assert abs(follower.universe() - datetime(2020, 1, 1, tzinfo=timezone.utc).timestamp()) < 2 - finally: - gateway.close() - - def test_a_changed_config_is_followed_at_once_during_a_held_watch(follower): first, second = Gateway(hold=30), Gateway(hold=30) try: diff --git a/tst/unit/task_step/agent_clock_test.py b/tst/unit/task_step/agent_clock_test.py index bedd460c2..a5b92f2c6 100644 --- a/tst/unit/task_step/agent_clock_test.py +++ b/tst/unit/task_step/agent_clock_test.py @@ -21,7 +21,6 @@ AGENT_CONTROL_TOKEN = "the-agents-control-token" SYNC_TIME = {"method": "POST", "endpoint": "/ext/clock/sync-time", "request": {"required": ["env_get_time_url"], "optional": ["timezone", "watch_url", "name", "read_token"]}} -USE_ENV_TIME = {"method": "POST", "endpoint": "/ext/clock/use-env-time"} def _step(**kw) -> SyncEnvClockTaskStep: @@ -29,9 +28,8 @@ def _step(**kw) -> SyncEnvClockTaskStep: return _sync_step(**{"agent_clock": True, **kw}) -def _agent(name="solver", sync_time=SYNC_TIME, env_ids=("e1",), env_step_id=None, use_env_time=None) -> DeployedAgent: - methods = {"sync_time": sync_time, **({"use_env_time": use_env_time} if use_env_time else {})} - extensions = [{"uri": EXT_CLOCK_URI, "params": {"endpoint": "/ext/clock", "methods": methods}}] +def _agent(name="solver", sync_time=SYNC_TIME, env_ids=("e1",), env_step_id=None) -> DeployedAgent: + extensions = [{"uri": EXT_CLOCK_URI, "params": {"endpoint": "/ext/clock", "methods": {"sync_time": sync_time}}}] return DeployedAgent(agent_name=name, api_url=AGENT_URL, a2a_url=AGENT_URL, env_ids=list(env_ids), env_bindings={env_id: env_step_id for env_id in env_ids} if env_step_id else {}, a2a_card={"capabilities": {"extensions": extensions if sync_time else []}}, @@ -70,44 +68,6 @@ async def test_an_agent_is_declared_a_follower_then_handed_its_config_with_the_s assert (agent["agent"], agent["synced"], agent["follower"]) == ("solver", True, "agent-solver") -@pytest.mark.asyncio -async def test_an_agent_whose_card_serves_use_env_time_is_opted_in_after_sync_time(monkeypatch): - sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) - _no_servers(monkeypatch) - context = await _context(_agent(use_env_time=USE_ENV_TIME)) - - await _step().execute(context) - - assert [(r.method, "/" + "/".join(r.url.path.split("/")[-2:])) for r in sent][3:] == [ - ("PUT", "/clock/followers"), ("POST", "/clock/sync-time"), ("POST", "/clock/use-env-time")] - assert sent[-1].headers[CONTROL_TOKEN_HEADER] == AGENT_CONTROL_TOKEN and sent[-1].content == b"" - [agent] = context.metadata["clock_configurations"][0]["agents"] - assert agent["synced"] is True and "env_time" in agent - - -@pytest.mark.asyncio -async def test_a_use_env_time_that_fails_fails_the_step_and_its_follower_is_retired(monkeypatch): - import httpx - - real, sent = httpx.AsyncClient, [] - - def handle(request: httpx.Request) -> httpx.Response: - sent.append((request.method, request.url.path)) - if request.url.path == "/ext/clock/use-env-time": - return httpx.Response(400, json={"detail": "invalid_argument: no config"}) - return httpx.Response(200, json={"env_get_time_url": CLOCK_URL} if request.url.path.endswith("/state") else {}) - - monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **k: real(transport=httpx.MockTransport(handle))) - _no_servers(monkeypatch) - context = await _context(_agent(use_env_time=USE_ENV_TIME)) - - with pytest.raises(RuntimeError, match="agent 'solver' doesn't follow the clock of env 'e1' \\(HTTP 400\\): .*no config"): - await _step().execute(context) - - assert [(m, "/" + "/".join(p.split("/")[-2:])) for m, p in sent[-2:]] == [ - ("POST", "/clock/use-env-time"), ("DELETE", "/clock/followers")] - - @pytest.mark.asyncio async def test_only_the_agents_registered_with_the_env_follow_its_clock(monkeypatch): sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL})