Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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.

18 changes: 15 additions & 3 deletions src/agent_env/env/gateway/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ def __init__(self, now_fn=time.monotonic):
self._lock = threading.Lock()
self._armed = False
self._t0: datetime | None = None
self._time_zone: str | None = None # the universe's zone, its users', as the arm named it
self._anchor = now_fn() # real time the current arm (or unarmed stretch) began
self._rate = 1.0
self._generation = 0
Expand Down Expand Up @@ -181,10 +182,13 @@ def t0(self) -> datetime | None:
with self._lock:
return self._t0

def set_time(self, virtual_time: str, rate=1.0) -> dict:
"""Arm/re-arm: anchor t0=virtual_time to now, advancing at `rate` virtual s per real s."""
def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> dict:
"""Arm/re-arm: anchor t0=virtual_time to now, advancing at `rate` virtual s per real s, in the universe's
`time_zone` (its users' IANA zone), or none."""
t0 = _parse_rfc3339(virtual_time)
r = _parse_rate(1.0 if rate is None else rate)
if time_zone is not None and _zone(time_zone) is None:
raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'")
if t0 > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r):
raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would overflow datetime near the max")
with self._lock:
Expand All @@ -193,6 +197,7 @@ def set_time(self, virtual_time: str, rate=1.0) -> dict:
self._rate = r
self._ahead = 0.0
self._armed = True
self._time_zone = time_zone
self._generation += 1
self._count += 1
return self.state()
Expand Down Expand Up @@ -239,6 +244,7 @@ def clear(self) -> dict:
self._bank()
self._armed = False
self._t0 = None
self._time_zone = None
self._rate = 1.0
self._ahead = 0.0
self._generation += 1
Expand All @@ -257,6 +263,12 @@ def now(self) -> datetime | None:
elapsed = self._now() - self._anchor
return _advance(self._t0, elapsed * self._rate + self._ahead)

@property
def time_zone(self) -> str | None:
"""The universe's zone, its users', as the current arm named it; None unarmed or when it named none."""
with self._lock:
return self._time_zone if self._armed else None

def at_elapsed(self, elapsed: float) -> datetime | None:
"""The virtual time at which elapsed() reaches `elapsed` on the current arm; None while unarmed."""
with self._lock:
Expand All @@ -278,7 +290,7 @@ def state(self) -> dict:
elapsed = self._now() - self._anchor
return {"armed": True, "t0": _iso(self._t0), "virtual_seconds_per_real_second": self._rate,
"virtual_time": _iso(_advance(self._t0, elapsed * self._rate + self._ahead)),
"version": self.version}
**({"time_zone": self._time_zone} if self._time_zone else {}), "version": self.version}

def _bank(self, t0: datetime | None = None) -> None:
"""Fold the stretch since the last arm/clear into `_lived` at its rate, and start the next one now."""
Expand Down
2 changes: 1 addition & 1 deletion src/agent_env/env/gateway/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def random_mcp_server_name() -> str:
"description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.",
"params": {"endpoint": "/clock/time", "methods": {
"get_time": {"method": "GET", "endpoint": "/clock/time"},
"set_time": {"method": "PUT", "endpoint": "/clock/set-time", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, "virtual_seconds_per_real_second": {"type": "number"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}},
"set_time": {"method": "PUT", "endpoint": "/clock/set-time", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, "virtual_seconds_per_real_second": {"type": "number"}, "time_zone": {"type": "string"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}},
"set_rate": {"method": "PUT", "endpoint": "/clock/set-rate", "request": {"type": "object", "properties": {"virtual_seconds_per_real_second": {"type": "number", "minimum": 0}, **_WAIT_FOLLOWERS}, "required": ["virtual_seconds_per_real_second"]}},
"advance": {"method": "PUT", "endpoint": "/clock/advance", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}},
"clear": {"method": "POST", "endpoint": "/clock/clear", "request": {"type": "object", "properties": {**_WAIT_FOLLOWERS}}},
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/env/gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,8 @@ async def clock_set_time(request: Request) -> Response:
{"ok": False, "error": f"'{GET_TIME_TOOL_NAME}' is already registered by a backing server"}, 409)

def arm(body: dict) -> dict:
state = self._clock.set_time(body.get("virtual_time"), body.get("virtual_seconds_per_real_second"))
state = self._clock.set_time(body.get("virtual_time"), body.get("virtual_seconds_per_real_second"),
body.get("time_zone"))
self._register_get_time_tool()
return state

Expand Down
15 changes: 9 additions & 6 deletions src/agent_env/env/gateway/get_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
"your own assumption about today's date. Call this tool and derive from its value every "
"absolute date, time or timestamp you pass to another tool, and every relative phrase you "
'resolve ("today", "this week", "overdue", "the last 30 days"). current_time is in UTC, as '
"are the dates and times the other tools here take, so derive those from current_time. If you "
"have been told your user's IANA time zone, you can pass it as time_zone to also get "
"local_time, the same instant in that zone, for telling your user the time in their own "
"terms; it does not change the dates you pass to tools. A date taken from any other "
"are the dates and times the other tools here take, so derive those from current_time. The "
"result also has time_zone and local_time when your user's time zone is known: the same "
"instant on their clock, for telling them the time in their own terms. Pass time_zone to get "
"local_time in another IANA zone instead. Neither changes the dates you pass to tools. A date "
"taken from any other "
"source can silently match no records on a read, or file a record at the wrong time on a "
"write. Time advances while you work, so re-read this before each write rather than reusing "
"an earlier value. Inside a raw SQL or free-form query string, prefer the literal date this "
Expand All @@ -36,8 +37,9 @@
"type": "object",
"properties": {"time_zone": {
"type": "string",
"description": "An IANA time zone name, such as \"America/New_York\" or \"Asia/Tokyo\". The result then "
"also has time_zone and local_time, the same instant with that zone's UTC offset.",
"description": "An IANA time zone name, such as \"America/New_York\" or \"Asia/Tokyo\", for local_time in "
"that zone instead: the result's time_zone and local_time are then the same instant with that "
"zone's UTC offset.",
}},
"additionalProperties": False,
}
Expand All @@ -64,6 +66,7 @@ def build_get_time_tool(clock: Clock, make_arg_model: Callable[[str, dict], Any]
"""Built by hand: ToolManager.add_tool only warns on a collision and would silently shadow this."""

async def get_time(time_zone: str | None = None) -> dict[str, str] | CallToolResult:
time_zone = time_zone if time_zone is not None else clock.time_zone
if time_zone is None:
return read_time(clock)
zone = _zone(time_zone)
Expand Down
13 changes: 10 additions & 3 deletions src/agent_env/task_step/task_steps/sync_env_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ def __init__(
1 real s -> 1 virtual day). For ~V virtual seconds over an ~R-real-second task, pass V/R.

timezone = optional IANA name. Unset keeps today's behaviour. Set, a wall-clock virtual_time is local time in
that zone, and every synced server is told the zone (a server that cannot take it fails the step)."""
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)."""
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")
Expand Down Expand Up @@ -131,7 +132,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
raise StepContextError(f"Env '{self.env_id}' not found in context.deployed_envs")
try:
await deployed.invoke(EXT_CLOCK_URI, "set_time",
{"virtual_time": self.armed_virtual_time, "virtual_seconds_per_real_second": self.virtual_seconds_per_real_second},
{"virtual_time": self.armed_virtual_time, "virtual_seconds_per_real_second": self.virtual_seconds_per_real_second,
**({"time_zone": self.timezone} if self.timezone else {})},
timeout=self.timeout_seconds)
Comment thread
earakely-scale marked this conversation as resolved.
Resolved
except httpx.HTTPStatusError as e:
raise RuntimeError(f"clock arm failed (HTTP {e.response.status_code}): {e.response.text}") from e
Expand All @@ -144,6 +146,10 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
"deploy it in a multi env, whose gateway it follows") from e
state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=self.timeout_seconds)
env_get_time_url = state.get("env_get_time_url")
if self.timezone is not None and state.get("time_zone") != self.timezone:
logger.warning(f"sync_env_clock env={self.env_id}: its gateway's clock didn't take time zone "
f"{self.timezone!r}, so get_time answers agents in UTC alone; a gateway image from before "
"time_zone does that: put the gateway env again (agent-env env gateway put)")

synced, skipped = [], []
for server in await self._backing_servers(deployed):
Expand All @@ -160,7 +166,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
"env_get_time_url": env_get_time_url, "synced": synced, "skipped": skipped,
}
if self.timezone is not None:
configuration.update(timezone=self.timezone, armed_at=self.armed_virtual_time)
configuration.update(timezone=self.timezone, armed_at=self.armed_virtual_time,
get_time_zone=state.get("time_zone"))
context.metadata.setdefault("clock_configurations", []).append(configuration)
logger.info(f"sync_env_clock env={self.env_id}: armed rate={self.virtual_seconds_per_real_second}; "
f"synced={[s['service'] for s in synced]} skipped={[s['service'] for s in skipped]}")
Expand Down
37 changes: 33 additions & 4 deletions tst/unit/env/gateway/get_time_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from datetime import datetime
from types import SimpleNamespace

import httpx
import pytest
from mcp.shared.memory import create_connected_server_and_client_session
from mcp.types import Tool as MCPTool
Expand Down Expand Up @@ -289,13 +290,41 @@ async def test_a_time_the_zone_cannot_show_is_a_tool_error_naming_it(gw, now, zo
200, {"content": [{"type": "text", "text": message}], "isError": True, "changelog_id": None})


def test_the_description_keeps_tool_dates_in_utc_and_offers_a_zone_only_to_an_agent_told_one():
def test_the_description_keeps_tool_dates_in_utc_and_gives_the_users_clock_when_their_zone_is_known():
assert ("current_time is in UTC, as are the dates and times the other tools here take, so derive those from "
"current_time.") in GET_TIME_TOOL_DESCRIPTION
assert ("If you have been told your user's IANA time zone, you can pass it as time_zone to also get "
"local_time") in GET_TIME_TOOL_DESCRIPTION
assert "it does not change the dates you pass to tools" in GET_TIME_TOOL_DESCRIPTION
assert ("The result also has time_zone and local_time when your user's time zone is known: the same instant on "
"their clock") in GET_TIME_TOOL_DESCRIPTION
assert "Neither changes the dates you pass to tools" in GET_TIME_TOOL_DESCRIPTION
assert not re.search(r"[A-Z][a-z]+/[A-Z]", GET_TIME_TOOL_DESCRIPTION)
assert "home time zone" not in GET_TIME_TOOL_DESCRIPTION # no setup words: a clock tool says the time


def test_a_clock_armed_in_a_zone_answers_in_it_with_no_argument_and_in_one_asked_for_instead(gw):
"""A task's clock armed in its users' zone (sync_env_clock's timezone): an agent that asks no zone still learns the
time on its user's clock, which an agent once took UTC for, scheduling a "morning" check at 00:32 in Denver."""
gw._clock.set_time("2027-02-06T00:32:00Z", 0, time_zone="America/Denver")
gw._register_get_time_tool()

assert _call(gw) == {"current_time": "2027-02-06T00:32:00Z", "time_zone": "America/Denver",
"local_time": "2027-02-05T17:32:00-07:00"}
assert asyncio.run(_tools(gw)[GET_TIME_TOOL_NAME].fn(time_zone="Asia/Tokyo")) == {
"current_time": "2027-02-06T00:32:00Z", "time_zone": "Asia/Tokyo", "local_time": "2027-02-06T09:32:00+09:00"}


@pytest.mark.asyncio
async def test_the_arm_route_takes_the_zone_which_the_state_shows_and_a_re_arm_or_clear_drops(gw):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=gw._asgi_app()), base_url="http://gw") as client:
armed = (await client.put("/clock/set-time", json={"virtual_time": T, "time_zone": "America/Denver"})).json()
unknown = await client.put("/clock/set-time", json={"virtual_time": T, "time_zone": "Mars/Olympus_Mons"})
kept = (await client.get("/clock/state")).json()
rearmed = (await client.put("/clock/set-time", json={"virtual_time": T})).json()
await client.put("/clock/set-time", json={"virtual_time": T, "time_zone": "America/Denver"})
await client.post("/clock/clear", json={})
cleared = gw._clock.time_zone

assert armed["time_zone"] == kept["time_zone"] == "America/Denver" and unknown.status_code == 400
assert "time_zone" not in rearmed and cleared is None


@pytest.mark.asyncio
Expand Down
23 changes: 21 additions & 2 deletions tst/unit/task_step/sync_env_clock_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,16 +350,35 @@ def test_without_a_zone_virtual_time_is_passed_through_untouched():

@pytest.mark.asyncio
async def test_execute_arms_the_gateway_at_the_local_instant_and_tells_every_server_the_zone(monkeypatch):
sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL})
sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL, "time_zone": "America/New_York"})
monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email"))
context = TaskStepContext(deployed_envs=[_carded(await _composed_card({"mcp-email": [_ZONE_EXT]}))])

await _zoned().execute(context)

assert json.loads(sent[0].content)["virtual_time"] == "2026-01-01T17:00:00Z"
assert json.loads(sent[0].content) == {"virtual_time": "2026-01-01T17:00:00Z", "virtual_seconds_per_real_second": 1.0,
"time_zone": "America/New_York"} # get_time answers in it too
assert json.loads(sent[2].content) == {"env_get_time_url": CLOCK_URL, "timezone": "America/New_York"}
cfg = context.metadata["clock_configurations"][0]
assert (cfg["timezone"], cfg["virtual_time"], cfg["armed_at"]) == ("America/New_York", "2026-01-01T12:00:00", "2026-01-01T17:00:00Z")
assert cfg["get_time_zone"] == "America/New_York"


@pytest.mark.asyncio
async def test_a_gateway_that_didnt_take_the_zone_is_named_in_a_warning_and_the_record_and_the_step_goes_on(
monkeypatch, caplog):
"""An older gateway image answers the arm without keeping time_zone, so get_time answers in UTC alone: the step
still arms and syncs, as it did with that gateway before, and says why get_time won't give the user's clock."""
_mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL})
monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email"))
context = TaskStepContext(deployed_envs=[_carded(await _composed_card({"mcp-email": [_ZONE_EXT]}))])

with caplog.at_level("WARNING"):
await _zoned().execute(context)

assert context.metadata["clock_configurations"][0]["get_time_zone"] is None
assert "its gateway's clock didn't take time zone 'America/New_York', so get_time answers agents in UTC alone" in (
caplog.text)


@pytest.mark.asyncio
Expand Down
Loading