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.

24 changes: 22 additions & 2 deletions src/agent_env/env/gateway/clock.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Wall-clock-derived virtual clock for the env gateway (urn:agentenv:clock/v1).

Reads compute t0 + real_elapsed * rate, so virtual time advances on its own (independent of
tool calls) and reads never mutate it. Off by default: an unarmed clock 404s.
Reads compute t0 + real_elapsed * rate, so virtual time advances on its own and reads never
mutate it; fixed mode (fixed_clock.py) can also move it on by a charge per agent tool call
(advance_by). Off by default: an unarmed clock 404s.
"""
from __future__ import annotations

Expand Down Expand Up @@ -238,6 +239,25 @@ def advance(self, virtual_time: str) -> dict:
self._count += 1
return self.state()

def advance_by(self, seconds) -> dict:
"""Move the time on by ``seconds`` (a finite number, 0 or more) in one step, keeping t0, rate and generation as
advance does: fixed mode's charge for one tool call, so calls charged at once each add theirs."""
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
raise ClockError(f"seconds must be a number, got {type(seconds).__name__}")
# As in _parse_rate: only a float can be NaN or infinite, and math.isfinite on an int past a float's range raises.
if (isinstance(seconds, float) and not math.isfinite(seconds)) or seconds < 0:
raise ClockError(f"seconds must be a finite number, 0 or more, got {seconds}")
with self._lock:
if not self._armed or self._t0 is None:
raise ClockError("clock is not armed")
current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead)
if seconds > (_MAX_T0 - current).total_seconds() - _OVERFLOW_HORIZON_S * self._rate:
raise ClockError(f"advancing {seconds:g} s at rate {self._rate:g} would overflow datetime near the max")
self._ahead += seconds
self._lived += seconds
self._count += 1
return self.state()

def clear(self) -> dict:
"""Disarm (idempotent). Afterwards reads 404."""
with self._lock:
Expand Down
39 changes: 37 additions & 2 deletions src/agent_env/env/gateway/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
proxy >= actual load time.
"""

import math
import os
from enum import Enum
from uuid import uuid4
Expand Down Expand Up @@ -98,6 +99,28 @@ def data_plane_load_timeout_s(size_bytes: int | None) -> int:
CLOCK_WATCH_HOLD_S = 25.0
# The longest a clock write's wait_followers_s may ask it to wait for the followers.
CLOCK_MAX_WAIT_FOLLOWERS_S = 30.0
# Fixed mode (clock/v1 fixed, fixed_clock.py, FD-7183): a task's clock step names it as its clock_mode, and the gateway then
# moves the frozen clock on by a charge for each tool call the agent makes inside a work window, which the step running
# the agent opens for the agent's roles. The clock step turns the mode on with the charge (seconds_per_tool_call):
# FIXED_SECONDS_PER_CALL by default, or the task's fixed_time_increment_on_tool_call_seconds, above 0 and at most
# FIXED_MAX_SECONDS_PER_CALL (a day). The same for every model a task runs.
CLOCK_FIXED_MODE = "fixed"
FIXED_SECONDS_PER_CALL = 60.0
FIXED_MAX_SECONDS_PER_CALL = 86400.0
CLOCK_FIXED_PATH = "/clock/fixed"
CLOCK_WORK_WINDOW_PATH = "/clock/fixed/window"


def fixed_seconds_per_call_error(value) -> str | None:
"""Why ``value`` is no charge per call for fixed mode, or None for one it takes: a finite number above 0 and at most
FIXED_MAX_SECONDS_PER_CALL, never a boolean. The gateway's /clock/fixed checks it, and the clock steps at load."""
if isinstance(value, bool) or not isinstance(value, (int, float)):
return f"must be a number of seconds, got {value!r}"
if not math.isfinite(value) or value <= 0:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Oversized integers cause server errors

fixed_seconds_per_call_error calls math.isfinite(value) before checking the upper bound. A JSON integer such as 10**400 raises OverflowError here. Since /clock/fixed catches only ClockError, the caller gets a server error instead of the promised 400.

Call math.isfinite only for floats, as _parse_rate already does, so oversized integers reach the maximum check.

Suggested change
if not math.isfinite(value) or value <= 0:
if (isinstance(value, float) and not math.isfinite(value)) or value <= 0:
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/env/gateway/constants.py
Line: 119

Comment:
**Oversized integers cause server errors**

`fixed_seconds_per_call_error` calls `math.isfinite(value)` before checking the upper bound. A JSON integer such as `10**400` raises `OverflowError` here. Since `/clock/fixed` catches only `ClockError`, the caller gets a server error instead of the promised 400.

Call `math.isfinite` only for floats, as `_parse_rate` already does, so oversized integers reach the maximum check.

```suggestion
    if (isinstance(value, float) and not math.isfinite(value)) or value <= 0:
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

return f"must be a finite number above 0, got {value!r}"
if value > FIXED_MAX_SECONDS_PER_CALL:
return f"must be at most {FIXED_MAX_SECONDS_PER_CALL:g} (a day), got {value!r}"
return None

# Env/gateway-level extensions the gateway itself owns (tool gating + triggers).
EXT_DISABLE_TOOL_URI = "urn:agentenv:disable-tool/v1"
Expand Down Expand Up @@ -230,7 +253,7 @@ def due_deferred_calls(state: dict) -> list[dict]:
f"/tools/{TOOL_DISABLE_ACTION}", f"/tools/{TOOL_ENABLE_ACTION}",
"/triggers/register", "/triggers/remove", "/triggers/clear",
"/notifications/config", "/notifications/take", "/notifications/clear",
CLOCK_FOLLOWERS_PATH,
CLOCK_FOLLOWERS_PATH, CLOCK_FIXED_PATH, CLOCK_WORK_WINDOW_PATH,
})
# The older REST routes a backing server serves beside its data plane, which reset, load or export its state.
# Behind the proxy, /svc/<key>/ takes the control token for each, and anything under it, on a gateway that has one.
Expand Down Expand Up @@ -304,14 +327,26 @@ def random_mcp_server_name() -> str:
},
{
"uri": EXT_CLOCK_URI,
"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); declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry, and retire_follower removes one so writes stop waiting for it (an agent the run tears down); 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.",
"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); declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry, and retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; fixed turns fixed mode on or off (on needs an armed clock at rate 0; set_time, set_rate and clear turn it off, ending every window), and open_work_window and close_work_window open and close a window naming the roles whose calls it charges (the step running the agent opens one around the agent's turns; a close answers what the window charged, and again on a retry): each answered tool call by a role an open window names moves the clock on by the seconds_per_tool_call fixed was turned on with, which turning it on requires (above 0, at most " f"{FIXED_MAX_SECONDS_PER_CALL:g}" "; the clock steps send " f"{FIXED_SECONDS_PER_CALL:g}" " unless the task sets fixed_time_increment_on_tool_call_seconds) (the gateway's own get_time and stay_quiet are free; a post-turn hook's call that shows the control token is not the agent's), and its answer waits, its barriers' wait included and up to the same budget, until the world's work runnable now has landed: every trigger fire at work and every deferred call the clock has reached; the switch and the windows change no version, each charge does, and state's fixed block shows the mode, its charge per call (seconds_per_call, null while off), the windows open and its totals; 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"}, "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}}},
"state": {"method": "GET", "endpoint": "/clock/state", "request": {"type": "object", "properties": {}}},
"fixed": {"method": "PUT", "endpoint": CLOCK_FIXED_PATH, "request": {
"type": "object",
"properties": {"on": {"type": "boolean"},
"seconds_per_tool_call": {"type": "number", "exclusiveMinimum": 0,
"maximum": FIXED_MAX_SECONDS_PER_CALL}},
"required": ["on"], "additionalProperties": False,
# Turning it on needs the charge per call; turning it off takes none.
"if": {"properties": {"on": {"const": True}}, "required": ["on"]},
"then": {"required": ["seconds_per_tool_call"]},
"else": {"not": {"required": ["seconds_per_tool_call"]}}}},
"open_work_window": {"method": "PUT", "endpoint": CLOCK_WORK_WINDOW_PATH, "request": {"type": "object", "properties": {"window": {"type": "string", "minLength": 1}, "roles": {"type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1}}, "required": ["window", "roles"], "additionalProperties": False}},
"close_work_window": {"method": "DELETE", "endpoint": CLOCK_WORK_WINDOW_PATH, "request": {"type": "object", "properties": {"window": {"type": "string", "minLength": 1}}, "required": ["window"], "additionalProperties": False}},
"declare_follower": {"method": "PUT", "endpoint": CLOCK_FOLLOWERS_PATH, "request": {"type": "object", "properties": {"name": {"type": "string"}, "read_token": {"type": "string"}}, "required": ["name", "read_token"]}},
"retire_follower": {"method": "DELETE", "endpoint": CLOCK_FOLLOWERS_PATH, "request": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}},
"watch": {"method": "GET", "endpoint": CLOCK_WATCH_PATH, "hold_s": CLOCK_WATCH_HOLD_S, "request": {"type": "object", "properties": {"after": {"type": "string"}, "follower": {"type": "string"}}}}}},
Expand Down
14 changes: 12 additions & 2 deletions src/agent_env/env/gateway/deferred_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import hashlib
import logging
from collections import deque
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
from typing import Any, Optional

from mcp.types import CallToolResult

Expand Down Expand Up @@ -67,6 +67,14 @@ def state(self) -> list[dict]:
"due": call.status == DEFERRED_CALL_PENDING and (call.at - now).total_seconds() < _VIRTUAL_RESOLUTION_S}
for (server, key), call in [*self._finished, *self._calls.items()]]

def due(self) -> dict[str, asyncio.Task]:
"""Each call still to make whose time the gateway clock has reached, by key, with the task making it: what a
fixed-mode hold waits for, as ``state``'s ``due`` marks it (Gateway._settle_world)."""
now = _now(self._gw._clock)
return {key: call.task for (_, key), call in self._calls.items()
if call.task is not None and call.status == DEFERRED_CALL_PENDING
and (call.at - now).total_seconds() < _VIRTUAL_RESOLUTION_S}

def in_state(self, state: dict) -> dict:
"""The trigger engine's ``state`` with the calls listed (GET /triggers/state), and the earliest still to make
counted in its next_event_at, so a harness that jumps the clock to the next event stops at it."""
Expand Down Expand Up @@ -100,6 +108,7 @@ def _schedule(self, entry: Any, server_url: str, role: str, report: bool) -> Non
record = _Call(at, call["tool"], call["arguments"], report_as, role, report)
self._calls[(server_url, key)] = record
task = asyncio.get_running_loop().create_task(self._make(key, record, server_url))
record.task = task
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)

Expand Down Expand Up @@ -204,3 +213,4 @@ class _Call:
report: bool
status: str = DEFERRED_CALL_PENDING
attempts: int = 0
task: Optional[asyncio.Task] = field(default=None, repr=False, compare=False)
Loading
Loading