Repository navigation
[FD-5916] feat(agents): agents can follow the env's clock the way computers do #714
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
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 eea933c
refactor(agents): leave the Claude Code image to its own PR; agents s…
williamloo-scale 608a93d
Merge origin/main
williamloo-scale bce00d4
fix(agents): agent clock review: new config's status, one clock per a…
williamloo-scale 84381b8
fix(agents): keep each agent's clock record on a key of its own; a re…
williamloo-scale 56dac45
fix(agents): agent clock keys can't collide; one clock env per agent;…
williamloo-scale c726743
chore: drop test run output committed by mistake
williamloo-scale cecc686
fix(agents): a failed agent sync retires its follower; the task's zon…
williamloo-scale afe55b4
Merge origin/main
williamloo-scale c8ed6e1
fix(agents): a later clock sync leaves agents teardown_sandboxes took…
williamloo-scale 25af21a
chore: drop test-run output committed again, and ignore where the pro…
williamloo-scale f8bd9ff
feat(a2a-agent): validate clock/v1 by the time the agent's own comman…
earakely-scale f9af1b6
refactor(a2a-agent): name the clock validation's timeouts and error l…
williamloo-scale 43fdb97
fix(gateway): get_time says the machine's clock may not be synchroniz…
earakely-scale 8bf8e4c
refactor(a2a-agent): move agent_clock to a2a_agent/clock.py, beside t…
earakely-scale c5ef5a4
chore: re-run review now that #726 imports FOLLOWING_KEY from a2a_age…
earakely-scale File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
102 changes: 102 additions & 0 deletions
102
packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/clock.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| 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} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
set_zoneonly changes this process'sTZ. In an e2e run I killed the A2A server withkill -9and supervisord restarted it. The clock kept following, since the follower reads its config from disk, but the zone was gone. The next turn'sdateprinted+00:00andTZ=instead of-05:00andAmerica/Chicago.Could the zone be saved with the follower's config and re-applied when the server starts, so a restart brings back both?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in cecc686.
sync_timenow saves the task's zone in the follower's config (timezone, which the follower ignores), andrestore_zoneruns 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 ownTZ. Tests:test_a_server_restarted_mid_run_takes_back_the_tasks_zone(sync withAmerica/Chicago, resetTZto UTC, start the app again,TZisAmerica/Chicago) andtest_a_server_starting_without_a_saved_zone_keeps_its_own.