Skip to content
Open
Original file line number Diff line number Diff line change
@@ -1,6 +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
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.
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
Expand Down Expand Up @@ -28,15 +30,23 @@ def follows() -> bool:
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
Expand Down Expand Up @@ -86,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():
Expand All @@ -97,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)
Comment thread
williamloo-scale marked this conversation as resolved.
Resolved
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}
Original file line number Diff line number Diff line change
Expand Up @@ -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={
Expand All @@ -1470,6 +1471,20 @@ 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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -1033,15 +1034,36 @@ 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) -> _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, ExtensionActivation(CLOCK_V1)))
return dataclasses.replace(definition, extensions=(*definition.extensions,
ExtensionActivation(CLOCK_V1, features=frozenset({"env_time"}))))


class DefaultExtensionHandlers:
Expand Down Expand Up @@ -1157,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)
Expand Down
100 changes: 97 additions & 3 deletions packages/agentenv-protocol/tests/test_a2a_agent_clock.py
Original file line number Diff line number Diff line change
@@ -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, 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
Expand All @@ -20,6 +21,8 @@
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",
Expand Down Expand Up @@ -115,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.")] == []
Expand Down Expand Up @@ -182,6 +185,97 @@ 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):
Expand Down
Loading
Loading