Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
ae1d4be
feat(agents): agents follow the env's clock the way computers do (FD-…
williamloo-scale Nov 16, 2026
eea933c
refactor(agents): leave the Claude Code image to its own PR; agents s…
williamloo-scale Nov 17, 2026
608a93d
Merge origin/main
williamloo-scale Nov 17, 2026
bce00d4
fix(agents): agent clock review: new config's status, one clock per a…
williamloo-scale Nov 17, 2026
84381b8
fix(agents): keep each agent's clock record on a key of its own; a re…
williamloo-scale Nov 17, 2026
56dac45
fix(agents): agent clock keys can't collide; one clock env per agent;…
williamloo-scale Nov 17, 2026
c726743
chore: drop test run output committed by mistake
williamloo-scale Nov 17, 2026
cecc686
fix(agents): a failed agent sync retires its follower; the task's zon…
williamloo-scale Nov 17, 2026
afe55b4
Merge origin/main
williamloo-scale Nov 17, 2026
c8ed6e1
fix(agents): a later clock sync leaves agents teardown_sandboxes took…
williamloo-scale Nov 17, 2026
25af21a
chore: drop test-run output committed again, and ignore where the pro…
williamloo-scale Nov 17, 2026
f8bd9ff
feat(a2a-agent): validate clock/v1 by the time the agent's own comman…
earakely-scale Nov 17, 2026
f9af1b6
refactor(a2a-agent): name the clock validation's timeouts and error l…
williamloo-scale Nov 17, 2026
43fdb97
fix(gateway): get_time says the machine's clock may not be synchroniz…
earakely-scale Nov 18, 2026
8bf8e4c
refactor(a2a-agent): move agent_clock to a2a_agent/clock.py, beside t…
earakely-scale Nov 18, 2026
c5ef5a4
chore: re-run review now that #726 imports FOLLOWING_KEY from a2a_age…
earakely-scale Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ cython_debug/

# Generated local-store state (stores default local; see runtime._ensure_agentenv_gitignore)
/.agentenv/
# ...and what the protocol package's tests write when run from its own folder (launches, browser tab events)
/packages/agentenv-protocol/.agentenv/

# Written by the release workflow into the wheels it publishes
src/agent_env/env/published_images.json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
STANDARD_EXTENSIONS,
TRAJECTORY_V1,
TRIGGERS_V1,
CLOCK_V1,
AttributionProbeResponse,
BundleSkillRequest,
CdpAddRequest,
Expand Down Expand Up @@ -152,6 +153,7 @@
"STANDARD_EXTENSIONS",
"TRAJECTORY_V1",
"TRIGGERS_V1",
"CLOCK_V1",
"A2AAgentApplication",
"AgentCapabilities",
"AgentConfig",
Expand Down
102 changes: 102 additions & 0 deletions packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""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.

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
computer's, whose config core writes through the sandbox's root channel, an agent's request carries the follower's
config itself (``watch_url``, ``name``, ``read_token``), and this server, running as the agent's user, writes it: the
model's own commands could rewrite it and fool their own view of the time, though never the env's clock, and the token
only reads. It answers once the follower shows the gateway's current version, or says why it doesn't. The task's zone
is kept in the config beside what the follower reads, so a server restarted mid-run (``restore_zone``) brings the zone
back as the follower brings back the clock."""
from __future__ import annotations

import json
import os
import time
import uuid
from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

from ..computer import clock as follower
from ..computer.errors import InvalidArgument, TargetUnavailable


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
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()
try:
if path.read_bytes() == raw:
return 0
except OSError:
pass
staged = path.with_name(f"{path.name}.{uuid.uuid4().hex}")
fd = os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o640)
try:
with os.fdopen(fd, "wb") as f:
f.write(raw)
os.chmod(staged, 0o640)
os.replace(staged, path)
except BaseException:
staged.unlink(missing_ok=True)
raise
return path.stat().st_mtime_ns


def set_zone(timezone: str) -> str:
"""The task's zone for every program this server starts from now on: ``TZ`` in its environment, which a started
program inherits; this server's own records keep UTC timestamps either way."""
zone = timezone.strip()
try:
ZoneInfo(zone)
except (ZoneInfoNotFoundError, ValueError) as e:
raise InvalidArgument(f"timezone must be an IANA name such as 'America/Chicago', got {timezone!r}") from e
os.environ["TZ"] = zone

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

set_zone only changes this process's TZ. In an e2e run I killed the A2A server with kill -9 and supervisord restarted it. The clock kept following, since the follower reads its config from disk, but the zone was gone. The next turn's date printed +00:00 and TZ= instead of -05:00 and America/Chicago.

Could the zone be saved with the follower's config and re-applied when the server starts, so a restart brings back both?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cecc686. sync_time now saves the task's zone in the follower's config (timezone, which the follower ignores), and restore_zone runs when the A2A application is built on an image with the follower, so the server supervisord restarts takes the zone back. A missing, malformed or invalid saved zone leaves the server's own TZ. Tests: test_a_server_restarted_mid_run_takes_back_the_tasks_zone (sync with America/Chicago, reset TZ to UTC, start the app again, TZ is America/Chicago) and test_a_server_starting_without_a_saved_zone_keeps_its_own.

time.tzset()
return 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."""
try:
zone = json.loads(Path(follower.CONFIG).read_text()).get("timezone")
except (OSError, ValueError, AttributeError):
return None
if not isinstance(zone, str) or not zone:
return None
try:
return set_zone(zone)
except InvalidArgument:
return 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
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():
raise TargetUnavailable("this agent's image doesn't run the clock follower")
if not (watch_url and name and read_token):
raise InvalidArgument("an agent follows the clock with its watch_url, name and read_token, which "
"sync_env_clock sends; this request names "
+ (", ".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)
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}
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,18 @@ class BundleSkillRequest(ExtensionRequest):
skill_bundle: SkillBundle


class ClockSyncTimeRequest(ExtensionRequest):
"""clock/v1's ``sync_time`` on an agent: what every server's takes, ``env_get_time_url`` and ``timezone``, and the
config of the follower an agent runs itself, the gateway's watch URL as its sandbox reaches it, the name the
gateway knows it by and its read token."""

env_get_time_url: str
timezone: str | None = None
watch_url: str | None = None
name: str | None = None
read_token: str | None = None


class SkillAddResponse(ExtensionResponse):
name: str

Expand Down Expand Up @@ -1345,6 +1357,25 @@ def _configure_trajectory(*, live: bool = False) -> ExtensionConfiguration:
},
)

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."
),
endpoint="/ext/clock",
core_operations={
"sync_time": _op(
"sync_time",
"POST",
"/ext/clock/sync-time",
SDK,
request_model=ClockSyncTimeRequest,
response_required=("synced", "timezone", "follower"),
),
},
)

INSTALL_V1 = ExtensionDefinition(
uri="urn:agentenv:install/v1",
description="Declare commands for installing the agent into an existing target.",
Expand Down Expand Up @@ -1392,6 +1423,7 @@ def _configure_trajectory(*, live: bool = False) -> ExtensionConfiguration:
PEER_AGENTS_V1,
ATTRIBUTION_PROBE_V1,
TRIGGERS_V1,
CLOCK_V1,
INSTALL_V1,
PROXY_V1,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import asyncio
import dataclasses
import inspect
import json
import logging
Expand Down Expand Up @@ -39,6 +40,8 @@
SKILL_CONFIG_V1,
TRAJECTORY_V1,
TRIGGERS_V1,
CLOCK_V1,
ClockSyncTimeRequest,
ContextEventsTrajectoryRequest,
ContextObjectTrajectoryRequest,
ContextTrajectoryRequest,
Expand All @@ -59,6 +62,8 @@
TriggerRegisterRequest,
enable,
)
from ..computer.errors import ComputerError
from . import clock as agent_clock
from .peer_agents import PEER_MCP_PATH, PEER_MCP_SERVER_NAME, PeerAgents
from .registry import RegisteredOperation, build_registry
from .staging import STAGING_ENDPOINT, StagingStore, staging_routes
Expand Down Expand Up @@ -631,6 +636,7 @@ def handlers(self) -> dict[tuple[str, str], Callable]:
(TRIGGERS_V1.uri, "register"): self.triggers_register,
(TRIGGERS_V1.uri, "decide"): self.triggers_decide,
(TRIGGERS_V1.uri, "state"): self.triggers_state,
(CLOCK_V1.uri, "sync_time"): self.clock_sync_time,
}

async def agent_config_set(self, request: AgentConfig) -> dict[str, Any]:
Expand Down Expand Up @@ -876,6 +882,22 @@ async def triggers_decide(self, request: TriggerDecideRequest) -> dict[str, Any]
async def triggers_state(self) -> dict[str, Any]:
return self.trigger_engine.state()

async def clock_sync_time(self, request: ClockSyncTimeRequest) -> dict[str, Any]:
try:
return await agent_clock.sync_time(**request.model_dump())
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 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)))


class DefaultExtensionHandlers:
"""Stable access to default implementations of SDK-owned operations."""
Expand Down Expand Up @@ -968,6 +990,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)
self.agent = agent
self.definition = definition
self.rpc_path = _rpc_path(definition.identity.url)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,17 @@ def session_zone() -> str:


def follower_status() -> dict:
return _status_written()[0]


def _status_written() -> tuple[dict, int]:
"""The follower's status and when it wrote it (``st_mtime_ns``; 0 when there is none)."""
try:
status = json.loads(Path(STATUS).read_text())
path = Path(STATUS)
written, status = path.stat().st_mtime_ns, json.loads(path.read_text())
except (OSError, ValueError):
return {}
return status if isinstance(status, dict) else {}
return {}, 0
return (status, written) if isinstance(status, dict) else ({}, 0)


def gateway_version(watch_url: str) -> str:
Expand All @@ -60,7 +66,10 @@ def gateway_version(watch_url: str) -> str:
return json.loads(answer.read())["version"]


def _why(status: dict, current: Optional[str], unread: Optional[str]) -> str:
def _why(status: dict, current: Optional[str], unread: Optional[str], stale: bool = False) -> str:
if stale:
return (f"it still shows the config it had, the gateway at {status.get('url')} as {status.get('name')!r}, "
f"not the one just written")
if status.get("error"):
return f"it can't reach the gateway at {status.get('url')}: {status['error']}"
if not status.get("url"):
Expand All @@ -82,19 +91,35 @@ async def sync_time(env_get_time_url: str, timezone: Optional[str] = None) -> di
if timezone is not None and timezone.strip() != zone:
raise InvalidArgument(f"the task's clock is in {timezone.strip()!r} and this computer's session in {zone!r}; "
f"deploy it with computer_settings.timezone = {timezone.strip()!r}")
deadline = time.monotonic() + CONNECT_WAIT_S
follower = await following("this computer's clock follower")
return {"synced": True, "timezone": zone, "env_get_time_url": env_get_time_url, "follower": follower}


async def following(whose: str, wait_s: float = CONNECT_WAIT_S, *, url: Optional[str] = None,
name: Optional[str] = None, since_ns: int = 0) -> dict:
"""The follower's status once it shows the gateway's current version; TargetUnavailable saying why ``whose``
doesn't within ``wait_s``. A computer's ``sync_time`` and an agent's (``agentenv_protocol.a2a_agent.clock``) both answer
with it. An agent's, which has just written the follower's config, names it: only a status of that ``url`` and
``name`` the follower wrote since ``since_ns`` counts, so what it showed of a config before is never taken for
this one's."""
deadline = time.monotonic() + wait_s

def read() -> tuple[dict, bool]:
status, written = _status_written()
stale = bool(status) and (written < since_ns or (url is not None and status.get("url") != url)
or (name is not None and status.get("name") != name))
return status, stale

while True:
status, current, unread = follower_status(), None, None
if status.get("connected") and status.get("url"):
(status, stale), current, unread = read(), None, None
if not stale and status.get("connected") and status.get("url"):
try:
current = await asyncio.to_thread(gateway_version, status["url"])
except Exception as e: # noqa: BLE001 - away or answering something else: said as why, tried again
unread = f"{type(e).__name__}: {e}"[:300]
status = follower_status()
if current is not None and status.get("connected") and status.get("version") == current:
return {"synced": True, "timezone": zone, "env_get_time_url": env_get_time_url,
"follower": {key: status.get(key) for key in ("name", "url", "version", "armed")}}
status, stale = read()
if not stale and current is not None and status.get("connected") and status.get("version") == current:
return {key: status.get(key) for key in ("name", "url", "version", "armed")}
if time.monotonic() >= deadline:
raise TargetUnavailable("this computer's clock follower isn't following the gateway: "
+ _why(status, current, unread))
raise TargetUnavailable(f"{whose} isn't following the gateway: " + _why(status, current, unread, stale))
await asyncio.sleep(0.1)
Loading
Loading