Skip to content
Open
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
0c8351c
fix(clock): the env clock follows any date to 9999, past 2262
earakely-scale Nov 23, 2026
651121d
fix(computers): an absolute realtime deadline before 1970 follows the…
earakely-scale Nov 23, 2026
9fb87bb
fix(clock): limit the env clock to 1677-09-21..2262-04-11, the times …
earakely-scale Nov 23, 2026
cb96982
fix(computers): exact deadlines and saturating universe arithmetic at…
earakely-scale Nov 23, 2026
cad7317
fix(clock): a clock that outlives its range stands at its end, and ev…
earakely-scale Nov 23, 2026
ffec8b6
test(clock): a periodic timer armed on a frozen clock ticks every sec…
earakely-scale Nov 23, 2026
bbe3e05
fix(clock): a clock frozen in its last real hour starts again, and li…
earakely-scale Nov 24, 2026
9dc3a3c
fix(clock): periodic timers stop at the end of the range when the clo…
earakely-scale Nov 24, 2026
0d6ebf9
test(clock): the end-periodic gate reads its timer as it ticks, as a …
earakely-scale Nov 24, 2026
d152406
docs(clock): say why stopping a periodic timer at the end drops its u…
earakely-scale Nov 24, 2026
811274d
refactor(clock): a follower that holds only a range of times declares…
earakely-scale Nov 24, 2026
ceea964
fix(clock): a follower's range refusals say what they refuse, and a b…
earakely-scale Nov 24, 2026
eeb111a
fix(clock): a clock that runs to the end of a follower's range stands…
earakely-scale Nov 24, 2026
ed0240a
test(clock): integration tests pin a computer's refusal past its rang…
earakely-scale Nov 24, 2026
3cc0d61
fix(clock): a clock that runs to the end of a follower's range stops …
earakely-scale Nov 24, 2026
3941a67
fix(clock): each clock operation reads real time once, so a reading a…
earakely-scale Nov 24, 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: 1 addition & 1 deletion AGENTS.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
TriggerRegisterRequest,
enable,
)
from ..computer.clock import RANGE as CLOCK_RANGE
from ..computer.errors import ComputerError
from ..errors import AgentEnvError
from ..types import error_body
Expand Down Expand Up @@ -1080,7 +1081,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_zone() # a server restarted mid-run takes back the task's zone
return dataclasses.replace(definition, extensions=(*definition.extensions, ExtensionActivation(CLOCK_V1)))
clock = ExtensionActivation(CLOCK_V1, wire_params={"range": dict(CLOCK_RANGE)})
return dataclasses.replace(definition, extensions=(*definition.extensions, clock))


class DefaultExtensionHandlers:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,14 @@ def __init__(self, response: httpx.Response) -> None:


def _error_fields(response: httpx.Response) -> dict:
"""The error object the body carries; an error that is a bare string, as an env gateway's own routes send, is its
message."""
try:
body = response.json()
except ValueError:
return {}
error = body.get("error") if isinstance(body, dict) else None
return error if isinstance(error, dict) else {}
return error if isinstance(error, dict) else {"message": error} if isinstance(error, str) else {}


def control_headers(token: str | None) -> dict[str, str]:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ def served_extensions(driver: ComputerDriverEnvironment,
continue
if extension.uri == COMPUTER_RECORDING and driver.recording is None:
continue
if extension.uri == clock.CLOCK and not clock.follows():
continue
if extension.uri == clock.CLOCK:
if not clock.follows():
continue
extension = extension.model_copy(update={"params": {**extension.params, "range": dict(clock.RANGE)}})
dropped = {op for (uri, op), need in _METHOD_NEEDS.items() if uri == extension.uri and not driver.has(need)}
if dropped:
methods = {op: entry for op, entry in extension.params["methods"].items() if op not in dropped}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@
#: The follower's clock file, replaced whole at each write: ``@<universe s> x<rate> ^<anchor s>`` while the clock is
#: armed (the universe at real time ``anchor``, running at ``rate``), ``+0 x1`` on real time.
CLOCK_FILE = "/run/agentenv-clock/clock"
#: The times a computer's and a clock-following agent's session programs hold: what 64 bits of nanoseconds since 1970
#: hold, as the clock page and Python keep time (outside them ``time.time()`` raises). Their cards declare it as clock/v1's
#: ``range``, and a gateway refuses to take its clock outside the range of a follower it has.
RANGE = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"}
#: The end of that range in epoch seconds: a clock that runs to it stands there, as the computers' do, before the follower
#: writes it standing.
END = 9223372036.0
#: What a disk form's guest has, made from the computer's container image: core's root channel reaches its launcher,
#: not the guest, so it can't configure a follower there, and a disk computer stays on real time for now.
DISK_GUEST = "/etc/agentenv/vm/image.env"
Expand All @@ -53,7 +60,7 @@ def session_time() -> float:
if not spec[0].startswith("@"):
return now
universe, rate, anchor = float(spec[0][1:]), float(spec[1][1:]), float(spec[2][1:])
return universe if rate == 0 or now <= anchor else universe + (now - anchor) * rate
return universe if rate == 0 or now <= anchor else min(universe + (now - anchor) * rate, END)


def session_zone() -> str:
Expand Down
2 changes: 2 additions & 0 deletions packages/agentenv-protocol/tests/test_a2a_agent_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ def test_every_agent_in_an_image_with_the_follower_serves_sync_time(image):
assert served is not None
request = served["params"]["methods"]["sync_time"]["request"]
assert request == {"required": ["env_get_time_url"], "optional": ["timezone", "watch_url", "name", "read_token"]}
assert served["params"]["range"] == {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"}


def test_an_agent_in_an_image_without_the_follower_serves_no_clock(image, monkeypatch):
Expand Down Expand Up @@ -198,6 +199,7 @@ def test_a_server_starting_without_a_saved_zone_keeps_its_own(image, monkeypatch
("@1748768400.000000000 x2 ^{past}\n", 1748768400.0 + 20),
("@1748768400.000000000 x1 ^{future}\n", 1748768400.0),
("@1748768400.000000000 x0 ^{past}\n", 1748768400.0),
("@9223372030.000000000 x1 ^{past}\n", 9223372036.0),
])
def test_the_session_time_is_the_universe_while_the_clock_is_armed_and_real_time_otherwise(
tmp_path, monkeypatch, spec, expected):
Expand Down
3 changes: 3 additions & 0 deletions packages/agentenv-protocol/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,9 @@ def _error_response(status: int, **kwargs) -> httpx.Response:
# A server from before the structured fields: its code, and nothing claimed about the effect.
(_error_response(500, json={"ok": False, "error": {"code": "extension_failed", "message": "kaboom"}}),
("extension_failed", "kaboom", False, "unknown", None)),
# A route whose error is a bare string, as an env gateway's clock refusals are: it is the message.
(_error_response(400, json={"ok": False, "error": "virtual_time '3026-01-01T00:00:00Z' is outside the range"}),
(None, "virtual_time '3026-01-01T00:00:00Z' is outside the range", False, "unknown", None)),
# A proxy's own error page.
(_error_response(502, text="<html>Bad Gateway</html>"), (None, "Bad Gateway", False, "unknown", None)),
(_error_response(404, json=["not", "an", "object"]), (None, "Not Found", False, "unknown", None)),
Expand Down
1 change: 1 addition & 0 deletions packages/agentenv-protocol/tests/test_computer_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ async def test_the_card_serves_sync_time_where_the_base_runs_the_follower_and_it

assert set(served["params"]["methods"]) == {"sync_time"}
assert set(served["params"]["methods"]["sync_time"]["request"]["properties"]) == {"env_get_time_url", "timezone"}
assert served["params"]["range"] == {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"}
assert on_a_disk is None and await _clock_extension(FakeDriver()) is None


Expand Down
32 changes: 29 additions & 3 deletions src/agent_env/a2a_agent/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@

import httpx

from agentenv_protocol.client import ExtensionCallError

from agent_env.a2a_agent.a2a_agent import A2AAgent
from agent_env.env.env import EnvCapabilityUnsupported, gateway_url_of
from agent_env.env.gateway.constants import CLOCK_WATCH_PATH, EXT_CLOCK_URI
from agent_env.env.gateway.clock import ClockError, FollowerRange, parse_follower_range
from agent_env.env.gateway.constants import CLOCK_OUTSIDE_RANGE, CLOCK_WATCH_PATH, EXT_CLOCK_URI
from agent_env.providers.sandbox_providers.local_docker.provider import host_url_for
from agent_env.providers.sandbox_providers.sandbox_provider import reachable_url, sandbox_request_headers_for_url
from agent_env.task_step.context import StepContextError
Expand Down Expand Up @@ -51,6 +54,20 @@ def follower_name(agent: DeployedAgent) -> str:
return f"agent-{agent.agent_name}"


def held_range(agent: DeployedAgent) -> Optional[FollowerRange]:
"""The times ``agent`` holds, when its card declares it holds only a range of them (clock/v1's ``range``); a card
from before it declares none, and one that doesn't parse is logged and left out, as if it declared none."""
held = (A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI) or {}).get("params", {}).get("range")
if held is None:
return None
try:
return parse_follower_range(held)
except ClockError as e:
logger.warning(f"agent '{agent.agent_name}': its card's clock/v1 range is left out, so the gateway's clock "
f"doesn't keep to it: {e}")
return None


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")

Expand All @@ -72,7 +89,9 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op
timezone: Optional[str], timeout: float) -> dict:
"""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
(``no_follower_fields``), the gateway takes no followers after it starts (``gateway_takes_no_followers``), or the
clock is outside the range of times the agent's card says it holds, or would run past its end from within a real
hour (``outside_range: <the gateway's refusal>``); raises
for one that serves it and fails, having retired the follower it declared, or can't take the task's zone, as for
a server."""
method, path = _sync_time(agent)
Expand All @@ -85,10 +104,17 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op
raise StepContextError(f"agent '{agent.agent_name}' serves {EXT_CLOCK_URI} sync_time without a timezone; "
f"rebuild its image or drop timezone={timezone!r} from the task")
name, token = follower_name(agent), secrets.token_urlsafe(READ_TOKEN_BYTES)
held = held_range(agent)
try:
await env.invoke(EXT_CLOCK_URI, "declare_follower", {"name": name, "read_token": token}, timeout=timeout)
await env.invoke(EXT_CLOCK_URI, "declare_follower",
{"name": name, "read_token": token, **({"range": held.as_dict()} if held else {})},
timeout=timeout)
except EnvCapabilityUnsupported:
return {"synced": False, "reason": "gateway_takes_no_followers"}
except ExtensionCallError as e:
if e.code != CLOCK_OUTSIDE_RANGE:
raise
return {"synced": False, "reason": f"outside_range: {e.detail}"}
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
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/env/envs/_multi_computers.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,8 @@ async def deploy(reach: Optional[str], control_token: Optional[str]) -> list[Ext
for error in failed[1:]:
logger.warning(f"multi env '{self._owner}': another computer failed to deploy too: {error!r}")
raise failed[0]
return [ExternalChild(env.environment_name, record.mcp_url, record.environment_url, _clock_read_token(record))
return [ExternalChild(env.environment_name, record.mcp_url, record.environment_url, _clock_read_token(record),
computer_clock.held_range(record))
for env, record in zip(self.every, results)]
return deploy

Expand Down
17 changes: 17 additions & 0 deletions src/agent_env/env/envs/computer/utils/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
from typing import TYPE_CHECKING, Optional

import httpx
from agentenv_protocol import client as protocol_v1
from agentenv_protocol.client import ExtensionCallError
from agentenv_protocol.computer.clock import CONFIG, FOLLOWER_USER

from agent_env.env.envs.computer.utils.sites import RootChannel
from agent_env.env.gateway.clock import ClockError, FollowerRange, parse_follower_range
from agent_env.env.gateway.constants import EXT_CLOCK_URI

if TYPE_CHECKING:
Expand All @@ -39,6 +41,21 @@ def follows(record: DeployedEnv) -> bool:
return record.supports(EXT_CLOCK_URI, "sync_time")


def held_range(record: DeployedEnv) -> Optional[FollowerRange]:
"""The times the computer ``record`` deployed holds, when its card declares it holds only a range of them
(clock/v1's ``range``, ``{"earliest": ..., "latest": ...}``); a card from before it declares none, and one that
doesn't parse, which would stop the gateway starting, is logged and left out, as if it declared none."""
held = protocol_v1.extension_params(record.environment_card or {}, EXT_CLOCK_URI).get("range")
if not follows(record) or held is None:
return None
try:
return parse_follower_range(held)
except ClockError as e:
logger.warning(f"{record.env_id}: its card's clock/v1 range is left out, so the gateway's clock doesn't keep to "
f"it: {e}")
return None


def recorded(record: DeployedEnv) -> Optional[dict]:
"""The follower's config ``record`` keeps, its token aside: the watch URL and the computer's name."""
clock = ((record.metadata or {}).get("computer") or {}).get("clock")
Expand Down
5 changes: 4 additions & 1 deletion src/agent_env/env/gateway/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from dataclasses import dataclass

from .clock import FollowerRange
from .constants import (
AGENT_ENV_HIDDEN_BY_DEFAULT_META_KEY,
AGENT_ENV_ROLE_HEADER,
Expand Down Expand Up @@ -31,12 +32,14 @@ class InternalMCPServer:
class ExternalChild:
"""A child env on a sandbox of its own, which the gateway fronts as it does an MCP server: its name, and its MCP
endpoint and base URL as the process holding it reaches them. A child that is a clock follower has the read token its
clock watch carries, and the gateway's clock writes wait for it."""
clock watch carries, and the gateway's clock writes wait for it; one that holds only a range of times has that range,
which the gateway's clock keeps to."""

name: str
mcp_url: str
base_url: str
clock_read_token: str | None = None
clock_range: FollowerRange | None = None


__all__ = [
Expand Down
Loading
Loading